diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..ea1653afc --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [libracoder] diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml new file mode 100644 index 000000000..c7deaf7b4 --- /dev/null +++ b/.github/workflows/benchmark.yml @@ -0,0 +1,63 @@ +# Head-to-head Linux benchmark comparing Kiri Engine against Docker Engine +# (`dockerd`) on the same runner (#776): ephemeral alpine lifecycle, multi-layer +# PHP app cold start & warm restart, container exec, 1,000-file bind-mount I/O, +# published-port HTTP latency, teardown, and engine RSS. +name: Linux Benchmark + +on: + release: + types: [published] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: linux-benchmark-${{ github.ref }} + cancel-in-progress: false + +jobs: + linux-benchmark: + name: Kiri vs Docker (Linux) + runs-on: ubuntu-24.04 + timeout-minutes: 45 + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Build static Linux engine + run: | + mkdir -p "$RUNNER_TEMP/bin" + docker run --rm -v "$PWD:/src" -v "$RUNNER_TEMP/bin:/out" \ + -w /src -e CARGO_TARGET_DIR=/tmp/target rust:1-alpine sh -c \ + 'apk add -q musl-dev && cargo build --release --locked -p kiri -p kiri-init && cp /tmp/target/release/kiri /tmp/target/release/kiri-init /out/' + - name: Run head-to-head Kiri vs Docker benchmark + env: + VERSION: ${{ github.event.release.tag_name || github.sha }} + run: | + set -eu + WORK="$RUNNER_TEMP/vs-docker" + mkdir -p "$WORK/data" "$WORK/run" + sudo env KIRI_DATA_DIR="$WORK/data" \ + KIRI_SOCKET="$WORK/run/docker.sock" KIRI_HTTP_PORT=18080 KIRI_HTTPS_PORT=18443 \ + "$RUNNER_TEMP/bin/kiri" daemon >"$WORK/daemon.log" 2>&1 & + KIRI_PID=$! + trap 'sudo kill -TERM $KIRI_PID 2>/dev/null || true' EXIT + for _ in $(seq 1 100); do + [ -S "$WORK/run/docker.sock" ] && break + sleep 0.2 + done + sudo python3 scripts/bench-linux-docker.py \ + --docker-sock /var/run/docker.sock \ + --kiri-sock "$WORK/run/docker.sock" \ + --kiri-pid "$KIRI_PID" \ + --version "${VERSION}" \ + --out "$WORK/benchmark.json" \ + --report "$WORK/report.md" + cat "$WORK/report.md" >> "$GITHUB_STEP_SUMMARY" + - name: Upload benchmark results + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: linux-benchmark-results + path: ${{ runner.temp }}/vs-docker/benchmark.json diff --git a/.github/workflows/ui-tests.yml b/.github/workflows/ui-tests.yml index afb67b91a..75eb23614 100644 --- a/.github/workflows/ui-tests.yml +++ b/.github/workflows/ui-tests.yml @@ -27,8 +27,11 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + # The commit before too: on a pull request it is main, which the + # translation check compares against to note words that may not fit. + fetch-depth: 2 - name: Check the translations match the words in use - run: python3 scripts/i18n-check.py + run: python3 scripts/i18n-check.py --since HEAD^1 - name: Run the page tests in headless Chrome run: | # The runner's Chrome, without the sandbox: it needs user diff --git a/.gitignore b/.gitignore index 110daab99..b5cf175ab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,16 @@ /target +/packaging/arch/src/ +/packaging/arch/pkg/ +/packaging/arch/*.pkg.tar.zst # Raw benchmark output: kept outside this repository. /bench/results/ /guest/out/ .wrangler/ +# Nix build symlinks +result +result-* + # Built binaries and downloaded installers: never in the repo. The Windows # bundle (cargo xtask windows) lands under /target and is shared from there. *.exe diff --git a/Cargo.lock b/Cargo.lock index 08651114d..64ef3a740 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -190,6 +190,22 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.3.1" @@ -748,7 +764,6 @@ dependencies = [ "tar", "ureq", "webkit2gtk", - "webpki-roots", ] [[package]] @@ -757,11 +772,16 @@ version = "0.0.0" dependencies = [ "rcgen", "rustls", + "rustls-native-certs", + "rustls-pki-types", + "schannel", + "security-framework", "serde", "serde_json", "sha2", "tar", "ureq", + "webpki-root-certs", ] [[package]] @@ -806,11 +826,15 @@ dependencies = [ "embed-resource", "kiri-share-proto", "libc", + "rcgen", "rustls", + "rustls-native-certs", + "rustls-pki-types", + "schannel", "serde", "serde_json", "sha2", - "webpki-roots", + "webpki-root-certs", "webview2-com", "windows", "windows-sys 0.52.0", @@ -1014,6 +1038,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "pango" version = "0.18.3" @@ -1215,6 +1245,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.15.1" @@ -1244,6 +1286,38 @@ dependencies = [ "twox-hash", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "semver" version = "1.0.28" @@ -1642,7 +1716,6 @@ dependencies = [ "rustls-pki-types", "ureq-proto", "utf8-zero", - "webpki-roots", ] [[package]] @@ -1746,10 +1819,10 @@ dependencies = [ ] [[package]] -name = "webpki-roots" -version = "1.0.11" +name = "webpki-root-certs" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" dependencies = [ "rustls-pki-types", ] diff --git a/NOTICE b/NOTICE index 08742d9be..840cf279d 100644 --- a/NOTICE +++ b/NOTICE @@ -3292,6 +3292,8 @@ Used by: - bitflags 2.13.2 (https://github.com/bitflags/bitflags) - cc 1.10.0 (https://github.com/rust-lang/cc-rs) - cfg-if 1.0.5 (https://github.com/rust-lang/cfg-if) +- core-foundation-sys 0.8.7 (https://github.com/servo/core-foundation-rs) +- core-foundation 0.10.1 (https://github.com/servo/core-foundation-rs) - equivalent 1.0.3 (https://github.com/indexmap-rs/equivalent) - errno 0.3.14 (https://github.com/lambda-fairy/rust-errno) - filetime 0.2.29 (https://github.com/alexcrichton/filetime) @@ -3305,13 +3307,17 @@ Used by: - linux-raw-sys 0.12.1 (https://github.com/sunfishcode/linux-raw-sys) - log 0.4.34 (https://github.com/rust-lang/log) - once_cell 1.21.4 (https://github.com/matklad/once_cell) +- openssl-probe 0.2.2 (https://github.com/rustls/openssl-probe) - percent-encoding 2.3.2 (https://github.com/servo/rust-url/) - pkg-config 0.3.34 (https://github.com/rust-lang/pkg-config-rs) - regex-lite 0.1.9 (https://github.com/rust-lang/regex) - ring 0.17.14 (https://github.com/briansmith/ring) - rustc_version 0.4.1 (https://github.com/djc/rustc-version-rs) - rustix 1.1.5 (https://github.com/bytecodealliance/rustix) +- rustls-native-certs 0.8.5 (https://github.com/rustls/rustls-native-certs) - rustls 0.23.46 (https://github.com/rustls/rustls) +- security-framework-sys 2.17.0 (https://github.com/kornelski/rust-security-framework) +- security-framework 3.7.0 (https://github.com/kornelski/rust-security-framework) - smallvec 1.16.4 (https://github.com/servo/rust-smallvec) - syn 1.0.109 (https://github.com/dtolnay/syn) - system-deps 6.2.2 (https://github.com/gdesmott/system-deps) @@ -4732,7 +4738,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Community Data License Agreement Permissive 2.0 ---------------------------------------------------------------------- Used by: -- webpki-roots 1.0.11 (https://github.com/rustls/webpki-roots) +- webpki-root-certs 1.0.12 (https://github.com/rustls/webpki-roots) # Community Data License Agreement - Permissive - Version 2.0 @@ -5549,6 +5555,20 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +MIT License +---------------------------------------------------------------------- +Used by: +- schannel 0.1.30 (https://github.com/steffengy/schannel-rs) + +Copyright (c) 2015 steffengy + +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. + + MIT License ---------------------------------------------------------------------- Used by: @@ -6375,9 +6395,9 @@ For more information, see https://www.bis.doc.gov See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. -Docker Compose 5.6.1 — Apache-2.0 +Docker Compose 5.8.0 — Apache-2.0 ---------------------------------------------------------------------- -Source: https://raw.githubusercontent.com/docker/compose/v5.6.1/LICENSE +Source: https://raw.githubusercontent.com/docker/compose/v5.8.0/LICENSE Apache License @@ -6582,9 +6602,9 @@ Source: https://raw.githubusercontent.com/docker/compose/v5.6.1/LICENSE See the License for the specific language governing permissions and limitations under the License. -Docker Compose 5.6.1 — upstream NOTICE +Docker Compose 5.8.0 — upstream NOTICE ---------------------------------------------------------------------- -Source: https://raw.githubusercontent.com/docker/compose/v5.6.1/NOTICE +Source: https://raw.githubusercontent.com/docker/compose/v5.8.0/NOTICE Docker Compose V2 Copyright 2020 Docker Compose authors diff --git a/README.md b/README.md index 334940e5b..d25a53d3e 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Latest release Apache 2.0 License Discord - 38 languages + 42 languages

@@ -25,7 +25,8 @@ Docs · Features · Download · - Security + Security · + 简体中文

@@ -102,7 +103,7 @@ comes from the Igbo word *ntakịrị*, "small". - **Local domains**: `http://.kiri.local`, with HTTPS from Kiri's own certificate authority. - **More than containers**: a one-command Kubernetes cluster and Linux machines. - **A native window** for containers, images, volumes and networks, plus a menu bar item. -- **In your language**: the window comes in 38 languages, on macOS, Windows and Linux alike. +- **In your language**: the window comes in 42 languages, on macOS, Windows and Linux alike. --- @@ -181,18 +182,21 @@ Kiri's own commands: | Command | What it does | |---------|--------------| | `kiri start` | Start Kiri again after a Stop, as Start in the window does | -| `kiri k8s start \| stop \| status \| delete` | A single-node Kubernetes cluster | -| `kiri machine create NAME [--distro D] \| list \| shell NAME \| stop \| delete NAME` | Linux machines | +| `kiri k8s start \| stop \| status [--json] \| delete` | A single-node Kubernetes cluster | +| `kiri machine create NAME [--distro D] \| list [--json] \| shell NAME \| stop \| delete NAME` | Linux machines | | `kiri share PORT\|CONTAINER [--name N]` | Share a local port or container on the internet | | `kiri import [orbstack \| desktop-linux]` | Bring images, volumes and containers over | -| `kiri domains [set --http N --https N \| reset]` | The ports local domains answer on | -| `kiri usb [list] \| attach DEVICE \| detach DEVICE` | USB devices for containers (beta) | +| `kiri domains [set --http N --https N \| reset] [--json]` | The ports local domains answer on | +| `kiri usb [list [--json]] \| attach DEVICE \| detach DEVICE` | USB devices for containers (beta) | | `kiri build-with [docker \| kiri]` | Which builder `docker build` uses | | `kiri update [--check]` | Install the newest release | +| `kiri doctor [--json]` | Whether Kiri works here, one line per part, and what to run when one doesn't | | `kiri diag logs \| report` | Logs, and a report file to send with a bug | | `kiri bench [--runs N] [--network none\|bridge]` | Measure container start on your machine | | `kiri ui` | Open the window | +`--json` prints one line of JSON for scripts, as the window gets it; `kiri registry` and `kiri share status` take it too. + --- ## Benchmarks diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 000000000..ed0d80bfc --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,352 @@ +
+ +

+ + + Kiri + +

+ +

Kiri:小巧、极速的 macOS / Windows / Linux 容器运行时

+ +

Docker Desktop 启动慢、空闲时占用资源多。Kiri 是用 Rust 编写的轻量级替代品。它能运行你的 Docker 镜像,并且兼容你已经在用的 docker CLI、Compose 和 buildx。

+ +

+ CI 状态 + 最新版本 + Apache 2.0 许可证 + Discord + 38 种语言 +

+ +

+ + 快速上手 · + 文档 · + 功能特性 · + 下载 · + 安全 · + English + +

+ +

+ Kiri 窗口:容器按 Compose 项目分组,显示状态、端口、本地域名和大小 +

+ +
+ +--- + +> 本文档是 [README.md](README.md) 的中文翻译。若两者内容有出入,以英文原版为准。 + +## 开始之前 + +请确认你的系统满足以下条件之一: + +- macOS 14 或更高版本,Apple 芯片或 Intel 均可 +- Windows 10 或 11,启用 WSL 2,x86-64 或 Arm 均可 +- Linux(Ubuntu、Fedora 等) + +## 第一步:安装并启动 Kiri + +macOS 上使用 Homebrew: + +```bash +brew install --cask libracoder/kiri/kiri +``` + +或下载对应系统的安装包: + +| 平台 | 获取方式 | +|------|----------| +| macOS 14+(Apple 芯片或 Intel) | 从 [runkiri.com/releases](https://runkiri.com/releases/) 下载 `.dmg`,或执行 `brew install --cask libracoder/kiri/kiri` | +| Windows 10 和 11(x86-64 或 Arm,通过 WSL 2) | 从 [runkiri.com/releases](https://runkiri.com/releases/) 下载 `.msi` | +| Linux(Ubuntu、Fedora 等) | 从 [runkiri.com/releases](https://runkiri.com/releases/) 下载 `.deb` 或 `.rpm` | + +首次打开 Kiri 时,它会自动配置一个 `kiri` Docker context。Kiri 会自动更新,并在更新前校验每个新版本的签名。 + +然后运行你的第一个容器: + +```bash +docker --context kiri run --rm alpine echo hello +``` + +--- + +## 目录 + +- [开始之前](#开始之前) +- [安装并启动 Kiri](#第一步安装并启动-kiri) +- [为什么选择 Kiri?](#为什么选择-kiri) +- [快速上手](#快速上手) +- [功能特性](#功能特性) +- [Docker 命令](#docker-命令) +- [基准测试](#基准测试) +- [对比](#对比) +- [Kiri 工作原理](#kiri-工作原理) +- [文档](#文档) +- [路线图](#路线图) +- [社区](#社区) +- [安全](#安全) +- [许可证](#许可证) + +--- + +## 为什么选择 Kiri? + +Kiri 在一个小型 Linux 虚拟机中运行容器(在 Linux 上则直接运行于内核之上),并实现了 Docker Engine API,因此你现有的工具可以直接使用。名字来源于伊博语单词 *ntakịrị*,意为"小"。 + +- **快**:通过 Docker API 启动并退出一个容器约需 2.5 毫秒,比 Docker Desktop 快约 80 倍。 +- **轻**:虚拟机空闲 60 秒后自动休眠,守护进程常驻内存约 15 MB,唤醒仅需约 0.15 秒。 +- **兼容**:支持 `docker`、Compose、buildx、`docker login`,在 Apple 芯片上可通过 Rosetta 运行 amd64 镜像。 +- **本地域名**:`http://.kiri.local`,并由 Kiri 自带的证书颁发机构提供 HTTPS。 +- **不止容器**:一条命令启动 Kubernetes 集群,还能创建 Linux 虚拟机。 +- **原生窗口**:管理容器、镜像、卷和网络,另有菜单栏图标。 +- **你的语言**:窗口支持 38 种语言,macOS、Windows 和 Linux 一致。 + +--- + +## 快速上手 + +```sh +docker --context kiri run --rm alpine echo hello +docker --context kiri compose up -d +kiri k8s start # 单节点 Kubernetes,作为 `kiri` kubectl context +kiri machine create dev --distro ubuntu && kiri machine shell dev +kiri import # 从 OrbStack 或 Docker Desktop 迁移镜像、卷和容器 +``` + +Docker 的命令同样可以作为 `kiri` 命令使用(`kiri run`、`kiri ps`、`kiri compose up` 等),并且始终指向 Kiri。 + +--- + +## 功能特性 + +| 领域 | 提供的能力 | +|------|------------| +| **容器** | 完整生命周期:`run`、`exec`、`logs`、`attach`、`stop`、`kill`、`restart`、`pause`、`update`、`stats`、`top`、`diff`、`export`、`commit`,以及双向 `cp`。守护进程重启后记录仍然保留。 | +| **资源限制与安全** | `--memory`、`--cpus`、`--pids-limit`、`--shm-size`。Docker 默认 capabilities 和默认 seccomp 过滤器,支持 `--cap-add`/`--cap-drop`、`--privileged`、`--read-only`、`no-new-privileges`。 | +| **网络** | 默认 bridge、按名称和别名 DNS 解析的自定义网络、TCP/UDP 的 `-p`/`-P`、`--network host\|none\|container:`、IPAM(`--subnet`、`--gateway`、`--ip`)、IPv6、`host.docker.internal`。 | +| **本地域名** | 每个容器都有 `http://.kiri.local`,Compose 服务为 `..kiri.local`,并由 Kiri 自带的证书颁发机构提供 HTTPS。 | +| **存储** | 具名和匿名卷、宿主机路径绑定挂载、`--tmpfs`、`--mount`。 | +| **镜像** | `pull`、`push`、`tag`、`save`、`load`、`history`、`search`,支持 `docker login` 凭据。Apple 芯片上通过 Rosetta 运行 amd64 镜像。 | +| **构建** | 通过 BuildKit 支持 `docker build` 和 `buildx build`,空闲时自动停止。 | +| **Compose** | `up`、`down`、`ps`、`logs`、`exec`、多网络、事件。项目在窗口中分组显示。 | +| **Kubernetes** | `kiri k8s start`:单节点 k3s 集群,约 20 秒就绪,作为 `kiri` kubectl context。LoadBalancer 服务发布在 `localhost` 上。 | +| **Linux 虚拟机** | `kiri machine create dev --distro ubuntu`:你的用户、sudo 和相同路径的家目录,可选 systemd。 | +| **分享** | `kiri share 3000` 将本地端口或容器发布到互联网。 | +| **USB 设备(beta)** | 将串口适配器、Zigbee 棒或开发板交给容器使用。 | +| **内存** | balloon 在运行时归还空闲内存,虚拟机空闲 60 秒后休眠。 | +| **窗口** | 容器、镜像、卷和网络,每个容器都有实时日志、命令行和文件浏览。菜单栏图标显示运行状态。 | +| **导入** | `kiri import` 从 OrbStack 或 Docker Desktop 迁移镜像、卷和容器。 | +| **更新** | Kiri 自动更新,更新前校验每个版本的 SHA-256 和签名。 | + +所有参数和已知问题见 **[docs/features.md](docs/features.md)**。 + +--- + +## Docker 命令 + +Kiri 实现了 Docker Engine API,你现有的 `docker` CLI 可以直接对接。只需切换一次 context,其余什么都不用改: + +```bash +docker context use kiri +``` + +| 领域 | 可用命令 | +|------|----------| +| 容器 | `run` `create` `start` `stop` `kill` `restart` `rm` `exec` `logs` `attach` `wait` `rename` `pause` `unpause` `update` `stats` `top` `diff` `export` `commit` `cp` `ps` `inspect` `container prune` | +| 镜像 | `pull` `push` `tag` `images` `rmi` `save` `load` `history` `search` `login` `image prune` | +| 构建 | `build` `buildx build` | +| 网络 | `network create` `ls` `rm` `inspect` `connect` `disconnect` | +| 卷 | `volume create` `ls` `rm` `inspect` `prune` | +| Compose | `compose up` `down` `ps` `logs` `exec` | +| 系统 | `system df` `events` `info` `version` | + +同样的命令也可以作为 `kiri` 命令使用,并且始终指向 Kiri: + +```bash +kiri run -d --name web -p 8080:80 nginx # 然后打开 http://web.kiri.local +kiri ps +kiri logs -f web +kiri exec -it web sh +kiri compose up -d +kiri build -t myapp . +``` + +Kiri 自有命令: + +| 命令 | 作用 | +|------|------| +| `kiri start` | 在 Stop 之后重新启动 Kiri,等同于窗口中的 Start | +| `kiri k8s start \| stop \| status [--json] \| delete` | 单节点 Kubernetes 集群 | +| `kiri machine create NAME [--distro D] \| list [--json] \| shell NAME \| stop \| delete NAME` | Linux 虚拟机 | +| `kiri share PORT\|CONTAINER [--name N]` | 将本地端口或容器分享到互联网 | +| `kiri import [orbstack \| desktop-linux]` | 迁移镜像、卷和容器 | +| `kiri domains [set --http N --https N \| reset] [--json]` | 本地域名监听的端口 | +| `kiri usb [list [--json]] \| attach DEVICE \| detach DEVICE` | 容器的 USB 设备(beta) | +| `kiri build-with [docker \| kiri]` | 选择 `docker build` 使用的构建器 | +| `kiri update [--check]` | 安装最新版本 | +| `kiri doctor [--json]` | 检查 Kiri 各组件是否正常工作,异常时给出修复命令 | +| `kiri diag logs \| report` | 日志,以及随 bug 报告提交的报告文件 | +| `kiri bench [--runs N] [--network none\|bridge]` | 在你的机器上测量容器启动速度 | +| `kiri ui` | 打开窗口 | + +--- + +## 基准测试 + +所有数据均为中位数,在同一台机器的一次会话中,使用相同的 `docker` CLI 和相同的镜像对每个引擎测得。 + +### macOS + +`alpine` 运行 `true` 后删除,30 次运行,Apple 芯片 Mac: + +| 引擎 | Docker Engine API, p50 | p99 | `docker` CLI, p50 | p99 | +|------|----------------------:|----:|------------------:|----:| +| **Kiri** | **2.55 ms** | **4.72 ms** | **14.2 ms** | **17.4 ms** | +| Docker Desktop | 213 ms | 774 ms | 243 ms | 351 ms | +| OrbStack | 380 ms | 829 ms | 442 ms | 2383 ms | + +Kiri 通过 `docker` CLI 的 14 ms 中,大部分是 CLI 自身的启动时间。 + +引擎运行时的开销: + +| 指标 | Kiri | +|------|-----:| +| 虚拟机冷启动到就绪 | 112 ms | +| 客户机内核启动到 PID 1 | 8 ms | +| 干净关闭虚拟机 | 2.2 ms | +| 从休眠唤醒 | 约 150 ms | +| 虚拟机休眠时守护进程内存 | 约 15 MB | +| 每个容器的 shim 内存 | 0 MB(没有 shim) | +| 空闲时守护进程 CPU | 0.0 % | +| 宿主机到客户机往返,p50 / p99 | 31 µs / 62 µs | +| 客户机内核镜像 | 10 MB | +| 客户机 agent(PID 1 兼容器运行时) | 小于 1 MB | + +### Linux + +在一台 16 核 x86-64 Ubuntu 24.04 机器上对比六个引擎: + +| 引擎 | `run --rm alpine true` | 200 MB 容器 → 宿主机 | 1 GB 绑定挂载写入 | 1 GB 绑定挂载读取 | `build`,3 层,无缓存 | 发布端口 | +|------|----:|----:|----:|----:|----:|----:| +| **Kiri** | **188 ms** | **209 MB/s** | **1467 MB/s** | **3851 MB/s** | **1113 ms** | 10.3 Gbit/s | +| Docker Engine | 697 ms | 56 MB/s | 819 MB/s | 1307 MB/s | 1723 ms | **100.7 Gbit/s** | +| Podman | 1105 ms | 70 MB/s | 593 MB/s | 907 MB/s | 1148 ms | 51.9 Gbit/s | +| nerdctl | 631 ms | 72 MB/s | 845 MB/s | 1485 MB/s | 1211 ms | 52.4 Gbit/s | +| Colima | 635 ms | 20 MB/s | 493 MB/s | 1496 MB/s | 2472 ms | 0.8 Gbit/s | +| Docker Desktop | 714 ms | 114 MB/s | 826 MB/s | 1283 MB/s | 2008 ms | 87.8 Gbit/s | + +Kiri 启动容器比 Docker Engine 快 3.4 倍,读取绑定挂载快 2.9 倍。在通过发布端口的大流量传输上 Kiri 较慢,因为 Kiri 在用户空间中转发流量:对 Web 应用没有影响,大文件传输时较为明显。完整报告见 [`bench/ubuntu-2026-10-26.md`](bench/ubuntu-2026-10-26.md)。 + +### Windows + +Windows 11,16 核 x86-64 PC,两个引擎均运行于 WSL 2: + +| | Kiri | Docker Desktop | +|---|----:|----:| +| `docker run --rm alpine true` | **78 ms** | 491 ms | +| `docker exec … true` | **57 ms** | 89 ms | +| 200 MB 容器 → 宿主机 | **255 MB/s** | 40 MB/s | + +完整报告见 [`bench/windows-2026-10-25.md`](bench/windows-2026-10-25.md)。 + +### 自己跑一遍 + +```bash +kiri bench --network bridge --runs 30 # 在你的机器上测量容器启动 +bench/suite.sh # 完整的 Linux 对比测试 +``` + +测试方法和所有其他数据见 [`bench/results.json`](bench/results.json)。 + +--- + +## 对比 + +| | Kiri | Docker Desktop | OrbStack | Colima | +|---|:---:|:---:|:---:|:---:| +| 开源 | ✅ Apache-2.0 | ❌ | ❌ | ✅ MIT | +| 商用免费 | ✅ | 大公司需付费 | 付费 | ✅ | +| macOS | ✅ | ✅ | ✅ | ✅ | +| Windows | ✅ | ✅ | ❌ | ❌ | +| Linux | ✅ | ✅ | ❌ | ✅ | +| 兼容 `docker` CLI、Compose 和 buildx | ✅ | ✅ | ✅ | ✅ | +| 容器、镜像、卷和网络的图形窗口 | ✅ | ✅ | ✅ | ❌ | +| Kubernetes | ✅ | ✅ | ✅ | ✅ | +| Linux 虚拟机 | ✅ | ❌ | ✅ | ❌ | +| 带 HTTPS 的本地域名 | ✅ | ❌ | ✅ | ❌ | +| 虚拟机空闲休眠 | ✅ | ✅ | ❌ | ❌ | +| 从其他引擎导入 | ✅ | ❌ | ✅ | ❌ | +| macOS 容器启动(Docker API, p50) | **2.55 ms** | 213 ms | 380 ms | 未测量 | + +--- + +## Kiri 工作原理 + +``` +docker CLI ─┐ +compose ────┼─ Docker Engine API ─► kiri daemon ── vsock ──► guest agent (PID 1) +buildx ─────┤ 管理虚拟机 clone3 → 容器 +kiri UI ────┘ +``` + +虚拟机使用定制的 10 MB 内核,其 PID 1 是一个约 900 KB 的 Rust agent。该 agent 通过一次 `clone3` 进入命名空间和 cgroup 来启动容器。没有 runc、没有 shim、也没有 dockerd。更多细节见 [docs/development.md](docs/development.md#architecture)。 + +--- + +## 文档 + +- [docs.runkiri.com](https://docs.runkiri.com):每个功能的使用指南 +- [功能特性](docs/features.md):当前支持的全部能力、发布文件和已知问题 +- [开发指南](docs/development.md):构建、从源码运行、架构和仓库结构 +- [发布说明](docs/releases) + +--- + +## 路线图 + +接下来是更多分享方式(Tailscale 和 Cloudflare Tunnel,0.3.0)以及 Coolify 支持(0.4.0)。每个版本的计划见 [ROADMAP.md](ROADMAP.md)。 + +--- + +## 社区 + +Kiri 在开放中构建。欢迎提 issue 和 pull request:见 **[CONTRIBUTING.md](CONTRIBUTING.md)** 和[行为准则](CODE_OF_CONDUCT.md)。想迈出贡献第一步?看看 [`good first issue`](https://github.com/libracoder/kiri/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) 标签下的任务。 + +

+ + 加入我们的 Discord + +

+ +

+ + + + Star History Chart + + +

+ +感谢这些了不起的贡献者: + + + 贡献者 + + +--- + +## 安全 + +Kiri 会自动更新,并在更新前校验每个新版本的签名。如需私下报告漏洞,见 **[SECURITY.md](SECURITY.md)**。 + +--- + +## 许可证 + +[Apache-2.0](LICENSE)。第三方许可证见 [NOTICE](NOTICE)。客户机内核为 Linux(GPL-2.0);其配置、补丁和源码获取方式见 [`guest/kernel`](guest/kernel)。 + +"Kiri" 名称和 Kiri 徽标不在许可证覆盖范围内。欢迎 fork,但请使用不同的名称和徽标。 diff --git a/bench/api.sh b/bench/api.sh index bc7a41abf..0be36ec68 100644 --- a/bench/api.sh +++ b/bench/api.sh @@ -2,22 +2,28 @@ # Engine-only latency: one container lifecycle (create, start, wait, delete) # and one exec, straight over the Docker API with curl, no docker CLI. # SOCK=/run/dockerd-bench.sock bench/api.sh docker-engine -set -u +set -euo pipefail label=$1; S=${SOCK:?}; OUT=${OUT:-$(dirname "$0")/results}; RUNS=${RUNS:-30} -c() { curl -s --unix-socket "$S" "$@"; } +mkdir -p "$OUT" +c() { curl -fsS --unix-socket "$S" "$@"; } +id="" +trap '[[ -n "$id" ]] && c -X DELETE "http://x/containers/$id?force=true" >/dev/null || true' EXIT c -X POST -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["true"]}' http://x/containers/create >/dev/null cat > /tmp/api-run.sh </dev/null; c -X POST http://x/containers/\$id/wait >/dev/null; c -X DELETE http://x/containers/\$id >/dev/null +c -X POST http://x/containers/\$id/start >/dev/null && c -X POST http://x/containers/\$id/wait >/dev/null && c -X DELETE http://x/containers/\$id >/dev/null R id=$(c -X POST -H 'Content-Type: application/json' -d '{"Image":"alpine","Cmd":["sleep","600"]}' http://x/containers/create | jq -r .Id); c -X POST "http://x/containers/$id/start" >/dev/null cat > /tmp/api-exec.sh </dev/null R -hyperfine --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-run.json" 'bash /tmp/api-run.sh' >/dev/null 2>&1 -hyperfine --ignore-failure --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-exec.json" 'bash /tmp/api-exec.sh' >/dev/null 2>&1 -c -X DELETE "http://x/containers/$id?force=true" >/dev/null -printf '%-14s API run %4s ms (min %4s) API exec %4s ms (min %4s)\n' "$label" $(jq -r '.results[0] | "\(.median*1000|round) \(.min*1000|round)"' "$OUT/$label.api-run.json") $(jq -r '.results[0] | "\(.median*1000|round) \(.min*1000|round)"' "$OUT/$label.api-exec.json") +out=$(hyperfine --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-run.json" 'bash /tmp/api-run.sh' 2>&1) || { printf '%s\n' "$out" >&2; exit 1; } +out=$(hyperfine --warmup 3 --runs "$RUNS" --export-json "$OUT/$label.api-exec.json" 'bash /tmp/api-exec.sh' 2>&1) || { printf '%s\n' "$out" >&2; exit 1; } +ms() { jq -r ".results[0] | (.summary.time_wall_clock // .) | .$1 * 1000 | round" "$OUT/$label.$2.json"; } +r_med=$(ms median api-run); r_min=$(ms min api-run); e_med=$(ms median api-exec); e_min=$(ms min api-exec) +printf '%-14s API run %4s ms (min %4s) API exec %4s ms (min %4s)\n' "$label" "$r_med" "$r_min" "$e_med" "$e_min" diff --git a/contrib/wsl/kiri-linux/kiri-start b/contrib/wsl/kiri-linux/kiri-start index d6aa313fc..63d349d10 100644 --- a/contrib/wsl/kiri-linux/kiri-start +++ b/contrib/wsl/kiri-linux/kiri-start @@ -7,7 +7,37 @@ # up), or the old one did not stop; 2: it exited as it started. export HOME=/var/lib/kiri-daemon sock=$HOME/.kiri/run/docker.sock +mounts=${KIRI_PROC_MOUNTS:-/proc/mounts} +ro_state=$(awk ' + BEGIN { l1 = 0; l2 = 0; k1 = 0; k2 = 0 } + function covers(mp, t) { return mp == "/" || t == mp || index(t, mp "/") == 1 } + function ro(opts, a, n, i, r) { + n = split(opts, a, ","); r = 0 + for (i = 1; i <= n; i++) { + if (a[i] == "emergency_ro") return 2 + if (a[i] == "ro") r = 1 + } + return r + } + NF >= 4 { + mp = $2; if (length(mp) > 1) sub("[/]+$", "", mp) + if (covers(mp, "/") && length(mp) >= l1) { l1 = length(mp); k1 = ro($4) } + if (covers(mp, "/var/lib/kiri") && length(mp) >= l2) { l2 = length(mp); k2 = ro($4) } + } + END { + if (k1 == 2 || k2 == 2) print "was remounted read-only by Linux (emergency_ro)" + else if (k1 > 0 || k2 > 0) print "is mounted read-only (emergency_ro)" + } +' "$mounts" 2>/dev/null) +if [ -n "$ro_state" ]; then + echo "Kiri's WSL2 disk (ext4.vhdx) $ro_state after an unclean shutdown or filesystem error. To recover: 1) run 'wsl --shutdown' in PowerShell; 2) attach the disk bare with 'wsl --mount /ext4.vhdx --vhd --bare' (default %LOCALAPPDATA%/Kiri/wsl/kiri/ext4.vhdx); 3) from another Linux distro in WSL, find the device with 'lsblk' and run 'sudo e2fsck -f -y -D /dev/', then 'wsl --unmount'; or move/recreate storage in Settings -> Storage." >&2 + exit 2 +fi mkdir -p "$HOME" /var/log +# Clear an empty /etc/localtime or /etc/timezone directory left by pre-fix +# `-v` bind mounts before the daemon starts and restores valid files (#938). +[ -d /etc/localtime ] && [ ! -L /etc/localtime ] && rmdir /etc/localtime 2>/dev/null || true +[ -d /etc/timezone ] && [ ! -L /etc/timezone ] && rmdir /etc/timezone 2>/dev/null || true # One at a time: the boot command, the bridge, kiri-win and `kiri` # (crates/kiri/src/wsl.rs) can each start it at once, and two would each # remove the socket and start a daemon. busybox flock has no time limit of @@ -52,9 +82,11 @@ nohup /usr/local/bin/kiri daemon >>/var/log/kiri.log 2>&1 9>&- & pid=$! i=0 while [ "$i" -lt 50 ]; do + # Exit 2: it cannot start, and kiri-win need not wait for it. Checked + # before the socket so a daemon that binds its socket and exits is not + # treated as running. + kill -0 "$pid" 2>/dev/null || { rm -f "$sock"; echo "kiri daemon exited as it started; see /var/log/kiri.log" >&2; exit 2; } [ -S "$sock" ] && exit 0 - # Exit 2: it cannot start, and kiri-win need not wait for it. - kill -0 "$pid" 2>/dev/null || { echo "kiri daemon exited as it started; see /var/log/kiri.log" >&2; exit 2; } sleep 0.1 i=$((i + 1)) done diff --git a/crates/kiri-image/Cargo.toml b/crates/kiri-image/Cargo.toml index 077c2815b..502417d55 100644 --- a/crates/kiri-image/Cargo.toml +++ b/crates/kiri-image/Cargo.toml @@ -11,13 +11,31 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" tar = "0.4" -ureq = { version = "3", default-features = false, features = ["rustls"] } +ureq = { version = "3", default-features = false, features = ["rustls-no-provider"] } +# The rustls and ring crypto provider ureq is built without +# ("rustls-no-provider"): connect.rs's tls_config hands ring to every agent. +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +# The system's root certificates (macOS keychain, Windows store, /etc/ssl), +# merged with the bundled Mozilla set for registries, updates and Share (#303). +# roots.rs is self-contained (rustls-pki-types, rustls-native-certs, the +# bundled set only): kiri-win compiles it by path, without kiri-image. +rustls-native-certs = "0.8" +rustls-pki-types = "1" +webpki-root-certs = "1" + +# The roots an administrator distrusted (roots.rs): "Never Trust" in the +# macOS trust settings, the Windows Disallowed store. Both already come in +# with rustls-native-certs. +[target.'cfg(target_os = "macos")'.dependencies] +security-framework = "3" + +[target.'cfg(windows)'.dependencies] +schannel = "0.1" [dev-dependencies] -# Tests serve TLS on localhost with a self-signed certificate, as an -# insecure registry does. Both crates are already in the workspace. +# Tests serve TLS on localhost with a self-signed CA to prove both insecure +# registries and merged-root trust (#303). rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "crypto"] } -rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } [lints] workspace = true diff --git a/crates/kiri-image/src/archive.rs b/crates/kiri-image/src/archive.rs index f23e74f51..7145e446b 100644 --- a/crates/kiri-image/src/archive.rs +++ b/crates/kiri-image/src/archive.rs @@ -1,7 +1,11 @@ //! `docker load` and `docker save`: image tarballs in Docker's format //! (`manifest.json` naming a config and layer files per image), which is -//! also what `docker buildx build --load` produces. Archives are streamed: -//! each file goes straight into the blob store as it is read. +//! also what `docker buildx build --load` produces, and in the OCI image +//! layout (`index.json` plus `blobs/sha256/...`), which is what +//! `docker buildx build --output type=oci` and `skopeo` produce. Archives are +//! streamed: each file goes straight into the blob store as it is read, and +//! content-addressed blobs already in the store are verified in memory without +//! rewriting disk files. use std::collections::HashMap; use std::io::{self, Read, Write}; @@ -10,83 +14,356 @@ use std::time::{SystemTime, UNIX_EPOCH}; use serde_json::{Value, json}; use crate::reference::Reference; +use crate::registry::Platform; use crate::store::{Image, Layer, RunConfig, Store}; /// Largest JSON file kept in memory while reading an archive. const MAX_JSON: u64 = 4 << 20; +/// Maximum recursion depth and total descriptors walked in an OCI index tree. +const MAX_OCI_DEPTH: usize = 8; +const MAX_OCI_STEPS: usize = 1024; /// Reads an archive into the store. Returns the images it named. pub fn load(store: &Store, archive: impl Read) -> io::Result> { + load_platforms(store, archive, &[]) +} + +/// As [`load`], but picks the matching entry of a multi-platform OCI index +/// when `platform` is given (`docker load --platform`). +pub fn load_with_platform(store: &Store, archive: impl Read, platform: Option<&Platform>) -> io::Result> { + load_platforms(store, archive, platform.map_or(&[], std::slice::from_ref)) +} + +/// As [`load`], filtering a multi-platform OCI index to `platforms` when non-empty. +pub fn load_platforms(store: &Store, archive: impl Read, platforms: &[Platform]) -> io::Result> { let mut tar = tar::Archive::new(archive); // Archive path → blob digest and size, for every regular file. let mut files: HashMap = HashMap::new(); let mut manifest: Option> = None; + let mut index: Option> = None; + let mut oci_layout: Option> = None; let before: Vec = store.images()?; - let existed = |d: &str| before.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d)); + let existed = |d: &str| before.iter().any(|i| i.referenced_digests().any(|r| r == d)); let mut ingested: Vec = Vec::new(); let mut pins = Vec::new(); - for entry in tar.entries()? { - let mut entry = entry?; - if !entry.header().entry_type().is_file() { - continue; - } - let path = entry.path()?.to_string_lossy().trim_start_matches("./").to_owned(); - if path == "manifest.json" { - let mut buf = Vec::new(); - (&mut entry).take(MAX_JSON).read_to_end(&mut buf)?; - manifest = Some(buf); - continue; + let read = (|| -> io::Result> { + for entry in tar.entries()? { + let mut entry = entry?; + if !entry.header().entry_type().is_file() { + continue; + } + let path = entry.path()?.to_string_lossy().trim_start_matches("./").to_owned(); + if path == "manifest.json" || path == "index.json" || path == "oci-layout" { + let mut buf = Vec::new(); + (&mut entry).take(MAX_JSON + 1).read_to_end(&mut buf)?; + if buf.len() as u64 > MAX_JSON { + return Err(invalid(format!("{path} is larger than {MAX_JSON} bytes"))); + } + match path.as_str() { + "manifest.json" => manifest = Some(buf), + "index.json" => index = Some(buf), + _ => oci_layout = Some(buf), + } + continue; + } + // Fast path for content-addressed blobs (`blobs/sha256/`): + // pin first so a concurrent removal cannot delete the blob while + // we inspect it, check it is already on disk with the right size, + // and hash every byte of the tar entry in memory instead of writing + // a temp file and fsyncing. + if let Some(hex) = path.strip_prefix("blobs/sha256/") + && hex.len() == 64 + && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) + { + let size = entry.header().size()?; + let digest = format!("sha256:{hex}"); + if let Some(pin) = store.pin_existing(&digest, size) { + let (computed_digest, computed_size) = crate::store::hash_stream(&mut entry)?; + if computed_size != size || computed_digest != digest { + return Err(invalid(format!("archive blob {digest} is damaged: its bytes hash to {computed_digest}"))); + } + pins.push(pin); + files.insert(path, (digest, size)); + continue; + } + } + // Every other file is kept, `.json` ones too: in the classic layout + // (podman save, older docker save) the image config is a top-level + // `.json`. Files no image names are removed after the manifest. + let mut w = store.ingest()?; + io::copy(&mut entry, &mut w)?; + // Held until its image is recorded: a removal of another image + // that shares the blob must not delete it meanwhile. + let (digest, size, pin) = w.finish_pinned()?; + pins.push(pin); + if !existed(&digest) && !ingested.contains(&digest) { + ingested.push(digest.clone()); + } + files.insert(path, (digest, size)); } - // Every other file is kept, `.json` ones too: in the classic layout - // (podman save, older docker save) the image config is a top-level - // `.json`. Files no image names are removed after the manifest. - let mut w = store.ingest()?; - io::copy(&mut entry, &mut w)?; - // Held until its image is recorded: a removal of another image - // that shares the blob must not delete it meanwhile. - let (digest, size, pin) = w.finish_pinned()?; - pins.push(pin); - if !existed(&digest) { - ingested.push(digest.clone()); + // A docker-archive has manifest.json; an OCI layout has index.json. A + // hybrid has both, and docker's wins: that keeps existing loads intact. + if let Some(manifest) = manifest { + load_docker(store, &files, &manifest) + } else if let Some(index) = index { + load_oci(store, &files, &index, oci_layout.as_deref(), platforms) + } else { + Err(invalid("not an image archive: no manifest.json or index.json")) } - files.insert(path, (digest, size)); + })(); + // Files no image uses (OCI index blobs, skipped platforms, or all of a refused archive) do not stay. + let used = |d: &str| read.as_ref().is_ok_and(|loaded| loaded.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d))); + // The images are recorded: what they name is safe, and what nothing + // names goes unless another image or writer has it now. + drop(pins); + for d in ingested.iter().filter(|d| !used(d)) { + store.remove_if_unused(d)?; } - let manifest = manifest.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "not an image archive: no manifest.json"))?; - let entries: Vec = serde_json::from_slice(&manifest).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("manifest.json: {e}")))?; - let lookup = |p: &str| files.get(p.trim_start_matches("./")).cloned().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("archive is missing {p}"))); + read +} + +fn invalid(message: impl Into) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message.into()) +} + +fn lookup(files: &HashMap, path: &str) -> io::Result<(String, u64)> { + files.get(path.trim_start_matches("./")).cloned().ok_or_else(|| invalid(format!("archive is missing {path}"))) +} + +fn parse_repo_tag(tag: &str) -> io::Result { + let r = Reference::parse(tag).map_err(|e| invalid(e.to_string()))?; + if tag.contains('@') || r.is_digest() { + return Err(invalid(format!("invalid repo tag: {tag}"))); + } + Ok(r.short()) +} + +fn load_docker(store: &Store, files: &HashMap, manifest: &[u8]) -> io::Result> { + let entries: Vec = serde_json::from_slice(manifest).map_err(|e| invalid(format!("manifest.json: {e}")))?; let mut loaded = Vec::new(); for m in &entries { - let (config_digest, _) = lookup(m["Config"].as_str().unwrap_or_default())?; + let (config_digest, _) = lookup(files, m["Config"].as_str().unwrap_or_default())?; let config: Value = serde_json::from_slice(&store.read_config(&config_digest)?) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("image config: {e}")))?; + .map_err(|e| invalid(format!("image config: {e}")))?; let mut layers = Vec::new(); for l in m["Layers"].as_array().into_iter().flatten() { - let (digest, size) = lookup(l.as_str().unwrap_or_default())?; + let (digest, size) = lookup(files, l.as_str().unwrap_or_default())?; let media_type = media_type_of(&store.blob_path(&digest)?)?; layers.push(Layer { digest, size, media_type: media_type.to_owned() }); } - let names: Vec = m["RepoTags"] - .as_array() - .into_iter() - .flatten() - .filter_map(Value::as_str) - .map(|t| Reference::parse(t).map(|r| r.short()).unwrap_or_else(|_| t.to_owned())) - .collect(); + let mut names = Vec::new(); + for t in m["RepoTags"].as_array().into_iter().flatten().filter_map(Value::as_str) { + names.push(parse_repo_tag(t)?); + } // An untagged image is known by its id. let names = if names.is_empty() { vec![config_digest.clone()] } else { names }; for name in names { - let image = from_config(name, &config_digest, &config, layers.clone()); - store.put_image(image.clone())?; - loaded.push(image); + loaded.push(from_config(name, &config_digest, &config, layers.clone())); } } - // Files no image uses (OCI index blobs and the like) do not stay. - let used = |d: &str| loaded.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d)); - // The images are recorded: what they name is safe, and what nothing - // names goes unless another image or writer has it now. - drop(pins); - for d in ingested.iter().filter(|d| !used(d)) { - store.remove_if_unused(d)?; + for image in &loaded { + store.put_image(image.clone())?; + } + Ok(loaded) +} + +/// The digest and size of the blob a descriptor points to, checked against +/// the bytes in the archive: validates the digest via [`crate::store::digest_hex`] +/// and verifies the actual hash and declared size. +fn descriptor_blob(files: &HashMap, descriptor: &Value) -> io::Result<(String, u64)> { + let digest = descriptor["digest"].as_str().ok_or_else(|| invalid("OCI descriptor has no digest"))?; + let hex = crate::store::digest_hex(digest).map_err(|e| invalid(e.to_string()))?; + if !hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + return Err(invalid(format!("invalid sha256 digest {digest:?}"))); + } + let (actual, size) = lookup(files, &format!("blobs/sha256/{hex}"))?; + if actual != digest { + return Err(invalid(format!("OCI blob {digest} is damaged: its bytes hash to {actual}"))); + } + if let Some(v) = descriptor.get("size").filter(|v| !v.is_null()) + && v.as_u64() != Some(size) + { + return Err(invalid(format!("OCI blob {digest} is damaged: expected size {v}, got {size}"))); + } + Ok((actual, size)) +} + +/// The os/architecture an OCI image config says it runs on. +fn config_platform(store: &Store, config_digest: &str) -> io::Result<(String, String)> { + let config: Value = serde_json::from_slice(&store.read_config(config_digest)?).map_err(|e| invalid(format!("image config: {e}")))?; + Ok((config["os"].as_str().unwrap_or("linux").to_owned(), config["architecture"].as_str().unwrap_or_default().to_owned())) +} + +#[derive(Debug, Clone)] +struct Candidate { + manifest: String, + tag: Option, +} + +/// Whether `descriptor` is a non-image artifact or Buildx provenance attestation. +fn is_attestation(descriptor: &Value) -> bool { + descriptor["annotations"]["vnd.docker.reference.type"].as_str() == Some("attestation-manifest") + || descriptor["platform"]["os"].as_str() == Some("unknown") + || descriptor["platform"]["architecture"].as_str() == Some("unknown") + || descriptor["artifactType"].is_string() +} + +/// Image reference from OCI annotations: `io.containerd.image.name` (the full +/// reference written by BuildKit/containerd, where `org.opencontainers.image.ref.name` +/// may carry only the tag) first, falling back to `org.opencontainers.image.ref.name`. +fn descriptor_tag(descriptor: &Value, parent_tag: Option<&str>) -> io::Result> { + let ann = &descriptor["annotations"]; + if let Some(full) = ann["io.containerd.image.name"].as_str().filter(|s| !s.is_empty()) { + return parse_repo_tag(full).map(Some); + } + if let Some(p) = parent_tag { + return Ok(Some(p.to_owned())); + } + match ann["org.opencontainers.image.ref.name"].as_str().filter(|s| !s.is_empty()) { + Some(tag) => parse_repo_tag(tag).map(Some), + None => Ok(None), + } +} + +fn platform_matches(p: &Value, target: &Platform) -> bool { + p["os"].as_str() == Some(target.os.as_str()) && p["architecture"].as_str() == Some(target.architecture.as_str()) +} + +fn resolve_index( + store: &Store, + files: &HashMap, + descriptors: &[Value], + platforms: &[Platform], + parent_tag: Option<&str>, + depth: usize, + steps: &mut usize, +) -> io::Result> { + if !platforms.is_empty() { + let mut found = Vec::new(); + for child in descriptors { + if is_attestation(child) { + continue; + } + let p = &child["platform"]; + if (p["os"].as_str().is_some() || p["architecture"].as_str().is_some()) + && !platforms.iter().any(|want| platform_matches(p, want)) + { + continue; + } + found.extend(oci_candidates(store, files, child, platforms, parent_tag, depth, steps)?); + } + return Ok(found); + } + // Group descriptors by their resolved image tag (preserving order) so that + // multiple distinct images in one archive all load, while multiple + // platforms for the same image (or untagged multi-arch) prefer the host. + let mut groups: Vec<(Option, Vec<&Value>)> = Vec::new(); + for child in descriptors { + if is_attestation(child) { + continue; + } + let tag = descriptor_tag(child, parent_tag)?; + match groups.iter_mut().find(|(t, _)| *t == tag) { + Some((_, list)) => list.push(child), + None => groups.push((tag, vec![child])), + } + } + let host = Platform::host_linux(); + let mut found = Vec::new(); + for (tag, group) in groups { + let host_only: Vec<&Value> = group.iter().copied().filter(|d| platform_matches(&d["platform"], &host)).collect(); + let chosen = if host_only.is_empty() { group } else { host_only }; + for child in chosen { + found.extend(oci_candidates(store, files, child, platforms, tag.as_deref(), depth, steps)?); + } + } + Ok(found) +} + +/// Walks an OCI index down to image manifests. A nested index is a +/// multi-platform image: take the host's entry (or those asked for), not +/// every architecture. +fn oci_candidates( + store: &Store, + files: &HashMap, + descriptor: &Value, + platforms: &[Platform], + parent_tag: Option<&str>, + depth: usize, + steps: &mut usize, +) -> io::Result> { + if depth > MAX_OCI_DEPTH { + return Err(invalid("OCI index is nested too deeply")); + } + if *steps >= MAX_OCI_STEPS { + return Err(invalid("OCI index has too many entries")); + } + *steps += 1; + let tag = descriptor_tag(descriptor, parent_tag)?; + let (digest, _) = descriptor_blob(files, descriptor)?; + let doc: Value = serde_json::from_slice(&store.read_config(&digest)?).map_err(|e| invalid(format!("OCI blob: {e}")))?; + if let Some(manifests) = doc["manifests"].as_array() { + return resolve_index(store, files, manifests, platforms, tag.as_deref(), depth + 1, steps); + } + if doc["config"].is_object() && doc["layers"].is_array() { + if !platforms.is_empty() { + let config_digest = descriptor_blob(files, &doc["config"])?.0; + let (os, arch) = config_platform(store, &config_digest)?; + if !platforms.iter().any(|want| os == want.os && arch == want.architecture) { + return Ok(Vec::new()); + } + } + return Ok(vec![Candidate { manifest: digest, tag }]); + } + Err(invalid(format!("OCI blob {digest} is neither an image manifest nor an index"))) +} + +fn load_oci( + store: &Store, + files: &HashMap, + index: &[u8], + oci_layout: Option<&[u8]>, + platforms: &[Platform], +) -> io::Result> { + if let Some(layout) = oci_layout { + let v: Value = serde_json::from_slice(layout).map_err(|e| invalid(format!("oci-layout: {e}")))?; + if v["imageLayoutVersion"].as_str() != Some("1.0.0") { + return Err(invalid("unsupported oci-layout version")); + } + } + let index: Value = serde_json::from_slice(index).map_err(|e| invalid(format!("index.json: {e}")))?; + let descriptors = index["manifests"].as_array().ok_or_else(|| invalid("index.json has no manifests"))?; + let mut steps = 0usize; + let candidates = resolve_index(store, files, descriptors, platforms, None, 0, &mut steps)?; + if candidates.is_empty() { + if !platforms.is_empty() { + let wanted = platforms.iter().map(Platform::to_string).collect::>().join(", "); + return Err(invalid(format!("requested platform ({wanted}) not found: image might be filtered out"))); + } + return Err(invalid("OCI index contains no image manifests")); + } + let mut loaded = Vec::new(); + for candidate in candidates { + let manifest: Value = serde_json::from_slice(&store.read_config(&candidate.manifest)?).map_err(|e| invalid(format!("OCI manifest: {e}")))?; + let config_digest = descriptor_blob(files, &manifest["config"])?.0; + let config: Value = serde_json::from_slice(&store.read_config(&config_digest)?).map_err(|e| invalid(format!("image config: {e}")))?; + let mut layers = Vec::new(); + for l in manifest["layers"].as_array().into_iter().flatten() { + let (digest, size) = descriptor_blob(files, l)?; + let media_type = match l["mediaType"] + .as_str() + .filter(|m| m.starts_with("application/vnd.") && !m.bytes().any(|b| b.is_ascii_control() || b.is_ascii_whitespace())) + { + Some(m) => m.to_owned(), + None => media_type_of(&store.blob_path(&digest)?)?.to_owned(), + }; + layers.push(Layer { digest, size, media_type }); + } + let name = candidate.tag.unwrap_or_else(|| config_digest.clone()); + loaded.push(from_config(name, &config_digest, &config, layers)); + } + for image in &loaded { + store.put_image(image.clone())?; } Ok(loaded) } @@ -120,7 +397,11 @@ pub fn save(store: &Store, images: &[Image], out: impl Write) -> io::Result<()> let mut by_config: Vec<(&Image, Vec)> = Vec::new(); for i in images { match by_config.iter_mut().find(|(first, _)| first.config_digest == i.config_digest) { - Some((_, tags)) => tags.push(i.name.clone()), + Some((_, tags)) => { + if !i.name.starts_with("sha256:") { + tags.push(i.name.clone()); + } + } None => by_config.push((i, if i.name.starts_with("sha256:") { vec![] } else { vec![i.name.clone()] })), } } @@ -389,10 +670,553 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + fn add_file(b: &mut tar::Builder>, name: &str, data: &[u8]) { + let mut h = tar::Header::new_ustar(); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut h, name, data).unwrap(); + } + + fn put(store: &Store, data: &[u8]) -> (String, u64) { + let mut w = store.ingest().unwrap(); + w.write_all(data).unwrap(); + w.finish().unwrap() + } + + fn add_blob(b: &mut tar::Builder>, store: &Store, digest: &str) { + let hex = digest.strip_prefix("sha256:").unwrap(); + add_file(b, &format!("blobs/sha256/{hex}"), &std::fs::read(store.blob_path(digest).unwrap()).unwrap()); + } + + /// One image manifest and its config/layer blobs, in `b`. Returns the + /// descriptor an OCI index would use to point at it. + fn add_image_with_layer(b: &mut tar::Builder>, store: &Store, arch: &str, layer: &[u8], media_type: &str) -> Value { + let config = serde_json::to_vec(&json!({ + "architecture": arch, "os": "linux", "created": "2026-01-01T00:00:00Z", + "config": {"Cmd": ["echo", "hi"], "Env": ["A=1"]}, "rootfs": {"type": "layers", "diff_ids": []}, + })) + .unwrap(); + let (config_digest, config_size) = put(store, &config); + let (layer_digest, layer_size) = put(store, layer); + let manifest = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": config_digest, "size": config_size}, + "layers": [{"mediaType": media_type, "digest": layer_digest, "size": layer_size}], + })) + .unwrap(); + let (digest, size) = put(store, &manifest); + for d in [&config_digest, &layer_digest, &digest] { + add_blob(b, store, d); + } + json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", "digest": digest, "size": size, + "platform": {"os": "linux", "architecture": arch}, + }) + } + + fn add_image(b: &mut tar::Builder>, store: &Store, arch: &str) -> Value { + let mut layer = tar::Builder::new(Vec::new()); + add_file(&mut layer, "etc/hi", b"hi"); + let layer = layer.into_inner().unwrap(); + add_image_with_layer(b, store, arch, &layer, "application/vnd.oci.image.layer.v1.tar") + } + + fn add_index(b: &mut tar::Builder>, descriptors: Vec) { + add_file(b, "oci-layout", br#"{"imageLayoutVersion":"1.0.0"}"#); + add_file(b, "index.json", &serde_json::to_vec(&json!({"schemaVersion": 2, "manifests": descriptors})).unwrap()); + } + + #[test] + fn loads_an_oci_layout_archive() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + let mut d = add_image(&mut b, &store, "arm64"); + d["annotations"] = json!({"org.opencontainers.image.ref.name": "demo/oci:1"}); + add_index(&mut b, vec![d]); + let bytes = b.into_inner().unwrap(); + + let other = Store::open(dir.join("other")).unwrap(); + let images = load(&other, bytes.as_slice()).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].name, "demo/oci:1"); + assert_eq!(images[0].platform, "linux/arm64"); + assert_eq!(images[0].config.cmd, ["echo", "hi"]); + assert_eq!(images[0].config.env, ["A=1"]); + assert_eq!(images[0].layers.len(), 1); + assert!(images[0].layers[0].media_type.ends_with("tar")); + assert_eq!(other.find("demo/oci:1").unwrap().unwrap().config_digest, images[0].config_digest); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn loads_oci_archive_with_containerd_image_name_over_tag_only_ref_name() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + // BuildKit/containerd writes full ref in io.containerd.image.name and only the tag in ref.name. + let mut d = add_image(&mut b, &store, "amd64"); + d["annotations"] = json!({ + "io.containerd.image.name": "docker.io/kiri-test/oci:1", + "org.opencontainers.image.ref.name": "1", + }); + add_index(&mut b, vec![d]); + let bytes = b.into_inner().unwrap(); + + let other = Store::open(dir.join("other")).unwrap(); + let images = load(&other, bytes.as_slice()).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].name, "kiri-test/oci:1"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn loads_an_untagged_oci_image_by_id() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + let d = add_image(&mut b, &store, "arm64"); + let mut d_empty = add_image(&mut b, &store, "amd64"); + d_empty["annotations"] = json!({"org.opencontainers.image.ref.name": ""}); + // Two distinct untagged descriptors would prefer host; test a single untagged one alone. + add_index(&mut b, vec![d]); + let bytes = b.into_inner().unwrap(); + + let other = Store::open(dir.join("other")).unwrap(); + let images = load(&other, bytes.as_slice()).unwrap(); + assert_eq!(images.len(), 1); + assert!(images[0].name.starts_with("sha256:")); + assert_eq!(images[0].name, images[0].config_digest); + + let mut b2 = tar::Builder::new(Vec::new()); + let mut d_empty2 = add_image(&mut b2, &store, "amd64"); + d_empty2["annotations"] = json!({"org.opencontainers.image.ref.name": ""}); + add_index(&mut b2, vec![d_empty2]); + let other2 = Store::open(dir.join("other2")).unwrap(); + let images2 = load(&other2, b2.into_inner().unwrap().as_slice()).unwrap(); + assert_eq!(images2.len(), 1); + assert!(images2[0].name.starts_with("sha256:")); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn loads_oci_layers_with_gzip_zstd_and_uncompressed() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let config = serde_json::to_vec(&json!({ + "architecture": "amd64", "os": "linux", "created": "2026-01-01T00:00:00Z", + "config": {"Cmd": ["true"]}, "rootfs": {"type": "layers", "diff_ids": []}, + })) + .unwrap(); + let (cfg, cfg_sz) = put(&store, &config); + let (raw, raw_sz) = put(&store, b"plain tar bytes"); + let (gz, gz_sz) = put(&store, b"\x1f\x8bgzip bytes"); + let (zst, zst_sz) = put(&store, b"\x28\xb5\x2f\xfdzstd bytes"); + let manifest = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": cfg, "size": cfg_sz}, + "layers": [ + {"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": raw, "size": raw_sz}, + {"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "digest": gz, "size": gz_sz}, + {"mediaType": "application/vnd.oci.image.layer.v1.tar+zstd", "digest": zst, "size": zst_sz}, + ], + })) + .unwrap(); + let (man, man_sz) = put(&store, &manifest); + let mut b = tar::Builder::new(Vec::new()); + for d in [&cfg, &raw, &gz, &zst, &man] { + add_blob(&mut b, &store, d); + } + add_index(&mut b, vec![json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": man, "size": man_sz, + "annotations": {"org.opencontainers.image.ref.name": "demo/layers:1"}, + })]); + + let other = Store::open(dir.join("other")).unwrap(); + let loaded = load(&other, b.into_inner().unwrap().as_slice()).unwrap(); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].layers[0].media_type, "application/vnd.oci.image.layer.v1.tar"); + assert_eq!(loaded[0].layers[1].media_type, "application/vnd.oci.image.layer.v1.tar+gzip"); + assert_eq!(loaded[0].layers[2].media_type, "application/vnd.oci.image.layer.v1.tar+zstd"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn picks_a_platform_from_a_nested_oci_index_and_skips_attestations() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + let host = Platform::host_linux(); + let other_arch = if host.architecture == "amd64" { "arm64" } else { "amd64" }; + let host_d = add_image(&mut b, &store, &host.architecture); + let other_d = add_image(&mut b, &store, other_arch); + let att_d = json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": format!("sha256:{}", "9".repeat(64)), + "size": 123, + "platform": {"os": "unknown", "architecture": "unknown"}, + "annotations": {"vnd.docker.reference.type": "attestation-manifest"}, + }); + let nested = serde_json::to_vec(&json!({"schemaVersion": 2, "manifests": [host_d, other_d, att_d]})).unwrap(); + let (nested_digest, nested_size) = put(&store, &nested); + add_blob(&mut b, &store, &nested_digest); + add_index(&mut b, vec![json!({ + "mediaType": "application/vnd.oci.image.index.v1+json", "digest": nested_digest, "size": nested_size, + "annotations": { + "io.containerd.image.name": "docker.io/demo/multi:1", + "org.opencontainers.image.ref.name": "1", + }, + })]); + let bytes = b.into_inner().unwrap(); + + // With no platform, this machine's entry wins. + let native = Store::open(dir.join("native")).unwrap(); + let images = load(&native, bytes.as_slice()).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].name, "demo/multi:1"); + assert_eq!(images[0].platform, format!("linux/{}", host.architecture)); + + // An explicit platform picks that entry instead. + let foreign = Store::open(dir.join("foreign")).unwrap(); + let wanted = Platform { os: "linux".into(), architecture: other_arch.into() }; + let images = load_with_platform(&foreign, bytes.as_slice(), Some(&wanted)).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].name, "demo/multi:1"); + assert_eq!(images[0].platform, format!("linux/{other_arch}")); + + // And a platform nobody carries is a clear error, not a silent load or attestation fallback. + let missing = Store::open(dir.join("missing")).unwrap(); + let wanted = Platform { os: "linux".into(), architecture: "s390x".into() }; + let err = load_with_platform(&missing, bytes.as_slice(), Some(&wanted)).unwrap_err(); + assert!(err.to_string().contains("linux/s390x"), "{err}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn picks_host_from_flat_oci_index_and_keeps_distinct_tags() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let host = Platform::host_linux(); + let other_arch = if host.architecture == "amd64" { "arm64" } else { "amd64" }; + + // Flat multi-arch index with same tag (and missing foreign blobs). + let mut b = tar::Builder::new(Vec::new()); + let mut host_d = add_image(&mut b, &store, &host.architecture); + host_d["annotations"] = json!({"org.opencontainers.image.ref.name": "demo/flat:1"}); + let other_d = json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": format!("sha256:{}", "7".repeat(64)), + "size": 99, + "platform": {"os": "linux", "architecture": other_arch}, + "annotations": {"org.opencontainers.image.ref.name": "demo/flat:1"}, + }); + add_index(&mut b, vec![other_d, host_d]); + let native = Store::open(dir.join("native")).unwrap(); + let images = load(&native, b.into_inner().unwrap().as_slice()).unwrap(); + assert_eq!(images.len(), 1); + assert_eq!(images[0].platform, format!("linux/{}", host.architecture)); + + // Multiple distinct images in index.json all load. + let mut b2 = tar::Builder::new(Vec::new()); + let mut a = add_image(&mut b2, &store, &host.architecture); + a["annotations"] = json!({"org.opencontainers.image.ref.name": "demo/a:1"}); + let mut c = add_image(&mut b2, &store, other_arch); + c["annotations"] = json!({"org.opencontainers.image.ref.name": "demo/b:1"}); + add_index(&mut b2, vec![a, c]); + let multi = Store::open(dir.join("multi")).unwrap(); + let images = load(&multi, b2.into_inner().unwrap().as_slice()).unwrap(); + assert_eq!(images.len(), 2); + assert_eq!(images[0].name, "demo/a:1"); + assert_eq!(images[1].name, "demo/b:1"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn rejects_a_damaged_or_traversal_oci_blob() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + let mut d = add_image(&mut b, &store, "arm64"); + d["digest"] = json!(format!("sha256:{}", "0".repeat(64))); + add_file(&mut b, &format!("blobs/sha256/{}", "0".repeat(64)), b"not that blob"); + add_index(&mut b, vec![d]); + let bytes = b.into_inner().unwrap(); + + let other = Store::open(dir.join("other")).unwrap(); + assert!(load(&other, bytes.as_slice()).unwrap_err().to_string().contains("damaged")); + assert_eq!(std::fs::read_dir(dir.join("other/blobs/sha256")).unwrap().count(), 0); + + // Traversal and uppercase digests in index.json are rejected by digest_hex / lowercase check. + for bad_digest in ["sha256:../../evil".to_owned(), format!("sha256:{}", "A".repeat(64))] { + let mut b2 = tar::Builder::new(Vec::new()); + add_file(&mut b2, "evil", b"{}"); + add_index(&mut b2, vec![json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": bad_digest, + "size": 2, + })]); + let other2 = Store::open(dir.join("other2")).unwrap(); + let err = load(&other2, b2.into_inner().unwrap().as_slice()).unwrap_err(); + assert!(err.to_string().contains("invalid sha256 digest"), "{err}"); + let _ = std::fs::remove_dir_all(dir.join("other2")); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn rejects_cyclic_oci_index_without_overflow() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + let leaf = add_image(&mut b, &store, "amd64"); + let mut prev = leaf; + for _ in 0..10 { + let idx = serde_json::to_vec(&json!({"schemaVersion": 2, "manifests": [prev]})).unwrap(); + let (d, sz) = put(&store, &idx); + add_blob(&mut b, &store, &d); + prev = json!({"mediaType": "application/vnd.oci.image.index.v1+json", "digest": d, "size": sz}); + } + add_index(&mut b, vec![prev]); + let other = Store::open(dir.join("other")).unwrap(); + let err = load(&other, b.into_inner().unwrap().as_slice()).unwrap_err(); + assert!(err.to_string().contains("nested too deeply"), "{err}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn fast_path_skips_disk_write_for_existing_blobs() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut layer_builder = tar::Builder::new(Vec::new()); + add_file(&mut layer_builder, "data.txt", b"fast path test content\n"); + let layer_bytes = layer_builder.into_inner().unwrap(); + let layer_digest = crate::store::sha256_digest(&layer_bytes); + let layer_hex = layer_digest.strip_prefix("sha256:").unwrap(); + + let config = json!({"architecture": "arm64", "os": "linux", "created": "2026-11-23T00:00:00Z", + "config": {"Cmd": ["/bin/sh"]}, + "rootfs": {"type": "layers", "diff_ids": []}}); + let config_bytes = serde_json::to_vec(&config).unwrap(); + let config_digest = crate::store::sha256_digest(&config_bytes); + let config_hex = config_digest.strip_prefix("sha256:").unwrap(); + + let manifest = json!([{ + "Config": format!("blobs/sha256/{config_hex}"), + "RepoTags": ["fastpath:v1"], + "Layers": [format!("blobs/sha256/{layer_hex}")] + }]); + + let mut archive = tar::Builder::new(Vec::new()); + add_file(&mut archive, &format!("blobs/sha256/{config_hex}"), &config_bytes); + add_file(&mut archive, &format!("blobs/sha256/{layer_hex}"), &layer_bytes); + add_file(&mut archive, "manifest.json", &serde_json::to_vec(&manifest).unwrap()); + let tar_data = archive.into_inner().unwrap(); + + let first = load(&store, tar_data.as_slice()).unwrap(); + assert_eq!(first.len(), 1); + let blob_path = store.blob_path(&layer_digest).unwrap(); + let mtime_before = std::fs::metadata(&blob_path).unwrap().modified().unwrap(); + + // Second load hits the fast-path without rewriting the blob on disk. + let second = load(&store, tar_data.as_slice()).unwrap(); + assert_eq!(second.len(), 1); + let mtime_after = std::fs::metadata(&blob_path).unwrap().modified().unwrap(); + assert_eq!(mtime_before, mtime_after); + + // Also test fast-path on an OCI layout archive sharing the same layer. + let oci_manifest = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": config_digest, "size": config_bytes.len()}, + "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": layer_digest, "size": layer_bytes.len()}], + })) + .unwrap(); + let oci_manifest_digest = crate::store::sha256_digest(&oci_manifest); + let oci_manifest_hex = oci_manifest_digest.strip_prefix("sha256:").unwrap(); + let mut oci_archive = tar::Builder::new(Vec::new()); + add_file(&mut oci_archive, &format!("blobs/sha256/{config_hex}"), &config_bytes); + add_file(&mut oci_archive, &format!("blobs/sha256/{layer_hex}"), &layer_bytes); + add_file(&mut oci_archive, &format!("blobs/sha256/{oci_manifest_hex}"), &oci_manifest); + add_index(&mut oci_archive, vec![json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": oci_manifest_digest, "size": oci_manifest.len(), + "annotations": {"org.opencontainers.image.ref.name": "fastpath-oci:v1"}, + })]); + let third = load(&store, oci_archive.into_inner().unwrap().as_slice()).unwrap(); + assert_eq!(third.len(), 1); + assert_eq!(std::fs::metadata(&blob_path).unwrap().modified().unwrap(), mtime_before); + + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn fast_path_rejects_tampered_tar_entry_matching_existing_blob_size() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let real_layer = b"authentic layer bytes!!"; + let (layer_digest, layer_size) = put(&store, real_layer); + let layer_hex = layer_digest.strip_prefix("sha256:").unwrap(); + let config = serde_json::to_vec(&json!({"architecture": "amd64", "os": "linux", "config": {}})).unwrap(); + let (cfg_digest, _cfg_size) = put(&store, &config); + let cfg_hex = cfg_digest.strip_prefix("sha256:").unwrap(); + + // Keep an image referencing the authentic layer in the store. + let existing = from_config("legit:1".into(), &cfg_digest, &serde_json::from_slice(&config).unwrap(), vec![Layer { + digest: layer_digest.clone(), size: layer_size, media_type: "application/vnd.oci.image.layer.v1.tar".into(), + }]); + store.put_image(existing).unwrap(); + + // Adversarial archive claims path blobs/sha256/ with the same byte size + // as the existing blob in the store, but different content. + let tampered_layer = b"tampered! layer bytes!!"; + assert_eq!(tampered_layer.len() as u64, layer_size); + let manifest = json!([{ + "Config": format!("blobs/sha256/{cfg_hex}"), + "RepoTags": ["spoof:1"], + "Layers": [format!("blobs/sha256/{layer_hex}")] + }]); + let mut archive = tar::Builder::new(Vec::new()); + add_file(&mut archive, &format!("blobs/sha256/{cfg_hex}"), &config); + add_file(&mut archive, &format!("blobs/sha256/{layer_hex}"), tampered_layer); + add_file(&mut archive, "manifest.json", &serde_json::to_vec(&manifest).unwrap()); + + let err = load(&store, archive.into_inner().unwrap().as_slice()).unwrap_err(); + assert!(err.to_string().contains("damaged"), "{err}"); + assert!(store.find("spoof:1").unwrap().is_none()); + assert_eq!(std::fs::read(store.blob_path(&layer_digest).unwrap()).unwrap(), real_layer); + + // Same adversarial check against an OCI layout archive. + let oci_manifest = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": cfg_digest, "size": config.len()}, + "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": layer_digest, "size": layer_size}], + })) + .unwrap(); + let oci_digest = crate::store::sha256_digest(&oci_manifest); + let oci_hex = oci_digest.strip_prefix("sha256:").unwrap(); + let mut oci_archive = tar::Builder::new(Vec::new()); + add_file(&mut oci_archive, &format!("blobs/sha256/{cfg_hex}"), &config); + add_file(&mut oci_archive, &format!("blobs/sha256/{layer_hex}"), tampered_layer); + add_file(&mut oci_archive, &format!("blobs/sha256/{oci_hex}"), &oci_manifest); + add_index(&mut oci_archive, vec![json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": oci_digest, "size": oci_manifest.len(), + "annotations": {"org.opencontainers.image.ref.name": "spoof-oci:1"}, + })]); + let err = load(&store, oci_archive.into_inner().unwrap().as_slice()).unwrap_err(); + assert!(err.to_string().contains("damaged"), "{err}"); + assert!(store.find("spoof-oci:1").unwrap().is_none()); + + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn rejects_invalid_oci_tags_and_cleans_up_new_blobs() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + // Pre-seed one blob in store; it must survive a refused load. + let (kept_layer, kept_size) = put(&store, b"preexisting layer"); + let kept_hex = kept_layer.strip_prefix("sha256:").unwrap(); + let config = serde_json::to_vec(&json!({"architecture": "amd64", "os": "linux", "config": {}})).unwrap(); + let (cfg_digest, _cfg_size) = put(&store, &config); + let cfg_hex = cfg_digest.strip_prefix("sha256:").unwrap(); + store.put_image(from_config("kept:1".into(), &cfg_digest, &serde_json::from_slice(&config).unwrap(), vec![Layer { + digest: kept_layer.clone(), size: kept_size, media_type: "application/vnd.oci.image.layer.v1.tar".into(), + }])).unwrap(); + + let fresh_config = serde_json::to_vec(&json!({"architecture": "amd64", "os": "linux", "config": {"Cmd": ["/bin/bad"]}})).unwrap(); + let fresh_cfg_digest = crate::store::sha256_digest(&fresh_config); + let fresh_cfg_hex = fresh_cfg_digest.strip_prefix("sha256:").unwrap(); + let manifest = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": fresh_cfg_digest, "size": fresh_config.len()}, + "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": kept_layer, "size": kept_size}], + })) + .unwrap(); + let man_digest = crate::store::sha256_digest(&manifest); + let man_hex = man_digest.strip_prefix("sha256:").unwrap(); + + let mut b = tar::Builder::new(Vec::new()); + add_file(&mut b, &format!("blobs/sha256/{cfg_hex}"), &config); + add_file(&mut b, &format!("blobs/sha256/{kept_hex}"), b"preexisting layer"); + add_file(&mut b, &format!("blobs/sha256/{fresh_cfg_hex}"), &fresh_config); + add_file(&mut b, &format!("blobs/sha256/{man_hex}"), &manifest); + add_index(&mut b, vec![json!({ + "mediaType": "application/vnd.oci.image.manifest.v1+json", + "digest": man_digest, "size": manifest.len(), + "annotations": {"org.opencontainers.image.ref.name": format!("alpine@sha256:{}", "a".repeat(64))}, + })]); + + assert!(load(&store, b.into_inner().unwrap().as_slice()).is_err()); + assert!(store.has_blob(&kept_layer, kept_size)); + assert!(!store.has_blob(&fresh_cfg_digest, fresh_config.len() as u64)); + assert!(!store.has_blob(&man_digest, manifest.len() as u64)); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn tags_get_latest() { assert_eq!(tagged("alpine"), "alpine:latest"); assert_eq!(tagged("localhost:5000/app"), "localhost:5000/app:latest"); assert_eq!(tagged("app:1"), "app:1"); } + + #[test] + fn rejects_invalid_repo_tags_and_cleans_up_blobs() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let config = br#"{"architecture":"amd64","os":"linux","config":{},"rootfs":{"type":"layers","diff_ids":[]}}"#; + let digest_tag = format!("alpine@sha256:{}", "a".repeat(64)); + for bad_tag in ["evil\".com/x:1", digest_tag.as_str()] { + let manifest = json!([{"Config": "cfg.json", "RepoTags": [bad_tag], "Layers": []}]); + let mut b = tar::Builder::new(Vec::new()); + add_file(&mut b, "cfg.json", config); + add_file(&mut b, "manifest.json", &serde_json::to_vec(&manifest).unwrap()); + let bytes = b.into_inner().unwrap(); + + assert!(load(&store, bytes.as_slice()).is_err(), "{bad_tag}"); + assert!(store.images().unwrap().is_empty(), "{bad_tag}"); + assert_eq!(std::fs::read_dir(dir.join("blobs/sha256")).unwrap().count(), 0, "{bad_tag}"); + } + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn failed_loads_remove_ingested_blobs_and_save_skips_untagged_ids() { + let dir = scratch(); + let store = Store::open(&dir).unwrap(); + let mut b = tar::Builder::new(Vec::new()); + for (name, body) in [("layer1.tar", &b"one"[..]), ("layer2.tar", &b"two"[..])] { + let mut h = tar::Header::new_ustar(); + h.set_size(body.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut h, name, body).unwrap(); + } + let mut cut = b.into_inner().unwrap(); + cut.truncate(512 + 300); + assert!(load(&store, cut.as_slice()).is_err()); + assert_eq!(std::fs::read_dir(dir.join("blobs/sha256")).unwrap().count(), 0); + + let put = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let cfg = json!({"os": "linux", "architecture": "arm64", "config": {}}); + let (cfg_digest, _) = put(&serde_json::to_vec(&cfg).unwrap()); + let (layer, size) = put(b"layer"); + let layers = vec![Layer { digest: layer, size, media_type: "application/vnd.oci.image.layer.v1.tar".into() }]; + let named = from_config("demo:1".into(), &cfg_digest, &cfg, layers.clone()); + let untagged = from_config(cfg_digest.clone(), &cfg_digest, &cfg, layers); + let mut tarball = Vec::new(); + save(&store, &[named, untagged], &mut tarball).unwrap(); + + let other = Store::open(dir.join("other")).unwrap(); + let loaded = load(&other, tarball.as_slice()).unwrap(); + assert_eq!(loaded.len(), 1); + assert_eq!(loaded[0].name, "demo:1"); + std::fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/kiri-image/src/cancel.rs b/crates/kiri-image/src/cancel.rs index a87a9a90d..bd537a48b 100644 --- a/crates/kiri-image/src/cancel.rs +++ b/crates/kiri-image/src/cancel.rs @@ -13,6 +13,24 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, Weak}; use std::time::{Duration, Instant}; +/// Windows does not reliably interrupt a blocking Winsock read when another +/// thread calls `shutdown`, so a cancellable read must not block for longer +/// than one poll: it runs nonblocking, and a poll with nothing to read waits +/// [`POLL`]. Everywhere else (Linux, or a pull no one can cancel) reads stay +/// blocking with the full budget, exactly as before. +pub(crate) const POLL: Duration = Duration::from_millis(100); + +/// Whether the current thread is inside a cancellable pull, on Windows. +/// Only there can a cross-thread `shutdown` leave the blocking recv asleep. +pub(crate) fn polling() -> bool { + cfg!(windows) && active() +} + +/// Whether the current thread is inside a cancellable pull. +pub(crate) fn active() -> bool { + CURRENT.with(|c| c.borrow().is_some()) +} + /// A pull's cancel switch. Clones share it. #[derive(Debug, Clone, Default)] pub struct Cancel(Arc); @@ -126,7 +144,23 @@ mod tests { let _on = cancel.enter(); watch(&client).unwrap(); let started = Instant::now(); - let n = (&*client).read(&mut [0u8; 16]).unwrap_or(0); + // The transport reads nonblocking under a cancellable pull on + // Windows (blocking Winsock reads ignore a cross-thread + // shutdown). A raw read must still end promptly once the + // switch flips, so poll the switch like await_input does. + let n = if polling() { + client.set_nonblocking(true).unwrap(); + loop { + match (&*client).read(&mut [0u8; 16]) { + Err(e) if e.kind() == io::ErrorKind::WouldBlock && !cancel.is_cancelled() => { + std::thread::sleep(Duration::from_millis(50)); + } + res => break res.unwrap_or(0), + } + } + } else { + (&*client).read(&mut [0u8; 16]).unwrap_or(0) + }; (n, started.elapsed()) }) }; diff --git a/crates/kiri-image/src/connect.rs b/crates/kiri-image/src/connect.rs index 9668b4211..079034d3f 100644 --- a/crates/kiri-image/src/connect.rs +++ b/crates/kiri-image/src/connect.rs @@ -49,11 +49,30 @@ pub(crate) fn connector_with(stall: Duration) -> impl Connector<(), Out = impl T ().chain(ConnectProxyConnector::default()).chain(HappyConnector { stall }).chain(RustlsConnector::default()) } +/// The TLS settings every verified ureq agent is built on: the merged roots +/// (`trusted`, the system's store and the bundled set) and ring. ureq is +/// built without its bundled roots or a default provider, so an agent +/// without these fails its first https call. +pub fn tls_config(roots: &[rustls_pki_types::CertificateDer<'static>]) -> ureq::tls::TlsConfig { + ureq::tls::TlsConfig::builder() + .root_certs(ureq::tls::RootCerts::Specific(Arc::new( + roots + .iter() + .map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()) + .collect::>(), + ))) + .unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider())) + .build() +} + /// TLS without checking the server's certificate: only for the hosts /// daemon.json lists in `insecure-registries` (a self-signed registry), as /// Docker reaches them. Nothing else is built on it. pub(crate) fn unverified_tls_config() -> ureq::tls::TlsConfig { - ureq::tls::TlsConfig::builder().disable_verification(true).build() + ureq::tls::TlsConfig::builder() + .disable_verification(true) + .unversioned_rustls_crypto_provider(Arc::new(rustls::crypto::ring::default_provider())) + .build() } /// The addresses in the order to try them: the family the resolver put @@ -247,6 +266,46 @@ impl Transport for TcpTransport { crate::cancel::watch(&self.stream)?; let started = Instant::now(); let input = self.buffers.input_append_buf(); + // Windows inside a cancellable pull: a cross-thread `shutdown` may + // leave the blocking recv asleep (verified: it waited out its whole + // timeout past the shutdown), so read nonblocking and check the + // cancel switch at most every POLL. `limit` stays the one full + // budget for this call: a poll that finds nothing loops on, it does + // not end the read; only `limit` running out does. Everywhere else + // the plain blocking read below keeps the socket timeout semantics + // unchanged. + if crate::cancel::polling() { + self.stream.set_nonblocking(true)?; + let result = loop { + if crate::cancel::current_cancelled() { + break Err(Error::Io(io::Error::other("pull cancelled"))); + } + match (&*self.stream).read(input) { + Err(e) if e.kind() == io::ErrorKind::Interrupted => continue, + // Nothing yet: wait one poll, then check the switch again. + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + let left = limit.map(|l| l.saturating_sub(started.elapsed())); + if left.is_some_and(|l| l.is_zero()) { + break Err(Error::Timeout(timeout.reason)); + } + std::thread::sleep(left.map_or(crate::cancel::POLL, |l| l.min(crate::cancel::POLL))); + } + // EOF, or a real error (a shutdown from the cancel side + // reads as ConnectionAborted/Reset): restore the mode, + // and report a cancelled pull as its own error. + Ok(n) => break Ok(n), + Err(_) if crate::cancel::current_cancelled() => { + break Err(Error::Io(io::Error::other("pull cancelled"))); + } + Err(e) => break Err(io_error(e, timeout.reason)), + } + }; + let restore = self.stream.set_nonblocking(false); + let amount = result?; + restore?; + self.buffers.input_appended(amount); + return Ok(amount > 0); + } let amount = loop { match (&*self.stream).read(input) { // A signal: Linux does not restart a socket read that has a @@ -262,7 +321,24 @@ impl Transport for TcpTransport { self.stream.set_read_timeout(Some(left))?; self.timeout_read = Some(left); } - result => break result.map_err(|e| io_error(e, timeout.reason))?, + result => { + break result.map_err(|e| { + if crate::cancel::current_cancelled() + && matches!( + e.kind(), + io::ErrorKind::TimedOut + | io::ErrorKind::WouldBlock + | io::ErrorKind::ConnectionReset + | io::ErrorKind::ConnectionAborted + | io::ErrorKind::BrokenPipe + ) + { + Error::Io(io::Error::other("pull cancelled")) + } else { + io_error(e, timeout.reason) + } + })?; + } } }; self.buffers.input_appended(amount); diff --git a/crates/kiri-image/src/jsonfile.rs b/crates/kiri-image/src/jsonfile.rs index 2aacc95d0..d29953db9 100644 --- a/crates/kiri-image/src/jsonfile.rs +++ b/crates/kiri-image/src/jsonfile.rs @@ -77,7 +77,7 @@ pub fn replace(path: &Path, bytes: &[u8], durable: Durable) -> io::Result<()> { /// folder, so the rename itself is on disk. Nothing to do if there is no /// file (yet). pub fn sync(path: &Path) -> io::Result<()> { - match File::open(path) { + match open_for_sync(path) { Ok(f) => synced(&f)?, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()), Err(e) => return Err(e), @@ -86,6 +86,20 @@ pub fn sync(path: &Path) -> io::Result<()> { Ok(()) } +/// Opens `path` so [`File::sync_all`] can flush it. Windows' +/// `FlushFileBuffers` rejects a read-only handle (`ERROR_ACCESS_DENIED`), +/// so ask for write access (without creating, truncating or modifying +/// anything) and fall back to read-only when the file cannot be opened for +/// writing. +fn open_for_sync(path: &Path) -> io::Result { + fs::OpenOptions::new().read(true).write(true).open(path).or_else(|e| match e.kind() { + io::ErrorKind::PermissionDenied + | io::ErrorKind::ReadOnlyFilesystem + | io::ErrorKind::IsADirectory => File::open(path), + _ => Err(e), + }) +} + fn parent(path: &Path) -> &Path { path.parent().unwrap_or(Path::new(".")) } @@ -231,6 +245,34 @@ mod tests { let _ = fs::remove_dir_all(d); } + #[test] + fn sync_keeps_contents_and_falls_back_read_only() { + let d = dir("sync"); + let p = d.join("list.json"); + let missing = d.join("missing.json"); + fs::write(&p, b"[1,2]").unwrap(); + + let before = syncs_here(); + sync(&p).unwrap(); + assert_eq!(syncs_here(), before + 1); + assert_eq!(fs::read(&p).unwrap(), b"[1,2]"); + + sync(&missing).unwrap(); + assert!(!missing.exists(), "sync never creates a missing file"); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&p, fs::Permissions::from_mode(0o444)).unwrap(); + sync(&p).unwrap(); + assert_eq!(fs::read(&p).unwrap(), b"[1,2]"); + sync(&d).unwrap(); + fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); + } + + let _ = fs::remove_dir_all(d); + } + #[test] fn move_aside_keeps_the_bytes_and_is_listed() { let d = dir("aside"); diff --git a/crates/kiri-image/src/lib.rs b/crates/kiri-image/src/lib.rs index d34334881..8b8569929 100644 --- a/crates/kiri-image/src/lib.rs +++ b/crates/kiri-image/src/lib.rs @@ -11,11 +11,14 @@ pub mod jsonfile; pub mod mirror; pub mod reference; pub mod registry; +pub mod roots; +pub mod storage; pub mod store; pub mod tags; pub use cancel::Cancel; pub use config::{Insecure, RegistryConfig}; +pub use connect::tls_config; pub use mirror::Mirror; pub use reference::Reference; pub use registry::{ diff --git a/crates/kiri-image/src/reference.rs b/crates/kiri-image/src/reference.rs index 9eb7e5b87..1f4d81ca1 100644 --- a/crates/kiri-image/src/reference.rs +++ b/crates/kiri-image/src/reference.rs @@ -33,6 +33,11 @@ impl Reference { if input.is_empty() || input.chars().any(char::is_whitespace) { return Err(bad()); } + let valid_tag = |t: &str| { + t.as_bytes().first().is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_') + && t.len() <= 128 + && t.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) + }; let (name, reference) = if let Some((name, digest)) = input.split_once('@') { if crate::store::digest_hex(digest).is_err() { return Err(bad()); @@ -41,8 +46,7 @@ impl Reference { // in Docker, but it must still be a valid one. let name = match name.rfind(':') { Some(i) if !name[i..].contains('/') => { - let tag = &name[i + 1..]; - if tag.is_empty() || !tag.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) { + if !valid_tag(&name[i + 1..]) { return Err(bad()); } &name[..i] @@ -52,13 +56,17 @@ impl Reference { (name, digest.to_owned()) } else { // A colon after the last slash is a tag; one before it is a port. - match input.rfind(':') { - Some(i) if !input[i..].contains('/') => (&input[..i], input[i + 1..].to_owned()), - _ => (input, "latest".to_owned()), + let (name, tag) = match input.rfind(':') { + Some(i) if !input[i..].contains('/') => (&input[..i], &input[i + 1..]), + _ => (input, "latest"), + }; + if !valid_tag(tag) { + return Err(bad()); } + (name, tag.to_owned()) }; // Repository names are lowercase; tags may use any case. - if name.is_empty() || reference.is_empty() || name.chars().any(|c| c.is_ascii_uppercase()) { + if name.is_empty() || name.chars().any(|c| c.is_ascii_uppercase()) { return Err(bad()); } // The first component is a registry only if it looks like a host. @@ -73,7 +81,18 @@ impl Reference { } else { repository }; - if repository.split('/').any(str::is_empty) { + // A reference names a registry on the network and a path in a store, and + // is written into buildkitd.toml, log lines and other programs' arguments. + // Only a real host[:port], clean repository path segments and a valid tag + // or digest are accepted: a quote or a backslash in a name a `docker load` + // archive supplies would close a string wherever it is written. + let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit(); + let valid_seg = |s: &str| { + s.as_bytes().first().is_some_and(|&b| alnum(b)) + && s.as_bytes().last().is_some_and(|&b| alnum(b)) + && s.bytes().all(|b| alnum(b) || b".-_".contains(&b)) + }; + if crate::config::canonical(®istry).is_none() || repository.is_empty() || !repository.split('/').all(valid_seg) { return Err(bad()); } Ok(Reference { registry, repository, reference }) @@ -151,8 +170,13 @@ mod tests { assert_eq!(r("bitnami/redis:7"), s("docker.io", "bitnami/redis", "7")); assert_eq!(r("ghcr.io/o/r:v1"), s("ghcr.io", "o/r", "v1")); assert_eq!(r("localhost:5000/app"), s("localhost:5000", "app", "latest")); + assert_eq!(r("[::1]:5000/app:1"), s("[::1]:5000", "app", "1")); + assert_eq!(r("[::1]:5000/app"), s("[::1]:5000", "app", "latest")); + assert_eq!(r("localhost:5000/my_app-1.2/sub.repo:v1.0_build-2"), s("localhost:5000", "my_app-1.2/sub.repo", "v1.0_build-2")); + assert_eq!(r("localhost:5000/a__b--c.d:_tag-1.0"), s("localhost:5000", "a__b--c.d", "_tag-1.0")); let d = format!("sha256:{}", "a".repeat(64)); assert_eq!(r(&format!("alpine@{d}")), s("docker.io", "library/alpine", &d)); + assert_eq!(r(&format!("[::1]:5000/my_app-1.2/sub.repo:v1.0_build-2@{d}")), s("[::1]:5000", "my_app-1.2/sub.repo", &d)); } #[test] @@ -183,7 +207,36 @@ mod tests { fn rejects_garbage() { let non_hex = format!("alpine@sha256:{}", "g".repeat(64)); let traversal = format!("alpine@sha256:{}", "../".repeat(21) + "ab"); - for s in ["", "a b", "alpine:", "alpine@sha256:short", "/x", "Alpine", &non_hex, &traversal] { + for s in [ + "", + "a b", + "alpine:", + "alpine:1:2", + "ghcr.io/o/r:1:2", + "alpine@sha256:short", + "/x", + "Alpine", + "evil\".com/x:1", + "evil\\com/x:1", + "host/x:ta\"g", + "host/x?y:1", + "h#x/y:1", + "docker.io/a/../b:1", + "docker.io/./a:1", + "alpine:..", + "alpine:.x", + "alpine:-x", + "-bad/app:1", + "bad-/app:1", + "_bad/app:1", + "bad_/app:1", + "docker.io/.bad:1", + "docker.io/bad.:1", + "[not-ipv6]:5000/app:1", + "host:99999/app:1", + &non_hex, + &traversal, + ] { assert!(Reference::parse(s).is_err(), "{s}"); } } diff --git a/crates/kiri-image/src/registry.rs b/crates/kiri-image/src/registry.rs index 9c7865d72..40f78bc48 100644 --- a/crates/kiri-image/src/registry.rs +++ b/crates/kiri-image/src/registry.rs @@ -14,7 +14,7 @@ use crate::config::{Reach, RegistryConfig}; use crate::mirror::Mirror; use crate::tags::{next_link, version_order}; use crate::reference::Reference; -use crate::store::{Image, Layer, RunConfig, Store, sha256_digest}; +use crate::store::{Image, Layer, Pin, RunConfig, Store, sha256_digest}; const ACCEPT: &str = "application/vnd.oci.image.index.v1+json, \ application/vnd.docker.distribution.manifest.list.v2+json, \ @@ -563,7 +563,7 @@ const IDLE: Duration = Duration::from_secs(90); /// hop is checked (never from HTTPS down to plain HTTP to a host the list /// does not allow, credentials only to the origin first asked). fn shared_agent() -> ureq::Agent { - static AGENT: Mutex> = Mutex::new(None); + static AGENT: Mutex> = Mutex::new(None); cached_agent(&AGENT, false) } @@ -573,15 +573,19 @@ fn shared_agent() -> ureq::Agent { /// goes to a verified connection. Made the first time a listed host is /// asked, never otherwise. fn insecure_agent() -> ureq::Agent { - static AGENT: Mutex> = Mutex::new(None); + static AGENT: Mutex> = Mutex::new(None); cached_agent(&AGENT, true) } -fn cached_agent(slot: &Mutex>, insecure: bool) -> ureq::Agent { +fn cached_agent(slot: &Mutex>, insecure: bool) -> ureq::Agent { let chosen = PROXY_SOURCE.get().and_then(|f| f()); + // A host's roots arriving (kiri-win, from the Windows store) builds the + // verified agent again too. + let roots = if insecure { 0 } else { crate::roots::generation() }; let mut slot = slot.lock().unwrap_or_else(|e| e.into_inner()); - if let Some((c, agent)) = slot.as_ref() + if let Some((c, g, agent)) = slot.as_ref() && *c == chosen + && *g == roots { return agent.clone(); } @@ -597,9 +601,12 @@ fn cached_agent(slot: &Mutex>, insecure: bool // Redirects are followed by hand, hop by hop ([`Client::get_following`]). .max_redirects(0); // A listed host's certificate is not checked, as Docker reaches an - // insecure registry; every other agent keeps ureq's verified TLS. + // insecure registry; every other agent verifies against the merged roots + // so corporate proxies and private CAs trusted by the OS work (#303). if insecure { cfg = cfg.tls_config(crate::connect::unverified_tls_config()); + } else { + cfg = cfg.tls_config(crate::tls_config(&crate::roots::trusted())); } if let Some(p) = proxy(chosen.clone()) { cfg = cfg.proxy(p); @@ -607,7 +614,7 @@ fn cached_agent(slot: &Mutex>, insecure: bool // Happy Eyeballs rather than ureq's one address after another, so an // IPv6 address without a working route does not stall the pull. let agent = ureq::Agent::with_parts(cfg.build(), crate::connect::connector(), ureq::unversioned::resolver::DefaultResolver::default()); - *slot = Some((chosen, agent.clone())); + *slot = Some((chosen, roots, agent.clone())); agent } @@ -1141,7 +1148,7 @@ impl Client { // An index lists one manifest per platform; pick ours and fetch it. let index_digest = manifest.manifests.is_some().then(|| sha256_digest(&bytes)); - let (manifest, digest) = if let Some(entries) = manifest.manifests { + let (index_bytes, manifest, manifest_bytes, digest) = if let Some(entries) = manifest.manifests { let wanted = entries.iter().find(|m| { m.platform.as_ref().is_some_and(|p| p.os == platform.os && p.architecture == platform.architecture) }); @@ -1156,19 +1163,20 @@ impl Client { .collect(), }); }; - let (bytes, _) = self.manifest(r, &entry.digest).map_err(stopped)?; - if sha256_digest(&bytes) != entry.digest { + let (entry_bytes, _) = self.manifest(r, &entry.digest).map_err(stopped)?; + if sha256_digest(&entry_bytes) != entry.digest { return Err(Error::Manifest(format!("manifest {} failed digest check", entry.digest))); } - let m: Manifest = serde_json::from_slice(&bytes).map_err(|e| Error::Manifest(e.to_string()))?; - (m, entry.digest.clone()) + let m: Manifest = serde_json::from_slice(&entry_bytes).map_err(|e| Error::Manifest(e.to_string()))?; + (Some(bytes), m, entry_bytes, entry.digest.clone()) } else { if r.is_digest() && sha256_digest(&bytes) != r.reference { return Err(Error::Manifest("manifest failed digest check".into())); } - (manifest, sha256_digest(&bytes)) + let d = sha256_digest(&bytes); + (None, manifest, bytes, d) }; - Ok(Resolved { target: r.clone(), index_digest, digest, manifest, media_type }) + Ok(Resolved { target: r.clone(), index_digest, index_bytes, digest, manifest, manifest_bytes, media_type }) } /// The second half of a pull: the config and layers of `resolved`, @@ -1183,7 +1191,7 @@ impl Client { progress: &(dyn Fn(Progress) + Sync), cancel: &Cancel, ) -> Result { - let Resolved { target, index_digest, digest, manifest, media_type } = resolved; + let Resolved { target, index_digest, index_bytes, digest, manifest, manifest_bytes, media_type } = resolved; let (Some(config), Some(layers)) = (manifest.config.as_ref(), manifest.layers.as_ref()) else { return Err(Error::Manifest(format!("{media_type} has no config or layers"))); }; @@ -1201,13 +1209,20 @@ impl Client { queue.sort_by_key(|l| l.size); let queue = Mutex::new(queue); let first_error: Mutex> = Mutex::new(None); + // Every reused and newly written blob is held until `store.put_image` + // records the image, so a concurrent tag replacement or removal of + // another image sharing a blob cannot delete it mid-pull. + let pins: Mutex> = Mutex::new(Vec::new()); // Bounded: the manifest declares the size, and a config is small. let fetch_config = || -> Result<(), Error> { let _on = cancel.enter(); - if store.has_blob(&config.digest, config.size) { + if let Some(pin) = store.pin_existing(&config.digest, config.size) { + pins.lock().unwrap_or_else(|e| e.into_inner()).push(pin); return Ok(()); } - self.download_with(store, target, &config.digest, crate::store::MAX_CONFIG, Some(config.size), &|_| {}, cancel).map(|_| ()) + let (_, pin) = self.download_with(store, target, &config.digest, crate::store::MAX_CONFIG, Some(config.size), &|_| {}, cancel)?; + pins.lock().unwrap_or_else(|e| e.into_inner()).push(pin); + Ok(()) }; // A mirror stands in for Docker Hub: an image for another platform // than the one asked is not Hub's answer, and the pull moves on @@ -1222,11 +1237,20 @@ impl Client { } } // The layers are announced once the pull will fetch them: a mirror - // passed over above shows none. - let cached = layers.iter().filter(|l| store.has_blob(&l.digest, l.size)).count(); - progress(Progress::Resolved { layers: layers.len(), bytes: total, cached }); + // passed over above shows none. Pin any already on disk right away so + // they stay cached until the workers and `put_image` finish. + let mut initial_cached = Vec::with_capacity(layers.len()); for l in &layers { - progress(Progress::Layer { digest: l.digest.clone(), size: l.size, cached: store.has_blob(&l.digest, l.size) }); + let pin = store.pin_existing(&l.digest, l.size); + initial_cached.push(pin.is_some()); + if let Some(pin) = pin { + pins.lock().unwrap_or_else(|e| e.into_inner()).push(pin); + } + } + let cached = initial_cached.iter().filter(|&&c| c).count(); + progress(Progress::Resolved { layers: layers.len(), bytes: total, cached }); + for (l, &cached) in layers.iter().zip(&initial_cached) { + progress(Progress::Layer { digest: l.digest.clone(), size: l.size, cached }); } std::thread::scope(|s| { // From the registry itself the config comes alongside the layers @@ -1248,15 +1272,21 @@ impl Client { if cancel.is_cancelled() || first_error.lock().unwrap_or_else(|e| e.into_inner()).is_some() { return; } - let cached = store.has_blob(&layer.digest, layer.size); - let result = if cached { - Ok(layer.size) + let (cached, result) = if let Some(pin) = store.pin_existing(&layer.digest, layer.size) { + pins.lock().unwrap_or_else(|e| e.into_inner()).push(pin); + (true, Ok(layer.size)) } else { // No more than the manifest says (one byte over is // what tells a longer body from the end), and // exactly that. let on_bytes = |got| progress(Progress::Downloading { digest: layer.digest.clone(), got, size: layer.size }); - self.download_with(store, target, &layer.digest, layer.size.saturating_add(1), Some(layer.size), &on_bytes, cancel) + match self.download_with(store, target, &layer.digest, layer.size.saturating_add(1), Some(layer.size), &on_bytes, cancel) { + Ok((bytes, pin)) => { + pins.lock().unwrap_or_else(|e| e.into_inner()).push(pin); + (false, Ok(bytes)) + } + Err(e) => (false, Err(e)), + } }; match result { Ok(bytes) => progress(Progress::LayerDone { digest: layer.digest.clone(), bytes, cached }), @@ -1276,6 +1306,7 @@ impl Client { if let Some(e) = first_error.into_inner().unwrap_or_else(|e| e.into_inner()) { return Err(e); } + let mut pins = pins.into_inner().unwrap_or_else(|e| e.into_inner()); let cfg_bytes = store.read_config(&config.digest)?; let cfg: ImageConfig = serde_json::from_slice(&cfg_bytes).map_err(|e| Error::Manifest(e.to_string()))?; @@ -1299,11 +1330,30 @@ impl Client { }, mirror, }; + // Keep the registry's exact manifest and multi-arch index bytes in the + // blob store so Kiri's build mirror can serve digest-pinned FROM + // references (`FROM repo:tag@sha256:…` and `FROM repo@sha256:…`) with + // matching SHA-256 digests (#288, #330). + let mut save_raw = |d: &str, bytes: &[u8]| -> Result<(), Error> { + if let Some(pin) = store.pin_existing(d, bytes.len() as u64) { + pins.push(pin); + return Ok(()); + } + let mut w = store.blob_writer(d)?; + w.write_all(bytes)?; + pins.push(w.finish_pinned()?); + Ok(()) + }; + save_raw(digest, manifest_bytes)?; + if let (Some(idx_digest), Some(idx_bytes)) = (index_digest.as_deref(), index_bytes.as_deref()) { + save_raw(idx_digest, idx_bytes)?; + } // The last moment a cancel can stop it: after this it is pulled. if cancel.is_cancelled() { return Err(Error::Cancelled); } store.put_image(image.clone())?; + drop(pins); Ok(image) } @@ -1331,7 +1381,7 @@ impl Client { /// Streams one blob into the store, verifying its digest. Returns its size. #[cfg(test)] fn download(&self, store: &Store, r: &Reference, digest: &str, on_bytes: &dyn Fn(u64)) -> Result { - self.download_with(store, r, digest, u64::MAX, None, on_bytes, &Cancel::new()) + Ok(self.download_with(store, r, digest, u64::MAX, None, on_bytes, &Cancel::new())?.0) } /// Downloads a blob, telling `on_bytes` how much has arrived every @@ -1343,7 +1393,7 @@ impl Client { /// exactly `want` bytes when given (before it goes into the store), and /// stops (removing what it wrote) once `cancel` is. #[allow(clippy::too_many_arguments)] - fn download_with(&self, store: &Store, r: &Reference, digest: &str, max: u64, want: Option, on_bytes: &dyn Fn(u64), cancel: &Cancel) -> Result { + fn download_with(&self, store: &Store, r: &Reference, digest: &str, max: u64, want: Option, on_bytes: &dyn Fn(u64), cancel: &Cancel) -> Result<(u64, Pin), Error> { // A declared size bounds the read too: one byte over it is enough // to tell a longer body from the end. let max = want.map_or(max, |w| w.saturating_add(1).min(max)); @@ -1386,7 +1436,7 @@ impl Client { Ok(()) if want.is_some_and(|w| w != got) => { return Err(Error::Manifest(format!("{digest} is {got} bytes, the manifest says {}", want.unwrap_or_default()))); } - Ok(()) => return Ok(out.finish()?), + Ok(()) => return Ok((got, out.finish_pinned()?)), Err(_) if cancel.is_cancelled() => return Err(Error::Cancelled), Err(e) if transient(&e) => { failed = if got > before { 1 } else { failed + 1 }; @@ -1844,7 +1894,10 @@ fn printable(text: &str) -> String { /// Parses `Bearer realm="…",service="…",scope="…"`. fn parse_challenge(header: &str) -> HashMap { - let rest = header.strip_prefix("Bearer ").unwrap_or(header); + let rest = match header.get(..7) { + Some(p) if p.eq_ignore_ascii_case("bearer ") => &header[7..], + _ => header, + }; let mut out = HashMap::new(); let mut s = rest; while let Some(eq) = s.find('=') { @@ -1879,8 +1932,10 @@ struct Token { struct Resolved { target: Reference, index_digest: Option, + index_bytes: Option>, digest: String, manifest: Manifest, + manifest_bytes: Vec, media_type: String, } @@ -2226,6 +2281,9 @@ mod tests { assert_eq!(p["realm"], "https://auth.docker.io/token"); assert_eq!(p["service"], "registry.docker.io"); assert_eq!(p["scope"], "repository:library/alpine:pull"); + let lower = parse_challenge(r#"bearer realm="https://ghcr.io/token",service="ghcr.io""#); + assert_eq!(lower["realm"], "https://ghcr.io/token"); + assert_eq!(lower["service"], "ghcr.io"); } #[test] @@ -2425,7 +2483,11 @@ mod tests { } fn test_client() -> Client { - let cfg = ureq::Agent::config_builder().http_status_as_error(false).max_redirects(0).build(); + let cfg = ureq::Agent::config_builder() + .http_status_as_error(false) + .max_redirects(0) + .tls_config(crate::tls_config(&crate::roots::trusted())) + .build(); let agent = ureq::Agent::with_parts(cfg, crate::connect::connector_with(Duration::from_millis(300)), ureq::unversioned::resolver::DefaultResolver::default()); Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None } } @@ -2658,6 +2720,43 @@ mod tests { let _ = std::fs::remove_dir_all(&root); } + #[test] + fn a_cancellable_download_keeps_its_read_budget_for_slow_data() { + let (data, digest) = blob(); + let body = data.clone(); + let (host, served) = blob_server(move |_, c| { + // Both response headers and body data may take longer than a + // cancellation poll. Neither is a stall within the 2 s budget. + std::thread::sleep(Duration::from_millis(400)); + let _ = write!(c, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len()); + let _ = c.write_all(&body[..body.len() / 2]); + std::thread::sleep(Duration::from_millis(400)); + let _ = c.write_all(&body[body.len() / 2..]); + }); + let root = std::env::temp_dir().join(format!("kiri-slow-cancel-test-{}", std::process::id())); + let store = Store::open(&root).unwrap(); + let reference = Reference::parse(&format!("{host}/test/blob:1")).unwrap(); + let config = ureq::Agent::config_builder() + .http_status_as_error(false) + .tls_config(crate::tls_config(&crate::roots::trusted())) + .build(); + let agent = ureq::Agent::with_parts(config, crate::connect::connector_with(Duration::from_secs(2)), ureq::unversioned::resolver::DefaultResolver::default()); + let client = Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None }; + let _ = client.base(&host); + let cancel = Cancel::new(); + let result = { + let _on = cancel.enter(); + client.download_with(&store, &reference, &digest, u64::MAX, None, &|_| {}, &cancel) + }; + quit(&host); + let requests = served.join().unwrap(); + let saved = store.has_blob(&digest, data.len() as u64); + let _ = std::fs::remove_dir_all(&root); + assert_eq!(result.unwrap().0, data.len() as u64); + assert!(saved); + assert_eq!(requests, [0], "slow data must not start a retry"); + } + #[test] fn a_cancelled_download_stops_at_once_and_leaves_nothing() { let (data, digest) = blob(); @@ -2672,7 +2771,10 @@ mod tests { let store = Store::open(&root).unwrap(); let r = Reference::parse(&format!("{host}/test/blob:1")).unwrap(); // Stalls only give up after 10 s: the cancel must not wait for that. - let cfg = ureq::Agent::config_builder().http_status_as_error(false).build(); + let cfg = ureq::Agent::config_builder() + .http_status_as_error(false) + .tls_config(crate::tls_config(&crate::roots::trusted())) + .build(); let agent = ureq::Agent::with_parts(cfg, crate::connect::connector_with(Duration::from_secs(10)), ureq::unversioned::resolver::DefaultResolver::default()); let client = Client { agent, credentials: None, config: Default::default(), use_mirrors: true, mirror_scheme: None }; // A loopback registry's scheme is asked once (HTTPS, then HTTP): @@ -4074,4 +4176,17 @@ mod tests { }); (host, served) } + + /// The shared pull agent verifies against the merged roots, every one + /// of them and in order, not the bundled set only (#303). + #[test] + fn the_shared_agent_trusts_the_merged_roots() { + let agent = shared_agent(); + let ureq::tls::RootCerts::Specific(certs) = agent.config().tls_config().root_certs() else { + panic!("the shared agent must trust a list of roots of its own"); + }; + let roots = crate::roots::trusted(); + assert_eq!(certs.len(), roots.len()); + assert!(certs.iter().zip(roots.iter()).all(|(a, b)| a.der() == b.as_ref())); + } } diff --git a/crates/kiri-image/src/roots.rs b/crates/kiri-image/src/roots.rs new file mode 100644 index 000000000..ff3a73004 --- /dev/null +++ b/crates/kiri-image/src/roots.rs @@ -0,0 +1,672 @@ +//! The roots every outbound TLS connection trusts: the system's own store +//! (the macOS keychain trust settings, the Windows store, `/etc/ssl` on +//! Linux) merged with the Mozilla set Kiri bundles. A company root CA the +//! system trusts then works for pulls, logins and Share (#303), and a +//! Linux host without `ca-certificates` still reaches Docker Hub. +//! +//! `SSL_CERT_FILE` and `SSL_CERT_DIR` are honoured on every platform, like +//! curl and OpenSSL: when either is set, [`system`] reads the certificates +//! from there instead of the platform store. The bundled roots stay in. +//! +//! A root the administrator distrusted stays out even though the bundled +//! set has it: "Never Trust" in the user or admin trust settings on macOS, +//! the Disallowed store (and roots disabled for Server Authentication) on +//! Windows. Linux has no such list to read (a root is distrusted there by +//! taking it out of the bundle), so a Mozilla root removed from `/etc/ssl` +//! is still trusted through the bundled set. A distrusted self-issued root +//! is matched by subject and public key, so a re-issued copy of it goes +//! too; a distrusted cross-certificate is matched as itself only, so the +//! self-signed root it shares a key with stays. With `KIRI_TLS_ROOTS=webpki` +//! nothing is read from the system, distrusted roots included: the bundled +//! set is used as it is. +//! +//! On Windows the engine runs in WSL, away from the Windows store: kiri-win +//! sends the daemon the Windows roots the bundled set lacks and the +//! distrusted list ([`host_export`]), and the daemon adds them +//! ([`set_host`]), so a company root works for pulls as on the Mac. +//! +//! Self-contained on purpose: kiri-win compiles this file by path, as it +//! does share.rs, without depending on kiri-image. Nothing here may name +//! ureq or rustls, only the crates kiri-win has for it (design after +//! brunoselvacj's, issue #303). + +use std::panic::{self, UnwindSafe}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; + +use rustls_pki_types::CertificateDer; + +/// Which roots to trust, from `KIRI_TLS_ROOTS`. The variable is read when +/// the roots are built, not at startup. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// The system's store and the bundled set: the default. + Merged, + /// The bundled set only, as it was before the system store was read: + /// `KIRI_TLS_ROOTS=webpki`, for a system store that causes trouble. + BundledOnly, +} + +/// The mode `var` (an environment lookup) asks for. Every value other than +/// `webpki` — including an unset variable — keeps the merged roots. +pub fn mode(var: impl Fn(&str) -> Option) -> Mode { + match var("KIRI_TLS_ROOTS").as_deref() { + Some("webpki") => Mode::BundledOnly, + _ => Mode::Merged, + } +} + +/// The roots to trust: `platform`'s, unless `mode` leaves them out, then +/// `bundled`. `platform` is only called when its roots are used. +pub fn merge( + mode: Mode, + platform: impl FnOnce() -> Vec>, + bundled: &[CertificateDer<'static>], +) -> Vec> { + let mut roots = match mode { + Mode::Merged => platform(), + Mode::BundledOnly => Vec::new(), + }; + roots.extend(bundled.iter().cloned()); + roots +} + +/// The Mozilla set Kiri bundles. +pub fn bundled() -> &'static [CertificateDer<'static>] { + webpki_root_certs::TLS_SERVER_ROOT_CERTS +} + +/// A certificate's issuer, subject and public key, each as DER. +type Identity<'a> = (&'a [u8], &'a [u8], &'a [u8]); + +/// The issuer, subject and public key of a certificate (their DER, as written in +/// it): what names a root, as opposed to one issue of it. None when `der` +/// is not a certificate this can read. +fn identity(der: &[u8]) -> Option> { + // One DER element: (tag, content, what follows). + fn element(b: &[u8]) -> Option<(u8, &[u8], &[u8])> { + let (&tag, rest) = b.split_first()?; + let (&first, rest) = rest.split_first()?; + let (len, rest) = if first < 0x80 { + (usize::from(first), rest) + } else { + let n = usize::from(first & 0x7f); + if n == 0 || n > 4 || rest.len() < n { + return None; + } + (rest[..n].iter().fold(0usize, |a, &x| a << 8 | usize::from(x)), &rest[n..]) + }; + (rest.len() >= len).then(|| (tag, &rest[..len], &rest[len..])) + } + // Certificate ::= SEQUENCE { tbsCertificate SEQUENCE { [0] version + // OPTIONAL, serial, signature, issuer, validity, subject, spki, ... } } + let (cert_tag, cert, tail) = element(der)?; + if cert_tag != 0x30 || !tail.is_empty() { + return None; + } + let (tbs_tag, tbs, _) = element(cert)?; + if tbs_tag != 0x30 { + return None; + } + let mut rest = tbs; + if let Some((0xa0, _, after_ver)) = element(rest) { + rest = after_ver; + } + // Serial number, signature algorithm, then issuer, validity, subject, spki. + for _ in 0..2 { + rest = element(rest)?.2; + } + let (issuer_tag, _, after_issuer) = element(rest)?; + if issuer_tag != 0x30 { + return None; + } + let issuer = &rest[..rest.len() - after_issuer.len()]; + let after_validity = element(after_issuer)?.2; + let (subject_tag, _, after_subject) = element(after_validity)?; + if subject_tag != 0x30 { + return None; + } + let subject = &after_validity[..after_validity.len() - after_subject.len()]; + let (spki_tag, _, after_spki) = element(after_subject)?; + if spki_tag != 0x30 { + return None; + } + let spki = &after_subject[..after_subject.len() - after_spki.len()]; + Some((issuer, subject, spki)) +} + +/// Whether `c` is `d`, a distrusted certificate. A self-issued root is +/// distrusted by its subject and public key, so a re-issued copy of it (new +/// dates, same key) goes too. Any other certificate (a cross-certificate: +/// the same name and key as a root, but issued by another one) is distrusted +/// as itself only, so the self-signed root it vouches for stays. Certificates +/// this cannot read are compared whole. +fn same_root(c: &CertificateDer<'_>, d: &CertificateDer<'_>) -> bool { + match (identity(c), identity(d)) { + (Some((_, subject, key)), Some((issuer, d_subject, d_key))) if issuer == d_subject => subject == d_subject && key == d_key, + _ => c == d, + } +} + +/// `roots` without any certificate that is one of `distrusted` (see +/// [`same_root`]). +pub fn without( + mut roots: Vec>, + distrusted: &[CertificateDer<'static>], +) -> Vec> { + if !distrusted.is_empty() { + roots.retain(|c| !distrusted.iter().any(|d| same_root(c, d))); + } + roots +} + +/// The roots a Windows host adds to the engine in WSL: the Windows store's +/// roots that the bundled set lacks (a company root, among them), and the +/// ones its administrator distrusted. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Host { + pub certs: Vec>, + pub distrusted: Vec>, +} + +/// The most certificates a [`Host`] list may hold, the largest single +/// certificate, and the most total DER bytes per list (so both lists hex-encoded +/// together always stay comfortably below the daemon's 8 MiB body limit). +pub const HOST_MAX_CERTS: usize = 1024; +pub const HOST_MAX_CERT_BYTES: usize = 16 << 10; +pub const HOST_MAX_LIST_DER_BYTES: usize = 1536 << 10; + +/// Keeps non-empty certificates within [`HOST_MAX_CERT_BYTES`], stopping once +/// [`HOST_MAX_CERTS`] or [`HOST_MAX_LIST_DER_BYTES`] would be exceeded. +fn cap_list(iter: impl IntoIterator>) -> Vec> { + let mut out = Vec::new(); + let mut bytes = 0usize; + for cert in iter { + let len = cert.as_ref().len(); + if len == 0 || len > HOST_MAX_CERT_BYTES { + continue; + } + if out.len() >= HOST_MAX_CERTS || bytes.saturating_add(len) > HOST_MAX_LIST_DER_BYTES { + break; + } + bytes += len; + out.push(cert); + } + out +} + +impl Host { + /// The lists, each certificate as hex (JSON has no bytes), dropping + /// what is past the caps. + pub fn from_hex<'a>( + certs: impl IntoIterator, + distrusted: impl IntoIterator, + ) -> Host { + let read = |list: &mut dyn Iterator| { + cap_list( + list.filter(|h| h.len() <= HOST_MAX_CERT_BYTES * 2) + .filter_map(unhex) + .map(CertificateDer::from), + ) + }; + Host { + certs: read(&mut certs.into_iter()), + distrusted: read(&mut distrusted.into_iter()), + } + } +} + +/// `der` as lowercase hex. +pub fn hex(der: &[u8]) -> String { + const DIGITS: &[u8; 16] = b"0123456789abcdef"; + let mut s = String::with_capacity(der.len().saturating_mul(2)); + for b in der { + s.push(DIGITS[usize::from(b >> 4)] as char); + s.push(DIGITS[usize::from(b & 15)] as char); + } + s +} + +/// The bytes `s` spells in hex, or none if it is not hex. +pub fn unhex(s: &str) -> Option> { + let digit = |c: u8| (c as char).to_digit(16).map(|d| d as u8); + let b = s.as_bytes(); + if !b.len().is_multiple_of(2) { + return None; + } + b.chunks(2).map(|p| Some(digit(p[0])? << 4 | digit(p[1])?)).collect() +} + +/// `base` with a host's roots: its certificates added, and every +/// certificate it distrusts taken out, its own included. +pub fn with_host(base: &[CertificateDer<'static>], host: &Host) -> Vec> { + let mut roots = base.to_vec(); + roots.extend(host.certs.iter().filter(|c| !base.contains(c)).cloned()); + without(roots, &host.distrusted) +} + +/// This process's mode, read once with its roots. +fn mode_now() -> Mode { + static MODE: OnceLock = OnceLock::new(); + *MODE.get_or_init(|| mode(|k| std::env::var(k).ok())) +} + +/// The roots from this machine, read once on first use: reading the macOS +/// keychain asks Security.framework about each certificate. +fn base() -> &'static Arc<[CertificateDer<'static>]> { + static ROOTS: OnceLock]>> = OnceLock::new(); + ROOTS.get_or_init(|| { + let mode = mode_now(); + let roots = merge(mode, || guarded(system), bundled()); + match mode { + Mode::Merged => without(roots, &guarded(distrusted_by_system)), + Mode::BundledOnly => roots, + } + .into() + }) +} + +/// A host's roots as last set, with the list they make. +static HOST: Mutex]>)>> = Mutex::new(None); +static GENERATION: AtomicU64 = AtomicU64::new(0); + +/// Takes a host's roots (from kiri-win), and says whether that changed the +/// roots. `KIRI_TLS_ROOTS=webpki` keeps the bundled set alone, so then +/// they are kept but not used. +pub fn set_host(host: Host) -> bool { + let mut slot = HOST.lock().unwrap_or_else(|e| e.into_inner()); + if slot.as_ref().is_some_and(|(h, _)| *h == host) { + return false; + } + let roots = with_host(base(), &host).into(); + *slot = Some((host, roots)); + GENERATION.fetch_add(1, Ordering::SeqCst); + true +} + +/// Sets a host's roots only when none have been set yet, atomically under +/// the host lock, so a startup load from disk can never overwrite roots +/// kiri-win already pushed. +pub fn set_host_if_unset(host: Host) -> bool { + let mut slot = HOST.lock().unwrap_or_else(|e| e.into_inner()); + if slot.is_some() { + return false; + } + let roots = with_host(base(), &host).into(); + *slot = Some((host, roots)); + GENERATION.fetch_add(1, Ordering::SeqCst); + true +} + +/// A host's roots as last set, if any. +pub fn host() -> Option { + HOST.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(h, _)| h.clone()) +} + +/// Counts the changes [`set_host`] made, so a client built on [`trusted`] +/// knows to build again. +pub fn generation() -> u64 { + GENERATION.load(Ordering::SeqCst) +} + +/// The roots to trust: this machine's (read once), with a host's. +pub fn trusted() -> Arc<[CertificateDer<'static>]> { + let base = base(); + if mode_now() == Mode::BundledOnly { + return base.clone(); + } + match HOST.lock().unwrap_or_else(|e| e.into_inner()).as_ref() { + Some((_, roots)) => roots.clone(), + None => base.clone(), + } +} + +/// What this machine adds to the engine in WSL (kiri-win's side of +/// [`set_host`]): the store's roots the bundled set lacks, and the ones +/// distrusted. Nothing with `KIRI_TLS_ROOTS=webpki`. +pub fn host_export() -> Host { + if mode_now() == Mode::BundledOnly { + return Host::default(); + } + let bundled = bundled(); + let certs = cap_list(guarded(system).into_iter().filter(|c| !bundled.contains(c))); + let distrusted = cap_list(guarded(distrusted_by_system)); + Host { certs, distrusted } +} + +/// Certificates in Windows' `ROOT` store whose Server Authentication EKU is +/// disabled (`CERT_TRUST_IS_NOT_VALID_FOR_USAGE`): kept as distrusted when +/// they match a bundled root and no Server-Auth-enabled root in `ROOT` +/// shares the same identity, so disabling a Mozilla root in Windows keeps it +/// out of the merged set without dropping enabled roots or non-TLS roots. +#[cfg(any(windows, test))] +fn windows_root_disallowed( + disallowed_for_tls: &[CertificateDer<'static>], + allowed_in_root: &[CertificateDer<'static>], + bundled: &[CertificateDer<'static>], +) -> Vec> { + disallowed_for_tls + .iter() + .filter(|d| { + !allowed_in_root.iter().any(|a| same_root(a, d)) + && bundled.iter().any(|b| same_root(b, d)) + }) + .cloned() + .collect() +} + +/// The roots the administrator distrusted on macOS: "Never Trust" in the +/// user or admin trust settings, a user's setting first, as macOS weighs +/// them. Only those domains: they hold the few certificates someone set, +/// where the system domain would mean asking about every root again. +#[cfg(target_os = "macos")] +fn distrusted_by_system() -> Vec> { + use security_framework::trust_settings::{Domain, TrustSettings, TrustSettingsForCertificate}; + let mut seen: Vec<(Vec, bool)> = Vec::new(); + for domain in [Domain::User, Domain::Admin] { + let ts = TrustSettings::new(domain); + let Ok(iter) = ts.iter() else { continue }; + for cert in iter { + let der = cert.to_der(); + if seen.iter().any(|(d, _)| *d == der) { + continue; + } + let denied = matches!( + ts.tls_trust_settings_for_certificate(&cert), + Ok(Some(TrustSettingsForCertificate::Deny)) + ); + seen.push((der, denied)); + } + } + seen.into_iter().filter(|(_, denied)| *denied).map(|(der, _)| CertificateDer::from(der)).collect() +} + +/// The roots the administrator distrusted on Windows: the current user's +/// Disallowed store (which takes in the machine's and Group Policy's), plus +/// any bundled root whose Server Authentication EKU was disabled in `ROOT` +/// (`CERT_TRUST_IS_NOT_VALID_FOR_USAGE`). +#[cfg(windows)] +fn distrusted_by_system() -> Vec> { + use schannel::cert_context::ValidUses; + use schannel::cert_store::CertStoreBuilder; + const PKIX_SERVER_AUTH: &str = "1.3.6.1.5.5.7.3.1"; + let mut out = Vec::new(); + if let Ok(store) = CertStoreBuilder::new().read_only().open_current_user("Disallowed") { + out.extend(store.certs().map(|c| CertificateDer::from(c.to_der().to_vec()))); + } + if let Ok(store) = CertStoreBuilder::new().read_only().open_current_user("ROOT") { + let mut allowed = Vec::new(); + let mut disallowed_for_tls = Vec::new(); + for cert in store.certs() { + let der = CertificateDer::from(cert.to_der().to_vec()); + let valid_now = cert.is_time_valid().unwrap_or(false); + match cert.valid_uses() { + Ok(ValidUses::All) if valid_now => allowed.push(der), + Ok(ValidUses::Oids(oids)) if oids.iter().any(|o| o == PKIX_SERVER_AUTH) && valid_now => allowed.push(der), + Ok(ValidUses::Oids(oids)) if !oids.iter().any(|o| o == PKIX_SERVER_AUTH) => disallowed_for_tls.push(der), + _ => {} + } + } + out.extend(windows_root_disallowed(&disallowed_for_tls, &allowed, bundled())); + } + out +} + +/// Linux keeps no list of distrusted roots (see the module comment). +#[cfg(not(any(target_os = "macos", windows)))] +fn distrusted_by_system() -> Vec> { + Vec::new() +} + +/// `load`'s roots, or none if it panics (rustls-native-certs unwraps on +/// Windows), so a broken store costs the system roots, not the process. +fn guarded( + load: impl FnOnce() -> Vec> + UnwindSafe, +) -> Vec> { + panic::catch_unwind(load).unwrap_or_else(|_| { + eprintln!( + "kiri: reading the system certificate store failed; trusting the bundled roots only" + ); + Vec::new() + }) +} + +/// The system's roots. With `SSL_CERT_FILE` or `SSL_CERT_DIR` set, +/// rustls-native-certs reads those instead of the store, as OpenSSL does; +/// say so, as a company CA in the keychain is then not trusted. +fn system() -> Vec> { + let set = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty()); + if set("SSL_CERT_FILE") || set("SSL_CERT_DIR") { + eprintln!( + "kiri: SSL_CERT_FILE or SSL_CERT_DIR is set, so the system certificate store is not read" + ); + } + let found = rustls_native_certs::load_native_certs(); + // A fixed message: an error's text can carry certificate data, which + // doesn't belong in a log. + if !found.errors.is_empty() { + eprintln!("kiri: part of the system certificate store could not be read; the rest is trusted"); + } + found.certs +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn cert(byte: u8) -> CertificateDer<'static> { + CertificateDer::from(vec![byte]) + } + + #[test] + fn merges_the_system_roots_with_the_bundled_roots_by_default() { + let got = merge(Mode::Merged, || vec![cert(1)], &[cert(2)]); + + assert_eq!(got, vec![cert(1), cert(2)]); + } + + #[test] + fn kiri_tls_roots_webpki_selects_the_bundled_roots_only() { + let got = mode(|_| Some("webpki".into())); + + assert_eq!(got, Mode::BundledOnly); + } + + #[test] + fn kiri_tls_roots_with_another_value_selects_the_merged_roots() { + let got = mode(|_| Some("system".into())); + + assert_eq!(got, Mode::Merged); + } + + #[test] + fn kiri_tls_roots_unset_selects_the_merged_roots() { + let got = mode(|_| None); + + assert_eq!(got, Mode::Merged); + } + + #[test] + fn keeps_the_bundled_roots_when_the_system_store_is_empty() { + let got = merge(Mode::Merged, Vec::new, &[cert(2)]); + + assert_eq!(got, vec![cert(2)]); + } + + #[test] + fn bundled_only_mode_never_reads_the_system_store() { + let read = Cell::new(false); + + let got = merge( + Mode::BundledOnly, + || { + read.set(true); + vec![cert(1)] + }, + &[cert(2)], + ); + + assert!(!read.get()); + assert_eq!(got, vec![cert(2)]); + } + + #[test] + fn keeps_the_bundled_roots_when_reading_the_system_store_panics() { + let got = merge( + Mode::Merged, + || guarded(|| panic!("broken store")), + &[cert(2)], + ); + + assert_eq!(got, vec![cert(2)]); + } + + #[test] + fn keeps_the_system_roots_when_reading_the_system_store_succeeds() { + let got = guarded(|| vec![cert(1)]); + + assert_eq!(got, vec![cert(1)]); + } + + #[test] + fn a_reissued_copy_of_a_distrusted_root_is_removed_too() { + let root = bundled()[0].clone(); + // Same subject and key, different bytes: another issue of the root. + let mut other = root.as_ref().to_vec(); + *other.last_mut().unwrap() ^= 0xff; + let reissued = CertificateDer::from(other); + assert_ne!(reissued, root); + assert!(identity(&root).is_some(), "the bundled roots are readable"); + let kept = without(vec![reissued.clone(), bundled()[1].clone()], std::slice::from_ref(&root)); + assert_eq!(kept, vec![bundled()[1].clone()]); + // Unreadable entries fall back to whole-certificate comparison. + assert_eq!(without(vec![cert(1), cert(2)], &[cert(2)]), vec![cert(1)]); + } + + /// A certificate with these names and key, as the parser reads one. + fn fake(issuer: &str, subject: &str, key: &str, tag: u8) -> CertificateDer<'static> { + fn tlv(tag: u8, body: &[u8]) -> Vec { + let mut v = vec![tag, body.len() as u8]; + v.extend_from_slice(body); + v + } + let name = |n: &str| tlv(0x30, n.as_bytes()); + let mut tbs = tlv(0x02, &[tag]); + for part in [tlv(0x30, &[]), name(issuer), tlv(0x30, &[]), name(subject), tlv(0x30, key.as_bytes())] { + tbs.extend(part); + } + CertificateDer::from(tlv(0x30, &tlv(0x30, &tbs))) + } + + #[test] + fn distrusting_a_cross_certificate_keeps_the_root_it_shares_a_key_with() { + let root = fake("R", "R", "key", 1); + let reissued = fake("R", "R", "key", 2); + let cross = fake("D", "R", "key", 3); + let other = fake("O", "O", "other", 4); + // The cross-certificate (R's name and key, issued by D): only itself. + let kept = without(vec![root.clone(), cross.clone(), other.clone()], std::slice::from_ref(&cross)); + assert_eq!(kept, vec![root.clone(), other.clone()]); + // The self-signed root: itself and its re-issues. + let kept = without(vec![root.clone(), reissued, other.clone()], std::slice::from_ref(&root)); + assert_eq!(kept, vec![other]); + } + + #[test] + fn windows_disabled_eku_drops_disabled_bundled_root_but_keeps_enabled_and_cross_roots() { + let disabled_bundled = fake("B", "B", "kB", 1); + let reissued_bundled = fake("B", "B", "kB", 2); + let replaced_old = fake("R", "R", "kR", 1); + let replaced_new = fake("R", "R", "kR", 2); + let cross_disabled = fake("D", "S", "kS", 1); + let self_signed = fake("S", "S", "kS", 2); + let code_signing = fake("M", "M", "kM", 1); + + let got = windows_root_disallowed( + &[disabled_bundled.clone(), replaced_old.clone(), cross_disabled.clone(), code_signing], + std::slice::from_ref(&replaced_new), + &[reissued_bundled, replaced_new.clone(), self_signed], + ); + assert_eq!(got, vec![disabled_bundled]); + } + + #[test] + fn identity_rejects_non_sequence_or_trailing_garbage() { + let valid = fake("R", "R", "key", 1); + assert!(identity(&valid).is_some()); + let mut with_tail = valid.as_ref().to_vec(); + with_tail.push(0x00); + assert!(identity(&with_tail).is_none()); + let mut wrong_tag = valid.as_ref().to_vec(); + wrong_tag[0] = 0x04; + assert!(identity(&wrong_tag).is_none()); + } + + #[test] + fn the_bundled_set_is_not_empty() { + assert!(!webpki_root_certs::TLS_SERVER_ROOT_CERTS.is_empty()); + } + + /// The merged list holds the bundled roots (real certificates now, not + /// the bare anchors webpki-roots shipped) plus everything the platform + /// store has (nothing on a bare container, hundreds on a desktop), + /// less what the administrator distrusted. + #[test] + fn merged_roots_are_the_bundled_set_plus_the_platform_store() { + // With these set the platform store is replaced or left out, so + // the count below would not hold. + let set = |k: &str| std::env::var_os(k).is_some_and(|v| !v.is_empty()); + if set("SSL_CERT_FILE") || set("SSL_CERT_DIR") || mode(|k| std::env::var(k).ok()) != Mode::Merged { + return; + } + let platform = rustls_native_certs::load_native_certs().certs; + let expected = without( + platform.into_iter().chain(bundled().iter().cloned()).collect(), + &distrusted_by_system(), + ); + assert_eq!(trusted().len(), expected.len()); + } + + #[test] + fn a_distrusted_root_is_left_out_of_the_bundled_set_too() { + let got = without(vec![cert(1), cert(2), cert(3)], &[cert(2)]); + + assert_eq!(got, vec![cert(1), cert(3)]); + } + + #[test] + fn a_hosts_roots_are_added_and_its_distrusted_ones_taken_out() { + let host = Host { certs: vec![cert(4), cert(1)], distrusted: vec![cert(2), cert(4)] }; + + let got = with_host(&[cert(1), cert(2), cert(3)], &host); + + assert_eq!(got, vec![cert(1), cert(3)]); + } + + #[test] + fn hex_goes_both_ways() { + let der = (0..=255u8).collect::>(); + + assert_eq!(unhex(&hex(&der)).unwrap(), der); + assert_eq!(unhex("0A"), Some(vec![10])); + assert_eq!(unhex("abc"), None); + assert_eq!(unhex("zz"), None); + } + + #[test] + fn host_lists_drop_what_does_not_decode_and_what_is_past_the_caps() { + let big = "00".repeat(HOST_MAX_CERT_BYTES + 1); + let many = vec!["01"; HOST_MAX_CERTS + 5]; + + let host = Host::from_hex(["0102", "nothex", "", big.as_str()], many.iter().copied()); + + assert_eq!(host.certs, vec![CertificateDer::from(vec![1, 2])]); + assert_eq!(host.distrusted.len(), HOST_MAX_CERTS); + + // Total DER byte budget also caps a list of maximum-size certificates. + let max_one = vec![0xab; HOST_MAX_CERT_BYTES]; + let capped = cap_list((0..200).map(|_| CertificateDer::from(max_one.clone()))); + assert_eq!(capped.len(), HOST_MAX_LIST_DER_BYTES / HOST_MAX_CERT_BYTES); + } +} diff --git a/crates/kiri-image/src/storage.rs b/crates/kiri-image/src/storage.rs new file mode 100644 index 000000000..816ee0e43 --- /dev/null +++ b/crates/kiri-image/src/storage.rs @@ -0,0 +1,176 @@ +//! Settings → Storage: the folder a person chose for Kiri's data, kept in +//! `~/.kiri/storage.json` (`{"path": "/Volumes/External/kiri"}`), beside +//! `vm.json` and never inside the data folder itself. +//! +//! Nobody who leaves the setting alone has the file: [`crate::Store::default_root`] +//! then gives the folder it always did. With the file, the chosen folder +//! counts only while it holds the [`MARKER`] a finished move writes there: +//! a drive that isn't connected must not get an empty store made in its +//! place under `/Volumes`, so the folder is reported unavailable instead +//! ([`Unavailable`]). + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// The file, under the state folder (`~/.kiri`). +pub const FILE: &str = "storage.json"; + +/// Written into a data folder once a move into it is complete: what tells +/// a Kiri data folder from an empty mount point or someone else's files. +pub const MARKER: &str = ".kiri-storage"; + +/// What `storage.json` holds. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Choice { + /// The data folder. + pub path: PathBuf, + /// The folder the data was moved from and that still holds a copy, + /// until Settings → Storage → Remove old data. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub previous: Option, +} + +/// The chosen folder isn't there, or isn't Kiri's (its drive isn't +/// connected): the error [`crate::Store::default_root`] gives for it. +#[derive(Debug)] +pub struct Unavailable(pub PathBuf); + +impl std::fmt::Display for Unavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Kiri's data folder {} isn't available: connect its drive, or choose Settings → Storage → Reset to default", self.0.display()) + } +} + +impl std::error::Error for Unavailable {} + +/// The folder an [`Unavailable`] error names. +pub fn unavailable(e: &io::Error) -> Option<&Path> { + e.get_ref().and_then(|inner| inner.downcast_ref::()).map(|u| u.0.as_path()) +} + +/// `~/.kiri/storage.json`. +pub fn config_path() -> io::Result { + let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; + Ok(home.join(".kiri").join(FILE)) +} + +/// The choice in `file`; None when there is no file. +pub fn read_at(file: &Path) -> io::Result> { + match fs::read(file) { + Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", file.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// The choice in `~/.kiri/storage.json`, if there is one. +pub fn read() -> io::Result> { + read_at(&config_path()?) +} + +/// Writes `choice` to `file` whole: a temporary file renamed over it and +/// synced, so a crash leaves the old choice or the new one. This write is +/// a move's commit point. +pub fn write_at(file: &Path, choice: &Choice) -> io::Result<()> { + if let Some(dir) = file.parent() { + fs::create_dir_all(dir)?; + } + let bytes = serde_json::to_vec_pretty(choice).map_err(io::Error::other)?; + crate::jsonfile::replace(file, &bytes, crate::jsonfile::Durable::Now) +} + +/// Writes `~/.kiri/storage.json`. +pub fn write(choice: &Choice) -> io::Result<()> { + write_at(&config_path()?, choice) +} + +/// Removes `~/.kiri/storage.json`: back to the default folder, as if the +/// setting had never been changed. +pub fn clear() -> io::Result<()> { + match fs::remove_file(config_path()?) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} + +/// Whether `dir` holds the marker of a finished move. +pub fn has_marker(dir: &Path) -> bool { + dir.join(MARKER).is_file() +} + +/// Writes the marker into `dir`. +pub fn write_marker(dir: &Path) -> io::Result<()> { + crate::jsonfile::replace(&dir.join(MARKER), b"{\"kiri\":1}\n", crate::jsonfile::Durable::Now) +} + +/// The data folder `choice` gives, where `default` is the one without +/// it: the chosen folder if it holds the marker, else [`Unavailable`]. +/// The default folder needs no marker. +pub fn resolve(choice: Option, default: PathBuf) -> io::Result { + match choice { + None => Ok(default), + Some(c) if c.path == default || has_marker(&c.path) => Ok(c.path), + Some(c) => Err(io::Error::new(io::ErrorKind::NotFound, Unavailable(c.path))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-storage-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + /// No file: the default folder, and nothing is written. + #[test] + fn no_file_is_the_default_folder() { + let d = scratch("none"); + let file = d.join(FILE); + assert_eq!(read_at(&file).unwrap(), None); + assert_eq!(resolve(read_at(&file).unwrap(), d.join("default")).unwrap(), d.join("default")); + assert!(!file.exists()); + let _ = fs::remove_dir_all(&d); + } + + /// A chosen folder counts once it holds the marker; without it (the + /// drive isn't connected) it is unavailable, never the default and + /// never made. + #[test] + fn a_chosen_folder_needs_its_marker() { + let d = scratch("marker"); + let file = d.join(FILE); + let chosen = d.join("external/kiri"); + write_at(&file, &Choice { path: chosen.clone(), previous: None }).unwrap(); + let e = resolve(read_at(&file).unwrap(), d.join("default")).unwrap_err(); + assert_eq!(unavailable(&e), Some(chosen.as_path())); + assert!(e.to_string().contains("isn't available"), "{e}"); + assert!(!chosen.exists(), "an unavailable folder is never made"); + fs::create_dir_all(&chosen).unwrap(); + write_marker(&chosen).unwrap(); + assert_eq!(resolve(read_at(&file).unwrap(), d.join("default")).unwrap(), chosen); + let _ = fs::remove_dir_all(&d); + } + + /// The file is replaced whole, and an old copy's `previous` is kept + /// only when written. + #[test] + fn the_choice_round_trips() { + let d = scratch("roundtrip"); + let file = d.join(FILE); + let c = Choice { path: d.join("a"), previous: Some(d.join("b")) }; + write_at(&file, &c).unwrap(); + assert_eq!(read_at(&file).unwrap(), Some(c)); + write_at(&file, &Choice { path: d.join("a"), previous: None }).unwrap(); + assert!(!fs::read_to_string(&file).unwrap().contains("previous")); + fs::write(&file, b"{not json").unwrap(); + assert_eq!(read_at(&file).unwrap_err().kind(), io::ErrorKind::InvalidData); + let _ = fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri-image/src/store.rs b/crates/kiri-image/src/store.rs index 32b201127..63a8438df 100644 --- a/crates/kiri-image/src/store.rs +++ b/crates/kiri-image/src/store.rs @@ -121,6 +121,18 @@ impl Image { let same_repo = Reference::parse(&self.name).is_ok_and(|n| n.registry == r.registry && n.repository == r.repository); same_repo && (self.digest == r.reference || self.index_digest.as_deref() == Some(r.reference.as_str())) } + + /// Every blob digest this image record owns in the store: its config, + /// its layers, and (when pulled from a registry) its raw manifest and + /// multi-arch index blobs so Kiri's build mirror can serve exact + /// digest-verified bytes. + pub fn referenced_digests(&self) -> impl Iterator { + let manifest = (self.digest != self.config_digest).then_some(self.digest.as_str()); + std::iter::once(self.config_digest.as_str()) + .chain(manifest) + .chain(self.index_digest.as_deref()) + .chain(self.layers.iter().map(|l| l.digest.as_str())) + } } #[derive(Debug)] @@ -135,8 +147,10 @@ static TMP_SEQ: AtomicU64 = AtomicU64::new(0); static INDEX_LOCK: Mutex<()> = Mutex::new(()); /// Taken around a blob's rename into place by a writer that holds it -/// ([`Ingest::finish_pinned`]) and around a removal's check of the holds -/// and its delete, so the two never interleave. +/// ([`BlobWriter::finish_pinned`], [`Ingest::finish_pinned`]), around taking a +/// hold ([`Store::pin`], [`Store::pin_existing`], [`Store::hold_image`]), and +/// around a removal's check of the holds and its delete, so none of them ever +/// interleave. static BLOB_LOCK: Mutex<()> = Mutex::new(()); /// Blobs something in this process is using that an image's removal must @@ -256,13 +270,22 @@ pub fn digest_hex(digest: &str) -> io::Result<&str> { } impl Store { - /// The per-user data directory: `~/Library/Application Support/Kiri` on - /// macOS, `$XDG_DATA_HOME/kiri` (or `~/.local/share/kiri`) elsewhere. - /// `KIRI_DATA_DIR` overrides both. + /// The data directory: `KIRI_DATA_DIR` if set, else the folder chosen + /// in Settings → Storage (`~/.kiri/storage.json`, see + /// [`crate::storage`]), else [`Store::os_default_root`]. A chosen folder + /// without its marker (a drive that isn't connected) is an error that + /// [`crate::storage::unavailable`] recognises, never a fresh folder. pub fn default_root() -> io::Result { if let Some(dir) = std::env::var_os("KIRI_DATA_DIR") { return Ok(PathBuf::from(dir)); } + crate::storage::resolve(crate::storage::read()?, Self::os_default_root()?) + } + + /// The per-user data directory when nothing else is chosen: + /// `~/Library/Application Support/Kiri` on macOS, `$XDG_DATA_HOME/kiri` + /// (or `~/.local/share/kiri`) elsewhere. + pub fn os_default_root() -> io::Result { let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; Ok(if cfg!(target_os = "macos") { home.join("Library/Application Support/Kiri") @@ -275,8 +298,14 @@ impl Store { pub fn open(root: impl Into) -> io::Result { let root = root.into(); - fs::create_dir_all(root.join("blobs/sha256"))?; - fs::create_dir_all(root.join("tmp"))?; + let blobs = root.join("blobs/sha256"); + if !blobs.is_dir() { + fs::create_dir_all(blobs)?; + } + let tmp = root.join("tmp"); + if !tmp.is_dir() { + fs::create_dir_all(tmp)?; + } Ok(Store { root }) } @@ -288,6 +317,7 @@ impl Store { /// registry could serve a huge blob under that name, so anything over /// `MAX_CONFIG` is refused rather than loaded into memory. pub fn read_config(&self, digest: &str) -> std::io::Result> { + let _pin = self.pin(digest); let path = self.blob_path(digest)?; let len = std::fs::metadata(&path)?.len(); if len > MAX_CONFIG { @@ -303,7 +333,7 @@ impl Store { /// True if the blob is present with the expected size. Blobs are only /// renamed into place after their digest was verified, so presence is proof. pub fn has_blob(&self, digest: &str, size: u64) -> bool { - self.blob_path(digest).is_ok_and(|p| fs::metadata(p).is_ok_and(|m| m.len() == size)) + self.blob_path(digest).is_ok_and(|p| blob_ready(&p, size)) } pub fn blob_writer(&self, digest: &str) -> io::Result { @@ -337,6 +367,25 @@ impl Store { } } + /// Reads the image index under the in-process index lock and passes it to + /// `f`, so `f` can pin blobs ([`Store::pin`], [`Store::hold_image`]) + /// atomically before a concurrent [`Store::put_image`] or + /// [`Store::remove_image`] can replace the index and delete them. + /// `f` must not call methods that re-acquire the index lock. + pub fn with_images(&self, f: impl FnOnce(&[Image]) -> T) -> io::Result { + let guard = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let images = match self.read_index()? { + Index::Valid(images) => images, + Index::Corrupt(..) => { + drop(guard); + let _lock = self.lock_index()?; + let images = self.read_locked()?; + return Ok(f(&images)); + } + }; + Ok(f(&images)) + } + fn read_index(&self) -> io::Result { match fs::read(self.root.join("images.json")) { Ok(bytes) => Ok(match serde_json::from_slice(&bytes) { @@ -443,13 +492,33 @@ impl Store { Ok(self.images()?.into_iter().find(|i| i.name == name || i.digest == name || r.as_ref().is_some_and(|r| i.matches(r)))) } - /// Adds `image`, replacing any image with the same name. + /// As [`Store::find`], holding every blob the found image references + /// ([`Store::hold_image`]) before releasing the index lock so a concurrent + /// tag replacement or removal cannot delete them in between. + pub fn find_pinned(&self, name: &str) -> io::Result)>> { + let r = Reference::parse(name).ok(); + self.with_images(|images| { + let found = images + .iter() + .find(|i| i.name == name || i.digest == name || r.as_ref().is_some_and(|r| i.matches(r))) + .cloned()?; + let pins = self.hold_image(&found); + Some((found, pins)) + }) + } + + /// Adds `image`, replacing any image with the same name. The blobs only + /// the replaced image used go, as [`Store::remove_image`] deletes them: + /// nothing would name them any more (#864). pub fn put_image(&self, image: Image) -> io::Result<()> { let _lock = self.lock_index()?; - let mut images = self.read_locked()?; - images.retain(|i| i.name != image.name); + let (replaced, mut images): (Vec, Vec) = self.read_locked()?.into_iter().partition(|i| i.name == image.name); images.push(image); - self.write_index(&images) + self.write_index(&images)?; + for old in &replaced { + self.remove_unused_blobs(old, &images); + } + Ok(()) } /// Records the manifest a push of `name` left in its registry, so @@ -468,15 +537,36 @@ impl Store { } /// Keeps the blob `digest` from deletion while the pin lives. Pin first, - /// then check the blob is there: a pin taken after the check could miss - /// a removal in between. + /// then check the blob is there: taking the blob lock serialises the pin + /// with [`Store::remove_unpinned`] so a deletion already past its check + /// finishes before this returns. pub fn pin(&self, digest: &str) -> Pin { match self.blob_path(digest) { - Ok(p) => Pin::take(p), + Ok(p) => { + let _one = BLOB_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + Pin::take(p) + } Err(_) => Pin(None), } } + /// Keeps the blob `digest` from deletion if it is already on disk with + /// `size` bytes. The presence check and the hold both run under the blob + /// lock so a concurrent [`Store::put_image`] or [`Store::remove_image`] + /// cannot delete the blob in between. + pub fn pin_existing(&self, digest: &str, size: u64) -> Option { + let path = self.blob_path(digest).ok()?; + let _one = BLOB_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + blob_ready(&path, size).then(|| Pin::take(path)) + } + + /// Keeps every blob `image` references (config, raw manifest, multi-arch + /// index, and layers) from deletion until the returned pins are dropped. + pub fn hold_image(&self, image: &Image) -> Vec { + let _one = BLOB_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + image.referenced_digests().filter_map(|d| self.blob_path(d).ok()).map(Pin::take).collect() + } + /// Removes the image and deletes blobs no remaining image uses and /// nothing holds ([`Store::pin`]). pub fn remove_image(&self, name: &str) -> io::Result> { @@ -485,13 +575,20 @@ impl Store { let Some(pos) = images.iter().position(|i| i.name == name) else { return Ok(None) }; let removed = images.remove(pos); self.write_index(&images)?; - let in_use = |d: &str| images.iter().any(|i| i.config_digest == d || i.layers.iter().any(|l| l.digest == d)); - for d in std::iter::once(&removed.config_digest).chain(removed.layers.iter().map(|l| &l.digest)) { + self.remove_unused_blobs(&removed, &images); + Ok(Some(removed)) + } + + /// Deletes the blobs of `gone` that no image in `images` uses and + /// nothing holds ([`Store::pin`]). Called with the index lock held, + /// once `images` is written. + fn remove_unused_blobs(&self, gone: &Image, images: &[Image]) { + let in_use = |d: &str| images.iter().any(|i| i.referenced_digests().any(|r| r == d)); + for d in gone.referenced_digests() { if !in_use(d) { self.remove_unpinned(d); } } - Ok(Some(removed)) } /// Deletes the blob `digest` if no image uses it and nothing holds it, @@ -500,7 +597,7 @@ impl Store { pub fn remove_if_unused(&self, digest: &str) -> io::Result<()> { let _lock = self.lock_index()?; let images = self.read_locked()?; - if !images.iter().any(|i| i.config_digest == digest || i.layers.iter().any(|l| l.digest == digest)) { + if !images.iter().any(|i| i.referenced_digests().any(|r| r == digest)) { self.remove_unpinned(digest); } Ok(()) @@ -552,7 +649,16 @@ impl Write for BlobWriter { impl BlobWriter { /// Verifies the digest and publishes the blob. Returns bytes written. - pub fn finish(mut self) -> io::Result { + pub fn finish(self) -> io::Result { + let written = self.written; + self.finish_pinned()?; + Ok(written) + } + + /// As [`BlobWriter::finish`], holding the blob ([`Store::pin`]) from before + /// it is in place: a concurrent removal or tag replacement cannot delete it + /// between the rename and the caller recording an image that names it. + pub fn finish_pinned(mut self) -> io::Result { let actual = format!("sha256:{}", hex(&std::mem::take(&mut self.hasher).finalize())); if actual != self.expected { let _ = fs::remove_file(&self.tmp); @@ -562,8 +668,14 @@ impl BlobWriter { )); } self.file.sync_all()?; + let _one = BLOB_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let pin = Pin::take(self.dest.clone()); + if blob_ready(&self.dest, self.written) { + let _ = fs::remove_file(&self.tmp); + return Ok(pin); + } fs::rename(&self.tmp, &self.dest)?; - Ok(self.written) + Ok(pin) } } @@ -598,12 +710,21 @@ impl Write for Ingest { } } +fn blob_ready(dest: &Path, expected_size: u64) -> bool { + fs::symlink_metadata(dest).is_ok_and(|m| m.is_file() && m.len() == expected_size) +} + impl Ingest { /// Publishes the blob under its digest. Returns (digest, size). pub fn finish(mut self) -> io::Result<(String, u64)> { let hex = hex(&std::mem::take(&mut self.hasher).finalize()); + let dest = self.root.join("blobs/sha256").join(&hex); + if blob_ready(&dest, self.written) { + let _ = fs::remove_file(&self.tmp); + return Ok((format!("sha256:{hex}"), self.written)); + } self.file.sync_all()?; - fs::rename(&self.tmp, self.root.join("blobs/sha256").join(&hex))?; + fs::rename(&self.tmp, dest)?; Ok((format!("sha256:{hex}"), self.written)) } @@ -613,10 +734,14 @@ impl Ingest { /// an image that names it (`docker load`). pub fn finish_pinned(mut self) -> io::Result<(String, u64, Pin)> { let hex = hex(&std::mem::take(&mut self.hasher).finalize()); - self.file.sync_all()?; let dest = self.root.join("blobs/sha256").join(&hex); let _one = BLOB_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let pin = Pin::take(dest.clone()); + if blob_ready(&dest, self.written) { + let _ = fs::remove_file(&self.tmp); + return Ok((format!("sha256:{hex}"), self.written, pin)); + } + self.file.sync_all()?; fs::rename(&self.tmp, &dest)?; Ok((format!("sha256:{hex}"), self.written, pin)) } @@ -628,6 +753,22 @@ impl Drop for Ingest { } } +/// Hashes every byte of `r` with SHA-256, returning `(digest, bytes_read)`. +pub fn hash_stream(mut r: impl io::Read) -> io::Result<(String, u64)> { + let mut hasher = Sha256::new(); + let mut buf = [0u8; 65536]; + let mut total = 0u64; + loop { + let n = r.read(&mut buf)?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + total += n as u64; + } + Ok((format!("sha256:{}", hex(&hasher.finalize())), total)) +} + pub fn sha256_digest(bytes: &[u8]) -> String { format!("sha256:{}", hex(&Sha256::digest(bytes))) } @@ -738,6 +879,41 @@ mod tests { fs::remove_dir_all(&root).unwrap(); } + #[test] + fn removes_raw_manifest_and_index_blobs_when_no_image_references_them() { + let root = std::env::temp_dir().join(format!("kiri-store-raw-manifest-test-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let store = Store::open(&root).unwrap(); + let put = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let (cfg, cfg_sz) = put(b"{\"os\":\"linux\",\"architecture\":\"amd64\"}"); + let (man, man_sz) = put(b"{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.manifest.v1+json\"}"); + let (idx, idx_sz) = put(b"{\"schemaVersion\":2,\"mediaType\":\"application/vnd.oci.image.index.v1+json\"}"); + let img = |name: &str| Image { + name: name.into(), + digest: man.clone(), + index_digest: Some(idx.clone()), + config_digest: cfg.clone(), + layers: Vec::new(), + size: 0, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: RunConfig::default(), + mirror: None, + }; + store.put_image(img("app:1")).unwrap(); + store.put_image(img("app:latest")).unwrap(); + store.remove_image("app:1").unwrap(); + assert!(store.has_blob(&cfg, cfg_sz) && store.has_blob(&man, man_sz) && store.has_blob(&idx, idx_sz), "second tag still holds all blobs"); + store.remove_image("app:latest").unwrap(); + assert!(!store.has_blob(&cfg, cfg_sz) && !store.has_blob(&man, man_sz) && !store.has_blob(&idx, idx_sz), "last tag frees raw manifest and index blobs"); + 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())); @@ -982,4 +1158,235 @@ mod tests { assert_eq!(named("localhost:5000/app").repo(), "localhost:5000/app"); assert_eq!(named(&format!("kindest/node@sha256:{}", "a".repeat(64))).repo(), "kindest/node"); } + + #[test] + fn ingest_skips_rewrite_only_when_existing_blob_matches_size() { + let root = scratch("ingest-skip"); + let _ = fs::remove_dir_all(&root); + let store = Store::open(&root).unwrap(); + let data = b"hello content addressed store"; + let mut w = store.ingest().unwrap(); + w.write_all(data).unwrap(); + let (digest, size) = w.finish().unwrap(); + let path = store.blob_path(&digest).unwrap(); + assert_eq!(size, data.len() as u64); + + // Existing matching file: finish_pinned keeps it without replacing it. + let mut w2 = store.ingest().unwrap(); + w2.write_all(data).unwrap(); + let (d2, s2, _pin) = w2.finish_pinned().unwrap(); + assert_eq!((d2, s2), (digest.clone(), size)); + assert_eq!(fs::read(&path).unwrap(), data); + + // Truncated/corrupted blob of wrong size on disk is repaired by rename. + fs::write(&path, b"short").unwrap(); + let mut w3 = store.ingest().unwrap(); + w3.write_all(data).unwrap(); + w3.finish().unwrap(); + assert_eq!(fs::read(&path).unwrap(), data); + + fs::remove_dir_all(&root).unwrap(); + } + + /// An image put under a name another image had (a commit, build, pull, + /// load or tag onto it) takes that image's place, and the blobs only the + /// old one used go as `remove_image` would delete them. Before, they + /// stayed with no image naming them and nothing could remove them (#864). + #[test] + fn an_image_put_under_a_taken_name_frees_the_blobs_only_the_old_one_used() { + let root = scratch("replace"); + let _ = fs::remove_dir_all(&root); + let store = Store::open(&root).unwrap(); + let put = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let layer = |(digest, size): &(String, u64)| Layer { digest: digest.clone(), size: *size, media_type: "application/vnd.oci.image.layer.v1.tar".into() }; + let (shared, old_layer, new_layer) = (put(b"base layer"), put(b"layer of the first build"), put(b"layer of the second build")); + let (old_cfg, new_cfg) = (put(b"{\"created\":\"first\"}"), put(b"{\"created\":\"second\"}")); + let (old_man, old_idx) = (put(b"{\"schemaVersion\":2,\"first\":true}"), put(b"{\"schemaVersion\":2,\"manifests\":[]}")); + let pinned_layer = put(b"layer a save or pull is still using"); + let img = |name: &str, cfg: &(String, u64), manifest: Option<&(String, u64)>, index: Option<&(String, u64)>, layers: &[&(String, u64)]| Image { + name: name.into(), + digest: manifest.map_or_else(|| cfg.0.clone(), |m| m.0.clone()), + index_digest: index.map(|i| i.0.clone()), + config_digest: cfg.0.clone(), + layers: layers.iter().map(|l| layer(l)).collect(), + size: 0, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: RunConfig::default(), + mirror: None, + }; + let has = |(digest, size): &(String, u64)| store.has_blob(digest, *size); + + // The old image under a second name keeps all its blobs. + store.put_image(img("app:latest", &old_cfg, Some(&old_man), Some(&old_idx), &[&shared, &old_layer])).unwrap(); + store.put_image(img("app:v1", &old_cfg, Some(&old_man), Some(&old_idx), &[&shared, &old_layer])).unwrap(); + store.put_image(img("app:latest", &new_cfg, None, None, &[&shared, &new_layer])).unwrap(); + assert!(has(&old_cfg) && has(&old_man) && has(&old_idx) && has(&old_layer), "app:v1 still names the old image"); + + // Its last name taken: its own config, manifest, index and layer go; + // the shared layer and the new image's blobs stay. + store.put_image(img("app:v1", &new_cfg, None, None, &[&shared, &new_layer])).unwrap(); + assert!(!has(&old_cfg) && !has(&old_man) && !has(&old_idx) && !has(&old_layer), "nothing names the old image's blobs any more"); + assert!(has(&shared) && has(&new_cfg) && has(&new_layer), "the new image uses these"); + + // Putting the exact same image again under its own name deletes nothing. + store.put_image(img("app:v1", &new_cfg, None, None, &[&shared, &new_layer])).unwrap(); + assert!(has(&shared) && has(&new_cfg) && has(&new_layer)); + + // A blob something still holds outlives the replacement. + let held_cfg = put(b"{\"created\":\"held\"}"); + store.put_image(img("held:1", &held_cfg, None, None, &[&pinned_layer])).unwrap(); + let pin = store.pin(&pinned_layer.0); + store.put_image(img("held:1", &new_cfg, None, None, &[&new_layer])).unwrap(); + assert!(has(&pinned_layer), "a pin still holds it"); + assert!(!has(&held_cfg), "unpinned old config went"); + drop(pin); + assert_eq!(store.images().unwrap().iter().map(|i| i.name.as_str()).collect::>(), ["app:latest", "app:v1", "held:1"]); + fs::remove_dir_all(&root).unwrap(); + } + + /// `pin_existing`, `BlobWriter::finish_pinned`, and `find_pinned` hold + /// blobs atomically across concurrent `put_image` tag overwrites so no + /// in-flight pull, build mirror, or container create sees ENOENT. + #[test] + fn concurrent_pin_existing_and_finish_pinned_survive_put_image_overwrites() { + let root = scratch("concurrent-pins"); + let _ = fs::remove_dir_all(&root); + let store = Store::open(&root).unwrap(); + + let shared_bytes = b"shared base layer bytes".to_vec(); + let shared_digest = sha256_digest(&shared_bytes); + let shared_size = shared_bytes.len() as u64; + let cfg1_bytes = br#"{"architecture":"amd64","os":"linux","config":{"Cmd":["v1"]}}"#.to_vec(); + let cfg1_digest = sha256_digest(&cfg1_bytes); + let cfg1_size = cfg1_bytes.len() as u64; + let cfg2_bytes = br#"{"architecture":"amd64","os":"linux","config":{"Cmd":["v2"]}}"#.to_vec(); + let cfg2_digest = sha256_digest(&cfg2_bytes); + let layer2_bytes = b"version two unique layer".to_vec(); + let layer2_digest = sha256_digest(&layer2_bytes); + let layer2_size = layer2_bytes.len() as u64; + + let write_pinned = |digest: &str, bytes: &[u8]| -> Pin { + let mut w = store.blob_writer(digest).unwrap(); + w.write_all(bytes).unwrap(); + w.finish_pinned().unwrap() + }; + + // 1. Deterministic checks: pin_existing misses when absent or wrong size, + // hits when matching, and protects against put_image overwrite; + // BlobWriter::finish_pinned rejects mismatched digests and pins on success. + assert!(store.pin_existing(&shared_digest, shared_size).is_none()); + let mut bad = store.blob_writer(&shared_digest).unwrap(); + bad.write_all(b"wrong bytes").unwrap(); + assert!(bad.finish_pinned().is_err()); + assert!(store.pin_existing(&shared_digest, shared_size).is_none()); + + let p_shared = write_pinned(&shared_digest, &shared_bytes); + let p_cfg1 = write_pinned(&cfg1_digest, &cfg1_bytes); + assert!(store.pin_existing(&shared_digest, shared_size + 1).is_none(), "wrong size is not a hit"); + let existing_pin = store.pin_existing(&shared_digest, shared_size).expect("blob present"); + + let make_img = |name: &str, cfg_digest: &str, layer_digest: &str, layer_size: u64| Image { + name: name.into(), + digest: cfg_digest.into(), + index_digest: None, + config_digest: cfg_digest.into(), + layers: vec![Layer { digest: layer_digest.into(), size: layer_size, media_type: "application/vnd.oci.image.layer.v1.tar".into() }], + size: layer_size, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: RunConfig::default(), + mirror: None, + }; + + let img1 = make_img("race:latest", &cfg1_digest, &shared_digest, shared_size); + let img2 = make_img("race:latest", &cfg2_digest, &layer2_digest, layer2_size); + store.put_image(img1.clone()).unwrap(); + drop((p_shared, p_cfg1)); + + // Overwrite race:latest with img2 while existing_pin holds shared_digest. + let p_cfg2 = write_pinned(&cfg2_digest, &cfg2_bytes); + let p_l2 = write_pinned(&layer2_digest, &layer2_bytes); + store.put_image(img2.clone()).unwrap(); + drop((p_cfg2, p_l2)); + assert!(store.has_blob(&shared_digest, shared_size), "pin_existing protects blob across put_image"); + assert!(!store.has_blob(&cfg1_digest, cfg1_size), "unpinned cfg1 was freed"); + drop(existing_pin); + + // 2. Multi-threaded stress: overwrite race:latest back and forth between + // img1 and img2 while concurrent readers use pin_existing, + // BlobWriter::finish_pinned, and find_pinned. + let done = std::sync::atomic::AtomicBool::new(false); + std::thread::scope(|s| { + // Writer thread: repeatedly swaps race:latest between img1 and img2. + s.spawn(|| { + for round in 0..150 { + if round % 2 == 0 { + let p1 = write_pinned(&cfg1_digest, &cfg1_bytes); + let p2 = write_pinned(&shared_digest, &shared_bytes); + store.put_image(img1.clone()).unwrap(); + drop((p1, p2)); + } else { + let p1 = write_pinned(&cfg2_digest, &cfg2_bytes); + let p2 = write_pinned(&layer2_digest, &layer2_bytes); + store.put_image(img2.clone()).unwrap(); + drop((p1, p2)); + } + } + done.store(true, Ordering::Release); + }); + + // Pull-like thread: alternates pin_existing and BlobWriter::finish_pinned + // on shared_digest and verifies the bytes remain readable while pinned. + s.spawn(|| { + let mut hits = 0usize; + let mut writes = 0usize; + while !done.load(Ordering::Acquire) { + if let Some(pin) = store.pin_existing(&shared_digest, shared_size) { + let got = fs::read(store.blob_path(&shared_digest).unwrap()).expect("blob vanished while pin_existing held"); + assert_eq!(got, shared_bytes); + drop(pin); + hits += 1; + } else { + let pin = write_pinned(&shared_digest, &shared_bytes); + let got = fs::read(store.blob_path(&shared_digest).unwrap()).expect("blob vanished while finish_pinned held"); + assert_eq!(got, shared_bytes); + drop(pin); + writes += 1; + } + } + assert!(hits + writes > 0); + }); + + // Reader thread (create/mirror-like): atomically looks up and pins + // race:latest via find_pinned and reads both its config and layer. + s.spawn(|| { + let mut reads = 0usize; + while !done.load(Ordering::Acquire) { + if let Some((img, pins)) = store.find_pinned("race:latest").unwrap() { + let cfg = store.read_config(&img.config_digest).expect("config vanished while find_pinned held"); + let layer = fs::read(store.blob_path(&img.layers[0].digest).unwrap()).expect("layer vanished while find_pinned held"); + if img.config_digest == cfg1_digest { + assert_eq!(cfg, cfg1_bytes); + assert_eq!(layer, shared_bytes); + } else { + assert_eq!(cfg, cfg2_bytes); + assert_eq!(layer, layer2_bytes); + } + drop(pins); + reads += 1; + } + } + assert!(reads > 0); + }); + }); + + fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/kiri-image/tests/host_roots.rs b/crates/kiri-image/tests/host_roots.rs new file mode 100644 index 000000000..651d02946 --- /dev/null +++ b/crates/kiri-image/tests/host_roots.rs @@ -0,0 +1,84 @@ +//! A Windows host's roots in the engine (#303): kiri-win sends the daemon +//! in WSL the Windows store's roots the bundled set lacks and the ones the +//! administrator distrusted, and every agent built on +//! [`kiri_image::roots::trusted`] then trusts the first and refuses the +//! second. Its own binary: setting a host's roots changes the process's. + +use kiri_image::roots::{Host, bundled, generation, set_host, set_host_if_unset, trusted}; +use rcgen::{BasicConstraints, CertificateParams, IsCa, Issuer, KeyPair, SanType}; +use rustls::pki_types::CertificateDer; + +#[test] +fn a_hosts_root_is_trusted_and_its_distrusted_root_is_not() { + // KIRI_TLS_ROOTS=webpki keeps the bundled set alone, on purpose. + if std::env::var("KIRI_TLS_ROOTS").as_deref() == Ok("webpki") { + return; + } + let (port, ca) = localhost_tls_server(); + let url = format!("https://127.0.0.1:{port}/"); + let agent = || -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_connect(Some(std::time::Duration::from_secs(5))) + .tls_config(kiri_image::tls_config(&trusted())) + .build() + .into() + }; + assert!(agent().get(&url).call().is_err(), "a root nobody sent is not trusted"); + + let distrusted = bundled()[0].clone(); + let before = generation(); + let host = Host { certs: vec![ca.der().clone()], distrusted: vec![distrusted.clone()] }; + assert!(set_host(host.clone())); + assert_eq!(generation(), before + 1, "agents built on the roots know to build again"); + assert!(!set_host(host), "the same roots again change nothing"); + assert_eq!(generation(), before + 1); + assert!(!set_host_if_unset(Host::default()), "startup disk load must not overwrite pushed host roots"); + assert_eq!(generation(), before + 1); + + let roots = trusted(); + assert!(roots.contains(&CertificateDer::from(ca.der().to_vec()))); + assert!(!roots.contains(&distrusted), "a root the host distrusted is out, bundled or not"); + assert_eq!(agent().get(&url).call().unwrap().body_mut().read_to_string().unwrap(), "ok"); +} + +/// A TLS server on localhost with a certificate for `127.0.0.1`, signed +/// by a fresh self-signed CA. Returns the port and the CA certificate. +fn localhost_tls_server() -> (u16, rcgen::Certificate) { + let ca_key = KeyPair::generate().unwrap(); + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let ca = ca_params.clone().self_signed(&ca_key).unwrap(); + let server_key = KeyPair::generate().unwrap(); + let mut p = CertificateParams::new(Vec::::new()).unwrap(); + p.subject_alt_names = vec![SanType::IpAddress("127.0.0.1".parse().unwrap())]; + let server = p.signed_by(&server_key, &Issuer::new(ca_params, &ca_key)).unwrap(); + let config = rustls::ServerConfig::builder_with_provider(std::sync::Arc::new(rustls::crypto::ring::default_provider())) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![server.der().clone()], + rustls::pki_types::PrivateKeyDer::Pkcs8(server_key.serialize_der().into()), + ) + .unwrap(); + let config = std::sync::Arc::new(config); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + for stream in listener.incoming().flatten() { + let config = config.clone(); + std::thread::spawn(move || { + use std::io::{Read, Write}; + let mut conn = rustls::ServerConnection::new(config).unwrap(); + let mut stream = stream; + let mut tls = rustls::Stream::new(&mut conn, &mut stream); + let mut buf = [0u8; 4096]; + if tls.read(&mut buf).is_ok() { + let _ = tls.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"); + let _ = tls.flush(); + } + }); + } + }); + (port, ca) +} diff --git a/crates/kiri-image/tests/localhost_tls.rs b/crates/kiri-image/tests/localhost_tls.rs new file mode 100644 index 000000000..e2a173336 --- /dev/null +++ b/crates/kiri-image/tests/localhost_tls.rs @@ -0,0 +1,134 @@ +//! `share` accepts a self-signed CA once it is trusted, and rejects the +//! same server before that: the merged roots, handed to a ureq agent +//! through [`kiri_image::tls_config`], are what decide (#303). +//! This lives outside the crate because it spins a live TLS server and +//! agents, not because the crate needs anything but its own roots. + +use kiri_image::roots::{Mode, merge, trusted}; +use rcgen::{ + BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, SanType, +}; +use rustls::pki_types::CertificateDer; + +/// An agent on the bundled set alone rejects the self-signed server, so +/// does an agent on the merged roots without the CA, and the merged roots +/// with the CA added accept it. +#[test] +fn self_signed_localhost_is_rejected_by_default_and_accepted_once_added() { + let (port, ca) = localhost_tls_server(); + let url = format!("https://127.0.0.1:{port}/"); + + let agent_on = |roots: &[CertificateDer<'static>]| { + ureq::Agent::config_builder() + .timeout_connect(Some(std::time::Duration::from_secs(5))) + .tls_config(kiri_image::tls_config(roots)) + .build() + .into() + }; + let accepted = |agent: ureq::Agent| { + let mut resp = agent + .get(&url) + .call() + .expect("merged store accepts the self-signed CA"); + resp.body_mut() + .with_config() + .limit(64 << 10) + .read_to_string() + .unwrap() + }; + let rejected = |agent: ureq::Agent| { + assert!( + agent.get(&url).call().is_err(), + "the agent must reject the self-signed CA" + ); + }; + + // Without the CA: the bundled set alone (what `KIRI_TLS_ROOTS=webpki` + // keeps, and all Kiri had before #303) and the merged store. + rejected(agent_on(&merge( + Mode::BundledOnly, + Vec::new, + webpki_root_certs::TLS_SERVER_ROOT_CERTS, + ))); + rejected(agent_on(&trusted())); + + // With the CA among the merged roots. + let mut certs = trusted().to_vec(); + certs.push(ca.der().clone()); + assert_eq!(accepted(agent_on(&certs)), "ok"); +} + +/// The bundled roots, being full certificates, sit in a rustls root store +/// as they are: subject, public key and name constraints are the +/// certificate's own, so nothing is rebuilt around them. +#[test] +fn the_bundled_roots_load_into_a_root_store_unchanged() { + let mut store = rustls::RootCertStore::empty(); + store.add_parsable_certificates(webpki_root_certs::TLS_SERVER_ROOT_CERTS.to_vec()); + assert_eq!(store.len(), webpki_root_certs::TLS_SERVER_ROOT_CERTS.len()); +} + +/// A TLS server on localhost with a certificate for `127.0.0.1`, signed +/// by a fresh self-signed CA. Returns the port and the CA certificate. +fn localhost_tls_server() -> (u16, rcgen::Certificate) { + let ca_key = KeyPair::generate().unwrap(); + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let ca = ca_params.clone().self_signed(&ca_key).unwrap(); + + let server_key = KeyPair::generate().unwrap(); + let mut p = CertificateParams::new(Vec::::new()).unwrap(); + p.subject_alt_names = vec![ + SanType::DnsName("localhost".to_owned().try_into().unwrap()), + SanType::IpAddress(std::net::IpAddr::from([127, 0, 0, 1])), + ]; + p.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + let server_cert = p + .signed_by(&server_key, &Issuer::new(ca_params, ca_key)) + .unwrap(); + + let key = rustls::pki_types::PrivatePkcs8KeyDer::from(server_key.serialize_der()); + let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider()); + let config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![ + CertificateDer::from(server_cert.der().to_vec()), + CertificateDer::from(ca.der().to_vec()), + ], + key.into(), + ) + .unwrap(); + let config = std::sync::Arc::new(config); + + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + std::thread::spawn(move || { + // The test makes a handful of connections (the ones it expects + // to be rejected dial too); serve a few more than that. + for _ in 0..8 { + let Ok((sock, _)) = listener.accept() else { + return; + }; + let _ = sock.set_read_timeout(Some(std::time::Duration::from_secs(10))); + let Ok(conn) = rustls::ServerConnection::new(config.clone()) else { + continue; + }; + // Reads and writes complete the handshake as they go. + let mut stream = rustls::StreamOwned::new(conn, sock); + let mut buf = [0u8; 4096]; + let _ = std::io::Read::read(&mut stream, &mut buf); + if std::io::Write::write_all( + &mut stream, + b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok", + ) + .is_ok() + { + let _ = std::io::Write::flush(&mut stream); + } + } + }); + (port, ca) +} diff --git a/crates/kiri-image/tests/ssl_cert_file.rs b/crates/kiri-image/tests/ssl_cert_file.rs new file mode 100644 index 000000000..a55f8eb5d --- /dev/null +++ b/crates/kiri-image/tests/ssl_cert_file.rs @@ -0,0 +1,46 @@ +//! `SSL_CERT_FILE` replaces the platform's roots for everything built on +//! [`kiri_image::roots`] (#303). The variable is read when the roots are +//! built, as with curl and OpenSSL, so a test can set it and see the +//! certificates come out. This lives outside the crate because the crate +//! forbids unsafe code and setting an environment variable is unsafe. + +use kiri_image::roots::trusted; + +/// The file's certificates replace the platform store, and the bundled +/// roots stay merged in. +#[test] +fn ssl_cert_file_replaces_the_platform_roots() { + let ca = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + let key = rcgen::KeyPair::generate().unwrap(); + let cert = ca.self_signed(&key).unwrap(); + let file = std::env::temp_dir().join(format!( + "kiri-roots-ssl-cert-file-{}.pem", + std::process::id() + )); + std::fs::write(&file, cert.pem()).unwrap(); + // SAFETY: the only test in this binary, so nothing else reads the + // environment meanwhile. KIRI_TLS_ROOTS=webpki would leave the file + // out, and SSL_CERT_DIR would add its certificates to the file's. + unsafe { + std::env::remove_var("KIRI_TLS_ROOTS"); + std::env::remove_var("SSL_CERT_DIR"); + std::env::set_var("SSL_CERT_FILE", &file); + } + let certs = trusted(); + unsafe { std::env::remove_var("SSL_CERT_FILE") }; + let _ = std::fs::remove_file(&file); + assert_eq!( + certs.len(), + webpki_root_certs::TLS_SERVER_ROOT_CERTS.len() + 1 + ); + // The file's certificate replaces the platform store at the front of + // the merged list, the bundled roots unchanged after it. (No root the + // administrator distrusted is in the bundled set on a test machine.) + assert_eq!(certs.first().unwrap().as_ref(), cert.der().as_ref()); + assert!( + certs[1..] + .iter() + .zip(webpki_root_certs::TLS_SERVER_ROOT_CERTS) + .all(|(a, b)| a.as_ref() == b.as_ref()) + ); +} diff --git a/crates/kiri-image/tests/webpki_mode.rs b/crates/kiri-image/tests/webpki_mode.rs new file mode 100644 index 000000000..e8a798652 --- /dev/null +++ b/crates/kiri-image/tests/webpki_mode.rs @@ -0,0 +1,48 @@ +//! `KIRI_TLS_ROOTS=webpki` keeps the bundled Mozilla set alone, reading +//! nothing from the platform store (or `SSL_CERT_FILE`), exporting nothing +//! to WSL, and ignoring any host roots sent via `set_host` (#303). +//! Its own binary: `MODE` and `ROOTS` are read once per process. + +use kiri_image::roots::{Host, bundled, host_export, set_host, trusted}; + +#[test] +fn kiri_tls_roots_webpki_uses_only_the_bundled_roots() { + let ca = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + let key = rcgen::KeyPair::generate().unwrap(); + let cert = ca.self_signed(&key).unwrap(); + let file = std::env::temp_dir().join(format!( + "kiri-roots-webpki-{}.pem", + std::process::id() + )); + std::fs::write(&file, cert.pem()).unwrap(); + // SAFETY: the only test in this binary, so nothing else reads the + // environment meanwhile. + unsafe { + std::env::set_var("KIRI_TLS_ROOTS", "webpki"); + std::env::set_var("SSL_CERT_FILE", &file); + std::env::remove_var("SSL_CERT_DIR"); + } + + let got = trusted(); + assert_eq!(got.len(), bundled().len()); + assert!(got.iter().zip(bundled()).all(|(a, b)| a.as_ref() == b.as_ref())); + + // host_export reads nothing from the system when webpki-only is set. + assert_eq!(host_export(), Host::default()); + + // Even after set_host adds a CA and distrusts a bundled root, trusted() + // keeps the bundled set intact while KIRI_TLS_ROOTS=webpki is active. + assert!(set_host(Host { + certs: vec![cert.der().clone()], + distrusted: vec![bundled()[0].clone()], + })); + let after = trusted(); + assert_eq!(after.len(), bundled().len()); + assert!(after.iter().zip(bundled()).all(|(a, b)| a.as_ref() == b.as_ref())); + + unsafe { + std::env::remove_var("KIRI_TLS_ROOTS"); + std::env::remove_var("SSL_CERT_FILE"); + } + let _ = std::fs::remove_file(&file); +} diff --git a/crates/kiri-init/src/linux/agent.rs b/crates/kiri-init/src/linux/agent.rs index e329e1a8c..413478b05 100644 --- a/crates/kiri-init/src/linux/agent.rs +++ b/crates/kiri-init/src/linux/agent.rs @@ -8,7 +8,7 @@ use std::io::{self, Read, Write}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; use std::path::Path; -use kiri_proto::{Exited, MAX_OUTPUT_CHUNK, Msg, Stats, Stream}; +use kiri_proto::{Exited, MAX_OUTPUT_CHUNK, MemoryPressure, Msg, Stats, Stream}; use super::container::{self, NetCtx, Paths, Process, Root}; use super::net::{self, Bridges, Dhcp}; @@ -47,6 +47,36 @@ impl Proc { /// How long a hung-up terminal waits before it's polled again. const TTY_HUP_WAIT: std::time::Duration = std::time::Duration::from_millis(100); +type FileStamp = Option<(u64, u64, i64, i64)>; + +/// Caches the host's DNS servers by the metadata of `/etc/resolv.conf` and +/// `/run/systemd/resolve/resolv.conf`, so DNS listener wake-ups only re-read +/// them when either file's inode, size or modification time has changed. +#[derive(Default)] +struct HostDns { + stamp: Option<[FileStamp; 2]>, + checked_at: Option, + servers: Vec<[u8; 4]>, +} + +impl HostDns { + fn get(&mut self) -> &[[u8; 4]] { + use std::os::unix::fs::MetadataExt; + let now_inst = std::time::Instant::now(); + if self.checked_at.is_some_and(|t| now_inst.saturating_duration_since(t) < std::time::Duration::from_millis(250)) { + return &self.servers; + } + self.checked_at = Some(now_inst); + let stat = |p: &str| std::fs::metadata(p).ok().map(|m| (m.ino(), m.len(), m.mtime(), m.mtime_nsec())); + let now = [stat("/etc/resolv.conf"), stat("/run/systemd/resolve/resolv.conf")]; + if self.stamp != Some(now) { + self.servers = super::transport::host_dns(); + self.stamp = Some(now); + } + &self.servers + } +} + pub fn serve(conn: File, paths: &Paths) -> io::Result<()> { let mut procs: HashMap = HashMap::new(); let served = serve_loop(conn, paths, &mut procs); @@ -78,9 +108,20 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap = Vec::new(); - let host_dns = if host_process { super::transport::host_dns() } else { Vec::new() }; + let mut host_dns = HostDns::default(); + if host_process { + host_dns.get(); + if super::sys::is_wsl() + && let Err(e) = super::localtime::ensure_localtime() + { + eprintln!("kiri-init: localtime: {e}"); + } + } let mut dhcp: Option = if host_process { if let Err(e) = net::host_uplink() { + if e.kind() == io::ErrorKind::AddrInUse { + return Err(e); + } eprintln!("kiri-init: no uplink: {e}"); } None @@ -95,8 +136,11 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap= std::time::Duration::from_millis(100) { last_pressure = std::time::Instant::now(); + let (_, mem_available_kib, _, _) = meminfo_full(); + let (mem_stall, _) = super::cgroup::memory_trouble(); out.clear(); - Msg::MemoryPressure.encode(&mut out); + Msg::MemoryPressure(MemoryPressure { mem_available_kib, mem_stall }).encode(&mut out); conn.write_all(&out)?; } continue; @@ -312,7 +368,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { - let (mem_total_kib, mem_available_kib, mem_balloon_kib) = meminfo_full(); + let (mem_total_kib, mem_available_kib, mem_balloon_kib, mem_committed_kib) = meminfo_full(); let agent_rss_kib = self_rss_kib(); let (mem_stall, oom_kills) = super::cgroup::memory_trouble(); Msg::Stats(Stats { @@ -427,6 +492,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap match { // A container that wants the network must not start before the // VM has it: right after boot the DHCP lease can be a few - // hundred milliseconds away. - if spec.flags & (kiri_proto::run_flags::NET_NONE | kiri_proto::run_flags::NET_HOST) == 0 { + // hundred milliseconds away. Only `--network none` skips it; + // `--network host` shares the VM's network and needs the lease + // too (on a Linux host `dhcp` is None so this is a no-op). + if needs_lease(spec.flags) { wait_for_lease(&mut dhcp, std::time::Duration::from_secs(3)); } // Only its network namespace is joined, which exists from @@ -448,11 +516,14 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { @@ -548,15 +619,18 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { - // In the VM: from the Mac over the NAT network, TCP only. + // In the VM: from the Mac over the NAT network (TCP only), + // or on loopback (127.0.0.1) so `--network host` containers + // reach published ports via the host relay even without eth0. let gateway = dhcp.as_ref().and_then(|d| d.lease.as_ref()).map(|l| l.gateway); - if !host_process && (p.udp || gateway.is_none()) { + let loopback = p.host_ip == super::netlink::LOOPBACK; + if !host_process && (p.udp || (!loopback && gateway.is_none())) { Msg::Error("published ports are relayed on this platform").encode(&mut out); } else { let d = super::netlink::Dnat { udp: p.udp, host_ip: p.host_ip, host_port: p.host_port, to_ip: p.to_ip, to_port: p.to_port }; published.push((p.id.to_owned(), d)); let all = published.iter().map(|(_, d)| *d).collect::>(); - match if host_process { net::publish(&all) } else { net::publish_vm(&all, gateway.expect("checked")) } { + match if host_process { net::publish(&all) } else { net::publish_vm(&all, gateway.unwrap_or([0; 4])) } { Ok(()) => Msg::Ack.encode(&mut out), Err(e) => { published.pop(); @@ -571,7 +645,7 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap>(); let gateway = dhcp.as_ref().and_then(|d| d.lease.as_ref()).map_or([0; 4], |l| l.gateway); - if let Err(e) = if host_process { net::publish(&all) } else { net::publish_vm(&all, gateway) } { + if let Err(e) = if host_process { net::unpublish(&all) } else { net::publish_vm(&all, gateway) } { eprintln!("kiri-init: unpublish {id}: {e}"); } } @@ -611,24 +685,54 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { + let parsed = net::parse_egress_routes(routes); + if !host_process && !parsed.is_empty() && egress.is_none() { + egress = super::relay::listen_host_bound(net::EGRESS_RELAY_PORT) + .inspect_err(|e| eprintln!("kiri-init: no egress relay listener: {e}")) + .ok(); + } + dns.prefer_relay = !host_process && net::egress_prefers_dns_relay(&parsed); + if let Err(e) = net::set_egress_routes(parsed) { + eprintln!("kiri-init: egress routes: {e}"); + } + continue; + } Ok(Msg::Retain(keep)) => { let running: Vec<&str> = procs.values().map(|p| p.run.id.as_str()).collect(); container::retain(paths, keep, &running); continue; } Ok(Msg::RetainLayers(keep)) => { - layers::retain(&paths.layers, keep.iter()); + // Any layer currently mounted as a lowerdir of a running + // container or copy job stays until its mount is released. + let mounted = super::roots::in_use_layers(); + layers::retain(&paths.layers, keep.iter().chain(mounted.iter().map(String::as_str))); continue; } Ok(Msg::SetTime(ns)) => { // A host process shares the host's clock; only the VM needs // telling. The host sends it again every minute and after - // the Mac wakes: stepped only when off by more than a - // quarter second, so the clock is not nudged back and forth. - if !host_process && clock_off(ns) { - let ts = libc::timespec { tv_sec: (ns / 1_000_000_000) as _, tv_nsec: (ns % 1_000_000_000) as _ }; - // SAFETY: `ts` is a valid timespec. - unsafe { libc::clock_settime(libc::CLOCK_REALTIME, &ts) }; + // the Mac wakes: slew sub-second drift smoothly with + // adjtimex (#509) and hard-step only large jumps (> 1 s). + if !host_process { + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64); + match clock_adjustment(now, ns) { + ClockAdjust::None => {} + ClockAdjust::Slew(offset_us) => { + // SAFETY: zeroed `libc::timex` is valid; only plain scalar fields are set. + let mut tx: libc::timex = unsafe { std::mem::zeroed() }; + tx.modes = libc::ADJ_OFFSET_SINGLESHOT; + tx.offset = offset_us as _; + // SAFETY: `tx` is a valid initialized `libc::timex`. + unsafe { libc::adjtimex(&mut tx) }; + } + ClockAdjust::Step => { + let ts = libc::timespec { tv_sec: (ns / 1_000_000_000) as _, tv_nsec: (ns % 1_000_000_000) as _ }; + // SAFETY: `ts` is a valid timespec. + unsafe { libc::clock_settime(libc::CLOCK_REALTIME, &ts) }; + } + } } continue; } @@ -675,46 +779,72 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap { - if let Some(name) = kiri_proto::net_opts::values(n.opts, kiri_proto::net_opts::NETWORK).next() { - dns.name_network(n.bridge, name); - } - if !plug.no_ipv4 { - dns.register(n.bridge, n.dns_names.iter(), n.ip); - } - if let Some(v) = v6 { - dns.register6(n.bridge, n.dns_names.iter(), n.ip, v.ip); + dns.set_bridge_ipv6(n.bridge, bridges.has_ipv6(n.bridge)); + if is_user { + if let Some(name) = kiri_proto::net_opts::values(n.opts, kiri_proto::net_opts::NETWORK).next() { + dns.name_network(n.bridge, name); + } + if !plug.no_ipv4 { + dns.register(n.bridge, n.dns_names.iter(), n.ip); + } + if let Some(v) = v6 { + dns.register6(n.bridge, n.dns_names.iter(), n.ip, v.ip); + } } if let Some(p) = procs.get_mut(&pid) { - p.run.dns_entries.push((n.bridge.to_owned(), n.ip)); - p.run.veths.push(host_if.clone()); + if is_user { + record_dns_entry(&mut p.run, n.bridge, n.ip); + } + p.run.uplinks.retain(|u| u.veth != host_if); + p.run.uplinks.extend(net::Uplink::of(&host_if, ifname, n.gateway, v6, plug)); + p.run.veths.retain(|(iface, _)| iface != ifname); + p.run.veths.push((ifname.to_owned(), host_if.clone())); } // A user network's names come from the embedded // DNS, which now answers in the container: its // resolv.conf names it from here on (#449). - if n.bridge != "kiri0" && !plug.no_ipv4 { - let upstream = dhcp.as_ref().and_then(|d| d.lease.as_ref()).map_or(&host_dns[..], |l| &l.dns); + if is_user { + if host_process { + host_dns.get(); + } + let upstream = dhcp.as_ref().and_then(|d| d.lease.as_ref()).map_or(&host_dns.servers[..], |l| &l.dns); let is_kiri = |a: [u8; 4]| upstream.contains(&a) || dns.serves_at(a) || a == [1, 1, 1, 1]; match container::use_embedded_dns(id, is_kiri) { Ok(Some(servers)) if !servers.is_empty() => { - if let Some(owner) = dns.owner_of(pid) { - dns.set_upstream(owner, servers); + dns.set_container_upstream(pid, servers.clone()); + dns.set_upstream(n.ip, servers); + } + Ok(_) => { + if let Some(servers) = dns.container_upstream(pid) { + dns.set_upstream(n.ip, servers); } } - Ok(_) => {} Err(e) => eprintln!("kiri-init: {id}: resolv.conf: {e}"), } + } else { + attach_kiri0_upstream(&mut dns, procs, pid, n.bridge, n.ip); } Msg::Ack.encode(&mut out) } @@ -741,6 +871,30 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap Msg::Uplink { ip: l.ip, gateway: l.gateway }.encode(&mut out), None => Msg::Error("no uplink lease").encode(&mut out), }, + Ok(Msg::DiskUsageQuery) => match super::trim::stat(super::DATA) { + Ok((in_use, capacity)) => Msg::DiskUsage { in_use, capacity }.encode(&mut out), + Err(e) => Msg::Error(&format!("disk usage: {e}")).encode(&mut out), + }, + Ok(Msg::TrimDisk) => match super::trim::trim(super::DATA) { + Ok(trimmed) => { + let (in_use, capacity) = super::trim::stat(super::DATA).unwrap_or((0, 0)); + Msg::DiskTrimmed { trimmed, in_use, capacity }.encode(&mut out); + } + Err(e) => Msg::Error(&format!("trim: {e}")).encode(&mut out), + }, + Ok(Msg::SetUplink { ip, prefix, gateway, dns: dns_ip }) => match dhcp.as_mut() { + _ if host_process => Msg::Error("set uplink is only for the VM").encode(&mut out), + Some(d) => match d.apply_static(ip, prefix, gateway, dns_ip) { + Ok(applied) => { + if applied { + eprintln!("kiri-init: DHCP did not answer; configured {} statically as {}/{} via {} from host", net::UPLINK, net::ip_str(ip), prefix, net::ip_str(gateway)); + } + Msg::Ack.encode(&mut out); + } + Err(e) => Msg::Error(&format!("set uplink: {e}")).encode(&mut out), + }, + None => Msg::Error("no uplink interface").encode(&mut out), + }, Ok(Msg::Route { dst, prefix, via, add }) => match net::route(dst, prefix, via, add) { Ok(()) => Msg::Ack.encode(&mut out), Err(e) => Msg::Error(&format!("route: {e}")).encode(&mut out), @@ -748,15 +902,26 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap match netns_pid(procs, id) { Some(pid) => { let num: u32 = ifname.strip_prefix("eth").and_then(|v| v.parse().ok()).unwrap_or(1); + let host_if = procs + .get(&pid) + .and_then(|p| p.run.veth_for(ifname).map(str::to_owned)) + .unwrap_or_else(|| extra_veth(id, num)); dns.unregister(bridge, ip); dns.leave(pid, bridge); - let host_if = extra_veth(id, num); if let Some(p) = procs.get_mut(&pid) { p.run.dns_entries.retain(|(b, a)| !(b == bridge && *a == ip)); - p.run.veths.retain(|v| *v != host_if); + p.run.veths.retain(|(iface, _)| iface != ifname); } match net::detach(&host_if) { - Ok(()) => Msg::Ack.encode(&mut out), + Ok(()) => { + if let Some(p) = procs.get_mut(&pid) { + // Unplugged already: a route that cannot move is no reason to fail the disconnect. + if let Err(e) = net::hand_over_default_routes(pid, &mut p.run.uplinks, &host_if) { + eprintln!("kiri-init: moving {id}'s default route after a disconnect: {e}"); + } + } + Msg::Ack.encode(&mut out) + } Err(e) => Msg::Error(&format!("disconnect: {e}")).encode(&mut out), } } @@ -789,6 +954,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap Msg::Error(&format!("container {id} is not running")).encode(&mut out), }, + Ok(Msg::FsReadLink { id, path }) => match running_rootfs(procs, paths, id) { + Some(root) => match super::fsview::read_link(&root, path, &mut fs_buf) { + Ok(()) => Msg::FsData(&fs_buf).encode(&mut out), + Err(e) => Msg::Error(&format!("readlink {path}: {e}")).encode(&mut out), + }, + None => Msg::Error(&format!("container {id} is not running")).encode(&mut out), + }, Ok(other) => Msg::Error(&format!("unexpected {other:?}")).encode(&mut out), // A frame the host expects no reply to gets none, decoded // or not: an answer would be read as the next one's reply. @@ -805,6 +977,13 @@ fn serve_loop(mut conn: File, paths: &Paths, procs: &mut HashMap bool { + flags & kiri_proto::run_flags::NET_NONE == 0 +} + /// Runs the DHCP client alone until it has a lease or `max` passes. fn wait_for_lease(dhcp: &mut Option, max: std::time::Duration) { let Some(d) = dhcp.as_mut() else { return }; @@ -820,7 +999,11 @@ fn wait_for_lease(dhcp: &mut Option, max: std::time::Duration) { // SAFETY: one valid pollfd. unsafe { libc::poll(&mut pfd, 1, wait.max(1)) }; if pfd.revents != 0 { - let _ = d.on_readable(); + if let Ok(true) = d.on_readable() + && let Some(l) = &d.lease + { + eprintln!("kiri-init: {} is {}/{} via {}", net::UPLINK, net::ip_str(l.ip), l.prefix, net::ip_str(l.gateway)); + } } let _ = d.on_timer(); } @@ -850,6 +1033,25 @@ fn live_pid(procs: &HashMap, id: &str) -> Option /// and is not yet entered: its child has perhaps not joined it, and /// `/proc//ns/net` could still be the host's. Answered as for a /// container that is not running. +/// Records `(bridge, ip)` once in `run.dns_entries` so container exit (or +/// `NetDetach`) cleans up any names and per-IP DNS upstreams registered for it. +fn record_dns_entry(run: &mut Process, bridge: &str, ip: [u8; 4]) { + if !run.dns_entries.iter().any(|(b, a)| b == bridge && *a == ip) { + run.dns_entries.push((bridge.to_owned(), ip)); + } +} + +/// Applies the container's `--dns` upstreams to a newly attached `kiri0` +/// address and records it in `dns_entries` so exit without `NetDetach` drops it. +fn attach_kiri0_upstream(dns: &mut super::dns::Dns, procs: &mut HashMap, pid: libc::pid_t, bridge: &str, ip: [u8; 4]) { + if let Some(servers) = dns.container_upstream(pid) { + dns.set_upstream(ip, servers); + if let Some(p) = procs.get_mut(&pid) { + record_dns_entry(&mut p.run, bridge, ip); + } + } +} + /// Whether a `DnsRename` may change names: `ip` on `bridge` is a live /// container's own entry, and the bridge is one of Kiri's user networks. fn rename_allowed(procs: &HashMap, id: &str, bridge: &str, ip: [u8; 4]) -> bool { @@ -1020,15 +1222,31 @@ fn self_rss_kib() -> u64 { pages * unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as u64 / 1024 } -/// Whether the guest's clock is more than a quarter second from `ns` -/// (Unix nanoseconds, the host's time). -fn clock_off(ns: u64) -> bool { - let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos() as u64); - off_by_more(now, ns, 250_000_000) +const CLOCK_SLOP_NS: u64 = 250_000_000; +const CLOCK_STEP_NS: u64 = 1_000_000_000; +const ADJ_MAX_PHASE_US: i64 = 500_000; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ClockAdjust { + None, + /// Smoothly slew `offset_us` microseconds via `adjtimex(ADJ_OFFSET_SINGLESHOT)`. + Slew(i64), + /// Hard-step `CLOCK_REALTIME` after large jumps (e.g. VM wake from sleep). + Step, } -fn off_by_more(a: u64, b: u64, limit: u64) -> bool { - a.abs_diff(b) > limit +/// Decides how the guest clock should correct drift toward `target_ns` (Unix ns): +/// ignore `<= 250 ms`, slew `(250 ms, 1 s]` smoothly, and hard-step `> 1 s` (#509). +fn clock_adjustment(now_ns: u64, target_ns: u64) -> ClockAdjust { + let diff = now_ns.abs_diff(target_ns); + if diff <= CLOCK_SLOP_NS { + return ClockAdjust::None; + } + if diff > CLOCK_STEP_NS { + return ClockAdjust::Step; + } + let signed_us = if target_ns >= now_ns { (diff / 1_000) as i64 } else { -((diff / 1_000) as i64) }; + ClockAdjust::Slew(signed_us.clamp(-ADJ_MAX_PHASE_US, ADJ_MAX_PHASE_US)) } /// Reads one frame into `buf`. Returns false on a clean end of stream. @@ -1266,6 +1484,27 @@ mod running_tests { assert!(!rename_allowed(&procs, "c1", "kiri1", ip)); } + #[test] + fn kiri0_upstream_is_recorded_in_dns_entries_and_cleaned_up_on_exit() { + let kiri0_ip = [172, 17, 0, 5]; + let mut dns = super::super::dns::Dns::default(); + let mut procs = HashMap::new(); + procs.insert(100, new_proc(Process::for_test("c1", 100), 0, 0)); + dns.set_container_upstream(100, vec![[8, 8, 8, 8]]); + + super::attach_kiri0_upstream(&mut dns, &mut procs, 100, "kiri0", kiri0_ip); + assert_eq!(procs[&100].run.dns_entries, [("kiri0".to_owned(), kiri0_ip)]); + assert_eq!(dns.ip_upstream(kiri0_ip), Some(vec![[8, 8, 8, 8]])); + assert!(!rename_allowed(&procs, "c1", "kiri0", kiri0_ip), "kiri0 stays disallowed for DnsRename"); + + let (_host, mut conn) = pipe(); + let mut exited = procs.remove(&100).unwrap(); + exited.exited = Some((0, 0)); + super::finish(&mut conn, &mut dns, &procs, exited, true).unwrap(); + assert_eq!(dns.ip_upstream(kiri0_ip), None, "container exit cleans up kiri0 per-IP upstream"); + assert_eq!(dns.container_upstream(100), None); + } + #[test] fn a_restarted_container_is_found_never_its_exited_run() { // Each map hashes with its own seed, so 20 of them walk the two @@ -1546,7 +1785,12 @@ mod running_tests { let mut procs = HashMap::new(); let mut dns = super::super::dns::Dns::default(); let mut failed = HashMap::new(); - let paths = super::Paths { layers: "/l".into(), containers: "/c".into(), cgroup: "/g".into() }; + let paths = super::Paths { + layers: "/l".into(), + containers: "/c".into(), + cgroup: "/g".into(), + cgroup_root: "/sys/fs/cgroup".into(), + }; procs.insert(300, new_proc(Process::starting_for_test("c1", 300, r.into(), None), 0, 0)); assert_eq!(super::running_rootfs(&procs, &paths, "c1"), Some("/c/c1/rootfs".into()), "not /proc/300/root, which is the agent's own root"); assert_eq!(super::running_rootfs(&procs, &paths, "nope"), None); @@ -1587,21 +1831,57 @@ mod running_tests { assert_ne!(unsafe { libc::kill(pid, 0) }, 0, "killed and reaped once its root was in place"); let _ = child.try_wait(); } + + #[test] + fn wait_for_lease_runs_for_bridged_and_host_but_not_none() { + use kiri_proto::run_flags; + assert!(super::needs_lease(0), "default bridge needs a lease"); + assert!(super::needs_lease(run_flags::NET_HOST), "host network in the VM shares eth0 and needs a lease"); + assert!(super::needs_lease(run_flags::NET_HOST | run_flags::REMOVE)); + assert!(!super::needs_lease(run_flags::NET_NONE), "--network none skips waiting for a lease"); + assert!(!super::needs_lease(run_flags::NET_NONE | run_flags::REMOVE)); + // On a Linux host there is no DHCP client; wait_for_lease is an immediate no-op. + let mut none = None; + let t = std::time::Instant::now(); + super::wait_for_lease(&mut none, std::time::Duration::from_secs(3)); + assert!(t.elapsed() < std::time::Duration::from_secs(1)); + } } #[cfg(test)] mod clock_tests { - use super::off_by_more; + use super::{ClockAdjust, clock_adjustment}; #[test] - fn steps_only_when_the_clock_is_off() { + fn slews_subsecond_drift_and_steps_only_large_jumps() { let now = 1_792_800_000_000_000_000; - assert!(!off_by_more(now, now, 250_000_000)); - assert!(!off_by_more(now, now + 200_000_000, 250_000_000)); - assert!(!off_by_more(now + 200_000_000, now, 250_000_000)); - // An hour behind, after the Mac slept. - assert!(off_by_more(now - 3_600_000_000_000, now, 250_000_000)); - assert!(off_by_more(now + 300_000_000, now, 250_000_000)); + assert_eq!(clock_adjustment(now, now), ClockAdjust::None); + assert_eq!(clock_adjustment(now, now + 200_000_000), ClockAdjust::None); + assert_eq!(clock_adjustment(now + 200_000_000, now), ClockAdjust::None); + // Sub-second drift (> 250 ms, <= 1 s) slews smoothly via adjtimex instead of stepping. + assert_eq!(clock_adjustment(now, now + 300_000_000), ClockAdjust::Slew(300_000)); + assert_eq!(clock_adjustment(now + 300_000_000, now), ClockAdjust::Slew(-300_000)); + assert_eq!(clock_adjustment(now, now + 800_000_000), ClockAdjust::Slew(500_000)); + assert_eq!(clock_adjustment(now + 800_000_000, now), ClockAdjust::Slew(-500_000)); + // An hour behind, after the Mac slept, still hard-steps. + assert_eq!(clock_adjustment(now - 3_600_000_000_000, now), ClockAdjust::Step); + assert_eq!(clock_adjustment(now, now + 1_500_000_000), ClockAdjust::Step); + } +} + +#[cfg(test)] +mod veth_tests { + use super::extra_veth; + use super::super::container::Process; + + #[test] + fn detach_looks_up_first_kv_and_fallback_kx_veths() { + let mut p = Process::for_test("0123456789abcdef", 10); + p.veths.push(("eth0".into(), "kv0123456780001".into())); + p.veths.push(("eth1".into(), extra_veth(&p.id, 1))); + assert_eq!(p.veth_for("eth0"), Some("kv0123456780001")); + assert_eq!(p.veth_for("eth1"), Some("kx0123456781")); + assert_eq!(p.veth_for("eth2"), None); } } diff --git a/crates/kiri-init/src/linux/cgroup.rs b/crates/kiri-init/src/linux/cgroup.rs index bf7c4fdbe..c19601aa9 100644 --- a/crates/kiri-init/src/linux/cgroup.rs +++ b/crates/kiri-init/src/linux/cgroup.rs @@ -2,24 +2,55 @@ //! `docker update`), freezing (`docker pause`), and what `docker stats` and //! `docker top` read. -use std::fs; -use std::io; +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; use std::path::Path; use kiri_proto::{ContainerStats, Limits}; use super::sys; +/// Writes a single cgroup v2 control file without `O_CREAT`: on kernfs, +/// `O_CREAT` against a missing control file fails with `EACCES` instead of +/// `ENOENT`. When a controller is held by cgroup v1 (stock WSL 2 hybrid +/// tree) or not delegated to this cgroup, its control files do not exist; +/// skip them instead of failing container start, and note when an explicit +/// limit could not be applied. +fn write_control(dir: &Path, file: &str, value: &str, requested: bool) -> io::Result<()> { + match OpenOptions::new().write(true).truncate(true).open(dir.join(file)) { + Ok(mut f) => f.write_all(value.as_bytes()).map_err(|e| io::Error::new(e.kind(), format!("{file}: {e}"))), + Err(e) if e.kind() == io::ErrorKind::NotFound => { + if requested { + eprintln!("kiri-init: {file} unavailable in this cgroup v2 hierarchy (controller held by cgroup v1 or not delegated); skipping limit"); + } + Ok(()) + } + Err(e) => Err(io::Error::new(e.kind(), format!("{file}: {e}"))), + } +} + /// Writes the limits into the cgroup. Zero fields mean "no limit". pub fn apply_limits(dir: &Path, l: &Limits) -> io::Result<()> { - let write = |file: &str, value: String| fs::write(dir.join(file), value).map_err(|e| io::Error::new(e.kind(), format!("{file}: {e}"))); - write("memory.max", if l.memory_max == 0 { "max".into() } else { l.memory_max.to_string() })?; - // No swap in the VM: a limit is a limit. - let _ = fs::write(dir.join("memory.swap.max"), "0"); + if !dir.is_dir() { + return Err(io::Error::new(io::ErrorKind::NotFound, format!("{}: cgroup directory not found", dir.display()))); + } + let mem = if l.memory_max == 0 { "max".into() } else { l.memory_max.to_string() }; + write_control(dir, "memory.max", &mem, l.memory_max != 0)?; + // Docker's `--memory-swap`, worked out by the daemon. The VM has no swap, + // so it matters on a Linux host, which may. A kernel without swap or a + // hybrid cgroup tree without the memory controller has no such file; open + // without `O_CREAT` so we never create fake files or hit kernfs `EACCES`. + if let Ok(mut f) = OpenOptions::new().write(true).truncate(true).open(dir.join("memory.swap.max")) { + let swap = if l.swap_max == kiri_proto::NO_LIMIT { "max".into() } else { l.swap_max.to_string() }; + let _ = f.write_all(swap.as_bytes()); + } let period = if l.cpu_period == 0 { 100_000 } else { l.cpu_period }; - write("cpu.max", if l.cpu_quota == 0 { format!("max {period}") } else { format!("{} {period}", l.cpu_quota) })?; - write("cpu.weight", if l.cpu_weight == 0 { "100".into() } else { l.cpu_weight.clamp(1, 10_000).to_string() })?; - write("pids.max", if l.pids_max == 0 { "max".into() } else { l.pids_max.to_string() })?; + let cpu_max = if l.cpu_quota == 0 { format!("max {period}") } else { format!("{} {period}", l.cpu_quota) }; + write_control(dir, "cpu.max", &cpu_max, l.cpu_quota != 0)?; + let cpu_weight = if l.cpu_weight == 0 { "100".into() } else { l.cpu_weight.clamp(1, 10_000).to_string() }; + write_control(dir, "cpu.weight", &cpu_weight, l.cpu_weight != 0)?; + let pids = if l.pids_max == 0 { "max".into() } else { l.pids_max.to_string() }; + write_control(dir, "pids.max", &pids, l.pids_max != 0)?; Ok(()) } @@ -36,8 +67,20 @@ pub fn freeze(dir: &Path, frozen: bool) -> io::Result<()> { Err(io::Error::new(io::ErrorKind::TimedOut, "the container did not freeze in time")) } +fn keyed_opt(text: &str, key: &str) -> Option { + text.lines().find_map(|l| l.strip_prefix(key).and_then(|v| v.strip_prefix(' '))).and_then(|v| v.trim().parse().ok()) +} + fn keyed(text: &str, key: &str) -> u64 { - text.lines().find_map(|l| l.strip_prefix(key).and_then(|v| v.strip_prefix(' '))).and_then(|v| v.trim().parse().ok()).unwrap_or(0) + keyed_opt(text, key).unwrap_or(0) +} + +/// CPU throttling counters from `cpu.stat`: `(nr_periods, nr_throttled, throttled_usec)`. +/// cgroup v2 reports `throttled_usec` in microseconds; cgroup v1 reports +/// `throttled_time` in nanoseconds. +fn cpu_throttling(cpu_stat: &str) -> (u64, u64, u64) { + let throttled_usec = keyed_opt(cpu_stat, "throttled_usec").unwrap_or_else(|| keyed(cpu_stat, "throttled_time") / 1000); + (keyed(cpu_stat, "nr_periods"), keyed(cpu_stat, "nr_throttled"), throttled_usec) } /// What the cgroup holds and cannot give back, in bytes: anonymous, shared @@ -83,6 +126,7 @@ pub fn stats(dir: &Path, pid: libc::pid_t) -> io::Result { let read = |f: &str| fs::read_to_string(dir.join(f)).unwrap_or_default(); let cpu = read("cpu.stat"); let mem_stat = read("memory.stat"); + let (cpu_periods, cpu_throttled_periods, cpu_throttled_usec) = cpu_throttling(&cpu); let mut s = ContainerStats { read_ns: sys::boottime_ns(), mem_current: read("memory.current").trim().parse().unwrap_or(0), @@ -91,6 +135,9 @@ pub fn stats(dir: &Path, pid: libc::pid_t) -> io::Result { cpu_usage_usec: keyed(&cpu, "usage_usec"), cpu_user_usec: keyed(&cpu, "user_usec"), cpu_system_usec: keyed(&cpu, "system_usec"), + cpu_periods, + cpu_throttled_periods, + cpu_throttled_usec, pids: read("pids.current").trim().parse().unwrap_or(0), // SAFETY: sysconf has no preconditions. online_cpus: unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) }.max(1) as u32, @@ -249,4 +296,94 @@ mod tests { assert_eq!(keyed("low 0\nhigh 0\nmax 3\noom 2\noom_kill 1\noom_group_kill 0\n", "oom_kill"), 1); assert_eq!(keyed("pgfault 9\noom_kill 0\n", "oom_kill"), 0); } + + fn temp_cgroup(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("kiri-cg-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir + } + + #[test] + fn apply_limits_writes_all_files_when_controllers_exist() { + let dir = temp_cgroup("all"); + for f in ["memory.max", "memory.swap.max", "cpu.max", "cpu.weight", "pids.max"] { + fs::write(dir.join(f), "").unwrap(); + } + let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 0, swap_max: 67_108_864 }; + apply_limits(&dir, &lim).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.max")).unwrap(), "67108864"); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "67108864"); + assert_eq!(fs::read_to_string(dir.join("cpu.max")).unwrap(), "50000 100000"); + assert_eq!(fs::read_to_string(dir.join("cpu.weight")).unwrap(), "250"); + assert_eq!(fs::read_to_string(dir.join("pids.max")).unwrap(), "64"); + + // Zero swap (`--memory-swap == --memory`) and unlimited swap (`-1`). + apply_limits(&dir, &Limits { swap_max: 0, ..lim }).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "0"); + apply_limits(&dir, &Limits { swap_max: kiri_proto::NO_LIMIT, ..lim }).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.swap.max")).unwrap(), "max"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn apply_limits_skips_missing_controllers_on_hybrid_tree() { + // Hybrid cgroup v2 directory whose controllers are bound to v1: none of + // memory.max, memory.swap.max, cpu.max, cpu.weight or pids.max exist. + let dir = temp_cgroup("hybrid"); + let lim = Limits { memory_max: 67_108_864, cpu_quota: 50_000, cpu_period: 100_000, cpu_weight: 250, pids_max: 64, shm_size: 134_217_728, swap_max: 67_108_864 }; + apply_limits(&dir, &lim).unwrap(); + // OpenOptions without O_CREAT must not create fake files either. + assert!(!dir.join("memory.max").exists()); + assert!(!dir.join("memory.swap.max").exists()); + assert!(!dir.join("cpu.max").exists()); + assert!(!dir.join("pids.max").exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn apply_limits_skips_missing_swap_file_when_memory_exists() { + // Kernel without swap accounting (or VM kernel with no swap): memory.max + // exists, memory.swap.max does not. + let dir = temp_cgroup("no-swap"); + fs::write(dir.join("memory.max"), "").unwrap(); + let lim = Limits { memory_max: 67_108_864, swap_max: 33_554_432, ..Default::default() }; + apply_limits(&dir, &lim).unwrap(); + assert_eq!(fs::read_to_string(dir.join("memory.max")).unwrap(), "67108864"); + assert!(!dir.join("memory.swap.max").exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn apply_limits_writes_available_subset_of_controllers() { + let dir = temp_cgroup("subset"); + fs::write(dir.join("pids.max"), "").unwrap(); + let lim = Limits { memory_max: 67_108_864, pids_max: 32, ..Default::default() }; + apply_limits(&dir, &lim).unwrap(); + assert_eq!(fs::read_to_string(dir.join("pids.max")).unwrap(), "32"); + assert!(!dir.join("memory.max").exists()); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn cpu_throttling_reads_v2_and_v1_formats() { + let v2 = "usage_usec 12345\nuser_usec 10000\nsystem_usec 2345\nnr_periods 12\nnr_throttled 5\nthrottled_usec 43210\n"; + assert_eq!(cpu_throttling(v2), (12, 5, 43_210)); + + let v2_zero = "usage_usec 500\nnr_periods 4\nnr_throttled 0\nthrottled_usec 0\n"; + assert_eq!(cpu_throttling(v2_zero), (4, 0, 0)); + + let v1 = "nr_periods 12\nnr_throttled 5\nthrottled_time 43210000\n"; + assert_eq!(cpu_throttling(v1), (12, 5, 43_210)); + + assert_eq!(cpu_throttling(""), (0, 0, 0)); + } + + #[test] + fn apply_limits_errors_when_cgroup_dir_is_missing() { + let missing = std::env::temp_dir().join(format!("kiri-cg-missing-{}", std::process::id())); + let _ = fs::remove_dir_all(&missing); + let err = apply_limits(&missing, &Limits { memory_max: 67_108_864, ..Default::default() }).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::NotFound); + } } diff --git a/crates/kiri-init/src/linux/container.rs b/crates/kiri-init/src/linux/container.rs index 8a80ebb98..9f6a0be18 100644 --- a/crates/kiri-init/src/linux/container.rs +++ b/crates/kiri-init/src/linux/container.rs @@ -1,9 +1,11 @@ //! Starts containers and execs. //! -//! A container is one clone3 straight into fresh namespaces and its cgroup; -//! the child sets up its root and execs. An exec joins a running container's -//! namespaces and cgroup the same way. No runc, no shim, no extra fork: -//! every process is a direct child of the agent, so waiting just works. +//! A container is one clone3 straight into fresh namespaces and its cgroup +//! (or, where clone3 is blocked, one clone that the agent then moves into +//! its cgroup); the child sets up its root and execs. An exec joins a +//! running container's namespaces and cgroup the same way. No runc, no shim, +//! no extra fork: every process is a direct child of the agent, so waiting +//! just works. use std::ffi::{CStr, CString}; use std::fs; @@ -41,6 +43,9 @@ const LAST_CAP: u32 = 40; const DEFAULT_PATH: &str = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; +/// The file Docker puts in every container's root, relative to that root. +pub const MARKER: &CStr = c".dockerenv"; + /// What networking the agent can offer a new container right now. pub struct NetCtx<'a> { pub bridges: &'a mut Bridges, @@ -59,6 +64,9 @@ pub struct Paths { pub layers: PathBuf, pub containers: PathBuf, pub cgroup: PathBuf, + /// The mounted cgroup v2 hierarchy root (`/sys/fs/cgroup`, or + /// `/sys/fs/cgroup/unified` on a hybrid host such as stock WSL 2). + pub cgroup_root: PathBuf, } /// A process the agent started: a container's PID 1, or an exec. @@ -78,10 +86,13 @@ pub struct Process { pub tty: bool, /// (bridge, ip) registered with the DNS server, to drop on exit. pub dns_entries: Vec<(String, [u8; 4])>, - /// Host sides of its veths. Deleted on exit: a container sharing this - /// network namespace would otherwise keep them, and the address that - /// goes back to the pool, alive. - pub veths: Vec, + /// `(ifname, host_veth)` for each attached bridge interface. Deleted on + /// exit: a container sharing this network namespace would otherwise keep + /// them, and the address that goes back to the pool, alive. + pub veths: Vec<(String, String)>, + /// Its non-internal networks, in the order they were plugged in: which + /// one takes the default route when the one holding it is disconnected. + pub uplinks: Vec, /// Inode of its own network namespace, or of the one it joined; 0 for /// the host's and for execs. Says whether a namespace outlives this /// container (see `teardown`). @@ -124,6 +135,11 @@ pub enum Root { } impl Process { + /// Host-side veth currently plugged in as container interface `ifname`. + pub fn veth_for(&self, ifname: &str) -> Option<&str> { + self.veths.iter().find(|(iface, _)| iface == ifname).map(|(_, host)| host.as_str()) + } + /// Settles where its root stands, without waiting: the child's byte /// means ready, the pipe's end means it ended first, nothing yet means /// still starting. @@ -245,6 +261,7 @@ impl Process { tty: false, dns_entries: Vec::new(), veths: Vec::new(), + uplinks: Vec::new(), netns: 0, joins_netns: false, seccomp: Vec::new(), @@ -268,6 +285,7 @@ struct Teardown { base: PathBuf, cgroup: PathBuf, remove: bool, + loop_mounts: Vec, } /// Everything the child needs, prepared before clone so the child does as @@ -308,12 +326,19 @@ struct Prepared { shm_size: u64, /// `--init`: PID 1 supervises the program instead of being it. init: bool, + /// `--cgroupns host`: no cgroup namespace of its own. + cgroupns_host: bool, + /// Timer slack in nanoseconds for the container's PID 1 (`timerslack_ns`). + timer_slack_ns: Option, /// Ulimits, groups and device nodes from the `opts` lines. host: HostApplied, /// The child's end of the pipe that says its root is in place (mounts /// made, `pivot_root` done), so a start is not reported before an exec /// can join its mount namespace (#311). root_ready: Option, + /// The child's end of the pipe that says it has been moved into its + /// cgroup. Only a start that fell back to clone(2) waits on it. + cgroup_ready: Option, } /// The parts of [`super::hostopts::HostOpts`] the child applies itself. @@ -322,6 +347,8 @@ struct HostApplied { rlimits: Vec<(u32, u64, u64)>, groups: Vec, nodes: Vec, + masked: Option>, + readonly: Option>, } /// Docker's default capability set as a mask. @@ -450,21 +477,68 @@ fn stdio(p: &Prepared) -> io::Result<(ParentStdio, ChildStdio)> { )) } +/// Maximum wait for a spawned/exec'd TTY child to open `/dev/ptmx` and send +/// its master fd back over the control socket. Prevents a child cloned into a +/// frozen cgroup or wedged before `open_pty` from blocking single-threaded +/// `kiri-init` forever (#948). +const TTY_READY_WAIT: std::time::Duration = std::time::Duration::from_secs(10); + /// After clone: collect the agent's ends. For a TTY this waits for the child /// to send the pty master, or the reason it could not. fn finish_stdio(parent: ParentStdio, child: ChildStdio) -> io::Result<(Option, Option, Option)> { + finish_stdio_timeout(parent, child, TTY_READY_WAIT) +} + +fn finish_stdio_timeout( + parent: ParentStdio, + child: ChildStdio, + wait: std::time::Duration, +) -> io::Result<(Option, Option, Option)> { drop(child); match parent { ParentStdio::Pipes { stdin, stdout, stderr } => Ok((stdin, Some(stdout), Some(stderr))), - ParentStdio::Tty { sock } => match sys::recv_fd(sock.as_raw_fd())? { - Received::Fd(master) => { - sys::set_nonblocking(master.as_raw_fd())?; - let input = master.try_clone()?; - Ok((Some(input), Some(master), None)) + ParentStdio::Tty { sock } => { + sys::set_nonblocking(sock.as_raw_fd())?; + let deadline = std::time::Instant::now() + wait; + let received = loop { + let timeout = deadline + .saturating_duration_since(std::time::Instant::now()) + .as_micros() + .div_ceil(1000) + .min(i32::MAX as u128) as i32; + let mut pfd = libc::pollfd { fd: sock.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + // SAFETY: one valid pollfd. + let n = unsafe { libc::poll(&mut pfd, 1, timeout) }; + if n == 0 { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container terminal")); + } + if n < 0 { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(e); + } + match sys::recv_fd(sock.as_raw_fd()) { + Ok(r) => break r, + Err(e) if e.kind() == io::ErrorKind::Interrupted || e.kind() == io::ErrorKind::WouldBlock => { + if std::time::Instant::now() >= deadline { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container terminal")); + } + } + Err(e) => return Err(e), + } + }; + match received { + Received::Fd(master) => { + sys::set_nonblocking(master.as_raw_fd())?; + let input = master.try_clone()?; + Ok((Some(input), Some(master), None)) + } + Received::Message(m) if m.is_empty() => Err(io::Error::other("container exited before its terminal was ready")), + Received::Message(m) => Err(io::Error::other(m)), } - Received::Message(m) if m.is_empty() => Err(io::Error::other("container exited before its terminal was ready")), - Received::Message(m) => Err(io::Error::other(m)), - }, + } } } @@ -473,12 +547,13 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

= spec.layers.iter().collect(); - let rootfs = super::roots::acquire(paths, spec.id, &layers)?; + let writable_rootfs = spec.flags & run_flags::READONLY_ROOTFS == 0; + let rootfs = super::roots::acquire(paths, spec.id, &layers, writable_rootfs)?; let base = paths.containers.join(spec.id); let cgroup = paths.cgroup.join(spec.id); let remove = spec.flags & run_flags::REMOVE != 0; - let undo = Teardown { base: base.clone(), cgroup: cgroup.clone(), remove }; + let undo = Teardown { base: base.clone(), cgroup: cgroup.clone(), remove, loop_mounts: Vec::new() }; // A restart that fails must not take the stopped container's files with it. let cleanup = |e: io::Error| { undo_now(&undo, remove); @@ -543,18 +618,38 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

= prepared.mounts.iter().filter_map(|m| m.loop_mount.clone()).collect(); + let undo = Teardown { base: base.clone(), cgroup: cgroup.clone(), remove, loop_mounts: loop_mounts.clone() }; + let cleanup = |e: io::Error| { + undo_now(&undo, remove); + e + }; // A network namespace of its own gets Docker's two defaults: any port // and ping without root. Host networking, and `--network container:` // (that container already has them), keep what they have. if spec.flags & run_flags::NET_HOST == 0 && prepared.net_join.is_none() { + let had_ping = host.sysctls.iter().any(|s| s.path == "net/ipv4/ping_group_range"); super::hostopts::add_net_defaults(&mut host.sysctls); + static SELF_PING_MAX: std::sync::OnceLock> = std::sync::OnceLock::new(); + if !had_ping + && let Some(max) = *SELF_PING_MAX.get_or_init(|| fs::read_to_string("/proc/self/gid_map").ok().map(|m| ping_group_max(&m))) + { + if max < DEFAULT_PING_MAX + && let Some(s) = host.sysctls.iter_mut().find(|s| s.path == "net/ipv4/ping_group_range") + { + s.value = format!("0 {max}"); + } + } } let bridged = !spec.net.bridge.is_empty() && spec.flags & (run_flags::NET_HOST | run_flags::NET_NONE) == 0 && prepared.net_join.is_none(); let mut go = None; @@ -570,10 +665,24 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

e, } }; + if !cloned.into_cgroup { + // clone(2) cannot put the child in its cgroup: do it now, before it + // mounts anything and its limits have to apply. The child waits on + // the pipe until this write is done. + fs::write(cgroup.join("cgroup.procs"), pid.to_string()) + .map_err(|e| kill_child(io::Error::new(e.kind(), format!("cgroup: {e}"))))?; + if let Some(go_fd) = &cgroup_go { + // SAFETY: one byte to a pipe we own: "you are in your cgroup". + if unsafe { libc::write(go_fd.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 { + return Err(kill_child(io::Error::last_os_error())); + } + } + } + drop(cgroup_go); // Before `pivot_root`, an exec joining its mount namespace gets the // agent's `/etc/passwd`, and an image user such as `dev` is unknown // (#311). So the start waits for the root, briefly (ROOT_READY_WAIT): @@ -679,15 +810,28 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

{} Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))), - Ok(RootWord::NotYet) if prepared.tty => match root_word(root_ready.as_raw_fd(), None, &mut began_fill) { - Ok(RootWord::Ready) => {} - Ok(_) => return Err(kill_child(io::Error::other(NOT_READY))), - Err(e) => return Err(kill_child(e)), - }, + Ok(RootWord::NotYet) if prepared.tty => { + let word = if began_fill { + root_word(root_ready.as_raw_fd(), None, &mut began_fill) + } else { + match root_word(root_ready.as_raw_fd(), Some(TTY_READY_WAIT), &mut began_fill) { + Ok(RootWord::NotYet) if began_fill => root_word(root_ready.as_raw_fd(), None, &mut began_fill), + other => other, + } + }; + filling.set(began_fill); + match word { + Ok(RootWord::Ready) => {} + Ok(RootWord::NotYet) => return Err(kill_child(io::Error::new(io::ErrorKind::TimedOut, "timed out waiting for container root"))), + Ok(RootWord::Ended) => return Err(kill_child(io::Error::other(NOT_READY))), + Err(e) => return Err(kill_child(e)), + } + } Ok(RootWord::NotYet) => starting.set(true), Err(e) => return Err(kill_child(e)), } let mut veths = Vec::new(); + let mut uplinks = Vec::new(); // Names, AAAA records and `--dns` servers to give the DNS server, once // nothing can fail any more: a failed start must not leave its names // answering (#325). Nothing is answered before then anyway, since the @@ -696,7 +840,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

f, + None => { + opened = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; + &opened } - Ok(()) - }) + }; + net.dns.serve_in(ns, pid, spec.net.bridge)?; + // User networks it joins once it runs: their names + // answer from its first lookup (#449). + for b in net_opts::values(spec.net.opts, net_opts::DNS_BRIDGE) { + net.dns.serve_in(ns, pid, b)?; + } + Ok(()) }); if let Some(e) = in_err { net.dns.drop_container(pid); @@ -766,7 +918,7 @@ pub fn spawn(spec: &RunSpec<'_>, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

, paths: &Paths, net: NetCtx<'_>) -> io::Result

io::Result { +fn plain_upper(base: &Path, writable: bool) -> io::Result { let marker = base.join(PLAIN_UPPER); if marker.exists() { return Ok(true); @@ -826,8 +980,22 @@ fn plain_upper(base: &Path) -> io::Result { // written into it since this one looked for the marker. return Ok(marker.exists()); } - fs::write(marker, b"")?; - Ok(true) + match fs::write(marker, b"") { + Ok(()) => Ok(true), + Err(e) if !writable && e.raw_os_error() == Some(libc::EROFS) => Ok(true), + Err(e) => Err(e), + } +} + +/// Marks a writable layer that `kiri import` brought in whole as plain +/// (see `plain_upper`): it holds whole files, whole directories, whiteouts +/// and opaque marks, and no overlayfs redirects or metadata-only copies +/// (`copy` strips those attributes). Without the mark its first mount would +/// find it already written to and keep the kernel's defaults, under which +/// later writes may redirect directories that `docker diff` and `commit` +/// can't read. +pub(super) fn mark_plain_upper(base: &Path) -> io::Result<()> { + fs::write(base.join(PLAIN_UPPER), b"") } /// The overlayfs features to mount with, whatever the kernel's defaults @@ -844,16 +1012,55 @@ fn overlay_features(plain: bool) -> &'static str { if plain { "index=off,redirect_dir=nofollow,metacopy=off" } else { "index=off" } } +/// Verifies that a writable container's backing directory and mounted overlay +/// root are not read-only (`ST_RDONLY` / `emergency_ro`). Linux `overlayfs` +/// silently falls back to mounting read-only (returning 0 from `mount(2)`) +/// when `work/work` fails on `EROFS` or `EEXIST` (#768). +pub(super) fn ensure_writable_rootfs(base: &Path, rootfs: &Path) -> io::Result<()> { + let kind = match (sys::detect_readonly_fs(base), sys::detect_readonly_fs(rootfs)) { + (Some(a), Some(b)) => Some(a.merge(b)), + (Some(a), None) | (None, Some(a)) => Some(a), + (None, None) => None, + }; + match kind { + Some(k) => Err(sys::readonly_storage_error(k)), + None => Ok(()), + } +} + +fn map_rofs_error(base: &Path, writable: bool, err: io::Error) -> io::Error { + if writable && err.raw_os_error() == Some(libc::EROFS) { + let kind = sys::detect_readonly_fs(base).unwrap_or(sys::ReadOnlyKind::ReadOnly); + return sys::readonly_storage_error(kind); + } + err +} + /// Mounts a container's root: its image layers under its writable layer, /// at `//rootfs`. Returns that path. Only `roots` calls /// this, which keeps it to one mount per container. -pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str]) -> io::Result { +pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str], writable: bool) -> io::Result { valid_id(id)?; let base = paths.containers.join(id); + let fresh_base = !base.exists(); + if !fresh_base + && writable + && let Some(kind) = sys::detect_readonly_fs(&base) + { + return Err(sys::readonly_storage_error(kind)); + } let (upper, work, rootfs) = (base.join("upper"), base.join("work"), base.join("rootfs")); - let _ = sys::umount_lazy(&rootfs); - for d in [&upper, &work, &rootfs] { - fs::create_dir_all(d)?; + if fresh_base { + for d in [&upper, &work, &rootfs] { + fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?; + } + } else { + let _ = sys::umount_lazy(&rootfs); + for d in [&upper, &work, &rootfs] { + if !d.is_dir() { + fs::create_dir_all(d).map_err(|e| map_rofs_error(&base, writable, e))?; + } + } } // Lower dirs are relative to the agent's working directory (the layer // store), which keeps the option string short enough for many layers. @@ -878,11 +1085,39 @@ pub(super) fn mount_rootfs(paths: &Paths, id: &str, image_layers: &[&str]) -> io // fails at exec, as Docker's does, instead of failing to mount. if lower.is_empty() { let empty = base.join("empty"); - fs::create_dir_all(&empty)?; + if !empty.is_dir() { + fs::create_dir_all(&empty).map_err(|e| map_rofs_error(&base, writable, e))?; + } lower.push(empty.to_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "container folder is not UTF-8"))?.to_owned()); } - let rest = format!(",upperdir={},workdir={},{}", upper.display(), work.display(), overlay_features(plain_upper(&base)?)); - sys::mount_overlay(&rootfs, &lower, &rest, 0)?; + let plain = if fresh_base { + match fs::write(base.join(PLAIN_UPPER), b"") { + Ok(()) => true, + Err(e) if !writable && e.raw_os_error() == Some(libc::EROFS) => true, + Err(e) => return Err(map_rofs_error(&base, writable, e)), + } + } else { + plain_upper(&base, writable).map_err(|e| map_rofs_error(&base, writable, e))? + }; + let rest = format!(",upperdir={},workdir={},{}", upper.display(), work.display(), overlay_features(plain)); + sys::mount_overlay(&rootfs, &lower, &rest, 0).map_err(|e| map_rofs_error(&base, writable, e))?; + if writable { + let ro_err = if fresh_base { + // `create_dir_all` already verified `base` is writable; one `statvfs` + // on `rootfs` catches overlayfs's silent read-only fallback (#768). + if sys::is_statvfs_readonly(&rootfs).unwrap_or(false) { + ensure_writable_rootfs(&base, &rootfs).err() + } else { + None + } + } else { + ensure_writable_rootfs(&base, &rootfs).err() + }; + if let Some(e) = ro_err { + super::roots::unmount(&rootfs); + return Err(e); + } + } Ok(rootfs) } @@ -908,10 +1143,19 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile let mut prepared = prepare(spec.argv, spec.env, spec.cwd, spec.user, None, spec.flags, spec.caps)?; // The container's ulimits and groups apply to its execs too, as with runc. let host = super::hostopts::parse(spec.opts)?; - prepared.host = HostApplied { rlimits: host.rlimits, groups: host.groups, nodes: Vec::new() }; + prepared.host = HostApplied { rlimits: host.rlimits, groups: host.groups, ..Default::default() }; // An exec runs under its container's profile, not the default. prepared.profile = profile.to_vec(); let (parent_io, child_io) = stdio(&prepared)?; + // The child waits here until the agent has moved it into its cgroup, for + // a start that clone3 could not place there itself. + let cgroup_go = if sys::clone3_works() { + None + } else { + let (child_cgroup_ready, go_fd) = sys::pipe()?; + prepared.cgroup_ready = Some(child_cgroup_ready); + Some(go_fd) + }; let args = CloneArgs { flags: CLONE_INTO_CGROUP, exit_signal: libc::SIGCHLD as u64, @@ -931,9 +1175,8 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile // no processes. Join the one its init lives in, as runc does. let init_cgroup; if cloned.as_ref().is_err_and(|e| e.kind() == io::ErrorKind::ResourceBusy) { - let rel = fs::read_to_string(format!("/proc/{target_pid}/cgroup")).unwrap_or_default(); - let rel = rel.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim_start_matches('/').to_owned(); - init_cgroup = fs::File::open(std::path::Path::new("/sys/fs/cgroup").join(&rel)); + let (rel, dir) = proc_cgroup(&paths.cgroup_root, target_pid); + init_cgroup = fs::File::open(dir); match &init_cgroup { Ok(fd) => { let retry = CloneArgs { cgroup: fd.as_raw_fd() as u64, ..args }; @@ -943,16 +1186,46 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile Err(e) => cloned = Err(io::Error::new(e.kind(), format!("cgroup {rel}: {e}"))), } } - if let Ok(0) = cloned { - exec_child(&prepared, &namespaces, &child_io); + if let Ok(c) = &cloned + && c.pid == 0 + { + exec_child(&prepared, &namespaces, &child_io, !c.into_cgroup); } let restored = sys::setns(own_pid_ns.as_raw_fd(), libc::CLONE_NEWPID); - let pid = cloned?; - restored?; + drop(prepared.cgroup_ready.take()); + let child = cloned?; + let pid = child.pid; + if let Err(e) = restored { + // SAFETY: killing and reaping the child we just cloned. + unsafe { + libc::kill(pid, libc::SIGKILL); + libc::waitpid(pid, std::ptr::null_mut(), 0); + } + return Err(e); + } + if !child.into_cgroup { + // clone(2) cannot put the exec in the container's cgroup: do it now, + // then let it join the container's namespaces. + if let Some(go_fd) = &cgroup_go + && let Err(e) = move_child(&paths.cgroup.join(spec.container_id), &paths.cgroup_root, pid, target_pid, go_fd) + { + // SAFETY: killing and reaping the child we just cloned. + unsafe { + libc::kill(pid, libc::SIGKILL); + libc::waitpid(pid, std::ptr::null_mut(), 0); + } + return Err(e); + } + } + drop(cgroup_go); drop(cgroup_fd); let (stdin, stdout, stderr) = finish_stdio(parent_io, child_io).map_err(|e| { - // SAFETY: killing the child we just cloned. - unsafe { libc::kill(pid, libc::SIGKILL) }; + // SAFETY: killing and reaping the child we just cloned so a failed or + // timed-out TTY setup never leaks a stuck or zombie process (#948). + unsafe { + libc::kill(pid, libc::SIGKILL); + libc::waitpid(pid, std::ptr::null_mut(), 0); + } e })?; Ok(Process { @@ -965,6 +1238,7 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile tty: prepared.tty, dns_entries: Vec::new(), veths: Vec::new(), + uplinks: Vec::new(), netns: 0, joins_netns: false, seccomp: Vec::new(), @@ -976,6 +1250,38 @@ pub fn exec(spec: &ExecSpec<'_>, target_pid: libc::pid_t, paths: &Paths, profile }) } +/// The cgroup v2 directory (under `cgroup_root`) where `pid` lives, and +/// its hierarchy-relative path for error messages. +fn proc_cgroup(cgroup_root: &Path, pid: libc::pid_t) -> (String, PathBuf) { + let text = fs::read_to_string(format!("/proc/{pid}/cgroup")).unwrap_or_default(); + cgroup_of_proc(cgroup_root, &text) +} + +fn cgroup_of_proc(cgroup_root: &Path, proc_cgroup: &str) -> (String, PathBuf) { + let rel = proc_cgroup.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("").trim().trim_start_matches('/').to_owned(); + let dir = if rel.is_empty() { cgroup_root.to_path_buf() } else { cgroup_root.join(&rel) }; + (rel, dir) +} + +/// Moves a child started with clone(2) into `cgroup`, then lets it go on. +/// `init_pid`: the container's init, whose cgroup is used when the +/// container's own cgroup takes no processes (Docker in Docker, BuildKit +/// move theirs into sub-cgroups), as runc does. +fn move_child(cgroup: &Path, cgroup_root: &Path, pid: libc::pid_t, init_pid: libc::pid_t, go: &OwnedFd) -> io::Result<()> { + if let Err(e) = fs::write(cgroup.join("cgroup.procs"), pid.to_string()) { + if e.kind() != io::ErrorKind::ResourceBusy { + return Err(e); + } + let (rel, dir) = proc_cgroup(cgroup_root, init_pid); + fs::write(dir.join("cgroup.procs"), pid.to_string()).map_err(|e| io::Error::new(e.kind(), format!("joining cgroup {rel}: {e}")))?; + } + // SAFETY: one byte to a pipe we own: "you are in your cgroup". + if unsafe { libc::write(go.as_raw_fd(), b"g".as_ptr().cast(), 1) } != 1 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + /// Unmounts a container and, for `--rm`, deletes its writable layer. /// Runs after the exit has been reported, off the critical path. Execs have /// nothing to undo. @@ -992,11 +1298,12 @@ pub fn oom_killed(p: &Process) -> bool { /// deletes them (see `net::retire`). pub fn teardown(p: &Process, netns_shared: bool) { if netns_shared { - for v in &p.veths { + for (_, v) in &p.veths { let _ = net::detach(v); } } else { - net::retire(&p.veths); + let host_veths: Vec = p.veths.iter().map(|(_, v)| v.clone()).collect(); + net::retire(&host_veths); } if let Some(t) = &p.teardown { undo_now(t, t.remove); @@ -1029,6 +1336,13 @@ fn undo_now(t: &Teardown, remove_files: bool) { let _ = fs::remove_dir_all(PathBuf::from("/run/kiri").join(id)); } remove_cgroup(&t.cgroup); + if t.cgroup.exists() { + kill_cgroup(&t.cgroup); + remove_cgroup(&t.cgroup); + } + for path in &t.loop_mounts { + super::volmount::release_loop(path); + } if remove_files { super::roots::remove(&t.base); } @@ -1091,15 +1405,22 @@ pub fn sweep(paths: &Paths, cgroup: &std::path::Path) { remove_cgroup(&cg); } } - // Host-side veths are kv<9 characters of the id><4 hex digits>. + // Host-side veths are kv<9 characters of the id><4 hex digits> or kx<9>. let Ok(links) = fs::read_dir("/sys/class/net") else { return }; for link in links.flatten() { let Ok(name) = link.file_name().into_string() else { continue }; - let ours = name.strip_prefix("kv").and_then(|rest| rest.get(..9)).is_some_and(|p| ids.iter().any(|id| id.starts_with(p))); + let ours = name + .strip_prefix("kv") + .or_else(|| name.strip_prefix("kx")) + .and_then(|rest| rest.get(..9)) + .is_some_and(|p| ids.iter().any(|id| id.starts_with(p))); if ours { let _ = net::detach(&name); } } + // Detach any loopback ext4 image mounted for `kiri-k8s` on a ZFS host so + // the filesystem flushes cleanly and no orphan loop mount remains. + super::volmount::release_k8s_ext4_if_mounted(); } /// Kills every process in a cgroup and below it, and waits (briefly) until @@ -1206,8 +1527,11 @@ fn prepare(argv: StrList<'_>, env: StrList<'_>, cwd: &str, user: &str, hostname: nodev_root: false, shm_size: 64 << 20, init: flags & run_flags::INIT != 0, + cgroupns_host: false, + timer_slack_ns: None, host: HostApplied::default(), root_ready: None, + cgroup_ready: None, }) } @@ -1246,18 +1570,18 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8; } } } - // On a Linux host there is no loopback redirect; host.docker.internal - // points at the bridge gateway, like Docker's host-gateway, so it reaches - // host services on 0.0.0.0 but not ones bound only to 127.0.0.1. - // A host-network container is on the host already, loopback included, - // so there the name is the loopback address. + // On a plain Linux host there is no loopback redirect; host.docker.internal + // points at the bridge gateway (or 127.0.0.1 for `--network host`). + // On Windows (WSL 2) when `kiri hostrelay` is active (`192.168.65.254` on + // `lo`), host.docker.internal / host.kiri.internal / host-gateway point at + // `192.168.65.254` for all networks (default bridge, user networks, and + // `--network host`), matching Docker Desktop. let host_addr = net::ip_str(net::HOST_ADDR); let host_net = spec.flags & run_flags::NET_HOST != 0; - let gateway = if host_net { "127.0.0.1".to_owned() } else { net::ip_str(spec.net.gateway) }; - let map_host = super::transport::is_host_process() && (host_net || spec.net.gateway != [0; 4]); + let mapped = host_etc_target(super::transport::is_host_process(), net::wsl_host_relay_active(), host_net, spec.net.gateway); for line in spec.net.extra_hosts.iter() { - if map_host { - hosts.push_str(&line.replace(&host_addr, &gateway)); + if let Some(target) = mapped.as_deref() { + hosts.push_str(&line.replace(&host_addr, target)); } else { hosts.push_str(line); } @@ -1274,6 +1598,25 @@ fn write_etc_files(spec: &RunSpec<'_>, base: &std::path::Path, upstream: &[[u8; Ok(out) } +/// Target IP replacing `net::HOST_ADDR` in container `/etc/hosts` lines. +/// Returns `None` in the macOS VM (keep `198.19.248.254`) and for `--network none` +/// on a plain Linux host. +fn host_etc_target(host_process: bool, wsl_relay_active: bool, host_net: bool, gateway: [u8; 4]) -> Option { + if !host_process { + return None; + } + if wsl_relay_active { + return Some(net::ip_str(net::WSL_HOST_ADDR)); + } + if host_net { + Some("127.0.0.1".to_owned()) + } else if gateway != [0; 4] { + Some(net::ip_str(gateway)) + } else { + None + } +} + /// The container's resolv.conf. On a user-defined network the embedded DNS /// at 127.0.0.11 is the only nameserver, as with Docker (it forwards to /// `--dns` servers); elsewhere `--dns` servers replace the VM's. @@ -1288,6 +1631,58 @@ fn embedded_dns(spec: &RunSpec<'_>, upstream: &[[u8; 4]], relay: bool) -> bool { embedded_dns_if(spec, || relay || net::local_resolver(upstream)) } +/// In the VM, a `--network host` container's resolver: the agent's on the +/// default bridge's gateway, which is one of the VM's own addresses, so the +/// container reaches it. As the default bridge's containers do, its +/// lookups then go through the Mac when the Mac's resolver for the VM +/// network doesn't answer (dns.rs), where asking that resolver directly +/// would just fail. Not on a Linux host (the container runs in the host's +/// network namespace and reaches `127.0.0.53` on host loopback directly), +/// nor with `--dns`. On a fresh VM before any bridged container has +/// started, `kiri0` is brought up on demand with the default bridge's +/// gateway and prefix. None, the VM's upstream as before, when the bridge +/// can't be brought up or the agent can't listen there. +fn host_network_resolver(spec: &RunSpec<'_>, bridges: &mut net::Bridges, dns: &mut super::dns::Dns) -> Option<[u8; 4]> { + if !host_network_uses_agent(spec, dns.relay) { + return None; + } + let gateway = match net::bridge_ipv4(DEFAULT_BRIDGE) { + Some(gw) => gw, + None => { + let (gw, prefix) = host_bridge_addr(spec); + if let Err(e) = bridges.ensure(DEFAULT_BRIDGE, Some(gw), prefix, None) { + eprintln!("kiri-init: dns: cannot bring up {DEFAULT_BRIDGE} for host-network DNS: {e}"); + return None; + } + gw + } + }; + dns.serve_or_warn(DEFAULT_BRIDGE, gateway).then_some(gateway) +} + +/// The default bridge, where the agent's resolver answers on the gateway. +const DEFAULT_BRIDGE: &str = "kiri0"; +const DEFAULT_BRIDGE_GATEWAY: [u8; 4] = [172, 17, 0, 1]; +const DEFAULT_BRIDGE_PREFIX: u8 = 16; + +/// Gateway and prefix for bringing up `DEFAULT_BRIDGE` when a `--network host` +/// container starts before any bridged one: what the daemon sent on `spec.net` +/// when present, falling back to Docker's default 172.17.0.1/16. +fn host_bridge_addr(spec: &RunSpec<'_>) -> ([u8; 4], u8) { + if spec.net.gateway == [0; 4] { + (DEFAULT_BRIDGE_GATEWAY, DEFAULT_BRIDGE_PREFIX) + } else { + let prefix = if spec.net.prefix == 0 { DEFAULT_BRIDGE_PREFIX } else { spec.net.prefix }; + (spec.net.gateway, prefix) + } +} + +/// Whether a container's lookups go to the agent's resolver on the default +/// bridge because it shares the VM's own network (see `host_network_resolver`). +fn host_network_uses_agent(spec: &RunSpec<'_>, relay: bool) -> bool { + relay && spec.flags & run_flags::NET_HOST != 0 && net_opts::values(spec.net.opts, net_opts::NAMESERVER).next().is_none() +} + /// `embedded_dns`, with `through_agent` saying whether the default bridge's /// lookups go through the agent (asked only when it matters). fn embedded_dns_if(spec: &RunSpec<'_>, through_agent: impl FnOnce() -> bool) -> bool { @@ -1351,12 +1746,17 @@ fn resolv_conf(spec: &RunSpec<'_>, upstream: &[[u8; 4]], embedded: Option<[u8; 4 for d in servers { resolv.push_str(&format!("nameserver {d}\n")); } - } else if upstream.is_empty() { - // The VM has no lease yet; a public resolver beats none. - resolv.push_str("nameserver 1.1.1.1\n"); } else { - for d in upstream { + let host_net = spec.flags & run_flags::NET_HOST != 0; + let mut wrote = false; + for d in upstream.iter().filter(|d| host_net || d[0] != 127) { resolv.push_str(&format!("nameserver {}\n", net::ip_str(*d))); + wrote = true; + } + if !wrote { + // The VM has no lease yet, or only a loopback stub remained + // without an agent listener; a public resolver beats none. + resolv.push_str("nameserver 1.1.1.1\n"); } } // `--dns-search .` means no search domains. @@ -1404,7 +1804,7 @@ pub(super) fn use_embedded_dns(id: &str, is_kiri: impl Fn([u8; 4]) -> bool) -> i } /// One mount, resolved before clone. -struct Mount { +pub(super) struct Mount { /// A guest path, or None for a tmpfs. source: Option, /// Relative to the container root (the child mounts before pivot_root). @@ -1418,6 +1818,18 @@ struct Mount { tmpfs_opts: Option, /// tmpfs mount flags (`noexec`, `nosuid`, `nodev`, `ro`). tmpfs_flags: libc::c_ulong, + /// Loopback ext4 volume mount acquired for this container (released on stop). + loop_mount: Option, +} + +impl Mount { + pub(super) fn is_tmpfs(&self) -> bool { + self.tmpfs_opts.is_some() + } + + pub(super) fn is_copy_up(&self) -> bool { + self.copy_up + } } /// `source\ttarget\tflags` entries. Flags: `ro`, `create` (make the source @@ -1425,52 +1837,101 @@ struct Mount { /// flags (`noexec`, `exec`, `nosuid`, …; later ones win). A volume with /// driver options adds `\ttype\tdevice\tflags(hex)\tdata`, and is mounted /// at its source first. -fn parse_mounts(list: StrList<'_>) -> io::Result> { +pub(super) fn parse_mounts(list: StrList<'_>) -> io::Result> { let mut out = Vec::with_capacity(list.len()); - for m in list.iter() { - let bad = || io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}")); - // Three fields: source, target, flags. Seven: the same, then a - // volume's driver options (`type`, `device`, flags, data). Any other - // count is a separator inside a field — a target alone comes from an - // image's VOLUME line — and is refused here as well as at the host. - let f: Vec<&str> = m.split('\t').collect(); - if f.len() != 3 && f.len() != 7 { - return Err(bad()); - } - let (src, given_target, words) = (f[0], f[1], f[2]); - let flags: Vec<&str> = words.split(',').filter(|f| !f.is_empty()).collect(); - if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") { - return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}"))); - } - let rel = given_target.trim_start_matches('/'); - let target = CString::new(if rel.is_empty() { "." } else { rel })?; - let ro = flags.contains(&"ro"); - if flags.contains(&"tmpfs") { - let opts: Vec<&str> = flags.iter().copied().filter(|f| f.contains('=')).collect(); - let opts = if opts.is_empty() { "mode=1777".to_owned() } else { opts.join(",") }; - let tmpfs_flags = tmpfs_flags(&flags); - let ro = tmpfs_flags & libc::MS_RDONLY != 0; - out.push(Mount { source: None, target, ro, dir: true, copy_up: false, tmpfs_opts: Some(CString::new(opts)?), tmpfs_flags }); - continue; + let release_acquired = |mounts: &[Mount]| { + for m in mounts { + if let Some(path) = &m.loop_mount { + super::volmount::release_loop(path); + } } - // A missing source becomes a directory, as Docker does; one that is - // there already (a file such as /etc/hostname, too) is used as it is. - if flags.contains(&"create") && fs::symlink_metadata(src).is_err() { - fs::create_dir_all(src)?; - } - if f.len() == 7 && !f[3].is_empty() { - super::volmount::ensure(src, f[3], f[4], f[5], f[6])?; - } - let meta = fs::metadata(src).map_err(|e| io::Error::new(e.kind(), format!("mount source {src}: {e}")))?; - out.push(Mount { - source: Some(sys::cstr(src)?), - target, - ro, - dir: meta.is_dir(), - copy_up: flags.contains(&"copyup"), - tmpfs_opts: None, - tmpfs_flags: 0, - }); + }; + let parsed = (|| -> io::Result<()> { + for m in list.iter() { + let bad = || io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}")); + // Three fields: source, target, flags. Seven: the same, then a + // volume's driver options (`type`, `device`, flags, data). Any other + // count is a separator inside a field — a target alone comes from an + // image's VOLUME line — and is refused here as well as at the host. + let f: Vec<&str> = m.split('\t').collect(); + if f.len() != 3 && f.len() != 7 { + return Err(bad()); + } + let (src, given_target, words) = (f[0], f[1], f[2]); + let flags: Vec<&str> = words.split(',').filter(|f| !f.is_empty()).collect(); + if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}"))); + } + let rel = given_target.trim_start_matches('/'); + let target = CString::new(if rel.is_empty() { "." } else { rel })?; + let ro = flags.contains(&"ro"); + if flags.contains(&"tmpfs") { + let opts: Vec<&str> = flags.iter().copied().filter(|f| f.contains('=')).collect(); + let opts = if opts.is_empty() { "mode=1777".to_owned() } else { opts.join(",") }; + let tmpfs_flags = tmpfs_flags(&flags); + let ro = tmpfs_flags & libc::MS_RDONLY != 0; + out.push(Mount { source: None, target, ro, dir: true, copy_up: false, tmpfs_opts: Some(CString::new(opts)?), tmpfs_flags, loop_mount: None }); + continue; + } + // A missing source becomes a directory, as Docker does; one that is + // there already (a file such as /etc/hostname, too) is used as it is. + // Never create a directory at /etc/localtime or /etc/timezone (#938). + let norm = lexical_normalize(Path::new(src)); + if norm == Path::new("/etc/localtime") { + if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir()) + || (flags.contains(&"create") && fs::metadata(src).is_err()) + { + super::localtime::ensure_localtime()?; + } + } else if norm == Path::new("/etc/timezone") { + if fs::symlink_metadata(src).is_ok_and(|m| m.file_type().is_dir()) + || (flags.contains(&"create") && fs::metadata(src).is_err()) + { + super::localtime::ensure_timezone()?; + } + } else if flags.contains(&"create") && fs::symlink_metadata(src).is_err() { + fs::create_dir_all(src)?; + } + let mut loop_mount = None; + if f.len() == 7 && !f[3].is_empty() { + super::volmount::ensure(src, f[3], f[4], f[5], f[6])?; + } else if super::volmount::ensure_k8s_ext4(src)? { + loop_mount = Some(src.to_owned()); + } + let meta = match fs::metadata(src) { + Ok(meta) => meta, + Err(e) => { + if let Some(path) = &loop_mount { + super::volmount::release_loop(path); + } + return Err(io::Error::new(e.kind(), format!("mount source {src}: {e}"))); + } + }; + let source = match sys::cstr(src) { + Ok(s) => s, + Err(e) => { + if let Some(path) = &loop_mount { + super::volmount::release_loop(path); + } + return Err(e); + } + }; + out.push(Mount { + source: Some(source), + target, + ro, + dir: meta.is_dir(), + copy_up: flags.contains(&"copyup"), + tmpfs_opts: None, + tmpfs_flags: 0, + loop_mount, + }); + } + Ok(()) + })(); + if let Err(e) = parsed { + release_acquired(&out); + return Err(e); } // 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` @@ -1487,7 +1948,7 @@ fn depth(target: &CStr) -> usize { /// 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 { +pub(super) fn tmpfs_flags(words: &[&str]) -> libc::c_ulong { let mut f = 0; for w in words { match *w { @@ -1507,17 +1968,264 @@ fn tmpfs_flags(words: &[&str]) -> libc::c_ulong { f } +const CGROUP_RO_ATTRS: u64 = sys::MOUNT_ATTR_RDONLY | sys::MOUNT_ATTR_NOSUID | sys::MOUNT_ATTR_NODEV | sys::MOUNT_ATTR_NOEXEC; +const CGROUP_RO_FLAGS: libc::c_ulong = libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC; + +/// Normalizes `path` lexically by collapsing `//`, `.`, and `..`. +fn lexical_normalize(path: &Path) -> PathBuf { + use std::path::Component; + let mut parts: Vec> = Vec::new(); + let mut is_abs = false; + for c in path.components() { + match c { + Component::RootDir => { + is_abs = true; + parts.clear(); + } + Component::CurDir => {} + Component::ParentDir => { + if matches!(parts.last(), Some(Component::Normal(_))) { + parts.pop(); + } else if !is_abs { + parts.push(c); + } + } + Component::Normal(_) | Component::Prefix(_) => parts.push(c), + } + } + let mut out = PathBuf::new(); + if is_abs { + out.push("/"); + } + for p in parts { + out.push(p.as_os_str()); + } + out +} + +/// Resolves symlinks via `fs::canonicalize` when `path` exists, falling back +/// to lexical normalization so `.`, `..`, and `//` are still collapsed. +fn canonical_path(path: &Path) -> PathBuf { + fs::canonicalize(path).unwrap_or_else(|_| lexical_normalize(path)) +} + +/// Normalizes a container-relative target path (stripping leading `/`, `.`, and +/// collapsing `//` and `..` within the container root). +fn normalize_rel_target(target: &Path) -> PathBuf { + use std::path::Component; + let mut out = PathBuf::new(); + for c in target.components() { + match c { + Component::RootDir | Component::CurDir | Component::Prefix(_) => {} + Component::ParentDir => { + out.pop(); + } + Component::Normal(n) => out.push(n), + } + } + out +} + +/// Pure path check for whether `(src, target)` is a self-bind of +/// `/sys/fs/cgroup` onto `/sys/fs/cgroup`. +fn is_cgroup_self_bind_paths(src: &Path, target: &Path) -> bool { + canonical_path(src) == Path::new("/sys/fs/cgroup") && normalize_rel_target(target) == Path::new("sys/fs/cgroup") +} + +/// Whether `src` and `target` (relative to `root`) are a bind of +/// `/sys/fs/cgroup` onto `/sys/fs/cgroup`, including symlinks on `src` or +/// inside `root`. `mount_container_filesystems` has already mounted `cgroup2` +/// there, rooted at the container's cgroup namespace (the host's for +/// `--cgroupns host`, the container's own cgroup otherwise) and read-only +/// unless `--privileged`. +fn is_cgroup_self_bind(root: BorrowedFd<'_>, src: &Path, target: &Path) -> bool { + if canonical_path(src) != Path::new("/sys/fs/cgroup") { + return false; + } + if normalize_rel_target(target) == Path::new("sys/fs/cgroup") { + return true; + } + matches!( + (inroot::open(root, target, Last::Exists), inroot::open(root, Path::new("sys/fs/cgroup"), Last::Exists)), + (Ok(at_t), Ok(at_cg)) if same_dir(&at_t, &at_cg) + ) +} + +/// Whether canonicalized `src` names the cgroup tree (v1 or v2, or a path +/// under `/sys/fs/cgroup` such as a hybrid `tmpfs`), which an unprivileged +/// container may only ever mount read-only. +fn is_cgroup_source(src: &Path) -> bool { + let real = canonical_path(src); + real.starts_with("/sys/fs/cgroup") || sys::is_cgroup(&real) || sys::is_cgroup(src) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct MountInfoEntry { + mount_point: PathBuf, + fstype: String, + options: String, +} + +fn unescape_mount_bytes(raw: &str) -> Vec { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' + && i + 3 < bytes.len() + && bytes[i + 1..i + 4].iter().all(|b| (b'0'..=b'7').contains(b)) + { + let val = ((bytes[i + 1] - b'0') << 6) | ((bytes[i + 2] - b'0') << 3) | (bytes[i + 3] - b'0'); + out.push(val); + i += 4; + } else { + out.push(bytes[i]); + i += 1; + } + } + out +} + +/// Parses `/proc/self/mountinfo` keeping only the topmost active mount for each +/// mountpoint path, ordered parents-first. +fn parse_mountinfo(mountinfo: &str) -> Vec { + use std::os::unix::ffi::OsStringExt; + let mut active = std::collections::BTreeMap::::new(); + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let mut b = before.split_whitespace(); + let (Some(_id), Some(_parent), Some(_dev), Some(_root), Some(mp), Some(mopts)) = + (b.next(), b.next(), b.next(), b.next(), b.next(), b.next()) + else { + continue; + }; + let Some(fstype) = after.split_whitespace().next() else { continue }; + let mount_point = PathBuf::from(std::ffi::OsString::from_vec(unescape_mount_bytes(mp))); + active.insert( + mount_point.clone(), + MountInfoEntry { mount_point, fstype: fstype.to_owned(), options: mopts.to_owned() }, + ); + } + active.into_values().collect() +} + +/// Active mountpoints in `mountinfo` at or beneath `target`. +fn submounts_under(mountinfo: &str, target: &Path) -> Vec { + parse_mountinfo(mountinfo) + .into_iter() + .filter(|e| e.mount_point == target || e.mount_point.starts_with(target)) + .collect() +} + +/// Active `cgroup` or `cgroup2` mountpoints in `mountinfo` at or beneath `target`. +fn cgroup_mounts_under(mountinfo: &str, target: &Path) -> Vec { + submounts_under(mountinfo, target) + .into_iter() + .filter(|e| e.fstype == "cgroup" || e.fstype == "cgroup2") + .collect() +} + +/// Translates mountinfo per-mount option words into `mount(2)` flags so locked +/// flags in a user namespace are preserved during `MS_BIND | MS_REMOUNT`. +fn mount_opts_flags(opts: &str) -> libc::c_ulong { + let mut f = 0 as libc::c_ulong; + for w in opts.split(',') { + match w { + "nosuid" => f |= libc::MS_NOSUID, + "nodev" => f |= libc::MS_NODEV, + "noexec" => f |= libc::MS_NOEXEC, + "noatime" => f |= libc::MS_NOATIME, + "nodiratime" => f |= libc::MS_NODIRATIME, + "relatime" => f |= libc::MS_RELATIME, + "strictatime" => f |= libc::MS_STRICTATIME, + _ => {} + } + } + f +} + +fn remount_single(target: &CStr, extra_flags: libc::c_ulong, mountinfo_opts: Option<&str>) -> io::Result<()> { + let mut flags = libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY | extra_flags; + if let Some(opts) = mountinfo_opts { + flags |= mount_opts_flags(opts); + } else { + // SAFETY: `statvfs` is plain zero-initialized data and `target` is NUL-terminated. + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: `target` is valid and `st` is writable. + if unsafe { libc::statvfs(target.as_ptr(), &mut st) } == 0 { + flags |= (st.f_flag & (libc::ST_NOSUID | libc::ST_NODEV | libc::ST_NOEXEC)) as libc::c_ulong; + } + } + sys::mount(c"none", target, c"none", flags, None) +} + +/// Remounts `target` and every submount beneath it read-only using +/// `mount_setattr(AT_RECURSIVE)`, falling back to `/proc/self/mountinfo` when +/// `mount_setattr` is unavailable (`ENOSYS`/seccomp) because Linux ignores +/// `MS_REC` on `MS_BIND | MS_REMOUNT`. +fn remount_ro_recursive(target: &CStr, attr_set: u64, remount_flags: libc::c_ulong) -> io::Result<()> { + if sys::mount_setattr_recursive(target, attr_set).is_ok() { + return Ok(()); + } + let target_path = Path::new(std::ffi::OsStr::from_bytes(target.to_bytes())); + let real = fs::read_link(target_path).unwrap_or_else(|_| target_path.to_path_buf()); + let mountinfo = fs::read_to_string("/proc/self/mountinfo")?; + let subs = submounts_under(&mountinfo, &real); + let mut remounted_target = false; + for entry in &subs { + if entry.mount_point == real { + remounted_target = true; + } + let mp = sys::cstr(&entry.mount_point)?; + remount_single(&mp, remount_flags, Some(&entry.options))?; + } + if !remounted_target { + remount_single(target, remount_flags, None)?; + } + Ok(()) +} + +/// Ensures any cgroup v1/v2 mount exposed at or beneath `t` after a bind mount +/// in an unprivileged container is strictly read-only (`nosuid,nodev,noexec,ro`). +fn harden_cgroup_mounts(root: BorrowedFd<'_>, t: &Path) -> io::Result<()> { + let at = inroot::open(root, t, Last::Exists)?; + let proc_path = at.proc_path(); + let proc_p = Path::new(std::ffi::OsStr::from_bytes(proc_path.to_bytes())); + if sys::is_cgroup(proc_p) { + remount_ro_recursive(&proc_path, CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)?; + } + let real = fs::read_link(proc_p)?; + let mountinfo = fs::read_to_string("/proc/self/mountinfo")?; + for entry in cgroup_mounts_under(&mountinfo, &real) { + let mp = sys::cstr(&entry.mount_point)?; + remount_ro_recursive(&mp, CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)?; + } + Ok(()) +} + /// Mounts one entry into the container (relative target, before /// 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<'_>, image: Option>, m: &Mount) -> io::Result<()> { +pub(super) fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount, privileged: bool) -> 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)?; return sys::mount(c"tmpfs", &at.proc_path(), c"tmpfs", m.tmpfs_flags, Some(opts)); } let src = m.source.as_ref().expect("bind mounts have a source"); + let src_path = Path::new(std::ffi::OsStr::from_bytes(src.to_bytes())); + if is_cgroup_self_bind(root, src_path, t) { + if !privileged || m.ro { + if let Ok(at) = inroot::open(root, Path::new("sys/fs/cgroup"), Last::Exists) { + let proc_path = at.proc_path(); + if sys::is_cgroup(Path::new(std::ffi::OsStr::from_bytes(proc_path.to_bytes()))) { + remount_ro_recursive(&proc_path, CGROUP_RO_ATTRS, CGROUP_RO_FLAGS)?; + } + } + } + return Ok(()); + } 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 { @@ -1548,7 +2256,6 @@ fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) - 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() { @@ -1557,11 +2264,20 @@ fn apply_mount(root: BorrowedFd<'_>, image: Option>, m: &Mount) - } } sys::mount(src, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?; - if m.ro { + let cgroup_src = !privileged && is_cgroup_source(src_path); + if m.ro || cgroup_src { // The descriptor is the directory under the new mount; look again // to reach the mount itself. let at = inroot::open(root, t, Last::Exists)?; - sys::mount(c"none", &at.proc_path(), c"none", libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY | libc::MS_REC, None)?; + let (attrs, flags) = if cgroup_src { + (CGROUP_RO_ATTRS, CGROUP_RO_FLAGS) + } else { + (sys::MOUNT_ATTR_RDONLY, libc::MS_RDONLY) + }; + remount_ro_recursive(&at.proc_path(), attrs, flags)?; + } + if !privileged { + harden_cgroup_mounts(root, t)?; } Ok(()) } @@ -1593,7 +2309,7 @@ fn same_dir(a: &inroot::Found, b: &inroot::Found) -> bool { /// 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 { +pub(super) fn image_tree() -> Option { 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) }; @@ -1762,6 +2478,29 @@ fn bind_file(root: BorrowedFd<'_>, src: &CStr, target: &CStr) -> io::Result<()> sys::mount(src, &at.proc_path(), c"none", libc::MS_BIND, None) } +/// Docker's `/.dockerenv`: an empty file, 0755, owned by root. Whatever the +/// image (or an earlier start) has there stays as it is: O_EXCL never +/// follows a link, so one that points out of the container is not written +/// through, and a link or directory there does not fail the start. +fn make_marker(root: BorrowedFd<'_>, readonly_rootfs: bool) -> io::Result<()> { + // SAFETY: valid directory fd and NUL-terminated name. + let fd = unsafe { libc::openat(root.as_raw_fd(), MARKER.as_ptr(), libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW | libc::O_CLOEXEC, 0o755) }; + if fd >= 0 { + // SAFETY: the descriptor opened just above, owned by nothing else; + // openat applies the process's umask, so set 0755 explicitly. + unsafe { + libc::fchmod(fd, 0o755); + libc::close(fd); + } + return Ok(()); + } + match io::Error::last_os_error() { + e if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), + e if readonly_rootfs && e.raw_os_error() == Some(libc::EROFS) => Ok(()), + e => Err(e), + } +} + /// Where the child reports a failure before it has execed: the stderr pipe, /// or the pty socket (the agent reads text there instead of a descriptor). fn report_fd(io: &ChildStdio) -> RawFd { @@ -1774,7 +2513,8 @@ fn report_fd(io: &ChildStdio) -> RawFd { /// The descriptors a container's child, right after its clone, still uses /// of those it inherited: its standard streams (or terminal socket), which /// are also where it reports a failure; the network namespace it joins; -/// the pipes it says "root ready" on and waits for its network on. Every +/// the pipes it says "root ready" on, waits for its network on, and waits +/// for its cgroup placement on. Every /// other descriptor it uses it opens itself, later (its root, the image's /// tree, its terminal). Standard input, output and error (0, 1, 2) always /// stay. Every field of `Prepared` is named, so a descriptor added to it @@ -1804,9 +2544,12 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { nodev_root: _, shm_size: _, init: _, + cgroupns_host: _, + timer_slack_ns: _, // Paths, numbers and names only. - host: HostApplied { rlimits: _, groups: _, nodes: _ }, + host: HostApplied { rlimits: _, groups: _, nodes: _, masked: _, readonly: _ }, root_ready, + cgroup_ready, } = p; let mut fds = match io { ChildStdio::Tty { sock } => vec![sock.as_raw_fd()], @@ -1819,12 +2562,15 @@ fn child_fds(p: &Prepared, io: &ChildStdio) -> Vec { fds.extend(net_join.as_ref().map(AsRawFd::as_raw_fd)); fds.extend(net_ready.as_ref().map(AsRawFd::as_raw_fd)); fds.extend(root_ready.as_ref().map(AsRawFd::as_raw_fd)); + fds.extend(cgroup_ready.as_ref().map(AsRawFd::as_raw_fd)); fds } /// Runs in the cloned child: PID 1 of the container, in its own namespaces /// and cgroup. Never returns: it execs or exits 127 with a message. -fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[(libc::c_uint, libc::c_uint)]) -> ! { +/// `fallback`: clone3 was blocked, so clone(2) made this child: it is not +/// in its cgroup yet and has no cgroup namespace of its own. +fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[(libc::c_uint, libc::c_uint)], fallback: bool) -> ! { // First of all: the clone gave this child a copy of every descriptor // the agent had open, and filling a new volume can take seconds while // the agent goes on. Held here, a network's DNS socket keeps its @@ -1839,6 +2585,22 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ let err = report_fd(io); let fail = |what: &str, e: io::Error| -> ! { child_fail(err, what, e) }; + if fallback { + // The agent moves us into the container's cgroup, then unshares a + // cgroup namespace rooted there, as clone3 with CLONE_INTO_CGROUP + // would have done before we ran anything. + if let Some(ready) = &p.cgroup_ready { + let mut b = [0u8; 1]; + // SAFETY: reading one byte into a local buffer from a pipe we own. + if unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) } != 1 { + fail("cgroup", io::Error::other("the agent could not move this container into its cgroup")); + } + } + if !p.cgroupns_host { + sys::unshare(libc::CLONE_NEWCGROUP).unwrap_or_else(|e| fail("cgroup namespace", e)); + } + } + // Mount events must not leak back into the agent's namespace. sys::remount(c"/", libc::MS_REC | libc::MS_PRIVATE).unwrap_or_else(|e| fail("make mounts private", e)); if let Some(ns) = &p.net_join { @@ -1850,11 +2612,20 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ } let root = inroot::open_root(Path::new(".")).unwrap_or_else(|e| fail("enter rootfs", e)); let root = root.as_fd(); - mount_container_filesystems(p.privileged, p.shm_size).unwrap_or_else(|e| fail("mount", e)); + mount_container_filesystems(p.privileged, p.shm_size, &p.host).unwrap_or_else(|e| fail("mount", e)); + // Taken before user mounts can cover /dev, as the source for MaskedPaths. + let null = (!p.privileged) + .then(|| p.host.masked.as_ref().filter(|m| !m.is_empty())) + .flatten() + .map(|_| dev_null().unwrap_or_else(|e| fail("masked paths", e))); super::hostopts::make_nodes(root, &p.host.nodes).unwrap_or_else(|e| fail("devices", e)); for (src, target) in &p.etc_files { bind_file(root, src, target).unwrap_or_else(|e| fail(&target.to_string_lossy(), e)); } + // SDKs use Docker's marker to detect container execution when cgroup + // namespaces hide the host's cgroup path. Made before changing user or + // making the root filesystem read-only. + make_marker(root, p.readonly_rootfs).unwrap_or_else(|e| fail("container marker", 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 }; @@ -1868,7 +2639,7 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ } } for m in &p.mounts { - 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)); + apply_mount(root, image.as_ref().map(|f| f.as_fd()), m, p.privileged).unwrap_or_else(|e| fail(&format!("mount {}", m.target.to_string_lossy()), e)); } drop(image); @@ -1887,6 +2658,8 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ // before it switches user and before the root goes read-only, so both // `-u 1000 -w /missing` and `--read-only -w /missing` start (#370). make_workdir(root, &p.cwd); + api_paths(root, p.privileged, p.host.readonly.as_deref().unwrap_or_default(), p.host.masked.as_deref().unwrap_or_default(), null.as_ref()) + .unwrap_or_else(|e| fail("masked paths", e)); if let Some(flags) = root_remount_flags(p.readonly_rootfs, p.nodev_root) { // Only the root itself: volumes, tmpfs and /dev stay as they are. sys::mount(c"none", c"/", c"none", flags, None).unwrap_or_else(|e| fail(if p.readonly_rootfs { "read-only root" } else { "nodev root" }, e)); @@ -1919,8 +2692,19 @@ fn container_child(p: &Prepared, rootfs: &CStr, io: &ChildStdio, close_first: &[ /// Runs in the cloned child of an exec: joins the container's remaining /// namespaces (the PID namespace was set before clone), then execs. -fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildStdio) -> ! { +/// `fallback`: clone3 was blocked, so it waits until the agent has moved it +/// into the container's cgroup. +fn exec_child(p: &Prepared, namespaces: &[(fs::File, libc::c_int)], io: &ChildStdio, fallback: bool) -> ! { let err = report_fd(io); + if fallback + && let Some(ready) = &p.cgroup_ready + { + let mut b = [0u8; 1]; + // SAFETY: reading one byte into a local buffer from a pipe we own. + if unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) } != 1 { + child_fail(err, "cgroup", io::Error::other("the agent could not move this exec into its cgroup")); + } + } for (fd, kind) in namespaces { sys::setns(fd.as_raw_fd(), *kind).unwrap_or_else(|e| child_fail(err, "join container", e)); } @@ -1999,7 +2783,12 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { // While still root with every capability: raising a hard limit needs // CAP_SYS_RESOURCE. - super::hostopts::set_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e)); + apply_rlimits(&p.host.rlimits).unwrap_or_else(|e| fail("ulimits", e)); + if console + && let Some(ns) = p.timer_slack_ns + { + apply_timer_slack(ns); + } for cap in 0..=LAST_CAP { if !p.privileged && p.caps & (1 << cap) == 0 { @@ -2102,6 +2891,22 @@ fn finish_child(p: &Prepared, io: &ChildStdio, console: bool) -> ! { sys::exec_fail(2, &exe, io::Error::last_os_error(), false) } +/// Applies timer slack (`ns`) to the container's PID 1 before `execve`. +/// Writing `/proc/self/timerslack_ns` updates both `timer_slack_ns` and +/// `default_timer_slack_ns` in Linux (`fs/proc/base.c`), so the slack survives +/// `execve` into `/bin/k3s` and coalesces staggered sub-100 ms tickers (#989). +fn apply_timer_slack(ns: u64) { + let _ = apply_timer_slack_to(Path::new("/proc/self/timerslack_ns"), ns); + // SAFETY: `PR_SET_TIMERSLACK` takes the slack in nanoseconds as `arg2`. + unsafe { + libc::prctl(libc::PR_SET_TIMERSLACK, ns as libc::c_ulong, 0, 0, 0); + } +} + +fn apply_timer_slack_to(path: &Path, ns: u64) -> io::Result<()> { + fs::write(path, ns.to_string()) +} + /// How the container's root is remounted once it is `/`, if at all: /// read-only for `--read-only`, and `nodev` when the device filter could not /// be attached. Without the filter, a block or character device node that an @@ -2126,7 +2931,7 @@ fn root_remount_flags(readonly: bool, nodev: bool) -> Option { /// /dev/pts, /dev/shm, /dev/mqueue and a read-only cgroup view. Relative /// paths: the current directory is the container root. A privileged /// container gets the VM's devices and writable /sys and cgroups instead. -fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<()> { +fn mount_container_filesystems(privileged: bool, shm_size: u64, host: &HostApplied) -> io::Result<()> { let nosuid_nodev_noexec = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC; let ro = if privileged { 0 } else { libc::MS_RDONLY }; for d in [c"proc", c"sys", c"dev"] { @@ -2151,22 +2956,19 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<() if privileged { copy_host_devices(Path::new("/dev"), Path::new("dev"))?; } - for (name, major, minor) in [ - (c"dev/null", 1, 3), - (c"dev/zero", 1, 5), - (c"dev/full", 1, 7), - (c"dev/random", 1, 8), - (c"dev/urandom", 1, 9), - (c"dev/tty", 5, 0), + for (host, name, major, minor) in [ + (c"/dev/null", c"dev/null", 1, 3), + (c"/dev/zero", c"dev/zero", 1, 5), + (c"/dev/full", c"dev/full", 1, 7), + (c"/dev/random", c"dev/random", 1, 8), + (c"/dev/urandom", c"dev/urandom", 1, 9), + (c"/dev/tty", c"dev/tty", 5, 0), ] { - if privileged { + if privileged && is_char_dev(name) { // Copied from the host already. continue; } - sys::mknod(name, libc::S_IFCHR | 0o666, major, minor)?; - // mknod applies the umask; every user in the container needs these. - // SAFETY: valid NUL-terminated path. - unsafe { libc::chmod(name.as_ptr(), 0o666) }; + make_or_bind_dev(host, name, major, minor)?; } // The host's /proc still, before the pivot. for (target, link) in dev_links(Path::new("/proc/kcore").exists()) { @@ -2185,12 +2987,127 @@ fn mount_container_filesystems(privileged: bool, shm_size: u64) -> io::Result<() sys::mount(c"mqueue", c"dev/mqueue", c"mqueue", nosuid_nodev_noexec, None)?; sys::mkdir(c"sys/fs/cgroup", 0o755); sys::mount(c"cgroup2", c"sys/fs/cgroup", c"cgroup2", nosuid_nodev_noexec | ro, None)?; - if !privileged { + // An API list replaces Docker's default for that half (see `api_paths`). + if !privileged && host.readonly.is_none() { harden_proc()?; } + if !privileged && host.masked.is_none() { + mask_proc(); + } Ok(()) } +/// The default `nofile` soft and hard limit the daemon sends when a run sets +/// no `--ulimit nofile=...` of its own. +const DEFAULT_NOFILE: u64 = 1_048_576; +const DEFAULT_PING_MAX: u64 = 2_147_483_647; + +/// The highest group id in the `/proc/self/gid_map` extent that maps 0, +/// clamped to `2147483647`. In the initial user namespace (`0 0 4294967295`) +/// this is `2147483647`; in a user namespace (`0 0 65536`) the kernel refuses +/// any upper bound that is not mapped (`EINVAL` on `ping_group_range`, #597). +fn ping_group_max(gid_map: &str) -> u64 { + for line in gid_map.lines() { + let mut f = line.split_whitespace(); + if let (Some("0"), Some(_outer), Some(count)) = (f.next(), f.next(), f.next()) + && let Ok(n) = count.parse::() + && n > 0 + { + return (n - 1).min(DEFAULT_PING_MAX); + } + } + DEFAULT_PING_MAX +} + +/// Caps the default `nofile` limit (`1048576:1048576`) to `rlim_max` when the +/// engine's own hard limit is lower (as in a user namespace or a nested +/// container with a `524288` ceiling, where raising past it is refused). An +/// explicit `--ulimit nofile=...` is left as given, so a lower value applies +/// and one above `rlim_max` still fails with the kernel's error. +fn cap_default_nofile(rlimits: &mut [(u32, u64, u64)], rlim_max: u64) -> bool { + let mut capped = false; + if rlim_max > 0 && rlim_max < DEFAULT_NOFILE { + for (res, soft, hard) in rlimits { + if *res == libc::RLIMIT_NOFILE as u32 && *soft == DEFAULT_NOFILE && *hard == DEFAULT_NOFILE { + *soft = rlim_max; + *hard = rlim_max; + capped = true; + } + } + } + capped +} + +/// Applies resource limits, falling back to the engine's own hard `nofile` +/// limit if the default `1048576` is refused with `EPERM` (#597). +fn apply_rlimits(rlimits: &[(u32, u64, u64)]) -> io::Result<()> { + match super::hostopts::set_rlimits(rlimits) { + Ok(()) => Ok(()), + Err(e) if e.raw_os_error() == Some(libc::EPERM) || e.kind() == io::ErrorKind::PermissionDenied => { + let mut rl = libc::rlimit { rlim_cur: 0, rlim_max: 0 }; + // SAFETY: valid writable rlimit struct. + if unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut rl) } != 0 { + return Err(e); + } + let mut capped = rlimits.to_vec(); + if !cap_default_nofile(&mut capped, rl.rlim_max) { + return Err(e); + } + super::hostopts::set_rlimits(&capped) + } + Err(e) => Err(e), + } +} + +/// Whether `path` already exists as a character device node (never following a symlink). +fn is_char_dev(path: &CStr) -> bool { + fstat_at(libc::AT_FDCWD, path, libc::AT_SYMLINK_NOFOLLOW) + .is_ok_and(|st| st.st_mode & libc::S_IFMT == libc::S_IFCHR) +} + +/// Creates a standard character device node at `target` on the container's +/// fresh `/dev` tmpfs, or, when `mknod` is refused in a user namespace +/// (`EPERM`), bind-mounts `host` onto a newly created empty file at `target`, +/// as runc does (#597). +fn make_or_bind_dev(host: &CStr, target: &CStr, major: u32, minor: u32) -> io::Result<()> { + match sys::mknod(target, libc::S_IFCHR | 0o666, major, minor) { + Ok(()) => { + // mknod applies the umask; every user in the container needs these. + // SAFETY: valid NUL-terminated path. + unsafe { libc::chmod(target.as_ptr(), 0o666) }; + Ok(()) + } + Err(e) if e.raw_os_error() == Some(libc::EPERM) || e.kind() == io::ErrorKind::PermissionDenied => { + let (host_fd, target_fd) = prepare_dev_bind(host, target)?; + let src = CString::new(format!("/proc/self/fd/{}", host_fd.as_raw_fd())).expect("no NUL"); + let dst = CString::new(format!("/proc/self/fd/{}", target_fd.as_raw_fd())).expect("no NUL"); + sys::mount(&src, &dst, c"none", libc::MS_BIND, None) + } + Err(e) => Err(e), + } +} + +/// Verifies that `host` is a real character device (not a symlink or other +/// file) and creates an empty regular mountpoint file at `target` without +/// following symlinks or overwriting an existing entry. +fn prepare_dev_bind(host: &CStr, target: &CStr) -> io::Result<(OwnedFd, OwnedFd)> { + let host_fd = open_at(libc::AT_FDCWD, host, libc::O_PATH | libc::O_NOFOLLOW)?; + let st = fstat_at(host_fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + if st.st_mode & libc::S_IFMT != libc::S_IFCHR { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("{} is not a character device", host.to_string_lossy()), + )); + } + let target_fd = open_at_mode( + libc::AT_FDCWD, + target, + libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOFOLLOW, + 0o666, + )?; + Ok((host_fd, target_fd)) +} + /// The links runc makes in a container's /dev (relative to its root): /// /dev/core only when the host has /proc/kcore, as runc checks. fn dev_links(kcore: bool) -> Vec<(&'static CStr, &'static CStr)> { @@ -2249,8 +3166,8 @@ fn copy_host_devices(from: &Path, to: &Path) -> io::Result<()> { 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 +/// Makes the dangerous parts of /proc read-only, as Docker's default +/// `readonlyPaths` does. The container is real root /// (no user namespace), and these sysctls and files are not namespaced, so /// without this a container could set `kernel.core_pattern` or /// `kernel.modprobe` and run code on the host. Paths are relative to the @@ -2268,6 +3185,11 @@ fn harden_proc() -> io::Result<()> { let _ = sys::remount(p, ro as libc::c_ulong); } } + Ok(()) +} + +/// Hides what Docker's default `maskedPaths` does, relative to the container root. +fn mask_proc() { // Hide files that leak host memory or kernel addresses, by covering them // with /dev/null (already created above). for p in [c"proc/kcore", c"proc/keys", c"proc/latency_stats", c"proc/timer_list", c"proc/timer_stats", c"proc/sched_debug", c"proc/interrupts"] { @@ -2277,9 +3199,135 @@ fn harden_proc() -> io::Result<()> { for p in [c"proc/scsi", c"proc/acpi", c"proc/asound", c"sys/firmware", c"sys/devices/virtual/powercap"] { let _ = sys::mount(c"tmpfs", p, c"tmpfs", (libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as libc::c_ulong, Some(c"size=0k")); } +} + +/// Looks up an existing `path` inside `root` without creating anything, +/// resolving symlinks and `..` against `root` so neither can leave it. +/// Returns the descriptor and whether it is a directory, or `None` when a +/// component is missing, a parent is not a directory, or the path resolves +/// to `root` itself. +fn lookup_existing(root: BorrowedFd<'_>, path: &Path) -> io::Result> { + use std::collections::VecDeque; + use std::ffi::OsString; + use std::path::Component; + + let parts = |p: &std::ffi::OsStr| -> VecDeque { + Path::new(p) + .components() + .filter_map(|c| match c { + Component::Normal(n) => Some(n.to_owned()), + Component::ParentDir => Some(OsString::from("..")), + Component::RootDir | Component::CurDir | Component::Prefix(_) => None, + }) + .collect() + }; + let root_st = fstat_at(root.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + let is_root = |st: &libc::stat| st.st_dev == root_st.st_dev && st.st_ino == root_st.st_ino; + let mut todo = parts(path.as_os_str()); + let mut dirs: Vec = vec![root.try_clone_to_owned()?]; + let mut links = 0u32; + while let Some(name) = todo.pop_front() { + if name == ".." { + if dirs.len() > 1 { + dirs.pop(); + } + continue; + } + let is_last = todo.is_empty(); + let dir = dirs.last().expect("root stays").as_raw_fd(); + let c = CString::new(name.as_os_str().as_bytes()).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "path contains NUL"))?; + let fd = match open_at(dir, &c, libc::O_PATH | libc::O_NOFOLLOW) { + Ok(fd) => fd, + Err(e) if matches!(e.raw_os_error(), Some(libc::ENOENT | libc::ENOTDIR)) => return Ok(None), + Err(e) => return Err(e), + }; + let st = fstat_at(fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + match st.st_mode & libc::S_IFMT { + libc::S_IFLNK => { + links += 1; + if links > 40 { + return Err(io::Error::from_raw_os_error(libc::ELOOP)); + } + let target = read_link_at(fd.as_raw_fd(), c"")?; + let bytes = target.as_bytes(); + if bytes.first() == Some(&b'/') { + dirs.truncate(1); + } + for comp in parts(std::ffi::OsStr::from_bytes(bytes)).into_iter().rev() { + todo.push_front(comp); + } + } + libc::S_IFDIR if !is_last => dirs.push(fd), + libc::S_IFDIR => return Ok((!is_root(&st)).then_some((fd, true))), + _ if is_last => return Ok(Some((fd, false))), + _ => return Ok(None), + } + } + let fd = dirs.pop().expect("root stays"); + let st = fstat_at(fd.as_raw_fd(), c"", libc::AT_EMPTY_PATH)?; + Ok((!is_root(&st)).then_some((fd, true))) +} + +/// The API's own `ReadonlyPaths` and `MaskedPaths`, applied after pivot_root as runc does. +fn api_paths(root: BorrowedFd<'_>, privileged: bool, readonly: &[CString], masked: &[CString], null: Option<&OwnedFd>) -> io::Result<()> { + if privileged { + return Ok(()); + } + let proc_fd = |fd: &OwnedFd| CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())).expect("no NUL"); + for p in readonly { + let path = Path::new(std::ffi::OsStr::from_bytes(p.as_bytes())); + let Some((fd, _)) = lookup_existing(root, path)? else { continue }; + let target = proc_fd(&fd); + sys::mount(&target, &target, c"none", libc::MS_BIND | libc::MS_REC, None)?; + // The first descriptor is under the new bind mount; look again to + // reach the mount itself, and keep its nosuid, nodev and noexec flags. + let Some((fd, _)) = lookup_existing(root, path)? else { continue }; + let target = proc_fd(&fd); + // SAFETY: statvfs is plain data; all-zero is a valid value. + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: valid NUL-terminated path and a writable struct. + if unsafe { libc::statvfs(target.as_ptr(), &mut st) } != 0 { + return Err(io::Error::last_os_error()); + } + let keep = st.f_flag & (libc::ST_NOSUID | libc::ST_NODEV | libc::ST_NOEXEC); + sys::remount(&target, (libc::MS_BIND | libc::MS_REMOUNT | libc::MS_RDONLY) as libc::c_ulong | keep)?; + } + for p in masked { + let null = null.ok_or_else(|| io::Error::other("no /dev/null to mask with"))?; + let path = Path::new(std::ffi::OsStr::from_bytes(p.as_bytes())); + let Some((fd, is_dir)) = lookup_existing(root, path)? else { continue }; + let target = proc_fd(&fd); + if is_dir { + sys::mount(c"tmpfs", &target, c"tmpfs", (libc::MS_RDONLY | libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as libc::c_ulong, Some(c"size=0k"))?; + } else { + let src = proc_fd(null); + sys::mount(&src, &target, c"none", libc::MS_BIND, None)?; + } + } Ok(()) } +/// The container's own /dev/null as an O_PATH descriptor, checked to be device 1:3. +fn dev_null() -> io::Result { + // SAFETY: valid NUL-terminated path; the descriptor is owned right away. + let fd = unsafe { libc::open(c"dev/null".as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: fresh descriptor nothing else owns. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + // SAFETY: stat is plain data; all-zero is a valid value. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + // SAFETY: a descriptor we own and a writable struct. + if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { + return Err(io::Error::last_os_error()); + } + if st.st_mode & libc::S_IFMT != libc::S_IFCHR || st.st_rdev != libc::makedev(1, 3) { + return Err(io::Error::other("/dev/null is not the null device")); + } + Ok(fd) +} + /// `""`, `root`, `1000`, `1000:1000`, `redis`, `redis:redis`: looked up in /// the container's /etc/passwd and /etc/group when not numeric. /// The home directory /etc/passwd gives `uid`. @@ -2646,12 +3694,12 @@ mod tests { let base = std::env::temp_dir().join(format!("kiri-plain-upper-{}", std::process::id())); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("upper")).unwrap(); - assert!(super::plain_upper(&base).unwrap(), "fresh"); + assert!(super::plain_upper(&base, true).unwrap(), "fresh"); assert!(base.join(super::PLAIN_UPPER).exists()); std::fs::write(base.join("upper/written"), b"x").unwrap(); - assert!(super::plain_upper(&base).unwrap(), "marked, then written to"); + assert!(super::plain_upper(&base, true).unwrap(), "marked, then written to"); std::fs::remove_file(base.join(super::PLAIN_UPPER)).unwrap(); - assert!(!super::plain_upper(&base).unwrap(), "written before the mark existed"); + assert!(!super::plain_upper(&base, true).unwrap(), "written before the mark existed"); assert!(!base.join(super::PLAIN_UPPER).exists(), "an old layer is never marked"); assert_eq!(super::overlay_features(true), "index=off,redirect_dir=nofollow,metacopy=off"); assert_eq!(super::overlay_features(false), "index=off"); @@ -3130,9 +4178,55 @@ mod tests { assert!(super::joined_user_network("", kiri).is_none(), "no file to speak of"); } + /// The marker is made empty where the root has none. What is there + /// already stays: a file (a restart), a directory, and a link, whose + /// target outside the root is neither made nor touched. + #[test] + fn marker_is_made_once_and_never_through_a_link() { + use std::os::fd::AsFd; + use std::os::unix::fs::MetadataExt; + let base = std::env::temp_dir().join(format!("kiri-marker-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let (plain, linked, linked_existing, dir) = (base.join("plain"), base.join("linked"), base.join("linked-existing"), base.join("dir")); + let marker = |root: &std::path::Path| root.join(super::MARKER.to_str().unwrap()); + let make = |root: &std::path::Path| super::make_marker(super::inroot::open_root(root).unwrap().as_fd(), false); + for root in [&plain, &linked, &linked_existing, &dir] { + std::fs::create_dir_all(root).unwrap(); + } + + make(&plain).unwrap(); + let meta = std::fs::symlink_metadata(marker(&plain)).unwrap(); + assert!(meta.is_file() && meta.len() == 0); + assert_eq!(meta.mode() & 0o7777, 0o755); + std::fs::write(marker(&plain), b"kept").unwrap(); + set_mode(&marker(&plain), 0o640); + make(&plain).unwrap(); + assert_eq!(std::fs::read(marker(&plain)).unwrap(), b"kept"); + assert_eq!(mode_of(&marker(&plain)), 0o640); + + std::os::unix::fs::symlink(base.join("outside"), marker(&linked)).unwrap(); + make(&linked).unwrap(); + assert!(std::fs::symlink_metadata(marker(&linked)).unwrap().file_type().is_symlink()); + assert!(!base.join("outside").exists(), "made through the link"); + + let existing = base.join("existing"); + std::fs::write(&existing, b"host").unwrap(); + set_mode(&existing, 0o600); + std::os::unix::fs::symlink(&existing, marker(&linked_existing)).unwrap(); + make(&linked_existing).unwrap(); + assert!(std::fs::symlink_metadata(marker(&linked_existing)).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(&existing).unwrap(), b"host"); + assert_eq!(mode_of(&existing), 0o600); + + std::fs::create_dir(marker(&dir)).unwrap(); + make(&dir).unwrap(); + assert!(marker(&dir).is_dir()); + 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 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, loop_mount: None }; 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(); @@ -3166,6 +4260,17 @@ mod tests { // TEST-NET-3: no machine running the tests has it. assert!(!super::embedded_dns(&spec, &[[203, 0, 113, 53]], false), "a resolver elsewhere is asked directly"); assert!(!super::embedded_dns(&spec, &[], false), "no resolver: the public fallback, not the agent"); + // systemd-resolved's 127.0.0.53 stub and Tailscale's 100.100.100.100 + // live in the host's network namespace: default-bridge containers ask + // the agent at the bridge gateway (172.17.0.1), never 127.0.0.53 (#330). + for stub in [&[[127, 0, 0, 53]][..], &[[127, 0, 0, 53], [168, 63, 129, 16]][..], &[[100, 100, 100, 100]][..]] { + assert!(super::embedded_dns(&spec, stub, false), "{stub:?} goes through the agent"); + assert_eq!(super::resolv_conf(&spec, stub, Some(super::embedded_address(&spec))), "nameserver 172.17.0.1\n"); + } + // Even if no agent listener could be made, a bridged container strips + // 127/8 stubs and keeps non-loopback fallbacks or 1.1.1.1. + assert_eq!(super::resolv_conf(&spec, &[[127, 0, 0, 53], [168, 63, 129, 16]], None), "nameserver 168.63.129.16\n"); + assert_eq!(super::resolv_conf(&spec, &[[127, 0, 0, 53]], None), "nameserver 1.1.1.1\n"); } #[test] @@ -3180,7 +4285,17 @@ mod tests { let gateway = [[192, 168, 64, 1]]; spec_with(0, &[], &|s| assert!(super::embedded_dns(s, &gateway, true), "so a refused gateway can fall back to the host")); spec_with(0, &["nameserver=8.8.8.8"], &|s| assert!(!super::embedded_dns(s, &gateway, true), "--dns servers are asked directly")); - spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking keeps the VM's resolv.conf")); + spec_with(run_flags::NET_HOST, &[], &|s| assert!(!super::embedded_dns(s, &gateway, true), "host networking has no embedded DNS of its own")); + // In the VM a host-network container asks the agent on the default + // bridge's gateway, so a refused gateway resolver falls back to the + // Mac too (#732); not with --dns, nor on a Linux host (no relay). + spec_with(run_flags::NET_HOST, &[], &|s| assert!(super::host_network_uses_agent(s, true))); + spec_with(run_flags::NET_HOST, &["nameserver=8.8.8.8"], &|s| assert!(!super::host_network_uses_agent(s, true), "--dns servers are asked directly")); + spec_with(run_flags::NET_HOST, &[], &|s| { + assert!(!super::host_network_uses_agent(s, false), "a Linux host has its own resolv.conf"); + assert_eq!(super::resolv_conf(s, &[[127, 0, 0, 53]], None), "nameserver 127.0.0.53\n", "Linux --network host keeps 127.0.0.53 directly"); + }); + spec_with(0, &[], &|s| assert!(!super::host_network_uses_agent(s, true), "a bridged container has its own")); // Named by the bridge's gateway, not 127.0.0.11: builders keep it // for their steps rather than swapping in 8.8.8.8. spec_with(0, &[], &|s| assert_eq!(super::embedded_address(s), [172, 17, 0, 1])); @@ -3189,6 +4304,30 @@ mod tests { spec_with(run_flags::DNS_GATEWAY, &[], &|s| assert_eq!(super::embedded_address(s), super::super::dns::EMBEDDED)); } + #[test] + fn host_network_resolver_picks_bridge_gateway_or_default() { + let check = |gateway: [u8; 4], prefix: u8, opts: &[&str], f: &mut dyn FnMut(&kiri_proto::RunSpec<'_>)| { + let mut buf = Vec::new(); + let net = Net { bridge: "", ip: [0; 4], prefix, gateway, extra_hosts: &[], dns_names: &[], opts }; + encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", run_flags::NET_HOST, net, &[], &Limits::default(), 0, &[] as &[&str], &[]); + let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() }; + f(&spec); + }; + check([172, 18, 0, 1], 24, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 18, 0, 1], 24))); + check([0; 4], 0, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 17, 0, 1], 16), "standalone caller falls back to 172.17.0.1/16")); + check([172, 18, 0, 1], 0, &[], &mut |s| assert_eq!(super::host_bridge_addr(s), ([172, 18, 0, 1], 16), "zero prefix falls back to /16")); + + let mut bridges = super::net::Bridges::default(); + let mut dns = super::super::dns::Dns::default(); + check([172, 17, 0, 1], 16, &[], &mut |s| { + assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "no relay on a Linux host"); + }); + dns.relay = true; + check([172, 17, 0, 1], 16, &["nameserver=8.8.8.8"], &mut |s| { + assert_eq!(super::host_network_resolver(s, &mut bridges, &mut dns), None, "--dns bypasses agent resolver"); + }); + } + /// WSL 2: the host's resolver is 10.255.255.254, an address on `lo`. /// The default bridge's lookups go through the agent, which the /// container finds at the bridge's gateway, as in the VM: a loopback @@ -3341,4 +4480,381 @@ mod tests { let both = super::root_remount_flags(true, true).expect("remounted"); assert_eq!(both & (libc::MS_RDONLY | libc::MS_NODEV), libc::MS_RDONLY | libc::MS_NODEV); } + + /// `MaskedPaths` and `ReadonlyPaths` targets are looked up inside the + /// container's root without creating missing folders: links inside the + /// image work, links pointing outside or to `/` (`../..`) never leave + /// the root or cover `/` itself, and a path under a file is skipped. + #[test] + fn lookup_existing_stays_in_root_and_makes_nothing() { + use std::os::fd::{AsFd, AsRawFd}; + use std::os::unix::fs::symlink; + use std::path::Path; + let (base, root, _vol, outside) = fill_dirs("lookup-existing"); + std::fs::create_dir_all(root.join("etc")).unwrap(); + std::fs::create_dir_all(root.join("usr/lib")).unwrap(); + std::fs::create_dir_all(root.join("var")).unwrap(); + std::fs::create_dir_all(root.join("custom")).unwrap(); + std::fs::write(root.join("usr/lib/os-release"), b"alpine").unwrap(); + std::fs::write(outside.join("secret"), b"host").unwrap(); + symlink("../usr/lib/os-release", root.join("etc/os-release")).unwrap(); + symlink(outside.join("secret"), root.join("custom/out")).unwrap(); + symlink("../../../../../../outside/secret", root.join("custom/rel")).unwrap(); + symlink("../..", root.join("custom/up")).unwrap(); + symlink("/custom/loop_b", root.join("custom/loop_a")).unwrap(); + symlink("/custom/loop_a", root.join("custom/loop_b")).unwrap(); + + let r = super::inroot::open_root(&root).unwrap(); + let (fd, is_dir) = super::lookup_existing(r.as_fd(), Path::new("/etc/os-release")).unwrap().expect("in-image link"); + assert!(!is_dir); + assert_eq!(std::fs::read(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap(), b"alpine"); + let (_fd, is_dir) = super::lookup_existing(r.as_fd(), Path::new("/var")).unwrap().expect("directory"); + assert!(is_dir); + assert!(super::lookup_existing(r.as_fd(), Path::new("/nope/sub")).unwrap().is_none()); + assert!(!root.join("nope").exists(), "missing parent is not created"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/usr/lib/os-release/sub")).unwrap().is_none(), "parent is a file"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/out")).unwrap().is_none(), "absolute link stays in root"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/rel")).unwrap().is_none(), ".. stops at root"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/custom/up")).unwrap().is_none(), "root itself is not returned"); + assert!(super::lookup_existing(r.as_fd(), Path::new("/")).unwrap().is_none(), "root itself is not returned"); + assert_eq!(super::lookup_existing(r.as_fd(), Path::new("/custom/loop_a")).unwrap_err().raw_os_error(), Some(libc::ELOOP)); + let paths = [std::ffi::CString::new("/etc/os-release").unwrap()]; + assert!(super::api_paths(r.as_fd(), true, &paths, &paths, None).is_ok(), "privileged skips api_paths"); + assert!(super::api_paths(r.as_fd(), false, &[], &paths, None).is_err(), "unprivileged applies masked paths"); + let _ = std::fs::remove_dir_all(&base); + } + + /// When clone3 is blocked (#529), `move_child` writes the child's PID to + /// `cgroup.procs` and signals `cgroup_go`; when a container's root cgroup + /// refuses processes (`EBUSY`), `cgroup_of_proc` resolves the container + /// init's cgroup under `paths.cgroup_root`, including hybrid trees (#277). + #[test] + fn move_child_places_fallback_child_and_resolves_hybrid_init_cgroup() { + use std::os::fd::AsRawFd; + use std::path::Path; + let dir = std::env::temp_dir().join(format!("kiri-move-child-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("cgroup.procs"), b"").unwrap(); + let (ready, go) = super::sys::pipe().unwrap(); + super::move_child(&dir, &dir, 4242, 1, &go).unwrap(); + assert_eq!(std::fs::read_to_string(dir.join("cgroup.procs")).unwrap(), "4242"); + let mut b = [0u8; 1]; + // SAFETY: reading the byte move_child just wrote to the pipe. + assert_eq!(unsafe { libc::read(ready.as_raw_fd(), b.as_mut_ptr().cast(), 1) }, 1); + assert_eq!(&b, b"g"); + let _ = std::fs::remove_dir_all(&dir); + + let unified = Path::new("/sys/fs/cgroup"); + assert_eq!( + super::cgroup_of_proc(unified, "0::/kiri/c1/init\n"), + ("kiri/c1/init".to_owned(), unified.join("kiri/c1/init")) + ); + let hybrid = Path::new("/sys/fs/cgroup/unified"); + assert_eq!( + super::cgroup_of_proc(hybrid, "2:devices:/\n1:name=systemd:/\n0::/kiri/c1/sub\n"), + ("kiri/c1/sub".to_owned(), hybrid.join("kiri/c1/sub")) + ); + assert_eq!( + super::cgroup_of_proc(hybrid, "1:name=systemd:/\n0::/\n"), + (String::new(), hybrid.to_path_buf()) + ); + } + + /// In a user namespace or nested container whose hard `nofile` limit is + /// below the default `1048576` (#597), only the default `nofile` entry is + /// clamped to `rlim_max`; explicit `--ulimit nofile=...` values and other + /// resources stay untouched. + #[test] + fn cap_default_nofile_clamps_only_the_default_nofile_limit() { + let nofile = libc::RLIMIT_NOFILE as u32; + let nproc = libc::RLIMIT_NPROC as u32; + let mut lims = vec![(nproc, 100, 200), (nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]; + assert!(super::cap_default_nofile(&mut lims, 524_288)); + assert_eq!(lims, [(nproc, 100, 200), (nofile, 524_288, 524_288)]); + + let mut high_host = vec![(nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]; + assert!(!super::cap_default_nofile(&mut high_host, super::DEFAULT_NOFILE)); + assert!(!super::cap_default_nofile(&mut high_host, 2_097_152)); + assert!(!super::cap_default_nofile(&mut high_host, 0)); + assert_eq!(high_host, [(nofile, super::DEFAULT_NOFILE, super::DEFAULT_NOFILE)]); + + let mut explicit = vec![(nofile, 65_536, 65_536), (nofile, 600_000, 600_000), (nofile, 65_536, super::DEFAULT_NOFILE)]; + assert!(!super::cap_default_nofile(&mut explicit, 524_288)); + assert_eq!( + explicit, + [(nofile, 65_536, 65_536), (nofile, 600_000, 600_000), (nofile, 65_536, super::DEFAULT_NOFILE)] + ); + assert_eq!(super::ping_group_max(" 0 0 4294967295\n"), super::DEFAULT_PING_MAX); + assert_eq!(super::ping_group_max(" 0 0 65536\n"), 65_535); + assert_eq!(super::ping_group_max(" 0 1000 1\n 1 100000 65536\n"), 0); + assert_eq!(super::ping_group_max(""), super::DEFAULT_PING_MAX); + } + + /// When `mknod` is refused in a user namespace (#597), `prepare_dev_bind` + /// verifies the host source is a real character device (never following a + /// symlink) and creates the mountpoint file with `O_CREAT | O_EXCL | + /// O_NOFOLLOW` so a symlink or existing file at the target is refused. + #[test] + fn prepare_dev_bind_verifies_char_device_and_refuses_symlinks() { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::symlink; + + let (base, dev, _vol, outside) = fill_dirs("dev-bind"); + let cstr = |p: &std::path::Path| CString::new(p.as_os_str().as_bytes()).unwrap(); + + let target = dev.join("null"); + let (_h, _t) = super::prepare_dev_bind(c"/dev/null", &cstr(&target)).expect("fresh target with /dev/null"); + assert!(std::fs::symlink_metadata(&target).unwrap().is_file()); + assert!(super::is_char_dev(c"/dev/null")); + assert!(!super::is_char_dev(&cstr(&target))); + + // Existing file at target is refused with EEXIST. + let e = super::prepare_dev_bind(c"/dev/null", &cstr(&target)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EEXIST)); + + // Symlink at target (to an existing outside file or dangling) is refused and never followed. + let victim = outside.join("victim"); + std::fs::write(&victim, b"untouched").unwrap(); + let link_existing = dev.join("zero"); + symlink(&victim, &link_existing).unwrap(); + let e = super::prepare_dev_bind(c"/dev/null", &cstr(&link_existing)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EEXIST)); + assert_eq!(std::fs::read(&victim).unwrap(), b"untouched"); + + let gone = outside.join("gone"); + let link_dangling = dev.join("full"); + symlink(&gone, &link_dangling).unwrap(); + let e = super::prepare_dev_bind(c"/dev/null", &cstr(&link_dangling)).unwrap_err(); + assert_eq!(e.raw_os_error(), Some(libc::EEXIST)); + assert!(!gone.exists()); + + // Non-character-device host sources (regular file, directory, symlink to /dev/null) are refused before creating target. + let fake_chr = outside.join("fake"); + std::fs::write(&fake_chr, b"").unwrap(); + let link_chr = outside.join("null-link"); + symlink("/dev/null", &link_chr).unwrap(); + assert!(!super::is_char_dev(&cstr(&link_chr))); + for bad_src in [&fake_chr, &outside, &link_chr] { + let unmade = dev.join("unmade"); + let e = super::prepare_dev_bind(&cstr(bad_src), &cstr(&unmade)).unwrap_err(); + assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput); + assert!(!unmade.exists(), "target must not be created when source is invalid"); + } + + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn host_etc_target_maps_wsl_host_relay_across_all_network_modes() { + // macOS VM keeps 198.19.248.254 unchanged. + assert_eq!(super::host_etc_target(false, false, false, [172, 17, 0, 1]), None); + assert_eq!(super::host_etc_target(false, true, true, [0; 4]), None); + // Plain Linux host uses bridge gateway or 127.0.0.1 for --network host. + assert_eq!(super::host_etc_target(true, false, false, [172, 17, 0, 1]).as_deref(), Some("172.17.0.1")); + assert_eq!(super::host_etc_target(true, false, true, [0; 4]).as_deref(), Some("127.0.0.1")); + assert_eq!(super::host_etc_target(true, false, false, [0; 4]), None); + // WSL 2 with active Windows host relay resolves to 192.168.65.254 everywhere. + assert_eq!(super::host_etc_target(true, true, false, [172, 17, 0, 1]).as_deref(), Some("192.168.65.254")); + assert_eq!(super::host_etc_target(true, true, false, [172, 18, 0, 1]).as_deref(), Some("192.168.65.254")); + assert_eq!(super::host_etc_target(true, true, true, [0; 4]).as_deref(), Some("192.168.65.254")); + } + + #[test] + fn cgroup_self_bind_canonicalization_and_source_checks() { + use std::os::fd::AsFd; + use std::os::unix::fs::symlink; + use std::path::{Path, PathBuf}; + + assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup"), Path::new("sys/fs/cgroup"))); + assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup/"), Path::new("/sys/fs/cgroup/"))); + assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/./cgroup"), Path::new("sys/fs/./cgroup"))); + assert!(super::is_cgroup_self_bind_paths(Path::new("/sys/fs/x/../cgroup"), Path::new("/sys//fs/cgroup"))); + assert!(!super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup/sub"), Path::new("sys/fs/cgroup"))); + assert!(!super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup"), Path::new("sys/fs/cgroup/sub"))); + assert!(!super::is_cgroup_self_bind_paths(Path::new("/tmp/cgroup"), Path::new("sys/fs/cgroup"))); + assert!(!super::is_cgroup_self_bind_paths(Path::new("/sys/fs/cgroup"), Path::new("mnt"))); + + assert!(super::is_cgroup_source(Path::new("/sys/fs/cgroup"))); + assert!(super::is_cgroup_source(Path::new("/sys/fs/cgroup/kiri"))); + assert!(super::is_cgroup_source(Path::new("/sys/fs/./cgroup"))); + assert!(super::is_cgroup_source(Path::new("/sys/fs/cgroup/kiri/../other"))); + assert!(!super::is_cgroup_source(Path::new("/sys/fs/cgroup2"))); + assert!(!super::is_cgroup_source(Path::new("/sys"))); + assert!(!super::is_cgroup_source(Path::new("/tmp/cgroup"))); + + // Canonicalization resolves symlinks on disk and inside container root. + let base = std::env::temp_dir().join(format!("kiri-cg-canon-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let root = base.join("root"); + std::fs::create_dir_all(root.join("sys/fs/cgroup")).unwrap(); + std::fs::create_dir_all(root.join("mnt")).unwrap(); + symlink("/sys/fs/cgroup", root.join("mycg")).unwrap(); + let real_dir = base.join("real"); + std::fs::create_dir_all(&real_dir).unwrap(); + let link_dir = base.join("link"); + symlink(&real_dir, &link_dir).unwrap(); + assert_eq!(super::canonical_path(&link_dir), real_dir.canonicalize().unwrap()); + + if Path::new("/sys/fs/cgroup").exists() { + let sys_cg_link = base.join("cglink"); + symlink("/sys/fs/cgroup", &sys_cg_link).unwrap(); + assert!(super::is_cgroup_source(&sys_cg_link)); + assert!(super::is_cgroup_self_bind_paths(&sys_cg_link, Path::new("sys/fs/cgroup"))); + } + + let root_fd = super::inroot::open_root(&root).unwrap(); + if Path::new("/sys/fs/cgroup").canonicalize().is_ok_and(|p| p == Path::new("/sys/fs/cgroup")) { + assert!(super::is_cgroup_self_bind(root_fd.as_fd(), Path::new("/sys/fs/cgroup"), Path::new("mycg"))); + assert!(!super::is_cgroup_self_bind(root_fd.as_fd(), Path::new("/sys/fs/cgroup"), Path::new("mnt"))); + } + assert_eq!(super::normalize_rel_target(Path::new("/sys/fs/./cgroup/")), PathBuf::from("sys/fs/cgroup")); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn mountinfo_finds_nested_cgroup_submounts_under_parent_bind() { + use std::path::{Path, PathBuf}; + + let target = Path::new("/var/lib/kiri/containers/c1/rootfs/hostsys"); + // Pure cgroup v2 parent bind plus a sibling prefix `/hostsystemd` that must not match. + let pure_v2 = "\ +28 24 0:26 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +101 24 0:30 / /var/lib/kiri/containers/c1/rootfs/hostsys rw,relatime - sysfs sysfs rw +102 101 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +103 24 0:30 / /var/lib/kiri/containers/c1/rootfs/hostsystemd rw,relatime - sysfs sysfs rw +104 103 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsystemd/fs/cgroup rw,relatime - cgroup2 cgroup2 rw +"; + let cg_v2: Vec = super::cgroup_mounts_under(pure_v2, target).into_iter().map(|e| e.mount_point).collect(); + assert_eq!(cg_v2, vec![PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup")]); + let all_v2: Vec = super::submounts_under(pure_v2, target).into_iter().map(|e| e.mount_point).collect(); + assert_eq!( + all_v2, + vec![ + PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys"), + PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup"), + ] + ); + + // Hybrid WSL 2 parent bind: tmpfs overmounts an earlier cgroup2 at `/hostsys/fs/cgroup`, + // with `unified` (cgroup2) and v1 controllers (`memory`, `pids`) beneath it, plus an escaped space mount. + let hybrid = "\ +101 24 0:30 / /var/lib/kiri/containers/c1/rootfs/hostsys rw,relatime - sysfs sysfs rw +102 101 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup rw,relatime - cgroup2 cgroup2 rw +103 102 0:31 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755 +104 103 0:26 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +105 103 0:32 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,memory +106 103 0:33 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/pids rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,pids +107 103 0:34 / /var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/my\\040cg\\134v1 rw,noatime,nodiratime - cgroup cgroup rw +"; + let cg_hybrid: Vec = super::cgroup_mounts_under(hybrid, target).into_iter().map(|e| e.mount_point).collect(); + assert_eq!( + cg_hybrid, + vec![ + PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/memory"), + PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/my cg\\v1"), + PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/pids"), + PathBuf::from("/var/lib/kiri/containers/c1/rootfs/hostsys/fs/cgroup/unified"), + ] + ); + let all_hybrid = super::submounts_under(hybrid, target); + assert_eq!(all_hybrid.len(), 6); + assert_eq!(all_hybrid[1].fstype, "tmpfs"); + + let flags = super::mount_opts_flags("rw,nosuid,nodev,noexec,relatime,noatime,nodiratime"); + assert_eq!( + flags, + libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC | libc::MS_RELATIME | libc::MS_NOATIME | libc::MS_NODIRATIME + ); + } + + #[test] + fn hostopts_cgroupns_host_is_parsed_cleanly() { + let mut buf = Vec::new(); + let net = Net { bridge: "", ip: [0; 4], prefix: 0, gateway: [0; 4], extra_hosts: &[], dns_names: &[], opts: &[] }; + encode_run(&mut buf, "c1", &[], &["sh"], &[], "/", "", "c1", 0, net, &[], &Limits::default(), 0, &["cgroupns\thost", "timerslack\t10000000"], &[]); + let Ok(Msg::Run(spec)) = decode(&buf) else { panic!() }; + let parsed = super::super::hostopts::parse(spec.opts).unwrap(); + assert!(parsed.cgroupns_host); + assert_eq!(parsed.timer_slack_ns, Some(10_000_000)); + let mut prepared = super::prepare(spec.argv, spec.env, spec.cwd, spec.user, Some(spec.hostname), spec.flags, spec.caps).unwrap(); + assert!(!prepared.cgroupns_host); + assert_eq!(prepared.timer_slack_ns, None); + prepared.cgroupns_host = parsed.cgroupns_host; + prepared.timer_slack_ns = parsed.timer_slack_ns; + assert!(prepared.cgroupns_host); + assert_eq!(prepared.timer_slack_ns, Some(10_000_000)); + let tmp = std::env::temp_dir().join(format!("kiri-timerslack-{}", std::process::id())); + super::apply_timer_slack_to(&tmp, 10_000_000).unwrap(); + assert_eq!(std::fs::read_to_string(&tmp).unwrap(), "10000000"); + let _ = std::fs::remove_file(&tmp); + } + + #[test] + fn finish_stdio_times_out_when_tty_child_never_sends_pty_and_reaps_child() { + use std::os::fd::AsRawFd; + use std::time::{Duration, Instant}; + + // 1. Stuck child holding its socket end open: times out promptly instead of blocking forever. + let (p_sock, hold_child) = super::sys::socketpair().unwrap(); + let dup_child = hold_child.try_clone().unwrap(); + let began = Instant::now(); + let err = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: dup_child }, + Duration::from_millis(30), + ) + .unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::TimedOut, "{err}"); + assert!(began.elapsed() < Duration::from_secs(2)); + drop(hold_child); + + // 2. Child exits without sending an fd: reports premature exit. + let (p_sock, c_sock) = super::sys::socketpair().unwrap(); + let err = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: c_sock }, + Duration::from_secs(1), + ) + .unwrap_err(); + assert!(err.to_string().contains("exited before its terminal was ready"), "{err}"); + + // 3. Child sends a valid fd: returns non-blocking input + master fds. + let (p_sock, c_sock) = super::sys::socketpair().unwrap(); + let (r_pipe, _w_pipe) = super::sys::pipe().unwrap(); + super::sys::send_fd(c_sock.as_raw_fd(), r_pipe.as_raw_fd()).unwrap(); + let (stdin, stdout, stderr) = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: c_sock }, + Duration::from_secs(1), + ) + .unwrap(); + assert!(stdin.is_some() && stdout.is_some() && stderr.is_none()); + + // 4. Real forked child that pauses before sending pty: timeout + SIGKILL + waitpid leaves no zombie. + let (p_sock, c_sock) = super::sys::socketpair().unwrap(); + // SAFETY: child only calls pause() and _exit(0), both async-signal-safe. + let pid = unsafe { libc::fork() }; + assert!(pid >= 0); + if pid == 0 { + unsafe { + libc::pause(); + libc::_exit(0); + } + } + let res = super::finish_stdio_timeout( + super::ParentStdio::Tty { sock: p_sock }, + super::ChildStdio::Tty { sock: c_sock }, + Duration::from_millis(25), + ); + assert_eq!(res.unwrap_err().kind(), std::io::ErrorKind::TimedOut); + // SAFETY: killing and reaping the child we just forked. + unsafe { + assert_eq!(libc::kill(pid, libc::SIGKILL), 0); + assert_eq!(libc::waitpid(pid, std::ptr::null_mut(), 0), pid); + assert_eq!(libc::kill(pid, 0), -1); + assert_eq!(std::io::Error::last_os_error().raw_os_error(), Some(libc::ESRCH)); + } + } } diff --git a/crates/kiri-init/src/linux/copy.rs b/crates/kiri-init/src/linux/copy.rs index f96b688f8..a859da474 100644 --- a/crates/kiri-init/src/linux/copy.rs +++ b/crates/kiri-init/src/linux/copy.rs @@ -8,17 +8,19 @@ //! child asks for it over a socket pair of its own, so a copy and a start at //! the same moment share one mount (see `roots`, #227). +use std::cell::RefCell; +use std::error::Error as StdError; use std::fs; use std::io::{self, BufReader, BufWriter, Read, Write}; -use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; +use std::os::unix::ffi::OsStrExt; use std::os::unix::fs::{FileTypeExt, MetadataExt}; +use std::path::{Path, PathBuf}; -use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, copy_flags, copy_op}; - -use std::cell::RefCell; -use std::path::PathBuf; +use kiri_proto::{COPY_PORT, CopySpec, FsEntry, Msg, StrList, copy_flags, copy_op}; -use super::container::Paths; +use super::container::{self, Paths}; +use super::inroot; use super::sys; /// A copy child as the agent sees it: its end of the child's socket pair @@ -118,7 +120,7 @@ pub fn on_readable(fd: i32, paths: &Paths) -> bool { let id = lines.next().unwrap_or(""); let layers: Vec<&str> = lines.collect(); let got = match kind { - "m" => super::roots::acquire(paths, id, &layers), + "m" => super::roots::acquire(paths, id, &layers, false), "h" => super::roots::hold(paths, id), _ => Err(io::Error::new(io::ErrorKind::InvalidInput, "unknown request")), }; @@ -189,14 +191,18 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa let result = match spec.op { // These read the writable layer itself, next to the image's layers. copy_op::DIFF | copy_op::COMMIT => layer_job(&mut conn, &spec, paths), + // And this one writes it, before the container ever runs. + copy_op::UPPER => upper_job(&mut conn, &spec, running, paths, &chan), _ => { - if let Err(e) = enter(&spec, running, paths, &chan) { - return reply_error(&mut conn, &format!("container {}: {e}", spec.id)); - } + let mounts = match enter(&spec, running, paths, &chan) { + Ok(m) => m, + Err(e) => return reply_error(&mut conn, &format!("container {}: {e}", spec.id)), + }; + drop(chan); match spec.op { - copy_op::IN => copy_in(&mut conn, &spec), + copy_op::IN => copy_in(&mut conn, &spec, &mounts), copy_op::OUT | copy_op::STAT => copy_out(&mut conn, &spec), - copy_op::EXPORT => export(&mut conn), + copy_op::EXPORT => export(&mut conn, &spec), op => Err(io::Error::new(io::ErrorKind::InvalidInput, format!("unknown copy op {op}"))), } } @@ -207,9 +213,59 @@ fn job(sock: OwnedFd, chan: OwnedFd, running: &[(&str, libc::pid_t)], paths: &Pa } } -/// Makes the container's root this process's `/`. -fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result<()> { - let root = match running.iter().find(|(id, _)| *id == spec.id) { +/// A mount active in the container's root view, used by `copy_in` to refuse +/// writes into read-only mounts and to overwrite bind-mounted files in place. +#[derive(Debug, Clone, PartialEq, Eq)] +struct MountAccess { + target: PathBuf, + ro: bool, + tmpfs: bool, +} + +/// Normalizes an absolute mount target path (`"/data/"` → `"/data"`, `"/"` stays `"/"`). +fn clean_mount_target(target: &str) -> String { + let parts: Vec<&str> = target.split('/').filter(|c| !c.is_empty() && *c != ".").collect(); + format!("/{}", parts.join("/")) +} + +/// Pure parsing of `CopySpec::mounts` (no filesystem I/O): validates each line +/// and sorts parent-first, matching `container::parse_mounts`. +fn parse_mount_access(list: StrList<'_>) -> io::Result> { + let mut out = Vec::with_capacity(list.len()); + for m in list.iter() { + let f: Vec<&str> = m.split('\t').collect(); + if f.len() != 3 && f.len() != 7 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount {m:?}"))); + } + let (given_target, words) = (f[1], f[2]); + if !given_target.starts_with('/') || given_target.split('/').any(|c| c == "..") { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("bad mount target {given_target}"))); + } + let flags: Vec<&str> = words.split(',').filter(|w| !w.is_empty()).collect(); + let tmpfs = flags.contains(&"tmpfs"); + let ro = if tmpfs { container::tmpfs_flags(&flags) & libc::MS_RDONLY != 0 } else { flags.contains(&"ro") }; + out.push(MountAccess { target: PathBuf::from(clean_mount_target(given_target)), ro, tmpfs }); + } + out.sort_by_key(|m| m.target.components().count()); + Ok(out) +} + +/// Resolves each mount's target inside the container chroot so symlinks in +/// mount target paths (e.g. `/var/run/cfg` → `/run/cfg`) match canonicalized +/// destination paths. +fn resolve_mount_targets(access: &mut [MountAccess]) { + for m in access { + if let Ok(real) = fs::canonicalize(&m.target) { + m.target = real; + } + } +} + +/// Makes the container's root this process's `/`, assembling non-tmpfs volumes +/// and bind mounts in a private mount namespace when the container is not +/// running (except for `EXPORT`, which reads only the overlay rootfs). +fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result> { + match running.iter().find(|(id, _)| *id == spec.id) { // An export is the container's own filesystem, without its mounts: // the overlay the agent mounted for it. // It may have stopped since: then the root is mounted for it. @@ -220,24 +276,70 @@ fn enter(spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, ch } ask(chan, 'm', spec)?; } - paths.containers.join(spec.id).join("rootfs") + chroot_into(&paths.containers.join(spec.id).join("rootfs"))?; + Ok(Vec::new()) } - // Through /proc the root shows the container's mounts (volumes) too. - // The copy holds the container's root meanwhile, so a restart can't - // mount a second one over the same layer while it still writes. + // Through /proc the root shows the container's live mounts (including + // tmpfs). The copy holds the container's root meanwhile, so a restart + // can't mount a second one over the same layer while it still writes. Some((_, pid)) => { let _ = ask(chan, 'h', spec); - std::path::PathBuf::from(format!("/proc/{pid}/root")) + let mut access = parse_mount_access(spec.mounts)?; + chroot_into(&PathBuf::from(format!("/proc/{pid}/root")))?; + resolve_mount_targets(&mut access); + Ok(access) } None => { if spec.layers.is_empty() { return Err(io::Error::new(io::ErrorKind::NotFound, "no such container")); } ask(chan, 'm', spec)?; - paths.containers.join(spec.id).join("rootfs") + let rootfs = paths.containers.join(spec.id).join("rootfs"); + if spec.op == copy_op::EXPORT { + chroot_into(&rootfs)?; + return Ok(Vec::new()); + } + // A stopped or created container has no live tmpfs mounts. + let mut access = parse_mount_access(spec.mounts)?; + access.retain(|m| !m.tmpfs); + if !access.is_empty() { + // Assemble mounts strictly inside this short-lived child's own + // mount namespace so nothing ever leaks into the agent's. + sys::unshare(libc::CLONE_NEWNS)?; + sys::remount(c"/", libc::MS_REC | libc::MS_SLAVE)?; + let mut mounts = container::parse_mounts(spec.mounts)?; + mounts.retain(|m| !m.is_tmpfs()); + let rootfs_c = sys::cstr(&rootfs)?; + // SAFETY: valid NUL-terminated path. + unsafe { sys::check(libc::chdir(rootfs_c.as_ptr()) as _, "chdir")? }; + let root = inroot::open_root(Path::new("."))?; + let image = if mounts.iter().any(container::Mount::is_copy_up) { container::image_tree() } else { None }; + for m in &mounts { + container::apply_mount(root.as_fd(), image.as_ref().map(|f| f.as_fd()), m, false)?; + } + drop(image); + drop(root); + if spec.op == copy_op::IN && spec.flags & copy_flags::READONLY_ROOTFS != 0 { + // Defense in depth: remount only the rootfs mount read-only + // in our private namespace, leaving writable mounts rw. + sys::mount(c"none", c".", c"none", libc::MS_REMOUNT | libc::MS_BIND | libc::MS_RDONLY, None)?; + } + // SAFETY: valid NUL-terminated paths. + unsafe { + sys::check(libc::chroot(c".".as_ptr()) as _, "chroot")?; + sys::check(libc::chdir(c"/".as_ptr()) as _, "chdir")?; + } + } else { + chroot_into(&rootfs)?; + } + resolve_mount_targets(&mut access); + Ok(access) } - }; - let c = sys::cstr(&root)?; + } +} + +fn chroot_into(root: &Path) -> io::Result<()> { + let c = sys::cstr(root)?; // SAFETY: valid NUL-terminated paths. unsafe { sys::check(libc::chroot(c.as_ptr()) as _, "chroot")?; @@ -270,43 +372,143 @@ fn ask(chan: &OwnedFd, kind: char, spec: &CopySpec<'_>) -> io::Result<()> { } } +/// Refuses writes when the innermost mount containing `canonical_path` is +/// read-only, or when `canonical_path` is outside every mount and the +/// container has `--read-only`. +fn check_writable(canonical_path: &Path, mounts: &[MountAccess], readonly_rootfs: bool) -> io::Result<()> { + let innermost = mounts + .iter() + .filter(|m| canonical_path == m.target || canonical_path.starts_with(&m.target)) + .max_by_key(|m| m.target.components().count()); + match innermost { + Some(m) if m.ro => Err(io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: mounted volume is marked read-only")), + Some(_) => Ok(()), + None if readonly_rootfs => Err(io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: container rootfs is marked read-only")), + None => Ok(()), + } +} + +/// Resolves a tar entry's target path under `canonical_dest`, following +/// existing symlinks in parent components (inside the container chroot) while +/// keeping the final component unfollowed (since unpacking replaces a final +/// symlink rather than writing through it). +fn resolve_entry_target(canonical_dest: &Path, entry_path: &Path) -> PathBuf { + let mut parts: Vec<&std::ffi::OsStr> = Vec::new(); + for c in entry_path.components() { + match c { + std::path::Component::Normal(p) => parts.push(p), + std::path::Component::ParentDir => { + parts.pop(); + } + std::path::Component::CurDir | std::path::Component::RootDir | std::path::Component::Prefix(_) => {} + } + } + let Some((last, parents)) = parts.split_last() else { + return canonical_dest.to_path_buf(); + }; + let mut cur = canonical_dest.to_path_buf(); + let mut exists = true; + for part in parents { + cur.push(part); + if exists { + match fs::canonicalize(&cur) { + Ok(real) => cur = real, + Err(_) => exists = false, + } + } + } + cur.push(last); + cur +} + +fn is_erofs(e: &io::Error) -> bool { + if e.raw_os_error() == Some(libc::EROFS) { + return true; + } + let mut cur: Option<&(dyn StdError + 'static)> = e.source(); + while let Some(src) = cur { + if src.downcast_ref::().is_some_and(|ioe| ioe.raw_os_error() == Some(libc::EROFS)) { + return true; + } + cur = src.source(); + } + false +} + +fn map_erofs(e: io::Error, path: &Path, mounts: &[MountAccess], readonly_rootfs: bool) -> io::Error { + if !is_erofs(&e) { + return e; + } + match check_writable(path, mounts, readonly_rootfs) { + Err(ro) => ro, + Ok(()) => io::Error::new(io::ErrorKind::PermissionDenied, "forbidden: mounted volume is marked read-only"), + } +} + +/// Overwrites an existing bind-mounted regular file in place: `unlink(2)` on a +/// file bind mount fails with `EBUSY`, so `tar::Entry::unpack_in` cannot +/// replace it by remove-and-recreate. +fn unpack_mount_file(entry: &mut tar::Entry<'_, R>, target: &Path, owner: Option<(libc::uid_t, libc::gid_t)>) -> io::Result<()> { + let c = sys::cstr(target)?; + // SAFETY: valid NUL-terminated path; O_NOFOLLOW never follows a symlink, + // and O_NONBLOCK avoids blocking if a FIFO was swapped in. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_WRONLY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: fresh descriptor owned only here. + let mut file = fs::File::from(unsafe { OwnedFd::from_raw_fd(fd) }); + // SAFETY: plain zeroed stat filled from our own descriptor. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + sys::check(unsafe { libc::fstat(file.as_raw_fd(), &mut st) } as _, "fstat")?; + if st.st_mode & libc::S_IFMT != libc::S_IFREG { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "mount target is not a regular file")); + } + // SAFETY: valid regular-file descriptor we own. + sys::check(unsafe { libc::ftruncate(file.as_raw_fd(), 0) } as _, "ftruncate")?; + io::copy(entry, &mut file)?; + if let Some((uid, gid)) = owner { + // SAFETY: valid descriptor we own. + sys::check(unsafe { libc::fchown(file.as_raw_fd(), uid, gid) } as _, "fchown")?; + } else if let (Ok(uid), Ok(gid)) = (entry.header().uid(), entry.header().gid()) { + // SAFETY: valid descriptor we own; best-effort like tar::Archive. + unsafe { libc::fchown(file.as_raw_fd(), uid as libc::uid_t, gid as libc::gid_t) }; + } + if let Ok(mode) = entry.header().mode() { + // SAFETY: valid descriptor we own. + sys::check(unsafe { libc::fchmod(file.as_raw_fd(), (mode & 0o7777) as libc::mode_t) } as _, "fchmod")?; + } + if let Ok(mtime) = entry.header().mtime() { + let times = [ + libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }, + libc::timespec { tv_sec: mtime as _, tv_nsec: 0 }, + ]; + // SAFETY: valid descriptor and 2-element timespec array. + unsafe { libc::futimens(file.as_raw_fd(), times.as_ptr()) }; + } + Ok(()) +} + /// Unpacks the archive that follows into `spec.path`, a directory. -fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { - let dest = std::path::Path::new(spec.path); +fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>, mounts: &[MountAccess]) -> io::Result<()> { + let (path, user) = if spec.flags & copy_flags::KEEP_OWNERS != 0 { + spec.path.split_once('\0').unwrap_or((spec.path, "")) + } else { + (spec.path, "") + }; + let dest = std::path::Path::new(path); match fs::metadata(dest) { Ok(m) if m.is_dir() => {} - Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {}", spec.path))), - Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {} in container {}", spec.path, spec.id))), + Ok(_) => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("notdir: extraction point is not a directory: {path}"))), + Err(_) => return Err(io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {path} in container {}", spec.id))), } + let canonical_dest = fs::canonicalize(dest)?; + let readonly_rootfs = spec.flags & copy_flags::READONLY_ROOTFS != 0; + check_writable(&canonical_dest, mounts, readonly_rootfs)?; + let owner = if user.is_empty() { None } else { Some(resolve_copy_user_in(std::path::Path::new("/"), user)?) }; let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) }; let mut reader = BufReader::with_capacity(256 * 1024, source); - { - let mut archive = tar::Archive::new(&mut reader); - archive.set_preserve_permissions(true); - archive.set_preserve_mtime(true); - archive.set_preserve_ownerships(spec.flags & copy_flags::KEEP_OWNERS != 0); - archive.set_unpack_xattrs(false); - archive.set_overwrite(true); - for entry in archive.entries()? { - let mut entry = entry?; - if spec.flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 { - let target = dest.join(entry.path()?); - if let Ok(m) = fs::symlink_metadata(&target) { - if m.is_dir() != entry.header().entry_type().is_dir() { - return Err(io::Error::new( - io::ErrorKind::AlreadyExists, - format!("cannot overwrite {} {} with {}", if m.is_dir() { "directory" } else { "non-directory" }, target.display(), if m.is_dir() { "non-directory" } else { "directory" }), - )); - } - } - } - let path = entry.path()?.into_owned(); - // `docker cp` and the classic build's context keep a time of 0. - if entry.unpack_in(dest)? { - super::layers::keep_zero_time(dest, &path, entry.header())?; - } - } - } + unpack_in(&mut reader, dest, &canonical_dest, spec.flags, owner, mounts, readonly_rootfs)?; // The archive's trailing padding: read it so the host's writes complete. io::copy(&mut reader, &mut io::sink())?; drop(reader); @@ -315,6 +517,140 @@ fn copy_in(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { conn.write_all(&out) } +/// Moby's `applyTarCopyUserOptions` (`getUIDGID`): resolves a container's +/// non-empty `Config.User` (`user[:group]`) against its `/etc/passwd` and +/// `/etc/group` when `copyUIDGID` (`docker cp -a`) is set. +fn resolve_copy_user_in(root: &std::path::Path, user: &str) -> io::Result<(libc::uid_t, libc::gid_t)> { + let (u, g) = user.split_once(':').unwrap_or((user, "")); + let (mut uid, mut gid) = (0, 0); + if !u.is_empty() { + let passwd = fs::read_to_string(root.join("etc/passwd")).unwrap_or_default(); + if let Ok(id) = u.parse::() + && id <= i32::MAX as u32 + { + uid = id; + gid = passwd + .lines() + .find_map(|l| { + let mut f = l.split(':'); + (f.nth(2)?.parse::().ok()? == id).then(|| f.next()?.parse::().ok()).flatten() + }) + .unwrap_or(0); + } else { + (uid, gid) = passwd + .lines() + .find_map(|l| { + let mut f = l.split(':'); + if f.next()? != u { + return None; + } + Some((f.nth(1)?.parse::().ok()?, f.next()?.parse::().ok()?)) + }) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("failed to look up user {u:?} in container")))?; + } + } + if !g.is_empty() { + if let Ok(id) = g.parse::() + && id <= i32::MAX as u32 + { + gid = id; + } else { + let group = fs::read_to_string(root.join("etc/group")).unwrap_or_default(); + gid = group + .lines() + .find_map(|l| { + let mut f = l.split(':'); + if f.next()? != g { + return None; + } + f.nth(1)?.parse::().ok() + }) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("failed to look up group {g:?} in container")))?; + } + } + Ok((uid, gid)) +} + +fn unpack_in( + reader: impl Read, + dest: &std::path::Path, + canonical_dest: &std::path::Path, + flags: u32, + owner: Option<(libc::uid_t, libc::gid_t)>, + mounts: &[MountAccess], + readonly_rootfs: bool, +) -> io::Result<()> { + let mut archive = tar::Archive::new(reader); + archive.set_preserve_permissions(true); + archive.set_preserve_mtime(true); + // Moby's `defaultTarCopyOptions` preserves the archive's header UID/GID + // (`ChownOpts == nil`); when `copyUIDGID` (`docker cp -a`) is set on a + // container with a non-empty `Config.User`, `applyTarCopyUserOptions` + // sets `ChownOpts` (`owner`) to chown every unpacked entry to that user. + archive.set_preserve_ownerships(owner.is_none()); + archive.set_unpack_xattrs(false); + archive.set_overwrite(true); + for entry in archive.entries()? { + let mut entry = entry?; + let path = entry.path()?.into_owned(); + let etype = entry.header().entry_type(); + let check_path = if !etype.is_pax_global_extensions() && !etype.is_pax_local_extensions() { + let resolved = resolve_entry_target(canonical_dest, &path); + check_writable(&resolved, mounts, readonly_rootfs)?; + Some(resolved) + } else { + None + }; + if flags & copy_flags::NO_OVERWRITE_DIR_NON_DIR != 0 { + let target = dest.join(&path); + if let Ok(m) = fs::symlink_metadata(&target) + && m.is_dir() != etype.is_dir() + { + return Err(io::Error::new( + io::ErrorKind::AlreadyExists, + format!("cannot overwrite {} {} with {}", if m.is_dir() { "directory" } else { "non-directory" }, target.display(), if m.is_dir() { "non-directory" } else { "directory" }), + )); + } + } + if let Some(ref resolved) = check_path + && etype.is_file() + && mounts.iter().any(|m| m.target == *resolved) + && fs::symlink_metadata(resolved).is_ok_and(|m| m.file_type().is_file()) + { + unpack_mount_file(&mut entry, resolved, owner).map_err(|e| map_erofs(e, resolved, mounts, readonly_rootfs))?; + continue; + } + // `docker cp` and the classic build's context keep a time of 0. + let target_for_err = check_path.as_deref().unwrap_or(canonical_dest); + if entry.unpack_in(dest).map_err(|e| map_erofs(e, target_for_err, mounts, readonly_rootfs))? { + if let Some((uid, gid)) = owner + && !etype.is_pax_global_extensions() + { + let mut file_dst = dest.to_path_buf(); + for part in path.components() { + if let std::path::Component::Normal(p) = part { + file_dst.push(p); + } + } + if file_dst != dest { + let c = sys::cstr(&file_dst)?; + // SAFETY: valid NUL-terminated path inside the container chroot. + sys::check(unsafe { libc::lchown(c.as_ptr(), uid, gid) } as _, "lchown")?; + if !fs::symlink_metadata(&file_dst)?.file_type().is_symlink() + && let Ok(mode) = entry.header().mode() + && mode & 0o6000 != 0 + { + // SAFETY: valid NUL-terminated non-symlink path. + sys::check(unsafe { libc::chmod(c.as_ptr(), (mode & 0o7777) as libc::mode_t) } as _, "chmod")?; + } + } + } + super::layers::keep_zero_time(dest, &path, entry.header())?; + } + } + Ok(()) +} + /// A `copy_flags::CHUNKED` archive: chunks of `len: u32 LE | bytes`, read /// as one stream that ends at the empty chunk, with the connection still /// open for the answer. @@ -351,15 +687,105 @@ impl Read for Chunks { } } +const PACED_CHUNK: usize = 64 * 1024; + +/// A `copy_flags::PACED` writer: sends the archive in `<= 64 KiB` chunks +/// (`len: u32 LE | bytes`), waiting for a 1-byte credit ack from the host +/// before sending each chunk, then an empty chunk at the end (#874). +struct PacedWriter { + conn: S, + buf: Vec, +} + +impl PacedWriter { + fn new(conn: S) -> Self { + let mut buf = Vec::with_capacity(4 + PACED_CHUNK); + buf.resize(4, 0); + Self { conn, buf } + } + + fn flush_chunk(&mut self) -> io::Result<()> { + let payload = self.buf.len() - 4; + if payload == 0 { + return Ok(()); + } + let mut ack = [0u8; 1]; + self.conn.read_exact(&mut ack)?; + self.buf[..4].copy_from_slice(&(payload as u32).to_le_bytes()); + self.conn.write_all(&self.buf)?; + self.buf.truncate(4); + Ok(()) + } + + fn finish(mut self) -> io::Result<()> { + self.flush_chunk()?; + let mut ack = [0u8; 1]; + self.conn.read_exact(&mut ack)?; + self.conn.write_all(&0u32.to_le_bytes())?; + Ok(()) + } +} + +impl Write for PacedWriter { + fn write(&mut self, data: &[u8]) -> io::Result { + if data.is_empty() { + return Ok(0); + } + if self.buf.len() - 4 == PACED_CHUNK { + self.flush_chunk()?; + } + let room = PACED_CHUNK - (self.buf.len() - 4); + let n = data.len().min(room); + self.buf.extend_from_slice(&data[..n]); + Ok(n) + } + + fn flush(&mut self) -> io::Result<()> { + self.flush_chunk()?; + self.conn.flush() + } +} + +fn stream_tar(conn: &mut fs::File, paced: bool, build: impl FnOnce(&mut tar::Builder<&mut dyn Write>) -> io::Result<()>) -> io::Result<()> { + if paced { + let mut w = PacedWriter::new(&mut *conn); + { + let mut b = tar::Builder::new(&mut w as &mut dyn Write); + b.follow_symlinks(false); + build(&mut b)?; + b.finish()?; + } + w.finish() + } else { + let mut w = BufWriter::with_capacity(256 * 1024, &mut *conn); + { + let mut b = tar::Builder::new(&mut w as &mut dyn Write); + b.follow_symlinks(false); + build(&mut b)?; + b.finish()?; + } + w.flush() + } +} + /// Answers with the path's metadata; for `OUT` an archive of it follows. fn copy_out(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { - let path = std::path::Path::new(spec.path); + // Docker archives a path with its "." and ".." resolved by name, but + // stats it as given. + let cleaned; + let source = if spec.op == copy_op::OUT && !spec.path.is_empty() { + cleaned = archived(spec.path); + cleaned.as_str() + } else { + spec.path + }; + let path = std::path::Path::new(source); let meta = fs::symlink_metadata(path) .map_err(|_| io::Error::new(io::ErrorKind::NotFound, format!("notfound: Could not find the file {} in container {}", spec.path, spec.id)))?; let link = if meta.file_type().is_symlink() { fs::read_link(path)?.to_string_lossy().into_owned() } else { String::new() }; - let name = path.file_name().map_or_else(|| "/".to_owned(), |n| n.to_string_lossy().into_owned()); + let name = base(source); let entry = FsEntry { - name: &name, + name, mode: meta.mode(), size: meta.len(), mtime: meta.mtime(), @@ -372,20 +798,56 @@ fn copy_out(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { if spec.op == copy_op::STAT { return Ok(()); } - let mut w = BufWriter::with_capacity(256 * 1024, &mut *conn); - { - let mut b = tar::Builder::new(&mut w); - b.follow_symlinks(false); - // The root itself archives as its contents under ".". - let top = if name == "/" { "." } else { name.as_str() }; + let paced = spec.flags & copy_flags::PACED != 0; + stream_tar(conn, paced, |b| { if meta.is_dir() { - append_tree(&mut b, path, std::path::Path::new(top))?; + append_tree(b, path, std::path::Path::new(name)) } else { - append_one(&mut b, path, std::path::Path::new(top), &meta)?; + append_one(b, path, std::path::Path::new(name), &meta) + } + }) +} + +/// The last component of `path` as Docker names it: "." and ".." are kept, +/// and the root is "/". +fn base(path: &str) -> &str { + path.trim_end_matches('/').rsplit('/').next().filter(|name| !name.is_empty()).unwrap_or("/") +} + +/// The path an archive is read from: `path` with its dots resolved by name. +/// Where that names nothing, `path` as given, so that every path found +/// before is still found: the window follows a start script's relative +/// link by asking for the link's directory, "..", and the rest, and behind +/// a linked directory (/bin on many images) only the kernel finds that. +fn archived(path: &str) -> String { + let cleaned = clean(path); + if fs::symlink_metadata(&cleaned).is_ok() { cleaned } else { path.to_owned() } +} + +/// `path` from the root, with "." and ".." resolved by name. A final "." (a +/// directory's contents) and a trailing "/" (a link's directory) are kept. +fn clean(path: &str) -> String { + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." => { + parts.pop(); + } + name => parts.push(name), } - b.finish()?; } - w.flush() + let mut cleaned = format!("/{}", parts.join("/")); + if base(path) == "." { + if !cleaned.ends_with('/') { + cleaned.push('/'); + } + cleaned.push('.'); + } + if path.ends_with('/') && !cleaned.ends_with('/') { + cleaned.push('/'); + } + cleaned } /// Like `append_dir_all`, but sockets (which tar cannot hold) are skipped, @@ -432,11 +894,16 @@ fn append_one(b: &mut tar::Builder, src: &std::path::Path, name: &st if ft.is_socket() { return Ok(()); } + // A directory's contents under "./" and the root's under "/" keep those names. + let verbatim = name.as_os_str().as_bytes().starts_with(b"./") || name.has_root(); if ft.is_file() { let mut h = tar::Header::new_gnu(); h.set_metadata(meta); h.set_mode(mode_bits(meta)); let mut f = fs::File::open(src)?; + if verbatim { + return append_contents(b, &mut h, name, None, &mut f); + } return b.append_data(&mut h, name, &mut f); } if ft.is_dir() || ft.is_symlink() || ft.is_fifo() || ft.is_char_device() || ft.is_block_device() { @@ -445,18 +912,53 @@ fn append_one(b: &mut tar::Builder, src: &std::path::Path, name: &st h.set_mode(mode_bits(meta)); h.set_size(0); if ft.is_symlink() { - return b.append_link(&mut h, name, fs::read_link(src)?); + let link = fs::read_link(src)?; + if verbatim { + return append_contents(b, &mut h, name, Some(&link), io::empty()); + } + return b.append_link(&mut h, name, link); } if ft.is_char_device() || ft.is_block_device() { let rdev = meta.rdev(); h.set_device_major(libc::major(rdev))?; h.set_device_minor(libc::minor(rdev))?; } + if verbatim { + return append_contents(b, &mut h, name, None, io::empty()); + } return b.append_data(&mut h, name, io::empty()); } Ok(()) } +/// tar's path setter drops "./" and refuses a leading "/". Docker's client +/// needs "./" when it rebases a directory-contents archive into a destination +/// that does not exist, and puts the new name in front of the root's "/". +/// These paths come from append_tree's "." or "/" plus directory entry names. +fn append_contents(b: &mut tar::Builder, h: &mut tar::Header, name: &std::path::Path, link: Option<&std::path::Path>, data: impl Read) -> io::Result<()> { + fn field(b: &mut tar::Builder, slot: &mut [u8], bytes: &[u8], kind: u8) -> io::Result<()> { + if bytes.len() > slot.len() { + let mut long = tar::Header::new_gnu(); + long.set_path("././@LongLink")?; + long.set_entry_type(tar::EntryType::new(kind)); + long.set_mode(0o644); + long.set_size(bytes.len() as u64 + 1); + long.set_cksum(); + b.append(&long, bytes.chain(io::repeat(0).take(1)))?; + } + slot.fill(0); + let count = bytes.len().min(slot.len()); + slot[..count].copy_from_slice(&bytes[..count]); + Ok(()) + } + field(b, &mut h.as_old_mut().name, name.as_os_str().as_bytes(), b'L')?; + if let Some(link) = link { + field(b, &mut h.as_old_mut().linkname, link.as_os_str().as_bytes(), b'K')?; + } + h.set_cksum(); + b.append(h, data) +} + fn done(conn: &mut fs::File) -> io::Result<()> { let mut out = Vec::new(); Msg::CopyDone.encode(&mut out); @@ -465,20 +967,17 @@ fn done(conn: &mut fs::File) -> io::Result<()> { /// `docker export`: everything under `/` (the chroot), entries named /// without a leading slash, as Docker writes them. -fn export(conn: &mut fs::File) -> io::Result<()> { +fn export(conn: &mut fs::File, spec: &CopySpec<'_>) -> io::Result<()> { done(conn)?; - let mut w = BufWriter::with_capacity(256 * 1024, &mut *conn); - { - let mut b = tar::Builder::new(&mut w); - b.follow_symlinks(false); + let paced = spec.flags & copy_flags::PACED != 0; + stream_tar(conn, paced, |b| { let mut children: Vec<_> = fs::read_dir("/")?.flatten().collect(); children.sort_by_key(|e| e.file_name()); for e in children { - append_tree(&mut b, &e.path(), std::path::Path::new(&e.file_name()))?; + append_tree(b, &e.path(), std::path::Path::new(&e.file_name()))?; } - b.finish()?; - } - w.flush() + Ok(()) + }) } /// An overlay whiteout: a 0:0 character device. @@ -494,6 +993,38 @@ fn is_opaque(path: &std::path::Path) -> bool { n == 1 && v[0] == b'y' } +/// The marker as the agent made it at start: not a change the container +/// made, so Docker shows it in neither `docker diff` nor a committed layer. +/// Once the container has written to it or changed its mode or owner, it is +/// a change like any other. +fn is_marker(rel: &std::path::Path, m: &fs::Metadata) -> bool { + is_marker_attr(rel, m.file_type().is_file(), m.len(), m.mode(), m.uid(), m.gid()) +} + +fn is_marker_attr(rel: &std::path::Path, is_file: bool, len: u64, mode: u32, uid: u32, gid: u32) -> bool { + rel.as_os_str().as_encoded_bytes() == container::MARKER.to_bytes() + && is_file + && len == 0 + && mode & 0o7777 == 0o755 + && uid == 0 + && gid == 0 +} + +fn in_lower_layers(lowers: &[OwnedFd], rel: &std::path::Path) -> bool { + for l in lowers { + let Some(rel) = rel.to_str() else { continue }; + let Ok(fd) = super::fsview::open_in(l.as_raw_fd(), rel, libc::O_PATH | libc::O_NOFOLLOW) else { continue }; + // SAFETY: fstat into a zeroed stat on a descriptor we own. + let mut st: libc::stat = unsafe { std::mem::zeroed() }; + if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { + continue; + } + let whiteout = st.st_mode & libc::S_IFMT == libc::S_IFCHR && st.st_rdev == 0; + return !whiteout; + } + false +} + /// `docker diff` and `docker commit`, from the writable layer. fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Result<()> { if spec.layers.is_empty() { @@ -513,6 +1044,7 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res (fd >= 0).then(|| unsafe { OwnedFd::from_raw_fd(fd) }) }) .collect(); + let in_lower = |rel: &std::path::Path| in_lower_layers(&lowers, rel); // A running container writes its upper layer while we walk it, and could // swap a directory for a link to `/` between our look and our read // (`docker diff`, `commit --pause=false`). Inside a chroot of the layer @@ -542,6 +1074,9 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res for e in names.into_iter().rev() { let r = rel.join(e.file_name()); let Ok(m) = fs::symlink_metadata(e.path()) else { continue }; + if is_marker(&r, &m) && !in_lower(&r) { + continue; + } if m.is_dir() { stack.push(r.clone()); } @@ -551,20 +1086,6 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res entries.sort_by(|a, b| a.0.cmp(&b.0)); done(conn)?; if spec.op == copy_op::DIFF { - let in_lower = |rel: &std::path::Path| { - for l in &lowers { - let Some(rel) = rel.to_str() else { continue }; - let Ok(fd) = super::fsview::open_in(l.as_raw_fd(), rel, libc::O_PATH | libc::O_NOFOLLOW) else { continue }; - // SAFETY: fstat into a zeroed stat on a descriptor we own. - let mut st: libc::stat = unsafe { std::mem::zeroed() }; - if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 { - continue; - } - let whiteout = st.st_mode & libc::S_IFMT == libc::S_IFCHR && st.st_rdev == 0; - return !whiteout; - } - false - }; let mut w = BufWriter::new(&mut *conn); for (rel, m) in &entries { let kind = if is_whiteout(m) { @@ -606,6 +1127,114 @@ fn layer_job(conn: &mut fs::File, spec: &CopySpec<'_>, paths: &Paths) -> io::Res w.flush() } +/// `kiri import`: the writable layer a container had on the engine it came +/// from, as an OCI layer tar (see `copy_op::UPPER`), becomes its own before +/// it ever runs. Writing under the upper dir of a mounted overlay is +/// undefined behaviour to the kernel, so a running container, or one whose +/// root is mounted for a copy, is refused, as is one that has a writable +/// layer already. +fn upper_job(conn: &mut fs::File, spec: &CopySpec<'_>, running: &[(&str, libc::pid_t)], paths: &Paths, chan: &OwnedFd) -> io::Result<()> { + if spec.layers.is_empty() { + return reply_error(conn, "no such container"); + } + container::valid_id(spec.id)?; + // `h` holds a root only when it is mounted; this child exits soon and + // lets it go again. + if running.iter().any(|(id, _)| *id == spec.id) || ask(chan, 'h', spec).is_ok() { + return reply_error(conn, &format!("container {} is in use: its writable layer can only be brought in before it runs", spec.id)); + } + let base = paths.containers.join(spec.id); + if fs::read_dir(base.join("upper")).is_ok_and(|mut d| d.next().is_some()) { + return reply_error(conn, &format!("container {} already has a writable layer of its own", spec.id)); + } + let source: Box = if spec.flags & copy_flags::CHUNKED != 0 { Box::new(Chunks::new(&mut *conn)) } else { Box::new(&mut *conn) }; + import_upper(BufReader::with_capacity(256 * 1024, source), &base)?; + done(conn) +} + +/// Unpacks the layer `reader` holds into `/upper`. It is unpacked +/// beside it first and moved in whole, so a copy cut short leaves the +/// container as it was; overlayfs's own attributes are stripped, and the +/// layer is marked plain (`container::mark_plain_upper`). +fn import_upper(mut reader: impl Read, base: &Path) -> io::Result<()> { + let upper = base.join("upper"); + let staging = base.join("upper.import"); + fs::create_dir_all(base)?; + match fs::remove_dir_all(&staging) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => {} + } + fs::create_dir(&staging)?; + let unpacked = (|| -> io::Result<()> { + // The root of the container's filesystem takes this directory's + // mode and owner, as with the `upper` a first start makes. + fs::set_permissions(&staging, std::os::unix::fs::PermissionsExt::from_mode(0o755))?; + super::layers::untar(&mut reader, &staging)?; + // The archive's trailing padding, so the host's writes complete. + io::copy(&mut reader, &mut io::sink())?; + strip_overlay_xattrs(&staging)?; + // An empty `upper` an earlier copy's mount left goes first. + match fs::remove_dir(&upper) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => {} + } + fs::rename(&staging, &upper) + })(); + if let Err(e) = unpacked { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + container::mark_plain_upper(base) +} + +/// Removes overlayfs's own attributes (`trusted.overlay.*`: redirects, +/// metacopy, origin) from everything under `root`, keeping the opaque mark +/// `layers::untar` sets for `.wh..wh..opq`. An imported layer is whole +/// files and directories; an attribute an archive carried must not make +/// the mount look elsewhere for them. +fn strip_overlay_xattrs(root: &Path) -> io::Result<()> { + let mut stack = vec![root.to_path_buf()]; + while let Some(path) = stack.pop() { + let meta = fs::symlink_metadata(&path)?; + let c = sys::cstr(&path)?; + let mut names = vec![0u8; 4096]; + let n = loop { + // SAFETY: valid NUL-terminated path; fills at most `names.len()` bytes. + let n = unsafe { libc::llistxattr(c.as_ptr(), names.as_mut_ptr().cast(), names.len()) }; + if n >= 0 { + break n as usize; + } + match io::Error::last_os_error() { + e if e.raw_os_error() == Some(libc::ERANGE) && names.len() < 1 << 20 => names.resize(names.len() * 4, 0), + e if e.raw_os_error() == Some(libc::ENOTSUP) => break 0, + e => return Err(e), + } + }; + for name in names[..n].split(|b| *b == 0).filter(|name| overlay_own(name)) { + let name = std::ffi::CString::new(name).map_err(io::Error::other)?; + // SAFETY: valid NUL-terminated path and attribute name. + if unsafe { libc::lremovexattr(c.as_ptr(), name.as_ptr()) } != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::ENODATA) { + return Err(e); + } + } + } + if meta.is_dir() { + for e in fs::read_dir(&path)? { + stack.push(e?.path()); + } + } + } + Ok(()) +} + +/// Whether an extended attribute is one overlayfs reads in an upper dir, +/// other than the opaque mark. +fn overlay_own(name: &[u8]) -> bool { + name.starts_with(b"trusted.overlay.") && name != b"trusted.overlay.opaque" +} + fn reply_error(conn: &mut fs::File, msg: &str) -> io::Result<()> { let mut out = Vec::new(); Msg::Error(msg).encode(&mut out); @@ -624,6 +1253,184 @@ fn read_frame(conn: &mut impl Read, buf: &mut Vec) -> io::Result<()> { mod tests { use super::*; + #[test] + fn only_overlayfs_own_attributes_but_the_opaque_mark_are_stripped() { + assert!(overlay_own(b"trusted.overlay.redirect")); + assert!(overlay_own(b"trusted.overlay.metacopy")); + assert!(overlay_own(b"trusted.overlay.origin")); + assert!(!overlay_own(b"trusted.overlay.opaque")); + assert!(!overlay_own(b"security.capability")); + assert!(!overlay_own(b"user.overlay.redirect")); + assert!(!overlay_own(b"trusted.overlayx")); + } + + /// `kiri import` (#410): a writable layer from another engine becomes + /// the container's `upper`, whiteouts and opaque marks as overlayfs reads + /// them, owners and links kept, overlayfs's own attributes gone, marked + /// plain; one cut short leaves nothing behind. + #[test] + fn an_imported_writable_layer_becomes_the_upper_dir_whole() { + // SAFETY: a plain getter. + if unsafe { libc::geteuid() } != 0 { + eprintln!("skipped: needs root for owners, whiteouts and trusted attributes"); + return; + } + let base = std::env::temp_dir().join(format!("kiri-import-upper-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let layer = |cut: bool| { + let mut b = tar::Builder::new(Vec::new()); + let h = |kind: tar::EntryType, size: u64, mode: u32, owner: u64| { + let mut h = tar::Header::new_ustar(); + h.set_entry_type(kind); + h.set_size(size); + h.set_mode(mode); + h.set_uid(owner); + h.set_gid(owner); + h.set_mtime(1_700_000_000); + h + }; + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o750, 1000), "added/", io::empty()).unwrap(); + b.append_pax_extensions([("SCHILY.xattr.trusted.overlay.redirect", &b"/elsewhere"[..])]).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 5, 0o640, 1000), "added/file", &b"hello"[..]).unwrap(); + b.append_link(&mut h(tar::EntryType::Symlink, 0, 0o777, 0), "link", "added/file").unwrap(); + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o755, 0), "etc/", io::empty()).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 0, 0o644, 0), "etc/.wh.gone", io::empty()).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 4, 0o644, 0), "etc/motd", &b"new\n"[..]).unwrap(); + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o755, 0), "again/", io::empty()).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 0, 0o644, 0), "again/.wh..wh..opq", io::empty()).unwrap(); + let mut bytes = b.into_inner().unwrap(); + if cut { + // Inside the first file's body. + bytes.truncate(512 * 4 + 2); + } + bytes + }; + + // Cut short: an error, and neither `upper` nor its staging is left. + assert!(import_upper(&layer(true)[..], &base).is_err()); + assert!(!base.join("upper").exists() && !base.join("upper.import").exists() && !base.join(super::container::PLAIN_UPPER).exists()); + + // An empty `upper` (an earlier copy's mount made it) is taken over. + fs::create_dir_all(base.join("upper")).unwrap(); + import_upper(&layer(false)[..], &base).unwrap(); + let upper = base.join("upper"); + let meta = |p: &str| fs::symlink_metadata(upper.join(p)).unwrap(); + assert!(!base.join("upper.import").exists()); + assert!(base.join(super::container::PLAIN_UPPER).exists(), "marked plain"); + assert_eq!(meta("").mode() & 0o7777, 0o755); + let added = meta("added"); + assert_eq!((added.uid(), added.gid(), added.mode() & 0o7777, added.mtime()), (1000, 1000, 0o750, 1_700_000_000)); + let file = meta("added/file"); + assert_eq!((file.uid(), file.gid(), file.mode() & 0o7777), (1000, 1000, 0o640)); + assert_eq!(fs::read(upper.join("added/file")).unwrap(), b"hello"); + assert_eq!(fs::read_link(upper.join("link")).unwrap(), Path::new("added/file")); + assert_eq!(fs::read(upper.join("etc/motd")).unwrap(), b"new\n"); + assert!(is_whiteout(&meta("etc/gone")), "a 0:0 character device"); + assert!(!upper.join("etc/.wh.gone").exists()); + assert!(is_opaque(&upper.join("again"))); + assert!(!upper.join("again/.wh..wh..opq").exists()); + let c = sys::cstr(upper.join("added/file")).unwrap(); + // SAFETY: valid path and name; a size query. + let redirect = unsafe { libc::lgetxattr(c.as_ptr(), c"trusted.overlay.redirect".as_ptr(), std::ptr::null_mut(), 0) }; + assert!(redirect < 0, "overlayfs's own attribute stripped"); + + let _ = fs::remove_dir_all(&base); + } + + #[test] + fn contents_keep_dot_prefix_and_long_names() { + for length in [4, 98, 99, 100, 101, 255] { + let name = format!("./{}", "a".repeat(length)); + let link = "../".to_owned() + &"b".repeat(length); + let mut bytes = Vec::new(); + { + let mut archive = tar::Builder::new(&mut bytes); + let mut header = tar::Header::new_gnu(); + header.set_entry_type(tar::EntryType::Symlink); + header.set_size(0); + append_contents(&mut archive, &mut header, std::path::Path::new(&name), Some(std::path::Path::new(&link)), io::empty()).unwrap(); + archive.finish().unwrap(); + } + let mut archive = tar::Archive::new(bytes.as_slice()); + let mut entries = archive.entries().unwrap(); + let entry = entries.next().unwrap().unwrap(); + assert_eq!(entry.path_bytes().as_ref(), name.as_bytes()); + assert_eq!(entry.link_name_bytes().unwrap().as_ref(), link.as_bytes()); + assert!(entries.next().is_none()); + } + } + + #[test] + fn archived_paths_resolve_dots_by_name_and_stats_keep_them() { + for (path, cleaned, name) in [ + ("/t/dir", "/t/dir", "dir"), + ("/t/dir/", "/t/dir/", "dir"), + ("/t/dir/.", "/t/dir/.", "."), + ("/t/dir/./", "/t/dir/./", "."), + ("/t/dir//.", "/t/dir/.", "."), + ("/t/dir/sub/..", "/t/dir", "dir"), + ("/t/dir/sub/../", "/t/dir/", "dir"), + ("/t/dir/sub/../.", "/t/dir/.", "."), + ("/t/link/../dir", "/t/dir", "dir"), + ("t/dir/..", "/t", "t"), + ("../../t/dir/.", "/t/dir/.", "."), + ("/", "/", "/"), + ("//", "/", "/"), + ("/.", "/.", "."), + ("/..", "/", "/"), + ("/etc/..", "/", "/"), + ("/etc/../.", "/.", "."), + (".", "/.", "."), + ("..", "/", "/"), + ] { + assert_eq!(clean(path), cleaned, "{path}"); + assert_eq!(base(cleaned), name, "{path}"); + } + for (path, name) in [("/t/dir/sub/..", ".."), ("/t/dir/sub/../", ".."), ("/t/dir/.", "."), ("/t/dir/", "dir"), ("/", "/"), ("//", "/"), ("/..", "..")] { + assert_eq!(base(path), name, "{path}"); + } + } + + #[test] + fn a_path_only_the_kernel_finds_is_archived_as_given() { + let dir = std::env::temp_dir().join(format!("kiri-archived-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("usr/bin")).unwrap(); + fs::create_dir_all(dir.join("usr/share")).unwrap(); + fs::create_dir_all(dir.join("share")).unwrap(); + fs::write(dir.join("usr/share/start.sh"), "").unwrap(); + fs::write(dir.join("usr/share/both"), "").unwrap(); + fs::write(dir.join("share/both"), "").unwrap(); + std::os::unix::fs::symlink("usr/bin", dir.join("bin")).unwrap(); + let at = |rest: &str| format!("{}/{rest}", dir.display()); + // By name this is share/start.sh, which is not there: the kernel's stays. + assert_eq!(archived(&at("bin/../share/start.sh")), at("bin/../share/start.sh")); + // Where the path by name is there, it is the one, as in Docker. + assert_eq!(archived(&at("bin/../share/both")), at("share/both")); + assert_eq!(archived(&at("usr/bin/..")), at("usr")); + // Nothing either way: the path as given, for the error to name. + assert_eq!(archived(&at("bin/../none")), at("bin/../none")); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn root_and_contents_entries_keep_their_prefix() { + let root = std::path::Path::new("/"); + let meta = fs::symlink_metadata(root).unwrap(); + let names = ["/", "/etc", ".", "./etc", "etc"]; + let mut bytes = Vec::new(); + { + let mut archive = tar::Builder::new(&mut bytes); + for name in names { + append_one(&mut archive, root, std::path::Path::new(name), &meta).unwrap(); + } + archive.finish().unwrap(); + } + let mut archive = tar::Archive::new(bytes.as_slice()); + let got: Vec<_> = archive.entries().unwrap().map(|entry| String::from_utf8(entry.unwrap().path_bytes().into_owned()).unwrap()).collect(); + assert_eq!(got, names); + } + #[test] fn chunks_end_at_the_empty_chunk_and_leave_the_rest() { let wire = [&3u32.to_le_bytes()[..], b"abc", &2u32.to_le_bytes(), b"de", &0u32.to_le_bytes(), b"after"].concat(); @@ -640,4 +1447,310 @@ mod tests { let err = Chunks::new(&wire[..]).read_to_end(&mut Vec::new()).unwrap_err(); assert_eq!(err.kind(), io::ErrorKind::UnexpectedEof); } + + #[test] + fn unpack_in_keeps_owners_and_does_not_chown_symlink_targets() { + // SAFETY: a plain getter. + if unsafe { libc::geteuid() } != 0 { + eprintln!("skipped: needs root to keep owners"); + return; + } + let dest = std::env::temp_dir().join(format!("kiri-copy-owners-{}", std::process::id())); + let _ = fs::remove_dir_all(&dest); + fs::create_dir_all(&dest).unwrap(); + fs::write(dest.join("target"), b"stay").unwrap(); + std::os::unix::fs::symlink("target", dest.join("replaced")).unwrap(); + + let mut b = tar::Builder::new(Vec::new()); + let h = |kind: tar::EntryType, size: u64, mode: u32| { + let mut h = tar::Header::new_gnu(); + h.set_entry_type(kind); + h.set_size(size); + h.set_mode(mode); + h.set_uid(1234); + h.set_gid(1235); + h.set_mtime(1_700_000_000); + h.set_cksum(); + h + }; + b.append_data(&mut h(tar::EntryType::Directory, 0, 0o750), "dir", &[][..]).unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 3, 0o600), "dir/owned.pem", &b"key"[..]).unwrap(); + b.append_link(&mut h(tar::EntryType::Symlink, 0, 0o777), "link", "target").unwrap(); + b.append_data(&mut h(tar::EntryType::Regular, 3, 0o640), "replaced", &b"new"[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + + unpack_in(&bytes[..], &dest, &dest, 0, None, &[], false).unwrap(); + + let meta = |p: &str| fs::symlink_metadata(dest.join(p)).unwrap(); + let dir = meta("dir"); + assert_eq!((dir.uid(), dir.gid(), dir.mode() & 0o777), (1234, 1235, 0o750)); + let pem = meta("dir/owned.pem"); + assert_eq!((pem.uid(), pem.gid(), pem.mode() & 0o777), (1234, 1235, 0o600)); + assert_eq!(fs::read(dest.join("dir/owned.pem")).unwrap(), b"key"); + let link = meta("link"); + assert!(link.file_type().is_symlink()); + assert_eq!((link.uid(), link.gid()), (1234, 1235)); + let replaced = meta("replaced"); + assert!(replaced.file_type().is_file()); + assert_eq!((replaced.uid(), replaced.gid(), replaced.mode() & 0o777), (1234, 1235, 0o640)); + assert_eq!(fs::read(dest.join("replaced")).unwrap(), b"new"); + let target = meta("target"); + assert_eq!((target.uid(), target.gid()), (0, 0)); + assert_eq!(fs::read(dest.join("target")).unwrap(), b"stay"); + + unpack_in(&bytes[..], &dest, &dest, 0, Some((2375, 2376)), &[], false).unwrap(); + assert_eq!((meta("dir").uid(), meta("dir").gid()), (2375, 2376)); + assert_eq!((meta("dir/owned.pem").uid(), meta("dir/owned.pem").gid(), meta("dir/owned.pem").mode() & 0o777), (2375, 2376, 0o600)); + assert_eq!((meta("link").uid(), meta("link").gid()), (2375, 2376)); + assert_eq!((meta("target").uid(), meta("target").gid()), (0, 0)); + + let _ = fs::remove_dir_all(&dest); + } + + #[test] + fn resolve_copy_user_matches_moby_get_uid_gid() { + let root = std::env::temp_dir().join(format!("kiri-copy-user-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + fs::create_dir_all(root.join("etc")).unwrap(); + fs::write(root.join("etc/passwd"), "root:x:0:0:root:/root:/bin/sh\ntestuser:x:2375:2376::/home/testuser:/bin/sh\n").unwrap(); + fs::write(root.join("etc/group"), "root:x:0:\ntestgroup:x:2376:\n").unwrap(); + + for (spec, want) in [ + ("7777:", (7777, 0)), + (":7777", (0, 7777)), + ("2375", (2375, 2376)), + ("7777", (7777, 0)), + ("2375:2376", (2375, 2376)), + ("testuser:testgroup", (2375, 2376)), + ("testuser", (2375, 2376)), + ("testuser:7777", (2375, 7777)), + ("7777:testgroup", (7777, 2376)), + ] { + assert_eq!(resolve_copy_user_in(&root, spec).unwrap(), want, "{spec}"); + } + assert!(resolve_copy_user_in(&root, "nosuchuser").is_err()); + assert!(resolve_copy_user_in(&root, "testuser:nosuchgroup").is_err()); + + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn only_an_untouched_root_marker_is_skipped_by_diff_and_commit() { + use std::os::unix::fs::PermissionsExt; + + let p = std::path::Path::new; + assert!(is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 0)); + assert!(!is_marker_attr(p("sub/.dockerenv"), true, 0, 0o100755, 0, 0)); + assert!(!is_marker_attr(p("added"), true, 0, 0o100755, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), false, 0, 0o120755, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 2, 0o100755, 0, 0)); + // `chmod 600 /.dockerenv`, `rm && touch` (0644), or special mode bits. + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100600, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100644, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o101755, 0, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o104755, 0, 0)); + // `chown 1000:1000 /.dockerenv` (or uid-only / gid-only changes). + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 1000, 0)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 1000)); + assert!(!is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 1000, 1000)); + + let base = std::env::temp_dir().join(format!("kiri-copy-marker-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + fs::create_dir_all(base.join("sub")).unwrap(); + let meta = |rel: &str| fs::symlink_metadata(base.join(rel)).unwrap(); + + fs::write(base.join(".dockerenv"), b"").unwrap(); + fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o755)).unwrap(); + let m = meta(".dockerenv"); + assert_eq!(is_marker(p(".dockerenv"), &m), m.uid() == 0 && m.gid() == 0); + assert!(!is_marker(p("sub/.dockerenv"), &m)); + assert!(!is_marker(p("added"), &m)); + + fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o600)).unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + fs::set_permissions(base.join(".dockerenv"), fs::Permissions::from_mode(0o755)).unwrap(); + fs::write(base.join(".dockerenv"), b"hi").unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + fs::remove_file(base.join(".dockerenv")).unwrap(); + std::os::unix::fs::symlink("/outside", base.join(".dockerenv")).unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + fs::remove_file(base.join(".dockerenv")).unwrap(); + fs::create_dir(base.join(".dockerenv")).unwrap(); + assert!(!is_marker(p(".dockerenv"), &meta(".dockerenv"))); + + // Truncating an image-provided `/.dockerenv` to 0 bytes leaves an empty + // `0755 0:0` file in `upper`, which must not be skipped when a lower + // layer already has `/.dockerenv`. + let lower_clean = base.join("lower-clean"); + let lower_image = base.join("lower-image"); + fs::create_dir_all(&lower_clean).unwrap(); + fs::create_dir_all(&lower_image).unwrap(); + fs::write(lower_image.join(".dockerenv"), b"from-image\n").unwrap(); + let open_dir = |dir: &std::path::Path| { + let c = sys::cstr(dir).unwrap(); + // SAFETY: plain open of a temp directory we just created. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + assert!(fd >= 0); + // SAFETY: fresh descriptor. + unsafe { OwnedFd::from_raw_fd(fd) } + }; + let clean_lowers = [open_dir(&lower_clean)]; + let image_lowers = [open_dir(&lower_image)]; + assert!(!in_lower_layers(&clean_lowers, p(".dockerenv"))); + assert!(in_lower_layers(&image_lowers, p(".dockerenv"))); + let skip = |lowers: &[OwnedFd]| is_marker_attr(p(".dockerenv"), true, 0, 0o100755, 0, 0) && !in_lower_layers(lowers, p(".dockerenv")); + assert!(skip(&clean_lowers)); + assert!(!skip(&image_lowers)); + + let _ = fs::remove_dir_all(&base); + } + + #[test] + fn parse_mount_access_sorts_parents_first_and_tracks_ro_and_tmpfs() { + let mut buf = Vec::new(); + kiri_proto::encode_copy( + &mut buf, + copy_op::IN, + "c1", + "/", + 0, + &["sha256:a"], + &[ + "/v/sub\t/app/sub/\tro", + "/v/app\t/app\tcreate,copyup", + "tmpfs\t/tmp\ttmpfs,noexec,ro", + "tmpfs\t/run\ttmpfs,ro,rw", + ], + ); + let Msg::Copy(spec) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + let got = parse_mount_access(spec.mounts).unwrap(); + assert_eq!( + got, + [ + MountAccess { target: PathBuf::from("/app"), ro: false, tmpfs: false }, + MountAccess { target: PathBuf::from("/tmp"), ro: true, tmpfs: true }, + MountAccess { target: PathBuf::from("/run"), ro: false, tmpfs: true }, + MountAccess { target: PathBuf::from("/app/sub"), ro: true, tmpfs: false }, + ] + ); + let mut bad = Vec::new(); + kiri_proto::encode_copy(&mut bad, copy_op::IN, "c1", "/", 0, &[], &["/src\t../escape\tro"]); + let Msg::Copy(bad_spec) = kiri_proto::decode(&bad).unwrap() else { panic!() }; + assert!(parse_mount_access(bad_spec.mounts).is_err()); + } + + #[test] + fn check_writable_enforces_innermost_mount_and_readonly_rootfs() { + let m = |target: &str, ro: bool| MountAccess { target: PathBuf::from(target), ro, tmpfs: false }; + let mounts = [m("/app", false), m("/app/ro", true), m("/app/ro/rw", false), m("/ro", true)]; + let err = |p: &str, ro_root: bool| check_writable(Path::new(p), &mounts, ro_root).unwrap_err().to_string(); + + assert_eq!(err("/ro", false), "forbidden: mounted volume is marked read-only"); + assert_eq!(err("/ro/sub/f", false), "forbidden: mounted volume is marked read-only"); + assert_eq!(err("/app/ro", false), "forbidden: mounted volume is marked read-only"); + assert_eq!(err("/app/ro/file", false), "forbidden: mounted volume is marked read-only"); + // Component boundary: `/app/ro2` is under `/app` (rw), not `/app/ro`. + assert!(check_writable(Path::new("/app/ro2/file"), &mounts, true).is_ok()); + // Writable nested mount inside a read-only mount succeeds. + assert!(check_writable(Path::new("/app/ro/rw"), &mounts, true).is_ok()); + assert!(check_writable(Path::new("/app/ro/rw/x"), &mounts, true).is_ok()); + // Path outside every mount: refused iff `--read-only`. + assert!(check_writable(Path::new("/etc"), &mounts, false).is_ok()); + assert_eq!(err("/etc", true), "forbidden: container rootfs is marked read-only"); + // Writable mount on a `--read-only` rootfs succeeds. + assert!(check_writable(Path::new("/app/file"), &mounts, true).is_ok()); + // `:ro` mount on a `--read-only` rootfs reports the mounted volume error. + assert_eq!(err("/ro/x", true), "forbidden: mounted volume is marked read-only"); + } + + #[test] + fn unpack_in_refuses_ro_mounts_and_overwrites_file_mounts_in_place() { + let base = std::env::temp_dir().join(format!("kiri-copy-ro-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let root = base.join("root"); + fs::create_dir_all(root.join("ro")).unwrap(); + fs::create_dir_all(root.join("rw")).unwrap(); + fs::create_dir_all(root.join("etc")).unwrap(); + fs::write(root.join("etc/app.conf"), b"old").unwrap(); + fs::write(root.join("etc/ro.conf"), b"stay").unwrap(); + std::os::unix::fs::symlink(root.join("etc"), root.join("rw/to_etc")).unwrap(); + let canonical_root = fs::canonicalize(&root).unwrap(); + let mounts = [ + MountAccess { target: canonical_root.join("ro"), ro: true, tmpfs: false }, + MountAccess { target: canonical_root.join("rw"), ro: false, tmpfs: false }, + MountAccess { target: canonical_root.join("etc/app.conf"), ro: false, tmpfs: false }, + MountAccess { target: canonical_root.join("etc/ro.conf"), ro: true, tmpfs: false }, + ]; + let tar_file = |name: &str, data: &[u8]| { + let mut b = tar::Builder::new(Vec::new()); + let mut h = tar::Header::new_gnu(); + h.set_entry_type(tar::EntryType::Regular); + h.set_size(data.len() as u64); + h.set_mode(0o640); + h.set_mtime(0); + h.set_cksum(); + b.append_data(&mut h, name, data).unwrap(); + b.into_inner().unwrap() + }; + + // Entry targeting a `:ro` file bind mount is refused before writing. + let bytes = tar_file("ro.conf", b"pwn"); + let err = unpack_in(&bytes[..], &canonical_root.join("etc"), &canonical_root.join("etc"), 0, None, &mounts, false).unwrap_err(); + assert_eq!(err.to_string(), "forbidden: mounted volume is marked read-only"); + assert_eq!(fs::read(canonical_root.join("etc/ro.conf")).unwrap(), b"stay"); + + // Entry escaping a `:rw` volume through a symlink to a `--read-only` rootfs is refused. + let bytes = tar_file("to_etc/pwn", b"bad"); + let err = unpack_in(&bytes[..], &canonical_root.join("rw"), &canonical_root.join("rw"), 0, None, &mounts, true).unwrap_err(); + assert_eq!(err.to_string(), "forbidden: container rootfs is marked read-only"); + assert!(!canonical_root.join("etc/pwn").exists()); + + // Entry targeting a `:rw` file bind mount overwrites in place (keeping inode and zero mtime). + let before_ino = fs::symlink_metadata(canonical_root.join("etc/app.conf")).unwrap().ino(); + let bytes = tar_file("app.conf", b"updated"); + unpack_in(&bytes[..], &canonical_root.join("etc"), &canonical_root.join("etc"), 0, None, &mounts, false).unwrap(); + let after = fs::symlink_metadata(canonical_root.join("etc/app.conf")).unwrap(); + assert_eq!(after.ino(), before_ino, "file bind mount must be overwritten in place, not unlinked"); + assert_eq!(fs::read(canonical_root.join("etc/app.conf")).unwrap(), b"updated"); + assert_eq!(after.mtime(), 0); + assert_eq!(after.mode() & 0o777, 0o640); + + let _ = fs::remove_dir_all(&base); + } + + #[test] + fn paced_writer_waits_for_credit_and_bounds_chunks_to_64kib() { + use std::os::unix::net::UnixStream; + let (mut host, guest) = UnixStream::pair().unwrap(); + let data = vec![0x5a_u8; PACED_CHUNK + 1234]; + let expected = data.clone(); + let t = std::thread::spawn(move || { + let mut w = PacedWriter::new(guest); + w.write_all(&data).unwrap(); + w.finish().unwrap(); + }); + + let mut received = Vec::new(); + let mut sizes = Vec::new(); + loop { + host.write_all(&[1]).unwrap(); + let mut hdr = [0u8; 4]; + host.read_exact(&mut hdr).unwrap(); + let len = u32::from_le_bytes(hdr) as usize; + if len == 0 { + break; + } + assert!(len <= PACED_CHUNK, "chunk {len} exceeded {PACED_CHUNK}"); + sizes.push(len); + let mut chunk = vec![0u8; len]; + host.read_exact(&mut chunk).unwrap(); + received.extend_from_slice(&chunk); + } + t.join().unwrap(); + assert_eq!(sizes, vec![PACED_CHUNK, 1234]); + assert_eq!(received, expected); + } } diff --git a/crates/kiri-init/src/linux/disk.rs b/crates/kiri-init/src/linux/disk.rs new file mode 100644 index 000000000..cca7d15d1 --- /dev/null +++ b/crates/kiri-init/src/linux/disk.rs @@ -0,0 +1,126 @@ +//! Expand the mounted ext4 filesystem to the backing device's capacity. + +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom}; +use std::os::fd::AsRawFd; +use std::path::Path; + +const EXT4_SUPER_OFFSET: u64 = 1024; +const EXT4_SUPER_LEN: usize = 1024; +const EXT4_SUPER_MAGIC: u16 = 0xEF53; +const EXT4_FEATURE_INCOMPAT_64BIT: u32 = 0x80; + +// EXT4_IOC_RESIZE_FS = _IOW('f', 16, __u64), on both guest architectures. +const EXT4_IOC_RESIZE_FS: libc::Ioctl = 0x4008_6610_u32 as libc::Ioctl; + +/// Parses the ext4 superblock's total block count (including metadata). +/// Returns `InvalidData` if the superblock magic does not match ext4. +fn superblock_blocks(sb: &[u8; EXT4_SUPER_LEN]) -> io::Result { + let magic = u16::from_le_bytes([sb[0x38], sb[0x39]]); + if magic != EXT4_SUPER_MAGIC { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("unexpected ext4 superblock magic 0x{magic:04x}"), + )); + } + let word = |offset: usize| u32::from_le_bytes(sb[offset..offset + 4].try_into().unwrap()); + let mut blocks = u64::from(word(0x04)); + if word(0x60) & EXT4_FEATURE_INCOMPAT_64BIT != 0 { + blocks |= u64::from(word(0x150)) << 32; + } + Ok(blocks) +} + +pub fn grow() -> io::Result<()> { + grow_device(Path::new("/dev/vda"), Path::new(super::DATA)) +} + +pub(crate) fn grow_device(device: &Path, mountpoint: &Path) -> io::Result<()> { + let mut disk = File::open(device)?; + let bytes = disk.seek(SeekFrom::End(0))?; + // The data disk has already mounted as ext4. Read its total block + // count, including metadata (statfs excludes metadata from f_blocks). + disk.seek(SeekFrom::Start(EXT4_SUPER_OFFSET))?; + let mut sb = [0u8; EXT4_SUPER_LEN]; + disk.read_exact(&mut sb)?; + let current = superblock_blocks(&sb)?; + let fs = File::open(mountpoint)?; + // SAFETY: statfs is plain data; fstatfs writes it before it is read. + let mut stat: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: fs is open and stat is valid writable storage. + super::sys::check( + unsafe { libc::fstatfs(fs.as_raw_fd(), &mut stat) } as _, + "data disk statfs", + )?; + let block_size = stat.f_bsize as u64; + if block_size == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid ext4 block size", + )); + } + let blocks = bytes / block_size; + if blocks <= current { + return Ok(()); + } + // SAFETY: fs is the mounted ext4 directory and blocks is a valid u64. + super::sys::check( + unsafe { libc::ioctl(fs.as_raw_fd(), EXT4_IOC_RESIZE_FS, &blocks) } as _, + "grow ext4 data disk", + )?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn fake_superblock(lo: u32, hi: u32, is_64bit: bool) -> [u8; EXT4_SUPER_LEN] { + let mut sb = [0u8; EXT4_SUPER_LEN]; + sb[0x38..0x3a].copy_from_slice(&EXT4_SUPER_MAGIC.to_le_bytes()); + sb[0x04..0x08].copy_from_slice(&lo.to_le_bytes()); + let incompat: u32 = if is_64bit { + EXT4_FEATURE_INCOMPAT_64BIT + } else { + 0 + }; + sb[0x60..0x64].copy_from_slice(&incompat.to_le_bytes()); + sb[0x150..0x154].copy_from_slice(&hi.to_le_bytes()); + sb + } + + #[test] + fn superblock_reads_32bit_and_64bit_block_counts() { + let sb32 = fake_superblock(16_777_216, 99, false); + assert_eq!(superblock_blocks(&sb32).unwrap(), 16_777_216); + + let sb64 = fake_superblock(0x0000_0001, 0x0000_0002, true); + assert_eq!(superblock_blocks(&sb64).unwrap(), (2u64 << 32) | 1); + } + + #[test] + fn superblock_rejects_bad_magic() { + let sb = [0u8; EXT4_SUPER_LEN]; + assert_eq!( + superblock_blocks(&sb).unwrap_err().kind(), + io::ErrorKind::InvalidData + ); + } + + /// Real online ext4 resize check when driven on a Linux host with a + /// mounted loop device (`KIRI_TEST_EXT4_DEV` + `KIRI_TEST_EXT4_MOUNT`). + #[test] + fn grows_mounted_ext4_online_when_configured() { + let (Ok(dev), Ok(mnt)) = ( + std::env::var("KIRI_TEST_EXT4_DEV"), + std::env::var("KIRI_TEST_EXT4_MOUNT"), + ) else { + return; + }; + let dev = Path::new(&dev); + let mnt = Path::new(&mnt); + grow_device(dev, mnt).expect("first online ext4 resize must succeed"); + // Calling grow again when already at full capacity must be a no-op. + grow_device(dev, mnt).expect("second online ext4 resize must be idempotent"); + } +} diff --git a/crates/kiri-init/src/linux/dns.rs b/crates/kiri-init/src/linux/dns.rs index 3ca8b5b0b..1049138d6 100644 --- a/crates/kiri-init/src/linux/dns.rs +++ b/crates/kiri-init/src/linux/dns.rs @@ -74,12 +74,25 @@ const OWN_DEADLINE: Duration = Duration::from_secs(4 * MAX_OWN_SERVERS as u64); /// than `MAX_PER_CLIENT`. One more is answered SERVFAIL at once. const MAX_OWN_PER_CLIENT: usize = 16; const _: () = assert!(MAX_OWN_PER_CLIENT < MAX_PER_CLIENT); -/// Largest reply the host relay may send (a DNS over TCP frame's limit). +/// Largest reply the host relay or a TCP upstream may send (a DNS over TCP frame's limit). const MAX_RELAYED: usize = 2 + 65_535; +/// Concurrent TCP DNS client connections accepted across all listeners. +const MAX_TCP_CLIENTS: usize = 64; +/// Maximum queued reply bytes for one TCP DNS client before it is dropped. +const MAX_TCP_SEND: usize = 65_536; /// Docker's embedded DNS address, inside each container. pub const EMBEDDED: [u8; 4] = [127, 0, 0, 11]; +/// Who owns a forwarded DNS query (`Pending`) or `--dns` upstream list. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum ClientKey { + /// A container queried a bridge's gateway from this source IP. + Ip([u8; 4]), + /// A container queried 127.0.0.11 in its own network namespace (PID 1). + Container(i32), +} + struct Server { /// Its own number, never reused: what a forwarded query names it by. id: u64, @@ -87,9 +100,20 @@ struct Server { /// network of the container it is in. bridges: Vec, sock: OwnedFd, - /// In a container's namespace: (its PID, the address its `--dns` - /// servers are kept under). Every query there comes from 127.0.0.1. - container: Option<(i32, [u8; 4])>, + /// PID of the container whose namespace this 127.0.0.11 server is in; + /// every query there comes from 127.0.0.1. + container: Option, +} + +struct TcpClient { + id: u64, + server: u64, + key: ClientKey, + sock: OwnedFd, + recv: Vec, + send: Vec, + eof: bool, + started: Instant, } struct Pending { @@ -101,11 +125,13 @@ struct Pending { sock: OwnedFd, /// The ID it went out with. our: u16, - /// Who asked, for `MAX_PER_CLIENT`: the container's address. - key: [u8; 4], + /// Who asked, for `MAX_PER_CLIENT`. + key: ClientKey, /// The server the query came in on (`Server::id`). server: u64, client: libc::sockaddr_in, + /// `Some(TcpClient::id)` when the client asked over TCP; `None` for UDP. + tcp_client: Option, id: u16, question: Vec, /// When it was asked of the server it is with now. @@ -115,13 +141,20 @@ struct Pending { /// The query as sent (with `our` ID), to send again. query: Vec, /// With the container's own `--dns` servers (kept under `key`): the - /// position of the one it is with. None for the VM's resolver. + /// position of the one it is with. None for the VM's / host's resolver. own: Option, + /// Host/VM upstream servers and the index currently asked when `own` is None. + upstreams: Vec<[u8; 4]>, + upstream_at: usize, /// It may still go through the host: in the VM, asked of the VM's own /// resolver (not `--dns` servers), and not tried there yet. may_relay: bool, /// Sent through the host: the reply's bytes so far, `u16 len | reply`. relayed: Option>, + /// Sent over TCP to an upstream server: remaining request bytes to write, + /// while `tcp_recv` collects the `u16 len | reply` answer. + tcp_send: Option>, + tcp_recv: Vec, } /// One name's IPv6 addresses, each with its container's IPv4 address. @@ -130,20 +163,36 @@ type Owned6 = Vec<([u8; 4], [u8; 16])>; #[derive(Default)] pub struct Dns { servers: Vec, + /// `(Server::id, listener)` for DNS over TCP on gateways and `127.0.0.11`. + tcp_servers: Vec<(u64, OwnedFd)>, + tcp_clients: Vec, /// bridge → name (lowercase) → addresses. names: HashMap>>, /// bridge → name → (the container's IPv4 address there, its IPv6 one): /// the IPv4 address is what `unregister` names the container by. names6: HashMap>, + /// Bridges with IPv6 enabled: external `AAAA` queries on a server whose + /// bridges are all IPv4-only are answered `NODATA` locally (matching + /// Docker's libnetwork) instead of returning unreachable global IPv6 + /// addresses (#932). + ipv6_bridges: std::collections::HashSet, /// bridge → its Docker network's name: the order a container's server /// searches its networks in. networks: HashMap, - /// Container address → its `--dns` servers, used instead of the VM's. + /// Container address → its `--dns` servers, used on a gateway listener. clients: HashMap<[u8; 4], Vec<[u8; 4]>>, + /// Container PID → its `--dns` servers, used on 127.0.0.11 so custom + /// resolvers survive disconnecting and reconnecting even the first network. + container_upstreams: HashMap>, pending: Vec, /// Lookups the VM's resolver fails go through the host (in the VM; a /// Linux host's agent asks the host's resolvers itself). pub relay: bool, + /// Send upstream lookups straight through the host relay instead of + /// asking the VM's gateway resolver first (when a macOS network + /// extension or host egress mode is active, or once the gateway resolver + /// has answered with a `198.18.0.0/15` Fake-IP address). + pub prefer_relay: bool, /// The host didn't take a relayed lookup: none are tried until then. relay_down_until: Option, /// Bridges whose gateway wouldn't take the listener (`serve_or_warn`): @@ -205,7 +254,11 @@ impl Dns { self.forget_pending(); } let sock = bound(gateway, 53)?; - self.servers.push(Server { id: server_id(), bridges: vec![bridge.to_owned()], sock, container: None }); + let id = server_id(); + if let Ok(tcp) = tcp_bound(gateway, 53) { + self.tcp_servers.push((id, tcp)); + } + self.servers.push(Server { id, bridges: vec![bridge.to_owned()], sock, container: None }); Ok(()) } @@ -234,47 +287,49 @@ impl Dns { /// Starts answering at 127.0.0.11:53 in container `pid`'s network /// namespace `netns` (lo up) for the names on `bridge`, or adds `bridge` - /// to the networks its server answers for. `owner` is the address its - /// `--dns` servers are kept under (`set_upstream`). - pub fn serve_in(&mut self, netns: &std::fs::File, pid: i32, owner: [u8; 4], bridge: &str) -> io::Result<()> { - if let Some(s) = self.servers.iter_mut().find(|s| s.container.is_some_and(|(p, _)| p == pid)) { + /// to the networks its server answers for. + pub fn serve_in(&mut self, netns: &std::fs::File, pid: i32, bridge: &str) -> io::Result<()> { + if let Some(s) = self.servers.iter_mut().find(|s| s.container == Some(pid)) { if !s.bridges.iter().any(|b| b == bridge) { s.bridges.push(bridge.to_owned()); } return Ok(()); } - let sock = super::netlink::in_netns(netns, embedded_socket)?; - self.servers.push(Server { id: server_id(), bridges: vec![bridge.to_owned()], sock, container: Some((pid, owner)) }); + let (sock, tcp) = super::netlink::in_netns(netns, embedded_socket)?; + let id = server_id(); + if let Some(tcp) = tcp { + self.tcp_servers.push((id, tcp)); + } + self.servers.push(Server { id, bridges: vec![bridge.to_owned()], sock, container: Some(pid) }); Ok(()) } /// Container `pid` left `bridge` (`network disconnect`). pub fn leave(&mut self, pid: i32, bridge: &str) { - for s in self.servers.iter_mut().filter(|s| s.container.is_some_and(|(p, _)| p == pid)) { + for s in self.servers.iter_mut().filter(|s| s.container == Some(pid)) { s.bridges.retain(|b| b != bridge); } } - /// The address container `pid`'s 127.0.0.11 server keeps its `--dns` - /// servers under (`set_upstream`), if it has one. - pub fn owner_of(&self, pid: i32) -> Option<[u8; 4]> { - self.servers.iter().find_map(|s| s.container.filter(|(p, _)| *p == pid).map(|(_, owner)| owner)) - } - /// Whether the agent answers DNS at `ip` on a bridge (its gateway). pub fn serves_at(&self, ip: [u8; 4]) -> bool { self.servers.iter().filter(|s| s.container.is_none()).any(|s| local_addr(&s.sock) == Some(ip)) } - /// Container `pid` is gone: its 127.0.0.11 server goes. + /// Container `pid` is gone: its 127.0.0.11 server and `--dns` servers go. pub fn drop_container(&mut self, pid: i32) { - self.servers.retain(|s| !s.container.is_some_and(|(p, _)| p == pid)); + self.servers.retain(|s| s.container != Some(pid)); + self.container_upstreams.remove(&pid); + self.pending.retain(|p| p.key != ClientKey::Container(pid)); + self.tcp_clients.retain(|c| c.key != ClientKey::Container(pid)); self.forget_pending(); } - /// Forwarded queries whose server is gone go too. + /// Forwarded queries and TCP sockets whose server is gone go too. fn forget_pending(&mut self) { let servers = &self.servers; + self.tcp_servers.retain(|(sid, _)| servers.iter().any(|s| s.id == *sid)); + self.tcp_clients.retain(|c| servers.iter().any(|s| s.id == c.server)); self.pending.retain(|p| servers.iter().any(|s| s.id == p.server)); } @@ -290,6 +345,7 @@ impl Dns { /// The IPv6 address of the container that has `owner` on this network. pub fn register6(&mut self, bridge: &str, names: impl Iterator>, owner: [u8; 4], ip: [u8; 16]) { + self.ipv6_bridges.insert(bridge.to_owned()); let table = self.names6.entry(bridge.to_owned()).or_default(); for n in names { let list = table.entry(n.as_ref().to_ascii_lowercase()).or_default(); @@ -299,6 +355,25 @@ impl Dns { } } + /// Records whether `bridge` has IPv6 enabled, controlling whether external + /// `AAAA` queries on servers attached to it are forwarded upstream or + /// answered `NODATA` locally (#932). + pub fn set_bridge_ipv6(&mut self, bridge: &str, enabled: bool) { + if enabled { + self.ipv6_bridges.insert(bridge.to_owned()); + } else { + self.ipv6_bridges.remove(bridge); + } + } + + /// Whether any network served by `server` has IPv6 enabled. + fn server_has_ipv6(&self, server: usize) -> bool { + self.servers[server] + .bridges + .iter() + .any(|b| self.ipv6_bridges.contains(b) || self.names6.get(b).is_some_and(|m| !m.is_empty())) + } + /// `bridge` is Docker network `name` (`net_opts::NETWORK`). pub fn name_network(&mut self, bridge: &str, name: &str) { if self.networks.get(bridge).is_none_or(|n| n != name) { @@ -314,6 +389,7 @@ impl Dns { } self.names.remove(bridge); self.names6.remove(bridge); + self.ipv6_bridges.remove(bridge); self.networks.remove(bridge); self.refused.remove(bridge); self.forget_pending(); @@ -330,11 +406,39 @@ impl Dns { } } + /// Where queries from container `pid`'s 127.0.0.11 listener go; kept per + /// container so disconnecting its first network does not erase `--dns`. + pub fn set_container_upstream(&mut self, pid: i32, mut servers: Vec<[u8; 4]>) { + servers.truncate(MAX_OWN_SERVERS); + if servers.is_empty() { + self.container_upstreams.remove(&pid); + } else { + self.container_upstreams.insert(pid, servers); + } + } + + pub fn container_upstream(&self, pid: i32) -> Option> { + self.container_upstreams.get(&pid).cloned() + } + + #[cfg(test)] + pub fn ip_upstream(&self, ip: [u8; 4]) -> Option> { + self.clients.get(&ip).cloned() + } + + fn own_servers(&self, key: ClientKey) -> Option<&Vec<[u8; 4]>> { + match key { + ClientKey::Ip(ip) => self.clients.get(&ip), + ClientKey::Container(pid) => self.container_upstreams.get(&pid), + } + } + pub fn unregister(&mut self, bridge: &str, ip: [u8; 4]) { self.clients.remove(&ip); // Its queries in flight go with it: a container given the address // next never gets them, or their answers. - self.pending.retain(|p| p.key != ip); + self.pending.retain(|p| p.key != ClientKey::Ip(ip)); + self.tcp_clients.retain(|c| c.key != ClientKey::Ip(ip)); self.drop_names(bridge, ip); } @@ -370,9 +474,47 @@ impl Dns { } } - /// Descriptors to poll: each server's, plus each forwarded query's. + /// Descriptors to poll: each server's (UDP and TCP), accepted TCP clients, + /// and forwarded queries in flight. pub fn fds(&self) -> impl Iterator + '_ { - self.servers.iter().map(|s| s.sock.as_raw_fd()).chain(self.pending.iter().map(|p| p.sock.as_raw_fd())) + self.servers + .iter() + .map(|s| s.sock.as_raw_fd()) + .chain(self.tcp_servers.iter().map(|(_, s)| s.as_raw_fd())) + .chain(self.tcp_clients.iter().map(|c| c.sock.as_raw_fd())) + .chain(self.pending.iter().map(|p| p.sock.as_raw_fd())) + } + + /// Appends poll descriptors with read/write interest for the agent's loop. + pub fn interest(&self, fds: &mut Vec) { + for s in &self.servers { + fds.push(libc::pollfd { fd: s.sock.as_raw_fd(), events: libc::POLLIN, revents: 0 }); + } + for (_, tcp) in &self.tcp_servers { + fds.push(libc::pollfd { fd: tcp.as_raw_fd(), events: libc::POLLIN, revents: 0 }); + } + for c in &self.tcp_clients { + let events = if !c.send.is_empty() { + libc::POLLOUT + } else if !c.eof { + libc::POLLIN + } else { + 0 + }; + if events != 0 { + fds.push(libc::pollfd { fd: c.sock.as_raw_fd(), events, revents: 0 }); + } + } + for p in &self.pending { + let events = if p.tcp_send.as_ref().is_some_and(|b| !b.is_empty()) { libc::POLLIN | libc::POLLOUT } else { libc::POLLIN }; + fds.push(libc::pollfd { fd: p.sock.as_raw_fd(), events, revents: 0 }); + } + } + + /// True when `fd` is a server listener (UDP socket or TCP listener), so + /// the host agent refreshes `/etc/resolv.conf` on new queries. + pub fn is_listener(&self, fd: RawFd) -> bool { + self.servers.iter().any(|s| s.sock.as_raw_fd() == fd) || self.tcp_servers.iter().any(|(_, s)| s.as_raw_fd() == fd) } pub fn owns(&self, fd: RawFd) -> bool { @@ -386,6 +528,10 @@ impl Dns { self.read_relayed(at); return; } + if self.pending[at].tcp_send.is_some() { + self.step_tcp_upstream(at); + return; + } // A forwarded answer: hand it back to whoever asked. loop { // SAFETY: receiving into a buffer we own. @@ -402,10 +548,25 @@ impl Dns { let msg = &mut buf[..n as usize]; let p = &self.pending[at]; if u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(msg, p) { - // REFUSED or SERVFAIL from one of its own servers: the - // next one, as with Docker. From the last, it goes back. - if matches!(msg[3] & 0x0f, 2 | 5) && self.pending[at].own.is_some() && self.ask_next_own(at) { - break; + // REFUSED or SERVFAIL from one of its own servers (or when + // another host upstream is listed): try the next one. + if matches!(msg[3] & 0x0f, 2 | 5) { + if self.pending[at].own.is_some() && self.ask_next_own(at) { + break; + } + if self.pending[at].own.is_none() && self.ask_next_upstream(at) { + break; + } + } + // A macOS security network extension intercepting the VM + // bridge's DNS answers with a Fake-IP in 198.18.0.0/15 + // (#367): ask the Mac's own resolvers over vsock instead, + // and prefer the host relay from then on. + if self.pending[at].own.is_none() && self.pending[at].may_relay && answer_has_fake_ip(msg) { + self.prefer_relay = true; + if self.relay(at) { + break; + } } self.answered(at, msg); break; @@ -413,6 +574,14 @@ impl Dns { } return; } + if let Some(at) = self.tcp_clients.iter().position(|c| c.sock.as_raw_fd() == fd) { + self.step_tcp_client(at, upstream); + return; + } + if let Some(&(sid, _)) = self.tcp_servers.iter().find(|(_, s)| s.as_raw_fd() == fd) { + self.accept_tcp_clients(fd, sid); + return; + } let Some(server) = self.servers.iter().position(|s| s.sock.as_raw_fd() == fd) else { return; }; @@ -435,8 +604,16 @@ impl Dns { /// Answers a query for a name on this network, or None to forward it. fn answer(&self, server: usize, q: &[u8]) -> Option> { + self.answer_with_host_fn(server, q, super::net::effective_host_addr) + } + + #[cfg(test)] + fn answer_with_host(&self, server: usize, q: &[u8], host_ip: [u8; 4]) -> Option> { + self.answer_with_host_fn(server, q, || host_ip) + } + + fn answer_with_host_fn(&self, server: usize, q: &[u8], host_ip: impl FnOnce() -> [u8; 4]) -> Option> { let (name, qtype, end) = parse_question(q)?; - let host = vec![super::net::HOST_ADDR]; // Of the server's networks that have the name, the first by Docker // network name answers, as with Docker: not the first joined. A // name Compose gives a service on every network it joins then @@ -444,27 +621,47 @@ impl Dns { // where another project's service has it too (#294). // The host's names are the host's whatever a container is called: // a name registered for one of them is never answered. - let is_host = HOST_NAMES.contains(&name.as_str()); + let known = |n: &str| { + HOST_NAMES.contains(&n) + || self.servers[server].bridges.iter().any(|b| self.names.get(b).is_some_and(|t| t.contains_key(n)) || self.names6.get(b).is_some_and(|t| t.contains_key(n))) + }; + // gRPC's SRV lookup of `_grpclb._tcp.` names a container on + // this network (or the host). Answer NODATA for the service here: + // there are no SRV records, and forwarding the query would leave + // Go's resolver waiting for an upstream we can't rely on (#715). + // A registered alias starting with `_` (such as `_app.web` alongside + // `web`) is answered with its own records, not taken for a selector. + let service = if known(&name) { None } else { service_base(&name, known) }; + let lookup = service.unwrap_or(&name); + let is_host = HOST_NAMES.contains(&lookup); let bridge = self.servers[server] .bridges .iter() - .filter(|b| !is_host && (self.names.get(*b).is_some_and(|t| t.contains_key(&name)) || self.names6.get(*b).is_some_and(|t| t.contains_key(&name)))) + .filter(|b| !is_host && (self.names.get(*b).is_some_and(|t| t.contains_key(lookup)) || self.names6.get(*b).is_some_and(|t| t.contains_key(lookup)))) .min_by_key(|b| self.networks.get(*b).map_or(b.as_str(), String::as_str)); - let addrs = bridge.and_then(|b| self.names.get(b)).and_then(|t| t.get(&name)); - let addrs6 = bridge.and_then(|b| self.names6.get(b)).and_then(|t| t.get(&name)); + let addrs = bridge.and_then(|b| self.names.get(b)).and_then(|t| t.get(lookup)); + let addrs6 = bridge.and_then(|b| self.names6.get(b)).and_then(|t| t.get(lookup)); // The host's names answer A with the host's address, and AAAA with - // no records: the host relay is IPv4 only. - let addrs = match addrs { - None if is_host => Some(&host), - a => a, + // no records: the host relay is IPv4 only. Resolve the host IP lazily + // so non-host DNS queries never touch the filesystem or procfs. + let host: [u8; 4]; + let a_addrs: Option<&[[u8; 4]]> = match addrs { + None if is_host => { + host = host_ip(); + Some(std::slice::from_ref(&host)) + } + a => a.map(Vec::as_slice), }; // A container name with no address of the asked type is NODATA, not // forwarded: the name is this network's. - if addrs.is_none() && addrs6.is_none() { + if a_addrs.is_none() && addrs6.is_none() { return None; } - let a: &[[u8; 4]] = if qtype == 1 || qtype == 255 { addrs.map_or(&[], Vec::as_slice) } else { &[] }; - let aaaa: &[([u8; 4], [u8; 16])] = if qtype == 28 || qtype == 255 { addrs6.map_or(&[], Vec::as_slice) } else { &[] }; + // A service name has no records of its own: the container it + // belongs to has the addresses, and the caller looks those up by + // the container's name. + let a: &[[u8; 4]] = if service.is_none() && (qtype == 1 || qtype == 255) { a_addrs.unwrap_or(&[]) } else { &[] }; + let aaaa: &[([u8; 4], [u8; 16])] = if service.is_none() && (qtype == 28 || qtype == 255) { addrs6.map_or(&[], Vec::as_slice) } else { &[] }; let mut r = Vec::with_capacity(end + 16 * a.len() + 28 * aaaa.len()); r.extend_from_slice(&q[0..2]); // id r.extend_from_slice(&[0x81, 0x80]); // response, recursion desired + available @@ -488,30 +685,56 @@ impl Dns { } fn forward(&mut self, server: usize, q: &[u8], client: libc::sockaddr_in, upstream: &[[u8; 4]]) { + let key = self.servers[server] + .container + .map_or_else(|| ClientKey::Ip(client.sin_addr.s_addr.to_ne_bytes()), ClientKey::Container); + self.forward_with(server, q, client, None, key, upstream); + } + + fn forward_with( + &mut self, + server: usize, + q: &[u8], + client: libc::sockaddr_in, + tcp_client: Option, + key: ClientKey, + upstream: &[[u8; 4]], + ) { let now = Instant::now(); - // A query with the container's own servers past its deadline is - // answered SERVFAIL here too, before the slots are counted. + // A query past its deadline is answered SERVFAIL here too, before + // the slots are counted: `on_readable` runs before `on_timer`. for at in (0..self.pending.len()).rev() { - if self.pending[at].own.is_some() && now.duration_since(self.pending[at].started) >= OWN_DEADLINE { + let p = &self.pending[at]; + let (from, wait) = if p.own.is_some() { (p.started, OWN_DEADLINE) } else { (p.sent, FORWARD_TIMEOUT) }; + if now.duration_since(from) >= wait { self.fail(at); } } - self.pending.retain(|p| p.own.is_some() || now.duration_since(p.sent) < FORWARD_TIMEOUT); - let key = self.servers[server].container.map_or(client.sin_addr.s_addr.to_ne_bytes(), |(_, owner)| owner); - let own = self.clients.get(&key).map(|v| (v.len(), v.first().copied())); - let Some((_, _, end)) = parse_question(q) else { + let own = self.own_servers(key).map(|v| v.len()); + let Some((_, qtype, end)) = parse_question(q) else { return; }; + // On IPv4-only networks (no bridge on this server has IPv6 enabled), + // return NOERROR/NODATA for external AAAA queries instead of forwarding + // upstream and returning unreachable global IPv6 records (matching + // Docker Engine's libnetwork resolver, #932). Containers with custom + // `--dns` servers keep forwarding unmodified. + if qtype == 28 && own.is_none() && !self.server_has_ipv6(server) { + let reply = nodata(id_of(q), rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &reply); + return; + } let (mut mine, mut mine_own) = (0, 0); for p in self.pending.iter().filter(|p| p.key == key) { mine += 1; mine_own += usize::from(p.own.is_some()); } if self.pending.len() >= MAX_PENDING || mine >= MAX_PER_CLIENT || (own.is_some() && mine_own >= MAX_OWN_PER_CLIENT) { - // With its own servers the client is told at once (they may - // hold a slot for `OWN_DEADLINE`); else it asks again. - if own.is_some() { - send_to(self.servers[server].sock.as_raw_fd(), &servfail(id_of(q), rd(q), &q[12..end]), &client); + // With its own servers (or over TCP) the client is told at once; + // else UDP asks again. + if own.is_some() || tcp_client.is_some() { + let fail = servfail(id_of(q), rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &fail); } return; } @@ -520,31 +743,52 @@ impl Dns { let id = u16::from_be_bytes([msg[0], msg[1]]); msg[0..2].copy_from_slice(&our.to_be_bytes()); let may_relay = self.relay && own.is_none(); - let mut at = None; - let sock = match own { + let use_tcp = tcp_client.is_some(); + let mut own_at = None; + let mut upstream_at = 0; + let upstreams: Vec<[u8; 4]> = if own.is_none() { upstream.to_vec() } else { Vec::new() }; + let dialed = match own { // The first of its own servers that can be sent to. - Some((len, _)) => (0..len).find_map(|i| { - let sock = self.clients.get(&key).and_then(|v| v.get(i)).and_then(|d| ask(*d, &msg))?; - at = Some(i); - Some(sock) + Some(len) => (0..len).find_map(|i| { + let d = self.own_servers(key).and_then(|v| v.get(i)).copied()?; + let s = ask_dest(d, &msg, use_tcp)?; + own_at = Some(i); + Some(s) + }), + None if self.prefer_relay && may_relay => None, + None => upstreams.iter().enumerate().find_map(|(i, d)| { + let s = ask_dest(*d, &msg, use_tcp)?; + upstream_at = i; + Some(s) }), - None => upstream.first().and_then(|d| ask(*d, &msg)), }; - // No resolver yet, or it can't be reached: the host, if allowed. - let (sock, relayed) = match sock { - Some(s) => (s, false), - None if may_relay => match self.relay_stream(&msg) { - Some(s) => (s, true), - None => return, - }, - // None of its own can be sent to: SERVFAIL, not silence. - None if own.is_some() => { - if let Some(s) = self.servers.get(server) { - send_to(s.sock.as_raw_fd(), &servfail(id_of(q), rd(q), &q[12..end]), &client); + // No resolver yet, or it can't be reached (or `prefer_relay` chose the host): the host, if allowed. + let (sock, tcp_send, relayed) = match dialed { + Some((s, tcp_send)) => (s, tcp_send, false), + None => match may_relay.then(|| self.relay_stream(&msg)).flatten() { + Some(s) => (s, None, true), + None if self.prefer_relay && own.is_none() => match upstreams.iter().enumerate().find_map(|(i, d)| { + let s = ask_dest(*d, &msg, use_tcp)?; + upstream_at = i; + Some(s) + }) { + Some((s, tcp_send)) => (s, tcp_send, false), + None => { + let fail = servfail(id, rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &fail); + return; + } + }, + // No upstream that can be sent to and no host relay (none on + // a Linux host, not used for `--dns`, or backing off): + // answer at once rather than leave Go's resolver to time + // out waiting for a reply that will never come (#715). + None => { + let fail = servfail(id, rd(q), &q[12..end]); + self.reply_now(server, client, tcp_client, &fail); + return; } - return; - } - None => return, + }, }; let p = Pending { sock, @@ -552,23 +796,38 @@ impl Dns { key, server: self.servers[server].id, client, + tcp_client, id, question: q[12..end].to_vec(), sent: now, started: now, query: msg, - own: at, + own: own_at, + upstreams, + upstream_at, may_relay: may_relay && !relayed, relayed: relayed.then(Vec::new), + tcp_send, + tcp_recv: Vec::new(), }; self.pending.push(p); } + fn reply_now(&mut self, server: usize, client: libc::sockaddr_in, tcp_client: Option, msg: &[u8]) { + if let Some(cid) = tcp_client { + self.send_tcp_reply(cid, msg); + } else { + send_to(self.servers[server].sock.as_raw_fd(), msg, &client); + } + } + /// Hands a matching answer to whoever asked, and forgets the query. fn answered(&mut self, at: usize, msg: &mut [u8]) { let p = self.pending.swap_remove(at); msg[0..2].copy_from_slice(&p.id.to_be_bytes()); - if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { + if let Some(cid) = p.tcp_client { + self.send_tcp_reply(cid, msg); + } else if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { send_to(s.sock.as_raw_fd(), msg, &p.client); } } @@ -582,7 +841,8 @@ impl Dns { let p = &self.pending[at]; let Some(mut i) = p.own else { return false }; let key = p.key; - if p.started.elapsed() >= OWN_DEADLINE || self.clients.get(&key).is_none_or(|v| i + 1 >= v.len()) { + let use_tcp = p.tcp_client.is_some(); + if p.started.elapsed() >= OWN_DEADLINE || self.own_servers(key).is_none_or(|v| i + 1 >= v.len()) { return false; } let Some(our) = random_id() else { return false }; @@ -590,13 +850,45 @@ impl Dns { self.pending[at].query[0..2].copy_from_slice(&our.to_be_bytes()); loop { i += 1; - let Some(dest) = self.clients.get(&key).and_then(|v| v.get(i)).copied() else { break }; - if let Some(sock) = ask(dest, &self.pending[at].query) { + let Some(dest) = self.own_servers(key).and_then(|v| v.get(i)).copied() else { break }; + if let Some((sock, tcp_send)) = ask_dest(dest, &self.pending[at].query, use_tcp) { let p = &mut self.pending[at]; p.sock = sock; p.our = our; p.own = Some(i); p.sent = Instant::now(); + p.tcp_send = tcp_send; + p.tcp_recv.clear(); + return true; + } + } + self.pending[at].query[0..2].copy_from_slice(&was); + false + } + + /// Sends pending query `at` to the next host/VM upstream server (e.g. + /// `systemd-resolved`'s upstream fallback when `127.0.0.53` refuses). + fn ask_next_upstream(&mut self, at: usize) -> bool { + let p = &self.pending[at]; + if p.own.is_some() || p.upstream_at + 1 >= p.upstreams.len() { + return false; + } + let mut i = p.upstream_at; + let use_tcp = p.tcp_client.is_some(); + let Some(our) = random_id() else { return false }; + let was = [p.query[0], p.query[1]]; + self.pending[at].query[0..2].copy_from_slice(&our.to_be_bytes()); + while i + 1 < self.pending[at].upstreams.len() { + i += 1; + let dest = self.pending[at].upstreams[i]; + if let Some((sock, tcp_send)) = ask_dest(dest, &self.pending[at].query, use_tcp) { + let p = &mut self.pending[at]; + p.sock = sock; + p.our = our; + p.upstream_at = i; + p.sent = Instant::now(); + p.tcp_send = tcp_send; + p.tcp_recv.clear(); return true; } } @@ -605,32 +897,29 @@ impl Dns { } /// The server a query is with can't be reached or refused: the next of - /// the container's own, else the host if the query may go through it, - /// else (its own servers all failed) SERVFAIL to the client. + /// the container's own, else the next host upstream, else the host relay + /// if the query may go through it, else SERVFAIL to the client. fn hand_over(&mut self, at: usize) { - if self.ask_next_own(at) { - return; - } - if self.pending[at].own.is_some() { + if !self.ask_next_own(at) && !self.ask_next_upstream(at) && !self.relay(at) { self.fail(at); - } else { - self.relay(at); } } /// Answers pending query `at` SERVFAIL and forgets it (closing its socket). fn fail(&mut self, at: usize) { let p = self.pending.swap_remove(at); - if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { - let reply = servfail(p.id, rd(&p.query), &p.question); + let reply = servfail(p.id, rd(&p.query), &p.question); + if let Some(cid) = p.tcp_client { + self.send_tcp_reply(cid, &reply); + } else if let Some(s) = self.servers.iter().find(|s| s.id == p.server) { send_to(s.sock.as_raw_fd(), &reply, &p.client); } } /// Sends pending query `at` again, through the host, once. - fn relay(&mut self, at: usize) { + fn relay(&mut self, at: usize) -> bool { if !self.pending[at].may_relay { - return; + return false; } self.pending[at].may_relay = false; let query = std::mem::take(&mut self.pending[at].query); @@ -640,7 +929,237 @@ impl Dns { if let Some(stream) = stream { p.sock = stream; p.relayed = Some(Vec::new()); + p.tcp_send = None; + p.tcp_recv.clear(); p.sent = Instant::now(); + true + } else { + false + } + } + + fn accept_tcp_clients(&mut self, listener: RawFd, server: u64) { + let container = self.servers.iter().find(|s| s.id == server).and_then(|s| s.container); + loop { + // SAFETY: sockaddr_in is plain data; accept4 fills it in. + let mut from: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: accept4 on a non-blocking TCP listener we own. + let fd = unsafe { libc::accept4(listener, (&mut from as *mut libc::sockaddr_in).cast(), &mut len, libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) }; + if fd < 0 { + break; + } + // SAFETY: fresh descriptor owned solely here. + let sock = unsafe { OwnedFd::from_raw_fd(fd) }; + if self.tcp_clients.len() >= MAX_TCP_CLIENTS { + continue; + } + let key = container.map_or_else(|| ClientKey::Ip(from.sin_addr.s_addr.to_ne_bytes()), ClientKey::Container); + self.tcp_clients.push(TcpClient { + id: server_id(), + server, + key, + sock, + recv: Vec::new(), + send: Vec::new(), + eof: false, + started: Instant::now(), + }); + } + } + + fn send_tcp_reply(&mut self, cid: u64, msg: &[u8]) { + let Ok(len) = u16::try_from(msg.len()) else { + self.drop_tcp_client(cid); + return; + }; + let Some(at) = self.tcp_clients.iter().position(|c| c.id == cid) else { return }; + if self.tcp_clients[at].send.len() + 2 + msg.len() > MAX_TCP_SEND { + self.drop_tcp_client(cid); + return; + } + self.tcp_clients[at].send.extend_from_slice(&len.to_be_bytes()); + self.tcp_clients[at].send.extend_from_slice(msg); + self.flush_tcp_client(at); + } + + fn flush_tcp_client(&mut self, at: usize) { + let fd = self.tcp_clients[at].sock.as_raw_fd(); + while !self.tcp_clients[at].send.is_empty() { + let buf = &self.tcp_clients[at].send; + // SAFETY: writing a buffer we own to a socket we own. + let n = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) }; + if n > 0 { + self.tcp_clients[at].send.drain(..n as usize); + self.tcp_clients[at].started = Instant::now(); + continue; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if err.kind() == io::ErrorKind::WouldBlock { + return; + } + let cid = self.tcp_clients[at].id; + self.drop_tcp_client(cid); + return; + } + let cid = self.tcp_clients[at].id; + if self.tcp_clients[at].eof && self.tcp_clients[at].send.is_empty() && !self.pending.iter().any(|p| p.tcp_client == Some(cid)) { + self.drop_tcp_client(cid); + } + } + + fn drop_tcp_client(&mut self, cid: u64) { + self.tcp_clients.retain(|c| c.id != cid); + } + + fn step_tcp_client(&mut self, at: usize, upstream: &[[u8; 4]]) { + let cid = self.tcp_clients[at].id; + let server_id_val = self.tcp_clients[at].server; + let key = self.tcp_clients[at].key; + if !self.tcp_clients[at].send.is_empty() { + self.flush_tcp_client(at); + } + let Some(at) = self.tcp_clients.iter().position(|c| c.id == cid) else { return }; + if !self.tcp_clients[at].send.is_empty() { + return; + } + let fd = self.tcp_clients[at].sock.as_raw_fd(); + let mut buf = [0u8; 4096]; + while !self.tcp_clients[at].eof { + // SAFETY: reading into a buffer we own from a non-blocking socket we own. + let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + self.tcp_clients[at].started = Instant::now(); + self.tcp_clients[at].recv.extend_from_slice(&buf[..n as usize]); + if self.tcp_clients[at].recv.len() > MAX_RELAYED { + self.drop_tcp_client(cid); + return; + } + continue; + } + if n == 0 { + self.tcp_clients[at].eof = true; + break; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if err.kind() == io::ErrorKind::WouldBlock { + break; + } + self.drop_tcp_client(cid); + return; + } + let Some(server) = self.servers.iter().position(|s| s.id == server_id_val) else { + self.drop_tcp_client(cid); + return; + }; + loop { + let Some(pos) = self.tcp_clients.iter().position(|c| c.id == cid) else { return }; + let Some(raw) = framed_reply(&self.tcp_clients[pos].recv) else { + if self.tcp_clients[pos].eof { + self.tcp_clients[pos].recv.clear(); + } + break; + }; + let query = raw.to_vec(); + let consumed = 2 + query.len(); + self.tcp_clients[pos].recv.drain(..consumed); + if query.len() < 12 || parse_question(&query).is_none() { + self.drop_tcp_client(cid); + return; + } + match self.answer(server, &query) { + Some(reply) => self.send_tcp_reply(cid, &reply), + None => { + // SAFETY: zeroed sockaddr_in placeholder; TCP replies use `cid`. + let placeholder: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + self.forward_with(server, &query, placeholder, Some(cid), key, upstream); + } + } + } + if let Some(pos) = self.tcp_clients.iter().position(|c| c.id == cid) { + self.flush_tcp_client(pos); + } + } + + fn step_tcp_upstream(&mut self, at: usize) { + let fd = self.pending[at].sock.as_raw_fd(); + while self.pending[at].tcp_send.as_ref().is_some_and(|b| !b.is_empty()) { + let buf = self.pending[at].tcp_send.as_ref().expect("checked"); + // SAFETY: writing a buffer we own to a non-blocking TCP socket we own. + let n = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) }; + if n > 0 { + if let Some(b) = &mut self.pending[at].tcp_send { + b.drain(..n as usize); + } + continue; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if matches!(err.raw_os_error(), Some(libc::EAGAIN | libc::EINPROGRESS)) || err.kind() == io::ErrorKind::WouldBlock { + return; + } + self.hand_over(at); + return; + } + let mut buf = [0u8; 4096]; + let mut eof = false; + loop { + // SAFETY: reading into a buffer we own from a non-blocking TCP socket we own. + let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + self.pending[at].tcp_recv.extend_from_slice(&buf[..n as usize]); + if self.pending[at].tcp_recv.len() > MAX_RELAYED { + self.hand_over(at); + return; + } + continue; + } + if n == 0 { + eof = true; + break; + } + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + continue; + } + if err.kind() == io::ErrorKind::WouldBlock { + break; + } + self.hand_over(at); + return; + } + if let Some(reply) = framed_reply(&self.pending[at].tcp_recv) { + let mut msg = reply.to_vec(); + let p = &self.pending[at]; + if msg.len() >= 12 && u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(&msg, p) { + if matches!(msg[3] & 0x0f, 2 | 5) { + if self.pending[at].own.is_some() && self.ask_next_own(at) { + return; + } + if self.pending[at].own.is_none() && self.ask_next_upstream(at) { + return; + } + } + if self.pending[at].own.is_none() && self.pending[at].may_relay && answer_has_fake_ip(&msg) { + self.prefer_relay = true; + if self.relay(at) { + return; + } + } + self.answered(at, &mut msg); + } else { + self.hand_over(at); + } + } else if eof { + self.hand_over(at); } } @@ -675,13 +1194,14 @@ impl Dns { if msg.len() >= 12 && u16::from_be_bytes([msg[0], msg[1]]) == p.our && response_matches(&msg, p) { self.answered(at, &mut msg); } else { - self.pending.swap_remove(at); + // A reply we can't use is still better answered than + // dropped: the client would only wait for its timeout. + self.fail(at); } } - // Gone before a whole reply: the client asks again. - None if eof => { - self.pending.swap_remove(at); - } + // Gone before a whole reply: answer SERVFAIL now, as with any + // other upstream that didn't answer (#715). + None if eof => self.fail(at), None => self.pending[at].relayed = Some(got), } } @@ -725,12 +1245,25 @@ impl Dns { } else if now.duration_since(p.sent) >= OWN_WAIT { self.hand_over(at); } - } else if p.may_relay && now.duration_since(p.sent) >= FALLBACK_AFTER { - self.relay(at); + } else if (p.upstream_at + 1 < p.upstreams.len() || p.may_relay) && now.duration_since(p.sent) >= FALLBACK_AFTER { + if !self.ask_next_upstream(at) { + self.relay(at); + } } else if now.duration_since(p.sent) >= FORWARD_TIMEOUT { - self.pending.swap_remove(at); + // An upstream that never answered must not leave the + // client to hit its own timeout with no reply at all. + self.fail(at); } } + let pending = &self.pending; + self.tcp_clients.retain(|c| { + let has_pending = pending.iter().any(|p| p.tcp_client == Some(c.id)); + if c.eof && c.send.is_empty() && !has_pending { + return false; + } + let limit = if has_pending { OWN_DEADLINE } else { FORWARD_TIMEOUT }; + now.duration_since(c.started) < limit + }); } /// Milliseconds until `on_timer` has something to do; -1 for never. @@ -739,17 +1272,22 @@ impl Dns { let left = |from: Instant, wait: Duration| wait.saturating_sub(now.duration_since(from)); self.pending .iter() - .filter_map(|p| { + .map(|p| { let due = if p.own.is_some() { left(p.sent, OWN_WAIT).min(left(p.started, OWN_DEADLINE)) - } else if p.may_relay { - left(p.sent, FALLBACK_AFTER) + } else if p.upstream_at + 1 < p.upstreams.len() || p.may_relay { + left(p.sent, FALLBACK_AFTER).min(left(p.sent, FORWARD_TIMEOUT)) } else { - // Swept by the next lookup (or `on_timer`), no wake-up for it. - return None; + // Even with no relay left, the query must be answered + // when its timeout expires, not only on the next lookup. + left(p.sent, FORWARD_TIMEOUT) }; - Some(wait_ms(due)) + wait_ms(due) }) + .chain(self.tcp_clients.iter().map(|c| { + let limit = if self.pending.iter().any(|p| p.tcp_client == Some(c.id)) { OWN_DEADLINE } else { FORWARD_TIMEOUT }; + wait_ms(left(c.started, limit)) + })) .min() .unwrap_or(-1) } @@ -778,6 +1316,18 @@ fn rd(q: &[u8]) -> bool { q.get(2).is_some_and(|f| f & 0x01 != 0) } +/// A NOERROR reply with zero answers (NODATA) for a query with this `id`, RD +/// flag and `question` section. +fn nodata(id: u16, rd: bool, question: &[u8]) -> Vec { + let mut r = Vec::with_capacity(12 + question.len()); + r.extend_from_slice(&id.to_be_bytes()); + r.extend_from_slice(&[0x80 | u8::from(rd), 0x80]); // response, RD as asked, recursion available, NOERROR + r.extend_from_slice(&1u16.to_be_bytes()); + r.extend_from_slice(&[0; 6]); + r.extend_from_slice(question); + r +} + /// A SERVFAIL for a query with this `id`, RD flag and `question` section. fn servfail(id: u16, rd: bool, question: &[u8]) -> Vec { let mut r = Vec::with_capacity(12 + question.len()); @@ -806,29 +1356,71 @@ fn ask(dest: [u8; 4], msg: &[u8]) -> Option { Some(sock) } +/// Dials `dest`:53 over UDP (`!tcp`) or non-blocking TCP (`tcp`). +fn ask_dest(dest: [u8; 4], msg: &[u8], tcp: bool) -> Option<(OwnedFd, Option>)> { + if tcp { ask_tcp(dest, msg).map(|(s, rem)| (s, Some(rem))) } else { ask(dest, msg).map(|s| (s, None)) } +} + +/// A non-blocking TCP socket connecting to `dest`:53 with framed `msg` queued +/// (and sent immediately when `connect` completes synchronously). +fn ask_tcp(dest: [u8; 4], msg: &[u8]) -> Option<(OwnedFd, Vec)> { + let len = u16::try_from(msg.len()).ok()?.to_be_bytes(); + let fd = sys::check( + unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) } as _, + "dns tcp socket", + ) + .ok()?; + // SAFETY: `fd` is fresh and ours. + let sock = unsafe { OwnedFd::from_raw_fd(fd as RawFd) }; + let to = sockaddr(dest, 53); + // SAFETY: connecting a socket we own to a valid sockaddr_in. + let rc = unsafe { libc::connect(sock.as_raw_fd(), (&to as *const libc::sockaddr_in).cast(), std::mem::size_of::() as u32) }; + if rc != 0 && io::Error::last_os_error().raw_os_error() != Some(libc::EINPROGRESS) { + return None; + } + let mut frame = Vec::with_capacity(2 + msg.len()); + frame.extend_from_slice(&len); + frame.extend_from_slice(msg); + if rc == 0 { + // SAFETY: writing a buffer we own on a connected non-blocking socket. + let n = unsafe { libc::write(sock.as_raw_fd(), frame.as_ptr().cast(), frame.len()) }; + if n > 0 { + frame.drain(..n as usize); + } + } + Some((sock, frame)) +} + /// The reply in `u16 len | reply`, once all of it is there. fn framed_reply(got: &[u8]) -> Option<&[u8]> { let len = u16::from_be_bytes([*got.first()?, *got.get(1)?]) as usize; got.get(2..2 + len) } -/// The embedded DNS's socket in a container's network namespace, which -/// the calling thread is in: on a free high port of 127.0.0.11, with -/// 127.0.0.11:53 redirected to it, as Docker does, so that a DNS server of -/// the container's own (dnsmasq, Pi-hole, CoreDNS, AdGuard) can bind -/// 0.0.0.0:53 while the container's lookups still reach this one. Where the -/// redirect can't be made (a kernel without nf_nat), port 53 itself. -fn embedded_socket() -> io::Result { +/// The embedded DNS's sockets (UDP and TCP) in a container's network +/// namespace, which the calling thread is in: on free high ports of +/// 127.0.0.11, with 127.0.0.11:53 (UDP and TCP) redirected to them, as Docker +/// does, so that a DNS server of the container's own (dnsmasq, Pi-hole, +/// CoreDNS, AdGuard) can bind 0.0.0.0:53 while the container's lookups still +/// reach this one. Where the redirect can't be made (a kernel without nf_nat), +/// port 53 itself. +fn embedded_socket() -> io::Result<(OwnedFd, Option)> { let sock = bound(EMBEDDED, 0)?; - match local_port(&sock).and_then(|port| super::netlink::redirect_embedded_dns(EMBEDDED, port)) { - Ok(()) => Ok(sock), + let (tcp, tcp_port) = match tcp_bound(EMBEDDED, 0).and_then(|t| local_port(&t).map(|p| (t, p))) { + Ok((t, p)) => (Some(t), Some(p)), + Err(_) => (None, None), + }; + let redirected = local_port(&sock).and_then(|up| super::netlink::redirect_embedded_dns(EMBEDDED, up, tcp_port)); + match redirected { + Ok(()) => Ok((sock, tcp)), Err(e) => { static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) { eprintln!("kiri-init: dns: no redirect to the embedded DNS ({e}); it takes port 53 in each container"); } - drop(sock); - bound(EMBEDDED, 53) + drop((sock, tcp)); + let udp53 = bound(EMBEDDED, 53)?; + Ok((udp53, tcp_bound(EMBEDDED, 53).ok())) } } } @@ -865,10 +1457,64 @@ fn bound(ip: [u8; 4], port: u16) -> io::Result { Ok(sock) } +/// A non-blocking TCP listening socket bound to `ip`:`port` (0: a free one). +fn tcp_bound(ip: [u8; 4], port: u16) -> io::Result { + // SAFETY: plain socket creation; owned immediately. + let fd = sys::check( + unsafe { libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) } as _, + "dns tcp listen socket", + )?; + // SAFETY: `fd` is fresh and ours. + let sock = unsafe { OwnedFd::from_raw_fd(fd as RawFd) }; + let one: libc::c_int = 1; + // SAFETY: valid integer option on a socket we own. + let _ = unsafe { libc::setsockopt(sock.as_raw_fd(), libc::SOL_SOCKET, libc::SO_REUSEADDR, (&one as *const libc::c_int).cast(), std::mem::size_of::() as u32) }; + let addr = sockaddr(ip, port); + // SAFETY: bind and listen on a socket we own with a sockaddr_in of its size. + sys::check( + unsafe { libc::bind(sock.as_raw_fd(), (&addr as *const libc::sockaddr_in).cast(), std::mem::size_of::() as u32) } as _, + "dns tcp bind", + )?; + sys::check(unsafe { libc::listen(sock.as_raw_fd(), 64) } as _, "dns tcp listen")?; + Ok(sock) +} + fn response_matches(msg: &[u8], pending: &Pending) -> bool { msg.get(2).is_some_and(|flags| flags & 0x80 != 0) && msg.get(12..12 + pending.question.len()).is_some_and(|question| question == pending.question) } +/// Whether a DNS reply carries an A record in `198.18.0.0/15` (RFC 2544 +/// benchmarking space, used by macOS security network extensions as a +/// synthetic Fake-IP range, #367), excluding `host.docker.internal`. +fn answer_has_fake_ip(msg: &[u8]) -> bool { + let Some((_, _, mut pos)) = parse_question(msg) else { return false }; + let ancount = u16::from_be_bytes([msg[6], msg[7]]) as usize; + for _ in 0..ancount { + loop { + let Some(&b) = msg.get(pos) else { return false }; + if b == 0 { + pos += 1; + break; + } + if b & 0xc0 == 0xc0 { + pos += 2; + break; + } + pos += 1 + (b as usize); + } + let Some(hdr) = msg.get(pos..pos + 10) else { return false }; + let rtype = u16::from_be_bytes([hdr[0], hdr[1]]); + let rdlen = u16::from_be_bytes([hdr[8], hdr[9]]) as usize; + pos += 10; + let Some(rdata) = msg.get(pos..pos + rdlen) else { return false }; + if rtype == 1 && rdlen == 4 && rdata[0] == 198 && (rdata[1] & 0xfe) == 18 && rdata != super::net::HOST_ADDR { + return true; + } + pos += rdlen; + } + false +} + fn random_id() -> Option { let mut bytes = [0u8; 2]; std::fs::File::open("/dev/urandom").ok()?.read_exact(&mut bytes).ok()?; @@ -906,6 +1552,25 @@ fn parse_question(q: &[u8]) -> Option<(String, u16, usize)> { Some((name, qtype, i + 4)) } +/// The container (or host) name a service query is about, when every label +/// before it is a non-empty underscore selector: gRPC looks up +/// `_grpclb._tcp.` as an SRV record before asking for the name's A +/// records. Such a name belongs to this network, so it is answered here +/// (NODATA) rather than forwarded to an upstream that may never answer (#715). +fn service_base(name: &str, known: impl Fn(&str) -> bool) -> Option<&str> { + let mut rest = name; + while let Some((label, tail)) = rest.split_once('.') { + if label.len() <= 1 || !label.starts_with('_') { + return None; + } + if known(tail) { + return Some(tail); + } + rest = tail; + } + None +} + #[cfg(test)] mod tests { use super::{Dns, Pending, Server, response_matches, udp_socket}; @@ -926,12 +1591,23 @@ mod tests { assert_eq!((r[3] & 0x0f, answers(&r, q6.len()).len()), (0, 0)); let q = query("gateway.docker.internal", 255); assert_eq!(answers(&dns.answer(0, &q).unwrap(), q.len()), [(1, super::super::net::HOST_ADDR.to_vec())]); + // Non-host queries must not invoke the host IP lookup callback at all. + assert!(dns.answer_with_host_fn(0, other, || panic!("host IP lookup called for non-host query")).is_none()); + // On WSL 2 with Windows host relay active, all host names answer 192.168.65.254 (A) and NODATA (AAAA). + let wsl = super::super::net::WSL_HOST_ADDR; + for name in ["host.docker.internal", "host.kiri.internal", "gateway.docker.internal"] { + let qa = query(name, 1); + assert_eq!(answers(&dns.answer_with_host(0, &qa, wsl).unwrap(), qa.len()), [(1, wsl.to_vec())], "{name} A"); + let qaaaa = query(name, 28); + let r = dns.answer_with_host(0, &qaaaa, wsl).unwrap(); + assert_eq!((r[3] & 0x0f, answers(&r, qaaaa.len()).len()), (0, 0), "{name} AAAA NODATA"); + } } #[test] fn a_containers_server_answers_for_each_of_its_networks() { let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some((42, [10, 5, 0, 2])) }); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some(42) }); dns.register("kiri1", ["web"].iter(), [10, 5, 0, 3]); dns.register("kiri2", ["db"].iter(), [10, 6, 0, 3]); let q = query("db", 1); @@ -944,6 +1620,147 @@ mod tests { assert!(dns.servers.is_empty()); } + /// #715: gRPC looks up `_grpclb._tcp.` before the name's A + /// records. The service belongs to this network, so answer NODATA + /// instead of forwarding a query only an upstream can time out on. + #[test] + fn service_names_of_known_containers_are_answered_nodata() { + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + dns.register("kiri1", ["temporal", "api.myproj"].iter(), [10, 5, 0, 3]); + let v6 = [0xfd, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4]; + dns.register("kiri1", ["_app.temporal"].iter(), [10, 5, 0, 4]); + dns.register6("kiri1", ["_app.temporal"].iter(), [10, 5, 0, 4], v6); + for name in ["_grpclb._tcp.temporal", "_http._tcp.api.myproj", "_grpclb._tcp._app.temporal", "_grpclb._tcp.host.docker.internal"] { + for qtype in [33, 1, 28] { + let q = query(name, qtype); + let r = dns.answer(0, &q).unwrap_or_else(|| panic!("{name} (qtype {qtype}) is answered here, not forwarded")); + assert_eq!((r[3] & 0x0f, answers(&r, q.len()).len()), (0, 0), "{name} (qtype {qtype}): NOERROR with no records"); + assert_eq!(&r[12..q.len()], &q[12..], "the question is echoed back"); + } + } + // A registered alias starting with `_` answers its own A/AAAA records, not NODATA. + let q = query("_app.temporal", 1); + assert_eq!(answers(&dns.answer(0, &q).unwrap(), q.len()), [(1, vec![10, 5, 0, 4])]); + let q6 = query("_app.temporal", 28); + assert_eq!(answers(&dns.answer(0, &q6).unwrap(), q6.len()), [(28, v6.to_vec())]); + // A service under a name we don't know, or with a non-selector label, is forwarded. + for unknown in ["_grpclb._tcp.other", "foo._tcp.temporal", "_.temporal", "_grpclb._.temporal"] { + assert!(dns.answer(0, &query(unknown, 33)).is_none(), "{unknown} must not match"); + } + } + + /// #715: a forwarded query whose upstream never answers must get a + /// SERVFAIL rather than being dropped, leaving Go's resolver to hit + /// its own timeout with no reply at all from 127.0.0.11. + #[test] + fn a_forwarded_query_that_times_out_gets_servfail() { + use std::os::fd::AsRawFd; + use std::time::{Duration, Instant}; + let bind = |ip: [u8; 4]| { + let s = udp_socket().unwrap(); + let a = super::sockaddr(ip, 0); + assert_eq!(unsafe { libc::bind(s.as_raw_fd(), (&a as *const libc::sockaddr_in).cast(), std::mem::size_of::() as u32) }, 0, "bind"); + s + }; + let addr = |fd: i32| { + let mut a: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as u32; + unsafe { libc::getsockname(fd, (&mut a as *mut libc::sockaddr_in).cast(), &mut len) }; + a + }; + let server = bind([127, 0, 0, 3]); + let client = bind([127, 0, 0, 1]); + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: server, container: None }); + let q = query("example.com", 1); + dns.forward(0, &q, addr(client.as_raw_fd()), &[[127, 0, 0, 65]]); + let p = dns.pending.last_mut().expect("forwarded"); + p.sent = Instant::now() - Duration::from_secs(10); + p.may_relay = false; // no host relay left to wait for + dns.on_timer(); + assert!(dns.pending.is_empty(), "the query is done"); + let mut buf = [0u8; 512]; + let n = { + let mut got = None; + for _ in 0..100 { + let n = unsafe { libc::recv(client.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), 0) }; + if n > 12 { + got = Some(n); + break; + } + std::thread::sleep(Duration::from_millis(10)); + } + got.expect("the client got a reply") + }; + assert_eq!(&buf[2..4], &[0x81, 0x82], "recursion available, SERVFAIL"); + assert_eq!(&buf[12..n as usize], &q[12..], "the question is echoed back"); + } + + /// `on_readable` runs before `on_timer`: a retry arriving at or after + /// `FORWARD_TIMEOUT` must answer the expired query SERVFAIL rather than + /// sweeping it silently. + #[test] + fn an_expired_query_is_answered_servfail_when_the_next_arrives() { + let ip = [127, 0, 0, 66]; + let _held = std::net::UdpSocket::from(super::bound(ip, 53).unwrap()); + let (client, from) = client(); + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + let mut first = query("example.com", 1); + first[0..2].copy_from_slice(&0x1111u16.to_be_bytes()); + dns.forward(0, &first, from, &[ip]); + dns.pending[0].sent = Instant::now() - super::FORWARD_TIMEOUT; + let mut retry = query("example.com", 1); + retry[0..2].copy_from_slice(&0x2222u16.to_be_bytes()); + dns.forward(0, &retry, from, &[ip]); + assert_eq!(dns.pending.len(), 1, "only the retry stays in flight"); + assert_eq!(dns.pending[0].id, 0x2222); + assert_eq!(told(&client, 1000), Some((0x1111, 2)), "the expired query got SERVFAIL"); + } + + /// On a Linux host (`relay == false`, `own.is_none()`), a query with no + /// upstream or an upstream that cannot be sent to is answered SERVFAIL + /// at once rather than dropped silently. + #[test] + fn a_query_with_no_reachable_upstream_is_answered_servfail_at_once() { + let (client, from) = client(); + let mut dns = Dns::default(); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + for (id, upstream) in [(0x3333u16, &[][..]), (0x4444, &[[255, 255, 255, 255]][..])] { + let mut q = query("example.com", 1); + q[0..2].copy_from_slice(&id.to_be_bytes()); + dns.forward(0, &q, from, upstream); + assert!(dns.pending.is_empty()); + assert_eq!(told(&client, 1000), Some((id, 2)), "id {id:#x} got SERVFAIL at once"); + } + } + + /// When the UDP upstream refuses the packet (`ECONNREFUSED`) and no host + /// relay can take it (either `relay == false` on a Linux host or the + /// host relay is unavailable), the query is answered SERVFAIL at once + /// rather than waiting `FORWARD_TIMEOUT` on a dead socket. + #[test] + fn a_refused_upstream_with_no_host_relay_answers_servfail_at_once() { + use std::os::fd::AsRawFd; + let (client, from) = client(); + let refused_ip = [127, 0, 0, 67]; + for (id, relay) in [(0x5555u16, false), (0x6666, true)] { + let mut dns = Dns { relay, ..Default::default() }; + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + let mut q = query("example.com", 1); + q[0..2].copy_from_slice(&id.to_be_bytes()); + dns.forward(0, &q, from, &[refused_ip]); + assert_eq!(dns.pending.len(), 1); + let fd = dns.pending[0].sock.as_raw_fd(); + wait_readable(fd); + dns.on_readable(fd, &[refused_ip]); + assert!(dns.pending.is_empty(), "relay={relay}: no dead entry left waiting"); + assert_eq!(told(&client, 1000), Some((id, 2)), "relay={relay}: SERVFAIL at once"); + assert_eq!(dns.relay_down_until.is_some(), relay); + } + } + /// #294: a container on its project's network and on a shared one, both /// with a `db`, joining the shared one first. Docker searches the /// networks by name, whatever the join order. @@ -952,7 +1769,7 @@ mod tests { // (shared network, project network, which one answers) for (shared, project, shared_answers) in [("kiri_shared_t", "kra_default", true), ("ddev_default", "ddev-a_default", false), ("zz_shared", "kca_default", false)] { let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some((42, [10, 1, 0, 2])) }); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into(), "kiri2".into()], sock: udp_socket().unwrap(), container: Some(42) }); dns.name_network("kiri1", shared); dns.name_network("kiri2", project); // This project's db on both networks, another project's on the shared one. @@ -1069,10 +1886,9 @@ mod tests { let from = super::sockaddr(addr.ip().octets(), addr.port()); // One server still works; refusals move through the list in order. for servers in [vec![resolver_ip], vec![[127, 0, 0, 4], resolver_ip], vec![[127, 0, 0, 4], [127, 0, 0, 6], resolver_ip]] { - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, servers.clone()); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, servers.clone()); let q = query("example.com", 1); dns.forward(0, &q, from, &[]); assert_eq!(dns.pending.len(), 1); @@ -1126,10 +1942,9 @@ mod tests { let client = UdpSocket::bind("127.0.0.1:0").unwrap(); let std::net::SocketAddr::V4(addr) = client.local_addr().unwrap() else { panic!() }; let from = super::sockaddr(addr.ip().octets(), addr.port()); - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![unsendable, resolver_ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![unsendable, resolver_ip]); dns.forward(0, &query("example.com", 1), from, &[]); assert_eq!(dns.pending.len(), 1); assert_eq!(peer(dns.pending[0].sock.as_raw_fd()), resolver_ip, "the server that can't be sent to was skipped"); @@ -1139,8 +1954,8 @@ mod tests { assert_eq!(&buf[..n], &dns.pending[0].query[..]); // With nothing to send to, no query is kept and the host is not asked. let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![unsendable]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![unsendable]); dns.forward(0, &query("example.com", 1), from, &[]); assert!(dns.pending.is_empty()); assert!(dns.relay_down_until.is_none(), "no host relay was tried"); @@ -1164,7 +1979,6 @@ mod tests { let client = UdpSocket::bind("127.0.0.1:0").unwrap(); let std::net::SocketAddr::V4(addr) = client.local_addr().unwrap() else { panic!() }; let from = super::sockaddr(addr.ip().octets(), addr.port()); - let owner = [10, 5, 0, 2]; // Answers the query waiting at `server` with `rcode`. let reply = |server: &UdpSocket, rcode: u8| { let mut buf = [0u8; 512]; @@ -1177,8 +1991,8 @@ mod tests { }; for (rcode, servers, answered_by) in [(5u8, vec![first_ip, second_ip], 1usize), (2, vec![first_ip, second_ip], 1), (5, vec![first_ip], 0)] { let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, servers.clone()); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, servers.clone()); let q = query("example.com", 1); dns.forward(0, &q, from, &[]); reply(&first, rcode); @@ -1232,10 +2046,9 @@ mod tests { let _silent = std::net::UdpSocket::from(super::bound(silent_ip, 53).unwrap()); let next = std::net::UdpSocket::from(super::bound(next_ip, 53).unwrap()); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![silent_ip, next_ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![silent_ip, next_ip]); let q = query("example.com", 1); dns.forward(0, &q, from, &[]); let first_query = dns.pending[0].query.clone(); @@ -1278,10 +2091,9 @@ mod tests { let (client, from) = client(); for servers in [vec![[127, 0, 0, 7]], vec![[127, 0, 0, 7], [127, 0, 0, 8]]] { let attempts = servers.len(); - let owner = [10, 5, 0, 2]; let mut dns = Dns { relay: true, ..Default::default() }; - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, servers); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, servers); let q = query("example.com", 1); dns.forward(0, &q, from, &[vm_ip]); assert_eq!(dns.pending.len(), 1); @@ -1318,10 +2130,9 @@ mod tests { let ips = [[127, 0, 0, 30], [127, 0, 0, 31], [127, 0, 0, 32]]; let _held: Vec<_> = ips.iter().map(|ip| std::net::UdpSocket::from(super::bound(*ip, 53).unwrap())).collect(); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, ips.to_vec()); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, ips.to_vec()); dns.forward(0, &query("example.com", 1), from, &[]); dns.pending[0].started = Instant::now() - super::OWN_DEADLINE; dns.pending[0].sent = Instant::now(); @@ -1355,10 +2166,9 @@ mod tests { let _a = std::net::UdpSocket::from(super::bound(a, 53).unwrap()); let _b = std::net::UdpSocket::from(super::bound(b, 53).unwrap()); let (_client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![a, b]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![a, b]); dns.forward(0, &query("example.com", 1), from, &[]); let first = dns.pending[0].our; assert_eq!(peer(dns.pending[0].sock.as_raw_fd()), a); @@ -1373,9 +2183,16 @@ mod tests { fn own_servers_go_with_the_container() { let mut dns = Dns::default(); dns.set_upstream([10, 5, 0, 2], vec![[8, 8, 8, 8]]); + dns.set_container_upstream(42, vec![[8, 8, 8, 8]]); assert_eq!(dns.clients.get(&[10, 5, 0, 2]), Some(&vec![[8, 8, 8, 8]])); + assert_eq!(dns.container_upstream(42), Some(vec![[8, 8, 8, 8]])); dns.unregister("kiri1", [10, 5, 0, 2]); assert!(dns.clients.is_empty()); + assert_eq!(dns.container_upstream(42), Some(vec![[8, 8, 8, 8]]), "disconnection keeps 127.0.0.11 --dns servers"); + dns.leave(42, "kiri1"); + assert_eq!(dns.container_upstream(42), Some(vec![[8, 8, 8, 8]])); + dns.drop_container(42); + assert!(dns.container_upstreams.is_empty()); dns.set_upstream([10, 5, 0, 3], vec![]); assert!(dns.clients.is_empty()); } @@ -1386,17 +2203,32 @@ mod tests { fn a_containers_queries_in_flight_go_with_it() { let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); + let gw_id = super::server_id(); + dns.servers.push(Server { id: gw_id, bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: None }); + let c_id = super::server_id(); + dns.servers.push(Server { id: c_id, bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); dns.set_upstream(owner, vec![[127, 0, 0, 1], [127, 0, 0, 2]]); let mut p = pending(); - p.key = owner; + p.server = gw_id; + p.key = super::ClientKey::Ip(owner); p.own = Some(0); dns.pending.push(p); let mut other = pending(); - other.key = [10, 5, 0, 3]; + other.server = gw_id; + other.key = super::ClientKey::Ip([10, 5, 0, 3]); dns.pending.push(other); + let mut in_ns = pending(); + in_ns.server = c_id; + in_ns.key = super::ClientKey::Container(42); + in_ns.own = Some(0); + dns.pending.push(in_ns); dns.unregister("kiri1", owner); + assert_eq!(dns.pending.len(), 2, "gateway queries for left IP go; 127.0.0.11 and another IP stay"); + assert_eq!(dns.pending[0].key, super::ClientKey::Ip([10, 5, 0, 3]), "another container's stay"); + assert_eq!(dns.pending[1].key, super::ClientKey::Container(42)); + dns.drop_container(42); assert_eq!(dns.pending.len(), 1); - assert_eq!(dns.pending[0].key, [10, 5, 0, 3], "another container's stay"); + assert_eq!(dns.pending[0].key, super::ClientKey::Ip([10, 5, 0, 3])); } /// A query names the server it came in on by a number that is never @@ -1435,13 +2267,12 @@ mod tests { let ip = [127, 0, 0, 61]; let _held = std::net::UdpSocket::from(super::bound(ip, 53).unwrap()); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![ip]); for _ in 0..super::MAX_OWN_PER_CLIENT { let mut p = pending(); - p.key = owner; + p.key = super::ClientKey::Container(42); p.own = Some(0); p.server = dns.servers[0].id; p.client = from; @@ -1462,10 +2293,9 @@ mod tests { let ip = [127, 0, 0, 62]; let _held = std::net::UdpSocket::from(super::bound(ip, 53).unwrap()); let (client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![ip]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![ip]); for _ in 0..super::MAX_OWN_PER_CLIENT { dns.forward(0, &query("example.com", 1), from, &[]); } @@ -1486,10 +2316,9 @@ mod tests { let next = std::net::UdpSocket::from(super::bound(b, 53).unwrap()); next.set_nonblocking(true).unwrap(); let (_client, from) = client(); - let owner = [10, 5, 0, 2]; let mut dns = Dns::default(); - dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some((42, owner)) }); - dns.set_upstream(owner, vec![a, b]); + dns.servers.push(Server { id: super::server_id(), bridges: vec!["kiri1".into()], sock: udp_socket().unwrap(), container: Some(42) }); + dns.set_container_upstream(42, vec![a, b]); dns.forward(0, &query("example.com", 1), from, &[]); let sent = dns.pending[0].query.clone(); dns.pending[0].started = Instant::now() - super::OWN_DEADLINE; @@ -1648,18 +2477,244 @@ mod tests { Pending { sock: udp_socket().unwrap(), our: 1, - key: [0; 4], + key: super::ClientKey::Ip([0; 4]), server: 0, client: unsafe { std::mem::zeroed() }, + tcp_client: None, id: 7, question: b"\x03www\x07example\x03com\x00\x00\x01\x00\x01".to_vec(), sent: Instant::now(), query: Vec::new(), own: None, + upstreams: Vec::new(), + upstream_at: 0, started: Instant::now(), may_relay: false, relayed: None, + tcp_send: None, + tcp_recv: Vec::new(), + } + } + + #[test] + fn host_upstreams_fall_back_when_stub_refuses_and_tcp_dns_answers_local_and_forwarded() { + use std::io::{Read, Write}; + use std::os::fd::AsRawFd; + + // 1. UDP upstream fallback: a refusing loopback stub (127.0.0.68) + // hands over to the secondary upstream (127.0.0.69:53) (#330). + let stub_refused = [127, 0, 0, 68]; + let fallback_ip = [127, 0, 0, 69]; + let fallback_udp = std::net::UdpSocket::from(super::bound(fallback_ip, 53).unwrap()); + let fallback_tcp = std::net::TcpListener::from(super::tcp_bound(fallback_ip, 53).unwrap()); + fallback_tcp.set_nonblocking(false).unwrap(); + let (client_udp, from) = client(); + let mut dns = Dns::default(); + let sid = super::server_id(); + let tcp_listener = super::tcp_bound([127, 0, 0, 1], 0).unwrap(); + let tcp_port = super::local_port(&tcp_listener).unwrap(); + dns.servers.push(Server { id: sid, bridges: vec!["kiri0".into()], sock: udp_socket().unwrap(), container: None }); + dns.tcp_servers.push((sid, tcp_listener)); + dns.register("kiri0", ["svc"].iter(), [172, 17, 0, 9]); + + let q = query("example.com", 1); + dns.forward(0, &q, from, &[stub_refused, fallback_ip]); + assert_eq!(dns.pending.len(), 1); + let fd0 = dns.pending[0].sock.as_raw_fd(); + wait_readable(fd0); + dns.on_readable(fd0, &[stub_refused, fallback_ip]); + assert_eq!(dns.pending.len(), 1, "handed over to fallback upstream"); + assert_eq!(peer(dns.pending[0].sock.as_raw_fd()), fallback_ip); + let mut buf = [0u8; 512]; + wait_readable(fallback_udp.as_raw_fd()); + let (n, peer_addr) = fallback_udp.recv_from(&mut buf).unwrap(); + buf[2] |= 0x80; + fallback_udp.send_to(&buf[..n], peer_addr).unwrap(); + let fd1 = dns.pending[0].sock.as_raw_fd(); + wait_readable(fd1); + dns.on_readable(fd1, &[stub_refused, fallback_ip]); + assert_eq!(told(&client_udp, 1000), Some((u16::from_be_bytes([q[0], q[1]]), 0))); + + // 2. TCP DNS listener: local network name (`svc`) and forwarded large + // upstream reply (>512 bytes, as after TC=1 in `bun install`, #330). + let upstream_worker = std::thread::spawn(move || { + let (mut s, _) = fallback_tcp.accept().unwrap(); + let mut len = [0u8; 2]; + s.read_exact(&mut len).unwrap(); + let mut uq = vec![0u8; u16::from_be_bytes(len) as usize]; + s.read_exact(&mut uq).unwrap(); + let mut reply = uq; + reply[2] = 0x81; + reply[3] = 0x80; + reply[6..8].copy_from_slice(&40u16.to_be_bytes()); + for i in 0..40u8 { + reply.extend_from_slice(&[0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 104, 16, 0, i]); + } + assert!(reply.len() > 600); + s.write_all(&(reply.len() as u16).to_be_bytes()).unwrap(); + s.write_all(&reply).unwrap(); + }); + + let client_worker = std::thread::spawn(move || { + let mut c = std::net::TcpStream::connect(("127.0.0.1", tcp_port)).unwrap(); + // First query: local container name `svc` -> 172.17.0.9. + let q1 = query("svc", 1); + c.write_all(&(q1.len() as u16).to_be_bytes()).unwrap(); + c.write_all(&q1).unwrap(); + let mut rlen = [0u8; 2]; + c.read_exact(&mut rlen).unwrap(); + let mut r1 = vec![0u8; u16::from_be_bytes(rlen) as usize]; + c.read_exact(&mut r1).unwrap(); + assert_eq!(&r1[r1.len() - 4..], &[172, 17, 0, 9]); + + // Second query on the same TCP stream: external large response via fallback_tcp. + let mut q2 = query("registry.npmjs.org", 1); + q2[0..2].copy_from_slice(&0x4242u16.to_be_bytes()); + c.write_all(&(q2.len() as u16).to_be_bytes()).unwrap(); + c.write_all(&q2).unwrap(); + c.read_exact(&mut rlen).unwrap(); + let mut r2 = vec![0u8; u16::from_be_bytes(rlen) as usize]; + c.read_exact(&mut r2).unwrap(); + assert!(r2.len() > 600); + assert_eq!(&r2[0..2], &[0x42, 0x42]); + assert_eq!(u16::from_be_bytes([r2[6], r2[7]]), 40); + }); + + let deadline = Instant::now() + std::time::Duration::from_secs(5); + while !client_worker.is_finished() && Instant::now() < deadline { + let mut fds = Vec::new(); + dns.interest(&mut fds); + let rc = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as _, 20) }; + if rc > 0 { + for pfd in fds { + if pfd.revents != 0 && dns.owns(pfd.fd) { + dns.on_readable(pfd.fd, &[stub_refused, fallback_ip]); + } + } + } + dns.on_timer(); } + client_worker.join().unwrap(); + upstream_worker.join().unwrap(); + } + + #[test] + fn multiple_timed_out_queries_on_a_closed_tcp_client_never_panic_and_tcp_interest_respects_eof_and_backpressure() { + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::time::Duration; + + let mut dns = Dns::default(); + let sid = super::server_id(); + dns.servers.push(Server { id: sid, bridges: vec!["kiri0".into()], sock: udp_socket().unwrap(), container: Some(77) }); + + // 1. >=3 timed-out/failing queries on a closed/reset TCP client: + // when `flush_tcp_client` drops the broken client on the first EPIPE, + // `drop_tcp_client` must not mutate `self.pending` while `on_timer` or + // `forward_with` walks `self.pending` by index. + for sweep_in_forward in [false, true] { + let mut fds = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds.as_mut_ptr()) }, 0); + let (server_end, client_end) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }; + drop(client_end); // close peer immediately so writes fail with EPIPE + let cid = super::server_id(); + dns.tcp_clients.push(super::TcpClient { + id: cid, + server: sid, + key: super::ClientKey::Container(77), + sock: server_end, + recv: Vec::new(), + send: Vec::new(), + eof: false, + started: Instant::now(), + }); + for qid in [1u16, 2, 3, 4] { + let mut p = pending(); + p.id = qid; + p.server = sid; + p.key = super::ClientKey::Container(77); + p.tcp_client = Some(cid); + p.sent = Instant::now() - super::FORWARD_TIMEOUT - Duration::from_secs(1); + dns.pending.push(p); + } + if sweep_in_forward { + let q = query("example.com", 1); + let placeholder: libc::sockaddr_in = unsafe { std::mem::zeroed() }; + dns.forward_with(0, &q, placeholder, Some(cid), super::ClientKey::Container(77), &[]); + } else { + dns.on_timer(); + } + assert!(dns.pending.is_empty(), "all 4 expired TCP queries failed cleanly without index panic"); + assert!(dns.tcp_clients.is_empty(), "broken TCP client was dropped"); + } + + // 2. EOF clears trailing incomplete frame, suppresses POLLIN in interest(), + // and reaps the client once pending queries finish; non-empty send buffer + // polls POLLOUT without POLLIN and drops the client if MAX_TCP_SEND is exceeded. + let mut fds = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds.as_mut_ptr()) }, 0); + let (server_end, client_end) = unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }; + let cid = super::server_id(); + let sock_fd = server_end.as_raw_fd(); + dns.tcp_clients.push(super::TcpClient { + id: cid, + server: sid, + key: super::ClientKey::Container(77), + sock: server_end, + recv: vec![0, 20, 1, 2], // incomplete frame + send: vec![1, 2, 3], + eof: false, + started: Instant::now() - Duration::from_secs(3), + }); + let mut pollfds = Vec::new(); + dns.interest(&mut pollfds); + let c_pfd = pollfds.iter().find(|p| p.fd == sock_fd).expect("polled for POLLOUT"); + assert_eq!(c_pfd.events, libc::POLLOUT, "no POLLIN while send buffer is non-empty"); + + // Shut down client write half so read returns 0 (EOF) while a pending query is in flight. + unsafe { libc::shutdown(client_end.as_raw_fd(), libc::SHUT_WR) }; + let mut p = pending(); + p.server = sid; + p.key = super::ClientKey::Container(77); + p.tcp_client = Some(cid); + dns.pending.push(p); + + // Drain send buffer and step client to hit EOF. + dns.step_tcp_client(0, &[]); + let mut drain = [0u8; 16]; + let _ = unsafe { libc::read(client_end.as_raw_fd(), drain.as_mut_ptr().cast(), drain.len()) }; + dns.step_tcp_client(0, &[]); + assert_eq!(dns.tcp_clients.len(), 1, "kept while pending query is in flight"); + assert!(dns.tcp_clients[0].eof, "marked eof"); + assert!(dns.tcp_clients[0].recv.is_empty(), "incomplete frame cleared on eof"); + + pollfds.clear(); + dns.interest(&mut pollfds); + assert!(pollfds.iter().all(|p| p.fd != sock_fd), "half-closed idle TCP client is not polled for POLLIN"); + + // Exceeding MAX_TCP_SEND drops the client; or once pending finishes, eof client is reaped. + dns.pending.clear(); + dns.on_timer(); + assert!(dns.tcp_clients.is_empty(), "reaped once eof, send empty, and no pending query"); + + // Verify MAX_TCP_SEND cap and that unregister(Ip) never drops ClientKey::Container clients. + let mut fds2 = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_NONBLOCK, 0, fds2.as_mut_ptr()) }, 0); + let (s2, _c2) = unsafe { (OwnedFd::from_raw_fd(fds2[0]), OwnedFd::from_raw_fd(fds2[1])) }; + let cid2 = super::server_id(); + dns.tcp_clients.push(super::TcpClient { + id: cid2, + server: sid, + key: super::ClientKey::Container(77), + sock: s2, + recv: Vec::new(), + send: vec![0u8; super::MAX_TCP_SEND - 10], + eof: false, + started: Instant::now(), + }); + dns.unregister("kiri0", [172, 17, 0, 2]); + assert_eq!(dns.tcp_clients.len(), 1, "unregistering an IP never drops a Container TCP client"); + dns.send_tcp_reply(cid2, &[0u8; 32]); + assert!(dns.tcp_clients.is_empty(), "client exceeding MAX_TCP_SEND is dropped"); } /// The default bridge moved off a subnet the host took (#489): its @@ -1685,7 +2740,7 @@ mod tests { let client = super::sockaddr([172, 17, 0, 2], 4000); for _ in 0..super::MAX_PER_CLIENT { let mut p = pending(); - p.key = [172, 17, 0, 2]; + p.key = super::ClientKey::Ip([172, 17, 0, 2]); dns.pending.push(p); } let q = query("example.com", 1); @@ -1722,7 +2777,10 @@ mod tests { let mut dns = Dns::default(); assert_eq!(dns.timeout_ms(), -1, "nothing pending"); dns.pending.push(pending()); - assert_eq!(dns.timeout_ms(), -1, "nothing to hand over"); + // With no host to try, the query still needs a wake-up at its + // timeout so it gets a SERVFAIL instead of being left unanswered. + let t = dns.timeout_ms(); + assert!((4000..=5000).contains(&t), "only the forward wait: {t}"); let mut p = pending(); p.may_relay = true; dns.pending.push(p); @@ -1733,6 +2791,13 @@ mod tests { assert_eq!(dns.timeout_ms(), 0); dns.on_timer(); assert!(!dns.pending[1].may_relay); + let t = dns.timeout_ms(); + assert!((3000..=5000).contains(&t), "the relayed query still has its wait: {t}"); + for p in &mut dns.pending { + p.sent = Instant::now() - super::FORWARD_TIMEOUT; + } + dns.on_timer(); + assert!(dns.pending.is_empty(), "both queries answered at their timeout"); assert_eq!(dns.timeout_ms(), -1); } @@ -1817,4 +2882,57 @@ mod tests { response[2] = 0x01; assert!(!response_matches(&response, &p)); } + + #[test] + fn detects_fake_ip_answers_in_198_18_range_and_ignores_real_or_host_ips() { + let mut msg = query("registry.npmjs.org", 1); + msg[2] = 0x81; + msg[3] = 0x80; + msg[6..8].copy_from_slice(&1u16.to_be_bytes()); + // Name pointer 0xc00c, type A (1), class IN (1), TTL 60, rdlen 4, rdata + msg.extend_from_slice(&[0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 198, 18, 2, 3]); + let rdata_off = msg.len() - 4; + assert!(super::answer_has_fake_ip(&msg), "198.18.2.3 is a Fake-IP answer (#367)"); + msg[rdata_off..].copy_from_slice(&[198, 19, 0, 42]); + assert!(super::answer_has_fake_ip(&msg), "198.19.0.42 is in 198.18.0.0/15"); + msg[rdata_off..].copy_from_slice(&super::super::net::HOST_ADDR); + assert!(!super::answer_has_fake_ip(&msg), "host.docker.internal is not a Fake-IP"); + msg[rdata_off..].copy_from_slice(&[104, 16, 25, 34]); + assert!(!super::answer_has_fake_ip(&msg), "real public IP is not a Fake-IP"); + } + + #[test] + fn ipv4_only_server_answers_external_aaaa_with_nodata_while_ipv6_forwards() { + use std::net::UdpSocket; + use std::os::fd::AsRawFd; + + let mut dns = Dns::default(); + let gw = UdpSocket::bind("127.0.0.1:0").unwrap(); + gw.set_nonblocking(true).unwrap(); + let gw_addr = gw.local_addr().unwrap(); + dns.servers.push(super::Server { id: super::server_id(), bridges: vec!["kiri0".into()], sock: gw.into(), container: None }); + + let client = UdpSocket::bind("127.0.0.1:0").unwrap(); + client.set_read_timeout(Some(std::time::Duration::from_secs(2))).unwrap(); + + // 1. IPv4-only bridge: external AAAA gets immediate NOERROR/NODATA without upstream traffic. + let q_aaaa = query("registry-1.docker.io", 28); + client.send_to(&q_aaaa, gw_addr).unwrap(); + let srv_fd = dns.servers[0].sock.as_raw_fd(); + wait_readable(srv_fd); + dns.on_readable(srv_fd, &[[127, 0, 0, 71]]); + assert!(dns.pending.is_empty(), "IPv4-only server must not forward external AAAA upstream"); + let mut reply = [0u8; 512]; + let n = client.recv(&mut reply).unwrap(); + assert_eq!(reply[3] & 0x0f, 0, "NOERROR"); + assert_eq!(u16::from_be_bytes([reply[6], reply[7]]), 0, "zero answers (NODATA)"); + assert!(n >= q_aaaa.len()); + + // 2. Enabling IPv6 on the bridge allows external AAAA queries to forward upstream. + dns.set_bridge_ipv6("kiri0", true); + client.send_to(&q_aaaa, gw_addr).unwrap(); + wait_readable(srv_fd); + dns.on_readable(srv_fd, &[[127, 0, 0, 71]]); + assert_eq!(dns.pending.len(), 1, "IPv6-enabled bridge forwards external AAAA upstream"); + } } diff --git a/crates/kiri-init/src/linux/firewall.rs b/crates/kiri-init/src/linux/firewall.rs index 644f2ee49..e63aa7cb0 100644 --- a/crates/kiri-init/src/linux/firewall.rs +++ b/crates/kiri-init/src/linux/firewall.rs @@ -5,18 +5,21 @@ //! table accepting its containers' traffic is not enough when the host has //! another forward chain that drops what it does not know: //! -//! - iptables' FORWARD with policy drop: set by Docker when it turns -//! ip_forward on, by ufw (its default), or by hand. Kiri adds three rules -//! (`kiri_rules`) with the host's own iptables, into Docker's DOCKER-USER -//! chain when it is there, else at the top of FORWARD. -//! - firewalld: Kiri's bridges go into its `trusted` zone (runtime only), -//! as Docker's and libvirt's bridges go into zones with target ACCEPT, -//! and Kiri's own forward chain then keeps their new connections to the -//! uplink (`netlink::FORWARD_GUARD`). +//! - iptables' FORWARD with policy drop (or an unconditional trailing +//! `DROP`/`REJECT` rule): set by Docker when it turns ip_forward on, by +//! ufw (its default), or by hand. Kiri adds three rules (`kiri_rules`) with +//! the host's own iptables, into Docker's DOCKER-USER chain when it is +//! there, else at the top of FORWARD, and allows gateway DNS on INPUT when +//! INPUT's policy is drop (ufw). +//! - firewalld: Kiri's bridges go into a runtime `kiri` zone with target +//! ACCEPT plus a `kiri-forwarding` policy (`ANY -> kiri`, target ACCEPT) so +//! both outbound multi-NIC/VPN traffic and inbound published-port DNAT work; +//! Kiri's own forward chain keeps containers off other programs' bridges. //! - any other nftables chain on the forward hook with policy drop (an //! /etc/nftables.conf of the administrator's own): Kiri does not change //! another program's nftables chain. It says once in its log, and in -//! `docker info`, which rules let its containers through. +//! `docker info`, which rules let its containers through, and while +//! forwarding is blocked falls back to user-space relays for published ports. //! //! Only what Kiri's containers need passes: new connections out through the //! uplink Kiri masquerades on, replies, and traffic into Kiri's bridges, @@ -48,29 +51,38 @@ pub enum Why { Stop, } -/// Kiri's rules in iptables' filter table, as iptables arguments after the -/// chain: containers out through the uplink (what Kiri masquerades), their -/// replies wherever they go (a published port reached from another -/// interface), and anything into Kiri's bridges, which Kiri's own forward -/// chain judges. -pub fn kiri_rules(uplink: &str) -> [Vec<&str>; 3] { +/// Kiri's rules in iptables' filter table FORWARD/DOCKER-USER chains, as +/// iptables arguments after the chain: containers out to any non-Kiri +/// interface (primary NIC, VPNs, secondary NICs — while Kiri's own forward +/// chain blocks other programs' bridges), their replies wherever they go, +/// and anything into Kiri's bridges, which Kiri's own forward chain judges. +pub fn kiri_rules() -> [Vec<&'static str>; 3] { [ - vec!["-i", "kiri+", "-o", uplink, "-m", "comment", "--comment", "kiri", "-j", "ACCEPT"], + vec!["-i", "kiri+", "!", "-o", "kiri+", "-m", "comment", "--comment", "kiri", "-j", "ACCEPT"], vec!["-i", "kiri+", "-m", "conntrack", "--ctstate", "RELATED,ESTABLISHED", "-m", "comment", "--comment", "kiri", "-j", "ACCEPT"], vec!["-o", "kiri+", "-m", "comment", "--comment", "kiri", "-j", "ACCEPT"], ] } +/// Kiri's rules in iptables' `INPUT` chain when the host's `INPUT` policy is +/// `DROP` (e.g. ufw): allow only DNS (UDP/TCP port 53) from `kiri+` so +/// containers reach the gateway's embedded DNS without opening host services. +pub fn dns_input_rules() -> [Vec<&'static str>; 2] { + [ + vec!["-i", "kiri+", "-p", "udp", "-m", "udp", "--dport", "53", "-m", "comment", "--comment", "kiri", "-j", "ACCEPT"], + vec!["-i", "kiri+", "-p", "tcp", "-m", "tcp", "--dport", "53", "-m", "comment", "--comment", "kiri", "-j", "ACCEPT"], + ] +} + /// Docker's chain for other software's rules in iptables' `filter` table. const DOCKER_USER: &str = "DOCKER-USER"; const FORWARD: &str = "FORWARD"; +const INPUT: &str = "INPUT"; /// Where Kiri's rules go in iptables' filter table of one family: Docker's /// DOCKER-USER when it is there (Docker jumps to it first and never empties /// it, also when it restarts), else the top of FORWARD when its policy is -/// drop (ufw, or set by hand), as Docker, libvirt and podman put theirs. -/// ufw reloads only its own chains, so rules at the top of FORWARD stay, -/// ahead of ufw's. None when nothing there drops Kiri's traffic. +/// drop or it carries an unconditional trailing `DROP`/`REJECT` rule. pub fn iptables_target(docker_user: bool, forward_drop: bool) -> Option<&'static str> { if docker_user { Some(DOCKER_USER) @@ -87,16 +99,22 @@ const NFPROTO_IPV6: u8 = libc::NFPROTO_IPV6 as u8; const NF_INET_FORWARD: u32 = 2; const NF_DROP: u32 = 0; -/// What the host's nf_tables chains say about its forward hook. +/// What the host's nf_tables chains say about its forward and input hooks. #[derive(Debug, Default, PartialEq, Eq)] pub struct Hook { /// Per family (IPv4, IPv6): where Kiri's rules go in iptables-nft's /// filter table. pub iptables: [Option<&'static str>; 2], + /// Per family (IPv4, IPv6): whether iptables-nft's `INPUT` chain has + /// policy `DROP` (e.g. ufw). + pub input_drop: [bool; 2], /// firewalld runs (its `inet firewalld` table), by the handle of a chain /// of it: a new one after firewalld reloads or restarts, which drops the /// runtime zone Kiri's bridges were put in. pub firewalld: Option, + /// Whether `inet firewalld` has a `filter_FORWARD_POLICIES` chain + /// (firewalld >= 0.9), requiring an ingress forwarding policy for `kiri`. + pub firewalld_policies: bool, /// Kiri's own forward chain, IPv4 and IPv6: gone after an `nft flush /// ruleset` (nftables.service starting or reloading). pub kiri: [bool; 2], @@ -111,9 +129,11 @@ pub fn read_hook(chains: &[Chain]) -> Hook { let has = |table: &str, name: &str| chains.iter().find(|c| c.family == family && c.table == table && c.name == name); let forward_drop = has("filter", FORWARD).is_some_and(|c| c.policy == Some(NF_DROP)); h.iptables[i] = iptables_target(has("filter", DOCKER_USER).is_some(), forward_drop); + h.input_drop[i] = has("filter", INPUT).is_some_and(|c| c.policy == Some(NF_DROP)); h.kiri[i] = has("kiri", "forward").is_some(); } h.firewalld = chains.iter().filter(|c| c.family == NFPROTO_INET && c.table == "firewalld").map(|c| c.handle).min(); + h.firewalld_policies = chains.iter().any(|c| c.family == NFPROTO_INET && c.table == "firewalld" && c.name == "filter_FORWARD_POLICIES"); for c in chains { let iptables = matches!(c.family, NFPROTO_IPV4 | NFPROTO_IPV6) && c.table == "filter" && c.name == FORWARD; let ours = c.table == "kiri" && c.family != NFPROTO_INET; @@ -138,23 +158,67 @@ pub fn kiri_lines(listing: &str) -> Vec<(String, Vec)> { .collect() } +/// Whether an `iptables -S` listing contains an unconditional `DROP` or +/// `REJECT` rule in `FORWARD` (ignoring any rule commented with `kiri`). +fn listed_forward_unconditional_drop(listing: &str) -> bool { + listing.lines().any(|l| { + let words: Vec<&str> = l.split_whitespace().collect(); + if words.len() < 4 || words[0] != "-A" || words[1] != FORWARD { + return false; + } + if words.windows(2).any(|w| w[0] == "--comment" && w[1].trim_matches('"') == "kiri") { + return false; + } + let mut i = 2; + let mut drops = false; + while i < words.len() { + match words[i] { + "-j" => match words.get(i + 1).copied() { + Some("DROP" | "REJECT") => { + drops = true; + i += 2; + } + _ => return false, + }, + "--reject-with" => i += 2, + "-m" => match words.get(i + 1).copied() { + Some("comment") => i += 2, + _ => return false, + }, + "--comment" => i += 2, + _ => return false, + } + } + drops + }) +} + +/// Whether an `iptables -S` listing has `INPUT` policy `DROP`. +pub fn listed_input_drop(listing: &str) -> bool { + listing.lines().any(|l| l.trim_end() == format!("-P {INPUT} DROP")) +} + /// Where Kiri's rules go, from an `iptables -S` listing of the filter /// table (iptables-legacy, which only the program reads). pub fn listed_target(listing: &str) -> Option<&'static str> { let docker_user = listing.lines().any(|l| l.trim_end() == format!("-N {DOCKER_USER}")); - let forward_drop = listing.lines().any(|l| l.trim_end() == format!("-P {FORWARD} DROP")); + let forward_drop = listing.lines().any(|l| l.trim_end() == format!("-P {FORWARD} DROP")) || listed_forward_unconditional_drop(listing); iptables_target(docker_user, forward_drop) } -/// The changes that bring Kiri's rules in `listing` in line: all three in -/// `target` (None: nowhere, the engine stopping) and none elsewhere, as -/// iptables arguments (`-D chain …`, then `-I chain …`). Rules an engine -/// that crashed left behind are kept where they belong, and taken out of a -/// chain they no longer belong in (or for an uplink that is not this one). -/// Inserted last rule first, so the three keep their order at the top. -pub fn iptables_changes(listing: &str, target: Option<&str>, uplink: &str) -> Vec> { +/// The changes that bring Kiri's rules in `listing` in line: `kiri_rules()` in +/// `target` (None: nowhere, the engine stopping) and `dns_input_rules()` in +/// `INPUT` when `allow_dns_input` is true, as iptables arguments (`-D chain …`, +/// then `-I chain …`). Rules an engine that crashed left behind are kept where +/// they belong, and taken out of a chain they no longer belong in. Inserted +/// last rule first, so each chain keeps its rules in order at the top. +pub fn iptables_changes(listing: &str, target: Option<&str>, allow_dns_input: bool) -> Vec> { let have = kiri_lines(listing); - let want: Vec<(String, Vec)> = target.map_or_else(Vec::new, |t| kiri_rules(uplink).iter().map(|r| (t.to_owned(), r.iter().map(|w| w.to_string()).collect())).collect()); + let mut want: Vec<(String, Vec)> = target + .map_or_else(Vec::new, |t| kiri_rules().iter().map(|r| (t.to_owned(), r.iter().map(|w| (*w).to_owned()).collect())).collect()); + if allow_dns_input { + want.extend(dns_input_rules().iter().map(|r| (INPUT.to_owned(), r.iter().map(|w| (*w).to_owned()).collect()))); + } let mut out = Vec::new(); for (chain, args) in &have { if !want.contains(&(chain.clone(), args.clone())) { @@ -171,19 +235,17 @@ pub fn iptables_changes(listing: &str, target: Option<&str>, uplink: &str) -> Ve /// What the administrator's own forward chain needs to let Kiri's /// containers through, as `nft` commands. -pub fn foreign_advice(family: u8, table: &str, chain: &str, up4: &str, up6: &str) -> String { +pub fn foreign_advice(family: u8, table: &str, chain: &str) -> String { let fam = match family { NFPROTO_INET => "inet", NFPROTO_IPV6 => "ip6", _ => "ip", }; - let mut ups = vec![if family == NFPROTO_IPV6 { up6 } else { up4 }]; - if family == NFPROTO_INET && up6 != up4 { - ups.push(up6); - } - let mut rules: Vec = ups.iter().map(|u| format!("iifname \"kiri*\" oifname \"{u}\" accept")).collect(); - rules.push("iifname \"kiri*\" ct state established,related accept".into()); - rules.push("oifname \"kiri*\" accept".into()); + let rules = [ + "iifname \"kiri*\" oifname != \"kiri*\" accept", + "iifname \"kiri*\" ct state established,related accept", + "oifname \"kiri*\" accept", + ]; let cmds: Vec = rules.iter().map(|r| format!("nft insert rule {fam} {table} {chain} {r}")).collect(); format!( "the firewall's nftables chain '{fam} {table} {chain}' (policy drop) drops the traffic of Kiri's containers, so they have no internet; Kiri does not change another program's chain. To let them through, run: {} (and add the same rules to that chain in /etc/nftables.conf to keep them)", @@ -212,9 +274,18 @@ impl Rules { struct State { /// iptables-nft and iptables-legacy, each for IPv4 and IPv6. iptables: [[Rules; 2]; 2], + /// Whether Kiri installed INPUT DNS port 53 rules (nft/legacy x v4/v6). + input_dns: [[bool; 2]; 2], firewalld: Rules, /// The firewalld (by `Hook::firewalld`) that `firewalld` is about. firewalld_seen: Option, + /// Whether firewalld blocks ingress forwarding into Kiri bridges (e.g. + /// `filter_FORWARD_POLICIES` present without an `ANY -> kiri` policy). + firewalld_blocked: bool, + /// Whether host kernel forwarding into Kiri bridges is blocked (by an + /// unmanaged foreign nftables forward drop chain, failed iptables, or + /// firewalld without an ingress policy), triggering user-space relay fallback. + forwarding_blocked: bool, /// Foreign chains already told about in the log. told: Vec, /// What `docker info` shows, as last written. @@ -223,24 +294,29 @@ struct State { static STATE: Mutex> = Mutex::new(None); -/// The Linux host's uplinks by name, IPv4 and IPv6 (`net::host_uplink`). -static UPLINKS: std::sync::OnceLock<(String, String)> = std::sync::OnceLock::new(); +/// Whether the host firewall blocks kernel `FORWARD` into Kiri's bridges, +/// in which case published ports must be relayed in user space (`INPUT`) +/// rather than DNATed in `prerouting`. +pub fn forwarding_blocked() -> bool { + STATE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|st| st.forwarding_blocked) +} -pub fn set_uplinks(up4: String, up6: String) { - let _ = UPLINKS.set((up4, up6)); +/// Checks whether forwarding is blocked given active firewall state and +/// unmanaged foreign nftables chains. +fn compute_forwarding_blocked(iptables_v4_failed: bool, firewalld_blocked: bool, unmanaged_foreign_v4: bool) -> bool { + iptables_v4_failed || firewalld_blocked || unmanaged_foreign_v4 } /// Brings the host's firewall in line with Kiri's needs (see the module /// documentation), or takes Kiri's part out of it (`Why::Stop`). `rebuild` /// builds Kiri's own tables (IPv4, IPv6) again as last built, when a flush -/// took them or their forward chain must change; it does nothing for a +/// took them or their forwarding policy changed; it does nothing for a /// table Kiri has not built. pub fn sync(why: Why, rebuild: impl Fn([bool; 2])) { - let Some((up4, up6)) = UPLINKS.get() else { return }; let mut guard = STATE.lock().unwrap_or_else(|e| e.into_inner()); let st = guard.get_or_insert_with(State::default); if why == Why::Stop { - stop(st, up4, up6); + stop(st); return; } let chains = match netlink::chains() { @@ -252,31 +328,46 @@ pub fn sync(why: Why, rebuild: impl Fn([bool; 2])) { }; let hook = read_hook(&chains); let mut warnings = Vec::new(); - let families = [(NFPROTO_IPV4, "iptables", "/proc/net/ip_tables_names", up4.as_str()), (NFPROTO_IPV6, "ip6tables", "/proc/net/ip6_tables_names", up6.as_str())]; - for (i, (family, tool, legacy_names, uplink)) in families.into_iter().enumerate() { + let families = [(NFPROTO_IPV4, "iptables", "/proc/net/ip_tables_names"), (NFPROTO_IPV6, "ip6tables", "/proc/net/ip6_tables_names")]; + for (i, (family, tool, legacy_names)) in families.into_iter().enumerate() { + // Detect unconditional trailing DROP/REJECT in FORWARD even when policy is ACCEPT (#649). + let nft_target = hook.iptables[i].or_else(|| netlink::has_unconditional_forward_drop(family).ok().filter(|&d| d).map(|_| FORWARD)); + let want_dns = hook.input_drop[i]; // iptables-nft: its filter table is in nf_tables, read above. let rules = &mut st.iptables[0][i]; if let Rules::In(chain) = *rules { - // Gone with a flush, `iptables -F`, a restore of saved rules. - if netlink::rules_with(family, "filter", chain, b"kiri\0").unwrap_or(0) < 3 { + // Gone with a flush, `iptables -F`, a restore of saved rules, or Docker appearing (FORWARD -> DOCKER-USER). + if nft_target != Some(chain) || netlink::rules_with(family, "filter", chain, b"kiri\0").unwrap_or(0) < 3 { *rules = Rules::None; } } + if st.input_dns[0][i] && (!want_dns || netlink::rules_with(family, "filter", INPUT, b"kiri\0").unwrap_or(0) < 2) { + st.input_dns[0][i] = false; + } // Tried again when the engine starts or makes a bridge, or when // the place changed (the chain it failed in went, Docker came). if let Rules::Failed(t) = *rules - && (why != Why::Event || hook.iptables[i] != Some(t)) + && (why != Why::Event || nft_target != Some(t)) { *rules = Rules::None; } - if let (Rules::None, Some(target)) = (*rules, hook.iptables[i]) { - *rules = match sbin(&format!("{tool}-nft")).or_else(|| sbin(tool)) { - Some(path) => iptables_sync(&path, None, Some(target), uplink), + let need_nft = (matches!(*rules, Rules::None) && nft_target.is_some()) || (want_dns && !st.input_dns[0][i]); + if need_nft { + match sbin(&format!("{tool}-nft")).or_else(|| sbin(tool)) { + Some(path) => { + let (r, dns_ok) = iptables_sync(&path, None, nft_target, want_dns); + if nft_target.is_some() { + *rules = r; + } + st.input_dns[0][i] = want_dns && dns_ok; + } None => { - eprintln!("kiri-init: iptables' {target} chain drops forwarded traffic on this host, but there is no {tool} to let Kiri's containers through it"); - Rules::Failed(target) + if let Some(target) = nft_target { + eprintln!("kiri-init: iptables' {target} chain drops forwarded traffic on this host, but there is no {tool} to let Kiri's containers through it"); + *rules = Rules::Failed(target); + } } - }; + } } if rules.failed() { warnings.push(format!("{tool}: Kiri could not add its rules to the filter table, whose FORWARD chain drops the traffic of Kiri's containers; see the engine log")); @@ -294,40 +385,30 @@ pub fn sync(why: Why, rebuild: impl Fn([bool; 2])) { (Rules::In(c), None) => Some(c), (_, target) => target, }; - if keep.is_some() { - *rules = iptables_sync(&path, Some(&listing), keep, uplink); + let legacy_dns = listed_input_drop(&listing); + if keep.is_some() || legacy_dns || st.input_dns[1][i] { + let (r, dns_ok) = iptables_sync(&path, Some(&listing), keep, legacy_dns); + if keep.is_some() || matches!(*rules, Rules::In(_)) { + *rules = r; + } + st.input_dns[1][i] = legacy_dns && dns_ok; } } if rules.failed() { warnings.push(format!("{tool}-legacy: Kiri could not add its rules to the filter table, whose FORWARD chain drops the traffic of Kiri's containers; see the engine log")); } } - firewalld(st, hook.firewalld, why, &mut warnings); - // Kiri's forward chain keeps new connections to the uplink while its - // bridges are in firewalld's trusted zone (`netlink::FORWARD_GUARD`). - let guard = (st.firewalld == Rules::In(ZONE)).then(|| (up4.clone(), up6.clone())); - let guard_changed = { - let mut g = netlink::FORWARD_GUARD.lock().unwrap_or_else(|e| e.into_inner()); - let changed = *g != guard; - *g = guard; - changed - }; - // A flush of the whole ruleset (nftables.service starting or - // reloading) took Kiri's own tables. The IPv6 one is there only with an - // IPv6 network, which `rebuild` knows. - let gone = [why == Why::Event && !hook.kiri[0], why == Why::Event && !hook.kiri[1]]; - if gone[0] { - eprintln!("kiri-init: Kiri's nftables table was removed (a flush of the whole ruleset?); building it again"); - } - if guard_changed || gone[0] || gone[1] { - rebuild([guard_changed || gone[0], guard_changed || gone[1]]); - } + firewalld(st, hook.firewalld, hook.firewalld_policies, why, &mut warnings); + let mut unmanaged_foreign_v4 = false; for (family, table, chain) in &hook.foreign { // Already let through (a rule naming Kiri's bridges). if netlink::rules_with(*family, table, chain, b"kiri").unwrap_or(0) > 0 { continue; } - let advice = foreign_advice(*family, table, chain, up4, up6); + if matches!(*family, NFPROTO_INET | NFPROTO_IPV4) { + unmanaged_foreign_v4 = true; + } + let advice = foreign_advice(*family, table, chain); let key = format!("{family} {table} {chain}"); if !st.told.contains(&key) { eprintln!("kiri-init: {advice}"); @@ -335,12 +416,27 @@ pub fn sync(why: Why, rebuild: impl Fn([bool; 2])) { } warnings.push(format!("Linux host: {advice}")); } + let new_blocked = compute_forwarding_blocked(st.iptables[0][0].failed() || st.iptables[1][0].failed(), st.firewalld_blocked, unmanaged_foreign_v4); + let blocked_changed = st.forwarding_blocked != new_blocked; + st.forwarding_blocked = new_blocked; + // A flush of the whole ruleset (nftables.service starting or + // reloading) took Kiri's own tables. The IPv6 one is there only with an + // IPv6 network, which `rebuild` knows. + let gone = [why == Why::Event && !hook.kiri[0], why == Why::Event && !hook.kiri[1]]; + if gone[0] { + eprintln!("kiri-init: Kiri's nftables table was removed (a flush of the whole ruleset?); building it again"); + } write_warnings(st, warnings.join("\n")); + drop(guard); + if blocked_changed || gone[0] || gone[1] { + rebuild([blocked_changed || gone[0], gone[1]]); + } } /// Brings Kiri's rules in iptables' filter table (`listing`, or listed -/// now) in line with `target`; see `iptables_changes`. -fn iptables_sync(tool: &Path, listing: Option<&str>, target: Option<&'static str>, uplink: &str) -> Rules { +/// now) in line with `target` and `allow_dns_input`; see `iptables_changes`. +/// Returns `(forward_rules, all_succeeded)`. +fn iptables_sync(tool: &Path, listing: Option<&str>, target: Option<&'static str>, allow_dns_input: bool) -> (Rules, bool) { let listed; let listing = match listing { Some(l) => l, @@ -351,16 +447,16 @@ fn iptables_sync(tool: &Path, listing: Option<&str>, target: Option<&'static str } None => { eprintln!("kiri-init: {} cannot list the filter table, so Kiri's containers may not pass the host's firewall", tool.display()); - return target.map_or(Rules::None, Rules::Failed); + return (target.map_or(Rules::None, Rules::Failed), false); } }, }; let mut ok = true; - for change in iptables_changes(listing, target, uplink) { + for change in iptables_changes(listing, target, allow_dns_input) { let args: Vec<&str> = change.iter().map(String::as_str).collect(); ok &= run(tool, &args).is_some(); } - match (target, ok) { + let r = match (target, ok) { (Some(t), true) => { eprintln!("kiri-init: the host's firewall drops forwarded traffic: Kiri's containers pass it by rules in iptables' {t} chain ({})", tool.display()); Rules::In(t) @@ -375,88 +471,149 @@ fn iptables_sync(tool: &Path, listing: Option<&str>, target: Option<&'static str } Rules::None } + }; + (r, ok) +} + +const ZONE_KIRI: &str = "kiri"; +const ZONE_TRUSTED: &str = "trusted"; +const POLICY_FORWARDING: &str = "kiri-forwarding"; + +fn firewall_cmd_out(cmd: &Path, args: &[&str]) -> Result { + match std::process::Command::new(cmd).args(args).stdin(std::process::Stdio::null()).output() { + Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).into_owned()), + Ok(o) => Err(String::from_utf8_lossy(&o.stderr).trim().to_owned()), + Err(e) => Err(e.to_string()), } } -/// firewalld's zone for Kiri's bridges (all of them: `kiri+`). -const ZONE: &str = "trusted"; - -/// Puts Kiri's bridges into firewalld's trusted zone, runtime only, once -/// per firewalld run (a reload or restart drops runtime settings, and makes -/// its table anew). An interface in no zone is in the default one, whose -/// rules can reject the containers' traffic: a zone without forwarding (as -/// firewalld before 1.0 had them, or set so), or the drop zone; and public -/// takes only ssh from them, not the host's other services. A zone with -/// target ACCEPT is what Docker (its `docker` zone) and libvirt give their -/// bridges; Kiri's own forward chain then keeps the containers' new -/// connections to the uplink, and the other programs' bridges keep their own -/// filters. When the administrator put `kiri+` in a zone already, that zone -/// stays. -fn firewalld(st: &mut State, seen: Option, why: Why, warnings: &mut Vec) { +/// Ensures `kiri` zone (`target=ACCEPT`) and `kiri-forwarding` policy (`ANY -> kiri`, +/// `target=ACCEPT`) exist in firewalld runtime, falling back gracefully on older +/// firewalld without policies or if `kiri` zone creation is rejected. +/// Returns `(rules_state, forwarding_blocked)`. +fn configure_firewalld(cmd: &Path, policies_hook: bool) -> (Rules, bool) { + let rt_zones = firewall_cmd_out(cmd, &["--get-zones"]).unwrap_or_default(); + let has_kiri_rt = rt_zones.split_whitespace().any(|z| z == ZONE_KIRI); + let rt_policies = firewall_cmd_out(cmd, &["--get-policies"]); + let policies_supported = rt_policies.is_ok(); + let has_policy_rt = rt_policies.as_deref().is_ok_and(|p| p.split_whitespace().any(|n| n == POLICY_FORWARDING)); + + let mut need_reload = false; + let mut zone_ready = has_kiri_rt; + if !has_kiri_rt { + let perm_zones = firewall_cmd_out(cmd, &["--permanent", "--get-zones"]).unwrap_or_default(); + let mut perm_ok = perm_zones.split_whitespace().any(|z| z == ZONE_KIRI); + if !perm_ok { + perm_ok = firewall_cmd_out(cmd, &["--permanent", "--new-zone=kiri"]).is_ok() + && firewall_cmd_out(cmd, &["--permanent", "--zone=kiri", "--set-target=ACCEPT"]).is_ok(); + } + if perm_ok { + need_reload = true; + zone_ready = true; + } + } + + let mut policy_ready = has_policy_rt; + if zone_ready && policies_supported && !has_policy_rt { + let perm_policies = firewall_cmd_out(cmd, &["--permanent", "--get-policies"]).unwrap_or_default(); + let mut perm_ok = perm_policies.split_whitespace().any(|p| p == POLICY_FORWARDING); + if !perm_ok { + perm_ok = firewall_cmd_out(cmd, &["--permanent", "--new-policy=kiri-forwarding"]).is_ok() + && firewall_cmd_out(cmd, &["--permanent", "--policy=kiri-forwarding", "--add-ingress-zone=ANY"]).is_ok() + && firewall_cmd_out(cmd, &["--permanent", "--policy=kiri-forwarding", "--add-egress-zone=kiri"]).is_ok() + && firewall_cmd_out(cmd, &["--permanent", "--policy=kiri-forwarding", "--set-target=ACCEPT"]).is_ok(); + } + if perm_ok { + need_reload = true; + policy_ready = true; + } + } + + if need_reload && firewall_cmd_out(cmd, &["--reload"]).is_err() { + zone_ready = has_kiri_rt; + policy_ready = has_policy_rt; + } + + let target_zone = if zone_ready { ZONE_KIRI } else { ZONE_TRUSTED }; + let add_arg = format!("--zone={target_zone}"); + match firewall_cmd_out(cmd, &[&add_arg, "--add-interface=kiri+"]) { + Ok(_) => { + let blocked = policies_hook && (!zone_ready || !policy_ready); + eprintln!("kiri-init: firewalld runs: Kiri's bridges (kiri+) are in its {target_zone} zone until the engine stops"); + (Rules::In(target_zone), blocked) + } + Err(why) if why.contains("ZONE_CONFLICT") => { + eprintln!("kiri-init: firewalld runs, and Kiri's bridges (kiri+) are in a zone of the administrator's already, which decides what Kiri's containers may reach"); + let blocked = policies_hook && netlink::rules_with(NFPROTO_INET, "firewalld", "filter_FORWARD_POLICIES", b"kiri").unwrap_or(0) == 0; + (Rules::None, blocked) + } + Err(why) => { + eprintln!("kiri-init: firewalld runs, but Kiri's bridges could not be put in its {target_zone} zone: {why}"); + (Rules::Failed(target_zone), true) + } + } +} + +/// Puts Kiri's bridges into firewalld's `kiri` zone (plus `kiri-forwarding` +/// policy when supported, falling back to `trusted` on older installations), +/// runtime interface attachment only, once per firewalld run. +fn firewalld(st: &mut State, seen: Option, policies_hook: bool, why: Why, warnings: &mut Vec) { if seen.is_none() { st.firewalld = Rules::None; st.firewalld_seen = None; + st.firewalld_blocked = false; return; } if st.firewalld_seen != seen || (st.firewalld.failed() && why != Why::Event) { st.firewalld_seen = seen; - st.firewalld = match sbin("firewall-cmd") { + match sbin("firewall-cmd") { None => { - eprintln!("kiri-init: firewalld runs, but there is no firewall-cmd to put Kiri's bridges in its {ZONE} zone"); - Rules::Failed(ZONE) + eprintln!("kiri-init: firewalld runs, but there is no firewall-cmd to put Kiri's bridges in a Kiri zone"); + st.firewalld = Rules::Failed(ZONE_KIRI); + st.firewalld_blocked = true; } - Some(cmd) => match std::process::Command::new(&cmd).args([&format!("--zone={ZONE}"), "--add-interface=kiri+"]).stdin(std::process::Stdio::null()).output() { - Ok(o) if o.status.success() => { - eprintln!("kiri-init: firewalld runs: Kiri's bridges (kiri+) are in its {ZONE} zone until the engine stops"); - Rules::In(ZONE) - } - Ok(o) => { - let why = String::from_utf8_lossy(&o.stderr).trim().to_owned(); - if why.contains("ZONE_CONFLICT") { - eprintln!("kiri-init: firewalld runs, and Kiri's bridges (kiri+) are in a zone of the administrator's already, which decides what Kiri's containers may reach"); - Rules::None - } else { - eprintln!("kiri-init: firewalld runs, but Kiri's bridges could not be put in its {ZONE} zone: {why}"); - Rules::Failed(ZONE) - } - } - Err(e) => { - eprintln!("kiri-init: firewalld runs, but firewall-cmd failed: {e}"); - Rules::Failed(ZONE) - } - }, - }; + Some(cmd) => { + let (rules, blocked) = configure_firewalld(&cmd, policies_hook); + st.firewalld = rules; + st.firewalld_blocked = blocked; + } + } } if st.firewalld.failed() { - warnings.push(format!("firewalld: Kiri could not put its bridges (kiri+) in the {ZONE} zone, so firewalld may reject its containers' traffic; see the engine log")); + warnings.push("firewalld: Kiri could not put its bridges (kiri+) in a firewalld zone, so firewalld may reject its containers' traffic; see the engine log".into()); + } else if st.firewalld_blocked { + warnings.push("firewalld: Kiri could not install an ingress forwarding policy for kiri+, so published ports will be relayed in user space".into()); } } /// The engine stopping: Kiri's rules out of iptables (where it put them) /// and its bridges out of firewalld's zone, unless the administrator put /// them there for good (the permanent configuration). -fn stop(st: &mut State, up4: &str, up6: &str) { +fn stop(st: &mut State) { for (backend, suffix) in ["-nft", "-legacy"].into_iter().enumerate() { - for (i, (tool, uplink)) in [("iptables", up4), ("ip6tables", up6)].into_iter().enumerate() { - if let Rules::In(_) = st.iptables[backend][i] + for (i, tool) in ["iptables", "ip6tables"].into_iter().enumerate() { + if (matches!(st.iptables[backend][i], Rules::In(_)) || st.input_dns[backend][i]) && let Some(path) = sbin(&format!("{tool}{suffix}")).or_else(|| sbin(tool)) { - iptables_sync(&path, None, None, uplink); + iptables_sync(&path, None, None, false); } st.iptables[backend][i] = Rules::None; + st.input_dns[backend][i] = false; } } - if st.firewalld == Rules::In(ZONE) + if let Rules::In(zone) = st.firewalld && let Some(cmd) = sbin("firewall-cmd") { - let kept = run(&cmd, &["--permanent", &format!("--zone={ZONE}"), "--query-interface=kiri+"]).is_some_and(|o| o.trim() == "yes"); - if !kept && run(&cmd, &[&format!("--zone={ZONE}"), "--remove-interface=kiri+"]).is_none() { - eprintln!("kiri-init: Kiri's bridges could not be taken out of firewalld's {ZONE} zone"); + let kept = run(&cmd, &["--permanent", &format!("--zone={zone}"), "--query-interface=kiri+"]).is_some_and(|o| o.trim() == "yes"); + if !kept && run(&cmd, &[&format!("--zone={zone}"), "--remove-interface=kiri+"]).is_none() { + eprintln!("kiri-init: Kiri's bridges could not be taken out of firewalld's {zone} zone"); } } st.firewalld = Rules::None; st.firewalld_seen = None; - *netlink::FORWARD_GUARD.lock().unwrap_or_else(|e| e.into_inner()) = None; + st.firewalld_blocked = false; + st.forwarding_blocked = false; + *netlink::FOREIGN_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()) = Vec::new(); write_warnings(st, String::new()); } @@ -512,10 +669,9 @@ mod tests { #[test] fn kiri_rules_accept_only_kiris_own_traffic() { - let [out, replies, into] = kiri_rules("eth0"); - // New connections out of Kiri's bridges only through the uplink, - // never into another program's bridges; replies anywhere. - assert_eq!(out.join(" "), "-i kiri+ -o eth0 -m comment --comment kiri -j ACCEPT"); + let [out, replies, into] = kiri_rules(); + // New connections out of Kiri's bridges to any non-Kiri interface (VPNs, secondary NICs, WAN), replies anywhere. + assert_eq!(out.join(" "), "-i kiri+ ! -o kiri+ -m comment --comment kiri -j ACCEPT"); assert_eq!(replies.join(" "), "-i kiri+ -m conntrack --ctstate RELATED,ESTABLISHED -m comment --comment kiri -j ACCEPT"); // Into Kiri's bridges, where Kiri's forward chain judges. assert_eq!(into.join(" "), "-o kiri+ -m comment --comment kiri -j ACCEPT"); @@ -561,69 +717,91 @@ mod tests { let own_accepting = chain(2, "mine", "fwd", Some(2), Some(1)); let h = read_hook(&[fwd, zones, own, own_input, own_accepting]); assert_eq!(h.firewalld, Some(7)); + assert!(h.firewalld_policies); assert_eq!(h.foreign, vec![(1, "filter".to_owned(), "forward".to_owned())]); assert_eq!(h.iptables, [None, None]); } #[test] - fn kiris_lines_are_found_in_a_listing() { - let listing = "-P INPUT DROP\n-P FORWARD DROP\n-N ufw-before-forward\n-A FORWARD -o kiri+ -m comment --comment kiri -j ACCEPT\n-A FORWARD -j ufw-before-forward\n-A ufw-before-forward -i kiri+ -j ACCEPT\n-A DOCKER-USER -i kiri+ -o eth0 -m comment --comment \"kiri\" -j ACCEPT\n"; + fn kiris_lines_and_trailing_drops_and_input_drop_are_found_in_a_listing() { + let listing = "-P INPUT DROP\n-P FORWARD DROP\n-N ufw-before-forward\n-A FORWARD -o kiri+ -m comment --comment kiri -j ACCEPT\n-A FORWARD -j ufw-before-forward\n-A ufw-before-forward -i kiri+ -j ACCEPT\n-A DOCKER-USER -i kiri+ ! -o kiri+ -m comment --comment \"kiri\" -j ACCEPT\n"; assert_eq!( kiri_lines(listing), vec![ ("FORWARD".to_owned(), "-o kiri+ -m comment --comment kiri -j ACCEPT".split(' ').map(String::from).collect()), - ("DOCKER-USER".to_owned(), "-i kiri+ -o eth0 -m comment --comment kiri -j ACCEPT".split(' ').map(String::from).collect()), + ("DOCKER-USER".to_owned(), "-i kiri+ ! -o kiri+ -m comment --comment kiri -j ACCEPT".split(' ').map(String::from).collect()), ] ); assert_eq!(listed_target(listing), Some("FORWARD")); + assert!(listed_input_drop(listing)); assert_eq!(listed_target("-P FORWARD DROP\n-N DOCKER-USER\n"), Some("DOCKER-USER")); assert_eq!(listed_target("-P FORWARD ACCEPT\n"), None); + assert_eq!(listed_target("-P FORWARD ACCEPT\n-A FORWARD -j REJECT --reject-with icmp-host-prohibited\n"), Some("FORWARD")); + assert_eq!(listed_target("-P FORWARD ACCEPT\n-A FORWARD -j DROP\n"), Some("FORWARD")); + assert_eq!(listed_target("-P FORWARD ACCEPT\n-A FORWARD -s 10.0.0.1 -j DROP\n"), None); } #[test] fn rules_left_by_a_crashed_engine_are_reused_not_doubled() { - let all = |chain: &str, up: &str| kiri_rules(up).iter().map(|r| format!("-A {chain} {}\n", r.join(" "))).collect::(); - let listing = format!("-P FORWARD DROP\n{}", all("FORWARD", "eth0")); - assert!(iptables_changes(&listing, Some("FORWARD"), "eth0").is_empty()); + let all = |chain: &str| kiri_rules().iter().map(|r| format!("-A {chain} {}\n", r.join(" "))).collect::(); + let listing = format!("-P FORWARD DROP\n{}", all("FORWARD")); + assert!(iptables_changes(&listing, Some("FORWARD"), false).is_empty()); // One missing: only it is added. let partial: String = listing.lines().filter(|l| !l.contains("RELATED")).map(|l| format!("{l}\n")).collect(); - let changes = iptables_changes(&partial, Some("FORWARD"), "eth0"); + let changes = iptables_changes(&partial, Some("FORWARD"), false); assert_eq!(changes.len(), 1); assert_eq!(changes[0][..3], ["-I", "FORWARD", "-i"]); assert!(changes[0].contains(&"RELATED,ESTABLISHED".to_owned())); // Stopping: all three out. - let out = iptables_changes(&listing, None, "eth0"); + let out = iptables_changes(&listing, None, false); assert_eq!(out.len(), 3); assert!(out.iter().all(|c| c[0] == "-D" && c[1] == "FORWARD")); } #[test] - fn rules_in_the_wrong_chain_or_for_another_uplink_move() { - let all = |chain: &str, up: &str| kiri_rules(up).iter().map(|r| format!("-A {chain} {}\n", r.join(" "))).collect::(); - // Left in FORWARD; Docker came since: kept where they are only if - // asked for there, so here they move to DOCKER-USER. - let changes = iptables_changes(&all("FORWARD", "eth0"), Some("DOCKER-USER"), "eth0"); + fn rules_in_the_wrong_chain_move_and_input_dns_tracks_drop_policy() { + let all = |chain: &str| kiri_rules().iter().map(|r| format!("-A {chain} {}\n", r.join(" "))).collect::(); + // Left in FORWARD; Docker came since: move to DOCKER-USER. + let changes = iptables_changes(&all("FORWARD"), Some("DOCKER-USER"), false); assert_eq!(changes.iter().filter(|c| c[0] == "-D" && c[1] == "FORWARD").count(), 3); assert_eq!(changes.iter().filter(|c| c[0] == "-I" && c[1] == "DOCKER-USER").count(), 3); - // The uplink changed: only the rule naming it is replaced. - let changes = iptables_changes(&all("FORWARD", "wlan0"), Some("FORWARD"), "eth0"); - assert_eq!(changes.len(), 2); - assert!(changes[0].join(" ").starts_with("-D FORWARD -i kiri+ -o wlan0")); - assert!(changes[1].join(" ").starts_with("-I FORWARD -i kiri+ -o eth0")); // Inserted last first, so they end up in order at the top. - let changes = iptables_changes("-P FORWARD DROP\n", Some("FORWARD"), "eth0"); + let changes = iptables_changes("-P FORWARD DROP\n", Some("FORWARD"), false); assert_eq!(changes.iter().map(|c| c[2].as_str()).collect::>(), ["-o", "-i", "-i"]); + // Old single-uplink rule left behind is replaced by `-i kiri+ ! -o kiri+`. + let old = "-P FORWARD DROP\n-A FORWARD -i kiri+ -o eth0 -m comment --comment kiri -j ACCEPT\n"; + let changes = iptables_changes(old, Some("FORWARD"), false); + assert!(changes.iter().any(|c| c[0] == "-D" && c.contains(&"eth0".to_owned()))); + assert!(changes.iter().any(|c| c[0] == "-I" && c.windows(3).any(|w| w == ["!", "-o", "kiri+"]))); + // Under ufw / INPUT DROP, DNS port 53 UDP/TCP rules are added in INPUT only and removed on stop. + let dns_changes = iptables_changes("-P INPUT DROP\n-P FORWARD DROP\n", Some("FORWARD"), true); + assert_eq!(dns_changes.iter().filter(|c| c[0] == "-I" && c[1] == "INPUT").count(), 2); + assert!(dns_changes.iter().any(|c| c[1] == "INPUT" && c.contains(&"udp".to_owned()) && c.contains(&"53".to_owned()))); + assert!(dns_changes.iter().any(|c| c[1] == "INPUT" && c.contains(&"tcp".to_owned()) && c.contains(&"53".to_owned()))); + // Once in place, no duplicate DNS or FORWARD rules are added. + let existing = format!( + "-P INPUT DROP\n-P FORWARD DROP\n{}{}", + all("FORWARD"), + dns_input_rules().iter().map(|r| format!("-A INPUT {}\n", r.join(" "))).collect::() + ); + assert!(iptables_changes(&existing, Some("FORWARD"), true).is_empty()); + assert_eq!(iptables_changes(&existing, None, false).len(), 5); } #[test] - fn advice_for_an_nftables_conf_names_the_chain_and_the_uplink() { - let a = foreign_advice(1, "filter", "forward", "eth0", "eth0"); - assert!(a.contains("nft insert rule inet filter forward iifname \"kiri*\" oifname \"eth0\" accept")); + fn advice_for_an_nftables_conf_uses_non_kiri_uplinks() { + let a = foreign_advice(1, "filter", "forward"); + assert!(a.contains("nft insert rule inet filter forward iifname \"kiri*\" oifname != \"kiri*\" accept")); assert!(a.contains("nft insert rule inet filter forward iifname \"kiri*\" ct state established,related accept")); assert!(a.contains("nft insert rule inet filter forward oifname \"kiri*\" accept")); - // Another IPv6 uplink in an inet chain: a rule for each. - let a = foreign_advice(1, "filter", "forward", "eth0", "wg0"); - assert!(a.contains("oifname \"wg0\" accept")); - assert!(foreign_advice(10, "f", "fwd", "eth0", "wg0").contains("nft insert rule ip6 f fwd iifname \"kiri*\" oifname \"wg0\" accept")); + assert!(foreign_advice(10, "f", "fwd").contains("nft insert rule ip6 f fwd iifname \"kiri*\" oifname != \"kiri*\" accept")); + } + + #[test] + fn forwarding_blocked_reflects_foreign_iptables_or_firewalld_block() { + assert!(!compute_forwarding_blocked(false, false, false)); + assert!(compute_forwarding_blocked(true, false, false)); + assert!(compute_forwarding_blocked(false, true, false)); + assert!(compute_forwarding_blocked(false, false, true)); } } diff --git a/crates/kiri-init/src/linux/fsnotify.rs b/crates/kiri-init/src/linux/fsnotify.rs index cab9698c4..79d2544dd 100644 --- a/crates/kiri-init/src/linux/fsnotify.rs +++ b/crates/kiri-init/src/linux/fsnotify.rs @@ -1,14 +1,30 @@ -//! Files the Mac changed under bind mounts, raised as inotify events in the -//! VM. Apple's virtiofs server tells the guest nothing when a file changes -//! on the Mac, so file watchers in containers (Vite, webpack, nodemon, -//! `cargo watch`) never heard of a save. The daemon watches the bind sources -//! with FSEvents and sends `OP\tPATH` lines (`Msg::FsEvents`); the guest -//! kernel's /proc/kiri-fsnotify (guest/kernel/patches/0006) raises the -//! event for each, as a change made in the VM would. Nothing is written to +//! Files changed on the host under bind mounts, raised as inotify events in +//! the guest or WSL 2 userland. +//! +//! On macOS, Apple's virtiofs server tells the guest nothing when a file +//! changes on the Mac, so the daemon watches bind sources with FSEvents and +//! sends `OP\tPATH` lines (`Msg::FsEvents`) to the guest kernel's +//! `/proc/kiri-fsnotify` (guest/kernel/patches/0006). Nothing is written to //! the files, so nothing goes back to the Mac. +//! +//! On Windows (WSL 2), `C:\` is mounted over 9P (`drvfs` at `/mnt/c/...`) and +//! Microsoft's WSL 2 kernel neither forwards Windows file-change events over +//! 9P nor provides `/proc/kiri-fsnotify`. When `/proc/kiri-fsnotify` is +//! absent and a path is under WSL's automount root (`/mnt//...`), the +//! agent raises real Linux VFS inotify events itself, never following a +//! symlink and never writing to a file: +//! - `M`, `C` and `A`: sets the mode the file or directory already has, which +//! raises `IN_ATTRIB` on it and its watched parent (`raise_vfs_under`). +//! - `D`: the same on the parent directory, whose watchers read it again. +//! - `P` and `U` (from `kiri-win` as it starts and stops watching a root): +//! hold and release `O_PATH` fds on the root's directories, without which +//! no inotify watch on `drvfs` hears of anything (`Pins`). -use std::collections::VecDeque; +use std::collections::{HashMap, VecDeque}; +use std::ffi::{CStr, CString}; use std::io::Write; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; +use std::sync::OnceLock; /// Where the Mac's filesystem is mounted in the VM (mod.rs). const MAC: &str = "/mnt/mac/"; @@ -17,63 +33,366 @@ const PROC: &str = "/proc/kiri-fsnotify"; /// that missed a change in a storm hears of the next one). const MAX_PENDING: usize = 8192; /// Lines raised per turn of the agent's loop, so a storm of changes on the -/// Mac doesn't hold up its other messages. +/// host doesn't hold up its other messages. const PER_TURN: usize = 64; +/// Most directories held open under watched WSL roots (see `Pins`). +const MAX_PINS: usize = 16384; +/// Directories opened per turn of the agent's loop while pinning a root. +const PINS_PER_TURN: usize = 64; +/// Skipped when pinning a root: dependency and git trees, which dev servers' +/// watchers ignore by default and which can hold most of a project's folders. +const SKIP_DIRS: [&str; 2] = ["node_modules", ".git"]; /// Changes waiting to be raised. Raised from the agent's own loop, a few at /// a time, not a thread: the agent must stay single-threaded (it starts /// containers with clone3, and a thread breaks setuid in the child). #[derive(Default)] -pub struct Pending(VecDeque); +pub struct Pending { + lines: VecDeque, + pins: Pins, +} impl Pending { - /// Queues the lines that name a file under the Mac's mount, in order. - /// Each is kept, repeats too: dropping one that is already queued would - /// lose a delete in `D a, C a, M a, D a`. The daemon merges each batch. + /// Queues the lines that name a file under the Mac's mount or WSL's + /// automount root, in order. Each is kept, repeats too: dropping one that + /// is already queued would lose a delete in `D a, C a, M a, D a`. The + /// sender merges each batch. pub fn add<'a>(&mut self, lines: impl Iterator) { for line in valid(lines) { - if self.0.len() < MAX_PENDING { - self.0.push_back(line); + if self.lines.len() < MAX_PENDING { + self.lines.push_back(line); } } } pub fn is_empty(&self) -> bool { - self.0.is_empty() + self.lines.is_empty() && self.pins.walk.is_empty() } - /// Raises up to PER_TURN lines. A kernel without the interface (or a - /// host-process engine) drops them all. + /// Raises up to PER_TURN lines. Uses `/proc/kiri-fsnotify` when present + /// (macOS guest VM); otherwise raises Linux VFS inotify events for valid + /// WSL automount paths (`/mnt//...`) and pins up to PINS_PER_TURN + /// directories of watched roots. pub fn raise_some(&mut self) { - let Ok(mut f) = std::fs::OpenOptions::new().write(true).open(PROC) else { - self.0.clear(); + let count = PER_TURN.min(self.lines.len()); + if let Ok(mut f) = std::fs::OpenOptions::new().write(true).open(PROC) { + // One write per line: the kernel answers each with its own result, + // and a file gone again by now (ENOENT) must not drop the rest. + for line in self.lines.drain(..count) { + let _ = f.write_all(line.as_bytes()); + } return; - }; - // One write per line: the kernel answers each with its own result, - // and a file gone again by now (ENOENT) must not drop the rest. - for line in self.0.drain(..PER_TURN.min(self.0.len())) { - let _ = f.write_all(line.as_bytes()); } + let root = wsl_automount_root(); + for line in self.lines.drain(..count) { + raise_vfs_line(&line, root, &mut self.pins); + } + self.pins.walk_some(root); + } +} + +/// `[automount] root` from `/etc/wsl.conf`, defaulting to `/mnt/`. +fn automount_root(conf: &str) -> String { + let mut section = String::new(); + let mut root = None; + for line in conf.lines() { + let line = line.split('#').next().unwrap_or("").trim(); + if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + section = s.trim().to_ascii_lowercase(); + continue; + } + let Some((key, value)) = line.split_once('=') else { continue }; + if section == "automount" && key.trim().eq_ignore_ascii_case("root") { + let value = value.trim().trim_matches('"').trim(); + if value.starts_with('/') { + root = Some(value.to_owned()); + } + } + } + let mut root = root.unwrap_or_else(|| "/mnt/".to_owned()); + if !root.ends_with('/') { + root.push('/'); + } + root +} + +fn wsl_automount_root() -> &'static str { + static ROOT: OnceLock = OnceLock::new(); + ROOT.get_or_init(|| automount_root(&std::fs::read_to_string("/etc/wsl.conf").unwrap_or_default())) +} + +/// Splits a validated WSL automount path (`/mnt/c/Users/a/app.js`) into +/// `(drive_root, rel_path)` (`("/mnt/c", "Users/a/app.js")`). +/// Rejects paths outside `/...`, empty relative paths, +/// control characters (`\n`, `\r`, `\0`), and `.` or `..` traversal components. +fn split_wsl_drive_path<'a>(path: &'a str, automount_root: &str) -> Option<(&'a str, &'a str)> { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return None; + } + if path.contains(['\n', '\r', '\0']) { + return None; + } + let rest = path.strip_prefix(automount_root)?; + let bytes = rest.as_bytes(); + if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b'/' { + return None; + } + let rel = &rest[2..]; + let mut has_component = false; + for part in rel.split('/') { + if part.is_empty() { + continue; + } + if part == "." || part == ".." { + return None; + } + has_component = true; } + if !has_component { + return None; + } + Some((&path[..automount_root.len() + 1], rel)) } -/// The lines the kernel takes, each ending in a newline: `C`, `M`, `A` or -/// `D`, a tab, and a path under /mnt/mac with no `..` and no newline. +/// The lines the raiser accepts, each ending in a newline: `C`, `M`, `A` or +/// `D`, a tab, and a path under `/mnt/mac/` or WSL's automount root with no +/// `..`, no NUL and no newline; or `P` or `U` and a path under WSL's +/// automount root. fn valid<'a>(lines: impl Iterator) -> impl Iterator { - lines.filter_map(|line| { + valid_for(lines, wsl_automount_root()) +} + +fn valid_for<'a>(lines: impl Iterator, automount_root: &'a str) -> impl Iterator { + lines.filter_map(move |line| { let (op, path) = line.split_once('\t')?; - let ok = matches!(op, "C" | "M" | "A" | "D") - && path.starts_with(MAC) - && path.len() > MAC.len() - && !path.contains('\n') - && !path.split('/').any(|part| part == ".."); + let no_bad_chars = !path.contains(['\n', '\r', '\0']) && !path.split('/').any(|part| part == ".."); + let is_mac = path.starts_with(MAC) && path.len() > MAC.len(); + let is_wsl = split_wsl_drive_path(path, automount_root).is_some(); + let ok = no_bad_chars && match op { + "C" | "M" | "A" | "D" => is_mac || is_wsl, + "P" | "U" => is_wsl, + _ => false, + }; ok.then(|| format!("{op}\t{path}\n")) }) } +/// Raises a single `OP\tPATH` line via Linux VFS syscalls, strictly restricted +/// to paths under `/...`. `P` and `U` pin and unpin a +/// watched root's directories (see `Pins`). +fn raise_vfs_line(line: &str, automount_root: &str, pins: &mut Pins) -> bool { + let line = line.trim_end_matches('\n'); + let Some((op, path)) = line.split_once('\t') else { return false }; + let Some((base, rel)) = split_wsl_drive_path(path, automount_root) else { return false }; + match op { + "P" => pins.pin_tree(path), + "U" => pins.unpin_tree(path), + "D" => pins.unpin_tree(path), + // A new directory is pinned before its parent hears of it, so a + // watcher that adds a watch on it in answer gets the pinned inode. + "C" if path.rsplit_once('/').is_some_and(|(parent, _)| pins.held.contains_key(parent)) => { + if let Some(fd) = open_dir_nofollow(base, rel) { + pins.hold(path, fd); + pins.walk.push_back(path.to_owned()); + } + } + _ => {} + } + matches!(op, "P" | "U") || raise_vfs_under(base, rel, op) +} + +/// Directories held open under watched WSL roots. +/// +/// `drvfs` (9P without metadata caching, `cache=5`) drops a dentry as soon as +/// nothing holds it and makes a new inode on every lookup. An inotify watch +/// sits on the inode it was added to, so once that directory's dentry is +/// gone, no change made later (in WSL or raised here) ever reaches the watch. +/// Holding an `O_PATH` fd on each directory keeps its dentry, and so its +/// inode, for every later lookup. `O_PATH` opens nothing on the Windows side +/// and raises no inotify event. +#[derive(Default)] +struct Pins { + held: HashMap, + /// Directories still to open and list, a few per turn of the agent's loop. + walk: VecDeque, +} + +impl Pins { + fn pin_tree(&mut self, path: &str) { + if !self.walk.iter().any(|p| p == path) { + self.walk.push_back(path.to_owned()); + } + } + + fn unpin_tree(&mut self, path: &str) { + let under = |p: &str| p == path || p.strip_prefix(path).is_some_and(|rest| rest.starts_with('/')); + self.held.retain(|p, _| !under(p)); + self.walk.retain(|p| !under(p)); + } + + fn hold(&mut self, path: &str, fd: OwnedFd) { + if self.held.len() < MAX_PINS || self.held.contains_key(path) { + self.held.insert(path.to_owned(), fd); + } + } + + /// Opens and lists up to PINS_PER_TURN queued directories, queueing their + /// subdirectories. Never follows a symlink; skips `SKIP_DIRS`. + fn walk_some(&mut self, automount_root: &str) { + for _ in 0..PINS_PER_TURN { + let Some(dir) = self.walk.pop_front() else { return }; + if self.held.len() >= MAX_PINS { + self.walk.clear(); + return; + } + let Some((base, rel)) = split_wsl_drive_path(&dir, automount_root) else { continue }; + let Some(fd) = open_dir_nofollow(base, rel) else { continue }; + let list = std::fs::read_dir(format!("/proc/self/fd/{}", fd.as_raw_fd())); + self.hold(&dir, fd); + for entry in list.into_iter().flatten().flatten() { + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { continue }; + if SKIP_DIRS.contains(&name.as_str()) || name.contains(['\n', '\r']) || !entry.file_type().is_ok_and(|t| t.is_dir()) { + continue; + } + if self.held.len() + self.walk.len() >= MAX_PINS { + break; + } + self.walk.push_back(format!("{dir}/{name}")); + } + } + } +} + +/// Opens `base_dir`, then each directory of `rel_path` but the last, with +/// `O_PATH | O_DIRECTORY | O_NOFOLLOW`: a symlink anywhere on the way fails. +/// Returns the parent directory and the last component. +fn open_parent_nofollow(base_dir: &str, rel_path: &str) -> Option<(OwnedFd, CString)> { + let comps: Vec<&str> = rel_path.split('/').filter(|s| !s.is_empty()).collect(); + if comps.is_empty() || comps.iter().any(|c| *c == "." || *c == ".." || c.contains('\0')) { + return None; + } + let c_base = CString::new(base_dir).ok()?; + // SAFETY: `c_base` is a valid NUL-terminated path; the returned fd is + // immediately wrapped in `OwnedFd` when non-negative. + let raw = unsafe { libc::open(c_base.as_ptr(), DIR_FLAGS) }; + if raw < 0 { + return None; + } + // SAFETY: `raw` is a newly opened valid file descriptor. + let mut parent = unsafe { OwnedFd::from_raw_fd(raw) }; + for comp in &comps[..comps.len() - 1] { + parent = open_at(&parent, &CString::new(*comp).ok()?, DIR_FLAGS)?; + } + Some((parent, CString::new(comps[comps.len() - 1]).ok()?)) +} + +/// The directory at `rel_path` under `base_dir`, opened `O_PATH` without +/// following any symlink. +fn open_dir_nofollow(base_dir: &str, rel_path: &str) -> Option { + let (parent, leaf) = open_parent_nofollow(base_dir, rel_path)?; + open_at(&parent, &leaf, DIR_FLAGS) +} + +const DIR_FLAGS: libc::c_int = libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC; + +fn open_at(dir: &OwnedFd, name: &CStr, flags: libc::c_int) -> Option { + // SAFETY: `dir` is a valid directory fd and `name` is NUL-terminated. + let raw = unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags) }; + // SAFETY: `raw` is a newly opened valid file descriptor when non-negative. + (raw >= 0).then(|| unsafe { OwnedFd::from_raw_fd(raw) }) +} + +/// Raises a real Linux VFS inotify event for `op` on `rel_path` under +/// `base_dir` without following symlinks and without writing to the file. +/// +/// The event is `IN_ATTRIB`, from setting the mode the file already has: +/// Node's `fs.watch` (libuv), Chokidar, Vite, webpack, nodemon, watchdog and +/// `notify` all listen for it. Nothing reaches Windows: `drvfs` changes no +/// timestamp or attribute and raises no `ReadDirectoryChangesW` event. Writing +/// a timestamp instead loses its sub-second part on `drvfs` and comes back +/// from Windows as a new change; changing the size to raise `IN_MODIFY` could +/// cut off a write Windows makes at the same moment. +fn raise_vfs_under(base_dir: &str, rel_path: &str, op: &str) -> bool { + let Some((parent, leaf)) = open_parent_nofollow(base_dir, rel_path) else { return false }; + match op { + "M" | "C" | "A" => { + let Some(fd) = open_at(&parent, &leaf, libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) else { return false }; + // Never a symlink (`O_PATH | O_NOFOLLOW` opens the link itself), + // FIFO, socket or device node. + fstat(&fd).is_some_and(|st| matches!(st.st_mode & libc::S_IFMT, libc::S_IFREG | libc::S_IFDIR) && chmod_same(&fd, &st)) + } + // The entry is gone: its parent directory raises the event, and a + // watcher on it reads the directory again. + "D" => fstat(&parent).is_some_and(|st| chmod_same(&parent, &st)), + _ => false, + } +} + +fn fstat(fd: &OwnedFd) -> Option { + // SAFETY: zeroed `libc::stat` filled by `fstat` on a valid fd. + unsafe { + let mut st: libc::stat = std::mem::zeroed(); + (libc::fstat(fd.as_raw_fd(), &mut st) == 0).then_some(st) + } +} + +/// Sets the mode `fd` already has, through `/proc/self/fd` (an `O_PATH` fd +/// can't be `fchmod`ed): the inode is the one `fd` was opened on, never a +/// symlink swapped in since. Raises `IN_ATTRIB` on it and its watched parent. +fn chmod_same(fd: &OwnedFd, st: &libc::stat) -> bool { + let Ok(path) = CString::new(format!("/proc/self/fd/{}", fd.as_raw_fd())) else { return false }; + // SAFETY: valid NUL-terminated path. + unsafe { libc::chmod(path.as_ptr(), st.st_mode & 0o7777) == 0 } +} + #[cfg(test)] mod tests { - use super::{Pending, valid}; + use super::{Pending, Pins, automount_root, raise_vfs_line, raise_vfs_under, split_wsl_drive_path, valid, valid_for}; + use std::ffi::CString; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::os::unix::fs::MetadataExt; + use std::path::PathBuf; + + fn temp_dir(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("kiri-fsnotify-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn watch_dir(dir: &std::path::Path, mask: u32) -> OwnedFd { + // SAFETY: standard Linux inotify syscalls on a valid NUL-terminated path. + unsafe { + let fd = libc::inotify_init1(libc::IN_NONBLOCK | libc::IN_CLOEXEC); + assert!(fd >= 0, "inotify_init1 failed"); + let c = CString::new(dir.to_str().unwrap()).unwrap(); + let wd = libc::inotify_add_watch(fd, c.as_ptr(), mask); + assert!(wd >= 0, "inotify_add_watch failed"); + OwnedFd::from_raw_fd(fd) + } + } + + fn read_inotify_masks(fd: &OwnedFd) -> Vec { + let mut buf = [0u8; 4096]; + let mut masks = Vec::new(); + loop { + // SAFETY: `fd` is a valid non-blocking inotify fd and `buf` is writable. + let n = unsafe { libc::read(fd.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; + if n <= 0 { + break; + } + let n = n as usize; + let mut off = 0; + let hdr = std::mem::size_of::(); + while off + hdr <= n { + // SAFETY: reading an unaligned `inotify_event` header within bounds. + let ev: libc::inotify_event = unsafe { std::ptr::read_unaligned(buf.as_ptr().add(off).cast()) }; + masks.push(ev.mask); + off += hdr + ev.len as usize; + } + } + masks + } #[test] fn only_paths_under_the_macs_mount() { @@ -86,7 +405,174 @@ mod tests { let mut p = Pending::default(); p.add(["D\t/mnt/mac/a", "C\t/mnt/mac/a", "M\t/mnt/mac/a"].into_iter()); p.add(["D\t/mnt/mac/a"].into_iter()); - assert_eq!(p.0.len(), 4); - assert_eq!(p.0.back().unwrap(), "D\t/mnt/mac/a\n"); + assert_eq!(p.lines.len(), 4); + assert_eq!(p.lines.back().unwrap(), "D\t/mnt/mac/a\n"); + } + + #[test] + fn wsl_drive_paths_are_validated_and_traversal_rejected() { + assert_eq!(split_wsl_drive_path("/mnt/c/Users/me/app.js", "/mnt/"), Some(("/mnt/c", "Users/me/app.js"))); + assert_eq!(split_wsl_drive_path("/windows/d/proj/x", "/windows/"), Some(("/windows/d", "proj/x"))); + assert_eq!(split_wsl_drive_path("/mnt/mac/Users/a", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c/", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c/../etc/shadow", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/mnt/c/./app.js", "/mnt/"), None); + assert_eq!(split_wsl_drive_path("/etc/passwd", "/mnt/"), None); + assert_eq!(automount_root("[automount]\nroot = /win\n"), "/win/"); + assert_eq!(automount_root(""), "/mnt/"); + + let lines = [ + "M\t/mnt/c/Users/me/app.js", + "D\t/mnt/d/old.txt", + "M\t/mnt/c/../etc/passwd", + "M\t/etc/shadow", + "M\t/mnt/c/", + ]; + assert_eq!( + valid_for(lines.into_iter(), "/mnt/").collect::>(), + ["M\t/mnt/c/Users/me/app.js\n", "D\t/mnt/d/old.txt\n"] + ); + let mut pins = Pins::default(); + assert!(!raise_vfs_line("M\t/etc/passwd\n", "/mnt/", &mut pins)); + assert!(!raise_vfs_line("M\t/mnt/c/../etc/passwd\n", "/mnt/", &mut pins)); + assert!(!raise_vfs_line("P\t/etc\n", "/mnt/", &mut pins)); + assert!(pins.walk.is_empty()); + } + + /// Pins a known mtime with nanoseconds, so a raiser that rewrites it shows. + fn pin_mtime(path: &std::path::Path, sec: i64, nsec: i64) { + let c = CString::new(path.to_str().unwrap()).unwrap(); + let times = [libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }, libc::timespec { tv_sec: sec, tv_nsec: nsec }]; + // SAFETY: valid path and timespec array. + assert_eq!(unsafe { libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), 0) }, 0); + } + + /// Holds `dir` open as `Pins` does: on `drvfs` a watch added to a directory + /// nothing holds hears of nothing (run with TMPDIR on `/mnt/c` to see). + fn pin(dir: &std::path::Path) -> OwnedFd { + let c = CString::new(dir.to_str().unwrap()).unwrap(); + // SAFETY: valid path; the fd is wrapped at once. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_PATH | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + assert!(fd >= 0); + // SAFETY: just opened. + unsafe { OwnedFd::from_raw_fd(fd) } + } + + fn mtime_and_mode(path: &std::path::Path) -> (i64, i64, u32) { + let m = std::fs::symlink_metadata(path).unwrap(); + (m.mtime(), m.mtime_nsec(), m.mode()) + } + + #[test] + fn vfs_fallback_raises_in_attrib_keeping_bytes_mtime_and_mode() { + let base = temp_dir("attrib"); + let sub = base.join("app"); + std::fs::create_dir_all(&sub).unwrap(); + let file = sub.join("main.js"); + std::fs::write(&file, b"console.log('hi');\n").unwrap(); + pin_mtime(&file, 1_700_000_123, 456_789_123); + let before = mtime_and_mode(&file); + + let _pin = pin(&sub); + let inotify = watch_dir(&sub, libc::IN_ALL_EVENTS); + for op in ["M", "C", "A"] { + assert!(raise_vfs_under(base.to_str().unwrap(), "app/main.js", op)); + let masks = read_inotify_masks(&inotify); + assert!(masks.iter().any(|m| m & libc::IN_ATTRIB != 0), "{op}: expected IN_ATTRIB, got {masks:?}"); + // O_PATH opens raise no IN_OPEN, and nothing is written. + assert!(masks.iter().all(|m| m & (libc::IN_OPEN | libc::IN_MODIFY | libc::IN_CLOSE_WRITE) == 0), "{op}: got {masks:?}"); + } + assert_eq!(std::fs::read(&file).unwrap(), b"console.log('hi');\n"); + assert_eq!(mtime_and_mode(&file), before); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn vfs_fallback_refuses_symlinks_leaf_and_intermediate() { + let base = temp_dir("symlink"); + let outside = temp_dir("symlink-outside"); + let secret = outside.join("shadow"); + std::fs::write(&secret, b"top-secret").unwrap(); + std::fs::set_permissions(&secret, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap(); + // drvfs keeps no Unix mode bits: compare with what it reports. + let mode = std::fs::symlink_metadata(&secret).unwrap().mode(); + + std::os::unix::fs::symlink(&secret, base.join("evil")).unwrap(); + std::os::unix::fs::symlink(&outside, base.join("sub")).unwrap(); + + let _pin = pin(&outside); + let inotify = watch_dir(&outside, libc::IN_ALL_EVENTS); + for op in ["M", "C", "A", "D"] { + assert!(!raise_vfs_under(base.to_str().unwrap(), "evil", op) || op == "D", "leaf symlink must be refused for {op}"); + assert!(!raise_vfs_under(base.to_str().unwrap(), "sub/shadow", op), "intermediate symlink must be refused for {op}"); + } + assert!(read_inotify_masks(&inotify).is_empty(), "target outside root must receive zero events"); + assert_eq!(std::fs::symlink_metadata(&secret).unwrap().mode(), mode); + let _ = std::fs::remove_dir_all(&base); + let _ = std::fs::remove_dir_all(&outside); + } + + #[test] + fn vfs_fallback_delete_raises_in_attrib_on_parent_keeping_mtime() { + let base = temp_dir("delete"); + let sub = base.join("proj"); + std::fs::create_dir_all(&sub).unwrap(); + pin_mtime(&sub, 1_720_000_000, 222_333_444); + let before = mtime_and_mode(&sub); + + let _pin = pin(&sub); + let inotify = watch_dir(&sub, libc::IN_ALL_EVENTS); + assert!(raise_vfs_under(base.to_str().unwrap(), "proj/gone.js", "D")); + let masks = read_inotify_masks(&inotify); + assert!(masks.iter().any(|m| m & libc::IN_ATTRIB != 0), "expected IN_ATTRIB on parent dir, got {masks:?}"); + assert_eq!(mtime_and_mode(&sub), before); + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn pins_hold_a_roots_directories_but_not_symlinks_or_skipped_trees() { + // An automount root of our own: `/` with drive `c`. + let base = temp_dir("pins"); + let root = format!("{}/", base.to_str().unwrap()); + let proj = base.join("c/proj"); + for d in ["src/a", "src/b", "node_modules/x", ".git/objects"] { + std::fs::create_dir_all(proj.join(d)).unwrap(); + } + std::fs::write(proj.join("src/file.js"), b"x").unwrap(); + let outside = temp_dir("pins-outside"); + std::os::unix::fs::symlink(&outside, proj.join("link")).unwrap(); + let p = |rel: &str| format!("{root}c/proj{rel}"); + + let mut pins = Pins::default(); + assert!(raise_vfs_line(&format!("P\t{}\n", p("")), &root, &mut pins)); + while !pins.walk.is_empty() { + pins.walk_some(&root); + } + let mut held: Vec<&str> = pins.held.keys().map(String::as_str).collect(); + held.sort(); + assert_eq!(held, [p(""), p("/src"), p("/src/a"), p("/src/b")]); + + // A watch added once the tree is pinned hears a change raised later. + let inotify = watch_dir(&proj.join("src"), libc::IN_ALL_EVENTS); + assert!(raise_vfs_line(&format!("M\t{}\n", p("/src/file.js")), &root, &mut pins)); + assert!(read_inotify_masks(&inotify).iter().any(|m| m & libc::IN_ATTRIB != 0)); + + // A new directory under a pinned one is pinned as it is raised. + std::fs::create_dir(proj.join("src/new")).unwrap(); + assert!(raise_vfs_line(&format!("C\t{}\n", p("/src/new")), &root, &mut pins)); + assert!(pins.held.contains_key(&p("/src/new"))); + + // A deleted directory lets go of its subtree; U lets go of the root. + std::fs::remove_dir_all(proj.join("src")).unwrap(); + raise_vfs_line(&format!("D\t{}\n", p("/src")), &root, &mut pins); + assert_eq!(pins.held.keys().collect::>(), [&p("")]); + assert!(raise_vfs_line(&format!("U\t{}\n", p("")), &root, &mut pins)); + assert!(pins.held.is_empty()); + + let lines = [format!("P\t{}", p("")), "P\t/mnt/mac/Users/a".to_owned(), format!("U\t{}", p(""))]; + assert_eq!(valid_for(lines.iter().map(String::as_str), &root).count(), 2); + let _ = std::fs::remove_dir_all(&base); + let _ = std::fs::remove_dir_all(&outside); } } diff --git a/crates/kiri-init/src/linux/fsview.rs b/crates/kiri-init/src/linux/fsview.rs index c84c85cba..bf0b47bee 100644 --- a/crates/kiri-init/src/linux/fsview.rs +++ b/crates/kiri-init/src/linux/fsview.rs @@ -2,6 +2,14 @@ //! from the Mac. Every path is resolved with openat2(RESOLVE_IN_ROOT): the //! container's root is `/` even for symlinks inside it, so nothing outside //! the container is reachable. +//! +//! Links are shown as links, never as what they point at (#648): a folder +//! link that leads back up, as in /sys (`virtio5/subsystem/drivers/…/virtio5`) +//! or Debian's `/usr/bin/X11 -> .`, made an endless tree that Spotlight, +//! Finder and backup tools walked until the path got too long, keeping the +//! VM busy. Tree walkers don't follow links. The kernel's own filesystems +//! (/proc, /sys and the like) are not shown at all: they hold the kernel's +//! state, not the container's files, and are large and loop on themselves. use std::ffi::CString; use std::io; @@ -71,23 +79,55 @@ fn stat_fd(fd: RawFd) -> io::Result { Ok(st) } -/// Metadata of `path`, following symlinks. RESOLVE_IN_ROOT keeps every link -/// inside the container (`/` in a link means the container's root), so a -/// link to a directory browses like the directory. A dangling link reports -/// as itself. +/// Whether `fd` is on one of the kernel's own filesystems: proc, sysfs and +/// what is mounted under them (cgroup, debugfs, tracefs, securityfs, bpf, +/// pstore, configfs, binfmt_misc, fusectl), devpts and mqueue. +fn kernel_fs(fd: RawFd) -> bool { + const MAGIC: [u64; 14] = [ + 0x9fa0, 0x6265_6572, 0x0027_e0eb, 0x6367_7270, 0x6462_6720, 0x7472_6163, 0x7365_6673, + 0xcafe_4a11, 0x6165_676c, 0x6265_6570, 0x4249_4e4d, 0x6573_5543, 0x1cd1, 0x1980_0202, + ]; + // SAFETY: fstatfs into a zeroed statfs. + let mut st: libc::statfs = unsafe { std::mem::zeroed() }; + let ok = unsafe { libc::fstatfs(fd, &mut st) } == 0; + ok && MAGIC.contains(&(st.f_type as u64)) +} + +/// `open_in`, for what the browser shows: the kernel's filesystems are not +/// there. +fn open_shown(root: RawFd, path: &str, flags: i32) -> io::Result { + let fd = open_in(root, path, flags)?; + if kernel_fs(fd.as_raw_fd()) { + return Err(io::Error::from_raw_os_error(libc::ENOENT)); + } + Ok(fd) +} + +/// Metadata of `path` itself: a link reports as a link (see the module). pub fn stat(rootfs: &Path, path: &str) -> io::Result { let root = root_of(rootfs)?; - let fd = match open_in(root.as_raw_fd(), path, libc::O_PATH) { - Ok(fd) => fd, - Err(_) => open_in(root.as_raw_fd(), path, libc::O_PATH | libc::O_NOFOLLOW)?, - }; + let fd = open_shown(root.as_raw_fd(), path, libc::O_PATH | libc::O_NOFOLLOW)?; Ok(Meta::from(&stat_fd(fd.as_raw_fd())?)) } +/// Where the link `path` points, as it says it. +pub fn read_link(rootfs: &Path, path: &str, buf: &mut Vec) -> io::Result<()> { + let root = root_of(rootfs)?; + let fd = open_shown(root.as_raw_fd(), path, libc::O_PATH | libc::O_NOFOLLOW)?; + buf.resize(libc::PATH_MAX as usize, 0); + // SAFETY: readlinkat of the link itself (an O_PATH descriptor and an + // empty name) into a buffer we own. + let n = unsafe { libc::readlinkat(fd.as_raw_fd(), c"".as_ptr(), buf.as_mut_ptr().cast(), buf.len()) }; + sys::check(n as _, "readlink")?; + buf.truncate(n as usize); + Ok(()) +} + /// A directory's entries, sorted by name, at most `MAX_ENTRIES`. pub fn list(rootfs: &Path, path: &str) -> io::Result> { let root = root_of(rootfs)?; - let dir = open_in(root.as_raw_fd(), path, libc::O_RDONLY | libc::O_DIRECTORY)?; + let dir = open_shown(root.as_raw_fd(), path, libc::O_RDONLY | libc::O_DIRECTORY)?; + let dev = stat_fd(dir.as_raw_fd())?.st_dev; let mut out = Vec::new(); // /proc/self/fd/N names the directory we already resolved safely. for entry in std::fs::read_dir(format!("/proc/self/fd/{}", dir.as_raw_fd()))? { @@ -99,15 +139,16 @@ pub fn list(rootfs: &Path, path: &str) -> io::Result> { if unsafe { libc::fstatat(dir.as_raw_fd(), c.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) } != 0 { continue; } - if st.st_mode & libc::S_IFMT == libc::S_IFLNK { - // Show what the link points at, resolved inside the container. - let target = format!("{}/{}", path.trim_end_matches('/'), name); - if let Ok(meta) = stat(rootfs, &target) { - out.push((name, meta)); - if out.len() >= MAX_ENTRIES { - break; + // Another filesystem is mounted here: left out if it is the kernel's. + if st.st_dev != dev && st.st_mode & libc::S_IFMT == libc::S_IFDIR { + // SAFETY: openat relative to the resolved directory, not following links. + let fd = unsafe { libc::openat(dir.as_raw_fd(), c.as_ptr(), libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC) }; + if fd >= 0 { + // SAFETY: openat returned a fresh descriptor. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + if kernel_fs(fd.as_raw_fd()) { + continue; } - continue; } } out.push((name, Meta::from(&st))); @@ -127,7 +168,7 @@ pub fn list(rootfs: &Path, path: &str) -> io::Result> { /// stopped every container's exec and start until it ended. pub fn read(rootfs: &Path, path: &str, offset: u64, len: usize, buf: &mut Vec) -> io::Result<()> { let root = root_of(rootfs)?; - let found = open_in(root.as_raw_fd(), path, libc::O_PATH)?; + let found = open_shown(root.as_raw_fd(), path, libc::O_PATH)?; if stat_fd(found.as_raw_fd())?.st_mode & libc::S_IFMT != libc::S_IFREG { return Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")); } @@ -186,4 +227,52 @@ mod tests { assert_eq!(buf, b"lo"); let _ = std::fs::remove_dir_all(&dir); } + + // #648: a link is a link, so a folder link back up (Debian's + // /usr/bin/X11 -> .) no longer makes an endless tree. + #[test] + fn links_are_shown_as_links() { + let dir = std::env::temp_dir().join(format!("kiri-fsview-links-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("usr/bin")).unwrap(); + std::os::unix::fs::symlink(".", dir.join("usr/bin/X11")).unwrap(); + std::os::unix::fs::symlink("/usr/bin", dir.join("bin")).unwrap(); + std::os::unix::fs::symlink("../../../../../../usr/bin", dir.join("escape")).unwrap(); + let link = |m: super::Meta| m.mode & libc::S_IFMT == libc::S_IFLNK; + + let list = super::list(&dir, "/usr/bin").unwrap(); + assert_eq!(list.iter().map(|(n, m)| (n.as_str(), link(*m))).collect::>(), [("X11", true)]); + assert!(link(super::stat(&dir, "/usr/bin/X11").unwrap())); + assert!(link(super::stat(&dir, "/bin").unwrap())); + assert!(link(super::stat(&dir, "/escape").unwrap())); + // A link on the way is still followed inside the container: only + // the last name is shown as itself. + assert!(link(super::stat(&dir, "/bin/X11").unwrap())); + assert!(link(super::stat(&dir, "/escape/X11").unwrap())); + let mut buf = Vec::new(); + super::read_link(&dir, "/usr/bin/X11", &mut buf).unwrap(); + assert_eq!(buf, b"."); + super::read_link(&dir, "/bin", &mut buf).unwrap(); + assert_eq!(buf, b"/usr/bin"); + super::read_link(&dir, "/escape/X11", &mut buf).unwrap(); + assert_eq!(buf, b"."); + assert!(super::read_link(&dir, "/usr", &mut buf).is_err(), "not a link"); + let _ = std::fs::remove_dir_all(&dir); + } + + // #648: /proc and /sys are the kernel's, not the container's files. + #[test] + fn the_kernels_filesystems_are_not_shown() { + let root = std::path::Path::new("/"); + let names: Vec = super::list(root, "/").unwrap().into_iter().map(|(n, _)| n).collect(); + assert!(names.iter().any(|n| n == "etc"), "{names:?}"); + assert!(!names.iter().any(|n| n == "proc" || n == "sys"), "{names:?}"); + for p in ["/proc", "/proc/self/status", "/sys", "/sys/kernel"] { + assert_eq!(super::stat(root, p).map_err(|e| e.kind()).err(), Some(ErrorKind::NotFound), "{p}"); + } + assert!(super::list(root, "/sys").is_err()); + let mut buf = Vec::new(); + assert!(super::read(root, "/proc/self/status", 0, 16, &mut buf).is_err()); + assert!(super::stat(root, "/etc").is_ok()); + } } diff --git a/crates/kiri-init/src/linux/hostopts.rs b/crates/kiri-init/src/linux/hostopts.rs index 6f3131e27..46b62a4a3 100644 --- a/crates/kiri-init/src/linux/hostopts.rs +++ b/crates/kiri-init/src/linux/hostopts.rs @@ -62,6 +62,16 @@ pub struct HostOpts { pub rules: Vec, /// `--group-add`: names (looked up in the container's /etc/group) or ids. pub groups: Vec, + /// `MaskedPaths` and `ReadonlyPaths` when the API set them; `None` keeps + /// the default (Docker's lists, or nothing for a privileged container). + pub masked: Option>, + pub readonly: Option>, + /// `--cgroupns host`: share the agent's cgroup namespace instead of + /// unsharing one rooted at the container's cgroup. + pub cgroupns_host: bool, + /// Timer slack (`timerslack_ns`, in nanoseconds) applied to the container's + /// init process so high-frequency background pollers coalesce cleanly (#989). + pub timer_slack_ns: Option, } fn bad(line: &str) -> io::Error { @@ -110,6 +120,27 @@ pub fn parse(list: StrList<'_>) -> io::Result { } ["devrule", kind, major, minor, perms] => o.rules.push(devices::parse_rule(kind, major, minor, perms).ok_or_else(|| bad(line))?), ["group", g] if !g.is_empty() => o.groups.push((*g).to_owned()), + [kind @ ("masked" | "readonly"), paths @ ..] => { + let paths = paths + .iter() + .map(|p| { + if p.starts_with('/') && !p.split('/').any(|c| c == "..") { + CString::new(*p).map_err(|_| bad(line)) + } else { + Err(bad(line)) + } + }) + .collect::>>()?; + *(if *kind == "masked" { &mut o.masked } else { &mut o.readonly }) = Some(paths); + } + ["cgroupns", "host"] => o.cgroupns_host = true, + ["timerslack", ns] => { + let ns: u64 = ns.parse().map_err(|_| bad(line))?; + if ns == 0 || ns > 1_000_000_000 { + return Err(bad(line)); + } + o.timer_slack_ns = Some(ns); + } _ => return Err(bad(line)), } } @@ -200,46 +231,85 @@ pub fn add_net_defaults(sysctls: &mut Vec) { sysctls.splice(0..0, mine); } +thread_local! { + static OWN_NS: std::cell::RefCell<[Option<(fs::File, (u64, u64))>; 3]> = const { std::cell::RefCell::new([None, None, None]) }; +} + +fn own_ns_entry(ns: Ns) -> io::Result<(std::os::fd::RawFd, (u64, u64))> { + let (slot, name) = match ns { + Ns::Net => (0, "net"), + Ns::Ipc => (1, "ipc"), + Ns::Uts => (2, "uts"), + }; + OWN_NS.with(|arr| { + let mut arr = arr.borrow_mut(); + if let Some((f, id)) = &arr[slot] { + return Ok((f.as_raw_fd(), *id)); + } + let f = fs::File::open(format!("/proc/self/ns/{name}"))?; + let m = f.metadata()?; + let id = (m.dev(), m.ino()); + let raw = f.as_raw_fd(); + arr[slot] = Some((f, id)); + Ok((raw, id)) + }) +} + /// Writes the sysctls from the agent, inside the container's namespaces: /// /proc/sys shows the calling task's network, IPC and UTS namespace, so /// the agent joins the one each key belongs to, writes, and comes back. /// Runs after the network is set up, so per-interface keys (eth0) exist. -pub fn apply_sysctls(pid: libc::pid_t, sysctls: &[Sysctl]) -> io::Result<()> { - for s in sysctls { - let (name, kind) = match s.ns { +pub fn apply_sysctls(pid: libc::pid_t, netns: Option<&fs::File>, sysctls: &[Sysctl]) -> io::Result<()> { + let mut i = 0; + while i < sysctls.len() { + let ns = sysctls[i].ns; + let mut end = i + 1; + while end < sysctls.len() && sysctls[end].ns == ns { + end += 1; + } + let (name, kind) = match ns { Ns::Net => ("net", libc::CLONE_NEWNET), Ns::Ipc => ("ipc", libc::CLONE_NEWIPC), Ns::Uts => ("uts", libc::CLONE_NEWUTS), }; - let own = fs::File::open(format!("/proc/self/ns/{name}"))?; - let theirs = fs::File::open(format!("/proc/{pid}/ns/{name}"))?; + let (own_fd, own_id) = own_ns_entry(ns)?; + let opened; + let theirs = match (ns, netns) { + (Ns::Net, Some(f)) => f, + _ => { + opened = fs::File::open(format!("/proc/{pid}/ns/{name}"))?; + &opened + } + }; + let tm = theirs.metadata()?; // The container shares the agent's own namespace (host network, // directly or through `--network container:`): the key would change // the whole VM or Linux host. The daemon refuses this first. - if same_namespace(&own, &theirs)? { + if (tm.dev(), tm.ino()) == own_id { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - format!("sysctl {:?} not allowed in host {name} namespace", s.path.replace('/', ".")), + format!("sysctl {:?} not allowed in host {name} namespace", sysctls[i].path.replace('/', ".")), )); } sys::setns(theirs.as_raw_fd(), kind)?; - let written = fs::write(format!("/proc/sys/{}", s.path), &s.value); + let mut result = Ok(()); + for s in &sysctls[i..end] { + if let Err(e) = fs::write(format!("/proc/sys/{}", s.path), &s.value) { + result = Err(io::Error::new(e.kind(), format!("write sysctl key {}: {}", s.path.replace('/', "."), errno_text(&e)))); + break; + } + } // Coming back must work, or the agent itself is in the container. - if let Err(e) = sys::setns(own.as_raw_fd(), kind) { + if let Err(e) = sys::setns(own_fd, kind) { eprintln!("kiri-init: cannot leave a container's {name} namespace: {e}"); std::process::abort(); } - written.map_err(|e| io::Error::new(e.kind(), format!("write sysctl key {}: {}", s.path.replace('/', "."), errno_text(&e))))?; + result?; + i = end; } Ok(()) } -/// Two /proc/*/ns files name the same namespace when their inodes match. -fn same_namespace(a: &fs::File, b: &fs::File) -> io::Result { - let (a, b) = (a.metadata()?, b.metadata()?); - Ok((a.dev(), a.ino()) == (b.dev(), b.ino())) -} - /// The limits the engine's agent sets on itself as it starts, before it /// starts anything, so that every container and build step inherits them /// (a run's own `--ulimit` still replaces them in the child). In the VM the @@ -398,7 +468,38 @@ mod tests { assert_eq!(o.devices[0].container, "/dev/fuse"); assert_eq!(o.rules.len(), 1); assert_eq!(o.groups, ["video"]); - for bad in ["sysctl\tnet\tkernel/core_pattern\t|x", "sysctl\tipc\tkernel/../x\t1", "sysctl\tuts\tkernel/hostname\tx", "rlimit\t99\t1\t1", "device\tdev\t/x\trwm", "nope"] { + assert!(o.masked.is_none() && o.readonly.is_none()); + assert!(!o.cgroupns_host); + let buf = list(&["masked", "readonly\t/proc/sys\t/data", "cgroupns\thost"]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + let o = parse(l).unwrap(); + assert_eq!(o.masked, Some(vec![])); + assert_eq!(o.readonly, Some(vec![c"/proc/sys".to_owned(), c"/data".to_owned()])); + assert!(o.cgroupns_host); + assert_eq!(o.timer_slack_ns, None); + let buf = list(&["timerslack\t10000000"]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + assert_eq!(parse(l).unwrap().timer_slack_ns, Some(10_000_000)); + for bad_path in ["masked\tproc/kcore", "masked\t/../etc", "readonly\t/proc/../etc"] { + let buf = list(&[bad_path]); + let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; + assert!(parse(l).is_err(), "{bad_path}"); + } + for bad in [ + "sysctl\tnet\tkernel/core_pattern\t|x", + "sysctl\tipc\tkernel/../x\t1", + "sysctl\tuts\tkernel/hostname\tx", + "rlimit\t99\t1\t1", + "device\tdev\t/x\trwm", + "cgroupns", + "cgroupns\tprivate", + "cgroupns\tbogus", + "timerslack", + "timerslack\t0", + "timerslack\t1000000001", + "timerslack\tnope", + "nope", + ] { let buf = list(&[bad]); let kiri_proto::Msg::Retain(l) = kiri_proto::decode(&buf).unwrap() else { panic!() }; assert!(parse(l).is_err(), "{bad}"); @@ -409,11 +510,13 @@ mod tests { fn own_namespace_is_refused() { // A "container" that is this very process shares every namespace. let me = std::process::id() as libc::pid_t; - let own = fs::File::open("/proc/self/ns/net").unwrap(); - assert!(same_namespace(&own, &fs::File::open(format!("/proc/{me}/ns/net")).unwrap()).unwrap()); - assert!(!same_namespace(&own, &fs::File::open("/proc/self/ns/ipc").unwrap()).unwrap()); + let (_, own_net) = own_ns_entry(Ns::Net).unwrap(); + let me_net = fs::File::open(format!("/proc/{me}/ns/net")).unwrap().metadata().unwrap(); + let me_ipc = fs::File::open("/proc/self/ns/ipc").unwrap().metadata().unwrap(); + assert_eq!(own_net, (me_net.dev(), me_net.ino())); + assert_ne!(own_net, (me_ipc.dev(), me_ipc.ino())); let s = Sysctl { ns: Ns::Net, path: "net/ipv4/ip_unprivileged_port_start".into(), value: "77".into() }; - let e = apply_sysctls(me, &[s]).unwrap_err(); + let e = apply_sysctls(me, None, &[s]).unwrap_err(); assert_eq!(e.to_string(), "sysctl \"net.ipv4.ip_unprivileged_port_start\" not allowed in host net namespace"); } } diff --git a/crates/kiri-init/src/linux/layers.rs b/crates/kiri-init/src/linux/layers.rs index ce663d26b..f02f067dc 100644 --- a/crates/kiri-init/src/linux/layers.rs +++ b/crates/kiri-init/src/linux/layers.rs @@ -91,25 +91,91 @@ fn sync_fs(path: &Path) -> io::Result<()> { /// Deletes every layer not in `keep` (blob digests), every layer without /// its marker, and whatever an unpack left half-done. Anything that isn't /// one of those names is left alone. +/// +/// The `.done` marker is removed before the layer directory so a layer +/// stops counting as present immediately, even if deleting its directory is +/// interrupted. pub fn retain<'a>(root: &Path, keep: impl Iterator) { let keep: std::collections::HashSet<&str> = keep.filter_map(|d| hex(d).ok()).collect(); let Ok(entries) = fs::read_dir(root) else { return }; + let mut leftovers = Vec::new(); + let mut seen = std::collections::HashSet::new(); for entry in entries.flatten() { let name = entry.file_name(); let Some(name) = name.to_str() else { continue }; - let leftover = name.starts_with(".tmp-") || name.starts_with(".stale-"); - let (h, is_marker) = match name.strip_suffix(".done") { - Some(h) => (h, true), - None => (name, false), - }; - let layer = h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()); - if !leftover && !layer { + if name.starts_with(".tmp-") || name.starts_with(".stale-") { + leftovers.push(entry.path()); continue; } - let whole = layer && root.join(h).is_dir() && root.join(format!("{h}.done")).is_file(); - if leftover || !keep.contains(h) || !whole { - let path = entry.path(); - let _ = if is_marker || !path.is_dir() { fs::remove_file(&path) } else { fs::remove_dir_all(&path) }; + let h = name.strip_suffix(".done").unwrap_or(name); + if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) { + seen.insert(h.to_owned()); + } + } + for path in leftovers { + remove_entry(&path); + } + for h in seen { + let dir = root.join(&h); + let mark = root.join(format!("{h}.done")); + let whole = dir.is_dir() && mark.is_file(); + if !keep.contains(h.as_str()) || !whole { + // Marker first: once gone, `present()` returns false even if + // removing the directory fails or is cut short. + remove_entry(&mark); + remove_entry(&dir); + } + } +} + +/// Removes a file, symlink or directory tree in the layer store. On +/// `PermissionDenied` inside a layer tree (read-only directories without +/// `CAP_DAC_OVERRIDE`), makes directories writable and retries once. +fn remove_entry(path: &Path) { + let meta = match fs::symlink_metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == io::ErrorKind::NotFound => return, + Err(e) => { + eprintln!("kiri-init: stat {}: {e}", path.display()); + return; + } + }; + if !meta.file_type().is_dir() { + if let Err(e) = fs::remove_file(path) + && e.kind() != io::ErrorKind::NotFound + { + eprintln!("kiri-init: remove {}: {e}", path.display()); + } + return; + } + match fs::remove_dir_all(path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => { + make_dirs_writable(path); + if let Err(e) = fs::remove_dir_all(path) + && e.kind() != io::ErrorKind::NotFound + { + eprintln!("kiri-init: remove {}: {e}", path.display()); + } + } + Err(e) => eprintln!("kiri-init: remove {}: {e}", path.display()), + } +} + +/// Grants owner rwx on every real directory under `root` so `remove_dir_all` +/// can unlink entries inside read-only image directories. Symlinks are never +/// followed. +fn make_dirs_writable(root: &Path) { + use std::os::unix::fs::PermissionsExt; + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + let _ = fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)); + let Ok(entries) = fs::read_dir(&dir) else { continue }; + for entry in entries.flatten() { + if entry.file_type().is_ok_and(|t| t.is_dir()) { + stack.push(entry.path()); + } } } } @@ -155,8 +221,9 @@ fn unpack(blob: &mut impl Read, media_type: &str, dest: &Path, compressed: u64) /// Unpacks a layer tarball, translating OCI whiteouts into the form overlayfs /// reads: `.wh.name` becomes a 0:0 character device `name`, and -/// `.wh..wh..opq` marks its directory opaque. -fn untar(reader: impl Read, dest: &Path) -> io::Result { +/// `.wh..wh..opq` marks its directory opaque. Also how `copy` unpacks a +/// container's imported writable layer. +pub(super) fn untar(reader: impl Read, dest: &Path) -> io::Result { untar_in(reader, dest, in_user_namespace) } @@ -165,7 +232,8 @@ fn untar(reader: impl Read, dest: &Path) -> io::Result { fn untar_in(reader: impl Read, dest: &Path, detect_userns: fn() -> bool) -> io::Result { // Only looked at once a device or fifo entry turns up. let mut userns = None; - let mut archive = tar::Archive::new(reader); + // Empty numbers in headers read as 0, as in Docker (#618). + let mut archive = tar::Archive::new(super::tarnum::GoNumbers::new(reader)); archive.set_preserve_permissions(true); archive.set_preserve_ownerships(true); archive.set_preserve_mtime(true); @@ -1488,6 +1556,32 @@ mod tests { let _ = fs::remove_dir_all(&root); } + /// Layers with read-only subdirectories (Go module caches, Nix stores) + /// are still removed along with their `.done` markers, and orphan `.done` + /// markers without a layer directory go too (#722). + #[test] + fn retain_removes_readonly_layer_dirs_and_orphan_markers() { + use std::os::unix::fs::PermissionsExt; + let root = scratch("retain-ro"); + let blob = layer_blob(&[("sub/file", b"hello")]); + send(&root, D1, &blob); + send(&root, D2, &blob); + // Make D2's subdirectory read-only (0555) so plain remove_dir_all + // fails when running without CAP_DAC_OVERRIDE. + let sub = dir(&root, D2).unwrap().join("sub"); + fs::set_permissions(&sub, fs::Permissions::from_mode(0o555)).unwrap(); + // An orphan `.done` marker with no directory beside it. + let orphan = "4".repeat(64); + fs::write(root.join(format!("{orphan}.done")), b"").unwrap(); + + retain(&root, [D1].into_iter()); + assert!(present(&root, D1), "referenced layer stays"); + assert!(!dir(&root, D2).unwrap().exists(), "unreferenced read-only layer dir must go"); + assert!(!marker(&root, D2).unwrap().exists(), "unreferenced layer .done marker must go"); + assert!(!root.join(format!("{orphan}.done")).exists(), "orphan .done marker must go"); + let _ = fs::remove_dir_all(&root); + } + /// Device nodes and fifos come out as such, numbers, owner and mode kept, /// not as the empty files the tar crate would make of them. #[test] diff --git a/crates/kiri-init/src/linux/localtime.rs b/crates/kiri-init/src/linux/localtime.rs new file mode 100644 index 000000000..b0b1e2197 --- /dev/null +++ b/crates/kiri-init/src/linux/localtime.rs @@ -0,0 +1,363 @@ +//! Ensures `/etc/localtime` (and `/etc/timezone`) is a valid timezone file or +//! symlink rather than missing or an empty directory (#938). +//! +//! Runs in `kiri-init` on WSL startup (self-healing upgraded pre-0.2.3 Kiri WSL +//! distros where Alpine minirootfs lacked `tzdata`) and guards `parse_mounts` +//! so bind-mount source creation never turns `/etc/localtime` or `/etc/timezone` +//! into a directory. + +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Canonical RFC 8536 `TZif2` binary for UTC (`UTC0`), 114 bytes: +/// v1 header (44 B) + v1 data (10 B) + v2 header (44 B) + v2 data (10 B) + +/// POSIX TZ footer (`\nUTC0\n`, 6 B). +pub const UTC_TZIF2: [u8; 114] = [ + // V1 header (44 bytes): magic "TZif", version '2', 15 reserved zero bytes, + // isutcnt=0, isstdcnt=0, leapcnt=0, timecnt=0, typecnt=1, charcnt=4. + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V1 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // V2 header (44 bytes): identical counts + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V2 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // POSIX TZ footer (6 bytes): "\nUTC0\n" + b'\n', b'U', b'T', b'C', b'0', b'\n', +]; + +static TMP_SEQ: AtomicU64 = AtomicU64::new(0); + +/// Strict validation for relative IANA zone names from `TZ`: non-empty, no +/// leading or trailing `/`, no `.` or `..` components, no `\` or `\0`, and +/// only ASCII `[A-Za-z0-9_+.-/]`. +pub fn valid_tz_name(tz: &str) -> bool { + if tz.is_empty() || tz.len() > 255 || tz.starts_with('/') || tz.ends_with('/') { + return false; + } + if !tz.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-' | b'.' | b'/')) { + return false; + } + tz.split('/').all(|c| !c.is_empty() && c != "." && c != "..") +} + +fn join_confined(root: &Path, rel: &Path) -> Option { + use std::path::Component; + let mut stack: Vec = Vec::new(); + for c in rel.components() { + match c { + Component::Normal(p) => stack.push(p.to_owned()), + Component::CurDir | Component::RootDir | Component::Prefix(_) => {} + Component::ParentDir => { + stack.pop()?; + } + } + } + let mut out = root.to_path_buf(); + for s in stack { + out.push(s); + } + Some(out) +} + +fn resolve_confined_file(root: &Path, allowed_bases: &[&Path], path: &Path) -> bool { + let Ok(canon_root) = fs::canonicalize(root) else { + return false; + }; + let mut cur = path.to_path_buf(); + for _ in 0..16 { + let Ok(meta) = fs::symlink_metadata(&cur) else { + return false; + }; + let ft = meta.file_type(); + if !ft.is_symlink() { + if !ft.is_file() || meta.len() == 0 { + return false; + } + let Ok(canon_target) = fs::canonicalize(&cur) else { + return false; + }; + if !canon_target.starts_with(&canon_root) { + return false; + } + return allowed_bases.iter().any(|base| { + fs::canonicalize(base).is_ok_and(|cb| canon_target.starts_with(&cb)) + }); + } + let Ok(target) = fs::read_link(&cur) else { + return false; + }; + let next = if target.is_absolute() { + if root != Path::new("/") && target.starts_with(root) { + let rel = target.strip_prefix(root).unwrap_or(&target); + join_confined(root, rel) + } else { + let rel = target.strip_prefix("/").unwrap_or(&target); + join_confined(root, rel) + } + } else { + let Some(parent_rel) = cur.parent().and_then(|p| p.strip_prefix(root).ok()) else { + return false; + }; + let combined = parent_rel.join(target); + join_confined(root, &combined) + }; + let Some(n) = next else { + return false; + }; + cur = n; + } + false +} + +fn resolve_symlink_is_file(root: &Path, path: &Path) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let etc = root.join("etc"); + resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path) +} + +fn zoneinfo_file_exists(root: &Path, tz: &str) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let Some(candidate) = join_confined(&zinfo, Path::new(tz)) else { + return false; + }; + resolve_confined_file(root, &[zinfo.as_path()], &candidate) +} + +fn temp_path_in(dir: &Path, prefix: &str) -> PathBuf { + let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".{prefix}.kiri.{}.{seq}.tmp", std::process::id())) +} + +fn atomic_write_file(dest: &Path, bytes: &[u8]) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + let write_res = (|| -> io::Result<()> { + let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?; + f.write_all(bytes)?; + f.set_permissions(fs::Permissions::from_mode(0o644))?; + f.sync_all()?; + Ok(()) + })(); + if let Err(e) = write_res { + let _ = fs::remove_file(&tmp); + return Err(e); + } + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn atomic_symlink(target: &str, dest: &Path) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + symlink(target, &tmp)?; + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn write_timezone_if_missing(root: &Path, zone: &str) { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) if meta.file_type().is_dir() => { + if fs::remove_dir(&tz_path).is_err() { + return; + } + } + Ok(meta) if meta.file_type().is_file() && meta.len() > 0 => return, + Ok(meta) if meta.file_type().is_symlink() && resolve_symlink_is_file(root, &tz_path) => return, + Ok(meta) if !meta.file_type().is_file() && !meta.file_type().is_symlink() => return, + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(_) => return, + } + let _ = atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()); +} + +/// Ensures `/etc/localtime` on `/` is a valid timezone file or symlink. +pub fn ensure_localtime() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_localtime_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/localtime` is a valid timezone file or symlink. +pub fn ensure_localtime_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let localtime = root.join("etc/localtime"); + match fs::symlink_metadata(&localtime) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + match fs::remove_dir(&localtime) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &localtime) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + localtime.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + if let Some(tz) = tz_env.filter(|tz| valid_tz_name(tz)) + && zoneinfo_file_exists(root, tz) + { + atomic_symlink(&format!("/usr/share/zoneinfo/{tz}"), &localtime)?; + write_timezone_if_missing(root, tz); + return Ok(()); + } + + if zoneinfo_file_exists(root, "Etc/UTC") { + atomic_symlink("/usr/share/zoneinfo/Etc/UTC", &localtime)?; + write_timezone_if_missing(root, "Etc/UTC"); + return Ok(()); + } + + atomic_write_file(&localtime, &UTC_TZIF2)?; + write_timezone_if_missing(root, "UTC"); + Ok(()) +} + +/// Ensures `/etc/timezone` on `/` is a valid timezone name file. +pub fn ensure_timezone() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_timezone_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/timezone` is a valid timezone name file (never a +/// directory), refusing to delete a non-empty directory. +pub fn ensure_timezone_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + match fs::remove_dir(&tz_path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &tz_path) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + tz_path.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + let inferred = fs::read_link(root.join("etc/localtime")) + .ok() + .and_then(|p| p.to_str().map(str::to_owned)) + .and_then(|s| s.split_once("zoneinfo/").map(|(_, z)| z.to_owned())) + .filter(|z| valid_tz_name(z)); + let zone = inferred + .as_deref() + .or_else(|| tz_env.filter(|tz| valid_tz_name(tz))) + .unwrap_or("UTC"); + atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_root(name: &str) -> PathBuf { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("kiri-init-localtime-{name}-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("etc")).unwrap(); + dir + } + + #[test] + fn repairs_empty_dir_and_refuses_non_empty_dir() { + let root = test_root("dir"); + let lt = root.join("etc/localtime"); + fs::create_dir(<).unwrap(); + ensure_localtime_at(&root, None).unwrap(); + let bytes = fs::read(<).unwrap(); + assert!(bytes.starts_with(b"TZif2")); + assert!(bytes.ends_with(b"\nUTC0\n")); + assert_eq!(bytes.len(), 114); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "UTC\n"); + + fs::remove_file(<).unwrap(); + fs::create_dir(<).unwrap(); + fs::write(lt.join("keep"), b"x").unwrap(); + assert!(ensure_localtime_at(&root, None).is_err()); + assert_eq!(fs::read(lt.join("keep")).unwrap(), b"x"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn preserves_valid_and_validates_tz() { + let root = test_root("tz"); + let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai"); + fs::create_dir_all(shanghai.parent().unwrap()).unwrap(); + fs::write(&shanghai, &UTC_TZIF2).unwrap(); + + ensure_localtime_at(&root, Some("../etc/shadow")).unwrap(); + assert!(fs::symlink_metadata(root.join("etc/localtime")).unwrap().file_type().is_file()); + + fs::remove_file(root.join("etc/localtime")).unwrap(); + fs::remove_file(root.join("etc/timezone")).unwrap(); + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai")); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Asia/Shanghai\n"); + + // Second call leaves valid symlink untouched. + ensure_localtime_at(&root, None).unwrap(); + assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai")); + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri-init/src/linux/mod.rs b/crates/kiri-init/src/linux/mod.rs index 6a3bc8a57..c7e8507af 100644 --- a/crates/kiri-init/src/linux/mod.rs +++ b/crates/kiri-init/src/linux/mod.rs @@ -2,6 +2,7 @@ mod agent; mod cgroup; mod container; mod devices; +mod disk; mod copy; mod dns; mod fsnotify; @@ -10,13 +11,16 @@ mod fsview; mod hostopts; mod inroot; mod layers; +mod localtime; mod net; mod netlink; mod pid1; mod relay; mod roots; mod seccomp; +mod swap; mod sys; +mod tarnum; mod transport; mod trim; mod usb; @@ -25,7 +29,7 @@ mod volmount; use std::fs::File; use std::io::{self, Read, Write}; -use std::os::unix::fs::PermissionsExt; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::path::PathBuf; use kiri_proto::{HOST_PORT, Hello, Msg, PROTOCOL}; @@ -36,6 +40,7 @@ use sys::{boottime_ns, check, mount}; const DATA: &str = "/var/lib/kiri"; pub fn main() { + install_panic_hook(); let init_start_ns = boottime_ns(); let result = run(init_start_ns); if let Err(e) = &result { @@ -48,6 +53,71 @@ pub fn main() { power_off(); } +/// Stack buffer size for panic reporting: avoids heap allocation in the panic +/// hook so panics during OOM or inside `eprintln!` still log cleanly. +const PANIC_BUF_LEN: usize = 512; + +/// With `panic = "abort"`, a panic in PID 1 or the host agent would otherwise +/// abort without leaving a message on the console/stderr. Format into a fixed +/// stack buffer and write directly to `STDERR_FILENO` via `libc::write` (no +/// heap allocation and no `std::io::stderr()` RefCell/lock, so a panic during +/// OOM or inside `eprintln!` argument formatting cannot double-panic). +fn install_panic_hook() { + std::panic::set_hook(Box::new(|info| { + let payload = info + .payload() + .downcast_ref::<&'static str>() + .copied() + .or_else(|| info.payload().downcast_ref::().map(String::as_str)); + let location = info.location().map(|l| (l.file(), l.line())); + let mut buf = [0u8; PANIC_BUF_LEN]; + let msg = format_panic_message(&mut buf, location, payload); + write_stderr_all(msg); + })); +} + +fn format_panic_message<'a>( + buf: &'a mut [u8], + location: Option<(&str, u32)>, + payload: Option<&str>, +) -> &'a [u8] { + if buf.is_empty() { + return &[]; + } + let what = payload.unwrap_or("a panic payload that is not a string"); + let mut cur = io::Cursor::new(&mut *buf); + let res = match location { + Some((file, line)) => write!(cur, "kiri-init: panic at {file}:{line}: {what}\n"), + None => write!(cur, "kiri-init: panic at : {what}\n"), + }; + let len = cur.position() as usize; + if res.is_err() { + let mut end = len.min(buf.len() - 1); + // Back up past any UTF-8 continuation bytes so truncation ends on a + // character boundary before overwriting the final byte with '\n'. + while end > 0 && (buf[end] & 0b1100_0000) == 0b1000_0000 { + end -= 1; + } + buf[end] = b'\n'; + return &buf[..=end]; + } + &buf[..len] +} + +fn write_stderr_all(mut bytes: &[u8]) { + while !bytes.is_empty() { + // SAFETY: writing a valid stack slice directly to STDERR_FILENO. + let n = unsafe { libc::write(libc::STDERR_FILENO, bytes.as_ptr().cast(), bytes.len()) }; + if n > 0 { + bytes = &bytes[n as usize..]; + } else if n < 0 && io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) { + continue; + } else { + break; + } + } +} + fn run(init_start_ns: u64) -> io::Result<()> { // Before anything starts: every container and step inherits them. engine_rlimits(); @@ -152,7 +222,18 @@ fn mount_kernel_filesystems() -> io::Result<()> { fn host_dirs() -> io::Result { // SAFETY: umask only changes this process's file-creation mask. unsafe { libc::umask(0o022) }; + // Claim the network namespace BEFORE touching `/var/lib/kiri` mounts so a + // second engine never detaches a running engine's mount before failing. + net::claim_host_netns()?; let root = PathBuf::from(DATA); + if let Some(data) = std::env::var_os("KIRI_AGENT_DATA").map(PathBuf::from).filter(|p| p.is_absolute() && p != &root) { + mount_agent_data(&data, &root)?; + } else { + detach_deleted_bind_mount(&root); + } + if let Some(kind) = sys::detect_readonly_fs(&root) { + return Err(sys::readonly_storage_error(kind)); + } let mkdir = |p: &std::path::Path, mode: u32| -> io::Result<()> { std::fs::create_dir_all(p)?; std::fs::set_permissions(p, std::fs::Permissions::from_mode(mode)) @@ -163,13 +244,24 @@ fn host_dirs() -> io::Result { let leftovers = || { let Ok(old) = std::fs::read_to_string(root.join("agent.cgroup")) else { return }; let old = PathBuf::from(old.trim()); - if old.starts_with("/sys/fs/cgroup") { - let paths = container::Paths { layers: root.join("layers"), containers: root.join("containers"), cgroup: old.clone() }; + if is_cgroup2_dir(&old) { + let paths = container::Paths { + layers: root.join("layers"), + containers: root.join("containers"), + cgroup: old.clone(), + cgroup_root: old.clone(), + }; container::sweep(&paths, &old); } }; take_over(&root, leftovers)?; - let paths = container::Paths { layers: root.join("layers"), containers: root.join("containers"), cgroup: host_cgroup()? }; + let (cgroup_root, cgroup) = host_cgroup()?; + let paths = container::Paths { + layers: root.join("layers"), + containers: root.join("containers"), + cgroup, + cgroup_root, + }; mkdir(&paths.layers, 0o700)?; mkdir(&paths.containers, 0o700)?; // What an agent that died uncleanly left running: under the cgroup it @@ -177,7 +269,7 @@ fn host_dirs() -> io::Result { let record = root.join("agent.cgroup"); if let Ok(old) = std::fs::read_to_string(&record) { let old = PathBuf::from(old.trim()); - if old != paths.cgroup && old.starts_with("/sys/fs/cgroup") { + if old != paths.cgroup && is_cgroup2_dir(&old) { container::sweep(&paths, &old); } } @@ -187,6 +279,65 @@ fn host_dirs() -> io::Result { Ok(paths) } +/// Bind-mounts `src` (the chosen folder's `agent` directory, from +/// `KIRI_AGENT_DATA`) onto `/var/lib/kiri` so every agent path stays under +/// `/var/lib/kiri` while living on the chosen disk. No-op when `src` is +/// already mounted there; detaches any other mount on `target` first. +fn mount_agent_data(src: &std::path::Path, target: &std::path::Path) -> io::Result<()> { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::MetadataExt; + std::fs::create_dir_all(src)?; + std::fs::create_dir_all(target)?; + let (sm, tm) = (std::fs::metadata(src)?, std::fs::metadata(target)?); + if (sm.dev(), sm.ino()) == (tm.dev(), tm.ino()) { + return Ok(()); + } + let c_target = CString::new(target.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + if std::fs::read_to_string("/proc/self/mountinfo").is_ok_and(|m| is_mounted_at(&m, target)) { + // SAFETY: valid NUL-terminated path; detaches a stale mount at `target`. + unsafe { libc::umount2(c_target.as_ptr(), libc::MNT_DETACH) }; + } + let c_src = CString::new(src.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + // SAFETY: valid NUL-terminated paths for a bind mount (fstype and data unused). + check(unsafe { libc::mount(c_src.as_ptr(), c_target.as_ptr(), std::ptr::null(), libc::MS_BIND, std::ptr::null()) } as _, "bind-mount KIRI_AGENT_DATA").map(drop) +} + +/// If `target` (`/var/lib/kiri`) is currently covered by a stale bind mount +/// whose backing directory was deleted (`st_nlink == 0`), detaches it so +/// `create_dir_all` can use the underlying `/var/lib/kiri` directory instead +/// of failing with `ENOENT`. Real filesystem roots always have `st_nlink >= 2`. +fn detach_deleted_bind_mount(target: &std::path::Path) { + use std::ffi::CString; + use std::os::unix::ffi::OsStrExt; + use std::os::unix::fs::MetadataExt; + let Ok(c_target) = CString::new(target.as_os_str().as_bytes()) else { return }; + for _ in 0..4 { + let Ok(md) = std::fs::symlink_metadata(target) else { break }; + if md.file_type().is_symlink() || md.nlink() != 0 { + break; + } + if !std::fs::read_to_string("/proc/self/mountinfo").is_ok_and(|m| is_mounted_at(&m, target)) { + break; + } + // SAFETY: valid NUL-terminated non-symlink mountpoint; `UMOUNT_NOFOLLOW` + // prevents following any racing symlink replacement. + if unsafe { libc::umount2(c_target.as_ptr(), libc::MNT_DETACH | libc::UMOUNT_NOFOLLOW) } != 0 { + eprintln!("kiri-init: detach deleted bind mount on {}: {}", target.display(), io::Error::last_os_error()); + break; + } + } +} + +/// Whether `/proc/self/mountinfo` lists a mount whose target is `target`. +fn is_mounted_at(mountinfo: &str, target: &std::path::Path) -> bool { + let want = target.to_string_lossy(); + mountinfo.lines().any(|line| { + let Some((before, _)) = line.split_once(" - ") else { return false }; + before.split_whitespace().nth(4).is_some_and(|mp| unescape_mount_path(mp) == want) + }) +} + /// The lock on a Linux host's data directory, held while the agent runs. static AGENT_LOCK: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -271,6 +422,95 @@ fn is_daemon(pid: libc::pid_t) -> bool { pid > 1 && std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| c.split(|b| *b == 0).any(|a| a == b"daemon")) } +fn is_cgroup2_dir(path: &std::path::Path) -> bool { + path.is_absolute() && path.is_dir() && sys::is_cgroup2(path) +} + +/// The cgroup v2 path relative to the unified hierarchy root from `/proc/self/cgroup`. +fn cgroup2_rel(proc_cgroup: &str) -> String { + proc_cgroup.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("/").trim().trim_start_matches('/').to_owned() +} + +/// Unescapes `/proc/self/mountinfo` octal escapes (`\040`, `\011`, `\012`, `\134`). +fn unescape_mount_path(raw: &str) -> String { + sys::unescape_mount_path(raw) +} + +/// Writable `cgroup2` mounts visible in `/proc/self/mountinfo`, ordered by +/// preference: `/sys/fs/cgroup`, `/sys/fs/cgroup/unified` (stock WSL 2 and +/// hybrid systemd), other mounts under `/sys/fs/cgroup/`, then any other +/// top-level (`root == "/"`) mount. Overmounted entries (for example `tmpfs` +/// stacked over an earlier `cgroup2` mount) are excluded because only the last +/// mount on each path is active. +fn cgroup2_mounts(mountinfo: &str) -> Vec { + struct Entry { + fstype: String, + root: String, + rw: bool, + } + let has_ro = |opts: &str| opts.split(',').any(|o| o == "ro"); + let mut active: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let mut b = before.split_whitespace(); + let (Some(_id), Some(_parent), Some(_dev), Some(root), Some(mp), Some(mopts)) = + (b.next(), b.next(), b.next(), b.next(), b.next(), b.next()) + else { + continue; + }; + let mut a = after.split_whitespace(); + let (Some(fstype), Some(_src), Some(sopts)) = (a.next(), a.next(), a.next()) else { continue }; + let mp = unescape_mount_path(mp); + active.insert( + mp, + Entry { fstype: fstype.to_owned(), root: unescape_mount_path(root), rw: !has_ro(mopts) && !has_ro(sopts) }, + ); + } + let mut found: Vec<(u8, PathBuf)> = active + .into_iter() + .filter(|(mp, e)| e.fstype == "cgroup2" && e.rw && mp != DATA && !mp.starts_with("/var/lib/kiri/")) + .map(|(mp, e)| { + let tier = if mp == "/sys/fs/cgroup" { + 0 + } else if mp == "/sys/fs/cgroup/unified" { + 1 + } else if mp.starts_with("/sys/fs/cgroup/") && e.root == "/" { + 2 + } else if e.root == "/" { + 3 + } else { + 4 + }; + (tier, PathBuf::from(mp)) + }) + .collect(); + found.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))); + found.into_iter().map(|(_, p)| p).collect() +} + +/// Finds an already-mounted writable `cgroup2` hierarchy (unified +/// `/sys/fs/cgroup`, stock WSL 2's `/sys/fs/cgroup/unified`, or another +/// mountpoint), or mounts one when none is present yet. +fn cgroup2_root() -> io::Result { + let is_usable = |p: &std::path::Path| sys::is_cgroup2(p) && p.join("cgroup.controllers").exists(); + let default = PathBuf::from("/sys/fs/cgroup"); + if is_usable(&default) { + return Ok(default); + } + if let Ok(mountinfo) = std::fs::read_to_string("/proc/self/mountinfo") { + for cand in cgroup2_mounts(&mountinfo) { + if is_usable(&cand) { + return Ok(cand); + } + } + } + let unified = PathBuf::from("/sys/fs/cgroup/unified"); + if is_usable(&unified) { + return Ok(unified); + } + mount_cgroup2(&default) +} + /// The cgroup containers go under on a Linux host, chosen as dockerd and /// containerd choose theirs on cgroup v2: /// @@ -289,12 +529,17 @@ fn is_daemon(pid: libc::pid_t) -> bool { /// /// Started again from inside a `kiri-host` leaf (the daemon stays there /// when its agent restarts), it is not nested again. -fn host_cgroup() -> io::Result { +/// +/// Returns `(cgroup_root, containers_cgroup)`. On a hybrid cgroup tree +/// (stock WSL 2, where `/sys/fs/cgroup` is a tmpfs holding v1 mounts and +/// `cgroup2` is at `/sys/fs/cgroup/unified`), `cgroup_root` is that +/// `cgroup2` mountpoint rather than `/sys/fs/cgroup`. +fn host_cgroup() -> io::Result<(PathBuf, PathBuf)> { let own = std::fs::read_to_string("/proc/self/cgroup")?; - let rel = own.lines().find_map(|l| l.strip_prefix("0::")).unwrap_or("/").trim().trim_start_matches('/').to_owned(); - let root = PathBuf::from("/sys/fs/cgroup"); - if !root.join("cgroup.controllers").exists() { - mount_cgroup2(&root)?; + let rel = cgroup2_rel(&own); + let root = cgroup2_root()?; + if root != std::path::Path::new("/sys/fs/cgroup") { + eprintln!("kiri-init: using cgroup v2 at {}", root.display()); } let own = root.join(&rel); let mut base = own.clone(); @@ -318,18 +563,18 @@ fn host_cgroup() -> io::Result { if root.join("cgroup.type").exists() { to_leaf(procs(&root)); } - root - } else if delegated(&own, &procs(&own)) { + root.clone() + } else if own.is_dir() && delegated(&own, &procs(&own)) { if own != base.join("kiri-host") { to_leaf(procs(&own)); } base } else { - root + root.clone() }; let kiri = base.join("kiri"); containers_cgroup(&kiri); - Ok(kiri) + Ok((root, kiri)) } /// Makes the cgroup containers go under, with the controllers handed down @@ -347,18 +592,54 @@ pub fn containers_cgroup(kiri: &std::path::Path) { } } -/// `ip netns exec` mounts a fresh /sys for its network namespace, without -/// the cgroup tree, and every container start then failed with ENOENT. An -/// empty /sys/fs/cgroup gets cgroup2 mounted on it (in that command's -/// private mount namespace, so nothing outside changes); anything else -/// there (cgroup v1) fails the start now, saying why. -fn mount_cgroup2(root: &std::path::Path) -> io::Result<()> { - let empty = std::fs::read_dir(root).map(|mut d| d.next().is_none()); - match empty { - Ok(true) => mount(c"cgroup2", c"/sys/fs/cgroup", c"cgroup2", libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC, None) - .map_err(|e| io::Error::new(e.kind(), format!("/sys/fs/cgroup has no cgroup tree (ip netns exec remounts /sys) and mounting cgroup2 there failed: {e}"))), - Ok(false) => Err(io::Error::new(io::ErrorKind::Unsupported, "Kiri needs cgroup v2 at /sys/fs/cgroup (this machine has cgroup v1 or a hybrid tree there)")), - Err(e) => Err(io::Error::new(e.kind(), format!("/sys/fs/cgroup: {e}; Kiri needs cgroup v2 mounted there"))), +/// Mounts `cgroup2` when none is mounted yet: +/// - An empty `/sys/fs/cgroup` (e.g. `ip netns exec` remounted a fresh `/sys`) +/// gets `cgroup2` mounted directly on `/sys/fs/cgroup`. +/// - A non-empty `/sys/fs/cgroup` (e.g. a cgroup v1 tree without +/// `/sys/fs/cgroup/unified` mounted yet) leaves the existing v1 mounts +/// untouched and mounts `cgroup2` at `/sys/fs/cgroup/unified`, falling back +/// to `/run/kiri/cgroup` if `/sys/fs/cgroup` is not writable. +fn mount_cgroup2(root: &std::path::Path) -> io::Result { + let flags = libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC; + let is_empty = |p: &std::path::Path| std::fs::read_dir(p).map(|mut d| d.next().is_none()); + let try_mount = |target: &std::path::Path| -> io::Result<()> { + let t = sys::cstr(target)?; + mount(c"cgroup2", &t, c"cgroup2", flags, None) + }; + match is_empty(root) { + Ok(true) => { + try_mount(root).map_err(|e| { + io::Error::new( + e.kind(), + format!("/sys/fs/cgroup has no cgroup tree (ip netns exec remounts /sys) and mounting cgroup2 there failed: {e}"), + ) + })?; + return Ok(root.to_path_buf()); + } + Ok(false) => {} + Err(e) => { + return Err(io::Error::new(e.kind(), format!("/sys/fs/cgroup: {e}; Kiri needs cgroup v2 mounted there"))); + } + } + let mut last_err = None; + for candidate in [root.join("unified"), PathBuf::from("/run/kiri/cgroup")] { + let _ = std::fs::create_dir_all(&candidate); + if is_empty(&candidate).unwrap_or(false) { + match try_mount(&candidate) { + Ok(()) => return Ok(candidate), + Err(e) => last_err = Some((candidate, e)), + } + } + } + match last_err { + Some((p, e)) => Err(io::Error::new( + e.kind(), + format!("Kiri needs cgroup v2; no cgroup2 mount was found and mounting cgroup2 at {} failed: {e}", p.display()), + )), + None => Err(io::Error::new( + io::ErrorKind::Unsupported, + "Kiri needs cgroup v2; no cgroup2 mount was found and neither /sys/fs/cgroup/unified nor /run/kiri/cgroup was available", + )), } } @@ -370,7 +651,7 @@ fn delegated(own: &std::path::Path, pids: &[String]) -> bool { return true; } let (me, parent) = (std::process::id().to_string(), std::os::unix::process::parent_id().to_string()); - pids.iter().all(|p| *p == me || *p == parent) + !pids.is_empty() && pids.iter().all(|p| *p == me || *p == parent) } /// Mounts the data disk (or a tmpfs without one), creates the layer and @@ -384,12 +665,21 @@ fn data_dirs() -> io::Result { if let Err(ref e) = disk { eprintln!("kiri-init: no data disk ({e}); keeping images in memory"); mount(c"kiri", c"/var/lib/kiri", c"tmpfs", libc::MS_NOATIME, Some(c"mode=0755"))?; + } else { + if let Err(e) = disk::grow() { + eprintln!("kiri-init: growing data disk: {e}"); + } + if let Some(kind) = sys::detect_readonly_fs(std::path::Path::new(DATA)) { + return Err(sys::readonly_storage_error(kind)); + } } // The Mac's filesystem over virtiofs, for bind mounts. sys::mkdir(c"/mnt", 0o755); sys::mkdir(c"/mnt/mac", 0o755); if let Err(e) = mount(c"kiri-mac", c"/mnt/mac", c"virtiofs", libc::MS_NOATIME, None) { eprintln!("kiri-init: no Mac file share ({e}); bind mounts of Mac paths will fail"); + } else if let Err(e) = mac_readahead() { + eprintln!("kiri-init: keeping the Mac file share's default read-ahead ({e})"); } // An x86-64 guest (Intel Macs, WSL2) runs amd64 binaries natively. #[cfg(target_arch = "aarch64")] @@ -400,6 +690,7 @@ fn data_dirs() -> io::Result { layers: root.join("layers"), containers: root.join("containers"), cgroup: PathBuf::from("/sys/fs/cgroup/kiri"), + cgroup_root: PathBuf::from("/sys/fs/cgroup"), }; std::fs::create_dir_all(&paths.layers)?; std::fs::create_dir_all(&paths.containers)?; @@ -417,11 +708,22 @@ fn data_dirs() -> io::Result { // Overlay lower dirs are given relative to the layer store. std::env::set_current_dir(&paths.layers)?; if disk.is_ok() { + // On the data disk only: swap in the tmpfs fallback would be memory. + swap::start(); trim::start(DATA); } Ok(paths) } +/// Batch sequential reads across virtiofs without changing cache coherence. +/// Only the Mac share's backing device is changed; Rosetta and the data disk +/// keep their own settings. Older kernels may omit this optional tuning. +fn mac_readahead() -> io::Result<()> { + let device = std::fs::metadata("/mnt/mac")?.dev(); + let path = format!("/sys/class/bdi/{}:{}/read_ahead_kb", libc::major(device), libc::minor(device)); + sys::write_file(&path, "1024\n") +} + /// x86-64 Linux binaries through Rosetta, when the Mac shares it: amd64 /// images then run as they do on Docker Desktop and OrbStack. The `F` flag /// opens the interpreter now, so it works inside every container's mounts. @@ -465,23 +767,29 @@ fn dial_host() -> io::Result { Err(io::Error::new(last.kind(), format!("dial host: {last}"))) } -/// MemTotal, MemAvailable and (when the kernel reports it) Balloon in KiB. -fn meminfo_full() -> (u64, u64, Option) { - let Ok(s) = std::fs::read_to_string("/proc/meminfo") else { return (0, 0, None) }; - let (total, avail, balloon) = parse_meminfo(&s); +/// MemTotal, MemAvailable and (when the kernel reports them) Balloon and +/// Committed_AS in KiB. +fn meminfo_full() -> (u64, u64, Option, Option) { + let Ok(s) = std::fs::read_to_string("/proc/meminfo") else { return (0, 0, None, None) }; + let (total, avail, balloon, committed) = parse_meminfo(&s); // Older kernels without `Balloon:` in /proc/meminfo still expose // balloon_inflate / balloon_deflate in /proc/vmstat inside the VM. let balloon = balloon.or_else(|| (std::process::id() == 1).then(vmstat_balloon_kib).flatten()); - (total, avail, balloon) + (total, avail, balloon, committed) } -fn parse_meminfo(s: &str) -> (u64, u64, Option) { +fn parse_meminfo(s: &str) -> (u64, u64, Option, Option) { let field = |name: &str| { s.lines() .find_map(|l| l.strip_prefix(name)) .and_then(|rest| rest.trim().trim_end_matches("kB").trim().parse().ok()) }; - (field("MemTotal:").unwrap_or(0), field("MemAvailable:").unwrap_or(0), field("Balloon:")) + ( + field("MemTotal:").unwrap_or(0), + field("MemAvailable:").unwrap_or(0), + field("Balloon:"), + field("Committed_AS:"), + ) } fn vmstat_balloon_kib() -> Option { @@ -506,7 +814,7 @@ fn parse_vmstat_balloon_kib(s: &str, page_kib: u64) -> Option { /// MemTotal and MemAvailable in KiB. fn meminfo() -> (u64, u64) { - let (total, avail, _) = meminfo_full(); + let (total, avail, _, _) = meminfo_full(); (total, avail) } @@ -574,13 +882,15 @@ mod take_over_tests { #[cfg(test)] mod meminfo_tests { #[test] - fn meminfo_reads_balloon_when_present() { - let with = "MemTotal: 24656160 kB\nMemFree: 24297640 kB\nMemAvailable: 24122580 kB\nBalloon: 262144 kB\n"; - assert_eq!(super::parse_meminfo(with), (24_656_160, 24_122_580, Some(262_144))); - let zero = "MemTotal: 8211244 kB\nMemAvailable: 8000000 kB\nBalloon: 0 kB\n"; - assert_eq!(super::parse_meminfo(zero), (8_211_244, 8_000_000, Some(0))); + fn meminfo_reads_balloon_and_committed_as_when_present() { + let with = "MemTotal: 24656160 kB\nMemFree: 24297640 kB\nMemAvailable: 24122580 kB\nCommitLimit: 12328080 kB\nCommitted_AS: 2097152 kB\nBalloon: 262144 kB\n"; + assert_eq!(super::parse_meminfo(with), (24_656_160, 24_122_580, Some(262_144), Some(2_097_152))); + let zero = "MemTotal: 8211244 kB\nMemAvailable: 8000000 kB\nCommitted_AS: 0 kB\nBalloon: 0 kB\n"; + assert_eq!(super::parse_meminfo(zero), (8_211_244, 8_000_000, Some(0), Some(0))); + let only_committed = "MemTotal: 8211244 kB\nMemAvailable: 8000000 kB\nCommitted_AS: 2148352 kB\n"; + assert_eq!(super::parse_meminfo(only_committed), (8_211_244, 8_000_000, None, Some(2_148_352))); let without = "MemTotal: 8211244 kB\nMemAvailable: 8000000 kB\n"; - assert_eq!(super::parse_meminfo(without), (8_211_244, 8_000_000, None)); + assert_eq!(super::parse_meminfo(without), (8_211_244, 8_000_000, None, None)); } #[test] @@ -591,3 +901,132 @@ mod meminfo_tests { assert_eq!(super::parse_vmstat_balloon_kib("nr_free_pages 100\n", 4), None); } } + +#[cfg(test)] +mod cgroup_discovery_tests { + use std::path::{Path, PathBuf}; + + #[test] + fn stock_wsl2_hybrid_mountinfo_picks_unified() { + let mountinfo = "\ +28 24 0:26 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755 +29 28 0:27 / /sys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate +30 28 0:28 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpuset +31 28 0:29 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,cpu +32 28 0:30 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,memory +33 28 0:31 / /sys/fs/cgroup/pids rw,nosuid,nodev,noexec,relatime - cgroup cgroup rw,pids +"; + assert_eq!(super::cgroup2_mounts(mountinfo), vec![PathBuf::from("/sys/fs/cgroup/unified")]); + } + + #[test] + fn overmounted_cgroup2_at_root_is_skipped_for_unified() { + // Simulates tmpfs stacked over an earlier /sys/fs/cgroup cgroup2 mount + // (as happens in a mount namespace or hybrid remount): only the active + // topmost mount per path counts. + let mountinfo = "\ +37 27 0:32 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime shared:10 - cgroup2 cgroup2 rw,nsdelegate +200 37 0:60 / /sys/fs/cgroup rw,relatime - tmpfs tmpfs rw,mode=755 +201 200 0:32 / /sys/fs/cgroup/unified rw,relatime - cgroup2 cgroup2 rw,nsdelegate +"; + assert_eq!(super::cgroup2_mounts(mountinfo), vec![PathBuf::from("/sys/fs/cgroup/unified")]); + } + + #[test] + fn pure_v2_mount_is_preferred_over_secondary_mounts() { + let mountinfo = "\ +37 27 0:32 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate +90 27 0:32 / /sys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw,nsdelegate +91 27 0:32 / /run/kiri/cgroup rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +"; + assert_eq!( + super::cgroup2_mounts(mountinfo), + vec![ + PathBuf::from("/sys/fs/cgroup"), + PathBuf::from("/sys/fs/cgroup/unified"), + PathBuf::from("/run/kiri/cgroup"), + ] + ); + } + + #[test] + fn readonly_and_container_cgroup2_mounts_are_ignored() { + let mountinfo = "\ +40 28 0:27 / /sys/fs/cgroup/unified ro,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 rw +41 28 0:27 / /sys/fs/cgroup/other rw,nosuid,nodev,noexec,relatime - cgroup2 cgroup2 ro +42 28 0:27 / /var/lib/kiri/containers/abc/rootfs/sys/fs/cgroup rw - cgroup2 cgroup2 rw +43 28 0:27 / /run/kiri/cgroup rw,nosuid,nodev,noexec - cgroup2 cgroup2 rw +"; + assert_eq!(super::cgroup2_mounts(mountinfo), vec![PathBuf::from("/run/kiri/cgroup")]); + } + + #[test] + fn mountinfo_octal_escapes_are_decoded() { + assert_eq!(super::unescape_mount_path(r"/mnt/my\040dir\134sub"), r"/mnt/my dir\sub"); + } + + #[test] + fn cgroup2_rel_parses_hybrid_proc_cgroup() { + let wsl_root = "15:name=systemd:/\n2:memory:/\n1:cpuset:/\n0::/\n"; + assert_eq!(super::cgroup2_rel(wsl_root), ""); + let systemd_hybrid = "12:memory:/system.slice/kiri.service\n0::/system.slice/kiri.service\n"; + assert_eq!(super::cgroup2_rel(systemd_hybrid), "system.slice/kiri.service"); + } + + #[test] + fn delegated_requires_non_empty_pids_for_non_service_cgroup() { + assert!(!super::delegated(Path::new("/sys/fs/cgroup/unified/init.scope"), &[])); + assert!(super::delegated(Path::new("/sys/fs/cgroup/unified/system.slice/kiri.service"), &[])); + assert!(super::delegated(Path::new("/sys/fs/cgroup/unified/custom"), &[std::process::id().to_string()])); + } + + #[test] + fn is_mounted_at_finds_exact_mountpoint() { + let mountinfo = "\ +28 1 8:1 / / rw,relatime - ext4 /dev/sda1 rw +55 28 8:2 /kiri/agent /var/lib/kiri rw,relatime - ext4 /dev/sdb1 rw +56 28 8:2 /sub /var/lib/kiri/volumes/x rw,relatime - ext4 /dev/sdb1 rw +"; + assert!(super::is_mounted_at(mountinfo, Path::new("/var/lib/kiri"))); + assert!(!super::is_mounted_at(mountinfo, Path::new("/var/lib"))); + assert!(!super::is_mounted_at(mountinfo, Path::new("/media/ssd"))); + } +} + +#[cfg(test)] +mod panic_hook_tests { + #[test] + fn formats_panic_location_and_payload_into_stack_buffer() { + let mut buf = [0u8; super::PANIC_BUF_LEN]; + assert_eq!( + super::format_panic_message(&mut buf, Some(("crates/kiri-init/src/linux/agent.rs", 42)), Some("boom")), + b"kiri-init: panic at crates/kiri-init/src/linux/agent.rs:42: boom\n" + ); + assert_eq!( + super::format_panic_message(&mut buf, None, Some("oops")), + b"kiri-init: panic at : oops\n" + ); + assert_eq!( + super::format_panic_message(&mut buf, Some(("mod.rs", 7)), None), + b"kiri-init: panic at mod.rs:7: a panic payload that is not a string\n" + ); + + // Oversized messages truncate cleanly inside the fixed stack buffer + // with a trailing newline and valid UTF-8. + let long = "x".repeat(super::PANIC_BUF_LEN * 2); + let out = super::format_panic_message(&mut buf, Some(("a.rs", 1)), Some(&long)); + assert_eq!(out.len(), super::PANIC_BUF_LEN); + assert!(out.ends_with(b"\n")); + assert!(std::str::from_utf8(out).is_ok()); + + let mut small = [0u8; 34]; + // "kiri-init: panic at a.rs:1: " is 28 bytes; "éééé" has 2-byte UTF-8 chars. + let out = super::format_panic_message(&mut small, Some(("a.rs", 1)), Some("éééé")); + assert!(out.ends_with(b"\n")); + let text = std::str::from_utf8(out).expect("truncated output must stay valid UTF-8"); + assert!(text.starts_with("kiri-init: panic at a.rs:1: ")); + + let mut empty = []; + assert_eq!(super::format_panic_message(&mut empty, Some(("a.rs", 1)), Some("x")), b""); + } +} diff --git a/crates/kiri-init/src/linux/net.rs b/crates/kiri-init/src/linux/net.rs index f64305e63..a090a7bc8 100644 --- a/crates/kiri-init/src/linux/net.rs +++ b/crates/kiri-init/src/linux/net.rs @@ -11,11 +11,78 @@ use super::netlink::{self, Netlink}; use super::sys; pub const UPLINK: &str = "eth0"; -/// What `host.docker.internal` resolves to inside containers. Connections to -/// it are redirected to the agent and relayed to the Mac's localhost. +/// What `host.docker.internal` resolves to inside containers in the VM. +/// Connections to it are redirected to the agent and relayed to the Mac's localhost. pub const HOST_ADDR: [u8; 4] = [198, 19, 248, 254]; +/// What `host.docker.internal`, `host.kiri.internal`, and `host-gateway` +/// resolve to on Windows (WSL 2) when `kiri hostrelay` is active, matching +/// Docker Desktop. +pub const WSL_HOST_ADDR: [u8; 4] = [192, 168, 65, 254]; /// Where the redirect lands: the agent's listener for host-bound connections. pub const HOST_RELAY_PORT: u16 = 1026; + +/// True when running inside WSL 2. +pub fn is_wsl() -> bool { + sys::is_wsl() +} + +const HOST_RELAY_PID_FILE: &str = "/run/kiri-hostrelay.pid"; + +/// Checks whether a Linux `/proc//cmdline` (NUL-separated argv) belongs +/// to `kiri hostrelay` (empty cmdline also excludes unreaped zombies). +fn is_hostrelay_cmdline(cmdline: &[u8]) -> bool { + let mut args = cmdline.split(|&b| b == 0); + let Some(argv0) = args.next() else { return false }; + let Some(argv1) = args.next() else { return false }; + !argv0.is_empty() && argv1 == b"hostrelay" +} + +fn read_pid_file(path: &std::path::Path) -> Option { + std::fs::read_to_string(path).ok()?.trim().parse::().ok().filter(|&p| p > 0) +} + +fn pid_is_alive(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + if pid <= 0 { + return false; + } + // SAFETY: signal 0 checks process existence without sending a signal. + if unsafe { libc::kill(pid, 0) } == 0 { + return true; + } + io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) +} + +fn pid_file_alive(path: &std::path::Path, verify: impl FnOnce(u32) -> bool) -> bool { + read_pid_file(path).is_some_and(|pid| pid_is_alive(pid) && verify(pid)) +} + +fn hostrelay_pid_matches(pid: u32) -> bool { + std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| is_hostrelay_cmdline(&c)) +} + +/// True when running on WSL 2 with a live `kiri hostrelay` process owning +/// `192.168.65.254` (verified via `/run/kiri-hostrelay.pid`, `kill(pid, 0)`, +/// and `/proc//cmdline`, catching unclean exits without `getifaddrs()`). +pub fn wsl_host_relay_active() -> bool { + is_wsl() && pid_file_alive(std::path::Path::new(HOST_RELAY_PID_FILE), hostrelay_pid_matches) +} + +/// Address answered for `host.docker.internal` / `host.kiri.internal` / +/// `gateway.docker.internal` in the embedded DNS: `192.168.65.254` on WSL 2 +/// when the Windows host relay is active, else `HOST_ADDR`. +pub fn effective_host_addr() -> [u8; 4] { + effective_host_addr_for(super::transport::is_host_process(), wsl_host_relay_active()) +} + +pub fn effective_host_addr_for(host_process: bool, wsl_relay_active: bool) -> [u8; 4] { + if host_process && wsl_relay_active { WSL_HOST_ADDR } else { HOST_ADDR } +} +/// Where outbound container TCP connections to VPN tunnel prefixes or under +/// host egress land, to be relayed over vsock to the host dialer. +pub const EGRESS_RELAY_PORT: u16 = 1038; /// Container interfaces stay below this, so any uplink MTU fits. const CONTAINER_MTU: u32 = 1500; @@ -72,13 +139,79 @@ pub struct Plug { pub internal: bool, /// IPv6-only: no IPv4 address on the container or the bridge. pub no_ipv4: bool, + /// `com.docker.network.bridge.enable_icc=false`: the container's veth + /// is an isolated bridge port, so it reaches no other container on the + /// network, only the gateway and beyond. + pub no_icc: bool, } impl Plug { pub fn from_opts(opts: kiri_proto::StrList<'_>) -> Plug { use kiri_proto::net_opts as k; - Plug { internal: k::values(opts, k::INTERNAL).next().is_some(), no_ipv4: k::values(opts, k::NO_IPV4).next().is_some() } + let has = |key| k::values(opts, key).next().is_some(); + Plug { internal: has(k::INTERNAL), no_ipv4: has(k::NO_IPV4), no_icc: has(k::NO_ICC) } + } +} + +/// A network a container can reach the outside through: one that is not +/// `--internal`, with the gateways it offers. Kept per running container, in +/// the order its networks were plugged in, so that a disconnect can hand the +/// default route on to the next one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Uplink { + /// Host side of its veth, which names the attachment on a disconnect. + pub veth: String, + /// Its interface in the container: `eth0`, `eth1` … + pub ifname: String, + pub v4: Option<[u8; 4]>, + pub v6: Option<[u8; 16]>, +} + +impl Uplink { + /// None for an internal network, which never gives a default route. + pub fn of(veth: &str, ifname: &str, gateway: [u8; 4], v6: Option, plug: Plug) -> Option { + let v4 = (!plug.internal && !plug.no_ipv4).then_some(gateway); + let v6 = v6.filter(|_| !plug.internal).map(|v| v.gateway); + (v4.is_some() || v6.is_some()).then(|| Uplink { veth: veth.to_owned(), ifname: ifname.to_owned(), v4, v6 }) + } +} + +/// The uplinks that hold the IPv4 and the IPv6 default route: for each, the +/// first one plugged in that has it. `attach` adds every uplink's route and +/// the kernel keeps the first (the later ones are EEXIST), so this is the +/// same choice. Docker would take the network whose name sorts first among +/// equals; keeping the first is steadier: plugging in a network never moves +/// a running container's traffic. +pub fn route_holders(uplinks: &[Uplink]) -> (Option<&Uplink>, Option<&Uplink>) { + (uplinks.iter().find(|u| u.v4.is_some()), uplinks.iter().find(|u| u.v6.is_some())) +} + +/// Takes the attachment whose host veth is `veth` out of `uplinks`, after it +/// was unplugged. If it held a default route, the next uplink gets it, as +/// Docker moves the default gateway when a container leaves that network; +/// with none left the container has no default route, as on internal-only +/// networks. The kernel dropped the old route with the interface. +pub fn hand_over_default_routes(pid: libc::pid_t, uplinks: &mut Vec, veth: &str) -> io::Result<()> { + let (old4, old6) = route_holders(uplinks); + let (was4, was6) = (old4.is_some_and(|u| u.veth == veth), old6.is_some_and(|u| u.veth == veth)); + uplinks.retain(|u| u.veth != veth); + if !was4 && !was6 { + return Ok(()); } + let (new4, new6) = route_holders(uplinks); + let (new4, new6) = (new4.filter(|_| was4), new6.filter(|_| was6)); + if new4.is_none() && new6.is_none() { + return Ok(()); + } + let netns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; + let mut inner = Netlink::open_in(&netns)?; + if let Some(u) = new4 { + netlink::replace_default_route(&mut inner, netlink::index_in(&netns, &u.ifname)?, u.v4.unwrap_or_default())?; + } + if let Some(u) = new6 { + netlink::replace_default_route6(&mut inner, netlink::index_in(&netns, &u.ifname)?, u.v6.unwrap_or_default())?; + } + Ok(()) } pub fn ip6_str(a: [u8; 16]) -> String { @@ -106,39 +239,248 @@ pub fn parse_mac(s: &str) -> Option<[u8; 6]> { parts.next().is_none().then_some(mac) } -/// On a Linux host: the interface of the default route, already configured -/// by the host, gets the masquerade and the host.docker.internal redirect. -pub fn host_uplink() -> io::Result<()> { - let routes = std::fs::read_to_string("/proc/net/route")?; - // Iface Destination Gateway …: the default route has destination 0. - let iface = routes - .lines() - .skip(1) - .filter_map(|l| { - let f: Vec<&str> = l.split_whitespace().collect(); - (f.len() > 2 && f[1] == "00000000").then(|| f[0].to_owned()) +/// Resolves active default-route interface names across all routing tables and +/// address families (primary NICs, failover NICs, Tailscale/WireGuard VPNs, etc.). +fn default_route_ifaces() -> Vec { + netlink::default_route_ifindices().unwrap_or_default().into_iter().filter_map(netlink::name_of).collect() +} + +/// Scans `sys_net` (`/sys/class/net`) for non-Kiri Linux bridges that are not +/// themselves holding a default route (e.g. Proxmox `vmbr0`), returning a +/// sorted list of local bridges (`docker0`, `br-*`, `virbr*`, etc.) to isolate. +fn collect_foreign_bridges(sys_net: &std::path::Path, default_ifaces: &[String]) -> Vec { + let Ok(entries) = std::fs::read_dir(sys_net) else { return Vec::new() }; + let mut out: Vec = entries + .filter_map(|e| e.ok()) + .filter_map(|e| { + let name = e.file_name().to_str()?.to_owned(); + if name.starts_with("kiri") || default_ifaces.iter().any(|u| u == &name) { + return None; + } + e.path().join("bridge").is_dir().then_some(name) }) - .next() - .ok_or_else(|| io::Error::other("no default route"))?; - let index = netlink::index_of(&iface)?; + .collect(); + out.sort(); + out.dedup(); + out +} + +/// Refreshes `netlink::FOREIGN_BRIDGES`, returning `true` if the set changed. +fn update_foreign_bridges() -> bool { + let default_ifaces = default_route_ifaces(); + let bridges = collect_foreign_bridges(std::path::Path::new("/sys/class/net"), &default_ifaces); + let mut g = netlink::FOREIGN_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()); + if *g == bridges { + false + } else { + *g = bridges; + true + } +} + +/// Abstract Unix-domain socket name guarding Kiri's host networking (`kiri0` +/// and `nft table ip/ip6 kiri`) within a Linux network namespace (#443). +/// Abstract socket addresses are scoped per network namespace and released by +/// the kernel automatically when the agent exits or crashes. +const HOST_NETNS_LOCK_NAME: &[u8] = b"kiri-engine-netns"; + +static HOST_NETNS_LOCK: std::sync::OnceLock = std::sync::OnceLock::new(); +static HOST_NETNS_CLAIMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +fn make_abstract_sockaddr(name: &[u8]) -> io::Result<(libc::sockaddr_un, libc::socklen_t)> { + // SAFETY: zeroed `sockaddr_un` is valid; `sun_path[0] = 0` followed by `name` + // forms a Linux abstract socket address of length `offsetof(sun_path) + 1 + name.len()`. + let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() }; + addr.sun_family = libc::AF_UNIX as libc::sa_family_t; + if 1 + name.len() > addr.sun_path.len() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "netns lock name too long")); + } + for (dst, &src) in addr.sun_path[1..1 + name.len()].iter_mut().zip(name) { + *dst = src as libc::c_char; + } + let addr_len = (std::mem::offset_of!(libc::sockaddr_un, sun_path) + 1 + name.len()) as libc::socklen_t; + Ok((addr, addr_len)) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LockProbe { + /// Connected and `SO_PEERCRED.uid == owner`. + OwnedByOwner, + /// Connected and `SO_PEERCRED.uid != owner` (unprivileged squatter). + OwnedByOther, + /// `connect()` failed transiently (`EAGAIN` backlog full, `ECONNREFUSED` + /// bind-to-listen window or closing holder, `EINTR`, etc.). Never treated + /// as an unprivileged squatter. + TransientBusy, +} + +/// Probes an active listener on `name` to distinguish a legitimate `owner` +/// engine from an unprivileged squatter or transient backlog/startup state. +fn probe_abstract_lock(name: &[u8], owner: u32) -> LockProbe { + let Ok((addr, addr_len)) = make_abstract_sockaddr(name) else { return LockProbe::TransientBusy }; + let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) }; + if raw < 0 { + return LockProbe::TransientBusy; + } + // SAFETY: `raw` is a freshly created socket descriptor owned here. + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + // SAFETY: `addr` is initialized through `addr_len` bytes. + if unsafe { libc::connect(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 { + return LockProbe::TransientBusy; + } + // SAFETY: zeroed `ucred` is valid for `getsockopt(SO_PEERCRED)`. + let mut peer: libc::ucred = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + let rc = unsafe { + libc::getsockopt( + fd.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_PEERCRED, + (&raw mut peer).cast(), + &mut len, + ) + }; + if rc != 0 || len != std::mem::size_of::() as libc::socklen_t { + return LockProbe::TransientBusy; + } + if peer.uid == owner { + LockProbe::OwnedByOwner + } else { + LockProbe::OwnedByOther + } +} + +fn try_bind_abstract_socket(name: &[u8]) -> Result { + let (addr, addr_len) = make_abstract_sockaddr(name).map_err(|_| libc::EINVAL)?; + let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) }; + if raw < 0 { + return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); + } + // SAFETY: `raw` is a freshly created socket descriptor owned here. + let fd = unsafe { OwnedFd::from_raw_fd(raw) }; + // SAFETY: `addr` is initialized through `addr_len` bytes. + if unsafe { libc::bind(fd.as_raw_fd(), (&raw const addr).cast(), addr_len) } != 0 { + return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); + } + // SAFETY: `fd` is a bound `SOCK_STREAM` socket owned here. + if unsafe { libc::listen(fd.as_raw_fd(), 128) } != 0 { + return Err(io::Error::last_os_error().raw_os_error().unwrap_or(libc::EIO)); + } + Ok(fd) +} + +/// Descriptor of the held abstract netns lock socket, polled by the +/// single-threaded `agent::serve_loop` (`kiri-init` never spawns threads, so +/// `signalfd` and `clone3` stay single-threaded). +pub fn netns_lock_fd() -> Option { + HOST_NETNS_LOCK.get().map(AsRawFd::as_raw_fd) +} + +/// Drains up to 64 pending `SO_PEERCRED` probe connections per `poll()` tick so +/// `sk_max_ack_backlog` does not fill under normal retries while a local +/// `connect()` flood can never starve `agent::serve_loop`. +pub fn drain_netns_lock(fd: std::os::fd::RawFd) { + for _ in 0..64 { + // SAFETY: `fd` is a non-blocking listening `AF_UNIX` socket. + let cfd = unsafe { libc::accept4(fd, std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK) }; + if cfd >= 0 { + // SAFETY: `cfd` is a freshly accepted descriptor owned here. + unsafe { libc::close(cfd) }; + continue; + } + let err = io::Error::last_os_error().raw_os_error().unwrap_or(libc::EAGAIN); + if err == libc::EMFILE || err == libc::ENFILE { + std::thread::sleep(Duration::from_millis(1)); + } + break; + } +} + +const NETNS_BUSY_MSG: &str = + "another Kiri engine is already running in this network namespace (for example in another WSL 2 distribution): stop it first"; +const MAX_NETNS_LOCK_SLOTS: usize = 64; + +fn netns_slot_name(base: &[u8], idx: usize) -> Vec { + if idx == 0 { + base.to_vec() + } else { + let mut v = Vec::with_capacity(base.len() + 8); + v.extend_from_slice(base); + v.extend_from_slice(format!("-{idx}").as_bytes()); + v + } +} + +/// Claims ownership of Kiri's bridge and firewall tables in the current Linux +/// network namespace (#443). All WSL 2 distributions share one network +/// namespace; refusing early prevents a second engine from overwriting +/// `nft table ip kiri` or deleting `kiri0` when stopping. +pub fn claim_host_netns() -> io::Result<()> { + claim_host_netns_on(HOST_NETNS_LOCK_NAME, &HOST_NETNS_LOCK, &HOST_NETNS_CLAIMED) +} + +fn claim_host_netns_on( + base: &[u8], + slot: &std::sync::OnceLock, + claimed: &std::sync::atomic::AtomicBool, +) -> io::Result<()> { + use std::sync::atomic::Ordering; + if claimed.load(Ordering::Acquire) { + return Ok(()); + } + // SAFETY: `geteuid` has no preconditions. + let me = unsafe { libc::geteuid() }; + let mut idx = 0usize; + while idx < MAX_NETNS_LOCK_SLOTS { + let candidate = netns_slot_name(base, idx); + let start = Instant::now(); + loop { + match try_bind_abstract_socket(&candidate) { + Ok(fd) => { + let _ = slot.set(fd); + claimed.store(true, Ordering::Release); + return Ok(()); + } + Err(code) if code == libc::EADDRINUSE => match probe_abstract_lock(&candidate, me) { + LockProbe::OwnedByOther => { + // Unprivileged squatter on `candidate`: advance to the next + // deterministic slot so the first root engine still binds a + // real lock and a second root engine hits that bound slot + // (preventing split-brain without arming `claimed` unlocked). + eprintln!("kiri-init: skipping unprivileged squatter on abstract netns socket slot {idx}"); + idx += 1; + break; + } + LockProbe::OwnedByOwner | LockProbe::TransientBusy => { + if start.elapsed() < Duration::from_millis(500) { + std::thread::sleep(Duration::from_millis(25)); + continue; + } + return Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG)); + } + }, + Err(code) => return Err(io::Error::from_raw_os_error(code)), + } + } + } + Err(io::Error::new(io::ErrorKind::AddrInUse, NETNS_BUSY_MSG)) +} + +/// On a Linux host: claims the network namespace, enables IPv4 forwarding, +/// detects foreign local bridges, installs Kiri's nftables table, and adapts +/// to any host firewall. Does not require a main-table default route at boot +/// (policy-routed VPNs such as Tailscale or delayed interfaces work as routes +/// appear). +pub fn host_uplink() -> io::Result<()> { + claim_host_netns()?; sys::write_file("/proc/sys/net/ipv4/ip_forward", "1")?; // No host.docker.internal loopback redirect on a Linux host: it would // let containers reach the real machine's 127.0.0.1 services. host.docker // .internal maps to the bridge gateway instead (write_etc_files). - let _ = HOST_UPLINK_INDEX.set(index); - let uplink6 = std::fs::read_to_string("/proc/net/ipv6_route").ok().and_then(|r| default_route6_iface(&r)); - firewall::set_uplinks(iface.clone(), uplink6.unwrap_or(iface)); + let _ = HOST_UPLINK_INDEX.set(0); + let _ = update_foreign_bridges(); through_firewall(firewall::Why::Start); - install_nat(Nat { uplink: index, redirect: false, dnat: Vec::new(), gateway: [0; 4] }) -} - -/// The interface of the IPv6 default route in /proc/net/ipv6_route (dest -/// `::/0`), but not `lo`, which holds the unreachable default. -fn default_route6_iface(routes: &str) -> Option { - routes.lines().find_map(|l| { - let f: Vec<&str> = l.split_whitespace().collect(); - (f.len() == 10 && f[0].bytes().all(|b| b == b'0') && f[1] == "00" && f[9] != "lo").then(|| f[9].to_owned()) - }) + install_nat(Nat { uplink: 0, redirect: false, dnat: Vec::new(), gateway: [0; 4] }) } /// Linux host: a socket that hears of every nf_tables change, so a firewall @@ -148,11 +490,43 @@ pub fn firewall_events() -> Option { netlink::nftables_events().inspect_err(|e| eprintln!("kiri-init: not watching the host's firewall: {e}")).ok() } +/// Linux host: a socket that hears of link and route changes so dynamic +/// foreign bridges (`docker0`, `br-*`, `virbr*`) and default-route bridges +/// stay current in Kiri's forward filters. +pub fn link_route_events() -> Option { + netlink::link_route_events().inspect_err(|e| eprintln!("kiri-init: not watching host links/routes: {e}")).ok() +} + /// `firewall_events` heard of a change: reads it and brings the host's /// firewall, and Kiri's own tables, in line. pub fn firewall_changed(events: &OwnedFd) { netlink::drain(events); + let foreign_changed = update_foreign_bridges(); through_firewall(firewall::Why::Event); + if foreign_changed { + rebuild_nat_all(); + } +} + +/// `link_route_events` heard a link or route change: updates foreign-bridge +/// isolation and rebuilds Kiri's forward filters when the bridge set changed. +pub fn link_route_changed(events: &OwnedFd) { + netlink::drain(events); + if update_foreign_bridges() { + rebuild_nat_all(); + } +} + +fn rebuild_nat_all() { + if let Err(e) = refresh_nat() { + eprintln!("kiri-init: NAT: {e}"); + } + let nat6 = NAT6.lock().unwrap_or_else(|e| e.into_inner()).clone(); + if !nat6.0.is_empty() + && let Err(e) = refresh_nat6(&nat6.0, &nat6.1) + { + eprintln!("kiri-init: IPv6 NAT: {e}"); + } } /// `firewall::sync`, with Kiri's own tables built again as last built when @@ -173,7 +547,7 @@ fn through_firewall(why: firewall::Why) { let nat6 = NAT6.lock().unwrap_or_else(|e| e.into_inner()).clone(); if v6 && !nat6.0.is_empty() - && let Err(e) = netlink::install_nat6(&nat6.0, &nat6.1) + && let Err(e) = refresh_nat6(&nat6.0, &nat6.1) { eprintln!("kiri-init: IPv6 NAT: {e}"); } @@ -185,6 +559,17 @@ fn through_firewall(why: firewall::Why) { #[allow(clippy::type_complexity)] static NAT6: std::sync::Mutex<(Vec<([u8; 16], u8)>, Vec)> = std::sync::Mutex::new((Vec::new(), Vec::new())); +/// Rebuilds Kiri's IPv6 table from `subnets`/`bridges` and, in the VM, the +/// loopback redirect and input guard for `HOST_RELAY_PORT`. +fn refresh_nat6(subnets: &[([u8; 16], u8)], bridges: &[String]) -> io::Result<()> { + let (redirect, dnat) = NAT + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + .map_or((false, Vec::new()), |n| (n.redirect, n.dnat.clone())); + netlink::install_nat6(subnets, bridges, HOST_RELAY_PORT, redirect, &dnat) +} + /// What Kiri's IPv4 table was last built from, so it can be rebuilt when a /// bridge comes or goes (the forward filter has a rule per bridge). struct Nat { @@ -195,17 +580,101 @@ struct Nat { } static NAT: std::sync::Mutex> = std::sync::Mutex::new(None); +/// Egress IPv4 CIDR prefixes redirected to `EGRESS_RELAY_PORT`. +static EGRESS_ROUTES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// Active bridge IPv4 subnets `(name, network, prefix)`, exempt from egress redirect. +static BRIDGE_SUBNETS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +/// The VM uplink's IPv4 subnet `(network, prefix)`, exempt from egress redirect. +static UPLINK_SUBNET: std::sync::Mutex> = std::sync::Mutex::new(None); /// The kernel has no nft_fib_ipv4 (`fib daddr type local`): ports /// published on every address are matched per address of this machine. static NO_FIB4: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); +pub fn parse_cidr(s: &str) -> Option<([u8; 4], u8)> { + let (ip, prefix) = s.trim().split_once('/')?; + let ip = parse_ip(ip)?; + let prefix: u8 = prefix.parse().ok().filter(|&p| p <= 32)?; + Some((netlink::mask_ipv4(ip, prefix), prefix)) +} + +pub fn parse_egress_routes(list: kiri_proto::StrList<'_>) -> Vec<([u8; 4], u8)> { + let mut out = Vec::new(); + for s in list.iter() { + if let Some(c) = parse_cidr(s) + && !out.contains(&c) + { + out.push(c); + } + } + out +} + +/// Whether `routes` includes full host egress (`0.0.0.0/0`), in which case +/// guest upstream DNS lookups should go straight through the host DNS relay. +pub fn egress_prefers_dns_relay(routes: &[([u8; 4], u8)]) -> bool { + routes.iter().any(|&(_, prefix)| prefix == 0) +} + +/// Updates the IPv4 CIDR prefixes redirected to the host egress dialer and +/// rebuilds Kiri's IPv4 nftables table. +pub fn set_egress_routes(routes: Vec<([u8; 4], u8)>) -> io::Result<()> { + *EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()) = routes; + refresh_nat() +} + +fn egress_skip_subnets() -> Vec<([u8; 4], u8)> { + let mut skip = vec![ + ([127, 0, 0, 0], 8), + ([169, 254, 0, 0], 16), + ([224, 0, 0, 0], 3), + ]; + if let Some(up) = *UPLINK_SUBNET.lock().unwrap_or_else(|e| e.into_inner()) + && !skip.contains(&up) + { + skip.push(up); + } + for &(_, net, prefix) in BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).iter() { + if !skip.contains(&(net, prefix)) { + skip.push((net, prefix)); + } + } + skip +} + /// Builds Kiri's IPv4 table from `nat` and the bridges made so far, and -/// keeps `nat` for `refresh_nat`. +/// keeps `nat` for `refresh_nat`. In the VM (`nat.redirect`), also installs +/// the IPv6 `::1` loopback redirect and input guard on a best-effort basis. fn install_nat(nat: Nat) -> io::Result<()> { use std::sync::atomic::Ordering; let bridges = MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let egress = EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let skip = if egress.is_empty() { Vec::new() } else { egress_skip_subnets() }; let any_addr = nat.dnat.iter().any(|d| d.host_ip == [0; 4]); - let install = |local: Option<&[[u8; 4]]>| netlink::install_nat_from(nat.uplink, HOST_ADDR, HOST_RELAY_PORT, nat.redirect, &nat.dnat, nat.gateway, &bridges, local); + let wsl_host = (!nat.redirect && is_wsl()).then_some(WSL_HOST_ADDR); + let bridge_subnets: Vec<([u8; 4], u8)> = if nat.redirect { + Vec::new() + } else { + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|&(_, net, prefix)| (net, prefix)).collect() + }; + let allow_prerouting_dnat = nat.redirect || !firewall::forwarding_blocked(); + let install = |local: Option<&[[u8; 4]]>| { + netlink::install_nat_full( + nat.uplink, + HOST_ADDR, + HOST_RELAY_PORT, + nat.redirect, + &nat.dnat, + nat.gateway, + &bridges, + local, + EGRESS_RELAY_PORT, + &egress, + &skip, + wsl_host, + &bridge_subnets, + allow_prerouting_dnat, + ) + }; let r = if any_addr && NO_FIB4.load(Ordering::Relaxed) { install(Some(&local_addrs())) } else { @@ -219,7 +688,12 @@ fn install_nat(nat: Nat) -> io::Result<()> { } }; if r.is_ok() { + let redirect = nat.redirect; *NAT.lock().unwrap_or_else(|e| e.into_inner()) = Some(nat); + if redirect { + let nat6 = NAT6.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let _ = refresh_nat6(&nat6.0, &nat6.1); + } } r } @@ -250,9 +724,40 @@ pub fn local_resolver(servers: &[[u8; 4]]) -> bool { !servers.is_empty() && local_resolver_among(servers, &local_addrs()) } -/// `local_resolver`, given this machine's addresses. +/// `local_resolver`, given this machine's addresses. Loopback stubs +/// (`127.0.0.53`, systemd-resolved) and Tailscale's MagicDNS (`100.100.100.100`) +/// live in the host's network namespace too, so bridged containers reach them +/// through the agent at the bridge gateway rather than naming them directly. pub fn local_resolver_among(servers: &[[u8; 4]], local: &[[u8; 4]]) -> bool { - servers.iter().any(|s| local.contains(s)) + servers.iter().any(|s| s[0] == 127 || *s == [100, 100, 100, 100] || local.contains(s)) +} + +/// The IPv4 address of interface `name`, if it has one: a bridge's gateway. +pub fn bridge_ipv4(name: &str) -> Option<[u8; 4]> { + if name.is_empty() || name.len() >= libc::IFNAMSIZ || name.contains('\0') { + return None; + } + let fd = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc::SOCK_CLOEXEC, 0) }; + if fd < 0 { + return None; + } + // SAFETY: all-zero is a valid `ifreq`; `ifr_name` gets an ASCII name shorter than IFNAMSIZ. + let mut ifr: libc::ifreq = unsafe { std::mem::zeroed() }; + for (dst, &src) in ifr.ifr_name.iter_mut().zip(name.as_bytes()) { + *dst = src as libc::c_char; + } + // SAFETY: `SIOCGIFADDR` fills `ifr_ifru.ifru_addr` with an `AF_INET` `sockaddr` for `ifr_name`. + let rc = unsafe { libc::ioctl(fd, libc::SIOCGIFADDR as _, &mut ifr) }; + unsafe { libc::close(fd) }; + if rc != 0 { + return None; + } + // SAFETY: `SIOCGIFADDR` initialized `ifru_addr`; in `sockaddr_in`, `sa_data[2..6]` is `sin_addr`. + let addr = unsafe { ifr.ifr_ifru.ifru_addr }; + (i32::from(addr.sa_family) == libc::AF_INET).then(|| { + let d = addr.sa_data; + [d[2] as u8, d[3] as u8, d[4] as u8, d[5] as u8] + }) } /// This machine's IPv4 addresses but loopback, what `fib daddr type local` @@ -271,7 +776,9 @@ fn local_addrs() -> Vec<[u8; 4]> { if !ifa.ifa_addr.is_null() && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET { // SAFETY: an AF_INET address is a sockaddr_in. let a = unsafe { (*(ifa.ifa_addr as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes(); - if a[0] != 127 && !out.contains(&a) { + // Exclude loopback and (on WSL 2) the Windows host-gateway address so + // published-port DNAT fallback rules never hijack host.docker.internal. + if a[0] != 127 && (!is_wsl() || a != WSL_HOST_ADDR) && !out.contains(&a) { out.push(a); } } @@ -286,37 +793,90 @@ fn local_addrs() -> Vec<[u8; 4]> { static HOST_UPLINK_INDEX: std::sync::OnceLock = std::sync::OnceLock::new(); /// Linux host: makes these, and only these, the published ports the kernel -/// forwards (see `netlink::Dnat`). +/// forwards (see `netlink::Dnat`). Returns an error when host firewall +/// `FORWARD` chains block kernel forwarding so the daemon serves them via +/// user-space `INPUT` relays instead of blackholing SYNs in `prerouting`. pub fn publish(dnat: &[netlink::Dnat]) -> io::Result<()> { + let index = *HOST_UPLINK_INDEX.get().ok_or_else(|| io::Error::other("no uplink"))?; + if !dnat.is_empty() && firewall::forwarding_blocked() { + return Err(io::Error::other("kernel forwarding is blocked by host firewall")); + } + install_nat(Nat { uplink: index, redirect: false, dnat: dnat.to_vec(), gateway: [0; 4] }) +} + +/// Linux host: updates Kiri's nftables table after unpublishing a container's +/// ports, even while `firewall::forwarding_blocked()` is true, so exiting +/// containers never leave stale `output` DNAT rules behind when other +/// containers remain published. +pub fn unpublish(dnat: &[netlink::Dnat]) -> io::Result<()> { let index = *HOST_UPLINK_INDEX.get().ok_or_else(|| io::Error::other("no uplink"))?; install_nat(Nat { uplink: index, redirect: false, dnat: dnat.to_vec(), gateway: [0; 4] }) } +/// Raises a numeric sysctl file to at least `min`, ignoring missing entries. +fn raise_sysctl_min(path: &std::path::Path, min: u64) { + let Ok(raw) = std::fs::read_to_string(path) else { return }; + if raw.trim().parse::().is_ok_and(|cur| cur < min) { + let _ = std::fs::write(path, min.to_string()); + } +} + /// Brings the uplink up and returns a DHCP client for it, or None if the VM -/// has no network card. +/// has no network card (shared NAT disabled: installs the VM nftables table +/// and a fallback default route on `lo` so host-network and bridged containers +/// route outbound TCP through the host egress relay over vsock). pub fn uplink() -> io::Result> { - let Ok(index) = netlink::index_of(UPLINK) else { return Ok(None) }; - 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)?)) + // In the VM root netns, bypass L2 bridge-netfilter hooks and conntrack for + // same-bridge container-to-container packets (such as Kong -> PostgREST on + // a user network), and raise `nf_conntrack_max` for sustained load (#509). + let _ = sys::write_file("/proc/sys/net/bridge/bridge-nf-call-iptables", "0"); + let _ = sys::write_file("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "0"); + raise_sysctl_min(std::path::Path::new("/proc/sys/net/netfilter/nf_conntrack_max"), 262_144); + match netlink::index_of(UPLINK) { + Ok(index) => { + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + netlink::set_up(&mut nl, index)?; + install_nat(Nat { uplink: index, redirect: true, dnat: Vec::new(), gateway: [0; 4] })?; + let _ = VM_UPLINK_INDEX.set(index); + Ok(Some(Dhcp::start(index)?)) + } + Err(_) => { + // Without an `eth0` NIC, locally originated connects in the VM root + // netns (`--network host` containers) perform IPv4 route lookup + // before NF_INET_LOCAL_OUT nftables redirect rules run. Add a + // fallback default route on `lo` so `connect()` reaches the output + // egress/host-relay redirect rules instead of failing ENETUNREACH. + if let Ok(lo) = netlink::index_of("lo") + && let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) + && let Err(e) = netlink::add_device_default_route(&mut nl, lo, Some(netlink::LOOPBACK)) + { + eprintln!("kiri-init: fallback default route on lo: {e}"); + } + install_nat(Nat { uplink: 0, redirect: true, dnat: Vec::new(), gateway: [0; 4] })?; + let _ = VM_UPLINK_INDEX.set(0); + Ok(None) + } + } } -/// The VM's uplink (eth0), once `uplink` brought it up. +/// The VM's uplink (eth0), or 0 when booted without a NIC (shared NAT off). static VM_UPLINK_INDEX: std::sync::OnceLock = std::sync::OnceLock::new(); /// In the VM: makes these the published ports the kernel forwards from the /// uplink, for connections the Mac makes from `gateway` (its address on the -/// NAT network). The table is rebuilt whole, so the host.docker.internal -/// redirect stays. +/// NAT network), and loopback redirects for `--network host` containers. +/// The table is rebuilt whole, so the host.docker.internal and egress +/// redirects stay. pub fn publish_vm(dnat: &[netlink::Dnat], gateway: [u8; 4]) -> io::Result<()> { let index = *VM_UPLINK_INDEX.get().ok_or_else(|| io::Error::other("no uplink"))?; + if index == 0 && dnat.iter().any(|d| d.host_ip != netlink::LOOPBACK) { + return Err(io::Error::other("no uplink")); + } install_nat(Nat { uplink: index, redirect: true, dnat: dnat.to_vec(), gateway }) } @@ -419,6 +979,31 @@ impl Dhcp { Ok(()) } + /// Configures `eth0` from host-supplied settings when DHCP did not answer. + /// No-op (`Ok(false)`) if a lease is already active. + pub fn apply_static(&mut self, ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4]) -> io::Result { + let index = self.index; + self.apply_static_with(ip, prefix, gateway, dns, |lease| { + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + netlink::add_address(&mut nl, index, lease.ip, lease.prefix)?; + netlink::add_default_route(&mut nl, index, lease.gateway) + }) + } + + fn apply_static_with(&mut self, ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4], configure: impl FnOnce(&Lease) -> io::Result<()>) -> io::Result { + if self.lease.is_some() { + return Ok(false); + } + if !valid_uplink(ip, prefix, gateway) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid uplink settings")); + } + let lease = Lease { ip, prefix, gateway, dns: if dns == [0; 4] { Vec::new() } else { vec![dns] } }; + configure(&lease)?; + self.state = DhcpState::Bound; + self.lease = Some(lease); + Ok(true) + } + /// Handles a reply. Returns true once a lease has been configured. pub fn on_readable(&mut self) -> io::Result { let mut buf = [0u8; 1500]; @@ -463,6 +1048,8 @@ impl Dhcp { let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; netlink::add_address(&mut nl, self.index, lease.ip, lease.prefix)?; netlink::add_default_route(&mut nl, self.index, lease.gateway)?; + *UPLINK_SUBNET.lock().unwrap_or_else(|e| e.into_inner()) = Some((netlink::mask_ipv4(lease.ip, lease.prefix), lease.prefix)); + let _ = refresh_nat(); self.state = DhcpState::Bound; self.lease = Some(lease); return Ok(true); @@ -479,6 +1066,18 @@ impl Dhcp { } } +fn valid_uplink(ip: [u8; 4], prefix: u8, gateway: [u8; 4]) -> bool { + if !(1..=30).contains(&prefix) || ip == [0; 4] || gateway == [0; 4] || ip == gateway { + return false; + } + if ip[0] == 127 || gateway[0] == 127 || ip[0] >= 224 || gateway[0] >= 224 { + return false; + } + let mask = u32::MAX << (32 - u32::from(prefix)); + let (ip_u, gw_u) = (u32::from_be_bytes(ip), u32::from_be_bytes(gateway)); + (ip_u & mask) == (gw_u & mask) && (ip_u & !mask) != 0 && (ip_u & !mask) != !mask && (gw_u & !mask) != 0 && (gw_u & !mask) != !mask +} + fn random_u32() -> u32 { let mut b = [0u8; 4]; let _ = std::fs::File::open("/dev/urandom").and_then(|mut f| std::io::Read::read_exact(&mut f, &mut b)); @@ -516,34 +1115,78 @@ fn mac_of(name: &str) -> io::Result<[u8; 6]> { type Bridge6 = Option<([u8; 16], u8)>; /// Bridges that exist so far: name → (index, gateway (none when -/// IPv6-only), prefix, IPv6). +/// IPv6-only), prefix, IPv6), plus a persistent host `NETLINK_ROUTE` socket. #[derive(Default)] pub struct Bridges { made: HashMap, u8, Bridge6)>, + route: Option, +} + +/// What `Bridges::ensure` needs to do for a bridge given its cached state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum BridgePlan { + /// Already up with everything asked for. + Reuse(i32), + /// Already up with the same IPv4 gateway/prefix; add IPv6 in place so + /// existing sockets and containers on the bridge are not disrupted. + AddV6(i32), + /// A different subnet took the bridge name: tear down and recreate. + Recreate, + /// Not created yet. + Create, } impl Bridges { + fn route_nl(&mut self) -> io::Result<&mut Netlink> { + if self.route.is_none() { + self.route = Some(Netlink::open(libc::NETLINK_ROUTE)?); + } + Ok(self.route.as_mut().expect("opened above")) + } + + /// Whether `name` currently exists with an IPv6 subnet configured. + pub fn has_ipv6(&self, name: &str) -> bool { + matches!(self.made.get(name), Some((.., Some(_)))) + } + + fn plan(&self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, want6: Bridge6) -> BridgePlan { + match self.made.get(name) { + Some(&(i, g, p, b6)) if (g, p) == (gateway, prefix) => match (b6, want6) { + (None, None) => BridgePlan::Reuse(i), + (None, Some(_)) => BridgePlan::AddV6(i), + // Already has IPv6 (e.g. a later container with IPv6 disabled, + // or a host-network caller that only needs IPv4): keep it. + (Some(_), None) => BridgePlan::Reuse(i), + (Some(a), Some(b)) if a == b => BridgePlan::Reuse(i), + (Some(_), Some(_)) => BridgePlan::Recreate, + }, + Some(_) => BridgePlan::Recreate, + None => BridgePlan::Create, + } + } + /// Creates the bridge (once) with its gateway address (and IPv6 one) /// and brings it up, with its rules in Kiri's tables. All or nothing: on /// an error the bridge is gone again and not recorded, so the next /// container tries afresh rather than starting with half the rules. pub fn ensure(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option) -> io::Result { let want6 = v6.map(|v| (v.gateway, v.prefix)); - match self.made.get(name) { - Some(&(i, g, p, b6)) if (g, p, b6) == (gateway, prefix, want6) => return Ok(i), + match self.plan(name, gateway, prefix, want6) { + BridgePlan::Reuse(i) => return Ok(i), + BridgePlan::AddV6(i) => return self.add_v6(name, i, gateway, prefix, v6.expect("AddV6 requires v6")), // The network was removed and its bridge name reused for one // with another subnet: start the bridge afresh. - Some(_) => { - self.remove(name); - } - None => {} + BridgePlan::Recreate => self.remove(name), + BridgePlan::Create => {} } - let r = self.bring_up(name, gateway, prefix, v6); + let mut created = false; + let r = self.bring_up(name, gateway, prefix, v6, &mut created); if r.is_err() { - if let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) { + if created && let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) { let _ = netlink::delete_link(&mut nl, name); } MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).retain(|m| m != name); + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(m, ..)| m != name); let had6 = matches!(self.made.remove(name), Some((.., Some(_)))); let _ = refresh_nat(); if had6 { @@ -553,14 +1196,32 @@ impl Bridges { r } - fn bring_up(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option) -> io::Result { + fn add_v6(&mut self, name: &str, index: i32, gateway: Option<[u8; 4]>, prefix: u8, v: Ip6) -> io::Result { + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + netlink::add_address6(&mut nl, index, v.gateway, v.prefix)?; + self.made.insert(name.to_owned(), (index, gateway, prefix, Some((v.gateway, v.prefix)))); + if let Err(e) = self.update_v6(Some(v)) { + self.made.insert(name.to_owned(), (index, gateway, prefix, None)); + return Err(e); + } + Ok(index) + } + + fn bring_up(&mut self, name: &str, gateway: Option<[u8; 4]>, prefix: u8, v6: Option, created: &mut bool) -> io::Result { let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; - netlink::create_bridge(&mut nl, name)?; + *created = netlink::create_bridge(&mut nl, name)?; let mut made = MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()); if !made.iter().any(|m| m == name) { made.push(name.to_owned()); } drop(made); + { + let mut subs = BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()); + subs.retain(|(m, ..)| m != name); + if let Some(g) = gateway { + subs.push((name.to_owned(), netlink::mask_ipv4(g, prefix), prefix)); + } + } let index = netlink::index_of(name)?; if let Some(g) = gateway { netlink::add_address(&mut nl, index, g, prefix)?; @@ -574,6 +1235,7 @@ impl Bridges { // DNATed from 127.0.0.1, so the bridge needs no `route_localnet`; // an older engine set it on bridges that may still exist. let _ = sys::write_file(&format!("/proc/sys/net/ipv4/conf/{name}/route_localnet"), "0"); + let _ = update_foreign_bridges(); // A firewall started after the engine, in iptables-legacy // (which makes no nf_tables event) too. through_firewall(firewall::Why::Bridge); @@ -594,6 +1256,7 @@ impl Bridges { let _ = netlink::delete_link(&mut nl, name); } MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).retain(|m| m != name); + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(m, ..)| m != name); if let Err(e) = refresh_nat() { eprintln!("kiri-init: NAT: {e}"); } @@ -619,7 +1282,7 @@ impl Bridges { if added.is_some() { ipv6_forwarding(true)?; } - let r = netlink::install_nat6(&subnets, &names); + let r = refresh_nat6(&subnets, &names); if r.is_ok() { *NAT6.lock().unwrap_or_else(|e| e.into_inner()) = (subnets.clone(), names.clone()); } @@ -681,7 +1344,12 @@ static MADE_BRIDGES: std::sync::Mutex> = std::sync::Mutex::new(Vec:: /// those: another engine's may share the network namespace) and Kiri's /// nftables table, so nothing of the engine is left in the host's network. pub fn remove_host_network() { + if !HOST_NETNS_CLAIMED.load(std::sync::atomic::Ordering::Acquire) { + return; + } let names = std::mem::take(&mut *MADE_BRIDGES.lock().unwrap_or_else(|e| e.into_inner())); + BRIDGE_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).clear(); + EGRESS_ROUTES.lock().unwrap_or_else(|e| e.into_inner()).clear(); if let Ok(mut nl) = Netlink::open(libc::NETLINK_ROUTE) { for name in names { let _ = netlink::delete_link(&mut nl, &name); @@ -690,7 +1358,7 @@ pub fn remove_host_network() { if let Err(e) = netlink::remove_nat() { eprintln!("kiri-init: removing the nftables table: {e}"); } - let _ = netlink::install_nat6(&[], &[]); + let _ = netlink::install_nat6(&[], &[], HOST_RELAY_PORT, false, &[]); let _ = ipv6_forwarding(false); through_firewall(firewall::Why::Stop); } @@ -704,6 +1372,7 @@ pub fn attach_container( bridge: &str, host_ifname: &str, pid: libc::pid_t, + netns: Option<&std::fs::File>, ip: [u8; 4], prefix: u8, gateway: [u8; 4], @@ -711,45 +1380,89 @@ pub fn attach_container( v6: Option, plug: Plug, ) -> io::Result<()> { - attach(bridges, bridge, host_ifname, pid, 0, ip, prefix, gateway, mac, v6, plug) + attach_with_ns(bridges, bridge, host_ifname, pid, netns, 0, ip, prefix, gateway, mac, v6, plug) } -/// Plugs the container into `bridge` as `eth{n}`. Only `eth0` gets the -/// default route; more networks add their subnets, as with Docker. The -/// first network with IPv6 gives the IPv6 default route. An `internal` -/// network gives no default route at all, so traffic beyond it fails at -/// once (unreachable), as with Docker. On a network without IPv6 the +/// Plugs the container into `bridge` as `eth{n}`. The first non-internal +/// network with IPv4 gives the IPv4 default route, even when it is not +/// `eth0` (an internal network first, an outside one second); later ones +/// keep it, and only add their subnets. The same goes for IPv6. An +/// `internal` network never gives a default route, so traffic beyond it +/// fails at once (unreachable), as with Docker. `hand_over_default_routes` +/// moves a route on when its network is disconnected. On a network without IPv6 the /// interface has IPv6 off (no link-local address), as Docker does. On an /// IPv6-only network `ip` is only the name the container is kept by (its /// MAC is made from it): neither the interface nor the bridge gets it. #[allow(clippy::too_many_arguments)] pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc::pid_t, n: u32, ip: [u8; 4], prefix: u8, gateway: [u8; 4], mac: Option<[u8; 6]>, v6: Option, plug: Plug) -> io::Result<()> { - let Plug { internal, no_ipv4 } = plug; + attach_with_ns(bridges, bridge, host_ifname, pid, None, n, ip, prefix, gateway, mac, v6, plug) +} + +#[allow(clippy::too_many_arguments)] +fn attach_with_ns( + bridges: &mut Bridges, + bridge: &str, + host_ifname: &str, + pid: libc::pid_t, + netns_fd: Option<&std::fs::File>, + n: u32, + ip: [u8; 4], + prefix: u8, + gateway: [u8; 4], + mac: Option<[u8; 6]>, + v6: Option, + plug: Plug, +) -> io::Result<()> { + let Plug { internal, no_ipv4, no_icc } = plug; let mac = Some(mac.unwrap_or_else(|| mac_for(ip))); let bridge_index = bridges.ensure(bridge, (!no_ipv4).then_some(gateway), prefix, v6)?; - let netns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; - let mut host = Netlink::open(libc::NETLINK_ROUTE)?; - // A stopped container's veth may still hold this address and MAC. - delete_retired(&mut host); + let opened_ns; + let netns = match netns_fd { + Some(f) => f, + None => { + opened_ns = std::fs::File::open(format!("/proc/{pid}/ns/net"))?; + &opened_ns + } + }; let ifname = format!("eth{n}"); - netlink::create_veth(&mut host, host_ifname, bridge_index, &netns, CONTAINER_MTU, &ifname, mac)?; - // By name: a new namespace may have tunl0, gre0 … before it. - let index = netlink::index_in(&netns, &ifname)?; - if v6.is_none() { - // Before it is up, so it never gets a link-local address. A kernel - // without IPv6 has no such file, and nothing to turn off. - let _ = netlink::in_netns(&netns, || sys::write_file(&format!("/proc/sys/net/ipv6/conf/{ifname}/disable_ipv6"), "1")); + { + let host = bridges.route_nl()?; + // A stopped container's veth may still hold this address and MAC. + delete_retired(host); + netlink::create_veth(host, host_ifname, bridge_index, netns, CONTAINER_MTU, &ifname, mac, no_icc)?; } - let mut inner = Netlink::open_in(&netns)?; - netlink::set_up(&mut inner, 1)?; // lo - if !no_ipv4 { - netlink::add_address(&mut inner, index, ip, prefix)?; - } - if let Some(v) = v6 { - netlink::add_address6(&mut inner, index, v.ip, v.prefix)?; + // Enter the container's network namespace once to resolve the peer index, + // disable IPv6 link-local when IPv6 is off, and open the inner route socket. + let (index, mut inner) = netlink::in_netns(netns, || { + let idx = netlink::index_of(&ifname)?; + if v6.is_none() { + let _ = sys::write_file(&format!("/proc/sys/net/ipv6/conf/{ifname}/disable_ipv6"), "1"); + } + let nl = Netlink::open(libc::NETLINK_ROUTE)?; + Ok((idx, nl)) + })?; + if n == 0 { + let mut batch = Vec::with_capacity(4); + batch.push(netlink::set_up_msg(1)); // lo + if !no_ipv4 { + batch.push(netlink::add_address_msg(index, ip, prefix)); + } + if let Some(v) = v6 { + batch.push(netlink::add_address6_msg(index, v.ip, v.prefix)); + } + batch.push(netlink::set_up_msg(index)); + inner.request(&mut batch)?; + } else { + netlink::set_up(&mut inner, 1)?; // lo + if !no_ipv4 { + netlink::add_address(&mut inner, index, ip, prefix)?; + } + if let Some(v) = v6 { + netlink::add_address6(&mut inner, index, v.ip, v.prefix)?; + } + netlink::set_up(&mut inner, index)?; } - netlink::set_up(&mut inner, index)?; - if n == 0 && !internal && !no_ipv4 { + if !internal && !no_ipv4 { netlink::add_default_route(&mut inner, index, gateway)?; } if let Some(v) = v6.filter(|_| !internal) { @@ -760,6 +1473,7 @@ pub fn attach(bridges: &mut Bridges, bridge: &str, host_ifname: &str, pid: libc: /// Host-side veths of stopped containers, deleted by the next `attach`. static RETIRED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +static HAS_RETIRED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Notes a stopped container's host-side veths for the next `attach` to /// delete. Deleting one waits out RCU, 15-40 ms that every request after @@ -770,12 +1484,19 @@ static RETIRED: std::sync::Mutex> = std::sync::Mutex::new(Vec::new() /// to the old namespace, and that answered with resets (a download that /// broke mid-TLS or stalled). pub fn retire(veths: &[String]) { + if veths.is_empty() { + return; + } RETIRED.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(veths); + HAS_RETIRED.store(true, std::sync::atomic::Ordering::Release); } /// Deletes the veths `retire` noted. Gone already (the kernel took them /// with their namespace) is fine. fn delete_retired(nl: &mut Netlink) { + if !HAS_RETIRED.swap(false, std::sync::atomic::Ordering::AcqRel) { + return; + } for v in std::mem::take(&mut *RETIRED.lock().unwrap_or_else(|e| e.into_inner())) { let _ = netlink::delete_link(nl, &v); } @@ -829,14 +1550,208 @@ mod tests { } #[test] - fn the_ipv6_uplink_is_the_default_routes_interface() { - let routes = "\ -fd00000000000000000000000000000000 40 00000000000000000000000000000000 00 00000000000000000000000000000000 00000100 00000001 00000000 00000001 eth0 -00000000000000000000000000000000 00 00000000000000000000000000000000 00 fe800000000000000000000000000001 00000400 00000002 00000000 00000003 wlan0 -00000000000000000000000000000000 00 00000000000000000000000000000000 00 00000000000000000000000000000000 ffffffff 00000001 00000000 00200200 lo -"; - assert_eq!(default_route6_iface(routes).as_deref(), Some("wlan0")); - // Only the unreachable default on lo: no IPv6 uplink. - assert_eq!(default_route6_iface(&routes.lines().skip(2).collect::>().join("\n")), None); + fn collect_foreign_bridges_skips_kiri_non_bridges_and_default_route_bridges() { + let dir = std::env::temp_dir().join(format!("kiri-net-foreign-bridges-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for dev in ["kiri0", "kiri1", "docker0", "br-1234", "virbr0", "vmbr0"] { + std::fs::create_dir_all(dir.join(dev).join("bridge")).unwrap(); + } + for dev in ["eth0", "tailscale0", "wg0", "lo"] { + std::fs::create_dir_all(dir.join(dev)).unwrap(); + } + let defaults = vec!["eth0".to_owned(), "tailscale0".to_owned(), "vmbr0".to_owned()]; + assert_eq!(collect_foreign_bridges(&dir, &defaults), vec!["br-1234", "docker0", "virbr0"]); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn raise_sysctl_min_raises_only_below_threshold() { + let path = std::env::temp_dir().join(format!("kiri-net-sysctl-{}", std::process::id())); + let _ = std::fs::remove_file(&path); + raise_sysctl_min(&path, 262_144); + assert!(!path.exists()); + std::fs::write(&path, "65536\n").unwrap(); + raise_sysctl_min(&path, 262_144); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "262144"); + std::fs::write(&path, "524288\n").unwrap(); + raise_sysctl_min(&path, 262_144); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "524288\n"); + let _ = std::fs::remove_file(&path); + } + + fn up(veth: &str, v4: bool, v6: bool) -> Uplink { + Uplink { veth: veth.into(), ifname: veth.into(), v4: v4.then_some([10, 0, 0, 1]), v6: v6.then_some([0xfd; 16]) } + } + + #[test] + fn internal_networks_are_no_uplink() { + let v6 = Some(Ip6 { ip: [0xfd; 16], prefix: 64, gateway: [0xfd; 16] }); + assert_eq!(Uplink::of("kv1", "eth0", [10, 0, 0, 1], v6, Plug { internal: true, ..Plug::default() }), None); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], None, Plug::default()).unwrap(); + assert_eq!((u.ifname.as_str(), u.v4, u.v6), ("eth1", Some([10, 0, 0, 1]), None)); + let u = Uplink::of("kv1", "eth1", [10, 0, 0, 1], v6, Plug { no_ipv4: true, ..Plug::default() }).unwrap(); + assert_eq!((u.v4, u.v6), (None, Some([0xfd; 16]))); + } + + #[test] + fn the_first_uplink_with_each_family_holds_its_default_route() { + let ups = [up("a", false, true), up("b", true, false), up("c", true, true)]; + let (r4, r6) = route_holders(&ups); + assert_eq!((r4.map(|u| u.veth.as_str()), r6.map(|u| u.veth.as_str())), (Some("b"), Some("a"))); + assert_eq!(route_holders(&[]), (None, None)); + } + + #[test] + fn leaving_first_of_three_networks_promotes_first_attached_external_gateway_and_ifname() { + let gw_a = [10, 98, 0, 1]; + let gw_zeta = [10, 98, 1, 1]; + let gw_beta = [10, 98, 2, 1]; + let mut ups = Vec::new(); + ups.extend(Uplink::of("kva0", "eth0", gw_a, None, Plug::default())); + // An internal network attached in between produces no uplink. + ups.extend(Uplink::of("kxi1", "eth1", [10, 98, 9, 1], None, Plug { internal: true, ..Plug::default() })); + ups.extend(Uplink::of("kxz2", "eth2", gw_zeta, None, Plug::default())); + ups.extend(Uplink::of("kxb3", "eth3", gw_beta, None, Plug::default())); + + let (r4, _) = route_holders(&ups); + assert_eq!(r4.map(|u| (u.ifname.as_str(), u.v4)), Some(("eth0", Some(gw_a)))); + + // Disconnecting `a` promotes `zeta` on eth2 (first-plugged external), not `beta` on eth3. + ups.retain(|u| u.veth != "kva0"); + let (r4, _) = route_holders(&ups); + assert_eq!(r4.map(|u| (u.ifname.as_str(), u.v4)), Some(("eth2", Some(gw_zeta)))); + + // Disconnecting `zeta` promotes `beta` on eth3. + ups.retain(|u| u.veth != "kxz2"); + let (r4, _) = route_holders(&ups); + assert_eq!(r4.map(|u| (u.ifname.as_str(), u.v4)), Some(("eth3", Some(gw_beta)))); + } + + #[test] + fn a_disconnect_that_takes_no_default_route_touches_nothing() { + // The pid is never used: nothing to hand over, so no namespace is opened. + let mut ups = vec![up("a", true, true), up("b", true, true)]; + hand_over_default_routes(-1, &mut ups, "b").unwrap(); + assert_eq!(ups, [up("a", true, true)]); + hand_over_default_routes(-1, &mut ups, "a").unwrap(); + assert!(ups.is_empty()); + } + + #[test] + fn bridge_ipv4_reads_an_interfaces_address() { + assert_eq!(bridge_ipv4("lo"), Some([127, 0, 0, 1])); + assert_eq!(bridge_ipv4("kiri-no-such-if"), None); + } + + #[test] + fn bridges_ensure_is_idempotent_and_adds_ipv6_in_place() { + let gw4 = [172, 17, 0, 1]; + let gw6 = [0xfd, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1]; + let other6 = [0xfd, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 1]; + let v6 = Ip6 { ip: gw6, prefix: 64, gateway: gw6 }; + + let mut bridges = Bridges::default(); + assert_eq!(bridges.plan("kiri0", Some(gw4), 16, None), BridgePlan::Create); + + // Once kiri0 is brought up IPv4-only (e.g. by host-network DNS on a fresh VM), + // a repeat ensure reuses it without touching netlink, and a later IPv6 attach + // upgrades it in place rather than tearing it down. + bridges.made.insert("kiri0".into(), (42, Some(gw4), 16, None)); + assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, None).unwrap(), 42); + assert_eq!(bridges.plan("kiri0", Some(gw4), 16, Some((gw6, 64))), BridgePlan::AddV6(42)); + assert_eq!(bridges.plan("kiri0", Some([172, 18, 0, 1]), 16, None), BridgePlan::Recreate); + assert_eq!(bridges.plan("kiri0", Some(gw4), 24, None), BridgePlan::Recreate); + assert_eq!(bridges.plan("kiri0", None, 16, Some((gw6, 64))), BridgePlan::Recreate); + + // Once IPv6 is configured on kiri0, both matching IPv6 callers and IPv4-only + // callers reuse the existing bridge; a different IPv6 subnet recreates it. + bridges.made.insert("kiri0".into(), (42, Some(gw4), 16, Some((gw6, 64)))); + assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, Some(v6)).unwrap(), 42); + assert_eq!(bridges.ensure("kiri0", Some(gw4), 16, None).unwrap(), 42); + assert_eq!(bridges.plan("kiri0", Some(gw4), 16, Some((other6, 64))), BridgePlan::Recreate); + } + + fn test_dhcp() -> Dhcp { + let (r, _w) = sys::pipe().unwrap(); + Dhcp { sock: r, index: 2, mac: [2, 0, 0, 0, 0, 1], xid: 1, state: DhcpState::Discovering, next_send: Instant::now() + Duration::from_secs(1), attempt: 1, lease: None } + } + + #[test] + fn set_uplink_applies_skips_when_leased_and_validates() { + let mut dhcp = test_dhcp(); + for (ip, prefix, gw) in [ + ([0; 4], 24, [192, 168, 64, 1]), + ([192, 168, 64, 2], 0, [192, 168, 64, 1]), + ([192, 168, 64, 2], 31, [192, 168, 64, 1]), + ([192, 168, 64, 2], 32, [192, 168, 64, 1]), + ([192, 168, 64, 2], 33, [192, 168, 64, 1]), + ([127, 0, 0, 2], 8, [127, 0, 0, 1]), + ([224, 0, 0, 2], 24, [224, 0, 0, 1]), + ([240, 0, 0, 2], 24, [240, 0, 0, 1]), + ([192, 168, 64, 1], 24, [192, 168, 64, 1]), + ([192, 168, 64, 255], 24, [192, 168, 64, 1]), + ([192, 168, 64, 0], 24, [192, 168, 64, 1]), + ([192, 168, 65, 2], 24, [192, 168, 64, 1]), + ] { + assert!(dhcp.apply_static_with(ip, prefix, gw, [0; 4], |_| panic!("must not configure")).is_err()); + } + assert!(dhcp.apply_static_with([192, 168, 64, 2], 24, [192, 168, 64, 1], [192, 168, 64, 1], |_| Ok(())).unwrap()); + assert_eq!(dhcp.timeout_ms(), -1); + let l = dhcp.lease.as_ref().unwrap(); + assert_eq!((l.ip, l.prefix, l.gateway, l.dns.as_slice()), ([192, 168, 64, 2], 24, [192, 168, 64, 1], &[[192, 168, 64, 1]][..])); + // No-op when a lease (from DHCP or SetUplink) is already active. + assert!(!dhcp.apply_static_with([192, 168, 64, 9], 24, [192, 168, 64, 1], [0; 4], |_| panic!("must not reconfigure")).unwrap()); + assert_eq!(dhcp.lease.as_ref().unwrap().ip, [192, 168, 64, 2]); + } + + #[test] + fn effective_host_addr_uses_wsl_host_addr_only_when_wsl_relay_active() { + assert_eq!(effective_host_addr_for(false, false), HOST_ADDR); + assert_eq!(effective_host_addr_for(false, true), HOST_ADDR); + assert_eq!(effective_host_addr_for(true, false), HOST_ADDR); + assert_eq!(effective_host_addr_for(true, true), WSL_HOST_ADDR); + assert!(is_hostrelay_cmdline(b"/usr/local/bin/kiri\0hostrelay\0")); + assert!(!is_hostrelay_cmdline(b"/usr/local/bin/kiri\0daemon\0")); + assert!(!is_hostrelay_cmdline(b"")); + let pid_path = std::env::temp_dir().join(format!("kiri-net-hostrelay-{}.pid", std::process::id())); + let _ = std::fs::remove_file(&pid_path); + assert!(!pid_file_alive(&pid_path, |_| true)); + std::fs::write(&pid_path, format!("{}\n", std::process::id())).unwrap(); + assert!(pid_file_alive(&pid_path, |_| true)); + assert!(!pid_file_alive(&pid_path, |_| false)); + let _ = std::fs::remove_file(&pid_path); + } + + #[test] + fn abstract_netns_lock_rejects_second_holder_across_full_retry_loop() { + use std::sync::atomic::AtomicBool; + use std::sync::OnceLock; + let name = format!("kiri-netns-test-{}", std::process::id()); + let slot1 = OnceLock::new(); + let claimed1 = AtomicBool::new(false); + claim_host_netns_on(name.as_bytes(), &slot1, &claimed1).expect("first holder claims abstract netns lock"); + + // Run 8 full 500ms `claim_host_netns_on` retry loops (> 160 probes, + // exceeding `listen(128)` when drained between ticks as `agent::serve_loop` + // does) to verify `drain_netns_lock` prevents `EAGAIN` false negatives. + for _ in 0..8 { + let slot2 = OnceLock::new(); + let claimed2 = AtomicBool::new(false); + let err = claim_host_netns_on(name.as_bytes(), &slot2, &claimed2) + .expect_err("second holder in same netns must fail after full retry window"); + assert_eq!(err.kind(), io::ErrorKind::AddrInUse); + assert!(!claimed2.load(std::sync::atomic::Ordering::Acquire)); + drain_netns_lock(slot1.get().unwrap().as_raw_fd()); + } + + let me = unsafe { libc::geteuid() }; + assert_eq!(probe_abstract_lock(name.as_bytes(), me), LockProbe::OwnedByOwner); + assert_eq!(probe_abstract_lock(name.as_bytes(), me.wrapping_add(1)), LockProbe::OwnedByOther); + + drop(slot1); + // Unbound socket returns TransientBusy (`ECONNREFUSED`), never OwnedByOther. + assert_eq!(probe_abstract_lock(name.as_bytes(), me), LockProbe::TransientBusy); + let rebound = try_bind_abstract_socket(name.as_bytes()).expect("rebind succeeds once first fd closes"); + drop(rebound); } } diff --git a/crates/kiri-init/src/linux/netlink.rs b/crates/kiri-init/src/linux/netlink.rs index 69fbb926b..663787a34 100644 --- a/crates/kiri-init/src/linux/netlink.rs +++ b/crates/kiri-init/src/linux/netlink.rs @@ -28,12 +28,16 @@ const IFLA_LINKINFO: u16 = 18; const IFLA_NET_NS_FD: u16 = 28; const IFLA_INFO_KIND: u16 = 1; const IFLA_INFO_DATA: u16 = 2; +const IFLA_INFO_SLAVE_KIND: u16 = 4; +const IFLA_INFO_SLAVE_DATA: u16 = 5; +const IFLA_BRPORT_ISOLATED: u16 = 33; const VETH_INFO_PEER: u16 = 1; const IFA_ADDRESS: u16 = 1; const IFA_LOCAL: u16 = 2; const RTA_DST: u16 = 1; const RTA_GATEWAY: u16 = 5; const RTA_OIF: u16 = 4; +const RTA_PREFSRC: u16 = 7; /// One netlink message under construction. pub struct Msg { @@ -125,11 +129,7 @@ impl Netlink { /// A route socket inside another network namespace: entered just long /// enough to create the socket, which stays bound to that namespace. pub fn open_in(netns: &std::fs::File) -> io::Result { - let own = std::fs::File::open("/proc/self/ns/net")?; - sys::setns(netns.as_raw_fd(), libc::CLONE_NEWNET)?; - let nl = Netlink::open(libc::NETLINK_ROUTE); - sys::setns(own.as_raw_fd(), libc::CLONE_NEWNET)?; - nl + in_netns(netns, || Netlink::open(libc::NETLINK_ROUTE)) } /// Sends messages (one batch) and waits for every acknowledgement. @@ -250,19 +250,23 @@ fn ifinfo(index: i32, flags: u32, change: u32) -> [u8; 16] { /// broke mid-TLS until it was asked again. Docker gives its bridges an /// address for the same reason. A bridge left by an earlier run without /// one (a Linux host) gets one too. -pub fn create_bridge(nl: &mut Netlink, name: &str) -> io::Result<()> { +/// Returns `Ok(true)` when a new bridge was created, or `Ok(false)` when an +/// interface named `name` already existed. +pub fn create_bridge(nl: &mut Netlink, name: &str) -> io::Result { match nl.request(&mut [new_bridge(name, bridge_mac(random_bytes()))]) { + Ok(()) => Ok(true), Err(e) if e.raw_os_error() == Some(libc::EEXIST) => { // NET_ADDR_SET (3): someone set it, so it no longer follows the ports. let kind = std::fs::read_to_string(format!("/sys/class/net/{name}/addr_assign_type")).unwrap_or_default(); if kind.trim() == "3" { - return Ok(()); + return Ok(false); } let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK); m.raw(&ifinfo(index_of(name)?, 0, 0)).attr(IFLA_ADDRESS, &bridge_mac(random_bytes())); - nl.request(&mut [m]) + nl.request(&mut [m])?; + Ok(false) } - r => r, + Err(e) => Err(e), } } @@ -289,7 +293,10 @@ fn random_bytes() -> [u8; 6] { /// peer is created straight inside `netns` as `peer`. The kernel picks the /// peer's interface index: a new namespace is not always only lo (with ipip /// or gre loaded it has tunl0, gre0 … too), so it is looked up by name. -pub fn create_veth(nl: &mut Netlink, host: &str, bridge_index: i32, netns: &std::fs::File, mtu: u32, peer: &str, peer_mac: Option<[u8; 6]>) -> io::Result<()> { +/// With `isolated` the host side becomes an isolated bridge port in the same +/// request, before the container runs. +#[allow(clippy::too_many_arguments)] +pub fn create_veth(nl: &mut Netlink, host: &str, bridge_index: i32, netns: &std::fs::File, mtu: u32, peer: &str, peer_mac: Option<[u8; 6]>, isolated: bool) -> io::Result<()> { let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); m.raw(&ifinfo(0, libc::IFF_UP as u32, libc::IFF_UP as u32)).attr_str(IFLA_IFNAME, host).attr_u32(IFLA_MASTER, bridge_index as u32); m.attr_u32(IFLA_MTU, mtu); @@ -300,7 +307,24 @@ pub fn create_veth(nl: &mut Netlink, host: &str, bridge_index: i32, netns: &std: m.attr(IFLA_ADDRESS, &mac); } m.end().end().end(); - nl.request(&mut [m]) + if isolated { + nl.request(&mut [m, isolate_port_msg(host)]) + } else { + nl.request(&mut [m]) + } +} + +/// `ip link set dev type bridge_slave isolated on`: the bridge port +/// forwards nothing to another isolated port, so containers on the same +/// network cannot reach each other (Docker's `enable_icc=false`), while the +/// bridge itself (the gateway, DNS, published ports, egress) still can. +fn isolate_port_msg(name: &str) -> Msg { + let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK); + m.raw(&ifinfo(0, 0, 0)).attr_str(IFLA_IFNAME, name); + m.nest(IFLA_LINKINFO).attr_str(IFLA_INFO_SLAVE_KIND, "bridge"); + m.nest(IFLA_INFO_SLAVE_DATA).attr(IFLA_BRPORT_ISOLATED, &[1]); + m.end().end(); + m } pub fn delete_link(nl: &mut Netlink, name: &str) -> io::Result<()> { @@ -309,13 +333,17 @@ pub fn delete_link(nl: &mut Netlink, name: &str) -> io::Result<()> { nl.request(&mut [m]) } -pub fn set_up(nl: &mut Netlink, index: i32) -> io::Result<()> { +pub fn set_up_msg(index: i32) -> Msg { let mut m = Msg::new(RTM_NEWLINK, NLM_F_ACK); m.raw(&ifinfo(index, libc::IFF_UP as u32, libc::IFF_UP as u32)); - nl.request(&mut [m]) + m } -pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> io::Result<()> { +pub fn set_up(nl: &mut Netlink, index: i32) -> io::Result<()> { + nl.request(&mut [set_up_msg(index)]) +} + +pub fn add_address_msg(index: i32, addr: [u8; 4], prefix: u8) -> Msg { let mut m = Msg::new(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); // struct ifaddrmsg: family, prefixlen, flags, scope, index. let mut ifa = [0u8; 8]; @@ -323,7 +351,11 @@ pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> i ifa[1] = prefix; ifa[4..8].copy_from_slice(&(index as u32).to_ne_bytes()); m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr); - match nl.request(&mut [m]) { + m +} + +pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> io::Result<()> { + match nl.request(&mut [add_address_msg(index, addr, prefix)]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, } @@ -332,7 +364,7 @@ pub fn add_address(nl: &mut Netlink, index: i32, addr: [u8; 4], prefix: u8) -> i /// An IPv6 address, usable at once: no duplicate address detection, which /// would leave it tentative (not usable as a source) for about a second. /// Kiri hands out every address on its networks, so none can be taken. -pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> io::Result<()> { +pub fn add_address6_msg(index: i32, addr: [u8; 16], prefix: u8) -> Msg { const IFA_F_NODAD: u8 = 0x02; let mut m = Msg::new(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); let mut ifa = [0u8; 8]; @@ -341,7 +373,11 @@ pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> ifa[2] = IFA_F_NODAD; ifa[4..8].copy_from_slice(&(index as u32).to_ne_bytes()); m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr); - match nl.request(&mut [m]) { + m +} + +pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> io::Result<()> { + match nl.request(&mut [add_address6_msg(index, addr, prefix)]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, } @@ -350,34 +386,68 @@ pub fn add_address6(nl: &mut Netlink, index: i32, addr: [u8; 16], prefix: u8) -> /// The IPv6 default route through `gateway` on `index`. The first network /// with IPv6 a container joins keeps it: a second one is EEXIST, left be. pub fn add_default_route6(nl: &mut Netlink, index: i32, gateway: [u8; 16]) -> io::Result<()> { - let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); + default_route(nl, libc::AF_INET6, &gateway, index, NLM_F_EXCL) +} + +/// The IPv4 default route through `gateway` on `index`. As with IPv6 the +/// first non-internal network keeps it: without EXCL Linux would take a +/// second default of the same metric, and send through either. +pub fn add_default_route(nl: &mut Netlink, index: i32, gateway: [u8; 4]) -> io::Result<()> { + default_route(nl, libc::AF_INET, &gateway, index, NLM_F_EXCL) +} + +/// Moves the IPv4 default route to `gateway` on `index`, or adds it. +pub fn replace_default_route(nl: &mut Netlink, index: i32, gateway: [u8; 4]) -> io::Result<()> { + default_route(nl, libc::AF_INET, &gateway, index, NLM_F_REPLACE) +} + +/// Moves the IPv6 default route to `gateway` on `index`, or adds it. +pub fn replace_default_route6(nl: &mut Netlink, index: i32, gateway: [u8; 16]) -> io::Result<()> { + default_route(nl, libc::AF_INET6, &gateway, index, NLM_F_REPLACE) +} + +fn default_route(nl: &mut Netlink, family: i32, gateway: &[u8], index: i32, flags: u16) -> io::Result<()> { + let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE | flags); + // struct rtmsg: family, dst_len, src_len, tos, table, protocol, scope, type, flags. let mut rt = [0u8; 12]; - rt[0] = libc::AF_INET6 as u8; + rt[0] = family as u8; rt[4] = libc::RT_TABLE_MAIN; rt[5] = libc::RTPROT_BOOT; rt[6] = libc::RT_SCOPE_UNIVERSE; rt[7] = libc::RTN_UNICAST; - m.raw(&rt).attr(RTA_GATEWAY, &gateway).attr_u32(RTA_OIF, index as u32); + m.raw(&rt).attr(RTA_GATEWAY, gateway).attr_u32(RTA_OIF, index as u32); match nl.request(&mut [m]) { Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), r => r, } } -pub fn add_default_route(nl: &mut Netlink, index: i32, gateway: [u8; 4]) -> io::Result<()> { - let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE); - // struct rtmsg: family, dst_len, src_len, tos, table, protocol, scope, type, flags. +/// Adds an IPv4 default route on device `index` with no gateway (`default dev +/// scope link [src ]`). Used in a VM booted without an `eth0` +/// NIC (shared NAT disabled) so locally originated connections (`--network host` +/// containers) succeed route lookup and reach nftables `output` redirect rules +/// instead of failing immediately with `ENETUNREACH`. +pub fn add_device_default_route(nl: &mut Netlink, index: i32, prefsrc: Option<[u8; 4]>) -> io::Result<()> { + let m = device_default_route_msg(index, prefsrc); + match nl.request(&mut [m]) { + Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), + r => r, + } +} + +fn device_default_route_msg(index: i32, prefsrc: Option<[u8; 4]>) -> Msg { + let mut m = Msg::new(RTM_NEWROUTE, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL); let mut rt = [0u8; 12]; rt[0] = libc::AF_INET as u8; rt[4] = libc::RT_TABLE_MAIN; rt[5] = libc::RTPROT_BOOT; - rt[6] = libc::RT_SCOPE_UNIVERSE; + rt[6] = libc::RT_SCOPE_LINK; rt[7] = libc::RTN_UNICAST; - m.raw(&rt).attr(RTA_GATEWAY, &gateway).attr_u32(RTA_OIF, index as u32); - match nl.request(&mut [m]) { - Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(()), - r => r, + m.raw(&rt).attr_u32(RTA_OIF, index as u32); + if let Some(src) = prefsrc { + m.attr(RTA_PREFSRC, &src); } + m } /// Adds (or replaces) the route `dst/prefix via gateway`, or removes it. @@ -406,12 +476,32 @@ pub fn index_in(netns: &std::fs::File, name: &str) -> io::Result { in_netns(netns, || index_of(name)) } +thread_local! { + static OWN_NETNS: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +fn own_netns_fd() -> io::Result { + OWN_NETNS.with(|slot| { + let mut slot = slot.borrow_mut(); + if let Some(f) = slot.as_ref() { + return Ok(f.as_raw_fd()); + } + let f = std::fs::File::open("/proc/self/ns/net")?; + let raw = f.as_raw_fd(); + *slot = Some(f); + Ok(raw) + }) +} + /// Runs `f` with this thread in `netns`, then back in its own. pub fn in_netns(netns: &std::fs::File, f: impl FnOnce() -> io::Result) -> io::Result { - let own = std::fs::File::open("/proc/self/ns/net")?; + let own = own_netns_fd()?; sys::setns(netns.as_raw_fd(), libc::CLONE_NEWNET)?; let r = f(); - sys::setns(own.as_raw_fd(), libc::CLONE_NEWNET)?; + if let Err(e) = sys::setns(own, libc::CLONE_NEWNET) { + eprintln!("kiri-init: cannot return to own network namespace: {e}"); + std::process::abort(); + } r } @@ -425,6 +515,65 @@ pub fn index_of(name: &str) -> io::Result { Ok(i as i32) } +/// Resolves an interface index back to its kernel device name. +pub fn name_of(index: i32) -> Option { + if index <= 0 { + return None; + } + let mut buf = [0u8; libc::IFNAMSIZ]; + // SAFETY: `buf` is `IFNAMSIZ` writable bytes; returns null on unknown index. + let p = unsafe { libc::if_indextoname(index as libc::c_uint, buf.as_mut_ptr().cast()) }; + (!p.is_null()).then(|| nl_str(&buf)) +} + +/// Parses one `RTM_NEWROUTE` netlink payload (`rtmsg` + attributes) and returns +/// any output interface indices for a IPv4/IPv6 unicast default route (`dst_len == 0`) +/// across all routing tables (including policy-routed VPNs and secondary NICs). +fn parse_default_route_ifindices(p: &[u8]) -> Vec { + const RTA_MULTIPATH: u16 = 9; + let Some(rt) = p.get(..12) else { return Vec::new() }; + let (family, dst_len, ty) = (rt[0], rt[1], rt[7]); + if dst_len != 0 || ty != libc::RTN_UNICAST || (family != libc::AF_INET as u8 && family != libc::AF_INET6 as u8) { + return Vec::new(); + } + let mut out = Vec::new(); + for (attr_ty, data) in attrs(&p[12..]) { + if attr_ty == RTA_OIF + && let Some(idx) = data.get(..4).and_then(|b| b.try_into().ok()).map(i32::from_ne_bytes) + { + out.push(idx); + } else if attr_ty == RTA_MULTIPATH { + // Sequence of `struct rtnexthop` (8-byte header: u16 len, u8 flags, u8 hops, i32 ifindex). + let mut off = 0; + while off + 8 <= data.len() { + let len = u16::from_ne_bytes([data[off], data[off + 1]]) as usize; + let idx = i32::from_ne_bytes(data[off + 4..off + 8].try_into().expect("4")); + if len < 8 || off + len > data.len() { + break; + } + out.push(idx); + off += (len + 3) & !3; + } + } + } + out +} + +/// Interface indices holding an IPv4 or IPv6 unicast default route in any +/// routing table (`RT_TABLE_MAIN`, policy tables such as Tailscale `52`, etc.). +pub fn default_route_ifindices() -> io::Result> { + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + let mut req = Msg::new(libc::RTM_GETROUTE, 0x300); // NLM_F_DUMP (includes NLM_F_REQUEST) + let mut rt = [0u8; 12]; + rt[0] = libc::AF_UNSPEC as u8; + req.raw(&rt); + let mut out = Vec::new(); + nl.dump(&mut req, |p| out.extend(parse_default_route_ifindices(p)))?; + out.sort_unstable(); + out.dedup(); + Ok(out) +} + // nf_tables, through NETLINK_NETFILTER. const NFNL_SUBSYS_NFTABLES: u16 = 10; const NFNL_MSG_BATCH_BEGIN: u16 = 0x10; @@ -479,12 +628,46 @@ fn nat_chain(name: &str, hook: u32, priority: i32) -> Msg { /// Kiri's container bridges are kiri0, kiri1, … (the daemon names them). const BRIDGE_PREFIX: &[u8] = b"kiri"; -/// `ip daddr tcp redirect to :`: connections to `addr` (any -/// port) go to a local listener, which can read the original port back. -/// With `from_bridges`, only packets arriving on a Kiri bridge match -/// (`iifname "kiri*"`): the redirect leads to the host's loopback, which -/// nothing on the uplink (the LAN, on a Linux host) may reach. -fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> Msg { +/// Netmask bytes for an IPv4 CIDR prefix length (`0..=32`). +pub fn ipv4_mask(prefix: u8) -> [u8; 4] { + let p = prefix.min(32); + if p == 0 { [0; 4] } else { (u32::MAX << (32 - p)).to_be_bytes() } +} + +/// Masks `ip` to its `prefix`-bit network address. +pub fn mask_ipv4(ip: [u8; 4], prefix: u8) -> [u8; 4] { + let m = ipv4_mask(prefix); + [ip[0] & m[0], ip[1] & m[1], ip[2] & m[2], ip[3] & m[3]] +} + +/// Matches an IPv4 header address (`offset` = 12 for saddr, 16 for daddr) against +/// `addr/prefix`. A `/0` prefix matches everything and emits no expressions. +fn match_ipv4_addr_prefix(rule: &mut Msg, offset: u32, addr: [u8; 4], prefix: u8) { + let p = prefix.min(32); + if p == 0 { + return; + } + // payload network header + offset, 4 bytes => reg 1 + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, offset).attr_be32(4, 4).end().end(); + if p < 32 { + let mask = ipv4_mask(p); + let net = mask_ipv4(addr, p); + rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); + rule.nest(4).attr(1, &mask).end().nest(5).attr(1, &[0; 4]).end().end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &net).end().end().end(); + } else { + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + } +} + +fn match_daddr_prefix(rule: &mut Msg, addr: [u8; 4], prefix: u8) { + match_ipv4_addr_prefix(rule, 16, addr, prefix); +} + +/// `ip daddr / tcp redirect to :`: connections to +/// `addr/prefix` (any port) go to a local listener, which can read the +/// original destination and port back via `SO_ORIGINAL_DST`. +fn redirect_prefix_rule(chain: &str, addr: [u8; 4], prefix: u8, port: u16, from_bridges: bool) -> Msg { let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, "kiri").attr_str(2, chain); rule.nest(4); @@ -497,9 +680,7 @@ fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> M // meta l4proto => reg 1; cmp eq tcp rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); - // payload network header + 16 (daddr), 4 bytes => reg 1; cmp eq addr - rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); - rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + match_daddr_prefix(&mut rule, addr, prefix); // immediate reg 1 = port; redir to it rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 1).nest(2).attr(1, &port.to_be_bytes()).end().end().end(); rule.nest(1).attr_str(1, "redir").nest(2).attr_be32(1, 1).end().end(); @@ -507,6 +688,33 @@ fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> M rule } +/// `ip daddr / tcp accept`: exempts local, bridge and uplink +/// subnets from subsequent broader egress redirect rules (such as `0.0.0.0/0`). +fn accept_prefix_rule(chain: &str, addr: [u8; 4], prefix: u8, from_bridges: bool) -> Msg { + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, chain); + rule.nest(4); + if from_bridges { + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + } + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + match_daddr_prefix(&mut rule, addr, prefix); + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_ACCEPT as u32).end().end().end().end(); + rule.end(); + rule +} + +/// `ip daddr tcp redirect to :`: connections to `addr` (any +/// port) go to a local listener, which can read the original port back. +/// With `from_bridges`, only packets arriving on a Kiri bridge match +/// (`iifname "kiri*"`): the redirect leads to the host's loopback, which +/// nothing on the uplink (the LAN, on a Linux host) may reach. +fn redirect_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> Msg { + redirect_prefix_rule(chain, addr, 32, port, from_bridges) +} + /// `iifname "kiri*" ip daddr udp dport 53 redirect to :53`: DNS /// sent to the host's address goes to the embedded DNS on the receiving /// bridge's gateway. A kind node rewrites its resolv.conf from 127.0.0.11 to @@ -546,20 +754,20 @@ pub struct Dnat { pub to_port: u16, } -/// `[ip daddr | fib daddr type local ip daddr != 127.0.0.0/8] +/// `[ip daddr | fib daddr type local [ip daddr != ] ip daddr != 127.0.0.0/8] /// dport dnat to :`. -fn dnat_rule(chain: &str, d: &Dnat) -> Msg { - dnat_rule_from(chain, d, None) +fn dnat_rule(chain: &str, d: &Dnat, exclude_ip: Option<[u8; 4]>) -> Msg { + dnat_rule_from(chain, d, None, exclude_ip) } /// `dnat_rule`, matching only packets that arrive on interface `from.0` /// from address `from.1` (`iif ip saddr ...`). -fn dnat_rule_from(chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>) -> Msg { - dnat_rule_in("kiri", chain, d, from) +fn dnat_rule_from(chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>, exclude_ip: Option<[u8; 4]>) -> Msg { + dnat_rule_in("kiri", chain, d, from, exclude_ip) } /// `dnat_rule_from` in table `table`. -fn dnat_rule_in(table: &str, chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>) -> Msg { +fn dnat_rule_in(table: &str, chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])>, exclude_ip: Option<[u8; 4]>) -> Msg { let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, table).attr_str(2, chain); rule.nest(4); @@ -575,10 +783,14 @@ fn dnat_rule_in(table: &str, chain: &str, d: &Dnat, from: Option<(i32, [u8; 4])> // fib daddr type => reg 1 (NFTA_FIB_DREG, RESULT = ADDRTYPE 3, FLAGS = DADDR 2); cmp eq RTN_LOCAL rule.nest(1).attr_str(1, "fib").nest(2).attr_be32(1, 1).attr_be32(2, 3).attr_be32(3, 2).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &2u32.to_ne_bytes()).end().end().end(); - // payload daddr => reg 1; reg 1 &= 255.0.0.0; cmp neq 127.0.0.0. Without - // it a packet for 127.0.0.1 is rewritten before routing: one arriving - // from the LAN would reach the container instead of being dropped. + // payload daddr => reg 1; optional cmp neq exclude_ip (WSL host-gateway + // 192.168.65.254 on `lo`); then reg 1 &= 255.0.0.0; cmp neq 127.0.0.0. + // Without the loopback guard a packet for 127.0.0.1 is rewritten before + // routing: one arriving from the LAN would reach the container instead of being dropped. rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + if let Some(skip) = exclude_ip { + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &skip).end().end().end(); + } rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); rule.nest(4).attr(1, &[255, 0, 0, 0]).end().nest(5).attr(1, &[0; 4]).end().end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &[127, 0, 0, 0]).end().end().end(); @@ -658,33 +870,81 @@ const CT_STATUS_DNAT: u32 = 1 << 5; /// and it passes. A container on two networks talks to each over its own /// interface there; a published port on another network is still reached /// through the host's address (ct status dnat), as with Docker. -fn forward_filter(bridges: &[String], guard: Option<&str>) -> Vec { - forward_filter_in(libc::NFPROTO_IPV4 as u8, bridges, guard) +/// Exact NUL-padded `IFNAMSIZ` name buffer for whole-interface nftables matches. +fn ifname_full(name: &str) -> [u8; 16] { + let mut full = [0u8; 16]; + let n = name.len().min(15); + full[..n].copy_from_slice(&name.as_bytes()[..n]); + full } -/// While Kiri's bridges are in firewalld's trusted zone (`firewall.rs`), -/// which accepts whatever they send, the uplinks (IPv4, IPv6) the forward -/// filter lets new connections out through: -/// -/// ```text -/// iifname "kiri*" oifname != "kiri*" oifname != "" -/// ct state & (established|related) == 0 ct status & dnat == 0 drop -/// ``` -/// -/// first in the chain. Kiri's containers then reach what the iptables rules -/// let them reach where there is no firewalld (the internet through the -/// uplink, published ports, replies), and not another program's bridge or -/// network, which firewalld kept them from before. -pub static FORWARD_GUARD: std::sync::Mutex> = std::sync::Mutex::new(None); +/// `ip saddr / oifname != "kiri*" oifname != "lo" masquerade` +/// for a Linux host, so container egress works across primary NICs, failover +/// NICs, policy-routed VPNs (`tailscale0`, `wg0`), and secondary interfaces +/// without sending bridge-to-bridge or loopback traffic through MASQUERADE. +fn masq4_rule(subnet: [u8; 4], prefix: u8) -> Msg { + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, "postrouting"); + rule.nest(4); + match_ipv4_addr_prefix(&mut rule, 12, subnet, prefix); + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 7).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + let lo = ifname_full("lo"); + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 7).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &lo).end().end().end(); + rule.nest(1).attr_str(1, "masq").end(); + rule.end(); + rule +} + +#[cfg(test)] +fn forward_filter(bridges: &[String], foreign: &[String]) -> Vec { + forward_filter_in(libc::NFPROTO_IPV4 as u8, bridges, foreign, false) +} -/// `FORWARD_GUARD`'s uplink for `family`. -fn forward_guard(family: u8) -> Option { - FORWARD_GUARD.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(up4, up6)| if family == libc::NFPROTO_IPV6 as u8 { up6.clone() } else { up4.clone() }) +fn forward_filter_v4(bridges: &[String], foreign: &[String], drop_lo: bool) -> Vec { + forward_filter_in(libc::NFPROTO_IPV4 as u8, bridges, foreign, drop_lo) +} + +/// Non-Kiri local bridges on a Linux host (e.g. `docker0`, `br-*`, `virbr*`, +/// excluding default-route bridges such as `vmbr0`) that containers on `kiri*` +/// must not initiate new connections into. Empty in the VM. +pub static FOREIGN_BRIDGES: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + +fn foreign_bridges() -> Vec { + FOREIGN_BRIDGES.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +/// `tcp flags syn tcp option maxseg size set rt mtu`: clamps the TCP MSS on +/// forwarded SYN packets to the route's path MTU. +fn tcp_mss_clamp_rule(family: u8) -> Msg { + let mut rule = nft_in(family, NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, "forward"); + rule.nest(4); + // meta l4proto => reg 1; cmp eq tcp + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + // payload transport header + 13 (tcp flags), 1 byte => reg 1; (reg 1 & 0x02) != 0 (SYN) + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 13).attr_be32(4, 1).end().end(); + rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 1); + rule.nest(4).attr(1, &[0x02]).end().nest(5).attr(1, &[0x00]).end().end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &[0x00]).end().end().end(); + // rt load tcpmss (NFT_RT_TCPMSS = 3) => reg 1 + rule.nest(1).attr_str(1, "rt").nest(2).attr_be32(1, 1).attr_be32(2, 3).end().end(); + // byteorder reg 1 = hton(reg 1, 2, 2) (NFT_BYTEORDER_HTON = 1) + rule.nest(1).attr_str(1, "byteorder").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 1).attr_be32(4, 2).attr_be32(5, 2).end().end(); + // exthdr write tcpopt reg 1 => 2b @ 2 + 2 (type 2 = TCPOPT_MAXSEG, op 1 = NFT_EXTHDR_OP_TCPOPT) + rule.nest(1).attr_str(1, "exthdr").nest(2).attr_be32(7, 1).attr(2, &[2]).attr_be32(3, 2).attr_be32(4, 2).attr_be32(6, 1).end().end(); + rule.end(); + rule } /// `forward_filter` for a table of `family`: the same rules hold for IPv6. -/// `guard`: the uplink, while `FORWARD_GUARD` holds one. -fn forward_filter_in(family: u8, bridges: &[String], guard: Option<&str>) -> Vec { +/// `foreign`: non-Kiri local bridges on a Linux host whose bridges `kiri*` +/// containers must not initiate new connections into. +/// `drop_lo`: drop forwarded packets routed out `lo` (when a VM has no `eth0` +/// and installs a fallback `default dev lo` route for host-network egress). +fn forward_filter_in(family: u8, bridges: &[String], foreign: &[String], drop_lo: bool) -> Vec { let nft = |msg, flags| nft_in(family, msg, flags); let mut chain = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); chain.attr_str(1, "kiri").attr_str(3, "forward"); @@ -707,20 +967,16 @@ fn forward_filter_in(family: u8, bridges: &[String], guard: Option<&str>) -> Vec r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, op).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); } }; - // ct => reg 1; reg 1 &= mask; cmp neq 0 - let ct_any = |key: u32, mask: u32| { - move |r: &mut Msg| { - r.nest(1).attr_str(1, "ct").nest(2).attr_be32(1, 1).attr_be32(2, key).end().end(); - r.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); - r.nest(4).attr(1, &mask.to_ne_bytes()).end().nest(5).attr(1, &0u32.to_ne_bytes()).end().end().end(); - r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &0u32.to_ne_bytes()).end().end().end(); - } + // ct => reg 1; reg 1 &= mask; cmp `op` 0 + let ct_mask = |r: &mut Msg, key: u32, mask: u32, op: u32| { + r.nest(1).attr_str(1, "ct").nest(2).attr_be32(1, 1).attr_be32(2, key).end().end(); + r.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); + r.nest(4).attr(1, &mask.to_ne_bytes()).end().nest(5).attr(1, &0u32.to_ne_bytes()).end().end().end(); + r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, op).nest(3).attr(1, &0u32.to_ne_bytes()).end().end().end(); }; // meta iifname, oifname => reg 1; cmp eq the whole name (IFNAMSIZ, NUL-padded) let same_bridge = |name: &str| { - let mut full = [0u8; 16]; - let n = name.len().min(15); - full[..n].copy_from_slice(&name.as_bytes()[..n]); + let full = ifname_full(name); move |r: &mut Msg| { for key in [6, 7] { r.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, key).end().end(); @@ -730,72 +986,68 @@ fn forward_filter_in(family: u8, bridges: &[String], guard: Option<&str>) -> Vec }; let (accept, drop) = (libc::NF_ACCEPT as u32, libc::NF_DROP as u32); let mut msgs = vec![chain]; - if let Some(uplink) = guard { - let mut full = [0u8; 16]; - let n = uplink.len().min(15); - full[..n].copy_from_slice(&uplink.as_bytes()[..n]); - // ct & mask == 0 - let ct_none = |r: &mut Msg, key: u32, mask: u32| { - r.nest(1).attr_str(1, "ct").nest(2).attr_be32(1, 1).attr_be32(2, key).end().end(); - r.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); - r.nest(4).attr(1, &mask.to_ne_bytes()).end().nest(5).attr(1, &0u32.to_ne_bytes()).end().end().end(); - r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &0u32.to_ne_bytes()).end().end().end(); - }; + if family == libc::NFPROTO_IPV4 as u8 { + // Block container forwarding to link-local / cloud IMDS (169.254.0.0/16) + // ahead of oifname != "kiri*" accept while leaving 100.64.0.0/10 untouched. msgs.push(rule( &|r| { ifname(6, 0)(r); - ifname(7, 1)(r); + match_ipv4_addr_prefix(r, 16, [169, 254, 0, 0], 16); + }, + drop, + )); + } + // Accept same-bridge traffic ahead of MSS clamping and conntrack checks so + // intra-bridge packets never undergo route-MTU SYN rewriting (#509). + msgs.extend(bridges.iter().map(|b| rule(&same_bridge(b), accept))); + for fb in foreign { + let full = ifname_full(fb); + msgs.push(rule( + &|r| { + ifname(6, 0)(r); + r.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 7).end().end(); + r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &full).end().end().end(); + ct_mask(r, 0, CT_ESTABLISHED | CT_RELATED, 0); + ct_mask(r, 2, CT_STATUS_DNAT, 0); + }, + drop, + )); + } + msgs.push(tcp_mss_clamp_rule(family)); + if drop_lo { + let lo = ifname_full("lo"); + msgs.push(rule( + &|r| { r.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 7).end().end(); - r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &full).end().end().end(); - ct_none(r, 0, CT_ESTABLISHED | CT_RELATED); - ct_none(r, 2, CT_STATUS_DNAT); + r.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &lo).end().end().end(); }, drop, )); } msgs.extend([ - rule(&ifname(7, 1), accept), // NFT_CMP_NEQ - rule(&ct_any(0, CT_ESTABLISHED | CT_RELATED), accept), // NFT_CT_STATE - rule(&ct_any(2, CT_STATUS_DNAT), accept), // NFT_CT_STATUS + rule(&ifname(7, 1), accept), // NFT_CMP_NEQ + rule(&|r| ct_mask(r, 0, CT_ESTABLISHED | CT_RELATED, 1), accept), // NFT_CT_STATE + rule(&|r| ct_mask(r, 2, CT_STATUS_DNAT, 1), accept), // NFT_CT_STATUS ]); - msgs.extend(bridges.iter().map(|b| rule(&same_bridge(b), accept))); msgs.push(rule(&|_| {}, drop)); msgs } -/// The input filter that keeps containers off the host's loopback: +/// The input filter rule blocking containers from reaching `addr/prefix` +/// unless it is a reply or DNATed connection: /// /// ```text -/// chain input { type filter hook input priority 0; policy accept; -/// iifname "kiri*" ip daddr 127.0.0.0/8 ct state & (established|related) == 0 -/// ct status & dnat == 0 drop -/// } +/// iifname "kiri*" ip daddr / ct state & (established|related) == 0 +/// ct status & dnat == 0 drop /// ``` -/// -/// With `route_localnet` on a bridge, the kernel would take a packet a -/// container sends to 127.0.0.1 (raw socket, gateway MAC) as local: any -/// service bound to the host's loopback answered (the CVE-2020-8558 hole, -/// closed as kube-proxy does). Kiri no longer sets it (the daemon relays -/// the host's loopback connections to published ports), but something -/// else on a Linux host may (kube-proxy sets `conf.all.route_localnet`), -/// so the guard stays. Replies to established connections still pass. -/// Harmless in the VM, which never sets `route_localnet`. -fn localnet_guard() -> Vec { - let mut chain = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); - chain.attr_str(1, "kiri").attr_str(3, "input"); - chain.nest(4).attr_be32(1, 1).attr_be32(2, 0).end(); // NF_INET_LOCAL_IN, priority 0 - chain.attr_be32(5, 1).attr_str(7, "filter"); +fn localnet_guard_rule(addr: [u8; 4], prefix: u8) -> Msg { let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, "kiri").attr_str(2, "input"); rule.nest(4); // meta iifname => reg 1; cmp eq "kiri" prefix rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); - // payload daddr => reg 1; reg 1 &= 255.0.0.0; cmp eq 127.0.0.0 - rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); - rule.nest(1).attr_str(1, "bitwise").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 4); - rule.nest(4).attr(1, &[255, 0, 0, 0]).end().nest(5).attr(1, &[0; 4]).end().end().end(); - rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[127, 0, 0, 0]).end().end().end(); + match_ipv4_addr_prefix(&mut rule, 16, addr, prefix); // ct state & (established|related) == 0; ct status & dnat == 0 for (key, mask) in [(0, CT_ESTABLISHED | CT_RELATED), (2, CT_STATUS_DNAT)] { rule.nest(1).attr_str(1, "ct").nest(2).attr_be32(1, 1).attr_be32(2, key).end().end(); @@ -805,7 +1057,18 @@ fn localnet_guard() -> Vec { } rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_DROP as u32).end().end().end().end(); rule.end(); - vec![chain, rule] + rule +} + +/// The input filter that keeps containers off the host's loopback (`127.0.0.0/8`, +/// CVE-2020-8558) and link-local / cloud metadata (`169.254.0.0/16`). Replies +/// to established connections and DNATed ports still pass. +fn localnet_guard() -> Vec { + let mut chain = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + chain.attr_str(1, "kiri").attr_str(3, "input"); + chain.nest(4).attr_be32(1, 1).attr_be32(2, 0).end(); // NF_INET_LOCAL_IN, priority 0 + chain.attr_be32(5, 1).attr_str(7, "filter"); + vec![chain, localnet_guard_rule([127, 0, 0, 0], 8), localnet_guard_rule([169, 254, 0, 0], 16)] } /// In the VM, the host.docker.internal listener (`port`, on 0.0.0.0) takes @@ -824,7 +1087,15 @@ fn localnet_guard() -> Vec { /// VM's address, a container dialling its gateway) never reached the Mac; /// now it is not even accepted. Redirected connections are DNATed and pass. fn host_relay_guard(port: u16) -> Msg { - let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + host_relay_guard_in(libc::NFPROTO_IPV4 as u8, port) +} + +fn host_relay_guard6(port: u16) -> Msg { + host_relay_guard_in(libc::NFPROTO_IPV6 as u8, port) +} + +fn host_relay_guard_in(family: u8, port: u16) -> Msg { + let mut rule = nft_in(family, NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); rule.attr_str(1, "kiri").attr_str(2, "input"); rule.nest(4); // meta l4proto => reg 1; cmp eq tcp @@ -846,10 +1117,10 @@ fn host_relay_guard(port: u16) -> Msg { /// A published port's DNAT rules: one, or with `local` (a kernel without /// nft_fib_ipv4, so no `fib daddr type local`) one per address of this /// machine for a port published on every address. -fn dnat_rules(chain: &str, d: &Dnat, local: Option<&[[u8; 4]]>) -> Vec { +fn dnat_rules(chain: &str, d: &Dnat, local: Option<&[[u8; 4]]>, exclude_ip: Option<[u8; 4]>) -> Vec { match local { - Some(addrs) if d.host_ip == [0; 4] => addrs.iter().map(|a| dnat_rule(chain, &Dnat { host_ip: *a, ..*d })).collect(), - _ => vec![dnat_rule(chain, d)], + Some(addrs) if d.host_ip == [0; 4] => addrs.iter().map(|a| dnat_rule(chain, &Dnat { host_ip: *a, ..*d }, None)).collect(), + _ => vec![dnat_rule(chain, d, exclude_ip)], } } @@ -879,8 +1150,9 @@ fn masq6_rule(subnet: [u8; 16], prefix: u8) -> Msg { rule } -/// Kiri's IPv6 table, for the IPv6 networks `subnets`, rebuilt whole (and -/// removed with the last one, so an engine with none has no IPv6 rules): +/// Kiri's IPv6 table, for the IPv6 networks `subnets` and (in the VM, when +/// `redirect` is true) the `::1` loopback redirect for published ports and +/// the input guard on `host_port`, rebuilt whole: /// /// ```text /// table ip6 kiri { @@ -888,9 +1160,15 @@ fn masq6_rule(subnet: [u8; 16], prefix: u8) -> Msg { /// ip6 saddr oifname != "kiri*" masquerade # one per network /// } /// chain forward { … } (the IPv4 table's `forward_filter`) +/// chain input { type filter hook input priority 0; +/// tcp dport ct status & dnat == 0 drop +/// } +/// chain output { type nat hook output priority -100; +/// ip6 daddr ::1 tcp dport redirect to : +/// } /// } /// ``` -pub fn install_nat6(subnets: &[([u8; 16], u8)], bridges: &[String]) -> io::Result<()> { +pub fn install_nat6(subnets: &[([u8; 16], u8)], bridges: &[String], host_port: u16, redirect: bool, dnat: &[Dnat]) -> io::Result<()> { let v6 = libc::NFPROTO_IPV6 as u8; let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); @@ -899,17 +1177,33 @@ pub fn install_nat6(subnets: &[([u8; 16], u8)], bridges: &[String]) -> io::Resul let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); let mut msgs = vec![begin, add, delete]; - if !subnets.is_empty() { + if !subnets.is_empty() || redirect { let mut table = nft_in(v6, NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); table.attr_str(1, "kiri"); + msgs.push(table); + } + if !subnets.is_empty() { let mut chain = nft_in(v6, NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); chain.attr_str(1, "kiri").attr_str(3, "postrouting"); chain.nest(4).attr_be32(1, 4).attr_be32(2, 100).end(); chain.attr_be32(5, 1).attr_str(7, "nat"); - msgs.push(table); msgs.push(chain); msgs.extend(subnets.iter().map(|(s, p)| masq6_rule(*s, *p))); - msgs.extend(forward_filter_in(v6, bridges, forward_guard(v6).as_deref())); + msgs.extend(forward_filter_in(v6, bridges, &foreign_bridges(), false)); + } + if redirect { + let mut input = nft_in(v6, NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + input.attr_str(1, "kiri").attr_str(3, "input"); + input.nest(4).attr_be32(1, 1).attr_be32(2, 0).end(); // NF_INET_LOCAL_IN, priority 0 + input.attr_be32(5, 1).attr_str(7, "filter"); + let mut output = nft_in(v6, NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + output.attr_str(1, "kiri").attr_str(3, "output"); + output.nest(4).attr_be32(1, 3).attr_be32(2, -100i32 as u32).end(); // NF_INET_LOCAL_OUT, priority -100 + output.attr_be32(5, 1).attr_str(7, "nat"); + msgs.extend([input, host_relay_guard6(host_port), output]); + for d in dnat.iter().filter(|d| !d.udp && d.host_ip == LOOPBACK && d.host_port != host_port) { + msgs.push(loopback_published_rule6(d.host_port, host_port)); + } } msgs.push(end); nl.request(&mut msgs) @@ -927,21 +1221,22 @@ const EMBEDDED_DNS_TABLE: &str = "kiri_dns"; /// ```text /// table ip kiri_dns { /// chain output { type nat hook output priority -100; -/// ip daddr 127.0.0.11 udp dport 53 dnat to 127.0.0.11: } +/// ip daddr 127.0.0.11 udp dport 53 dnat to 127.0.0.11: +/// ip daddr 127.0.0.11 tcp dport 53 dnat to 127.0.0.11: } /// } /// ``` /// -/// The embedded DNS listens on 127.0.0.11:`port`, a free high port, so port -/// 53 stays free for a DNS server of the container's own (dnsmasq, Pi-hole, -/// CoreDNS bind 0.0.0.0:53), while the container's lookups at 127.0.0.11:53 -/// still reach Kiri's. Replies are mapped back to port 53 by conntrack. TCP -/// is not redirected: the embedded DNS answers over UDP only. -pub fn redirect_embedded_dns(addr: [u8; 4], port: u16) -> io::Result<()> { +/// The embedded DNS listens on 127.0.0.11's free high ports, so port 53 (UDP +/// and TCP) stays free for a DNS server of the container's own (dnsmasq, +/// Pi-hole, CoreDNS bind 0.0.0.0:53), while the container's lookups at +/// 127.0.0.11:53 still reach Kiri's. Replies are mapped back to port 53 by +/// conntrack. +pub fn redirect_embedded_dns(addr: [u8; 4], udp_port: u16, tcp_port: Option) -> io::Result<()> { let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; - nl.request(&mut embedded_dns_batch(addr, port)) + nl.request(&mut embedded_dns_batch(addr, udp_port, tcp_port)) } -fn embedded_dns_batch(addr: [u8; 4], port: u16) -> Vec { +fn embedded_dns_batch(addr: [u8; 4], udp_port: u16, tcp_port: Option) -> Vec { let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); begin.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); let mut table = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); @@ -957,10 +1252,15 @@ fn embedded_dns_batch(addr: [u8; 4], port: u16) -> Vec { // that took 15-30 ms of every container start. let mut flush = nft(NFT_MSG_DELRULE, NLM_F_ACK); flush.attr_str(1, EMBEDDED_DNS_TABLE).attr_str(2, "output"); - let rule = dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: true, host_ip: addr, host_port: 53, to_ip: addr, to_port: port }, None); + let udp_rule = dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: true, host_ip: addr, host_port: 53, to_ip: addr, to_port: udp_port }, None, None); + let mut out = vec![begin, table, chain, flush, udp_rule]; + if let Some(tp) = tcp_port { + out.push(dnat_rule_in(EMBEDDED_DNS_TABLE, "output", &Dnat { udp: false, host_ip: addr, host_port: 53, to_ip: addr, to_port: tp }, None, None)); + } let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); - vec![begin, table, chain, flush, rule, end] + out.push(end); + out } const NLM_F_DUMP: u16 = 0x300; @@ -1008,15 +1308,12 @@ fn parse_chain(p: &[u8]) -> Option { Some(c) } -/// How many rules of `chain` in `table` of `family` carry `needle` -/// somewhere in their encoding (an interface name, a comment). A chain -/// that is not there has none. -pub fn rules_with(family: u8, table: &str, chain: &str, needle: &[u8]) -> io::Result { +/// Dumps every rule in `chain` of `table` in `family` (`ENOENT` ignored). +fn dump_chain_rules(family: u8, table: &str, chain: &str, mut each: impl FnMut(&[u8])) -> io::Result<()> { const NFT_MSG_GETRULE: u16 = 7; let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; let mut get = nft_in(family, NFT_MSG_GETRULE, NLM_F_DUMP); get.attr_str(1, table).attr_str(2, chain); // NFTA_RULE_TABLE, NFTA_RULE_CHAIN: the kernel dumps only those - let mut n = 0; let r = nl.dump(&mut get, |p| { // Checked here too, for a kernel that dumps every rule. let mut ours = (false, false); @@ -1027,22 +1324,101 @@ pub fn rules_with(family: u8, table: &str, chain: &str, needle: &[u8]) -> io::Re _ => {} } } - if ours == (true, true) && p.windows(needle.len()).any(|w| w == needle) { - n += 1; + if ours == (true, true) { + each(p); } }); match r { - Err(e) if e.raw_os_error() == Some(libc::ENOENT) => Ok(0), - r => r.map(|()| n), + Err(e) if e.raw_os_error() == Some(libc::ENOENT) => Ok(()), + r => r, } } -/// A socket in nf_tables' multicast group (NFNLGRP_NFTABLES), readable -/// after any change to any table; `drain` empties it. -pub fn nftables_events() -> io::Result { - const NFNLGRP_NFTABLES: u32 = 7; +/// How many rules of `chain` in `table` of `family` carry `needle` +/// somewhere in their encoding (an interface name, a comment). A chain +/// that is not there has none. +pub fn rules_with(family: u8, table: &str, chain: &str, needle: &[u8]) -> io::Result { + let mut n = 0; + dump_chain_rules(family, table, chain, |p| { + if p.windows(needle.len()).any(|w| w == needle) { + n += 1; + } + })?; + Ok(n) +} + +/// Whether `p` (a `NFT_MSG_NEWRULE` netlink payload after its 16-byte header) +/// represents an unconditional `DROP` or `REJECT` rule in `iptables-nft` (for +/// example, a trailing `-A FORWARD -j DROP` or `-A FORWARD -j REJECT` when the +/// `FORWARD` policy itself is `ACCEPT`), ignoring any rule tagged with `"kiri"`. +fn is_unconditional_drop_rule(p: &[u8]) -> bool { + let mut exprs_data: Option<&[u8]> = None; + for (ty, data) in attrs(p.get(4..).unwrap_or_default()) { + match ty { + 4 => exprs_data = Some(data), + 7 if data.windows(BRIDGE_PREFIX.len()).any(|w| w == BRIDGE_PREFIX) => return false, + _ => {} + } + } + let Some(exprs) = exprs_data else { return false }; + let mut drops = false; + for (_, elem) in attrs(exprs) { + let mut name = None; + let mut data = &[][..]; + for (t, d) in attrs(elem) { + match t { + 1 => name = Some(nl_str(d)), + 2 => data = d, + _ => {} + } + } + match name.as_deref() { + Some("counter") => {} + Some("reject") => drops = true, + Some("immediate") => { + let dreg = attrs(data).find(|(t, _)| *t == 1).and_then(|(_, d)| be32(d)); + let code = attrs(data) + .find(|(t, _)| *t == 2) + .and_then(|(_, d)| attrs(d).find(|(t, _)| *t == 2)) + .and_then(|(_, d)| attrs(d).find(|(t, _)| *t == 1)) + .and_then(|(_, d)| be32(d)); + if dreg == Some(0) && code == Some(libc::NF_DROP as u32) { + drops = true; + } else { + return false; + } + } + Some("target") => { + let target = attrs(data).find(|(t, _)| *t == 1).map(|(_, d)| nl_str(d)); + if matches!(target.as_deref(), Some("DROP" | "REJECT")) { + drops = true; + } else { + return false; + } + } + _ => return false, + } + } + drops +} + +/// Whether `iptables-nft`'s `filter FORWARD` chain for `family` contains an +/// unconditional `DROP` or `REJECT` rule (such as a trailing `-j REJECT` when +/// the `FORWARD` policy itself is `ACCEPT`). +pub fn has_unconditional_forward_drop(family: u8) -> io::Result { + let mut found = false; + dump_chain_rules(family, "filter", "FORWARD", |p| { + if is_unconditional_drop_rule(p) { + found = true; + } + })?; + Ok(found) +} + +/// Opens a non-blocking, close-on-exec netlink multicast socket joined to `groups`. +fn netlink_events(protocol: libc::c_int, groups: u32) -> io::Result { // SAFETY: plain socket creation; owned immediately. - let fd = sys::check(unsafe { libc::socket(libc::AF_NETLINK, libc::SOCK_RAW | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, libc::NETLINK_NETFILTER) } as _, "netlink")?; + let fd = sys::check(unsafe { libc::socket(libc::AF_NETLINK, libc::SOCK_RAW | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, protocol) } as _, "netlink")?; // SAFETY: `fd` is a fresh descriptor that nothing else owns. let fd = unsafe { OwnedFd::from_raw_fd(fd as i32) }; // Bound (the kernel picks the port id) and in the group: an unbound @@ -1050,7 +1426,7 @@ pub fn nftables_events() -> io::Result { // SAFETY: a zeroed sockaddr_nl is valid; the fields set are plain integers. let mut addr: libc::sockaddr_nl = unsafe { std::mem::zeroed() }; addr.nl_family = libc::AF_NETLINK as libc::sa_family_t; - addr.nl_groups = 1 << (NFNLGRP_NFTABLES - 1); + addr.nl_groups = groups; // SAFETY: binding our socket to an address that outlives the call. sys::check( unsafe { libc::bind(fd.as_raw_fd(), (&addr as *const libc::sockaddr_nl).cast(), std::mem::size_of::() as libc::socklen_t) } as _, @@ -1059,6 +1435,19 @@ pub fn nftables_events() -> io::Result { Ok(fd) } +/// A socket in nf_tables' multicast group (NFNLGRP_NFTABLES), readable +/// after any change to any table; `drain` empties it. +pub fn nftables_events() -> io::Result { + const NFNLGRP_NFTABLES: u32 = 7; + netlink_events(libc::NETLINK_NETFILTER, 1 << (NFNLGRP_NFTABLES - 1)) +} + +/// A socket in RTNetlink's link and route multicast groups, readable when an +/// interface (such as a foreign bridge or VPN) or a default route appears or goes. +pub fn link_route_events() -> io::Result { + netlink_events(libc::NETLINK_ROUTE, (libc::RTMGRP_LINK | libc::RTMGRP_IPV4_ROUTE | libc::RTMGRP_IPV6_ROUTE) as u32) +} + /// Reads and drops everything waiting on a `nftables_events` socket. pub fn drain(fd: &OwnedFd) { let mut buf = [0u8; 8192]; @@ -1103,9 +1492,78 @@ pub fn remove_nat() -> io::Result<()> { /// Mac reaches over the NAT network, so they match only connections from /// the uplink's gateway `gateway` (the Mac itself): other VMs on the NAT /// network, or the LAN routed through the Mac, never reach a container. +#[cfg(test)] #[allow(clippy::too_many_arguments)] -pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, redirect: bool, dnat: &[Dnat], gateway: [u8; 4], bridges: &[String], local: Option<&[[u8; 4]]>) -> io::Result<()> { +pub fn install_nat_with_egress( + uplink_index: i32, + host_addr: [u8; 4], + host_port: u16, + redirect: bool, + dnat: &[Dnat], + gateway: [u8; 4], + bridges: &[String], + local: Option<&[[u8; 4]]>, + egress_port: u16, + egress_routes: &[([u8; 4], u8)], + egress_skip: &[([u8; 4], u8)], +) -> io::Result<()> { + install_nat_full(uplink_index, host_addr, host_port, redirect, dnat, gateway, bridges, local, egress_port, egress_routes, egress_skip, None, &[], true) +} + +#[allow(clippy::too_many_arguments)] +pub fn install_nat_full( + uplink_index: i32, + host_addr: [u8; 4], + host_port: u16, + redirect: bool, + dnat: &[Dnat], + gateway: [u8; 4], + bridges: &[String], + local: Option<&[[u8; 4]]>, + egress_port: u16, + egress_routes: &[([u8; 4], u8)], + egress_skip: &[([u8; 4], u8)], + wsl_host: Option<[u8; 4]>, + bridge_subnets: &[([u8; 4], u8)], + allow_prerouting_dnat: bool, +) -> io::Result<()> { let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; + let mut msgs = build_nat_batch( + uplink_index, + host_addr, + host_port, + redirect, + dnat, + gateway, + bridges, + local, + egress_port, + egress_routes, + egress_skip, + wsl_host, + bridge_subnets, + allow_prerouting_dnat, + ); + nl.request(&mut msgs) +} + +#[allow(clippy::too_many_arguments)] +fn build_nat_batch( + uplink_index: i32, + host_addr: [u8; 4], + host_port: u16, + redirect: bool, + dnat: &[Dnat], + gateway: [u8; 4], + bridges: &[String], + local: Option<&[[u8; 4]]>, + egress_port: u16, + egress_routes: &[([u8; 4], u8)], + egress_skip: &[([u8; 4], u8)], + wsl_host: Option<[u8; 4]>, + bridge_subnets: &[([u8; 4], u8)], + allow_prerouting_dnat: bool, +) -> Vec { // The table is replaced, not appended to (on a Linux host it outlives // the agent and changes with every published port), in one batch: // see clear_table. @@ -1116,40 +1574,74 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r let mut table = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); table.attr_str(1, "kiri"); // NFTA_TABLE_NAME - let mut chain = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); - chain.attr_str(1, "kiri").attr_str(3, "postrouting"); // NFTA_CHAIN_TABLE, NFTA_CHAIN_NAME - chain.nest(4).attr_be32(1, 4).attr_be32(2, 100).end(); // NFTA_CHAIN_HOOK: hooknum POSTROUTING, priority - chain.attr_be32(5, 1).attr_str(7, "nat"); // NFTA_CHAIN_POLICY accept, NFTA_CHAIN_TYPE - - let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); // NLM_F_APPEND - rule.attr_str(1, "kiri").attr_str(2, "postrouting"); // NFTA_RULE_TABLE, NFTA_RULE_CHAIN - rule.nest(4); // NFTA_RULE_EXPRESSIONS - // meta load oif => reg 1 (NFTA_META_DREG, NFTA_META_KEY = NFT_META_OIF, which is 5) - rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 5).end().end(); - // cmp eq reg 1, uplink index - rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0); - rule.nest(3).attr(1, &(uplink_index as u32).to_ne_bytes()).end().end().end(); - // masquerade - rule.nest(1).attr_str(1, "masq").end(); - rule.end(); + let has_uplink = uplink_index > 0; + let mut msgs = vec![begin, add, delete, table]; + if !redirect { + // Linux host: masquerade each Kiri bridge subnet regardless of which + // non-Kiri, non-loopback interface handles the route (Tailscale/VPNs, + // policy routing tables, or secondary NICs), matching `masq6_rule`. + let mut chain = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + chain.attr_str(1, "kiri").attr_str(3, "postrouting"); + chain.nest(4).attr_be32(1, 4).attr_be32(2, 100).end(); + chain.attr_be32(5, 1).attr_str(7, "nat"); + msgs.push(chain); + msgs.extend(bridge_subnets.iter().map(|&(s, p)| masq4_rule(s, p))); + } else if has_uplink { + let mut chain = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + chain.attr_str(1, "kiri").attr_str(3, "postrouting"); // NFTA_CHAIN_TABLE, NFTA_CHAIN_NAME + chain.nest(4).attr_be32(1, 4).attr_be32(2, 100).end(); // NFTA_CHAIN_HOOK: hooknum POSTROUTING, priority + chain.attr_be32(5, 1).attr_str(7, "nat"); // NFTA_CHAIN_POLICY accept, NFTA_CHAIN_TYPE + + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); // NLM_F_APPEND + rule.attr_str(1, "kiri").attr_str(2, "postrouting"); // NFTA_RULE_TABLE, NFTA_RULE_CHAIN + rule.nest(4); // NFTA_RULE_EXPRESSIONS + // meta load oif => reg 1 (NFTA_META_DREG, NFTA_META_KEY = NFT_META_OIF, which is 5) + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 5).end().end(); + // cmp eq reg 1, uplink index + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0); + rule.nest(3).attr(1, &(uplink_index as u32).to_ne_bytes()).end().end().end(); + // masquerade + rule.nest(1).attr_str(1, "masq").end(); + rule.end(); + msgs.push(chain); + msgs.push(rule); + } let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + let have_egress = egress_port != 0 && !egress_routes.is_empty(); if !redirect { // A Linux host: no host.docker.internal redirect, but its published - // ports are DNATed here (prerouting for the LAN, output for the host - // itself), the whole table rebuilt on every change, atomically. - let mut msgs = vec![begin, add, delete, table, chain, rule]; - msgs.extend(forward_filter(bridges, forward_guard(libc::NFPROTO_IPV4 as u8).as_deref())); + // ports are DNATed here (prerouting for the LAN when kernel forwarding + // allows it, output for the host itself), rebuilt atomically. + msgs.extend(forward_filter_v4(bridges, &foreign_bridges(), false)); msgs.extend(localnet_guard()); + if have_egress { + msgs.push(host_relay_guard(egress_port)); + } msgs.push(nat_chain("prerouting", 0, -100)); msgs.push(nat_chain("output", 3, -100)); + if let Some(wsl_addr) = wsl_host { + // UDP 53 sent to 192.168.65.254 from container bridges goes to + // the embedded DNS on the receiving bridge's gateway. + msgs.push(dns_redirect_rule(wsl_addr)); + } for d in dnat { - msgs.extend(dnat_rules("prerouting", d, local)); - msgs.extend(dnat_rules("output", d, local)); + if allow_prerouting_dnat { + msgs.extend(dnat_rules("prerouting", d, local, wsl_host)); + } + msgs.extend(dnat_rules("output", d, local, wsl_host)); + } + if have_egress { + for &(subnet, prefix) in egress_skip { + msgs.push(accept_prefix_rule("prerouting", subnet, prefix, true)); + } + for &(dst, prefix) in egress_routes { + msgs.push(redirect_prefix_rule("prerouting", dst, prefix, egress_port, true)); + } } msgs.push(end); - return nl.request(&mut msgs); + return msgs; } let pre = nat_chain("prerouting", 0, -100); // NF_INET_PRE_ROUTING let out = nat_chain("output", 3, -100); // NF_INET_LOCAL_OUT @@ -1157,18 +1649,87 @@ pub fn install_nat_from(uplink_index: i32, host_addr: [u8; 4], host_port: u16, r let pre_rule = redirect_rule("prerouting", host_addr, host_port, true); // The host's own connections (and `--network host` containers). let out_rule = redirect_rule("output", host_addr, host_port, false); - let mut msgs = vec![begin, add, delete, table, chain, rule, pre, out, dns_redirect_rule(host_addr), pre_rule, out_rule]; - msgs.extend(forward_filter(bridges, forward_guard(libc::NFPROTO_IPV4 as u8).as_deref())); + msgs.extend([pre, out, dns_redirect_rule(host_addr), pre_rule, out_rule]); + msgs.extend(forward_filter_v4(bridges, &foreign_bridges(), !has_uplink)); msgs.extend(localnet_guard()); msgs.push(host_relay_guard(host_port)); + if have_egress { + msgs.push(host_relay_guard(egress_port)); + } for d in dnat.iter().filter(|d| !d.udp) { - msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)))); + if d.host_ip == LOOPBACK { + // A port the Mac has on its loopback, for the VM's own + // connections (`--network host` containers) to 127.0.0.1. + // Skip `host_port` itself: redirecting to the same port does not + // mark `ct status dnat`, so `host_relay_guard` and `redirected_from` + // reject direct connections to the relay listener. + if d.host_port != host_port { + msgs.push(loopback_published_rule(d.host_port, host_port)); + } + } else if has_uplink { + msgs.push(dnat_rule_from("prerouting", d, Some((uplink_index, gateway)), None)); + } + } + if have_egress { + for &(subnet, prefix) in egress_skip { + msgs.push(accept_prefix_rule("prerouting", subnet, prefix, true)); + msgs.push(accept_prefix_rule("output", subnet, prefix, false)); + } + for &(dst, prefix) in egress_routes { + msgs.push(redirect_prefix_rule("prerouting", dst, prefix, egress_port, true)); + msgs.push(redirect_prefix_rule("output", dst, prefix, egress_port, false)); + } } - if dnat.iter().any(|d| !d.udp) { + if has_uplink && dnat.iter().any(|d| !d.udp && d.host_ip != LOOPBACK) { msgs.push(published_masq_rule(uplink_index, gateway)); } msgs.push(end); - nl.request(&mut msgs) + msgs +} + +/// A published port's `host_ip` in the VM that means "the Mac's loopback": +/// the VM's own connections to 127.0.0.1 or ::1 on it reach the Mac's 127.0.0.1. +pub const LOOPBACK: [u8; 4] = [127, 0, 0, 1]; +pub const LOOPBACK6: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]; + +/// `ip daddr 127.0.0.1 tcp dport redirect to :`, in output: +/// in the VM, a connection the VM itself makes (a `--network host` +/// container) to a port published on the Mac's loopback goes to the host +/// relay, which dials the Mac's 127.0.0.1 on that port, where Kiri's own +/// listener forwards it to the container. As on Docker, where the +/// published port is bound in the host's own network namespace. The +/// redirect stays on the loopback, so `route_localnet` stays off. +fn loopback_published_rule(port: u16, relay: u16) -> Msg { + loopback_published_rule_in(libc::NFPROTO_IPV4 as u8, 16, &LOOPBACK, port, relay) +} + +/// `ip6 daddr ::1 tcp dport redirect to :`, in output of +/// `table ip6 kiri`: the IPv6 counterpart of `loopback_published_rule`, so +/// clients in a `--network host` container that resolve `localhost` to `::1` +/// first (musl's `getaddrinfo`) and do not fall back to `127.0.0.1` reach +/// the Mac's loopback-published port too. +fn loopback_published_rule6(port: u16, relay: u16) -> Msg { + loopback_published_rule_in(libc::NFPROTO_IPV6 as u8, 24, &LOOPBACK6, port, relay) +} + +fn loopback_published_rule_in(family: u8, daddr_offset: u32, loopback: &[u8], port: u16, relay: u16) -> Msg { + let mut rule = nft_in(family, NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | 0x800); + rule.attr_str(1, "kiri").attr_str(2, "output"); + rule.nest(4); + // meta l4proto => reg 1; cmp eq tcp + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + // payload daddr => reg 1; cmp eq loopback (127.0.0.1 or ::1) + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, daddr_offset).attr_be32(4, loopback.len() as u32).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, loopback).end().end().end(); + // payload transport header + 2 (dport) => reg 1; cmp eq port + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 2).attr_be32(4, 2).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &port.to_be_bytes()).end().end().end(); + // immediate reg 1 = relay; redir to it + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 1).nest(2).attr(1, &relay.to_be_bytes()).end().end().end(); + rule.nest(1).attr_str(1, "redir").nest(2).attr_be32(1, 1).end().end(); + rule.end(); + rule } #[cfg(test)] @@ -1195,18 +1756,33 @@ mod tests { u32::from_be_bytes(d.try_into().unwrap()) } + /// `enable_icc=false` (#213): the host-side veth, found by name, gets + /// the bridge's port attribute `isolated` set, as + /// `ip link set dev kv1 type bridge_slave isolated on` sends it. + #[test] + fn isolate_port_marks_the_veth_an_isolated_bridge_port() { + let m = isolate_port_msg("kv1"); + assert_eq!(u16::from_ne_bytes([m.buf[4], m.buf[5]]), RTM_NEWLINK); + // nlmsghdr (16) + ifinfomsg (16), then the attributes. + let top = attrs(&m.buf[32..]); + assert_eq!(get(&top, IFLA_IFNAME), b"kv1\0"); + let info = attrs(get(&top, IFLA_LINKINFO)); + assert_eq!(get(&info, IFLA_INFO_SLAVE_KIND), b"bridge\0"); + assert_eq!(attrs(get(&info, IFLA_INFO_SLAVE_DATA)), vec![(IFLA_BRPORT_ISOLATED, &[1u8][..])]); + } + /// The embedded DNS's redirect in a container's namespace: its own /// table (an engine inside the container replaces `kiri`), one output - /// nat chain emptied first, one rule that sends UDP for 127.0.0.11:53 to - /// the server's port. + /// nat chain emptied first, and UDP/TCP rules that send 127.0.0.11:53 to + /// the server's ports. #[test] fn the_embedded_dns_redirect_is_one_rule_in_a_table_of_its_own() { - let mut msgs = embedded_dns_batch([127, 0, 0, 11], 40123); + let mut msgs = embedded_dns_batch([127, 0, 0, 11], 40123, Some(40124)); let types: Vec = msgs.iter().map(|m| u16::from_ne_bytes([m.buf[4], m.buf[5]])).collect(); let t = |m: u16| (NFNL_SUBSYS_NFTABLES << 8) | m; // No DELTABLE: unregistering a hook waits for an RCU grace period. - assert_eq!(types, [NFNL_MSG_BATCH_BEGIN, t(NFT_MSG_NEWTABLE), t(NFT_MSG_NEWCHAIN), t(NFT_MSG_DELRULE), t(NFT_MSG_NEWRULE), NFNL_MSG_BATCH_END]); - for m in &msgs[1..5] { + assert_eq!(types, [NFNL_MSG_BATCH_BEGIN, t(NFT_MSG_NEWTABLE), t(NFT_MSG_NEWCHAIN), t(NFT_MSG_DELRULE), t(NFT_MSG_NEWRULE), t(NFT_MSG_NEWRULE), NFNL_MSG_BATCH_END]); + for m in &msgs[1..6] { assert_eq!(get(&attrs(&m.buf[20..]), 1), b"kiri_dns\0"); } assert_eq!(get(&attrs(&msgs[3].buf[20..]), 2), b"output\0", "the chain's rules, no handle: all of them"); @@ -1214,9 +1790,13 @@ mod tests { let hook = attrs(get(&chain, 4)); assert_eq!((be32(get(&hook, 1)), be32(get(&hook, 2)) as i32), (3, -100), "the output hook, at nat priority"); assert_eq!(get(&chain, 7), b"nat\0"); - let rule = msgs[4].finish(1).to_vec(); - let has = |needle: &[u8]| rule.windows(needle.len()).any(|w| w == needle); - assert!(has(&[127, 0, 0, 11]) && has(&53u16.to_be_bytes()) && has(&40123u16.to_be_bytes()) && has(b"nat\0")); + let udp_rule = msgs[4].finish(1).to_vec(); + let tcp_rule = msgs[5].finish(1).to_vec(); + let has = |rule: &[u8], needle: &[u8]| rule.windows(needle.len()).any(|w| w == needle); + assert!(has(&udp_rule, &[127, 0, 0, 11]) && has(&udp_rule, &53u16.to_be_bytes()) && has(&udp_rule, &40123u16.to_be_bytes()) && has(&udp_rule, b"nat\0")); + assert!(has(&tcp_rule, &[127, 0, 0, 11]) && has(&tcp_rule, &53u16.to_be_bytes()) && has(&tcp_rule, &40124u16.to_be_bytes()) && has(&tcp_rule, b"nat\0")); + let udp_only = embedded_dns_batch([127, 0, 0, 11], 40123, None); + assert_eq!(udp_only.len(), 6, "UDP redirect proceeds alone when TCP bind fails"); } /// The table is replaced with messages every kernel since 3.13 knows: @@ -1280,23 +1860,21 @@ mod tests { #[test] fn forward_keeps_networks_apart() { - let msgs = forward_filter(&["kiri1".to_owned(), "kiri22".to_owned()], None); - assert_eq!(msgs.len(), 7); - let rules = &msgs[1..]; - // Nothing from a bridge is accepted on the interface name alone: that - // let any network reach any other. - for r in rules { - let e = exprs(r); - let iifname_only = names(r) == ["meta", "cmp", "immediate"] && be32(get(&e[0].1, 2)) == 6; - assert!(!iifname_only, "a bridge-to-any-bridge accept"); - } - // One rule per bridge: in by it and out by it, the whole name. No - // fib expression anywhere (WSL2's kernel has no nft_fib_ipv6). - for (same, name) in rules[3..5].iter().zip([&b"kiri1"[..], b"kiri22"]) { + let msgs = forward_filter(&["kiri1".to_owned(), "kiri22".to_owned()], &[]); + assert_eq!(msgs.len(), 9); + // Rule 1: IPv4 link-local / cloud IMDS (169.254.0.0/16) is blocked ahead of everything else. + let imds = &msgs[1]; + assert_eq!(names(imds), ["meta", "cmp", "payload", "bitwise", "cmp", "immediate"]); + let ie = exprs(imds); + assert_eq!((be32(get(&ie[0].1, 2)), get(&attrs(get(&ie[1].1, 3)), 1)), (6, &b"kiri"[..])); + assert_eq!(get(&attrs(get(&ie[3].1, 4)), 1), &[255, 255, 0, 0]); + assert_eq!(get(&attrs(get(&ie[4].1, 3)), 1), &[169, 254, 0, 0]); + assert_eq!(verdict(imds), libc::NF_DROP as u32); + // Same-bridge fast-path rules run BEFORE SYN MSS clamping so L2 bridge traffic skips it (#509). + for (same, name) in msgs[2..4].iter().zip([&b"kiri1"[..], b"kiri22"]) { assert_eq!(names(same), ["meta", "cmp", "meta", "cmp", "immediate"]); let e = exprs(same); - let mut full = [0u8; 16]; - full[..name.len()].copy_from_slice(name); + let full = ifname_full(std::str::from_utf8(name).unwrap()); assert_eq!(be32(get(&e[0].1, 2)), 6, "meta iifname"); assert_eq!(be32(get(&e[2].1, 2)), 7, "meta oifname"); for c in [&e[1].1, &e[3].1] { @@ -1305,40 +1883,62 @@ mod tests { } assert_eq!(verdict(same), libc::NF_ACCEPT as u32); } - // and everything else headed into a bridge is dropped - assert_eq!(names(&rules[5]), ["immediate"]); - assert_eq!(verdict(&rules[5]), libc::NF_DROP as u32); - // ahead of it: not into a bridge, replies, published ports + assert_eq!(names(&msgs[4]), ["meta", "cmp", "payload", "bitwise", "cmp", "rt", "byteorder", "exthdr"], "SYN MSS clamping to route MTU"); + let rules = &msgs[5..]; + // Nothing from a bridge is accepted on the interface name alone: that + // let any network reach any other. + for r in &msgs[2..] { + let e = exprs(r); + let iifname_only = names(r) == ["meta", "cmp", "immediate"] && be32(get(&e[0].1, 2)) == 6; + assert!(!iifname_only, "a bridge-to-any-bridge accept"); + } + // Not into a bridge, replies, published ports, and everything else dropped. assert_eq!(verdict(&rules[0]), libc::NF_ACCEPT as u32); assert_eq!(be32(get(&exprs(&rules[0])[0].1, 2)), 7, "meta oifname"); assert_eq!(be32(get(&exprs(&rules[1])[0].1, 2)), 0, "ct state"); assert_eq!(be32(get(&exprs(&rules[2])[0].1, 2)), 2, "ct status"); + assert_eq!(names(&rules[3]), ["immediate"]); + assert_eq!(verdict(&rules[3]), libc::NF_DROP as u32); + } + + #[test] + fn egress_prefix_redirect_and_accept_rules_match_cidr() { + let r24 = redirect_prefix_rule("prerouting", [10, 0, 5, 10], 24, 1038, true); + assert_eq!(names(&r24), ["meta", "cmp", "meta", "cmp", "payload", "bitwise", "cmp", "immediate", "redir"]); + let e = exprs(&r24); + assert_eq!(get(&attrs(get(&e[5].1, 4)), 1), &[255, 255, 255, 0]); + assert_eq!(get(&attrs(get(&e[6].1, 3)), 1), &[10, 0, 5, 0]); + + let r0 = redirect_prefix_rule("output", [0, 0, 0, 0], 0, 1038, false); + assert_eq!(names(&r0), ["meta", "cmp", "immediate", "redir"], "0.0.0.0/0 needs no payload daddr match"); + + let skip = accept_prefix_rule("prerouting", [172, 17, 0, 1], 16, true); + assert_eq!(names(&skip), ["meta", "cmp", "meta", "cmp", "payload", "bitwise", "cmp", "immediate"]); + assert_eq!(verdict(&skip), libc::NF_ACCEPT as u32); } #[test] - fn with_firewalld_new_connections_leave_only_through_the_uplink() { + fn foreign_bridges_are_isolated_while_non_bridge_uplinks_pass() { let bridges = ["kiri0".to_owned()]; - let plain = forward_filter(&bridges, None); - let guarded = forward_filter(&bridges, Some("eth0")); - // One rule more, first: the chain is msgs[0]. - assert_eq!(guarded.len(), plain.len() + 1); - let g = &guarded[1]; - assert_eq!(names(g), ["meta", "cmp", "meta", "cmp", "meta", "cmp", "ct", "bitwise", "cmp", "ct", "bitwise", "cmp", "immediate"]); - let e = exprs(g); - // iifname "kiri*", oifname != "kiri*", oifname != "eth0" - assert_eq!(be32(get(&e[0].1, 2)), 6); - assert_eq!((be32(get(&e[1].1, 2)), get(&attrs(get(&e[1].1, 3)), 1)), (0, &b"kiri"[..])); - assert_eq!(be32(get(&e[2].1, 2)), 7); - assert_eq!((be32(get(&e[3].1, 2)), get(&attrs(get(&e[3].1, 3)), 1)), (1, &b"kiri"[..])); - let mut eth0 = [0u8; 16]; - eth0[..4].copy_from_slice(b"eth0"); - assert_eq!((be32(get(&e[5].1, 2)), get(&attrs(get(&e[5].1, 3)), 1)), (1, ð0[..])); - // not a reply, not a published port - assert_eq!(be32(get(&e[6].1, 2)), 0, "ct state"); - assert_eq!(be32(get(&e[9].1, 2)), 2, "ct status"); - assert_eq!(verdict(g), libc::NF_DROP as u32); - // The rest is as without firewalld. - assert_eq!(guarded[2..].iter().map(|m| m.buf.len()).collect::>(), plain[1..].iter().map(|m| m.buf.len()).collect::>()); + let foreign = ["docker0".to_owned(), "br-abc".to_owned()]; + for family in [libc::NFPROTO_IPV4 as u8, libc::NFPROTO_IPV6 as u8] { + let plain = forward_filter_in(family, &bridges, &[], false); + let guarded = forward_filter_in(family, &bridges, &foreign, false); + assert_eq!(guarded.len(), plain.len() + foreign.len()); + let start = if family == libc::NFPROTO_IPV4 as u8 { 3 } else { 2 }; + for (g, name) in guarded[start..start + foreign.len()].iter().zip(&foreign) { + assert_eq!(names(g), ["meta", "cmp", "meta", "cmp", "ct", "bitwise", "cmp", "ct", "bitwise", "cmp", "immediate"]); + let e = exprs(g); + assert_eq!(be32(get(&e[0].1, 2)), 6, "iifname"); + assert_eq!((be32(get(&e[1].1, 2)), get(&attrs(get(&e[1].1, 3)), 1)), (0, &b"kiri"[..])); + assert_eq!(be32(get(&e[2].1, 2)), 7, "oifname"); + let fb = ifname_full(name); + assert_eq!((be32(get(&e[3].1, 2)), get(&attrs(get(&e[3].1, 3)), 1)), (0, &fb[..])); + assert_eq!(be32(get(&e[4].1, 2)), 0, "ct state"); + assert_eq!(be32(get(&e[7].1, 2)), 2, "ct status"); + assert_eq!(verdict(g), libc::NF_DROP as u32); + } + } } #[test] @@ -1358,26 +1958,251 @@ mod tests { let odd = masq6_rule(subnet, 61); let e = exprs(&odd); assert_eq!(get(&attrs(get(&e[1].1, 4)), 1)[..8], [255, 255, 255, 255, 255, 255, 255, 0xf8]); - // the IPv6 forward filter is the IPv4 one in another family + // the IPv6 forward filter is the IPv4 one without the IPv4-only IMDS rule. let bridges = ["kiri3".to_owned()]; - let f = forward_filter_in(libc::NFPROTO_IPV6 as u8, &bridges, None); - assert_eq!(f.len(), forward_filter(&bridges, None).len()); + let f = forward_filter_in(libc::NFPROTO_IPV6 as u8, &bridges, &[], false); + assert_eq!(f.len() + 1, forward_filter(&bridges, &[]).len()); assert!(f[1..].iter().all(|m| !names(m).contains(&"fib".to_owned())), "no nft_fib_ipv6 needed"); assert!(f.iter().all(|m| m.buf[16] == libc::NFPROTO_IPV6 as u8)); } + /// In the VM, a port published on the Mac's loopback: the VM's own TCP + /// connections to 127.0.0.1 or ::1 on it, in output, go to the host relay. #[test] - fn host_relay_takes_only_redirected_connections() { - let r = host_relay_guard(1026); - assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "ct", "bitwise", "cmp", "immediate"]); + fn a_loopback_published_port_redirects_the_vms_own_connections_to_the_relay() { + let r = loopback_published_rule(5999, 1026); + assert_eq!(r.buf[16], libc::NFPROTO_IPV4 as u8); + let top = attrs(&r.buf[20..]); + assert_eq!(get(&top, 2), b"output\0", "the VM's own connections only, not the bridges'"); + assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "payload", "cmp", "immediate", "redir"]); let e = exprs(&r); assert_eq!(get(&attrs(get(&e[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); + // network header + 16, 4 bytes: daddr, which must be 127.0.0.1 + assert_eq!((be32(get(&e[2].1, 2)), be32(get(&e[2].1, 3)), be32(get(&e[2].1, 4))), (1, 16, 4)); + assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &LOOPBACK); // transport header + 2, 2 bytes: dport - assert_eq!((be32(get(&e[2].1, 2)), be32(get(&e[2].1, 3)), be32(get(&e[2].1, 4))), (2, 2, 2)); - assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &1026u16.to_be_bytes()); - assert_eq!(be32(get(&e[4].1, 2)), 2, "ct status"); - assert_eq!(get(&attrs(get(&e[5].1, 4)), 1), &CT_STATUS_DNAT.to_ne_bytes()); - assert_eq!(be32(get(&e[6].1, 2)), 0, "== 0"); - assert_eq!(verdict(&r), libc::NF_DROP as u32); + assert_eq!((be32(get(&e[4].1, 2)), be32(get(&e[4].1, 3)), be32(get(&e[4].1, 4))), (2, 2, 2)); + assert_eq!(get(&attrs(get(&e[5].1, 3)), 1), &5999u16.to_be_bytes()); + assert_eq!(get(&attrs(get(&e[6].1, 2)), 1), &1026u16.to_be_bytes(), "redirected to the relay's port"); + + let r6 = loopback_published_rule6(5999, 1026); + assert_eq!(r6.buf[16], libc::NFPROTO_IPV6 as u8); + let top6 = attrs(&r6.buf[20..]); + assert_eq!(get(&top6, 2), b"output\0"); + assert_eq!(names(&r6), ["meta", "cmp", "payload", "cmp", "payload", "cmp", "immediate", "redir"]); + let e6 = exprs(&r6); + assert_eq!(get(&attrs(get(&e6[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); + // network header + 24, 16 bytes: ip6 daddr, which must be ::1 + assert_eq!((be32(get(&e6[2].1, 2)), be32(get(&e6[2].1, 3)), be32(get(&e6[2].1, 4))), (1, 24, 16)); + assert_eq!(get(&attrs(get(&e6[3].1, 3)), 1), &LOOPBACK6); + assert_eq!((be32(get(&e6[4].1, 2)), be32(get(&e6[4].1, 3)), be32(get(&e6[4].1, 4))), (2, 2, 2)); + assert_eq!(get(&attrs(get(&e6[5].1, 3)), 1), &5999u16.to_be_bytes()); + assert_eq!(get(&attrs(get(&e6[6].1, 2)), 1), &1026u16.to_be_bytes()); + } + + #[test] + fn host_relay_takes_only_redirected_connections() { + for (r, family) in [(host_relay_guard(1026), libc::NFPROTO_IPV4 as u8), (host_relay_guard6(1026), libc::NFPROTO_IPV6 as u8)] { + assert_eq!(r.buf[16], family); + let top = attrs(&r.buf[20..]); + assert_eq!(get(&top, 2), b"input\0", "guards every incoming interface, loopback included"); + assert_eq!(names(&r), ["meta", "cmp", "payload", "cmp", "ct", "bitwise", "cmp", "immediate"]); + let e = exprs(&r); + assert_eq!(get(&attrs(get(&e[1].1, 3)), 1), &[libc::IPPROTO_TCP as u8]); + // transport header + 2, 2 bytes: dport + assert_eq!((be32(get(&e[2].1, 2)), be32(get(&e[2].1, 3)), be32(get(&e[2].1, 4))), (2, 2, 2)); + assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &1026u16.to_be_bytes()); + assert_eq!(be32(get(&e[4].1, 2)), 2, "ct status"); + assert_eq!(get(&attrs(get(&e[5].1, 4)), 1), &CT_STATUS_DNAT.to_ne_bytes()); + assert_eq!(be32(get(&e[6].1, 2)), 0, "== 0"); + assert_eq!(verdict(&r), libc::NF_DROP as u32); + } + } + + #[test] + fn published_dnat_excludes_wsl_host_gateway_when_set() { + let d = Dnat { udp: false, host_ip: [0; 4], host_port: 8080, to_ip: [172, 17, 0, 2], to_port: 80 }; + let plain = dnat_rule("prerouting", &d, None); + let wsl = dnat_rule("prerouting", &d, Some([192, 168, 65, 254])); + assert_eq!(names(&plain), ["fib", "cmp", "payload", "bitwise", "cmp", "meta", "cmp", "payload", "cmp", "immediate", "immediate", "nat"]); + assert_eq!(names(&wsl), ["fib", "cmp", "payload", "cmp", "bitwise", "cmp", "meta", "cmp", "payload", "cmp", "immediate", "immediate", "nat"]); + let e = exprs(&wsl); + assert_eq!(be32(get(&e[3].1, 2)), 1, "cmp neq"); + assert_eq!(get(&attrs(get(&e[3].1, 3)), 1), &[192, 168, 65, 254]); + } + + #[test] + fn device_default_route_and_no_uplink_nat_batch() { + // Fallback default route on lo (`default dev lo scope link src 127.0.0.1`). + let m = device_default_route_msg(1, Some(LOOPBACK)); + assert_eq!(u16::from_ne_bytes([m.buf[4], m.buf[5]]), RTM_NEWROUTE); + assert_eq!(m.buf[16], libc::AF_INET as u8); + assert_eq!(m.buf[17], 0, "dst_len 0 (default route)"); + assert_eq!(m.buf[20], libc::RT_TABLE_MAIN); + assert_eq!(m.buf[22], libc::RT_SCOPE_LINK); + assert_eq!(m.buf[23], libc::RTN_UNICAST); + let a = attrs(&m.buf[28..]); // nlmsghdr (16) + rtmsg (12) + assert_eq!(get(&a, RTA_OIF), &1u32.to_ne_bytes()); + assert_eq!(get(&a, RTA_PREFSRC), &LOOPBACK); + + // VM NAT table with uplink_index == 0 (no eth0): no postrouting chain/masq, + // forward drops oifname "lo", egress 0.0.0.0/0 redirects in prerouting+output, + // loopback published port rule still installed in output. + let lb = Dnat { udp: false, host_ip: LOOPBACK, host_port: 8080, to_ip: [172, 17, 0, 2], to_port: 80 }; + let batch = build_nat_batch( + 0, + [198, 19, 248, 254], + 1026, + true, + &[lb], + [0; 4], + &["kiri0".to_owned()], + None, + 1038, + &[([0, 0, 0, 0], 0)], + &[([127, 0, 0, 0], 8)], + None, + &[], + true, + ); + let msg_ty = |m: &Msg| u16::from_ne_bytes([m.buf[4], m.buf[5]]); + let newchain = (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWCHAIN; + let newrule = (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWRULE; + let chains: Vec<&[u8]> = batch.iter().filter(|m| msg_ty(m) == newchain).map(|m| get(&attrs(&m.buf[20..]), 3)).collect(); + assert!(!chains.contains(&&b"postrouting\0"[..]), "no postrouting chain when uplink_index == 0"); + assert!(chains.contains(&&b"prerouting\0"[..]) && chains.contains(&&b"output\0"[..]) && chains.contains(&&b"forward\0"[..]) && chains.contains(&&b"input\0"[..])); + + let rules: Vec<&Msg> = batch.iter().filter(|m| msg_ty(m) == newrule).collect(); + assert!(rules.iter().all(|r| !names(r).contains(&"masq".to_owned())), "no masquerade rule without eth0"); + + let mut lo_full = [0u8; 16]; + lo_full[..2].copy_from_slice(b"lo"); + let has_lo_drop = rules.iter().any(|r| { + get(&attrs(&r.buf[20..]), 2) == b"forward\0" + && names(r) == ["meta", "cmp", "immediate"] + && be32(get(&exprs(r)[0].1, 2)) == 7 + && get(&attrs(get(&exprs(r)[1].1, 3)), 1) == &lo_full + && verdict(r) == libc::NF_DROP as u32 + }); + assert!(has_lo_drop, "forward chain must drop packets routed out lo when uplink_index == 0"); + + let has_egress_out = rules.iter().any(|r| { + get(&attrs(&r.buf[20..]), 2) == b"output\0" + && names(r) == ["meta", "cmp", "immediate", "redir"] + && get(&attrs(get(&exprs(r)[2].1, 2)), 1) == &1038u16.to_be_bytes() + }); + assert!(has_egress_out, "output chain must redirect 0.0.0.0/0 TCP to egress port 1038"); + + let has_lb_rule = rules.iter().any(|r| { + get(&attrs(&r.buf[20..]), 2) == b"output\0" + && names(r) == ["meta", "cmp", "payload", "cmp", "payload", "cmp", "immediate", "redir"] + && get(&attrs(get(&exprs(r)[5].1, 3)), 1) == &8080u16.to_be_bytes() + }); + assert!(has_lb_rule, "loopback published port rule must still be installed without eth0"); + } + + #[test] + fn linux_host_masq_uses_bridge_subnets_and_skips_prerouting_when_forwarding_blocked() { + let host_addr = crate::linux::net::HOST_ADDR; + let d = Dnat { udp: false, host_ip: [0; 4], host_port: 8080, to_ip: [172, 17, 0, 2], to_port: 80 }; + let open = build_nat_batch(0, host_addr, 1026, false, &[d], [0; 4], &["kiri0".to_owned()], None, 0, &[], &[], None, &[([172, 17, 0, 0], 16)], true); + let blocked = build_nat_batch(0, host_addr, 1026, false, &[d], [0; 4], &["kiri0".to_owned()], None, 0, &[], &[], None, &[([172, 17, 0, 0], 16)], false); + let msg_ty = |m: &Msg| u16::from_ne_bytes([m.buf[4], m.buf[5]]); + let newrule = (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWRULE; + let chain_of = |r: &Msg| nl_str(get(&attrs(&r.buf[20..]), 2)); + + // Even with uplink_index == 0 (no main-table default route at boot), postrouting masquerades 172.17.0.0/16. + let masqs: Vec<&Msg> = open.iter().filter(|m| msg_ty(m) == newrule && chain_of(m) == "postrouting").collect(); + assert_eq!(masqs.len(), 1); + assert_eq!(names(masqs[0]), ["payload", "bitwise", "cmp", "meta", "cmp", "meta", "cmp", "masq"]); + let e = exprs(masqs[0]); + assert_eq!((be32(get(&e[0].1, 2)), be32(get(&e[0].1, 3)), be32(get(&e[0].1, 4))), (1, 12, 4)); + assert_eq!(get(&attrs(get(&e[1].1, 4)), 1), &[255, 255, 0, 0]); + assert_eq!(get(&attrs(get(&e[2].1, 3)), 1), &[172, 17, 0, 0]); + assert_eq!((be32(get(&e[3].1, 2)), be32(get(&e[4].1, 2)), get(&attrs(get(&e[4].1, 3)), 1)), (7, 1, &b"kiri"[..])); + let lo = ifname_full("lo"); + assert_eq!((be32(get(&e[5].1, 2)), be32(get(&e[6].1, 2)), get(&attrs(get(&e[6].1, 3)), 1)), (7, 1, &lo[..])); + + // When forwarding is open, prerouting and output both carry DNAT; when blocked, prerouting is skipped. + assert!(open.iter().any(|m| msg_ty(m) == newrule && chain_of(m) == "prerouting" && names(m).contains(&"nat".to_owned()))); + assert!(!blocked.iter().any(|m| msg_ty(m) == newrule && chain_of(m) == "prerouting" && names(m).contains(&"nat".to_owned()))); + assert!(blocked.iter().any(|m| msg_ty(m) == newrule && chain_of(m) == "output" && names(m).contains(&"nat".to_owned()))); + + // input chain blocks both 127.0.0.0/8 (CVE-2020-8558) and 169.254.0.0/16 (IMDS). + let inputs: Vec<&Msg> = open.iter().filter(|m| msg_ty(m) == newrule && chain_of(m) == "input").collect(); + assert_eq!(inputs.len(), 2); + assert_eq!(get(&attrs(get(&exprs(inputs[0])[4].1, 3)), 1), &[127, 0, 0, 0]); + assert_eq!(get(&attrs(get(&exprs(inputs[1])[4].1, 3)), 1), &[169, 254, 0, 0]); + } + + #[test] + fn unconditional_forward_drop_and_default_route_parsers() { + let make_rule = |userdata: Option<&[u8]>, build_exprs: &dyn Fn(&mut Msg)| -> Vec { + let mut m = nft(NFT_MSG_NEWRULE, 0); + m.attr_str(1, "filter").attr_str(2, "FORWARD"); + m.nest(4); + build_exprs(&mut m); + m.end(); + if let Some(ud) = userdata { + m.attr(7, ud); + } + m.buf[16..].to_vec() + }; + let drop_bare = make_rule(None, &|r| { + r.nest(1).attr_str(1, "counter").end(); + r.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_DROP as u32).end().end().end().end(); + }); + let reject_bare = make_rule(None, &|r| { + r.nest(1).attr_str(1, "counter").end(); + r.nest(1).attr_str(1, "reject").end(); + }); + let accept_bare = make_rule(None, &|r| { + r.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_ACCEPT as u32).end().end().end().end(); + }); + let conditional_drop = make_rule(None, &|r| { + r.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 7).end().end(); + r.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_DROP as u32).end().end().end().end(); + }); + let kiri_tagged = make_rule(Some(b"kiri"), &|r| { + r.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_DROP as u32).end().end().end().end(); + }); + assert!(is_unconditional_drop_rule(&drop_bare)); + assert!(is_unconditional_drop_rule(&reject_bare)); + assert!(!is_unconditional_drop_rule(&accept_bare)); + assert!(!is_unconditional_drop_rule(&conditional_drop)); + assert!(!is_unconditional_drop_rule(&kiri_tagged)); + + // Default routes across RT_TABLE_MAIN (v4), policy table 52 (Tailscale), AF_INET6, non-default /24, and RTA_MULTIPATH. + let mut policy_v4 = Msg::new(0, 0); + let mut rt = [0u8; 12]; + rt[0] = libc::AF_INET as u8; + rt[4] = 52; + rt[7] = libc::RTN_UNICAST; + policy_v4.raw(&rt).attr_u32(RTA_OIF, 17); + assert_eq!(parse_default_route_ifindices(&policy_v4.buf[16..]), vec![17]); + + let mut v6 = Msg::new(0, 0); + rt[0] = libc::AF_INET6 as u8; + rt[4] = libc::RT_TABLE_MAIN; + v6.raw(&rt).attr_u32(RTA_OIF, 9); + assert_eq!(parse_default_route_ifindices(&v6.buf[16..]), vec![9]); + + let mut non_default = Msg::new(0, 0); + rt[0] = libc::AF_INET as u8; + rt[1] = 24; + non_default.raw(&rt).attr_u32(RTA_OIF, 5); + assert!(parse_default_route_ifindices(&non_default.buf[16..]).is_empty()); + + let mut mp = Msg::new(0, 0); + rt[1] = 0; + mp.raw(&rt); + let mut mp_buf = Vec::new(); + for idx in [3i32, 4i32] { + mp_buf.extend_from_slice(&8u16.to_ne_bytes()); + mp_buf.extend_from_slice(&[0, 0]); + mp_buf.extend_from_slice(&idx.to_ne_bytes()); + } + mp.attr(9, &mp_buf); + assert_eq!(parse_default_route_ifindices(&mp.buf[16..]), vec![3, 4]); } } diff --git a/crates/kiri-init/src/linux/relay.rs b/crates/kiri-init/src/linux/relay.rs index 12576ec02..c5ef31372 100644 --- a/crates/kiri-init/src/linux/relay.rs +++ b/crates/kiri-init/src/linux/relay.rs @@ -346,11 +346,28 @@ fn connect(ip: [u8; 4], port: u16) -> io::Result { } } -/// The reverse direction, for `host.docker.internal`: TCP connections a -/// container makes to the reserved host address are redirected here. +/// The reverse direction, for `host.docker.internal` and loopback-published +/// ports: TCP connections a container makes to the reserved host address or +/// (from the VM itself) to a port published on the Mac's loopback (`127.0.0.1` +/// or `::1`) are redirected here. Dual-stack (`[::]` with `IPV6_V6ONLY = 0`), +/// falling back to `AF_INET` only if the kernel has no IPv6. pub fn listen_host_bound(port: u16) -> io::Result { // SAFETY: plain socket setup; the fd is owned immediately. unsafe { + let fd = libc::socket(libc::AF_INET6, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0); + if fd >= 0 { + let sock = OwnedFd::from_raw_fd(fd as RawFd); + let zero: libc::c_int = 0; + sys::check(libc::setsockopt(sock.as_raw_fd(), libc::IPPROTO_IPV6, libc::IPV6_V6ONLY, (&zero as *const libc::c_int).cast(), 4) as _, "v6only")?; + let one: libc::c_int = 1; + libc::setsockopt(sock.as_raw_fd(), libc::SOL_SOCKET, libc::SO_REUSEADDR, (&one as *const libc::c_int).cast(), 4); + let mut a: libc::sockaddr_in6 = std::mem::zeroed(); + a.sin6_family = libc::AF_INET6 as libc::sa_family_t; + a.sin6_port = port.to_be(); + sys::check(libc::bind(sock.as_raw_fd(), (&a as *const libc::sockaddr_in6).cast(), std::mem::size_of::() as u32) as _, "bind")?; + sys::check(libc::listen(sock.as_raw_fd(), 128) as _, "listen")?; + return Ok(sock); + } let fd = sys::check(libc::socket(libc::AF_INET, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) as _, "socket")?; let sock = OwnedFd::from_raw_fd(fd as RawFd); let one: libc::c_int = 1; @@ -366,31 +383,150 @@ pub fn listen_host_bound(port: u16) -> io::Result { /// The host side listens on this vsock port for host-bound connections. pub const HOST_VSOCK_PORT: u32 = 1026; +/// The host side listens on this vsock port for outbound TCP connections +/// redirected from containers (split-tunnel VPN routes, network extensions). +pub const EGRESS_VSOCK_PORT: u32 = kiri_proto::EGRESS_TCP_PORT; -/// Accepts one redirected connection, finds the port the container meant, -/// dials the Mac and returns a relay between the two. Only connections that -/// were redirected from `host_addr` are relayed: one made to the listener -/// directly (from the LAN, on a Linux host) would reach the host's loopback. -pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4]) -> Option { +/// Whether a redirected container connection's original destination may be +/// sent to the host egress dialer: never loopback, unspecified, link-local, +/// multicast/reserved, port 0, or `host.docker.internal` (which has its own +/// listener). +pub fn egress_dst_allowed(ip: [u8; 4], port: u16, host_addr: [u8; 4]) -> bool { + port != 0 + && ip[0] != 0 + && ip[0] != 127 + && !(ip[0] == 169 && ip[1] == 254) + && ip[0] < 224 + && ip != host_addr +} + +/// Accepts one connection redirected by an egress route rule, reads the +/// original IPv4 destination and port via `SO_ORIGINAL_DST`, dials the host on +/// `EGRESS_VSOCK_PORT` with `ip[4] port[2]`, and returns a relay between the +/// two. Direct connections not redirected by netfilter are dropped by +/// `host_relay_guard` in the input chain and rejected here if their +/// destination is local or forbidden. +pub fn accept_egress(listener: &OwnedFd, host_addr: [u8; 4]) -> Option { + accept_egress_with(listener, host_addr, || dial_host(EGRESS_VSOCK_PORT)) +} + +pub fn accept_egress_with( + listener: &OwnedFd, + host_addr: [u8; 4], + dial: impl FnOnce() -> io::Result, +) -> Option { // SAFETY: accept4 on a listening socket we own; the fd is owned immediately. - let fd = unsafe { libc::accept4(listener.as_raw_fd(), std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) }; + let fd = unsafe { + libc::accept4( + listener.as_raw_fd(), + std::ptr::null_mut(), + std::ptr::null_mut(), + libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC, + ) + }; if fd < 0 { return None; } // SAFETY: `fd` is a fresh descriptor that nothing else owns. let client = unsafe { OwnedFd::from_raw_fd(fd) }; + let one: libc::c_int = 1; + // SAFETY: setting TCP_NODELAY on a stream socket we own. + unsafe { + libc::setsockopt( + client.as_raw_fd(), + libc::IPPROTO_TCP, + libc::TCP_NODELAY, + (&one as *const libc::c_int).cast(), + 4, + ); + } // SAFETY: SO_ORIGINAL_DST fills a sockaddr_in with the pre-redirect destination. - let port = unsafe { + let (ip, port) = unsafe { let mut dst: libc::sockaddr_in = std::mem::zeroed(); let mut len = std::mem::size_of::() as u32; const SO_ORIGINAL_DST: libc::c_int = 80; - if libc::getsockopt(client.as_raw_fd(), libc::SOL_IP, SO_ORIGINAL_DST, (&mut dst as *mut libc::sockaddr_in).cast(), &mut len) != 0 { + if libc::getsockopt( + client.as_raw_fd(), + libc::SOL_IP, + SO_ORIGINAL_DST, + (&mut dst as *mut libc::sockaddr_in).cast(), + &mut len, + ) != 0 + { return Some(Relay::dead_one(client)); } - if dst.sin_addr.s_addr != u32::from_ne_bytes(host_addr) { - return Some(Relay::dead_one(client)); + let mut local: libc::sockaddr_in = std::mem::zeroed(); + let mut local_len = std::mem::size_of::() as u32; + if libc::getsockname( + listener.as_raw_fd(), + (&mut local as *mut libc::sockaddr_in).cast(), + &mut local_len, + ) == 0 + && dst.sin_port == local.sin_port + && (dst.sin_addr.s_addr == local.sin_addr.s_addr || local.sin_addr.s_addr == 0) + { + // A direct non-redirected connection to the listener's own port has + // SO_ORIGINAL_DST equal to the socket's local endpoint; reject it + // if the port matches and the IP is one of this machine's own. + let mut own: libc::sockaddr_in = std::mem::zeroed(); + let mut own_len = std::mem::size_of::() as u32; + if libc::getsockname( + client.as_raw_fd(), + (&mut own as *mut libc::sockaddr_in).cast(), + &mut own_len, + ) == 0 + && dst.sin_addr.s_addr == own.sin_addr.s_addr + { + return Some(Relay::dead_one(client)); + } } - u16::from_be(dst.sin_port) + (dst.sin_addr.s_addr.to_ne_bytes(), u16::from_be(dst.sin_port)) + }; + if !egress_dst_allowed(ip, port, host_addr) { + return Some(Relay::dead_one(client)); + } + let Ok(host) = dial() else { + return Some(Relay::dead_one(client)); + }; + let mut header = [ip[0], ip[1], ip[2], ip[3], 0, 0]; + header[4..].copy_from_slice(&port.to_be_bytes()); + // SAFETY: a 6-byte write to a just-connected stream; the socket buffer is empty. + if unsafe { libc::write(host.as_raw_fd(), header.as_ptr().cast(), 6) } != 6 { + return Some(Relay::dead_one(client)); + } + if sys::set_nonblocking(host.as_raw_fd()).is_err() { + return Some(Relay::dead_one(client)); + } + Some(Relay { + host, + target: Some(client), + connected: true, + header: Vec::new(), + up: Pipe::new(), + down: Pipe::new(), + dead: false, + udp: false, + framed: false, + }) +} + +/// Accepts one redirected connection, finds the port the container meant, +/// dials the Mac and returns a relay between the two. Only connections that +/// were redirected from `host_addr`, or from 127.0.0.1 / ::1 on another port +/// (a port published on the Mac's loopback, which only the VM's own output +/// chain redirects), are relayed: one made to the listener directly (from +/// the LAN, or from a `--network host` container dialling `127.0.0.1:relay_port` +/// or `[::1]:relay_port`) would reach the host's loopback. +pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4], relay_port: u16) -> Option { + // SAFETY: accept4 on a listening socket we own; the fd is owned immediately. + let fd = unsafe { libc::accept4(listener.as_raw_fd(), std::ptr::null_mut(), std::ptr::null_mut(), libc::SOCK_NONBLOCK | libc::SOCK_CLOEXEC) }; + if fd < 0 { + return None; + } + // SAFETY: `fd` is a fresh descriptor that nothing else owns. + let client = unsafe { OwnedFd::from_raw_fd(fd) }; + let Some(port) = original_dst_port(client.as_raw_fd(), host_addr, relay_port) else { + return Some(Relay::dead_one(client)); }; let Ok(host) = dial_host(HOST_VSOCK_PORT) else { return Some(Relay::dead_one(client)) }; // The Mac connects to its own loopback: services bound to 127.0.0.1 work. @@ -416,6 +552,45 @@ pub fn accept_host_bound(listener: &OwnedFd, host_addr: [u8; 4]) -> Option Option { + const SO_ORIGINAL_DST: libc::c_int = 80; // also IP6T_SO_ORIGINAL_DST on SOL_IPV6 + // SAFETY: SO_ORIGINAL_DST / IP6T_SO_ORIGINAL_DST fill sockaddr_in / sockaddr_in6. + unsafe { + let mut dst: libc::sockaddr_in = std::mem::zeroed(); + let mut len = std::mem::size_of::() as u32; + if libc::getsockopt(fd, libc::SOL_IP, SO_ORIGINAL_DST, (&mut dst as *mut libc::sockaddr_in).cast(), &mut len) == 0 { + let dst_port = u16::from_be(dst.sin_port); + return redirected_from(dst.sin_addr.s_addr.to_ne_bytes(), dst_port, host_addr, relay_port).then_some(dst_port); + } + let mut dst6: libc::sockaddr_in6 = std::mem::zeroed(); + let mut len6 = std::mem::size_of::() as u32; + if libc::getsockopt(fd, libc::SOL_IPV6, SO_ORIGINAL_DST, (&mut dst6 as *mut libc::sockaddr_in6).cast(), &mut len6) == 0 { + let dst_port = u16::from_be(dst6.sin6_port); + return redirected_from6(dst6.sin6_addr.s6_addr, dst_port, relay_port).then_some(dst_port); + } + None + } +} + +/// Whether a host-bound connection's original destination is one the +/// redirect rules send to the relay: the host's reserved address, or the +/// VM's loopback on another port (published ports only, see +/// `loopback_published_rule`; `relay_port` itself on 127.0.0.1 is +/// indistinguishable from a direct, non-redirected connection). +fn redirected_from(dst: [u8; 4], dst_port: u16, host_addr: [u8; 4], relay_port: u16) -> bool { + dst == host_addr || (dst == super::netlink::LOOPBACK && dst_port != relay_port) +} + +/// The IPv6 counterpart of `redirected_from`: the VM's `::1` loopback on a +/// published port (`loopback_published_rule6`), never `relay_port` itself or +/// any other IPv6 address. +fn redirected_from6(dst: [u8; 16], dst_port: u16, relay_port: u16) -> bool { + dst == super::netlink::LOOPBACK6 && dst_port != relay_port +} + fn dial_host(port: u32) -> io::Result { super::transport::dial(port) } @@ -430,29 +605,89 @@ impl Relay { /// SSH agent forwarding: containers that mount this socket reach the Mac's /// SSH agent. Each connection is relayed over vsock; keys never leave the Mac. pub const SSH_AGENT_SOCK: &str = "/run/host-services/ssh-auth.sock"; +/// The same socket on a Linux host: under Kiri's own runtime directory, not +/// the host's /run/host-services, which Docker Desktop for Linux also uses +/// for its docker.proxy.sock. Creating that directory root 0700 stopped +/// Docker Desktop from starting (#420), so on a host process the agent +/// never creates or chmods it. +pub const HOST_SSH_AGENT_SOCK: &str = "/run/kiri/host-services/ssh-auth.sock"; pub const SSH_VSOCK_PORT: u32 = 1027; +/// Where the agent listens for SSH agent connections: the VM's +/// /run/host-services, or Kiri's own directory on a Linux host. +fn ssh_agent_sock() -> &'static str { + ssh_agent_sock_for(super::transport::is_host_process()) +} + +fn ssh_agent_sock_for(host_process: bool) -> &'static str { + if host_process { HOST_SSH_AGENT_SOCK } else { SSH_AGENT_SOCK } +} + pub fn listen_ssh_agent() -> io::Result { - std::fs::create_dir_all("/run/host-services")?; - let _ = std::fs::remove_file(SSH_AGENT_SOCK); - // SAFETY: plain unix socket setup; the fd is owned immediately. + listen_ssh_agent_at(ssh_agent_sock()) +} + +fn listen_ssh_agent_at(sock_path: &str) -> io::Result { + use std::os::unix::fs::DirBuilderExt; + let (dir, sock_name) = match sock_path.rsplit_once('/') { + Some((d, name)) if !name.is_empty() => (if d.is_empty() { "/" } else { d }, name), + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid socket path: {sock_path}"))), + }; + if let Some((parent, _)) = dir.rsplit_once('/') + && !parent.is_empty() + { + std::fs::create_dir_all(parent)?; + } + match std::fs::DirBuilder::new().mode(0o700).create(dir) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + // SAFETY: plain unix socket setup against a directory fd opened with O_NOFOLLOW; fds are owned immediately. unsafe { - // The socket below is 0777 for any user in a container. On a Linux - // host this directory is the host's own, so only root, which - // bind-mounts the socket into containers, may reach it by path. - let dir = std::ffi::CString::new("/run/host-services").expect("no NUL"); - sys::check(libc::chmod(dir.as_ptr(), 0o700) as _, "chmod /run/host-services")?; - let fd = sys::check(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) as _, "socket")?; - let sock = OwnedFd::from_raw_fd(fd as RawFd); + // The socket below is 0777 for any user in a container. This + // directory is the agent's own (the VM's /run/host-services, or + // Kiri's /run/kiri/host-services on a Linux host), so only root, + // which bind-mounts the socket into containers, may reach it by path. + // Opened with O_DIRECTORY | O_NOFOLLOW before unlinking or binding so + // a symlink there is refused without touching its target. + let dir_c = std::ffi::CString::new(dir).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in directory path"))?; + let sock_c = std::ffi::CString::new(sock_name).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "NUL in socket name"))?; + let dfd = sys::check( + libc::open(dir_c.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) as _, + &format!("open {dir}"), + )?; + let dfd = OwnedFd::from_raw_fd(dfd as RawFd); + if libc::geteuid() == 0 { + sys::check(libc::fchown(dfd.as_raw_fd(), 0, 0) as _, &format!("chown {dir}"))?; + } + sys::check(libc::fchmod(dfd.as_raw_fd(), 0o700) as _, &format!("chmod {dir}"))?; + if libc::unlinkat(dfd.as_raw_fd(), sock_c.as_ptr(), 0) != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::ENOENT) { + return Err(e); + } + } let mut a: libc::sockaddr_un = std::mem::zeroed(); a.sun_family = libc::AF_UNIX as libc::sa_family_t; - for (d, s) in a.sun_path.iter_mut().zip(SSH_AGENT_SOCK.bytes()) { + if sock_path.len() >= a.sun_path.len() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("socket path too long: {sock_path}"))); + } + let proc_dir = format!("/proc/self/fd/{}", dfd.as_raw_fd()); + let proc_sock = format!("{proc_dir}/{sock_name}"); + let bind_path = if proc_sock.len() < a.sun_path.len() && std::path::Path::new(&proc_dir).exists() { + proc_sock.as_str() + } else { + sock_path + }; + for (d, s) in a.sun_path.iter_mut().zip(bind_path.bytes()) { *d = s as libc::c_char; } + let fd = sys::check(libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0) as _, "socket")?; + let sock = OwnedFd::from_raw_fd(fd as RawFd); sys::check(libc::bind(sock.as_raw_fd(), (&a as *const libc::sockaddr_un).cast(), std::mem::size_of::() as u32) as _, "bind")?; // Any user in a container may use it, as with Docker Desktop. - let path = std::ffi::CString::new(SSH_AGENT_SOCK).expect("no NUL"); - libc::chmod(path.as_ptr(), 0o777); + sys::check(libc::fchmodat(dfd.as_raw_fd(), sock_c.as_ptr(), 0o777, 0) as _, &format!("chmod {sock_path}"))?; sys::check(libc::listen(sock.as_raw_fd(), 64) as _, "listen")?; Ok(sock) } @@ -521,6 +756,37 @@ pub fn accept_engine(listener: &OwnedFd) -> Option { mod tests { use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + /// The host relay takes connections redirected from the host's address + /// and from the VM's loopback (`127.0.0.1` and `::1`) on another port + /// (published ports), never direct connections to the relay's own port or + /// other addresses. + #[test] + fn the_host_relay_takes_the_host_address_and_loopback() { + let host = [198, 19, 248, 254]; + let relay = 1026; + assert!(super::redirected_from(host, 8080, host, relay)); + assert!(super::redirected_from(host, relay, host, relay)); + assert!(super::redirected_from([127, 0, 0, 1], 5999, host, relay)); + assert!(!super::redirected_from([127, 0, 0, 1], relay, host, relay), "direct loopback connection to the relay"); + for other in [[192, 168, 64, 2], [172, 17, 0, 1], [127, 0, 0, 2], [0, 0, 0, 0]] { + assert!(!super::redirected_from(other, 5999, host, relay), "{other:?}"); + assert!(!super::redirected_from(other, relay, host, relay), "{other:?}"); + } + let lo6 = super::super::netlink::LOOPBACK6; + assert!(super::redirected_from6(lo6, 5999, relay)); + assert!(!super::redirected_from6(lo6, relay, relay), "direct ::1 connection to the relay"); + for other6 in [ + [0; 16], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2], + [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1], + [0xfd, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1], + [0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + ] { + assert!(!super::redirected_from6(other6, 5999, relay), "{other6:?}"); + assert!(!super::redirected_from6(other6, relay, relay), "{other6:?}"); + } + } + #[test] fn framed_reads_carry_their_length_and_end_with_an_empty_frame() { let mut fds = [0; 2]; @@ -539,4 +805,261 @@ mod tests { let full = buf.len() + 4; assert_eq!(super::read_frame_into(r.as_raw_fd(), &mut buf, full).unwrap(), 1); } + + #[test] + fn ssh_agent_socket_stays_out_of_the_host_run_host_services() { + use std::os::unix::fs::{FileTypeExt, PermissionsExt}; + // In the VM the socket is the VM's own /run/host-services; on a Linux + // host it moves under Kiri's /run/kiri, so Docker Desktop for Linux + // keeps its docker.proxy.sock there (#420). + assert_eq!(super::ssh_agent_sock_for(false), "/run/host-services/ssh-auth.sock"); + assert_eq!(super::ssh_agent_sock_for(true), "/run/kiri/host-services/ssh-auth.sock"); + + let root = std::path::PathBuf::from(format!("/tmp/kiri-ssh-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let sock = root.join("kiri/host-services/ssh-auth.sock"); + let sock_str = sock.to_str().unwrap(); + let listener = super::listen_ssh_agent_at(sock_str).unwrap(); + assert!(!root.join("host-services").exists(), "sibling host-services must not be created"); + let dir_mode = std::fs::metadata(root.join("kiri/host-services")).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o700, "parent directory must be 0700 so unprivileged host users cannot traverse it"); + let meta = std::fs::symlink_metadata(&sock).unwrap(); + assert!(meta.file_type().is_socket()); + assert_eq!(meta.permissions().mode() & 0o777, 0o777); + drop(listener); + + // An existing broader directory is tightened to 0700 and a stale socket is replaced. + std::fs::set_permissions(root.join("kiri/host-services"), std::fs::Permissions::from_mode(0o755)).unwrap(); + let listener = super::listen_ssh_agent_at(sock_str).unwrap(); + let dir_mode = std::fs::metadata(root.join("kiri/host-services")).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o700); + drop(listener); + + // A symlink at the host-services directory is refused without chmodding + // its target or unlinking an existing file inside it. + std::fs::remove_dir_all(root.join("kiri/host-services")).unwrap(); + let victim = root.join("victim"); + std::fs::create_dir(&victim).unwrap(); + std::fs::set_permissions(&victim, std::fs::Permissions::from_mode(0o755)).unwrap(); + let canary = victim.join("ssh-auth.sock"); + std::fs::write(&canary, b"keep").unwrap(); + std::os::unix::fs::symlink(&victim, root.join("kiri/host-services")).unwrap(); + assert!(super::listen_ssh_agent_at(sock_str).is_err()); + assert_eq!(std::fs::metadata(&victim).unwrap().permissions().mode() & 0o777, 0o755); + assert_eq!(std::fs::read(&canary).unwrap(), b"keep", "symlink target contents must not be unlinked"); + + let long = format!("{}/{}", root.display(), "a".repeat(120)); + assert_eq!(super::listen_ssh_agent_at(&long).unwrap_err().kind(), std::io::ErrorKind::InvalidInput); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn egress_dst_guard_rejects_local_and_allows_vpn_and_public_destinations() { + let host = super::super::net::HOST_ADDR; + assert!(!super::egress_dst_allowed([127, 0, 0, 1], 443, host)); + assert!(!super::egress_dst_allowed([0, 0, 0, 0], 443, host)); + assert!(!super::egress_dst_allowed([169, 254, 169, 254], 80, host)); + assert!(!super::egress_dst_allowed([224, 0, 0, 1], 80, host)); + assert!(!super::egress_dst_allowed([255, 255, 255, 255], 80, host)); + assert!(!super::egress_dst_allowed(host, 80, host)); + assert!(!super::egress_dst_allowed([10, 0, 5, 10], 0, host)); + assert!(super::egress_dst_allowed([10, 0, 5, 10], 443, host)); + assert!(super::egress_dst_allowed([10, 254, 99, 10], 8443, host)); + assert!(super::egress_dst_allowed([198, 18, 2, 3], 443, host)); + } + + #[test] + fn egress_redirect_relays_vpn_tcp_with_original_dst_and_exempts_bridge_peers() { + use std::io::{Read, Write}; + use super::super::{net, netlink, sys}; + + // Requires root (CAP_NET_ADMIN / CLONE_NEWNET) on Linux. + if unsafe { libc::geteuid() } != 0 { + return; + } + + let spawn_netns_holder = || -> (libc::pid_t, std::fs::File) { + let mut pipe = [0; 2]; + assert_eq!(unsafe { libc::pipe(pipe.as_mut_ptr()) }, 0); + let pid = unsafe { libc::fork() }; + assert!(pid >= 0); + if pid == 0 { + unsafe { + libc::close(pipe[0]); + if libc::unshare(libc::CLONE_NEWNET) != 0 { + libc::_exit(1); + } + let _ = libc::write(pipe[1], b"1".as_ptr().cast(), 1); + libc::close(pipe[1]); + loop { + libc::pause(); + } + } + } + unsafe { libc::close(pipe[1]) }; + let mut b = [0u8; 1]; + assert_eq!(unsafe { libc::read(pipe[0], b.as_mut_ptr().cast(), 1) }, 1); + unsafe { libc::close(pipe[0]) }; + let ns = std::fs::File::open(format!("/proc/{pid}/ns/net")).expect("open child netns"); + (pid, ns) + }; + + // Run inside a forked child with its own root network namespace so the + // host machine's interfaces and nftables rules are never touched. + let child = unsafe { libc::fork() }; + assert!(child >= 0); + if child == 0 { + unsafe { + if libc::unshare(libc::CLONE_NEWNET) != 0 { + libc::_exit(2); + } + } + let mut nl = netlink::Netlink::open(libc::NETLINK_ROUTE).unwrap(); + netlink::set_up(&mut nl, 1).unwrap(); + netlink::create_bridge(&mut nl, "eth0").unwrap(); + let eth0 = netlink::index_of("eth0").unwrap(); + netlink::add_address(&mut nl, eth0, [192, 168, 64, 2], 24).unwrap(); + netlink::set_up(&mut nl, eth0).unwrap(); + netlink::add_default_route(&mut nl, eth0, [192, 168, 64, 1]).unwrap(); + sys::write_file("/proc/sys/net/ipv4/ip_forward", "1").unwrap(); + + let (c1_pid, c1_ns) = spawn_netns_holder(); + let (c2_pid, c2_ns) = spawn_netns_holder(); + + let mut bridges = net::Bridges::default(); + net::attach_container( + &mut bridges, + "kiri0", + "kv_eg1", + c1_pid, + None, + [172, 18, 0, 2], + 16, + [172, 18, 0, 1], + None, + None, + net::Plug::default(), + ) + .unwrap(); + net::attach_container( + &mut bridges, + "kiri0", + "kv_eg2", + c2_pid, + None, + [172, 18, 0, 3], + 16, + [172, 18, 0, 1], + None, + None, + net::Plug::default(), + ) + .unwrap(); + + let skip = [([127, 0, 0, 0], 8), ([172, 18, 0, 0], 16), ([192, 168, 64, 0], 24)]; + netlink::install_nat_with_egress( + eth0, + net::HOST_ADDR, + net::HOST_RELAY_PORT, + true, + &[], + [192, 168, 64, 1], + &["kiri0".to_owned()], + None, + net::EGRESS_RELAY_PORT, + &[([10, 254, 99, 0], 24)], + &skip, + ) + .unwrap(); + + let listener = super::listen_host_bound(net::EGRESS_RELAY_PORT).unwrap(); + + // 1) Container 1 dials mock VPN destination 10.254.99.10:8443. + let c1_sock = netlink::in_netns(&c1_ns, || super::connect([10, 254, 99, 10], 8443)).unwrap(); + let mut pfd = libc::pollfd { fd: listener.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + assert_eq!(unsafe { libc::poll(&mut pfd, 1, 2000) }, 1, "egress listener must receive redirected SYN"); + + let mut pair = [0; 2]; + assert_eq!(unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC, 0, pair.as_mut_ptr()) }, 0); + let mut mock_host = unsafe { std::fs::File::from_raw_fd(pair[0]) }; + let relay_host = unsafe { OwnedFd::from_raw_fd(pair[1]) }; + + let mut relay = super::accept_egress_with(&listener, net::HOST_ADDR, || Ok(relay_host)).expect("accept_egress"); + assert!(!relay.dead, "redirected VPN connection must be accepted"); + + let mut hdr = [0u8; 6]; + mock_host.read_exact(&mut hdr).unwrap(); + assert_eq!(hdr, [10, 254, 99, 10, 0x20, 0xfb], "SO_ORIGINAL_DST must report 10.254.99.10:8443"); + + let mut c1_pfd = libc::pollfd { fd: c1_sock.as_raw_fd(), events: libc::POLLOUT, revents: 0 }; + assert_eq!(unsafe { libc::poll(&mut c1_pfd, 1, 2000) }, 1); + let req = b"GET /vpn HTTP/1.1\r\n\r\n"; + assert_eq!(unsafe { libc::write(c1_sock.as_raw_fd(), req.as_ptr().cast(), req.len()) }, req.len() as isize); + + relay.step(); + let mut got_req = vec![0u8; req.len()]; + mock_host.read_exact(&mut got_req).unwrap(); + assert_eq!(got_req, req); + + let resp = b"HTTP/1.1 200 OK\r\n\r\nvpn-ok"; + mock_host.write_all(resp).unwrap(); + drop(mock_host); + + for _ in 0..20 { + relay.step(); + if relay.dead { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + unsafe { + let flags = libc::fcntl(c1_sock.as_raw_fd(), libc::F_GETFL); + libc::fcntl(c1_sock.as_raw_fd(), libc::F_SETFL, flags & !libc::O_NONBLOCK); + } + let mut c1_file = unsafe { std::fs::File::from_raw_fd(c1_sock.as_raw_fd()) }; + std::mem::forget(c1_sock); + let mut got_resp = vec![0u8; resp.len()]; + c1_file.read_exact(&mut got_resp).unwrap(); + assert_eq!(got_resp, resp); + let mut eof = [0u8; 1]; + assert_eq!(c1_file.read(&mut eof).unwrap(), 0, "relay must pass clean EOF to container"); + + // 2) Even under full host egress (0.0.0.0/0), container-to-container + // TCP on the bridge (172.18.0.2 -> 172.18.0.3:9090) is exempt and + // connects directly without hitting the egress relay listener. + netlink::install_nat_with_egress( + eth0, + net::HOST_ADDR, + net::HOST_RELAY_PORT, + true, + &[], + [192, 168, 64, 1], + &["kiri0".to_owned()], + None, + net::EGRESS_RELAY_PORT, + &[([0, 0, 0, 0], 0)], + &skip, + ) + .unwrap(); + + let peer_listener = netlink::in_netns(&c2_ns, || std::net::TcpListener::bind("172.18.0.3:9090")).unwrap(); + let mut peer_client = netlink::in_netns(&c1_ns, || std::net::TcpStream::connect("172.18.0.3:9090")).unwrap(); + let mut check_egress = libc::pollfd { fd: listener.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + assert_eq!(unsafe { libc::poll(&mut check_egress, 1, 50) }, 0, "bridge peer traffic must not hit egress listener"); + let (mut peer_accepted, _) = peer_listener.accept().unwrap(); + peer_client.write_all(b"peer-ping").unwrap(); + let mut peer_buf = [0u8; 9]; + peer_accepted.read_exact(&mut peer_buf).unwrap(); + assert_eq!(&peer_buf, b"peer-ping"); + + unsafe { + libc::kill(c1_pid, libc::SIGKILL); + libc::kill(c2_pid, libc::SIGKILL); + libc::_exit(0); + } + } + let mut status: libc::c_int = 0; + assert_eq!(unsafe { libc::waitpid(child, &mut status, 0) }, child); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, "child failed with status {status}"); + } } diff --git a/crates/kiri-init/src/linux/roots.rs b/crates/kiri-init/src/linux/roots.rs index b91d037c3..dfbeb6b61 100644 --- a/crates/kiri-init/src/linux/roots.rs +++ b/crates/kiri-init/src/linux/roots.rs @@ -23,6 +23,9 @@ struct Root { /// Removed (`docker rm`, `--rm`) while in use: its files go with the /// last user. remove: bool, + /// Unpacked layer hex digests mounted as lowerdirs for this root, kept + /// safe from live `RetainLayers` until the mount goes away. + layers: Vec, } /// What letting go of a root leaves to do. @@ -37,10 +40,20 @@ struct Table(HashMap); impl Table { /// True when this is the first user, who must mount it. - fn take(&mut self, base: &Path) -> bool { + fn take(&mut self, base: &Path, layers: &[&str]) -> bool { let r = self.0.entry(base.to_owned()).or_default(); r.users += 1; - r.users == 1 + if r.users == 1 { + r.layers = layers.iter().filter_map(|d| super::layers::hex(d).ok().map(str::to_owned)).collect(); + true + } else { + false + } + } + + /// Layer hex digests currently held by any active overlay mount. + fn in_use_layers(&self) -> Vec { + self.0.values().filter(|r| r.users > 0).flat_map(|r| r.layers.iter().cloned()).collect() } /// One more user of a root already mounted; false if it isn't. @@ -95,13 +108,27 @@ thread_local! { } /// The container's mounted root, mounting it if nobody has yet. -pub fn acquire(paths: &Paths, id: &str, layers: &[&str]) -> io::Result { +/// When `writable` is true (containers without `--read-only`), refuses a +/// read-only / `emergency_ro` upper filesystem or read-only overlay fallback. +pub fn acquire(paths: &Paths, id: &str, layers: &[&str], writable: bool) -> io::Result { container::valid_id(id)?; let base = paths.containers.join(id); - if !TABLE.with_borrow_mut(|t| t.take(&base)) { - return Ok(base.join("rootfs")); + if !TABLE.with_borrow_mut(|t| t.take(&base, layers)) { + let rootfs = base.join("rootfs"); + if writable + && let Err(e) = container::ensure_writable_rootfs(&base, &rootfs) + { + release(&base); + return Err(e); + } + return Ok(rootfs); } - container::mount_rootfs(paths, id, layers).inspect_err(|_| TABLE.with_borrow_mut(|t| t.forget(&base))) + container::mount_rootfs(paths, id, layers, writable).inspect_err(|_| TABLE.with_borrow_mut(|t| t.forget(&base))) +} + +/// Layer hex digests currently held by any active overlay mount. +pub fn in_use_layers() -> Vec { + TABLE.with_borrow(Table::in_use_layers) } /// Holds a root that is mounted now (a running container's), for a copy @@ -141,7 +168,7 @@ pub fn remove(base: &Path) { /// Unmounts at once when nothing holds the mount, so the next mount of the /// same layer never overlaps one still being let go; lazily otherwise. -fn unmount(rootfs: &Path) { +pub(super) fn unmount(rootfs: &Path) { let Ok(t) = sys::cstr(rootfs) else { return }; // SAFETY: `t` is a valid NUL-terminated string. if unsafe { libc::umount2(t.as_ptr(), 0) } != 0 { @@ -157,20 +184,20 @@ mod tests { #[test] fn the_first_user_mounts_and_the_last_unmounts() { let (mut t, a) = (Table::default(), Path::new("/c/a")); - assert!(t.take(a), "the container starts: it mounts"); - assert!(!t.take(a), "a copy meanwhile uses the same mount"); + assert!(t.take(a, &[]), "the container starts: it mounts"); + assert!(!t.take(a, &[]), "a copy meanwhile uses the same mount"); assert_eq!(t.give(a), Some(Left::InUse), "the copy ends: still running"); assert_eq!(t.give(a), Some(Left::Unmount { remove: false }), "the container exits"); assert_eq!(t.give(a), None, "nothing left to let go"); - assert!(t.take(a), "a later start mounts again"); + assert!(t.take(a, &[]), "a later start mounts again"); } #[test] fn a_root_removed_in_use_goes_with_its_last_user() { let (mut t, a) = (Table::default(), Path::new("/c/a")); assert!(t.doom(a), "not in use: removed now"); - t.take(a); - t.take(a); + t.take(a, &[]); + t.take(a, &[]); assert!(!t.doom(a)); assert_eq!(t.give(a), Some(Left::InUse)); assert_eq!(t.give(a), Some(Left::Unmount { remove: true })); @@ -180,10 +207,10 @@ mod tests { fn a_copy_into_a_running_container_keeps_its_root_past_a_restart() { let (mut t, a) = (Table::default(), Path::new("/c/a")); assert!(!t.hold(a), "nothing mounted: nothing to hold"); - t.take(a); + t.take(a, &[]); assert!(t.hold(a)); assert_eq!(t.give(a), Some(Left::InUse), "the container exits: the copy still writes"); - assert!(!t.take(a), "the restart shares it instead of mounting again"); + assert!(!t.take(a, &[]), "the restart shares it instead of mounting again"); assert_eq!(t.give(a), Some(Left::InUse)); assert_eq!(t.give(a), Some(Left::Unmount { remove: false })); } @@ -191,8 +218,30 @@ mod tests { #[test] fn a_failed_mount_is_not_counted() { let (mut t, a) = (Table::default(), Path::new("/c/a")); - assert!(t.take(a)); + assert!(t.take(a, &[])); + t.forget(a); + assert!(t.take(a, &[]), "the next user mounts"); + } + + #[test] + fn in_use_layers_tracks_mounted_roots_until_release() { + let (mut t, a) = (Table::default(), Path::new("/c/a")); + let h1 = "a".repeat(64); + let h2 = "b".repeat(64); + let d1 = format!("sha256:{h1}"); + let d2 = format!("sha256:{h2}"); + assert!(t.in_use_layers().is_empty()); + assert!(t.take(a, &[d1.as_str(), d2.as_str()])); + assert_eq!(t.in_use_layers(), vec![h1.clone(), h2.clone()]); + // A second user (e.g. docker cp) keeps the same layers mounted. + assert!(!t.take(a, &[])); + assert_eq!(t.give(a), Some(Left::InUse)); + assert_eq!(t.in_use_layers(), vec![h1, h2]); + assert_eq!(t.give(a), Some(Left::Unmount { remove: false })); + assert!(t.in_use_layers().is_empty()); + // A failed mount drops its layers too. + assert!(t.take(a, &[d1.as_str()])); t.forget(a); - assert!(t.take(a), "the next user mounts"); + assert!(t.in_use_layers().is_empty()); } } diff --git a/crates/kiri-init/src/linux/swap.rs b/crates/kiri-init/src/linux/swap.rs new file mode 100644 index 000000000..f6c84e40c --- /dev/null +++ b/crates/kiri-init/src/linux/swap.rs @@ -0,0 +1,206 @@ +//! The VM's swap (#326): a file on the data disk, the size the host names +//! on the kernel command line (`kiri.swap=`). Docker Desktop gives its +//! VM 1 GiB the same way; without it a container that outgrows the VM's +//! memory is killed even when its pages could wait on disk. zswap is on in +//! the kernel, so pages are compressed in memory first, and its shrinker +//! moves them on to the file. + +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::os::fd::AsRawFd; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; +use std::path::Path; + +/// Where the swap file lives: the data disk's top, beside `layers` and +/// `containers`, so nothing that sweeps those touches it. +pub(super) const FILE: &str = "/var/lib/kiri/swapfile"; + +/// ``: freed swap pages are discarded, so the Mac's sparse +/// disk image gets their space back as for trimmed ext4 blocks. +const SWAP_FLAG_DISCARD: libc::c_int = 0x10000; + +/// Lets zswap write cold pages out to the swap file under memory pressure. +const ZSWAP_SHRINKER: &str = "/sys/module/zswap/parameters/shrinker_enabled"; + +/// The size the host asked for, in MiB, from the kernel command line. None +/// when it said nothing (an older host): the file is then left as it is. +pub(super) fn requested(cmdline: &str) -> Option { + cmdline.split_ascii_whitespace().filter_map(|a| a.strip_prefix("kiri.swap=")).next_back().and_then(|v| v.parse().ok()) +} + +/// Reads the command line and keeps the swap file as asked; only says why +/// on the console if it can't, since the VM runs without swap all the same. +pub(super) fn start() { + let Some(mib) = fs::read_to_string("/proc/cmdline").ok().as_deref().and_then(requested) else { return }; + // SAFETY: sysconf has no preconditions. + let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap_or(4096); + let path = Path::new(FILE); + match ensure(path, mib, page) { + Ok(false) => {} + Ok(true) => { + if let Err(e) = swapon(path) { + // A file that is not fit for swap (holes, a header the + // kernel refuses) is made again once. + let _ = fs::remove_file(path); + if let Err(e2) = ensure(path, mib, page).and_then(|_| swapon(path)) { + let _ = fs::remove_file(path); + eprintln!("kiri-init: no swap ({e}; again: {e2})"); + return; + } + } + // zswap keeps swapped pages compressed in memory, charged to the + // container. Without its shrinker they never reach the file, and + // a container over its `--memory` is killed with its swap unused. + if let Err(e) = super::sys::write_file(ZSWAP_SHRINKER, "Y") { + eprintln!("kiri-init: zswap's shrinker stays off ({e}); swap may fill memory first"); + } + } + Err(e) => { + let _ = fs::remove_file(path); + eprintln!("kiri-init: no swap of {mib} MiB ({e})"); + } + } +} + +/// Makes `path` a swap file of `mib` MiB, keeping one already that size, +/// or removes it for 0. Returns whether there is a swap file to turn on. +pub(super) fn ensure(path: &Path, mib: u64, page: usize) -> io::Result { + if mib == 0 { + return match fs::remove_file(path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(false), + }; + } + let len = mib.checked_shl(20).ok_or_else(|| io::Error::from_raw_os_error(libc::EFBIG))?; + if len < (page as u64).saturating_mul(10) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "swap file smaller than kernel minimum (10 pages)")); + } + if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file() && m.len() == len && (m.permissions().mode() & 0o777) == 0o600) + && has_header(path, page) + { + return Ok(true); + } + let _ = fs::remove_file(path); + // Only root may read it: swapped pages are any container's memory. + let f = OpenOptions::new().write(true).create_new(true).mode(0o600).custom_flags(libc::O_NOFOLLOW).open(path)?; + // Real blocks, not a sparse file: the kernel refuses swap with holes. + // ext4 marks them unwritten, so no zeros go to the Mac's disk. + let size = libc::off_t::try_from(len).map_err(|_| io::Error::from_raw_os_error(libc::EFBIG))?; + // SAFETY: fallocate on a descriptor this function owns. + if unsafe { libc::fallocate(f.as_raw_fd(), 0, 0, size) } != 0 { + return Err(io::Error::last_os_error()); + } + fs::set_permissions(path, fs::Permissions::from_mode(0o600))?; + write_header(&f, len, page)?; + f.sync_all()?; + Ok(true) +} + +/// mkswap's header, version 1: the page count at 1028 and the magic at the +/// end of the first page. +pub(super) fn header(len: u64, page: usize) -> Vec { + let mut h = vec![0u8; page]; + let last_page = u32::try_from((len / page as u64).saturating_sub(1)).unwrap_or(u32::MAX); + h[1024..1028].copy_from_slice(&1u32.to_ne_bytes()); + h[1028..1032].copy_from_slice(&last_page.to_ne_bytes()); + h[page - 10..].copy_from_slice(b"SWAPSPACE2"); + h +} + +fn write_header(mut f: &File, len: u64, page: usize) -> io::Result<()> { + f.seek(SeekFrom::Start(0))?; + f.write_all(&header(len, page)) +} + +/// Whether the regular file starts with a swap header for this page size. +fn has_header(path: &Path, page: usize) -> bool { + let mut h = vec![0u8; page]; + OpenOptions::new() + .read(true) + .custom_flags(libc::O_NOFOLLOW) + .open(path) + .and_then(|mut f| f.read_exact(&mut h)) + .is_ok() + && &h[page - 10..] == b"SWAPSPACE2" +} + +fn swapon(path: &Path) -> io::Result<()> { + let c = std::ffi::CString::new(path.as_os_str().as_bytes()).map_err(io::Error::other)?; + // SAFETY: a NUL-terminated path and flags; the kernel reads nothing else. + if unsafe { libc::swapon(c.as_ptr(), SWAP_FLAG_DISCARD) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_size_comes_from_the_kernel_command_line() { + assert_eq!(requested("console=hvc0 rdinit=/init kiri.swap=1024 quiet"), Some(1024)); + assert_eq!(requested("kiri.swap=0"), Some(0)); + assert_eq!(requested("kiri.swap=512 kiri.swap=2048"), Some(2048), "the last one counts, as for the kernel's own"); + assert_eq!(requested("console=hvc0 quiet"), None, "an older host says nothing"); + assert_eq!(requested("kiri.swap=lots"), None); + assert_eq!(requested("kiri.swapfile=1"), None); + } + + #[test] + fn the_header_is_mkswaps() { + for page in [4096, 16384] { + let h = header(1 << 30, page); + assert_eq!(h.len(), page); + assert_eq!(&h[1024..1028], &1u32.to_ne_bytes(), "version 1"); + assert_eq!(u32::from_ne_bytes(h[1028..1032].try_into().unwrap()) as u64, (1u64 << 30) / page as u64 - 1, "last page"); + assert_eq!(&h[1032..1036], &[0; 4], "no bad pages"); + assert_eq!(&h[page - 10..], b"SWAPSPACE2"); + } + } + + #[test] + fn the_file_is_made_kept_resized_and_removed() { + let dir = std::env::temp_dir().join(format!("kiri-swap-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let path = dir.join("swapfile"); + let page = 4096; + + assert!(ensure(&path, 2, page).unwrap()); + let m = fs::metadata(&path).unwrap(); + assert_eq!(m.len(), 2 << 20); + assert_eq!(m.permissions().mode() & 0o777, 0o600, "only root reads swapped memory"); + assert!(has_header(&path, page)); + use std::os::unix::fs::MetadataExt; + assert!(m.blocks() * 512 >= 2 << 20, "allocated, not sparse: the kernel refuses holes"); + + // The same size is kept as it is (its inode too). + let ino = m.ino(); + assert!(ensure(&path, 2, page).unwrap()); + assert_eq!(fs::metadata(&path).unwrap().ino(), ino); + + // A new size, or a file with no header, is made again. + assert!(ensure(&path, 3, page).unwrap()); + assert_eq!(fs::metadata(&path).unwrap().len(), 3 << 20); + fs::write(&path, vec![0u8; 3 << 20]).unwrap(); + assert!(ensure(&path, 3, page).unwrap()); + assert!(has_header(&path, page)); + + // A symlink at `path` is never followed; it is replaced by a real 0600 file. + let target = dir.join("decoy"); + fs::write(&target, vec![0u8; 3 << 20]).unwrap(); + let _ = fs::remove_file(&path); + std::os::unix::fs::symlink(&target, &path).unwrap(); + assert!(ensure(&path, 3, page).unwrap()); + assert!(fs::symlink_metadata(&path).unwrap().file_type().is_file()); + assert!(!has_header(&target, page), "decoy target was never written"); + + // 0: no swap file, and none is fine too. + assert!(!ensure(&path, 0, page).unwrap()); + assert!(!path.exists()); + assert!(!ensure(&path, 0, page).unwrap()); + let _ = fs::remove_dir_all(dir); + } +} diff --git a/crates/kiri-init/src/linux/sys.rs b/crates/kiri-init/src/linux/sys.rs index 72bc6b5c6..1c5bfa26b 100644 --- a/crates/kiri-init/src/linux/sys.rs +++ b/crates/kiri-init/src/linux/sys.rs @@ -106,12 +106,346 @@ pub fn remount(target: &CStr, flags: libc::c_ulong) -> io::Result<()> { check(ret as _, &format!("remount {}", target.to_string_lossy())).map(drop) } +pub fn umount(target: &Path) -> io::Result<()> { + let t = cstr(target)?; + // SAFETY: `t` is a valid NUL-terminated string. + check(unsafe { libc::umount2(t.as_ptr(), 0) } as _, "umount").map(drop) +} + pub fn umount_lazy(target: &Path) -> io::Result<()> { let t = cstr(target)?; // SAFETY: `t` is a valid NUL-terminated string. check(unsafe { libc::umount2(t.as_ptr(), libc::MNT_DETACH) } as _, "umount").map(drop) } +/// Linux's `CGROUP_SUPER_MAGIC` (``). +const CGROUP_SUPER_MAGIC: i64 = 0x27_e0eb; +/// Linux's `CGROUP2_SUPER_MAGIC` (``). +const CGROUP2_SUPER_MAGIC: i64 = 0x6367_7270; + +/// OpenZFS's `ZFS_SUPER_MAGIC` (`zpl_super.c`). +pub const ZFS_SUPER_MAGIC: i64 = 0x2fc1_2fc1; + +fn fs_magic(path: &Path) -> Option { + let c = cstr(path).ok()?; + // SAFETY: `st` is plain zero-initialized data; `c` is a valid C string. + let mut st: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: statfs writes into `st`. + (unsafe { libc::statfs(c.as_ptr(), &mut st) } == 0).then_some(st.f_type as i64) +} + +/// Whether `path` sits on a mounted `cgroup2` filesystem. +pub fn is_cgroup2(path: &Path) -> bool { + fs_magic(path) == Some(CGROUP2_SUPER_MAGIC) +} + +/// Whether `path` sits on a mounted cgroup v1 or v2 filesystem. +pub fn is_cgroup(path: &Path) -> bool { + matches!(fs_magic(path), Some(CGROUP_SUPER_MAGIC | CGROUP2_SUPER_MAGIC)) +} + +/// Linux `` `mount_attr` for `mount_setattr(2)` (Linux 5.12+). +#[repr(C)] +#[derive(Default)] +struct MountAttr { + attr_set: u64, + attr_clr: u64, + propagation: u64, + userns_fd: u64, +} + +pub const MOUNT_ATTR_RDONLY: u64 = 0x0000_0001; +pub const MOUNT_ATTR_NOSUID: u64 = 0x0000_0002; +pub const MOUNT_ATTR_NODEV: u64 = 0x0000_0004; +pub const MOUNT_ATTR_NOEXEC: u64 = 0x0000_0008; + +/// Recursively sets `attr_set` mount attributes on `target` and every mount +/// beneath it via `mount_setattr(2)`. +pub fn mount_setattr_recursive(target: &CStr, attr_set: u64) -> io::Result<()> { + let attr = MountAttr { attr_set, ..Default::default() }; + // SAFETY: `target` is a valid NUL-terminated path and `attr` is a valid + // `mount_attr` struct of the passed size. + let ret = unsafe { + libc::syscall( + libc::SYS_mount_setattr, + libc::AT_FDCWD, + target.as_ptr(), + libc::AT_RECURSIVE as libc::c_uint, + &attr as *const MountAttr, + std::mem::size_of::(), + ) + }; + check(ret as _, &format!("mount_setattr {}", target.to_string_lossy())).map(drop) +} + +/// Whether `statfs(2)` reports `ZFS_SUPER_MAGIC` on `path`. +pub fn is_statfs_zfs(path: &Path) -> bool { + let Ok(c) = cstr(path) else { return false }; + // SAFETY: `st` is plain zero-initialized data; `c` is a valid C string. + let mut st: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: statfs writes into `st`. + unsafe { libc::statfs(c.as_ptr(), &mut st) == 0 && st.f_type as i64 == ZFS_SUPER_MAGIC } +} + +/// Why a container storage filesystem is read-only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReadOnlyKind { + /// Linux ext4 aborted its journal (`errors=remount-ro`) and added `emergency_ro`. + EmergencyRo, + /// Mounted read-only (`ro` / `ST_RDONLY`), or overlayfs fell back to read-only. + ReadOnly, +} + +impl ReadOnlyKind { + pub fn merge(self, other: Self) -> Self { + if self == Self::EmergencyRo || other == Self::EmergencyRo { + Self::EmergencyRo + } else { + Self::ReadOnly + } + } +} + +/// Unescapes `/proc/mounts` and `/proc/self/mountinfo` octal escapes (`\040`, `\011`, `\012`, `\134`). +pub fn unescape_mount_path(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' + && i + 3 < bytes.len() + && bytes[i + 1..i + 4].iter().all(|b| (b'0'..=b'7').contains(b)) + { + let val = ((bytes[i + 1] - b'0') << 6) | ((bytes[i + 2] - b'0') << 3) | (bytes[i + 3] - b'0'); + out.push(val); + i += 4; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +fn norm_mount_path(p: &str) -> &str { + let trimmed = p.trim_end_matches('/'); + if trimmed.is_empty() { "/" } else { trimmed } +} + +fn mount_covers(mp: &str, target: &str) -> bool { + let mp = norm_mount_path(mp); + let target = norm_mount_path(target); + mp == "/" || target == mp || (target.starts_with(mp) && target.as_bytes().get(mp.len()) == Some(&b'/')) +} + +/// Parses comma-separated mount options (`rw,...,emergency_ro` or `ro,...`) +/// into `ReadOnlyKind`, ignoring substrings such as `errors=remount-ro`. +pub fn parse_opts_readonly(opts: &str) -> Option { + let mut ro = false; + for opt in opts.split(',') { + match opt.trim() { + "emergency_ro" => return Some(ReadOnlyKind::EmergencyRo), + "ro" => ro = true, + _ => {} + } + } + ro.then_some(ReadOnlyKind::ReadOnly) +} + +/// Inspects `/proc/mounts` text for the active mount covering `target`. +/// Picks the longest ancestor mountpoint, with later lines winning ties (overmounts). +pub fn proc_mounts_readonly(proc_mounts: &str, target: &Path) -> Option { + let target_str = target.to_string_lossy(); + let mut best: Option<(usize, Option)> = None; + for line in proc_mounts.lines() { + let mut fields = line.split_whitespace(); + let (Some(_spec), Some(mp_raw), Some(_fstype), Some(opts)) = + (fields.next(), fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let mp = unescape_mount_path(mp_raw); + let mp_norm = norm_mount_path(&mp); + if mount_covers(mp_norm, &target_str) && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + best = Some((mp_norm.len(), parse_opts_readonly(opts))); + } + } + best.and_then(|(_, kind)| kind) +} + +/// Inspects `/proc/self/mountinfo` text for the active mount covering `target`. +pub fn mountinfo_readonly(mountinfo: &str, target: &Path) -> Option { + let target_str = target.to_string_lossy(); + let mut best: Option<(usize, Option)> = None; + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let mut b = before.split_whitespace(); + let (Some(_id), Some(_parent), Some(_dev), Some(_root), Some(mp_raw), Some(mopts)) = + (b.next(), b.next(), b.next(), b.next(), b.next(), b.next()) + else { + continue; + }; + let mut a = after.split_whitespace(); + let (Some(_fstype), Some(_src), Some(sopts)) = (a.next(), a.next(), a.next()) else { continue }; + let mp = unescape_mount_path(mp_raw); + let mp_norm = norm_mount_path(&mp); + if mount_covers(mp_norm, &target_str) && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + let kind = match (parse_opts_readonly(mopts), parse_opts_readonly(sopts)) { + (Some(a), Some(b)) => Some(a.merge(b)), + (Some(a), None) | (None, Some(a)) => Some(a), + (None, None) => None, + }; + best = Some((mp_norm.len(), kind)); + } + } + best.and_then(|(_, kind)| kind) +} + +/// Inspects `/proc/self/mountinfo` text for the filesystem type of the active +/// mount covering `target` (longest ancestor mountpoint, with later lines +/// winning ties for overmounts). +pub fn mountinfo_fstype<'a>(mountinfo: &'a str, target: &Path) -> Option<&'a str> { + let target_str = target.to_string_lossy(); + let mut best: Option<(usize, &'a str)> = None; + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let Some(mp_raw) = before.split_whitespace().nth(4) else { continue }; + let Some(fstype) = after.split_whitespace().next() else { continue }; + let mp = unescape_mount_path(mp_raw); + let mp_norm = norm_mount_path(&mp); + if mount_covers(mp_norm, &target_str) && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + best = Some((mp_norm.len(), fstype)); + } + } + best.map(|(_, fstype)| fstype) +} + +/// Whether `/proc/self/mountinfo` reports fstype `"zfs"` for the active mount covering `target`. +pub fn is_zfs_mountinfo(mountinfo: &str, target: &Path) -> bool { + mountinfo_fstype(mountinfo, target) == Some("zfs") +} + +/// Whether `path` (or its nearest existing ancestor) sits on a ZFS filesystem, +/// checked via `statfs(ZFS_SUPER_MAGIC)` with `/proc/self/mountinfo` fallback. +pub fn is_zfs(path: &Path) -> bool { + let Some(existing) = path.ancestors().find(|p| !p.as_os_str().is_empty() && p.exists()) else { + return false; + }; + if is_statfs_zfs(existing) { + return true; + } + let Ok(mi) = std::fs::read_to_string("/proc/self/mountinfo") else { + return false; + }; + let canon = existing.canonicalize().ok(); + is_zfs_mountinfo(&mi, canon.as_deref().unwrap_or(existing)) +} + +/// Whether `statvfs(2)` reports `ST_RDONLY` on `path`. +pub fn is_statvfs_readonly(path: &Path) -> io::Result { + let c = cstr(path)?; + // SAFETY: `st` is plain zero-initialized data; `c` is a valid C string. + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: statvfs writes into `st`. + check(unsafe { libc::statvfs(c.as_ptr(), &mut st) } as _, &format!("statvfs {}", path.display()))?; + Ok((st.f_flag as u64) & (libc::ST_RDONLY as u64) != 0) +} + +/// Classifies an already-known read-only path (`EmergencyRo` vs `ReadOnly`) +/// by reading `/proc/self/mountinfo` and `/proc/mounts`. +pub fn inspect_readonly_kind(existing: &Path) -> ReadOnlyKind { + let canon = existing.canonicalize().ok(); + let targets = [canon.as_deref(), Some(existing)]; + if let Ok(mi) = std::fs::read_to_string("/proc/self/mountinfo") { + for t in targets.into_iter().flatten() { + if mountinfo_readonly(&mi, t) == Some(ReadOnlyKind::EmergencyRo) { + return ReadOnlyKind::EmergencyRo; + } + } + } + if let Ok(pm) = std::fs::read_to_string("/proc/mounts") { + for t in targets.into_iter().flatten() { + if proc_mounts_readonly(&pm, t) == Some(ReadOnlyKind::EmergencyRo) { + return ReadOnlyKind::EmergencyRo; + } + } + } + ReadOnlyKind::ReadOnly +} + +/// Fast-path read-only filesystem check on `path` (or its nearest existing +/// ancestor): 1 `statvfs` syscall when writable; inspects `/proc/self/mountinfo` +/// and `/proc/mounts` for `emergency_ro` only when `ST_RDONLY` is set. +pub fn detect_readonly_fs(path: &Path) -> Option { + let existing = path.ancestors().find(|p| !p.as_os_str().is_empty() && p.exists())?; + if is_statvfs_readonly(existing).ok()? { + Some(inspect_readonly_kind(existing)) + } else { + None + } +} + +/// Pure helper testing whether `osrelease` or WSL interop markers indicate WSL. +pub fn is_wsl_env(osrelease: &str, interop_exists: bool) -> bool { + if interop_exists { + return true; + } + let lower = osrelease.to_ascii_lowercase(); + lower.contains("microsoft") || lower.contains("wsl") +} + +/// True when running inside WSL 2 (Microsoft or custom WSL kernel / WSLInterop). +pub fn is_wsl() -> bool { + static WSL: std::sync::OnceLock = std::sync::OnceLock::new(); + *WSL.get_or_init(|| { + let interop = Path::new("/proc/sys/fs/binfmt_misc/WSLInterop").exists() + || Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late").exists() + || Path::new("/run/WSL").is_dir(); + let osrelease = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap_or_default(); + is_wsl_env(&osrelease, interop) + }) +} + +/// Formats an actionable error message for a read-only container storage filesystem. +pub fn format_readonly_storage_error(kind: ReadOnlyKind, wsl: bool, host_process: bool) -> String { + if wsl { + let state = match kind { + ReadOnlyKind::EmergencyRo => "was remounted read-only by Linux (emergency_ro)", + ReadOnlyKind::ReadOnly => "is mounted read-only (emergency_ro)", + }; + format!( + "Kiri's WSL2 disk (ext4.vhdx) {state} after an unclean shutdown or filesystem error. \ + To recover: 1) run `wsl --shutdown` in PowerShell; \ + 2) attach the disk bare with `wsl --mount \\ext4.vhdx --vhd --bare` (default `%LOCALAPPDATA%\\Kiri\\wsl\\kiri\\ext4.vhdx`); \ + 3) from another Linux distro in WSL, find the device with `lsblk` and run `sudo e2fsck -f -y -D /dev/`, then `wsl --unmount`; \ + or move/recreate storage in Settings -> Storage." + ) + } else if host_process { + match kind { + ReadOnlyKind::EmergencyRo => { + "Kiri's container storage filesystem (/var/lib/kiri) was remounted read-only by Linux (emergency_ro) after a filesystem error: check `dmesg` and run `fsck` to repair the filesystem, then restart Kiri.".to_owned() + } + ReadOnlyKind::ReadOnly => { + "Kiri's container storage filesystem (/var/lib/kiri) is mounted read-only: check `dmesg` and mount options, or run `fsck` to repair the filesystem, then restart Kiri.".to_owned() + } + } + } else { + match kind { + ReadOnlyKind::EmergencyRo => { + "Kiri's container storage filesystem (/var/lib/kiri) was remounted read-only by Linux (emergency_ro) after a filesystem error: check `dmesg`, restart Kiri, or run `fsck` on the VM data disk.".to_owned() + } + ReadOnlyKind::ReadOnly => { + "Kiri's container storage filesystem (/var/lib/kiri) is mounted read-only: check `dmesg`, restart Kiri, or run `fsck` on the VM data disk.".to_owned() + } + } + } +} + +pub fn readonly_storage_error(kind: ReadOnlyKind) -> io::Error { + let msg = format_readonly_storage_error(kind, is_wsl(), super::transport::is_host_process()); + io::Error::new(io::Error::from_raw_os_error(libc::EROFS).kind(), msg) +} + pub fn mkdir(p: &CStr, mode: libc::mode_t) { // SAFETY: `p` is a valid NUL-terminated string. EEXIST is expected and fine. unsafe { libc::mkdir(p.as_ptr(), mode) }; @@ -181,17 +515,89 @@ pub struct CloneArgs { pub const CLONE_INTO_CGROUP: u64 = 0x2_0000_0000; +/// A started child: its pid, and whether clone3 placed it in its cgroup. +pub struct Cloned { + pub pid: libc::pid_t, + /// False when the child was started with clone(2): the caller must move + /// it into `CloneArgs::cgroup` itself before letting it run. + pub into_cgroup: bool, +} + +/// Whether clone3 is unavailable rather than refusing this request: an old +/// kernel answers ENOSYS, and a seccomp filter (Docker's and Android's) may +/// answer ENOSYS or EPERM. glibc and runc fall back to clone(2) for these. +fn clone3_unavailable(errno: Option) -> bool { + matches!(errno, Some(code) if code == libc::ENOSYS || code == libc::EPERM) +} + +/// The clone(2) flags for `args`: clone3-only flags above 32 bits +/// (CLONE_INTO_CGROUP, CLONE_CLEAR_SIGHAND) and fields clone(2) has no place +/// for (the cgroup, a pidfd, set_tid, tls) are dropped, and clone3's separate +/// exit signal goes back into the low byte of the flags. CLONE_NEWCGROUP +/// goes too: clone3 places the child in its cgroup before making it, so the +/// namespace is rooted there; clone(2) cannot, and a namespace made now +/// would be rooted at the agent's cgroup. The caller unshares it after +/// moving the child. +fn clone_flags(args: &CloneArgs) -> libc::c_ulong { + ((args.flags & 0xffff_ffff & !(libc::CLONE_NEWCGROUP as u64)) | (args.exit_signal & 0xff)) as libc::c_ulong +} + /// Like fork(), but straight into new namespaces and a cgroup. Returns 0 in /// the child and the child's pid in the parent. /// +/// Uses clone3(2), which puts the child in its cgroup atomically. Where +/// clone3 is blocked (an old kernel, or a seccomp filter answering ENOSYS or +/// EPERM, as on Android/Droidspaces, #529), it falls back to clone(2), as +/// glibc and runc do, and reports `into_cgroup: false`. clone(2) cannot make +/// the cgroup namespace either, so the caller must move the child into its +/// cgroup and unshare CLONE_NEWCGROUP before it proceeds. +/// /// # Safety /// The caller must be single-threaded, as with fork(): the child gets a copy /// of this thread only, so no other thread may hold a lock it needs. -pub unsafe fn clone3(args: &CloneArgs) -> io::Result { +static CLONE3_STATE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0); + +/// True once `clone3(..., CLONE_INTO_CGROUP)` has succeeded in this process, +/// allowing later spawns/execs to skip creating the fallback `cgroup_ready` pipe. +pub fn clone3_works() -> bool { + CLONE3_STATE.load(std::sync::atomic::Ordering::Relaxed) == 1 +} + +pub unsafe fn clone3(args: &CloneArgs) -> io::Result { // SAFETY: `args` is a valid clone_args of the size passed; the caller // upholds the single-thread requirement. let ret = unsafe { libc::syscall(libc::SYS_clone3, args as *const CloneArgs, std::mem::size_of::()) }; - check(ret, "clone3").map(|p| p as libc::pid_t) + if ret >= 0 { + if ret > 0 { + CLONE3_STATE.store(1, std::sync::atomic::Ordering::Relaxed); + } + return Ok(Cloned { pid: ret as libc::pid_t, into_cgroup: true }); + } + let e = io::Error::last_os_error(); + if !clone3_unavailable(e.raw_os_error()) { + return Err(io::Error::new(e.kind(), format!("clone3: {e}"))); + } + CLONE3_STATE.store(2, std::sync::atomic::Ordering::Relaxed); + // SAFETY: as above. clone(2) has no cgroup, pidfd, set_tid, stack or tls + // arguments here: the child runs on a copy of this thread's stack, like + // fork(). Passing 0 for the four arguments after `flags` is identical on + // x86_64 and aarch64 (CONFIG_CLONE_BACKWARDS). The caller upholds + // single-threadedness, which that requires. + let ret = unsafe { + libc::syscall(libc::SYS_clone, clone_flags(args), 0 as libc::c_ulong, 0 as libc::c_ulong, 0 as libc::c_ulong, 0 as libc::c_ulong) + }; + if ret < 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("clone: {e}"))); + } + Ok(Cloned { pid: ret as libc::pid_t, into_cgroup: false }) +} + +/// Makes this thread's namespace view like `unshare(2)`: a new cgroup +/// namespace here is rooted at the caller's cgroup. +pub fn unshare(flags: libc::c_int) -> io::Result<()> { + // SAFETY: plain syscall on the calling thread. + check(unsafe { libc::unshare(flags) } as _, "unshare").map(drop) } /// The engine's own message as one line of the container's log: a value @@ -556,4 +962,142 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); assert_eq!(super::exec_failure(file.to_str().unwrap(), &err, super::Found { exists: true, dir: false }, false).0, 126, "{err}"); } + + /// Only a clone3 that is blocked (a seccomp filter answering ENOSYS or + /// EPERM, as Docker's and Android's do, #529) falls back to clone(2); + /// a refusal of the request itself is reported as it is. + #[test] + fn only_a_blocked_clone3_falls_back() { + let f = super::clone3_unavailable; + assert!(f(Some(libc::ENOSYS))); + assert!(f(Some(libc::EPERM))); + for code in [libc::EINVAL, libc::EBUSY, libc::EAGAIN, libc::ENOMEM] { + assert!(!f(Some(code)), "errno {code}"); + } + assert!(!f(None)); + } + + /// clone(2) cannot take CLONE_INTO_CGROUP (or any >32-bit clone3 flag such + /// as CLONE_CLEAR_SIGHAND), and a CLONE_NEWCGROUP made before the child is + /// in its cgroup would be rooted at the agent's, so all of those are + /// dropped; clone3's exit signal goes in the low byte, as clone(2) expects. + #[test] + fn clone2_flags_drop_what_it_cannot_place() { + const CLONE_CLEAR_SIGHAND: u64 = 0x1_0000_0000; + let args = super::CloneArgs { + flags: (libc::CLONE_NEWPID | libc::CLONE_NEWCGROUP) as u64 | super::CLONE_INTO_CGROUP | CLONE_CLEAR_SIGHAND, + exit_signal: libc::SIGCHLD as u64, + ..Default::default() + }; + let flags = super::clone_flags(&args) as u64; + assert_eq!(flags & libc::CLONE_NEWPID as u64, libc::CLONE_NEWPID as u64); + assert_eq!(flags & super::CLONE_INTO_CGROUP, 0); + assert_eq!(flags & CLONE_CLEAR_SIGHAND, 0); + assert_eq!(flags & libc::CLONE_NEWCGROUP as u64, 0); + assert_eq!(flags & 0xff, libc::SIGCHLD as u64); + } + + /// The real thing: a seccomp filter answering ENOSYS or EPERM for clone3, + /// as Android's and Docker's do (#529), must fall back to clone(2) instead + /// of failing the start. The filter is installed in a child process of + /// this test binary, so it does not outlive the test. + #[test] + fn blocked_clone3_falls_back_to_clone() { + if let Some(val) = std::env::var_os("KIRI_CLONE3_SEccomp") { + let code = if val == "EPERM" { libc::EPERM } else { libc::ENOSYS }; + install_clone3_denial(code); + // SAFETY: this helper process runs no other thread, as clone(2) + // without CLONE_VM needs; the child only calls _exit. + let cloned = unsafe { + super::clone3(&super::CloneArgs { exit_signal: libc::SIGCHLD as u64, ..Default::default() }) + } + .expect("a blocked clone3 must fall back to clone"); + assert!(!cloned.into_cgroup, "clone(2) cannot place the child in a cgroup"); + if cloned.pid == 0 { + // SAFETY: _exit neither unwinds nor runs destructors. + unsafe { libc::_exit(0) }; + } + let mut status = 0; + // SAFETY: waiting for the child just cloned. + let waited = unsafe { libc::waitpid(cloned.pid, &mut status, 0) }; + assert_eq!(waited, cloned.pid); + assert!(libc::WIFEXITED(status) && libc::WEXITSTATUS(status) == 0, "child status {status}"); + return; + } + let module = module_path!(); + let module = module.split_once("::").map_or(module, |(_, m)| m); + let name = format!("{module}::blocked_clone3_falls_back_to_clone"); + for kind in ["1", "EPERM"] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", &name, "--nocapture", "--test-threads=1"]) + .env("KIRI_CLONE3_SEccomp", kind) + .output() + .expect("spawn this test binary"); + assert!( + out.status.success(), + "the clone3-blocked helper ({kind}) failed:\n{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + } + } + + /// Installs a seccomp filter that makes clone3 return `errno`. + fn install_clone3_denial(errno: i32) { + #[repr(C)] + struct Insn { + code: u16, + jt: u8, + jf: u8, + k: u32, + } + #[repr(C)] + struct Prog { + len: u16, + filter: *const Insn, + } + const LD_W_ABS: u16 = 0x20; + const JEQ_K: u16 = 0x15; + const RET_K: u16 = 0x06; + const RET_ALLOW: u32 = 0x7fff_0000; + const RET_ERRNO: u32 = 0x0005_0000; + let insns = [ + Insn { code: LD_W_ABS, jt: 0, jf: 0, k: 0 }, // seccomp_data.nr + Insn { code: JEQ_K, jt: 0, jf: 1, k: libc::SYS_clone3 as u32 }, + Insn { code: RET_K, jt: 0, jf: 0, k: RET_ERRNO | errno as u32 }, + Insn { code: RET_K, jt: 0, jf: 0, k: RET_ALLOW }, + ]; + let prog = Prog { len: insns.len() as u16, filter: insns.as_ptr() }; + // SAFETY: valid prctl calls; `prog` lives until they return. + unsafe { + assert_eq!(libc::prctl(libc::PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0), 0, "no_new_privs: {}", io::Error::last_os_error()); + let n = libc::prctl(libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER as libc::c_ulong, &prog); + assert_eq!(n, 0, "seccomp: {}", io::Error::last_os_error()); + } + } + + #[test] + fn parses_readonly_mounts_and_formats_wsl_and_linux_diagnostics() { + use std::path::Path; + let healthy = "/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered 0 0\n"; + assert_eq!(super::proc_mounts_readonly(healthy, Path::new("/var/lib/kiri")), None); + + let emergency = "/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered,emergency_ro 0 0\ntmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0\n"; + assert_eq!(super::proc_mounts_readonly(emergency, Path::new("/var/lib/kiri/containers/abc")), Some(super::ReadOnlyKind::EmergencyRo)); + assert_eq!(super::proc_mounts_readonly(emergency, Path::new("/run/kiri")), None); + + let mountinfo = "25 1 8:48 / / rw,relatime - ext4 /dev/sdd rw,discard,errors=remount-ro,data=ordered,emergency_ro\n"; + assert_eq!(super::mountinfo_readonly(mountinfo, Path::new("/var/lib/kiri")), Some(super::ReadOnlyKind::EmergencyRo)); + + assert!(super::is_wsl_env("6.6.87.2-microsoft-standard-WSL2\n", false)); + assert!(super::is_wsl_env("6.18.58.1-1\n", true)); + assert!(!super::is_wsl_env("6.18.58.1-1-generic\n", false)); + + let wsl = super::format_readonly_storage_error(super::ReadOnlyKind::EmergencyRo, true, true); + assert!(wsl.contains("ext4.vhdx") && wsl.contains("emergency_ro") && wsl.contains("e2fsck -f -y -D"), "{wsl}"); + let host = super::format_readonly_storage_error(super::ReadOnlyKind::EmergencyRo, false, true); + assert!(host.contains("/var/lib/kiri") && host.contains("fsck"), "{host}"); + let vm = super::format_readonly_storage_error(super::ReadOnlyKind::ReadOnly, false, false); + assert!(vm.contains("VM data disk"), "{vm}"); + } } diff --git a/crates/kiri-init/src/linux/tarnum.rs b/crates/kiri-init/src/linux/tarnum.rs new file mode 100644 index 000000000..241c128d7 --- /dev/null +++ b/crates/kiri-init/src/linux/tarnum.rs @@ -0,0 +1,561 @@ +//! Tar numbers as Go's `archive/tar`, so Docker, reads them: a numeric header +//! field that is empty, only NULs or spaces, is 0. tar-rs refuses one +//! ("numeric field was not a number"), and some image builders leave a +//! directory's size, uid and gid empty, so their layers did not unpack (#618). + +use std::io::{self, Read}; + +const BLOCK: usize = 512; + +/// The size field, which tar-rs reads in every header, as (start, end). +const SIZE: (usize, usize) = (124, 136); +/// mode, uid, gid and mtime, which it reads for an entry it unpacks, not for +/// an extension header (PAX, GNU long name): tar-rs itself leaves those +/// empty there. +const ENTRY: [(usize, usize); 4] = [(100, 108), (108, 116), (116, 124), (136, 148)]; +/// devmajor and devminor, which it reads for a device of a ustar or GNU +/// header only. +const DEVICE: [(usize, usize); 2] = [(329, 337), (337, 345)]; +/// realsize, which it reads for a GNU sparse header only. +const REALSIZE: [(usize, usize); 1] = [(483, 495)]; + +/// Passes a tar stream through, writing each empty number of a header as 0 +/// and making that header's checksum again. Only a header whose checksum is +/// right is touched: a broken one goes on as it came, for tar-rs to refuse. +/// Headers are found where tar-rs looks for them: after each entry's data, +/// whose size a PAX `size` record overrides, and after a GNU sparse header's +/// extension blocks. A zero block ends the archive for tar-rs, and from there +/// on everything passes as it is. +pub struct GoNumbers { + inner: R, + block: [u8; BLOCK], + /// The bytes of `block` read, and how many of them have gone out. + len: usize, + at: usize, + /// Bytes of entry data, with padding, before the next header. + data: u64, + /// A GNU sparse extension block comes next. + sparse_ext: bool, + /// The data of the PAX `x` entry being read, and how many unpadded bytes + /// of it remain (tar-rs skips the block padding after it). + pax: Option<(Vec, u64)>, + /// The size a PAX `x` entry gave the entry after it. + pax_size: Option, + passthrough: bool, +} + +impl GoNumbers { + pub fn new(inner: R) -> GoNumbers { + GoNumbers { inner, block: [0; BLOCK], len: 0, at: 0, data: 0, sparse_ext: false, pax: None, pax_size: None, passthrough: false } + } + + /// The next block, read whole if the stream has one. + fn next_block(&mut self) -> io::Result<()> { + let mut len = 0; + while len < BLOCK { + match self.inner.read(&mut self.block[len..]) { + Ok(0) => break, + Ok(n) => len += n, + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => return Err(e), + } + } + (self.len, self.at) = (len, 0); + if len < BLOCK { + // The end, or a cut-off block tar-rs will report. + self.passthrough = true; + } + Ok(()) + } + + fn header(&mut self) { + let h = &mut self.block; + if h.iter().all(|&b| b == 0) || Some(checksum(h)) != octal(&h[148..156]) { + self.passthrough = true; + return; + } + let ustar = &h[257..263] == b"ustar\0" && &h[263..265] == b"00"; + let gnu = &h[257..263] == b"ustar " && &h[263..265] == b" \0"; + let kind = h[156]; + let extension = matches!(kind, b'L' | b'K' | b'x' | b'g'); + let continues = (ustar || gnu) && matches!(kind, b'L' | b'K' | b'x'); + let device = (ustar || gnu) && matches!(kind, b'3' | b'4'); + let sparse = gnu && kind == b'S'; + let entry: &[(usize, usize)] = if extension { &[] } else { &ENTRY }; + let devices: &[(usize, usize)] = if device { &DEVICE } else { &[] }; + let realsize: &[(usize, usize)] = if sparse { &REALSIZE } else { &[] }; + let mut changed = false; + for &(a, b) in std::iter::once(&SIZE).chain(entry).chain(devices).chain(realsize) { + if h[a..b].iter().all(|&c| c == 0 || c == b' ') { + h[a..b - 1].fill(b'0'); + h[b - 1] = 0; + changed = true; + } + } + if changed { + let sum = format!("{:06o}\0 ", checksum(h)); + h[148..156].copy_from_slice(sum.as_bytes()); + } + + let Some(mut size) = number(&h[SIZE.0..SIZE.1]) else { + self.passthrough = true; + return; + }; + if !continues + && let Some(pax) = self.pax_size.take() + && !extension + { + size = pax; + } + self.sparse_ext = sparse && h[482] == 1; + self.data = size.div_ceil(BLOCK as u64).saturating_mul(BLOCK as u64); + if kind == b'x' && (ustar || gnu) { + self.pax = Some((Vec::new(), size)); + self.end_of_data(); + } + } + + /// An entry's data has all gone: a PAX entry's records take effect. + fn end_of_data(&mut self) { + if self.data == 0 + && let Some((pax, _)) = self.pax.take() + { + self.pax_size = pax_size(&pax); + } + } +} + +impl Read for GoNumbers { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + loop { + if buf.is_empty() { + return Ok(0); + } + if self.at < self.len { + let n = buf.len().min(self.len - self.at); + buf[..n].copy_from_slice(&self.block[self.at..self.at + n]); + self.at += n; + return Ok(n); + } + if self.passthrough { + return self.inner.read(buf); + } + if self.sparse_ext { + self.next_block()?; + self.sparse_ext = self.len == BLOCK && self.block[504] == 1; + continue; + } + if self.data > 0 { + let want = buf.len().min(usize::try_from(self.data).unwrap_or(usize::MAX)); + let n = self.inner.read(&mut buf[..want])?; + if n == 0 { + return Ok(0); + } + if let Some((pax, left)) = &mut self.pax { + let take = (n as u64).min(*left) as usize; + pax.extend_from_slice(&buf[..take]); + *left -= take as u64; + } + self.data -= n as u64; + self.end_of_data(); + return Ok(n); + } + self.next_block()?; + if !self.passthrough { + self.header(); + } + } + } +} + +/// The header's checksum as tar-rs reckons it: its bytes, the checksum field +/// counted as spaces. +fn checksum(h: &[u8; BLOCK]) -> u64 { + h[..148].iter().chain(&h[156..]).map(|&b| u64::from(b)).sum::() + 8 * 32 +} + +/// An octal field as tar-rs reads it: up to its first NUL, spaces trimmed. +fn octal(field: &[u8]) -> Option { + let text = field.split(|&b| b == 0).next().unwrap_or_default(); + u64::from_str_radix(std::str::from_utf8(text).ok()?.trim(), 8).ok() +} + +/// A numeric field, octal or (high bit set) base-256, as tar-rs reads it. +fn number(field: &[u8]) -> Option { + if field[0] & 0x80 == 0 { + return octal(field); + } + let (first, rest) = if field.len() == 8 { (u64::from(field[0] ^ 0x80), &field[1..]) } else { (0, &field[field.len() - 8..]) }; + Some(rest.iter().fold(first, |n, &b| (n << 8) | u64::from(b))) +} + +/// The `size` record of PAX extension data, the first one, as tar-rs takes it. +fn pax_size(data: &[u8]) -> Option { + for line in data.split(|&b| b == b'\n') { + if line.is_empty() { + break; + } + let space = line.iter().position(|&b| b == b' ')?; + let len: usize = std::str::from_utf8(&line[..space]).ok()?.parse().ok()?; + if line.len() + 1 != len { + return None; + } + let rest = &line[space + 1..]; + let eq = rest.iter().position(|&b| b == b'=')?; + if &rest[..eq] == b"size" { + return std::str::from_utf8(&rest[eq + 1..]).ok()?.parse().ok(); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::*; + + fn header(path: &str, kind: tar::EntryType, size: u64) -> tar::Header { + let mut h = tar::Header::new_ustar(); + h.set_path(path).unwrap(); + h.set_entry_type(kind); + h.set_size(size); + h.set_mode(0o755); + h.set_uid(0); + h.set_gid(0); + h.set_mtime(1); + h.set_cksum(); + h + } + + /// What the servicebus-emulator layer has (#618): a directory whose size, + /// uid and gid are all NULs, its checksum right. + fn blank(h: &mut tar::Header) { + let b = h.as_mut_bytes(); + b[108..136].fill(0); + let sum = format!("{:06o}\0 ", checksum(b)); + b[148..156].copy_from_slice(sum.as_bytes()); + } + + fn archive(blank_dir: bool) -> Vec { + let mut b = tar::Builder::new(Vec::new()); + // A PAX header first, as in the layer, and a long name after it. + b.append_pax_extensions([("mtime", &b"1.5"[..])]).unwrap(); + let mut dir = header("app", tar::EntryType::Directory, 0); + if blank_dir { + blank(&mut dir); + } + b.append(&dir, io::empty()).unwrap(); + let long = format!("app/{}", "n".repeat(120)); + b.append_data(&mut header("x", tar::EntryType::Regular, 5), &long, &b"hello"[..]).unwrap(); + b.append(&header("app/b", tar::EntryType::Regular, 600), &[7u8; 600][..]).unwrap(); + b.into_inner().unwrap() + } + + fn entries(bytes: &[u8]) -> io::Result)>> { + let mut a = tar::Archive::new(GoNumbers::new(bytes)); + let mut out = Vec::new(); + for e in a.entries()? { + let mut e = e?; + let mut data = Vec::new(); + e.read_to_end(&mut data)?; + out.push((e.path()?.to_string_lossy().into_owned(), e.header().uid()?, data)); + } + Ok(out) + } + + #[test] + fn empty_numbers_read_as_zero_like_go() { + let bytes = archive(true); + let err = tar::Archive::new(&bytes[..]).entries().unwrap().find_map(Result::err).expect("tar-rs alone refuses it"); + assert!(err.to_string().contains("numeric field was not a number"), "{err}"); + let got = entries(&bytes).unwrap(); + assert_eq!(got.iter().map(|e| e.0.as_str()).collect::>(), ["app", &format!("app/{}", "n".repeat(120)), "app/b"]); + assert_eq!(got[0].1, 0, "an empty uid is root's"); + assert_eq!(got[1].2, b"hello"); + assert_eq!(got[2].2, [7u8; 600]); + } + + /// Passes `bytes` through, failing at the first byte that changed. + fn assert_unchanged(bytes: &[u8]) { + let mut out = Vec::new(); + GoNumbers::new(bytes).read_to_end(&mut out).unwrap(); + if let Some(i) = out.iter().zip(bytes).position(|(a, b)| a != b) { + panic!("byte {i} (block {}, offset {}) changed: {:?} -> {:?}", i / BLOCK, i % BLOCK, bytes[i] as char, out[i] as char); + } + assert_eq!(out.len(), bytes.len()); + } + + #[test] + fn a_complete_archive_passes_unchanged() { + let bytes = archive(false); + assert_unchanged(&bytes); + } + + #[test] + fn data_that_looks_like_a_header_is_left_alone() { + // A file holding a header with empty numbers, then a PAX size that + // makes the next entry's data longer than its header says. + let mut inner = header("fake", tar::EntryType::Directory, 0); + blank(&mut inner); + let mut b = tar::Builder::new(Vec::new()); + b.append(&header("tarball", tar::EntryType::Regular, 512), &inner.as_bytes()[..]).unwrap(); + b.append_pax_extensions([("size", &b"512"[..])]).unwrap(); + b.append(&header("sized", tar::EntryType::Regular, 0), &inner.as_bytes()[..]).unwrap(); + let bytes = b.into_inner().unwrap(); + assert_unchanged(&bytes); + } + + #[test] + fn a_header_with_a_wrong_checksum_is_not_mended() { + let mut bytes = archive(true); + // The directory's header follows the PAX header and its data. + let dir = bytes.chunks(BLOCK).position(|b| b.starts_with(b"app\0")).unwrap() * BLOCK; + bytes[dir + 150] ^= 1; + assert_unchanged(&bytes); + assert!(entries(&bytes).is_err()); + } + + #[test] + fn numbers_and_pax_records_parse_as_in_tar_rs() { + assert_eq!(octal(b"0000755\0"), Some(0o755)); + assert_eq!(octal(b" 755 \0\0\0"), Some(0o755)); + assert_eq!(octal(b"\0\0\0\0"), None); + assert_eq!(number(&[0x80, 0, 0, 0, 0, 0, 1, 0]), Some(256)); + assert_eq!(number(&[0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1]), Some(513)); + assert_eq!(pax_size(b"20 path=a/b/c/d/e/f\n12 size=600\n"), Some(600)); + assert_eq!(pax_size(b"12 size=600\n11 size=10\n"), Some(600)); + assert_eq!(pax_size(b"28 mtime=1768240195.7895585\n\0\0\0"), None); + assert_eq!(pax_size(b"99 size=1\n"), None); + assert_eq!(pax_size(b"11 size=512"), None, "missing trailing newline"); + assert_eq!(pax_size(b"24 comment=a\n12 size=512\n"), None, "embedded newline breaks line length"); + assert_eq!(pax_size(b"11 foobar!\n12 size=512\n"), None, "record without '=' aborts parsing"); + } + + /// A reader that yields at most `step` bytes at a time, and `Interrupted` + /// every other call, as a decompressor or pipe may. + struct Trickle<'a> { + bytes: &'a [u8], + step: usize, + tick: usize, + } + + impl Read for Trickle<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.tick += 1; + if self.tick.is_multiple_of(2) { + return Err(io::Error::from(io::ErrorKind::Interrupted)); + } + let n = buf.len().min(self.step).min(self.bytes.len()); + buf[..n].copy_from_slice(&self.bytes[..n]); + self.bytes = &self.bytes[n..]; + Ok(n) + } + } + + #[test] + fn short_reads_and_interrupted_reads_stay_in_sync() { + let raw = archive(true); + let mut expected = Vec::new(); + GoNumbers::new(&raw[..]).read_to_end(&mut expected).unwrap(); + + for step in [1, 7, 73, 511, 512, 513] { + let mut r = GoNumbers::new(Trickle { bytes: &raw, step, tick: 0 }); + let mut got = Vec::new(); + let mut chunk = vec![0u8; step]; + loop { + match r.read(&mut chunk) { + Ok(0) => break, + Ok(n) => got.extend_from_slice(&chunk[..n]), + Err(e) if e.kind() == io::ErrorKind::Interrupted => {} + Err(e) => panic!("step {step}: {e}"), + } + } + assert_eq!(got, expected, "step {step}"); + } + } + + #[test] + fn pax_size_tracks_tar_rs_across_global_longname_and_padding() { + let mut fake = header("fake", tar::EntryType::Directory, 0); + blank(&mut fake); + let mut real = header("after", tar::EntryType::Directory, 0); + blank(&mut real); + + // 1. PAX `x` followed by GNU `L` longname: `x`'s size=512 still applies + // to the regular file after `L`, so its 512-byte payload (a blank-number + // header) is left untouched, while `real` after it is mended. + let mut b = tar::Builder::new(Vec::new()); + b.append_pax_extensions([("size", &b"512"[..])]).unwrap(); + let long = format!("dir/{}", "l".repeat(120)); + let mut lhdr = tar::Header::new_gnu(); + lhdr.set_entry_type(tar::EntryType::GNULongName); + lhdr.set_size(long.len() as u64 + 1); + lhdr.set_cksum(); + let mut ldata = long.clone().into_bytes(); + ldata.push(0); + b.append(&lhdr, &ldata[..]).unwrap(); + let mut bytes = b.into_inner().unwrap(); + bytes.truncate(bytes.len() - 2 * BLOCK); + bytes.extend_from_slice(header("short", tar::EntryType::Regular, 0).as_bytes()); + let payload_at = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let mut out = Vec::new(); + GoNumbers::new(&bytes[..]).read_to_end(&mut out).unwrap(); + assert_eq!(&out[payload_at..payload_at + BLOCK], fake.as_bytes(), "file payload after PAX x + GNU L must not be touched"); + let got = entries(&bytes).unwrap(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].0, long); + assert_eq!(got[0].2, fake.as_bytes()); + assert_eq!(got[1].0, "after"); + + // 2. PAX `x` (size=512) followed by PAX global `g` (size=0): tar-rs + // yields `g` and drops `x`'s pax_extensions, so the next entry + // ("zero", header size=0) has 0 bytes of data, and `real` right + // after it is a header that must be mended. + let mut b = tar::Builder::new(Vec::new()); + b.append_pax_extensions([("size", &b"512"[..])]).unwrap(); + let mut bytes = b.into_inner().unwrap(); + bytes.truncate(bytes.len() - 2 * BLOCK); + let mut g = header("pax_global", tar::EntryType::XGlobalHeader, 0); + g.set_cksum(); + bytes.extend_from_slice(g.as_bytes()); + bytes.extend_from_slice(header("zero", tar::EntryType::Regular, 0).as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let got = entries(&bytes).unwrap(); + assert_eq!(got.iter().map(|e| e.0.as_str()).collect::>(), ["pax_global", "zero", "after"]); + + // 3. PAX `x` whose unpadded size is 11 ("11 foo=bar\n"), with + // "12 size=512\n" hidden in the 512-byte block padding after byte 11: + // tar-rs reads only 11 bytes of `x`, so "zero" has size 0 and `real` + // right after it is a header that must be mended. + let mut x = tar::Header::new_ustar(); + x.set_entry_type(tar::EntryType::XHeader); + x.set_size(11); + x.set_cksum(); + let mut xblock = [0u8; BLOCK]; + xblock[..23].copy_from_slice(b"11 foo=bar\n12 size=512\n"); + let mut bytes = Vec::new(); + bytes.extend_from_slice(x.as_bytes()); + bytes.extend_from_slice(&xblock); + bytes.extend_from_slice(header("zero", tar::EntryType::Regular, 0).as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let got = entries(&bytes).unwrap(); + assert_eq!(got.iter().map(|e| e.0.as_str()).collect::>(), ["zero", "after"]); + } + + #[test] + fn base256_size_and_symlink_with_nonzero_size_keep_payload_untouched() { + let mut fake = header("fake", tar::EntryType::Directory, 0); + blank(&mut fake); + let mut real = header("after", tar::EntryType::Directory, 0); + blank(&mut real); + + // 1. Regular file with GNU base-256 size = 512 holding `fake` as data. + let mut h256 = header("big", tar::EntryType::Regular, 0); + h256.as_mut_bytes()[124..136].copy_from_slice(&[0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0]); + h256.set_cksum(); + + // 2. Symlink (`2`) with non-zero size = 512: tar-rs advances `self.next` + // past the 512-byte data block (`fake`), so GoNumbers must treat it + // as data and not mutate it, then mend `real` after it. + let mut sym = header("sym", tar::EntryType::Symlink, 512); + sym.set_link_name("target").unwrap(); + sym.set_cksum(); + + // 3. Character device (`3`) with empty mode, uid, gid, size, mtime, + // devmajor and devminor. + let mut chr = header("null", tar::EntryType::Char, 0); + { + let b = chr.as_mut_bytes(); + b[100..148].fill(0); + b[329..345].fill(0); + let sum = format!("{:06o}\0 ", checksum(b)); + b[148..156].copy_from_slice(sum.as_bytes()); + } + + let mut bytes = Vec::new(); + bytes.extend_from_slice(h256.as_bytes()); + let p1 = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(sym.as_bytes()); + let p2 = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(chr.as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let mut out = Vec::new(); + GoNumbers::new(&bytes[..]).read_to_end(&mut out).unwrap(); + assert_eq!(&out[p1..p1 + BLOCK], fake.as_bytes(), "base-256 file payload must not be mutated"); + assert_eq!(&out[p2..p2 + BLOCK], fake.as_bytes(), "symlink skipped data block must not be mutated"); + + let mut a = tar::Archive::new(GoNumbers::new(&bytes[..])); + let mut names = Vec::new(); + for e in a.entries().unwrap() { + let e = e.unwrap(); + if e.header().entry_type().is_character_special() { + assert_eq!(e.header().device_major().unwrap(), Some(0)); + assert_eq!(e.header().device_minor().unwrap(), Some(0)); + } + names.push(e.path().unwrap().to_string_lossy().into_owned()); + } + assert_eq!(names, ["big", "sym", "null", "after"]); + } + + #[test] + fn gnu_sparse_extended_headers_and_data_stay_in_sync() { + let mut fake = header("fake", tar::EntryType::Directory, 0); + blank(&mut fake); + let mut real = header("after", tar::EntryType::Directory, 0); + blank(&mut real); + + // GNU sparse header ('S') with isextended = 1 (offset 482), two + // GnuExtSparseHeader blocks (first with offset 504 = 1, second with 0), + // and 1 block (512 bytes) of sparse data holding `fake`. + let mut sp = tar::Header::new_gnu(); + sp.set_path("sparse.bin").unwrap(); + sp.set_entry_type(tar::EntryType::GNUSparse); + sp.set_mode(0o644); + sp.set_uid(0); + sp.set_gid(0); + sp.set_mtime(1); + sp.set_size(512); + { + let gnu = sp.as_gnu_mut().unwrap(); + gnu.sparse[0].set_offset(0); + gnu.sparse[0].set_length(512); + gnu.set_is_extended(true); + gnu.set_real_size(512); + } + sp.set_cksum(); + + let mut ext1 = [0u8; BLOCK]; + ext1[504] = 1; + let ext2 = [0u8; BLOCK]; + + let mut bytes = Vec::new(); + bytes.extend_from_slice(sp.as_bytes()); + bytes.extend_from_slice(&ext1); + bytes.extend_from_slice(&ext2); + let payload_at = bytes.len(); + bytes.extend_from_slice(fake.as_bytes()); + bytes.extend_from_slice(real.as_bytes()); + bytes.extend_from_slice(&[0u8; 2 * BLOCK]); + + let mut out = Vec::new(); + GoNumbers::new(&bytes[..]).read_to_end(&mut out).unwrap(); + assert_eq!(&out[payload_at..payload_at + BLOCK], fake.as_bytes(), "sparse file payload must not be mutated"); + + let got = entries(&bytes).unwrap(); + assert_eq!(got.len(), 2); + assert_eq!(got[0].0, "sparse.bin"); + assert_eq!(got[0].2, fake.as_bytes()); + assert_eq!(got[1].0, "after"); + } +} diff --git a/crates/kiri-init/src/linux/transport.rs b/crates/kiri-init/src/linux/transport.rs index e8c101210..bccda6900 100644 --- a/crates/kiri-init/src/linux/transport.rs +++ b/crates/kiri-init/src/linux/transport.rs @@ -115,34 +115,71 @@ pub fn dial_within(port: u32, timeout: std::time::Duration) -> io::Result Vec<[u8; 4]> { - let parse = |path: &str| nameservers(&std::fs::read_to_string(path).unwrap_or_default()); - let direct = parse("/etc/resolv.conf"); - if direct.is_empty() { parse("/run/systemd/resolve/resolv.conf") } else { direct } + let read = |path: &str| std::fs::read_to_string(path).unwrap_or_default(); + host_dns_from(&read("/etc/resolv.conf"), &read("/run/systemd/resolve/resolv.conf")) } -/// A resolv.conf's IPv4 nameservers but loopback ones (127.0.0.0/8). An -/// address of this machine's on another interface, or on `lo` outside -/// 127/8 (WSL's 10.255.255.254), is kept: `net::local_resolver` tells it. -fn nameservers(text: &str) -> Vec<[u8; 4]> { - text.lines() - .filter_map(|l| l.strip_prefix("nameserver")) +fn host_dns_from(resolv_conf: &str, systemd_resolv_conf: &str) -> Vec<[u8; 4]> { + let mut out = nameservers(resolv_conf, true); + if out.iter().all(|ip| ip[0] == 127) { + for ip in nameservers(systemd_resolv_conf, false) { + if !out.contains(&ip) { + out.push(ip); + } + } + } + out +} + +/// A resolv.conf's IPv4 nameservers, keeping loopback ones (`127.0.0.0/8`) +/// only when `allow_loopback` is set. An address of this machine's on another +/// interface, or on `lo` outside 127/8 (WSL's 10.255.255.254), is always +/// kept: `net::local_resolver` tells it. +fn nameservers(text: &str, allow_loopback: bool) -> Vec<[u8; 4]> { + let mut out = Vec::new(); + for ip in text + .lines() + .filter_map(|l| l.trim().strip_prefix("nameserver")) + .filter(|rest| rest.starts_with([' ', '\t'])) .filter_map(|ip| ip.trim().parse::().ok()) - .filter(|ip| !ip.is_loopback()) + .filter(|ip| allow_loopback || !ip.is_loopback()) .map(|ip| ip.octets()) - .collect() + { + if !out.contains(&ip) { + out.push(ip); + } + } + out } #[cfg(test)] mod tests { #[test] - fn host_resolvers_skip_loopback_ones_but_keep_wsls() { - // systemd-resolved's stub: its upstreams are read instead. - assert!(super::nameservers("nameserver 127.0.0.53\noptions edns0 trust-ad\n").is_empty()); + fn host_resolvers_keep_loopback_stub_with_systemd_fallbacks_and_keep_wsls() { + // systemd-resolved's stub alone (no /run/systemd/resolve/resolv.conf): + // kept so the host-netns agent forwards container lookups to 127.0.0.53. + assert_eq!(super::host_dns_from("nameserver 127.0.0.53\noptions edns0 trust-ad\n", ""), [[127, 0, 0, 53]]); + // Stub with systemd-resolved's upstream file: stub first (split-DNS), + // then non-loopback upstreams as fallbacks if nothing listens on the stub. + assert_eq!( + super::host_dns_from("nameserver 127.0.0.53\n", "nameserver 127.0.0.53\nnameserver 168.63.129.16\n"), + [[127, 0, 0, 53], [168, 63, 129, 16]] + ); + // Empty /etc/resolv.conf falls back to systemd-resolved's upstreams. + assert_eq!(super::host_dns_from("", "nameserver 10.0.2.3\n"), [[10, 0, 2, 3]]); + // Non-loopback /etc/resolv.conf is used as-is without mixing in stale systemd files. + assert_eq!( + super::host_dns_from("nameserver 192.168.5.2\nnameserver fe80::1\n", "nameserver 10.0.2.3\n"), + [[192, 168, 5, 2]] + ); // WSL 2's forwarder is on `lo` but outside 127/8: kept, and then // asked through the agent (net::local_resolver). - assert_eq!(super::nameservers("# generated by WSL\nnameserver 10.255.255.254\n"), [[10, 255, 255, 254]]); - assert_eq!(super::nameservers("nameserver 192.168.5.2\nnameserver fe80::1\n"), [[192, 168, 5, 2]]); + assert_eq!(super::host_dns_from("# generated by WSL\nnameserver 10.255.255.254\n", ""), [[10, 255, 255, 254]]); } } diff --git a/crates/kiri-init/src/linux/trim.rs b/crates/kiri-init/src/linux/trim.rs index bed2e913a..f3cdd05e2 100644 --- a/crates/kiri-init/src/linux/trim.rs +++ b/crates/kiri-init/src/linux/trim.rs @@ -59,8 +59,18 @@ fn run(mountpoint: &str) { } } -fn trim(mountpoint: &str) -> io::Result<()> { +/// Runs `FITRIM` on `mountpoint` and returns the trimmed byte count reported +/// by the kernel (`fstrim_range.len`). Single-threaded and safe from the agent loop. +pub(super) fn trim(mountpoint: &str) -> io::Result { let disk = File::open(mountpoint)?; + // Commit any pending ext4 journal transactions (e.g. a `docker image prune` + // or `docker volume rm` that finished moments ago) before FITRIM scans free + // block bitmaps; otherwise jbd2 still pins those blocks and marks the block + // group trimmed. + // SAFETY: syncfs takes any valid open file descriptor on the filesystem. + unsafe { + libc::syncfs(disk.as_raw_fd()); + } let mut range = FstrimRange { start: 0, len: u64::MAX, @@ -70,5 +80,25 @@ fn trim(mountpoint: &str) -> io::Result<()> { if unsafe { libc::ioctl(disk.as_raw_fd(), FITRIM, &mut range) } < 0 { return Err(io::Error::last_os_error()); } - Ok(()) + Ok(range.len) +} + +/// Reports `(in_use, capacity)` in bytes for the filesystem mounted at +/// `mountpoint`, using `statvfs` (`in_use = (blocks - bfree) * frsize`, +/// `capacity = blocks * frsize`). Uses `f_bfree` rather than `f_bavail` +/// because `FITRIM` discards free blocks (`f_bfree`), never root-reserved +/// non-free blocks. +pub(super) fn stat(mountpoint: &str) -> io::Result<(u64, u64)> { + let path = std::ffi::CString::new(mountpoint).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + // SAFETY: statvfs fills a zero-initialized struct for a valid NUL-terminated path. + let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(path.as_ptr(), &mut s) } != 0 { + return Err(io::Error::last_os_error()); + } + let frsize = if s.f_frsize > 0 { s.f_frsize as u64 } else { s.f_bsize as u64 }; + let blocks = s.f_blocks as u64; + let bfree = s.f_bfree as u64; + let in_use = blocks.saturating_sub(bfree).saturating_mul(frsize); + let capacity = blocks.saturating_mul(frsize); + Ok((in_use, capacity)) } diff --git a/crates/kiri-init/src/linux/volmount.rs b/crates/kiri-init/src/linux/volmount.rs index 89fed5c82..6941be8f2 100644 --- a/crates/kiri-init/src/linux/volmount.rs +++ b/crates/kiri-init/src/linux/volmount.rs @@ -1,24 +1,387 @@ //! Volumes with the local driver's options (`type=nfs`, `type=tmpfs`, -//! `type=none,o=bind`, `type=cifs`): the guest mounts the device at the -//! volume's own path the first time a container starts with it, as Docker's -//! local driver does, and the container binds that path in like any other -//! volume. The mount stays until the volume is removed or the VM stops. +//! `type=none,o=bind`, `type=cifs`), plus sparse loopback `ext4` backing for +//! `kiri-k8s` when `/var/lib/kiri/volumes` sits on ZFS (#607): the guest +//! mounts the device at the volume's own path the first time a container +//! starts with it, as Docker's local driver does, and the container binds +//! that path in like any other volume. Driver-option mounts stay until the +//! volume is removed or the VM stops; `kiri-k8s` loopback `ext4` mounts +//! unmount cleanly when the last container using them stops, on volume +//! removal, or on agent sweep. -use std::ffi::CString; -use std::fs; -use std::io; +use std::collections::HashMap; +use std::ffi::{CString, OsStr, OsString}; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Seek, SeekFrom}; +use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd}; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; /// Where volumes live; nothing outside it is ever mounted over. const ROOT: &str = "/var/lib/kiri/volumes/"; +/// Data directory of Kiri's Kubernetes (`k3s`) named volume. +pub const K8S_VOLUME_DATA: &str = "/var/lib/kiri/volumes/kiri-k8s/_data"; +/// Sparse ext4 backing image stored beside `_data` inside `/var/lib/kiri/volumes/kiri-k8s`. +const K8S_EXT4_IMAGE: &str = "ext4.img"; +const K8S_EXT4_TMP: &str = ".ext4.img.tmp"; +/// Logical sparse image size (64 GiB; near-zero initial allocated blocks on ZFS). +const K8S_EXT4_SIZE_BYTES: u64 = 64 << 30; + +const EXT4_SUPER_OFFSET: u64 = 1024; +const EXT4_SUPER_MAGIC_OFFSET: u64 = 0x38; +const EXT4_SUPER_MAGIC: u16 = 0xEF53; + +// Linux constants (identical across x86_64 and aarch64). +const LOOP_SET_FD: libc::Ioctl = 0x4C00 as libc::Ioctl; +const LOOP_CLR_FD: libc::Ioctl = 0x4C01 as libc::Ioctl; +const LOOP_SET_STATUS64: libc::Ioctl = 0x4C04 as libc::Ioctl; +const LOOP_GET_STATUS64: libc::Ioctl = 0x4C05 as libc::Ioctl; +const LOOP_CTL_GET_FREE: libc::Ioctl = 0x4C82 as libc::Ioctl; +const LO_FLAGS_AUTOCLEAR: u32 = 4; +const LO_NAME_SIZE: usize = 64; +const LO_KEY_SIZE: usize = 32; +const LOOP_MAJOR: u32 = 7; + +#[repr(C)] +#[derive(Clone, Copy)] +struct LoopInfo64 { + lo_device: u64, + lo_inode: u64, + lo_rdevice: u64, + lo_offset: u64, + lo_sizelimit: u64, + lo_number: u32, + lo_encrypt_type: u32, + lo_encrypt_key_size: u32, + lo_flags: u32, + lo_file_name: [u8; LO_NAME_SIZE], + lo_crypt_name: [u8; LO_NAME_SIZE], + lo_encrypt_key: [u8; LO_KEY_SIZE], + lo_init: [u64; 2], +} + +impl Default for LoopInfo64 { + fn default() -> Self { + // SAFETY: LoopInfo64 is plain integer/byte kernel UAPI data. + unsafe { std::mem::zeroed() } + } +} + +#[derive(Default)] +struct LoopRefs { + counts: HashMap, +} + +impl LoopRefs { + fn acquire(&mut self, path: &str) { + *self.counts.entry(path.to_owned()).or_insert(0) += 1; + } + + /// Releases one holder; returns true when no holders remain and the mount + /// should be unmounted. + fn release(&mut self, path: &str) -> bool { + match self.counts.get_mut(path) { + Some(n) if *n > 1 => { + *n -= 1; + false + } + _ => { + self.counts.remove(path); + true + } + } + } + + fn clear(&mut self, path: &str) { + self.counts.remove(path); + } +} + +fn loop_refs() -> &'static Mutex { + static REFS: OnceLock> = OnceLock::new(); + REFS.get_or_init(|| Mutex::new(LoopRefs::default())) +} + fn invalid(what: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidInput, what.to_owned()) } +/// Whether `/proc/self/mountinfo` text lists `path` as an active mount point. +fn mounted_in(mountinfo: &str, path: &str) -> bool { + mountinfo.lines().any(|line| { + let Some((before, _)) = line.split_once(" - ") else { return false }; + before.split_whitespace().nth(4).is_some_and(|mp| super::sys::unescape_mount_path(mp) == path) + }) +} + /// Whether `path` is a mount point in this mount namespace. pub fn mounted(path: &str) -> bool { let Ok(info) = fs::read_to_string("/proc/self/mountinfo") else { return false }; - info.lines().any(|l| l.split(' ').nth(4) == Some(path)) + mounted_in(&info, path) +} + +/// Whether `path` is the `kiri-k8s` named volume's `_data` directory. +pub fn is_k8s_volume_data(path: &str) -> bool { + path == K8S_VOLUME_DATA +} + +/// Path of the sparse ext4 image stored beside a volume's `_data` directory. +pub fn k8s_ext4_image_path(data_path: &Path) -> Option { + if data_path.file_name() != Some(OsStr::new("_data")) { + return None; + } + Some(data_path.parent()?.join(K8S_EXT4_IMAGE)) +} + +/// Returns true if `path` has a valid ext4 superblock magic (`0xEF53`) at offset 1080. +pub fn has_ext4_superblock(path: &Path) -> io::Result { + let mut f = File::open(path)?; + if f.metadata()?.len() < EXT4_SUPER_OFFSET + EXT4_SUPER_MAGIC_OFFSET + 2 { + return Ok(false); + } + f.seek(SeekFrom::Start(EXT4_SUPER_OFFSET + EXT4_SUPER_MAGIC_OFFSET))?; + let mut magic = [0u8; 2]; + f.read_exact(&mut magic)?; + Ok(u16::from_le_bytes(magic) == EXT4_SUPER_MAGIC) +} + +/// Creates a new `0o600` sparse file of logical length `size_bytes`. +fn create_sparse_file(path: &Path, size_bytes: u64) -> io::Result<()> { + let file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)?; + file.set_len(size_bytes) +} + +fn is_executable_file(path: &Path) -> bool { + fs::metadata(path).is_ok_and(|m| m.is_file() && (m.mode() & 0o111 != 0)) +} + +/// Locates `mkfs.ext4` (preferred) or `mke2fs` across standard sbin/bin dirs and `PATH`. +/// Returns `(binary_path, is_mke2fs)`. +fn find_mkfs_ext4_in(extra_dirs: &[&Path], path_env: Option<&OsStr>) -> Option<(PathBuf, bool)> { + let mut dirs: Vec = extra_dirs.iter().map(|d| d.to_path_buf()).collect(); + if let Some(p) = path_env { + for d in std::env::split_paths(p) { + if !dirs.contains(&d) { + dirs.push(d); + } + } + } + for (bin, is_mke2fs) in [("mkfs.ext4", false), ("mke2fs", true)] { + for dir in &dirs { + let candidate = dir.join(bin); + if is_executable_file(&candidate) { + return Some((candidate, is_mke2fs)); + } + } + } + None +} + +fn mkfs_ext4_args(is_mke2fs: bool, img: &Path) -> Vec { + let mut args: Vec = Vec::with_capacity(11); + if is_mke2fs { + args.push(OsString::from("-t")); + args.push(OsString::from("ext4")); + } + for flag in ["-F", "-q", "-m", "0", "-L", "kiri-k8s", "-E", "lazy_itable_init=1,lazy_journal_init=1"] { + args.push(OsString::from(flag)); + } + args.push(img.as_os_str().to_owned()); + args +} + +fn format_ext4_image(img: &Path) -> io::Result<()> { + let standard = [Path::new("/sbin"), Path::new("/usr/sbin"), Path::new("/bin"), Path::new("/usr/bin")]; + let Some((exe, is_mke2fs)) = find_mkfs_ext4_in(&standard, std::env::var_os("PATH").as_deref()) else { + return Err(io::Error::new( + io::ErrorKind::NotFound, + "Kiri Kubernetes on a ZFS host requires `mkfs.ext4` (`e2fsprogs`) to create the ext4 backing image for `kiri-k8s`; install `e2fsprogs` and retry", + )); + }; + let output = Command::new(&exe) + .args(mkfs_ext4_args(is_mke2fs, img)) + .output() + .map_err(|e| io::Error::new(e.kind(), format!("running {} on {}: {e}", exe.display(), img.display())))?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let detail = stderr.trim(); + let why = if detail.is_empty() { format!("exit status {}", output.status) } else { detail.to_owned() }; + return Err(io::Error::other(format!("{} failed to format {}: {why}", exe.display(), img.display()))); + } + Ok(()) +} + +/// Ensures `img_path` exists and contains a valid ext4 filesystem, formatting +/// atomically via a sibling temp file on first creation. +fn ensure_ext4_image(img_path: &Path, size_bytes: u64) -> io::Result<()> { + if img_path.exists() { + if has_ext4_superblock(img_path)? { + return Ok(()); + } + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "{} is not a valid ext4 image; remove the kiri-k8s volume (`kiri k8s delete`) and start Kubernetes again", + img_path.display() + ), + )); + } + let parent = img_path.parent().ok_or_else(|| invalid("ext4 image path has no parent"))?; + let tmp_path = parent.join(K8S_EXT4_TMP); + let _ = fs::remove_file(&tmp_path); + let setup = (|| -> io::Result<()> { + create_sparse_file(&tmp_path, size_bytes)?; + format_ext4_image(&tmp_path)?; + if !has_ext4_superblock(&tmp_path)? { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("formatted {} does not contain an ext4 superblock", tmp_path.display()), + )); + } + fs::rename(&tmp_path, img_path) + })(); + if setup.is_err() { + let _ = fs::remove_file(&tmp_path); + } + setup +} + +/// Populates a `LoopInfo64` with `LO_FLAGS_AUTOCLEAR` and a NUL-terminated +/// copy of `backing` (truncated to fit `LO_NAME_SIZE - 1` bytes). +fn make_loop_info64(mut info: LoopInfo64, backing: &Path) -> LoopInfo64 { + info.lo_flags |= LO_FLAGS_AUTOCLEAR; + info.lo_file_name = [0u8; LO_NAME_SIZE]; + let bytes = backing.as_os_str().as_bytes(); + let n = bytes.len().min(LO_NAME_SIZE - 1); + info.lo_file_name[..n].copy_from_slice(&bytes[..n]); + info +} + +fn open_rw_cloexec(path: &Path) -> io::Result { + let c = super::sys::cstr(path)?; + // SAFETY: `c` is a valid NUL-terminated path; returned fd is owned immediately. + let fd = unsafe { libc::open(c.as_ptr(), libc::O_RDWR | libc::O_CLOEXEC) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: open succeeded, so `fd` is fresh and ours. + Ok(unsafe { OwnedFd::from_raw_fd(fd as RawFd) }) +} + +fn mount_loop_ext4(img_path: &Path, target: &Path) -> io::Result<()> { + let img_fd = open_rw_cloexec(img_path) + .map_err(|e| io::Error::new(e.kind(), format!("open {}: {e}", img_path.display())))?; + let ctl_fd = open_rw_cloexec(Path::new("/dev/loop-control")).map_err(|e| { + io::Error::new( + e.kind(), + format!( + "Kiri Kubernetes on a ZFS host needs Linux loop devices (/dev/loop-control: {e}); ensure the `loop` kernel module is loaded (`modprobe loop`) and loop devices are permitted" + ), + ) + })?; + let target_c = super::sys::cstr(target)?; + + let mut last_busy = None; + for _ in 0..16 { + // SAFETY: LOOP_CTL_GET_FREE allocates or returns a free loop device number. + let n = unsafe { libc::ioctl(ctl_fd.as_raw_fd(), LOOP_CTL_GET_FREE, 0 as libc::c_ulong) }; + if n < 0 { + let e = io::Error::last_os_error(); + return Err(io::Error::new(e.kind(), format!("LOOP_CTL_GET_FREE: {e}"))); + } + let dev_path = PathBuf::from(format!("/dev/loop{n}")); + let loop_fd = match open_rw_cloexec(&dev_path) { + Ok(fd) => fd, + Err(e) if e.raw_os_error() == Some(libc::ENOENT) => { + if let Ok(dev_c) = super::sys::cstr(&dev_path) { + let _ = super::sys::mknod(&dev_c, libc::S_IFBLK | 0o660, LOOP_MAJOR, n as u32); + } + open_rw_cloexec(&dev_path).map_err(|e| io::Error::new(e.kind(), format!("open {}: {e}", dev_path.display())))? + } + Err(e) => return Err(io::Error::new(e.kind(), format!("open {}: {e}", dev_path.display()))), + }; + + // SAFETY: binds `img_fd` to `loop_fd`; EBUSY means another process claimed this loop number. + let set = unsafe { libc::ioctl(loop_fd.as_raw_fd(), LOOP_SET_FD, img_fd.as_raw_fd() as libc::c_ulong) }; + if set < 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() == Some(libc::EBUSY) { + last_busy = Some(e); + continue; + } + return Err(io::Error::new(e.kind(), format!("LOOP_SET_FD on {}: {e}", dev_path.display()))); + } + + let mut info = LoopInfo64::default(); + // SAFETY: best-effort read of kernel defaults into `info`. + let _ = unsafe { libc::ioctl(loop_fd.as_raw_fd(), LOOP_GET_STATUS64, &mut info) }; + info = make_loop_info64(info, img_path); + // SAFETY: sets LO_FLAGS_AUTOCLEAR and lo_file_name on `loop_fd`. + if unsafe { libc::ioctl(loop_fd.as_raw_fd(), LOOP_SET_STATUS64, &info) } < 0 { + let e = io::Error::last_os_error(); + // SAFETY: clear the loop device before dropping `loop_fd` since AUTOCLEAR failed. + unsafe { libc::ioctl(loop_fd.as_raw_fd(), LOOP_CLR_FD, 0 as libc::c_ulong) }; + return Err(io::Error::new(e.kind(), format!("LOOP_SET_STATUS64 on {}: {e}", dev_path.display()))); + } + + let dev_c = super::sys::cstr(&dev_path)?; + // noinit_itable matches the VM ext4 mount so the kernel does not slowly + // write zeros across the sparse 64 GiB image in the background. + // SAFETY: valid NUL-terminated strings for mount(2). + let mut r = unsafe { + libc::mount(dev_c.as_ptr(), target_c.as_ptr(), c"ext4".as_ptr(), 0, c"noinit_itable".as_ptr().cast()) + }; + if r != 0 && io::Error::last_os_error().raw_os_error() == Some(libc::EINVAL) { + // SAFETY: fallback mount with default kernel options. + r = unsafe { libc::mount(dev_c.as_ptr(), target_c.as_ptr(), c"ext4".as_ptr(), 0, std::ptr::null()) }; + } + if r != 0 { + let e = io::Error::last_os_error(); + // SAFETY: defensively clear loop binding on mount failure (AUTOCLEAR also detaches on close). + unsafe { libc::ioctl(loop_fd.as_raw_fd(), LOOP_CLR_FD, 0 as libc::c_ulong) }; + return Err(io::Error::new( + e.kind(), + format!("mount ext4 loop {} on {}: {e}", dev_path.display(), target.display()), + )); + } + // `loop_fd` closes here while the kernel mount keeps the loop device alive + // and LO_FLAGS_AUTOCLEAR detaches it automatically on unmount. + return Ok(()); + } + let e = last_busy.unwrap_or_else(|| io::Error::from_raw_os_error(libc::EBUSY)); + Err(io::Error::new(e.kind(), format!("could not claim a free loop device for {}: {e}", img_path.display()))) +} + +/// On a Linux host where `/var/lib/kiri/volumes` sits on ZFS, ensures the +/// `kiri-k8s` volume's `_data` directory is loop-mounted from a sparse `ext4` +/// image (`ext4.img`) so k3s's kubelet/cAdvisor and containerd overlayfs run +/// on a real block device instead of ZFS (#607). +/// +/// Returns `Ok(true)` when a loopback ext4 mount is held for `data_path` and +/// must be released via [`release_loop`] when the container stops. +pub fn ensure_k8s_ext4(data_path: &str) -> io::Result { + if !is_k8s_volume_data(data_path) || !super::transport::is_host_process() { + return Ok(false); + } + let target = Path::new(data_path); + let vol_dir = target.parent().ok_or_else(|| invalid("k8s volume path has no parent"))?; + if !super::sys::is_zfs(vol_dir) { + return Ok(false); + } + fs::create_dir_all(target)?; + if mounted(data_path) { + loop_refs().lock().unwrap_or_else(|e| e.into_inner()).acquire(data_path); + return Ok(true); + } + let img_path = k8s_ext4_image_path(target).ok_or_else(|| invalid("invalid k8s volume data path"))?; + ensure_ext4_image(&img_path, K8S_EXT4_SIZE_BYTES)?; + mount_loop_ext4(&img_path, target)?; + loop_refs().lock().unwrap_or_else(|e| e.into_inner()).acquire(data_path); + Ok(true) } /// Mounts the volume at `path` unless something already is: `kind` is the @@ -78,21 +441,65 @@ fn hide_password(data: &str) -> String { data.split(',').map(|w| if w.starts_with("password=") { "password=********" } else { w }).collect::>().join(",") } -/// Unmounts whatever is mounted at a volume's path before its data is -/// deleted, so removing a volume never deletes the NFS export or the host -/// folder behind it. False if something is still mounted there. -pub fn release(path: &str) -> bool { +/// Unmounts `path` synchronously first (with short retries on `EBUSY` while a +/// stopped container's mount namespace tears down) so loopback ext4 flushes +/// and `LO_FLAGS_AUTOCLEAR` detaches before deletion; falls back to lazy +/// unmount (`MNT_DETACH`) if still busy. +fn unmount_clean(path: &str) -> bool { + let target = Path::new(path); for _ in 0..16 { if !mounted(path) { return true; } - if super::sys::umount_lazy(std::path::Path::new(path)).is_err() { + let mut unmounted = false; + for attempt in 0..10 { + match super::sys::umount(target) { + Ok(()) => { + unmounted = true; + break; + } + Err(e) if e.kind() == io::ErrorKind::ResourceBusy && attempt < 9 => { + std::thread::sleep(Duration::from_millis(20)); + } + Err(_) => break, + } + } + if !unmounted && super::sys::umount_lazy(target).is_err() { break; } } !mounted(path) } +/// Releases one container's hold on a loopback volume mount and unmounts it +/// cleanly once no running containers still hold it. +pub fn release_loop(path: &str) { + let last = loop_refs().lock().unwrap_or_else(|e| e.into_inner()).release(path); + if last { + let _ = unmount_clean(path); + } +} + +/// Unmounts the `kiri-k8s` loopback ext4 image if mounted on agent startup or +/// shutdown sweep so no orphaned loop mount stays active on the Linux host. +pub fn release_k8s_ext4_if_mounted() { + let data = Path::new(K8S_VOLUME_DATA); + let Some(img) = k8s_ext4_image_path(data) else { return }; + if img.exists() && mounted(K8S_VOLUME_DATA) { + loop_refs().lock().unwrap_or_else(|e| e.into_inner()).clear(K8S_VOLUME_DATA); + let _ = unmount_clean(K8S_VOLUME_DATA); + } +} + +/// Unmounts whatever is mounted at a volume's path before its data is +/// deleted, so removing a volume never deletes the NFS export or the host +/// folder behind it, and a loopback ext4 volume detaches without `EBUSY`. +/// False if something is still mounted there. +pub fn release(path: &str) -> bool { + loop_refs().lock().unwrap_or_else(|e| e.into_inner()).clear(path); + unmount_clean(path) +} + #[cfg(test)] mod tests { use super::*; @@ -107,4 +514,128 @@ mod tests { assert!(ensure("/etc", "tmpfs", "tmpfs", "0", "").is_err()); assert!(ensure("/var/lib/kiri/volumes/../../etc/_data", "tmpfs", "tmpfs", "0", "").is_err()); } + + #[test] + fn k8s_ext4_paths_and_loop_info_layout() { + assert!(is_k8s_volume_data("/var/lib/kiri/volumes/kiri-k8s/_data")); + assert!(!is_k8s_volume_data("/var/lib/kiri/volumes/other/_data")); + assert!(!is_k8s_volume_data("/var/lib/kiri/volumes/kiri-k8s/_data/sub")); + assert!(!is_k8s_volume_data("/var/lib/kiri/volumes/kiri-k8s")); + + assert_eq!( + k8s_ext4_image_path(Path::new("/var/lib/kiri/volumes/kiri-k8s/_data")), + Some(PathBuf::from("/var/lib/kiri/volumes/kiri-k8s/ext4.img")) + ); + assert_eq!(k8s_ext4_image_path(Path::new("/var/lib/kiri/volumes/kiri-k8s")), None); + + // Matches Linux struct loop_info64 ABI size across x86_64 and aarch64. + assert_eq!(std::mem::size_of::(), 232); + + let mut base = LoopInfo64::default(); + base.lo_flags = 1; + let info = make_loop_info64(base, Path::new("/var/lib/kiri/volumes/kiri-k8s/ext4.img")); + assert_eq!(info.lo_flags, 1 | LO_FLAGS_AUTOCLEAR); + let name = std::ffi::CStr::from_bytes_until_nul(&info.lo_file_name).unwrap().to_str().unwrap(); + assert_eq!(name, "/var/lib/kiri/volumes/kiri-k8s/ext4.img"); + + // Paths longer than LO_NAME_SIZE - 1 truncate cleanly and stay NUL-terminated. + let long = format!("/{}", "a".repeat(120)); + let info_long = make_loop_info64(LoopInfo64::default(), Path::new(&long)); + assert_eq!(info_long.lo_file_name[LO_NAME_SIZE - 1], 0); + let trunc = std::ffi::CStr::from_bytes_until_nul(&info_long.lo_file_name).unwrap().to_str().unwrap(); + assert_eq!(trunc.len(), LO_NAME_SIZE - 1); + } + + #[test] + fn sparse_file_and_ext4_superblock_detection() { + let dir = std::env::temp_dir().join(format!("kiri-volmount-sparse-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + + let img = dir.join("ext4.img"); + let size = 4 << 20; + create_sparse_file(&img, size).unwrap(); + let meta = fs::metadata(&img).unwrap(); + assert_eq!(meta.len(), size); + assert_eq!(meta.mode() & 0o777, 0o600); + assert!(!has_ext4_superblock(&img).unwrap()); + + // Write ext4 superblock magic 0xEF53 at 1024 + 0x38. + let mut f = OpenOptions::new().write(true).open(&img).unwrap(); + f.seek(SeekFrom::Start(EXT4_SUPER_OFFSET + EXT4_SUPER_MAGIC_OFFSET)).unwrap(); + std::io::Write::write_all(&mut f, &EXT4_SUPER_MAGIC.to_le_bytes()).unwrap(); + drop(f); + assert!(has_ext4_superblock(&img).unwrap()); + + // Short / empty file is not ext4. + let short = dir.join("short.img"); + fs::write(&short, b"tiny").unwrap(); + assert!(!has_ext4_superblock(&short).unwrap()); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn finds_mkfs_ext4_or_mke2fs_and_builds_args() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("kiri-volmount-mkfs-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let sbin = dir.join("sbin"); + let usr_sbin = dir.join("usr_sbin"); + fs::create_dir_all(&sbin).unwrap(); + fs::create_dir_all(&usr_sbin).unwrap(); + + assert_eq!(find_mkfs_ext4_in(&[&sbin], None), None); + + // Fallback to mke2fs when mkfs.ext4 is absent. + let mke2fs = usr_sbin.join("mke2fs"); + fs::write(&mke2fs, "#!/bin/sh\n").unwrap(); + fs::set_permissions(&mke2fs, fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(find_mkfs_ext4_in(&[&sbin, &usr_sbin], None), Some((mke2fs.clone(), true))); + + // Non-executable mkfs.ext4 is ignored in favor of executable mke2fs. + let nonexec = sbin.join("mkfs.ext4"); + fs::write(&nonexec, "not exec").unwrap(); + fs::set_permissions(&nonexec, fs::Permissions::from_mode(0o644)).unwrap(); + assert_eq!(find_mkfs_ext4_in(&[&sbin, &usr_sbin], None), Some((mke2fs.clone(), true))); + + // Executable mkfs.ext4 is preferred over mke2fs. + fs::set_permissions(&nonexec, fs::Permissions::from_mode(0o755)).unwrap(); + assert_eq!(find_mkfs_ext4_in(&[&sbin, &usr_sbin], None), Some((nonexec.clone(), false))); + + let img = Path::new("/var/lib/kiri/volumes/kiri-k8s/ext4.img"); + let direct = mkfs_ext4_args(false, img); + assert_eq!(direct.first().unwrap(), "-F"); + assert_eq!(direct.last().unwrap(), img.as_os_str()); + assert!(!direct.iter().any(|a| a == "-t")); + + let via_mke2fs = mkfs_ext4_args(true, img); + assert_eq!(via_mke2fs[0], "-t"); + assert_eq!(via_mke2fs[1], "ext4"); + assert_eq!(via_mke2fs.last().unwrap(), img.as_os_str()); + + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn loop_refs_and_mountinfo_matching() { + let mut refs = LoopRefs::default(); + refs.acquire(K8S_VOLUME_DATA); + refs.acquire(K8S_VOLUME_DATA); + assert!(!refs.release(K8S_VOLUME_DATA), "still held by second container"); + assert!(refs.release(K8S_VOLUME_DATA), "last holder released -> unmount"); + assert!(refs.release(K8S_VOLUME_DATA), "idempotent once released"); + + refs.acquire(K8S_VOLUME_DATA); + refs.acquire(K8S_VOLUME_DATA); + refs.clear(K8S_VOLUME_DATA); + assert!(refs.release(K8S_VOLUME_DATA)); + + let mi = "\ +25 1 0:30 / / rw,relatime - zfs rpool/ROOT/ubuntu rw,xattr,posixacl +91 25 7:3 / /var/lib/kiri/volumes/kiri-k8s/_data rw,relatime - ext4 /dev/loop3 rw,noinit_itable +"; + assert!(mounted_in(mi, K8S_VOLUME_DATA)); + assert!(!mounted_in(mi, "/var/lib/kiri/volumes/kiri-k8s")); + } } diff --git a/crates/kiri-proto/src/lib.rs b/crates/kiri-proto/src/lib.rs index 7d7366533..359d79d31 100644 --- a/crates/kiri-proto/src/lib.rs +++ b/crates/kiri-proto/src/lib.rs @@ -25,6 +25,13 @@ pub const MAX_FRAME: usize = 1 << 20; /// Bytes before the payload: length plus kind. pub const HEADER: usize = 6; +/// Largest frame body a sender may emit so the whole frame stays within +/// `MAX_FRAME`. A reply built from guest- or container-controlled content (a +/// directory listing, a `top` table) is capped to this; otherwise one huge +/// reply overflows `MAX_FRAME`, the peer rejects the frame, and the whole VM +/// is declared lost and restarted. +pub const MAX_BODY: usize = MAX_FRAME - HEADER; + /// Largest `Output` chunk; keeps frames well under `MAX_FRAME`. pub const MAX_OUTPUT_CHUNK: usize = 64 * 1024; /// Stdin bytes the host may have sent a process beyond what the guest has @@ -44,8 +51,14 @@ pub const INPUT_WINDOW: usize = 4 << 20; /// the container's root is in place. 7 added `CancelStart`, which has no /// reply: an older agent's "unexpected" error would be taken as the reply /// to the next request. 8 added `DnsRename`, another no-reply message, for -/// the same reason. -pub const PROTOCOL: u16 = 8; +/// the same reason. 9 added `Limits::swap_max`: an older agent would read +/// the limits one field short. 10 added a payload on `MemoryPressure` +/// (MemAvailable and PSI full avg10): an older agent's bare `MemoryPressure` +/// has neither field, so decode rejects it as truncated. 11 added +/// `SetEgressRoutes`, another no-reply message (sent on every VM boot): an +/// older agent's "unexpected" error would be taken as the reply to the next +/// request. +pub const PROTOCOL: u16 = 11; /// Most names a `DnsRename` may carry: a name, its aliases and a hostname. pub const MAX_DNS_NAMES: usize = 256; @@ -123,8 +136,8 @@ pub enum Msg<'a> { /// Sent once after connecting. No reply. Retain(StrList<'a>), /// Host → guest: delete every unpacked layer except these (by blob - /// digest), and any left half-written. Sent once after connecting, - /// before anything runs. No reply. + /// digest), and any left half-written. Sent on connect and after images + /// or containers stop referencing layers. No reply. RetainLayers(StrList<'a>), /// Asks how much disk the guest's layers, containers and volumes use. UsageQuery, @@ -143,9 +156,13 @@ pub enum Msg<'a> { /// Host → guest: up to `len` bytes from `offset`. Answered by `FsData` or `Error`. FsRead { id: &'a str, path: &'a str, offset: u64, len: u32 }, FsData(&'a [u8]), + /// Host → guest: where a link inside a running container's root points, + /// as the link says it. Answered by `FsData` or `Error`. + FsReadLink { id: &'a str, path: &'a str }, /// Guest → host: memory is tight right now (a PSI trigger fired); grow - /// the VM's memory. No reply. - MemoryPressure, + /// the VM's memory, and carry the readings that go with a memory kill. + /// No reply. + MemoryPressure(MemoryPressure), /// Host → guest: delete a named volume's data. No reply. RemoveVolume { name: &'a str }, /// Host → guest, first frame on a connection to [`COPY_PORT`]: copy @@ -200,6 +217,11 @@ pub enum Msg<'a> { /// or `Error` with no lease yet; an older agent answers `Error`. UplinkQuery, Uplink { ip: [u8; 4], gateway: [u8; 4] }, + /// Host → guest, in the VM: configure the uplink (`eth0`) directly when + /// DHCP did not answer. Ignored (still answered `Ack`) if the guest + /// already obtained a DHCP lease. `dns` of `[0; 4]` leaves DNS unset. + /// Answered by `Ack` or `Error`; an older agent answers `Error`. + SetUplink { ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4] }, /// Host → guest: container `id` on `bridge` was renamed. Its old DNS /// names are dropped and `names` registered to the same address (A /// records only when `v4`: a network without IPv4 addresses keeps the @@ -221,6 +243,23 @@ pub enum Msg<'a> { /// request; the VM runs inside the daemon process today, so the two /// versions cannot differ. FsEvents(StrList<'a>), + /// Host → guest: IPv4 CIDR prefixes (`a.b.c.d/prefix`) whose outbound + /// container TCP connections are redirected to the agent and relayed over + /// [`EGRESS_TCP_PORT`] for the host to dial (split-tunnel VPN routes, + /// security network extensions, or `0.0.0.0/0` under host egress). Empty + /// clears the redirect rules. No reply. + SetEgressRoutes(StrList<'a>), + /// Host → guest: query the guest data disk's (`DATA`) filesystem usage via + /// `statvfs`. Answered by `DiskUsage` or `Error`; an older agent answers `Error`. + DiskUsageQuery, + /// Guest → host: data disk bytes currently in use (`(blocks - bavail) * frsize`) + /// and total capacity (`blocks * frsize`). + DiskUsage { in_use: u64, capacity: u64 }, + /// Host → guest: run `FITRIM` immediately on the guest data disk (`DATA`). + /// Answered by `DiskTrimmed` or `Error`; an older agent answers `Error`. + TrimDisk, + /// Guest → host: bytes discarded by `FITRIM`, plus updated `statvfs` usage. + DiskTrimmed { trimmed: u64, in_use: u64, capacity: u64 }, /// Success, for requests with nothing else to say. Ack, } @@ -233,6 +272,11 @@ pub const COPY_PORT: u32 = 1028; /// TCP frames it, and gets `u16 len | reply` back: one lookup per connection. pub const DNS_RELAY_PORT: u32 = 1037; +/// vsock port of the host's outbound TCP relay. The agent sends `ip[4] port[2]` +/// for a connection redirected from a container, and the host dials it and +/// relays bytes both ways. +pub const EGRESS_TCP_PORT: u32 = 1038; + /// vsock port of the guest's USB passthrough: one connection per device, /// `speed u32 | devid u32` then USB/IP (crates/kiri-init/src/linux/usb.rs). pub const USB_PORT: u32 = 1040; @@ -250,10 +294,19 @@ pub mod copy_op { /// `docker commit`: the writable layer as an OCI layer tar (whiteouts as /// `.wh.` files). pub const COMMIT: u8 = 6; + /// `kiri import`: a writable layer brought from another engine, as an + /// OCI layer tar (whiteouts as `.wh.` files) sent like `IN`'s archive, + /// becomes the writable layer of a container that is not running and + /// has none yet. Answers `CopyDone` (or `Error`) once it is in place. + pub const UPPER: u8 = 7; } pub mod copy_flags { - /// Keep the archive's owners (`docker cp -a`); otherwise root owns everything. + /// `docker cp -a` (`copyUIDGID`): chown unpacked entries to the + /// container's `Config.User` when one is set (Moby's + /// `applyTarCopyUserOptions`), sent as `"\0"` in + /// `CopySpec::path`. Without `-a`, or when `Config.User` is empty, the + /// archive's header UID/GID are kept. pub const KEEP_OWNERS: u32 = 1; /// Refuse to replace a directory with a file or the reverse. pub const NO_OVERWRITE_DIR_NON_DIR: u32 = 2; @@ -263,6 +316,15 @@ pub mod copy_flags { /// Intel Mac with macOS 14 passes a half-close on as a full one, and the /// guest's answer fails with EPIPE. pub const CHUNKED: u32 = 4; + /// `IN`: the container has `--read-only` (`HostConfig.ReadonlyRootfs`), so + /// writes outside writable mounts are refused. + pub const READONLY_ROOTFS: u32 = 8; + /// `OUT` / `EXPORT`: the guest sends the archive in `<= 64 KiB` chunks + /// (`len: u32 LE | bytes`, ending with an empty chunk), waiting for a + /// 1-byte credit ack from the host before sending each chunk, so + /// `COPY_PORT` is never left unread while the host writes to + /// `ENGINE_API_PORT` (#874). + pub const PACED: u32 = 16; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -272,16 +334,21 @@ pub struct CopySpec<'a> { pub path: &'a str, pub flags: u32, pub layers: StrList<'a>, + /// The container's mounts (`source\ttarget\tflags[\t…]`, as in + /// [`RunSpec::mounts`]). Empty from an older daemon, and empty for + /// `EXPORT`, `DIFF`, `COMMIT` and `UPPER`. + pub mounts: StrList<'a>, } /// Encodes a `Copy` frame from the sender's side. -pub fn encode_copy>(out: &mut Vec, op: u8, id: &str, path: &str, flags: u32, layers: &[S]) { +pub fn encode_copy>(out: &mut Vec, op: u8, id: &str, path: &str, flags: u32, layers: &[S], mounts: &[S]) { frame(out, kind::COPY, |o| { o.push(op); put_str(o, id); put_str(o, path); put_u32(o, flags); StrList::put(o, layers); + StrList::put(o, mounts); }); } @@ -312,10 +379,22 @@ fn put_entry(out: &mut Vec, e: &FsEntry<'_>) { /// Encodes an `FsList` reply from entries. pub fn encode_fs_list(out: &mut Vec, entries: &[FsEntry<'_>]) { frame(out, kind::FS_LIST, |o| { - put_u32(o, entries.len() as u32); + // Cap the reply at MAX_BODY, dropping trailing entries: a directory + // with thousands of long names would otherwise overflow MAX_FRAME and + // make the peer lose the whole VM. + let start = o.len(); + put_u32(o, 0); + let mut n: u32 = 0; for e in entries { + // Encoded entry: 4+name | mode u32 | size u64 | mtime u64 | nsec u32 | ino u64. + let entry_len = 4 + e.name.len() + 4 + 8 + 8 + 4 + 8; + if o.len() - start + entry_len > MAX_BODY { + break; + } put_entry(o, e); + n += 1; } + o[start..start + 4].copy_from_slice(&n.to_le_bytes()); }); } @@ -367,6 +446,10 @@ pub struct Stats { /// Pages held by the memory balloon, in KiB. None from an agent or /// kernel that does not report it. pub mem_balloon_kib: Option, + /// Committed address space (`Committed_AS` from `/proc/meminfo`: writable + /// `VM_ACCOUNT` mappings, excluding `MAP_NORESERVE` virtual arenas), in + /// KiB. None from an older agent or kernel that does not report it. + pub mem_committed_kib: Option, } /// What the guest knows about its own boot, in nanoseconds of CLOCK_BOOTTIME. @@ -478,6 +561,10 @@ pub mod net_opts { /// only the name the guest keeps it by: neither it nor the bridge gets /// one, and DNS has no A record for it. pub const NO_IPV4: &str = "noipv4"; + /// `noicc=1`: the network has `com.docker.network.bridge.enable_icc=false`: + /// the container's bridge port is isolated, so it reaches no other + /// container on that network (#213). + pub const NO_ICC: &str = "noicc"; /// `dnsbridge=kiri3`, one per network: a user network the container /// joins once it runs (`NetAttach`). Its embedded DNS answers that /// network's names from the start, as Docker's does with every network @@ -516,7 +603,8 @@ pub struct RunSpec<'a> { pub caps: u64, /// HostConfig settings applied at start, one per line, tab-separated: /// `rlimit res soft hard`, `sysctl ns path value`, `device host - /// container perms`, `devrule type major minor perms`, `group name`. + /// container perms`, `devrule type major minor perms`, `group name`, + /// `masked path…`, `readonly path…`, `cgroupns host`. /// Empty from an older daemon. pub opts: StrList<'a>, /// The container's own seccomp profile, compiled by the daemon to a @@ -527,9 +615,10 @@ pub struct RunSpec<'a> { pub seccomp: &'a [u8], } -/// cgroup limits (`--memory`, `--cpus`, `--cpu-shares`, `--pids-limit`). -/// Zero means no limit. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +/// cgroup limits (`--memory`, `--memory-swap`, `--cpus`, `--cpu-shares`, +/// `--pids-limit`). Zero means no limit, except `swap_max` where `0` means no +/// swap and [`NO_LIMIT`] means no limit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Limits { pub memory_max: u64, /// CPU time allowed per `cpu_period` microseconds (`--cpus 1.5` is 150000/100000). @@ -540,6 +629,17 @@ pub struct Limits { pub pids_max: u32, /// `--shm-size` in bytes; 0 means 64 MiB. pub shm_size: u64, + /// cgroup v2 `memory.swap.max` in bytes, [`NO_LIMIT`] for `max`. + pub swap_max: u64, +} + +/// A limit of `max`. +pub const NO_LIMIT: u64 = u64::MAX; + +impl Default for Limits { + fn default() -> Self { + Self { memory_max: 0, cpu_quota: 0, cpu_period: 0, cpu_weight: 0, pids_max: 0, shm_size: 0, swap_max: NO_LIMIT } + } } fn put_limits(out: &mut Vec, l: &Limits) { @@ -549,10 +649,19 @@ fn put_limits(out: &mut Vec, l: &Limits) { put_u32(out, l.cpu_weight); put_u32(out, l.pids_max); put_u64(out, l.shm_size); + put_u64(out, l.swap_max); } fn read_limits(r: &mut Reader<'_>) -> Result { - Ok(Limits { memory_max: r.u64()?, cpu_quota: r.u64()?, cpu_period: r.u32()?, cpu_weight: r.u32()?, pids_max: r.u32()?, shm_size: r.u64()? }) + Ok(Limits { + memory_max: r.u64()?, + cpu_quota: r.u64()?, + cpu_period: r.u32()?, + cpu_weight: r.u32()?, + pids_max: r.u32()?, + shm_size: r.u64()?, + swap_max: r.u64()?, + }) } /// One container's resource use, read from its cgroup and network namespace. @@ -578,6 +687,9 @@ pub struct ContainerStats { pub tx_packets: u64, pub io_read_bytes: u64, pub io_write_bytes: u64, + pub cpu_periods: u64, + pub cpu_throttled_periods: u64, + pub cpu_throttled_usec: u64, } fn put_container_stats(o: &mut Vec, s: &ContainerStats) { @@ -589,10 +701,13 @@ fn put_container_stats(o: &mut Vec, s: &ContainerStats) { for v in [s.rx_bytes, s.rx_packets, s.tx_bytes, s.tx_packets, s.io_read_bytes, s.io_write_bytes] { put_u64(o, v); } + for v in [s.cpu_periods, s.cpu_throttled_periods, s.cpu_throttled_usec] { + put_u64(o, v); + } } fn read_container_stats(r: &mut Reader<'_>) -> Result { - Ok(ContainerStats { + let mut stats = ContainerStats { read_ns: r.u64()?, mem_current: r.u64()?, mem_max: r.u64()?, @@ -609,7 +724,15 @@ fn read_container_stats(r: &mut Reader<'_>) -> Result { pub oom_killed: bool, } +/// What the guest sends with [`Msg::MemoryPressure`]: the readings behind a +/// memory kill, so the host can log the numbers in the same event. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MemoryPressure { + /// MemAvailable from /proc/meminfo, in KiB. + pub mem_available_kib: u64, + /// PSI "full avg10" in hundredths of a percent (see `Stats::mem_stall`). + pub mem_stall: u64, +} + /// A list of strings borrowed from a frame. Iterate it; it never allocates. #[derive(Clone, Copy, PartialEq, Eq, Default)] pub struct StrList<'a> { @@ -678,6 +811,29 @@ impl<'a> StrList<'a> { put_str(out, s.as_ref()); } } + + /// Like `put`, but keeps the encoded list within `budget` bytes, dropping + /// trailing items (and truncating a single over-long item on a char + /// boundary) so the frame cannot exceed `MAX_FRAME`. The count written is + /// the number actually encoded. Use for replies whose size the sender does + /// not control, such as `top` or a directory listing. + pub fn put_capped>(out: &mut Vec, items: &[S], budget: usize) { + let start = out.len(); + out.extend_from_slice(&0u32.to_le_bytes()); + let mut n: u32 = 0; + for s in items { + // Leave headroom so at least a truncated first item fits: the + // 4-byte count already written plus a 4-byte length prefix. + let s = s.as_ref(); + let s = &s[..s.floor_char_boundary(budget.saturating_sub(8))]; + if out.len() - start + 4 + s.len() > budget { + break; + } + put_str(out, s); + n += 1; + } + out[start..start + 4].copy_from_slice(&n.to_le_bytes()); + } } mod kind { @@ -742,6 +898,13 @@ mod kind { pub const AWAIT_START: u16 = 79; pub const CANCEL_START: u16 = 80; pub const DNS_RENAME: u16 = 81; + pub const FS_READ_LINK: u16 = 82; + pub const SET_UPLINK: u16 = 83; + pub const SET_EGRESS_ROUTES: u16 = 84; + pub const DISK_USAGE_QUERY: u16 = 85; + pub const DISK_USAGE: u16 = 86; + pub const TRIM_DISK: u16 = 87; + pub const DISK_TRIMMED: u16 = 88; } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -811,10 +974,15 @@ pub fn encode_net_attach>(out: &mut Vec, id: &str, ifname: &st } /// Whether `frame` is of a kind the guest answers with no reply -/// (`DnsRename`): one that doesn't decode is then dropped, not answered -/// with an `Error` the host would read as the next request's reply. +/// (`DnsRename`, `SetEgressRoutes`): one that doesn't decode is then dropped, +/// not answered with an `Error` the host would read as the next request's reply. pub fn takes_no_reply(frame: &[u8]) -> bool { - frame.len() >= HEADER && u16::from_le_bytes([frame[4], frame[5]]) == kind::DNS_RENAME + frame.len() >= HEADER && matches!(u16::from_le_bytes([frame[4], frame[5]]), kind::DNS_RENAME | kind::SET_EGRESS_ROUTES) +} + +/// Encodes a `SetEgressRoutes` frame from the sender's CIDR strings. +pub fn encode_set_egress_routes>(out: &mut Vec, routes: &[S]) { + frame(out, kind::SET_EGRESS_ROUTES, |out| StrList::put_capped(out, routes, MAX_BODY)); } /// Encodes a `DnsRename` frame from the sender's slices. @@ -831,27 +999,27 @@ pub fn encode_dns_rename>(out: &mut Vec, id: &str, bridge: &st /// Encodes a `Usage` reply from the sender's lines. pub fn encode_usage>(out: &mut Vec, lines: &[S]) { - frame(out, kind::USAGE, |out| StrList::put(out, lines)); + frame(out, kind::USAGE, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `Top` reply from the sender's lines. pub fn encode_top>(out: &mut Vec, lines: &[S]) { - frame(out, kind::TOP, |out| StrList::put(out, lines)); + frame(out, kind::TOP, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `UsbNodes` reply from the sender's lines. pub fn encode_usb_nodes>(out: &mut Vec, lines: &[S]) { - frame(out, kind::USB_NODES, |out| StrList::put(out, lines)); + frame(out, kind::USB_NODES, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes an `FsEvents` frame from the sender's `OP\tPATH` lines. pub fn encode_fs_events>(out: &mut Vec, lines: &[S]) { - frame(out, kind::FS_EVENTS, |out| StrList::put(out, lines)); + frame(out, kind::FS_EVENTS, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `Listening` reply from the sender's lines. pub fn encode_listening>(out: &mut Vec, lines: &[S]) { - frame(out, kind::LISTENING, |out| StrList::put(out, lines)); + frame(out, kind::LISTENING, |out| StrList::put_capped(out, lines, MAX_BODY)); } /// Encodes a `Retain` frame from the sender's ids. @@ -947,15 +1115,19 @@ impl Msg<'_> { Msg::Ping(v) => frame(out, kind::PING, |o| put_u64(o, v)), Msg::Pong(v) => frame(out, kind::PONG, |o| put_u64(o, v)), Msg::Shutdown => frame(out, kind::SHUTDOWN, |_| {}), - Msg::Error(s) => frame(out, kind::ERROR, |o| o.extend_from_slice(s.as_bytes())), + Msg::Error(s) => frame(out, kind::ERROR, |o| { + let s = &s[..s.floor_char_boundary(MAX_BODY)]; + o.extend_from_slice(s.as_bytes()); + }), Msg::StatsRequest => frame(out, kind::STATS_REQUEST, |_| {}), Msg::Stats(st) => frame(out, kind::STATS, |o| { for v in [st.uptime_ns, st.mem_total_kib, st.mem_available_kib, st.agent_rss_kib, st.mem_used_kib, st.mem_stall, st.oom_kills] { put_u64(o, v); } - // Always emit the 8th word (u64::MAX for None) so any future - // trailing fields stay at fixed offsets. + // Always emit the 8th and 9th words (u64::MAX for None) so any + // future trailing fields stay at fixed offsets. put_u64(o, st.mem_balloon_kib.unwrap_or(u64::MAX)); + put_u64(o, st.mem_committed_kib.unwrap_or(u64::MAX)); }), Msg::LayerQuery(d) => frame(out, kind::LAYER_QUERY, |o| put_str(o, d)), Msg::LayerStatus(have) => frame(out, kind::LAYER_STATUS, |o| o.push(have as u8)), @@ -1070,7 +1242,14 @@ impl Msg<'_> { put_u32(o, len); }), Msg::FsData(d) => frame(out, kind::FS_DATA, |o| put_bytes(o, d)), - Msg::MemoryPressure => frame(out, kind::MEMORY_PRESSURE, |_| {}), + Msg::FsReadLink { id, path } => frame(out, kind::FS_READ_LINK, |o| { + put_str(o, id); + put_str(o, path); + }), + Msg::MemoryPressure(p) => frame(out, kind::MEMORY_PRESSURE, |o| { + put_u64(o, p.mem_available_kib); + put_u64(o, p.mem_stall); + }), Msg::RemoveVolume { name } => frame(out, kind::REMOVE_VOLUME, |o| put_str(o, name)), Msg::RemoveBridge { bridge } => frame(out, kind::REMOVE_BRIDGE, |o| put_str(o, bridge)), Msg::DnsRename { id, bridge, ip, ip6, v4, names } => frame(out, kind::DNS_RENAME, |o| { @@ -1089,6 +1268,8 @@ impl Msg<'_> { put_u32(o, c.flags); put_u32(o, c.layers.count); o.extend_from_slice(c.layers.raw); + put_u32(o, c.mounts.count); + o.extend_from_slice(c.mounts.raw); }), Msg::CopyStat { entry, link } => frame(out, kind::COPY_STAT, |o| { put_entry(o, &entry); @@ -1120,6 +1301,21 @@ impl Msg<'_> { put_u32(o, lines.count); o.extend_from_slice(lines.raw); }), + Msg::SetEgressRoutes(routes) => frame(out, kind::SET_EGRESS_ROUTES, |o| { + put_u32(o, routes.count); + o.extend_from_slice(routes.raw); + }), + Msg::DiskUsageQuery => frame(out, kind::DISK_USAGE_QUERY, |_| {}), + Msg::DiskUsage { in_use, capacity } => frame(out, kind::DISK_USAGE, |o| { + put_u64(o, in_use); + put_u64(o, capacity); + }), + Msg::TrimDisk => frame(out, kind::TRIM_DISK, |_| {}), + Msg::DiskTrimmed { trimmed, in_use, capacity } => frame(out, kind::DISK_TRIMMED, |o| { + put_u64(o, trimmed); + put_u64(o, in_use); + put_u64(o, capacity); + }), Msg::Listening(lines) => frame(out, kind::LISTENING, |o| { put_u32(o, lines.count); o.extend_from_slice(lines.raw); @@ -1151,6 +1347,12 @@ impl Msg<'_> { o.extend_from_slice(&ip); o.extend_from_slice(&gateway); }), + Msg::SetUplink { ip, prefix, gateway, dns } => frame(out, kind::SET_UPLINK, |o| { + o.extend_from_slice(&ip); + o.push(prefix); + o.extend_from_slice(&gateway); + o.extend_from_slice(&dns); + }), Msg::Ack => frame(out, kind::ACK, |_| {}), Msg::InputConsumed { id, bytes } => frame(out, kind::INPUT_CONSUMED, |o| { put_str(o, id); @@ -1280,6 +1482,12 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { } else { None }, + mem_committed_kib: if r.remaining() >= 8 { + let v = r.u64()?; + (v != u64::MAX).then_some(v) + } else { + None + }, }), kind::LAYER_QUERY => Msg::LayerQuery(r.str()?), kind::LAYER_STATUS => Msg::LayerStatus(r.u8()? != 0), @@ -1370,6 +1578,7 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::FS_STAT_REQUEST => Msg::FsStatRequest { id: r.str()?, path: r.str()? }, kind::FS_STAT => Msg::FsStat(read_entry(&mut r)?), kind::FS_LIST_REQUEST => Msg::FsListRequest { id: r.str()?, path: r.str()? }, + kind::FS_READ_LINK => Msg::FsReadLink { id: r.str()?, path: r.str()? }, kind::FS_LIST => { let count = r.u32()?; let start = r.pos; @@ -1380,7 +1589,10 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { } kind::FS_READ => Msg::FsRead { id: r.str()?, path: r.str()?, offset: r.u64()?, len: r.u32()? }, kind::FS_DATA => Msg::FsData(r.bytes()?), - kind::MEMORY_PRESSURE => Msg::MemoryPressure, + kind::MEMORY_PRESSURE => Msg::MemoryPressure(MemoryPressure { + mem_available_kib: r.u64()?, + mem_stall: r.u64()?, + }), kind::REMOVE_VOLUME => Msg::RemoveVolume { name: r.str()? }, kind::REMOVE_BRIDGE => Msg::RemoveBridge { bridge: r.str()? }, kind::DNS_RENAME => { @@ -1398,7 +1610,15 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { } Msg::DnsRename { id, bridge, ip, ip6, v4, names } } - kind::COPY => Msg::Copy(CopySpec { op: r.u8()?, id: r.str()?, path: r.str()?, flags: r.u32()?, layers: r.list()? }), + kind::COPY => Msg::Copy(CopySpec { + op: r.u8()?, + id: r.str()?, + path: r.str()?, + flags: r.u32()?, + layers: r.list()?, + // Trailing list; absent from an older daemon. + mounts: if r.remaining() >= 4 { r.list()? } else { StrList::default() }, + }), kind::COPY_STAT => Msg::CopyStat { entry: read_entry(&mut r)?, link: r.str()? }, kind::COPY_DONE => Msg::CopyDone, kind::UPDATE => Msg::Update { id: r.str()?, limits: read_limits(&mut r)? }, @@ -1412,6 +1632,11 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::USB_NODES_QUERY => Msg::UsbNodesQuery, kind::USB_NODES => Msg::UsbNodes(r.list()?), kind::FS_EVENTS => Msg::FsEvents(r.list()?), + kind::SET_EGRESS_ROUTES => Msg::SetEgressRoutes(r.list()?), + kind::DISK_USAGE_QUERY => Msg::DiskUsageQuery, + kind::DISK_USAGE => Msg::DiskUsage { in_use: r.u64()?, capacity: r.u64()? }, + kind::TRIM_DISK => Msg::TrimDisk, + kind::DISK_TRIMMED => Msg::DiskTrimmed { trimmed: r.u64()?, in_use: r.u64()?, capacity: r.u64()? }, kind::NET_ATTACH => Msg::NetAttach { id: r.str()?, ifname: r.str()?, @@ -1434,6 +1659,12 @@ pub fn decode(frame: &[u8]) -> Result, DecodeError> { kind::NET_DETACH => Msg::NetDetach { id: r.str()?, ifname: r.str()?, bridge: r.str()?, ip: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)? }, kind::UPLINK_QUERY => Msg::UplinkQuery, kind::UPLINK => Msg::Uplink { ip: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, gateway: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)? }, + kind::SET_UPLINK => Msg::SetUplink { + ip: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, + prefix: r.u8()?, + gateway: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, + dns: r.take(4)?.try_into().map_err(|_| DecodeError::Truncated)?, + }, kind::ACK => Msg::Ack, kind::INPUT_CONSUMED => Msg::InputConsumed { id: r.str()?, bytes: r.u32()? }, kind::PUBLISH => Msg::Publish(Publish { @@ -1460,6 +1691,29 @@ mod tests { assert_eq!(decode(&buf).unwrap(), m); } + #[test] + fn cpu_throttling_stats() { + let stats = ContainerStats { + cpu_periods: 8, + cpu_throttled_periods: 3, + cpu_throttled_usec: 1200, + ..Default::default() + }; + round(Msg::ContainerStats(stats)); + // An older agent omits the three trailing throttling words. + let mut frame = Vec::new(); + Msg::ContainerStats(stats).encode(&mut frame); + let mut old = frame[..frame.len() - 24].to_vec(); + let len = (old.len() - 4) as u32; + old[..4].copy_from_slice(&len.to_le_bytes()); + assert_eq!(decode(&old).unwrap(), Msg::ContainerStats(ContainerStats::default())); + // A truncated trailing section is rejected rather than partially decoded. + let mut partial = frame[..frame.len() - 8].to_vec(); + let len = (partial.len() - 4) as u32; + partial[..4].copy_from_slice(&len.to_le_bytes()); + assert_eq!(decode(&partial), Err(DecodeError::Truncated)); + } + #[test] fn round_trip() { round(Msg::Hello(Hello { protocol: PROTOCOL, init_start_ns: 1, ready_ns: 2, mem_total_kib: 3, mem_available_kib: 4 })); @@ -1468,18 +1722,26 @@ mod tests { round(Msg::Shutdown); round(Msg::Error("boom")); round(Msg::StatsRequest); - let full = Stats { uptime_ns: 5, mem_total_kib: 6, mem_available_kib: 7, agent_rss_kib: 8, mem_used_kib: 9, mem_stall: 9173, oom_kills: 2, mem_balloon_kib: Some(4096) }; + let full = Stats { uptime_ns: 5, mem_total_kib: 6, mem_available_kib: 7, agent_rss_kib: 8, mem_used_kib: 9, mem_stall: 9173, oom_kills: 2, mem_balloon_kib: Some(4096), mem_committed_kib: Some(2_097_152) }; round(Msg::Stats(full)); - round(Msg::Stats(Stats { mem_balloon_kib: Some(0), ..full })); + round(Msg::Stats(Stats { mem_balloon_kib: Some(0), mem_committed_kib: Some(0), ..full })); round(Msg::Stats(Stats { mem_balloon_kib: None, ..full })); + round(Msg::Stats(Stats { mem_committed_kib: None, ..full })); + round(Msg::Stats(Stats { mem_balloon_kib: None, mem_committed_kib: None, ..full })); + round(Msg::DiskUsageQuery); + round(Msg::DiskUsage { in_use: 17_300_000_000, capacity: 68_719_476_736 }); + round(Msg::TrimDisk); + round(Msg::DiskTrimmed { trimmed: 12_100_000_000, in_use: 17_300_000_000, capacity: 68_719_476_736 }); // Older agents' Stats, without the later words, still decode. let mut buf = Vec::new(); Msg::Stats(full).encode(&mut buf); - let no_balloon = Stats { mem_balloon_kib: None, ..full }; - assert_eq!(decode(&buf[..buf.len() - 8]).unwrap(), Msg::Stats(no_balloon)); + let no_committed = Stats { mem_committed_kib: None, ..full }; + assert_eq!(decode(&buf[..buf.len() - 8]).unwrap(), Msg::Stats(no_committed)); + let no_balloon = Stats { mem_balloon_kib: None, ..no_committed }; + assert_eq!(decode(&buf[..buf.len() - 16]).unwrap(), Msg::Stats(no_balloon)); let no_memory_words = Stats { mem_stall: 0, oom_kills: 0, ..no_balloon }; - assert_eq!(decode(&buf[..buf.len() - 24]).unwrap(), Msg::Stats(no_memory_words)); - assert_eq!(decode(&buf[..buf.len() - 32]).unwrap(), Msg::Stats(Stats { mem_used_kib: 0, ..no_memory_words })); + assert_eq!(decode(&buf[..buf.len() - 32]).unwrap(), Msg::Stats(no_memory_words)); + assert_eq!(decode(&buf[..buf.len() - 40]).unwrap(), Msg::Stats(Stats { mem_used_kib: 0, ..no_memory_words })); round(Msg::LayerQuery("sha256:ab")); round(Msg::LayerStatus(true)); round(Msg::LayerBegin(LayerBegin { digest: "sha256:ab", media_type: "x+gzip", size: 9 })); @@ -1519,21 +1781,28 @@ mod tests { #[test] fn stats_none_balloon_keeps_wire_offset() { - let base = Stats { uptime_ns: 5, mem_total_kib: 6, mem_available_kib: 7, agent_rss_kib: 8, mem_used_kib: 9, mem_stall: 10, oom_kills: 1, mem_balloon_kib: Some(4096) }; - let absent = Stats { mem_balloon_kib: None, ..base }; - let mut with_balloon = Vec::new(); - let mut without_balloon = Vec::new(); - Msg::Stats(base).encode(&mut with_balloon); - Msg::Stats(absent).encode(&mut without_balloon); - assert_eq!(without_balloon.len(), with_balloon.len()); - // Appending a future 9th word must not be decoded into mem_balloon_kib. - let mut extended = without_balloon.clone(); + let base = Stats { uptime_ns: 5, mem_total_kib: 6, mem_available_kib: 7, agent_rss_kib: 8, mem_used_kib: 9, mem_stall: 10, oom_kills: 1, mem_balloon_kib: Some(4096), mem_committed_kib: Some(8192) }; + let no_balloon_with_commit = Stats { mem_balloon_kib: None, ..base }; + round(Msg::Stats(no_balloon_with_commit)); + let absent = Stats { mem_balloon_kib: None, mem_committed_kib: None, ..base }; + let mut with_optional = Vec::new(); + let mut without_optional = Vec::new(); + Msg::Stats(base).encode(&mut with_optional); + Msg::Stats(absent).encode(&mut without_optional); + assert_eq!(without_optional.len(), with_optional.len()); + // Appending a future 10th word must not be decoded into mem_balloon_kib or mem_committed_kib. + let mut extended = without_optional.clone(); extended.extend_from_slice(&42u64.to_le_bytes()); let len = (extended.len() - 4) as u32; extended[..4].copy_from_slice(&len.to_le_bytes()); assert_eq!(decode(&extended).unwrap(), Msg::Stats(absent)); - // An older 7-word agent omitting the 8th word still decodes as None. - let mut old = without_balloon[..without_balloon.len() - 8].to_vec(); + // An older 8-word agent omitting mem_committed_kib decodes it as None while preserving mem_balloon_kib. + let mut eight_word = with_optional[..with_optional.len() - 8].to_vec(); + let len = (eight_word.len() - 4) as u32; + eight_word[..4].copy_from_slice(&len.to_le_bytes()); + assert_eq!(decode(&eight_word).unwrap(), Msg::Stats(Stats { mem_committed_kib: None, ..base })); + // An older 7-word agent omitting both optional words still decodes both as None. + let mut old = without_optional[..without_optional.len() - 16].to_vec(); let len = (old.len() - 4) as u32; old[..4].copy_from_slice(&len.to_le_bytes()); assert_eq!(decode(&old).unwrap(), Msg::Stats(absent)); @@ -1543,10 +1812,11 @@ mod tests { fn run_spec_lists_survive_encoding() { let mut buf = Vec::new(); let net = Net { bridge: "kiri0", ip: [172, 17, 0, 2], prefix: 16, gateway: [172, 17, 0, 1], extra_hosts: &["1.2.3.4 x"], dns_names: &["web"], opts: &["netns=c0", "nameserver=8.8.8.8"] }; - let limits = Limits { memory_max: 256 << 20, cpu_quota: 150_000, cpu_period: 100_000, cpu_weight: 100, pids_max: 64, shm_size: 1 << 20 }; + let limits = Limits { memory_max: 256 << 20, cpu_quota: 150_000, cpu_period: 100_000, cpu_weight: 100, pids_max: 64, shm_size: 1 << 20, swap_max: 512 << 20 }; encode_run(&mut buf, "c1", &["sha256:top", "sha256:base"], &["echo", "hi"], &["A=1"], "/", "", "c1", 3, net, &["/a\t/b\tro"], &limits, 0b101, &["rlimit\t7\t1024\t2048"], &[]); let Msg::Run(r) = decode(&buf).unwrap() else { panic!() }; assert_eq!(r.id, "c1"); + assert_eq!(r.limits, limits); assert_eq!(r.layers.iter().collect::>(), ["sha256:top", "sha256:base"]); assert_eq!(r.argv.iter().collect::>(), ["echo", "hi"]); assert_eq!(r.env.len(), 1); @@ -1588,7 +1858,7 @@ mod tests { fn the_protocol_version_covers_the_seccomp_field() { // An agent from before `RunSpec::seccomp` says 4, and the host refuses // it (guest.rs compares the Hello's version with this one). - assert!(PROTOCOL >= 5); + const { assert!(PROTOCOL >= 5) }; let mut buf = Vec::new(); Msg::Hello(Hello { protocol: PROTOCOL, init_start_ns: 1, ready_ns: 2, mem_total_kib: 3, mem_available_kib: 4 }).encode(&mut buf); let Msg::Hello(h) = decode(&buf).unwrap() else { panic!() }; @@ -1699,18 +1969,51 @@ mod tests { const { assert!(PROTOCOL >= 8) }; } + #[test] + fn the_protocol_version_covers_set_egress_routes() { + // An agent from before `SetEgressRoutes` answers it with an error + // that the host would take as the reply to its next request. + const { assert!(PROTOCOL >= 11) }; + let mut buf = Vec::new(); + encode_set_egress_routes(&mut buf, &["10.0.5.0/24"]); + assert!(takes_no_reply(&buf)); + } + + #[test] + fn the_protocol_version_covers_swap_max() { + // An agent from before `Limits::swap_max` reads the limits one field short. + const { assert!(PROTOCOL >= 9) }; + assert_eq!(Limits::default().swap_max, NO_LIMIT); + } + + #[test] + fn memory_pressure_payload_survives_encoding_and_covers_protocol() { + // An agent from before `MemoryPressure`'s payload sends a bare frame + // with neither field; the host rejects it on `Hello`. + const { assert!(PROTOCOL >= 10) }; + round(Msg::MemoryPressure(MemoryPressure { mem_available_kib: 0, mem_stall: 0 })); + round(Msg::MemoryPressure(MemoryPressure { mem_available_kib: 524_288, mem_stall: 1234 })); + let mut bare = Vec::new(); + frame(&mut bare, kind::MEMORY_PRESSURE, |_| {}); + assert_eq!(decode(&bare), Err(DecodeError::Truncated)); + let mut half = Vec::new(); + frame(&mut half, kind::MEMORY_PRESSURE, |o| put_u64(o, 4096)); + assert_eq!(decode(&half), Err(DecodeError::Truncated)); + } + #[test] fn fs_messages_survive_encoding() { round(Msg::FsStatRequest { id: "c1", path: "/etc" }); round(Msg::FsStat(FsEntry { name: "etc", mode: 0o40755, size: 4096, mtime: 1_700_000_000, mtime_nsec: 5, ino: 77 })); round(Msg::FsRead { id: "c1", path: "/etc/os-release", offset: 10, len: 4096 }); round(Msg::FsData(b"NAME=Alpine")); - round(Msg::MemoryPressure); + round(Msg::FsReadLink { id: "c1", path: "/usr/bin/X11" }); + round(Msg::MemoryPressure(MemoryPressure { mem_available_kib: 1, mem_stall: 2 })); round(Msg::RemoveVolume { name: "pgdata" }); round(Msg::RemoveBridge { bridge: "kiri3" }); round(Msg::CopyStat { entry: FsEntry { name: "hosts", mode: 0o100644, size: 9, mtime: 3, mtime_nsec: 4, ino: 5 }, link: "" }); round(Msg::CopyDone); - round(Msg::Update { id: "c1", limits: Limits { memory_max: 1, cpu_quota: 2, cpu_period: 3, cpu_weight: 4, pids_max: 5, shm_size: 6 } }); + round(Msg::Update { id: "c1", limits: Limits { memory_max: 1, cpu_quota: 2, cpu_period: 3, cpu_weight: 4, pids_max: 5, shm_size: 6, swap_max: NO_LIMIT } }); round(Msg::Freeze { id: "c1", frozen: true }); round(Msg::StatsQuery { id: "c1" }); round(Msg::ContainerStats(ContainerStats { read_ns: 1, mem_current: 2, online_cpus: 4, rx_bytes: 9, io_write_bytes: 11, ..Default::default() })); @@ -1731,6 +2034,11 @@ mod tests { let Msg::FsEvents(lines) = decode(&buf).unwrap() else { panic!() }; assert_eq!(lines.iter().collect::>(), ["M\t/mnt/mac/Users/a/app/main.js", "D\t/mnt/mac/Users/a/app/old.js"]); let mut buf = Vec::new(); + encode_set_egress_routes(&mut buf, &["10.0.5.0/24", "198.18.0.0/15"]); + let Msg::SetEgressRoutes(routes) = decode(&buf).unwrap() else { panic!() }; + assert_eq!(routes.iter().collect::>(), ["10.0.5.0/24", "198.18.0.0/15"]); + assert!(takes_no_reply(&buf)); + let mut buf = Vec::new(); encode_listening(&mut buf, &[" 0: 00000000:11D7 00000000:0000 0A"]); let Msg::Listening(lines) = decode(&buf).unwrap() else { panic!() }; assert_eq!(lines.iter().collect::>(), [" 0: 00000000:11D7 00000000:0000 0A"]); @@ -1753,15 +2061,28 @@ mod tests { round(Msg::Route { dst: [10, 43, 0, 0], prefix: 16, via: [172, 17, 0, 4], add: true }); round(Msg::UplinkQuery); round(Msg::Uplink { ip: [192, 168, 64, 18], gateway: [192, 168, 64, 1] }); + round(Msg::SetUplink { ip: [192, 168, 64, 2], prefix: 24, gateway: [192, 168, 64, 1], dns: [192, 168, 64, 1] }); + round(Msg::SetUplink { ip: [10, 0, 0, 5], prefix: 16, gateway: [10, 0, 0, 1], dns: [0, 0, 0, 0] }); round(Msg::Ack); let mut buf = Vec::new(); - encode_copy(&mut buf, copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS, &["sha256:a", "sha256:b"]); + let mounts = ["/var/lib/kiri/volumes/pg/_data\t/var/lib/postgresql/data\tcreate,copyup", "/host/cfg\t/etc/app\tro"]; + encode_copy(&mut buf, copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS | copy_flags::READONLY_ROOTFS, &["sha256:a", "sha256:b"], &mounts); let Msg::Copy(c) = decode(&buf).unwrap() else { panic!() }; - assert_eq!((c.op, c.id, c.path, c.flags), (copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS)); + assert_eq!((c.op, c.id, c.path, c.flags), (copy_op::IN, "c1", "/etc", copy_flags::KEEP_OWNERS | copy_flags::READONLY_ROOTFS)); assert_eq!(c.layers.iter().collect::>(), ["sha256:a", "sha256:b"]); + assert_eq!(c.mounts.iter().collect::>(), mounts); let mut again = Vec::new(); Msg::Copy(c).encode(&mut again); assert_eq!(buf, again); + // An older daemon's Copy frame without the mount list still decodes. + let mut old = Vec::new(); + encode_copy(&mut old, copy_op::OUT, "c1", "/etc", 0, &["sha256:a"], &[]); + old.truncate(old.len() - 4); + let len = (old.len() - 4) as u32; + old[..4].copy_from_slice(&len.to_le_bytes()); + let Msg::Copy(old_c) = decode(&old).unwrap() else { panic!() }; + assert_eq!(old_c.layers.iter().collect::>(), ["sha256:a"]); + assert!(old_c.mounts.is_empty()); let mut buf = Vec::new(); let entries = [ FsEntry { name: "a", mode: 0o100644, size: 1, mtime: 2, mtime_nsec: 9, ino: 1 }, @@ -1784,4 +2105,187 @@ mod tests { buf.truncate(buf.len() - 1); assert_eq!(decode(&buf), Err(DecodeError::Truncated)); } + + #[test] + fn oversized_replies_stay_within_max_frame() { + // A single `top` line far larger than MAX_FRAME (a container process + // with a huge cmdline): the frame must stay decodable, not overflow. + let huge = "x".repeat(MAX_FRAME * 2); + let mut buf = Vec::new(); + encode_top(&mut buf, core::slice::from_ref(&huge)); + assert!(buf.len() <= MAX_FRAME, "top frame {} > MAX_FRAME", buf.len()); + assert!(frame_len(&buf[..4].try_into().unwrap()).is_ok()); + let Msg::Top(lines) = decode(&buf).unwrap() else { panic!() }; + let got: Vec<_> = lines.iter().collect(); + assert_eq!(got.len(), 1); + assert!(got[0].len() < huge.len()); // truncated to fit + + // Many long lines: trailing ones are dropped, the frame still fits. + let many: Vec = (0..5000).map(|_| "y".repeat(500)).collect(); + buf.clear(); + encode_top(&mut buf, &many); + assert!(buf.len() <= MAX_FRAME); + let Msg::Top(lines) = decode(&buf).unwrap() else { panic!() }; + let kept = lines.iter().count(); + assert!(kept > 0 && kept < many.len()); + + // Same for a directory listing with thousands of max-length names. + let names: Vec = (0..5000).map(|_| "n".repeat(255)).collect(); + let entries: Vec> = names + .iter() + .map(|n| FsEntry { name: n, mode: 0o100644, size: 0, mtime: 0, mtime_nsec: 0, ino: 1 }) + .collect(); + buf.clear(); + encode_fs_list(&mut buf, &entries); + assert!(buf.len() <= MAX_FRAME, "fs_list frame {} > MAX_FRAME", buf.len()); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + let kept = fs_entries(count, raw).count(); + assert!(kept > 0 && kept < entries.len()); + } + + #[test] + fn capped_str_list_replies_fit_at_exact_boundary_and_utf8() { + type ListEnc = fn(&mut Vec, &[String]); + let encoders: &[(&str, ListEnc)] = &[ + ("top", encode_top::), + ("usage", encode_usage::), + ("usb_nodes", encode_usb_nodes::), + ("fs_events", encode_fs_events::), + ("set_egress_routes", encode_set_egress_routes::), + ("listening", encode_listening::), + ]; + // Exact single-item fit (MAX_BODY - 8 bytes) and 1 byte over. + let exact = "a".repeat(MAX_BODY - 8); + let over = "a".repeat(MAX_BODY - 7); + for &(name, enc) in encoders { + let mut buf = Vec::new(); + enc(&mut buf, core::slice::from_ref(&exact)); + assert_eq!(buf.len(), MAX_FRAME, "{name}: exact fit should hit MAX_FRAME"); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len()), "{name}: exact frame_len"); + assert!(decode(&buf).is_ok(), "{name}: exact decode"); + + buf.clear(); + enc(&mut buf, core::slice::from_ref(&over)); + assert_eq!(buf.len(), MAX_FRAME, "{name}: 1-byte-over should cap to MAX_FRAME"); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len()), "{name}: over frame_len"); + assert!(decode(&buf).is_ok(), "{name}: over decode"); + + // 1.5 MiB of 2-byte (`é`) and 4-byte (`🦀`) UTF-8 at every alignment 0..4. + for ch in ["é", "🦀"] { + for pad in 0..4 { + let mut huge = "p".repeat(pad); + let reps = (MAX_FRAME + MAX_FRAME / 2) / ch.len(); + for _ in 0..reps { + huge.push_str(ch); + } + buf.clear(); + enc(&mut buf, &[huge]); + assert!(buf.len() <= MAX_FRAME, "{name} {ch} pad={pad}: {} > MAX_FRAME", buf.len()); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + assert!(decode(&buf).is_ok(), "{name} {ch} pad={pad}: decode failed"); + } + } + + // 20,000 entries crossing MAX_FRAME, also when appending after existing bytes in buf. + let many: Vec = (0..20_000).map(|i| format!("line-{i:05}-{}", "z".repeat(80))).collect(); + buf.clear(); + buf.extend_from_slice(b"prefix"); + enc(&mut buf, &many); + let frame = &buf[6..]; + assert!(frame.len() <= MAX_FRAME, "{name}: many frame {} > MAX_FRAME", frame.len()); + assert_eq!(frame_len(&frame[..4].try_into().unwrap()), Ok(frame.len())); + assert!(decode(frame).is_ok(), "{name}: many decode failed"); + } + + // Short first item followed by an oversized second item: keeps the first + // and drops the second cleanly without exceeding MAX_FRAME. + let mut buf = Vec::new(); + encode_top(&mut buf, &["first".to_owned(), "x".repeat(MAX_FRAME * 2), "third".to_owned()]); + assert!(buf.len() <= MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::Top(lines) = decode(&buf).unwrap() else { panic!() }; + assert_eq!(lines.iter().collect::>(), ["first"]); + } + + #[test] + fn fs_list_stays_within_max_frame_at_boundary_and_utf8() { + // Each encoded entry takes 36 + name.len() bytes; body starts with 4-byte count. + // Pick an entry name length that lands right on MAX_BODY: + // MAX_BODY = 1_048_570; 4 + 10_485 * 100 (64-byte names) = 1_048_504, + // leaving 66 bytes -> a 30-byte name fills 36 + 30 = 66 bytes to hit + // MAX_BODY (and MAX_FRAME) to the exact byte. + let mut names: Vec = (0..10_485).map(|i| format!("{i:064}")).collect(); + names.push("b".repeat(30)); + names.push("overflow".to_owned()); + let entries: Vec> = names + .iter() + .enumerate() + .map(|(i, n)| FsEntry { name: n, mode: 0o100644, size: i as u64, mtime: 1, mtime_nsec: 2, ino: i as u64 }) + .collect(); + let mut buf = Vec::new(); + encode_fs_list(&mut buf, &entries); + assert_eq!(buf.len(), MAX_FRAME, "exact boundary entries should hit MAX_FRAME"); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(MAX_FRAME)); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + assert_eq!(count as usize, 10_486); + let decoded: Vec<_> = fs_entries(count, raw).collect(); + assert_eq!(decoded, entries[..10_486]); + + // 20,000 entries with max-length multi-byte UTF-8 names. + let utf8_name = "🦀".repeat(63); // 252 bytes (<= NAME_MAX 255) + let utf8_entries: Vec> = (0..20_000) + .map(|i| FsEntry { name: &utf8_name, mode: 0o100644, size: i as u64, mtime: 0, mtime_nsec: 0, ino: i as u64 }) + .collect(); + buf.clear(); + encode_fs_list(&mut buf, &utf8_entries); + assert!(buf.len() <= MAX_FRAME, "utf8 fs_list {} > MAX_FRAME", buf.len()); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + let kept = fs_entries(count, raw).count(); + assert!(kept > 0 && kept < utf8_entries.len()); + + // Single impossibly huge entry (> MAX_BODY): encodes 0 entries, still decodable. + let giant = "g".repeat(MAX_FRAME); + buf.clear(); + encode_fs_list(&mut buf, &[FsEntry { name: &giant, mode: 0o100644, size: 0, mtime: 0, mtime_nsec: 0, ino: 1 }]); + assert!(buf.len() <= MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::FsList { count, raw } = decode(&buf).unwrap() else { panic!() }; + assert_eq!(count, 0); + assert_eq!(fs_entries(count, raw).count(), 0); + } + + #[test] + fn oversized_error_stays_within_max_frame_and_valid_utf8() { + let mut buf = Vec::new(); + let exact = "e".repeat(MAX_BODY); + Msg::Error(&exact).encode(&mut buf); + assert_eq!(buf.len(), MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(MAX_FRAME)); + assert_eq!(decode(&buf).unwrap(), Msg::Error(&exact)); + + let over = "e".repeat(MAX_BODY + 1); + buf.clear(); + Msg::Error(&over).encode(&mut buf); + assert_eq!(buf.len(), MAX_FRAME); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(MAX_FRAME)); + assert_eq!(decode(&buf).unwrap(), Msg::Error(&exact)); + + for ch in ["é", "🦀"] { + for pad in 0..4 { + let mut huge = "p".repeat(pad); + let reps = (MAX_FRAME + MAX_FRAME / 2) / ch.len(); + for _ in 0..reps { + huge.push_str(ch); + } + buf.clear(); + Msg::Error(&huge).encode(&mut buf); + assert!(buf.len() <= MAX_FRAME, "error {ch} pad={pad}: {} > MAX_FRAME", buf.len()); + assert_eq!(frame_len(&buf[..4].try_into().unwrap()), Ok(buf.len())); + let Msg::Error(got) = decode(&buf).unwrap() else { panic!() }; + assert!(huge.starts_with(got)); + assert!(got.len() <= MAX_BODY && got.len() >= MAX_BODY - 3); + } + } + } } diff --git a/crates/kiri-vmm/src/process.rs b/crates/kiri-vmm/src/process.rs index fda1cf6ed..96e778446 100644 --- a/crates/kiri-vmm/src/process.rs +++ b/crates/kiri-vmm/src/process.rs @@ -132,6 +132,11 @@ impl Vm { })?; let mut cmd = Command::new(&cfg.initrd); cmd.env("KIRI_AGENT_DIR", &dir).env_remove("KIRI_SOCKET"); + if let Some(data) = &cfg.disk { + cmd.env("KIRI_AGENT_DATA", data); + } else { + cmd.env_remove("KIRI_AGENT_DATA"); + } if let Some(fd) = cfg.console { cmd.stderr(std::process::Stdio::from(fd.try_clone()?)).stdout(std::process::Stdio::from(fd)); } else { diff --git a/crates/kiri-win/Cargo.toml b/crates/kiri-win/Cargo.toml index 36288d85f..279269025 100644 --- a/crates/kiri-win/Cargo.toml +++ b/crates/kiri-win/Cargo.toml @@ -11,10 +11,15 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" sha2 = "0.11" # Share in the window: crates/kiri/src/share.rs, the same library as -# `kiri share`, with what it needs for the TLS connection to the edge. +# `kiri share`. Its roots come from crates/kiri-image/src/roots.rs, compiled +# by path, so kiri-win needs that file's crates instead of kiri-image. kiri-share-proto = { path = "../kiri-share-proto" } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } -webpki-roots = "1" +rustls-native-certs = "0.8" +rustls-pki-types = "1" +webpki-root-certs = "1" +# roots.rs's distrusted roots: the Disallowed store and disabled ROOT entries. +schannel = "0.1" libc = "0.2" windows-sys = { version = "0.52", features = ["Win32_Foundation", "Win32_Globalization", "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_RemoteDesktop", "Win32_System_Services", "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 @@ -25,6 +30,8 @@ windows = { version = "0.62", features = ["Win32_Foundation", "Win32_Graphics_Dw [dev-dependencies] # crates/kiri-win/src/refuse.rs's tests, on any host. serde_json = "1" +# share.rs's tests (compiled here by path) make a certificate authority. +rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "crypto"] } [build-dependencies] # The icon resource in kiri-win.exe (build.rs). diff --git a/crates/kiri-win/src/app.rs b/crates/kiri-win/src/app.rs index 9959a00d7..e88d5cf42 100644 --- a/crates/kiri-win/src/app.rs +++ b/crates/kiri-win/src/app.rs @@ -142,6 +142,13 @@ pub struct Ui { loaded: bool, /// The webview has been asked for. started: bool, + /// Counts the webviews asked for: one that arrives after the window + /// let go of it (closed while WebView2 was still making it) is dropped. + generation: u64, + /// The window let go of its webview (Settings → Closing the window → + /// Close): what the engine sends meanwhile is dropped, not queued, as + /// the page asks for everything again when it next loads. + released: bool, menu: Menu, /// Every message the page sends; called outside the borrow of UI. on_message: Rc, @@ -186,6 +193,42 @@ pub fn pick_file(title: &str, filters: &[(String, String)], done: impl FnOnce(Op } } +/// Settings → Storage → Change…: Windows' own folder picker (`FOS_PICKFOLDERS`) +/// over the window, on its thread, outside `with_ui`. `done` gets the chosen +/// folder, or None when cancelled, on a thread of its own. +pub fn pick_folder(title: &str, done: impl FnOnce(Option) + Send + 'static) { + let title = HSTRING::from(title); + BARE.lock().unwrap_or_else(PoisonError::into_inner).push(Box::new(move |hwnd| { + // SAFETY: on the window's thread, where COM is initialised (run). + let path = unsafe { folder_dialog(hwnd, &title) }.ok().flatten(); + std::thread::spawn(move || done(path)); + })); + let hwnd = WINDOW.load(Ordering::SeqCst); + if hwnd != 0 { + // SAFETY: posting to our own window; a closed one just drops it. + let _ = unsafe { PostMessageW(Some(HWND(hwnd as _)), WM_RUN, WPARAM(0), LPARAM(0)) }; + } +} + +/// IFileOpenDialog with `FOS_PICKFOLDERS`: one local folder on disk, or None when cancelled. +unsafe fn folder_dialog(owner: HWND, title: &HSTRING) -> windows::core::Result> { + use windows::Win32::System::Com::{CoCreateInstance, CoTaskMemFree, CLSCTX_INPROC_SERVER}; + use windows::Win32::UI::Shell::{FileOpenDialog, IFileOpenDialog, FOS_FORCEFILESYSTEM, FOS_PATHMUSTEXIST, FOS_PICKFOLDERS, SIGDN_FILESYSPATH}; + // SAFETY: COM calls on this thread's apartment. + unsafe { + let d: IFileOpenDialog = CoCreateInstance(&FileOpenDialog, None, CLSCTX_INPROC_SERVER)?; + d.SetTitle(title)?; + d.SetOptions(d.GetOptions()? | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST)?; + if d.Show(Some(owner)).is_err() { + return Ok(None); + } + let name = d.GetResult()?.GetDisplayName(SIGDN_FILESYSPATH)?; + let path = name.to_string().ok(); + CoTaskMemFree(Some(name.0 as *const _)); + Ok(path.map(std::path::PathBuf::from)) + } +} + /// Jobs that need only the window's handle and run outside with_ui (a modal /// dialog), on the window's thread. type BareJob = Box; @@ -262,8 +305,8 @@ unsafe fn foreground(hwnd: HWND) { /// Shows the window, making its webview the first time. The webview is /// made outside the borrow of UI: its callbacks borrow it too. fn show() { - if let Some(Some(hwnd)) = with_ui(Ui::show) { - if let Err(e) = start_webview(hwnd) { + if let Some(Some((hwnd, generation))) = with_ui(Ui::show) { + if let Err(e) = start_webview(hwnd, generation) { crate::serve::log(&format!("webview: {e}")); } } @@ -278,12 +321,14 @@ impl Ui { // SAFETY: a live webview, on its own thread. let _ = unsafe { w.ExecuteScript(*js.as_ref().as_pcwstr(), &done) }; } + _ if self.released => {} _ => self.pending.push(js), } } - /// Shows the window; the window to make a webview for, the first time. - fn show(&mut self) -> Option { + /// Shows the window; the window to make a webview for (and which one + /// it is) when it has none. + fn show(&mut self) -> Option<(HWND, u64)> { // SAFETY: our window, on its thread. unsafe { let _ = ShowWindow(self.hwnd, SW_RESTORE); @@ -294,7 +339,12 @@ impl Ui { // whatever was behind it: once more, shortly. SetTimer(Some(self.hwnd), TIMER_FOREGROUND, 400, None); } - (!std::mem::replace(&mut self.started, true)).then_some(self.hwnd) + if std::mem::replace(&mut self.started, true) { + return None; + } + self.released = false; + self.generation += 1; + Some((self.hwnd, self.generation)) } pub fn hide(&mut self) { @@ -304,6 +354,35 @@ impl Ui { } } + /// The window's close button: hidden, as it always was, or (Settings → + /// Closing the window → Close) hidden and its webview let go, which ends + /// WebView2's processes. The tray icon and the pipe stay; the window + /// makes a new webview when it opens again. Setup's page keeps its + /// progress in the page, so the window only hides during setup. + fn close(&mut self) { + self.hide(); + if in_setup() || crate::engine::prefs()["closeButton"] != "close" { + return; + } + let controller = self.controller.take(); + self.webview = None; + self.started = false; + self.released = true; + self.loaded = false; + self.pending.clear(); + STRING_LOAD.set(false); + if let Some(c) = controller { + // SAFETY: our window's controller, on its thread. Its handlers + // find the window busy (with_ui gives None) and do nothing. + unsafe { + let _ = c.Close(); + } + } + // What the page followed (terminals, a log, live figures) goes + // with it, as when Linux's window closes. + crate::engine::page_gone(); + } + pub fn visible(&self) -> bool { // SAFETY: our window. unsafe { IsWindowVisible(self.hwnd).as_bool() } @@ -411,7 +490,7 @@ pub fn run(show: bool, setup: bool, on_message: impl Fn(String) + 'static, on_tr SendMessageW(hwnd, WM_SETICON, Some(WPARAM(ICON_SMALL as usize)), Some(LPARAM(i.0 as isize))); } } - UI.with(|u| *u.borrow_mut() = Some(Ui { hwnd, webview: None, controller: None, pending: Vec::new(), loaded: false, started: false, menu: Menu::default(), on_message: Rc::new(on_message) })); + UI.with(|u| *u.borrow_mut() = Some(Ui { hwnd, webview: None, controller: None, pending: Vec::new(), loaded: false, started: false, generation: 0, released: false, menu: Menu::default(), on_message: Rc::new(on_message) })); tray(hwnd, small, NIM_ADD); if show { self::show(); @@ -541,7 +620,12 @@ fn tray_menu(hwnd: HWND) { ID_START => tray_cmd("start"), ID_STOP => tray_cmd("stop"), ID_UPDATE => tray_cmd("update"), - ID_QUIT => PostQuitMessage(0), + ID_QUIT => { + if crate::engine::prefs()["stopOnQuit"] == true { + crate::engine::stop(); + } + PostQuitMessage(0); + } n if n >= ID_CONTAINER => { if let Some((id, _)) = menu.running.get(n - ID_CONTAINER) { show(); @@ -567,7 +651,7 @@ extern "system" fn window_proc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPA } } WM_SIZE => with_ui_soon(|ui| ui.resize()), - WM_CLOSE => with_ui_soon(Ui::hide), + WM_CLOSE => with_ui_soon(Ui::close), WM_TRAY => match (lparam.0 & 0xffff) as u32 { WM_LBUTTONUP => { if with_ui(|ui| ui.visible()) == Some(true) { @@ -598,7 +682,7 @@ fn data_dir() -> HSTRING { HSTRING::from(dir.as_os_str()) } -fn start_webview(hwnd: HWND) -> windows::core::Result<()> { +fn start_webview(hwnd: HWND, generation: u64) -> windows::core::Result<()> { let env_done = CreateCoreWebView2EnvironmentCompletedHandler::create(Box::new(move |result, env: Option| { result?; let Some(env) = env else { return Ok(()) }; @@ -606,7 +690,7 @@ fn start_webview(hwnd: HWND) -> windows::core::Result<()> { let ctl_done = CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |result, ctl: Option| { result?; if let Some(ctl) = ctl - && let Err(e) = webview_ready(hwnd, &env_for_page, ctl) + && let Err(e) = webview_ready(hwnd, generation, &env_for_page, ctl) { crate::serve::log(&format!("webview: {e}")); } @@ -619,7 +703,13 @@ fn start_webview(hwnd: HWND) -> windows::core::Result<()> { unsafe { CreateCoreWebView2EnvironmentWithOptions(PCWSTR::null(), &data_dir(), None, &env_done) } } -fn webview_ready(hwnd: HWND, env: &ICoreWebView2Environment, ctl: ICoreWebView2Controller) -> windows::core::Result<()> { +fn webview_ready(hwnd: HWND, generation: u64, env: &ICoreWebView2Environment, ctl: ICoreWebView2Controller) -> windows::core::Result<()> { + // Closed while WebView2 was making it: not wanted any more. A busy + // window (None) is one still showing, so it keeps the webview. + if with_ui(|ui| ui.started && ui.generation == generation) == Some(false) { + // SAFETY: the new controller, on the window's thread. + return unsafe { ctl.Close() }; + } // SAFETY: the new controller and its webview, on the window's thread. unsafe { let mut r = RECT::default(); diff --git a/crates/kiri-win/src/client.rs b/crates/kiri-win/src/client.rs index a8e461b2c..7c7599a58 100644 --- a/crates/kiri-win/src/client.rs +++ b/crates/kiri-win/src/client.rs @@ -3,14 +3,71 @@ //! crates/kiri/src/client.rs over the unix socket: one short connection //! per request, and long-lived ones for `/events`, logs and stats. +#![cfg_attr(not(windows), allow(dead_code))] + use std::io::{self, BufRead, BufReader, Read, Write}; -use std::sync::{Arc, OnceLock}; +#[cfg(windows)] +use std::sync::Arc; +use std::sync::OnceLock; use std::time::Duration; use serde_json::Value; +#[cfg(windows)] use crate::pipe::Pipe; +#[cfg(test)] +mod mock { + use std::cell::RefCell; + use std::collections::VecDeque; + use std::io::{self, Cursor, Read, Write}; + use std::sync::{Arc, Mutex}; + + pub struct Recorded { + pub wire: Arc>>, + pub reply: Cursor>, + } + + impl Read for Recorded { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + self.reply.read(buf) + } + } + + impl Write for Recorded { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.wire.lock().unwrap().extend_from_slice(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + + type Queue = VecDeque<(Arc>>, Vec)>; + thread_local! { + static QUEUE: RefCell = const { RefCell::new(VecDeque::new()) }; + } + + pub fn push(reply: &[u8]) -> Arc>> { + let wire = Arc::new(Mutex::new(Vec::new())); + QUEUE.with(|q| q.borrow_mut().push_back((wire.clone(), reply.to_vec()))); + wire + } + + pub fn take() -> Option { + QUEUE.with(|q| q.borrow_mut().pop_front()).map(|(wire, reply)| Recorded { wire, reply: Cursor::new(reply) }) + } +} + +/// Queues one canned HTTP response for the next client call on this thread, +/// returning the buffer that captures the request bytes written to the wire. +#[cfg(test)] +pub(crate) fn mock_reply(reply: &[u8]) -> std::sync::Arc>> { + mock::push(reply) +} + static PIPE: OnceLock = OnceLock::new(); /// The pipe the daemon is served on (once, at start). @@ -23,6 +80,7 @@ pub fn pipe() -> String { PIPE.get().cloned().unwrap_or_else(|| r"\\.\pipe\kiri".to_owned()) } +#[cfg(windows)] fn connect() -> io::Result> { Pipe::open(PIPE.get().map_or(r"\\.\pipe\kiri", String::as_str)).map(Arc::new) } @@ -30,17 +88,49 @@ fn connect() -> io::Result> { /// A connection as a byte stream. With `timeout`, a read that gets nothing /// for that long fails (TimedOut) instead of waiting on: for the ping, which /// gates the engine thread at start and must never hang it. -struct Conn(Arc, Option); +enum Conn { + #[cfg(windows)] + Pipe(Arc, Option), + #[cfg(test)] + Mock(mock::Recorded), +} + +fn open_conn(timeout: Option) -> io::Result { + #[cfg(test)] + if let Some(m) = mock::take() { + let _ = timeout; + return Ok(Conn::Mock(m)); + } + #[cfg(windows)] + { + Ok(Conn::Pipe(connect()?, timeout)) + } + #[cfg(not(windows))] + { + let _ = timeout; + Err(io::Error::new(io::ErrorKind::NotConnected, "no mock response queued")) + } +} impl Read for Conn { fn read(&mut self, buf: &mut [u8]) -> io::Result { - self.0.read_client(buf, self.1) + match self { + #[cfg(windows)] + Conn::Pipe(p, timeout) => p.read_client(buf, *timeout), + #[cfg(test)] + Conn::Mock(m) => m.read(buf), + } } } impl Write for Conn { fn write(&mut self, buf: &[u8]) -> io::Result { - Write::write(&mut &*self.0, buf) + match self { + #[cfg(windows)] + Conn::Pipe(p, _) => Write::write(&mut &**p, buf), + #[cfg(test)] + Conn::Mock(m) => m.write(buf), + } } fn flush(&mut self) -> io::Result<()> { @@ -150,7 +240,7 @@ const QUICK: Duration = Duration::from_secs(3); /// `request_with`, failing (TimedOut) when a read waits longer than `timeout`. pub fn request_within(method: &str, path: &str, body: Option<&Value>, background: bool, timeout: Option) -> io::Result { line_safe(path)?; - let mut s = Conn(connect()?, timeout); + let mut s = open_conn(timeout)?; let payload = body.map(Value::to_string).unwrap_or_default(); write!( s, @@ -158,6 +248,11 @@ pub fn request_within(method: &str, path: &str, body: Option<&Value>, background background_header(background), payload.len() )?; + answer(s) +} + +/// The answer to a request just sent; the whole body is read, chunked or not. +fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut body = Vec::new(); @@ -177,6 +272,56 @@ pub fn request_within(method: &str, path: &str, body: Option<&Value>, background Ok(Response { status, body }) } +/// A POST whose body `write` streams, chunked, so its length need not be +/// known first: `kiri import`'s copy of a container's writable layer, as +/// crates/kiri/src/client.rs sends it. A body `write` gives up on is never +/// ended, so the daemon sees it cut short, not as a whole one; if the daemon +/// stopped reading first (it refused the request), its answer is returned, +/// which says why. +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + line_safe(path)?; + line_safe(content_type)?; + let mut s = open_conn(None)?; + write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\nContent-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n")?; + match stream_body(&mut s, write) { + Ok(()) => answer(s), + Err(e) if matches!(e.kind(), io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionAborted) => match answer(s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + +/// Writes a body chunked, in chunks of up to 256 KiB, and ends it only when +/// `write` succeeds. +fn stream_body(to: impl Write, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result<()> { + let mut body = io::BufWriter::with_capacity(256 << 10, Chunked(to)); + write(&mut body)?; + let mut chunked = body.into_inner().map_err(io::IntoInnerError::into_error)?; + chunked.0.write_all(b"0\r\n\r\n")?; + chunked.0.flush() +} + +/// HTTP/1.1 chunked transfer coding: each write is one chunk. +struct Chunked(W); + +impl Write for Chunked { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + write!(self.0, "{:x}\r\n", buf.len())?; + self.0.write_all(buf)?; + self.0.write_all(b"\r\n")?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + /// Kiri's own version from a `/version` answer: `KiriVersion`, or `Version` /// from an engine older than that field (it reported Kiri's version there; /// it is now the Docker Engine version clients gate on). @@ -193,8 +338,9 @@ pub fn get(path: &str) -> io::Result { } /// A GET of the window's own refresh, failing after QUICK without an answer. +/// Marked as the window's own, so the refresh never keeps the VM awake. pub fn get_quick(path: &str) -> io::Result { - let r = request_within("GET", path, None, false, Some(QUICK))?; + let r = request_within("GET", path, None, true, Some(QUICK))?; if !r.ok() { return Err(io::Error::other(r.error())); } @@ -202,9 +348,9 @@ pub fn get_quick(path: &str) -> io::Result { } /// A GET marked as the window's own, which doesn't count as use (as the -/// Mac's `get_background`, for crates/kiri/src/builds.rs). +/// Mac's `get_background`, for crates/kiri/src/builds.rs), bounded by 120 s. pub fn get_background(path: &str) -> io::Result { - let r = request_with("GET", path, None, true)?; + let r = request_within("GET", path, None, true, Some(Duration::from_secs(120)))?; if !r.ok() { return Err(io::Error::other(r.error())); } @@ -212,6 +358,7 @@ pub fn get_background(path: &str) -> io::Result { } /// The docker CLI Kiri ships, as the Mac's `docker_cli` (for builds.rs). +#[cfg(windows)] pub fn docker_cli() -> Option { Some(crate::detail::docker_cli()) } @@ -219,11 +366,13 @@ pub fn docker_cli() -> Option { /// A POST whose answer is a stream of JSON lines (`/images/create`), each /// given to `on_line` as it arrives; returns the HTTP status. As the Mac's /// client::post_lines. +#[cfg(windows)] pub fn post_lines(path: &str, on_line: impl FnMut(Value)) -> io::Result { post_lines_with(path, None, on_line) } /// `post_lines` with a registry sign-in (`X-Registry-Auth`, base64url) for a pull. +#[cfg(windows)] pub fn post_lines_with(path: &str, auth: Option<&str>, on_line: impl FnMut(Value)) -> io::Result { post_lines_closable(path, auth, |_| {}, on_line) } @@ -231,6 +380,7 @@ pub fn post_lines_with(path: &str, auth: Option<&str>, on_line: impl FnMut(Value /// `post_lines_with`, handing `opened` a Closer for the connection once it /// is made, so another thread can stop the request (Cancel on a pull). A /// stopped read ends as if the body had. +#[cfg(windows)] pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(Closer), mut on_line: impl FnMut(Value)) -> io::Result { line_safe(path)?; if let Some(a) = auth { @@ -239,7 +389,7 @@ pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(C let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); let pipe = connect()?; opened(Closer(pipe.clone())); - let mut s = Conn(pipe, None); + let mut s = Conn::Pipe(pipe, None); write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n")?; let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; @@ -270,21 +420,69 @@ pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(C } /// Whether the daemon answers at all, waiting for a start the bridge has -/// under way (Start). +/// under way (Start). Marked as the window's own, as on the Mac, so status +/// and diagnostic checks never keep an idle VM awake. pub fn alive() -> bool { - request_within("GET", "/_ping", None, false, Some(PING_WAIT)).is_ok_and(|r| r.ok()) + alive_within(PING_WAIT) +} + +/// Probes the engine pipe for CLI-shared callers (`import.rs`), surfacing the +/// pipe's refusal message when Kiri is stopped or setup is unfinished. +#[allow(dead_code)] +pub fn check_alive() -> io::Result<()> { + match request_within("GET", "/_ping", None, true, Some(PING_WAIT)) { + Ok(r) if r.ok() => Ok(()), + Ok(r) => { + let err = r.error(); + let msg = if err.trim().is_empty() { "Kiri isn't running. Open Kiri, or start it with `kiri start`" } else { err.trim() }; + Err(io::Error::new(io::ErrorKind::NotConnected, msg.to_owned())) + } + Err(_) => Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri isn't running. Open Kiri, or start it with `kiri start`")), + } } /// `alive`, for the event watcher: false after QUICK without an answer. pub fn alive_quick() -> bool { - request_within("GET", "/_ping", None, false, Some(QUICK)).is_ok_and(|r| r.ok()) + alive_within(QUICK) +} + +/// `alive`, giving up after `timeout` without an answer. +pub fn alive_within(timeout: Duration) -> bool { + request_within("GET", "/_ping", None, true, Some(timeout)).is_ok_and(|r| r.ok()) +} + +/// Polls `/_ping` until the daemon answers or `limit` has passed, pausing +/// `pause` between failed tries. Each try gets only the time left before +/// the deadline, so a pipe that accepts connections without answering +/// (for example a hung `wsl.exe`) cannot stretch the loop past `limit`. +pub fn wait_alive(limit: Duration, pause: Duration) -> bool { + wait_alive_with(limit, pause, alive_within) +} + +fn wait_alive_with(limit: Duration, pause: Duration, mut probe: impl FnMut(Duration) -> bool) -> bool { + let deadline = std::time::Instant::now() + limit; + loop { + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + return false; + } + if probe(left) { + return true; + } + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + return false; + } + std::thread::sleep(pause.min(left)); + } } /// A long-lived streamed response (`/events`, `logs?follow=1`, `stats`), /// read chunk by chunk. `closer` ends it from another thread. #[derive(Debug)] pub struct Stream { - pipe: Arc, + #[cfg(windows)] + pipe: Option>, reader: BufReader, } @@ -304,9 +502,11 @@ impl Read for ConnReader { } /// Ends a Stream's wait from another thread. +#[cfg(windows)] #[derive(Debug, Clone)] pub struct Closer(Arc); +#[cfg(windows)] impl Closer { pub fn close(&self) { self.0.cancel(); @@ -315,20 +515,34 @@ impl Closer { impl Stream { pub fn open(path: &str) -> io::Result { + Self::open_with(path, false) + } + + fn open_with(path: &str, background: bool) -> io::Result { line_safe(path)?; - let pipe = connect()?; - let mut s = Conn(pipe.clone(), None); - write!(s, "GET {path} HTTP/1.1\r\nHost: kiri\r\n\r\n")?; + let mut s = open_conn(None)?; + #[cfg(windows)] + let pipe = match &s { + Conn::Pipe(p, _) => Some(p.clone()), + #[cfg(test)] + Conn::Mock(_) => None, + }; + write!(s, "GET {path} HTTP/1.1\r\nHost: kiri\r\n{}\r\n", background_header(background))?; let mut reader = BufReader::new(ConnReader(s)); let (status, _, chunked) = head(&mut reader)?; if status != 200 || !chunked { return Err(io::Error::other(format!("{path}: HTTP {status}"))); } - Ok(Stream { pipe, reader }) + Ok(Stream { + #[cfg(windows)] + pipe, + reader, + }) } + #[cfg(windows)] pub fn closer(&self) -> Closer { - Closer(self.pipe.clone()) + Closer(self.pipe.as_ref().expect("stream backed by a pipe").clone()) } pub fn next(&mut self) -> Option> { @@ -338,16 +552,16 @@ impl Stream { /// Calls `on_event` for each event until the connection ends or it returns false. pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { - let mut s = Stream::open("/events")?; + let mut s = Stream::open_with("/events", true)?; let mut pending = Vec::new(); while let Some(c) = s.next() { pending.extend_from_slice(&c); while let Some(i) = pending.iter().position(|&b| b == b'\n') { let line: Vec = pending.drain(..=i).collect(); - if let Ok(v) = serde_json::from_slice::(&line) { - if !on_event(v) { - return Ok(()); - } + if let Ok(v) = serde_json::from_slice::(&line) + && !on_event(v) + { + return Ok(()); } } } @@ -358,6 +572,7 @@ pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { /// arrives unframed, read from this, until it ends. `closer()` ends a read /// that waits (a log that follows) from another thread; the exec itself /// goes on in the container. +#[cfg(windows)] #[derive(Debug)] pub struct Exec { pub id: String, @@ -365,18 +580,21 @@ pub struct Exec { reader: BufReader, } +#[cfg(windows)] impl Exec { pub fn closer(&self) -> Closer { Closer(self.pipe.clone()) } } +#[cfg(windows)] impl Read for Exec { fn read(&mut self, buf: &mut [u8]) -> io::Result { self.reader.read(buf) } } +#[cfg(windows)] impl BufRead for Exec { fn fill_buf(&mut self) -> io::Result<&[u8]> { self.reader.fill_buf() @@ -389,6 +607,7 @@ impl BufRead for Exec { /// Starts `cmd` in a running container, through the exec API with a /// terminal; `background` marks it as the window's own. +#[cfg(windows)] pub fn exec_start(container: &str, cmd: &[&str], background: bool) -> io::Result { line_safe(container)?; let created = request_with("POST", &format!("/containers/{container}/exec"), Some(&serde_json::json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": true})), background)?; @@ -397,7 +616,7 @@ pub fn exec_start(container: &str, cmd: &[&str], background: bool) -> io::Result } let id = created.json()["Id"].as_str().unwrap_or_default().to_owned(); let pipe = connect()?; - let mut s = Conn(pipe.clone(), None); + let mut s = Conn::Pipe(pipe.clone(), None); let body = r#"{"Detach":false,"Tty":true}"#; write!( s, @@ -415,6 +634,7 @@ pub fn exec_start(container: &str, cmd: &[&str], background: bool) -> io::Result /// Runs `cmd` in a running container and returns (exit code, output), /// through the exec API with a terminal, so output arrives unframed. +#[cfg(windows)] pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let mut e = exec_start(container, cmd, false)?; let mut out = Vec::new(); @@ -422,3 +642,165 @@ pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let code = get(&format!("/exec/{}/json", e.id))?["ExitCode"].as_i64().unwrap_or(-1); Ok((code, String::from_utf8_lossy(&out).replace("\r\n", "\n"))) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const OK_JSON: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"; + const OK_PING: &[u8] = b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK"; + const OK_CHUNKED: &[u8] = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n"; + + fn wire_text(buf: &std::sync::Arc>>) -> String { + String::from_utf8(buf.lock().unwrap().clone()).unwrap() + } + + #[test] + fn background_polls_carry_the_background_header() { + let info = mock_reply(OK_JSON); + get_quick("/info").unwrap(); + let req = wire_text(&info); + assert!(req.starts_with("GET /info HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "get_quick must mark background: {req}"); + + let list = mock_reply(OK_JSON); + get_quick("/containers/json?all=1").unwrap(); + let req = wire_text(&list); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "get_quick lists must mark background: {req}"); + + let proxy_get = mock_reply(OK_JSON); + get_background("/kiri/proxy").unwrap(); + let req = wire_text(&proxy_get); + assert!(req.starts_with("GET /kiri/proxy HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "get_background must mark background: {req}"); + + let proxy_put = mock_reply(OK_JSON); + let body = json!({"http": null, "https": null}); + request_with("PUT", "/kiri/proxy/system", Some(&body), true).unwrap(); + let req = wire_text(&proxy_put); + assert!(req.starts_with("PUT /kiri/proxy/system HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "background proxy push must mark background: {req}"); + } + + #[test] + fn a_streamed_body_is_chunked_and_ended_only_when_whole() { + let sent = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + let r = post_stream("/kiri/containers/db/upper", "application/x-tar", |w| { + w.write_all(b"hello")?; + w.write_all(b" world") + }) + .unwrap(); + assert_eq!(r.status, 204); + let req = wire_text(&sent); + assert!(req.starts_with("POST /kiri/containers/db/upper HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nTransfer-Encoding: chunked\r\n") && req.contains("\r\nContent-Type: application/x-tar\r\n"), "{req}"); + assert!(req.ends_with("\r\n\r\nb\r\nhello world\r\n0\r\n\r\n"), "{req}"); + + let cut = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + let e = post_stream("/kiri/containers/db/upper", "application/x-tar", |w| { + w.write_all(b"part")?; + Err(io::Error::other("the source failed")) + }) + .unwrap_err(); + assert_eq!(e.to_string(), "the source failed"); + assert!(!wire_text(&cut).ends_with("0\r\n\r\n"), "a body cut short is never ended"); + } + + #[test] + fn alive_and_events_carry_the_background_header() { + let ping = mock_reply(OK_PING); + assert!(alive()); + let req = wire_text(&ping); + assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive must mark background: {req}"); + + let quick_ping = mock_reply(OK_PING); + assert!(alive_quick()); + let req = wire_text(&quick_ping); + assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive_quick must mark background: {req}"); + + let bounded_ping = mock_reply(OK_PING); + assert!(alive_within(Duration::from_secs(2))); + let req = wire_text(&bounded_ping); + assert!(req.starts_with("GET /_ping HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "alive_within must mark background: {req}"); + + let _fail = mock_reply(b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n"); + assert!(!alive_within(Duration::from_secs(2))); + + let ev = mock_reply(OK_CHUNKED); + events(|_| false).unwrap(); + let req = wire_text(&ev); + assert!(req.starts_with("GET /events HTTP/1.1\r\n"), "{req}"); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "events must mark background: {req}"); + } + + /// A hung ping (pipe accepts, nothing behind it answers) consumes at most + /// the remaining budget and ends the wait loop at `limit`, rather than + /// multiplying per-call timeouts across 100 iterations. + #[test] + fn wait_alive_bounds_slow_probes_and_retries_fast_ones() { + use std::time::Instant; + + // A hanging probe: sleeps for the timeout it was given and returns false. + let mut calls = 0usize; + let limit = Duration::from_millis(120); + let began = Instant::now(); + assert!(!wait_alive_with(limit, Duration::from_millis(20), |timeout| { + calls += 1; + assert!(timeout <= limit, "probe timeout {timeout:?} exceeded limit {limit:?}"); + std::thread::sleep(timeout); + false + })); + assert_eq!(calls, 1, "a single hung probe should exhaust the budget and stop"); + assert!(began.elapsed() < Duration::from_millis(400), "waited {:?}", began.elapsed()); + + // Fast failing probes retry with shrinking budgets until one answers. + let mut seen = Vec::new(); + assert!(wait_alive_with(Duration::from_millis(500), Duration::from_millis(25), |timeout| { + seen.push(timeout); + seen.len() == 3 + })); + assert_eq!(seen.len(), 3); + assert!(seen[2] < seen[0], "remaining budget should shrink across retries: {seen:?}"); + + // Fast failing probes stop once `limit` passes (generous window so a + // 5 ms sleep oversleeping on a loaded CI VM still gets >= 2 tries). + let mut fast_calls = 0usize; + let began = Instant::now(); + assert!(!wait_alive_with(Duration::from_millis(450), Duration::from_millis(5), |_| { + fast_calls += 1; + false + })); + assert!(fast_calls >= 2, "unexpected retry count: {fast_calls}"); + assert!(began.elapsed() >= Duration::from_millis(400) && began.elapsed() < Duration::from_secs(3), "waited {:?}", began.elapsed()); + } + + #[test] + fn foreground_requests_omit_the_background_header() { + let fg_get = mock_reply(OK_JSON); + get("/info").unwrap(); + let req = wire_text(&fg_get); + assert!(req.starts_with("GET /info HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "foreground get must not mark background: {req}"); + + let wake = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + request("POST", "/kiri/wake", None).unwrap(); + let req = wire_text(&wake); + assert!(req.starts_with("POST /kiri/wake HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "POST /kiri/wake must not mark background: {req}"); + + let start = mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + request("POST", "/containers/c1/start", None).unwrap(); + let req = wire_text(&start); + assert!(!req.contains("X-Kiri-Background"), "foreground POST must not mark background: {req}"); + + let logs = mock_reply(OK_CHUNKED); + let _ = Stream::open("/containers/c1/logs?follow=1").unwrap(); + let req = wire_text(&logs); + assert!(req.starts_with("GET /containers/c1/logs?follow=1 HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "foreground Stream::open must not mark background: {req}"); + } +} diff --git a/crates/kiri-win/src/diag.rs b/crates/kiri-win/src/diag.rs index c308363ba..3c576e450 100644 --- a/crates/kiri-win/src/diag.rs +++ b/crates/kiri-win/src/diag.rs @@ -172,9 +172,16 @@ fn windows_version() -> String { cmd.args(["/c", "ver"]).output().map(|o| String::from_utf8_lossy(&o.stdout).trim().to_owned()).ok().filter(|v| !v.is_empty()).unwrap_or_else(|| "Windows".into()) } -/// The report: versions, the container list if asked, and both logs. +/// The report: versions, storage health, the container list if asked, and both logs. fn report_text(containers: bool) -> String { let mut out = format!("Kiri for Windows {}\n{}\n{}\n", env!("CARGO_PKG_VERSION"), windows_version(), std::env::consts::ARCH); + let storage_ro = crate::client::get_quick("/info") + .ok() + .and_then(|i| i["KiriStorageReadOnly"].as_str().map(str::to_owned)) + .or_else(|| crate::engine::probe_wsl_readonly(crate::engine::distro().as_deref())); + if let Some(ro) = storage_ro { + out.push_str(&format!("Storage: {ro}\n")); + } if containers { out.push_str("\n== Containers ==\n"); match crate::client::get("/containers/json?all=1") { diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rs index 0b1bafaf2..6d7ecc25f 100644 --- a/crates/kiri-win/src/engine.rs +++ b/crates/kiri-win/src/engine.rs @@ -129,6 +129,15 @@ pub fn emit(json: String) { Handle.eval(format!("window.kiri && kiri.on({json})")); } +/// The window let go of its page (app.rs, Ui::close): the terminals, the +/// log and the live figures it followed end with it, as when Linux's window +/// closes. The page asks for what it needs again when it next loads. +pub fn page_gone() { + crate::term::handle("closeall", "", &Value::Null, emit); + crate::detail::stop_logs(); + crate::detail::stop_stats(); +} + pub fn notice(kind: &str, text: &str) -> String { json!({"type": "notice", "kind": kind, "text": text}).to_string() } @@ -142,11 +151,74 @@ fn state(name: &str, error: Option<&str>) -> String { .to_string() } +/// Terminates Kiri's dedicated WSL distro (`kiri`) so `vmmemWSL` releases RAM +/// when no other WSL distro is running. Never terminates a shared user distro +/// (e.g. Ubuntu), which would kill unrelated WSL shells. +fn terminate_kiri_distro() { + if let Some(d) = crate::refuse::terminate_target(distro().as_deref(), crate::setup::KIRI_DISTRO) { + crate::serve::log(&format!("engine: terminating WSL distro {d}")); + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + if let Err(e) = crate::update::output_within(cmd.args(["--terminate", d]), crate::update::WSL_LIMIT) { + crate::serve::log(&format!("engine: wsl --terminate {d} failed: {e}")); + } + } +} + +/// Emits stopped UI state and updates the tray menu directly without touching WSL. +/// When `zero_vm` is true (on an explicit Stop transition from `"stopping"`), +/// also emits a zeroed `vm` panel before `"stopped"` so counters clear immediately. +fn emit_stopped(zero_vm: bool) { + RUNNING.lock().unwrap_or_else(PoisonError::into_inner).clear(); + *STORAGE_RO_SHOWN.lock().unwrap_or_else(PoisonError::into_inner) = None; + if zero_vm { + emit(json!({ + "type": "vm", + "awake": false, + "target_mib": 0, + "ceiling_mib": 0, + "used_mib": 0, + "running": 0, + "cpus": 0, + "daemon_kib": 0, + }) + .to_string()); + } + emit(state("stopped", None)); + Handle.set_menu(Menu { vm: "Stopped".into(), running: Vec::new() }); +} + +/// Called after an external `POST /kiri/wake` (for example `kiri start` from +/// the CLI) wakes Kiri through the named pipe while `kiri-win` was stopped. +pub(crate) fn on_external_wake() { + std::thread::spawn(|| send_windows_roots(true)); + std::thread::spawn(send_windows_proxy); + std::thread::spawn(crate::update::catch_up_engine); + crate::wslconfig::sync_wsl_integration_soon(); + crate::watch::notify_containers_changed(); + crate::ports::notify(); + send(Cmd::Refresh); +} + +/// Called after an external `POST /kiri/stop` (`kiri engine stop`) stops the +/// WSL daemon through the named pipe: marks `kiri-win` stopped immediately so +/// subsequent pipe/status checks see the stopped gate without a race, then +/// tells the engine thread to tear down bridges/relays, terminate Kiri's +/// dedicated WSL distro, and update the window and tray (#983). +pub(crate) fn on_external_stop() { + crate::serve::set_stopped(true); + send(Cmd::Stop); +} + fn engine(rx: &Receiver, tx: Sender) { watch(tx); - // Windows' proxy for the daemon, now and every minute. + // Windows' proxy and root certificates for the daemon, now and every + // minute. std::thread::spawn(|| loop { - send_windows_proxy(); + if !crate::serve::is_stopped() { + send_windows_proxy(); + send_windows_roots(false); + } std::thread::sleep(Duration::from_secs(60)); }); let mut pending: Option = None; @@ -159,19 +231,28 @@ fn engine(rx: &Receiver, tx: Sender) { Ok(Cmd::Start) => bring_up(false), Ok(Cmd::Launch) => bring_up(true), // Stop means off: every container stopped, the engine off until - // Start (nothing wakes it meanwhile), and this window's shares closed. + // Start (nothing wakes it meanwhile), this window's shares closed, + // and Kiri's dedicated WSL distro terminated so vmmemWSL frees RAM. Ok(Cmd::Stop) => { emit(state("stopping", None)); sharing::close_all(); - let stopped = match expect_ok(client::request("POST", "/kiri/stop", None)) { - // An engine older than Stop: its sleep. - Err(e) if e.to_string().contains("404") => expect_ok(client::request("POST", "/kiri/sleep", None)), - r => r, - }; - if let Err(e) = stopped { - emit(notice("error", &e.to_string())); + if !crate::serve::is_stopped() { + let stopped = match expect_ok(client::request("POST", "/kiri/stop", None)) { + // An engine older than Stop: its sleep. + Err(e) if e.to_string().contains("404") => expect_ok(client::request("POST", "/kiri/sleep", None)), + r => r, + }; + if let Err(e) = stopped { + emit(notice("error", &e.to_string())); + } } - refresh(); + crate::serve::set_stopped(true); + crate::serve::stop_bridge(); + crate::relay::stop(); + crate::ports::notify(); + crate::watch::notify_containers_changed(); + terminate_kiri_distro(); + emit_stopped(true); } Ok(Cmd::Refresh) => { // Events come in bursts (create, start, …): one refresh per @@ -190,43 +271,65 @@ fn engine(rx: &Receiver, tx: Sender) { } Ok(Cmd::Pull(name)) => pull(name), Ok(Cmd::Run(name, env)) => { - // The page shows its spinner until this says how it went. - let result = run_image(&name, &env); - emit(json!({"type": "ran", "name": name, "error": result.is_err()}).to_string()); - act(result) + std::thread::spawn(move || { + // The page shows its spinner until this says how it went. + let result = run_image(&name, &env); + emit(json!({"type": "ran", "name": name, "error": result.is_err()}).to_string()); + act(result); + }); + } + Ok(Cmd::RemoveImage(name)) => { + std::thread::spawn(move || { + match client::request("DELETE", &format!("/images/{}", path_escape(&name)), None) { + Ok(r) if r.ok() => { + // Only untagged when another name still points at it: nothing freed. + let deleted = r.json().as_array().is_some_and(|a| a.iter().any(|v| v.get("Deleted").is_some())); + emit(json!({"type": "removed", "name": name, "deleted": deleted}).to_string()); + } + Ok(r) => emit(notice("error", &r.error())), + Err(e) => emit(notice("error", &e.to_string())), + } + send(Cmd::Refresh); + }); } - Ok(Cmd::RemoveImage(name)) => match client::request("DELETE", &format!("/images/{}", path_escape(&name)), None) { - Ok(r) if r.ok() => { - // Only untagged when another name still points at it: nothing freed. - let deleted = r.json().as_array().is_some_and(|a| a.iter().any(|v| v.get("Deleted").is_some())); - emit(json!({"type": "removed", "name": name, "deleted": deleted}).to_string()); - } - Ok(r) => emit(notice("error", &r.error())), - Err(e) => emit(notice("error", &e.to_string())), - }, Ok(Cmd::Container { action, id }) => { let (method, path) = match action.as_str() { "remove" => ("DELETE", format!("/containers/{id}?force=1&v=1")), a @ ("start" | "stop" | "restart" | "pause" | "unpause") => ("POST", format!("/containers/{id}/{a}")), _ => continue, }; - let result = expect_done(client::request(method, &path, None)); - // Refused to start (a port taken): the container's page says why. - if let (Err(e), "start") = (&result, action.as_str()) { - emit(json!({"type": "startfailed", "id": id, "error": e.to_string()}).to_string()); - } - act(result); + std::thread::spawn(move || { + let result = expect_done(client::request(method, &path, None)); + // Refused to start (a port taken): the container's page says why. + if let (Err(e), "start") = (&result, action.as_str()) { + emit(json!({"type": "startfailed", "id": id, "error": e.to_string()}).to_string()); + } + act(result); + }); + } + Ok(Cmd::RemoveVolume(name)) => { + std::thread::spawn(move || act(expect_ok(client::request("DELETE", &format!("/volumes/{}", path_escape(&name)), None)))); + } + Ok(Cmd::RemoveNetwork(id)) => { + std::thread::spawn(move || act(expect_ok(client::request("DELETE", &format!("/networks/{id}"), None)))); + } + Ok(Cmd::Ports { id, ports }) => { + std::thread::spawn(move || act(set_ports(&id, ports))); + } + Ok(Cmd::Env { id, env }) => { + std::thread::spawn(move || act(set_env(&id, env))); + } + Ok(Cmd::About) => { + std::thread::spawn(about); } - Ok(Cmd::RemoveVolume(name)) => act(expect_ok(client::request("DELETE", &format!("/volumes/{}", path_escape(&name)), None))), - Ok(Cmd::RemoveNetwork(id)) => act(expect_ok(client::request("DELETE", &format!("/networks/{id}"), None))), - Ok(Cmd::Ports { id, ports }) => act(set_ports(&id, ports)), - Ok(Cmd::Env { id, env }) => act(set_env(&id, env)), - Ok(Cmd::About) => about(), Err(RecvTimeoutError::Disconnected) => return, Err(RecvTimeoutError::Timeout) => { - vm_panel(); - if LISTED.lock().unwrap_or_else(|e| e.into_inner()).elapsed() >= LIST_EVERY { - refresh(); + emit_docker_state_if_changed(); + if !crate::serve::is_stopped() { + vm_panel(); + if LISTED.lock().unwrap_or_else(|e| e.into_inner()).elapsed() >= LIST_EVERY { + refresh(); + } } } } @@ -237,13 +340,20 @@ fn engine(rx: &Receiver, tx: Sender) { /// the engine for a refresh. Reconnects when the daemon comes back. fn watch(tx: Sender) { let _ = std::thread::Builder::new().name("kiri-ui-events".into()).spawn(move || loop { - if client::alive_quick() { + if !crate::serve::is_stopped() && client::alive_quick() { if tx.send(Cmd::Refresh).is_err() { return; } // A Kubernetes node already running gets its kubectl context. crate::k8s::sync_soon(); - let _ = client::events(|_| tx.send(Cmd::Refresh).is_ok()); + crate::watch::notify_containers_changed(); + crate::ports::notify(); + crate::wslconfig::sync_wsl_integration_soon(); + let _ = client::events(|_| { + crate::watch::notify_containers_changed(); + crate::ports::notify(); + tx.send(Cmd::Refresh).is_ok() + }); } std::thread::sleep(Duration::from_secs(1)); }); @@ -278,6 +388,13 @@ pub(crate) fn path_escape(s: &str) -> String { /// Before, the hidden launch at login, and the window opening before the /// daemon was up, sent Start and so undid it (#394). fn bring_up(launch: bool) { + if launch && crate::serve::is_stopped() { + emit_stopped(false); + return; + } + if !launch { + crate::serve::set_stopped(false); + } // Up and stopped already: nothing to bring up, and no "booting" shown. if launch && client::alive_quick() && stopped() == Some(true) { return refresh(); @@ -288,9 +405,14 @@ fn bring_up(launch: bool) { let woken = ensure_daemon().and_then(|()| if wakes(launch, stopped()) { wake().map(|()| true) } else { Ok(false) }); match woken { Ok(woken) => { + // Before the first pull, not up to a minute after. + std::thread::spawn(|| send_windows_roots(true)); if woken { std::thread::spawn(ensure_builder); + std::thread::spawn(send_windows_proxy); } + crate::watch::notify_containers_changed(); + crate::ports::notify(); refresh(); } Err(e) => emit(state("stopped", Some(&e.to_string()))), @@ -309,7 +431,7 @@ fn wakes(launch: bool, stopped: Option) -> bool { /// Whether Kiri was stopped (Stop in the window or the tray): then it stays /// off until Start. None when the engine's /info did not answer. fn stopped() -> Option { - client::get("/info").ok().map(|i| i["KiriStopped"] == true) + client::get_background("/info").ok().map(|i| i["KiriStopped"] == true) } /// The daemon's wake; a Linux host has no VM to wake, which is fine. @@ -328,12 +450,36 @@ pub(crate) fn ensure_daemon() -> io::Result<()> { if !client::alive() { start_daemon()?; } + crate::relay::ensure_started(); std::thread::spawn(crate::update::catch_up_engine); + crate::wslconfig::sync_wsl_integration_soon(); Ok(()) } +/// Checks `/proc/mounts` inside `distro` for a read-only `/` or `/var/lib/kiri` +/// (`ro` or ext4 `emergency_ro`, #768) and formats recovery steps naming the +/// configured `ext4.vhdx` path. +pub(crate) fn probe_wsl_readonly(distro: Option<&str>) -> Option { + let mut cmd = crate::win::tool("wsl.exe"); + if let Some(d) = distro { + cmd.args(["-d", d]); + } + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let out = crate::update::output_within(cmd.args(["-u", "root", "-e", "cat", "/proc/mounts"]), Duration::from_secs(10)).ok()?; + if !out.status.success() { + return None; + } + let text = crate::wslsync::wsl_text(&out.stdout); + let kind = crate::wslsync::parse_wsl_readonly_mounts(&text)?; + Some(crate::wslsync::wsl_readonly_message(kind, Some(&crate::storage::current_vhdx()))) +} + /// Starts the daemon in WSL, this app's engine copied in first. fn start_daemon() -> io::Result<()> { + if let Some(missing) = crate::storage::unavailable() { + crate::storage::emit_report(); + return Err(io::Error::other(crate::storage::unavailable_message(&missing))); + } crate::serve::log("engine: not answering; starting it in WSL"); // The engine this app installed, not one an update left behind. match crate::update::sync_engine() { @@ -353,19 +499,31 @@ fn start_daemon() -> io::Result<()> { std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // Each killed after WSL_LIMIT: a wsl.exe right after Windows wakes can hang. let started = crate::update::output_within(cmd.args(["-u", "root", "--", "systemctl", "start", "kiri"]), crate::update::WSL_LIMIT); + let mut fatal_exit = false; + let mut start_err = None; if !started.is_ok_and(|o| o.status.success()) { let mut cmd = crate::win::tool("wsl.exe"); if let Some(d) = &distro { cmd.args(["-d", d]); } std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let _ = crate::update::output_within(cmd.args(["-u", "root", "--", "/usr/local/bin/kiri-start"]), crate::update::WSL_LIMIT); - } - for _ in 0..100 { - if client::alive() { - return Ok(()); + if let Ok(out) = crate::update::output_within(cmd.args(["-u", "root", "--", "/usr/local/bin/kiri-start"]), crate::update::WSL_LIMIT) + && !out.status.success() + { + fatal_exit = out.status.code() == Some(2); + start_err = crate::wslsync::wsl_text(&out.stderr).lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned); } - std::thread::sleep(Duration::from_millis(100)); + } + let wait = if fatal_exit { Duration::from_millis(200) } else { Duration::from_secs(10) }; + if client::wait_alive(wait, Duration::from_millis(100)) { + return Ok(()); + } + if let Some(ro_msg) = probe_wsl_readonly(distro.as_deref()) { + crate::serve::log(&format!("engine: {ro_msg}")); + return Err(io::Error::other(ro_msg)); + } + if let Some(err) = start_err { + return Err(io::Error::other(format!("Kiri's engine did not start in WSL: {err}"))); } Err(io::Error::other("Kiri's engine did not start in WSL: run contrib\\windows\\kiri.ps1 to install it")) } @@ -406,6 +564,10 @@ fn ensure_builder() { /// Sends the page every list, from the daemon. fn refresh() { *LISTED.lock().unwrap_or_else(|e| e.into_inner()) = std::time::Instant::now(); + if crate::serve::is_stopped() { + emit_stopped(false); + return; + } let lists = (|| -> io::Result { // Quick: a refresh never holds the engine thread behind a start. let containers = client::get_quick("/containers/json?all=1")?; @@ -440,8 +602,13 @@ fn refresh() { } } +static STORAGE_RO_SHOWN: Mutex> = Mutex::new(None); + /// The sidebar's engine panel and the tray menu's state. fn vm_panel() { + if crate::serve::is_stopped() { + return; + } match client::get_quick("/info") { Ok(info) => { // A Linux host has no VM to put to sleep: it is always awake. @@ -461,6 +628,14 @@ fn vm_panel() { let stopped = info["KiriStopped"] == true; let awake = awake && !stopped; emit(state(if awake { "running" } else if stopped { "stopped" } else { "asleep" }, None)); + let ro = info["KiriStorageReadOnly"].as_str().map(str::to_owned); + let mut shown = STORAGE_RO_SHOWN.lock().unwrap_or_else(PoisonError::into_inner); + if ro.as_deref() != shown.as_deref() { + if let Some(ref msg) = ro { + emit(notice("error", msg)); + } + *shown = ro; + } let running = RUNNING.lock().unwrap_or_else(PoisonError::into_inner).clone(); Handle.set_menu(Menu { vm: if awake { "Running" } else if stopped { "Stopped" } else { "Asleep" }.into(), running }); } @@ -477,6 +652,7 @@ fn no_answer(e: &io::Error) { match unanswered(e.kind(), SHOWN.load(Ordering::SeqCst)) { Some("stopped") => { RUNNING.lock().unwrap_or_else(PoisonError::into_inner).clear(); + *STORAGE_RO_SHOWN.lock().unwrap_or_else(PoisonError::into_inner) = None; Handle.set_menu(Menu { vm: "Not running".into(), running: Vec::new() }); emit(state("stopped", None)); } @@ -694,6 +870,7 @@ fn host_ports(info: &Value, with_inner: bool) -> Vec { fn set_ports(id: &str, ports: Value) -> io::Result<()> { expect_ok(client::request("POST", &format!("/kiri/containers/{id}/ports"), Some(&json!({"ports": ports}))))?; + crate::ports::sync_now(); let now = host_ports(&client::get(&format!("/containers/{id}/json"))?, true); emit(notice("ok", &if now.is_empty() { tr("Ports removed") } else { trf("Ports saved: {ports}", &[("ports", &now.join(", "))]) })); Ok(()) @@ -748,12 +925,93 @@ fn about() { ); } -/// The status bar's left side: this build, and which engine `docker` talks -/// to by default, as `docker context show` says (it knows DOCKER_CONTEXT, -/// DOCKER_HOST and wherever Docker Desktop keeps the CLI config). -fn status_event() -> String { - let context = docker(&["context", "show"]).ok().map(|s| s.trim().to_owned()).filter(|c| !c.is_empty()); - json!({"type": "status", "version": env!("CARGO_PKG_VERSION"), "share": true, "app": "Kiri", "ours": "kiri", "context": context.unwrap_or_else(|| "default".into())}).to_string() +fn npipe_host(pipe: &str) -> String { + format!("npipe:{}", pipe.replace('\\', "/")) +} + +fn context_meta(dir: &std::path::Path, name: &str) -> std::path::PathBuf { + use sha2::Digest as _; + let sum = sha2::Sha256::digest(name.as_bytes()); + let hex: String = sum.iter().map(|b| format!("{b:02x}")).collect(); + dir.join("contexts/meta").join(hex) +} + +fn docker_state() -> (String, String) { + let endpoint = crate::serve::docker_engine_endpoint(); + let pipe = crate::client::pipe(); + let ours = npipe_host(&pipe); + let ctx = crate::flavor::CONTEXT.get(); + let cli = crate::dockerctx::current_cli(ctx, &[&ours], &endpoint); + let status = crate::dockerctx::status_event(env!("CARGO_PKG_VERSION"), false, crate::flavor::APP.get(), ctx, &cli).to_string(); + let sock = crate::dockerctx::sock_event(crate::serve::DOCKER_ENGINE, &endpoint, &ours, false).to_string(); + (status, sock) +} + +static LAST_DOCKER_STATE: Mutex<(String, String)> = Mutex::new((String::new(), String::new())); + +fn emit_docker_state() { + let (status, sock) = docker_state(); + *LAST_DOCKER_STATE.lock().unwrap_or_else(PoisonError::into_inner) = (status.clone(), sock.clone()); + emit(status); + emit(sock); +} + +fn emit_docker_state_if_changed() { + let (status, sock) = docker_state(); + let (send_status, send_sock) = { + let mut last = LAST_DOCKER_STATE.lock().unwrap_or_else(PoisonError::into_inner); + let ss = if last.0 != status { last.0 = status.clone(); true } else { false }; + let sd = if last.1 != sock { last.1 = sock.clone(); true } else { false }; + (ss, sd) + }; + if send_status { + emit(status); + } + if send_sock { + emit(sock); + } +} + +/// Ensures Kiri's `cliPluginsExtraDirs` and `kiri` context in +/// `%USERPROFILE%\.docker`, repairing `config.json` if another engine's +/// uninstaller (such as Docker Desktop's) removed it (#984). +pub fn heal_docker_config(pipe: &str) { + let Some(dir) = crate::dockerctx::docker_dir() else { return }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from); + let plugins = crate::dockerctx::find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| std::path::Path::new(&p).join(r"Docker\Docker\Docker Desktop.exe").is_file()); + let host = npipe_host(pipe); + match crate::dockerctx::repair_windows_config( + &dir, + crate::dockerctx::WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ) { + Ok(r) if r.context_written || r.plugins_added || r.current_context_set => { + crate::serve::log(&format!( + "docker config self-healed (context={}, plugins={}, current={})", + r.context_written, r.plugins_added, r.current_context_set + )); + } + Ok(_) => {} + Err(e) => crate::serve::log(&format!("docker config: could not self-heal ({e})")), + } +} + +/// Ensures the `kiri` context exists and is plain `docker`'s current context, +/// keeping logins, credential helpers and plugin folders untouched (#369). +pub fn use_kiri_context() -> io::Result<()> { + let dir = crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let ours = crate::flavor::CONTEXT.get(); + crate::dockerctx::use_ours(&dir, &context_meta(&dir, ours), ours, "Kiri (WSL2)", &npipe_host(&crate::client::pipe())) } /// The docker CLI on Kiri's context, without a console window, for Compose @@ -770,18 +1028,6 @@ fn compose_store() -> Option { prefs_path().map(|p| p.with_file_name("compose.json")) } -/// Runs the docker CLI without a console window: its output, or why it failed. -fn docker(args: &[&str]) -> io::Result { - let mut cmd = crate::win::tool(&crate::detail::docker_cli()); - std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let out = cmd.args(args).output()?; - if out.status.success() { - Ok(String::from_utf8_lossy(&out.stdout).into_owned()) - } else { - Err(io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_owned())) - } -} - fn builds_event() -> String { match crate::builds::list() { Ok(b) => json!({"type": "builds", "builds": b}), @@ -818,10 +1064,15 @@ fn build_with() { } } -/// Which engine plain `docker` uses: Kiri, or back to the one before. +/// Which engine plain `docker` uses: Kiri (made first if missing), "default", +/// or another context that exists, keeping logins and plugin folders. fn use_context(name: &str) { - let result = if name.is_empty() { Err(io::Error::other("no context named")) } else { docker(&["context", "use", name]).map(drop) }; - emit(status_event()); + let result = (|| -> io::Result<()> { + let dir = crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let ours = crate::flavor::CONTEXT.get(); + crate::dockerctx::switch(&dir, &context_meta(&dir, name), name, ours, "Kiri (WSL2)", &npipe_host(&crate::client::pipe())) + })(); + emit_docker_state(); emit(json!({"type": "usedcontext", "name": name, "error": result.as_ref().err().map(|e| e.to_string())}).to_string()); } @@ -899,9 +1150,31 @@ pub fn prefs() -> Value { if p.get("theme").is_none() { p["theme"] = "dark".into(); } + p["watchBindMounts"] = json!(crate::watch::is_enabled()); + if p.get("startAtLogin").is_none() { + p["startAtLogin"] = crate::setup::start_at_login().into(); + } + if p.get("stopOnQuit").is_none() { + p["stopOnQuit"] = false.into(); + } p } +/// Stops running containers and terminates Kiri's WSL distro when quitting +/// with "Stop the engine when Kiri quits" on. +pub fn stop() { + sharing::close_all(); + let _ = match expect_ok(client::request("POST", "/kiri/stop", None)) { + Err(e) if e.to_string().contains("404") => expect_ok(client::request("POST", "/kiri/sleep", None)), + r => r, + }; + if let Some(d) = distro() { + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let _ = crate::update::output_within(cmd.args(["--terminate", &d]), crate::update::WSL_LIMIT); + } +} + /// `en` in the window's language (lang.rs), for words sent to the page: /// notices, and the setup steps. pub fn tr(en: &str) -> String { @@ -914,7 +1187,18 @@ pub fn trf(en: &str, vars: &[(&str, &dyn std::fmt::Display)]) -> String { } fn set_pref(name: &str, value: Value) { - if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked") { + if name == "watchBindMounts" { + let on = value.as_bool().unwrap_or(false); + if crate::watch::save_enabled(on).is_err() { + emit(notice("error", &trf("Could not save the setting to {path}", &[("path", &"%LOCALAPPDATA%\\Kiri\\settings.json")]))); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); + return; + } + crate::watch::set_enabled(crate::watch::is_enabled()); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); + return; + } + if !matches!(name, "font" | "mono" | "scale" | "termH" | "termFs" | "termFont" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto" | "lang" | "langAsked" | "closeButton" | "startAtLogin" | "stopOnQuit") { return; } let Some(path) = prefs_path() else { return }; @@ -929,7 +1213,29 @@ fn set_pref(name: &str, value: Value) { /// A page link: only Kiri's own addresses, as on the Mac. fn allowed_url(url: &str) -> bool { - if url == "https://kiri.canestack.com" || url == "https://learn.microsoft.com/windows/wsl/about" || url == "https://github.com/libracoder/kiri/issues/new" || url == "https://github.com/libracoder/kiri" || url == "https://login.docker.com/activate" || url == "https://github.com/login/device" { + if matches!( + url, + "https://kiri.canestack.com" + | "https://runkiri.com" + | "https://runkiri.com/releases/" + | "https://runkiri.com/share/notice" + | "https://canestack.com" + | "https://discord.gg/K5A8wuqcC" + | "https://x.com/runkiri" + | "https://learn.microsoft.com/windows/wsl/about" + | "https://github.com/libracoder/kiri/issues/new" + | "https://github.com/libracoder/kiri" + | "https://github.com/anchore/grype" + | "https://login.docker.com/activate" + | "https://github.com/login/device" + ) { + return true; + } + // A build warning's rule page (docs.docker.com/go/dockerfile/rule/…). + if url + .strip_prefix("https://docs.docker.com/go/") + .is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"-/".contains(&b))) + { return true; } let Some(rest) = url.strip_prefix("http://").or_else(|| url.strip_prefix("https://")) else { return false }; @@ -949,6 +1255,14 @@ mod tests { use super::{allowed_url, unanswered, wakes}; use std::io::ErrorKind; + #[test] + fn roots_are_sent_when_they_change_or_the_engine_is_new() { + assert!(super::roots_need_sending(None, "a", false)); + assert!(!super::roots_need_sending(Some("a"), "a", false)); + assert!(super::roots_need_sending(Some("a"), "b", false)); + assert!(super::roots_need_sending(Some("a"), "a", true)); + } + /// As on the Mac and Linux: Stop on a stopped container, or Start on a /// running one, is done (Docker's 304, with no body), not an empty error. #[test] @@ -991,14 +1305,76 @@ mod tests { assert!(allowed_url("http://localhost:8080/app")); assert!(allowed_url("https://web.kiri.localhost/")); assert!(allowed_url("http://api.kiri.local")); + assert!(allowed_url("https://runkiri.com")); + assert!(allowed_url("https://runkiri.com/releases/")); + assert!(allowed_url("https://runkiri.com/share/notice")); + assert!(allowed_url("https://canestack.com")); + assert!(allowed_url("https://discord.gg/K5A8wuqcC")); + assert!(allowed_url("https://x.com/runkiri")); + assert!(allowed_url("https://kiri.canestack.com")); assert!(allowed_url("https://github.com/libracoder/kiri")); + assert!(allowed_url("https://github.com/libracoder/kiri/issues/new")); + assert!(allowed_url("https://github.com/anchore/grype")); + assert!(allowed_url("https://docs.docker.com/go/dockerfile/rule/from-as-casing/")); assert!(!allowed_url("http://evil.example/")); + assert!(!allowed_url("https://runkiri.com.evil.com")); // Bypass attempts the audit found. assert!(!allowed_url("http://localhost:1@evil.example/")); assert!(!allowed_url("http://evil.example\\x.kiri.localhost")); assert!(!allowed_url("https://evil.example/#.kiri.localhost")); assert!(!allowed_url("ftp://localhost/")); } + + #[test] + fn background_engine_checks_mark_background_and_wake_does_not() { + let info = super::client::mock_reply(b"HTTP/1.1 200 OK\r\nContent-Length: 20\r\n\r\n{\"KiriStopped\":true}"); + assert_eq!(super::stopped(), Some(true)); + let req = String::from_utf8(info.lock().unwrap().clone()).unwrap(); + assert!(req.contains("\r\nX-Kiri-Background: 1\r\n"), "stopped() must mark background: {req}"); + + let wake_wire = super::client::mock_reply(b"HTTP/1.1 204 No Content\r\n\r\n"); + super::wake().unwrap(); + let req = String::from_utf8(wake_wire.lock().unwrap().clone()).unwrap(); + assert!(req.starts_with("POST /kiri/wake HTTP/1.1\r\n"), "{req}"); + assert!(!req.contains("X-Kiri-Background"), "wake() must not mark background: {req}"); + + let proxy_get = super::client::mock_reply(b"HTTP/1.1 200 OK\r\nContent-Length: 15\r\n\r\n{\"settings\":{}}"); + let proxy_put = super::client::mock_reply(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"); + super::push_windows_proxy(serde_json::json!({"http": null, "https": null, "no_proxy": [], "pac": false}), |_| std::collections::HashMap::new()); + let get_req = String::from_utf8(proxy_get.lock().unwrap().clone()).unwrap(); + let put_req = String::from_utf8(proxy_put.lock().unwrap().clone()).unwrap(); + assert!(get_req.starts_with("GET /kiri/proxy HTTP/1.1\r\n") && get_req.contains("\r\nX-Kiri-Background: 1\r\n"), "{get_req}"); + assert!(put_req.starts_with("PUT /kiri/proxy/system HTTP/1.1\r\n") && put_req.contains("\r\nX-Kiri-Background: 1\r\n"), "{put_req}"); + } + + #[test] + fn saves_stop_on_quit_and_start_at_login_prefs() { + let dir = std::env::temp_dir().join(format!("kiri-win-prefs-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let old = std::env::var_os("LOCALAPPDATA"); + // SAFETY: serialized within this test binary's prefs test. + unsafe { std::env::set_var("LOCALAPPDATA", &dir) }; + assert_eq!(super::prefs()["stopOnQuit"], false); + super::set_pref("stopOnQuit", serde_json::json!(true)); + assert_eq!(super::prefs()["stopOnQuit"], true); + super::set_pref("stopOnQuit", serde_json::json!(false)); + assert_eq!(super::prefs()["stopOnQuit"], false); + super::set_pref("startAtLogin", serde_json::json!(false)); + assert_eq!(super::prefs()["startAtLogin"], false); + super::set_pref("startAtLogin", serde_json::json!(true)); + assert_eq!(super::prefs()["startAtLogin"], true); + match old { + Some(v) => unsafe { std::env::set_var("LOCALAPPDATA", v) }, + None => unsafe { std::env::remove_var("LOCALAPPDATA") }, + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn npipe_host_formats_pipe_url() { + assert_eq!(super::npipe_host(r"\\.\pipe\kiri"), "npipe:////./pipe/kiri"); + } } /// The page's "fonts" event, made once (the window asks each time Settings @@ -1034,7 +1410,8 @@ pub fn on_message(msg: &str) { emit(r#"{"type":"starprompt"}"#.to_owned()); } emit(domains_event()); - emit(status_event()); + emit_docker_state(); + std::thread::spawn(crate::storage::emit_report); ask_language(); // The first time, offer .kiri.local, as the Mac does. if !crate::dns::installed() && crate::dns::serving() && prefs()["domainsAsked"] != true { @@ -1051,8 +1428,9 @@ pub fn on_message(msg: &str) { emit(crate::buildwith::event()); }); send(Cmd::Refresh); - // Opening the window starts Kiri, unless it was stopped: that waits for Start. - send(Cmd::Launch); + // Opening the window starts Kiri, unless it was stopped: that waits + // for Start (except when quitting stopped it with stopOnQuit). + send(if prefs()["stopOnQuit"] == true { Cmd::Start } else { Cmd::Launch }); // Anything newer than this build, and a staged update not yet in. crate::update::check_now(false); // For checking the page by hand in a debug build. @@ -1102,10 +1480,35 @@ pub fn on_message(msg: &str) { emit(crate::buildwith::event()); }); } - // The docker CLI can take a moment: off the window's thread. + "buildprune" => { + std::thread::spawn(|| { + let e = match client::request("POST", "/build/prune?all=1", None) { + Ok(r) if r.ok() => json!({"type": "buildpruned", "freed": r.json()["SpaceReclaimed"]}), + Ok(r) => json!({"type": "buildpruned", "error": r.error()}), + Err(e) => json!({"type": "buildpruned", "error": e.to_string()}), + }; + emit(e.to_string()); + send(Cmd::Refresh); + }); + } + "buildersettings" => { + std::thread::spawn(|| builder_settings(None)); + } + "setbuildersettings" => { + let body = c.value; + std::thread::spawn(move || builder_settings(Some(body))); + } + // macOS-only settings: report unsupported cleanly on Windows. + "vmnet" => emit(json!({"type": "vmnet", "supported": false}).to_string()), + "setvmnet" => {} + "shellpath" => emit(json!({"type": "shellpath", "supported": false}).to_string()), + "setshellpath" => {} + "uninstall" => emit(notice("error", &tr("Uninstall Kiri from Windows Settings → Apps"))), + // Config update can be done synchronously or off-thread. "usecontext" => { std::thread::spawn(move || use_context(&c.name)); } + "dockersock" => emit_docker_state(), // The Kubernetes section: Pods, Services, a pod's logs, Start. "k8s" => crate::k8s::handle(&c.action, &c.value), // Share: public links for a port or container, and the Share account. @@ -1209,7 +1612,18 @@ pub fn on_message(msg: &str) { let theme = c.value.as_str().unwrap_or("").to_owned(); Handle.run(move |ui| ui.set_theme(&theme)); } + let start_login = (c.name == "startAtLogin").then(|| c.value.as_bool()).flatten(); set_pref(&c.name, c.value); + if let Some(on) = start_login { + std::thread::spawn(move || { + if let Err(e) = crate::setup::set_start_at_login(on) { + crate::serve::log(&format!("start at sign-in: {e}")); + set_pref("startAtLogin", (!on).into()); + emit(notice("error", &e.to_string())); + emit(json!({"type": "prefs", "prefs": prefs()}).to_string()); + } + }); + } } // A language the page doesn't carry yet (the main window and setup open // with one; setup's langwords comes here too, not being a setup- command): @@ -1351,6 +1765,39 @@ pub fn on_message(msg: &str) { emit(builds_event()); }); } + // Settings → Storage: where WSL keeps Kiri's VHDX, and moving it. + "storage" => { + std::thread::spawn(crate::storage::emit_report); + } + "volumesizes" => { + spawn_volume_sizes(); + } + "storagepick" => { + crate::app::pick_folder(&tr("Choose a storage folder"), |path| { + if let Some(p) = path { + let s = p.to_string_lossy().into_owned(); + std::thread::spawn(move || crate::storage::check_and_emit(Some(s), false, false)); + } + }); + } + "storagecheck" => { + let path = (!c.path.trim().is_empty()).then(|| c.path.clone()); + let fresh = c.value["fresh"] == true; + let reset = c.value["reset"] == true; + std::thread::spawn(move || crate::storage::check_and_emit(path, fresh, reset)); + } + "storagemove" => { + let path = (!c.path.trim().is_empty()).then(|| c.path.clone()); + let fresh = c.value["fresh"] == true; + crate::storage::start_move(path, fresh); + } + "storagereset" => crate::storage::reset(), + "storageretry" => crate::storage::retry(), + "storageremoveold" => crate::storage::remove_old(), + "storagereclaim" => crate::storage::reclaim(), + "storageprune" => { + std::thread::spawn(storage_prune); + } // Settings → Diagnostics and an error's Details: crate::diag. cmd @ ("diaglogs" | "diagreport" | "diagsend" | "diagcrashes" | "diagsendcrash" | "diagfolder") => { crate::diag::handle(cmd, c.name, c.id, &c.value); @@ -1437,10 +1884,14 @@ fn windows_proxy() -> Value { /// Tells the daemon what Windows' proxy is. A proxy on Windows' own /// 127.0.0.1 (Windows' or one set in Settings → Network) is reached through -/// the relay (relay.rs), and the daemon gets its ports too. +/// the relay (relay.rs), and the daemon gets its ports too. Sent every +/// minute, so marked as the window's own: it never keeps the VM awake. pub(crate) fn send_windows_proxy() { - let mut body = windows_proxy(); - let custom = client::get("/kiri/proxy").map(|v| v["settings"].clone()).unwrap_or_default(); + push_windows_proxy(windows_proxy(), crate::relay::ports); +} + +fn push_windows_proxy(mut body: Value, relay_ports: impl FnOnce(&[u16]) -> std::collections::HashMap) { + let custom = client::get_background("/kiri/proxy").map(|v| v["settings"].clone()).unwrap_or_default(); let mut targets: Vec = [&body["http"], &body["https"], &custom["http"], &custom["https"]] .iter() .filter_map(|v| v.as_str()) @@ -1448,9 +1899,41 @@ pub(crate) fn send_windows_proxy() { .collect(); targets.sort_unstable(); targets.dedup(); - let relay = crate::relay::ports(&targets); + let relay = relay_ports(&targets); body["relay"] = relay.iter().map(|(t, l)| (t.to_string(), json!(l))).collect::>().into(); - let _ = client::request("PUT", "/kiri/proxy/system", Some(&body)); + let _ = client::request_with("PUT", "/kiri/proxy/system", Some(&body), true); +} + +/// The Windows store's root certificates for the daemon in WSL (#303): the +/// ones the bundled set lacks (a company root, Group Policy's) and the +/// distrusted ones, so pulls trust what Windows trusts, as on the Mac. +/// The daemon keeps them and only acts on a change, so they are sent when +/// they differ from what was last sent, or when `force` (the engine has just +/// started, and may be a new one). Marked as the window's own (background) so +/// periodic sends never keep the VM awake. +pub(crate) fn send_windows_roots(force: bool) { + static SENT: std::sync::Mutex> = std::sync::Mutex::new(None); + let host = crate::roots::host_export(); + let list = |l: &[rustls_pki_types::CertificateDer<'static>]| l.iter().map(|c| crate::roots::hex(c)).collect::>(); + let body = json!({"certs": list(&host.certs), "distrusted": list(&host.distrusted)}); + let digest = { + use sha2::{Digest, Sha256}; + Sha256::digest(body.to_string().as_bytes()).iter().map(|b| format!("{b:02x}")).collect::() + }; + let mut last = SENT.lock().unwrap_or_else(|e| e.into_inner()); + if !roots_need_sending(last.as_deref(), &digest, force) { + return; + } + // Kept only once the daemon took them, so a failed send is tried again. + if client::request_with("PUT", "/kiri/roots/host", Some(&body), true).is_ok_and(|r| r.ok()) { + *last = Some(digest); + } +} + +/// Whether the roots with `digest` go to the daemon: they changed since +/// `last` was sent, nothing was sent yet, or `force`. +fn roots_need_sending(last: Option<&str>, digest: &str, force: bool) -> bool { + force || last != Some(digest) } /// Settings → Domains: reads (or moves, then reads) the routers' ports. The @@ -1517,6 +2000,98 @@ fn registry_config(set: Option) { emit(ev.to_string()); } +fn storage_prune() { + let mut freed = 0u64; + let mut containers = 0usize; + let mut images = 0usize; + let mut err: Option = None; + for (endpoint, kind) in [("/containers/prune", "c"), ("/images/prune", "i"), ("/build/prune?all=1", "b")] { + match client::request("POST", endpoint, None) { + Ok(r) if r.ok() => { + let v = r.json(); + freed = freed.saturating_add(v["SpaceReclaimed"].as_u64().unwrap_or(0)); + if kind == "c" { + containers = v["ContainersDeleted"].as_array().map_or(0, Vec::len); + } else if kind == "i" { + images = v["ImagesDeleted"].as_array().map_or(0, Vec::len); + } + } + Ok(r) => { + err = Some(r.error()); + break; + } + Err(e) => { + err = Some(e.to_string()); + break; + } + } + } + let ev = match err { + Some(e) => json!({"type": "storagepruned", "error": e}), + None => json!({"type": "storagepruned", "freed": freed, "containers": containers, "images": images}), + }; + emit(ev.to_string()); + crate::storage::emit_report(); + send(Cmd::Refresh); +} + +fn builder_settings(save: Option) { + if let Some(body) = save { + match client::request("POST", "/kiri/builder", Some(&body)) { + Ok(r) if r.ok() => { + let mut v = r.json(); + v["type"] = json!("buildersettings"); + emit(v.to_string()); + emit(notice("ok", &tr("Builder settings saved"))); + return; + } + Ok(r) => emit(notice("error", &trf("Could not save builder settings: {error}", &[("error", &r.error())]))), + Err(e) => emit(notice("error", &trf("Could not save builder settings: {error}", &[("error", &e)]))), + } + } + let mut ev = client::get_background("/kiri/builder").unwrap_or_else(|e| json!({"error": e.to_string()})); + ev["type"] = json!("buildersettings"); + emit(ev.to_string()); +} + +/// Volumes view: reads each volume's disk usage asynchronously without waking +/// a sleeping VM or touching WSL while stopped. Single-flight with coalesced +/// re-run so repeated UI messages never accumulate background threads. +fn spawn_volume_sizes() { + use std::sync::atomic::{AtomicBool, Ordering}; + static BUSY: AtomicBool = AtomicBool::new(false); + static RERUN: AtomicBool = AtomicBool::new(false); + + if BUSY.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { + RERUN.store(true, Ordering::Release); + return; + } + std::thread::spawn(|| { + struct Guard<'a>(&'a AtomicBool); + impl Drop for Guard<'_> { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } + } + let _guard = Guard(&BUSY); + loop { + RERUN.store(false, Ordering::Release); + let sizes = if crate::serve::is_stopped() { + json!({}) + } else { + client::get_background("/kiri/volumes/sizes") + .ok() + .and_then(|v| v.get("sizes").filter(|s| s.is_object()).cloned()) + .unwrap_or_else(|| json!({})) + }; + emit(json!({"type": "volumesizes", "sizes": sizes}).to_string()); + if !RERUN.swap(false, Ordering::AcqRel) { + break; + } + } + }); +} + /// The tray's commands. pub fn on_tray(cmd: &str) { match cmd { diff --git a/crates/kiri-win/src/k8s.rs b/crates/kiri-win/src/k8s.rs index 94b531b6d..60de22678 100644 --- a/crates/kiri-win/src/k8s.rs +++ b/crates/kiri-win/src/k8s.rs @@ -79,12 +79,33 @@ pub fn handle(action: &str, value: &Value) { "start" => op("start", |say| start(say)), "stop" => op("stop", |say| stop(say)), "deletecluster" => op("deletecluster", |say| delete_cluster(say)), - // Settings → Kubernetes → Network: saved, and the node recreated with them. + // Settings → Kubernetes: saved, and the node recreated with them. "set" => { let sans: Vec = value["tls_san"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect(); let lan = value["lan"] == true; let port = value["port"].as_u64().and_then(|p| u16::try_from(p).ok()); - op("set", move |say| set(lan, sans, port, say)); + let version = value.get("version").map(|v| { + v.as_str() + .map(str::trim) + .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("default")) + .map(str::to_owned) + }); + let k3s_args = value.get("k3s_args").and_then(Value::as_array).map(|arr| { + arr.iter() + .filter_map(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .collect::>() + }); + op("set", move |say| set(lan, sans, port, version, k3s_args, say)); + } + "manifests" => { + if let Ok(dir) = manifests_dir() { + let _ = std::fs::create_dir_all(&dir); + let mut cmd = crate::win::tool("explorer.exe"); + let _ = cmd.arg(dir).spawn(); + } } "delete" => delete(arg("ns"), arg("pod")), "logs" => logs(arg("ns"), arg("pod"), arg("container"), value["previous"] == true), @@ -110,7 +131,7 @@ fn copy(text: &str) { /// and the port asked for. They are applied when the node container is /// created, so a change recreates it; the cluster's state is in the volume /// and stays. -#[derive(Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)] struct Config { #[serde(default)] lan: bool, @@ -120,12 +141,64 @@ struct Config { /// the node takes the next free one; `port` in its container says which. #[serde(default, skip_serializing_if = "Option::is_none")] port: Option, + /// Custom k3s image tag (`rancher/k3s:`), or `None` for `IMAGE.1`. + #[serde(default, skip_serializing_if = "Option::is_none")] + version: Option, + /// Extra arguments appended to `k3s server`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + k3s_args: Vec, } +/// Maximum byte length of a single custom `--k3s-arg` value. +const MAX_K3S_ARG_LEN: usize = 512; + impl Config { fn api_port(&self) -> u16 { self.port.unwrap_or(API_PORT) } + + fn version_tag(&self) -> &str { + self.version.as_deref().filter(|v| valid_version(v)).unwrap_or(IMAGE.1) + } +} + +fn valid_version(tag: &str) -> bool { + !tag.is_empty() + && tag.len() <= 128 + && !tag.eq_ignore_ascii_case("default") + && !tag.contains("..") + && tag.as_bytes()[0].is_ascii_alphanumeric() + && tag.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + +fn valid_k3s_arg(arg: &str) -> bool { + !arg.trim().is_empty() + && arg.len() <= MAX_K3S_ARG_LEN + && !arg.bytes().any(|b| b < 0x20 || b == 0x7f) + && !arg.chars().any(char::is_control) +} + +fn server_cmd(cfg: &Config) -> Vec { + let mut cmd: Vec = [ + "server", + "--disable", + "traefik", + "--tls-san", + "127.0.0.1", + "--tls-san", + "localhost", + "--write-kubeconfig-mode", + "644", + ] + .map(String::from) + .to_vec(); + for name in cfg.tls_san.iter().filter(|n| valid_san(n)) { + cmd.extend(["--tls-san".to_owned(), name.clone()]); + } + for arg in cfg.k3s_args.iter().filter(|a| valid_k3s_arg(a)) { + cmd.push(arg.clone()); + } + cmd } /// %LOCALAPPDATA%\Kiri, where the window keeps its settings. @@ -137,6 +210,10 @@ fn config_path() -> io::Result { Ok(state_dir()?.join("k8s.json")) } +fn manifests_dir() -> io::Result { + Ok(state_dir()?.join("k8s-manifests")) +} + 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() } @@ -145,7 +222,11 @@ fn config() -> Config { /// 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(), drives())).unwrap_or_default() + if cfg.version.is_none() && cfg.k3s_args.is_empty() { + serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), drives())).unwrap_or_default() + } else { + serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), drives(), cfg.version_tag(), &cfg.k3s_args)).unwrap_or_default() + } } /// Where WSL puts this PC's drives (`/mnt`, unless `[automount] root` in @@ -305,6 +386,10 @@ fn read_lists() -> Value { v["op"] = json!(current_op()); v["context"] = json!(context()); v["config"] = json!(config()); + v["default_version"] = json!(IMAGE.1); + if let Ok(dir) = manifests_dir() { + v["manifests_dir"] = json!(dir); + } v } @@ -443,13 +528,11 @@ fn start(say: &dyn Fn(&str)) -> io::Result<()> { if port != want { say(&format!("port {want} is in use; the API server takes {port}")); } - let (repo, tag) = IMAGE; + let repo = IMAGE.0; + let tag = cfg.version_tag(); say(&format!("pulling {repo}:{tag}…")); pull(repo, tag)?; - let mut cmd: Vec = ["server", "--disable", "traefik", "--tls-san", "127.0.0.1", "--tls-san", "localhost", "--write-kubeconfig-mode", "644"].map(String::from).to_vec(); - for name in cfg.tls_san.iter().filter(|n| valid_san(n)) { - cmd.extend(["--tls-san".to_owned(), name.clone()]); - } + let cmd = server_cmd(&cfg); let body = json!({ "Image": format!("{repo}:{tag}"), "Cmd": cmd, @@ -537,9 +620,16 @@ fn delete_cluster(say: &dyn Fn(&str)) -> io::Result<()> { /// `kiri k8s set`: saves the settings and, if the cluster exists and they /// changed, recreates its node with them. -fn set(lan: bool, sans: Vec, port: Option, say: &dyn Fn(&str)) -> io::Result<()> { +fn set( + lan: bool, + sans: Vec, + port: Option, + version: Option>, + k3s_args: Option>, + say: &dyn Fn(&str), +) -> io::Result<()> { let mut cfg = config(); - let before = (cfg.lan, cfg.tls_san.clone(), cfg.api_port()); + let before = cfg.clone(); cfg.lan = lan; let list: Vec = sans.iter().map(|n| n.trim().to_owned()).filter(|n| !n.is_empty()).collect(); if let Some(bad) = list.iter().find(|n| !valid_san(n)) { @@ -552,10 +642,26 @@ fn set(lan: bool, sans: Vec, port: Option, say: &dyn Fn(&str)) -> i } cfg.port = (p != API_PORT).then_some(p); } + if let Some(ver) = version { + match ver { + None => cfg.version = None, + Some(tag) if valid_version(&tag) => cfg.version = Some(tag), + Some(tag) => return Err(io::Error::other(format!("invalid k3s version tag `{tag}`"))), + } + } + if let Some(args) = k3s_args { + if args.len() > 64 { + return Err(io::Error::other("too many --k3s-arg values (at most 64)")); + } + if let Some(bad) = args.iter().find(|a| !valid_k3s_arg(a)) { + return Err(io::Error::other(format!("invalid --k3s-arg `{bad}`"))); + } + cfg.k3s_args = args; + } let node = if exists()? { Some(client::get(&format!("/containers/{NAME}/json"))?) } else { None }; // A port asked for that the node doesn't already hold must be free now. let port = cfg.api_port(); - if port != before.2 && node.as_ref().and_then(bound_port) != Some(port) && !port_free(port, cfg.lan) { + if port != before.api_port() && node.as_ref().and_then(bound_port) != Some(port) && !port_free(port, cfg.lan) { return Err(io::Error::other(format!("port {port} is in use on this PC; choose another"))); } let path = config_path()?; @@ -567,7 +673,7 @@ fn set(lan: bool, sans: Vec, port: Option, say: &dyn Fn(&str)) -> i if cfg.tls_san.is_empty() { "none".to_owned() } else { cfg.tls_san.join(", ") } )); let Some(node) = node else { return Ok(()) }; - if (cfg.lan, cfg.tls_san.clone(), port) == before { + if cfg == before { return Ok(()); } if node["State"]["Running"] != true { @@ -627,6 +733,9 @@ pub(crate) fn sync_soon() { let result = (|| -> io::Result { let deadline = Instant::now() + Duration::from_secs(180); loop { + if crate::serve::is_stopped() { + return Ok(false); + } let (status, info) = request("GET", &format!("/containers/{NAME}/json"), None)?; if status == 404 || info["State"]["Running"] != true { return Ok(false); @@ -796,4 +905,42 @@ mod tests { assert!(!super::valid_san(bad), "{bad}"); } } + + #[test] + fn custom_k3s_version_and_args_are_validated_and_applied() { + assert!(super::valid_version("v1.31.4-k3s1")); + assert!(!super::valid_version("default")); + assert!(!super::valid_version("rancher/k3s:v1.31.4-k3s1")); + assert!(super::valid_k3s_arg("--flannel-backend=none")); + assert!(!super::valid_k3s_arg("")); + assert!(!super::valid_k3s_arg("--bad\0arg")); + + let cfg = super::Config { + lan: false, + tls_san: vec!["my-pc.local".into()], + port: None, + version: Some("v1.31.4-k3s1".into()), + k3s_args: vec!["--flannel-backend=none".into(), "--disable-network-policy".into()], + }; + assert_eq!(cfg.version_tag(), "v1.31.4-k3s1"); + assert_eq!( + super::server_cmd(&cfg), + vec![ + "server", + "--disable", + "traefik", + "--tls-san", + "127.0.0.1", + "--tls-san", + "localhost", + "--write-kubeconfig-mode", + "644", + "--tls-san", + "my-pc.local", + "--flannel-backend=none", + "--disable-network-policy", + ] + ); + assert_ne!(super::made_with(&cfg), super::made_with(&super::Config::default())); + } } diff --git a/crates/kiri-win/src/main.rs b/crates/kiri-win/src/main.rs index b184c761b..9f5737ba3 100644 --- a/crates/kiri-win/src/main.rs +++ b/crates/kiri-win/src/main.rs @@ -25,7 +25,7 @@ mod assemble; #[cfg(windows)] #[path = "../../kiri/src/ui/lang.rs"] mod lang; -#[cfg(windows)] +#[cfg(any(windows, test))] mod client; #[cfg(windows)] mod detail; @@ -44,6 +44,10 @@ mod relay; #[cfg(windows)] #[path = "../../kiri/src/hostrelay.rs"] mod hostrelay; +#[cfg(any(windows, test))] +#[cfg_attr(not(windows), allow(dead_code))] +#[path = "../../kiri/src/dockerctx.rs"] +mod dockerctx; #[cfg(windows)] mod win; // The window's USB view, through usbipd-win. @@ -70,6 +74,7 @@ mod builds; // and Linux's own crates/kiri/src/buildwith.rs. #[cfg(windows)] #[path = "../../kiri/src/buildwith.rs"] +#[allow(dead_code)] mod buildwith; // Kiri's program moved or deleted from where it started: the Mac's and // Linux's own crates/kiri/src/appwatch.rs. @@ -94,11 +99,18 @@ mod daemon { #[cfg(windows)] mod wslconfig; // Kiri Dev's names (the window on Windows is always Kiri) and Share, the -// Mac's own files: crates/kiri/src/flavor.rs and share.rs. +// Mac's own files: crates/kiri/src/flavor.rs and share.rs. Share's roots +// come from crates/kiri-image/src/roots.rs, mounted here directly as +// crate::roots — the name share.rs reaches it by in kiri, whose main.rs +// aliases kiri_image::roots — so the same file compiles unchanged. #[cfg(windows)] #[path = "../../kiri/src/flavor.rs"] mod flavor; #[cfg(windows)] +#[path = "../../kiri-image/src/roots.rs"] +#[allow(dead_code)] +mod roots; +#[cfg(windows)] #[path = "../../kiri/src/share.rs"] #[allow(dead_code)] mod share; @@ -110,6 +122,34 @@ mod update; mod wslsync; #[cfg(any(windows, test))] mod refuse; +// Opt-in Windows bind-mount watcher (ReadDirectoryChangesW -> /kiri/fs-events): +// path mapping, buffer decoding and coalescing tested on any host. +#[cfg(any(windows, test))] +mod watch; +// Windows inbound published-port forwarder (UDP and non-loopback host-IP TCP +// to WSL 2's eth0 IPv4 address): tested on any host. +#[cfg(any(windows, test))] +mod ports; +// Settings → Storage: custom WSL distro location in %LOCALAPPDATA%\Kiri\storage.json. +#[cfg(any(windows, test))] +mod storage; + +#[cfg(any(windows, test))] +pub(crate) fn format_try_wait(res: std::io::Result>) -> Option { + match res { + Ok(None) => None, + Ok(Some(status)) => Some(format!("{status}")), + Err(e) => Some(format!("{e}")), + } +} + +#[cfg(any(windows, test))] +pub(crate) fn format_wait_status(res: std::io::Result) -> String { + match res { + Ok(status) => format!("{status}"), + Err(e) => format!("{e}"), + } +} // Settings → Import from Docker Desktop: the Mac's and Linux's own // crates/kiri/src/import.rs, through the docker CLI's contexts. #[cfg(windows)] @@ -162,6 +202,7 @@ fn main() -> std::process::ExitCode { // distro (--distro) is for development and skips it. let setup = !std::env::args().any(|a| a == "--distro") && setup::needed(); serve::set_setup_pending(setup); + serve::init_stopped(); if let Err(e) = serve::start(cfg.clone()) { // Another kiri-win already serves the pipe: show its window instead. if app::running() { @@ -178,10 +219,15 @@ fn main() -> std::process::ExitCode { return std::process::ExitCode::FAILURE; } client::set_pipe(&cfg.pipe); + if !setup { + engine::heal_docker_config(&cfg.pipe); + } + ports::start(); if let Err(e) = dns::start() { serve::log(&format!("dns on 127.0.0.1:53: {e}")); } engine::start(engine::Env { distro: cfg.distro.clone(), pipe: cfg.pipe.clone() }); + watch::start_if_enabled(); // Its folder renamed, moved or deleted around it (Windows won't delete // a running program itself): docker build handed back as it was before // Kiri took it, the choice kept for when Kiri runs again, and Kiri quits. @@ -235,3 +281,33 @@ fn main() -> std::process::ExitCode { eprintln!("kiri-win runs on Windows only"); std::process::ExitCode::FAILURE } + +#[cfg(test)] +mod exit_status_tests { + #[test] + fn formats_exit_status_with_display_instead_of_nested_debug() { + let run = |code: i32| { + #[cfg(windows)] + let mut cmd = { + let mut c = std::process::Command::new("cmd"); + c.args(["/C", &format!("exit {code}")]); + c + }; + #[cfg(not(windows))] + let mut cmd = { + let mut c = std::process::Command::new("sh"); + c.args(["-c", &format!("exit {code}")]); + c + }; + cmd.status().unwrap() + }; + let status = run(15); + let waited = super::format_wait_status(Ok(status)); + assert!(!waited.contains("Ok(") && !waited.contains("ExitStatus("), "nested Debug leaked: {waited}"); + assert!(waited.contains("15"), "{waited}"); + let polled = super::format_try_wait(Ok(Some(status))).unwrap(); + assert_eq!(polled, waited); + assert_eq!(super::format_try_wait(Ok(None)), None); + assert_eq!(super::format_wait_status(Err(std::io::Error::other("wait failed"))), "wait failed"); + } +} diff --git a/crates/kiri-win/src/ports.rs b/crates/kiri-win/src/ports.rs new file mode 100644 index 000000000..ec00eed54 --- /dev/null +++ b/crates/kiri-win/src/ports.rs @@ -0,0 +1,1071 @@ +//! Published container ports on Windows (`#640`, `#218`). +//! +//! WSL 2's built-in `localhostForwarding` (`wslrelay.exe`) only forwards TCP on +//! Windows loopback (`127.0.0.1:/tcp` and `[::1]:/tcp`): +//! - It never forwards UDP at all (`#640`). +//! - It never binds non-loopback Windows host interface addresses (``) +//! for `-p 0.0.0.0:port:cport` or `-p :port:cport` (`#218`). +//! +//! This module pushes the Windows host's interface IPs to the WSL daemon via +//! `POST /kiri/win-ports` (so `-p :port:cport` binds WSL's internal +//! `eth0` IP without leaking `127.0.0.1:port` on Windows, while bogus IPs still +//! fail with `Address not available (os error 99)`), and maintains Windows-side +//! UDP and non-loopback TCP forwarders to `:`. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::collections::{BTreeSet, HashMap}; +use std::io::{self, Read, Write}; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, SocketAddrV4, SocketAddrV6, TcpListener, TcpStream, UdpSocket}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; +use std::time::{Duration, Instant}; + +/// Idle timeout for a per-client UDP forwarding session, matching conntrack. +const UDP_IDLE: Duration = Duration::from_secs(60); +/// Read timeout on UDP sockets so the loop can check `stop` and reap idle sessions. +const UDP_POLL: Duration = Duration::from_millis(250); +/// Poll interval on non-blocking `TcpListener::accept` so `stop()` joins within ~100ms +/// without needing a self-connect that could hang if the bound IP disappeared. +const TCP_ACCEPT_POLL: Duration = Duration::from_millis(100); +/// Maximum concurrent UDP client sessions per published UDP port. +const MAX_UDP_SESSIONS: usize = 1024; +/// Connect timeout when dialing the WSL 2 `eth0` target for a forwarded TCP connection. +const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Proto { + Tcp, + Udp, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct PublishedPort { + pub proto: String, + pub host_ip: String, + pub host_port: u16, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct ForwardSpec { + pub proto: Proto, + pub bind_addr: SocketAddr, + pub target_addr: SocketAddr, +} + +/// Parses a bare or bracketed IPv4/IPv6 address, stripping any `%scope` suffix. +pub fn parse_ip(s: &str) -> Option { + let bare = s.trim().strip_prefix('[').and_then(|i| i.strip_suffix(']')).unwrap_or(s.trim()); + let bare = bare.split('%').next().unwrap_or(bare); + bare.parse::().ok().map(|a| a.to_canonical()) +} + +/// Computes the Windows-side TCP and UDP listeners needed for `published`, +/// forwarding to `wsl_ip:`: +/// - UDP: every published UDP port (`0.0.0.0:port`, `[::]:port`, `127.0.0.1:port`, +/// `[::1]:port`, or `:port`), since `wslrelay.exe` never forwards UDP. +/// - TCP: +/// - `127.0.0.1` and `::1` are left to `wslrelay.exe`. +/// - `0.0.0.0` (or `""`) expands to every non-loopback Windows IPv4 interface +/// address in `win_ipv4` so `-p 0.0.0.0:port:cport` answers on both +/// `127.0.0.1:port` (via `wslrelay.exe`) and `:port`. +/// - `::` expands to every non-loopback global Windows IPv6 interface address +/// in `win_ipv6`. +/// - A specific non-loopback `` binds `:port` alone. +pub fn plan_forwards( + wsl_ip: Ipv4Addr, + published: &[PublishedPort], + win_ipv4: &[Ipv4Addr], + win_ipv6: &[Ipv6Addr], +) -> Vec { + // In WSL 2 mirrored or bridged networking mode, `wsl_ip` is itself one of + // the Windows host's interface addresses; skip Windows-side forwarding so + // we never create a self-forwarding loop. + if wsl_ip.is_loopback() || wsl_ip.is_unspecified() || win_ipv4.contains(&wsl_ip) { + return Vec::new(); + } + let mut specs = BTreeSet::new(); + for p in published { + if p.host_port == 0 { + continue; + } + let target_addr = SocketAddr::V4(SocketAddrV4::new(wsl_ip, p.host_port)); + let host_ip = p.host_ip.trim(); + let proto = p.proto.to_ascii_lowercase(); + match proto.as_str() { + "udp" => { + if host_ip.is_empty() || host_ip == "0.0.0.0" { + specs.insert(ForwardSpec { + proto: Proto::Udp, + bind_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, p.host_port)), + target_addr, + }); + } else if host_ip == "::" || host_ip == "[::]" { + specs.insert(ForwardSpec { + proto: Proto::Udp, + bind_addr: SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, p.host_port, 0, 0)), + target_addr, + }); + } else if let Some(ip) = parse_ip(host_ip) + && ip != IpAddr::V4(wsl_ip) + { + specs.insert(ForwardSpec { + proto: Proto::Udp, + bind_addr: SocketAddr::new(ip, p.host_port), + target_addr, + }); + } + } + "tcp" => { + if host_ip.is_empty() || host_ip == "0.0.0.0" { + for &ip4 in win_ipv4 { + if !ip4.is_loopback() + && !ip4.is_unspecified() + && !ip4.is_multicast() + && !(ip4.octets()[0] == 169 && ip4.octets()[1] == 254) + && ip4 != wsl_ip + { + specs.insert(ForwardSpec { + proto: Proto::Tcp, + bind_addr: SocketAddr::V4(SocketAddrV4::new(ip4, p.host_port)), + target_addr, + }); + } + } + } else if host_ip == "::" || host_ip == "[::]" { + for &ip6 in win_ipv6 { + if !ip6.is_loopback() + && !ip6.is_unspecified() + && !ip6.is_multicast() + && (ip6.segments()[0] & 0xffc0) != 0xfe80 + { + specs.insert(ForwardSpec { + proto: Proto::Tcp, + bind_addr: SocketAddr::V6(SocketAddrV6::new(ip6, p.host_port, 0, 0)), + target_addr, + }); + } + } + } else if let Some(ip) = parse_ip(host_ip) + && !ip.is_loopback() + && !ip.is_unspecified() + && !ip.is_multicast() + && ip != IpAddr::V4(wsl_ip) + { + specs.insert(ForwardSpec { + proto: Proto::Tcp, + bind_addr: SocketAddr::new(ip, p.host_port), + target_addr, + }); + } + } + _ => {} + } + } + specs.into_iter().collect() +} + +/// Whether the initial bytes of an HTTP request on Kiri's pipe represent a +/// container or engine lifecycle mutation that can create, start, stop, or +/// update published ports. +pub fn is_port_affecting_request(head: &[u8]) -> bool { + let line_end = head.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(head.len().min(256)); + let Ok(line) = std::str::from_utf8(&head[..line_end]) else { + return false; + }; + let mut parts = line.split_whitespace(); + let Some(method) = parts.next() else { + return false; + }; + let Some(path) = parts.next() else { + return false; + }; + if !matches!(method, "POST" | "DELETE") { + return false; + } + let path = path.split('?').next().unwrap_or(path); + path.contains("/containers") + || matches!(path, "/kiri/stop" | "/kiri/sleep" | "/kiri/wake") +} + +fn wake_connect_addr(bound: SocketAddr) -> SocketAddr { + match bound { + SocketAddr::V4(v4) if v4.ip().is_unspecified() => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, v4.port())), + SocketAddr::V6(v6) if v6.ip().is_unspecified() => SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, v6.port(), 0, 0)), + other => other, + } +} + +pub struct TcpForwarder { + local_addr: SocketAddr, + stop: Arc, + thread: Option>, +} + +impl TcpForwarder { + pub fn start(bind_addr: SocketAddr, target_addr: SocketAddr) -> io::Result { + let listener = TcpListener::bind(bind_addr)?; + listener.set_nonblocking(true)?; + let local_addr = listener.local_addr()?; + let stop = Arc::new(AtomicBool::new(false)); + let stop_loop = stop.clone(); + let thread = std::thread::Builder::new() + .name(format!("kiri-win-tcp-{}", local_addr.port())) + .spawn(move || tcp_accept_loop(listener, target_addr, stop_loop))?; + Ok(TcpForwarder { + local_addr, + stop, + thread: Some(thread), + }) + } + + #[cfg(test)] + pub fn local_addr(&self) -> SocketAddr { + self.local_addr + } + + pub fn stop(mut self) { + self.stop_inner(); + } + + fn stop_inner(&mut self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +impl Drop for TcpForwarder { + fn drop(&mut self) { + self.stop_inner(); + } +} + +fn tcp_accept_loop(listener: TcpListener, target_addr: SocketAddr, stop: Arc) { + while !stop.load(Ordering::SeqCst) { + let (client, _) = match listener.accept() { + Ok(pair) => pair, + Err(e) if e.kind() == io::ErrorKind::WouldBlock => { + std::thread::sleep(TCP_ACCEPT_POLL); + continue; + } + Err(_) => { + if stop.load(Ordering::SeqCst) { + break; + } + std::thread::sleep(TCP_ACCEPT_POLL); + continue; + } + }; + if stop.load(Ordering::SeqCst) { + break; + } + let _ = client.set_nonblocking(false); + let _ = std::thread::Builder::new().name("kiri-win-tcp-conn".into()).spawn(move || { + let _ = relay_tcp_conn(client, target_addr); + }); + } +} + +fn relay_tcp_conn(client: TcpStream, target_addr: SocketAddr) -> io::Result<()> { + let backend = TcpStream::connect_timeout(&target_addr, TCP_CONNECT_TIMEOUT)?; + let _ = client.set_nodelay(true); + let _ = backend.set_nodelay(true); + let mut client_read = client.try_clone()?; + let mut backend_write = backend.try_clone()?; + let up = std::thread::Builder::new().name("kiri-win-tcp-up".into()).spawn(move || { + let how = if copy_stream(&mut client_read, &mut backend_write).is_ok() { + Shutdown::Write + } else { + Shutdown::Both + }; + let _ = backend_write.shutdown(how); + })?; + let mut backend_read = backend; + let mut client_write = client; + let how = if copy_stream(&mut backend_read, &mut client_write).is_ok() { + Shutdown::Write + } else { + Shutdown::Both + }; + let _ = client_write.shutdown(how); + let _ = up.join(); + Ok(()) +} + +fn copy_stream(from: &mut impl Read, to: &mut impl Write) -> io::Result<()> { + let mut buf = vec![0u8; 64 * 1024]; + loop { + let n = from.read(&mut buf)?; + if n == 0 { + return Ok(()); + } + to.write_all(&buf[..n])?; + } +} + +struct UdpClientSession { + backend: UdpSocket, + target_addr: SocketAddr, + last: Arc>, + stop: Arc, + reader: Option>, +} + +impl UdpClientSession { + fn open(listener: &UdpSocket, target_addr: SocketAddr, client_addr: SocketAddr) -> io::Result { + let bind_any = if target_addr.is_ipv6() { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)) + } else { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)) + }; + let backend = UdpSocket::bind(bind_any)?; + disable_udp_connreset(&backend); + let backend_read = backend.try_clone()?; + backend_read.set_read_timeout(Some(UDP_POLL))?; + let reply_sock = listener.try_clone()?; + let last = Arc::new(Mutex::new(Instant::now())); + let last_r = last.clone(); + let stop = Arc::new(AtomicBool::new(false)); + let stop_r = stop.clone(); + let reader = std::thread::Builder::new().name("kiri-win-udp-reply".into()).spawn(move || { + let mut rbuf = vec![0u8; 65_536]; + while !stop_r.load(Ordering::SeqCst) { + match backend_read.recv_from(&mut rbuf) { + Ok((n, from)) => { + if stop_r.load(Ordering::SeqCst) { + break; + } + if from == target_addr { + *last_r.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); + let _ = reply_sock.send_to(&rbuf[..n], client_addr); + } + } + Err(e) + if matches!( + e.kind(), + io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::ConnectionReset | io::ErrorKind::Interrupted + ) => + { + if last_r.lock().unwrap_or_else(PoisonError::into_inner).elapsed() >= UDP_IDLE { + break; + } + } + Err(_) => break, + } + } + })?; + Ok(UdpClientSession { backend, target_addr, last, stop, reader: Some(reader) }) + } + + fn send(&self, payload: &[u8]) -> io::Result { + self.backend.send_to(payload, self.target_addr) + } + + fn is_finished(&self) -> bool { + self.reader.as_ref().is_none_or(JoinHandle::is_finished) + } + + fn last_active(&self) -> Instant { + *self.last.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn touch(&self) { + *self.last.lock().unwrap_or_else(PoisonError::into_inner) = Instant::now(); + } + + fn stop_inner(&mut self) { + self.stop.store(true, Ordering::SeqCst); + if let Some(r) = self.reader.take() { + if !r.is_finished() + && let Ok(local) = self.backend.local_addr() + { + let wake_target = wake_connect_addr(local); + let bind_any = if wake_target.is_ipv6() { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + } else { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)) + }; + if let Ok(waker) = UdpSocket::bind(bind_any) { + let _ = waker.send_to(&[], wake_target); + } + } + let _ = r.join(); + } + } + + fn close(mut self) { + self.stop_inner(); + } +} + +impl Drop for UdpClientSession { + fn drop(&mut self) { + self.stop_inner(); + } +} + +pub struct UdpForwarder { + local_addr: SocketAddr, + stop: Arc, + thread: Option>, +} + +impl UdpForwarder { + pub fn start(bind_addr: SocketAddr, target_addr: SocketAddr) -> io::Result { + let listener = UdpSocket::bind(bind_addr)?; + disable_udp_connreset(&listener); + listener.set_read_timeout(Some(UDP_POLL))?; + let local_addr = listener.local_addr()?; + let stop = Arc::new(AtomicBool::new(false)); + let stop_loop = stop.clone(); + let thread = std::thread::Builder::new() + .name(format!("kiri-win-udp-{}", local_addr.port())) + .spawn(move || udp_forward_loop(listener, target_addr, stop_loop))?; + Ok(UdpForwarder { + local_addr, + stop, + thread: Some(thread), + }) + } + + #[cfg(test)] + pub fn local_addr(&self) -> SocketAddr { + self.local_addr + } + + pub fn stop(mut self) { + self.stop_inner(); + } + + fn stop_inner(&mut self) { + self.stop.store(true, Ordering::SeqCst); + let wake_target = wake_connect_addr(self.local_addr); + let bind_any = if wake_target.is_ipv6() { + SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::LOCALHOST, 0, 0, 0)) + } else { + SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0)) + }; + if let Ok(waker) = UdpSocket::bind(bind_any) { + let _ = waker.send_to(&[], wake_target); + } + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + } +} + +impl Drop for UdpForwarder { + fn drop(&mut self) { + self.stop_inner(); + } +} + +fn udp_forward_loop(listener: UdpSocket, target_addr: SocketAddr, stop: Arc) { + let mut sessions: HashMap = HashMap::new(); + let mut buf = vec![0u8; 65_536]; + let mut last_reap = Instant::now(); + while !stop.load(Ordering::SeqCst) { + match listener.recv_from(&mut buf) { + Ok((len, peer)) => { + if stop.load(Ordering::SeqCst) { + break; + } + let stale = sessions.get(&peer).is_some_and(UdpClientSession::is_finished); + if stale && let Some(old) = sessions.remove(&peer) { + old.close(); + } + if !sessions.contains_key(&peer) { + if sessions.len() >= MAX_UDP_SESSIONS + && let Some(oldest) = sessions.iter().min_by_key(|(_, s)| s.last_active()).map(|(k, _)| *k) + && let Some(old) = sessions.remove(&oldest) + { + old.close(); + } + match UdpClientSession::open(&listener, target_addr, peer) { + Ok(s) => { + sessions.insert(peer, s); + } + Err(_) => continue, + } + } + if let Some(s) = sessions.get(&peer) { + s.touch(); + if s.send(&buf[..len]).is_err() + && let Some(dead) = sessions.remove(&peer) + { + dead.close(); + } + } + } + Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut | io::ErrorKind::ConnectionReset | io::ErrorKind::Interrupted) => {} + Err(_) => { + if stop.load(Ordering::SeqCst) { + break; + } + } + } + if last_reap.elapsed() >= Duration::from_secs(1) { + last_reap = Instant::now(); + let expired: Vec = sessions.iter().filter(|(_, s)| s.last_active().elapsed() >= UDP_IDLE || s.is_finished()).map(|(k, _)| *k).collect(); + for k in expired { + if let Some(s) = sessions.remove(&k) { + s.close(); + } + } + } + } + for (_, s) in sessions.drain() { + s.close(); + } +} + +/// Disables WinSock's `SIO_UDP_CONNRESET` on `sock` so an ICMP Port Unreachable +/// from one closed client does not make the next `recv_from` return `WSAECONNRESET`. +#[cfg(windows)] +fn disable_udp_connreset(sock: &UdpSocket) { + use std::os::windows::io::AsRawSocket; + use windows_sys::Win32::Networking::WinSock::{WSAIoctl, SOCKET}; + const SIO_UDP_CONNRESET: u32 = 0x9800_000C; + let enable: u32 = 0; + let mut bytes_returned: u32 = 0; + // SAFETY: valid socket handle and 4-byte boolean buffer for SIO_UDP_CONNRESET. + unsafe { + let _ = WSAIoctl( + sock.as_raw_socket() as SOCKET, + SIO_UDP_CONNRESET, + (&enable as *const u32).cast(), + std::mem::size_of::() as u32, + std::ptr::null_mut(), + 0, + &mut bytes_returned, + std::ptr::null_mut(), + None, + ); + } +} + +#[cfg(not(windows))] +fn disable_udp_connreset(_sock: &UdpSocket) {} + +#[cfg(windows)] +mod runtime { + use super::*; + use std::collections::HashSet; + use std::os::windows::io::AsRawSocket; + use std::sync::Condvar; + use serde_json::json; + use windows_sys::Win32::Networking::WinSock::{ + AF_INET, AF_INET6, SIO_ADDRESS_LIST_QUERY, SOCKADDR_IN, SOCKADDR_IN6, SOCKET, SOCKET_ADDRESS_LIST, WSAIoctl, + }; + + const RESYNC_INTERVAL: Duration = Duration::from_secs(3); + + enum ActiveForwarder { + Tcp(TcpForwarder), + Udp(UdpForwarder), + } + + impl ActiveForwarder { + fn stop(self) { + match self { + ActiveForwarder::Tcp(f) => f.stop(), + ActiveForwarder::Udp(f) => f.stop(), + } + } + } + + static ACTIVE: AtomicBool = AtomicBool::new(false); + static WAKE: std::sync::LazyLock<(Mutex, Condvar)> = std::sync::LazyLock::new(|| (Mutex::new(false), Condvar::new())); + static SYNC_LOCK: Mutex<()> = Mutex::new(()); + static LAST_SYNC: Mutex> = Mutex::new(None); + static FORWARDERS: std::sync::LazyLock>> = std::sync::LazyLock::new(|| Mutex::new(HashMap::new())); + + /// Queries WinSock `SIO_ADDRESS_LIST_QUERY` for all active local IPv4 and + /// IPv6 interface addresses on the Windows host. + pub fn query_windows_host_ips() -> (Vec, Vec, Vec) { + let mut all = BTreeSet::from(["127.0.0.1".to_owned(), "::1".to_owned()]); + let mut v4_set = BTreeSet::new(); + let mut v6_set = BTreeSet::new(); + + if let Ok(sock4) = UdpSocket::bind("127.0.0.1:0") { + let mut buf = vec![0usize; 2048]; + let cap = (buf.len() * std::mem::size_of::()) as u32; + let mut returned = 0u32; + // SAFETY: `buf` is usize-aligned and sized to `cap` bytes for SOCKET_ADDRESS_LIST. + let rc = unsafe { + WSAIoctl( + sock4.as_raw_socket() as SOCKET, + SIO_ADDRESS_LIST_QUERY, + std::ptr::null(), + 0, + buf.as_mut_ptr().cast(), + cap, + &mut returned, + std::ptr::null_mut(), + None, + ) + }; + if rc == 0 && (returned as usize) >= std::mem::size_of::() { + // SAFETY: WSAIoctl succeeded and filled ` SOCKET_ADDRESS_LIST` inside `buf`. + unsafe { + let list = &*(buf.as_ptr() as *const SOCKET_ADDRESS_LIST); + let count = (list.iAddressCount.max(0) as usize).min(256); + let addrs = std::slice::from_raw_parts(list.Address.as_ptr(), count); + for entry in addrs { + if !entry.lpSockaddr.is_null() + && (entry.iSockaddrLength as usize) >= std::mem::size_of::() + && (*entry.lpSockaddr).sa_family == AF_INET + { + let sin = &*(entry.lpSockaddr as *const SOCKADDR_IN); + let ip = Ipv4Addr::from(sin.sin_addr.S_un.S_addr.to_ne_bytes()); + if !ip.is_unspecified() && !ip.is_multicast() { + all.insert(ip.to_string()); + if !ip.is_loopback() && !(ip.octets()[0] == 169 && ip.octets()[1] == 254) { + v4_set.insert(ip); + } + } + } + } + } + } + } + + if let Ok(sock6) = UdpSocket::bind("[::1]:0") { + let mut buf = vec![0usize; 2048]; + let cap = (buf.len() * std::mem::size_of::()) as u32; + let mut returned = 0u32; + // SAFETY: `buf` is usize-aligned and sized to `cap` bytes for SOCKET_ADDRESS_LIST. + let rc = unsafe { + WSAIoctl( + sock6.as_raw_socket() as SOCKET, + SIO_ADDRESS_LIST_QUERY, + std::ptr::null(), + 0, + buf.as_mut_ptr().cast(), + cap, + &mut returned, + std::ptr::null_mut(), + None, + ) + }; + if rc == 0 && (returned as usize) >= std::mem::size_of::() { + // SAFETY: WSAIoctl succeeded and filled `SOCKET_ADDRESS_LIST` inside `buf`. + unsafe { + let list = &*(buf.as_ptr() as *const SOCKET_ADDRESS_LIST); + let count = (list.iAddressCount.max(0) as usize).min(256); + let addrs = std::slice::from_raw_parts(list.Address.as_ptr(), count); + for entry in addrs { + if !entry.lpSockaddr.is_null() + && (entry.iSockaddrLength as usize) >= std::mem::size_of::() + && (*entry.lpSockaddr).sa_family == AF_INET6 + { + let sin6 = &*(entry.lpSockaddr as *const SOCKADDR_IN6); + let ip = Ipv6Addr::from(sin6.sin6_addr.u.Byte); + if !ip.is_unspecified() && !ip.is_multicast() { + all.insert(ip.to_string()); + if !ip.is_loopback() && (ip.segments()[0] & 0xffc0) != 0xfe80 { + v6_set.insert(ip); + } + } + } + } + } + } + } + + ( + all.into_iter().collect(), + v4_set.into_iter().collect(), + v6_set.into_iter().collect(), + ) + } + + fn clear_all_forwarders() { + let old: Vec = FORWARDERS + .lock() + .unwrap_or_else(PoisonError::into_inner) + .drain() + .map(|(_, f)| f) + .collect(); + for f in old { + f.stop(); + } + } + + /// Synchronizes Windows host interface IPs and published container port + /// forwarders with the WSL daemon right now. + pub fn sync_now() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + let _guard = SYNC_LOCK.lock().unwrap_or_else(PoisonError::into_inner); + if crate::serve::is_stopped() { + clear_all_forwarders(); + return; + } + let (all_ips, win_v4, win_v6) = query_windows_host_ips(); + let body = json!({ "host_ips": all_ips }); + let resp = match crate::client::request_within("POST", "/kiri/win-ports", Some(&body), true, Some(Duration::from_secs(3))) { + Ok(r) => r, + // Do not tear down active port forwarders on a transient HTTP + // read timeout when WSL is still running and busy. + Err(e) if matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted) => return, + Err(_) => { + clear_all_forwarders(); + return; + } + }; + if !resp.ok() { + if resp.status == 503 || resp.error().contains("stopped") || resp.error().contains("did not start") { + clear_all_forwarders(); + } + return; + } + *LAST_SYNC.lock().unwrap_or_else(PoisonError::into_inner) = Some(Instant::now()); + let payload = resp.json(); + let Some(wsl_ip) = payload["wsl_ip"].as_str().and_then(|s| s.parse::().ok()) else { + clear_all_forwarders(); + return; + }; + let mut published = Vec::new(); + for item in payload["ports"].as_array().into_iter().flatten() { + let Some(proto) = item["proto"].as_str() else { continue }; + let host_ip = item["host_ip"].as_str().unwrap_or("").to_owned(); + let Some(host_port) = item["host_port"].as_u64().and_then(|p| u16::try_from(p).ok()) else { continue }; + published.push(PublishedPort { + proto: proto.to_owned(), + host_ip, + host_port, + }); + } + let want = plan_forwards(wsl_ip, &published, &win_v4, &win_v6); + let want_set: HashSet = want.iter().cloned().collect(); + + let to_stop: Vec = { + let mut active = FORWARDERS.lock().unwrap_or_else(PoisonError::into_inner); + let remove_keys: Vec = active.keys().filter(|k| !want_set.contains(*k)).cloned().collect(); + remove_keys.into_iter().filter_map(|k| active.remove(&k)).collect() + }; + for f in to_stop { + f.stop(); + } + + let mut active = FORWARDERS.lock().unwrap_or_else(PoisonError::into_inner); + for spec in want { + if active.contains_key(&spec) { + continue; + } + let started = match spec.proto { + Proto::Tcp => TcpForwarder::start(spec.bind_addr, spec.target_addr).map(ActiveForwarder::Tcp), + Proto::Udp => UdpForwarder::start(spec.bind_addr, spec.target_addr).map(ActiveForwarder::Udp), + }; + match started { + Ok(fwd) => { + active.insert(spec, fwd); + } + Err(e) => { + crate::serve::log(&format!("ports: could not bind {:?} {} -> {}: {e}", spec.proto, spec.bind_addr, spec.target_addr)); + } + } + } + } + + /// Ensures the WSL daemon has received the Windows host's current interface + /// IPs before a container create/start request is processed. + pub fn before_container_op() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + let stale = LAST_SYNC + .lock() + .unwrap_or_else(PoisonError::into_inner) + .is_none_or(|t| t.elapsed() >= Duration::from_secs(2)); + if stale { + sync_now(); + } + } + + /// Synchronizes Windows TCP and UDP port forwarders immediately after a + /// container start/stop/remove/ports request completes, before the HTTP + /// response returns to the Docker client. + pub fn after_container_op() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + sync_now(); + } + + /// Wakes the background port forwarder thread to synchronize with WSL. + pub fn notify() { + if !ACTIVE.load(Ordering::Relaxed) { + return; + } + let (m, cv) = &*WAKE; + *m.lock().unwrap_or_else(PoisonError::into_inner) = true; + cv.notify_all(); + } + + /// Starts the background Windows port forwarder synchronization loop. + pub fn start() { + if ACTIVE.swap(true, Ordering::SeqCst) { + return; + } + let _ = std::thread::Builder::new().name("kiri-win-ports".into()).spawn(|| { + loop { + sync_now(); + let (m, cv) = &*WAKE; + let mut signaled = m.lock().unwrap_or_else(PoisonError::into_inner); + if !*signaled { + let (g, _) = cv.wait_timeout(signaled, RESYNC_INTERVAL).unwrap_or_else(PoisonError::into_inner); + signaled = g; + } + *signaled = false; + } + }); + } +} + +#[cfg(windows)] +pub use runtime::{after_container_op, before_container_op, notify, start, sync_now}; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plans_udp_and_non_loopback_tcp_forwards() { + let wsl_ip = Ipv4Addr::new(198, 51, 100, 107); + let win_v4 = vec![ + Ipv4Addr::new(192, 0, 2, 50), + Ipv4Addr::new(198, 51, 100, 1), + Ipv4Addr::new(169, 254, 10, 20), // link-local APIPA ignored for 0.0.0.0 expansion + ]; + let win_v6 = vec![ + "2001:db8::42".parse::().unwrap(), + "fe80::1".parse::().unwrap(), // link-local ignored for :: expansion + ]; + let published = vec![ + // -p 18120:18120/udp (produces 0.0.0.0 and :: in daemon) + PublishedPort { proto: "udp".into(), host_ip: "0.0.0.0".into(), host_port: 18120 }, + PublishedPort { proto: "udp".into(), host_ip: "::".into(), host_port: 18120 }, + // -p 127.0.0.1:18121:18121/udp + PublishedPort { proto: "udp".into(), host_ip: "127.0.0.1".into(), host_port: 18121 }, + // -p 192.0.2.50:18122:18122/udp + PublishedPort { proto: "udp".into(), host_ip: "192.0.2.50".into(), host_port: 18122 }, + // -p 127.0.0.1:18079:8080/tcp (left to wslrelay.exe) + PublishedPort { proto: "tcp".into(), host_ip: "127.0.0.1".into(), host_port: 18079 }, + PublishedPort { proto: "tcp".into(), host_ip: "::1".into(), host_port: 18079 }, + // -p 192.0.2.50:18080:8080/tcp (specific Windows host IP only) + PublishedPort { proto: "tcp".into(), host_ip: "192.0.2.50".into(), host_port: 18080 }, + // -p 0.0.0.0:18082:8080/tcp (expands to non-loopback Windows IPv4 interfaces) + PublishedPort { proto: "tcp".into(), host_ip: "0.0.0.0".into(), host_port: 18082 }, + PublishedPort { proto: "tcp".into(), host_ip: "::".into(), host_port: 18082 }, + ]; + let specs = plan_forwards(wsl_ip, &published, &win_v4, &win_v6); + let expected = vec![ + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "192.0.2.50:18080".parse().unwrap(), + target_addr: "198.51.100.107:18080".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "192.0.2.50:18082".parse().unwrap(), + target_addr: "198.51.100.107:18082".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "198.51.100.1:18082".parse().unwrap(), + target_addr: "198.51.100.107:18082".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Tcp, + bind_addr: "[2001:db8::42]:18082".parse().unwrap(), + target_addr: "198.51.100.107:18082".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "0.0.0.0:18120".parse().unwrap(), + target_addr: "198.51.100.107:18120".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "127.0.0.1:18121".parse().unwrap(), + target_addr: "198.51.100.107:18121".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "192.0.2.50:18122".parse().unwrap(), + target_addr: "198.51.100.107:18122".parse().unwrap(), + }, + ForwardSpec { + proto: Proto::Udp, + bind_addr: "[::]:18120".parse().unwrap(), + target_addr: "198.51.100.107:18120".parse().unwrap(), + }, + ]; + assert_eq!(specs, expected); + } + + #[test] + fn skips_self_forwarding_in_mirrored_or_bridged_wsl_mode() { + let mirrored_ip = Ipv4Addr::new(192, 0, 2, 50); + let win_v4 = vec![mirrored_ip, Ipv4Addr::new(203, 0, 113, 10)]; + let win_v6 = vec!["2001:db8::42".parse::().unwrap()]; + let published = vec![ + PublishedPort { proto: "udp".into(), host_ip: "0.0.0.0".into(), host_port: 18120 }, + PublishedPort { proto: "udp".into(), host_ip: "127.0.0.1".into(), host_port: 18121 }, + PublishedPort { proto: "tcp".into(), host_ip: "0.0.0.0".into(), host_port: 18082 }, + PublishedPort { proto: "tcp".into(), host_ip: "192.0.2.50".into(), host_port: 18080 }, + ]; + assert!(plan_forwards(mirrored_ip, &published, &win_v4, &win_v6).is_empty()); + } + + #[test] + fn detects_port_affecting_http_requests() { + assert!(is_port_affecting_request(b"POST /v1.47/containers/create HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(is_port_affecting_request(b"POST /containers/abc123/start HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"POST /containers/abc123/stop?t=10 HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"DELETE /v1.47/containers/abc123?force=1 HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"POST /kiri/containers/abc123/ports HTTP/1.1\r\n")); + assert!(is_port_affecting_request(b"POST /kiri/stop HTTP/1.1\r\n")); + assert!(!is_port_affecting_request(b"GET /containers/json?all=1 HTTP/1.1\r\n")); + assert!(!is_port_affecting_request(b"GET /_ping HTTP/1.1\r\n")); + assert!(!is_port_affecting_request(b"POST /kiri/win-ports HTTP/1.1\r\n")); + } + + #[test] + fn udp_forwarder_relays_datagrams_and_replies_per_client_session() { + // Stand-in for the container's UDP echo service reachable on WSL's eth0 IP. + let backend = UdpSocket::bind("127.0.0.1:0").unwrap(); + backend.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let backend_addr = backend.local_addr().unwrap(); + let echo_thread = std::thread::spawn(move || { + let mut buf = [0u8; 1024]; + let mut seen_peers = Vec::new(); + for _ in 0..2 { + let (n, peer) = backend.recv_from(&mut buf).unwrap(); + seen_peers.push(peer); + let mut reply = b"echo:".to_vec(); + reply.extend_from_slice(&buf[..n]); + backend.send_to(&reply, peer).unwrap(); + } + seen_peers + }); + + let fwd = UdpForwarder::start("127.0.0.1:0".parse().unwrap(), backend_addr).unwrap(); + let fwd_addr = fwd.local_addr(); + + let client1 = UdpSocket::bind("127.0.0.1:0").unwrap(); + client1.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let client2 = UdpSocket::bind("127.0.0.1:0").unwrap(); + client2.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + + client1.send_to(b"one", fwd_addr).unwrap(); + client2.send_to(b"two", fwd_addr).unwrap(); + + let mut r1 = [0u8; 64]; + let (n1, from1) = client1.recv_from(&mut r1).unwrap(); + assert_eq!(&r1[..n1], b"echo:one"); + assert_eq!(from1, fwd_addr); + + let mut r2 = [0u8; 64]; + let (n2, from2) = client2.recv_from(&mut r2).unwrap(); + assert_eq!(&r2[..n2], b"echo:two"); + assert_eq!(from2, fwd_addr); + + // Two distinct clients get distinct backend session sockets. + let peers = echo_thread.join().unwrap(); + assert_ne!(peers[0], peers[1]); + fwd.stop(); + } + + #[test] + fn tcp_forwarder_relays_streams_and_releases_port_on_stop() { + let backend = TcpListener::bind("127.0.0.1:0").unwrap(); + let backend_addr = backend.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (mut s, _) = backend.accept().unwrap(); + let mut req = Vec::new(); + s.read_to_end(&mut req).unwrap(); + s.write_all(b"reply:").unwrap(); + s.write_all(&req).unwrap(); + let _ = s.shutdown(Shutdown::Write); + }); + + let fwd = TcpForwarder::start("127.0.0.1:0".parse().unwrap(), backend_addr).unwrap(); + let fwd_addr = fwd.local_addr(); + + let mut client = TcpStream::connect(fwd_addr).unwrap(); + client.write_all(b"hello-win-tcp").unwrap(); + client.shutdown(Shutdown::Write).unwrap(); + let mut resp = Vec::new(); + client.read_to_end(&mut resp).unwrap(); + assert_eq!(resp, b"reply:hello-win-tcp"); + + server.join().unwrap(); + fwd.stop(); + // Port is immediately free to bind again after stop(). + let rebound = TcpListener::bind(fwd_addr); + assert!(rebound.is_ok(), "port should be released after TcpForwarder::stop()"); + } + + #[test] + fn udp_forwarder_releases_bound_port_on_stop_and_plans_uppercase_protos() { + for explicit_stop in [true, false] { + let backend = UdpSocket::bind("127.0.0.1:0").unwrap(); + backend.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + let backend_addr = backend.local_addr().unwrap(); + let spoofer = UdpSocket::bind("127.0.0.1:0").unwrap(); + let echo = std::thread::spawn(move || { + let mut buf = [0u8; 64]; + let (n, peer) = backend.recv_from(&mut buf).unwrap(); + spoofer.send_to(b"spoofed", peer).unwrap(); + backend.send_to(&buf[..n], peer).unwrap(); + }); + + // Pick a port outside the OS ephemeral range (49152..65535) so a concurrent + // `:0` bind in another parallel test thread never steals `fwd_addr` right + // after `fwd.stop()` releases it. + let fwd = (38100..38900) + .find_map(|port| UdpForwarder::start(SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)), backend_addr).ok()) + .expect("free loopback UDP port in 38100..38900"); + let fwd_addr = fwd.local_addr(); + let client = UdpSocket::bind("127.0.0.1:0").unwrap(); + client.set_read_timeout(Some(Duration::from_secs(5))).unwrap(); + client.send_to(b"ping", fwd_addr).unwrap(); + let mut rbuf = [0u8; 64]; + let (n, from) = client.recv_from(&mut rbuf).unwrap(); + assert_eq!(&rbuf[..n], b"ping"); + assert_eq!(from, fwd_addr); + echo.join().unwrap(); + + if explicit_stop { + fwd.stop(); + } else { + drop(fwd); + } + // Allow brief retries in case a concurrent test's `Command::spawn` on Unix + // is mid-fork/exec when the socket fd closes. + let mut rebound = UdpSocket::bind(fwd_addr); + for _ in 0..50 { + if rebound.is_ok() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + rebound = UdpSocket::bind(fwd_addr); + } + assert!(rebound.is_ok(), "port should be released after UdpForwarder shutdown: {:?}", rebound.err()); + } + + let upper = vec![ + PublishedPort { proto: "UDP".into(), host_ip: "127.0.0.1".into(), host_port: 19123 }, + PublishedPort { proto: "TCP".into(), host_ip: "192.0.2.50".into(), host_port: 19124 }, + ]; + let specs = plan_forwards(Ipv4Addr::new(198, 51, 100, 107), &upper, &[Ipv4Addr::new(192, 0, 2, 50)], &[]); + assert_eq!(specs.len(), 2); + } +} diff --git a/crates/kiri-win/src/refuse.rs b/crates/kiri-win/src/refuse.rs index 82d45e87f..7a1df3030 100644 --- a/crates/kiri-win/src/refuse.rs +++ b/crates/kiri-win/src/refuse.rs @@ -2,12 +2,146 @@ //! WSL (crates/kiri/src/bridge.rs closes the connection with why), rather //! than a pipe that simply breaks. Plain functions, tested on any host. +use std::path::Path; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Condvar, Mutex, PoisonError}; use std::time::Duration; /// How long a client's request may take to come before it is answered anyway. pub const REQUEST_WAIT: Duration = Duration::from_secs(2); +/// What a docker client is told while Kiri is stopped (explicit Stop in the +/// window or tray): matches `crates/kiri/src/daemon/engine.rs::STOPPED`. +pub const STOPPED: &str = "Kiri is stopped: run `kiri start`, or press Start in the Kiri window, to run containers again"; + +/// Strips an optional Docker API version prefix (`/v1.47`) from `path`, +/// matching `crates/kiri/src/daemon/http.rs::strip_version`. +fn strip_version(path: &str) -> &str { + if let Some(rest) = path.strip_prefix("/v") + && let Some(i) = rest.find('/') + && !rest[..i].is_empty() + && rest[..i].bytes().any(|b| b.is_ascii_digit()) + && rest[..i].bytes().all(|b| b.is_ascii_digit() || b == b'.') + { + return &rest[i..]; + } + path +} + +fn matches_post_endpoint(request: &[u8], endpoint: &str) -> bool { + let line_end = request.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(request.len().min(1024)); + let Ok(line) = std::str::from_utf8(&request[..line_end]) else { + return false; + }; + let mut parts = line.split_whitespace(); + let Some("POST") = parts.next() else { + return false; + }; + let Some(target) = parts.next() else { + return false; + }; + if let Some(version) = parts.next() + && (!version.eq_ignore_ascii_case("HTTP/1.1") && !version.eq_ignore_ascii_case("HTTP/1.0") || parts.next().is_some()) + { + return false; + } + let path = target.split('?').next().unwrap_or(target); + strip_version(path) == endpoint +} + +/// Whether the first HTTP request line in `request` is `POST /kiri/wake` +/// (or versioned `POST /v*/kiri/wake`). +pub fn is_wake_request(request: &[u8]) -> bool { + matches_post_endpoint(request, "/kiri/wake") +} + +/// Whether the first HTTP request line in `request` is `POST /kiri/stop` +/// (or versioned `POST /v*/kiri/stop`). +pub fn is_stop_request(request: &[u8]) -> bool { + matches_post_endpoint(request, "/kiri/stop") +} + +/// Returns `Some(d)` only when `distro` is Kiri's dedicated bundled distro +/// (`kiri_distro`, i.e. `"kiri"`). Never returns a shared user distro such as +/// Ubuntu so explicit Stop / Stop-on-quit never kills unrelated WSL shells. +pub fn terminate_target<'a>(distro: Option<&'a str>, kiri_distro: &str) -> Option<&'a str> { + distro.filter(|&d| d == kiri_distro) +} + +/// Action the Windows pipe server should take for an incoming connection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GateDecision { + /// Engine is not stopped: forward normally. + Forward, + /// Engine was stopped and the request is `POST /kiri/wake` (or `/v*/kiri/wake`): + /// gate and marker are now cleared; forward the already-read request bytes. + Wake, + /// Engine is already stopped and the request is `POST /kiri/stop`: reply + /// HTTP 204 No Content immediately without spawning `wsl.exe`. + AlreadyStopped, + /// Engine is stopped and the request is not a wake: reply HTTP 503 with + /// [`STOPPED`] without spawning `wsl.exe`. + Refuse, +} + +/// Windows-side stopped gate (`AtomicBool`) mirrored on disk at +/// `%LOCALAPPDATA%\Kiri\stopped` so `kiri-win.exe` keeps WSL off after an +/// explicit Stop and across restarts until Start or `kiri start`. +pub struct StoppedGate { + stopped: AtomicBool, +} + +impl StoppedGate { + pub const fn new() -> Self { + Self { stopped: AtomicBool::new(false) } + } + + pub fn is_stopped(&self) -> bool { + self.stopped.load(Ordering::SeqCst) + } + + /// Initializes the stopped flag from `marker`'s existence on disk. + pub fn init_from(&self, marker: Option<&Path>) -> bool { + let stopped = marker.is_some_and(Path::is_file); + self.stopped.store(stopped, Ordering::SeqCst); + stopped + } + + /// Updates both the in-memory flag and the on-disk `marker` file. + pub fn set(&self, stopped: bool, marker: Option<&Path>) { + if stopped { + self.stopped.store(true, Ordering::SeqCst); + if let Some(p) = marker { + if let Some(dir) = p.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(p, b""); + } + } else { + if let Some(p) = marker { + let _ = std::fs::remove_file(p); + } + self.stopped.store(false, Ordering::SeqCst); + } + } + + /// Decides what to do with `first_request` when the pipe server saw + /// `is_stopped()`. Clears the gate and marker on `POST /kiri/wake`. + pub fn inspect_request(&self, first_request: &[u8], marker: Option<&Path>) -> GateDecision { + if !self.is_stopped() { + return GateDecision::Forward; + } + if is_wake_request(first_request) { + self.set(false, marker); + GateDecision::Wake + } else if is_stop_request(first_request) { + GateDecision::AlreadyStopped + } else { + GateDecision::Refuse + } + } +} + /// What a client the engine cannot serve is told: why the bridge could not /// reach it, and what to do. A CLOSE with no reason says only what /// happened: this bridge sends one when the daemon itself closed the @@ -15,6 +149,9 @@ pub const REQUEST_WAIT: Duration = Duration::from_secs(2); /// before reasons sends it for an engine it could not reach too. pub fn message(why: Option<&str>) -> String { match why { + Some(why) if why.contains("emergency_ro") || why.contains("mounted read-only") || why.contains("remounted read-only") => { + format!("Kiri's engine did not start: {why}") + } Some(why) => format!("Kiri's engine did not start: {why}. Run `kiri start`, or open Kiri and press Start"), None => "Kiri's engine closed the connection without answering".to_owned(), } @@ -114,6 +251,10 @@ mod tests { #[test] fn a_close_with_no_reason_says_only_what_happened() { assert_eq!(message(None), "Kiri's engine closed the connection without answering"); + let ro = "Kiri's WSL2 disk (ext4.vhdx) was remounted read-only by Linux (emergency_ro) after an unclean shutdown or filesystem error."; + let got = message(Some(ro)); + assert_eq!(got, format!("Kiri's engine did not start: {ro}")); + assert!(!got.contains("press Start"), "{got}"); } /// The refusal waits for the request, and no longer than it is given. @@ -135,4 +276,125 @@ mod tests { assert!(!none.head(Duration::from_millis(100))); assert!(began.elapsed() >= Duration::from_millis(100)); } + + #[test] + fn stopped_gate_persists_and_initializes_from_marker() { + let dir = std::env::temp_dir().join(format!("kiri-win-stopped-gate-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let marker = dir.join("Kiri").join("stopped"); + + let gate = StoppedGate::new(); + assert!(!gate.init_from(Some(&marker))); + assert!(!gate.is_stopped()); + + gate.set(true, Some(&marker)); + assert!(gate.is_stopped()); + assert!(marker.is_file()); + + // A fresh process sees the marker at startup without touching WSL. + let restarted = StoppedGate::new(); + assert!(restarted.init_from(Some(&marker))); + assert!(restarted.is_stopped()); + + restarted.set(false, Some(&marker)); + assert!(!restarted.is_stopped()); + assert!(!marker.exists()); + + let after_start = StoppedGate::new(); + assert!(!after_start.init_from(Some(&marker))); + + // POST /kiri/stop while already stopped returns AlreadyStopped and keeps the marker. + gate.set(true, Some(&marker)); + assert_eq!(gate.inspect_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::AlreadyStopped); + assert!(gate.is_stopped()); + assert!(marker.is_file()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn stopped_gate_allows_wake_and_refuses_other_requests_with_503() { + let dir = std::env::temp_dir().join(format!("kiri-win-wake-gate-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let marker = dir.join("Kiri").join("stopped"); + + // Request matcher coverage. + assert!(is_wake_request(b"POST /kiri/wake HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(is_wake_request(b"POST /kiri/wake HTTP/1.0\r\n\r\n")); + assert!(is_wake_request(b"POST /kiri/wake?from=cli HTTP/1.1\r\n\r\n")); + assert!(is_wake_request(b"POST /v1.47/kiri/wake HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(is_wake_request(b"POST /v1.24/kiri/wake?x=1 HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"GET /kiri/wake HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"HEAD /_ping HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"GET /_ping HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"GET /v1.47/containers/json HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"POST /containers/create HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"POST /kiri/stop HTTP/1.1\r\n\r\n")); + assert!(is_stop_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(is_stop_request(b"POST /v1.47/kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n")); + assert!(!is_stop_request(b"GET /kiri/stop HTTP/1.1\r\n\r\n")); + assert!(!is_stop_request(b"POST /kiri/wake HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"POST /kiri/wake/extra HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"POST /v/kiri/wake HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"POST /v./kiri/wake HTTP/1.1\r\n\r\n")); + assert!(!is_wake_request(b"")); + + let gate = StoppedGate::new(); + // When running, everything forwards without refusal. + assert_eq!(gate.inspect_request(b"GET /_ping HTTP/1.1\r\n\r\n", Some(&marker)), GateDecision::Forward); + + // Once stopped, ordinary Docker requests are refused with 503 STOPPED + // and leave the gate + marker intact. + gate.set(true, Some(&marker)); + for req in [ + b"GET /_ping HTTP/1.1\r\nHost: kiri\r\n\r\n".as_slice(), + b"HEAD /_ping HTTP/1.1\r\nHost: kiri\r\n\r\n".as_slice(), + b"GET /v1.47/containers/json HTTP/1.1\r\n\r\n".as_slice(), + b"POST /containers/create HTTP/1.1\r\n\r\n".as_slice(), + b"GET /kiri/wake HTTP/1.1\r\n\r\n".as_slice(), + b"".as_slice(), + ] { + assert_eq!(gate.inspect_request(req, Some(&marker)), GateDecision::Refuse); + assert!(gate.is_stopped()); + assert!(marker.is_file()); + let (head, body) = split(&refusal(is_head(req), STOPPED)); + assert!(head.starts_with("HTTP/1.1 503 Service Unavailable\r\n"), "{head}"); + if is_head(req) { + assert!(body.is_empty()); + } else { + assert_eq!(serde_json::from_str::(&body).unwrap()["message"], STOPPED); + } + } + + // POST /kiri/wake clears the gate and removes the marker. + assert_eq!(gate.inspect_request(b"POST /kiri/wake HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::Wake); + assert!(!gate.is_stopped()); + assert!(!marker.exists()); + + // Versioned POST /v1.47/kiri/wake also wakes and clears the marker. + gate.set(true, Some(&marker)); + assert_eq!(gate.inspect_request(b"POST /v1.47/kiri/wake HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::Wake); + assert!(!gate.is_stopped()); + assert!(!marker.exists()); + + // POST /kiri/stop while already stopped returns AlreadyStopped and keeps the marker. + gate.set(true, Some(&marker)); + assert_eq!(gate.inspect_request(b"POST /kiri/stop HTTP/1.1\r\nHost: kiri\r\n\r\n", Some(&marker)), GateDecision::AlreadyStopped); + assert!(gate.is_stopped()); + assert!(marker.is_file()); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn terminate_target_only_allows_kiri_distro() { + assert_eq!(terminate_target(Some("kiri"), "kiri"), Some("kiri")); + assert_eq!(terminate_target(Some("Ubuntu"), "kiri"), None); + assert_eq!(terminate_target(Some("Ubuntu-26.04"), "kiri"), None); + assert_eq!(terminate_target(Some("Debian"), "kiri"), None); + assert_eq!(terminate_target(Some("kiri-linux"), "kiri"), None); + assert_eq!(terminate_target(Some("Kiri"), "kiri"), None); + assert_eq!(terminate_target(Some(""), "kiri"), None); + assert_eq!(terminate_target(None, "kiri"), None); + } } diff --git a/crates/kiri-win/src/relay.rs b/crates/kiri-win/src/relay.rs index 5c0deeefe..2c146c43b 100644 --- a/crates/kiri-win/src/relay.rs +++ b/crates/kiri-win/src/relay.rs @@ -1,21 +1,56 @@ -//! Windows' end of the proxy relay (crates/kiri/src/hostrelay.rs): a proxy -//! on Windows' own 127.0.0.1, as most Windows proxy apps set, can't be -//! reached from WSL, so `kiri hostrelay` in the distro listens for it and -//! sends each connection here over wsl.exe's stdio, and this dials the proxy. +//! Windows' end of the host and proxy relay (crates/kiri/src/hostrelay.rs): +//! services and proxies on Windows' own loopback (`127.0.0.1` / `[::1]`) +//! can't be reached directly from WSL 2, so `kiri hostrelay` in the distro +//! listens for static proxy ports on `127.0.0.1` and for `host.docker.internal` +//! / `host.kiri.internal` on `192.168.65.254` (via nftables DNAT + +//! `SO_ORIGINAL_DST`), sends each connection here over wsl.exe's stdio, and +//! this dials Windows' loopback (`127.0.0.1`, then `[::1]` on refusal). use std::collections::{HashMap, HashSet}; +use std::io::{self, Write}; use std::os::windows::process::CommandExt; -use std::process::Stdio; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::process::{ChildStdin, Stdio}; +use std::sync::atomic::{AtomicBool, AtomicU16, Ordering}; use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::time::{Duration, Instant}; use crate::hostrelay::{self, Out}; +/// Minimum interval between automatic background restart attempts after the +/// relay exits or fails to start. +const RETRY_WAIT: Duration = Duration::from_secs(2); + +/// Stdin handle to `wsl.exe` that can be closed on demand (`renew`) so the +/// WSL-side `kiri hostrelay` sees EOF and tears down cleanly. +struct CloseableStdin(Option); + +impl Write for CloseableStdin { + fn write(&mut self, buf: &[u8]) -> io::Result { + match self.0.as_mut() { + Some(w) => w.write(buf), + None => Err(io::Error::new(io::ErrorKind::BrokenPipe, "relay closed")), + } + } + + fn flush(&mut self) -> io::Result<()> { + match self.0.as_mut() { + Some(w) => w.flush(), + None => Ok(()), + } + } +} + struct Relay { out: Out, + stdin: Arc>, distro: Option, - /// Windows ports it was asked to listen for: the only ones dialled. + kiri: String, + /// Dynamic host-gateway forwarding (`host.docker.internal` -> any non-zero + /// Windows loopback port). + host_enabled: AtomicBool, + /// Catch-all relay port reported by WSL (`LISTENING_HOST`), or 0. + host_port: AtomicU16, + /// Static proxy ports requested via `LISTEN`. allowed: Mutex>, /// Windows port → the distro's port; 0 when it couldn't listen. ports: Mutex>, @@ -23,7 +58,17 @@ struct Relay { dead: AtomicBool, } +impl Relay { + fn close(&self) { + self.dead.store(true, Ordering::SeqCst); + let _ = lock(&self.stdin).0.take(); + self.changed.notify_all(); + } +} + static RELAY: Mutex>> = Mutex::new(None); +/// Last automatic start attempt, to throttle retries if WSL is unavailable. +static LAST_START: Mutex> = Mutex::new(None); /// The last failure logged, so a minute's retry doesn't repeat it. static LAST_ERROR: Mutex = Mutex::new(String::new()); @@ -39,73 +84,183 @@ fn log_once(msg: String) { } } -fn start(distro: Option) -> std::io::Result> { +fn current_distro_and_kiri() -> Option<(String, String)> { + if crate::serve::is_stopped() || crate::storage::moving() || crate::storage::unavailable().is_some() { + return None; + } + // The bridge's distro, the engine's, or during setup the one setup just made. + // None before setup has made one: WSL's default distro may be anything. + let distro = crate::serve::distro().or_else(crate::engine::distro).or_else(crate::setup::distro)?; + Some((distro, crate::serve::kiri())) +} + +fn start(distro: Option, kiri: String) -> io::Result> { let mut cmd = crate::win::tool("wsl.exe"); if let Some(d) = &distro { cmd.args(["-d", d]); } let mut child = cmd - .args(["-u", "root", "--", "/usr/local/bin/kiri", "hostrelay"]) + .args(["-u", "root", "--", &kiri, "hostrelay"]) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .creation_flags(0x0800_0000) .spawn()?; - let (Some(input), Some(output)) = (child.stdin.take(), child.stdout.take()) else { return Err(std::io::Error::other("wsl.exe has no stdio")) }; + let (Some(input), Some(output)) = (child.stdin.take(), child.stdout.take()) else { + return Err(io::Error::other("wsl.exe has no stdio")); + }; + let stdin = Arc::new(Mutex::new(CloseableStdin(Some(input)))); + let out: Out = stdin.clone(); let relay = Arc::new(Relay { - out: Arc::new(Mutex::new(input)), + out, + stdin, distro, + kiri, + host_enabled: AtomicBool::new(true), + host_port: AtomicU16::new(0), allowed: Mutex::new(HashSet::new()), ports: Mutex::new(HashMap::new()), changed: Condvar::new(), dead: AtomicBool::new(false), }); + // Ask WSL immediately to bind 192.168.65.254 and install its nftables DNAT. + // An older `kiri hostrelay` ignores unknown frame kinds cleanly. + let _ = hostrelay::send(&relay.out, hostrelay::LISTEN_HOST, 0, &[]); let r = relay.clone(); std::thread::spawn(move || { - let (a, p) = (r.clone(), r.clone()); - let end = hostrelay::dial_side( + let (a, p, h) = (r.clone(), r.clone(), r.clone()); + let end = hostrelay::dial_side_with_host( output, &r.out, - move |port| lock(&a.allowed).contains(&port), + move |port| port != 0 && (a.host_enabled.load(Ordering::SeqCst) || lock(&a.allowed).contains(&port)), move |target, local| { lock(&p.ports).insert(target, local); p.changed.notify_all(); }, + move |local| { + h.host_port.store(local, Ordering::SeqCst); + h.changed.notify_all(); + if local != 0 { + log_once(format!( + "host relay: {} -> Windows loopback (WSL port {local})", + hostrelay::WSL_HOST_ADDR_STR + )); + } else { + log_once(format!( + "host relay: WSL could not bind {}", + hostrelay::WSL_HOST_ADDR_STR + )); + } + }, ); r.dead.store(true, Ordering::SeqCst); r.changed.notify_all(); - let status = child.wait(); - log_once(format!("proxy relay ended: {end:?}, {status:?}")); + let end = match end { + Ok(()) => "closed".to_owned(), + Err(e) => format!("{e}"), + }; + let status = crate::format_wait_status(child.wait()); + log_once(format!("host relay ended: {end}, {status}")); }); Ok(relay) } -/// For each Windows loopback port, the distro's port that leads to it, -/// starting the relay when it isn't running. Empty when it can't run (an -/// engine from before the relay), and the proxy is used as set. -pub fn ports(targets: &[u16]) -> HashMap { - if targets.is_empty() { - return HashMap::new(); - } - // The engine's distro, or during setup the one setup just made, as the bridge finds it. - // None before setup has made one: WSL's default distro may be anything. - let Some(distro) = crate::engine::distro().or_else(crate::setup::distro) else { return HashMap::new() }; +fn ensure_relay(distro: String, kiri: String) -> Option> { let distro = Some(distro); - let relay = { - let mut slot = lock(&RELAY); - match slot.as_ref() { - Some(r) if !r.dead.load(Ordering::SeqCst) && r.distro == distro => r.clone(), - _ => match start(distro) { + let mut slot = lock(&RELAY); + if crate::serve::is_stopped() { + return None; + } + match slot.as_ref() { + Some(r) if !r.dead.load(Ordering::SeqCst) && r.distro == distro && r.kiri == kiri => Some(r.clone()), + old => { + if let Some(old) = old { + old.close(); + } + match start(distro, kiri) { Ok(r) => { *slot = Some(r.clone()); - r + Some(r) } Err(e) => { - log_once(format!("proxy relay: {e}")); - return HashMap::new(); + log_once(format!("host relay: {e}")); + None } - }, + } } + } +} + +/// Ensures the WSL host relay is running in the background so CLI-only users +/// (serving `\\.\pipe\kiri` or `\\.\pipe\docker_engine` without opening the +/// window) get `host.docker.internal` automatically. Non-blocking and throttled +/// when a recent attempt just failed. +pub fn ensure_started() { + if crate::serve::is_stopped() { + return; + } + let Some((distro, kiri)) = current_distro_and_kiri() else { + return; + }; + { + let slot = lock(&RELAY); + if slot.as_ref().is_some_and(|r| !r.dead.load(Ordering::SeqCst) && r.distro.as_deref() == Some(distro.as_str()) && r.kiri == kiri) { + return; + } + } + { + let mut last = lock(&LAST_START); + if last.is_some_and(|t| t.elapsed() < RETRY_WAIT) { + return; + } + *last = Some(Instant::now()); + } + let _ = std::thread::Builder::new().name("kiri-hostrelay-start".into()).spawn(move || { + let _ = ensure_relay(distro, kiri); + }); +} + +/// Tears down the running host relay (`kiri hostrelay` in WSL) so no open +/// `wsl.exe` keeps `vmmemWSL` alive after an explicit Stop. +pub fn stop() { + let old = lock(&RELAY).take(); + *lock(&LAST_START) = None; + if let Some(old) = old { + old.close(); + } +} + +/// Replaces the running host relay (e.g. after setup picks a distro or an +/// engine update replaces `/usr/local/bin/kiri` in WSL). +pub fn renew() { + let old = lock(&RELAY).take(); + *lock(&LAST_START) = None; + let _ = std::thread::Builder::new().name("kiri-hostrelay-renew".into()).spawn(move || { + if let Some(old) = old { + old.close(); + } + if let Some((distro, kiri)) = current_distro_and_kiri() { + let _ = ensure_relay(distro, kiri); + } + }); +} + +/// For each Windows loopback proxy port, the distro's port that leads to it, +/// starting the relay when it isn't running. Also ensures the `host.docker.internal` +/// catch-all relay is active even when no proxy ports are configured. +pub fn ports(targets: &[u16]) -> HashMap { + if crate::serve::is_stopped() { + return HashMap::new(); + } + if targets.is_empty() { + ensure_started(); + return HashMap::new(); + } + let Some((distro, kiri)) = current_distro_and_kiri() else { + return HashMap::new(); + }; + let Some(relay) = ensure_relay(distro, kiri) else { + return HashMap::new(); }; for &t in targets { if lock(&relay.allowed).insert(t) { diff --git a/crates/kiri-win/src/serve.rs b/crates/kiri-win/src/serve.rs index 96e16dade..3adb65122 100644 --- a/crates/kiri-win/src/serve.rs +++ b/crates/kiri-win/src/serve.rs @@ -101,6 +101,46 @@ static HUB: std::sync::OnceLock> = std::sync::OnceLock::new(); /// told so, rather than having its connection simply closed. static SETUP_PENDING: AtomicBool = AtomicBool::new(false); +/// User explicitly stopped Kiri (Stop in the window or tray): mirrored at +/// `%LOCALAPPDATA%\Kiri\stopped` so `kiri-win.exe` does not respawn `wsl.exe` +/// in the background until Start or `kiri start` (`POST /kiri/wake`). +static STOPPED: crate::refuse::StoppedGate = crate::refuse::StoppedGate::new(); + +fn stopped_marker() -> Option { + std::env::var_os("LOCALAPPDATA").map(|d| std::path::PathBuf::from(d).join("Kiri").join("stopped")) +} + +/// Initializes the stopped gate from `%LOCALAPPDATA%\Kiri\stopped` at startup. +pub fn init_stopped() { + if STOPPED.init_from(stopped_marker().as_deref()) { + log("stopped marker present; keeping WSL off until Start or `kiri start`"); + } +} + +/// Whether Kiri is stopped on the Windows side and must not spawn `wsl.exe`. +pub fn is_stopped() -> bool { + STOPPED.is_stopped() +} + +/// Marks Kiri stopped or running on the Windows side, keeping +/// `%LOCALAPPDATA%\Kiri\stopped` in sync. +pub fn set_stopped(stopped: bool) { + STOPPED.set(stopped, stopped_marker().as_deref()); + if !stopped + && let Some(hub) = HUB.get() + { + *hub.silent.lock().unwrap_or_else(PoisonError::into_inner) = None; + } +} + +/// Immediately terminates any running bridge `wsl.exe` and closes its open +/// connections (such as `/events`) so nothing keeps `vmmemWSL` alive. +pub fn stop_bridge() { + if let Some(hub) = HUB.get() { + hub.stop(); + } +} + pub fn set_setup_pending(pending: bool) { SETUP_PENDING.store(pending, Ordering::SeqCst); } @@ -136,6 +176,16 @@ fn refuse_new(pipe: &Pipe, message: &str) -> bool { refuse(pipe, is_head(&buf[..n]), message) } +/// `refuse`, reusing the already-read request bytes when present so a client +/// whose request was inspected before connecting to the bridge is answered +/// immediately without waiting another `REQUEST_WAIT`. +fn refuse_client(pipe: &Pipe, prefetched: Option<&[u8]>, message: &str) -> bool { + match prefetched { + Some(head) => refuse(pipe, is_head(head), message), + None => refuse_new(pipe, message), + } +} + /// Docker's own pipe. docker-py, the Go and Java SDKs, Testcontainers and /// IDE plugins open it without reading docker contexts, so Kiri serves it /// too while no other engine does. @@ -146,6 +196,33 @@ pub const DOCKER_ENGINE: &str = r"\\.\pipe\docker_engine"; /// while any instance of Kiri's is open). const OTHER_ENGINES: &[&str] = &["Docker Desktop.exe", "com.docker.backend.exe", "dockerd.exe", "Rancher Desktop.exe"]; +static DOCKER_ENGINE_OWNER: std::sync::LazyLock>> = std::sync::LazyLock::new(|| Mutex::new(None)); + +fn set_docker_engine_owner(owner: crate::dockerctx::Endpoint) { + *DOCKER_ENGINE_OWNER.lock().unwrap_or_else(PoisonError::into_inner) = Some(owner); +} + +/// Who currently serves `\\.\pipe\docker_engine`, for `docker` CLI detection +/// (#369) and Settings → Network (#577). +pub fn docker_engine_endpoint() -> crate::dockerctx::Endpoint { + if let Some(ep) = DOCKER_ENGINE_OWNER.lock().unwrap_or_else(PoisonError::into_inner).clone() { + return ep; + } + other_engine().map(|o| crate::dockerctx::Endpoint::Taken(o.to_owned())).unwrap_or(crate::dockerctx::Endpoint::Free) +} + +/// The WSL distro the pipe bridge targets, once `serve::start` has run. +pub fn distro() -> Option { + HUB.get().and_then(|hub| hub.cfg.lock().unwrap_or_else(PoisonError::into_inner).distro.clone()) +} + +/// The `kiri` binary path inside WSL configured for the pipe bridge. +pub fn kiri() -> String { + HUB.get() + .map(|hub| hub.cfg.lock().unwrap_or_else(PoisonError::into_inner).kiri.clone()) + .unwrap_or_else(|| "/usr/local/bin/kiri".to_owned()) +} + /// Carries connections to `distro` from now on (setup has just made it); /// the bridge to the old one is left to end. pub fn set_distro(distro: &str) { @@ -153,6 +230,7 @@ pub fn set_distro(distro: &str) { hub.cfg.lock().unwrap_or_else(PoisonError::into_inner).distro = Some(distro.to_owned()); hub.retire(); } + crate::relay::renew(); } /// The engine in WSL was replaced by this version's: connections from now @@ -165,6 +243,7 @@ pub fn renew_bridge() { { log("bridge: the engine in WSL was replaced; new connections get a bridge from the new one"); } + crate::relay::renew(); } /// Serves the pipe on threads of its own. Fails if another kiri-win @@ -177,15 +256,20 @@ pub fn start(cfg: Config) -> io::Result<()> { let _ = HUB.set(hub.clone()); let h = hub.clone(); thread::Builder::new().name("kiri-docker-engine".into()).spawn(move || docker_engine(&h))?; - // Start WSL now, so the first docker command does not wait for it. - let h = hub.clone(); - thread::spawn(move || { - if let Err(e) = h.bridge() { - if e.kind() != io::ErrorKind::NotConnected { - log(&format!("bridge: {e}")); + // Start WSL and the Windows host relay now, so the first docker command + // gets both the daemon and host.docker.internal without waiting for the UI. + // When stopped, keep WSL untouched until Start or `kiri start`. + if !is_stopped() { + crate::relay::ensure_started(); + let h = hub.clone(); + thread::spawn(move || { + if let Err(e) = h.bridge() { + if e.kind() != io::ErrorKind::NotConnected { + log(&format!("bridge: {e}")); + } } - } - }); + }); + } thread::Builder::new().name("kiri-pipe".into()).spawn(move || { let mut pipe = first; loop { @@ -227,6 +311,7 @@ fn docker_engine(hub: &Arc) { }; loop { if let Some(other) = other_engine() { + set_docker_engine_owner(crate::dockerctx::Endpoint::Taken(other.to_owned())); say(format!("{DOCKER_ENGINE} left to {other}")); thread::sleep(std::time::Duration::from_secs(5)); continue; @@ -234,14 +319,30 @@ fn docker_engine(hub: &Arc) { let first = match Pipe::create(DOCKER_ENGINE, true) { Ok(p) => p, Err(e) => { + set_docker_engine_owner(crate::dockerctx::Endpoint::Taken(other_engine().unwrap_or("").to_owned())); say(format!("{DOCKER_ENGINE} left to whatever serves it: {e}")); thread::sleep(std::time::Duration::from_secs(5)); continue; } }; + set_docker_engine_owner(crate::dockerctx::Endpoint::Kiri); say(format!("serving {DOCKER_ENGINE} as well (no other engine has it)")); + if !is_stopped() { + crate::relay::ensure_started(); + } let (h, mut new) = (hub.clone(), NewEngines::default()); - serve_while_free(DOCKER_ENGINE, first, move || new.find(), move |p| serve_shared(&h, p)); + serve_while_free( + DOCKER_ENGINE, + first, + move || { + let found = new.find(); + if let Some(other) = found { + set_docker_engine_owner(crate::dockerctx::Endpoint::Taken(other.to_owned())); + } + found + }, + move |p| serve_shared(&h, p), + ); } } @@ -1354,16 +1455,35 @@ impl Hub { true } + /// Takes the running bridge out of use and ends its `wsl.exe` immediately, + /// closing any open connections (such as `/events`) so nothing keeps WSL alive. + fn stop(&self) -> bool { + let Some(b) = self.current.lock().unwrap_or_else(PoisonError::into_inner).take() else { return false }; + b.retired.store(true, Ordering::SeqCst); + b.kill("Kiri stopped"); + true + } + fn bridge(&self) -> io::Result> { let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner); if let Some(b) = current.as_ref().filter(|b| !b.dead.load(Ordering::SeqCst)) { return Ok(b.clone()); } + if is_stopped() { + return Err(io::Error::new(io::ErrorKind::NotConnected, crate::refuse::STOPPED)); + } let cfg = self.cfg.lock().unwrap_or_else(PoisonError::into_inner).clone(); // Until setup has made Kiri's Linux there is nothing to bridge to. if cfg.distro.is_none() { return Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri is not set up yet")); } + // Never boot WSL while storage is moving or its custom drive is offline. + if crate::storage::moving() { + return Err(io::Error::new(io::ErrorKind::NotConnected, "Kiri is moving its data")); + } + if let Some(missing) = crate::storage::unavailable() { + return Err(io::Error::new(io::ErrorKind::NotConnected, crate::storage::unavailable_message(&missing))); + } // The last one has gone (WSL restarted, Windows slept): a docker // client is waiting, so a new one starts now, and the log says why; // once, not again for each try while new ones die as they start. @@ -1398,10 +1518,7 @@ impl Process for Wsl { } fn exited(&mut self) -> Option { - match self.0.try_wait() { - Ok(None) => None, - status => Some(format!("{status:?}")), - } + crate::format_try_wait(self.0.try_wait()) } } @@ -1455,6 +1572,7 @@ impl Bridge { .spawn()?; let (Some(input), Some(output)) = (child.stdin.take(), child.stdout.take()) else { return Err(io::Error::other("wsl.exe has no stdio")) }; log("bridge started"); + crate::relay::ensure_started(); Ok(Bridge::over(Box::new(input), output, Box::new(Wsl(child)))) } @@ -1670,6 +1788,59 @@ fn serve(hub: &Hub, pipe: Pipe) { fn serve_shared(hub: &Hub, pipe: Arc) { let flush = FlushOnDrop(pipe); let pipe = &flush.0; + if crate::storage::moving() { + if refuse_new(pipe, "Kiri is moving its data to another folder: try again when Settings → Storage says it's done") { + linger(pipe); + } + return; + } + if let Some(missing) = crate::storage::unavailable() { + if refuse_new(pipe, &crate::storage::unavailable_message(&missing)) { + linger(pipe); + } + return; + } + let mut prefetched: Option> = None; + let mut woke = false; + if is_stopped() { + let mut first = vec![0u8; 64 * 1024]; + let n = pipe.read_within(&mut first, Some(REQUEST_WAIT)).unwrap_or(0); + if pipe.is_aborted() { + return; + } + first.truncate(n); + match STOPPED.inspect_request(&first, stopped_marker().as_deref()) { + crate::refuse::GateDecision::Wake => { + log("pipe: POST /kiri/wake received while stopped; waking Kiri"); + *hub.silent.lock().unwrap_or_else(PoisonError::into_inner) = None; + prefetched = Some(first); + woke = true; + } + crate::refuse::GateDecision::AlreadyStopped => { + if pipe.write(b"HTTP/1.1 204 No Content\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").is_ok() { + pipe.flush(); + if !pipe.is_aborted() && pipe.write(&[]).is_ok() { + linger(pipe); + } + } + return; + } + crate::refuse::GateDecision::Refuse => { + if refuse(pipe, is_head(&first), crate::refuse::STOPPED) { + linger(pipe); + } + return; + } + crate::refuse::GateDecision::Forward => { + if !first.is_empty() { + prefetched = Some(first); + } + } + } + } + if HUB.get().is_some() { + crate::relay::ensure_started(); + } // A bridge can die between hub.bridge() and the insert below: while WSL // is still booting, wsl.exe exits at once. `replies` ends every // connection it finds when that happens, but one registered after that @@ -1692,14 +1863,26 @@ fn serve_shared(hub: &Hub, pipe: Arc) { if pipe.is_aborted() { return; } + if is_stopped() { + if refuse_client(pipe, prefetched.as_deref(), crate::refuse::STOPPED) { + linger(pipe); + } + return; + } let bridge = match hub.bridge() { Ok(b) => b, Err(e) => { let answered = if e.kind() == io::ErrorKind::NotConnected { - setup_pending() && refuse_new(pipe, SETUP_UNFINISHED) + if setup_pending() { + refuse_client(pipe, prefetched.as_deref(), SETUP_UNFINISHED) + } else if is_stopped() { + refuse_client(pipe, prefetched.as_deref(), crate::refuse::STOPPED) + } else { + false + } } else { log(&format!("bridge: {e}")); - refuse_new(pipe, &message(Some(&format!("WSL did not start Kiri's Linux ({e})")))) + refuse_client(pipe, prefetched.as_deref(), &message(Some(&format!("WSL did not start Kiri's Linux ({e})")))) }; if answered { linger(pipe); @@ -1722,7 +1905,7 @@ fn serve_shared(hub: &Hub, pipe: Arc) { bridge.kill("it was started while WSL was not answering, and has said nothing"); continue; } - if refuse_new(pipe, &message(Some(&why))) { + if refuse_client(pipe, prefetched.as_deref(), &message(Some(&why))) { linger(pipe); } return; @@ -1748,7 +1931,7 @@ fn serve_shared(hub: &Hub, pipe: Arc) { } *told = Some((Instant::now(), why.clone())); drop(told); - if refuse_new(pipe, &message(Some(&why))) { + if refuse_client(pipe, prefetched.as_deref(), &message(Some(&why))) { linger(pipe); } return; @@ -1778,9 +1961,15 @@ fn serve_shared(hub: &Hub, pipe: Arc) { break (bridge, id, window, rx, queued); } bridge.conns.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); + if is_stopped() { + if refuse_client(pipe, prefetched.as_deref(), crate::refuse::STOPPED) { + linger(pipe); + } + return; + } if gave_up(dying_since.elapsed()) { log(&format!("bridge: kept stopping as soon as it started, for {} s; told the docker client", BRIDGE_WAIT.as_secs())); - if refuse_new(pipe, &message(Some("Kiri's Linux in WSL kept stopping as the command came in"))) { + if refuse_client(pipe, prefetched.as_deref(), &message(Some("Kiri's Linux in WSL kept stopping as the command came in"))) { linger(pipe); } return; @@ -1796,25 +1985,42 @@ fn serve_shared(hub: &Hub, pipe: Arc) { // Whether the client's request has come, and is a HEAD: a refusal // waits for it (see `refuse_new`). let request = Arc::new(Arrival::default()); - let (p, b, w, r) = (pipe.clone(), bridge.clone(), window.clone(), request.clone()); - let writer = thread::spawn(move || to_client(&p, &rx, &queued, &b, w.as_deref().map(|w| (id, w)), &r)); + let port_op = Arc::new(AtomicBool::new(false)); + let (p, b, w, r, po) = (pipe.clone(), bridge.clone(), window.clone(), request.clone(), port_op.clone()); + let writer = thread::spawn(move || to_client(&p, &rx, &queued, &b, w.as_deref().map(|w| (id, w)), &r, &po)); let mut buf = vec![0u8; 64 * 1024]; + let mut first_chunk = true; + let mut stopped_req = false; let end = loop { - match pipe.read(&mut buf) { - Ok(0) => break EOF, - Ok(n) => { - request.set(is_head(&buf[..n])); - // Out of credit with the client gone (nothing to read its - // reply), or the connection closed: stop. - if window.as_ref().is_some_and(|w| !w.take(n, || pipe.alive())) { - break CLOSE; - } - if bridge.send(DATA, id, &buf[..n]).is_err() { - break CLOSE; - } + let from_prefetch = prefetched.take(); + let chunk: &[u8] = match from_prefetch.as_deref() { + Some(data) => data, + None => match pipe.read(&mut buf) { + Ok(0) => break EOF, + Ok(n) => &buf[..n], + // The client closed the pipe. + Err(_) => break CLOSE, + }, + }; + let n = chunk.len(); + if first_chunk { + first_chunk = false; + if crate::refuse::is_stop_request(chunk) { + stopped_req = true; + } + if crate::ports::is_port_affecting_request(chunk) { + port_op.store(true, Ordering::SeqCst); + crate::ports::before_container_op(); } - // The client closed the pipe. - Err(_) => break CLOSE, + } + request.set(is_head(chunk)); + // Out of credit with the client gone (nothing to read its + // reply), or the connection closed: stop. + if window.as_ref().is_some_and(|w| !w.take(n, || pipe.alive())) { + break CLOSE; + } + if bridge.send(DATA, id, chunk).is_err() { + break CLOSE; } }; // Gone before a word: nothing for a refusal to wait for. @@ -1837,6 +2043,14 @@ fn serve_shared(hub: &Hub, pipe: Arc) { }); } let replies_ended = writer.join().unwrap_or(false); + if woke && HUB.get().is_some() { + crate::engine::on_external_wake(); + } else if stopped_req && HUB.get().is_some() { + crate::engine::on_external_stop(); + } + if port_op.load(Ordering::Relaxed) { + crate::ports::notify(); + } let aborted = pipe.is_aborted(); if end == EOF && replies_ended && !aborted { linger(pipe); @@ -1876,7 +2090,7 @@ fn gave_up(waited: Duration) -> bool { /// bridge (`credit`) as they go when it does flow control. True if they /// ended with EOF, or the client was told why the engine could not serve /// it (once its `request` had come). -fn to_client(pipe: &Pipe, rx: &Receiver, queued: &AtomicUsize, bridge: &Bridge, credit: Option<(u32, &Window)>, request: &Arrival) -> bool { +fn to_client(pipe: &Pipe, rx: &Receiver, queued: &AtomicUsize, bridge: &Bridge, credit: Option<(u32, &Window)>, request: &Arrival, port_op: &AtomicBool) -> bool { let mut done = 0usize; let mut answered = false; loop { @@ -1913,6 +2127,9 @@ fn to_client(pipe: &Pipe, rx: &Receiver, queued: &AtomicUsize, bridge: &B // that is EOF reads as one only with no data queued ahead of // it; behind data it is merged away and the client waits on. Reply::Eof => { + if port_op.load(Ordering::Relaxed) { + crate::ports::after_container_op(); + } pipe.flush(); return !pipe.is_aborted() && pipe.write(&[]).is_ok(); } diff --git a/crates/kiri-win/src/setup.html b/crates/kiri-win/src/setup.html index 8a9eb7498..55d5884e6 100644 --- a/crates/kiri-win/src/setup.html +++ b/crates/kiri-win/src/setup.html @@ -27,10 +27,11 @@ [lang|=ja]{--f-text:"Segoe UI Variable Text","Segoe UI","Yu Gothic UI","Meiryo UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Yu Gothic UI","Meiryo UI",sans-serif} [lang|=ko]{--f-text:"Segoe UI Variable Text","Segoe UI","Malgun Gothic",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Malgun Gothic",sans-serif} [lang|=ko]{word-break:keep-all} -/* India's scripts in Nirmala UI, Windows' face for them; Thai and Lao in Leelawadee UI; Ethiopic in Ebrima. */ +/* India's scripts in Nirmala UI, Windows' face for them; Thai and Lao in Leelawadee UI; Ethiopic in Ebrima; Armenian in Sylfaen. */ +[lang|=hy]{--f-text:"Segoe UI Variable Text","Segoe UI","Noto Sans Armenian","Mshtakan","Sylfaen",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Noto Sans Armenian","Mshtakan","Sylfaen",sans-serif} [lang|=am]{--f-text:"Segoe UI Variable Text","Segoe UI","Ebrima","Nyala",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Ebrima","Nyala",sans-serif} [lang|=th],[lang|=lo]{--f-text:"Segoe UI Variable Text","Segoe UI","Leelawadee UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Leelawadee UI",sans-serif} -[lang|=hi],[lang|=bn],[lang|=ta],[lang|=te]{--f-text:"Segoe UI Variable Text","Segoe UI","Nirmala UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Nirmala UI",sans-serif} +[lang|=hi],[lang|=ne],[lang|=bn],[lang|=ta],[lang|=te]{--f-text:"Segoe UI Variable Text","Segoe UI","Nirmala UI",sans-serif;--f-display:"Segoe UI Variable Display","Segoe UI","Nirmala UI",sans-serif} *{box-sizing:border-box} html,body{margin:0;height:100%;background:var(--bg)} body{color:var(--ink);font:15px/1.4 var(--f-text);overflow:hidden;-webkit-font-smoothing:antialiased} @@ -865,8 +866,8 @@ tasks: [T('Download Ubuntu', 'active', '156 / 418 MB'), T('Unpack it into WSL', 'todo', '≈ 1.6 GB*'), T('Start Ubuntu', 'todo', 'next')] }, engine: { step: 'engine', linux: 'kiri', tasks: [T('Start the engine', 'done', 'ready in 33 ms'), T('Connect Windows to it', 'done', '\\\\.\\pipe\\kiri'), T('Run a test container', 'active', 'pulling alpine')], log: ['kiri daemon: ready in 33 ms', '$ docker run --rm alpine echo hello', 'latest: Pulling from library/alpine'] }, - tools: { step: 'tools', linux: 'kiri', tasks: [T('docker', 'done', '29.9.2 · checked'), T('Compose', 'done', 'v5.6.1 · checked'), T('buildx', 'done', 'v0.38.1 · checked'), T('docker build on Kiri', 'active', 'builder kiri-build')] }, - 'tools-other': { step: 'tools', linux: 'kiri', otherDocker: true, otherEngine: 'Docker Desktop', makeDefault: false, buildKiri: false, tasks: [T('docker', 'done', '29.9.2 · checked'), T('Compose', 'active', 'v5.6.1'), T('buildx', 'todo', 'v0.38.1'), T('docker build on Kiri', 'todo', 'builder kiri-build')] }, + tools: { step: 'tools', linux: 'kiri', tasks: [T('docker', 'done', '29.9.2 · checked'), T('Compose', 'done', 'v5.8.0 · checked'), T('buildx', 'done', 'v0.38.1 · checked'), T('docker build on Kiri', 'active', 'builder kiri-build')] }, + 'tools-other': { step: 'tools', linux: 'kiri', otherDocker: true, otherEngine: 'Docker Desktop', makeDefault: false, buildKiri: false, tasks: [T('docker', 'done', '29.9.2 · checked'), T('Compose', 'active', 'v5.8.0'), T('buildx', 'todo', 'v0.38.1'), T('docker build on Kiri', 'todo', 'builder kiri-build')] }, ready: { step: 'ready', linux: 'kiri' }, error: Object.assign({}, wsl, { progress: Object.assign({}, wsl.progress, { rate: 0, eta: null }), tasks: [wsl.tasks[0], T('Download WSL', 'error', 'stopped at 224 MB'), wsl.tasks[2], wsl.tasks[3]], error: 'The download from Microsoft stopped: this PC seems to be offline. Check the connection and try again.' }) diff --git a/crates/kiri-win/src/setup.rs b/crates/kiri-win/src/setup.rs index a5c42d6d5..84bed560a 100644 --- a/crates/kiri-win/src/setup.rs +++ b/crates/kiri-win/src/setup.rs @@ -121,7 +121,7 @@ static STATE: Mutex> = Mutex::new(None); static BUSY: AtomicBool = AtomicBool::new(false); static CANCEL: AtomicBool = AtomicBool::new(false); -fn dir() -> PathBuf { +pub(crate) fn dir() -> PathBuf { std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Kiri")).unwrap_or_else(|| PathBuf::from(".")) } @@ -202,6 +202,11 @@ fn quiet(program: &str) -> Command { /// as UTF-16LE, and anything else as UTF-8. UTF-16 with no ASCII and no BOM /// at all is the one thing this cannot tell from UTF-8. NULs and a leading /// BOM are dropped either way. +/// Combines wsl.exe's stdout and stderr, decoding UTF-16LE when WSL speaks it. +pub(crate) fn wsl_output(stdout: &[u8], stderr: &[u8]) -> String { + wsl_text(stdout) + &wsl_text(stderr) +} + fn wsl_text(bytes: &[u8]) -> String { let (bytes, bom) = bytes.strip_prefix(&[0xFF, 0xFE]).map_or((bytes, false), |rest| (rest, true)); let text = if bom || looks_utf16(bytes) { @@ -345,7 +350,12 @@ fn restarted_since(at: u64) -> bool { } /// Whether the window should open on setup rather than Kiri. +/// Never opens setup (which could re-create an empty distro) when a custom +/// storage folder in `storage.json` is currently offline. pub fn needed() -> bool { + if crate::storage::unavailable().is_some() { + return false; + } let s = saved(); needs_setup(s.done, s.distro.as_deref(), distros) } @@ -900,13 +910,17 @@ fn tools() -> io::Result<()> { update(|s| { s.step = "tools"; s.progress = None; - s.tasks = tasks(&["docker 29.9.2".to_owned(), "Compose v5.6.1".to_owned(), "buildx v0.38.1".to_owned(), tr("docker build on Kiri"), tr("Make Kiri the default")]); + s.tasks = tasks(&["docker 29.9.2".to_owned(), "Compose v5.8.0".to_owned(), "buildx v0.38.1".to_owned(), tr("docker build on Kiri"), tr("Make Kiri the default")]); }); task(0, "active", ""); for f in ["bin/docker.exe", "bin/kiri.exe", "bin/cli-plugins/docker-compose.exe", "bin/cli-plugins/docker-buildx.exe"] { verified(f)?; } let make_default = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default); + let before_ctx = crate::dockerctx::docker_dir().and_then(|d| { + let cfg: Value = crate::dockerctx::read_json(&d.join("config.json")).ok()?; + cfg["currentContext"].as_str().map(str::to_owned) + }); // setup-tools.ps1 (contrib/windows), checked like the bundle's other // files and run from its file with its parameters as arguments. Not a // copy in this binary run through [scriptblock]::Create from Base64: @@ -951,6 +965,20 @@ fn tools() -> io::Result<()> { .unwrap_or_else(|| "installing the Docker tools failed".to_owned()); return Err(io::Error::other(why)); } + // The user may have toggled "Make Kiri the default for docker" while + // setup-tools.ps1 ran, after `make_default` above was already read (#369). + let want_default = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default); + if want_default { + crate::engine::use_kiri_context()?; + if !make_default { + task(4, "done", ""); + } + } else if make_default + && let Some(dir) = crate::dockerctx::docker_dir() + { + let _ = crate::dockerctx::set_current(&dir.join("config.json"), before_ctx.as_deref().unwrap_or("default")); + task(4, "done", &tr("skipped")); + } // From here on Kiri runs from %LOCALAPPDATA%\Kiri, not the download folder. if let Ok(exe) = std::env::current_exe() { let installed = dir().join("kiri-win.exe"); @@ -968,6 +996,13 @@ fn tools() -> io::Result<()> { /// Ready → Open Kiri: remember setup is done, start at sign-in if asked. fn finish() { let autostart = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_none_or(|s| s.autostart); + crate::engine::heal_docker_config(&crate::client::pipe()); + // Apply "Make Kiri the default for docker" on finish too (e.g. if checked after tools finished). + if STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().is_some_and(|s| s.make_default) + && let Err(e) = crate::engine::use_kiri_context() + { + crate::serve::log(&format!("docker context: could not make kiri default ({e})")); + } // Which builder docker build uses: asked with another engine here, Kiri's without. let asked = STATE.lock().unwrap_or_else(PoisonError::into_inner).as_ref().filter(|s| s.other_docker).map(|s| s.build_kiri); let built = match asked { @@ -985,20 +1020,83 @@ fn finish() { save(&s); crate::serve::set_setup_pending(false); let exe = dir().join("kiri-win.exe"); - let run_key = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; if autostart { if exe.is_file() { - let _ = quiet("reg.exe").args(["add", run_key, "/v", "Kiri", "/t", "REG_SZ", "/d", &format!("\"{}\" --background", exe.display()), "/f"]).status(); + let _ = set_start_at_login_named(RUN_VALUE, true, &exe); } else { crate::serve::log("not set to start at sign-in: kiri-win.exe is not installed"); } } else { - let _ = quiet("reg.exe").args(["delete", run_key, "/v", "Kiri", "/f"]).status(); + let _ = set_start_at_login_named(RUN_VALUE, false, &exe); } let _ = quiet("reg.exe").args(["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce", "/v", "KiriSetup", "/f"]).status(); Handle.run(|ui| ui.navigate_main()); } +pub const RUN_KEY: &str = r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run"; +pub const RUN_VALUE: &str = "Kiri"; + +pub fn run_reg_value(exe: &Path) -> String { + format!("\"{}\" --background", exe.display()) +} + +pub fn run_reg_args(value_name: &str, on: bool, exe: &Path) -> Vec { + if on { + vec![ + "add".into(), + RUN_KEY.into(), + "/v".into(), + value_name.into(), + "/t".into(), + "REG_SZ".into(), + "/d".into(), + run_reg_value(exe), + "/f".into(), + ] + } else { + vec!["delete".into(), RUN_KEY.into(), "/v".into(), value_name.into(), "/f".into()] + } +} + +pub fn parse_run_reg_query(status_ok: bool, stdout: &str, value_name: &str) -> bool { + status_ok + && stdout.lines().any(|l| { + let mut parts = l.split_whitespace(); + parts.next().is_some_and(|n| n.eq_ignore_ascii_case(value_name)) + && parts.next().is_some_and(|t| t.eq_ignore_ascii_case("REG_SZ")) + }) +} + +pub fn start_at_login_named(value_name: &str) -> bool { + quiet("reg.exe") + .args(["query", RUN_KEY, "/v", value_name]) + .output() + .is_ok_and(|o| parse_run_reg_query(o.status.success(), &String::from_utf8_lossy(&o.stdout), value_name)) +} + +pub fn start_at_login() -> bool { + start_at_login_named(RUN_VALUE) +} + +pub fn set_start_at_login_named(value_name: &str, on: bool, exe: &Path) -> io::Result<()> { + if !on && !start_at_login_named(value_name) { + return Ok(()); + } + let args = run_reg_args(value_name, on, exe); + let out = quiet("reg.exe").args(&args).output()?; + if out.status.success() { + Ok(()) + } else { + Err(io::Error::other(String::from_utf8_lossy(&out.stderr).trim().to_owned())) + } +} + +pub fn set_start_at_login(on: bool) -> io::Result<()> { + let installed = dir().join("kiri-win.exe"); + let exe = if installed.is_file() { installed } else { std::env::current_exe()? }; + set_start_at_login_named(RUN_VALUE, on, &exe) +} + fn copy_to_clipboard(text: &str) { if let Ok(mut c) = quiet("clip.exe").stdin(Stdio::piped()).spawn() { if let Some(mut i) = c.stdin.take() { @@ -1381,4 +1479,40 @@ mod tests { let silent = listing_by(quiet("cmd.exe").raw_arg("/c echo Error code: Wsl/Service/WSAETIMEDOUT 1>&2 & exit 1"), ten); assert!(!silent.components_off && silent.distros.is_none()); } + + #[test] + fn start_at_login_registry_commands_and_query_parsing() { + let exe = std::path::Path::new(r"C:\Users\me\AppData\Local\Kiri\kiri-win.exe"); + assert_eq!(super::run_reg_value(exe), r#""C:\Users\me\AppData\Local\Kiri\kiri-win.exe" --background"#); + assert_eq!( + super::run_reg_args("Kiri", true, exe), + vec![ + "add", + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", + "/v", + "Kiri", + "/t", + "REG_SZ", + "/d", + r#""C:\Users\me\AppData\Local\Kiri\kiri-win.exe" --background"#, + "/f", + ] + ); + assert_eq!( + super::run_reg_args("Kiri", false, exe), + vec!["delete", r"HKCU\Software\Microsoft\Windows\CurrentVersion\Run", "/v", "Kiri", "/f"] + ); + let out = "\r\nHKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run\r\n Kiri REG_SZ \"C:\\Users\\me\\AppData\\Local\\Kiri\\kiri-win.exe\" --background\r\n\r\n"; + assert!(super::parse_run_reg_query(true, out, "Kiri")); + assert!(!super::parse_run_reg_query(false, out, "Kiri")); + assert!(!super::parse_run_reg_query(true, "", "Kiri")); + + let test_val = format!("KiriTest368_{}", std::process::id()); + let _ = super::set_start_at_login_named(&test_val, false, exe); + assert!(!super::start_at_login_named(&test_val)); + super::set_start_at_login_named(&test_val, true, exe).unwrap(); + assert!(super::start_at_login_named(&test_val)); + super::set_start_at_login_named(&test_val, false, exe).unwrap(); + assert!(!super::start_at_login_named(&test_val)); + } } diff --git a/crates/kiri-win/src/storage.rs b/crates/kiri-win/src/storage.rs new file mode 100644 index 000000000..4950693b5 --- /dev/null +++ b/crates/kiri-win/src/storage.rs @@ -0,0 +1,1036 @@ +//! Settings → Storage on Windows: where Kiri keeps its WSL 2 distro VHDX +//! (`ext4.vhdx`), recorded in `%LOCALAPPDATA%\Kiri\storage.json` when changed +//! from the default `%LOCALAPPDATA%\Kiri\wsl\`. +//! +//! Users who never change storage have no `storage.json` and zero behavior +//! change. When a custom path is configured, it must hold `.kiri-storage`: +//! if an external drive letter is unplugged or offline, Kiri refuses to +//! wipe or re-create an empty distro, surfaces `state: "unavailable"` in +//! Settings → Storage, and offers Retry, Change…, or Reset to default. +//! +//! Moving the distro tries native `wsl.exe --manage --move

` +//! first (Windows 11 / modern WSL 2), falling back to `wsl.exe --export` +//! (with `--vhd` when supported, else `.tar`) -> `wsl.exe --unregister` -> +//! `wsl.exe --import --version 2`, rolling back to +//! the original folder if `--import` fails. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +/// The settings file, under `%LOCALAPPDATA%\Kiri`. +pub const FILE: &str = "storage.json"; + +/// Written into a custom storage folder once a move completes so an offline +/// drive or an unrelated non-empty folder is never mistaken for Kiri's data. +pub const MARKER: &str = ".kiri-storage"; + +const MOVING: &str = ".kiri-moving"; +const IGNORED: &[&str] = &["desktop.ini", "Thumbs.db", MOVING, MARKER]; + +/// What `storage.json` holds. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Choice { + pub path: PathBuf, + pub previous: Option, +} + +/// Result of checking a target path before moving. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Checked { + pub needed: u64, + pub free: u64, + pub replaces: bool, +} + +/// Whether `dir` holds the marker written by a completed move. +pub fn has_marker(dir: &Path) -> bool { + dir.join(MARKER).is_file() +} + +/// Atomically writes `bytes` to `file` via a sibling temp file + rename. +pub fn write_atomic(file: &Path, bytes: &[u8]) -> io::Result<()> { + if let Some(parent) = file.parent() { + fs::create_dir_all(parent)?; + } + let tmp = file.with_extension(format!("tmp-{}", std::process::id())); + let write_res = (|| -> io::Result<()> { + let mut f = fs::File::create(&tmp)?; + io::Write::write_all(&mut f, bytes)?; + f.sync_all() + })(); + if let Err(e) = write_res { + let _ = fs::remove_file(&tmp); + return Err(e); + } + // On Windows fs::rename fails if the destination exists; remove and rename + // only after the temp file is flushed, keeping the window minimal. + #[cfg(windows)] + if file.exists() { + let _ = fs::remove_file(file); + } + fs::rename(&tmp, file).inspect_err(|_| { + let _ = fs::remove_file(&tmp); + }) +} + +/// Writes the marker into `dir`. +pub fn write_marker(dir: &Path) -> io::Result<()> { + write_atomic(&dir.join(MARKER), b"{\"kiri\":1}\n") +} + +/// Reads `Choice` from `file`; `None` when absent. +pub fn read_at(file: &Path) -> io::Result> { + match fs::read(file) { + Ok(bytes) => { + let v: serde_json::Value = serde_json::from_slice(&bytes) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", file.display())))?; + let path = v["path"] + .as_str() + .map(PathBuf::from) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("{}: missing path", file.display())))?; + let previous = v["previous"].as_str().map(PathBuf::from); + Ok(Some(Choice { path, previous })) + } + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e), + } +} + +/// Writes `Choice` atomically to `file`. +pub fn write_at(file: &Path, choice: &Choice) -> io::Result<()> { + let mut map = serde_json::Map::new(); + map.insert("path".into(), serde_json::Value::String(choice.path.to_string_lossy().into_owned())); + if let Some(prev) = &choice.previous { + map.insert("previous".into(), serde_json::Value::String(prev.to_string_lossy().into_owned())); + } + let bytes = serde_json::to_vec_pretty(&serde_json::Value::Object(map)).map_err(io::Error::other)?; + write_atomic(file, &bytes) +} + +/// Removes `file` if present. +pub fn clear_at(file: &Path) -> io::Result<()> { + match fs::remove_file(file) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e), + _ => Ok(()), + } +} + +/// Resolves whether a configured choice is currently offline / unavailable. +/// Returns `Some(missing_path)` if `choice` points to a non-default folder +/// whose `.kiri-storage` marker is missing (for example an unplugged drive). +pub fn unavailable_for(choice: Option<&Choice>, default: &Path) -> Option { + let c = choice?; + if same_path(&c.path, default) || has_marker(&c.path) { + None + } else { + Some(c.path.clone()) + } +} + +/// Case-insensitive normalized comparison suitable for Windows paths. +pub fn same_path(a: &Path, b: &Path) -> bool { + norm_key(a) == norm_key(b) +} + +/// Whether `child` is inside `parent` (strictly or equal), case-insensitively. +pub fn is_within(child: &Path, parent: &Path) -> bool { + let c = norm_key(child); + let p = norm_key(parent); + if c == p { + return true; + } + let prefix = if p.ends_with('/') { p } else { format!("{p}/") }; + c.starts_with(&prefix) +} + +fn norm_key(p: &Path) -> String { + let s = p.to_string_lossy().replace('\\', "/"); + let s = s.trim_end_matches('/'); + // Preserve root drive like "c:" -> "c:/" + if s.len() == 2 && s.as_bytes()[1] == b':' { + format!("{}/", s.to_ascii_lowercase()) + } else { + s.to_ascii_lowercase() + } +} + +/// Whether `raw` is an absolute local Windows drive path (`C:\...`), +/// rejecting relative paths, parent traversal (`..`), and UNC shares (`\\...`). +pub fn is_local_windows_path(raw: &str) -> bool { + let s = raw.trim(); + if s.starts_with(r"\\") || s.starts_with("//") { + return false; + } + let bytes = s.as_bytes(); + if bytes.len() < 3 || !bytes[0].is_ascii_alphabetic() || bytes[1] != b':' || (bytes[2] != b'\\' && bytes[2] != b'/') { + return false; + } + !s.split(['\\', '/']).any(|seg| seg == "..") +} + +/// Filesystems that cannot reliably hold a WSL 2 `ext4.vhdx`. +pub fn refused_fs(name: &str) -> bool { + let n = name.trim().to_ascii_lowercase(); + matches!(n.as_str(), "fat" | "fat32" | "exfat" | "msdos" | "vfat") +} + +/// Margin kept free beside the data: 10% plus 1 GB. +pub fn headroom(bytes: u64) -> u64 { + bytes / 10 + 1_000_000_000 +} + +/// Persisted non-compactable VHDX + ext4 metadata floor (`/vhdx-overhead`), +/// measured right after `fstrim` + VHDX compaction so WSL2's VHDX header/BAT and +/// allocated ext4 metadata aren't repeatedly advertised as reclaimable space. +pub const VHDX_OVERHEAD_FILE: &str = "vhdx-overhead"; + +/// Reclaimable bytes below 64 MiB are reported as 0 to avoid prompting +/// pointless VHDX compaction over filesystem slack. +pub const RECLAIM_THRESHOLD: u64 = 64 << 20; + +/// Effective bytes occupied inside `ext4.vhdx`, adding the measured post-compact +/// metadata floor (`recorded_overhead`, clamped downward if blocks were reused) +/// without guessing from WSL's 1 TB virtual capacity on an uncompacted dynamic VHDX. +pub fn effective_vhdx_in_use( + disk_host: Option, + raw_in_use: Option, + recorded_overhead: Option, +) -> (Option, Option) { + let Some(raw) = raw_in_use else { + return (None, None); + }; + let Some(saved) = recorded_overhead else { + return (Some(raw), None); + }; + let overhead = match disk_host { + Some(host) => saved.min(host.saturating_sub(raw)), + None => saved, + }; + let clamped = (overhead < saved).then_some(overhead); + (Some(raw.saturating_add(overhead)), clamped) +} + +pub fn read_vhdx_overhead(root: &Path) -> Option { + fs::read_to_string(root.join(VHDX_OVERHEAD_FILE)).ok()?.trim().parse::().ok() +} + +pub fn write_vhdx_overhead(root: &Path, bytes: u64) { + let path = root.join(VHDX_OVERHEAD_FILE); + let tmp = root.join("vhdx-overhead.tmp"); + if fs::write(&tmp, format!("{bytes}\n")).is_ok() { + let _ = fs::rename(&tmp, &path); + } +} + +/// Reclaimable bytes from host `ext4.vhdx` allocated size vs in-use bytes +/// inside WSL, applying [`RECLAIM_THRESHOLD`]. +pub fn reclaimable_bytes(disk_host: Option, disk_in_use: Option) -> Option { + let diff = disk_host?.saturating_sub(disk_in_use?); + Some(if diff > RECLAIM_THRESHOLD { diff } else { 0 }) +} + +fn format_gb(bytes: u64) -> String { + format!("{:.1} GB", bytes as f64 / 1e9) +} + +/// Pure validation helper shared between Windows production code and host tests. +pub fn validate_target( + current: &Path, + target_raw: &str, + used_bytes: u64, + copy: bool, + fs_type: impl FnOnce(&Path) -> io::Result, + free_bytes: impl FnOnce(&Path) -> io::Result, + probe_write: impl FnOnce(&Path) -> io::Result<()>, +) -> Result { + let trimmed = target_raw.trim(); + if !is_local_windows_path(trimmed) { + return Err(format!("{trimmed} isn't a local drive path: choose a folder on a local drive (for example D:\\Kiri)")); + } + let target = PathBuf::from(trimmed); + if same_path(current, &target) { + return Err(format!("Kiri's data is already in {}", target.display())); + } + if is_within(&target, current) { + return Err(format!("{} is inside Kiri's data folder {}: choose a folder outside it", target.display(), current.display())); + } + if is_within(current, &target) { + return Err(format!("Kiri's data folder {} is inside {}: choose another folder", current.display(), target.display())); + } + let mut replaces = false; + if target.symlink_metadata().is_ok() { + if !target.is_dir() { + return Err(format!("{} isn't a folder", target.display())); + } + let others = fs::read_dir(&target) + .map_err(|e| format!("{}: {e}", target.display()))? + .flatten() + .any(|e| { + let name = e.file_name(); + !IGNORED.iter().any(|n| name.eq_ignore_ascii_case(n)) + }); + if has_marker(&target) { + replaces = others; + } else if others { + return Err(format!("{} isn't empty and doesn't hold Kiri's data: choose an empty folder, or make a new one", target.display())); + } + } + let near = target.ancestors().find(|p| p.is_dir()).ok_or_else(|| format!("{} isn't on any connected drive", target.display()))?; + let fs = fs_type(near).map_err(|e| format!("{}: {e}", near.display()))?; + if refused_fs(&fs) { + return Err(format!("{} is on a {fs} drive, which can't hold Kiri's WSL disk: choose a folder on an NTFS drive", target.display())); + } + probe_write(near).map_err(|e| format!("Kiri can't write in {}: {e}", near.display()))?; + let needed = if copy { used_bytes + headroom(used_bytes) } else { headroom(0) }; + let free = free_bytes(near).map_err(|e| format!("{}: {e}", near.display()))?; + if free < needed { + return Err(format!("{} has {} free, and Kiri's data needs {} there", near.display(), format_gb(free), format_gb(needed))); + } + Ok(Checked { needed, free, replaces }) +} + +#[cfg(windows)] +mod imp { + use super::*; + use serde_json::{Value, json}; + use std::os::windows::ffi::OsStrExt; + use std::os::windows::process::CommandExt; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Mutex, PoisonError}; + + use crate::engine::{Cmd, emit, notice, send, tr, trf}; + + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + + #[derive(Default)] + struct Moving { + to: Option, + phase: &'static str, + done: u64, + total: u64, + error: Option, + } + + static MOVE: Mutex = Mutex::new(Moving { to: None, phase: "", done: 0, total: 0, error: None }); + static ACTIVE: AtomicBool = AtomicBool::new(false); + static RECLAIMING: AtomicBool = AtomicBool::new(false); + + fn state() -> std::sync::MutexGuard<'static, Moving> { + MOVE.lock().unwrap_or_else(PoisonError::into_inner) + } + + pub fn moving() -> bool { + ACTIVE.load(Ordering::SeqCst) + } + + fn vhdx_allocated(path: &Path) -> Option { + use windows_sys::Win32::Foundation::{GetLastError, NO_ERROR}; + use windows_sys::Win32::Storage::FileSystem::GetCompressedFileSizeW; + if !path.is_file() { + return None; + } + let w = wide(path); + let mut high = 0u32; + // SAFETY: `w` is NUL-terminated UTF-16 and `high` is a valid out pointer. + let low = unsafe { GetCompressedFileSizeW(w.as_ptr(), &mut high) }; + if low == u32::MAX && unsafe { GetLastError() } != NO_ERROR { + return fs::metadata(path).ok().map(|m| m.len()); + } + Some(((high as u64) << 32) | (low as u64)) + } + + fn wsl_disk_usage() -> (Option, Option) { + if !crate::client::alive_quick() { + return (None, None); + } + let Ok(v) = crate::client::get_quick("/kiri/storage") else { + return (None, None); + }; + (v["fs_in_use"].as_u64(), v["fs_capacity"].as_u64()) + } + + fn config_path() -> PathBuf { + crate::setup::dir().join(FILE) + } + + fn distro_name() -> String { + crate::engine::distro().unwrap_or_else(|| crate::setup::KIRI_DISTRO.to_owned()) + } + + pub fn default_root() -> PathBuf { + crate::setup::dir().join("wsl").join(distro_name()) + } + + pub fn read() -> Option { + read_at(&config_path()).ok().flatten() + } + + /// Returns `Some(missing_path)` if `storage.json` configures a custom + /// folder whose drive is currently offline / marker is missing. + pub fn unavailable() -> Option { + let choice = read(); + unavailable_for(choice.as_ref(), &default_root()) + } + + pub fn unavailable_message(missing: &Path) -> String { + format!("Kiri's data folder {} isn't available: connect its drive, or choose Settings → Storage → Reset to default", missing.display()) + } + + fn current_root() -> PathBuf { + read().map(|c| c.path).unwrap_or_else(default_root) + } + + pub fn current_vhdx() -> PathBuf { + current_root().join("ext4.vhdx") + } + + fn dir_size(dir: &Path) -> u64 { + let Ok(entries) = fs::read_dir(dir) else { return 0 }; + let mut total = 0u64; + for e in entries.flatten() { + let Ok(m) = e.metadata() else { continue }; + if m.is_file() { + total = total.saturating_add(m.len()); + } else if m.is_dir() { + total = total.saturating_add(dir_size(&e.path())); + } + } + total + } + + fn wide(p: &Path) -> Vec { + p.as_os_str().encode_wide().chain(std::iter::once(0)).collect() + } + + fn free_space(dir: &Path) -> io::Result { + use windows_sys::Win32::Storage::FileSystem::GetDiskFreeSpaceExW; + let w = wide(dir); + let mut avail = 0u64; + // SAFETY: `w` is NUL-terminated UTF-16 and `avail` is a valid out pointer. + if unsafe { GetDiskFreeSpaceExW(w.as_ptr(), &mut avail, std::ptr::null_mut(), std::ptr::null_mut()) } == 0 { + return Err(io::Error::last_os_error()); + } + Ok(avail) + } + + fn fs_name(dir: &Path) -> io::Result { + use windows_sys::Win32::Storage::FileSystem::{GetVolumeInformationW, GetVolumePathNameW}; + let w = wide(dir); + let mut root = [0u16; 260]; + // SAFETY: valid UTF-16 path and output buffer of length 260. + if unsafe { GetVolumePathNameW(w.as_ptr(), root.as_mut_ptr(), root.len() as u32) } == 0 { + return Err(io::Error::last_os_error()); + } + let mut fs_buf = [0u16; 64]; + // SAFETY: `root` is NUL-terminated; `fs_buf` receives the filesystem name. + if unsafe { + GetVolumeInformationW( + root.as_ptr(), + std::ptr::null_mut(), + 0, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + fs_buf.as_mut_ptr(), + fs_buf.len() as u32, + ) + } == 0 + { + return Err(io::Error::last_os_error()); + } + let end = fs_buf.iter().position(|&c| c == 0).unwrap_or(fs_buf.len()); + Ok(String::from_utf16_lossy(&fs_buf[..end])) + } + + fn probe_writable(dir: &Path) -> io::Result<()> { + let probe = dir.join(format!(".kiri-probe-{}", std::process::id())); + let res = (|| { + let mut f = fs::OpenOptions::new().write(true).create_new(true).open(&probe)?; + io::Write::write_all(&mut f, b"kiri")?; + f.sync_all() + })(); + let _ = fs::remove_file(&probe); + res + } + + pub fn report() -> Value { + let default = default_root(); + let choice = read(); + let missing = unavailable_for(choice.as_ref(), &default); + let is_missing = missing.is_some(); + let root = missing.unwrap_or_else(|| choice.as_ref().map(|c| c.path.clone()).unwrap_or_else(|| default.clone())); + let custom = !same_path(&root, &default); + let old = choice.and_then(|c| c.previous).filter(|p| !same_path(p, &root) && p.is_dir()); + let active = moving(); + let m = state(); + let near = root.ancestors().find(|p| p.is_dir()); + let (disk_host, disk_in_use, disk_limit, reclaimable) = if !is_missing && !active { + let host = vhdx_allocated(&root.join("ext4.vhdx")); + let (raw_in_use, limit) = wsl_disk_usage(); + let recorded = read_vhdx_overhead(&root); + let (in_use, clamped) = effective_vhdx_in_use(host, raw_in_use, recorded); + if let Some(updated) = clamped { + write_vhdx_overhead(&root, updated); + } + let rec = reclaimable_bytes(host, in_use); + (host, in_use, limit, rec) + } else { + (None, None, None, None) + }; + json!({ + "type": "storage", + "path": root, + "default": default, + "custom": custom, + "env": false, + "state": if is_missing { "unavailable" } else if active { "moving" } else { "ok" }, + "used": (!is_missing && !active).then(|| dir_size(&root)), + "free": if is_missing { None } else { near.and_then(|p| free_space(p).ok()) }, + "fs": if is_missing { None } else { near.and_then(|p| fs_name(p).ok()) }, + "disk_host": disk_host, + "disk_in_use": disk_in_use, + "disk_limit": disk_limit, + "reclaimable": reclaimable, + "moving": m.to.as_ref().filter(|_| active).map(|to| json!({"to": to, "phase": m.phase, "done": m.done, "total": m.total})), + "error": m.error, + "old": old, + }) + } + + pub fn emit_report() { + emit(report().to_string()); + } + + pub fn check_and_emit(path: Option, fresh: bool, reset: bool) { + let default = default_root(); + let current = current_root(); + let target_str = match path.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + Some(p) => p.to_owned(), + None => default.to_string_lossy().into_owned(), + }; + let is_unavail = unavailable().is_some(); + let used = if is_unavail || fresh { 0 } else { dir_size(¤t) }; + match validate_target(¤t, &target_str, used, !is_unavail && !fresh, fs_name, free_space, probe_writable) { + Ok(c) => emit(json!({"type": "storagecheck", "path": target_str, "needed": c.needed, "free": c.free, "replaces": c.replaces, "reset": reset}).to_string()), + Err(e) => emit(json!({"type": "storagecheck", "path": target_str, "error": e, "reset": reset}).to_string()), + } + } + + fn wsl_run(args: &[&std::ffi::OsStr]) -> io::Result { + let mut cmd = crate::win::tool("wsl.exe"); + cmd.creation_flags(CREATE_NO_WINDOW).args(args); + let out = cmd.output()?; + let text = crate::setup::wsl_output(&out.stdout, &out.stderr); + if out.status.success() { + Ok(text) + } else { + let line = text.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("wsl.exe failed"); + Err(io::Error::other(line.to_owned())) + } + } + + fn set_phase(phase: &'static str, done: u64, total: u64) { + { + let mut m = state(); + m.phase = phase; + m.done = done; + m.total = total; + } + emit_report(); + } + + pub fn start_move(path: Option, fresh: bool) { + std::thread::Builder::new() + .name("kiri-storage-move".into()) + .spawn(move || run_move(path, fresh)) + .ok(); + } + + fn run_move(path: Option, fresh: bool) { + let default = default_root(); + let current = current_root(); + let distro = distro_name(); + let target_str = match path.as_deref().map(str::trim).filter(|s| !s.is_empty()) { + Some(p) => p.to_owned(), + None => default.to_string_lossy().into_owned(), + }; + let is_unavail = unavailable().is_some(); + let used = if is_unavail || fresh { 0 } else { dir_size(¤t) }; + if let Err(e) = validate_target(¤t, &target_str, used, !is_unavail && !fresh, fs_name, free_space, probe_writable) { + emit(notice("error", &e)); + emit_report(); + return; + } + let target = PathBuf::from(&target_str); + if ACTIVE.swap(true, Ordering::SeqCst) { + emit(notice("error", &tr("Kiri's data is moving already"))); + return; + } + *state() = Moving { to: Some(target.clone()), phase: "stopping", done: 0, total: used, error: None }; + emit_report(); + + let result = (|| -> io::Result> { + let running = if !is_unavail && crate::client::alive_quick() { + let list = crate::client::get_quick("/containers/json").ok(); + let ids: Vec = list + .as_ref() + .and_then(|v| v.as_array()) + .map(|a| a.iter().filter_map(|c| c["Id"].as_str().map(str::to_owned)).collect()) + .unwrap_or_default(); + let _ = crate::client::request("POST", "/kiri/stop", None); + ids + } else { + Vec::new() + }; + crate::serve::renew_bridge(); + let _ = wsl_run(&[std::ffi::OsStr::new("--terminate"), std::ffi::OsStr::new(&distro)]); + fs::create_dir_all(&target)?; + + if is_unavail || fresh { + set_phase("switching", 0, 0); + // Switching to a fresh store on Kiri Linux: verify bundle before touching WSL. + let tar = crate::setup::verified("kiri-linux.tar.gz")?; + let _ = wsl_run(&[std::ffi::OsStr::new("--unregister"), std::ffi::OsStr::new(&distro)]); + wsl_run(&[ + std::ffi::OsStr::new("--import"), + std::ffi::OsStr::new(&distro), + target.as_os_str(), + tar.as_os_str(), + std::ffi::OsStr::new("--version"), + std::ffi::OsStr::new("2"), + ])?; + } else { + set_phase("copying", 0, used); + move_distro(&distro, ¤t, &target)?; + } + + set_phase("switching", 0, 0); + write_marker(&target)?; + if same_path(&target, &default) { + clear_at(&config_path())?; + } else { + write_at(&config_path(), &Choice { path: target.clone(), previous: None })?; + } + + set_phase("restarting", 0, 0); + crate::serve::renew_bridge(); + crate::engine::ensure_daemon()?; + Ok(if fresh || is_unavail { Vec::new() } else { running }) + })(); + + match result { + Ok(running) => { + { + let mut m = state(); + m.to = None; + m.phase = ""; + m.error = None; + } + ACTIVE.store(false, Ordering::SeqCst); + for id in &running { + let _ = crate::client::request("POST", &format!("/containers/{id}/start"), None); + } + emit(notice("ok", &trf("Kiri's data moved to {path}", &[("path", &target.display().to_string())]))); + emit_report(); + send(Cmd::Refresh); + } + Err(e) => { + crate::serve::log(&format!("storage move failed: {e}")); + { + let mut m = state(); + m.to = None; + m.phase = ""; + m.error = Some(e.to_string()); + } + ACTIVE.store(false, Ordering::SeqCst); + let _ = crate::engine::ensure_daemon(); + emit(notice("error", &e.to_string())); + emit_report(); + } + } + } + + /// Moves WSL distro `distro` from `old_dir` to `target`. Tries native + /// `wsl --manage --move ` first, then falls back to + /// `--export` -> `--unregister` -> `--import` with rollback on failure. + fn move_distro(distro: &str, old_dir: &Path, target: &Path) -> io::Result<()> { + let managed = wsl_run(&[ + std::ffi::OsStr::new("--manage"), + std::ffi::OsStr::new(distro), + std::ffi::OsStr::new("--move"), + target.as_os_str(), + ]); + if managed.is_ok() { + return Ok(()); + } + // Fallback: export into staging folder inside target, unregister, import. + let staging = target.join(MOVING); + let _ = fs::remove_dir_all(&staging); + fs::create_dir_all(&staging)?; + let vhd_file = staging.join("distro.vhdx"); + let tar_file = staging.join("distro.tar"); + let (archive, is_vhd) = match wsl_run(&[ + std::ffi::OsStr::new("--export"), + std::ffi::OsStr::new(distro), + vhd_file.as_os_str(), + std::ffi::OsStr::new("--vhd"), + ]) { + Ok(_) if vhd_file.is_file() && fs::metadata(&vhd_file).is_ok_and(|m| m.len() > 0) => (vhd_file, true), + _ => { + let _ = fs::remove_file(&vhd_file); + if let Err(e) = wsl_run(&[std::ffi::OsStr::new("--export"), std::ffi::OsStr::new(distro), tar_file.as_os_str()]) { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + if !tar_file.is_file() || fs::metadata(&tar_file).is_ok_and(|m| m.len() == 0) { + let _ = fs::remove_dir_all(&staging); + return Err(io::Error::other("WSL export produced an empty archive")); + } + (tar_file, false) + } + }; + if let Err(e) = wsl_run(&[std::ffi::OsStr::new("--unregister"), std::ffi::OsStr::new(distro)]) { + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + let import_to = |dest: &Path| { + let mut args: Vec<&std::ffi::OsStr> = vec![ + std::ffi::OsStr::new("--import"), + std::ffi::OsStr::new(distro), + dest.as_os_str(), + archive.as_os_str(), + std::ffi::OsStr::new("--version"), + std::ffi::OsStr::new("2"), + ]; + if is_vhd { + args.push(std::ffi::OsStr::new("--vhd")); + } + wsl_run(&args) + }; + if let Err(e) = import_to(target) { + // Roll back: restore the distro at its original folder before deleting staging. + let _ = fs::create_dir_all(old_dir); + let _ = import_to(old_dir); + let _ = fs::remove_dir_all(&staging); + return Err(e); + } + let _ = fs::remove_dir_all(&staging); + Ok(()) + } + + pub fn retry() { + std::thread::spawn(|| { + if let Some(missing) = unavailable() { + emit(notice("error", &unavailable_message(&missing))); + emit_report(); + return; + } + crate::serve::renew_bridge(); + match crate::engine::ensure_daemon() { + Ok(()) => { + emit(notice("ok", &tr("Storage is available again"))); + emit_report(); + send(Cmd::Refresh); + } + Err(e) => { + emit(notice("error", &e.to_string())); + emit_report(); + } + } + }); + } + + pub fn reset() { + if unavailable().is_some() { + start_move(None, true); + } else { + start_move(None, false); + } + } + + pub fn remove_old() { + std::thread::spawn(|| { + if moving() { + emit(notice("error", &tr("Kiri's data is moving already"))); + return; + } + let Some(mut choice) = read() else { return }; + let Some(old) = choice.previous.clone() else { return }; + let current = current_root(); + if same_path(&old, ¤t) || is_within(&old, ¤t) || is_within(¤t, &old) { + emit(notice("error", &format!("{} holds Kiri's data now", old.display()))); + return; + } + if old.exists() { + if !has_marker(&old) { + emit(notice("error", &format!("{} doesn't look like Kiri's old data; remove it yourself if you're sure", old.display()))); + return; + } + if let Err(e) = fs::remove_dir_all(&old) { + emit(notice("error", &format!("{}: {e}", old.display()))); + return; + } + } + choice.previous = None; + let _ = if same_path(&choice.path, &default_root()) { clear_at(&config_path()) } else { write_at(&config_path(), &choice) }; + emit(notice("ok", &tr("Old data removed"))); + emit_report(); + }); + } + + fn compact_vhdx(vhdx: &Path) -> io::Result<()> { + // First try Hyper-V's Optimize-VHD via PowerShell if installed. + let escaped = vhdx.to_string_lossy().replace('\'', "''"); + let ps = crate::win::tool("powershell.exe") + .creation_flags(CREATE_NO_WINDOW) + .args([ + "-NoProfile", + "-NonInteractive", + "-Command", + &format!("Optimize-VHD -Path '{escaped}' -Mode Full"), + ]) + .output(); + if ps.as_ref().is_ok_and(|o| o.status.success()) { + return Ok(()); + } + // Fallback: diskpart compact vdisk on an offline VHDX. + let script = std::env::temp_dir().join(format!("kiri-compact-{}.txt", std::process::id())); + let vhdx_str = vhdx.to_string_lossy().replace('"', ""); + let content = format!( + "select vdisk file=\"{vhdx_str}\"\r\nattach vdisk readonly\r\ncompact vdisk\r\ndetach vdisk\r\n" + ); + fs::write(&script, content.as_bytes())?; + let res = crate::win::tool("diskpart.exe") + .creation_flags(CREATE_NO_WINDOW) + .arg("/s") + .arg(&script) + .output(); + let _ = fs::remove_file(&script); + match res { + Ok(o) if o.status.success() => Ok(()), + Ok(o) => { + let text = crate::setup::wsl_output(&o.stdout, &o.stderr); + let line = text.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("diskpart compact failed"); + Err(io::Error::other(line.to_owned())) + } + Err(e) => Err(e), + } + } + + /// Reclaims unused space in Kiri's WSL 2 `ext4.vhdx` via `fstrim` + sparse + /// mode or offline VHDX compact, restarting the engine and previously + /// running containers if offline compaction was needed. + pub fn reclaim() { + std::thread::Builder::new() + .name("kiri-storage-reclaim".into()) + .spawn(|| { + if moving() { + emit(json!({"type": "storagereclaimed", "error": tr("Kiri's data is moving already")}).to_string()); + return; + } + if RECLAIMING.swap(true, Ordering::SeqCst) { + emit(json!({"type": "storagereclaimed", "error": tr("Disk reclaim is already running")}).to_string()); + return; + } + struct Guard; + impl Drop for Guard { + fn drop(&mut self) { + RECLAIMING.store(false, Ordering::SeqCst); + } + } + let _guard = Guard; + let t0 = std::time::Instant::now(); + let distro = distro_name(); + let vhdx = current_vhdx(); + let before = vhdx_allocated(&vhdx).unwrap_or(0); + let running: Vec = if crate::client::alive_quick() { + crate::client::get_quick("/containers/json") + .ok() + .and_then(|v| v.as_array().cloned()) + .map(|a| a.iter().filter_map(|c| c["Id"].as_str().map(str::to_owned)).collect()) + .unwrap_or_default() + } else { + Vec::new() + }; + // 1. Discard freed ext4 blocks inside WSL. + let _ = wsl_run(&[ + std::ffi::OsStr::new("-d"), + std::ffi::OsStr::new(&distro), + std::ffi::OsStr::new("-u"), + std::ffi::OsStr::new("root"), + std::ffi::OsStr::new("--"), + std::ffi::OsStr::new("sh"), + std::ffi::OsStr::new("-c"), + std::ffi::OsStr::new("fstrim /var/lib/kiri 2>/dev/null || true; fstrim / 2>/dev/null || true"), + ]); + // 2. Enable sparse VHDX if WSL supports it (can reclaim immediately). + let _ = wsl_run(&[ + std::ffi::OsStr::new("--manage"), + std::ffi::OsStr::new(&distro), + std::ffi::OsStr::new("--set-sparse"), + std::ffi::OsStr::new("true"), + std::ffi::OsStr::new("--allow-unsafe"), + ]); + let mid = vhdx_allocated(&vhdx).unwrap_or(before); + let (in_use_before, _) = wsl_disk_usage(); + let still_reclaimable = reclaimable_bytes(Some(mid), in_use_before).unwrap_or(0) > 0 || mid >= before; + let mut compact_err: Option = None; + if still_reclaimable && vhdx.is_file() { + if crate::client::alive_quick() { + let _ = crate::client::request("POST", "/kiri/stop", None); + } + crate::serve::renew_bridge(); + let _ = wsl_run(&[std::ffi::OsStr::new("--terminate"), std::ffi::OsStr::new(&distro)]); + if let Err(e) = compact_vhdx(&vhdx) { + crate::serve::log(&format!("storage reclaim compact failed: {e}")); + compact_err = Some(e.to_string()); + } + crate::serve::renew_bridge(); + let _ = crate::engine::ensure_daemon(); + for id in &running { + let _ = crate::client::request("POST", &format!("/containers/{id}/start"), None); + } + } + let after = vhdx_allocated(&vhdx).unwrap_or(mid); + let reclaimed = before.saturating_sub(after); + let elapsed_ms = t0.elapsed().as_millis() as u64; + let (raw_in_use, _) = wsl_disk_usage(); + if compact_err.is_none() + && let (Some(raw), Some(root)) = (raw_in_use, vhdx.parent()) + { + write_vhdx_overhead(root, after.saturating_sub(raw)); + } + let recorded = vhdx.parent().and_then(read_vhdx_overhead); + let (in_use, _) = effective_vhdx_in_use(Some(after), raw_in_use, recorded); + if let Some(err) = compact_err && reclaimed == 0 { + emit(json!({"type": "storagereclaimed", "error": err}).to_string()); + } else { + emit( + json!({ + "type": "storagereclaimed", + "before": before, + "after": after, + "reclaimed": reclaimed, + "in_use": in_use, + "elapsed_ms": elapsed_ms, + }) + .to_string(), + ); + } + emit_report(); + send(Cmd::Refresh); + }) + .ok(); + } +} + +#[cfg(windows)] +pub use imp::*; + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-win-storage-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn offline_custom_drive_is_unavailable_and_never_created() { + let d = scratch("unavail"); + let file = d.join(FILE); + let default = d.join("wsl/kiri"); + let offline = d.join("external-drive/kiri"); + write_at(&file, &Choice { path: offline.clone(), previous: None }).unwrap(); + assert_eq!(unavailable_for(read_at(&file).unwrap().as_ref(), &default), Some(offline.clone())); + assert!(!offline.exists(), "offline path must never be created"); + fs::create_dir_all(&offline).unwrap(); + write_marker(&offline).unwrap(); + assert_eq!(unavailable_for(read_at(&file).unwrap().as_ref(), &default), None); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn no_storage_json_uses_default_without_marker() { + let d = scratch("default"); + let file = d.join(FILE); + assert_eq!(read_at(&file).unwrap(), None); + assert_eq!(unavailable_for(None, &d.join("wsl/kiri")), None); + assert!(!file.exists()); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn validates_windows_paths_case_insensitively_and_refuses_fat_exfat_unc() { + assert!(is_local_windows_path(r"D:\Kiri")); + assert!(is_local_windows_path("E:/kiri/data")); + assert!(!is_local_windows_path(r"\\nas\share\kiri")); + assert!(!is_local_windows_path(r"relative\kiri")); + assert!(!is_local_windows_path(r"D:\Kiri\..\Other")); + assert!(same_path(Path::new(r"C:\Users\Me\Kiri"), Path::new(r"c:\users\me\kiri\"))); + assert!(is_within(Path::new(r"D:\Kiri\sub"), Path::new(r"d:\kiri"))); + assert!(!is_within(Path::new(r"D:\Kiri2"), Path::new(r"d:\kiri"))); + assert!(refused_fs("FAT32") && refused_fs("exFAT") && refused_fs("FAT")); + assert!(!refused_fs("NTFS") && !refused_fs("ReFS")); + } + + #[test] + fn choice_round_trips_atomically_and_clears() { + let d = scratch("roundtrip"); + let file = d.join(FILE); + let c = Choice { path: PathBuf::from(r"E:\Kiri"), previous: Some(PathBuf::from(r"C:\Users\u\AppData\Local\Kiri\wsl\kiri")) }; + write_at(&file, &c).unwrap(); + assert_eq!(read_at(&file).unwrap(), Some(c)); + clear_at(&file).unwrap(); + assert_eq!(read_at(&file).unwrap(), None); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn validate_target_checks_path_fs_space_and_contents() { + let ok_fs = |_: &Path| Ok("NTFS".to_owned()); + let plenty = |_: &Path| Ok(100_000_000_000u64); + let writable = |_: &Path| Ok(()); + let cur = Path::new(r"C:\Users\u\AppData\Local\Kiri\wsl\kiri"); + assert!(validate_target(cur, r"relative\path", 0, true, ok_fs, plenty, writable).unwrap_err().contains("local drive path")); + assert!(validate_target(cur, r"\\nas\share\kiri", 0, true, ok_fs, plenty, writable).unwrap_err().contains("local drive path")); + assert!(validate_target(cur, r"c:\users\u\appdata\local\kiri\wsl\kiri", 0, true, ok_fs, plenty, writable).unwrap_err().contains("already in")); + assert!(validate_target(cur, r"C:\Users\u\AppData\Local\Kiri\wsl\kiri\sub", 0, true, ok_fs, plenty, writable).unwrap_err().contains("inside Kiri's data folder")); + assert!(validate_target(cur, r"C:\Users\u\AppData\Local\Kiri", 0, true, ok_fs, plenty, writable).unwrap_err().contains("is inside")); + assert_eq!(headroom(10_000_000_000), 2_000_000_000); + assert_eq!(reclaimable_bytes(Some(10_000_000_000), Some(10_000_000_000)), Some(0)); + assert_eq!(reclaimable_bytes(Some(100 + RECLAIM_THRESHOLD), Some(100)), Some(0)); + assert_eq!(reclaimable_bytes(Some(100 + RECLAIM_THRESHOLD + 1), Some(100)), Some(RECLAIM_THRESHOLD + 1)); + assert_eq!(reclaimable_bytes(None, Some(100)), None); + // On non-Windows hosts a Windows drive path like D:\ has no existing ancestor, so check the error cleanly. + let r = validate_target(cur, r"D:\Kiri", 5_000_000_000, true, |_| Ok("exFAT".into()), plenty, writable); + assert!(r.is_err()); + let _ = (Checked { needed: 0, free: 0, replaces: false }, IGNORED, MOVING, format_gb(1_000_000_000)); + } + + #[test] + fn vhdx_overhead_floor_prevents_phantom_reclaimable_and_clamps_downward() { + let d = scratch("vhdx-overhead"); + assert_eq!(read_vhdx_overhead(&d), None); + // Before first compaction: dynamic VHDX never guesses overhead from 1 TB virtual limit. + let (eff0, clamp0) = effective_vhdx_in_use(Some(20_000_000_000), Some(15_000_000_000), None); + assert_eq!((eff0, clamp0), (Some(15_000_000_000), None)); + assert_eq!(reclaimable_bytes(Some(20_000_000_000), eff0), Some(5_000_000_000)); + + // After compaction leaves 2.4 GB of non-compactable VHDX + ext4 metadata: + write_vhdx_overhead(&d, 2_400_000_000); + assert_eq!(read_vhdx_overhead(&d), Some(2_400_000_000)); + let (eff1, clamp1) = effective_vhdx_in_use(Some(17_400_000_000), Some(15_000_000_000), read_vhdx_overhead(&d)); + assert_eq!((eff1, clamp1), (Some(17_400_000_000), None)); + assert_eq!(reclaimable_bytes(Some(17_400_000_000), eff1), Some(0)); + + // If new container files reuse preallocated blocks so host - raw < saved floor, clamp downward. + let (eff2, clamp2) = effective_vhdx_in_use(Some(17_400_000_000), Some(16_000_000_000), read_vhdx_overhead(&d)); + assert_eq!((eff2, clamp2), (Some(17_400_000_000), Some(1_400_000_000))); + let _ = fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri-win/src/term.rs b/crates/kiri-win/src/term.rs index 48aba41bd..d31a6269b 100644 --- a/crates/kiri-win/src/term.rs +++ b/crates/kiri-win/src/term.rs @@ -46,10 +46,16 @@ impl Console { } } +static NEXT_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +enum State { + Opening { size: (u16, u16), pending: Vec> }, + Running { console: Arc, process: Arc, input: Sender> }, +} + struct Session { - console: Arc, - process: Arc, - input: Sender>, + seq: u64, + state: State, } static SESSIONS: Mutex>> = Mutex::new(None); @@ -58,6 +64,10 @@ fn with(f: impl FnOnce(&mut HashMap) -> R) -> R { f(SESSIONS.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(HashMap::new)) } +fn live(id: &str, seq: u64) -> bool { + with(|s| s.get(id).is_some_and(|s| s.seq == seq)) +} + /// 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 { @@ -68,30 +78,34 @@ pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) { 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()))); - } - }); - } + "open" if termwire::valid_id(id) => start_open(id, value, emit, shells), "input" => { if let Some(bytes) = value.as_str().and_then(termwire::unb64) { - with(|s| s.get(id).map(|s| s.input.send(bytes))); + with(|s| { + if let Some(slot) = s.get_mut(id) { + match &mut slot.state { + State::Opening { pending, .. } => pending.push(bytes), + State::Running { input, .. } => { + let _ = input.send(bytes); + } + } + } + }); } } "resize" => { let (cols, rows) = termwire::size(value); - with(|s| s.get(id).map(|s| s.console.resize(cols, rows))); + let console = with(|s| match s.get_mut(id).map(|slot| &mut slot.state) { + Some(State::Opening { size, .. }) => { + *size = (cols, rows); + None + } + Some(State::Running { console, .. }) => Some(console.clone()), + None => None, + }); + if let Some(c) = console { + c.resize(cols, rows); + } } "close" => { if let Some(s) = with(|s| s.remove(id)) { @@ -109,11 +123,45 @@ pub fn handle(action: &str, id: &str, value: &Value, emit: fn(String)) { /// Closes a session's console, which ends what runs in it, and its shell. fn end(s: Session) { + let State::Running { console, process, .. } = s.state else { return }; + end_running(console, process); +} + +fn start_open(id: &str, value: &Value, emit: fn(String), list_shells: impl FnOnce() -> Vec + Send + 'static) { + let (cols, rows) = termwire::size(value); + let asked = value["shell"].as_str().unwrap_or("").to_owned(); + let seq = NEXT_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if let Some(old) = with(|s| s.insert(id.to_owned(), Session { seq, state: State::Opening { size: (cols, rows), pending: Vec::new() } })) { + end(old); + } + let id = id.to_owned(); + // Listing WSL's distros runs wsl.exe: not on the window's thread. + std::thread::spawn(move || { + let list = list_shells(); + if !live(&id, seq) { + return; + } + // 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 { + if with(|s| s.get(&id).is_some_and(|s| s.seq == seq) && s.remove(&id).is_some()) { + emit(termwire::exit(&id, None, Some("No shell found"))); + } + return; + }; + if let Err(e) = open(&id, seq, &command_line(&shell.id), emit) + && with(|s| s.get(&id).is_some_and(|s| s.seq == seq) && s.remove(&id).is_some()) + { + emit(termwire::exit(&id, None, Some(&e.to_string()))); + } + }); +} + +fn end_running(console: Arc, process: Arc) { // 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) }; + console.close(); + // SAFETY: the process handle is open while process holds it. + unsafe { TerminateProcess(process.as_raw_handle() as HANDLE, 1) }; }); } @@ -264,10 +312,13 @@ fn pipe() -> std::io::Result<(OwnedHandle, OwnedHandle)> { } } -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); - } +fn open(id: &str, seq: u64, command: &str, emit: fn(String)) -> std::io::Result<()> { + let Some((cols, rows)) = with(|s| match s.get(id) { + Some(Session { seq: cur, state: State::Opening { size, .. } }) if *cur == seq => Some(*size), + _ => None, + }) else { + return Ok(()); + }; // 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()?; @@ -289,7 +340,25 @@ fn open(id: &str, command: &str, cols: u16, rows: u16, emit: fn(String)) -> std: }; let (input, typed) = channel::>(); - with(|s| s.insert(id.to_owned(), Session { console: console.clone(), process: process.clone(), input })); + let attached = with(|s| { + let slot = s.get_mut(id).filter(|slot| slot.seq == seq)?; + let (latest_size, pending) = match &mut slot.state { + State::Opening { size, pending } => (*size, std::mem::take(pending)), + _ => ((cols, rows), Vec::new()), + }; + for bytes in pending { + let _ = input.send(bytes); + } + slot.state = State::Running { console: console.clone(), process: process.clone(), input }; + Some(latest_size) + }); + let Some(latest_size) = attached else { + end_running(console, process); + return Ok(()); + }; + if latest_size != (cols, rows) { + console.resize(latest_size.0, latest_size.1); + } let mut writer = File::from(typed_w); std::thread::spawn(move || { @@ -324,12 +393,13 @@ fn open(id: &str, command: &str, cols: u16, rows: u16, emit: fn(String)) -> std: loop { match screen.read(&mut buf) { Ok(0) | Err(_) => break, - Ok(n) => emit(termwire::data(&id, &buf[..n])), + Ok(n) if live(&id, seq) => emit(termwire::data(&id, &buf[..n])), + Ok(_) => break, } } let _ = waiter.join(); let mine = with(|s| { - let mine = s.get(&id).is_some_and(|s| Arc::ptr_eq(&s.process, &process)); + let mine = s.get(&id).is_some_and(|s| s.seq == seq); if mine { s.remove(&id); } @@ -520,8 +590,9 @@ mod tests { 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", ">"); + // cmd's banner: its prompt is the user's own (Clink's AutoRun draws `❯`, not `>`), + // and what is typed before it shows waits in the console's input. + output_until(&rx, "w1", "Microsoft Corporation"); typed("set /a 40+2 & echo. & echo DONE\r"); let (out, _) = output_until(&rx, "w1", "DONE"); assert!(out.contains("42"), "{out}"); @@ -537,4 +608,58 @@ mod tests { assert!(!list.iter().any(|s| s.id.to_ascii_lowercase().starts_with("wsl:kiri"))); assert!(command_line("wsl:Ubuntu").ends_with("-d Ubuntu --cd ~")); } + + #[test] + fn closing_or_replacing_a_shell_while_it_opens_drops_the_stale_open() { + let (tx, rx) = channel(); + EVENTS.lock().unwrap().push(tx); + let cmd_shell = || vec![Shell { id: "cmd".into(), label: "Command Prompt".into(), group: "" }]; + + // 1. Open -> close while shells() is still running -> release stale open -> no shell spawned. + let (entered1, entered1_rx) = channel(); + let (release1, release1_rx) = channel(); + let (done1, done1_rx) = channel(); + start_open("w2", &serde_json::json!({"shell": "cmd", "cols": 80, "rows": 20}), record, move || { + entered1.send(()).unwrap(); + release1_rx.recv().unwrap(); + let list = cmd_shell(); + let _ = done1.send(()); + list + }); + entered1_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + handle("close", "w2", &serde_json::json!({}), record); + release1.send(()).unwrap(); + done1_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + + // 2. Stale open#1 finishing after newer open#2 must not replace open#2; early input while opening arrives. + let (entered_a, entered_a_rx) = channel(); + let (release_a, release_a_rx) = channel(); + start_open("w3", &serde_json::json!({"shell": "cmd", "cols": 80, "rows": 20}), record, move || { + entered_a.send(()).unwrap(); + release_a_rx.recv().unwrap(); + cmd_shell() + }); + entered_a_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + + let (entered_b, entered_b_rx) = channel(); + let (release_b, release_b_rx) = channel(); + start_open("w3", &serde_json::json!({"shell": "cmd", "cols": 100, "rows": 25}), record, move || { + entered_b.send(()).unwrap(); + release_b_rx.recv().unwrap(); + cmd_shell() + }); + entered_b_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + handle("input", "w3", &Value::String(termwire::b64(b"echo EARLY_OK\r")), record); + release_b.send(()).unwrap(); + output_until(&rx, "w3", "EARLY_OK"); + + // Now release stale open#1 and verify open#2 still answers on w3. + release_a.send(()).unwrap(); + handle("input", "w3", &Value::String(termwire::b64(b"set /a 19+23 & echo KEPT_W3\r")), record); + let (out, _) = output_until(&rx, "w3", "KEPT_W3"); + assert!(out.contains("42"), "{out}"); + handle("close", "w3", &serde_json::json!({}), record); + + assert!(!with(|s| s.contains_key("w2")), "closed pending w2 must not remain in SESSIONS"); + } } diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rs index d8d7f2acb..0cb3aea50 100644 --- a/crates/kiri-win/src/update.rs +++ b/crates/kiri-win/src/update.rs @@ -66,8 +66,27 @@ pub struct Release { pub size: u64, } -/// `1.2.10` > `1.2.9`; a missing part counts as 0. +/// Whether `v` reads as a version: `[v]N(.N)*`, optionally `-` and +/// dot-separated alphanumeric identifiers (`0.1.8-dev.42`). +fn is_version(v: &str) -> bool { + let s = v.strip_prefix('v').unwrap_or(v); + let (core, pre) = match s.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (s, None), + }; + let numeric = |seg: &str| !seg.is_empty() && seg.bytes().all(|b| b.is_ascii_digit()); + let ident = |id: &str| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'); + core.split('.').all(numeric) && pre.is_none_or(|p| p.split('.').all(ident)) +} + +/// `1.2.10` > `1.2.9`; a missing part counts as 0, and a test build +/// (`0.1.8-dev.42`, scripts/ci/test-version.sh) sorts above its release. +/// A string that isn't a version is never newer, and nothing is newer +/// than one. pub fn newer(candidate: &str, current: &str) -> bool { + if !is_version(candidate) || !is_version(current) { + return false; + } let parts = |v: &str| -> Vec { v.trim_start_matches('v').split(['.', '-']).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(candidate), parts(current)); for i in 0..a.len().max(b.len()) { @@ -169,6 +188,7 @@ fn fetch_and_check(release: &Release, dir: &Path, progress: &mut dyn FnMut(u64, loop { if cancel.load(Ordering::Relaxed) { let _ = child.kill(); + let _ = child.wait(); return Err(io::Error::new(io::ErrorKind::Interrupted, "cancelled")); } let got = std::fs::metadata(&part).map_or(0, |m| m.len()); @@ -207,10 +227,15 @@ fn staged_msi(version: &str) -> PathBuf { stage_dir().join(format!("Kiri-{version}.msi")) } +fn staged_in(dir: &Path) -> Option { + let raw = std::fs::read_to_string(dir.join("version")).ok()?; + let version = raw.trim().strip_prefix('v').unwrap_or(raw.trim()).to_owned(); + (is_version(&version) && dir.join(format!("Kiri-{version}.msi")).is_file() && newer(&version, CURRENT)).then_some(version) +} + /// The staged update's version, when there is one newer than this build. pub fn staged() -> Option { - let version = std::fs::read_to_string(stage_dir().join("version")).ok()?.trim().to_owned(); - (staged_msi(&version).is_file() && newer(&version, CURRENT)).then_some(version) + staged_in(&stage_dir()) } /// The staged MSI, checked again (it sat on disk since the download). @@ -290,6 +315,9 @@ pub fn restart_engine() -> io::Result<()> { std::os::windows::process::CommandExt::creation_flags(&mut cmd, CREATE_NO_WINDOW); let out = output_within(cmd.args(crate::wslsync::wsl_sh(&distro, &script)), RESTART_LIMIT)?; if !out.status.success() { + if let Some(ro) = crate::engine::probe_wsl_readonly(Some(&distro)) { + return Err(io::Error::other(ro)); + } return Err(io::Error::other(first_line(&out.stderr, "the engine did not restart"))); } // Done only when the engine answers as this version: a restart that @@ -592,6 +620,9 @@ pub fn sync_engine() -> io::Result { std::os::windows::process::CommandExt::creation_flags(&mut cmd, CREATE_NO_WINDOW); let out = output_within(cmd.args(crate::wslsync::wsl_sh(&distro, &script)), WSL_LIMIT)?; if !out.status.success() { + if let Some(ro) = crate::engine::probe_wsl_readonly(Some(&distro)) { + return Err(io::Error::other(ro)); + } return Err(io::Error::other(first_line(&out.stderr, "could not copy the engine into WSL"))); } Ok(String::from_utf8_lossy(&out.stdout).contains("copied")) @@ -617,6 +648,17 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result>| { + std::thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(mut r) = pipe { + let _ = r.read_to_end(&mut buf); + } + buf + }) + }; + let out_reader = drain(child.stdout.take().map(|s| Box::new(s) as Box)); + let err_reader = drain(child.stderr.take().map(|s| Box::new(s) as Box)); let ms = u32::try_from(limit.as_millis()).unwrap_or(u32::MAX - 1); // SAFETY: waits on the child's own process handle, open while `child` lives. let waited = unsafe { windows_sys::Win32::System::Threading::WaitForSingleObject(child.as_raw_handle() as _, ms) }; @@ -626,15 +668,23 @@ pub(crate) fn output_within(cmd: &mut Command, limit: Duration) -> io::Result Option { - crate::client::request("GET", "/version", None).ok().filter(|r| r.ok()).and_then(|r| crate::client::kiri_version(&r.json()).map(str::to_owned)) + if crate::serve::is_stopped() { + return None; + } + crate::client::get_background("/version").ok().and_then(|v| crate::client::kiri_version(&v).map(str::to_owned)) } static CATCH_UP: crate::wslsync::CatchUp = crate::wslsync::CatchUp::new(); @@ -676,6 +726,7 @@ fn restart_and_report() { } Err(e) => { crate::serve::log(&format!("engine: did not restart ({e})")); + emit(json!({"type": "enginerestarted", "error": e.to_string()}).to_string()); emit(notice("error", &trf("Could not restart the engine: {error}", &[("error", &e)]))); if let Some(v) = engine_version() && newer(CURRENT, &v) @@ -696,8 +747,40 @@ mod tests { assert!(newer("0.2.0", "0.1.9")); assert!(newer("1.2.10", "1.2.9")); assert!(newer("v1.0.1", "1.0")); + assert!(!newer("1.0.0", "1.0")); assert!(!newer("0.1.0", "0.1.0")); assert!(!newer("0.1.0", "0.2.0")); + // A test build (scripts/ci/test-version.sh) sorts above its release. + assert!(newer("0.1.8-dev.42", "0.1.8")); + assert!(!newer("0.1.8", "0.1.8-dev.42")); + assert!(newer("0.1.8-dev.43", "0.1.8-dev.42")); + for bad in ["", "vv1.0.0", "1.+2.0", "1.2.", "1.2.0-", "1.2.0-rc..1", "99.0.0/../../evil", r"99.0.0\evil", "99.0.0:ads"] { + assert!(!newer(bad, "0.2.0"), "accepted invalid candidate {bad:?}"); + assert!(!newer("99.0.0", bad), "accepted invalid current {bad:?}"); + } + } + + #[test] + fn staged_rejects_traversal_and_output_within_drains_large_pipes() { + let tmp = std::env::temp_dir().join(format!("kiri-win-update-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&tmp); + let stage = tmp.join("Kiri").join("update"); + std::fs::create_dir_all(&stage).unwrap(); + std::fs::write(tmp.join("evil.msi"), b"fake").unwrap(); + std::fs::write(stage.join("version"), "99.0.0/../../../evil").unwrap(); + assert_eq!(super::staged_in(&stage), None); + + std::fs::write(stage.join("Kiri-99.1.2.msi"), b"msi").unwrap(); + std::fs::write(stage.join("version"), "v99.1.2\n").unwrap(); + assert_eq!(super::staged_in(&stage).as_deref(), Some("99.1.2")); + let _ = std::fs::remove_dir_all(&tmp); + + let mut cmd = crate::win::tool("powershell.exe"); + cmd.args(["-NoProfile", "-NonInteractive", "-Command", "[Console]::Out.Write('A' * 131072); [Console]::Error.Write('B' * 131072)"]); + let out = super::output_within(&mut cmd, std::time::Duration::from_secs(15)).unwrap(); + assert!(out.status.success()); + assert_eq!(out.stdout.len(), 131_072); + assert_eq!(out.stderr.len(), 131_072); } #[test] diff --git a/crates/kiri-win/src/watch.rs b/crates/kiri-win/src/watch.rs new file mode 100644 index 000000000..54652cc06 --- /dev/null +++ b/crates/kiri-win/src/watch.rs @@ -0,0 +1,891 @@ +//! Opt-in Windows bind-mount watcher for WSL 2 (`C:\...` -> `/mnt/c/...`). +//! +//! WSL 2 mounts Windows drives over 9P (`drvfs`), and Microsoft's kernel does +//! not forward Windows file-change notifications into Linux inotify. When the +//! user opts in (`%LOCALAPPDATA%\Kiri\settings.json` with +//! `{"watchBindMounts": true}`, or `KIRI_WIN_WATCH_BINDS=1`), this watches +//! active `/mnt//...` bind sources of running containers using +//! kernel-blocking `ReadDirectoryChangesW` (0% CPU when idle), debounces +//! changes over 50 ms in batches of at most 512, and posts `OP\t/mnt/...` +//! lines to `POST /kiri/fs-events` so `kiri-init` raises real Linux VFS +//! inotify events. As it starts and stops watching a root it posts +//! `P\t/mnt/...` and `U\t/mnt/...`: `kiri-init` holds the root's directories +//! open meanwhile, without which no inotify watch on `drvfs` hears of +//! anything (a watcher started before that misses changes until it restarts). +//! +//! When opt-in is OFF (the default): zero threads, zero directory handles, +//! and zero polling. + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::collections::{HashMap, HashSet}; +use std::io; +use std::path::PathBuf; + +use serde_json::{Value, json}; + +/// At most this many coalesced lines per `POST /kiri/fs-events` request. +pub const BATCH: usize = 512; +/// Debounce window before flushing a burst of Windows file-change events. +#[cfg(windows)] +const DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(50); +/// Maximum raw events buffered during one debounce window. +#[cfg(windows)] +const MAX_BURST: usize = 4096; +/// Fallback rescan interval when the watcher is active (container events also +/// wake it immediately). +#[cfg(windows)] +const RESCAN_FALLBACK: std::time::Duration = std::time::Duration::from_secs(5); + +/// `%LOCALAPPDATA%\Kiri\settings.json`. +fn settings_path() -> Option { + std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Kiri").join("settings.json")) +} + +/// Parses an environment flag (`KIRI_WIN_WATCH_BINDS`). +fn parse_env_bool(val: &str) -> Option { + match val.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + } +} + +/// Resolves whether bind-mount watching is enabled from `settings.json` text +/// and the optional `KIRI_WIN_WATCH_BINDS` override. Off by default. +pub fn parse_settings_enabled(settings_json: Option<&str>, env_override: Option<&str>) -> bool { + if let Some(b) = env_override.and_then(parse_env_bool) { + return b; + } + settings_json + .and_then(|s| serde_json::from_str::(s).ok()) + .and_then(|v| v.get("watchBindMounts")?.as_bool()) + .unwrap_or(false) +} + +/// Whether bind-mount watching is currently enabled (env override or +/// `%LOCALAPPDATA%\Kiri\settings.json`). Off by default. +pub fn is_enabled() -> bool { + let env = std::env::var("KIRI_WIN_WATCH_BINDS").ok(); + let text = settings_path().and_then(|p| std::fs::read_to_string(p).ok()); + parse_settings_enabled(text.as_deref(), env.as_deref()) +} + +/// Persists `watchBindMounts` into `%LOCALAPPDATA%\Kiri\settings.json` while +/// preserving any other keys in that file. +pub fn save_enabled(enabled: bool) -> io::Result<()> { + let Some(path) = settings_path() else { + return Err(io::Error::other("LOCALAPPDATA is not set")); + }; + let mut obj: Value = std::fs::read_to_string(&path) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .filter(Value::is_object) + .unwrap_or_else(|| json!({})); + obj["watchBindMounts"] = json!(enabled); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, obj.to_string())?; + std::fs::rename(&tmp, &path) +} + +/// Translates a WSL automount path (`/mnt/c/Users/me/app`) to a Windows path +/// (`C:\Users\me\app`). Rejects paths outside `automount_root`, non-drive +/// entries (like `/mnt/mac/...`), control characters, and `..` traversal. +pub fn wsl_to_windows(wsl_path: &str, automount_root: &str) -> Option { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return None; + } + if wsl_path.contains(['\n', '\r', '\0', '\t']) { + return None; + } + let rest = wsl_path.strip_prefix(automount_root)?; + let bytes = rest.as_bytes(); + if bytes.is_empty() || !bytes[0].is_ascii_alphabetic() { + return None; + } + let drive = (bytes[0] as char).to_ascii_uppercase(); + if bytes.len() == 1 { + return Some(format!("{drive}:\\")); + } + if bytes[1] != b'/' { + return None; + } + let mut parts = Vec::new(); + for part in rest[2..].split('/') { + if part.is_empty() { + continue; + } + if part == "." || part == ".." || part.contains(['\\', ':']) { + return None; + } + parts.push(part); + } + if parts.is_empty() { + Some(format!("{drive}:\\")) + } else { + Some(format!("{drive}:\\{}", parts.join("\\"))) + } +} + +/// Translates a watched Windows root (`C:\Users\me\app`) plus a relative path +/// from `ReadDirectoryChangesW` (`src\main.js`) back to a WSL automount path +/// (`/mnt/c/Users/me/app/src/main.js`). Rejects `..`, `.`, control characters, +/// NTFS Alternate Data Streams (`:`), or malformed roots. +pub fn windows_to_wsl(win_root: &str, rel_win: &str, automount_root: &str) -> Option { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return None; + } + if win_root.contains(['\n', '\r', '\0', '\t']) || rel_win.contains(['\n', '\r', '\0', '\t']) { + return None; + } + let b = win_root.as_bytes(); + if b.len() < 3 || !b[0].is_ascii_alphabetic() || b[1] != b':' || (b[2] != b'\\' && b[2] != b'/') { + return None; + } + let drive = (b[0] as char).to_ascii_lowercase(); + let mut comps: Vec<&str> = Vec::new(); + for part in win_root[3..].split(['\\', '/']) { + if part.is_empty() { + continue; + } + if part == "." || part == ".." || part.contains(':') { + return None; + } + comps.push(part); + } + let mut rel_count = 0usize; + for part in rel_win.split(['\\', '/']) { + if part.is_empty() { + continue; + } + if part == "." || part == ".." || part.contains(':') { + return None; + } + comps.push(part); + rel_count += 1; + } + if rel_count == 0 { + return None; + } + Some(format!("{automount_root}{drive}/{}", comps.join("/"))) +} + +/// Whether a relative path belongs to high-volume `.git` internals (object +/// store, reflogs, lockfiles) that cause event storms during git operations. +pub fn is_git_storm_path(rel: &str) -> bool { + let parts: Vec<&str> = rel.split(['\\', '/']).filter(|p| !p.is_empty()).collect(); + for i in 0..parts.len() { + if parts[i].eq_ignore_ascii_case(".git") + && let Some(next) = parts.get(i + 1) + && (next.eq_ignore_ascii_case("objects") || next.eq_ignore_ascii_case("logs") || next.to_ascii_lowercase().ends_with(".lock")) + { + return true; + } + } + false +} + +/// Decodes a Win32 `FILE_NOTIFY_INFORMATION` buffer (UTF-16LE filenames) into +/// `(op, relative_path)` pairs: +/// - `FILE_ACTION_ADDED (1)` -> `'C'` +/// - `FILE_ACTION_REMOVED (2)` / `FILE_ACTION_RENAMED_OLD_NAME (4)` -> `'D'` +/// - `FILE_ACTION_MODIFIED (3)` / `FILE_ACTION_RENAMED_NEW_NAME (5)` -> `'M'` +pub fn decode_notify_buffer(buf: &[u8]) -> Vec<(char, String)> { + const ACTION_ADDED: u32 = 1; + const ACTION_REMOVED: u32 = 2; + const ACTION_MODIFIED: u32 = 3; + const ACTION_RENAMED_OLD: u32 = 4; + const ACTION_RENAMED_NEW: u32 = 5; + + let mut out = Vec::new(); + let mut offset = 0usize; + while offset + 12 <= buf.len() { + let next_offset = u32::from_le_bytes([buf[offset], buf[offset + 1], buf[offset + 2], buf[offset + 3]]) as usize; + let action = u32::from_le_bytes([buf[offset + 4], buf[offset + 5], buf[offset + 6], buf[offset + 7]]); + let name_bytes = u32::from_le_bytes([buf[offset + 8], buf[offset + 9], buf[offset + 10], buf[offset + 11]]) as usize; + let name_start = offset + 12; + let Some(name_end) = name_start.checked_add(name_bytes) else { break }; + if name_end > buf.len() || !name_bytes.is_multiple_of(2) { + break; + } + let op = match action { + ACTION_ADDED => Some('C'), + ACTION_REMOVED | ACTION_RENAMED_OLD => Some('D'), + ACTION_MODIFIED | ACTION_RENAMED_NEW => Some('M'), + _ => None, + }; + if let Some(op) = op && name_bytes > 0 { + let units: Vec = buf[name_start..name_end].as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect(); + let name = String::from_utf16_lossy(&units); + if !name.is_empty() && !name.contains('\0') { + out.push((op, name)); + } + } + if next_offset == 0 { + break; + } + let Some(next) = offset.checked_add(next_offset) else { break }; + if next <= offset || next > buf.len() { + break; + } + offset = next; + } + out +} + +/// Merges two ops for the same path arriving within one 50 ms debounce window. +fn merge_op(prev: char, next: char) -> char { + match (prev, next) { + (_, 'D') | ('D', 'A') => 'D', + ('C', 'M') | ('M', 'C') | ('C', 'C') | ('C', 'A') | ('A', 'C') => 'C', + ('D', 'C') | ('D', 'M') | ('M', 'M') | ('M', 'A') | ('A', 'M') => 'M', + _ => next, + } +} + +/// Coalesces duplicate/burst events within a batch, preserving arrival order +/// and emitting at most one change line per distinct path. A root's pin +/// (`P`) or unpin (`U`) is kept apart from changes to the same path; the +/// later of the two wins. +pub fn coalesce_events(events: &[(char, String)]) -> Vec { + let mut order: Vec<(bool, String)> = Vec::new(); + let mut ops: HashMap<(bool, String), char> = HashMap::new(); + for (op, path) in events { + if !matches!(op, 'C' | 'M' | 'A' | 'D' | 'P' | 'U') || path.is_empty() { + continue; + } + let key = (matches!(op, 'P' | 'U'), path.clone()); + if let Some(existing) = ops.get_mut(&key) { + *existing = if key.0 { *op } else { merge_op(*existing, *op) }; + } else { + ops.insert(key.clone(), *op); + order.push(key); + } + } + order.into_iter().filter_map(|k| ops.get(&k).map(|op| format!("{op}\t{}", k.1))).collect() +} + +/// The WSL path of a watched Windows directory (`C:\Users\me\app` -> +/// `/mnt/c/Users/me/app`), for its `P` and `U` lines. None for a drive root. +fn wsl_dir(win_dir: &str, automount_root: &str) -> Option { + let (parent, name) = win_dir.trim_end_matches('\\').rsplit_once('\\')?; + let parent = if parent.len() == 2 { format!("{parent}\\") } else { parent.to_owned() }; + windows_to_wsl(&parent, name, automount_root) +} + +/// A Windows directory watch specification: either a recursive directory tree +/// or a single-file mount watched non-recursively via its parent directory. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +struct WatchSpec { + /// Directory opened with `CreateFileW` (`C:\Users\me\app`). + dir: String, + /// `true` for a directory bind mount, `false` for a single-file mount. + recursive: bool, + /// When `recursive == false`, only match this exact filename (case-insensitive). + only_file: Option, +} + +/// Removes directory specs already covered by a parent recursive directory watch. +fn collapse_specs(specs: Vec) -> Vec { + let mut dirs: Vec = specs.iter().filter(|s| s.recursive).map(|s| s.dir.clone()).collect(); + dirs.sort_by_key(|d| d.len()); + dirs.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); + + let covered_by_dir = |path: &str, exclude_self: bool| -> bool { + dirs.iter().any(|parent| { + if exclude_self && parent.eq_ignore_ascii_case(path) { + return false; + } + if path.len() < parent.len() { + return false; + } + let head = &path[..parent.len()]; + if !head.eq_ignore_ascii_case(parent) { + return false; + } + let rest = &path[parent.len()..]; + parent.ends_with('\\') || rest.is_empty() || rest.starts_with('\\') + }) + }; + + let mut seen: HashSet = HashSet::new(); + let mut out = Vec::new(); + for s in specs { + if s.recursive { + if covered_by_dir(&s.dir, true) { + continue; + } + let key = format!("d:{}", s.dir.to_ascii_lowercase()); + if seen.insert(key) { + out.push(s); + } + } else { + let full = match &s.only_file { + Some(f) if s.dir.ends_with('\\') => format!("{}{f}", s.dir), + Some(f) => format!("{}\\{f}", s.dir), + None => s.dir.clone(), + }; + if covered_by_dir(&full, false) { + continue; + } + let key = format!("f:{}", full.to_ascii_lowercase()); + if seen.insert(key) { + out.push(s); + } + } + } + out +} + +#[cfg(windows)] +mod runtime { + use super::*; + use std::ffi::OsStr; + use std::os::windows::ffi::OsStrExt; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::{Arc, Condvar, Mutex, PoisonError, mpsc}; + use std::thread::JoinHandle; + use std::time::{Duration, Instant}; + + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE, WAIT_OBJECT_0}; + use windows_sys::Win32::Storage::FileSystem::{ + CreateFileW, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OVERLAPPED, FILE_LIST_DIRECTORY, FILE_NOTIFY_CHANGE_DIR_NAME, FILE_NOTIFY_CHANGE_FILE_NAME, + FILE_NOTIFY_CHANGE_LAST_WRITE, FILE_NOTIFY_CHANGE_SIZE, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING, ReadDirectoryChangesW, + }; + use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED}; + use windows_sys::Win32::System::Threading::{CreateEventW, INFINITE, SetEvent, WaitForMultipleObjects}; + + const NOTIFY_FILTER: u32 = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_SIZE; + + struct Coordinator { + stop: Arc, + wake: Arc<(Mutex, Condvar)>, + thread: Option>, + } + + static STATE: Mutex> = Mutex::new(None); + + /// Starts the watcher ONLY if opt-in is enabled. When disabled (the + /// default), spawns zero threads and opens zero handles. + pub fn start_if_enabled() { + if is_enabled() { + set_enabled(true); + } + } + + /// Starts or stops the watcher dynamically. Turning it off cancels all + /// `ReadDirectoryChangesW` calls, closes every handle, and stops all + /// watcher threads. + pub fn set_enabled(enabled: bool) { + let mut guard = STATE.lock().unwrap_or_else(PoisonError::into_inner); + if enabled { + if guard.is_some() { + return; + } + let stop = Arc::new(AtomicBool::new(false)); + let wake = Arc::new((Mutex::new(false), Condvar::new())); + let stop_c = stop.clone(); + let wake_c = wake.clone(); + let thread = std::thread::Builder::new().name("kiri-win-watch".into()).spawn(move || coordinate(stop_c, wake_c)).ok(); + if thread.is_some() { + *guard = Some(Coordinator { stop, wake, thread }); + } + } else if let Some(mut coord) = guard.take() { + coord.stop.store(true, Ordering::SeqCst); + { + let (m, cv) = &*coord.wake; + *m.lock().unwrap_or_else(PoisonError::into_inner) = true; + cv.notify_all(); + } + drop(guard); + if let Some(t) = coord.thread.take() { + let _ = t.join(); + } + } + } + + /// Wakes the coordinator when running containers change. No-op when off. + pub fn notify_containers_changed() { + let guard = STATE.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(coord) = guard.as_ref() { + let (m, cv) = &*coord.wake; + *m.lock().unwrap_or_else(PoisonError::into_inner) = true; + cv.notify_all(); + } + } + + pub(super) struct DirWatcher { + /// Manual-reset event: once set, the worker's wait returns at once, + /// whether it is waiting already or not yet. + stop: HANDLE, + thread: Option>, + /// Whether `watch_dir_loop` opened the directory and emitted `P`. + pinned: Arc, + /// The root's WSL path and the channel its `U` line goes out on. + unpin: Option<(String, mpsc::Sender<(char, String)>)>, + } + + impl DirWatcher { + pub(super) fn start(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>) -> Option { + // SAFETY: an unnamed manual-reset event, initially not set. + let stop = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; + if stop == 0 { + return None; + } + let pin = if spec.recursive { wsl_dir(&spec.dir, &automount_root) } else { None }; + let pinned = Arc::new(AtomicBool::new(false)); + let pinned_w = pinned.clone(); + let pin_w = pin.clone(); + let tx_c = tx.clone(); + let thread = + std::thread::Builder::new().name("kiri-win-dirwatch".into()).spawn(move || watch_dir_loop(spec, automount_root, tx_c, stop, pin_w, pinned_w)); + let Ok(thread) = thread else { + // SAFETY: our own event, never shared. + unsafe { CloseHandle(stop) }; + return None; + }; + Some(DirWatcher { stop, thread: Some(thread), pinned, unpin: pin.map(|root| (root, tx)) }) + } + + pub(super) fn stop(mut self) { + // SAFETY: `self.stop` stays open until after the join below. + unsafe { SetEvent(self.stop) }; + if let Some(t) = self.thread.take() { + let _ = t.join(); + } + // SAFETY: the worker has exited; nothing else uses the event. + unsafe { CloseHandle(self.stop) }; + if self.pinned.load(Ordering::Acquire) + && let Some((root, tx)) = self.unpin.take() + { + let _ = tx.send(('U', root)); + } + } + } + + /// Reads changes with overlapped `ReadDirectoryChangesW`, waiting on the + /// read and `stop` together, so a stop ends the wait at once. + fn watch_dir_loop(spec: WatchSpec, automount_root: String, tx: mpsc::Sender<(char, String)>, stop: HANDLE, pin: Option, pinned: Arc) { + let wide: Vec = OsStr::new(&spec.dir).encode_wide().chain(std::iter::once(0)).collect(); + // SAFETY: valid NUL-terminated UTF-16 path with standard directory flags. + let h = unsafe { + CreateFileW( + wide.as_ptr(), + FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + std::ptr::null(), + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, + 0, + ) + }; + if h == INVALID_HANDLE_VALUE || h == 0 { + return; + } + // SAFETY: an unnamed manual-reset event, initially not set. + let io = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) }; + if io == 0 { + // SAFETY: our own handle. + unsafe { CloseHandle(h) }; + return; + } + if let Some(root) = &pin { + if tx.send(('P', root.clone())).is_err() { + // SAFETY: closing our own handles before any read is started. + unsafe { + CloseHandle(io); + CloseHandle(h); + } + return; + } + pinned.store(true, Ordering::Release); + } + + // 64 KiB DWORD-aligned buffer as required by ReadDirectoryChangesW. + let mut buf = vec![0u32; 16384]; + let buf_len = (buf.len() * std::mem::size_of::()) as u32; + let subtree = i32::from(spec.recursive); + + loop { + // SAFETY: zeroed OVERLAPPED is valid; its event is ours. + let mut ov: OVERLAPPED = unsafe { std::mem::zeroed() }; + ov.hEvent = io; + // SAFETY: `h`, `buf` and `ov` outlive the read: every path out of + // this iteration waits for it to complete or be cancelled. + let ok = unsafe { ReadDirectoryChangesW(h, buf.as_mut_ptr().cast(), buf_len, subtree, NOTIFY_FILTER, std::ptr::null_mut(), &mut ov, None) }; + if ok == 0 { + break; + } + let waits = [io, stop]; + // SAFETY: two valid event handles. + let woke = unsafe { WaitForMultipleObjects(2, waits.as_ptr(), 0, INFINITE) }; + let mut returned: u32 = 0; + if woke != WAIT_OBJECT_0 { + // Stopped (or the wait failed): cancel the read and wait for it + // to finish before `buf` and `ov` go away. + // SAFETY: `h` and `ov` are the pending read's. + unsafe { + CancelIoEx(h, &ov); + GetOverlappedResult(h, &ov, &mut returned, 1); + } + break; + } + // SAFETY: the read completed; `ov` is its OVERLAPPED. + if unsafe { GetOverlappedResult(h, &ov, &mut returned, 0) } == 0 { + break; + } + let n = (returned as usize).min(buf_len as usize); + // SAFETY: `buf` holds `n` initialized bytes written by Windows. + let bytes = unsafe { std::slice::from_raw_parts(buf.as_ptr().cast::(), n) }; + for (op, rel) in decode_notify_buffer(bytes) { + if let Some(only) = &spec.only_file + && !rel.eq_ignore_ascii_case(only) + { + continue; + } + if is_git_storm_path(&rel) { + continue; + } + let Some(wsl_path) = windows_to_wsl(&spec.dir, &rel, &automount_root) else { continue }; + if tx.send((op, wsl_path)).is_err() { + break; + } + } + } + + // SAFETY: closing our own handles; no read is pending. + unsafe { + CloseHandle(io); + CloseHandle(h); + } + } + + fn flush_loop(rx: mpsc::Receiver<(char, String)>) { + while let Ok(first) = rx.recv() { + let mut batch = vec![first]; + let deadline = Instant::now() + DEBOUNCE; + while batch.len() < MAX_BURST { + let Some(rem) = deadline.checked_duration_since(Instant::now()) else { break }; + match rx.recv_timeout(rem) { + Ok(ev) => batch.push(ev), + Err(mpsc::RecvTimeoutError::Timeout) => break, + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + if crate::serve::is_stopped() { + continue; + } + let lines = coalesce_events(&batch); + for chunk in lines.chunks(BATCH) { + if crate::serve::is_stopped() { + break; + } + let body = json!({"events": chunk}); + let _ = crate::client::request_within("POST", "/kiri/fs-events", Some(&body), true, Some(Duration::from_secs(3))); + } + } + } + + fn desired_watches() -> Option<(String, Vec)> { + if crate::serve::is_stopped() { + return None; + } + let resp = crate::client::get_quick("/kiri/watch-roots").ok()?; + let root = resp["automount_root"].as_str().unwrap_or("/mnt/").to_owned(); + let mut specs = Vec::new(); + for wsl in resp["roots"].as_array().into_iter().flatten().filter_map(Value::as_str) { + let Some(win) = wsl_to_windows(wsl, &root) else { continue }; + let p = std::path::Path::new(&win); + if p.is_dir() { + specs.push(WatchSpec { dir: win, recursive: true, only_file: None }); + } else if p.is_file() + && let (Some(parent), Some(name)) = (p.parent(), p.file_name()) + { + specs.push(WatchSpec { + dir: parent.to_string_lossy().into_owned(), + recursive: false, + only_file: Some(name.to_string_lossy().into_owned()), + }); + } + } + Some((root, collapse_specs(specs))) + } + + fn coordinate(stop: Arc, wake: Arc<(Mutex, Condvar)>) { + let (tx, rx) = mpsc::channel::<(char, String)>(); + let sender = std::thread::Builder::new().name("kiri-win-watch-tx".into()).spawn(move || flush_loop(rx)).ok(); + let mut active: HashMap = HashMap::new(); + let mut last_root = String::from("/mnt/"); + + while !stop.load(Ordering::SeqCst) { + if crate::serve::is_stopped() { + for (_, w) in active.drain() { + w.stop(); + } + } else if let Some((root, want)) = desired_watches() { + let root_changed = root != last_root; + last_root = root.clone(); + let want_set: HashSet = want.iter().cloned().collect(); + let remove: Vec = active.keys().filter(|k| root_changed || !want_set.contains(*k)).cloned().collect(); + for k in remove { + if let Some(w) = active.remove(&k) { + w.stop(); + } + } + for spec in want { + if !active.contains_key(&spec) + && let Some(w) = DirWatcher::start(spec.clone(), root.clone(), tx.clone()) + { + active.insert(spec, w); + } + } + } + if stop.load(Ordering::SeqCst) { + break; + } + let (m, cv) = &*wake; + let mut signaled = m.lock().unwrap_or_else(PoisonError::into_inner); + if !*signaled { + let (g, _) = cv.wait_timeout(signaled, RESCAN_FALLBACK).unwrap_or_else(PoisonError::into_inner); + signaled = g; + } + *signaled = false; + } + + for (_, w) in active.drain() { + w.stop(); + } + drop(tx); + if let Some(t) = sender { + let _ = t.join(); + } + } +} + +#[cfg(windows)] +pub use runtime::{notify_containers_changed, set_enabled, start_if_enabled}; + +#[cfg(test)] +mod tests { + use super::*; + + fn encode_notify_entries(entries: &[(u32, &str)]) -> Vec { + let mut buf = Vec::new(); + for (idx, (action, name)) in entries.iter().enumerate() { + let utf16: Vec = name.encode_utf16().collect(); + let name_bytes = utf16.len() * 2; + let raw_len = 12 + name_bytes; + let padded_len = (raw_len + 3) & !3; + let next_offset = if idx + 1 < entries.len() { padded_len as u32 } else { 0u32 }; + buf.extend_from_slice(&next_offset.to_le_bytes()); + buf.extend_from_slice(&action.to_le_bytes()); + buf.extend_from_slice(&(name_bytes as u32).to_le_bytes()); + for u in utf16 { + buf.extend_from_slice(&u.to_le_bytes()); + } + buf.resize(buf.len() + (padded_len - raw_len), 0); + } + buf + } + + #[test] + fn opt_in_is_off_by_default_and_honors_settings_and_env() { + assert!(!parse_settings_enabled(None, None)); + assert!(!parse_settings_enabled(Some("{}"), None)); + assert!(!parse_settings_enabled(Some(r#"{"watchBindMounts": false}"#), None)); + assert!(parse_settings_enabled(Some(r#"{"watchBindMounts": true}"#), None)); + assert!(parse_settings_enabled(None, Some("1"))); + assert!(parse_settings_enabled(Some(r#"{"watchBindMounts": false}"#), Some("true"))); + assert!(!parse_settings_enabled(Some(r#"{"watchBindMounts": true}"#), Some("0"))); + assert!(!parse_settings_enabled(Some("not json"), None)); + } + + #[test] + fn wsl_and_windows_path_mapping_and_traversal_rejection() { + assert_eq!(wsl_to_windows("/mnt/c/Users/me/app", "/mnt/").as_deref(), Some(r"C:\Users\me\app")); + assert_eq!(wsl_to_windows("/mnt/d/My Project/src", "/mnt/").as_deref(), Some(r"D:\My Project\src")); + assert_eq!(wsl_to_windows("/mnt/c", "/mnt/").as_deref(), Some(r"C:\")); + assert_eq!(wsl_to_windows("/windows/e/code", "/windows/").as_deref(), Some(r"E:\code")); + // Reject non-/mnt/, multi-letter mount names, and .. traversal. + assert_eq!(wsl_to_windows("/home/me/app", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/mac/Users/a", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/../etc/passwd", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/Users/../../etc/shadow", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/a\nb", "/mnt/"), None); + + assert_eq!(windows_to_wsl(r"C:\Users\me\app", r"src\main.js", "/mnt/").as_deref(), Some("/mnt/c/Users/me/app/src/main.js")); + assert_eq!(windows_to_wsl(r"C:\", r"test\app.js", "/mnt/").as_deref(), Some("/mnt/c/test/app.js")); + assert_eq!(windows_to_wsl(r"D:\proj", r"sub\file.ts", "/windows/").as_deref(), Some("/windows/d/proj/sub/file.ts")); + assert_eq!(windows_to_wsl(r"C:\Users\me\app", r"..\secret.txt", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"C:\Users\me\app", "", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"\\server\share", r"a.txt", "/mnt/"), None); + } + + #[test] + fn decodes_utf16le_file_notify_information_buffer() { + let buf = encode_notify_entries(&[ + (1, r"src\new.ts"), + (2, r"src\old.ts"), + (3, r"src\app.ts"), + (4, r"src\before.ts"), + (5, r"src\after.ts"), + (3, "src\\caf\u{00e9}.js"), + ]); + assert_eq!( + decode_notify_buffer(&buf), + vec![ + ('C', r"src\new.ts".into()), + ('D', r"src\old.ts".into()), + ('M', r"src\app.ts".into()), + ('D', r"src\before.ts".into()), + ('M', r"src\after.ts".into()), + ('M', "src\\caf\u{00e9}.js".into()), + ] + ); + // Truncated buffer does not panic. + assert!(decode_notify_buffer(&buf[..5]).is_empty()); + assert!(decode_notify_buffer(&[]).is_empty()); + } + + #[test] + fn coalesces_bursts_and_filters_git_object_storms() { + assert!(is_git_storm_path(r".git\objects\ab\123456")); + assert!(is_git_storm_path(r"sub\.git\objects\pack\pack-1.idx")); + assert!(is_git_storm_path(r".git\logs\HEAD")); + assert!(is_git_storm_path(r".git\index.lock")); + assert!(!is_git_storm_path(r".gitignore")); + assert!(!is_git_storm_path(r"src\app.js")); + assert!(!is_git_storm_path(r".git\HEAD")); + + let events = vec![ + ('M', "/mnt/c/app/a.js".into()), + ('M', "/mnt/c/app/a.js".into()), + ('C', "/mnt/c/app/b.js".into()), + ('M', "/mnt/c/app/b.js".into()), + ('D', "/mnt/c/app/c.js".into()), + ('M', "/mnt/c/app/c.js".into()), + ('C', "/mnt/c/app/tmp.js".into()), + ('D', "/mnt/c/app/tmp.js".into()), + ('P', "/mnt/c/app".into()), + ('M', "/mnt/c/app".into()), + ('U', "/mnt/c/app".into()), + ]; + assert_eq!( + coalesce_events(&events), + vec![ + "M\t/mnt/c/app/a.js", + "C\t/mnt/c/app/b.js", + "M\t/mnt/c/app/c.js", + "D\t/mnt/c/app/tmp.js", + "U\t/mnt/c/app", + "M\t/mnt/c/app", + ] + ); + assert_eq!(wsl_dir(r"C:\Users\me\app", "/mnt/").as_deref(), Some("/mnt/c/Users/me/app")); + assert_eq!(wsl_dir(r"D:\proj\", "/mnt/").as_deref(), Some("/mnt/d/proj")); + assert_eq!(wsl_dir(r"C:\", "/mnt/"), None); + } + + #[test] + fn collapses_nested_watch_specs() { + let specs = vec![ + WatchSpec { dir: r"C:\Users\me\app".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me\app\src".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me\app".into(), recursive: false, only_file: Some(".env".into()) }, + WatchSpec { dir: r"C:\Users\me\application".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me".into(), recursive: false, only_file: Some(".env".into()) }, + ]; + let collapsed = collapse_specs(specs); + assert_eq!( + collapsed, + vec![ + WatchSpec { dir: r"C:\Users\me\app".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me\application".into(), recursive: true, only_file: None }, + WatchSpec { dir: r"C:\Users\me".into(), recursive: false, only_file: Some(".env".into()) }, + ] + ); + } + + #[test] + fn preserves_mutations_across_attribute_events_and_rejects_ads_and_tabs() { + let expected_pairs = [ + (('C', 'C'), 'C'), + (('C', 'M'), 'C'), + (('C', 'A'), 'C'), + (('C', 'D'), 'D'), + (('M', 'C'), 'C'), + (('M', 'M'), 'M'), + (('M', 'A'), 'M'), + (('M', 'D'), 'D'), + (('A', 'C'), 'C'), + (('A', 'M'), 'M'), + (('A', 'A'), 'A'), + (('A', 'D'), 'D'), + (('D', 'C'), 'M'), + (('D', 'M'), 'M'), + (('D', 'A'), 'D'), + (('D', 'D'), 'D'), + ]; + for ((first, second), want) in expected_pairs { + assert_eq!(coalesce_events(&[(first, "/mnt/c/app/f.js".into()), (second, "/mnt/c/app/f.js".into())]), vec![format!("{want}\t/mnt/c/app/f.js")]); + } + + assert_eq!(windows_to_wsl(r"C:\Users\me\app", r"assets\logo.png:Zone.Identifier:$DATA", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"C:\Users\bad:ads", r"a.js", "/mnt/"), None); + assert_eq!(windows_to_wsl(r"C:\Users\me\app", "src\\bad\tname.js", "/mnt/"), None); + assert_eq!(windows_to_wsl("C:\\Users\\bad\troot", r"a.js", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/Users/me/bad\tname", "/mnt/"), None); + assert_eq!(wsl_to_windows("/mnt/c/Users/me/file:Zone.Identifier", "/mnt/"), None); + } + + #[cfg(windows)] + #[test] + fn dir_watcher_emits_pin_before_events_and_skips_unopened_roots() { + let (vtx, vrx) = std::sync::mpsc::channel(); + let vanished = WatchSpec { dir: format!(r"C:\kiri-nonexistent-watch-{}", std::process::id()), recursive: true, only_file: None }; + if let Some(w) = runtime::DirWatcher::start(vanished, "/mnt/".into(), vtx) { + w.stop(); + } + assert!(vrx.try_recv().is_err(), "unopened directory must emit neither P nor U"); + + let dir = std::env::temp_dir().join(format!("kiri-win-watch-pin-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let win_dir = dir.to_string_lossy().replace('/', "\\"); + let wsl_root = wsl_dir(&win_dir, "/mnt/").unwrap(); + + let (tx, rx) = std::sync::mpsc::channel(); + let spec = WatchSpec { dir: win_dir, recursive: true, only_file: None }; + let watcher = runtime::DirWatcher::start(spec, "/mnt/".into(), tx).unwrap(); + + let first = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + assert_eq!(first, ('P', wsl_root.clone())); + + let file = dir.join("app.js"); + std::fs::write(&file, b"1\n").unwrap(); + let _ = std::fs::write(format!("{}:Zone.Identifier", file.display()), b"[ZoneTransfer]\r\nZoneId=3\r\n"); + + let want_file = format!("{wsl_root}/app.js"); + let mut saw_file = false; + while !saw_file { + let (op, path) = rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap(); + assert!(!path.contains(":Zone.Identifier"), "ADS event leaked: {path}"); + if path == want_file { + assert!(matches!(op, 'C' | 'M')); + saw_file = true; + } + } + + watcher.stop(); + let mut tail = Vec::new(); + while let Ok(ev) = rx.try_recv() { + assert!(!ev.1.contains(":Zone.Identifier")); + tail.push(ev); + } + assert_eq!(tail.last(), Some(&('U', wsl_root))); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/kiri-win/src/wslconfig.rs b/crates/kiri-win/src/wslconfig.rs index 2adfed17b..0ce3a4aef 100644 --- a/crates/kiri-win/src/wslconfig.rs +++ b/crates/kiri-win/src/wslconfig.rs @@ -15,6 +15,148 @@ fn path() -> Option { std::env::var_os("USERPROFILE").map(|h| PathBuf::from(h).join(".wslconfig")) } +fn integration_path() -> Option { + std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Kiri").join("wsl-integration.json")) +} + +/// Enabled WSL integration distros from `%LOCALAPPDATA%\Kiri\wsl-integration.json` +/// (off by default). +pub fn enabled_distros() -> Vec { + integration_path() + .and_then(|p| std::fs::read(p).ok()) + .map(|b| crate::wslsync::parse_enabled_distros(&b)) + .unwrap_or_default() +} + +fn save_enabled_distros(distros: &[String]) -> io::Result<()> { + let p = integration_path().ok_or_else(|| io::Error::other("LOCALAPPDATA is not set"))?; + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent)?; + } + let tmp = p.with_extension("json.tmp"); + std::fs::write(&tmp, crate::wslsync::encode_enabled_distros(distros))?; + std::fs::rename(&tmp, &p) +} + +/// User WSL distros discovered by `wsl.exe --list --quiet` (excluding `kiri` +/// and `docker-desktop*`). +fn user_distros() -> Vec { + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let Ok(out) = crate::update::output_within(cmd.args(["-l", "-q"]), std::time::Duration::from_secs(15)) else { + return Vec::new(); + }; + if !out.status.success() { + return Vec::new(); + } + crate::wslsync::parse_wsl_distros(&out.stdout, crate::engine::distro().as_deref()) +} + +fn run_distro_script(distro: &str, script: &str) -> io::Result { + let mut cmd = crate::win::tool("wsl.exe"); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + let out = crate::update::output_within( + cmd.args(crate::wslsync::wsl_sh(distro, script)), + crate::update::WSL_LIMIT, + )?; + if !out.status.success() { + let err = crate::wslsync::wsl_text(&out.stderr); + let msg = err.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("WSL command failed"); + return Err(io::Error::other(format!("{distro}: {msg}"))); + } + Ok(crate::wslsync::wsl_text(&out.stdout).trim().to_owned()) +} + +static WSL_SYNC_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +/// Applies the current WSL integration settings to all enabled distros and updates +/// the daemon's per-distro sockets in `/mnt/wsl/kiri/sockets//docker.sock`. +pub fn apply_wsl_integration(disabled: Option<&str>, background: bool) -> io::Result<()> { + if background && crate::serve::is_stopped() { + return Ok(()); + } + let _guard = WSL_SYNC_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let enabled = enabled_distros(); + if enabled.is_empty() && disabled.is_none() { + if background && crate::client::alive_quick() { + if let Ok(v) = crate::client::get_background("/kiri/wsl") + && v["distros"].as_array().is_some_and(|a| !a.is_empty()) + { + let _ = crate::client::request_with("POST", "/kiri/wsl", Some(&json!({"distros": []})), true); + } + } + return Ok(()); + } + if !background { + crate::engine::ensure_daemon()?; + } else if !crate::client::alive_quick() { + return Ok(()); + } + let available = user_distros(); + let mut active = Vec::new(); + let mut first_err: Option = None; + for want in &enabled { + let Some(name) = available.iter().find(|a| a.eq_ignore_ascii_case(want)) else { + continue; + }; + let script = crate::wslsync::wsl_enable_script(name, ""); + match run_distro_script(name, &script) { + Ok(out) => { + let gid = out.lines().next_back().and_then(|l| l.trim().parse::().ok()).unwrap_or(0); + active.push(json!({"name": name, "gid": gid})); + } + Err(e) => { + crate::serve::log(&format!("wsl integration ({name}): {e}")); + if first_err.is_none() { + first_err = Some(e); + } + } + } + } + let res = crate::client::request_with("POST", "/kiri/wsl", Some(&json!({"distros": active})), background); + if let Err(e) = crate::engine::expect_ok(res) + && first_err.is_none() + { + first_err = Some(e); + } + if let Some(off) = disabled { + let script = crate::wslsync::wsl_disable_script(off, ""); + if let Err(e) = run_distro_script(off, &script) { + crate::serve::log(&format!("wsl integration disable ({off}): {e}")); + if first_err.is_none() { + first_err = Some(e); + } + } + } + match first_err { + Some(e) => Err(e), + None => Ok(()), + } +} + +/// Re-applies enabled WSL distros in the background when Kiri starts or +/// reconnects to the engine (handling `wsl --shutdown`). +pub fn sync_wsl_integration_soon() { + std::thread::spawn(|| { + if let Err(e) = apply_wsl_integration(None, true) { + crate::serve::log(&format!("wsl integration sync: {e}")); + } + }); +} + +fn toggle_distro(distro: &str, on: bool) -> io::Result<()> { + if !crate::wslsync::valid_distro_name(distro) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid WSL distro name")); + } + let mut list = enabled_distros(); + list.retain(|d| !d.eq_ignore_ascii_case(distro)); + if on { + list.push(distro.to_owned()); + } + save_enabled_distros(&list)?; + apply_wsl_integration((!on).then_some(distro), false) +} + /// `32GB`, `8192MB`, `512m` → MiB. fn mib(v: &str) -> Option { let v = v.trim().to_ascii_uppercase(); @@ -93,7 +235,7 @@ fn physical_mib() -> u64 { /// (MemTotal; see `as_set`). None while Kiri's engine isn't running, so /// that Settings never starts WSL. fn running() -> Option<(u64, u64)> { - if !crate::client::alive() { + if crate::serve::is_stopped() || !crate::client::alive() { return None; } let mut cmd = crate::win::tool("wsl.exe"); @@ -129,6 +271,14 @@ fn event() -> Value { let cpus = get(&text, "processors").and_then(|v| v.parse().ok()).unwrap_or(max_cpus).clamp(1, max_cpus); let memory = get(&text, "memory").and_then(|v| mib(&v)).unwrap_or(max_mib / 2); let now = running(); + let enabled = enabled_distros(); + let wsl_distros: Vec = user_distros() + .into_iter() + .map(|name| { + let on = enabled.iter().any(|e| e.eq_ignore_ascii_case(&name)); + json!({ "name": name, "on": on }) + }) + .collect(); json!({ "type": "resources", "cpus": cpus, @@ -140,6 +290,7 @@ fn event() -> Value { "max_memory_mib": max_mib, "overridden": false, "restart_note": "Restarting restarts WSL: every WSL distro stops, not only Kiri's, and Kiri's containers start again as they're set to.", + "wsl_distros": wsl_distros, }) } @@ -155,14 +306,25 @@ fn save(body: &Value) -> io::Result<()> { std::fs::write(&p, text) } -/// Reads (or saves, then reads) the CPUs and memory for Settings. +/// Reads (or saves, then reads) the CPUs, memory and WSL integration for Settings. pub fn resources(body: Option) { std::thread::spawn(move || { + if let Some(b) = &body + && let Some(distro) = b["wsl_distro"].as_str() + { + let on = b["on"].as_bool().unwrap_or(false); + if let Err(e) = toggle_distro(distro, on) { + emit(notice("error", &e.to_string())); + } + emit(event().to_string()); + return; + } let saved = body.map(|b| save(&b)); let ev = event(); + let running = ev["awake"] == true || !crate::serve::is_stopped(); match saved { - // While Kiri's engine runs, the toast offers to restart WSL now. - Some(Ok(())) => emit(json!({"type": "notice", "kind": "ok", "text": tr("Saved in .wslconfig. WSL uses these from its next start"), "act": if ev["awake"] == true { "restartvm" } else { "" }}).to_string()), + // While Kiri's engine is on, the toast offers to restart WSL now. + Some(Ok(())) => emit(json!({"type": "notice", "kind": "ok", "text": tr("Saved in .wslconfig. WSL uses these from its next start"), "act": if running { "restartvm" } else { "" }}).to_string()), Some(Err(e)) => emit(notice("error", &trf("Could not save .wslconfig: {error}", &[("error", &e)]))), None => {} } @@ -173,14 +335,23 @@ pub fn resources(body: Option) { /// Restart to apply: WSL stops and Kiri's engine starts again. pub fn restart() { std::thread::spawn(|| { + emit(json!({"type": "state", "state": "stopping"}).to_string()); let mut cmd = crate::win::tool("wsl.exe"); std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| crate::engine::ensure_daemon()); + let r = cmd.arg("--shutdown").status().and_then(|s| if s.success() { Ok(()) } else { Err(io::Error::other("wsl --shutdown failed")) }).and_then(|()| { + emit(json!({"type": "state", "state": "booting"}).to_string()); + crate::engine::ensure_daemon() + }); + if r.is_ok() { + let _ = apply_wsl_integration(None, true); + } + emit(json!({"type": "vmrestarted", "ok": r.is_ok()}).to_string()); emit(match r { Ok(()) => notice("ok", &tr("WSL restarted with the new resources")), Err(e) => notice("error", &trf("Could not restart WSL: {error}", &[("error", &e)])), }); emit(event().to_string()); + crate::engine::send(crate::engine::Cmd::Refresh); }); } diff --git a/crates/kiri-win/src/wslsync.rs b/crates/kiri-win/src/wslsync.rs index 673ba9605..46272517a 100644 --- a/crates/kiri-win/src/wslsync.rs +++ b/crates/kiri-win/src/wslsync.rs @@ -58,8 +58,9 @@ fn boot_command() -> &'static str { /// spaces, a `#` comment, or the `\r` of a file saved with CRLF /// ([[:space:]] has it). On one line, with no backslash, as the rest of /// the script. -const BOOT_AWK: &str = "function key(l) { sub(/#.*/, \"\", l); gsub(/[[:space:]]/, \"\", l); return l } \ +const BOOT_AWK: &str = "function key(l) { if (NR == 1) sub(/^\u{feff}/, \"\", l); sub(/[#;].*/, \"\", l); gsub(/[[:space:]]/, \"\", l); return tolower(l) } \ function flush() { if (boot && !done) { print want; done = 1 } } \ + NR == 1 { sub(/^\u{feff}/, \"\") } \ substr(key($0), 1, 1) == \"[\" { flush(); boot = key($0) == \"[boot]\"; print; next } \ boot && index(key($0), \"command=\") == 1 { if (!done) { print want; done = 1 } next } \ { print } \ @@ -129,6 +130,284 @@ pub fn wsl_sh<'a>(distro: &'a str, script: &'a str) -> [&'a str; 8] { ["-d", distro, "-u", "root", "-e", "sh", "-c", script] } +/// Whether `name` is a valid single-component WSL distro name. +pub fn valid_distro_name(name: &str) -> bool { + !name.is_empty() + && name != "." + && name != ".." + && !name.starts_with('-') + && !name.contains(['/', '\\', '\0', ':', '*', '?', '"', '<', '>', '|']) + && !name.bytes().any(|b| b.is_ascii_control()) +} + +/// Decodes `wsl.exe` output (UTF-16LE with or without BOM, or UTF-8), +/// dropping any leading BOM and NUL bytes. +pub fn wsl_text(bytes: &[u8]) -> String { + let (bytes, bom) = bytes.strip_prefix(&[0xFF, 0xFE]).map_or((bytes, false), |rest| (rest, true)); + let units = bytes.len() / 2; + let ascii = bytes.as_chunks::<2>().0.iter().filter(|&&[lo, hi]| lo != 0 && hi == 0).count(); + let looks_utf16 = ascii >= 2 && ascii * 4 >= units; + let text = if bom || looks_utf16 { + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|&p| u16::from_le_bytes(p)).collect(); + String::from_utf16_lossy(&units) + } else { + String::from_utf8_lossy(bytes).into_owned() + }; + text.trim_start_matches('\u{feff}').replace('\0', "") +} + +/// Parses `wsl.exe --list --quiet` output into user distros eligible for WSL +/// integration, filtering out `kiri`, `engine_distro`, `docker-desktop`, +/// `docker-desktop-data` (`docker-desktop*`), empty lines and BOMs. +pub fn parse_wsl_distros(bytes: &[u8], engine_distro: Option<&str>) -> Vec { + let mut out = Vec::new(); + for line in wsl_text(bytes).lines() { + let d = line.trim().trim_matches('\u{feff}').trim(); + if !valid_distro_name(d) { + continue; + } + let lower = d.to_ascii_lowercase(); + if lower == "kiri" || lower.starts_with("docker-desktop") { + continue; + } + if engine_distro.is_some_and(|e| d.eq_ignore_ascii_case(e)) { + continue; + } + if !out.iter().any(|x: &String| x.eq_ignore_ascii_case(d)) { + out.push(d.to_owned()); + } + } + out +} + +/// Parses `%LOCALAPPDATA%\Kiri\wsl-integration.json`; off (empty) by default. +pub fn parse_enabled_distros(bytes: &[u8]) -> Vec { + let v: serde_json::Value = serde_json::from_slice(bytes).unwrap_or(serde_json::Value::Null); + let arr = v["distros"].as_array().or_else(|| v.as_array()); + let mut out = Vec::new(); + for item in arr.into_iter().flatten() { + let Some(d) = item.as_str().map(str::trim) else { continue }; + if valid_distro_name(d) + && !d.eq_ignore_ascii_case("kiri") + && !d.to_ascii_lowercase().starts_with("docker-desktop") + && !out.iter().any(|x: &String| x.eq_ignore_ascii_case(d)) + { + out.push(d.to_owned()); + } + } + out +} + +/// Encodes the enabled distros for `%LOCALAPPDATA%\Kiri\wsl-integration.json`. +pub fn encode_enabled_distros(distros: &[String]) -> Vec { + serde_json::to_vec_pretty(&serde_json::json!({ "distros": distros })).unwrap_or_default() +} + +/// Why Kiri's WSL 2 storage filesystem (`/` or `/var/lib/kiri`) is read-only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WslReadOnly { + /// Linux ext4 aborted its journal (`errors=remount-ro`) and added `emergency_ro`. + EmergencyRo, + /// Mounted read-only (`ro`). + ReadOnly, +} + +impl WslReadOnly { + fn merge(self, other: Self) -> Self { + if self == Self::EmergencyRo || other == Self::EmergencyRo { + Self::EmergencyRo + } else { + Self::ReadOnly + } + } +} + +fn unescape_proc_mount_path(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' + && i + 3 < bytes.len() + && bytes[i + 1..i + 4].iter().all(|b| (b'0'..=b'7').contains(b)) + { + let val = ((bytes[i + 1] - b'0') << 6) | ((bytes[i + 2] - b'0') << 3) | (bytes[i + 3] - b'0'); + out.push(val); + i += 4; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +fn parse_mount_opts(opts: &str) -> Option { + let mut ro = false; + for opt in opts.split(',') { + match opt.trim() { + "emergency_ro" => return Some(WslReadOnly::EmergencyRo), + "ro" => ro = true, + _ => {} + } + } + ro.then_some(WslReadOnly::ReadOnly) +} + +fn mount_for_target(proc_mounts: &str, target: &str) -> Option { + let mut best: Option<(usize, Option)> = None; + for line in proc_mounts.lines() { + let mut f = line.split_whitespace(); + let (Some(_spec), Some(mp_raw), Some(_fstype), Some(opts)) = (f.next(), f.next(), f.next(), f.next()) else { + continue; + }; + let mp = unescape_proc_mount_path(mp_raw); + let mp_norm = { + let t = mp.trim_end_matches('/'); + if t.is_empty() { "/" } else { t } + }; + let covers = mp_norm == "/" + || target == mp_norm + || (target.starts_with(mp_norm) && target.as_bytes().get(mp_norm.len()) == Some(&b'/')); + if covers && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + best = Some((mp_norm.len(), parse_mount_opts(opts))); + } + } + best.and_then(|(_, kind)| kind) +} + +/// Checks `/proc/mounts` text from Kiri's WSL distro for `/` or `/var/lib/kiri` +/// mounted read-only (`ro` or ext4 `emergency_ro`, #768). +pub fn parse_wsl_readonly_mounts(proc_mounts: &str) -> Option { + match (mount_for_target(proc_mounts, "/"), mount_for_target(proc_mounts, "/var/lib/kiri")) { + (Some(a), Some(b)) => Some(a.merge(b)), + (Some(a), None) | (None, Some(a)) => Some(a), + (None, None) => None, + } +} + +/// Formats an actionable recovery message naming `vhdx_path` when known. +pub fn wsl_readonly_message(kind: WslReadOnly, vhdx_path: Option<&Path>) -> String { + let state = match kind { + WslReadOnly::EmergencyRo => "was remounted read-only by Linux (emergency_ro)", + WslReadOnly::ReadOnly => "is mounted read-only (emergency_ro)", + }; + let vhdx = vhdx_path + .map(|p| p.display().to_string()) + .unwrap_or_else(|| r"\ext4.vhdx".to_owned()); + format!( + "Kiri's WSL2 disk (ext4.vhdx) {state} after an unclean shutdown or filesystem error. \ + To recover: 1) run `wsl --shutdown` in PowerShell; \ + 2) attach the disk bare with `wsl --mount \"{vhdx}\" --vhd --bare`; \ + 3) from another Linux distro in WSL, find the device with `lsblk` and run `sudo e2fsck -f -y -D /dev/`, then `wsl --unmount`; \ + or move/recreate storage in Settings -> Storage." + ) +} + +/// SHA-256 of `"kiri"`, used by the Docker CLI for `~/.docker/contexts/meta//meta.json`. +const KIRI_CONTEXT_HASH: &str = "c288b06224b0bc4af8a3d80f683a27a8fc72e45f901a7e6766109e2fc1d5c2b9"; + +const DEFAULT_USER_AWK: &str = "function k(s) { sub(/#.*/, \"\", s); gsub(/[[:space:]]/, \"\", s); return s } \ + substr(k($0), 1, 1) == \"[\" { u = tolower(k($0)) == \"[user]\"; next } \ + u && index(tolower(k($0)), \"default=\") == 1 { s = k($0); sub(/^[dD][eE][fF][aA][uU][lL][tT]=/, \"\", s); print s; exit }"; + +const PASSWD_AWK: &str = "def != \"\" && $1 == def && $3 != 0 && $4 ~ /^[0-9]+$/ { print $1 \":\" $3 \":\" $4 \":\" $6; found = 1; exit } \ + $3 == 1000 && $4 ~ /^[0-9]+$/ && !u1000 { u1000 = $1 \":\" $3 \":\" $4 \":\" $6 } \ + $3 >= 1000 && $3 < 65534 && $4 ~ /^[0-9]+$/ && !ufirst { ufirst = $1 \":\" $3 \":\" $4 \":\" $6 } \ + END { if (!found) { if (u1000) print u1000; else if (ufirst) print ufirst } }"; + +/// The script, run as root inside `distro`, that enables Kiri's WSL integration: +/// 1. Mounts `distro`'s `/` onto `/mnt/wsl/kiri/roots/`. +/// 2. Determines the socket GID (`docker` group GID if `docker` exists in +/// `/etc/group`, otherwise the default non-root user's primary GID in +/// `/etc/passwd`, so NixOS without `groupadd` works cleanly). +/// 3. Links `/var/run/docker.sock -> /mnt/wsl/kiri/sockets//docker.sock` +/// unless `/var/run/docker.sock` belongs to a running `dockerd` inside `distro`, +/// and writes the `kiri` Docker context for the default user. +/// 4. Prints the numeric GID on stdout. +/// `root` is `""` in production and a stand-in directory in unit tests. +pub fn wsl_enable_script(distro: &str, root: &str) -> String { + let bind_root = sh_quote(&format!("{root}/mnt/wsl/kiri/roots/{distro}")); + let sock_target = sh_quote(&format!("{root}/mnt/wsl/kiri/sockets/{distro}/docker.sock")); + let src_root = sh_quote(if root.is_empty() { "/" } else { root }); + let etc_group = sh_quote(&format!("{root}/etc/group")); + let etc_passwd = sh_quote(&format!("{root}/etc/passwd")); + let etc_wsl = sh_quote(&format!("{root}/etc/wsl.conf")); + let var_run = sh_quote(&format!("{root}/var/run")); + let host_prefix = sh_quote(root); + let ctx_meta = serde_json::json!({ + "Name": "kiri", + "Metadata": { "Description": "Kiri" }, + "Endpoints": { + "docker": { + "Host": format!("unix://{root}/mnt/wsl/kiri/sockets/{distro}/docker.sock"), + "SkipTLSVerify": false + } + } + }) + .to_string(); + format!( + "export PATH=\"$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/run/current-system/sw/bin:/nix/var/nix/profiles/default/bin\"; \ + r={bind_root}; mkdir -p \"$r\" || exit 1; \ + if ! mountpoint -q \"$r\" 2>/dev/null && ! grep -Fqs \" $r \" /proc/mounts 2>/dev/null; then mount --bind {src_root} \"$r\" || exit 1; fi; \ + defuser=\"\"; [ -f {etc_wsl} ] && defuser=$(awk {} {etc_wsl} 2>/dev/null); \ + uinfo=\"\"; [ -f {etc_passwd} ] && uinfo=$(awk -F: -v def=\"$defuser\" {} {etc_passwd} 2>/dev/null); \ + uname=$(printf %s \"$uinfo\" | cut -d: -f1); \ + uuid=$(printf %s \"$uinfo\" | cut -d: -f2); \ + ugid=$(printf %s \"$uinfo\" | cut -d: -f3); \ + uhome=$(printf %s \"$uinfo\" | cut -d: -f4); \ + dgid=\"\"; [ -f {etc_group} ] && dgid=$(awk -F: '$1 == \"docker\" && $3 ~ /^[0-9]+$/ {{ print $3; exit }}' {etc_group} 2>/dev/null); \ + if [ -n \"$dgid\" ]; then \ + gid=\"$dgid\"; \ + if [ -n \"$uname\" ] && command -v usermod >/dev/null 2>&1; then usermod -aG docker \"$uname\" 2>/dev/null || true; fi; \ + elif [ -n \"$ugid\" ]; then \ + gid=\"$ugid\"; \ + else \ + gid=0; \ + fi; \ + vr={var_run}; mkdir -p \"$vr\" || exit 1; \ + busy=0; \ + if [ -S \"$vr/docker.sock\" ] && [ ! -L \"$vr/docker.sock\" ]; then \ + if [ -f \"$vr/docker.pid\" ] && kill -0 \"$(cat \"$vr/docker.pid\" 2>/dev/null)\" 2>/dev/null; then busy=1; \ + elif pgrep -x dockerd >/dev/null 2>&1 || pidof dockerd >/dev/null 2>&1; then busy=1; fi; \ + fi; \ + [ \"$busy\" = 0 ] && ln -sfn {sock_target} \"$vr/docker.sock\"; \ + if [ -n \"$uhome\" ] && [ -d {host_prefix}\"$uhome\" ]; then \ + cdir={host_prefix}\"$uhome/.docker/contexts/meta/{KIRI_CONTEXT_HASH}\"; \ + mkdir -p \"$cdir\" 2>/dev/null && printf %s {} | base64 -d >\"$cdir/meta.json\" 2>/dev/null; \ + [ -n \"$uuid\" ] && [ -n \"$ugid\" ] && chown -R \"$uuid:$ugid\" {host_prefix}\"$uhome/.docker\" 2>/dev/null || true; \ + fi; \ + echo \"$gid\"", + sh_quote(DEFAULT_USER_AWK), + sh_quote(PASSWD_AWK), + base64(ctx_meta.as_bytes()), + ) +} + +/// The script, run as root inside `distro`, that tears down Kiri's WSL +/// integration when `distro` is disabled: removes `/var/run/docker.sock` if it +/// points into `/mnt/wsl/kiri/`, unmounts `/mnt/wsl/kiri/roots/`, and +/// removes `/mnt/wsl/kiri/sockets//docker.sock`. +pub fn wsl_disable_script(distro: &str, root: &str) -> String { + let bind_root = sh_quote(&format!("{root}/mnt/wsl/kiri/roots/{distro}")); + let sock_dir = sh_quote(&format!("{root}/mnt/wsl/kiri/sockets/{distro}")); + let var_run = sh_quote(&format!("{root}/var/run")); + format!( + "export PATH=\"$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/run/current-system/sw/bin:/nix/var/nix/profiles/default/bin\"; \ + vr={var_run}; \ + if [ -L \"$vr/docker.sock\" ]; then \ + t=$(readlink \"$vr/docker.sock\" 2>/dev/null || true); \ + case \"$t\" in */mnt/wsl/kiri/*) rm -f \"$vr/docker.sock\" ;; esac; \ + fi; \ + r={bind_root}; \ + if mountpoint -q \"$r\" 2>/dev/null || grep -Fqs \" $r \" /proc/mounts 2>/dev/null; then \ + umount -l \"$r\" 2>/dev/null || umount \"$r\" 2>/dev/null || true; \ + fi; \ + rmdir \"$r\" 2>/dev/null || true; \ + sd={sock_dir}; rm -f \"$sd/docker.sock\" 2>/dev/null || true; rmdir \"$sd\" 2>/dev/null || true; true" + ) +} + #[cfg(all(test, unix))] mod tests { use super::*; @@ -228,6 +507,16 @@ mod tests { assert_eq!(run(Some("[boot] # Kiri's\ncommand=/old # mine\n")), format!("[boot] # Kiri's\n{want}\n")); // A commented-out command is left, and one added. assert_eq!(run(Some("[boot]\n# command = /off\n")), format!("[boot]\n# command = /off\n{want}\n")); + // Case-insensitive [Boot]/Command, UTF-8 BOM, and ';' comments. + assert_eq!(run(Some("[Boot]\nCommand = /old\nsystemd = false\n")), format!("[Boot]\n{want}\nsystemd = false\n")); + assert_eq!( + run(Some("\u{feff}[BOOT]\nCOMMAND = /old\n[automount]\noptions = metadata;umask=22\n")), + format!("[BOOT]\n{want}\n[automount]\noptions = metadata;umask=22\n") + ); + assert_eq!( + run(Some("; [boot]\n[boot] ; header\n; command = /off\ncommand = /old ; inline\n")), + format!("; [boot]\n[boot] ; header\n; command = /off\n{want}\n") + ); assert_eq!(run(None), format!("[boot]\n{want}\n")); let _ = std::fs::remove_dir_all(root.parent().unwrap()); } @@ -250,9 +539,35 @@ mod tests { /// is Windows' quoting, not sh's. #[test] fn the_script_has_no_backslash() { + assert!(!KIRI_START.contains('\\')); assert!(!sync_script(Path::new("C:/Users/x/AppData/Local/Kiri"), "", true).contains('\\')); } + #[test] + fn kiri_start_refuses_emergency_ro_with_clean_recovery_message() { + let dir = std::env::temp_dir().join(format!("kiri-start-ro-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mounts = dir.join("mounts"); + std::fs::write( + &mounts, + "/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered,emergency_ro 0 0\ntmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0\n", + ) + .unwrap(); + let out = Command::new("sh") + .args(["-c", KIRI_START]) + .env("KIRI_PROC_MOUNTS", &mounts) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + let err = String::from_utf8_lossy(&out.stderr); + assert!(err.contains("Kiri's WSL2 disk (ext4.vhdx) was remounted read-only by Linux (emergency_ro)"), "{err}"); + assert!(err.contains("wsl --shutdown") && err.contains("wsl --mount") && err.contains("e2fsck -f -y -D"), "{err}"); + assert!(err.contains("Settings -> Storage"), "{err}"); + assert!(!err.contains(r"'\''") && !err.contains('\x1b'), "unescaped quotes or control chars leaked: {err:?}"); + let _ = std::fs::remove_dir_all(&dir); + } + /// An engine older than this app is restarted once: not again after /// that (a restart that failed does not loop), not while it does not /// answer, not when it is not behind (current, newer, a development @@ -321,4 +636,145 @@ mod tests { fn quotes_one_word() { assert_eq!(sh_quote("C:/Users/O'Neil/x"), r"'C:/Users/O'\''Neil/x'"); } + + #[test] + fn parses_utf16le_wsl_list_and_filters_system_distros() { + let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_le_bytes).collect::>(); + let raw = "\u{feff}kiri\r\nUbuntu\r\ndocker-desktop\r\ndocker-desktop-data\r\n\r\nNixOS\r\nDebian\r\nUbuntu\r\n"; + assert_eq!( + parse_wsl_distros(&utf16(raw), Some("kiri")), + vec!["Ubuntu".to_owned(), "NixOS".to_owned(), "Debian".to_owned()] + ); + // With explicit UTF-16LE BOM prefix and custom engine distro. + let mut with_bom = vec![0xFF, 0xFE]; + with_bom.extend_from_slice(&utf16("Ubuntu-26.04\nNixOS\ndocker-desktop\nkiri\n")); + assert_eq!( + parse_wsl_distros(&with_bom, Some("Ubuntu-26.04")), + vec!["NixOS".to_owned()] + ); + // Enabled distros file defaults to off (empty) and filters system distros. + assert!(parse_enabled_distros(b"").is_empty()); + let saved = encode_enabled_distros(&["Ubuntu".into(), "NixOS".into()]); + assert_eq!(parse_enabled_distros(&saved), vec!["Ubuntu".to_owned(), "NixOS".to_owned()]); + } + + #[test] + fn wsl_integration_scripts_have_no_backslash() { + assert!(!wsl_enable_script("Ubuntu", "").contains('\\')); + assert!(!wsl_disable_script("Ubuntu", "").contains('\\')); + } + + #[test] + fn wsl_enable_and_disable_scripts_setup_gid_symlink_and_teardown() { + use std::os::unix::net::UnixListener; + let dir = std::env::temp_dir().join(format!("kiri-wsl-integ-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let (root, tools) = (dir.join("root"), dir.join("tools")); + for d in [&root.join("etc"), &root.join("var/run"), &root.join("home/alice"), &tools] { + std::fs::create_dir_all(d).unwrap(); + } + // Mock mountpoint, mount and umount in PATH so the test runs unprivileged. + let mounted_flag = dir.join("mounted"); + std::fs::write( + tools.join("mountpoint"), + format!("#!/bin/sh\n[ -f '{}' ]\n", mounted_flag.display()), + ) + .unwrap(); + std::fs::write( + tools.join("mount"), + format!("#!/bin/sh\n[ \"$1\" = --bind ] && [ -d \"$3\" ] && touch '{}'\n", mounted_flag.display()), + ) + .unwrap(); + std::fs::write( + tools.join("umount"), + format!("#!/bin/sh\nrm -f '{}'\n", mounted_flag.display()), + ) + .unwrap(); + for tool in ["mountpoint", "mount", "umount"] { + std::fs::set_permissions(tools.join(tool), std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let path = format!("{}:{}", tools.display(), std::env::var("PATH").unwrap_or_default()); + let root_str = root.to_string_lossy(); + + // 1. NixOS-like distro without `docker` group: uses default user's primary GID (100). + std::fs::write(root.join("etc/passwd"), "root:x:0:0:root:/root:/bin/sh\nalice:x:1000:100:Alice:/home/alice:/bin/sh\n").unwrap(); + std::fs::write(root.join("etc/group"), "root:x:0:\nusers:x:100:\n").unwrap(); + let enable = wsl_enable_script("NixOS", &root_str); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "100"); + assert!(mounted_flag.exists(), "root bind mount must be performed"); + assert!(root.join("mnt/wsl/kiri/roots/NixOS").is_dir()); + let link = std::fs::read_link(root.join("var/run/docker.sock")).unwrap(); + assert_eq!(link, root.join("mnt/wsl/kiri/sockets/NixOS/docker.sock")); + assert!(root.join("home/alice/.docker/contexts/meta").join(KIRI_CONTEXT_HASH).join("meta.json").is_file()); + + // 2. Distro with `docker` group in /etc/group: uses `docker` group GID (131). + std::fs::write(root.join("etc/group"), "root:x:0:\nusers:x:100:\ndocker:x:131:alice\n").unwrap(); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "131"); + + // 3. Disable script unmounts root, removes /var/run/docker.sock symlink and socket dir. + let sock_dir = root.join("mnt/wsl/kiri/sockets/NixOS"); + std::fs::create_dir_all(&sock_dir).unwrap(); + std::fs::write(sock_dir.join("docker.sock"), "").unwrap(); + let disable = wsl_disable_script("NixOS", &root_str); + let out = Command::new("sh").args(["-c", &disable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(!mounted_flag.exists(), "root bind mount must be unmounted"); + assert!(std::fs::symlink_metadata(root.join("var/run/docker.sock")).is_err(), "symlink must be removed"); + assert!(!sock_dir.exists(), "socket dir must be removed"); + + // 4. When a live dockerd owns /var/run/docker.sock, enable leaves it untouched. + let own_sock = root.join("var/run/docker.sock"); + let _listener = UnixListener::bind(&own_sock).unwrap(); + std::fs::write(root.join("var/run/docker.pid"), std::process::id().to_string()).unwrap(); + let out = Command::new("sh").args(["-c", &enable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert!(!std::fs::symlink_metadata(&own_sock).unwrap().file_type().is_symlink(), "running dockerd socket must not be overwritten"); + // And disable leaves a real dockerd socket untouched too. + let out = Command::new("sh").args(["-c", &disable]).env("PATH", &path).output().unwrap(); + assert!(out.status.success()); + assert!(own_sock.exists(), "running dockerd socket must not be removed on disable"); + + let _ = std::fs::remove_dir_all(&dir); + } +} + +#[cfg(test)] +mod ro_tests { + use super::*; + use std::path::Path; + + #[test] + fn parses_wsl_proc_mounts_and_formats_vhdx_recovery_message() { + let healthy = "/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered 0 0\n"; + assert_eq!(parse_wsl_readonly_mounts(healthy), None); + + let emergency = "/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered,emergency_ro 0 0\n"; + assert_eq!(parse_wsl_readonly_mounts(emergency), Some(WslReadOnly::EmergencyRo)); + + let separate_ro = "/dev/sda1 / ext4 rw,relatime 0 0\n/dev/sdb1 /var/lib/kiri ext4 ro,relatime 0 0\n"; + assert_eq!(parse_wsl_readonly_mounts(separate_ro), Some(WslReadOnly::ReadOnly)); + + let overmounted_rw = "/dev/sda1 / ext4 rw,relatime 0 0\n/dev/sdb1 /var/lib/kiri ext4 ro,relatime 0 0\n/dev/sdb1 /var/lib/kiri ext4 rw,relatime 0 0\n"; + assert_eq!(parse_wsl_readonly_mounts(overmounted_rw), None); + + let msg = wsl_readonly_message(WslReadOnly::EmergencyRo, Some(Path::new(r"D:\KiriData\ext4.vhdx"))); + assert!(msg.contains(r#"wsl --mount "D:\KiriData\ext4.vhdx" --vhd --bare"#), "{msg}"); + assert!(msg.contains("wsl --shutdown") && msg.contains("e2fsck -f -y -D") && msg.contains("Settings -> Storage"), "{msg}"); + } + + #[test] + fn validates_distro_names_and_sync_script_has_no_backslash() { + for bad in ["", ".", "..", "-e", "--shutdown", "a/b", r"a\b", "bad:distro", "bad*distro", "bad?distro", "bad\"distro", "bad|distro"] { + assert!(!valid_distro_name(bad), "expected false for {bad:?}"); + } + for good in ["Ubuntu", "Ubuntu-24.04", "NixOS", "Arch_Linux", "my.distro"] { + assert!(valid_distro_name(good), "expected true for {good:?}"); + } + assert_eq!(parse_enabled_distros(br#"{"distros":["Ubuntu","--shutdown","bad:name","NixOS"]}"#), vec!["Ubuntu".to_owned(), "NixOS".to_owned()]); + assert!(!sync_script(Path::new("C:/Users/x/AppData/Local/Kiri"), "", true).contains('\\')); + } } diff --git a/crates/kiri/Cargo.toml b/crates/kiri/Cargo.toml index 26f58bd54..d61921852 100644 --- a/crates/kiri/Cargo.toml +++ b/crates/kiri/Cargo.toml @@ -17,11 +17,9 @@ sha2 = "0.11" flate2 = "1" # zstd uploads to the same endpoints: the decoder the guest unpacks layers with. ruzstd = "0.9" -ureq = { version = "3", default-features = false, features = ["rustls"] } +ureq = { version = "3", default-features = false, features = ["rustls-no-provider"] } # HTTPS for container names: the same rustls and ring ureq already brings in. rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } -# Roots for `kiri share`'s connection to the edge. -webpki-roots = "1" rcgen = { version = "0.14", default-features = false, features = ["ring", "pem", "crypto"] } # The `name` filter is a regular expression in Docker (k3d sends `^[/]?name$`). # regex-lite: RE2 syntax like Go's regexp, without the Unicode tables' size. diff --git a/crates/kiri/src/bench.rs b/crates/kiri/src/bench.rs index 5c8594b9d..9985ff568 100644 --- a/crates/kiri/src/bench.rs +++ b/crates/kiri/src/bench.rs @@ -39,6 +39,12 @@ const ENGINES: [(&str, &str, &str); 3] = [ ]; pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let mut o = Opts { runs: 50, image: "alpine:latest".into(), bridge: false, only: None }; let mut it = args.iter(); while let Some(a) = it.next() { @@ -113,7 +119,7 @@ fn pct(v: &[Duration], p: usize) -> Duration { fn kiri(o: &Opts, warmup: usize) -> io::Result> { let store = Store::open(Store::default_root()?)?; - let image = image(&store, &o.image)?; + let (image, _blob_pins) = image(&store, &o.image)?; let mut guest = Guest::boot(&BootOptions { data_disk: true, ..Default::default() })?; ensure_layers(&mut guest, &store, &image)?; let layers = layers_top_down(&image); diff --git a/crates/kiri/src/boot.rs b/crates/kiri/src/boot.rs index 81b811df2..eca6a2f91 100644 --- a/crates/kiri/src/boot.rs +++ b/crates/kiri/src/boot.rs @@ -5,7 +5,15 @@ use std::time::Duration; use crate::guest::{BootOptions, Guest}; +const USAGE: &str = "usage: kiri boot [--console] [--pings N]"; + pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } let mut opts = BootOptions::default(); let mut pings = 1000usize; let mut it = args.iter(); diff --git a/crates/kiri/src/bridge.rs b/crates/kiri/src/bridge.rs index f469c5941..3833a9e56 100644 --- a/crates/kiri/src/bridge.rs +++ b/crates/kiri/src/bridge.rs @@ -81,6 +81,11 @@ const LIMIT: usize = 2 * WINDOW; /// socket), or about as long waiting on its lock behind another; 5 s more /// so one that would just make it is not killed. const START_LIMIT: Duration = Duration::from_secs(25); +/// How long a socket that refuses connections is retried after a start +/// returns before concluding the daemon created it and exited. A healthy +/// daemon takes milliseconds between bind and listen (or to remove a stale +/// socket under systemd), never the full START_LIMIT. +const REFUSED_LIMIT: Duration = Duration::from_secs(1); /// After a start failed, connections within this get its reason at once, /// rather than each starting the engine again. Doubled after each failed /// start in a row, up to RETRY_MOST: an engine that exits as it starts @@ -98,9 +103,32 @@ const LOG: &str = "/var/log/kiri.log"; type Out = Arc>; +const USAGE: &str = "usage: kiri bridge [--socket PATH]"; + pub fn run(args: &[String]) -> io::Result<()> { - let socket = match args.iter().position(|a| a == "--socket").and_then(|i| args.get(i + 1)) { - Some(s) => PathBuf::from(s), + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let mut socket_opt = None; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--socket" => { + socket_opt = Some( + it.next() + .filter(|s| !s.is_empty()) + .map(PathBuf::from) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, USAGE))?, + ); + } + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } + } + let socket = match socket_opt { + Some(s) => s, None => crate::daemon::socket_path()?, }; let out: Out = Arc::new(Mutex::new(BufWriter::with_capacity(64 * 1024, io::stdout()))); @@ -303,6 +331,8 @@ struct Starter { tell: Option>, /// The most one start takes (START_LIMIT). limit: Duration, + /// The most a socket refusing connections is retried after a start (REFUSED_LIMIT). + refused_limit: Duration, state: Mutex, cv: Condvar, } @@ -324,7 +354,16 @@ struct StartState { impl Starter { fn new(socket: PathBuf, start: Box Result<(), String> + Send + Sync>, log: PathBuf) -> Starter { - Starter { socket, start, log, tell: None, limit: START_LIMIT, state: Mutex::new(StartState { backoff: RETRY_AFTER, ..StartState::default() }), cv: Condvar::new() } + Starter { + socket, + start, + log, + tell: None, + limit: START_LIMIT, + refused_limit: REFUSED_LIMIT, + state: Mutex::new(StartState { backoff: RETRY_AFTER, ..StartState::default() }), + cv: Condvar::new(), + } } /// A connection to the daemon, or why there is none. @@ -340,13 +379,15 @@ impl Starter { let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner()); st = self.cv.wait_while(st, |s| s.running).unwrap_or_else(|e| e.into_inner()); // A start ended since the try above (this one waited for it, or it - // ended just after): its outcome is this connection's too. + // ended just after): try the socket first in case a daemon came up + // externally while a failed start ran, else use its outcome. if st.ended != ended { - if let Some((_, why)) = st.failed.as_ref().filter(|_| !st.connected) { - return Err(why.clone()); - } + let why = st.failed.as_ref().filter(|_| !st.connected).map(|(_, w)| w.clone()); drop(st); - return UnixStream::connect(&self.socket).map_err(|e| format!("it started, then did not answer ({e})")); + return match UnixStream::connect(&self.socket) { + Ok(s) => Ok(s), + Err(e) => Err(why.unwrap_or_else(|| format!("it started, then did not answer ({e})"))), + }; } if let Some((at, why)) = &st.failed && at.elapsed() < st.backoff @@ -388,6 +429,7 @@ impl Starter { if let Err(why) = (self.start)(until) { return failed(why); } + let mut refused_since: Option = None; loop { match UnixStream::connect(&self.socket) { Ok(s) => { @@ -397,7 +439,17 @@ impl Starter { return Ok(s); } Err(e) if Instant::now() >= until => return failed(format!("it did not answer within {} s ({e}); see {LOG}", self.limit.as_secs())), - Err(_) => std::thread::sleep(Duration::from_millis(100)), + Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => { + let since = *refused_since.get_or_insert_with(Instant::now); + if since.elapsed() >= self.refused_limit { + return failed(format!("its socket refused connections ({e}); see {LOG}")); + } + std::thread::sleep(Duration::from_millis(100)); + } + Err(_) => { + refused_since = None; + std::thread::sleep(Duration::from_millis(100)); + } } } } @@ -812,6 +864,105 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// A daemon that creates its socket and then exits leaves a socket that + /// refuses connections: the bridge fails quickly instead of waiting out + /// the full start limit, and back-off still applies. + #[test] + fn a_refusing_socket_does_not_wait_the_full_start_limit() { + let dir = temp("refused"); + let sock = dir.join("d.sock"); + let starts = Arc::new(AtomicUsize::new(0)); + let (s, n) = (sock.clone(), starts.clone()); + let mut starter = Starter::new( + sock, + Box::new(move |_| { + n.fetch_add(1, Ordering::SeqCst); + let _ = std::fs::remove_file(&s); + // Bound, then dropped: the socket file stays and refuses connections. + drop(UnixListener::bind(&s).unwrap()); + Ok(()) + }), + dir.join("log"), + ); + starter.limit = Duration::from_secs(10); + let began = Instant::now(); + let why = starter.connect().unwrap_err(); + assert!(began.elapsed() < Duration::from_secs(3), "waited {:?} ({why})", began.elapsed()); + assert!(why.contains("refused") && why.contains(LOG), "{why}"); + // Back-off still applies: the next connect gets the reason without another start. + assert_eq!(starter.connect().unwrap_err(), why); + assert_eq!(starts.load(Ordering::SeqCst), 1); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A stale socket that briefly refuses connections while the new daemon + /// replaces it (for example under systemd) still connects within REFUSED_LIMIT. + #[test] + fn a_transiently_refusing_socket_still_connects() { + let dir = temp("transient-refused"); + let sock = dir.join("d.sock"); + // Stale socket present before and right after start returns. + drop(UnixListener::bind(&sock).unwrap()); + let s = sock.clone(); + let starter = Starter::new( + sock, + Box::new(move |_| { + let s = s.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(200)); + let _ = std::fs::remove_file(&s); + echo_daemon(&s); + }); + Ok(()) + }), + dir.join("log"), + ); + let mut conn = starter.connect().expect("daemon replaced stale socket within REFUSED_LIMIT"); + conn.write_all(b"hi").unwrap(); + conn.shutdown(Shutdown::Write).unwrap(); + let mut reply = Vec::new(); + conn.read_to_end(&mut reply).unwrap(); + assert_eq!(reply, b"hi"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A connection waiting behind a start that fails still connects if the + /// daemon came up externally meanwhile, instead of returning the stale error. + #[test] + fn a_waiter_connects_if_the_daemon_comes_up_while_a_start_fails() { + let dir = temp("waiter-recovers"); + let sock = dir.join("d.sock"); + let (started_tx, started_rx) = channel(); + let (finish_tx, finish_rx) = channel(); + let finish_rx = Mutex::new(finish_rx); + let starter = Arc::new(Starter::new( + sock.clone(), + Box::new(move |_| { + let _ = started_tx.send(()); + let _ = finish_rx.lock().unwrap().recv(); + Err("kiri-start failed".to_owned()) + }), + dir.join("log"), + )); + let s1 = starter.clone(); + let first = std::thread::spawn(move || s1.connect()); + started_rx.recv().unwrap(); + let s2 = starter.clone(); + let second = std::thread::spawn(move || s2.connect()); + std::thread::sleep(Duration::from_millis(100)); + // The daemon comes up externally while the first start is failing. + echo_daemon(&sock); + let _ = finish_tx.send(()); + assert_eq!(first.join().unwrap().unwrap_err(), "kiri-start failed"); + let mut conn = second.join().unwrap().expect("waiter should connect once daemon is up"); + conn.write_all(b"ok").unwrap(); + conn.shutdown(Shutdown::Write).unwrap(); + let mut reply = Vec::new(); + conn.read_to_end(&mut reply).unwrap(); + assert_eq!(reply, b"ok"); + let _ = std::fs::remove_dir_all(&dir); + } + /// Failed starts in a row wait longer each time, 5 s doubling to 5 min, /// and one that works resets that. At the longest, the same failure is /// not logged again; a new reason is. diff --git a/crates/kiri/src/builds.rs b/crates/kiri/src/builds.rs index 3f67abca1..7f94573ac 100644 --- a/crates/kiri/src/builds.rs +++ b/crates/kiri/src/builds.rs @@ -17,13 +17,34 @@ use crate::flavor::{CONTEXT, Name}; /// Kiri's BuildKit builder, a docker-container one on Kiri's context. pub const BUILDER: Name = Name("kiri-build", "kiri-dev-build"); -fn buildx(args: &[&str]) -> io::Result<(String, String)> { +#[cfg(unix)] +fn kiri_host() -> io::Result { + Ok(format!("unix://{}", crate::client::socket()?.display())) +} + +#[cfg(windows)] +fn kiri_host() -> io::Result { + Ok(format!("npipe://{}", crate::client::pipe().replace('\\', "/"))) +} + +fn buildx_command(args: &[&str]) -> io::Result { let docker = crate::client::docker_cli().ok_or_else(|| io::Error::other("no docker CLI found (Kiri.app bundles one)"))?; + let host = kiri_host()?; let mut cmd = Command::new(docker); // No console window flashing up from Kiri's window on Windows. #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); - let out = cmd.args(["--context", CONTEXT.get(), "buildx"]).args(args).stdin(Stdio::null()).output()?; + // Clear DOCKER_CONTEXT and point DOCKER_HOST at Kiri's socket/pipe so the + // implicit "default" builder (used by `docker compose build`) resolves to + // Kiri's engine while named builders on Kiri's context still work. + cmd.env_remove("DOCKER_CONTEXT").env("DOCKER_HOST", host).arg("buildx").args(args).stdin(Stdio::null()); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + Ok(cmd) +} + +fn buildx(args: &[&str]) -> io::Result<(String, String)> { + let out = buildx_command(args)?.output()?; let (stdout, stderr) = (String::from_utf8_lossy(&out.stdout).into_owned(), String::from_utf8_lossy(&out.stderr).into_owned()); if !out.status.success() { let msg = stderr.lines().rev().find(|l| !l.trim().is_empty()).unwrap_or("buildx failed").trim_start_matches("ERROR: ").to_owned(); @@ -32,12 +53,102 @@ fn buildx(args: &[&str]) -> io::Result<(String, String)> { Ok((stdout, stderr)) } +/// What `buildx` prints to stderr within `limit`, then the command and the +/// plugin it started are stopped. `history logs` on a running build follows +/// it until it ends: waiting for that left the steps unshown and, with the +/// window asking again every 2 s, a reader piling up per ask (#923). +fn buildx_stderr_for(args: &[&str], limit: std::time::Duration) -> io::Result { + stderr_for(buildx_command(args)?, limit) +} + +fn stderr_for(mut cmd: Command, limit: std::time::Duration) -> io::Result { + cmd.stdout(Stdio::null()).stderr(Stdio::piped()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = cmd.spawn()?; + let mut err = child.stderr.take().ok_or_else(|| io::Error::other("no stderr"))?; + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut b = Vec::new(); + let _ = io::Read::read_to_end(&mut err, &mut b); + let _ = tx.send(b); + }); + let until = std::time::Instant::now() + limit; + while child.try_wait()?.is_none() { + if std::time::Instant::now() >= until { + kill_tree(&mut child); + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + // The tree is gone, so the pipe closes; the wait only covers a straggler. + let b = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap_or_default(); + Ok(String::from_utf8_lossy(&b).into_owned()) +} + +/// Kills `child` and what it started: docker runs buildx as a child of its +/// own. As ui/compose.rs's, which the Windows build of this file can't reach. +fn kill_tree(child: &mut std::process::Child) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: a plain signal to the group this child leads (`process_group(0)`). + unsafe { + libc::killpg(pid, libc::SIGKILL); + } + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + let _ = Command::new("taskkill").args(["/F", "/T", "/PID", &child.id().to_string()]).creation_flags(0x0800_0000).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status(); + } + let _ = child.kill(); + let _ = child.wait(); +} + /// Every JSON value in `s`, whether one per line or run together. fn values(s: &str) -> Vec { serde_json::Deserializer::from_str(s).into_iter::().map_while(Result::ok).collect() } -/// The docker-container builders on Kiri's context whose BuildKit container exists. +fn endpoint_is_kiri(endpoint: Option<&str>, kiri_context: &str, kiri_host: &str) -> bool { + let Some(ep) = endpoint.filter(|s| !s.is_empty()) else { return false }; + if ep == kiri_context || ep == "default" || ep == kiri_host { + return true; + } + if kiri_host.get(..8).is_some_and(|s| s.eq_ignore_ascii_case("npipe://")) && ep.get(..8).is_some_and(|s| s.eq_ignore_ascii_case("npipe://")) { + return ep.replace('\\', "/").eq_ignore_ascii_case(&kiri_host.replace('\\', "/")); + } + false +} + +fn builders_from(buildx_ls: &[Value], containers: &Value, kiri_context: &str, kiri_host: &str) -> Vec { + let have: Vec = containers + .as_array() + .into_iter() + .flatten() + .flat_map(|c| c["Names"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(|n| n.trim_start_matches('/').to_owned()))) + .collect(); + let mut found = Vec::new(); + for b in buildx_ls { + if b["Driver"] != "docker-container" { + continue; + } + let on_kiri = b["Nodes"].as_array().into_iter().flatten().any(|n| { + endpoint_is_kiri(n["Endpoint"].as_str(), kiri_context, kiri_host) + && n["Name"].as_str().is_some_and(|name| have.iter().any(|c| *c == format!("buildx_buildkit_{name}"))) + }); + if on_kiri + && let Some(name) = b["Name"].as_str() + && !name.is_empty() + && !found.iter().any(|existing| existing == name) + { + found.push(name.to_owned()); + } + } + found +} + +/// The docker-container builders on Kiri's engine whose BuildKit container exists. /// No buildx plugin (a distribution's plain docker CLI) means no builds yet, not an error. fn builders() -> io::Result> { // Without the plugin, docker reads `buildx` as an unknown command or flag. @@ -45,22 +156,8 @@ fn builders() -> io::Result> { return Ok(Vec::new()); } let (out, _) = buildx(&["ls", "--format", "json"])?; - let have: Vec = crate::client::get_background("/containers/json?all=1")? - .as_array() - .into_iter() - .flatten() - .flat_map(|c| c["Names"].as_array().into_iter().flatten().filter_map(|n| n.as_str().map(|n| n.trim_start_matches('/').to_owned()))) - .collect(); - Ok(values(&out) - .into_iter() - .filter(|b| b["Driver"] == "docker-container") - .filter(|b| { - b["Nodes"].as_array().into_iter().flatten().any(|n| { - n["Endpoint"] == CONTEXT.get() && n["Name"].as_str().is_some_and(|name| have.iter().any(|c| *c == format!("buildx_buildkit_{name}"))) - }) - }) - .filter_map(|b| b["Name"].as_str().map(str::to_owned)) - .collect()) + let containers = crate::client::get_background("/containers/json?all=1")?; + Ok(builders_from(&values(&out), &containers, CONTEXT.get(), &kiri_host()?)) } /// The newest builds first, from every builder: {builder, id, name, status, @@ -83,16 +180,26 @@ pub fn list() -> io::Result> { Ok(all) } +fn valid_build_ref(builder: &str, id: &str) -> bool { + !builder.is_empty() && !builder.starts_with('-') && !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric()) +} + /// One build: the record, its steps in the order they ran (each with its /// start, end, cached, error and output) and its warnings. pub fn detail(builder: &str, id: &str) -> io::Result { - if !id.bytes().all(|b| b.is_ascii_alphanumeric()) || builder.starts_with('-') { + if !valid_build_ref(builder, id) { return Err(io::Error::other("not a build")); } let (info, _) = buildx(&["history", "inspect", "--builder", builder, id, "--format", "json"])?; let info: Value = serde_json::from_str(&info).map_err(io::Error::other)?; - // The raw progress stream goes to stderr. - let (_, raw) = buildx(&["history", "logs", "--builder", builder, "--progress", "rawjson", id]).unwrap_or_default(); + // The raw progress stream goes to stderr. A running build's is what it + // has printed so far: the window asks again for the rest. + let logs_args = ["history", "logs", "--builder", builder, "--progress", "rawjson", id]; + let raw = if info["Status"] == "Running" { + buildx_stderr_for(&logs_args, std::time::Duration::from_secs(2)).unwrap_or_default() + } else { + buildx(&logs_args).map(|(_, e)| e).unwrap_or_default() + }; let mut order: Vec = Vec::new(); let mut steps: HashMap = HashMap::new(); @@ -172,7 +279,7 @@ pub fn detail(builder: &str, id: &str) -> io::Result { /// config, read from the manifest and config BuildKit keeps with the record. /// Builds that made no image (cache only, or failed) have none. pub fn layers(builder: &str, id: &str) -> io::Result { - if !id.bytes().all(|b| b.is_ascii_alphanumeric()) || builder.starts_with('-') { + if !valid_build_ref(builder, id) { return Err(io::Error::other("not a build")); } let (info, _) = buildx(&["history", "inspect", "--builder", builder, id, "--format", "json"])?; @@ -212,18 +319,31 @@ pub fn image_layers(name: &str) -> io::Result { /// and its config. #[cfg(not(windows))] pub(crate) fn stored(store: &kiri_image::Store, name: &str) -> io::Result<(kiri_image::Image, Value, Value)> { - let found = match store.find(name)? { - Some(i) => Some(i), - // An untagged image goes by its ID, whole or the window's short form. - None => { - let id = name.trim_start_matches("sha256:"); - store.images()?.into_iter().find(|i| !id.is_empty() && i.config_digest.trim_start_matches("sha256:").starts_with(id)) - } - }; - let i = found.ok_or_else(|| io::Error::other(format!("no image {name} in Kiri")))?; + let (i, manifest, config, _pins) = stored_pinned(store, name)?; + Ok((i, manifest, config)) +} + +/// As [`stored`], keeping every blob the image references pinned until the +/// returned pins are dropped. +#[cfg(not(windows))] +pub(crate) fn stored_pinned(store: &kiri_image::Store, name: &str) -> io::Result<(kiri_image::Image, Value, Value, Vec)> { + let r = kiri_image::Reference::parse(name).ok(); + let id = name.trim_start_matches("sha256:"); + let (i, pins) = store + .with_images(|images| { + let found = images + .iter() + .find(|i| i.name == name || i.digest == name || r.as_ref().is_some_and(|r| i.matches(r))) + // An untagged image goes by its ID, whole or the window's short form. + .or_else(|| images.iter().find(|i| !id.is_empty() && i.config_digest.trim_start_matches("sha256:").starts_with(id))) + .cloned()?; + let pins = store.hold_image(&found); + Some((found, pins)) + })? + .ok_or_else(|| io::Error::other(format!("no image {name} in Kiri")))?; let manifest = json!({"config": {"digest": i.config_digest}, "layers": i.layers.iter().map(|l| json!({"size": l.size, "digest": l.digest})).collect::>()}); let config: Value = serde_json::from_slice(&store.read_config(&i.config_digest)?).map_err(io::Error::other)?; - Ok((i, manifest, config)) + Ok((i, manifest, config, pins)) } /// One platform's image: the config's history lines paired with the @@ -271,7 +391,7 @@ pub(crate) fn image(manifest: &Value, config: &Value, platform: Option<&str>) -> /// Removes a build from the history. pub fn remove(builder: &str, id: &str) -> io::Result<()> { - if !id.bytes().all(|b| b.is_ascii_alphanumeric()) || builder.starts_with('-') { + if !valid_build_ref(builder, id) { return Err(io::Error::other("not a build")); } already_gone(buildx(&["history", "rm", "--builder", builder, id]).map(|_| ()), id, || listed(builder, id)) @@ -342,25 +462,32 @@ pub fn builder() -> io::Result { std::thread::sleep(std::time::Duration::from_millis(200)); } let quiet = || std::process::Stdio::null(); - if !Command::new(&docker).args(["buildx", "version"]).stdout(quiet()).stderr(quiet()).status()?.success() { + let new_docker = || { + #[allow(unused_mut)] + let mut cmd = Command::new(&docker); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd + }; + if !new_docker().args(["buildx", "version"]).stdout(quiet()).stderr(quiet()).status()?.success() { println!("docker build: no buildx plugin here, so docker builds with Kiri's classic builder API (the same BuildKit, run by the daemon)"); return Ok(false); } - let inspect = Command::new(&docker).args(["buildx", "inspect", BUILDER.get()]).stderr(quiet()).output()?; + let inspect = new_docker().args(["buildx", "inspect", BUILDER.get()]).stderr(quiet()).output()?; let mut exists = inspect.status.success(); // Without default-load a docker-container builder keeps what it builds // to itself: `docker build -t x .` builds and `docker run x` finds // nothing. One made without it is made again; --keep-state keeps its // cache volume, which the daemon's builder container reuses. if exists && !String::from_utf8_lossy(&inspect.stdout).contains("default-load") { - exists = !Command::new(&docker).args(["buildx", "rm", "--keep-state", BUILDER.get()]).stdout(quiet()).stderr(quiet()).status()?.success(); + exists = !new_docker().args(["buildx", "rm", "--keep-state", BUILDER.get()]).stdout(quiet()).stderr(quiet()).status()?.success(); } if !exists { // buildx create takes the Kiri context's name; without that context // (Linux makes it only in the optional "docker uses Kiri" step) buildx // reads the name as a host and fails on tcp://kiri:2375. ensure_context(&docker)?; - let made = Command::new(&docker) + let made = new_docker() .args(["buildx", "create", "--name", BUILDER.get(), "--driver", "docker-container", "--driver-opt", "default-load=true", CONTEXT.get()]) .stdout(quiet()) .output()?; @@ -376,13 +503,24 @@ pub fn builder() -> io::Result { Ok(true) } -/// The docker context named CONTEXT, pointing at Kiri's socket, made when -/// missing. It is only made, never made current: which engine plain docker -/// uses stays the user's choice. -/// On Windows, setup (kiri.ps1) makes the context, on the pipe. -#[cfg(not(unix))] -fn ensure_context(_docker: impl AsRef) -> io::Result<()> { - Ok(()) +/// The docker context named CONTEXT, pointing at Kiri's socket or Windows +/// named pipe, made when missing. It is only made, never made current: which +/// engine plain docker uses stays the user's choice. +#[cfg(windows)] +fn ensure_context(docker: impl AsRef) -> io::Result<()> { + let docker = docker.as_ref(); + let quiet = || std::process::Stdio::null(); + let new_cmd = || { + let mut cmd = Command::new(docker); + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd + }; + if new_cmd().args(["context", "inspect", CONTEXT.get()]).stdout(quiet()).stderr(quiet()).status()?.success() { + return Ok(()); + } + let host = format!("host=npipe://{}", crate::client::pipe().replace('\\', "/")); + let out = new_cmd().args(["context", "create", CONTEXT.get(), "--description", "Kiri (WSL2)", "--docker", &host]).stdout(quiet()).output()?; + if out.status.success() { Ok(()) } else { Err(io::Error::other(failure("docker context create failed", &out.stderr))) } } #[cfg(unix)] @@ -410,6 +548,22 @@ fn failure(what: &str, stderr: &[u8]) -> String { mod tests { use super::*; + /// A follower that never exits (a running build's `history logs`, its + /// plugin a child of docker) gives what it printed and is gone (#923). + #[cfg(unix)] + #[test] + fn a_follower_gives_what_it_printed_and_is_stopped_with_its_children() { + let marker = format!("kiri-builds-follow-{}", std::process::id()); + let mut cmd = Command::new("sh"); + cmd.args(["-c", &format!("echo '{{\"a\":1}}' >&2; sh -c 'exec sleep 30 {marker}' 2>/dev/null & sleep 30; wait")]); + let started = std::time::Instant::now(); + let out = stderr_for(cmd, std::time::Duration::from_millis(500)).unwrap(); + assert!(started.elapsed() < std::time::Duration::from_secs(3), "{:?}", started.elapsed()); + assert_eq!(values(&out), vec![json!({"a": 1})]); + let left = Command::new("pgrep").args(["-f", &marker]).output().unwrap(); + assert!(left.stdout.is_empty(), "left running: {}", String::from_utf8_lossy(&left.stdout)); + } + /// A build already removed (a second click, or several removed at once) /// is removed: BuildKit's "lease not found" isn't an error to show. But /// BuildKit says the same for a build still running, which stays listed: @@ -470,6 +624,62 @@ mod tests { assert_eq!(values("{\"a\":1}\n{\"a\":2}").len(), 2); assert_eq!(values("{\"a\":1}{\"a\":2}").len(), 2); } + + #[test] + fn discovers_every_buildkit_builder_on_kiris_engine() { + let host = "unix:///Users/alice/.kiri/run/docker.sock"; + let buildx_ls = vec![ + json!({"Name": "kiri-build", "Driver": "docker-container", "Nodes": [{"Name": "kiri-build0", "Endpoint": "kiri"}]}), + json!({"Name": "default", "Driver": "docker-container", "Nodes": [{"Name": "default", "Endpoint": "default"}]}), + json!({"Name": "compose-url", "Driver": "docker-container", "Nodes": [{"Name": "compose-url0", "Endpoint": host}]}), + json!({"Name": "custom-kiri", "Driver": "docker-container", "Nodes": [{"Name": "custom-kiri0", "Endpoint": "kiri"}]}), + // Duplicate name must appear only once, keeping first-seen order. + json!({"Name": "kiri-build", "Driver": "docker-container", "Nodes": [{"Name": "kiri-build0", "Endpoint": "kiri"}]}), + // Builder on Kiri without an existing BuildKit container must be skipped (never wake/create). + json!({"Name": "not-started", "Driver": "docker-container", "Nodes": [{"Name": "not-started0", "Endpoint": "kiri"}]}), + json!({"Name": "default-missing", "Driver": "docker-container", "Nodes": [{"Name": "default-missing0", "Endpoint": "default"}]}), + // Non-docker-container driver must be skipped. + json!({"Name": "plain-docker", "Driver": "docker", "Nodes": [{"Name": "default", "Endpoint": "default"}]}), + // Foreign contexts / sockets must be rejected even if a container of that name exists. + json!({"Name": "desktop-builder", "Driver": "docker-container", "Nodes": [{"Name": "desktop-builder0", "Endpoint": "desktop-linux"}]}), + json!({"Name": "orb-builder", "Driver": "docker-container", "Nodes": [{"Name": "orb-builder0", "Endpoint": "orbstack"}]}), + json!({"Name": "other-sock", "Driver": "docker-container", "Nodes": [{"Name": "other-sock0", "Endpoint": "unix:///var/run/other.sock"}]}), + ]; + let containers = json!([ + {"Names": ["/buildx_buildkit_kiri-build0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_default"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_compose-url0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_custom-kiri0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_desktop-builder0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_orb-builder0"], "Image": "moby/buildkit:buildx-stable-1"}, + {"Names": ["/buildx_buildkit_other-sock0"], "Image": "moby/buildkit:buildx-stable-1"}, + ]); + let found = builders_from(&buildx_ls, &containers, "kiri", host); + assert_eq!(found, vec!["kiri-build", "default", "compose-url", "custom-kiri"]); + } + + #[test] + fn matches_windows_npipe_endpoints_case_and_slash_insensitively() { + let host = "npipe:////./pipe/kiri"; + let buildx_ls = vec![ + json!({"Name": "default", "Driver": "docker-container", "Nodes": [{"Name": "default", "Endpoint": r"NPIPE://\\.\pipe\KIRI"}]}), + json!({"Name": "other-pipe", "Driver": "docker-container", "Nodes": [{"Name": "other-pipe0", "Endpoint": "npipe:////./pipe/docker_engine"}]}), + ]; + let containers = json!([ + {"Names": ["/buildx_buildkit_default"]}, + {"Names": ["/buildx_buildkit_other-pipe0"]}, + ]); + assert_eq!(builders_from(&buildx_ls, &containers, "kiri", host), vec!["default"]); + } + + #[test] + fn rejects_empty_or_flag_like_builder_in_detail_layers_and_remove() { + for (builder, id) in [("", "abc123"), ("-bad", "abc123"), ("--builder", "abc123"), ("kiri-build", ""), ("kiri-build", "bad/id")] { + assert_eq!(detail(builder, id).unwrap_err().to_string(), "not a build", "detail({builder:?}, {id:?})"); + assert_eq!(layers(builder, id).unwrap_err().to_string(), "not a build", "layers({builder:?}, {id:?})"); + assert_eq!(remove(builder, id).unwrap_err().to_string(), "not a build", "remove({builder:?}, {id:?})"); + } + } } /// An image in a real store: diff --git a/crates/kiri/src/buildwith.rs b/crates/kiri/src/buildwith.rs index 87832d19d..68a927ee3 100644 --- a/crates/kiri/src/buildwith.rs +++ b/crates/kiri/src/buildwith.rs @@ -86,14 +86,28 @@ fn read_json(path: &Path) -> io::Result { } } +fn read_object(path: &Path) -> io::Result { + let v = read_json(path)?; + if v.is_object() { + Ok(v) + } else { + Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", path.display()))) + } +} + /// Through a temporary file, so a crash never leaves half a file. fn write_bytes(path: &Path, bytes: &[u8]) -> io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("kiri-tmp"); - std::fs::write(&tmp, bytes)?; - std::fs::rename(tmp, path) + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir)?; + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("tmp"); + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); + let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + if res.is_err() { + let _ = std::fs::remove_file(&tmp); + } + res } fn write_json(path: &Path, v: &Value) -> io::Result<()> { @@ -114,7 +128,7 @@ impl Places { } fn state(&self) -> Value { - read_json(&self.state).unwrap_or_else(|_| json!({})) + read_json(&self.state).ok().filter(Value::is_object).unwrap_or_else(|| json!({})) } /// What was chosen (or set for a machine with no other engine). @@ -163,10 +177,16 @@ impl Places { Ok(()) } - /// Whether a builder is Kiri's copy: its nodes are Kiri's builder's. + /// Whether a builder is Kiri's copy: its nodes are Kiri's builder's (`0`, …). fn copied(&self, instance: &Value) -> bool { let nodes = instance["Nodes"].as_array().map(Vec::as_slice).unwrap_or_default(); - !nodes.is_empty() && nodes.iter().all(|n| n["Name"].as_str().is_some_and(|name| name.starts_with(&self.builder))) + !nodes.is_empty() + && nodes.iter().all(|n| { + n["Name"] + .as_str() + .and_then(|name| name.strip_prefix(&self.builder)) + .is_some_and(|idx| !idx.is_empty() && idx.bytes().all(|b| b.is_ascii_digit())) + }) } fn save(&self, with: With, auto: bool) -> io::Result<()> { @@ -185,7 +205,7 @@ impl Places { } let mut s = self.state(); if s["before"].is_null() { - let cfg = read_json(&self.config())?; + let cfg = read_object(&self.config())?; let current = match std::fs::read_to_string(self.current()) { Ok(t) => Value::String(t), Err(e) if e.kind() == io::ErrorKind::NotFound => Value::Null, @@ -194,7 +214,7 @@ impl Places { s["before"] = json!({"alias": cfg["aliases"]["builder"], "aliases": cfg.get("aliases").is_some(), "current": current}); write_json(&self.state, &s)?; } - let mut cfg = read_json(&self.config())?; + let mut cfg = read_object(&self.config())?; if !cfg["aliases"].is_object() { cfg["aliases"] = json!({}); } @@ -217,7 +237,7 @@ impl Places { if before.is_null() { return Ok(()); } - let mut cfg = read_json(&self.config())?; + let mut cfg = read_object(&self.config())?; if cfg["aliases"]["builder"] == "buildx" { match &before["alias"] { Value::Null => { @@ -417,13 +437,27 @@ pub fn ask() -> Option<&'static str> { places().ok().filter(|p| p.ask(other)).and(other) } -/// `kiri build-with [docker|kiri]`: says which, or switches. -#[cfg(unix)] +const USAGE: &str = "usage: kiri build-with [docker|kiri|status]"; + +/// `kiri build-with [docker|kiri|status]`: says which, or switches. +#[cfg(any(unix, windows))] pub fn cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + if args.len() > 1 { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)); + } + let choice = match args.first().map(String::as_str) { + None | Some("status") => None, + Some(a) => Some(With::parse(a).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, USAGE))?), + }; let p = places()?; let other = other_engine(); - if let Some(a) = args.first() { - let with = With::parse(a).ok_or_else(|| io::Error::other("usage: kiri build-with [docker|kiri]"))?; + if let Some(with) = choice { p.choose(with)?; if with == With::Kiri && !p.ready() { crate::builds::ensure_builder(); @@ -598,4 +632,37 @@ mod tests { assert_eq!(read_json(&p.config()).unwrap(), json!({})); assert!(!p.current().exists() && !p.instance("kiri").exists() && !p.state.exists()); } + + #[test] + fn rejects_non_object_configs_without_panicking_and_preserves_prefix_builders() { + let d = scratch("non-obj"); + let p = places(&d); + builder(&p); + std::fs::create_dir_all(&p.docker).unwrap(); + for bad in ["[1, 2]", "\"str\"", "true", "null"] { + std::fs::write(p.config(), bad).unwrap(); + assert_eq!(p.choose(With::Kiri).unwrap_err().kind(), io::ErrorKind::InvalidData, "{bad}"); + assert_eq!(std::fs::read_to_string(p.config()).unwrap(), bad); + } + std::fs::remove_file(p.config()).unwrap(); + + // Corrupt non-object build.json recovers as `{}` without panicking. + std::fs::create_dir_all(p.state.parent().unwrap()).unwrap(); + std::fs::write(&p.state, "[1, 2]").unwrap(); + p.choose(With::Kiri).unwrap(); + assert!(p.taken()); + p.choose(With::Docker).unwrap(); + assert!(!p.taken()); + + // Foreign builders whose node names share prefix `kiri-build` (`kiri-builder0`, `kiri-build-dev0`) stay untouched. + for node_name in ["kiri-builder0", "kiri-build-dev0", "kiri-build"] { + let foreign = json!({"Name": "kiri", "Driver": "docker-container", "Nodes": [{"Name": node_name, "Endpoint": "desktop-linux"}]}); + write_json(&p.instance("kiri"), &foreign).unwrap(); + p.choose(With::Docker).unwrap(); + assert_eq!(read_json(&p.instance("kiri")).unwrap(), foreign, "{node_name}"); + p.uninstall().unwrap(); + assert!(p.instance("kiri").is_file(), "{node_name}"); + } + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/cli_pins.rs b/crates/kiri/src/cli_pins.rs index b5d8d4717..d62b2b511 100644 --- a/crates/kiri/src/cli_pins.rs +++ b/crates/kiri/src/cli_pins.rs @@ -5,7 +5,7 @@ #![allow(dead_code)] pub const DOCKER_CLI: (&str, &str) = ("29.9.2", "ea8a2ce5ac31f9f5f3fb711a7a485e1e46cc7a69798a629a70306f6e6af25b7a"); -pub const COMPOSE: (&str, &str) = ("v5.6.1", "fcce41226abd2b7b2936094e688bbd61284673dddafea542e08cb9a3b4423a8b"); +pub const COMPOSE: (&str, &str) = ("v5.8.0", "008b8fcf6c6d60340f5796626a0f0d51c042085793a9b1653343011727140b71"); pub const BUILDX: (&str, &str) = ("v0.38.1", "6f20ba2437865311ef99015bf5d1039c3c8e4d2177c1c64aa41b134b5ecd3012"); /// Grype, Anchore's image scanner (Builds → Security): the Apple Silicon @@ -46,7 +46,7 @@ pub fn buildx_url(v: &str) -> String { /// (`cargo xtask app --arch x86_64`). Compose and buildx are GitHub's asset /// digests; the docker tarball as download.docker.com served it. pub const X86_DOCKER_CLI: (&str, &str) = ("29.9.2", "089c3f618df88bdef4f1257d9d604499136a1ec5168b67d194c260acad2b522f"); -pub const X86_COMPOSE: (&str, &str) = ("v5.6.1", "245c191b11a6345dd3b32b8f6eadeed1e1dcd5147aa46dfa423462e95f587e93"); +pub const X86_COMPOSE: (&str, &str) = ("v5.8.0", "5c41cd573c549dc66abb03c5b29d6d4dfaae206b2e79848d1c32482bb2a3b416"); pub const X86_BUILDX: (&str, &str) = ("v0.38.1", "76e7a809cc98d34a4c1b7db23feac673def5b8dcdddd9e713ef26598689aa796"); pub const X86_GRYPE: (&str, &str) = ("0.120.1", "5313004ccbc524c8757521dc3913f1edf4309f56bef06a2fb2d0c0eeade7cc62"); @@ -120,7 +120,7 @@ impl MacArch { /// `docker/docker` inside download.docker.com's static tarball; Compose and /// buildx are GitHub's asset digests. pub const LINUX_DOCKER_CLI: (&str, &str) = ("29.9.2", "9ac225999fd5e863f7694c728ef23d480616b1e5639328fa309befd4243d69eb"); -pub const LINUX_COMPOSE: (&str, &str) = ("v5.6.1", "47737f4236e6d3ccea7291995203f8f018058783b4c3a9469119811a0b5db8c0"); +pub const LINUX_COMPOSE: (&str, &str) = ("v5.8.0", "b8840f5008c447f41fce0a57ae3adeab42c89b1eb6e6012524bcabbfb4ffbaf6"); pub const LINUX_BUILDX: (&str, &str) = ("v0.38.1", "e25d5cd675092bb5d1d03632fdc46cdf3fede7b514dc5f023a105e00d3ce5ad4"); pub fn linux_docker_url(v: &str) -> String { @@ -138,14 +138,14 @@ pub fn linux_buildx_url(v: &str) -> String { /// The same versions for Linux arm64, in the arm64 `kiri` .deb and .rpm, /// from the same places (packaging/linux/fetch-cli.sh). pub const LINUX_ARM64_DOCKER_CLI: (&str, &str) = ("29.9.2", "873b3e0207857c3b2f28392fb922f3ea6efe37620c16d4d4aaf2fef409c90b73"); -pub const LINUX_ARM64_COMPOSE: (&str, &str) = ("v5.6.1", "42cfa75f51ad0ccf290bad37899e0038a8c10a0069e85233ecc1d53e3ff1347d"); +pub const LINUX_ARM64_COMPOSE: (&str, &str) = ("v5.8.0", "1a9c918b2fb49b9c87f0018c64b5abd0d30715155e98dc939779fbaee6c414d3"); pub const LINUX_ARM64_BUILDX: (&str, &str) = ("v0.38.1", "3b83b3731916ba433feccaaa689fe5bcdc81c641d92c8e6c2ea865dfa141c97a"); /// The same versions for Windows x86-64, bundled with kiri-win /// (`cargo xtask windows`). Compose and buildx are GitHub's asset digests; /// the docker CLI's zip as download.docker.com served it. pub const WIN_DOCKER_CLI: (&str, &str) = ("29.9.2", "b2be959bfed1281ddaf665c0972cba9a62ce30c542b6bcce82f055bf8886bc7d"); -pub const WIN_COMPOSE: (&str, &str) = ("v5.6.1", "91b1492f0a923427651e2b955739d732ac36b8191193bf4799e62f3e3525c4cd"); +pub const WIN_COMPOSE: (&str, &str) = ("v5.8.0", "0c2d9245a5f61e8e3cc85009b8b4888fa82fded08239d28bd6da5ca818eda2b2"); pub const WIN_BUILDX: (&str, &str) = ("v0.38.1", "fd2e18501910dd535ea3aa7f69010b3cfdfba0f47aa27674124554386dfa26f3"); /// The static docker CLI for Windows; the binary is `docker/docker.exe` inside. @@ -167,7 +167,7 @@ pub fn win_buildx_url(v: &str) -> String { /// x86_64 only), so it is built from docker/cli's own source at the release /// tag's commit, with Go's toolchain pinned and cgo off: Go builds that way /// are reproducible on any host, so the result is pinned like a download. -pub const WIN_ARM64_COMPOSE: (&str, &str) = ("v5.6.1", "2a8ab89b27a7ba79c3ec5b3eb59e099b39990d2c7ea47fc38433fc24812ad266"); +pub const WIN_ARM64_COMPOSE: (&str, &str) = ("v5.8.0", "ec7a100a77d9aedbaa6e2b13a10140729860b58b8d2b6855d8191c52e7dd50fc"); pub const WIN_ARM64_BUILDX: (&str, &str) = ("v0.38.1", "2d4e2e78d7ddf0ea6d63acde7e73599717e94e3f9417edd23d4ffeceef6777fc"); /// docker/cli at tag v29.9.2 (WIN_DOCKER_CLI's version): the commit the diff --git a/crates/kiri/src/client.rs b/crates/kiri/src/client.rs index d0fb0a493..7b80ce4d9 100644 --- a/crates/kiri/src/client.rs +++ b/crates/kiri/src/client.rs @@ -1,27 +1,138 @@ //! The window and `kiri` subcommands talk to `kiri daemon` the way the docker CLI does: HTTP over -//! the daemon's unix socket. One short connection per request, and one -//! long-lived one for `/events`. +//! the daemon's unix socket (or `\\.\pipe\kiri` on Windows). One short connection per request, +//! and one long-lived one for `/events`. // Parts of this serve only the Mac (the window, boot timings). #![cfg_attr(not(target_os = "macos"), allow(dead_code))] +#[cfg(any(unix, test))] +use std::ffi::OsStr; use std::io::{self, BufRead, BufReader, Read, Write}; +#[cfg(unix)] use std::os::unix::net::UnixStream; +#[cfg(any(unix, test))] +use std::path::Component; use std::path::PathBuf; +#[cfg(any(unix, test))] +use std::path::Path; use std::time::Duration; use serde_json::Value; +#[cfg(windows)] +pub const DEFAULT_PIPE: &str = r"\\.\pipe\kiri"; + +/// The Windows named pipe `kiri-win` serves the Docker API on. +#[cfg(windows)] +pub fn pipe() -> String { + std::env::var("KIRI_PIPE") + .ok() + .filter(|s| !s.is_empty()) + .unwrap_or_else(|| DEFAULT_PIPE.to_owned()) +} + +#[cfg(unix)] pub fn socket() -> io::Result { - if let Some(s) = std::env::var_os("KIRI_SOCKET") { + let kiri_socket = std::env::var_os("KIRI_SOCKET"); + let home = std::env::var_os("HOME"); + #[cfg(target_os = "linux")] + { + let wsl_distro = std::env::var_os("WSL_DISTRO_NAME"); + let wsl_sockets_dir = PathBuf::from(crate::daemon::binds::wsl_kiri_dir()).join("sockets"); + socket_for( + kiri_socket.as_deref(), + Some(Path::new(SERVICE_SOCKET)), + wsl_distro.as_deref(), + Some(wsl_sockets_dir.as_path()), + &[Path::new("/var/run/docker.sock"), Path::new("/run/docker.sock")], + home.as_deref(), + ) + } + #[cfg(not(target_os = "linux"))] + { + socket_for(kiri_socket.as_deref(), None, None, None, &[], home.as_deref()) + } +} + +#[cfg(any(unix, test))] +fn safe_wsl_distro(name: &str) -> bool { + #[cfg(unix)] + { + crate::daemon::binds::valid_distro_name(name) && !name.contains("..") + } + #[cfg(not(unix))] + { + !name.is_empty() + && !name.contains("..") + && name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.')) + } +} + +#[cfg(any(unix, test))] +fn is_wsl_socket_path(target: &Path, wsl_sockets_dir: &Path) -> bool { + let Ok(rel) = target.strip_prefix(wsl_sockets_dir) else { + return false; + }; + let mut comps = rel.components(); + match (comps.next(), comps.next(), comps.next()) { + (Some(Component::Normal(distro)), Some(Component::Normal(file)), None) => { + distro.to_str().is_some_and(safe_wsl_distro) && file == "docker.sock" + } + _ => false, + } +} + +/// Whether a socket path is present on disk, treating `EACCES` on a parent +/// directory (such as a `0750` WSL integration socket directory) as present so +/// `check_alive` surfaces a clear permission-denied error instead of falling +/// back to a missing home socket. +#[cfg(any(unix, test))] +fn socket_present(path: &Path) -> bool { + match std::fs::metadata(path) { + Ok(_) => true, + Err(e) => e.kind() == io::ErrorKind::PermissionDenied, + } +} + +#[cfg(any(unix, test))] +fn socket_for( + kiri_socket: Option<&OsStr>, + service_socket: Option<&Path>, + wsl_distro: Option<&OsStr>, + wsl_sockets_dir: Option<&Path>, + docker_sock_links: &[&Path], + home: Option<&OsStr>, +) -> io::Result { + if let Some(s) = kiri_socket { return Ok(PathBuf::from(s)); } - // Linux: the engine is the `kiri` system service (contrib/linux/kiri.service). - #[cfg(target_os = "linux")] - if std::path::Path::new(SERVICE_SOCKET).exists() { - return Ok(PathBuf::from(SERVICE_SOCKET)); + // Linux: the engine is the `kiri` system service (contrib/linux/kiri.service) + // or a root-run `sudo kiri daemon` at `/run/kiri/docker.sock`. + if let Some(service) = service_socket + && socket_present(service) + { + return Ok(service.to_path_buf()); } - let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; + // WSL 2 integration: Kiri for Windows exposes per-distro sockets under + // `/mnt/wsl/kiri/sockets//docker.sock` and symlinks + // `/var/run/docker.sock` to them. + if let Some(wsl_dir) = wsl_sockets_dir { + if let Some(distro) = wsl_distro.and_then(|d| d.to_str()).filter(|d| safe_wsl_distro(d)) { + let candidate = wsl_dir.join(distro).join("docker.sock"); + if socket_present(&candidate) { + return Ok(candidate); + } + } + for link in docker_sock_links { + if let Ok(target) = std::fs::read_link(link) + && is_wsl_socket_path(&target, wsl_dir) + && socket_present(&target) + { + return Ok(target); + } + } + } + let home = home.map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; Ok(home.join(crate::flavor::STATE.get()).join("run/docker.sock")) } @@ -50,12 +161,106 @@ impl Response { } } -fn connect(timeout: Option) -> io::Result { - let s = UnixStream::connect(socket()?)?; +#[cfg(unix)] +fn op_header() -> String { + crate::diag::op_header() +} + +#[cfg(windows)] +fn op_header() -> String { + String::new() +} + +#[cfg(unix)] +fn connect_to(sock: &Path, timeout: Option) -> io::Result { + let s = UnixStream::connect(sock)?; s.set_read_timeout(timeout)?; Ok(s) } +#[cfg(unix)] +fn connect(timeout: Option) -> io::Result { + connect_to(&socket()?, timeout) +} + +#[cfg(windows)] +struct WinPipe(std::fs::File); + +#[cfg(windows)] +impl WinPipe { + fn open(name: &str) -> io::Result { + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; + const ERROR_PIPE_BUSY: i32 = 231; + const SECURITY_IDENTIFICATION: u32 = 0x0001_0000; + const PIPE_READMODE_MESSAGE: u32 = 0x0000_0002; + unsafe extern "system" { + fn SetNamedPipeHandleState( + hNamedPipe: *mut core::ffi::c_void, + lpMode: *const u32, + lpMaxCollectionCount: *const u32, + lpCollectDataTimeout: *const u32, + ) -> i32; + } + for _ in 0..20 { + match std::fs::OpenOptions::new() + .read(true) + .write(true) + .share_mode(0) + .security_qos_flags(SECURITY_IDENTIFICATION) + .open(name) + { + Ok(file) => { + // `kiri-win` serves `\\.\pipe\kiri` in message mode and ends + // unframed HTTP responses with a 0-byte message. + let mode = PIPE_READMODE_MESSAGE; + // SAFETY: `file` owns a valid handle for the duration of the call. + unsafe { + SetNamedPipeHandleState( + file.as_raw_handle(), + &mode, + std::ptr::null(), + std::ptr::null(), + ); + } + return Ok(Self(file)); + } + Err(e) if e.raw_os_error() == Some(ERROR_PIPE_BUSY) => { + std::thread::sleep(Duration::from_millis(50)); + } + Err(e) => return Err(e), + } + } + Err(io::Error::new(io::ErrorKind::TimedOut, format!("pipe {name} stayed busy"))) + } +} + +#[cfg(windows)] +impl Read for WinPipe { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + const ERROR_BROKEN_PIPE: i32 = 109; + const ERROR_PIPE_NOT_CONNECTED: i32 = 233; + const ERROR_MORE_DATA: i32 = 234; + match self.0.read(buf) { + Ok(n) => Ok(n), + Err(e) if e.raw_os_error() == Some(ERROR_MORE_DATA) => Ok(buf.len()), + Err(e) if matches!(e.raw_os_error(), Some(ERROR_BROKEN_PIPE | ERROR_PIPE_NOT_CONNECTED)) => Ok(0), + Err(e) => Err(e), + } + } +} + +#[cfg(windows)] +impl Write for WinPipe { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.0.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + fn head(r: &mut impl BufRead) -> io::Result<(u16, Option, bool)> { let mut line = String::new(); r.read_line(&mut line)?; @@ -112,16 +317,46 @@ pub fn get_background(path: &str) -> io::Result { Ok(r.json()) } +#[cfg(unix)] fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { - let mut s = connect(Some(Duration::from_secs(120)))?; + send_to(&socket()?, method, path, body, extra) +} + +#[cfg(unix)] +fn send_to(sock: &Path, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + let mut s = connect_to(sock, Some(Duration::from_secs(120)))?; let payload = body.map(Value::to_string).unwrap_or_default(); // The window's action this is part of, for the engine's log lines. - let op = crate::diag::op_header(); + let op = op_header(); + write!( + s, + "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", + payload.len() + )?; + answer(s) +} + +#[cfg(windows)] +fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + send_to_pipe(&pipe(), method, path, body, extra) +} + +#[cfg(windows)] +fn send_to_pipe(name: &str, method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Result { + let mut s = WinPipe::open(name)?; + let payload = body.map(Value::to_string).unwrap_or_default(); + let op = op_header(); write!( s, "{method} {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{extra}{op}Content-Type: application/json\r\nContent-Length: {}\r\n\r\n{payload}", payload.len() )?; + s.flush()?; + answer(s) +} + +/// The answer to a request just sent; the whole body is read, chunked or not. +fn answer(s: impl Read) -> io::Result { let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut body = Vec::new(); @@ -142,6 +377,79 @@ fn send(method: &str, path: &str, body: Option<&Value>, extra: &str) -> io::Resu Ok(Response { status, body }) } +/// A POST whose body `write` streams, chunked, so its length need not be +/// known first: `kiri import`'s copy of a container's writable layer. A +/// body `write` gives up on is never ended, so the daemon sees it cut +/// short, not as a whole one; if the daemon stopped reading first (it +/// refused the request), its answer is returned, which says why. +#[cfg(unix)] +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + let s = connect(Some(Duration::from_secs(300)))?; + let op = op_header(); + (&s).write_all(format!("POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n").as_bytes())?; + match stream_body(&s, write) { + Ok(()) => answer(&s), + Err(e) if refused(&e) => match answer(&s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + +#[cfg(windows)] +pub fn post_stream(path: &str, content_type: &str, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result { + let mut s = WinPipe::open(&pipe())?; + let op = op_header(); + write!( + s, + "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{op}Content-Type: {content_type}\r\nTransfer-Encoding: chunked\r\n\r\n" + )?; + match stream_body(&mut s, write) { + Ok(()) => answer(s), + Err(e) if refused(&e) => match answer(s) { + Ok(r) if !r.ok() => Ok(r), + _ => Err(e), + }, + Err(e) => Err(e), + } +} + +/// Writes a body chunked, in chunks of up to 256 KiB, and ends it only when +/// `write` succeeds. +pub(crate) fn stream_body(to: impl Write, write: impl FnOnce(&mut dyn Write) -> io::Result<()>) -> io::Result<()> { + let mut body = io::BufWriter::with_capacity(256 << 10, Chunked(to)); + write(&mut body)?; + let mut chunked = body.into_inner().map_err(io::IntoInnerError::into_error)?; + chunked.0.write_all(b"0\r\n\r\n")?; + chunked.0.flush() +} + +/// Whether a write failed because the other end closed: the daemon may +/// have answered before reading the whole body. +fn refused(e: &io::Error) -> bool { + matches!(e.kind(), io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionAborted) +} + +/// HTTP/1.1 chunked transfer coding: each write is one chunk. +struct Chunked(W); + +impl Write for Chunked { + fn write(&mut self, buf: &[u8]) -> io::Result { + if buf.is_empty() { + return Ok(0); + } + write!(self.0, "{:x}\r\n", buf.len())?; + self.0.write_all(buf)?; + self.0.write_all(b"\r\n")?; + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + self.0.flush() + } +} + /// Kiri's own version from a `/version` answer: `KiriVersion`, or `Version` /// from an engine older than that field (it reported Kiri's version there; /// it is now the Docker Engine version clients gate on). @@ -162,19 +470,128 @@ pub fn alive() -> bool { send("GET", "/_ping", None, "X-Kiri-Background: 1\r\n").is_ok_and(|r| r.ok()) } +#[cfg(any(target_os = "linux", test))] +fn is_wsl_env(wsl_distro: Option<&OsStr>, wsl_interop_paths: &[&Path]) -> bool { + wsl_distro.is_some_and(|s| !s.is_empty()) || wsl_interop_paths.iter().any(|p| p.exists()) +} + +fn not_running_message_for(is_linux: bool, is_wsl: bool) -> &'static str { + if !is_linux { + "Kiri isn't running. Open Kiri, or start it with `kiri daemon`" + } else if is_wsl { + "Kiri isn't running. Open Kiri on Windows (and enable this distro in Settings -> Resources -> WSL integration), or run `sudo kiri host-access $USER`" + } else { + "Kiri isn't running. Open Kiri, or run `sudo kiri host-access $USER` (or `sudo kiri daemon`)" + } +} + +/// Actionable OS-specific error text when the engine is not running. +pub fn not_running_message() -> &'static str { + #[cfg(windows)] + { + "Kiri isn't running. Open Kiri, or start it with `kiri start`" + } + #[cfg(not(windows))] + { + #[cfg(target_os = "linux")] + let wsl = is_wsl_env( + std::env::var_os("WSL_DISTRO_NAME").as_deref(), + &[Path::new("/proc/sys/fs/binfmt_misc/WSLInterop"), Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late")], + ); + #[cfg(not(target_os = "linux"))] + let wsl = false; + not_running_message_for(cfg!(target_os = "linux"), wsl) + } +} + +#[cfg(any(unix, test))] +fn permission_denied_error(sock: &Path, is_linux: bool) -> io::Error { + let msg = if is_linux { + format!( + "cannot connect to Kiri's socket ({}): permission denied. Run `sudo kiri host-access $USER` (or open Kiri) to grant access", + sock.display() + ) + } else { + format!("cannot connect to Kiri's socket ({}): permission denied", sock.display()) + }; + io::Error::new(io::ErrorKind::PermissionDenied, msg) +} + +#[cfg(unix)] +fn check_alive_at(sock: &Path, not_running: &str) -> io::Result<()> { + match send_to(sock, "GET", "/_ping", None, "X-Kiri-Background: 1\r\n") { + Ok(r) if r.ok() => Ok(()), + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => Err(permission_denied_error(sock, cfg!(target_os = "linux"))), + _ => Err(io::Error::new(io::ErrorKind::NotConnected, not_running)), + } +} + +#[cfg(unix)] +pub(crate) fn probe_socket(sock: &Path) -> io::Result<()> { + check_alive_at(sock, not_running_message()) +} + +#[cfg(unix)] +pub(crate) fn get_background_at(sock: &Path, path: &str) -> io::Result { + let r = send_to(sock, "GET", path, None, "X-Kiri-Background: 1\r\n")?; + if !r.ok() { + return Err(io::Error::other(r.error())); + } + Ok(r.json()) +} + +/// Probes the engine socket, distinguishing `PermissionDenied` (`EACCES`) from +/// the daemon not running and formatting OS-appropriate guidance. +pub fn check_alive() -> io::Result<()> { + check_alive_with(not_running_message()) +} + +/// Like [`check_alive`], using `not_running` when the daemon is not running. +#[cfg(unix)] +pub fn check_alive_with(not_running: &str) -> io::Result<()> { + let sock = socket()?; + check_alive_at(&sock, not_running) +} + +#[cfg(windows)] +pub fn check_alive_with(not_running: &str) -> io::Result<()> { + let p = pipe(); + match send_to_pipe(&p, "GET", "/_ping", None, "X-Kiri-Background: 1\r\n") { + Ok(r) if r.ok() => Ok(()), + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("cannot connect to Kiri's pipe ({p}): permission denied"), + )), + _ => Err(io::Error::new(io::ErrorKind::NotConnected, not_running)), + } +} + /// A POST whose answer is JSON lines arriving over time (a pull's /// progress): `on_line` sees each as it comes. Returns the HTTP status. /// `auth` is a registry sign-in for a pull (`X-Registry-Auth`, base64url). /// `opened` gets the connection once it is made, so another thread can /// shut it down to stop the request (Cancel on a pull). -pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { +#[cfg(unix)] +pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(&UnixStream), on_line: impl FnMut(Value)) -> io::Result { + post_lines_inner(path, auth, Some(Duration::from_secs(120)), opened, on_line) +} + +/// Like `post_lines_closable` without a read timeout, for long-running +/// streamed operations such as `/kiri/images/scan` (first-time DB download). +#[cfg(target_os = "linux")] +pub fn post_lines_unbounded(path: &str, on_line: impl FnMut(Value)) -> io::Result { + post_lines_inner(path, None, None, |_| {}, on_line) +} + +#[cfg(unix)] +fn post_lines_inner(path: &str, auth: Option<&str>, timeout: Option, opened: impl FnOnce(&UnixStream), mut on_line: impl FnMut(Value)) -> io::Result { if auth.is_some_and(|a| a.contains(['\r', '\n'])) { return Err(io::Error::new(io::ErrorKind::InvalidInput, "header contains a line break")); } let auth = auth.map(|a| format!("X-Registry-Auth: {a}\r\n")).unwrap_or_default(); - let mut s = connect(Some(Duration::from_secs(120)))?; + let mut s = connect(timeout)?; opened(&s); - write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", crate::diag::op_header())?; + write!(s, "POST {path} HTTP/1.1\r\nHost: kiri\r\nConnection: close\r\n{auth}{}Content-Type: application/json\r\nContent-Length: 0\r\n\r\n", op_header())?; let mut r = BufReader::new(s); let (status, len, chunked) = head(&mut r)?; let mut pending = Vec::new(); @@ -204,6 +621,7 @@ pub fn post_lines_closable(path: &str, auth: Option<&str>, opened: impl FnOnce(& } /// Calls `on_event` for each event until the connection ends or it returns false. +#[cfg(unix)] pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { let mut s = connect(None)?; write!(s, "GET /events HTTP/1.1\r\nHost: kiri\r\nX-Kiri-Background: 1\r\n\r\n")?; @@ -229,10 +647,12 @@ pub fn events(mut on_event: impl FnMut(Value) -> bool) -> io::Result<()> { /// A long-lived streamed response, such as `logs?follow=1`, read chunk by /// chunk. `closer` ends it from another thread. +#[cfg(unix)] pub struct Stream { reader: BufReader, } +#[cfg(unix)] impl Stream { pub fn open(path: &str) -> io::Result { let mut s = connect(None)?; @@ -257,6 +677,7 @@ impl Stream { /// Runs `cmd` in a running container and returns (exit code, output), /// through the exec API with a terminal, so output arrives unframed. +#[cfg(unix)] pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { let created = request("POST", &format!("/containers/{container}/exec"), Some(&serde_json::json!({"Cmd": cmd, "AttachStdout": true, "AttachStderr": true, "Tty": true})))?; if !created.ok() { @@ -281,7 +702,8 @@ pub fn exec(container: &str, cmd: &[&str]) -> io::Result<(i64, String)> { Ok((code, String::from_utf8_lossy(&out).replace("\r\n", "\n"))) } -/// A docker CLI: on PATH, else the one bundled in Kiri.app. +/// A docker CLI: on PATH, else the one bundled in Kiri.app (or Kiri's bin folder on Windows). +#[cfg(unix)] pub fn docker_cli() -> Option { let on_path = std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join("docker")).find(|d| d.is_file())); on_path @@ -292,6 +714,29 @@ pub fn docker_cli() -> Option { .or_else(lite_cli) } +#[cfg(windows)] +pub fn docker_cli() -> Option { + let beside = std::env::current_exe() + .ok() + .and_then(|e| e.parent().map(|d| d.join("docker.exe"))) + .filter(|d| d.is_file()); + let local = || { + let base = PathBuf::from(std::env::var_os("LOCALAPPDATA")?); + [ + base.join("Kiri").join("bin").join("docker.exe"), + base.join("Programs").join("Kiri").join("bin").join("docker.exe"), + base.join("Programs").join("Kiri").join("docker.exe"), + ] + .into_iter() + .find(|d| d.is_file()) + }; + let on_path = || { + std::env::var_os("PATH") + .and_then(|p| std::env::split_paths(&p).map(|d| d.join("docker.exe")).find(|d| d.is_file())) + }; + beside.or_else(local).or_else(on_path) +} + /// Kiri Lite's downloaded CLI. #[cfg(target_os = "macos")] fn lite_cli() -> Option { @@ -302,3 +747,205 @@ fn lite_cli() -> Option { fn lite_cli() -> Option { None } + +#[cfg(test)] +mod tests { + #[cfg(unix)] + use std::ffi::OsStr; + #[cfg(unix)] + use std::io::{Read, Write}; + use std::io; + #[cfg(unix)] + use std::os::unix::fs::PermissionsExt; + #[cfg(unix)] + use std::os::unix::net::UnixListener; + #[cfg(unix)] + use std::path::{Path, PathBuf}; + #[cfg(unix)] + use std::sync::atomic::{AtomicU64, Ordering}; + + #[cfg(unix)] + fn temp_dir(tag: &str) -> PathBuf { + static SEQ: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!("kiri-client-{tag}-{}-{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + /// `kiri import` streams a container's writable layer (#410): the body + /// is chunked, and ended only when all of it was written, so the daemon + /// never takes a copy cut short for a whole one. + #[test] + fn a_streamed_body_is_chunked_and_ended_only_when_whole() { + let mut wire = Vec::new(); + super::stream_body(&mut wire, |w| { + w.write_all(b"hello")?; + w.write_all(b" world") + }) + .unwrap(); + assert_eq!(wire, b"b\r\nhello world\r\n0\r\n\r\n"); + let mut wire = Vec::new(); + let e = super::stream_body(&mut wire, |w| { + w.write_all(b"part")?; + Err(io::Error::other("the source failed")) + }) + .unwrap_err(); + assert_eq!(e.to_string(), "the source failed"); + assert!(!wire.ends_with(b"0\r\n\r\n"), "{:?}", String::from_utf8_lossy(&wire)); + assert!(super::refused(&io::Error::from(io::ErrorKind::BrokenPipe)) && !super::refused(&io::Error::other("x"))); + } + + #[cfg(unix)] + #[test] + fn socket_for_discovers_wsl_integration_sockets_and_symlinks() { + let root = temp_dir("wsl-sock"); + let home = root.join("home/alice"); + let service = root.join("run/kiri/docker.sock"); + let wsl_sockets = root.join("mnt/wsl/kiri/sockets"); + let ubuntu_sock = wsl_sockets.join("Ubuntu/docker.sock"); + let var_run_link = root.join("var/run/docker.sock"); + let run_link = root.join("run/docker.sock"); + for d in [home.as_path(), service.parent().unwrap(), ubuntu_sock.parent().unwrap(), var_run_link.parent().unwrap(), run_link.parent().unwrap()] { + std::fs::create_dir_all(d).unwrap(); + } + let home_sock = home.join(crate::flavor::STATE.get()).join("run/docker.sock"); + + // 1. Nothing exists yet: falls back to HOME socket. + assert_eq!( + super::socket_for(None, Some(&service), Some(OsStr::new("Ubuntu")), Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + home_sock + ); + + // 2. WSL integration socket for WSL_DISTRO_NAME exists: discovered cleanly. + std::fs::write(&ubuntu_sock, "").unwrap(); + assert_eq!( + super::socket_for(None, Some(&service), Some(OsStr::new("Ubuntu")), Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + ubuntu_sock + ); + + // 3. Unsafe WSL_DISTRO_NAME values are ignored (never traverse outside wsl_sockets). + for bad in ["", ".", "..", "../Ubuntu", "Ubuntu/..", "a/b", r"a\b", "foo..bar", "Ubuntu\n"] { + assert_eq!( + super::socket_for(None, Some(&service), Some(OsStr::new(bad)), Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + home_sock, + "unsafe distro name must be ignored: {bad:?}" + ); + } + + // 4. When WSL_DISTRO_NAME is stripped (sudo/ssh/cron), /var/run/docker.sock -> /mnt/wsl/kiri/sockets//docker.sock resolves. + std::os::unix::fs::symlink(&ubuntu_sock, &var_run_link).unwrap(); + assert_eq!( + super::socket_for(None, Some(&service), None, Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + ubuntu_sock + ); + // Same through /run/docker.sock when /var/run/docker.sock is absent. + std::fs::remove_file(&var_run_link).unwrap(); + std::os::unix::fs::symlink(&ubuntu_sock, &run_link).unwrap(); + assert_eq!( + super::socket_for(None, Some(&service), None, Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + ubuntu_sock + ); + + // 5. Symlinks outside wsl_sockets or with traversal are ignored. + std::fs::remove_file(&run_link).unwrap(); + let other_sock = root.join("other.sock"); + std::fs::write(&other_sock, "").unwrap(); + std::os::unix::fs::symlink(&other_sock, &var_run_link).unwrap(); + let traversal = wsl_sockets.join("../other/docker.sock"); + std::os::unix::fs::symlink(&traversal, &run_link).unwrap(); + assert_eq!( + super::socket_for(None, Some(&service), None, Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + home_sock + ); + + // 6. Service socket (/run/kiri/docker.sock) takes precedence over WSL sockets. + std::fs::write(&service, "").unwrap(); + assert_eq!( + super::socket_for(None, Some(&service), Some(OsStr::new("Ubuntu")), Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + service + ); + + // 7. Explicit KIRI_SOCKET takes precedence over everything. + assert_eq!( + super::socket_for(Some(OsStr::new("/custom/kiri.sock")), Some(&service), Some(OsStr::new("Ubuntu")), Some(&wsl_sockets), &[&var_run_link, &run_link], Some(home.as_os_str())).unwrap(), + PathBuf::from("/custom/kiri.sock") + ); + + let _ = std::fs::remove_dir_all(&root); + } + + #[cfg(unix)] + #[test] + fn check_alive_distinguishes_alive_not_running_and_permission_denied() { + let dir = temp_dir("alive"); + let missing = dir.join("missing.sock"); + let err = super::check_alive_at(&missing, "not running msg").unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::NotConnected); + assert_eq!(err.to_string(), "not running msg"); + + // Live server responding 200 OK to /_ping succeeds. + let live = dir.join("live.sock"); + let listener = UnixListener::bind(&live).unwrap(); + let server = std::thread::spawn(move || { + let (mut conn, _) = listener.accept().unwrap(); + let mut req = Vec::new(); + let mut buf = [0u8; 256]; + while !req.windows(4).any(|w| w == b"\r\n\r\n") { + match conn.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => req.extend_from_slice(&buf[..n]), + } + } + conn.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK").unwrap(); + let _ = conn.flush(); + let _ = conn.shutdown(std::net::Shutdown::Write); + }); + super::check_alive_at(&live, "not running msg").unwrap(); + server.join().unwrap(); + + // Linux permission-denied message guides user to host-access. + let linux_perm = super::permission_denied_error(Path::new("/run/kiri/docker.sock"), true); + assert_eq!(linux_perm.kind(), io::ErrorKind::PermissionDenied); + assert_eq!( + linux_perm.to_string(), + "cannot connect to Kiri's socket (/run/kiri/docker.sock): permission denied. Run `sudo kiri host-access $USER` (or open Kiri) to grant access" + ); + + // Unprivileged connect to a 0000 socket surfaces PermissionDenied directly. + // SAFETY: geteuid cannot fail. + if unsafe { libc::geteuid() } != 0 { + let locked = dir.join("locked.sock"); + let _listener = UnixListener::bind(&locked).unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap(); + let err = super::check_alive_at(&locked, "not running msg").unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert!(err.to_string().contains("permission denied"), "got: {err}"); + assert!(err.to_string().contains(&locked.display().to_string()), "got: {err}"); + } + + // OS- and WSL-specific not-running messages. + assert_eq!( + super::not_running_message_for(false, false), + "Kiri isn't running. Open Kiri, or start it with `kiri daemon`" + ); + assert_eq!( + super::not_running_message_for(true, true), + "Kiri isn't running. Open Kiri on Windows (and enable this distro in Settings -> Resources -> WSL integration), or run `sudo kiri host-access $USER`" + ); + assert_eq!( + super::not_running_message_for(true, false), + "Kiri isn't running. Open Kiri, or run `sudo kiri host-access $USER` (or `sudo kiri daemon`)" + ); + + // WSL detection via WSL_DISTRO_NAME or binfmt_misc interop file. + let interop = dir.join("WSLInterop"); + assert!(!super::is_wsl_env(None, &[&interop])); + assert!(!super::is_wsl_env(Some(OsStr::new("")), &[&interop])); + assert!(super::is_wsl_env(Some(OsStr::new("Ubuntu")), &[&interop])); + std::fs::write(&interop, "enabled\n").unwrap(); + assert!(super::is_wsl_env(None, &[&interop])); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/kiri/src/daemon/access.rs b/crates/kiri/src/daemon/access.rs index 8236377c0..ce175796d 100644 --- a/crates/kiri/src/daemon/access.rs +++ b/crates/kiri/src/daemon/access.rs @@ -269,19 +269,44 @@ enum GetentRaw { Ran(std::process::ExitStatus, Vec), } -/// Runs `program -- ` with a sanitized environment, bounded duration, +#[derive(Clone, Copy)] +enum GetentDb { + Passwd, + Group, + Initgroups, +} + +impl GetentDb { + fn as_str(self) -> &'static str { + match self { + Self::Passwd => "passwd", + Self::Group => "group", + Self::Initgroups => "initgroups", + } + } +} + +/// Runs `program ` with a sanitized environment, bounded duration, /// and bounded stdout capture. Kills the child process group and reaps it on /// timeout or oversized output. -fn exec_getent(program: &Path, args: &[&OsStr], timeout: Duration, max_bytes: usize) -> io::Result { +/// +/// `db` is a closed enum (`passwd`, `group`, `initgroups`) and every element of +/// `keys` is validated against empty or dash-prefixed values so no option flag +/// can be injected without needing `"--"` (which `musl-utils` `getent` rejects). +fn exec_getent(program: &Path, db: GetentDb, keys: &[&OsStr], timeout: Duration, max_bytes: usize) -> io::Result { use std::io::Read; use std::os::unix::process::CommandExt; use std::process::{Command, Stdio}; + if keys.is_empty() || keys.iter().any(|a| a.as_bytes().is_empty() || a.as_bytes()[0] == b'-') { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "invalid getent argument")); + } + let mut cmd = Command::new(program); cmd.env_clear() .env("LC_ALL", "C") - .arg("--") - .args(args) + .arg(db.as_str()) + .args(keys) .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::null()) @@ -394,8 +419,8 @@ fn getent_account_lookup_with(program: &Path, key: &[u8], timeout: Duration, max if !valid_key(key) { return Ok(LookupResult::NotFound); } - let args = [OsStr::new("passwd"), OsStr::from_bytes(key)]; - match exec_getent(program, &args, timeout, max_bytes)? { + let keys = [OsStr::from_bytes(key)]; + match exec_getent(program, GetentDb::Passwd, &keys, timeout, max_bytes)? { GetentRaw::NoBinary => Ok(LookupResult::NotFound), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => passwd_line(&stdout) @@ -453,12 +478,8 @@ fn getent_accounts_batch_with(program: &Path, keys: &[&CStr], timeout: Duration, if keys.is_empty() { return Ok(BatchAccounts::default()); } - let mut args: Vec<&OsStr> = Vec::with_capacity(1 + keys.len()); - args.push(OsStr::new("passwd")); - for k in keys { - args.push(OsStr::from_bytes(k.to_bytes())); - } - match exec_getent(program, &args, timeout, max_bytes)? { + let args: Vec<&OsStr> = keys.iter().map(|k| OsStr::from_bytes(k.to_bytes())).collect(); + match exec_getent(program, GetentDb::Passwd, &args, timeout, max_bytes)? { GetentRaw::NoBinary => Ok(BatchAccounts::default()), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => { @@ -508,8 +529,8 @@ fn getent_group_lookup_with(program: &Path, key: &[u8]) -> io::Result Ok(None), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => group_line(&stdout) @@ -557,8 +578,8 @@ fn initgroups_has_detailed_with_limits(program: &Path, user: &CStr, gid: u32, ti if !valid_key(key) { return Ok(InitgroupsResult::NotMember); } - let args = [OsStr::new("initgroups"), OsStr::from_bytes(key)]; - match exec_getent(program, &args, timeout, max_bytes)? { + let keys = [OsStr::from_bytes(key)]; + match exec_getent(program, GetentDb::Initgroups, &keys, timeout, max_bytes)? { GetentRaw::NoBinary => Ok(InitgroupsResult::NotMember), GetentRaw::Ran(status, stdout) => match status.code() { Some(0) => { @@ -833,6 +854,103 @@ fn peer_uid(conn: &UnixStream) -> io::Result { Ok(cred.uid) } +/// Parses a `/proc//status` `Groups:` line into GIDs. +fn parse_status_groups(status: &str) -> Vec { + status + .lines() + .find_map(|l| l.strip_prefix("Groups:")) + .map(|line| line.split_whitespace().filter_map(|tok| tok.parse::().ok()).collect()) + .unwrap_or_default() +} + +fn status_groups_contain(status: &str, want_gid: u32) -> bool { + parse_status_groups(status).contains(&want_gid) +} + +/// Verifies that the effective UID in `/proc//status` (`Uid:\treal\teff...`) +/// matches `want_uid` from `SO_PEERCRED`, defeating PID-reuse races. +fn status_euid_matches(status: &str, want_uid: u32) -> bool { + status + .lines() + .find_map(|l| l.strip_prefix("Uid:")) + .and_then(|line| line.split_whitespace().nth(1)) + .and_then(|tok| tok.parse::().ok()) + == Some(want_uid) +} + +fn read_proc_file_at(dir_fd: std::os::fd::RawFd, name: &CStr) -> Option { + use std::io::Read; + use std::os::fd::FromRawFd; + // SAFETY: `dir_fd` is a valid open directory fd and `name` is NUL-terminated. + let raw = unsafe { libc::openat(dir_fd, name.as_ptr(), libc::O_RDONLY | libc::O_CLOEXEC | libc::O_NOFOLLOW) }; + if raw < 0 { + return None; + } + // SAFETY: `raw` is a freshly opened descriptor owned here. + let mut f = unsafe { std::fs::File::from_raw_fd(raw) }; + let mut out = String::new(); + f.take(64 * 1024).read_to_string(&mut out).ok()?; + Some(out) +} + +/// Snapshot of a peer's credentials and `/proc/` state captured +/// synchronously at `accept()` time through a single pinned `/proc/` +/// directory descriptor before spawning `kiri-api` (prevents short-lived client +/// exit races and multi-step `/proc/` PID-reuse TOCTOU). +pub struct PinnedPeer { + uid: u32, + gid: u32, + groups: Vec, + cgroup: String, +} + +impl PinnedPeer { + pub fn capture(conn: &UnixStream) -> Option { + use std::os::fd::FromRawFd; + // SAFETY: connected socket and zeroed `ucred` storage. + let mut cred: libc::ucred = unsafe { std::mem::zeroed() }; + let mut len = std::mem::size_of::() as libc::socklen_t; + // SAFETY: valid output pointers and buffer length. + 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::() || cred.pid <= 0 { + return None; + } + // `uid == 0` is unconditionally admitted by `Gate::check_subject` + // without inspecting supplementary groups or container cgroups. + if cred.uid == 0 { + return Some(PinnedPeer { + uid: 0, + gid: cred.gid, + groups: Vec::new(), + cgroup: String::new(), + }); + } + let proc_path = CString::new(format!("/proc/{}", cred.pid)).ok()?; + // SAFETY: valid NUL-terminated path; pins the `/proc/` directory inode. + let raw_dir = unsafe { libc::open(proc_path.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) }; + if raw_dir < 0 { + return None; + } + // SAFETY: `raw_dir` is a freshly opened directory descriptor owned here. + let dir_fd = unsafe { std::os::fd::OwnedFd::from_raw_fd(raw_dir) }; + let status = read_proc_file_at(dir_fd.as_raw_fd(), c"status")?; + if !status_euid_matches(&status, cred.uid) { + return None; + } + let cgroup = read_proc_file_at(dir_fd.as_raw_fd(), c"cgroup")?; + Some(PinnedPeer { + uid: cred.uid, + gid: cred.gid, + groups: parse_status_groups(&status), + cgroup, + }) + } + + fn holds_gid(&self, want_gid: u32) -> bool { + self.gid == want_gid || self.groups.contains(&want_gid) + } +} + /// 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: &Group) -> bool { primary_gid == group.gid || group.members.iter().any(|m| m.as_c_str() == user) @@ -1025,6 +1143,17 @@ impl AclState { } } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +enum PeerSubject { + HostUser(u32), + /// Containerized client on `docker.container.sock` verified to belong to a + /// live Kiri container cgroup and holding `gid`, whose numeric `uid` had no + /// host account at connect time (#127). Retains `uid` so sweeps re-verify + /// both group GID validity (with `DIRECTORY_MISS_GRACE`) and host user + /// absence. + ContainerGroup { uid: u32, gid: u32 }, +} + /// 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. @@ -1033,18 +1162,23 @@ pub struct Gate { /// The daemon's socket, and the one containers are given (caller.rs). sockets: Vec, owner: u32, - open: Mutex>, + open: Mutex>, next: AtomicU64, failing: AtomicBool, /// Recent per-uid decisions, in-flight coalescing, and concurrency cap so /// bursts of connections or local lookup storms stay bounded. lookup: Mutex, lookup_slot: Condvar, + /// Bounded/cached host-account absence checks for container UIDs (#127) so + /// bursts of container socket connections never spawn unthrottled `getent`. + container_uid_absent: Mutex>, /// Short-TTL group lookup cache for the accept path, invalidated when /// `/etc/group` changes. group_cache: Mutex>, /// Consecutive ambiguous exit-2 misses per connected uid. misses: Mutex>, + /// Consecutive ambiguous exit-2 group misses per container subject. + container_misses: Mutex>, /// UIDs written by `grant()` at startup, used to seed `watch()` so an /// outage right after boot does not shrink the initial ACL on tick 1. startup_uids: Mutex>>, @@ -1076,8 +1210,10 @@ impl Gate { failing: AtomicBool::new(false), lookup: Mutex::default(), lookup_slot: Condvar::new(), + container_uid_absent: Mutex::default(), group_cache: Mutex::default(), misses: Mutex::default(), + container_misses: Mutex::default(), startup_uids: Mutex::default(), })) } @@ -1137,6 +1273,17 @@ impl Gate { }) } + #[cfg(test)] + pub(crate) fn allowed_for_test(&self, uid: u32) -> io::Result { + let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner()); + state.recent.remove(&uid); + drop(state); + self.allowed_with(uid, |u| { + let group = self.cached_group()?; + Ok(member_of_detailed(u, &group)? == Membership::Allowed) + }) + } + fn allowed_with(&self, uid: u32, check: impl Fn(u32) -> io::Result) -> io::Result { if uid == 0 || uid == self.owner { return Ok(true); @@ -1212,13 +1359,30 @@ impl Gate { } let closed_uids = if connected { - self.sweep_membership_with(|uid| { - if uid == 0 || uid == self.owner { - return Ok(Membership::Allowed); - } - let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?; - check_member(uid, g) - }) + self.sweep_subjects_with( + |uid| { + if uid == 0 || uid == self.owner { + return Ok(Membership::Allowed); + } + let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?; + check_member(uid, g) + }, + |uid, gid| { + let g = group.as_ref().map_err(|e| io::Error::new(e.kind(), e.to_string()))?; + match g { + LookupResult::Found(found) if found.gid == gid => { + // Re-verify `uid` is still not a revoked host account + // (e.g., if NSS recovered after an ambiguous connect-time miss). + match account_by_uid_detailed(uid)? { + LookupResult::Found(_) => check_member(uid, g), + LookupResult::NotFound | LookupResult::UnavailableOrNotFound => Ok(Membership::Allowed), + } + } + LookupResult::Found(_) | LookupResult::NotFound => Ok(Membership::Revoked), + LookupResult::UnavailableOrNotFound => Ok(Membership::MissingFromDirectory), + } + }, + ) } else { HashSet::new() }; @@ -1423,11 +1587,108 @@ impl Gate { set_each(&self.sockets, uids, set) } - /// Checks a new connection. `None`: refused, and the reason logged. + /// Checks a new host connection. `None`: refused, and the reason logged. pub fn admit(self: &Arc, conn: &UnixStream) -> Option { self.admit_with(conn, |uid| self.allowed(uid)) } + /// Checks a new connection on `docker.container.sock`: admits host group + /// members as usual, and also admits containerized clients inside a live + /// Kiri container cgroup holding the access group's GID whose numeric UID + /// has no host account (#127). + pub fn admit_container( + self: &Arc, + conn: &UnixStream, + pinned: Option, + is_running_container_cgroup: impl FnOnce(&str) -> bool, + ) -> Option { + let uid = match pinned.as_ref().map(|p| Ok(p.uid)).unwrap_or_else(|| peer_uid(conn)) { + Ok(u) => u, + Err(e) => { + crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e); + return None; + } + }; + let subject = match self.allowed(uid) { + Ok(true) => PeerSubject::HostUser(uid), + Ok(false) => match self.container_group_subject(pinned, is_running_container_cgroup) { + Ok(Some(sub)) => sub, + Ok(None) => { + 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; + } + }, + Err(e) => { + crate::diag::warn!("socket connection refused: access check failed", group = self.name(), error = e); + return None; + } + }; + self.track_seat(conn, subject) + } + + fn uid_absent_throttled(&self, uid: u32) -> io::Result { + { + let mut cache = self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()); + cache.retain(|_, (_, at)| at.elapsed() < RECHECK); + if let Some(&(absent, _)) = cache.get(&uid) { + return Ok(absent); + } + } + // Acquire one of Gate's bounded lookup slots (MAX_CONCURRENT_LOOKUPS = 4) + // so container connection bursts never spawn unthrottled `getent` children. + { + let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner()); + while state.active >= MAX_CONCURRENT_LOOKUPS { + if state.waiting >= MAX_WAITING_LOOKUPS { + return Err(io::Error::new(io::ErrorKind::WouldBlock, "too many concurrent access checks")); + } + state.waiting += 1; + state = self.lookup_slot.wait(state).unwrap_or_else(|e| e.into_inner()); + state.waiting -= 1; + } + state.active += 1; + } + let lookup_res = account_by_uid_detailed(uid); + { + let mut state = self.lookup.lock().unwrap_or_else(|e| e.into_inner()); + state.active = state.active.saturating_sub(1); + self.lookup_slot.notify_all(); + } + let absent = match lookup_res? { + LookupResult::NotFound | LookupResult::UnavailableOrNotFound => true, + LookupResult::Found(_) => false, + }; + let mut cache = self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()); + if cache.len() >= MAX_RECENT_ENTRIES + && !cache.contains_key(&uid) + && let Some(&oldest) = cache.iter().min_by_key(|(_, (_, at))| *at).map(|(k, _)| k) + { + cache.remove(&oldest); + } + cache.insert(uid, (absent, Instant::now())); + Ok(absent) + } + + fn container_group_subject( + &self, + pinned: Option, + is_running_container_cgroup: impl FnOnce(&str) -> bool, + ) -> io::Result> { + let Some(peer) = pinned else { return Ok(None) }; + let LookupResult::Found(group) = self.cached_group()? else { return Ok(None) }; + if !peer.holds_gid(group.gid) || !is_running_container_cgroup(&peer.cgroup) { + return Ok(None); + } + if !self.uid_absent_throttled(peer.uid)? { + return Ok(None); + } + Ok(Some(PeerSubject::ContainerGroup { uid: peer.uid, gid: group.gid })) + } + fn admit_with(self: &Arc, conn: &UnixStream, check: impl Fn(u32) -> io::Result) -> Option { let checked = peer_uid(conn).and_then(|uid| Ok((uid, check(uid)?))); let uid = match checked { @@ -1441,6 +1702,10 @@ impl Gate { return None; } }; + self.track_seat(conn, PeerSubject::HostUser(uid)) + } + + fn track_seat(self: &Arc, conn: &UnixStream, subject: PeerSubject) -> Option { let keep = match conn.try_clone() { Ok(c) => c, Err(e) => { @@ -1449,44 +1714,88 @@ impl Gate { } }; let id = self.next.fetch_add(1, Ordering::Relaxed); - self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (uid, keep)); + self.open.lock().unwrap_or_else(|e| e.into_inner()).insert(id, (subject, keep)); Some(Seat { gate: self.clone(), id }) } - /// Checks everyone still connected, once per account, and closes the + #[cfg(test)] + fn sweep_membership_with(&self, check: impl Fn(u32) -> io::Result) -> HashSet { + self.sweep_subjects_with(check, |_, _| Ok(Membership::Allowed)) + } + + /// Checks everyone still connected, once per subject, and closes the /// connections of anyone no longer allowed. A failed lookup leaves the /// connections open (new ones are refused until lookups work again). /// Ambiguous directory exit-2 misses use a grace window before closing. - fn sweep_membership_with(&self, check: impl Fn(u32) -> io::Result) -> HashSet { - let uids: HashSet = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(u, _)| *u).collect(); - let mut removed = HashSet::new(); + fn sweep_subjects_with( + &self, + check_user: impl Fn(u32) -> io::Result, + check_container: impl Fn(u32, u32) -> io::Result, + ) -> HashSet { + let subjects: HashSet = self.open.lock().unwrap_or_else(|e| e.into_inner()).values().map(|(s, _)| *s).collect(); + let host_uids: HashSet = subjects + .iter() + .filter_map(|s| match s { + PeerSubject::HostUser(u) => Some(*u), + PeerSubject::ContainerGroup { .. } => None, + }) + .collect(); + let mut removed_subjects = HashSet::new(); + let mut removed_uids = HashSet::new(); + let mut removed_container_uids = HashSet::new(); let mut failed = None; - let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner()); - misses.retain(|u, _| uids.contains(u)); - drop(misses); - - for uid in uids { - match check(uid) { - Ok(Membership::Allowed) => { - self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); - self.remember_decision(uid, CachedDecision::Allowed); - } - Ok(Membership::Revoked) => { - self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); - self.remember_decision(uid, CachedDecision::Denied); - removed.insert(uid); - } - Ok(Membership::MissingFromDirectory) => { - self.remember_decision(uid, CachedDecision::Denied); - let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner()); - let count = misses.entry(uid).or_insert(0); - *count = count.saturating_add(1); - if *count >= DIRECTORY_MISS_GRACE { - misses.remove(&uid); - removed.insert(uid); + self.misses.lock().unwrap_or_else(|e| e.into_inner()).retain(|u, _| host_uids.contains(u)); + self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).retain(|s, _| subjects.contains(s)); + + for subject in subjects { + match subject { + PeerSubject::HostUser(uid) => match check_user(uid) { + Ok(Membership::Allowed) => { + self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + self.remember_decision(uid, CachedDecision::Allowed); } - } - Err(e) => failed = Some(e), + Ok(Membership::Revoked) => { + self.misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + self.remember_decision(uid, CachedDecision::Denied); + removed_subjects.insert(subject); + removed_uids.insert(uid); + } + Ok(Membership::MissingFromDirectory) => { + self.remember_decision(uid, CachedDecision::Denied); + let mut misses = self.misses.lock().unwrap_or_else(|e| e.into_inner()); + let count = misses.entry(uid).or_insert(0); + *count = count.saturating_add(1); + if *count >= DIRECTORY_MISS_GRACE { + misses.remove(&uid); + removed_subjects.insert(subject); + removed_uids.insert(uid); + } + } + Err(e) => failed = Some(e), + }, + PeerSubject::ContainerGroup { uid, gid } => match check_container(uid, gid) { + Ok(Membership::Allowed) => { + self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&subject); + } + Ok(Membership::Revoked) => { + self.container_misses.lock().unwrap_or_else(|e| e.into_inner()).remove(&subject); + self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + removed_subjects.insert(subject); + removed_container_uids.insert(uid); + } + Ok(Membership::MissingFromDirectory) => { + let mut misses = self.container_misses.lock().unwrap_or_else(|e| e.into_inner()); + let count = misses.entry(subject).or_insert(0); + *count = count.saturating_add(1); + if *count >= DIRECTORY_MISS_GRACE { + misses.remove(&subject); + self.container_uid_absent.lock().unwrap_or_else(|e| e.into_inner()).remove(&uid); + removed_subjects.insert(subject); + removed_container_uids.insert(uid); + } + } + Err(e) => failed = Some(e), + }, } } match failed { @@ -1494,13 +1803,13 @@ impl Gate { None if self.failing.swap(false, Ordering::Relaxed) => crate::diag::info!("access check works again", group = self.name()), _ => {} } - if removed.is_empty() { - return removed; + if removed_subjects.is_empty() { + return removed_uids; } // 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) { + self.open.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, (subject, conn)| { + if !removed_subjects.contains(subject) { return true; } // Ends the connection for every thread using it: reads see the @@ -1508,10 +1817,10 @@ impl Gate { let _ = conn.shutdown(Shutdown::Both); false }); - for uid in &removed { + for uid in removed_uids.iter().chain(removed_container_uids.iter()) { crate::diag::warn!("connections closed: user is no longer in the access group", group = self.name(), uid = uid); } - removed + removed_uids } #[cfg(test)] @@ -1547,6 +1856,22 @@ pub fn set(socket: &Path, uids: &[u32]) -> io::Result<()> { if r == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } +/// Best-effort grants a single non-root `uid` (such as `SUDO_UID` when running +/// `sudo kiri daemon`) read-write POSIX ACL access on each socket, keeping +/// owner/group rw and other `---`. Ignores filesystems without ACL support. +pub fn grant_uid(sockets: &[&Path], uid: u32) { + if uid == 0 || uid == u32::MAX { + return; + } + for socket in sockets { + if let Err(e) = set(socket, &[uid]) + && !unsupported(&e) + { + crate::diag::warn!("socket access list for invoking user not written", uid = uid, path = socket.display(), error = e); + } + } +} + /// Writes the access list of every one of `sockets` with `set`, each tried /// whatever became of the one before; the first error, if any. fn set_each(sockets: &[PathBuf], uids: &[u32], set: impl Fn(&Path, &[u32]) -> io::Result<()>) -> io::Result<()> { @@ -1937,8 +2262,7 @@ mod tests { let touched = dir.join("touched"); let script = format!( "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ db=\"$1\"; key=\"$2\"\n\ case \"$key\" in -*) echo bad > \"{}\"; exit 9 ;; esac\n\ case \"$db:$key\" in\n\ @@ -2060,8 +2384,7 @@ mod tests { "fake-getent", &format!( "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$1\" in\n\ passwd) export -p > \"{}\"; echo 'alice:x:5001:5001::/:/bin/sh'; exit 0 ;;\n\ initgroups) export -p > \"{}\"; echo 'alice 998'; exit 0 ;;\n\ @@ -2085,7 +2408,7 @@ mod tests { assert!(v == "'C'" || v == "C" || v == "\"C\"", "unexpected LC_ALL: {line}"); saw_lc_all = true; } else { - assert!(matches!(k, "PWD" | "SHLVL" | "_"), "unexpected inherited env var in getent: {line}"); + assert!(matches!(k, "PWD" | "OLDPWD" | "SHLVL" | "_"), "unexpected inherited env var in getent: {line}"); } } assert!(saw_lc_all, "LC_ALL=C not set in {text}"); @@ -2101,8 +2424,7 @@ mod tests { &dir, "fake-getent", "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$2\" in\n\ hang) [ -x /bin/sleep ] && /bin/sleep 30 || /usr/bin/sleep 30; exit 0 ;;\n\ hang_closed) exec >&-; [ -x /bin/sleep ] && /bin/sleep 30 || /usr/bin/sleep 30; exit 0 ;;\n\ @@ -2166,8 +2488,7 @@ mod tests { &dir, "fake-getent", "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$1:$2\" in\n\ passwd:alice|passwd:Alice@corp.example) echo 'alice@corp.example:x:5001:5001::/home/alice:/bin/sh'; exit 0 ;;\n\ passwd:0|'passwd:+0'|'passwd: 0'|'passwd: -0') echo 'root:x:0:0:root:/root:/bin/sh'; exit 0 ;;\n\ @@ -2218,8 +2539,7 @@ mod tests { &dir, "fake-getent", "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ case \"$1:$2\" in\n\ initgroups:alice) echo 'alice -2147483648 -1000 998'; exit 0 ;;\n\ *) exit 2 ;;\n\ @@ -2240,8 +2560,7 @@ mod tests { "fake-getent", &format!( "#!/bin/sh\n\ - [ \"$1\" = \"--\" ] || exit 9\n\ - shift\n\ + [ \"$1\" = \"--\" ] && exit 1\n\ db=\"$1\"; shift\n\ echo x >> \"{}\"\n\ [ \"$db\" = \"passwd\" ] || exit 2\n\ @@ -3010,4 +3329,28 @@ mod tests { assert_eq!(state.uids, Some(vec![1001, 5002]), "bob must get a fresh grace window after alice was dropped"); assert_eq!(state.shrink_streak, 1); } + + #[test] + fn container_group_subject_parses_supplementary_groups_and_revokes_on_gid_change() { + let status = "Name:\tpython3\nUid:\t54321\t54321\t54321\t54321\nGid:\t54321\t54321\t54321\t54321\nGroups:\t100 998 65534 \n"; + assert!(status_groups_contain(status, 998)); + assert!(!status_groups_contain(status, 999)); + assert!(status_euid_matches(status, 54321)); + assert!(!status_euid_matches(status, 1000)); + assert!(exec_getent(Path::new("/usr/bin/getent"), GetentDb::Passwd, &[OsStr::new("-V")], Duration::from_secs(1), 1024).is_err()); + + let g = gate(); + let (a, _b) = UnixStream::pair().unwrap(); + let _seat = g.track_seat(&a, PeerSubject::ContainerGroup { uid: 54321, gid: 998 }).unwrap(); + // Matching GID keeps the container connection open across sweeps. + assert!(g.sweep_subjects_with(|_| unreachable!(), |u, gid| Ok(if u == 54321 && gid == 998 { Membership::Allowed } else { Membership::Revoked })).is_empty()); + assert_eq!(g.open.lock().unwrap().len(), 1); + // Transient directory exit-2 misses honor DIRECTORY_MISS_GRACE before closing. + for _ in 1..DIRECTORY_MISS_GRACE { + assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty()); + assert_eq!(g.open.lock().unwrap().len(), 1); + } + assert!(g.sweep_subjects_with(|_| unreachable!(), |_, _| Ok(Membership::MissingFromDirectory)).is_empty()); + assert!(g.open.lock().unwrap().is_empty()); + } } diff --git a/crates/kiri/src/daemon/api.rs b/crates/kiri/src/daemon/api.rs index 986363eae..1f8c6e180 100644 --- a/crates/kiri/src/daemon/api.rs +++ b/crates/kiri/src/daemon/api.rs @@ -24,7 +24,15 @@ use super::time; pub fn serve(stream: UnixStream, engine: Arc, caller: Caller) -> io::Result<()> { let mut w = stream.try_clone()?; let mut r = BufReader::new(stream); - while let Some(req) = http::read_request(&mut r, streams_body)? { + loop { + let req = match http::read_request_with_timeout(&mut r, http::HEADER_TIMEOUT, streams_body) { + Ok(Some(req)) => req, + Ok(None) => break, + Err(e) if e.kind() == io::ErrorKind::InvalidData => { + return http::refuse_bad_request(&mut w, &mut r, &e.to_string()).or(Ok(())); + } + Err(e) => return Err(e), + }; // A body too large to hold: answered and ended, never routed. if req.too_large() { return http::refuse_too_large(&req, &mut w, &mut r).or(Ok(())); @@ -38,7 +46,7 @@ pub fn serve(stream: UnixStream, engine: Arc, caller: Caller) -> io::Res if req.header("X-Kiri-Background").is_none() { engine.touch(); } - match route(&req, &engine, caller, &mut w, &mut r) { + match route(&req, &engine, &caller, &mut w, &mut r) { // `Connection: close` or HTTP/1.0: the client reads to the end of // the stream (a 204 has no length to read by), which `close` // gives it cleanly. @@ -78,7 +86,9 @@ pub fn serve(stream: UnixStream, engine: Arc, caller: Caller) -> io::Res /// (`/images/create` is `docker import`'s; a pull's, when a client sends /// one, is read out after it, by `http::finish_body`). fn streams_body(method: &str, path: &str) -> bool { - matches!((method, path), ("PUT", p) if p.starts_with("/containers/") && p.ends_with("/archive")) || (method == "POST" && matches!(path, "/images/load" | "/images/create" | "/build")) + matches!((method, path), ("PUT", p) if p.starts_with("/containers/") && p.ends_with("/archive")) + || matches!((method, path), ("POST", p) if p.starts_with("/kiri/containers/") && p.ends_with("/upper")) + || (method == "POST" && matches!(path, "/images/load" | "/images/create" | "/build")) } pub(super) enum Next { @@ -115,6 +125,7 @@ fn status_of(e: Error) -> (u16, String) { Error::Conflict(m) => (409, m), Error::BadRequest(m) => (400, m), Error::Unauthorized(m) => (401, m), + Error::Forbidden(m) => (403, m), Error::Io(e) => (500, e.to_string()), } } @@ -133,7 +144,7 @@ fn container_may(method: &str, path: &str) -> bool { !kiri || matches!(method, "GET" | "HEAD") || CONTAINER_MAY.contains(&(method, path)) } -fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream, r: &mut BufReader) -> io::Result { +fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStream, r: &mut BufReader) -> io::Result { if req.api_version.is_some_and(|v| v < http::MIN_API_VERSION) { let (major, minor) = req.api_version.unwrap_or_default(); let (min_major, min_minor) = http::MIN_API_VERSION; @@ -143,21 +154,25 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream let m = req.method.as_str(); // Kiri's own endpoints that change something are for this machine's // programs (caller.rs), not for a container given the socket. - if caller == Caller::Container && !container_may(m, p) { + if *caller == Caller::Container && !container_may(m, p) { // Closed after the answer: a body the request carried is not left // on the connection to be read as the next request. http::error(w, 403, "this is changed in Kiri's window or with the kiri command on this machine, not from a container")?; return Ok(Next::Close); } - if let Some(done) = super::ops::route(req, engine, w) { + // While Settings → Storage moves the data, nothing may change it. + if super::storage::moving() && !matches!(m, "GET" | "HEAD") { + super::storage::refuse_while_moving(w)?; + return Ok(Next::Close); + } + if let Some(done) = super::ops::route(req, engine, caller, w) { return done; } match (m, p) { ("GET" | "HEAD", "/_ping") => { - // Builder-Version 1: the classic POST /build, which Kiri serves - // with its managed BuildKit (builder.rs). "2" would tell older - // CLIs and Compose to use BuildKit inside the engine (/session, - // /grpc), which Kiri doesn't have. + // Builder-Version 1 keeps classic CLIs, older Compose and SDKs + // without buildx on POST /build (served by builder.rs), while + // buildx probes POST /grpc directly and uses the docker driver. http::respond_with(w, 200, "text/plain; charset=utf-8", "Builder-Version: 1\r\n", if m == "HEAD" { b"" } else { b"OK" })?; return Ok(Next::KeepAlive); } @@ -175,6 +190,9 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream ("GET", "/kiri/proxy") => return reply(w, Ok(super::proxy::report()), 200), ("POST", "/kiri/proxy") => return reply(w, set_proxy(req), 200), ("PUT", "/kiri/proxy/system") => return reply(w, set_host_proxy(req), 200), + // kiri-win's Windows roots, for the engine in WSL (#303). + #[cfg(target_os = "linux")] + ("PUT", "/kiri/roots/host") => return reply(w, set_host_roots(req, caller), 200), // daemon.json's registry keys: Settings → Registries, `kiri registry`. ("GET", "/kiri/registries") => return reply(w, Ok(super::daemon_json::report()), 200), ("POST", "/kiri/registries") => return reply(w, set_registries(req, engine), 200), @@ -184,6 +202,9 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream ("POST", "/kiri/domains") => return reply(w, set_domain_ports(req, engine), 200), // Back to the ports a start gives (a test copy's routers stop). ("DELETE", "/kiri/domains") => return reply(w, super::domains::reset(engine).map_err(Error::Conflict), 200), + // Settings → Resources → WSL integration: per-distro sockets in /mnt/wsl/kiri. + ("GET", "/kiri/wsl") => return reply(w, Ok(super::wsl_report()), 200), + ("POST", "/kiri/wsl") => return reply(w, set_wsl(req, caller), 200), // USB passthrough (macOS: the root helper `kiri usb serve` connects here). #[cfg(target_os = "macos")] ("POST", "/kiri/usb") => return super::usb::attach(req, engine, w, r), @@ -219,6 +240,12 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream let id = p.strip_prefix("/kiri/containers/").and_then(|r| r.strip_suffix("/env")).unwrap_or_default(); return reply(w, set_env(req, engine, id), 204); } + // `kiri import`: the writable layer a container had on the engine + // it came from (an OCI layer tar), before it first runs here. + ("POST", p) if p.strip_prefix("/kiri/containers/").and_then(|r| r.strip_suffix("/upper")).is_some_and(|id| !id.is_empty()) => { + let id = p.strip_prefix("/kiri/containers/").and_then(|r| r.strip_suffix("/upper")).unwrap_or_default(); + return upper_put(req, engine, id, w, r); + } // An image's page for kiri-win, whose window can't read the store // inside WSL: its layers and its Grype scans (crate::scan), as the // Mac's window reads them itself. @@ -241,8 +268,21 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream ("POST", "/build") => return super::builder::build(req, engine, w, r), ("POST", "/build/cancel") => return reply(w, super::builder::cancel(req, engine), 200), ("POST", "/build/prune") => return reply(w, super::builder::prune(req, engine), 200), + ("POST", "/grpc") => return super::grpc::grpc(req, engine, w, r), + ("POST", "/session") => return super::grpc::session(req, engine, w, r), + // Settings → Storage: where the data is, and moving it (storage.rs). + ("GET", "/kiri/storage") => return reply(w, Ok(super::storage::report(engine)), 200), + ("POST", "/kiri/storage/check") => return reply(w, super::storage::check_request(req, engine), 200), + ("POST", "/kiri/storage") => return reply(w, super::storage::start(req, engine), 202), + ("POST", "/kiri/storage/reset") => return reply(w, super::storage::start_reset(engine), 202), + ("POST", "/kiri/storage/reclaim") => return reply(w, super::storage::reclaim(engine), 200), + ("DELETE", "/kiri/storage/old") => return reply(w, super::storage::remove_old(engine), 200), ("GET", "/kiri/builder") => return reply(w, Ok(super::builder::settings_report(engine)), 200), ("POST", "/kiri/builder") => return reply(w, super::builder::set_settings(req).map(|()| super::builder::settings_report(engine)), 200), + ("GET", "/kiri/watch-roots") => return reply(w, Ok(watch_roots(engine)), 200), + ("POST", "/kiri/fs-events") => return reply(w, fs_events(req, engine), 204), + ("GET", "/kiri/win-ports") => return reply(w, Ok(win_ports(engine)), 200), + ("POST", "/kiri/win-ports") => return reply(w, sync_win_ports(req, engine), 200), ("GET", "/images/json") => return reply(w, images(req, engine), 200), ("POST", "/images/create") if req.query("fromSrc").is_some_and(|s| !s.is_empty()) => return image_import(req, engine, w, r), ("POST", "/images/create") => return pull(req, engine, w), @@ -252,10 +292,10 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream return image_save(engine, &names, w); } ("POST", "/containers/create") => { - if let Some(made) = super::builder::create_for_buildx(engine, req.query("name")) { + if let Some(made) = super::builder::create_for_buildx(engine, req) { return reply(w, made, 201); } - return reply(w, create(req, engine), 201); + return reply(w, create_by(req, engine, caller), 201); } ("GET", "/containers/json") => return reply(w, list(req, engine), 200), ("GET", "/networks") => return reply(w, networks(req, engine), 200), @@ -344,7 +384,7 @@ fn route(req: &Request, engine: &Arc, caller: Caller, w: &mut UnixStream super::builder::before_exec(engine, id); return reply(w, exec_create(req, engine, id), 201); } - ("HEAD" | "GET", "archive") => return archive_get(req, engine, id, w), + ("HEAD" | "GET", "archive") => return archive_get(req, engine, id, caller, w), ("PUT", "archive") => return archive_put(req, engine, id, w, r), ("DELETE", "") => return reply(w, engine.remove(id, req.flag("force"), req.flag("v")).map(|()| Value::Null), 204), _ => {} @@ -453,7 +493,7 @@ fn parse_release(raw: &str) -> Option { /// `KiriVersion`, and a component named "Kiri". Moves with `API_VERSION`. pub const ENGINE_VERSION: &str = "27.5.1"; -fn version() -> Value { +pub(super) fn version() -> Value { let kiri = env!("CARGO_PKG_VERSION"); json!({ "Platform": {"Name": "Kiri"}, @@ -512,6 +552,7 @@ fn info(engine: &Engine) -> Value { "RegistryConfig": super::daemon_json::info(), "KiriAgentMemory": engine.agent_rss().unwrap_or(0), "KiriVmAwake": engine.is_awake(), + "KiriVmUplink": engine.uplink_info(), "KiriStopped": engine.is_stopped(), "KiriMemoryCeiling": engine.memory().0, "KiriMemoryTarget": engine.memory().1, @@ -519,6 +560,8 @@ fn info(engine: &Engine) -> Value { "KiriMemoryStall": engine.memory_trouble().0, "KiriOomKills": engine.memory_trouble().1, "KiriCpuPercent": engine.cpu_percent(), + "KiriStorageReadOnly": engine.storage_readonly(), + "KiriStorageZfs": engine.storage_zfs(), "Warnings": engine.records_damage().into_iter().chain(engine.image_damage()).chain(engine.host_warnings()).collect::>(), }) } @@ -668,7 +711,7 @@ fn image_list_dangling(f: &Filters) -> Result, Error> { } fn image_inspect(engine: &Engine, name: &str) -> Result { - let i = engine.image(name)?.ok_or_else(|| Error::NotFound(format!("No such image: {name}")))?; + let (i, _blob_pins) = engine.image_pinned(name)?.ok_or_else(|| Error::NotFound(format!("No such image: {name}")))?; let cfg = image_config_json(engine, &i.config_digest); // Docker's RootFS.Layers are the image config's uncompressed diff_ids, // not the manifest's compressed blob digests (scanners like Trivy match @@ -723,13 +766,14 @@ fn image_remove(engine: &Engine, name: &str, force: bool) -> Result Result<(), Error> { - let i = engine.image(source)?.ok_or_else(|| Error::NotFound(format!("No such image: {source}")))?; + let (i, _blob_pins) = engine.image_pinned(source)?.ok_or_else(|| Error::NotFound(format!("No such image: {source}")))?; let repo = req.query("repo").unwrap_or_default(); if repo.is_empty() { return Err(Error::BadRequest("repository name must have at least one component".into())); @@ -738,18 +782,58 @@ fn image_tag(req: &Request, engine: &Engine, source: &str) -> Result<(), Error> 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(i.tagged(name.clone()))?; + engine.prune_layers(); engine.emit_image("tag", &i.config_digest, &name); Ok(()) } +fn platform_value(v: &Value) -> Option { + if let Some(s) = v.as_str() { + return Platform::parse(s); + } + let arch = v["architecture"].as_str().filter(|s| !s.is_empty())?; + let os = v["os"].as_str().filter(|s| !s.is_empty()).unwrap_or("linux"); + Platform::parse(&format!("{os}/{arch}")) +} + +/// Platforms asked for by `POST /images/load?platform=...`, accepting both +/// Kiri/plain `os/arch` strings and Docker API v1.48 JSON `ocispec.Platform` +/// objects or arrays. +fn parse_load_platforms(req: &Request) -> Result, Error> { + let mut out = Vec::new(); + for raw in req.queries("platform").filter(|p| !p.is_empty()) { + let trimmed = raw.trim(); + if trimmed.starts_with('[') { + let list: Vec = serde_json::from_str(trimmed).map_err(|_| Error::BadRequest(format!("invalid platform: {raw}")))?; + for item in list { + out.push(platform_value(&item).ok_or_else(|| Error::BadRequest(format!("invalid platform: {raw}")))?); + } + } else if trimmed.starts_with('{') { + let v: Value = serde_json::from_str(trimmed).map_err(|_| Error::BadRequest(format!("invalid platform: {raw}")))?; + out.push(platform_value(&v).ok_or_else(|| Error::BadRequest(format!("invalid platform: {raw}")))?); + } else { + out.push(Platform::parse(trimmed).ok_or_else(|| Error::BadRequest(format!("invalid platform: {raw}")))?); + } + } + Ok(out) +} + /// `docker load`: an image archive, plain or gzip- or zstd-compressed as Docker /// accepts it, streamed into the store. fn image_load(req: &Request, engine: &Engine, w: &mut UnixStream, r: &mut BufReader) -> io::Result { use std::io::Read; let mut body = http::Body::new(req, r); + let platforms = match parse_load_platforms(req) { + Ok(p) => p, + Err(e) => { + let _ = io::copy(&mut body, &mut io::sink()); + error_closing(w, e)?; + return Ok(Next::Close); + } + }; let mut head = Vec::with_capacity(6); (&mut body).take(6).read_to_end(&mut head)?; - let loaded = upload_reader(head, &mut body).map(|archive| kiri_image::archive::load(&engine.store, archive)); + let loaded = upload_reader(head, &mut body).map(|archive| kiri_image::archive::load_platforms(&engine.store, archive, &platforms)); let loaded = match loaded { Ok(loaded) => loaded, Err(e) => { @@ -762,6 +846,7 @@ fn image_load(req: &Request, engine: &Engine, w: &mut UnixStream, r: &mut BufRea }; match loaded { Ok(images) => { + engine.prune_layers(); http::begin_stream_with(w, 200, "application/json", http::CLOSE)?; for i in &images { engine.emit_image("load", &i.config_digest, &i.name); @@ -787,9 +872,11 @@ fn image_import(req: &Request, engine: &Engine, w: &mut UnixStream, r: &mut BufR http::end(w)?; } Err(e) => { - // The CLI is still sending the archive: read it out, or it gets - // a broken pipe instead of the message. - let _ = io::copy(&mut body, &mut io::sink()); + // The CLI may still be sending the archive: read it out unless it + // is still waiting on an unsent `100 Continue`. + if !req.needs_continue() { + let _ = io::copy(&mut body, &mut io::sink()); + } error_closing(w, e)?; } } @@ -840,15 +927,16 @@ fn import(req: &Request, engine: &Engine, stdin: &mut dyn io::Read) -> Result bool { /// `docker save`: the named images as one archive. fn image_save(engine: &Engine, names: &[String], w: &mut UnixStream) -> io::Result { let mut images = Vec::new(); + let mut _lookup_pins = Vec::new(); for n in names { - match engine.image(n) { - Ok(Some(i)) => images.push(i), + match engine.image_pinned(n) { + Ok(Some((i, pins))) => { + images.push(i); + _lookup_pins.extend(pins); + } Ok(None) => return reply(w, Err(Error::NotFound(format!("No such image: {n}"))), 200), Err(e) => return reply(w, Err(Error::Io(e)), 200), } @@ -941,16 +1033,68 @@ fn image_scan(req: &Request, w: &mut UnixStream) -> io::Result { /// the limits of this Mac. fn resources(engine: &Engine) -> Value { use super::engine as e; - json!({ - "cpus": e::vm_cpus(), - "memory_mib": e::memory_ceiling() >> 20, - "running_cpus": engine.cpus(), - "running_memory_mib": engine.memory().0 >> 20, - "awake": engine.is_awake(), - "max_cpus": e::max_cpus(), - "max_memory_mib": e::physical_memory_bytes() >> 20, - "overridden": std::env::var_os("KIRI_CPUS").is_some() || std::env::var_os("KIRI_MEMORY_MIB").is_some(), - }) + #[cfg(target_os = "macos")] + let disk = Some((crate::guest::disk::current_gb(), e::vm_disk_gb(), engine.disk_gb())); + #[cfg(not(target_os = "macos"))] + let disk: Option<(u64, u64, u64)> = None; + let overridden = std::env::var_os("KIRI_CPUS").is_some() + || std::env::var_os("KIRI_MEMORY_MIB").is_some() + || (cfg!(target_os = "macos") && (std::env::var_os("KIRI_DISK_GB").is_some() || std::env::var_os("KIRI_SWAP_MIB").is_some())); + let mut v = resources_payload( + e::vm_cpus(), + e::memory_ceiling() >> 20, + engine.cpus(), + engine.memory().0 >> 20, + engine.is_awake(), + e::max_cpus(), + e::physical_memory_bytes() >> 20, + overridden, + disk, + ); + // Swap is the VM's, on its data disk: a Linux host has its own. + if cfg!(target_os = "macos") { + swap_payload(&mut v, e::vm_swap_mib(), engine.swap_mib()); + } + v +} + +/// The swap the VM boots with next, what it has now, and the most it may have. +fn swap_payload(v: &mut Value, swap_mib: u64, running_swap_mib: u64) { + v["swap_mib"] = json!(swap_mib); + v["running_swap_mib"] = json!(running_swap_mib); + v["max_swap_mib"] = json!(super::engine::MAX_SWAP_MIB); +} + +#[allow(clippy::too_many_arguments)] +fn resources_payload( + cpus: usize, + memory_mib: u64, + running_cpus: usize, + running_memory_mib: u64, + awake: bool, + max_cpus: usize, + max_memory_mib: u64, + overridden: bool, + disk: Option<(u64, u64, u64)>, +) -> Value { + let mut v = json!({ + "cpus": cpus, + "memory_mib": memory_mib, + "running_cpus": running_cpus, + "running_memory_mib": running_memory_mib, + "awake": awake, + "max_cpus": max_cpus, + "max_memory_mib": max_memory_mib, + "overridden": overridden, + }); + if let Some((current_disk_gb, disk_gb, running_disk_gb)) = disk { + let (min_disk_gb, max_disk_gb) = crate::guest::disk::ui_bounds(current_disk_gb, disk_gb); + v["disk_gb"] = json!(disk_gb); + v["running_disk_gb"] = json!(running_disk_gb); + v["min_disk_gb"] = json!(min_disk_gb); + v["max_disk_gb"] = json!(max_disk_gb); + } + v } /// The host's system proxy, from kiri-win on Windows: `{http, https, @@ -968,6 +1112,22 @@ fn set_host_proxy(req: &Request) -> Result { Ok(super::proxy::report()) } +#[cfg(any(target_os = "linux", test))] +fn set_host_roots(req: &Request, caller: &Caller) -> Result { + // Only the Windows host (via kiri-win over the daemon's own socket) may + // supply host roots: never a container or an integrated WSL distro (#303). + if *caller != Caller::Host { + return Err(Error::Forbidden("the Windows roots can only be set from Kiri on Windows".into())); + } + // Only the engine in WSL takes them: a native Linux daemon has its own + // certificate store. + if !super::hostroots::in_wsl() { + return Err(Error::BadRequest("the Windows roots are for the engine in WSL".into())); + } + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + super::hostroots::set(&body).map_err(Error::Io) +} + fn set_proxy(req: &Request) -> Result { let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; let mode = body["mode"].as_str().filter(|m| ["system", "custom", "none"].contains(m)).ok_or_else(|| Error::BadRequest("mode must be system, custom or none".into()))?; @@ -1011,15 +1171,89 @@ fn set_domain_ports(req: &Request, engine: &Arc) -> Result super::domains::set_ports(engine, port("http")?, port("https")?).map_err(Error::Conflict) } +fn set_wsl(req: &Request, caller: &Caller) -> Result { + if caller.wsl_distro().is_some() { + return Err(Error::Forbidden("WSL integration settings can only be changed from Kiri on Windows".into())); + } + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + let mut distros = Vec::new(); + for item in body["distros"].as_array().ok_or_else(|| Error::BadRequest("distros must be an array".into()))? { + let name = item["name"].as_str().unwrap_or_default(); + if !super::binds::valid_distro_name(name) { + return Err(Error::BadRequest(format!("invalid WSL distro name: {name}"))); + } + let gid = item["gid"] + .as_u64() + .and_then(|g| u32::try_from(g).ok()) + .ok_or_else(|| Error::BadRequest(format!("invalid gid for WSL distro {name}")))?; + distros.push(super::WslDistroConfig { name: name.to_owned(), gid }); + } + super::sync_wsl_sockets(&distros).map_err(Error::Io)?; + Ok(super::wsl_report()) +} + fn set_resources(req: &Request) -> Result<(), Error> { use super::engine as e; - let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; - let max_mem = e::physical_memory_bytes() >> 20; - let cpus = body["cpus"].as_u64().filter(|c| (1..=e::max_cpus() as u64).contains(c)).ok_or_else(|| Error::BadRequest(format!("cpus must be 1 to {}", e::max_cpus())))?; - let mem = body["memory_mib"].as_u64().filter(|m| (1024..=max_mem).contains(m)).ok_or_else(|| Error::BadRequest(format!("memory_mib must be 1024 to {max_mem}")))?; let path = e::resources_path().ok_or_else(|| Error::Io(io::Error::other("HOME is not set")))?; + let current_disk = cfg!(target_os = "macos").then(crate::guest::disk::current_gb); + save_resources( + &req.body, + &path, + e::max_cpus() as u64, + e::physical_memory_bytes() >> 20, + current_disk, + e::vm_disk_gb_config(), + e::vm_shared_nat_config(), + ) +} + +fn save_resources( + raw_body: &[u8], + path: &std::path::Path, + max_cpus: u64, + max_mem: u64, + current_disk_gb: Option, + existing_disk_gb: Option, + existing_shared_nat: Option, +) -> Result<(), Error> { + let body: Value = serde_json::from_slice(raw_body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + let cpus = body["cpus"].as_u64().filter(|c| (1..=max_cpus).contains(c)).ok_or_else(|| Error::BadRequest(format!("cpus must be 1 to {max_cpus}")))?; + let mem = body["memory_mib"].as_u64().filter(|m| (1024..=max_mem).contains(m)).ok_or_else(|| Error::BadRequest(format!("memory_mib must be 1024 to {max_mem}")))?; + let mut out = std::fs::read_to_string(path) + .ok() + .and_then(|s| serde_json::from_str::(&s).ok()) + .filter(Value::is_object) + .unwrap_or_else(|| json!({})); + out["cpus"] = json!(cpus); + out["memory_mib"] = json!(mem); + // Left out, the saved swap stays (#326). + if let Some(val) = body.get("swap_mib").filter(|v| !v.is_null()) { + let max = super::engine::MAX_SWAP_MIB; + let swap = val.as_u64().filter(|s| *s <= max).ok_or_else(|| Error::BadRequest(format!("swap_mib must be 0 to {max}")))?; + out["swap_mib"] = json!(swap); + } + if let Some(val) = body.get("disk_gb").filter(|v| !v.is_null()) { + let current = current_disk_gb.unwrap_or(crate::guest::disk::DEFAULT_GB); + let (min_disk, max_disk) = crate::guest::disk::ui_bounds(current, existing_disk_gb.unwrap_or(current)); + let disk_gb = val + .as_u64() + .filter(|d| (min_disk..=max_disk).contains(d)) + .ok_or_else(|| Error::BadRequest(format!("disk_gb must be {min_disk} to {max_disk}")))?; + out["disk_gb"] = json!(disk_gb); + } else if let Some(prev) = existing_disk_gb { + out["disk_gb"] = json!(prev); + } + if let Some(val) = body.get("shared_nat").filter(|v| !v.is_null()) { + let shared_nat = val.as_bool().ok_or_else(|| Error::BadRequest("shared_nat must be a boolean".into()))?; + out["shared_nat"] = json!(shared_nat); + } else if let Some(prev) = existing_shared_nat { + out["shared_nat"] = json!(prev); + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(Error::Io)?; + } let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, json!({"cpus": cpus, "memory_mib": mem}).to_string()).and_then(|()| std::fs::rename(&tmp, &path)).map_err(Error::Io) + std::fs::write(&tmp, out.to_string()).and_then(|()| std::fs::rename(&tmp, path)).map_err(Error::Io) } fn set_ports(req: &Request, engine: &Engine, id: &str) -> Result { @@ -1061,6 +1295,73 @@ fn set_env(req: &Request, engine: &Engine, id: &str) -> Result { Ok(Value::Null) } +/// Active WSL drive bind sources of running containers, for `kiri-win`'s +/// opt-in bind-mount watcher. +fn watch_roots(engine: &Engine) -> Value { + let root = super::binds::wsl().map_or("/mnt/", |w| w.root.as_str()); + json!({ + "automount_root": root, + "roots": engine.wsl_bind_sources(root), + }) +} + +/// Parses `POST /kiri/fs-events` (`{"events": ["OP\tPATH", ...]}` or newline- +/// separated `OP\tPATH` text), filters to valid WSL automount paths under +/// `automount_root` with no `..` traversal, and caps per-request volume. OP is +/// a change (`C`, `M`, `A`, `D`) or a watched root's pin (`P`) or unpin (`U`). +fn parse_fs_events(body: &[u8], automount_root: &str) -> Result, Error> { + const MAX_EVENTS: usize = 4096; + let raw: Vec = if body.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{') { + let v: Value = serde_json::from_slice(body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + strings(&v["events"]).ok_or_else(|| Error::BadRequest("events must be a list of OP\\tPATH lines".into()))? + } else { + let text = std::str::from_utf8(body).map_err(|_| Error::BadRequest("invalid UTF-8 body".into()))?; + text.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect() + }; + if raw.len() > MAX_EVENTS { + return Err(Error::BadRequest(format!("too many events ({}, limit is {MAX_EVENTS})", raw.len()))); + } + Ok(raw + .into_iter() + .filter(|line| { + let Some((op, path)) = line.split_once('\t') else { return false }; + matches!(op, "C" | "M" | "A" | "D" | "P" | "U") && super::binds::is_wsl_drive_path(path, automount_root, false) + }) + .collect()) +} + +fn fs_events(req: &Request, engine: &Engine) -> Result { + let root = super::binds::wsl().map_or("/mnt/", |w| w.root.as_str()); + let lines = parse_fs_events(&req.body, root)?; + engine.send_fs_events(&lines); + Ok(Value::Null) +} + +/// Active published ports and WSL's internal `eth0` IPv4 address for +/// `kiri-win`'s Windows UDP and host-IP port forwarder. +fn win_ports(engine: &Engine) -> Value { + let wsl_ip = super::ports::wsl_ipv4().map(|ip| ip.to_string()); + let ports: Vec = engine + .published_ports() + .into_iter() + .map(|p| json!({"proto": p.proto, "host_ip": p.host_ip, "host_port": p.host_port})) + .collect(); + json!({ + "wsl_ip": wsl_ip, + "ports": ports, + }) +} + +fn sync_win_ports(req: &Request, engine: &Engine) -> Result { + if !req.body.is_empty() { + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + if let Some(ips) = strings(&body["host_ips"]) { + super::ports::set_windows_host_ips(&ips); + } + } + Ok(win_ports(engine)) +} + /// A registry client with the credentials the CLI sent, if any. fn client_for(req: &Request) -> Client { Client::new().with_credentials(req.header("x-registry-auth").and_then(kiri_image::Credentials::from_header)) @@ -1096,8 +1397,8 @@ fn auth(req: &Request) -> Result { fn push(req: &Request, engine: &Engine, name: &str, w: &mut UnixStream) -> io::Result { let tag = req.query("tag").unwrap_or_default(); let full = if tag.is_empty() { name.to_owned() } else { format!("{name}:{tag}") }; - let (image, target) = match (engine.image(&full), Reference::parse(&full)) { - (Ok(Some(i)), Ok(r)) => (i, r), + let (image, _blob_pins, target) = match (engine.image_pinned(&full), Reference::parse(&full)) { + (Ok(Some((i, pins))), Ok(r)) => (i, pins, r), (Ok(None), _) => return reply(w, Err(Error::NotFound(format!("An image does not exist locally with the tag: {full}"))), 200), (Err(e), _) => return reply(w, Err(Error::Io(e)), 200), (_, Err(e)) => return reply(w, Err(Error::BadRequest(e.to_string())), 200), @@ -1212,6 +1513,7 @@ fn run_pull(req: &Request, engine: &Engine, reference: &Reference, job: &super:: } match result { Ok(image) => { + engine.prune_layers(); // Docker reports the digest it was asked for: the index's, if any. line(json!({"status": format!("Digest: {}", image.index_digest.as_ref().unwrap_or(&image.digest))})); line(json!({"status": format!("Status: Downloaded newer image for {}", image.name)})); @@ -1316,14 +1618,19 @@ fn pull_hint(e: &kiri_image::registry::Error, registry: &str, proxy: Option<&str /// `-p` (`HostConfig.PortBindings`) and `-P` (`PublishAllPorts`: every port /// the image or `--expose` declares, on a free host port). -fn port_bindings(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result, Error> { +fn port_bindings(body: &Value, exposed: &[String]) -> Result, Error> { let parse = |key: &str| -> Result<(u16, String), Error> { let (port, proto) = key.split_once('/').unwrap_or((key, "tcp")); - let port = port.parse().map_err(|_| Error::BadRequest(format!("invalid port {key}")))?; + let port: u16 = port + .parse() + .ok() + .filter(|&p| p > 0 && port.bytes().all(|b| b.is_ascii_digit())) + .ok_or_else(|| Error::BadRequest(format!("invalid port {key}")))?; + let proto = proto.to_ascii_lowercase(); if proto != "tcp" && proto != "udp" { return Err(Error::BadRequest(format!("Kiri forwards TCP and UDP ports, not {key}"))); } - Ok((port, proto.to_owned())) + Ok((port, proto)) }; let mut out = Vec::new(); if let Some(map) = body["HostConfig"]["PortBindings"].as_object() { @@ -1344,17 +1651,8 @@ fn port_bindings(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Re } } if body["HostConfig"]["PublishAllPorts"].as_bool() == Some(true) { - let mut exposed: Vec = body["ExposedPorts"].as_object().map(|m| m.keys().cloned().collect()).unwrap_or_default(); - // The image's own EXPOSE lines live in its config blob. - if let Ok(bytes) = engine.store.read_config(&image.config_digest) { - if let Ok(cfg) = serde_json::from_slice::(&bytes) { - if let Some(m) = cfg["config"]["ExposedPorts"].as_object() { - exposed.extend(m.keys().cloned()); - } - } - } for key in exposed { - let Ok((container_port, proto)) = parse(&key) else { continue }; + let Ok((container_port, proto)) = parse(key) else { continue }; if !out.iter().any(|b| b.container_port == container_port && b.proto == proto) { out.push(super::ports::Binding { container_port, proto, host_ip: String::new(), host_port: 0 }); } @@ -1366,6 +1664,99 @@ fn port_bindings(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Re /// The VM path containers mount to reach the Mac's SSH agent (Docker /// Desktop's and OrbStack's name for it). const SSH_AGENT_SOCK: &str = "/run/host-services/ssh-auth.sock"; +const HOST_SSH_AGENT_SOCK: &str = "/run/kiri/host-services/ssh-auth.sock"; + +/// What the guest is given for that bind: the VM's path, or on a Linux host +/// where the agent listens, under Kiri's own /run/kiri. The host's +/// /run/host-services belongs to Docker Desktop for Linux, and the agent +/// never creates it there (#420). Inspect still shows the path asked for. +fn ssh_agent_source() -> &'static str { + ssh_agent_source_for(cfg!(target_os = "linux")) +} + +fn ssh_agent_source_for(linux: bool) -> &'static str { + if linux { HOST_SSH_AGENT_SOCK } else { SSH_AGENT_SOCK } +} + +fn is_ssh_agent_sock(src: &str) -> bool { + src.starts_with('/') && lexical_path(src) == SSH_AGENT_SOCK +} + +/// Classification of a container bind mount source that should be backed by +/// Kiri's SSH agent relay socket instead of a plain filesystem bind. +#[derive(Debug, PartialEq, Eq)] +enum SshAgentBind { + /// Docker Desktop / OrbStack's virtual `/run/host-services/ssh-auth.sock`. + Virtual, + /// A macOS host SSH agent Unix socket (virtiofs cannot forward host Unix + /// domain sockets into the Linux VM). Holds `Some(canonical_path)` when a + /// live, current-UID-owned socket exists on disk; `None` when a well-known + /// agent socket path does not exist yet. + MacHost(Option), +} + +fn ssh_agent_bind_for(src: &str, mac: bool) -> Option { + if is_ssh_agent_sock(src) { + return Some(SshAgentBind::Virtual); + } + if !mac || !src.starts_with('/') { + return None; + } + let p = std::path::Path::new(src); + match std::fs::symlink_metadata(p) { + Ok(_) => { + // Resolve symlinks first so a link named `S.gpg-agent.ssh` pointing + // to `docker.sock` or another socket is judged by its real target. + let canon = std::fs::canonicalize(p).ok()?; + if !super::ports::is_owned_unix_socket(&canon) || super::ports::is_kiri_socket_path(&canon) { + return None; + } + if super::ports::is_known_mac_ssh_agent_sock_path(&canon) + || super::ports::matches_default_ssh_auth_sock(&canon) + { + Some(SshAgentBind::MacHost(Some(canon))) + } else { + None + } + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + // Not on disk yet (e.g. gpg-agent not started): still translate + // well-known Mac agent socket paths to the guest relay so `-v` does + // not create a directory over `S.gpg-agent.ssh`. + let clean = std::path::PathBuf::from(lexical_path(src)); + if !super::ports::is_kiri_socket_path(&clean) + && super::ports::is_known_mac_ssh_agent_sock_path(&clean) + { + Some(SshAgentBind::MacHost(None)) + } else { + None + } + } + Err(_) => None, + } +} + +/// Restores a strict host SSH agent bind mount as the preferred upstream on +/// container start (macOS only), so restarting a container after a daemon +/// reboot keeps reaching the agent it mounted without allowing container-created +/// specs to point `serve_ssh_agent` at arbitrary sockets. +pub(super) fn refresh_ssh_agent_mounts(info: &[Value]) { + if !cfg!(target_os = "macos") { + return; + } + for m in info { + if m["Type"] != "bind" { + continue; + } + let Some(src) = m["Source"].as_str() else { continue }; + if super::binds::engine_socket(src).is_some() { + continue; + } + if let Some(SshAgentBind::MacHost(Some(host_path))) = ssh_agent_bind_for(src, true) { + super::ports::set_preferred_ssh_auth_sock_strict(&host_path); + } + } +} /// A container's mounts, worked out at create time. struct Mounts { @@ -1466,11 +1857,20 @@ fn fresh_bind_sources_with(guest: &[String], info: &[Value], engine_socket: impl let Some((old, rest)) = line.split_once('\t') else { return line.clone() }; let src = info.get(idx).filter(|i| paired && i["Type"] == "bind").and_then(|i| i["Source"].as_str()); if !mac { + if is_ssh_agent_sock(old) || src.is_some_and(is_ssh_agent_sock) { + return format!("{}\t{rest}", ssh_agent_source_for(!mac)); + } let given = src.and_then(&engine_socket).or_else(|| old.starts_with('/').then(|| engine_socket(old)).flatten()); return given.map_or_else(|| line.clone(), |given| format!("{given}\t{rest}")); } let Some(src) = src else { return line.clone() }; - if !old.strip_prefix(MAC_ROOT).is_some_and(|p| p.starts_with('/')) || engine_socket(src).is_some() { + if engine_socket(src).is_some() { + return line.clone(); + } + if ssh_agent_bind_for(src, mac).is_some() { + return format!("{}\t{rest}", ssh_agent_source_for(!mac)); + } + if !old.strip_prefix(MAC_ROOT).is_some_and(|p| p.starts_with('/')) { return line.clone(); } format!("{}\t{rest}", guest_bind_source(src)) @@ -1478,12 +1878,39 @@ fn fresh_bind_sources_with(guest: &[String], info: &[Value], engine_socket: impl .collect() } +/// Parses `--add-host name:ip` entries into `/etc/hosts` lines (`ip\tname`). +/// `host-gateway` is always stored as `HOST_ADDR` (never baking `192.168.65.254` +/// into the saved container spec) so `kiri-init`'s `host_etc_target` maps it +/// dynamically at container start time based on whether the WSL host relay is +/// live, falling back to the bridge gateway if the relay isn't running later. +fn extra_hosts_from(raw: &[String]) -> Result, Error> { + let mut extra_hosts = Vec::with_capacity(raw.len()); + for h in raw { + let Some((name, ip)) = h.split_once(':') else { continue }; + let ip = if ip == "host-gateway" { super::ports::HOST_ADDR } else { ip }; + if ip.parse::().is_err() { + return Err(Error::BadRequest(format!("invalid IP address: {ip}"))); + } + if !valid_hosts_name(name) { + return Err(Error::BadRequest(format!("invalid host name ({name})"))); + } + extra_hosts.push(format!("{ip}\t{name}")); + } + Ok(extra_hosts) +} + /// An NFS or CIFS server name as an address the guest kernel can use. -/// `host.docker.internal` is the Mac, as it is for containers. +/// `host.docker.internal` is the Mac (or the Windows host under WSL 2), +/// as it is for containers. fn resolve_server(host: &str) -> Option { use std::net::ToSocketAddrs; - if cfg!(target_os = "macos") && matches!(host, "host.docker.internal" | "host.kiri.internal") { - return Some(super::ports::HOST_ADDR.to_owned()); + if matches!(host, "host.docker.internal" | "host.kiri.internal") { + if cfg!(target_os = "macos") { + return Some(super::ports::HOST_ADDR.to_owned()); + } + if crate::hostrelay::wsl_host_active() { + return Some(crate::hostrelay::WSL_HOST_ADDR_STR.to_owned()); + } } let addrs: Vec = (host, 0).to_socket_addrs().ok()?.collect(); addrs.iter().find(|a| a.is_ipv4()).or(addrs.first()).map(|a| a.ip().to_string()) @@ -1613,9 +2040,66 @@ fn volumes_from_mounts(guest: &[String], info: &[Value], ro: bool) -> Vec<(Strin .collect() } +/// Prepares a host bind-mount source path before adding it to a container spec. +/// On Linux/WSL, `/etc/localtime` and `/etc/timezone` are never created as +/// directories: if missing (for `-v`) or an empty directory (left by an earlier +/// version before #938), they are created/repaired as valid timezone files. +fn prepare_bind_source(src: &str, here: &str, create_missing: bool) -> Result<(), Error> { + let tz = std::env::var("TZ").ok(); + prepare_bind_source_at(std::path::Path::new("/"), src, here, create_missing, !cfg!(target_os = "macos"), tz.as_deref()) +} + +fn prepare_bind_source_at( + root: &std::path::Path, + src: &str, + here: &str, + create_missing: bool, + linux_tz_guard: bool, + tz_env: Option<&str>, +) -> Result<(), Error> { + let norm = lexical_path(here); + let p = if root == std::path::Path::new("/") { + std::path::PathBuf::from(here) + } else { + root.join(norm.trim_start_matches('/')) + }; + if linux_tz_guard && matches!(norm.as_str(), "/etc/localtime" | "/etc/timezone") { + let heal = || match norm.as_str() { + "/etc/localtime" => super::localtime::ensure_localtime_at(root, tz_env).map_err(Error::Io), + _ => super::localtime::ensure_timezone_at(root, tz_env).map_err(Error::Io), + }; + let is_dir = std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_dir()); + if is_dir { + return heal(); + } + if !super::localtime::is_valid_timezone_file_at(root, &p) { + if !create_missing && !std::fs::symlink_metadata(&p).is_ok_and(|m| m.file_type().is_file()) { + return Err(Error::BadRequest(format!( + "invalid mount config for type \"bind\": bind source path does not exist: {src}" + ))); + } + return heal(); + } + return Ok(()); + } + if !p.exists() { + if !create_missing { + return Err(Error::BadRequest(format!("invalid mount config for type \"bind\": bind source path does not exist: {src}"))); + } + super::binds::make_source(&p).map_err(Error::Io)?; + } + Ok(()) +} + /// `-v`, `--mount`, `--tmpfs`, `--volumes-from`, `-v /path` and the image's /// VOLUME lines. +#[cfg(test)] fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result { + mounts_for(body, engine, image, &super::caller::Caller::Host) +} + +fn mounts_for(body: &Value, engine: &Engine, image: &kiri_image::Image, caller: &super::caller::Caller) -> Result { + let wsl_distro = caller.wsl_distro(); let host = &body["HostConfig"]; let mut out = Mounts { guest: Vec::new(), info: Vec::new(), volumes: Vec::new(), anon: Vec::new() }; let check_target = |t: &str| -> Result<(), Error> { @@ -1649,14 +2133,24 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result { out.guest.push(format!("{}\t{dst}\t{}", engine_sock.as_deref().unwrap_or_default(), flag(""))); out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); } - "bind" if src == SSH_AGENT_SOCK => { - out.guest.push(format!("{src}\t{dst}\t{}", flag(""))); + "bind" if ssh_sock.is_some() => { + if let Some(SshAgentBind::MacHost(Some(ref host_path))) = ssh_sock + && *caller == super::caller::Caller::Host + { + super::ports::set_preferred_ssh_auth_sock(host_path); + } + out.guest.push(format!("{}\t{dst}\t{}", ssh_agent_source(), flag(""))); out.info.push(json!({"Type": "bind", "Source": src, "Destination": dst, "Mode": "", "RW": !ro, "Propagation": "rprivate"})); } "bind" => { @@ -1672,13 +2166,7 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result Result Result super::binds::source(src, w)?, + let src = match (wsl, wsl_distro) { + (_, Some(d)) if kind == "bind" => super::binds::distro_source(src, d, wsl)?, + (Some(w), None) if kind == "bind" => super::binds::source(src, w)?, _ => src.to_owned(), }; let src = src.as_str(); @@ -1822,6 +2312,80 @@ fn mounts(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Result Value { + let host = &body["HostConfig"]; + let mut volumes = serde_json::Map::new(); + for given in [&body["Volumes"], &image_cfg["config"]["Volumes"]] { + for path in given.as_object().into_iter().flat_map(|m| m.keys()) { + volumes.entry(path.clone()).or_insert_with(|| json!({})); + } + } + json!({ + "Binds": host["Binds"], + "Mounts": host["Mounts"], + "Tmpfs": host["Tmpfs"], + "Volumes": if volumes.is_empty() { Value::Null } else { Value::Object(volumes) }, + }) +} + +/// [`mount_request`] for inspect. A container saved before it was kept has +/// only Docker's `Mounts` entries, so they are made from those: a bind or a +/// named volume as a `Binds` line, a tmpfs in `Tmpfs` (or `Mounts` when +/// read-only), an anonymous volume in `Volumes` (or `Mounts` when read-only), +/// never leaking generated anonymous volume IDs or internal paths. +fn inspect_mounts(spec: &Spec, is_anon_volume: impl Fn(&str) -> bool) -> Value { + if !spec.mount_request.is_null() { + return spec.mount_request.clone(); + } + let (mut binds, mut mounts, mut tmpfs, mut volumes) = (Vec::new(), Vec::new(), serde_json::Map::new(), serde_json::Map::new()); + let mut seen = std::collections::HashSet::new(); + for m in &spec.mount_info { + let dst = m["Destination"].as_str().unwrap_or_default(); + if dst.is_empty() || !seen.insert(dst.trim_end_matches('/').to_owned()) { + continue; + } + let rw = m["RW"] != false; + let ro = if rw { "" } else { ":ro" }; + match (m["Type"].as_str(), m["Name"].as_str()) { + (Some("bind"), _) => { + let src = m["Source"].as_str().unwrap_or_default(); + if !src.is_empty() { + binds.push(format!("{src}:{dst}{ro}")); + } + } + (Some("volume"), Some(name)) if spec.anon_volumes.iter().any(|a| a == name) || is_anon_volume(name) => { + if rw { + volumes.insert(dst.to_owned(), json!({})); + } else { + mounts.push(json!({"Type": "volume", "Target": dst, "ReadOnly": true})); + } + } + (Some("volume"), Some(name)) if !name.is_empty() => { + binds.push(format!("{name}:{dst}{ro}")); + } + (Some("tmpfs"), _) => { + if rw { + tmpfs.insert(dst.to_owned(), json!("")); + } else { + mounts.push(json!({"Type": "tmpfs", "Target": dst, "ReadOnly": true})); + } + } + _ => {} + } + } + let or_null = |v: Value, empty: bool| if empty { Value::Null } else { v }; + json!({ + "Binds": or_null(json!(binds), binds.is_empty()), + "Mounts": or_null(json!(mounts), mounts.is_empty()), + "Tmpfs": or_null(json!(tmpfs), tmpfs.is_empty()), + "Volumes": or_null(json!(volumes), volumes.is_empty()), + }) +} + fn volume_json(v: &super::volumes::Volume) -> Value { json!({ "Name": v.name, @@ -1898,17 +2462,16 @@ fn volumes(req: &Request, engine: &Engine) -> Result { Ok(json!({"Volumes": list, "Warnings": []})) } -/// The TCP ports an image declares (EXPOSE) plus `--expose`. -fn exposed_ports(body: &Value, engine: &Engine, image: &kiri_image::Image) -> Vec { - let mut keys: Vec = body["ExposedPorts"].as_object().map(|m| m.keys().cloned().collect()).unwrap_or_default(); - if let Ok(bytes) = engine.store.read_config(&image.config_digest) { - if let Ok(cfg) = serde_json::from_slice::(&bytes) { - if let Some(m) = cfg["config"]["ExposedPorts"].as_object() { - keys.extend(m.keys().cloned()); +/// The image's and create request's ExposedPorts keys; a bare port means TCP. +fn exposed_ports(body: &Value, image_cfg: &Value) -> Vec { + let mut ports = Vec::new(); + for map in [body["ExposedPorts"].as_object(), image_cfg["config"]["ExposedPorts"].as_object()].into_iter().flatten() { + for key in map.keys() { + if let Some(norm) = super::engine::normalize_exposed_key(key) { + ports.push(norm); } } } - let mut ports: Vec = keys.iter().filter(|k| k.ends_with("/tcp") || !k.contains('/')).filter_map(|k| k.split('/').next()?.parse().ok()).collect(); ports.sort_unstable(); ports.dedup(); ports @@ -1942,13 +2505,13 @@ fn inspect_bindings(ports: &[super::ports::Binding]) -> Value { /// Config.ExposedPorts: the image's and `--expose`'s ports, and every /// published one, as Docker lists them (`"80/tcp": {}`); null with none, /// as Docker leaves it out. -fn inspect_exposed(ports: &[super::ports::Binding], exposed: &[u16]) -> Value { +fn inspect_exposed(ports: &[super::ports::Binding], exposed: &[String]) -> Value { let mut m = serde_json::Map::new(); for b in ports { m.insert(format!("{}/{}", b.container_port, b.proto), json!({})); } - for p in exposed { - m.entry(format!("{p}/tcp")).or_insert_with(|| json!({})); + for key in exposed { + m.entry(key.clone()).or_insert_with(|| json!({})); } if m.is_empty() { Value::Null } else { Value::Object(m) } } @@ -1967,7 +2530,7 @@ fn ports_map(c: &Container) -> Value { /// given) every exposed or `-p` port that has none as a key with a null value /// (`"80/tcp": null`), as Docker shows them. Traefik's docker provider picks /// a container's port from these keys alone. -fn ports_map_of(bound: &[(super::ports::Binding, String, u16)], exposed: Option<(&[super::ports::Binding], &[u16])>) -> Value { +fn ports_map_of(bound: &[(super::ports::Binding, String, u16)], exposed: Option<(&[super::ports::Binding], &[String])>) -> Value { let mut m = serde_json::Map::new(); for (b, ip, port) in bound { let key = format!("{}/{}", b.container_port, b.proto); @@ -1980,8 +2543,8 @@ fn ports_map_of(bound: &[(super::ports::Binding, String, u16)], exposed: Option< for b in asked { m.entry(format!("{}/{}", b.container_port, b.proto)).or_insert(Value::Null); } - for p in exposed { - m.entry(format!("{p}/tcp")).or_insert(Value::Null); + for key in exposed { + m.entry(key.clone()).or_insert(Value::Null); } } Value::Object(m) @@ -2016,7 +2579,7 @@ fn command(entry: Option>, cmd: Option>, image_entry: &[ }) } -/// The primary network when NetworkMode is empty or `default`: the first +/// The primary network when NetworkMode is empty, `default` or `bridge`: the first /// resolved endpoint's name, unless bridge is listed. No match keeps bridge. /// Unknown endpoints are left for create to reject. `keys` come from the /// request's JSON map, so they are sorted and "first" is the same every time. @@ -2137,11 +2700,30 @@ pub(super) fn cpu_weight(shares: u64) -> u32 { ((w * 1e9).round() / 1e9).ceil() as u32 } -pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> super::engine::Limits { +pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> Result { let mut l = base; + // Normalize pre-#545 containers (`memory_max > 0, memory_swap == 0`) to + // Docker's effective `2 * memory` limit before checking updates against it. + l.memory_swap = l.memory_swap(); + // Docker's checks for `--memory-swap`, in Docker's words. + let swap = h["MemorySwap"].as_i64().filter(|s| *s != 0); if let Some(m) = h["Memory"].as_u64().filter(|m| *m > 0) { + if swap.is_none() && l.memory_swap > 0 && m > l.memory_swap as u64 { + return Err(Error::BadRequest("Memory limit should be smaller than already set memoryswap limit, update the memoryswap at the same time".into())); + } l.memory_max = m; } + if let Some(s) = swap { + if s > 0 && l.memory_max == 0 { + return Err(Error::BadRequest("You should always set the Memory limit when using Memoryswap limit, see usage".into())); + } + if s > 0 && (s as u64) < l.memory_max { + return Err(Error::BadRequest("Minimum memoryswap limit should be larger than memory limit, see usage".into())); + } + l.memory_swap = s.max(-1); + } + // Only a memory limit: as much swap again, which Docker writes down. + l.memory_swap = l.memory_swap(); if let Some(n) = h["NanoCpus"].as_u64().filter(|n| *n > 0) { // --cpus 1.5 → 150 ms of CPU time every 100 ms. l.cpu_period = 100_000; @@ -2149,32 +2731,167 @@ pub(super) fn limits_from(h: &Value, base: super::engine::Limits) -> super::engi } if let Some(q) = h["CpuQuota"].as_i64().filter(|q| *q > 0) { l.cpu_quota = q as u64; - l.cpu_period = h["CpuPeriod"].as_u64().filter(|p| *p > 0).unwrap_or(100_000) as u32; + l.cpu_period = u32::try_from(h["CpuPeriod"].as_u64().filter(|p| *p > 0).unwrap_or(100_000)) + .map_err(|_| Error::BadRequest("CpuPeriod is too large".into()))?; } if let Some(shares) = h["CpuShares"].as_u64().filter(|s| *s > 0) { l.cpu_shares = shares; l.cpu_weight = cpu_weight(shares); } - if let Some(p) = h["PidsLimit"].as_i64().filter(|p| *p > 0) { - l.pids_max = p as u32; + if let Some(p) = h["PidsLimit"].as_u64().filter(|p| *p > 0) { + l.pids_max = u32::try_from(p).map_err(|_| Error::BadRequest("PidsLimit is too large".into()))?; } - l + Ok(l) +} + +pub(super) fn restart_policy(v: &Value, creating: bool) -> Result { + let name = match v["Name"].as_str() { + Some("") | None => "no", + Some(n) => n, + }; + if !matches!(name, "no" | "always" | "unless-stopped" | "on-failure") { + let message = if creating { + format!("invalid restart policy {name}") + } else { + format!( + "invalid restart policy: unknown policy '{name}'; use one of 'no', 'always', 'on-failure', or 'unless-stopped'" + ) + }; + return Err(Error::BadRequest(message)); + } + if v["MaximumRetryCount"].as_i64().is_some_and(|n| n < 0) { + return Err(Error::BadRequest( + "invalid restart policy: maximum retry count cannot be negative".into(), + )); + } + let max_retries = v["MaximumRetryCount"].as_u64().unwrap_or(0); + if max_retries > 0 && name != "on-failure" { + return Err(Error::BadRequest( + "invalid restart policy: maximum retry count can only be used with 'on-failure'".into(), + )); + } + let max_retries = u32::try_from(max_retries) + .map_err(|_| Error::BadRequest("invalid restart policy: maximum retry count is too large".into()))?; + Ok(RestartPolicy { + name: name.to_owned(), + max_retries, + }) } +/// Returned in `POST /containers/create`'s `Warnings` when the caller asks for +/// `--security-opt seccomp=unconfined` (or `seccomp:unconfined`). Kiri lifts +/// the default syscall filter there, but `kiri-init` still installs the host +/// boundary on both VM and Linux-host containers (no `io_uring`, no `AF_VSOCK` +/// sockets), so workloads that ask for `seccomp=unconfined` to get `io_uring` +/// are told up front instead of failing silently with `EPERM` (#516). +const SECCOMP_UNCONFINED_WARNING: &str = + "seccomp=unconfined lifts the default syscall filter, but Kiri keeps its host boundary: io_uring and vsock sockets stay blocked"; + pub(super) fn create(req: &Request, engine: &Engine) -> Result { + create_by(req, engine, &super::caller::Caller::Host) +} + +fn unc_wsl_distro(s: &str) -> Option { + if s.bytes().any(|b| b.is_ascii_control()) { + return None; + } + let rest = if let Some(after_q) = s.strip_prefix(r"\\?\") { + if s.contains('/') || after_q.len() < 4 || !after_q[..4].eq_ignore_ascii_case(r"UNC\") { + return None; + } + after_q[4..].to_owned() + } else { + let norm = s.replace('/', "\\"); + if norm.starts_with(r"\\?\") || norm.starts_with(r"\\.\") { + return None; + } + norm.strip_prefix(r"\\")?.to_owned() + }; + let (host, after_host) = rest.split_once('\\')?; + if !(host.eq_ignore_ascii_case("wsl.localhost") || host.eq_ignore_ascii_case("wsl$")) { + return None; + } + let (distro, _) = after_host.split_once('\\').unwrap_or((after_host, "")); + super::binds::valid_distro_name(distro).then(|| distro.to_owned()) +} + +fn looks_windows_drive_path(s: &str) -> bool { + let s = s.strip_prefix(r"\\?\").unwrap_or(s); + let b = s.as_bytes(); + b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'\\' | b'/') +} + +fn created_wsl_distro(caller: &Caller, engine_distro: Option<&str>, labels: &Value) -> Option { + match caller { + Caller::Wsl(d) if super::binds::valid_distro_name(d) => Some(d.clone()), + Caller::Host => { + let paths = [ + "com.docker.compose.project.working_dir", + "com.docker.compose.project.config_files", + "com.docker.compose.project.environment_file", + ] + .into_iter() + .filter_map(|k| labels[k].as_str()) + .flat_map(|v| v.split(',').map(str::trim)) + .filter(|v| !v.is_empty()); + let mut saw_drive = false; + for p in paths { + if let Some(d) = unc_wsl_distro(p) { + return Some(d); + } + if looks_windows_drive_path(p) { + saw_drive = true; + } + } + if saw_drive { + None + } else { + engine_distro.filter(|d| super::binds::valid_distro_name(d)).map(str::to_owned) + } + } + _ => None, + } +} + +fn create_by(req: &Request, engine: &Engine, caller: &Caller) -> Result { + let body_labels = serde_json::from_slice::(&req.body).ok().map(|b| b["Labels"].clone()).unwrap_or(Value::Null); + let record_distro = created_wsl_distro(caller, super::binds::wsl().and_then(|w| w.distro.as_deref()), &body_labels); + create_inner(req, engine, caller, record_distro) +} + +#[cfg(test)] +pub(super) fn create_for(req: &Request, engine: &Engine, wsl_distro: Option<&str>) -> Result { + let record_distro = wsl_distro.filter(|d| super::binds::valid_distro_name(d)).map(str::to_owned); + let caller = match wsl_distro { + Some(d) => Caller::Wsl(d.to_owned()), + None => Caller::Host, + }; + create_inner(req, engine, &caller, record_distro) +} + +fn create_inner(req: &Request, engine: &Engine, caller: &Caller, record_wsl_distro: Option) -> Result { let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; let image_name = body["Image"].as_str().unwrap_or_default(); if image_name.is_empty() { return Err(Error::BadRequest("no image specified".into())); } let host = &body["HostConfig"]; + let security_opt = strings(&host["SecurityOpt"]).unwrap_or_default(); // A seccomp profile Kiri cannot apply fails the create, before anything // (volumes) is made for it. - if let super::seccomp::Choice::Profile(json) = super::seccomp::choice(&strings(&host["SecurityOpt"]).unwrap_or_default()).map_err(Error::BadRequest)? { - super::seccomp::compile(json, profile_caps(caps_from(host)?, host["Privileged"].as_bool().unwrap_or(false))).map_err(Error::BadRequest)?; - } + let seccomp_unconfined = match super::seccomp::choice(&security_opt).map_err(Error::BadRequest)? { + super::seccomp::Choice::Profile(json) => { + super::seccomp::compile(json, profile_caps(caps_from(host)?, host["Privileged"].as_bool().unwrap_or(false))).map_err(Error::BadRequest)?; + false + } + super::seccomp::Choice::Unconfined => true, + super::seccomp::Choice::Default => false, + }; + // NetworkMode `bridge` too: Docker joins only the endpoints' networks + // when there are any, whatever the mode names (k3d sends `bridge` with + // its cluster network, #727), unless they list bridge. let network_mode = match host["NetworkMode"].as_str().unwrap_or("default") { - "" | "default" => body["NetworkingConfig"]["EndpointsConfig"].as_object() + "" | "default" | "bridge" => body["NetworkingConfig"]["EndpointsConfig"].as_object() .and_then(|eps| endpoints_primary(eps.keys().map(String::as_str), |key| engine.lock_net().find(key).map(|n| (n.name.clone(), n.internal)))) .unwrap_or_else(|| "bridge".to_owned()), m => m.to_owned(), @@ -2246,29 +2963,23 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { // `--add-host name:ip` arrives as "name:ip"; /etc/hosts wants "ip name". // Both are written into the container's /etc/hosts by the guest, so a // newline in either would add lines of its own. - let mut extra_hosts = Vec::new(); - for h in strings(&host["ExtraHosts"]).unwrap_or_default() { - let Some((name, ip)) = h.split_once(':') else { continue }; - let ip = if ip == "host-gateway" { super::ports::HOST_ADDR } else { ip }; - if ip.parse::().is_err() { - return Err(Error::BadRequest(format!("invalid IP address: {ip}"))); - } - if !valid_hosts_name(name) { - return Err(Error::BadRequest(format!("invalid host name ({name})"))); - } - extra_hosts.push(format!("{ip}\t{name}")); + let extra_hosts = extra_hosts_from(&strings(&host["ExtraHosts"]).unwrap_or_default())?; + let mut warnings: Vec<&str> = Vec::new(); + if seccomp_unconfined { + warnings.push(SECCOMP_UNCONFINED_WARNING); } - let warnings: Vec<&str> = Vec::new(); // --ulimit, --sysctl, --device, --device-cgroup-rule, --group-add: // refused now with Docker's error rather than at start. let host_opts = super::hostopts::from_host(host); super::hostopts::guest_lines(&host_opts, network_mode == "host").map_err(Error::BadRequest)?; super::hostopts::check_device_requests(host).map_err(Error::BadRequest)?; + let limits = super::engine::Limits { shm_size: host["ShmSize"].as_u64().unwrap_or(0), ..limits_from(host, super::engine::Limits::default())? }; if let Some(s) = body["StopSignal"].as_str().filter(|s| !s.is_empty()) { parse_signal(s)?; } - let image = engine.image(image_name)?.ok_or_else(|| Error::NotFound(format!("No such image: {image_name}")))?; + let (image, _blob_pins) = engine.image_pinned(image_name)?.ok_or_else(|| Error::NotFound(format!("No such image: {image_name}")))?; + let _layer_pin = engine.pin_layers(image.layers.iter().map(|l| l.digest.as_str())); if let Some(why) = intel_mac_refusal(image_name, std::slice::from_ref(&image.platform)) { return Err(Error::BadRequest(why)); } @@ -2284,8 +2995,16 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { // Checked before mounts, which may create volumes. let healthcheck = healthcheck_from(&body, &image_cfg)?; let (entrypoint, cmd) = command(strings(&body["Entrypoint"]), strings(&body["Cmd"]), &image.config.entrypoint, &image.config.cmd)?; - let mounts = mounts(&body, engine, &image)?; - let ports = port_bindings(&body, engine, &image)?; + let restart = restart_policy(&host["RestartPolicy"], true)?; + let auto_remove = host["AutoRemove"].as_bool().unwrap_or(false); + if auto_remove && restart.name != "no" { + return Err(Error::BadRequest( + "can't create 'AutoRemove' container with restart policy".into(), + )); + } + let mounts = mounts_for(&body, engine, &image, caller)?; + let exposed = exposed_ports(&body, &image_cfg); + let ports = port_bindings(&body, &exposed)?; if !ports.is_empty() && network_mode == "none" { return Err(Error::BadRequest("a container with --network none cannot publish ports".into())); } @@ -2320,13 +3039,13 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { env, cwd: pick("WorkingDir", &image.config.working_dir), user: pick("User", &image.config.user), - auto_remove: host["AutoRemove"].as_bool().unwrap_or(false), + auto_remove, privileged: host["Privileged"].as_bool().unwrap_or(false), - limits: super::engine::Limits { shm_size: host["ShmSize"].as_u64().unwrap_or(0), ..limits_from(host, super::engine::Limits::default()) }, + limits, caps: caps_from(host)?, cap_add: strings(&host["CapAdd"]).unwrap_or_default(), cap_drop: strings(&host["CapDrop"]).unwrap_or_default(), - security_opt: strings(&host["SecurityOpt"]).unwrap_or_default(), + security_opt, readonly_rootfs: host["ReadonlyRootfs"].as_bool().unwrap_or(false), hostname, stop_signal: body["StopSignal"].as_str().filter(|s| !s.is_empty()).map(signal).or_else(|| { @@ -2355,28 +3074,18 @@ pub(super) fn create(req: &Request, engine: &Engine) -> Result { aliases, extra_hosts, ports, - exposed: exposed_ports(&body, engine, &image), + exposed, host_opts, volumes_from: strings(&host["VolumesFrom"]).unwrap_or_default(), pid_mode, + wsl_distro: record_wsl_distro, mounts: mounts.guest, mount_info: mounts.info, + mount_request: mount_request(&body, &image_cfg), volumes: mounts.volumes, anon_volumes: mounts.anon, - restart: RestartPolicy { - name: match host["RestartPolicy"]["Name"].as_str() { - Some("") | None => "no".to_owned(), - Some(n) => n.to_owned(), - }, - max_retries: host["RestartPolicy"]["MaximumRetryCount"].as_u64().unwrap_or(0) as u32, - }, + restart, }; - if !matches!(spec.restart.name.as_str(), "no" | "always" | "unless-stopped" | "on-failure") { - return Err(Error::BadRequest(format!("invalid restart policy {}", spec.restart.name))); - } - if spec.auto_remove && spec.restart.name != "no" { - return Err(Error::BadRequest("can't create 'AutoRemove' container with restart policy".into())); - } let id = engine.create(req.query("name").map(str::to_owned), spec, &image)?; Ok(json!({"Id": id, "Warnings": warnings})) } @@ -2487,14 +3196,7 @@ fn links_from(list: &[String], engine: &Engine) -> Result String { let ago = |t: Option| { - let s = t.and_then(|t| t.elapsed().ok()).map_or(0, |d| d.as_secs()); - match s { - 0..=1 => "Less than a second".to_owned(), - 2..=59 => format!("{s} seconds"), - 60..=3599 => format!("{} minutes", s / 60), - 3600..=86399 => format!("{} hours", s / 3600), - _ => format!("{} days", s / 86400), - } + super::time::human_duration(t.and_then(|t| t.elapsed().ok()).map_or(0, |d| d.as_secs())) }; match c.status { Status::Created => "Created".into(), @@ -2600,11 +3302,13 @@ fn ipam_config(want4: &str, want6: &str) -> Value { /// networks and healthcheck state. fn container_inspect(engine: &Engine, key: &str) -> Result { let id = engine.resolve(key)?; - let networks: Vec = engine.lock_net().all().to_vec(); let health = engine.health(&id); + let anon_vols: Vec = engine.volume_list().into_iter().filter(|v| v.anonymous).map(|v| v.name).collect(); engine.with(&id, |c| { - let mut v = inspect(c, &networks); - v["NetworkSettings"]["Networks"] = endpoints(c, &networks); + let net = engine.lock_net(); + let networks = net.all(); + let mut v = inspect(c, networks, &anon_vols); + v["NetworkSettings"]["Networks"] = endpoints(c, networks); // The old top-level fields describe the default bridge only. if c.spec.network_mode == "bridge" { let ep = v["NetworkSettings"]["Networks"]["bridge"].clone(); @@ -2631,69 +3335,115 @@ fn container_inspect(engine: &Engine, key: &str) -> Result { }) } +fn spec_wsl_distro(spec: &super::engine::Spec) -> Option { + if let Some(d) = spec.wsl_distro.as_deref().filter(|d| super::binds::valid_distro_name(d)) { + return Some(d.to_owned()); + } + if spec.mount_info.is_empty() { + return None; + } + let custom = format!("{}/roots/", super::binds::wsl_kiri_dir()); + for m in &spec.mount_info { + let Some(src) = m["Source"].as_str() else { continue }; + for prefix in [custom.as_str(), "/mnt/wsl/kiri/roots/"] { + if let Some(rest) = src.strip_prefix(prefix) { + let d = rest.split('/').next().unwrap_or(rest); + if super::binds::valid_distro_name(d) { + return Some(d.to_owned()); + } + } + } + } + None +} + fn list(req: &Request, engine: &Engine) -> Result { let f = filters(req, &["id", "name", "label", "label!", "status", "ancestor", "network", "exited", "volume", "health"])?; if let Some(bad) = f.values("health").and_then(|v| v.iter().find(|v| !super::health::valid_filter(v))) { return Err(Error::BadRequest(format!("Unrecognised filter value for health: {bad}"))); } + let limit = match req.query("limit").filter(|v| !v.is_empty()) { + Some(v) => { + let n = v + .parse::() + .map_err(|_| Error::BadRequest(format!("invalid limit: {v}")))?; + usize::try_from(n).ok().filter(|n| *n > 0) + } + None => None, + }; let health = engine.health_statuses(); // Docker matches the image each `ancestor` value names, by ID (#442). let ancestors = f.values("ancestor").map(|v| engine.ancestor_ids(v)).transpose()?; - // A status filter lists stopped containers without --all, as Docker does. - let all = req.flag("all") || f.values("status").is_some() || f.values("exited").is_some(); - let networks: Vec = engine.lock_net().all().to_vec(); - let mut rows = engine.each(|c| { + // A status filter or a limit lists stopped containers without --all, as Docker does. + let all = req.flag("all") + || limit.is_some() + || f.values("status").is_some() + || f.values("exited").is_some(); + let mut rows = engine.each_with_networks(|c, networks| { if !all && c.status != Status::Running { return None; } let labels = if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }; - let net = networks.iter().find(|n| n.name == c.spec.network_mode || n.id == c.spec.network_mode || (c.spec.network_mode == "default" && n.name == "bridge")); + let first = (!c.spec.left_all_networks) + .then(|| networks.iter().find(|n| n.name == c.spec.network_mode || n.id == c.spec.network_mode || (c.spec.network_mode == "default" && n.name == "bridge"))) + .flatten(); let keep = f.any("id", |v| c.id.starts_with(v)) && f.name(&c.name) && f.labels(&labels) && f.any("status", |v| v == state_word(c)) && f.any("exited", |v| c.status == Status::Exited && v.parse() == Ok(c.exit_code)) && ancestors.as_ref().is_none_or(|ids| ids.contains(&c.spec.image_id)) - && f.any("network", |v| net.is_some_and(|n| n.name == v || n.id.starts_with(v))) + && f.any("network", |v| { + first.is_some_and(|n| n.name == v || n.id.starts_with(v)) + || c.spec.extra_networks.iter().any(|x| networks.iter().find(|n| n.name == x.name).is_some_and(|n| n.name == v || n.id.starts_with(v))) + }) && f.any("volume", |v| c.spec.volumes.iter().chain(&c.spec.anon_volumes).any(|n| n == v) || c.spec.mount_info.iter().any(|m| m["Destination"] == v || m["Source"] == v)) && f.any("health", |v| v == health.get(&c.id).map_or("none", |h| h.status.as_str())); if !keep { return None; } - Some(( - time::unix(c.created), - json!({ - "Id": c.id, - "Names": [format!("/{}", c.name)], - "Image": c.spec.image, - "ImageID": c.spec.image_id, - "Command": c.argv().join(" "), - "Created": time::unix(c.created), - "State": state_word(c), - "Status": ps_status(c, health.get(&c.id)), - // Kiri's own: the window counts "Up 3 s" from these every second. - // Docker clients ignore fields they don't know. - "KiriStartedAt": c.started.map(time::unix), - "KiriFinishedAt": c.finished.map(time::unix), - "KiriExitCode": c.exit_code, - "KiriOOMKilled": c.oom_killed, - "KiriVmStopped": c.vm_stopped, - "Ports": ports_list(c), - "Labels": if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }, - "HostConfig": {"NetworkMode": c.spec.network_mode}, - "NetworkSettings": {"Networks": endpoints(c, &networks)}, - "Mounts": c.spec.mount_info, - }), - )) + let mut row = json!({ + "Id": c.id, + "Names": [format!("/{}", c.name)], + "Image": c.spec.image, + "ImageID": c.spec.image_id, + "Command": c.argv().join(" "), + "Created": time::unix(c.created), + "State": state_word(c), + "Status": ps_status(c, health.get(&c.id)), + // Kiri's own: the window counts "Up 3 s" from these every second. + // Docker clients ignore fields they don't know. + "KiriStartedAt": c.started.map(time::unix), + "KiriFinishedAt": c.finished.map(time::unix), + "KiriExitCode": c.exit_code, + "KiriOOMKilled": c.oom_killed, + "KiriVmStopped": c.vm_stopped, + "KiriStoppedByUser": c.stopped_by_user, + "Ports": ports_list(c), + "Labels": if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }, + "HostConfig": {"NetworkMode": c.spec.network_mode}, + "NetworkSettings": {"Networks": endpoints(c, networks)}, + "Mounts": c.spec.mount_info, + }); + if let Some(distro) = spec_wsl_distro(&c.spec) { + row["KiriWslDistro"] = json!(distro); + } + Some((c.created, row)) }); - rows.sort_by_key(|r| std::cmp::Reverse(r.0)); + rows.sort_by(|a, b| { + b.0.cmp(&a.0) + .then_with(|| a.1["Id"].as_str().cmp(&b.1["Id"].as_str())) + }); + if let Some(limit) = limit { + rows.truncate(limit); + } Ok(Value::Array(rows.into_iter().map(|(_, v)| v).collect())) } -fn inspect(c: &Container, nets: &[super::network::Network]) -> Value { +fn inspect(c: &Container, nets: &[super::network::Network], anon_vols: &[String]) -> Value { let when = |t: Option| t.map_or_else(|| time::ZERO.to_owned(), time::rfc3339); let argv = c.argv(); - json!({ + let mut v = json!({ "Id": c.id, "Created": time::rfc3339(c.created), "Path": argv.first().cloned().unwrap_or_default(), @@ -2773,7 +3523,19 @@ fn inspect(c: &Container, nets: &[super::network::Network]) -> Value { }, "NetworkSettings": network_settings(c, nets), "Mounts": c.spec.mount_info, - }) + }); + for key in ["MaskedPaths", "ReadonlyPaths"] { + v["HostConfig"][key] = super::hostopts::system_paths(&c.spec.host_opts, key, c.spec.privileged); + } + v["HostConfig"]["CgroupnsMode"] = super::hostopts::inspect(&c.spec.host_opts, "CgroupnsMode"); + // Set apart: more keys in the macro above pass its recursion limit. + v["HostConfig"]["MemorySwap"] = json!(c.spec.limits.memory_swap()); + let mounts = inspect_mounts(&c.spec, |name| anon_vols.iter().any(|a| a == name)); + v["Config"]["Volumes"] = mounts["Volumes"].clone(); + for key in ["Binds", "Mounts", "Tmpfs"] { + v["HostConfig"][key] = mounts[key].clone(); + } + v } fn network_settings(c: &Container, nets: &[super::network::Network]) -> Value { @@ -3028,7 +3790,7 @@ fn forward_stdin(engine: Arc, id: String, r: &mut BufReader) /// it closely follows data, though the next read would see the end. For /// `docker run -i` that was a process waiting forever for the end of its input, /// in 1 to 5 runs in 100. poll is woken for it. -fn wait_readable(stream: &UnixStream) { +pub(super) fn wait_readable(stream: &UnixStream) { let mut fd = libc::pollfd { fd: stream.as_raw_fd(), events: libc::POLLIN, revents: 0 }; // SAFETY: one valid pollfd. Any other failure leaves the read to block or to // report it, as without this. @@ -3259,6 +4021,8 @@ pub(super) fn send_chunks(archive: &mut dyn io::Read, to_guest: &mut impl io::Wr pub(super) fn copy_error(m: &str) -> Error { if let Some(m) = m.strip_prefix("notfound: ") { Error::NotFound(m.to_owned()) + } else if let Some(m) = m.strip_prefix("forbidden: ") { + Error::Forbidden(m.to_owned()) } else if let Some(m) = m.strip_prefix("notdir: ") { Error::BadRequest(m.to_owned()) } else if m.contains("no such container") { @@ -3298,12 +4062,55 @@ fn path_stat_header(e: &kiri_proto::FsEntry<'_>, link: &str) -> String { format!("X-Docker-Container-Path-Stat: {}\r\n", kiri_image::b64::encode(stat.to_string().as_bytes())) } +const COPY_OUT_CHUNK: usize = 64 * 1024; + +pub(super) fn use_paced_copy(caller: &Caller) -> bool { + cfg!(target_os = "macos") && *caller == Caller::Container +} + +/// Streams a `COPY_PORT` archive (`OUT` or `EXPORT`) to an HTTP chunked +/// response. When `paced` is true, sends a 1-byte credit ack before reading +/// each `<= 64 KiB` chunk and finishes `f` before `http::chunk` writes to `w`, +/// so `COPY_PORT` never fills its host buffer while `w` blocks on +/// `ENGINE_API_PORT` (#874). +pub(super) fn stream_copy_out(f: &mut (impl io::Read + io::Write), w: &mut impl io::Write, paced: bool) -> io::Result<()> { + let mut buf = vec![0u8; COPY_OUT_CHUNK]; + if paced { + let mut hdr = [0u8; 4]; + loop { + f.write_all(&[1])?; + f.read_exact(&mut hdr)?; + let n = u32::from_le_bytes(hdr) as usize; + if n == 0 { + return Ok(()); + } + if n > COPY_OUT_CHUNK { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("oversized paced copy chunk {n}"))); + } + f.read_exact(&mut buf[..n])?; + http::chunk(w, &buf[..n])?; + } + } + loop { + let n = f.read(&mut buf)?; + if n == 0 { + return Ok(()); + } + http::chunk(w, &buf[..n])?; + } +} + /// `docker cp` out of a container (GET), or the stat it starts with (HEAD). -fn archive_get(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> io::Result { - use std::io::Read; +fn archive_get(req: &Request, engine: &Engine, id: &str, caller: &Caller, w: &mut UnixStream) -> io::Result { let path = req.query("path").unwrap_or("/"); - let op = if req.method == "HEAD" { kiri_proto::copy_op::STAT } else { kiri_proto::copy_op::OUT }; - let stream = match engine.copy(id, op, path, 0) { + let (op, paced, flags) = if req.method == "HEAD" { + (kiri_proto::copy_op::STAT, false, 0) + } else { + let paced = use_paced_copy(caller); + let flags = if paced { kiri_proto::copy_flags::PACED } else { 0 }; + (kiri_proto::copy_op::OUT, paced, flags) + }; + let stream = match engine.copy(id, op, path, flags) { Ok(s) => s, Err(e) => return reply(w, Err(e), 200), }; @@ -3315,7 +4122,11 @@ fn archive_get(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> // HEAD answers carry no body, so the reason goes nowhere; the CLI // reports "no such file" from the status alone. if req.method == "HEAD" { - let status = match copy_error(m) { Error::NotFound(_) => 404, _ => 400 }; + let status = match copy_error(m) { + Error::NotFound(_) => 404, + Error::Forbidden(_) => 403, + _ => 400, + }; http::head_only(w, status, "")?; return Ok(Next::KeepAlive); } @@ -3328,14 +4139,7 @@ fn archive_get(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream) -> return Ok(Next::KeepAlive); } http::begin_stream_with(w, 200, "application/x-tar", &header)?; - let mut buf = vec![0u8; 256 * 1024]; - loop { - let n = f.read(&mut buf)?; - if n == 0 { - break; - } - http::chunk(w, &buf[..n])?; - } + stream_copy_out(&mut f, w, paced)?; http::end(w)?; drop(stream); Ok(Next::KeepAlive) @@ -3442,14 +4246,27 @@ fn upload_reader<'a>(head: Vec, rest: impl io::Read + 'a) -> Result) -> io::Result { use kiri_proto::copy_flags; - let path = req.query("path").unwrap_or("/"); + let raw_path = req.query("path").unwrap_or("/"); let mut flags = copy_flags::CHUNKED; - if req.flag("copyUIDGID") { + let path = if req.flag("copyUIDGID") { flags |= copy_flags::KEEP_OWNERS; - } + let user = engine.with(id, |c| c.spec.user.clone()).unwrap_or_default(); + if user.is_empty() { raw_path.to_owned() } else { format!("{raw_path}\0{user}") } + } else { + raw_path.to_owned() + }; if req.flag("noOverwriteDirNonDir") { flags |= copy_flags::NO_OVERWRITE_DIR_NON_DIR; } + // Resolve the container and open the guest copy session before reading the + // body so missing containers fail with 404 without emitting `100 Continue`. + let stream = match engine.copy(id, kiri_proto::copy_op::IN, &path, flags) { + Ok(s) => s, + Err(e) => { + error_closing(w, e)?; + return Ok(Next::Close); + } + }; // Docker takes the archive plain or compressed; the guest unpacks tar. use std::io::Read; let mut body = http::Body::new(req, r); @@ -3463,13 +4280,6 @@ fn archive_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: return Ok(Next::Close); } }; - let stream = match engine.copy(id, kiri_proto::copy_op::IN, path, flags) { - Ok(s) => s, - Err(e) => { - error_closing(w, e)?; - return Ok(Next::Close); - } - }; let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); if let Err(e) = send_chunks(&mut archive, &mut to_guest) { // The body broke off or isn't valid gzip: dropping the stream ends @@ -3507,6 +4317,64 @@ fn archive_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: } } +/// `POST /kiri/containers/{id}/upper`: `kiri import`'s copy of the writable +/// layer a container had on Docker Desktop or OrbStack, an uncompressed OCI +/// layer tar (whiteouts as `.wh.` files), unpacked by the guest into the +/// container's own writable layer (copy.rs, `copy_op::UPPER`). Only for a +/// container that is not running and has no writable layer yet. A +/// container's connection never gets here (`container_may`). +fn upper_put(req: &Request, engine: &Engine, id: &str, w: &mut UnixStream, r: &mut BufReader) -> io::Result { + let refused = match engine.with(id, |c| c.status == Status::Running || c.paused) { + Ok(true) => Some(Error::Conflict(format!("container {id} is running: its writable layer can only be brought in before it runs"))), + Ok(false) => None, + Err(e) => Some(e), + }; + if let Some(e) = refused { + error_closing(w, e)?; + return Ok(Next::Close); + } + let mut body = http::Body::new(req, r); + let stream = match engine.copy(id, kiri_proto::copy_op::UPPER, "/", kiri_proto::copy_flags::CHUNKED) { + Ok(s) => s, + Err(e) => { + error_closing(w, e)?; + return Ok(Next::Close); + } + }; + let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); + if let Err(e) = send_chunks(&mut body, &mut to_guest) { + // Cut short: dropping the stream ends the guest's copy, which then + // leaves the container as it was. + error_closing(w, Error::BadRequest(format!("the layer could not be read: {e}")))?; + return Ok(Next::Close); + } + let mut from_guest = std::fs::File::from(stream.fd.try_clone()?); + let result = match guest_frame(&mut from_guest) { + Ok(frame) => match kiri_proto::decode(&frame) { + Ok(kiri_proto::Msg::CopyDone) => Ok(()), + Ok(kiri_proto::Msg::Error(m)) if m.contains("in use") || m.contains("already has") => Err(Error::Conflict(m.to_owned())), + Ok(kiri_proto::Msg::Error(m)) => Err(copy_error(m)), + Ok(other) => Err(Error::Io(io::Error::other(format!("unexpected copy reply: {other:?}")))), + Err(e) => Err(Error::Io(io::Error::other(format!("bad copy reply: {e:?}")))), + }, + Err(e) => Err(Error::Io(e)), + }; + match result { + Ok(()) if io::copy(&mut body, &mut io::sink()).is_ok() => { + http::empty(w, 204)?; + Ok(Next::KeepAlive) + } + Ok(()) => { + error_closing(w, Error::BadRequest("the layer could not be read to its end".into()))?; + Ok(Next::Close) + } + Err(e) => { + error_closing(w, e)?; + Ok(Next::Close) + } + } +} + /// A signal by name or number for a stop signal Docker has already /// accepted; one it could not parse is SIGTERM, Docker's default. pub(super) fn signal(name: &str) -> u32 { @@ -3675,6 +4543,62 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + #[test] + fn ps_limit_lists_the_latest_containers_in_any_state() { + let (root, engine) = engine_in("ps-limit", false); + let image = test_image("local:1"); + let spec: super::super::engine::Spec = serde_json::from_value(json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0} + })).unwrap(); + for name in ["first", "second", "third"] { + engine + .create(Some(name.into()), spec.clone(), &image) + .unwrap(); + } + drop(engine); + + // Give the containers distinct creation times within the same second. + let records = root.join("containers.json"); + let mut saved: Vec = + serde_json::from_slice(&std::fs::read(&records).unwrap()).unwrap(); + saved.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); + for (i, record) in saved.iter_mut().enumerate() { + record["created_ns"] = json!(1_000_000_000 + i); + } + std::fs::write(&records, serde_json::to_vec(&saved).unwrap()).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + + let names = |query: &[(&str, &str)]| { + let req = Request::internal("GET", "/containers/json", query, Vec::new()); + let rows = list(&req, &engine).unwrap(); + rows.as_array() + .unwrap() + .iter() + .map(|row| row["Names"][0].as_str().unwrap().to_owned()) + .collect::>() + }; + assert_eq!(names(&[("limit", "1")]), ["/third"]); + assert_eq!(names(&[("limit", "2")]), ["/third", "/second"]); + assert!(names(&[]).is_empty()); + for limit in ["0", "-1"] { + assert!(names(&[("limit", limit)]).is_empty(), "limit={limit}"); + } + let bad = Request::internal("GET", "/containers/json", &[("limit", "abc")], Vec::new()); + assert!(matches!(list(&bad, &engine), Err(Error::BadRequest(_)))); + assert_eq!( + names(&[("all", "1"), ("limit", "2")]), + ["/third", "/second"] + ); + assert_eq!( + names(&[("limit", "1"), ("filters", r#"{"name":["first"]}"#)]), + ["/first"] + ); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + fn engine_in(name: &str, damaged: bool) -> (std::path::PathBuf, std::sync::Arc) { let root = std::env::temp_dir().join(format!("kiri-rm-{name}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&root); @@ -3693,6 +4617,272 @@ mod tests { } } + #[test] + fn restart_policies_are_refused_like_docker() { + let retry_only = + "invalid restart policy: maximum retry count can only be used with 'on-failure'"; + let negative = "invalid restart policy: maximum retry count cannot be negative"; + let with_retries = |name, count| json!({"Name": name, "MaximumRetryCount": count}); + for (policy, expected) in [ + ( + json!({"Name": "bogus"}), + Err("invalid restart policy bogus"), + ), + (with_retries("always", 3), Err(retry_only)), + (with_retries("on-failure", -1), Err(negative)), + (with_retries("always", -1), Err(negative)), + (with_retries("no", 1), Err(retry_only)), + (with_retries("", 2), Err(retry_only)), + (with_retries("", -1), Err(negative)), + (with_retries("unless-stopped", 1), Err(retry_only)), + (json!({"Name": "always"}), Ok(("always", 0))), + (json!({"Name": "unless-stopped"}), Ok(("unless-stopped", 0))), + (json!({"Name": "no"}), Ok(("no", 0))), + (with_retries("on-failure", 0), Ok(("on-failure", 0))), + (with_retries("on-failure", 5), Ok(("on-failure", 5))), + (Value::Null, Ok(("no", 0))), + (json!({"Name": ""}), Ok(("no", 0))), + ] { + let result = restart_policy(&policy, true); + let actual = match &result { + Ok(p) => Ok((p.name.as_str(), p.max_retries)), + Err(Error::BadRequest(message)) => Err(message.as_str()), + other => panic!("{other:?}"), + }; + assert_eq!(actual, expected, "{policy}"); + } + } + + #[test] + fn create_restart_policy_is_validated_before_container_creation() { + let (root, engine) = engine_in("create-restart", false); + let mut image = test_image("restart-create:1"); + image.platform = format!("linux/{}", go_arch()); + engine.store.put_image(image).unwrap(); + let make = |name: &str, auto_remove: bool, policy: Value| { + let body = json!({ + "Image": "restart-create:1", "Cmd": ["true"], + "HostConfig": { + "AutoRemove": auto_remove, + "NetworkMode": "none", + "RestartPolicy": policy, + } + }); + let req = Request::internal( + "POST", + "/containers/create", + &[("name", name)], + serde_json::to_vec(&body).unwrap(), + ); + create(&req, &engine) + }; + for (name, auto_remove, policy, expected_msg) in [ + ( + "bad-name", + false, + json!({"Name": "bogus"}), + "invalid restart policy bogus", + ), + ( + "invalid-restart", + false, + json!({"Name": "always", "MaximumRetryCount": 3}), + "maximum retry count can only be used with 'on-failure'", + ), + ( + "negative-restart", + false, + json!({"Name": "on-failure", "MaximumRetryCount": -1}), + "maximum retry count cannot be negative", + ), + ( + "autoremove-always", + true, + json!({"Name": "always"}), + "can't create 'AutoRemove' container with restart policy", + ), + ( + "autoremove-unless-stopped", + true, + json!({"Name": "unless-stopped"}), + "can't create 'AutoRemove' container with restart policy", + ), + ( + "autoremove-on-failure", + true, + json!({"Name": "on-failure", "MaximumRetryCount": 2}), + "can't create 'AutoRemove' container with restart policy", + ), + ] { + let result = make(name, auto_remove, policy); + match &result { + Err(Error::BadRequest(msg)) => assert!(msg.contains(expected_msg), "{name}: {msg}"), + other => panic!("{name}: {other:?}"), + } + assert!(engine.with(name, |_| ()).is_err(), "{name} should not exist"); + } + for (name, auto_remove, policy, want) in [ + ( + "valid-restart", + false, + json!({"Name": "on-failure", "MaximumRetryCount": 3}), + ("on-failure", 3), + ), + ( + "autoremove-no", + true, + json!({"Name": "no"}), + ("no", 0), + ), + ( + "autoremove-empty", + true, + json!({"Name": ""}), + ("no", 0), + ), + ] { + make(name, auto_remove, policy).unwrap(); + let stored = engine + .with(name, |c| (c.spec.auto_remove, c.spec.restart.clone())) + .unwrap(); + assert_eq!( + (stored.0, stored.1.name.as_str(), stored.1.max_retries), + (auto_remove, want.0, want.1) + ); + } + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn update_restart_policy_is_validated_before_it_is_stored() { + let (root, engine) = engine_in("update-restart", false); + let mut image = test_image("restart-test:1"); + image.platform = format!("linux/{}", go_arch()); + engine.store.put_image(image).unwrap(); + for (name, auto_remove) in [("ordinary", false), ("auto-remove", true)] { + let body = json!({ + "Image": "restart-test:1", "Cmd": ["true"], "HostConfig": {"AutoRemove": auto_remove, "NetworkMode": "none"} + }); + let req = Request::internal( + "POST", + "/containers/create", + &[("name", name)], + serde_json::to_vec(&body).unwrap(), + ); + create(&req, &engine).unwrap(); + assert_eq!( + engine + .with(name, |c| (c.spec.auto_remove, c.spec.restart.name.clone())) + .unwrap(), + (auto_remove, "no".to_owned()) + ); + } + let update = |key: &str, body: Value| { + use std::io::Read; + let req = Request::internal( + "POST", + &format!("/containers/{key}/update"), + &[], + serde_json::to_vec(&body).unwrap(), + ); + let (mut client, mut server) = UnixStream::pair().unwrap(); + super::super::ops::route(&req, &engine, &Caller::Host, &mut server) + .unwrap() + .unwrap(); + drop(server); + let mut result = String::new(); + client.read_to_string(&mut result).unwrap(); + result + }; + let stored = |key| engine.with(key, |c| (c.spec.restart.clone(), c.spec.limits.memory_max)).unwrap(); + let auto_remove = + "Restart policy cannot be updated because AutoRemove is enabled for the container"; + let unknown = "invalid restart policy: unknown policy 'bogus'; use one of 'no', 'always', 'on-failure', or 'unless-stopped'"; + let retry_only = "maximum retry count can only be used with 'on-failure'"; + let negative = "maximum retry count cannot be negative"; + // Give `ordinary` an active policy first so refused updates verify that + // neither an existing active policy nor container limits are overwritten. + let response = update("ordinary", json!({"RestartPolicy": {"Name": "always"}})); + assert!(response.starts_with("HTTP/1.1 200 "), "{response}"); + assert_eq!( + stored("ordinary"), + (RestartPolicy { name: "always".into(), max_retries: 0 }, 0) + ); + for (key, policy, status, message) in [ + ("auto-remove", json!({"Name": "always"}), 409, auto_remove), + ("auto-remove", json!({"Name": "unless-stopped"}), 409, auto_remove), + ("auto-remove", json!({"Name": "on-failure", "MaximumRetryCount": 2}), 409, auto_remove), + ("ordinary", json!({"Name": "bogus"}), 400, unknown), + ( + "ordinary", + json!({"Name": "always", "MaximumRetryCount": 3}), + 400, + retry_only, + ), + ( + "ordinary", + json!({"Name": "no", "MaximumRetryCount": 1}), + 400, + retry_only, + ), + ( + "ordinary", + json!({"Name": "", "MaximumRetryCount": 2}), + 400, + retry_only, + ), + ( + "ordinary", + json!({"Name": "", "MaximumRetryCount": -1}), + 400, + negative, + ), + ( + "ordinary", + json!({"Name": "on-failure", "MaximumRetryCount": -1}), + 400, + negative, + ), + ] { + let before = stored(key); + let response = update(key, json!({"Memory": 134_217_728, "RestartPolicy": policy})); + assert!( + response.starts_with(&format!("HTTP/1.1 {status} ")) && response.contains(message), + "{policy}: {response}" + ); + assert_eq!(stored(key), before, "{policy}"); + } + let response = update("auto-remove", json!({"RestartPolicy": {"Name": "no"}})); + assert!(response.starts_with("HTTP/1.1 200 "), "{response}"); + assert_eq!(stored("auto-remove").0.name, "no"); + let response = update( + "ordinary", + json!({"RestartPolicy": {"Name": "on-failure", "MaximumRetryCount": 3}}), + ); + assert!(response.starts_with("HTTP/1.1 200 "), "{response}"); + let expected = RestartPolicy { + name: "on-failure".into(), + max_retries: 3, + }; + assert_eq!(stored("ordinary"), (expected.clone(), 0)); + // Partial updates (e.g. `docker update --memory 256m`) omit RestartPolicy + // or send `{"Name": "", "MaximumRetryCount": 0}` and must keep the + // container's existing restart policy intact. + for (body, want_mem) in [ + (json!({}), 0), + (json!({"RestartPolicy": {"Name": ""}}), 0), + (json!({"Memory": 268_435_456, "RestartPolicy": {"Name": "", "MaximumRetryCount": 0}}), 268_435_456), + (json!({"Memory": 536_870_912}), 536_870_912), + ] { + let response = update("ordinary", body); + assert!(response.starts_with("HTTP/1.1 200 "), "{response}"); + assert_eq!(stored("ordinary"), (expected.clone(), want_mem)); + } + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// A container using `volume` and `image`, in the list. fn listed_user(engine: &Engine, volume: &str, image: &kiri_image::Image) { let spec: super::super::engine::Spec = serde_json::from_value(json!({ @@ -3714,6 +4904,9 @@ mod tests { engine.volume_ensure_with("free", json!({}), Default::default()).unwrap(); listed_user(&engine, "used", &image); assert!(matches!(engine.volume_remove("used", false), Err(Error::Conflict(m)) if m.contains("volume is in use"))); + // Force doesn't remove a volume in use either, as in Docker (#773). + assert!(matches!(engine.volume_remove("used", true), Err(Error::Conflict(m)) if m.contains("volume is in use"))); + assert!(engine.volume_get("used").is_some(), "the volume in use is kept"); engine.volume_remove("free", false).unwrap(); assert!(engine.volume_get("free").is_none()); assert!(matches!(image_remove(&engine, "used:1", false), Err(Error::Conflict(m)) if m.contains("is using its referenced image"))); @@ -3753,6 +4946,100 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + fn delete_volume_http(engine: &Arc, target: &str) -> (u16, String) { + use std::io::{Read, Write}; + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.write_all(format!("DELETE /volumes/{target} HTTP/1.1\r\nHost: d\r\nConnection: close\r\n\r\n").as_bytes()).unwrap(); + let mut raw = String::new(); + client.read_to_string(&mut raw).unwrap(); + served.join().unwrap().unwrap(); + let (head, body) = raw.split_once("\r\n\r\n").unwrap_or((&raw, "")); + let code = head.lines().next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap_or(0); + (code, body.to_owned()) + } + + fn create_mounted(engine: &Engine, name: &str, image: &kiri_image::Image, body: Value) -> String { + let m = mounts(&body, engine, image).unwrap(); + let volumes_from = strings(&body["HostConfig"]["VolumesFrom"]).unwrap_or_default(); + let spec: super::super::engine::Spec = serde_json::from_value(json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0}, "volumes": m.volumes, "anon_volumes": m.anon, + "mounts": m.guest, "mount_info": m.info, "volumes_from": volumes_from, + })).unwrap(); + engine.create(Some(name.into()), spec, image).unwrap() + } + + /// `DELETE /volumes/{name}` matches Docker's exact status codes and errors: + /// 404/204 for missing volumes (without/with `force`), and 409 Conflict for + /// volumes in use via `-v`, `--mount type=volume`, or `--volumes-from` + /// across created/running/stopped containers regardless of `force` (#773). + #[test] + fn delete_volume_http_status_and_in_use_match_docker() { + let (root, engine) = engine_in("vol-http", false); + let image = test_image("vol:1"); + engine.store.put_image(image.clone()).unwrap(); + + // Missing volume: 404 without force (or force=0/false), 204 with force=1/true. + for path in ["missing", "missing?force=0", "missing?force=false"] { + let (code, body) = delete_volume_http(&engine, path); + assert_eq!(code, 404, "{path}: {body}"); + assert!(body.contains("get missing: no such volume"), "{path}: {body}"); + } + for path in ["missing?force=1", "missing?force=true"] { + let (code, body) = delete_volume_http(&engine, path); + assert_eq!(code, 204, "{path}: {body}"); + assert!(body.is_empty(), "{path}: {body}"); + } + + // `-v` bind-style named volume on created and exited container. + let c_bind = create_mounted(&engine, "c-bind", &image, json!({"HostConfig": {"Binds": ["v-bind:/d"]}})); + for target in ["v-bind", "v-bind?force=1", "v-bind?force=true"] { + let (code, body) = delete_volume_http(&engine, target); + assert_eq!(code, 409, "{target}: {body}"); + assert!(body.contains("remove v-bind: volume is in use - [c-bind]"), "{target}: {body}"); + assert!(engine.volume_get("v-bind").is_some()); + } + engine.set_status(&c_bind, super::super::engine::Status::Exited); + assert_eq!(delete_volume_http(&engine, "v-bind?force=1").0, 409); + + // `--mount type=volume` on running container. + let c_mount = create_mounted( + &engine, + "c-mount", + &image, + json!({"HostConfig": {"Mounts": [{"Type": "volume", "Source": "v-mount", "Target": "/d"}]}}), + ); + engine.set_status(&c_mount, super::super::engine::Status::Running); + let (code, body) = delete_volume_http(&engine, "v-mount?force=1"); + assert_eq!(code, 409, "{body}"); + assert!(body.contains("remove v-mount: volume is in use - [c-mount]"), "{body}"); + + // `--volumes-from` retains the volume even after the source container is removed. + let c_vfrom = create_mounted(&engine, "c-vfrom", &image, json!({"HostConfig": {"VolumesFrom": ["c-bind"]}})); + engine.remove(&c_bind, false, false).unwrap(); + let (code, body) = delete_volume_http(&engine, "v-bind?force=1"); + assert_eq!(code, 409, "{body}"); + assert!(body.contains("remove v-bind: volume is in use - [c-vfrom]"), "{body}"); + assert!(engine.volume_get("v-bind").is_some()); + + // Removing holders frees the volumes for removal. + engine.remove(&c_vfrom, false, false).unwrap(); + engine.set_status(&c_mount, super::super::engine::Status::Exited); + engine.remove(&c_mount, false, false).unwrap(); + assert_eq!(delete_volume_http(&engine, "v-bind?force=1").0, 204); + assert_eq!(delete_volume_http(&engine, "v-mount").0, 204); + assert!(engine.volume_get("v-bind").is_none()); + assert!(engine.volume_get("v-mount").is_none()); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// `--volumes-from` entries: the container and its mode, as Docker parses them. #[test] fn volumes_from_takes_a_container_and_a_mode() { @@ -3843,6 +5130,165 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// Both `-v /run/host-services/ssh-auth.sock:...` and `--mount type=bind,source=/run/host-services/ssh-auth.sock,...` + /// resolve to `ssh_agent_source()` for the guest while keeping `/run/host-services/ssh-auth.sock` + /// in inspect, without needing `/run/host-services` to exist on the host (#420). + #[test] + fn ssh_agent_mounts_resolve_without_touching_host_run_host_services() { + let (root, engine) = engine_in("ssh-agent-mounts", false); + let image = test_image("ssh:1"); + let body = json!({ + "HostConfig": { + "Binds": ["/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock"], + "Mounts": [{"Type": "bind", "Source": "/run/host-services/ssh-auth.sock", "Target": "/agent.sock", "ReadOnly": true}], + } + }); + let m = mounts(&body, &engine, &image).unwrap(); + let src = ssh_agent_source(); + assert_eq!(m.guest, [format!("{src}\t/run/host-services/ssh-auth.sock\t"), format!("{src}\t/agent.sock\tro")]); + assert_eq!(m.info[0]["Source"], "/run/host-services/ssh-auth.sock"); + assert_eq!(m.info[0]["RW"], true); + assert_eq!(m.info[1]["Source"], "/run/host-services/ssh-auth.sock"); + assert_eq!(m.info[1]["Destination"], "/agent.sock"); + assert_eq!(m.info[1]["RW"], false); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + + /// On macOS, direct bind mounts of host SSH agent sockets (GnuPG's + /// `S.gpg-agent.ssh`, 1Password's `agent.sock`, launchd's `Listeners`) map + /// the guest source to `/run/host-services/ssh-auth.sock` while keeping + /// inspect's `Source` intact — and never treat Kiri's `docker.sock` or + /// symlinks to it as an SSH agent socket (#763). + #[test] + fn mac_host_ssh_agent_bind_mounts_translate_and_never_match_kiri_socket() { + use std::os::unix::net::UnixListener; + + // Well-known Mac SSH agent socket paths match only when mac == true. + for path in [ + "/Users/alice/.gnupg/S.gpg-agent.ssh", + "/Users/alice/.1password/agent.sock", + "/Users/alice/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock", + "/private/tmp/com.apple.launchd.abc123/Listeners", + "/var/run/com.apple.launchd.abc123/Listeners", + ] { + assert!(super::ssh_agent_bind_for(path, true).is_some(), "mac should recognize {path}"); + assert!(super::ssh_agent_bind_for(path, false).is_none(), "linux must leave {path} alone"); + } + + // Security: Kiri's socket (synthetic or real) is never recognized as an SSH agent socket. + assert!(super::ssh_agent_bind_for("/Users/alice/.kiri/run/docker.sock", true).is_none()); + assert!(super::ssh_agent_bind_for("/var/run/docker.sock", true).is_none()); + if let Ok(own) = super::super::socket_path() { + assert!(super::ssh_agent_bind_for(&own.to_string_lossy(), true).is_none()); + } + + // Real filesystem checks: live socket vs regular file vs symlink to docker.sock. + let dir = std::env::temp_dir().join(format!("kiri-api-ssh-bind-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("real")).unwrap(); + std::fs::create_dir_all(dir.join("fake")).unwrap(); + std::fs::create_dir_all(dir.join("link")).unwrap(); + + let live_gpg = dir.join("real/S.gpg-agent.ssh"); + let _gpg_listener = UnixListener::bind(&live_gpg).unwrap(); + let live_gpg_str = live_gpg.to_str().unwrap(); + assert_eq!( + super::ssh_agent_bind_for(live_gpg_str, true), + Some(super::SshAgentBind::MacHost(Some(std::fs::canonicalize(&live_gpg).unwrap()))) + ); + assert_eq!(super::ssh_agent_bind_for(live_gpg_str, false), None); + + // Regular file with the same name is not intercepted. + let regular_file = dir.join("fake/S.gpg-agent.ssh"); + std::fs::write(®ular_file, b"plain file").unwrap(); + assert_eq!(super::ssh_agent_bind_for(regular_file.to_str().unwrap(), true), None); + + // Symlink named S.gpg-agent.ssh pointing to docker.sock is rejected after canonicalize. + let docker_sock = dir.join("docker.sock"); + let _docker_listener = UnixListener::bind(&docker_sock).unwrap(); + let evil_link = dir.join("link/S.gpg-agent.ssh"); + std::os::unix::fs::symlink(&docker_sock, &evil_link).unwrap(); + assert_eq!(super::ssh_agent_bind_for(evil_link.to_str().unwrap(), true), None); + + // fresh_bind_sources_with on macOS preserves /run/host-services/ssh-auth.sock on + // restart and upgrades legacy /mnt/mac/.../S.gpg-agent.ssh mounts while keeping + // engine socket binds untouched. + let gpg_info = vec![ + json!({"Type": "bind", "Source": "/Users/alice/.gnupg/S.gpg-agent.ssh"}), + json!({"Type": "bind", "Source": "/Users/alice/.kiri/run/docker.sock"}), + ]; + let restarted = vec![ + "/run/host-services/ssh-auth.sock\t/ssh-agent\t".to_owned(), + "/run/host-services/docker.sock\t/var/run/docker.sock\t".to_owned(), + ]; + let legacy = vec![ + "/mnt/mac/Users/alice/.gnupg/S.gpg-agent.ssh\t/ssh-agent\tro".to_owned(), + "/run/host-services/docker.sock\t/var/run/docker.sock\t".to_owned(), + ]; + let sock = |s: &str| (s == "/Users/alice/.kiri/run/docker.sock").then(|| "/run/host-services/docker.sock".to_owned()); + assert_eq!(super::fresh_bind_sources_with(&restarted, &gpg_info, sock, true), restarted); + assert_eq!( + super::fresh_bind_sources_with(&legacy, &gpg_info, sock, true), + [ + "/run/host-services/ssh-auth.sock\t/ssh-agent\tro", + "/run/host-services/docker.sock\t/var/run/docker.sock\t", + ] + ); + + #[cfg(target_os = "macos")] + { + let _guard = super::super::ports::PREFERRED_SSH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + super::super::ports::clear_preferred_ssh_auth_sock(); + + let (root, engine) = engine_in("mac-gpg-ssh-mounts", false); + let image = test_image("ssh:1"); + let own_sock = super::super::socket_path().unwrap().to_string_lossy().into_owned(); + let body = json!({ + "HostConfig": { + "Binds": [ + "/Users/alice/.gnupg/S.gpg-agent.ssh:/ssh-agent", + format!("{live_gpg_str}:/live-gpg.sock:ro"), + format!("{own_sock}:/not-ssh"), + ], + "Mounts": [ + {"Type": "bind", "Source": "/Users/alice/.1password/agent.sock", "Target": "/op.sock", "ReadOnly": true}, + ], + } + }); + // Container caller must never mutate the daemon's preferred SSH agent socket. + let m_container = super::mounts_for(&body, &engine, &image, &super::super::caller::Caller::Container).unwrap(); + assert!(super::super::ports::current_preferred_ssh_auth_sock().is_none(), "Caller::Container must not set preferred SSH socket"); + assert_eq!( + m_container.guest, + [ + "/run/host-services/ssh-auth.sock\t/ssh-agent\t", + "/run/host-services/ssh-auth.sock\t/live-gpg.sock\tro", + "/run/host-services/docker.sock\t/not-ssh\t", + "/run/host-services/ssh-auth.sock\t/op.sock\tro", + ] + ); + assert_eq!(m_container.info[0]["Source"], "/Users/alice/.gnupg/S.gpg-agent.ssh"); + assert_eq!(m_container.info[1]["Source"], live_gpg_str); + assert_eq!(m_container.info[2]["Source"], own_sock); + assert_eq!(m_container.info[3]["Source"], "/Users/alice/.1password/agent.sock"); + + // Host caller records the live GPG socket as preferred while keeping inspect intact. + let m_host = super::mounts_for(&body, &engine, &image, &super::super::caller::Caller::Host).unwrap(); + assert_eq!(m_host.guest, m_container.guest); + assert_eq!( + super::super::ports::current_preferred_ssh_auth_sock(), + Some(std::fs::canonicalize(&live_gpg).unwrap()) + ); + + super::super::ports::clear_preferred_ssh_auth_sock(); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + + let _ = std::fs::remove_dir_all(&dir); + } + /// `--pid`: empty and `host` as given, `container:` kept with the /// full id; anything else, or an unknown container, refused. #[test] @@ -3999,6 +5445,120 @@ mod tests { assert!(asked.borrow().iter().all(|k| !k.starts_with("container:")), "a container: key was looked up as a network"); } + /// `POST /containers/create` network selection across `HostConfig.NetworkMode` + /// and `NetworkingConfig.EndpointsConfig` (#407, #727). + #[test] + fn create_network_mode_with_endpoints_config() { + let (root, engine) = engine_in("create-net-endpoints", false); + let image = test_image("net-ep:1"); + engine.store.put_image(image.clone()).unwrap(); + let k3d = engine.lock_net().create("k3d-net", Default::default()).unwrap(); + engine.lock_net().create("custom-a", Default::default()).unwrap(); + engine.lock_net().create("custom-b", Default::default()).unwrap(); + engine.lock_net().create("back-net", super::super::network::Settings { internal: true, ..Default::default() }).unwrap(); + + let make = |name: &str, body: Value| -> Result<(String, Value), Error> { + let req = Request::internal("POST", "/containers/create", &[("name", name)], serde_json::to_vec(&body).unwrap()); + let created = create(&req, &engine)?; + let id = created["Id"].as_str().unwrap().to_owned(); + let inspected = container_inspect(&engine, &id)?; + Ok((id, inspected)) + }; + let net_names = |inspected: &Value| -> Vec { + let mut names: Vec = inspected["NetworkSettings"]["Networks"].as_object().unwrap().keys().cloned().collect(); + names.sort(); + names + }; + + // 1. NetworkMode "bridge" + non-empty EndpointsConfig without bridge -> joins ONLY k3d-net. + let (id1, ins1) = make("bridge-k3d", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "bridge"}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {"Aliases": ["node-0"]}}}, + })).unwrap(); + assert_eq!(net_names(&ins1), ["k3d-net"]); + assert_eq!(ins1["NetworkSettings"]["Networks"]["k3d-net"]["Aliases"], json!(["node-0"])); + engine.with(&id1, |c| { + assert_eq!(c.spec.network_mode, "k3d-net"); + assert!(c.spec.extra_networks.is_empty()); + }).unwrap(); + + // Same when EndpointsConfig names the network by ID, and with internal + outside networks. + let (_, ins1_id) = make("bridge-k3d-id", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "bridge"}, + "NetworkingConfig": {"EndpointsConfig": {k3d.id.as_str(): {}, "back-net": {}}}, + })).unwrap(); + assert_eq!(net_names(&ins1_id), ["back-net", "k3d-net"]); + assert_eq!(ins1_id["HostConfig"]["NetworkMode"], "k3d-net", "outside network beats internal"); + + // 2. NetworkMode "bridge" + EndpointsConfig including both bridge and k3d-net -> joins BOTH. + let (id2, ins2) = make("bridge-and-k3d", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "bridge"}, + "NetworkingConfig": {"EndpointsConfig": {"bridge": {}, "k3d-net": {"Aliases": ["both"]}}}, + })).unwrap(); + assert_eq!(net_names(&ins2), ["bridge", "k3d-net"]); + assert_eq!(ins2["NetworkSettings"]["Networks"]["k3d-net"]["Aliases"], json!(["both"])); + engine.with(&id2, |c| { + assert_eq!(c.spec.network_mode, "bridge"); + assert_eq!(c.spec.extra_networks.len(), 1); + assert_eq!(c.spec.extra_networks[0].name, "k3d-net"); + }).unwrap(); + + // 3. NetworkMode "bridge" + empty or absent EndpointsConfig -> joins bridge as usual. + for (name, body) in [ + ("bridge-empty-eps", json!({"Image": "net-ep:1", "Cmd": ["true"], "HostConfig": {"NetworkMode": "bridge"}, "NetworkingConfig": {"EndpointsConfig": {}}})), + ("bridge-no-eps", json!({"Image": "net-ep:1", "Cmd": ["true"], "HostConfig": {"NetworkMode": "bridge"}})), + ] { + let (id, ins) = make(name, body).unwrap(); + assert_eq!(net_names(&ins), ["bridge"], "{name}"); + engine.with(&id, |c| { + assert_eq!(c.spec.network_mode, "bridge", "{name}"); + assert!(c.spec.extra_networks.is_empty(), "{name}"); + }).unwrap(); + } + + // 4. Named user network in NetworkMode + another in EndpointsConfig -> keeps NetworkMode primary + extra. + let (id4, ins4) = make("custom-a-and-b", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "custom-a"}, + "NetworkingConfig": {"EndpointsConfig": {"custom-b": {"Aliases": ["b-alias"]}}}, + })).unwrap(); + assert_eq!(net_names(&ins4), ["custom-a", "custom-b"]); + assert_eq!(ins4["NetworkSettings"]["Networks"]["custom-b"]["Aliases"], json!(["b-alias"])); + engine.with(&id4, |c| { + assert_eq!(c.spec.network_mode, "custom-a"); + assert_eq!(c.spec.extra_networks.len(), 1); + assert_eq!(c.spec.extra_networks[0].name, "custom-b"); + }).unwrap(); + + // 5. Special NetworkModes ("host", "none", "container:") with EndpointsConfig stay unaffected / rejected. + let (id_host, _) = make("host-with-ep", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "host"}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {}}}, + })).unwrap(); + engine.with(&id_host, |c| assert_eq!(c.spec.network_mode, "host")).unwrap(); + + let (id_none, _) = make("none-with-ep", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": "none"}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {}}}, + })).unwrap(); + engine.with(&id_none, |c| assert_eq!(c.spec.network_mode, "none")).unwrap(); + + let err_ctr = make("ctr-with-ep", json!({ + "Image": "net-ep:1", "Cmd": ["true"], + "HostConfig": {"NetworkMode": format!("container:{id1}")}, + "NetworkingConfig": {"EndpointsConfig": {"k3d-net": {}}}, + })); + assert!(matches!(err_ctr, Err(Error::BadRequest(ref m)) if m.contains("sharing network namespace")), "{err_ctr:?}"); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + #[test] fn archive_uploads_are_sniffed() { assert_eq!(upload_compression(&[0x1f, 0x8b, 8, 0, 0, 0]), Upload::Gzip); @@ -4102,6 +5662,27 @@ mod tests { // A close asked for on the second request ends it after that one. let (got, ended) = exchange("GET /_ping HTTP/1.1\r\nHost: d\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\nConnection: close\r\n\r\n"); assert!(ended && got.matches("HTTP/1.1 200 ").count() == 2 && got.matches("Connection: close\r\n").count() == 1, "{got}"); + // Absolute-form targets route as origin-form (#757), while malformed + // targets or request lines answer 400 Bad Request and close cleanly. + let (got, ended) = exchange("GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\nConnection: close\r\n\r\n"); + assert!(ended && got.starts_with("HTTP/1.1 200 OK\r\n") && got.ends_with("OK"), "{got}"); + for bad in [ + "GET http:///containers/json HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n", + "GET ftp://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n", + "GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n", + "GET\t/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + ] { + let (got, ended) = exchange(bad); + assert!( + ended && got.starts_with("HTTP/1.1 400 Bad Request\r\n") && got.contains("Connection: close\r\n") && got.contains("\"message\":\"bad request "), + "{bad:?}: {got}" + ); + } + let (got, ended) = exchange("GET /_ping HTTP/1.1\r\nHost: d\r\n\r\nGET http:///bad HTTP/1.1\r\nHost: d\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"); + assert!( + ended && got.matches("HTTP/1.1 200 OK\r\n").count() == 1 && got.matches("HTTP/1.1 400 Bad Request\r\n").count() == 1 && got.matches("Connection: close\r\n").count() == 1, + "{got}" + ); drop(engine); let _ = std::fs::remove_dir_all(root); } @@ -4164,7 +5745,7 @@ mod tests { }; let mut routes = kiri_routes(body_of(include_str!("api.rs"), "\nfn route(")); routes.extend(kiri_routes(body_of(include_str!("ops.rs"), "\npub fn route("))); - for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("DELETE", "/kiri/k8s/forward/1")] { + for known in [("POST", "/kiri/stop"), ("POST", "/kiri/sleep"), ("POST", "/kiri/registries"), ("PUT", "/kiri/proxy/system"), ("PUT", "/kiri/roots/host"), ("POST", "/kiri/builder"), ("POST", "/kiri/containers/1/ports"), ("POST", "/kiri/containers/1/upper"), ("DELETE", "/kiri/k8s/forward/1"), ("GET", "/kiri/watch-roots"), ("POST", "/kiri/fs-events")] { assert!(routes.iter().any(|(m, p)| (m.as_str(), p.as_str()) == known), "{known:?} not found in route(): {routes:?}"); } for (m, p) in &routes { @@ -4183,18 +5764,65 @@ mod tests { } } - /// Through the API itself: a container's Stop and settings are refused, - /// and the engine stays as it was. #[test] - fn a_containers_stop_and_settings_are_refused() { + fn fs_events_parsing_validates_paths_and_rejects_traversal() { + let json_body = br#"{"events":["M\t/mnt/c/Users/me/app.js","D\t/etc/passwd","C\t/mnt/c/../etc/shadow","X\t/mnt/c/a","C\t/mnt/d/new.ts"]}"#; + assert_eq!(parse_fs_events(json_body, "/mnt/").unwrap(), vec!["M\t/mnt/c/Users/me/app.js", "C\t/mnt/d/new.ts"]); + let text_body = b"M\t/mnt/c/test/app.js\nD\t/mnt/mac/Users/a\nP\t/mnt/c/test\nU\t/etc\n"; + assert_eq!(parse_fs_events(text_body, "/mnt/").unwrap(), vec!["M\t/mnt/c/test/app.js", "P\t/mnt/c/test"]); + assert!(parse_fs_events(b"{not json", "/mnt/").is_err()); + let too_many = vec!["M\t/mnt/c/a"; 4097].join("\n"); + assert!(parse_fs_events(too_many.as_bytes(), "/mnt/").is_err()); + } + + #[test] + fn watch_roots_and_fs_events_endpoints_work_without_waking_vm() { use std::io::{Read, Write}; - let (root, engine) = engine_in("container-gate", false); - for req in ["POST /v1.47/kiri/stop", "POST /kiri/sleep", "POST /kiri/registries", "POST /kiri/proxy", "POST /kiri/resources", "POST /kiri/domains", "DELETE /kiri/domains"] { - let (mut client, server) = UnixStream::pair().unwrap(); - let served = std::thread::spawn({ - let engine = engine.clone(); - move || serve(server, engine, Caller::Container) - }); + let (root, engine) = engine_in("watch-roots", false); + // GET /kiri/watch-roots + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.write_all(b"GET /kiri/watch-roots HTTP/1.1\r\nHost: d\r\nX-Kiri-Background: 1\r\nConnection: close\r\n\r\n").unwrap(); + let mut got = String::new(); + client.read_to_string(&mut got).unwrap(); + served.join().unwrap().unwrap(); + assert!(got.starts_with("HTTP/1.1 200 "), "{got}"); + assert!(got.contains("\"automount_root\":\"/mnt/\""), "{got}"); + assert!(got.contains("\"roots\":[]"), "{got}"); + + // POST /kiri/fs-events from Host returns 204 and does not wake VM + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + let body = r#"{"events":["M\t/mnt/c/test/app.js"]}"#; + client.write_all(format!("POST /kiri/fs-events HTTP/1.1\r\nHost: d\r\nX-Kiri-Background: 1\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}", body.len()).as_bytes()).unwrap(); + let mut got = String::new(); + client.read_to_string(&mut got).unwrap(); + served.join().unwrap().unwrap(); + assert!(got.starts_with("HTTP/1.1 204 "), "{got}"); + assert!(!engine.is_awake()); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + + /// Through the API itself: a container's Stop and settings are refused, + /// and the engine stays as it was. + #[test] + fn a_containers_stop_and_settings_are_refused() { + use std::io::{Read, Write}; + let (root, engine) = engine_in("container-gate", false); + for req in ["POST /v1.47/kiri/stop", "POST /kiri/sleep", "POST /kiri/registries", "POST /kiri/proxy", "PUT /kiri/roots/host", "POST /kiri/resources", "POST /kiri/domains", "DELETE /kiri/domains", "POST /kiri/fs-events"] { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Container) + }); client.write_all(format!("{req} HTTP/1.1\r\nHost: d\r\nConnection: close\r\nContent-Length: 2\r\n\r\n{{}}").as_bytes()).unwrap(); let mut got = String::new(); client.read_to_string(&mut got).unwrap(); @@ -4230,6 +5858,40 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// `PUT /kiri/roots/host` accepts only `Caller::Host` (kiri-win): neither a + /// container nor an integrated WSL distro may inject root CAs (#303). + #[test] + fn host_roots_endpoint_requires_host_caller() { + let req = Request::internal("PUT", "/kiri/roots/host", &[], br#"{"certs":["3001"],"distrusted":[]}"#.to_vec()); + assert!(matches!(set_host_roots(&req, &Caller::Container), Err(Error::Forbidden(_)))); + assert!(matches!(set_host_roots(&req, &Caller::Wsl("Ubuntu".into())), Err(Error::Forbidden(_)))); + if !crate::daemon::hostroots::in_wsl() { + assert!(matches!(set_host_roots(&req, &Caller::Host), Err(Error::BadRequest(_)))); + } + + // Over the live HTTP handler: a WSL distro receives 403 on Linux. + #[cfg(target_os = "linux")] + { + use std::io::{Read, Write}; + let (root, engine) = engine_in("wsl-host-roots-gate", false); + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Wsl("Ubuntu".into())) + }); + let body = r#"{"certs":["3001"],"distrusted":[]}"#; + client + .write_all(format!("PUT /kiri/roots/host HTTP/1.1\r\nHost: d\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}", body.len()).as_bytes()) + .unwrap(); + let mut got = String::new(); + client.read_to_string(&mut got).unwrap(); + served.join().unwrap().unwrap(); + assert!(got.starts_with("HTTP/1.1 403 "), "{got}"); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + } + /// `POST /kiri/registries` refreshes synchronously on the request thread /// only when the save changed settings, never from a detached thread after /// answering. @@ -4387,6 +6049,141 @@ mod tests { let _ = std::fs::remove_dir_all(root); } + /// End-to-end check through `serve`: TE+CL smuggling returns 400 and closes + /// without running a smuggled request; chunked trailers leave keep-alive + /// intact; `Expect: 100-continue` gets `100 Continue` before body upload. + #[test] + fn serve_handles_chunked_trailers_expect_continue_and_rejects_smuggling() { + use std::io::{Read, Write}; + let (root, engine) = engine_in("http-framing", false); + + // 1. Conflicting framing, malformed header lines (obs-fold, space before ':'), + // and bare-LF chunk size lines -> 400 Bad Request, Connection: close, no second reply. + for smuggle in [ + &b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + &b"POST /auth HTTP/1.1\r\nHost: d\r\n Transfer-Encoding: chunked\r\n\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + &b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding : chunked\r\n\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + &b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\n{}\r\n0\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"[..], + ] { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client.write_all(smuggle).unwrap(); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let got = String::from_utf8_lossy(&got); + assert!(got.starts_with("HTTP/1.1 400 Bad Request\r\n"), "{got}"); + assert!(got.contains("Connection: close\r\n"), "{got}"); + assert_eq!(got.matches("HTTP/1.1 ").count(), 1, "{got}"); + } + + // 2. Chunked request with trailers followed by GET /_ping on the same connection. + { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client + .write_all( + b"POST /auth HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\nX-Checksum: 1\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\nConnection: close\r\n\r\n", + ) + .unwrap(); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let got = String::from_utf8_lossy(&got); + assert!(got.contains("HTTP/1.1 200 OK\r\n") && got.ends_with("OK"), "{got}"); + assert_eq!(got.matches("HTTP/1.1 ").count(), 2, "{got}"); + } + + // 3. Buffered Expect: 100-continue sends 100 Continue before reading body, then answers normally. + { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client + .write_all(b"POST /auth HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 2\r\nConnection: close\r\n\r\n") + .unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + client.write_all(b"{}").unwrap(); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let rest = String::from_utf8_lossy(&rest); + assert!(rest.starts_with("HTTP/1.1 400 ") || rest.starts_with("HTTP/1.1 200 "), "{rest}"); + } + + // 4. Streamed 404 (PUT /archive on missing container) and early 400 (bad import repo) + // with Expect: 100-continue must NOT emit 100 Continue and must close cleanly. + for (req_head, want_status) in [ + ("PUT /containers/no-such-container/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 1073741824\r\n\r\n", "HTTP/1.1 404 Not Found\r\n"), + ("POST /images/create?fromSrc=-&repo=INVALID_UPPERCASE HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 1073741824\r\n\r\n", "HTTP/1.1 400 Bad Request\r\n"), + ] { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client.write_all(req_head.as_bytes()).unwrap(); + let mut got = Vec::new(); + client.read_to_end(&mut got).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let got = String::from_utf8_lossy(&got); + assert!(got.starts_with(want_status), "expected {want_status:?} for {req_head:?}, got: {got}"); + assert!(got.contains("Connection: close\r\n"), "{got}"); + assert!(!got.contains("100 Continue"), "{got}"); + assert_eq!(got.matches("HTTP/1.1 ").count(), 1, "{got}"); + } + + // 5. Valid streamed upload (POST /images/create?fromSrc=-) with Expect: 100-continue + // DOES emit 100 Continue before reading the body, then completes with 200 OK. + { + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client + .write_all(b"POST /images/create?fromSrc=- HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nTransfer-Encoding: chunked\r\n\r\n") + .unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + // Two 512-byte zero blocks form a valid empty tar archive. + let empty_tar = [0u8; 1024]; + write!(client, "{:x}\r\n", empty_tar.len()).unwrap(); + client.write_all(&empty_tar).unwrap(); + client.write_all(b"\r\n0\r\nX-Digest: ok\r\n\r\n").unwrap(); + let mut rest = Vec::new(); + client.read_to_end(&mut rest).unwrap(); + drop(client); + served.join().unwrap().unwrap(); + let rest = String::from_utf8_lossy(&rest); + assert!(rest.starts_with("HTTP/1.1 200 OK\r\n"), "{rest}"); + assert!(rest.contains("sha256:"), "{rest}"); + } + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// `docker save | gzip | docker load` loads, as on Docker (issue 528): /// the body goes through the same detection as `docker cp` uploads. /// Each archive is sent to `POST /images/load` as the CLI sends it. @@ -4444,6 +6241,112 @@ mod tests { assert_eq!(found, None); } + /// `POST /images/load` accepts OCI image-layout archives (plain, gzipped, + /// untagged, and with `?platform=...` as plain string or Docker API v1.48 JSON). + #[test] + fn image_load_takes_oci_archives_and_platform_queries() { + use std::io::{Read, Write}; + let (src, src_engine) = engine_in("load-oci-src", false); + let put = |bytes: &[u8]| { + let mut w = src_engine.store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let make_manifest = |arch: &str| { + let cfg_bytes = serde_json::to_vec(&json!({"os": "linux", "architecture": arch, "created": "2026-01-01T00:00:00Z", "config": {"Cmd": [arch]}})).unwrap(); + let (cfg, cfg_sz) = put(&cfg_bytes); + let (layer, layer_sz) = put(format!("layer-{arch}").as_bytes()); + let man_bytes = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": cfg, "size": cfg_sz}, + "layers": [{"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": layer, "size": layer_sz}], + })) + .unwrap(); + let (man, man_sz) = put(&man_bytes); + (cfg, cfg_bytes, layer, format!("layer-{arch}").into_bytes(), man, man_bytes, man_sz) + }; + let amd = make_manifest("amd64"); + let arm = make_manifest("arm64"); + let nested_bytes = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "manifests": [ + {"mediaType": "application/vnd.oci.image.manifest.v1+json", "digest": amd.4, "size": amd.6, "platform": {"os": "linux", "architecture": "amd64"}}, + {"mediaType": "application/vnd.oci.image.manifest.v1+json", "digest": arm.4, "size": arm.6, "platform": {"os": "linux", "architecture": "arm64"}}, + ] + })) + .unwrap(); + let (nested, nested_sz) = put(&nested_bytes); + drop(src_engine); + let _ = std::fs::remove_dir_all(src); + + let build_oci = |tag: Option<&str>| { + let mut b = tar::Builder::new(Vec::new()); + let mut add = |name: &str, data: &[u8]| { + let mut h = tar::Header::new_ustar(); + h.set_size(data.len() as u64); + h.set_mode(0o644); + h.set_entry_type(tar::EntryType::Regular); + b.append_data(&mut h, name, data).unwrap(); + }; + for (cfg, cfg_b, layer, layer_b, man, man_b, _) in [&amd, &arm] { + add(&format!("blobs/sha256/{}", cfg.strip_prefix("sha256:").unwrap()), cfg_b); + add(&format!("blobs/sha256/{}", layer.strip_prefix("sha256:").unwrap()), layer_b); + add(&format!("blobs/sha256/{}", man.strip_prefix("sha256:").unwrap()), man_b); + } + add(&format!("blobs/sha256/{}", nested.strip_prefix("sha256:").unwrap()), &nested_bytes); + add("oci-layout", br#"{"imageLayoutVersion":"1.0.0"}"#); + let mut desc = json!({"mediaType": "application/vnd.oci.image.index.v1+json", "digest": nested, "size": nested_sz}); + if let Some(t) = tag { + desc["annotations"] = json!({"io.containerd.image.name": format!("docker.io/{t}"), "org.opencontainers.image.ref.name": "1"}); + } + add("index.json", &serde_json::to_vec(&json!({"schemaVersion": 2, "manifests": [desc]})).unwrap()); + b.into_inner().unwrap() + }; + + let tagged_tar = build_oci(Some("demo/oci:1")); + let untagged_tar = build_oci(None); + let mut gz_tar = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gz_tar.write_all(&tagged_tar).unwrap(); + let gz_tar = gz_tar.finish().unwrap(); + + let post = |name: &str, query: &str, body: &[u8]| { + let (root, engine) = engine_in(name, false); + let (mut client, server) = UnixStream::pair().unwrap(); + let served = std::thread::spawn({ + let engine = engine.clone(); + move || serve(server, engine, Caller::Host) + }); + write!(client, "POST /v1.48/images/load{query} HTTP/1.1\r\nHost: docker\r\nContent-Type: application/x-tar\r\nContent-Length: {}\r\n\r\n", body.len()).unwrap(); + client.write_all(body).unwrap(); + let mut answer = String::new(); + client.read_to_string(&mut answer).unwrap(); + served.join().unwrap().unwrap(); + let images = engine.store.images().unwrap(); + drop(engine); + let _ = std::fs::remove_dir_all(root); + (answer, images) + }; + + let (ans, imgs) = post("oci-gz-amd", "?platform=linux%2Famd64", &gz_tar); + assert!(ans.starts_with("HTTP/1.1 200") && ans.contains("Loaded image: demo/oci:1"), "{ans}"); + assert_eq!(imgs[0].platform, "linux/amd64"); + + // Docker API v1.48 sends platform as JSON-encoded ocispec.Platform. + let (ans, imgs) = post("oci-json-arm", "?platform=%7B%22architecture%22%3A%22arm64%22%2C%22os%22%3A%22linux%22%7D", &tagged_tar); + assert!(ans.starts_with("HTTP/1.1 200") && ans.contains("Loaded image: demo/oci:1"), "{ans}"); + assert_eq!(imgs[0].platform, "linux/arm64"); + + // Untagged OCI archive loads by ID. + let (ans, imgs) = post("oci-untagged", "", &untagged_tar); + assert!(ans.starts_with("HTTP/1.1 200") && ans.contains("Loaded image ID: sha256:"), "{ans}"); + assert!(imgs[0].name.starts_with("sha256:")); + + // Invalid platform returns 400 after draining body. + let (ans, imgs) = post("oci-bad-plat", "?platform=%2F", &tagged_tar); + assert!(ans.starts_with("HTTP/1.1 400") && ans.contains("invalid platform"), "{ans}"); + assert!(imgs.is_empty()); + } + /// Every damaged gzip is a 400, including the ones Docker 29 accepts /// with 200 because it never reads the trailer: a wrong CRC or length, /// no trailer at all, and a byte flipped mid-stream (Docker writes that @@ -4502,6 +6405,16 @@ mod tests { assert_eq!((got, at), (archive, wire.len())); } + #[test] + fn copy_error_maps_readonly_refusals_to_forbidden_403() { + for msg in ["mounted volume is marked read-only", "container rootfs is marked read-only"] { + let err = copy_error(&format!("forbidden: {msg}")); + assert_eq!(status_of(err), (403, msg.to_owned())); + } + assert_eq!(status_of(copy_error("notfound: Could not find the file /x in container c1")), (404, "Could not find the file /x in container c1".to_owned())); + assert_eq!(status_of(copy_error("notdir: extraction point is not a directory: /x")), (400, "extraction point is not a directory: /x".to_owned())); + } + #[test] fn intel_macs_refuse_images_without_amd64() { let p = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); @@ -4842,6 +6755,99 @@ mod tests { drop(engine); let _ = std::fs::remove_dir_all(root); } + + #[test] + fn network_create_ignores_ipv6_ipam_when_ipv6_disabled() { + let root = std::env::temp_dir().join(format!("kiri-net-ipv6-off-api-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + let post = |body: Value| network_create(&Request::internal("POST", "/networks/create", &[], serde_json::to_vec(&body).unwrap()), &engine); + + // 1a. Explicit EnableIPv6: false + IPv4 & IPv6 subnets (mailcow-dockerized). + post(json!({ + "Name": "mailcow", + "EnableIPv6": false, + "IPAM": { + "Driver": "default", + "Config": [ + {"Subnet": "172.22.1.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"} + ] + } + })) + .unwrap(); + let ins = network_inspect(&engine, "mailcow").unwrap(); + assert_eq!(ins["EnableIPv4"], json!(true)); + assert_eq!(ins["EnableIPv6"], json!(false)); + assert_eq!(ins["IPAM"]["Config"], json!([{"Subnet": "172.22.1.0/24", "Gateway": "172.22.1.1"}])); + + // 1b. EnableIPv6 omitted + IPv4 & IPv6 subnets. + post(json!({ + "Name": "mailcow-omitted", + "IPAM": { + "Config": [ + {"Subnet": "172.22.2.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"} + ] + } + })) + .unwrap(); + let ins = network_inspect(&engine, "mailcow-omitted").unwrap(); + assert_eq!(ins["EnableIPv6"], json!(false)); + assert_eq!(ins["IPAM"]["Config"], json!([{"Subnet": "172.22.2.0/24", "Gateway": "172.22.2.1"}])); + + // 2. EnableIPv6: false + ONLY an IPv6 subnet: auto-allocates IPv4 subnet. + post(json!({ + "Name": "v6-only-cfg", + "EnableIPv6": false, + "IPAM": {"Config": [{"Subnet": "fd4d:6169:6c63:6f77::/64"}]} + })) + .unwrap(); + let ins = network_inspect(&engine, "v6-only-cfg").unwrap(); + assert_eq!(ins["EnableIPv4"], json!(true)); + assert_eq!(ins["EnableIPv6"], json!(false)); + let cfg = ins["IPAM"]["Config"].as_array().unwrap(); + assert_eq!(cfg.len(), 1); + let sub = cfg[0]["Subnet"].as_str().unwrap(); + assert!(sub.contains('.') && !sub.contains(':'), "expected auto IPv4 subnet, got {sub}"); + + // 3. Malformed subnet strings with EnableIPv6: false are still 400 BadRequest. + for bad in [ + json!([{"Subnet": "fd4d::not-a-cidr"}]), + json!([{"Subnet": "172.22.3.0/24"}, {"Subnet": "fd4d::not-a-cidr"}]), + json!([{"Subnet": "not-an-ip/64"}]), + json!([{"Subnet": "172.22.3.0/24"}, {"Subnet": "not-an-ip/64"}]), + ] { + let res = post(json!({"Name": "bad-cidr", "EnableIPv6": false, "IPAM": {"Config": bad}})); + assert!(matches!(res, Err(Error::BadRequest(ref m)) if m.contains("invalid CIDR block notation")), "{bad} -> {res:?}"); + } + + // 4. EnableIPv6: true + valid IPv6 subnet still works identically. + post(json!({ + "Name": "mailcow-on", + "EnableIPv6": true, + "IPAM": { + "Config": [ + {"Subnet": "172.22.4.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"} + ] + } + })) + .unwrap(); + let ins = network_inspect(&engine, "mailcow-on").unwrap(); + assert_eq!(ins["EnableIPv6"], json!(true)); + assert_eq!( + ins["IPAM"]["Config"], + json!([ + {"Subnet": "172.22.4.0/24", "Gateway": "172.22.4.1"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64", "Gateway": "fd4d:6169:6c63:6f77::1"} + ]) + ); + + drop(engine); + let _ = std::fs::remove_dir_all(root); + } } #[cfg(test)] @@ -4872,8 +6878,27 @@ mod network_option_tests { for (shares, weight) in [(2, 1), (512, 59), (1024, 100), (4096, 303), (262_144, 10_000), (1, 1), (999_999, 10_000)] { assert_eq!(super::cpu_weight(shares), weight, "{shares}"); } - let l = super::limits_from(&json!({"CpuShares": 1024}), Default::default()); + let l = super::limits_from(&json!({"CpuShares": 1024}), Default::default()).unwrap(); assert_eq!((l.cpu_shares, l.cpu_weight), (1024, 100)); + // Limits above `u32::MAX` were silently truncated (`as u32`); they are + // a 400 now, while legal values and `0`/`-1` sentinels stay intact. + let big = (u32::MAX as u64) + 1; + assert!(matches!(limits_from(&json!({"CpuQuota": 100_000, "CpuPeriod": big}), Default::default()), Err(Error::BadRequest(_)))); + assert!(matches!(limits_from(&json!({"CpuQuota": 100_000, "CpuPeriod": u64::MAX}), Default::default()), Err(Error::BadRequest(_)))); + assert_eq!(limits_from(&json!({"CpuQuota": 100_000, "CpuPeriod": 50_000}), Default::default()).unwrap().cpu_period, 50_000); + assert_eq!(limits_from(&json!({"CpuQuota": 100_000, "CpuPeriod": 0}), Default::default()).unwrap().cpu_period, 100_000); + assert_eq!(limits_from(&json!({"CpuQuota": 100_000, "CpuPeriod": -1}), Default::default()).unwrap().cpu_period, 100_000); + assert!(matches!(limits_from(&json!({"PidsLimit": big}), Default::default()), Err(Error::BadRequest(_)))); + assert!(matches!(limits_from(&json!({"PidsLimit": u64::MAX}), Default::default()), Err(Error::BadRequest(_)))); + let pids_set = limits_from(&json!({"PidsLimit": 256}), Default::default()).unwrap(); + assert_eq!(pids_set.pids_max, 256); + assert_eq!(limits_from(&json!({"PidsLimit": 0}), Default::default()).unwrap().pids_max, 0); + assert_eq!(limits_from(&json!({"PidsLimit": -1}), Default::default()).unwrap().pids_max, 0); + assert_eq!(limits_from(&json!({"PidsLimit": 0}), pids_set).unwrap().pids_max, 256); + assert_eq!(limits_from(&json!({"PidsLimit": -1}), pids_set).unwrap().pids_max, 256); + assert!(matches!(restart_policy(&json!({"Name": "on-failure", "MaximumRetryCount": big}), true), Err(Error::BadRequest(_)))); + assert!(matches!(restart_policy(&json!({"Name": "on-failure", "MaximumRetryCount": u64::MAX}), false), Err(Error::BadRequest(_)))); + assert_eq!(restart_policy(&json!({"Name": "on-failure", "MaximumRetryCount": 5}), true).unwrap().max_retries, 5); // Rises with the shares, never backwards. let mut last = 0; for s in 2..5000 { @@ -4883,6 +6908,136 @@ mod network_option_tests { } } + #[test] + fn inspect_keeps_exposed_protocols_from_the_image_and_create() { + let dir = std::env::temp_dir().join(format!("kiri-exposed-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({ + "architecture": "arm64", "os": "linux", + "config": {"Cmd": ["true"], "ExposedPorts": {"53/udp": {}, "132/SCTP": {}, "0/tcp": {}, "bad/udp": {}}} + }); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:dns".into(), &digest, &cfg, Vec::new())).unwrap(); + + let udp = json!({"53/udp": [{"HostIp": "127.0.0.1", "HostPort": "5353"}]}); + for bindings in [json!({}), udp.clone()] { + let body = json!({ + "Image": "demo:dns", + "ExposedPorts": { + "53": {}, "53/TCP": {}, "5353/UDP": {}, + "0": {}, "0/udp": {}, "70000/tcp": {}, "+53/tcp": {}, "53/": {}, "53/udp/extra": {}, "53/u dp": {} + }, + "HostConfig": {"PortBindings": bindings} + }); + let created = create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap(); + let id = created["Id"].as_str().unwrap(); + let inspected = container_inspect(&engine, id).unwrap(); + assert_eq!(inspected["Config"]["ExposedPorts"], json!({"132/sctp": {}, "53/tcp": {}, "53/udp": {}, "5353/udp": {}})); + assert_eq!(inspected["HostConfig"]["PortBindings"], bindings); + engine + .with(id, |c| { + // Deterministic normalized order in stored Spec.exposed. + assert_eq!(c.spec.exposed, ["132/sctp", "53/tcp", "53/udp", "5353/udp"]); + let bound: Vec<_> = c.spec.ports.iter().map(|b| (b.clone(), b.host_ip.clone(), b.host_port)).collect(); + assert_eq!( + ports_map_of(&bound, Some((&c.spec.ports, &c.spec.exposed))), + json!({"132/sctp": null, "53/tcp": null, "53/udp": bindings["53/udp"], "5353/udp": null}) + ); + }) + .unwrap(); + } + + // PublishAllPorts (-P) publishes exposed TCP and UDP ports (normalizing case), + // skips non-TCP/UDP protocols like SCTP without failing, and keeps explicit bindings. + let body = json!({ + "Image": "demo:dns", + "ExposedPorts": {"53": {}, "5353/UDP": {}}, + "HostConfig": {"PublishAllPorts": true, "PortBindings": udp} + }); + let created = create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap(); + let id = created["Id"].as_str().unwrap(); + engine + .with(id, |c| { + let mut got: Vec<_> = c.spec.ports.iter().map(|b| (b.container_port, b.proto.as_str(), b.host_port)).collect(); + got.sort_unstable(); + assert_eq!(got, [(53, "tcp", 0), (53, "udp", 5353), (5353, "udp", 0)]); + }) + .unwrap(); + + // Domain routing picks only TCP exposed ports, ignoring UDP and SCTP. + let dom_body = json!({"Image": "demo:dns", "ExposedPorts": {"53": {}, "5353/UDP": {}}}); + let created = create(&Request::internal("POST", "/containers/create", &[("name", "dnsdom")], serde_json::to_vec(&dom_body).unwrap()), &engine).unwrap(); + let dom_id = created["Id"].as_str().unwrap(); + engine.mark_running_for_test(dom_id, [10, 88, 0, 2]); + let target = engine.route("dnsdom.kiri.localhost").expect("running container domain target"); + assert_eq!(target.exposed, [53]); + + // With NetworkMode: "host" and PortBindings (#764), HostConfig.PortBindings + // and Config.ExposedPorts are preserved in inspect, while NetworkSettings.Ports + // is {} and ps Ports is [] when no host-side port forwarder is bound. + let host_bindings = json!({"18081/tcp": [{"HostIp": "", "HostPort": "18081"}]}); + let host_body = json!({ + "Image": "demo:dns", + "HostConfig": { + "NetworkMode": "host", + "PortBindings": host_bindings + } + }); + let created = create(&Request::internal("POST", "/containers/create", &[("name", "hostweb")], serde_json::to_vec(&host_body).unwrap()), &engine).unwrap(); + let host_id = created["Id"].as_str().unwrap(); + let inspected_created = container_inspect(&engine, host_id).unwrap(); + assert_eq!(inspected_created["HostConfig"]["NetworkMode"], "host"); + assert_eq!(inspected_created["HostConfig"]["PortBindings"], host_bindings); + assert_eq!(inspected_created["NetworkSettings"]["Ports"], json!({})); + + engine.mark_running_for_test(host_id, [0; 4]); + let inspected_running = container_inspect(&engine, host_id).unwrap(); + assert_eq!(inspected_running["HostConfig"]["NetworkMode"], "host"); + assert_eq!(inspected_running["HostConfig"]["PortBindings"], host_bindings); + assert_eq!(inspected_running["Config"]["ExposedPorts"]["18081/tcp"], json!({})); + assert_eq!(inspected_running["NetworkSettings"]["Ports"], json!({})); + let listed = list(&Request::internal("GET", "/containers/json", &[], Vec::new()), &engine).unwrap(); + let row = listed.as_array().unwrap().iter().find(|r| r["Id"] == host_id).expect("hostweb listed"); + assert_eq!(row["Ports"], json!([])); + let host_route = engine.route("hostweb.kiri.localhost").expect("host network domain target"); + assert_eq!(host_route.ip, [127, 0, 0, 1]); + assert_eq!(host_route.published, [18081]); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn exposed_ports_in_old_and_new_specs_round_trip() { + let mut record = json!({ + "image": "demo:dns", "image_id": "sha256:0123", "entrypoint": [], "cmd": ["true"], "env": [], + "cwd": "/", "user": "", "auto_remove": false, "network_mode": "bridge", "labels": {}, "exposed": [53, 8080] + }); + let old: Spec = serde_json::from_value(record.clone()).unwrap(); + assert_eq!(inspect_exposed(&old.ports, &old.exposed), json!({"53/tcp": {}, "8080/tcp": {}})); + assert_eq!(ports_map_of(&[], Some((&old.ports, &old.exposed))), json!({"53/tcp": null, "8080/tcp": null})); + assert_eq!(serde_json::to_value(&old).unwrap()["exposed"], json!(["53/tcp", "8080/tcp"])); + + record["exposed"] = json!(["132/sctp", "53/tcp", "53/udp"]); + let new: Spec = serde_json::from_value(record.clone()).unwrap(); + let saved = serde_json::to_vec(&new).unwrap(); + let loaded: Spec = serde_json::from_slice(&saved).unwrap(); + assert_eq!(serde_json::to_value(&loaded).unwrap()["exposed"], record["exposed"]); + assert_eq!(inspect_exposed(&loaded.ports, &loaded.exposed), json!({"132/sctp": {}, "53/tcp": {}, "53/udp": {}})); + + // Mixed legacy/new/uppercase/duplicate/invalid entries normalize cleanly, and null is empty. + record["exposed"] = json!([53, "53", "53/TCP", "53/UDP", 0, "0/udp", "bad"]); + let mixed: Spec = serde_json::from_value(record.clone()).unwrap(); + assert_eq!(mixed.exposed, ["53/tcp", "53/udp"]); + + record["exposed"] = Value::Null; + let null_spec: Spec = serde_json::from_value(record).unwrap(); + assert!(null_spec.exposed.is_empty()); + } + #[test] fn container_network_mode_refuses_what_docker_refuses() { assert!(container_mode_allowed(&json!({"HostConfig": {"NetworkMode": "container:web"}}), "web").is_ok()); @@ -4892,13 +7047,13 @@ mod network_option_tests { assert_eq!(inspect_bindings(&ports), json!({"80/tcp": [{"HostIp": "", "HostPort": "8080"}, {"HostIp": "127.0.0.1", "HostPort": ""}], "53/udp": [{"HostIp": "", "HostPort": "5353"}]})); assert_eq!(inspect_bindings(&[]), json!({})); assert_eq!(inspect_exposed(&[], &[]), Value::Null); - assert_eq!(inspect_exposed(&ports, &[80, 9000]), json!({"80/tcp": {}, "53/udp": {}, "9000/tcp": {}})); + assert_eq!(inspect_exposed(&ports, &["80/tcp".into(), "9000/tcp".into()]), json!({"80/tcp": {}, "53/udp": {}, "9000/tcp": {}})); // NetworkSettings.Ports: published ports with their addresses, exposed // ones without as null keys (#492); none at all while not running. let bound = [(b(80, "tcp", "", 8080), "0.0.0.0".to_string(), 8080)]; - assert_eq!(ports_map_of(&[], Some((&[], &[80]))), json!({"80/tcp": null})); + assert_eq!(ports_map_of(&[], Some((&[], &["80/tcp".into()]))), json!({"80/tcp": null})); assert_eq!( - ports_map_of(&bound, Some((&ports, &[80, 9000]))), + ports_map_of(&bound, Some((&ports, &["80/tcp".into(), "9000/tcp".into()]))), json!({"80/tcp": [{"HostIp": "0.0.0.0", "HostPort": "8080"}], "53/udp": null, "9000/tcp": null}) ); assert_eq!(ports_map_of(&[], None), json!({})); @@ -5007,6 +7162,340 @@ mod network_option_tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn cgroupns_mode_is_kept_in_inspect_and_bad_modes_are_refused() { + let dir = std::env::temp_dir().join(format!("kiri-cgroupns-api-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-23T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"]}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + + let make = |host: Value| { + let body = json!({"Image": "demo:local", "HostConfig": host}); + super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine) + }; + let default_id = make(json!({})).unwrap()["Id"].as_str().unwrap().to_owned(); + assert_eq!(super::container_inspect(&engine, &default_id).unwrap()["HostConfig"]["CgroupnsMode"], "private"); + let null_id = make(json!({"CgroupnsMode": Value::Null})).unwrap()["Id"].as_str().unwrap().to_owned(); + assert_eq!(super::container_inspect(&engine, &null_id).unwrap()["HostConfig"]["CgroupnsMode"], "private"); + let empty_id = make(json!({"CgroupnsMode": ""})).unwrap()["Id"].as_str().unwrap().to_owned(); + assert_eq!(super::container_inspect(&engine, &empty_id).unwrap()["HostConfig"]["CgroupnsMode"], "private"); + let priv_id = make(json!({"CgroupnsMode": "private"})).unwrap()["Id"].as_str().unwrap().to_owned(); + assert_eq!(super::container_inspect(&engine, &priv_id).unwrap()["HostConfig"]["CgroupnsMode"], "private"); + let host_id = make(json!({"CgroupnsMode": "host"})).unwrap()["Id"].as_str().unwrap().to_owned(); + let host_inspected = super::container_inspect(&engine, &host_id).unwrap(); + assert_eq!(host_inspected["HostConfig"]["CgroupnsMode"], "host"); + // Recreating from inspect keeps CgroupnsMode persisted. + let mut recreate = host_inspected["Config"].clone(); + recreate["HostConfig"] = host_inspected["HostConfig"].clone(); + let host_id2 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&recreate).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + assert_eq!(super::container_inspect(&engine, &host_id2).unwrap()["HostConfig"]["CgroupnsMode"], "host"); + for bad in [json!("bogus"), json!("container:abc"), json!(123)] { + let want = match &bad { + Value::String(s) => format!("invalid cgroup namespace mode: {s}"), + other => format!("invalid cgroup namespace mode: {other}"), + }; + assert_eq!(super::status_of(make(json!({"CgroupnsMode": bad})).unwrap_err()), (400, want)); + } + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + /// `--security-opt seccomp=unconfined` (and `seccomp:unconfined`) warns in + /// `POST /containers/create`'s `Warnings` that Kiri's host boundary stays + /// in place; default containers, `--privileged` alone, and options where a + /// later `seccomp=` entry overrides `unconfined` produce no warning (#516). + #[test] + fn seccomp_unconfined_warns_that_the_host_boundary_stays() { + let dir = std::env::temp_dir().join(format!("kiri-seccomp-warn-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-23T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"]}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + let warnings_for = |host: Value| { + let body = json!({"Image": "demo:local", "HostConfig": host}); + let res = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap(); + res["Warnings"].clone() + }; + let expected = json!([super::SECCOMP_UNCONFINED_WARNING]); + assert_eq!(warnings_for(json!({})), json!([])); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=builtin"]})), json!([])); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=unconfined"]})), expected); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp:unconfined"]})), expected); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=builtin", "seccomp=unconfined"]})), expected); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=unconfined", "seccomp=builtin"]})), json!([])); + assert_eq!(warnings_for(json!({"SecurityOpt": ["seccomp=unconfined", r#"seccomp={"defaultAction":"SCMP_ACT_ALLOW"}"#]})), json!([])); + assert_eq!(warnings_for(json!({"Privileged": true})), json!([])); + assert_eq!(warnings_for(json!({"Privileged": true, "SecurityOpt": ["seccomp=unconfined"]})), expected); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Creates a container from `body` (on an image with a VOLUME line) and + /// returns its inspect, as `docker inspect` shows it. + fn inspect_after_create(name: &str, body: Value) -> Value { + let dir = std::env::temp_dir().join(format!("kiri-inspect-mounts-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-20T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"], "Volumes": {"/var/lib/img": {}}}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + let mut body = body; + body["Image"] = json!("demo:local"); + let id = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v = container_inspect(&engine, &id).unwrap(); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + v + } + + /// `-v` and Compose's short syntax arrive as Binds, `--mount` and the + /// long syntax as Mounts, `--tmpfs` as Tmpfs. Docker gives each back as + /// it came, and tools that recreate a container (Watchtower, Portainer, + /// Arcane) copy HostConfig: without them the new container has no volumes (#610). + #[test] + fn inspect_gives_back_binds_mounts_and_tmpfs_as_created() { + let src = std::env::temp_dir().join(format!("kiri-inspect-src-{}", std::process::id())); + std::fs::create_dir_all(&src).unwrap(); + let src = src.to_str().unwrap().to_owned(); + let binds = json!([ + format!("{src}:/b:ro"), + "k610vol:/data:rw", + "/var/run/docker.sock:/var/run/docker.sock", + "/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", + ]); + let mounts = json!([ + {"Type": "bind", "Source": src, "Target": "/b2", "ReadOnly": true}, + {"Type": "bind", "Source": "/run/host-services/ssh-auth.sock", "Target": "/ssh2.sock", "ReadOnly": true}, + {"Type": "volume", "Source": "k610other", "Target": "/data2", "ReadOnly": true, "VolumeOptions": {"NoCopy": true}}, + {"Type": "volume", "Target": "/anon2", "VolumeOptions": {}}, + {"Type": "tmpfs", "Target": "/t", "TmpfsOptions": {"SizeBytes": 1048576}}, + ]); + let tmpfs = json!({"/t2": "size=2m"}); + let v = inspect_after_create("given", json!({"HostConfig": {"Binds": binds, "Mounts": mounts, "Tmpfs": tmpfs}})); + assert_eq!(v["HostConfig"]["Binds"], binds); + assert_eq!(v["HostConfig"]["Mounts"], mounts); + assert_eq!(v["HostConfig"]["Tmpfs"], tmpfs); + assert_eq!(v["Config"]["Volumes"], json!({"/var/lib/img": {}})); + // HostConfig must never leak internal volume or relay socket paths. + let hc_text = v["HostConfig"].to_string(); + assert!(!hc_text.contains("/var/lib/kiri/volumes/"), "HostConfig leaked volume path: {hc_text}"); + assert!(!hc_text.contains("/run/kiri/host-services/ssh-auth.sock"), "HostConfig leaked host ssh relay path: {hc_text}"); + assert!(!hc_text.contains("/run/host-services/docker.sock"), "HostConfig leaked vm docker relay path: {hc_text}"); + assert!(!hc_text.contains("docker.container.sock"), "HostConfig leaked container socket path: {hc_text}"); + let _ = std::fs::remove_dir_all(&src); + } + + /// With no mounts asked for, Docker shows none. + #[test] + fn inspect_without_mounts_shows_none() { + let v = inspect_after_create("none", json!({"HostConfig": {}})); + assert_eq!(v["HostConfig"]["Binds"], Value::Null); + assert_eq!(v["HostConfig"]["Mounts"], Value::Null); + assert_eq!(v["HostConfig"]["Tmpfs"], Value::Null); + assert_eq!(v["Config"]["Volumes"], json!({"/var/lib/img": {}})); + } + + /// `-v /path` arrives in Config.Volumes; Docker's inspect lists it there + /// with the image's VOLUME lines, never in HostConfig.Binds under its + /// generated 64-hex volume ID, so a recreate makes fresh anonymous volumes. + #[test] + fn inspect_lists_anonymous_volumes_in_config_volumes() { + let v = inspect_after_create("anon", json!({"Volumes": {"/anon": {}}, "HostConfig": {}})); + assert_eq!(v["Config"]["Volumes"], json!({"/anon": {}, "/var/lib/img": {}})); + assert_eq!(v["HostConfig"]["Binds"], Value::Null); + assert_eq!(v["HostConfig"]["Mounts"], Value::Null); + assert_eq!(v["HostConfig"]["Tmpfs"], Value::Null); + } + + /// Recreating a container directly from its inspect `Config` + `HostConfig` + /// verbatim (as Watchtower, Portainer and Arcane do) succeeds with no + /// duplicate mount points and keeps named volumes, `:ro`, `ReadOnly: true`, + /// tmpfs, and socket paths while giving anonymous volumes fresh IDs (#610). + #[test] + fn inspect_recreate_round_trip_keeps_mounts_without_duplicates() { + let dir = std::env::temp_dir().join(format!("kiri-inspect-recreate-{}", std::process::id())); + let src = std::env::temp_dir().join(format!("kiri-inspect-recreate-src-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&src); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::create_dir_all(&src).unwrap(); + let src_s = src.to_str().unwrap().to_owned(); + let engine = super::super::engine::boot_without_vm(&dir); + let cfg = json!({"created": "2026-11-20T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"], "Volumes": {"/var/lib/img": {}, "/img-overridden": {}}}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + engine.store.put_image(kiri_image::archive::from_config("demo:local".into(), &digest, &cfg, Vec::new())).unwrap(); + + let body = json!({ + "Image": "demo:local", + "Volumes": {"/anon": {}}, + "HostConfig": { + "Binds": [ + format!("{src_s}:/b:ro"), + "k610vol:/data", + "k610img:/img-overridden", + "/var/run/docker.sock:/var/run/docker.sock", + "/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", + ], + "Mounts": [ + {"Type": "bind", "Source": src_s, "Target": "/b2", "ReadOnly": true}, + {"Type": "volume", "Source": "k610rovol", "Target": "/rovol", "ReadOnly": true}, + {"Type": "tmpfs", "Target": "/t", "TmpfsOptions": {"SizeBytes": 1048576}}, + ], + "Tmpfs": {"/t2": "size=2m"}, + } + }); + let id1 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&body).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v1 = container_inspect(&engine, &id1).unwrap(); + + let mut recreate = v1["Config"].clone(); + recreate["HostConfig"] = v1["HostConfig"].clone(); + let id2 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&recreate).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v2 = container_inspect(&engine, &id2).unwrap(); + + assert_eq!(v2["HostConfig"]["Binds"], v1["HostConfig"]["Binds"]); + assert_eq!(v2["HostConfig"]["Mounts"], v1["HostConfig"]["Mounts"]); + assert_eq!(v2["HostConfig"]["Tmpfs"], v1["HostConfig"]["Tmpfs"]); + assert_eq!(v2["Config"]["Volumes"], json!({"/anon": {}, "/var/lib/img": {}, "/img-overridden": {}})); + + // Top-level Mounts has every expected destination exactly once. + let mounts2 = v2["Mounts"].as_array().unwrap(); + let dsts: Vec<&str> = mounts2.iter().map(|m| m["Destination"].as_str().unwrap()).collect(); + let unique: std::collections::HashSet<&str> = dsts.iter().copied().collect(); + assert_eq!(dsts.len(), unique.len(), "duplicate mount targets after recreate: {dsts:?}"); + let find = |dst: &str| mounts2.iter().find(|m| m["Destination"] == dst).unwrap_or_else(|| panic!("missing {dst}")); + assert_eq!(find("/b")["RW"], false); + assert_eq!(find("/b2")["RW"], false); + assert_eq!(find("/data")["Name"], "k610vol"); + assert_eq!(find("/img-overridden")["Name"], "k610img"); + assert_eq!(find("/rovol")["Name"], "k610rovol"); + assert_eq!(find("/rovol")["RW"], false); + assert_eq!(find("/var/run/docker.sock")["Source"], "/var/run/docker.sock"); + assert_eq!(find("/run/host-services/ssh-auth.sock")["Source"], "/run/host-services/ssh-auth.sock"); + assert_eq!(find("/t")["Type"], "tmpfs"); + assert_eq!(find("/t2")["Type"], "tmpfs"); + // Anonymous volumes get fresh IDs on recreate instead of being pinned in Binds. + let anon1 = v1["Mounts"].as_array().unwrap().iter().find(|m| m["Destination"] == "/anon").unwrap()["Name"].as_str().unwrap(); + let anon2 = find("/anon")["Name"].as_str().unwrap(); + assert_ne!(anon1, anon2, "recreated container must get a fresh anonymous volume"); + assert!(!v1["HostConfig"]["Binds"].to_string().contains(anon1)); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + let _ = std::fs::remove_dir_all(&src); + } + + /// A container saved before `mount_request` was kept has only Docker's + /// `Mounts` entries: its Binds, Mounts, Tmpfs and anonymous volumes are + /// made from those without leaking `/var/lib/kiri/volumes/...`, internal + /// socket paths, or anonymous 64-hex IDs, and recreating from inspect works. + #[test] + fn inspect_of_an_older_container_derives_its_mounts() { + let root = std::env::temp_dir().join(format!("kiri-inspect-older-{}", std::process::id())); + let src = std::env::temp_dir().join(format!("kiri-inspect-older-src-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let _ = std::fs::remove_dir_all(&src); + std::fs::create_dir_all(&root).unwrap(); + std::fs::create_dir_all(&src).unwrap(); + let src_s = src.to_str().unwrap().to_owned(); + let engine = super::super::engine::boot_without_vm(&root); + let cfg = json!({"created": "2026-11-20T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["true"]}}); + let mut w = engine.store.ingest().unwrap(); + io::Write::write_all(&mut w, &serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + let image = kiri_image::archive::from_config("older:1".into(), &digest, &cfg, Vec::new()); + engine.store.put_image(image.clone()).unwrap(); + // An anonymous volume borrowed via --volumes-from lives in volumes.json + // as anonymous even when not listed on this container's anon_volumes. + let borrowed_anon = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + engine.volume_ensure(borrowed_anon, json!({}), true).unwrap(); + let spec: super::super::engine::Spec = serde_json::from_value(json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0}, "volumes": ["named", "namedro", borrowed_anon], "anon_volumes": ["0123abcd", "deadbeef"], + "mount_info": [ + {"Type": "bind", "Source": src_s, "Destination": "/src", "Mode": "", "RW": false, "Propagation": "rprivate"}, + {"Type": "bind", "Source": "/var/run/docker.sock", "Destination": "/var/run/docker.sock", "Mode": "", "RW": true, "Propagation": "rprivate"}, + {"Type": "bind", "Source": "/run/host-services/ssh-auth.sock", "Destination": "/run/host-services/ssh-auth.sock", "Mode": "", "RW": true, "Propagation": "rprivate"}, + {"Type": "volume", "Name": "named", "Source": "/var/lib/kiri/volumes/named/_data", "Destination": "/data", "Driver": "local", "Mode": "z", "RW": true, "Propagation": ""}, + {"Type": "volume", "Name": "namedro", "Source": "/var/lib/kiri/volumes/namedro/_data", "Destination": "/dataro", "Driver": "local", "Mode": "z", "RW": false, "Propagation": ""}, + {"Type": "volume", "Name": "0123abcd", "Source": "/var/lib/kiri/volumes/0123abcd/_data", "Destination": "/anon", "Driver": "local", "Mode": "z", "RW": true, "Propagation": ""}, + {"Type": "volume", "Name": "deadbeef", "Source": "/var/lib/kiri/volumes/deadbeef/_data", "Destination": "/anonro", "Driver": "local", "Mode": "z", "RW": false, "Propagation": ""}, + {"Type": "volume", "Name": borrowed_anon, "Source": format!("/var/lib/kiri/volumes/{borrowed_anon}/_data"), "Destination": "/borrowed", "Driver": "local", "Mode": "z", "RW": true, "Propagation": ""}, + {"Type": "tmpfs", "Source": "", "Destination": "/t", "Mode": "", "RW": true, "Propagation": ""}, + {"Type": "tmpfs", "Source": "", "Destination": "/tro", "Mode": "", "RW": false, "Propagation": ""}, + ], + })).unwrap(); + let id = engine.create(Some("older".into()), spec, &image).unwrap(); + let v = container_inspect(&engine, &id).unwrap(); + assert_eq!( + v["HostConfig"]["Binds"], + json!([ + format!("{src_s}:/src:ro"), + "/var/run/docker.sock:/var/run/docker.sock", + "/run/host-services/ssh-auth.sock:/run/host-services/ssh-auth.sock", + "named:/data", + "namedro:/dataro:ro", + ]) + ); + assert_eq!( + v["HostConfig"]["Mounts"], + json!([ + {"Type": "volume", "Target": "/anonro", "ReadOnly": true}, + {"Type": "tmpfs", "Target": "/tro", "ReadOnly": true}, + ]) + ); + assert_eq!(v["HostConfig"]["Tmpfs"], json!({"/t": ""})); + assert_eq!(v["Config"]["Volumes"], json!({"/anon": {}, "/borrowed": {}})); + let hc_text = v["HostConfig"].to_string(); + assert!(!hc_text.contains("/var/lib/kiri/volumes/")); + assert!(!hc_text.contains("0123abcd")); + assert!(!hc_text.contains("deadbeef")); + assert!(!hc_text.contains(borrowed_anon)); + + // Recreating from the legacy container's inspect succeeds with no duplicates. + let mut recreate = v["Config"].clone(); + recreate["HostConfig"] = v["HostConfig"].clone(); + let id2 = super::create(&Request::internal("POST", "/containers/create", &[], serde_json::to_vec(&recreate).unwrap()), &engine).unwrap()["Id"] + .as_str() + .unwrap() + .to_owned(); + let v2 = container_inspect(&engine, &id2).unwrap(); + let dsts: Vec<&str> = v2["Mounts"].as_array().unwrap().iter().map(|m| m["Destination"].as_str().unwrap()).collect(); + let unique: std::collections::HashSet<&str> = dsts.iter().copied().collect(); + assert_eq!(dsts.len(), unique.len(), "duplicate mount targets after legacy recreate: {dsts:?}"); + assert_eq!(dsts.len(), 10); + + drop(engine); + let _ = std::fs::remove_dir_all(&root); + let _ = std::fs::remove_dir_all(&src); + } + #[test] fn image_and_container_labels_follow_docker() { let dir = std::env::temp_dir().join(format!("kiri-labels-test-{}", std::process::id())); @@ -5181,6 +7670,38 @@ mod network_option_tests { assert!(super::check_volume_device(&opts(&[])).is_ok()); } + #[test] + fn ssh_agent_bind_uses_the_agent_host_path_on_linux() { + // The guest is told where the agent listens: the VM's path, or + // Kiri's own /run/kiri on a Linux host (#420). + assert_eq!(super::ssh_agent_source_for(false), "/run/host-services/ssh-auth.sock"); + assert_eq!(super::ssh_agent_source_for(true), "/run/kiri/host-services/ssh-auth.sock"); + assert_eq!( + super::ssh_agent_source(), + if cfg!(target_os = "linux") { "/run/kiri/host-services/ssh-auth.sock" } else { "/run/host-services/ssh-auth.sock" } + ); + assert!(super::is_ssh_agent_sock("/run/host-services/ssh-auth.sock")); + assert!(super::is_ssh_agent_sock("/run/host-services//ssh-auth.sock")); + assert!(super::is_ssh_agent_sock("/run/./host-services/ssh-auth.sock")); + assert!(!super::is_ssh_agent_sock("run/host-services/ssh-auth.sock")); + // A container made before #420 with /run/host-services/ssh-auth.sock + // in its saved guest mount line gets /run/kiri/host-services/ssh-auth.sock + // when started on Linux, while inspect keeps the path asked for. + let guest = vec!["/run/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro".to_owned()]; + let info = vec![serde_json::json!({"Type": "bind", "Source": "/run/host-services/ssh-auth.sock"})]; + assert_eq!( + super::fresh_bind_sources_with(&guest, &info, |_| None, false), + ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"] + ); + assert_eq!(super::fresh_bind_sources_with(&guest, &[], |_| None, false), ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"]); + let slash_guest = vec!["/run/host-services//ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro".to_owned()]; + assert_eq!( + super::fresh_bind_sources_with(&slash_guest, &[], |_| None, false), + ["/run/kiri/host-services/ssh-auth.sock\t/run/host-services/ssh-auth.sock\tro"] + ); + assert_eq!(super::fresh_bind_sources_with(&guest, &info, |_| None, true), guest); + } + /// `--add-host name:ip` and `--hostname` are written into the container's /// /etc/hosts by the guest, so neither may add a line of its own. #[test] @@ -5201,6 +7722,101 @@ mod network_option_tests { assert!(!super::valid_hosts_name(bad), "{bad:?}"); } } + + /// `--memory-swap` as Docker Engine takes it (#523): memory plus swap, + /// twice the memory when not given, -1 for unlimited swap. + #[test] + fn memory_swap_is_memory_plus_swap_as_in_docker() { + let create = |h: Value| limits_from(&h, super::super::engine::Limits::default()); + let swap = |l: super::super::engine::Limits| l.wire().swap_max; + const G: u64 = 1 << 30; + + let l = create(json!({"Memory": 4 * G})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (8 * G as i64, 4 * G)); + let l = create(json!({"Memory": 4 * G, "MemorySwap": 6 * G})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (6 * G as i64, 2 * G)); + let l = create(json!({"Memory": 4 * G, "MemorySwap": 4 * G})).unwrap(); + assert_eq!(swap(l), 0, "--memory-swap equal to --memory: no swap"); + let l = create(json!({"Memory": 4 * G, "MemorySwap": -1})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (-1, kiri_proto::NO_LIMIT)); + let l = create(json!({"MemorySwap": -1})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (-1, kiri_proto::NO_LIMIT)); + let l = create(json!({})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (0, kiri_proto::NO_LIMIT), "no memory limit, no swap limit"); + assert_eq!(l.wire(), kiri_proto::Limits::default(), "unlimited container matches wire default"); + + // Overflow near i64::MAX: 2 * Memory saturates at i64::MAX without wrapping or panicking. + let five_eb: u64 = 5 << 60; + let l = create(json!({"Memory": five_eb})).unwrap(); + assert_eq!(l.memory_swap, i64::MAX); + assert_eq!(swap(l), (i64::MAX as u64) - five_eb); + let l = create(json!({"Memory": i64::MAX as u64})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (i64::MAX, 0)); + let l = create(json!({"Memory": u64::MAX})).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (i64::MAX, 0)); + + let bad = |h: Value| match create(h) { + Err(Error::BadRequest(m)) => m, + other => panic!("{other:?}"), + }; + assert!(bad(json!({"MemorySwap": G})).starts_with("You should always set the Memory limit")); + assert!(bad(json!({"Memory": 2 * G, "MemorySwap": G})).starts_with("Minimum memoryswap limit")); + + // docker update keeps what it isn't given, and refuses a memory + // limit above the memory plus swap already set. + let base = create(json!({"Memory": 4 * G, "MemorySwap": 6 * G})).unwrap(); + let l = limits_from(&json!({"Memory": 0, "MemorySwap": 0, "NanoCpus": 2_000_000_000u64}), base).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (4 * G, 6 * G as i64, 2 * G), "updating --cpus keeps custom MemorySwap"); + let l = limits_from(&json!({"Memory": 5 * G}), base).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (5 * G, 6 * G as i64, G)); + let l = limits_from(&json!({"Memory": 4 * G, "MemorySwap": 8 * G}), base).unwrap(); + assert_eq!(swap(l), 4 * G); + let l = limits_from(&json!({"MemorySwap": -1}), base).unwrap(); + assert_eq!((l.memory_swap, swap(l)), (-1, kiri_proto::NO_LIMIT)); + match limits_from(&json!({"Memory": 7 * G}), base) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Memory limit should be smaller than already set memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + match limits_from(&json!({"MemorySwap": 2 * G}), base) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Minimum memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + match limits_from(&json!({"Memory": 8 * G, "MemorySwap": 6 * G}), base) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Minimum memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + let no_mem = create(json!({})).unwrap(); + match limits_from(&json!({"MemorySwap": G}), no_mem) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("You should always set the Memory limit"), "{m}"), + other => panic!("{other:?}"), + } + + // Updating --memory or --cpus when base.memory_swap == -1 keeps -1 (unlimited swap). + let unlim = create(json!({"Memory": 4 * G, "MemorySwap": -1})).unwrap(); + let l = limits_from(&json!({"Memory": 512 << 20}), unlim).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (512 << 20, -1, kiri_proto::NO_LIMIT)); + let l = limits_from(&json!({"Memory": 8 * G}), unlim).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (8 * G, -1, kiri_proto::NO_LIMIT)); + let l = limits_from(&json!({"NanoCpus": 2_000_000_000u64}), unlim).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (4 * G, -1, kiri_proto::NO_LIMIT)); + + // Updating Memory above i64::MAX against an i64::MAX MemorySwap is refused. + let huge = create(json!({"Memory": five_eb})).unwrap(); + match limits_from(&json!({"Memory": u64::MAX}), huge) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Memory limit should be smaller than already set memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + + // Saved before `memory_swap`: Docker's default, not no swap, and updates honour it. + let old: super::super::engine::Limits = serde_json::from_value(json!({"memory_max": G, "cpu_quota": 0, "cpu_period": 0, "cpu_weight": 0, "pids_max": 0})).unwrap(); + assert_eq!((old.memory_swap(), swap(old)), (2 * G as i64, G)); + let l = limits_from(&json!({"Memory": 3 * G / 2}), old).unwrap(); + assert_eq!((l.memory_max, l.memory_swap, swap(l)), (3 * G / 2, 2 * G as i64, G / 2)); + match limits_from(&json!({"Memory": 3 * G}), old) { + Err(Error::BadRequest(m)) => assert!(m.starts_with("Memory limit should be smaller than already set memoryswap limit"), "{m}"), + other => panic!("{other:?}"), + } + } } #[cfg(test)] @@ -5234,10 +7850,348 @@ mod leave_first_network_tests { let networks: Vec = engine.lock_net().all().to_vec(); assert_eq!(names(&container_inspect(&engine, &id).unwrap()["NetworkSettings"]["Networks"]), ["probe-net"]); assert_eq!(names(&engine.with(&id, |c| network_settings(c, &networks)).unwrap()["Networks"]), ["probe-net"]); + let filter_has = |net: &str| { + let filters = format!(r#"{{"network":["{net}"]}}"#); + let req = Request::internal("GET", "/containers/json", &[("all", "1"), ("filters", &filters)], Vec::new()); + list(&req, &engine).unwrap().as_array().unwrap().iter().any(|r| r["Id"] == id) + }; + assert!(filter_has("probe-net")); + assert!(!filter_has("bridge")); engine.disconnect("probe-net", &id).unwrap(); assert!(names(&container_inspect(&engine, &id).unwrap()["NetworkSettings"]["Networks"]).is_empty()); assert!(names(&engine.with(&id, |c| network_settings(c, &networks)).unwrap()["Networks"]).is_empty()); + assert!(!filter_has("probe-net")); + assert!(!filter_has("none")); + assert!(engine.network_members("none").is_empty()); drop(engine); let _ = std::fs::remove_dir_all(root); } } + +#[cfg(test)] +mod resources_disk_tests { + use super::*; + + #[test] + fn resources_payload_round_trip_and_disk_bounds() { + let dir = std::env::temp_dir().join(format!( + "kiri-res-disk-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + let path = dir.join("vm.json"); + + // Save CPUs, memory and disk_gb; verify vm.json contents. + let body = json!({"cpus": 4, "memory_mib": 8192, "disk_gb": 128}).to_string(); + save_resources(body.as_bytes(), &path, 12, 32768, Some(64), None, None).unwrap(); + let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved, json!({"cpus": 4, "memory_mib": 8192, "disk_gb": 128})); + + // Omitting disk_gb preserves the existing disk_gb in vm.json, and omitting + // shared_nat preserves an existing shared_nat flag in vm.json. + let body2 = json!({"cpus": 6, "memory_mib": 4096}).to_string(); + save_resources(body2.as_bytes(), &path, 12, 32768, Some(64), saved["disk_gb"].as_u64(), Some(false)).unwrap(); + let saved2: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved2, json!({"cpus": 6, "memory_mib": 4096, "disk_gb": 128, "shared_nat": false})); + + // Explicitly updating shared_nat works and non-boolean values are rejected with 400. + let body3 = json!({"cpus": 6, "memory_mib": 4096, "shared_nat": true}).to_string(); + save_resources(body3.as_bytes(), &path, 12, 32768, Some(64), Some(128), Some(false)).unwrap(); + let saved3: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved3, json!({"cpus": 6, "memory_mib": 4096, "disk_gb": 128, "shared_nat": true})); + + // Existing balloon / memory_min_mib fields in vm.json survive save_resources updates. + std::fs::write( + &path, + json!({"cpus": 6, "memory_mib": 4096, "disk_gb": 128, "shared_nat": true, "balloon": false, "memory_min_mib": 2048}).to_string(), + ) + .unwrap(); + let body4 = json!({"cpus": 8, "memory_mib": 8192}).to_string(); + save_resources(body4.as_bytes(), &path, 12, 32768, Some(64), Some(128), Some(true)).unwrap(); + let saved4: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!( + saved4, + json!({"cpus": 8, "memory_mib": 8192, "disk_gb": 128, "shared_nat": true, "balloon": false, "memory_min_mib": 2048}) + ); + + let bad_nat = json!({"cpus": 4, "memory_mib": 8192, "shared_nat": "off"}).to_string(); + match save_resources(bad_nat.as_bytes(), &path, 12, 32768, Some(64), None, None) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("shared_nat must be a boolean"), "{msg}"), + other => panic!("expected BadRequest for non-bool shared_nat, got {other:?}"), + } + + // Shrinking below current data.img size (128 GiB) is rejected with 400. + let shrink = json!({"cpus": 4, "memory_mib": 8192, "disk_gb": 96}).to_string(); + match save_resources(shrink.as_bytes(), &path, 12, 32768, Some(128), Some(128), None) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("disk_gb must be 128 to 1024"), "{msg}"), + other => panic!("expected BadRequest for shrink, got {other:?}"), + } + + // Below 64 GiB template floor, zero, negative, and oversized values are rejected. + for bad in [json!(0), json!(32), json!(-1), json!(2048), json!("128")] { + let raw = json!({"cpus": 4, "memory_mib": 8192, "disk_gb": bad}).to_string(); + match save_resources(raw.as_bytes(), &path, 12, 32768, Some(64), None, None) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("disk_gb must be"), "{msg}"), + other => panic!("expected BadRequest for {bad}, got {other:?}"), + } + } + + // Payload includes disk fields on macOS and omits them when None (Linux). + let mac = resources_payload(4, 8192, 4, 8192, true, 12, 32768, false, Some((128, 256, 128))); + assert_eq!(mac["disk_gb"], 256); + assert_eq!(mac["running_disk_gb"], 128); + assert_eq!(mac["min_disk_gb"], 128); + assert_eq!(mac["max_disk_gb"], 1024); + + let linux = resources_payload(4, 8192, 4, 8192, true, 12, 32768, false, None); + assert!(linux.get("disk_gb").is_none()); + assert!(linux.get("min_disk_gb").is_none()); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn host_gateway_extra_host_stores_placeholder_not_wsl_addr() { + let raw = vec!["myhost:host-gateway".to_owned(), "db:10.0.0.2".to_owned()]; + assert_eq!( + extra_hosts_from(&raw).unwrap(), + vec![format!("{}\tmyhost", super::super::ports::HOST_ADDR), "10.0.0.2\tdb".to_owned()] + ); + assert!(extra_hosts_from(&["bad:not-an-ip".to_owned()]).is_err()); + } + + #[test] + fn wsl_distro_is_recorded_from_caller_and_inferred_from_legacy_mounts() { + let empty = json!({}); + assert_eq!(created_wsl_distro(&Caller::Wsl("Debian".into()), Some("kiri"), &empty), Some("Debian".into())); + assert_eq!(created_wsl_distro(&Caller::Host, Some("Ubuntu"), &empty), Some("Ubuntu".into())); + assert_eq!( + created_wsl_distro( + &Caller::Host, + Some("kiri"), + &json!({"com.docker.compose.project.config_files": r"\\wsl.localhost\Ubuntu-24.04\home\simone\services\docker-compose.yml"}) + ), + Some("Ubuntu-24.04".into()) + ); + assert_eq!( + created_wsl_distro( + &Caller::Host, + Some("kiri"), + &json!({"com.docker.compose.project.working_dir": r"C:\Users\me\shop"}) + ), + None + ); + assert_eq!(created_wsl_distro(&Caller::Host, None, &empty), None); + assert_eq!(created_wsl_distro(&Caller::Container, Some("Ubuntu"), &empty), None); + assert_eq!(created_wsl_distro(&Caller::Wsl("../evil".into()), Some("kiri"), &empty), None); + + let base_spec = || -> super::super::engine::Spec { + serde_json::from_value(json!({ + "image": "alpine:1", "image_id": "sha256:0123", "entrypoint": [], "cmd": ["true"], "env": [], + "cwd": "/", "user": "", "auto_remove": false, "labels": {}, "network_mode": "bridge", + "restart": {"name": "no", "max_retries": 0}, + })) + .unwrap() + }; + assert!(serde_json::to_value(base_spec()).unwrap().get("wsl_distro").is_none(), "omitted when None"); + + let mut recorded = base_spec(); + recorded.wsl_distro = Some("Debian".into()); + assert_eq!(spec_wsl_distro(&recorded), Some("Debian".into())); + assert_eq!(serde_json::to_value(&recorded).unwrap()["wsl_distro"], "Debian"); + + let mut legacy = base_spec(); + legacy.mount_info = vec![json!({"Type": "bind", "Source": "/mnt/wsl/kiri/roots/Ubuntu-24.04/home/simone/services/data", "Destination": "/data"})]; + assert_eq!(spec_wsl_distro(&legacy), Some("Ubuntu-24.04".into())); + assert_eq!(spec_wsl_distro(&base_spec()), None); + + // End-to-end through Engine and GET /containers/json?all=1. + let root = std::env::temp_dir().join(format!("kiri-wsl-distro-api-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + let image = kiri_image::Image { + mirror: None, + name: "alpine:1".into(), + digest: "sha256:0123".into(), + index_digest: None, + config_digest: "sha256:0123".into(), + layers: Vec::new(), + size: 0, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + }; + engine.store.put_image(image.clone()).unwrap(); + let create_req = Request::internal( + "POST", + "/containers/create", + &[("name", "from-debian")], + serde_json::to_vec(&json!({"Image": "alpine:1", "Cmd": ["true"]})).unwrap(), + ); + create_by(&create_req, &engine, &Caller::Wsl("Debian".into())).unwrap(); + engine.create(Some("legacy-ubuntu".into()), legacy, &image).unwrap(); + engine.create(Some("plain-host".into()), base_spec(), &image).unwrap(); + + let rows = list(&Request::internal("GET", "/containers/json", &[("all", "1")], Vec::new()), &engine).unwrap(); + let by_name = |name: &str| { + rows.as_array() + .unwrap() + .iter() + .find(|r| r["Names"][0] == format!("/{name}")) + .cloned() + .unwrap() + }; + assert_eq!(by_name("from-debian")["KiriWslDistro"], "Debian"); + assert_eq!(by_name("legacy-ubuntu")["KiriWslDistro"], "Ubuntu-24.04"); + assert!(by_name("plain-host").get("KiriWslDistro").is_none()); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + + #[test] + fn stream_copy_out_paces_chunks_and_rejects_oversized_frames() { + use std::io::{Read, Write}; + use std::os::unix::net::UnixStream; + + let (mut host_copy, mut guest_copy) = UnixStream::pair().unwrap(); + let (mut api_client, mut api_server) = UnixStream::pair().unwrap(); + let payload: Vec = (0..(150 * 1024)).map(|i| (i % 251) as u8).collect(); + let expected = payload.clone(); + + let guest = std::thread::spawn(move || { + for chunk in payload.chunks(COPY_OUT_CHUNK) { + let mut ack = [0u8; 1]; + guest_copy.read_exact(&mut ack).unwrap(); + assert_eq!(ack[0], 1); + guest_copy.write_all(&(chunk.len() as u32).to_le_bytes()).unwrap(); + guest_copy.write_all(chunk).unwrap(); + } + let mut ack = [0u8; 1]; + guest_copy.read_exact(&mut ack).unwrap(); + guest_copy.write_all(&0u32.to_le_bytes()).unwrap(); + }); + + let server = std::thread::spawn(move || { + super::stream_copy_out(&mut host_copy, &mut api_server, true).unwrap(); + http::end(&mut api_server).unwrap(); + }); + + let mut raw = Vec::new(); + api_client.read_to_end(&mut raw).unwrap(); + guest.join().unwrap(); + server.join().unwrap(); + + // Decode HTTP chunked response body and verify exact payload. + let mut decoded = Vec::new(); + let mut pos = 0; + loop { + let line_end = raw[pos..].windows(2).position(|w| w == b"\r\n").unwrap() + pos; + let len_str = std::str::from_utf8(&raw[pos..line_end]).unwrap(); + let len = usize::from_str_radix(len_str, 16).unwrap(); + pos = line_end + 2; + if len == 0 { + assert_eq!(&raw[pos..], b"\r\n"); + break; + } + assert!(len <= COPY_OUT_CHUNK); + decoded.extend_from_slice(&raw[pos..pos + len]); + pos += len; + assert_eq!(&raw[pos..pos + 2], b"\r\n"); + pos += 2; + } + assert_eq!(decoded, expected); + + // Oversized paced chunk header (or BE Msg::Error frame) is rejected cleanly. + let (mut host_bad, mut guest_bad) = UnixStream::pair().unwrap(); + let mut sink = Vec::new(); + let bad_guest = std::thread::spawn(move || { + let mut ack = [0u8; 1]; + guest_bad.read_exact(&mut ack).unwrap(); + guest_bad.write_all(&((COPY_OUT_CHUNK as u32) + 1).to_le_bytes()).unwrap(); + }); + let err = super::stream_copy_out(&mut host_bad, &mut sink, true).unwrap_err(); + bad_guest.join().unwrap(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + } + + #[test] + fn bind_mount_preparation_never_creates_localtime_or_timezone_directory() { + let root = std::env::temp_dir().join(format!("kiri-api-localtime-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("etc")).unwrap(); + + // `--mount type=bind` (`create_missing = false`) refuses missing /etc/localtime without creating a directory. + let err = super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/localtime", false, true, None).unwrap_err(); + assert!(matches!(err, super::Error::BadRequest(ref m) if m.contains("bind source path does not exist")), "{err:?}"); + assert!(std::fs::symlink_metadata(root.join("etc/localtime")).is_err()); + + // `-v /etc/localtime:/etc/localtime:ro` (`create_missing = true`) creates a valid TZif2 file, never a directory. + super::prepare_bind_source_at(&root, "/etc/localtime", "/etc//localtime", true, true, None).unwrap(); + let lt = root.join("etc/localtime"); + assert!(std::fs::symlink_metadata(<).unwrap().file_type().is_file()); + let bytes = std::fs::read(<).unwrap(); + assert!(bytes.starts_with(b"TZif2") && bytes.ends_with(b"\nUTC0\n")); + + // Existing empty directory at /etc/localtime is repaired into a file for both `-v` and `--mount`. + std::fs::remove_file(<).unwrap(); + std::fs::create_dir(<).unwrap(); + super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/./localtime", false, true, None).unwrap(); + assert!(std::fs::symlink_metadata(<).unwrap().file_type().is_file()); + + // Non-empty directory at /etc/localtime is refused without deleting its contents. + std::fs::remove_file(<).unwrap(); + std::fs::create_dir(<).unwrap(); + std::fs::write(lt.join("keep"), b"keep").unwrap(); + assert!(super::prepare_bind_source_at(&root, "/etc/localtime", "/etc/localtime", true, true, None).is_err()); + assert_eq!(std::fs::read(lt.join("keep")).unwrap(), b"keep"); + std::fs::remove_dir_all(<).unwrap(); + + // `-v /etc/timezone:/etc/timezone:ro` creates/repairs a regular file, never a directory. + let tz = root.join("etc/timezone"); + let _ = std::fs::remove_file(&tz); + super::prepare_bind_source_at(&root, "/etc/timezone", "/etc/timezone", true, true, Some("Asia/Shanghai")).unwrap(); + assert!(std::fs::symlink_metadata(&tz).unwrap().file_type().is_file()); + assert_eq!(std::fs::read_to_string(&tz).unwrap(), "Asia/Shanghai\n"); + + // Regular missing bind paths still become directories under `-v`. + super::prepare_bind_source_at(&root, "/srv/app", "/srv/app", true, true, None).unwrap(); + assert!(root.join("srv/app").is_dir()); + + let _ = std::fs::remove_dir_all(&root); + } + + /// Settings → Resources keeps the VM's swap (#326): 0 to 16 GiB, kept + /// when a save leaves it out. + #[test] + fn swap_is_saved_checked_and_kept() { + let dir = std::env::temp_dir().join(format!("kiri-res-swap-{}", std::process::id())); + let path = dir.join("vm.json"); + let _ = std::fs::remove_dir_all(&dir); + let save = |body: Value| save_resources(body.to_string().as_bytes(), &path, 12, 32768, Some(64), None, None); + let saved = || serde_json::from_slice::(&std::fs::read(&path).unwrap()).unwrap(); + + save(json!({"cpus": 4, "memory_mib": 8192, "swap_mib": 2048})).unwrap(); + assert_eq!(saved()["swap_mib"], 2048); + save(json!({"cpus": 4, "memory_mib": 4096})).unwrap(); + assert_eq!(saved()["swap_mib"], 2048, "left out, the swap stays"); + save(json!({"cpus": 4, "memory_mib": 4096, "swap_mib": 0})).unwrap(); + assert_eq!(saved()["swap_mib"], 0, "0 is no swap"); + for bad in [json!(-1), json!(16 * 1024 + 1), json!("1024"), json!(1.5)] { + match save(json!({"cpus": 4, "memory_mib": 4096, "swap_mib": bad})) { + Err(Error::BadRequest(msg)) => assert!(msg.contains("swap_mib must be 0 to 16384"), "{msg}"), + other => panic!("expected BadRequest for {bad}, got {other:?}"), + } + } + assert_eq!(saved()["swap_mib"], 0, "a refused save changes nothing"); + + let mut v = json!({}); + swap_payload(&mut v, 2048, 1024); + assert_eq!(v, json!({"swap_mib": 2048, "running_swap_mib": 1024, "max_swap_mib": 16384})); + let _ = std::fs::remove_dir_all(dir); + } +} diff --git a/crates/kiri/src/daemon/binds.rs b/crates/kiri/src/daemon/binds.rs index e77fb0b78..b45b0abe5 100644 --- a/crates/kiri/src/daemon/binds.rs +++ b/crates/kiri/src/daemon/binds.rs @@ -8,6 +8,125 @@ use std::sync::OnceLock; use super::engine::Error; +/// Shared `/mnt/wsl/kiri` directory across all WSL 2 distros. +pub const WSL_KIRI_DIR: &str = "/mnt/wsl/kiri"; + +/// Active WSL integration base directory (`KIRI_WSL_DIR` override or `/mnt/wsl/kiri`). +pub fn wsl_kiri_dir() -> String { + std::env::var("KIRI_WSL_DIR") + .ok() + .map(|s| s.trim_end_matches('/').to_owned()) + .filter(|s| s.starts_with('/')) + .unwrap_or_else(|| WSL_KIRI_DIR.to_owned()) +} + +fn wsl_roots_dir() -> String { + format!("{}/roots", wsl_kiri_dir()) +} + +fn wsl_sockets_dir() -> String { + format!("{}/sockets", wsl_kiri_dir()) +} + +/// Whether `name` is a safe single-component WSL distro name. +pub fn valid_distro_name(name: &str) -> bool { + !name.is_empty() + && name != "." + && name != ".." + && !name.contains(['/', '\\', '\0']) + && !name.bytes().any(|b| b.is_ascii_control()) +} + +/// Normalizes a path into `/a/b/c`, clamping `..` at `/` so traversal can never +/// climb above the root. +fn lexical_clean(p: &str) -> String { + let mut out: Vec<&str> = Vec::new(); + for c in p.split('/') { + match c { + "" | "." => {} + ".." => { + out.pop(); + } + c => out.push(c), + } + } + format!("/{}", out.join("/")) +} + +/// Joins `inner` under `root` (`/mnt/wsl/kiri/roots/`), clamping any +/// `..` traversal so the result cannot escape `root`. +pub fn confine_to_root(root: &str, inner: &str) -> String { + let root = root.trim_end_matches('/'); + let rel = lexical_clean(inner); + if rel == "/" { + root.to_owned() + } else { + format!("{root}{rel}") + } +} + +/// When `distro_root` exists on disk, verifies that no existing symlink along +/// `target` escapes `distro_root`. +fn verify_on_disk_confinement(src: &str, distro: &str, distro_root: &Path, target: &Path) -> Result<(), Error> { + if !distro_root.exists() { + return Ok(()); + } + let Ok(canon_root) = std::fs::canonicalize(distro_root) else { + return Ok(()); + }; + let Ok(rel) = target.strip_prefix(distro_root) else { + return Err(Error::BadRequest(format!("invalid mount source {src}: escapes WSL distro {distro}"))); + }; + let mut cur = distro_root.to_path_buf(); + for comp in rel.components() { + cur.push(comp); + if let Ok(link) = std::fs::read_link(&cur) { + let link_str = link.to_string_lossy(); + if !cur.exists() && (link.is_absolute() || link_str.split('/').any(|c| c == "..")) { + return Err(Error::BadRequest(format!("invalid mount source {src}: escapes WSL distro {distro}"))); + } + } + if cur.exists() { + let canon = std::fs::canonicalize(&cur).map_err(Error::Io)?; + if !canon.starts_with(&canon_root) { + return Err(Error::BadRequest(format!("invalid mount source {src}: escapes WSL distro {distro}"))); + } + } + } + Ok(()) +} + +/// Finds `/roots/` on disk if `` is integrated and mounted. +fn mounted_distro_root(distro: &str) -> Option { + if !valid_distro_name(distro) { + return None; + } + let roots_dir = wsl_roots_dir(); + let exact = format!("{roots_dir}/{distro}"); + if Path::new(&exact).is_dir() { + return Some(exact); + } + let entries = std::fs::read_dir(&roots_dir).ok()?; + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name) = name.to_str() else { continue }; + if name.eq_ignore_ascii_case(distro) && entry.path().is_dir() { + return Some(entry.path().to_string_lossy().into_owned()); + } + } + None +} + +fn is_wsl_engine_socket(p: &str) -> bool { + let sockets_dir = wsl_sockets_dir(); + let matches_prefix = |prefix: &str| { + p.strip_prefix(prefix) + .and_then(|rest| rest.strip_suffix("/docker.sock")) + .is_some_and(valid_distro_name) + }; + matches_prefix(&format!("{sockets_dir}/")) || matches_prefix(&format!("{WSL_KIRI_DIR}/sockets/")) +} + /// Where WSL mounts the Windows drives, and which distro the daemon runs in. #[derive(Debug, Clone, PartialEq)] pub struct Wsl { @@ -83,14 +202,20 @@ fn distro_of(unc: &str) -> Option { /// One `-v` spec (HostConfig.Binds) as source, target and options. In WSL a /// drive letter's colon belongs to the source (`C:\src:/app:ro`), and the /// source is made a path in this Linux. +#[cfg(test)] pub fn split(spec: &str, wsl: Option<&Wsl>) -> Result<(String, String, String), Error> { + split_for(spec, wsl, None) +} + +/// [`split`], translating Linux paths from an integrated WSL distro +/// (`wsl_distro = Some("")`) into `/mnt/wsl/kiri/roots//…`. +pub fn split_for(spec: &str, wsl: Option<&Wsl>, wsl_distro: Option<&str>) -> Result<(String, String, String), Error> { let bad = || Error::BadRequest(format!("invalid volume specification: {spec}")); // `c:/app` is the volume `c` at /app, as in moby's Windows parser: a // drive is the source only when an absolute target follows it. - let skip = match wsl { - Some(_) if spec[drive_prefix(spec)..].split(':').nth(1).is_some_and(|d| d.starts_with('/')) => drive_prefix(spec), - _ => 0, - }; + let has_drive = (wsl.is_some() || wsl_distro.is_some()) + && spec[drive_prefix(spec)..].split(':').nth(1).is_some_and(|d| d.starts_with('/')); + let skip = if has_drive { drive_prefix(spec) } else { 0 }; let Some(i) = spec[skip..].find(':').map(|i| skip + i) else { return Err(bad()) }; let (src, rest) = (&spec[..i], &spec[i + 1..]); let (dst, opts) = match rest.split(':').collect::>().as_slice() { @@ -98,14 +223,121 @@ pub fn split(spec: &str, wsl: Option<&Wsl>) -> Result<(String, String, String), [d, o] => (*d, *o), _ => return Err(bad()), }; - let src = match wsl { + let src = match (wsl, wsl_distro) { + (_, Some(d)) if src.starts_with('/') || looks_windows(src) => distro_source(src, d, wsl)?, // A volume name stays a name; only paths are translated. - Some(w) if looks_windows(src) => source(src, w)?, + (Some(w), None) if looks_windows(src) => source(src, w)?, _ => src.to_owned(), }; Ok((src, dst.to_owned(), opts.to_owned())) } +/// Translates a bind mount source from an integrated WSL distro ``: +/// - `/var/run/docker.sock` (and engine socket aliases) stays the engine socket +/// - `/mnt/c/proj` (under the Windows automount root) stays `/mnt/c/proj` +/// - `/home/alice/app` becomes `/mnt/wsl/kiri/roots//home/alice/app` +/// - `..` traversal is confined so it can never escape ``'s root +pub fn distro_source(src: &str, distro: &str, wsl: Option<&Wsl>) -> Result { + if !valid_distro_name(distro) { + return Err(Error::BadRequest(format!("invalid WSL distro: {distro}"))); + } + let kiri_dir = wsl_kiri_dir(); + let roots_dir = format!("{kiri_dir}/roots"); + if looks_windows(src) { + let default_wsl = Wsl { root: "/mnt/".into(), distro: None }; + let w = wsl.unwrap_or(&default_wsl); + return source_with_roots(src, w, |d| { + if d.eq_ignore_ascii_case(distro) { + Some(format!("{roots_dir}/{distro}")) + } else { + mounted_distro_root(d) + } + }); + } + if !src.starts_with('/') { + return Ok(src.to_owned()); + } + let distro_root = format!("{roots_dir}/{distro}"); + let cleaned = clean(src); + if ENGINE_SOCKS.contains(&cleaned.as_str()) || is_wsl_engine_socket(&cleaned) { + return Ok(cleaned); + } + if cleaned == distro_root || cleaned.strip_prefix(&distro_root).is_some_and(|r| r.starts_with('/')) { + let rest = cleaned.strip_prefix(&distro_root).unwrap_or(""); + let target = confine_to_root(&distro_root, rest); + verify_on_disk_confinement(src, distro, Path::new(&distro_root), Path::new(&target))?; + return Ok(target); + } + let lex = lexical_clean(src); + if ENGINE_SOCKS.contains(&lex.as_str()) || is_wsl_engine_socket(&lex) { + return Ok(lex); + } + let is_internal_wsl = |p: &str| { + p == kiri_dir + || p.starts_with(&format!("{kiri_dir}/")) + || p == WSL_KIRI_DIR + || p.starts_with(&format!("{WSL_KIRI_DIR}/")) + }; + if is_internal_wsl(&lex) { + return Err(Error::BadRequest(format!( + "invalid mount source {src}: cannot mount Kiri's internal WSL directory" + ))); + } + let mnt = wsl.map_or("/mnt/", |w| w.root.as_str()); + let mnt_trimmed = mnt.trim_end_matches('/'); + let on_drive = |p: &str| (!mnt_trimmed.is_empty() && (p == mnt_trimmed || p.starts_with(mnt))) && p != "/mnt/wsl" && !is_internal_wsl(p); + if on_drive(&lex) { + return Ok(lex); + } + // An absolute link in the distro (`/etc/localtime -> /usr/share/zoneinfo/...`) + // means the distro's own file: follow it inside the distro's root. With + // only relative links on the way the source stays as given; the kernel + // follows those inside the root itself. + let target = match resolve_in_root(Path::new(&distro_root), &lex) { + Some((inside, true)) if on_drive(&inside) => return Ok(inside), + Some((inside, true)) => confine_to_root(&distro_root, &inside), + Some((_, false)) => confine_to_root(&distro_root, &lex), + None => return Err(Error::BadRequest(format!("invalid mount source {src}: too many levels of symbolic links"))), + }; + verify_on_disk_confinement(src, distro, Path::new(&distro_root), Path::new(&target))?; + Ok(target) +} + +/// `path` (absolute, in a distro whose `/` is `root` on disk) with every +/// symlink on the way followed as the distro would: an absolute target +/// from `root`, `..` stopping at it. The path returned is the distro's +/// spelling, with whether an absolute link was on the way; None after 40 +/// links, as Linux gives up. +fn resolve_in_root(root: &Path, path: &str) -> Option<(String, bool)> { + if !root.is_dir() { + return Some((lexical_clean(path), false)); + } + let parts = |p: &str| p.split('/').filter(|c| !c.is_empty() && *c != ".").map(str::to_owned).rev().collect::>(); + let (mut todo, mut done, mut links, mut absolute) = (parts(path), Vec::::new(), 0, false); + while let Some(c) = todo.pop() { + if c == ".." { + done.pop(); + continue; + } + match std::fs::read_link(root.join(done.join("/")).join(&c)) { + Ok(link) => { + links += 1; + if links > 40 { + return None; + } + let link = link.to_string_lossy().into_owned(); + if link.starts_with('/') { + done.clear(); + absolute = true; + } + todo.extend(parts(&link)); + } + Err(_) => done.push(c), + } + } + Some((format!("/{}", done.join("/")), absolute)) +} + /// How many leading bytes hold a colon that is not a separator: `C:` and /// `\\?\C:` (moby's Windows parser allows both). fn drive_prefix(spec: &str) -> usize { @@ -130,6 +362,10 @@ fn looks_windows(src: &str) -> bool { /// Anything else (a network share, another distro's files, a relative /// path) is refused: WSL can't reach it as a path here. pub fn source(src: &str, wsl: &Wsl) -> Result { + source_with_roots(src, wsl, mounted_distro_root) +} + +pub fn source_with_roots(src: &str, wsl: &Wsl, distro_root: impl Fn(&str) -> Option) -> Result { let bad = |why: &str| Error::BadRequest(format!("invalid mount source {src}: {why}")); if !looks_windows(src) { return Ok(src.to_owned()); @@ -152,6 +388,11 @@ pub fn source(src: &str, wsl: &Wsl) -> Result { return Err(bad("no WSL distro named")); } if let Some(ours) = wsl.distro.as_deref().filter(|d| !d.eq_ignore_ascii_case(distro)) { + if let Some(root) = distro_root(distro) { + let target = confine_to_root(&root, inner); + verify_on_disk_confinement(src, distro, Path::new(&root), Path::new(&target))?; + return Ok(target); + } return Err(bad(&format!("it is in the WSL distro {distro}, and Kiri runs in {ours}; use a path on a Windows drive or in {ours}"))); } return Ok(clean(&format!("/{inner}"))); @@ -166,9 +407,44 @@ pub fn source(src: &str, wsl: &Wsl) -> Result { Err(bad("Kiri's WSL can reach the Windows drives (C:\\…) and its own files, not network shares or devices")) } -/// A path on drive `letter`, under WSL's automount root. +/// A path on drive `letter`, under WSL's automount root. `..` stops at the +/// drive's root, as Windows resolves `C:\..` to `C:\`. fn drive(wsl: &Wsl, letter: u8, rest: &str) -> String { - clean(&format!("{}{}/{}", wsl.root, letter.to_ascii_lowercase() as char, rest.replace('\\', "/"))) + confine_to_root(&format!("{}{}", wsl.root, letter.to_ascii_lowercase() as char), &rest.replace('\\', "/")) +} + +/// Whether `path` is under WSL's automount root (`/...`, +/// or `` when `allow_drive_root` is true), with no +/// control characters and no `.` or `..` traversal components. +pub fn is_wsl_drive_path(path: &str, automount_root: &str, allow_drive_root: bool) -> bool { + if !automount_root.starts_with('/') || !automount_root.ends_with('/') { + return false; + } + if path.contains(['\n', '\r', '\0']) { + return false; + } + let Some(rest) = path.strip_prefix(automount_root) else { return false }; + let bytes = rest.as_bytes(); + if bytes.is_empty() || !bytes[0].is_ascii_alphabetic() { + return false; + } + if bytes.len() == 1 { + return allow_drive_root; + } + if bytes[1] != b'/' { + return false; + } + let mut has_component = false; + for part in rest[2..].split('/') { + if part.is_empty() { + continue; + } + if part == "." || part == ".." { + return false; + } + has_component = true; + } + has_component || allow_drive_root } /// Single slashes, none at the end. @@ -232,27 +508,63 @@ pub fn real(p: &str) -> Option { pub fn engine_socket(src: &str) -> Option { let own = super::socket_path().ok()?; let own = own.to_string_lossy(); - engine_socket_for(src, &own, real) + let alias = if std::env::var_os("KIRI_SOCKET").is_none() { + super::home_socket_path().ok().filter(|p| p.as_os_str() != own.as_ref()) + } else { + None + }; + let alias = alias.as_deref().and_then(|p| p.to_str()); + engine_socket_with_alias(src, &own, alias, real) +} + +/// [`engine_socket`] for a create request that arrived from `wsl_distro`: +/// inside an integrated WSL distro, `/var/run/docker.sock` (and `/run/docker.sock`) +/// refers to Kiri's engine socket regardless of whether the host or engine +/// distro has another socket at `/var/run/docker.sock`. +pub fn engine_socket_for_distro(src: &str, wsl_distro: Option<&str>) -> Option { + if wsl_distro.is_some() { + let text = clean(src); + if ENGINE_SOCKS.contains(&text.as_str()) || is_wsl_engine_socket(&text) { + let own = super::socket_path().ok()?; + #[cfg(target_os = "macos")] + { + let _ = own; + return Some(VM_ENGINE_SOCK.to_owned()); + } + #[cfg(not(target_os = "macos"))] + return Some(super::caller::container_socket(&own).to_string_lossy().into_owned()); + } + } + engine_socket(src) } /// [`engine_socket`], with `resolve` giving where a path that exists /// really is. The path as given is followed first, as the kernel will /// follow it; only a path that is not there is compared as text. +#[cfg(test)] fn engine_socket_for(src: &str, own: &str, resolve: impl Fn(&str) -> Option) -> Option { + engine_socket_with_alias(src, own, None, resolve) +} + +fn engine_socket_with_alias(src: &str, own: &str, alias: Option<&str>, resolve: impl Fn(&str) -> Option) -> Option { let found = resolve(src); - let is_own = found.as_ref().zip(resolve(own)).is_some_and(|(a, b)| a.same(&b)); let text = clean(src); + let matches_text = |p: &str| text == clean(p); + let is_own = found.as_ref().is_some_and(|a| { + resolve(own).is_some_and(|b| a.same(&b)) || alias.and_then(&resolve).is_some_and(|b| a.same(&b)) + }) || is_wsl_engine_socket(&text) + || found.as_ref().is_some_and(|r| is_wsl_engine_socket(&r.path)); #[cfg(target_os = "macos")] { let named = ENGINE_SOCKS.contains(&text.as_str()) || found.as_ref().is_some_and(|r| ENGINE_SOCKS.contains(&r.path.as_str())); - (is_own || named || text == clean(own)).then(|| VM_ENGINE_SOCK.to_owned()) + (is_own || named || matches_text(own) || alias.is_some_and(matches_text)).then(|| VM_ENGINE_SOCK.to_owned()) } #[cfg(not(target_os = "macos"))] { let given = || super::caller::container_socket(Path::new(own)).to_string_lossy().into_owned(); match found { Some(_) => is_own.then(given), - None => (text == clean(own) || ENGINE_SOCKS.contains(&text.as_str())).then(given), + None => (is_own || matches_text(own) || alias.is_some_and(matches_text) || ENGINE_SOCKS.contains(&text.as_str())).then(given), } } } @@ -266,6 +578,16 @@ fn engine_socket_for(src: &str, own: &str, resolve: impl Fn(&str) -> Option std::io::Result<()> { + #[cfg(target_os = "linux")] + if path.is_absolute() { + let norm = lexical_clean(&path.to_string_lossy()); + if norm == "/etc/localtime" { + return super::localtime::ensure_localtime(); + } + if norm == "/etc/timezone" { + return super::localtime::ensure_timezone(); + } + } use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; let missing: Vec<&Path> = path.ancestors().take_while(|a| std::fs::symlink_metadata(a).is_err_and(|e| e.kind() == std::io::ErrorKind::NotFound)).collect(); if missing.is_empty() { @@ -514,8 +836,111 @@ mod tests { let raw = fake(&spelled, &[]); let raw = |p: &str| if p == "/tmp/l//../kiri/docker.sock" || p == own { raw(p) } else { None }; assert_eq!(engine_socket_for("/tmp/l//../kiri/docker.sock", own, raw).as_deref(), given); + // Compatibility home socket alias alongside /run/kiri/docker.sock also maps to the container socket. + let home_alias = "/root/.kiri/run/docker.sock"; + assert_eq!(engine_socket_with_alias(home_alias, own, Some(home_alias), &itself).as_deref(), given); } assert_eq!(engine_socket_for("/srv/app.sock", "/x/docker.sock", none), None); assert_eq!(engine_socket_for("/srv/app.sock", "/x/docker.sock", &itself), None); } + + #[test] + fn wsl_drive_path_validation() { + assert!(is_wsl_drive_path("/mnt/c/Users/me/app", "/mnt/", false)); + assert!(is_wsl_drive_path("/mnt/c", "/mnt/", true)); + assert!(!is_wsl_drive_path("/mnt/c", "/mnt/", false)); + assert!(!is_wsl_drive_path("/mnt/c/", "/mnt/", false)); + assert!(!is_wsl_drive_path("/mnt/mac/Users/a", "/mnt/", true)); + assert!(!is_wsl_drive_path("/etc/passwd", "/mnt/", true)); + assert!(!is_wsl_drive_path("/mnt/c/../etc/passwd", "/mnt/", true)); + assert!(!is_wsl_drive_path("/mnt/c/a\nb", "/mnt/", true)); + assert!(is_wsl_drive_path("/windows/d/proj", "/windows/", false)); + } + + #[test] + fn wsl_distro_path_translation_and_confinement() { + let w = wsl(); + assert_eq!( + split_for("/home/me/app:/app", Some(&w), Some("Ubuntu")).unwrap(), + t("/mnt/wsl/kiri/roots/Ubuntu/home/me/app", "/app", "") + ); + assert_eq!( + split_for("/home/me/app:/app:ro", None, Some("Ubuntu")).unwrap(), + t("/mnt/wsl/kiri/roots/Ubuntu/home/me/app", "/app", "ro") + ); + assert_eq!( + split_for("/mnt/c/proj:/app", Some(&w), Some("Ubuntu")).unwrap(), + t("/mnt/c/proj", "/app", "") + ); + assert_eq!( + split_for("/var/run/docker.sock:/var/run/docker.sock", Some(&w), Some("Ubuntu")).unwrap(), + t("/var/run/docker.sock", "/var/run/docker.sock", "") + ); + assert_eq!( + split_for("/run/docker.sock:/var/run/docker.sock", Some(&w), Some("Ubuntu")).unwrap(), + t("/run/docker.sock", "/var/run/docker.sock", "") + ); + assert_eq!( + split_for("myvol:/data", Some(&w), Some("Ubuntu")).unwrap(), + t("myvol", "/data", "") + ); + // `..` traversal confinement: cannot escape ``'s root. + for traversal in [ + "/mnt/wsl/kiri/roots/Ubuntu/../../etc", + "/mnt/wsl/kiri/roots/Ubuntu/../../../../etc", + "/../../etc", + "/home/me/../../../etc", + "/mnt/c/../../etc", + ] { + assert_eq!( + distro_source(traversal, "Ubuntu", Some(&w)).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/etc", + "{traversal}" + ); + } + // Mounting another distro's root or Kiri's internal WSL dir is refused. + assert!(distro_source("/mnt/wsl/kiri/roots/Debian/etc", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source("/mnt/wsl/kiri/sockets/Ubuntu", "Ubuntu", Some(&w)).is_err()); + assert!(distro_source("/home/me", "../evil", Some(&w)).is_err()); + + // From Windows: `\\wsl.localhost\\...` is allowed when ``'s root is mounted. + let with_ubuntu = |d: &str| d.eq_ignore_ascii_case("Ubuntu").then(|| "/mnt/wsl/kiri/roots/Ubuntu".to_owned()); + assert_eq!( + source_with_roots(r"\\wsl.localhost\Ubuntu\home\alice\app", &w, with_ubuntu).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/home/alice/app" + ); + assert_eq!( + source_with_roots(r"\\wsl$\ubuntu\home\alice\..\..\etc", &w, with_ubuntu).unwrap(), + "/mnt/wsl/kiri/roots/Ubuntu/etc" + ); + assert!(source_with_roots(r"\\wsl.localhost\Debian\home\alice", &w, with_ubuntu).is_err()); + } + + #[test] + fn dotdot_on_a_drive_stops_at_its_root() { + assert_eq!(ok(r"C:\..\..\etc:/x:ro"), t("/mnt/c/etc", "/x", "ro")); + assert_eq!(ok("//c/../../etc:/x"), t("/mnt/c/etc", "/x", "")); + assert_eq!(ok(r"C:\Users\me\proj\..\other:/x"), t("/mnt/c/Users/me/other", "/x", "")); + } + + #[test] + fn a_link_in_a_distro_is_followed_inside_it() { + let root = std::env::temp_dir().join(format!("kiri-binds-distro-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("usr/share/zoneinfo/Europe")).unwrap(); + std::fs::create_dir_all(root.join("etc")).unwrap(); + std::fs::write(root.join("usr/share/zoneinfo/Europe/Berlin"), b"TZif").unwrap(); + std::os::unix::fs::symlink("/usr/share/zoneinfo/Europe/Berlin", root.join("etc/localtime")).unwrap(); + std::os::unix::fs::symlink("../../../..", root.join("etc/up")).unwrap(); + std::os::unix::fs::symlink("/mnt/c/Users/me", root.join("etc/win")).unwrap(); + std::os::unix::fs::symlink("loop", root.join("loop")).unwrap(); + let followed = |p: &str| resolve_in_root(&root, p); + assert_eq!(followed("/etc/localtime").unwrap(), ("/usr/share/zoneinfo/Europe/Berlin".to_owned(), true)); + assert_eq!(followed("/etc/up/etc").unwrap(), ("/etc".to_owned(), false)); + assert_eq!(followed("/etc/win/src").unwrap(), ("/mnt/c/Users/me/src".to_owned(), true)); + assert_eq!(followed("/home/me/app").unwrap(), ("/home/me/app".to_owned(), false)); + assert_eq!(followed("/loop"), None); + assert_eq!(resolve_in_root(&root.join("missing"), "/etc/../x").unwrap(), ("/x".to_owned(), false)); + let _ = std::fs::remove_dir_all(&root); + } } diff --git a/crates/kiri/src/daemon/builder.rs b/crates/kiri/src/daemon/builder.rs index 00e984788..ef49b1f31 100644 --- a/crates/kiri/src/daemon/builder.rs +++ b/crates/kiri/src/daemon/builder.rs @@ -105,11 +105,15 @@ fn default_cache(disk: u64) -> u64 { if disk == 0 { 20 * GB } else { (disk / 10).clamp(GB, 20 * GB) } } +fn cache_limit_from(gb: Option, disk: impl FnOnce() -> u64) -> u64 { + gb.filter(|g| *g > 0).map_or_else(|| default_cache(disk()), |g| g.saturating_mul(GB)) +} + /// The build cache's cap in bytes: `KIRI_BUILD_CACHE_GB`, else Settings, /// else [`default_cache`]. BuildKit's garbage collector keeps the cache under it. pub fn cache_limit() -> u64 { let gb = std::env::var("KIRI_BUILD_CACHE_GB").ok().and_then(|v| v.parse::().ok()).or_else(|| settings()["cache_gb"].as_u64()); - gb.filter(|g| *g > 0).map_or_else(|| default_cache(disk_total()), |g| g * GB) + cache_limit_from(gb, disk_total) } /// Seconds without a build before the builder stops: `KIRI_BUILDER_IDLE_SECS`, @@ -193,9 +197,11 @@ fn ensure_image(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result Value { - json!({ +/// buildkitd flag), without a restart policy, since it starts on demand, +/// keeping network, DNS and environment options when buildx creates the +/// builder container (`--driver-opt network=host`, `env.*`, #209). +fn create_body_from(requested: Option<&Value>) -> Value { + let mut body = json!({ "Image": IMAGE, "Cmd": ["--allow-insecure-entitlement=network.host"], "Labels": {LABEL: "1"}, @@ -204,13 +210,32 @@ fn create_body() -> Value { "Mounts": [{"Type": "volume", "Source": volume_name(), "Target": "/var/lib/buildkit"}], "RestartPolicy": {"Name": "no"}, }, - }) + }); + if let Some(req) = requested { + if let Some(env) = req.get("Env").filter(|v| v.is_array()) { + body["Env"] = env.clone(); + } + let host = &req["HostConfig"]; + if let Some(mode) = host["NetworkMode"].as_str().filter(|m| !m.is_empty() && *m != "default") { + body["HostConfig"]["NetworkMode"] = json!(mode); + } + for key in ["Dns", "DnsSearch", "DnsOptions", "ExtraHosts"] { + if let Some(val) = host.get(key).filter(|v| v.is_array()) { + body["HostConfig"][key] = val.clone(); + } + } + } + body } fn create(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result { + create_with(engine, None, say) +} + +fn create_with(engine: &Engine, requested: Option<&Value>, say: &mut dyn FnMut(&str)) -> Result { ensure_image(engine, say)?; let name = container_name(); - let req = Request::internal("POST", "/containers/create", &[("name", &name)], create_body().to_string().into_bytes()); + let req = Request::internal("POST", "/containers/create", &[("name", &name)], create_body_from(requested).to_string().into_bytes()); let made = api::create(&req, engine)?; crate::diag::info!("builder created", name = name); let id = made["Id"].as_str().unwrap_or_default().to_owned(); @@ -257,28 +282,36 @@ fn start_with( } /// What the builder's registry tables come from: daemon.json's settings, -/// and the registries the store's images came from that those settings -/// reach without verified TLS (a network entry covers a registry only once -/// an image from it is pulled). +/// the registries mirrored from Kiri's store, those reached without verified +/// TLS, and whether the builder runs on the host network. #[derive(Debug, PartialEq)] struct Registries { config: std::sync::Arc, + mirrored: Vec, unverified: Vec, + host_net: bool, } impl Registries { - fn now(names: &[String]) -> Registries { + fn now(names: &[String], host_net: bool) -> Registries { let config = super::daemon_json::current(); + let mut mirrored = names.to_vec(); + mirrored.sort(); + mirrored.dedup(); let unverified = super::mirror::unverified(&config, names); - Registries { config, unverified } + Registries { config, mirrored, unverified, host_net } } } +pub(super) fn builder_host_net(engine: &Engine, id: &str) -> bool { + engine.with(id, |c| c.spec.network_mode == "host").unwrap_or(false) +} + /// [`Registries`] as the builder's config last had them, so a hand edit, or -/// an image pulled from a registry inside a listed network, reaches a -/// running builder at the next build. `None` until this daemon has written -/// the file: a builder found running then (left from before the daemon -/// started) may have anything, and is treated as stale. +/// an image pulled from a new registry, reaches a running builder at the next +/// build. `None` until this daemon has written the file: a builder found +/// running then (left from before the daemon started) may have anything, and +/// is treated as stale. static WRITTEN: std::sync::Mutex>> = std::sync::Mutex::new(None); /// Whether a running builder's registry settings are not today's. @@ -290,8 +323,9 @@ fn is_stale(written: Option<&Registries>, current: &Registries) -> bool { /// start. [`WRITTEN`] says so only once the file is in place. fn write_config(engine: &Engine, id: &str) -> Result<(), Error> { let names = super::mirror::registry_names(engine); - let current = Registries::now(&names); - let toml = config_toml(cache_limit(), &super::mirror::config(engine, ¤t.config, &names)); + let host_net = builder_host_net(engine, id); + let current = Registries::now(&names, host_net); + let toml = config_toml(cache_limit(), &super::mirror::config_for(engine, ¤t.config, &names, host_net)); let archive = tar(&[("buildkit/", None), ("buildkit/buildkitd.toml", Some(toml.as_bytes()))]); let written = copy_in(engine, id, "/etc", &mut io::Cursor::new(archive)); *WRITTEN.lock().unwrap_or_else(|e| e.into_inner()) = written.is_ok().then(|| std::sync::Arc::new(current)); @@ -391,10 +425,10 @@ enum Step { const STOP_THEN_WRITE: [Step; 3] = [Step::Resume, Step::Stop, Step::Write]; /// Whether the config the builder runs with is not today's: daemon.json -/// edited by hand, or a registry in a listed network pulled from, since it -/// was written. +/// edited by hand, or a new registry pulled into the store since it was written. fn stale_now(engine: &Engine) -> bool { - is_stale(WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_deref(), &Registries::now(&super::mirror::registry_names(engine))) + let host_net = find(engine).is_some_and(|(id, _)| builder_host_net(engine, &id)); + is_stale(WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_deref(), &Registries::now(&super::mirror::registry_names(engine), host_net)) } /// Whether a builder is restarted with today's config now: only one that is @@ -522,20 +556,37 @@ fn hide_amd64_qemu(engine: &Engine, id: &str) { /// ls`, `inspect`, the window's Builds view) makes and pulls nothing, so a /// fresh Kiri has no builder, image or cache volume until the first build. /// None for any other name, or when the builder exists (the usual 409). -pub fn create_for_buildx(engine: &Engine, name: Option<&str>) -> Option> { - if name.map(|n| n.trim_start_matches('/')) != Some(container_name().as_str()) { +pub fn create_for_buildx(engine: &Engine, req: &Request) -> Option> { + if req.query("name").map(|n| n.trim_start_matches('/')) != Some(container_name().as_str()) { return None; } + let requested = if req.body.is_empty() { + None + } else { + match serde_json::from_slice::(&req.body) { + Ok(v) => Some(v), + Err(e) => return Some(Err(Error::BadRequest(format!("invalid JSON: {e}")))), + } + }; let _g = ENSURE.lock().unwrap_or_else(|e| e.into_inner()); if find(engine).is_some() { return None; } - Some(create(engine, &mut |_| {}).map(|id| json!({"Id": id, "Warnings": []}))) + Some(create_with(engine, requested.as_ref(), &mut |_| {}).map(|id| json!({"Id": id, "Warnings": []}))) +} + +/// Claims the builder for a build or prune after checking whether it must +/// be restarted first: this build is counted in [`BUILDS`] only after the +/// busy check, so an idle stale builder is restarted while one another +/// build is using is not. +fn claim_for_build(up: bool, execs: usize, stale: bool) -> (bool, Busy) { + let restart = restart_now(up, BUILDS.load(Ordering::Relaxed) > 0 || execs > 0, stale); + (restart, Busy::new()) } /// The builder, made if need be, started and answering. `say` hears what /// takes a while (a pull, a start). -fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result { +pub(super) fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result<(String, Busy), Error> { if find(engine).is_none() { // Before the lock: a pull must not hold the builder up for others. ensure_image(engine, say)?; @@ -545,12 +596,10 @@ fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result found, None => (create(engine, say)?, Status::Created), }; - // daemon.json edited by hand since the builder started (Settings and - // `kiri registry` refresh it at once): restarted with the new file - // while no build uses it, as buildkitd reads it only when it starts. - let stale = status == Status::Running - && !builder_busy(engine, &id) - && is_stale(WRITTEN.lock().unwrap_or_else(|e| e.into_inner()).as_deref(), &Registries::now(&super::mirror::registry_names(engine))); + // daemon.json edited by hand, or a setting saved while the builder ran: + // restarted with the new file while no other build uses it, as buildkitd + // reads it only when it starts. + let (stale, busy) = claim_for_build(status == Status::Running, engine.running_execs(&id), stale_now(engine)); if stale { if engine.is_paused(&id) { engine.pause(&id, false)?; @@ -566,7 +615,7 @@ fn ensure_running(engine: &Engine, say: &mut dyn FnMut(&str)) -> Result bool { } /// A build in progress, for the idle watch. -struct Busy; +pub(super) struct Busy; impl Busy { fn new() -> Busy { @@ -659,7 +708,7 @@ impl Drop for Busy { // --- In and out of the container ------------------------------------------- -fn internal_exec(argv: &[String], stdin: bool, env: Vec) -> ExecConfig { +pub(super) fn internal_exec(argv: &[String], stdin: bool, env: Vec) -> ExecConfig { ExecConfig { console_size: None, argv: argv.to_vec(), env, cwd: "/".into(), user: String::new(), tty: false, stdin, privileged: true, internal: true } } @@ -774,7 +823,7 @@ fn json_query(req: &Request, key: &str) -> Result { /// `a/b/Dockerfile` stays; a leading `./` or `/` goes; `..` is refused. fn clean_path(p: &str) -> Result { - let parts: Vec<&str> = p.split('/').filter(|s| !s.is_empty() && *s != ".").collect(); + let parts: Vec<&str> = p.split(['/', '\\']).filter(|s| !s.is_empty() && *s != ".").collect(); if parts.contains(&"..") { return Err(Error::BadRequest(format!("the Dockerfile ({p}) must be within the build context"))); } @@ -981,15 +1030,34 @@ enum Context { Dockerfile, } +/// Whether `head` begins a tar archive: an empty body, `ustar` magic, an +/// all-zero end-of-archive block, or a V7 header whose octal checksum matches. +fn tar_header(head: &[u8]) -> bool { + if head.is_empty() || head.get(257..262) == Some(b"ustar") { + return true; + } + if head.len() < 512 { + return false; + } + if head[..512].iter().all(|&b| b == 0) { + return true; + } + let Some(s) = std::str::from_utf8(&head[148..156]).ok().map(|s| s.trim_matches([' ', '\0'])).filter(|s| !s.is_empty()) else { + return false; + }; + let Ok(want) = u32::from_str_radix(s, 8) else { return false }; + let unsigned = head[..148].iter().chain(&head[156..512]).map(|&b| u32::from(b)).sum::() + 8 * 32; + let signed = head[..148].iter().chain(&head[156..512]).map(|&b| i32::from(b as i8)).sum::() + 8 * 32; + want == unsigned || i32::try_from(want).ok() == Some(signed) +} + fn sniff(head: &[u8]) -> Context { match head { [0x1f, 0x8b, ..] => Context::Compressed("-z"), [b'B', b'Z', b'h', ..] => Context::Compressed("-j"), [0xfd, b'7', b'z', b'X', b'Z', 0, ..] => Context::Compressed("-J"), [0x28, 0xb5, 0x2f, 0xfd, ..] => Context::Zstd, - // Every tar Docker clients write is ustar or PAX (`ustar` at 257); - // an empty body is an empty context. - h if h.is_empty() || h.get(257..262) == Some(b"ustar") => Context::Tar, + h if tar_header(h) => Context::Tar, _ => Context::Dockerfile, } } @@ -1003,16 +1071,29 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu return Ok(Next::Close); } }; - // `host-gateway` was parsed as the Mac's address; on a Linux host it's - // the bridge gateway, as `docker run` gives (kiri-init maps it there). - let host = super::mirror::host_addr(engine); + // `host-gateway` was parsed as the Mac's address; on WSL 2 with the Windows + // host relay active it's 192.168.65.254, and on a plain Linux host it's the + // bridge gateway, or 127.0.0.1 for `--network host`, as `docker run` gives + // (kiri-init maps it there). + let host = if crate::hostrelay::wsl_host_active() { + crate::hostrelay::WSL_HOST_ADDR_STR.to_owned() + } else if cfg!(target_os = "linux") && o.network == "host" { + "127.0.0.1".to_owned() + } else { + super::mirror::host_addr(engine) + }; if host != super::ports::HOST_ADDR { let mac = format!("={}", super::ports::HOST_ADDR); for h in o.extra_hosts.iter_mut().filter(|h| h.ends_with(&mac)) { *h = format!("{}={host}", &h[..h.len() - mac.len()]); } } - let _busy = Busy::new(); + // Emit `100 Continue` before the streamed 200 OK header when the build will + // read its context from the request body, so `send_context` never writes + // an interim response after `200 OK`. + if o.remote.is_none() { + http::send_continue(req, r)?; + } // The context may be left partly unread: the connection closes after. http::begin_stream_with(w, 200, "application/json", http::CLOSE)?; let probe = w.try_clone()?; @@ -1021,6 +1102,7 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu let result = run(req, engine, &mut o, r, &mut out, &probe); match result { Ok(images) => { + engine.prune_layers(); let id = images[0].config_digest.clone(); let short: String = id.trim_start_matches("sha256:").chars().take(12).collect(); out.line(json!({"aux": {"ID": id}})); @@ -1051,13 +1133,13 @@ pub fn build(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut Bu fn run(req: &Request, engine: &Engine, o: &mut Options, r: &mut BufReader, out: &mut Out<'_>, probe: &UnixStream) -> Result, String> { let quiet = o.quiet; - let id = ensure_running(engine, &mut |m| { + let (id, _busy) = ensure_running(engine, &mut |m| { if !quiet { out.stream(&format!("{m}\n")); } }) .map_err(|e| match e { - Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) => m, + Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) | Error::Forbidden(m) => m, Error::Io(e) => e.to_string(), })?; let dir = format!("{WORK}/{}", super::engine::random_hex(8)); @@ -1079,6 +1161,15 @@ fn run(req: &Request, engine: &Engine, o: &mut Options, r: &mut BufReader, body: impl Read) -> Result, String> { + let limit = (MAX_DOCKERFILE + 1).saturating_sub(text.len() as u64); + body.take(limit).read_to_end(&mut text).map_err(|e| format!("reading the Dockerfile: {e}"))?; + if text.len() as u64 > MAX_DOCKERFILE { + return Err(format!("the Dockerfile exceeds {} MiB", MAX_DOCKERFILE >> 20)); + } + Ok(text) +} + /// The request body, unpacked into `dir/context` in the builder. fn send_context(engine: &Engine, id: &str, dir: &str, req: &Request, r: &mut BufReader, o: &mut Options) -> Result<(), String> { let mut body = http::Body::new(req, r); @@ -1099,8 +1190,7 @@ fn send_context(engine: &Engine, id: &str, dir: &str, req: &Request, r: &mut Buf } Context::Zstd => Err("a zstd-compressed build context isn't supported: send it as tar, gzip, bzip2 or xz".into()), Context::Dockerfile => { - let mut text = head; - body.take(MAX_DOCKERFILE).read_to_end(&mut text).map_err(|e| format!("reading the Dockerfile: {e}"))?; + let text = read_dockerfile(head, body)?; o.dockerfile = "Dockerfile".into(); copy_in(engine, id, &ctx, &mut io::Cursor::new(tar(&[("Dockerfile", Some(&text))]))).map_err(|e| format!("{e:?}")) } @@ -1220,8 +1310,7 @@ pub fn prune(req: &Request, engine: &Engine) -> Result { if find(engine).is_none() { return Ok(json!({"CachesDeleted": [], "SpaceReclaimed": 0})); } - let _busy = Busy::new(); - let id = ensure_running(engine, &mut |_| {})?; + let (id, _busy) = ensure_running(engine, &mut |_| {})?; let argv: Vec<&str> = argv.iter().map(String::as_str).collect(); let (code, text) = engine.exec_capture(&id, &argv)?; if code != 0 { @@ -1342,7 +1431,12 @@ mod tests { /// its recorded config is not advanced. #[test] fn a_builder_whose_config_is_unknown_or_old_is_stale() { - let r = |c: kiri_image::RegistryConfig, unverified: &[&str]| Registries { config: std::sync::Arc::new(c), unverified: unverified.iter().map(|s| s.to_string()).collect() }; + let r = |c: kiri_image::RegistryConfig, unverified: &[&str]| Registries { + config: std::sync::Arc::new(c), + mirrored: vec!["docker.io".into()], + unverified: unverified.iter().map(|s| s.to_string()).collect(), + host_net: false, + }; let none = r(kiri_image::RegistryConfig::default(), &[]); let some = r(kiri_image::RegistryConfig { insecure: vec![kiri_image::Insecure::parse("registry.lan:5000").unwrap()], ..Default::default() }, &[]); assert!(is_stale(None, &none), "never written by this daemon"); @@ -1350,19 +1444,84 @@ mod tests { assert!(!is_stale(Some(&some), &some)); } - /// An image pulled from a registry inside a listed network, after the - /// builder started, makes it stale: its config has no table for it. + /// An image pulled from a new registry after the builder started makes it + /// stale so `buildkitd.toml` gets Kiri's mirror table (and unverified flags + /// when inside a listed network) for that registry; pulling again from an + /// already-mirrored registry changes nothing. #[test] fn a_registry_pulled_from_inside_a_listed_network_makes_the_builder_stale() { let c = std::sync::Arc::new(kiri_image::RegistryConfig { insecure: vec![kiri_image::Insecure::parse("10.0.0.0/8").unwrap()], ..Default::default() }); - let names = |n: &[&str]| n.iter().map(|s| s.to_string()).collect::>(); - let before = Registries { config: c.clone(), unverified: super::super::mirror::unverified(&c, &names(&["docker.io"])) }; - let after = Registries { config: c.clone(), unverified: super::super::mirror::unverified(&c, &names(&["docker.io", "ghcr.io", "10.1.2.3:5000"])) }; + let make = |n: &[&str], host_net: bool| { + let mut mirrored: Vec = n.iter().map(|s| s.to_string()).collect(); + let unverified = super::super::mirror::unverified(&c, &mirrored); + mirrored.sort(); + mirrored.dedup(); + Registries { config: c.clone(), mirrored, unverified, host_net } + }; + let before = make(&["docker.io", "ghcr.io"], false); + let after = make(&["docker.io", "ghcr.io", "10.1.2.3:5000"], false); assert_eq!(after.unverified, ["10.1.2.3:5000"]); assert!(is_stale(Some(&before), &after)); - // A registry outside the list changes nothing. - let other = Registries { config: c.clone(), unverified: super::super::mirror::unverified(&c, &names(&["docker.io", "ghcr.io"])) }; - assert!(!is_stale(Some(&before), &other)); + // Pulling another image from an already-mirrored registry changes nothing. + let same = make(&["ghcr.io", "docker.io"], false); + assert!(!is_stale(Some(&before), &same)); + // Switching the builder to `--driver-opt network=host` marks its mirror config stale. + assert!(is_stale(Some(&before), &make(&["docker.io", "ghcr.io"], true))); + } + + #[test] + fn create_for_buildx_preserves_host_network_and_dns_options() { + use std::io::Write as _; + let def = create_body_from(None); + assert!(def["HostConfig"].get("NetworkMode").is_none()); + + let asked = json!({ + "Image": "moby/buildkit:buildx-stable-1", + "Env": ["HTTP_PROXY=http://10.0.0.1:3128"], + "HostConfig": { + "NetworkMode": "host", + "Dns": ["10.0.0.53"], + "DnsSearch": ["corp.example"], + "DnsOptions": ["ndots:2"], + "ExtraHosts": ["reg.corp:10.0.0.9"], + "RestartPolicy": {"Name": "always"}, + } + }); + let merged = create_body_from(Some(&asked)); + assert_eq!(merged["HostConfig"]["NetworkMode"], "host"); + assert_eq!(merged["HostConfig"]["Dns"], json!(["10.0.0.53"])); + assert_eq!(merged["HostConfig"]["DnsSearch"], json!(["corp.example"])); + assert_eq!(merged["HostConfig"]["DnsOptions"], json!(["ndots:2"])); + assert_eq!(merged["HostConfig"]["ExtraHosts"], json!(["reg.corp:10.0.0.9"])); + assert_eq!(merged["Env"], json!(["HTTP_PROXY=http://10.0.0.1:3128"])); + assert_eq!(merged["HostConfig"]["RestartPolicy"]["Name"], "no", "managed builder starts on demand"); + + // Full create_for_buildx round-trip against Engine::boot with IMAGE pre-seeded. + let dir = std::env::temp_dir().join(format!("kiri-builder-hostnet-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let cfg = json!({"created": "2026-11-16T00:00:00Z", "architecture": "arm64", "os": "linux", "config": {"Cmd": ["buildkitd"]}}); + let mut w = store.ingest().unwrap(); + w.write_all(&serde_json::to_vec(&cfg).unwrap()).unwrap(); + let (digest, _) = w.finish().unwrap(); + store.put_image(kiri_image::archive::from_config(IMAGE.into(), &digest, &cfg, Vec::new())).unwrap(); + let engine = Engine::boot(store).unwrap(); + + let other = Request::internal("POST", "/containers/create", &[("name", "not-builder")], serde_json::to_vec(&asked).unwrap()); + assert!(create_for_buildx(&engine, &other).is_none()); + + let name = container_name(); + let bad = Request::internal("POST", "/containers/create", &[("name", &name)], b"{not-json".to_vec()); + assert!(matches!(create_for_buildx(&engine, &bad), Some(Err(Error::BadRequest(_))))); + + let create_req = Request::internal("POST", "/containers/create", &[("name", &name)], serde_json::to_vec(&asked).unwrap()); + let created = create_for_buildx(&engine, &create_req).expect("intercepted").expect("created"); + let id = created["Id"].as_str().unwrap(); + assert!(builder_host_net(&engine, id), "builder container kept HostConfig.NetworkMode = host"); + assert!(create_for_buildx(&engine, &create_req).is_none(), "existing builder falls through to 409"); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); } /// A builder on an old config is restarted only when it is up and @@ -1376,6 +1535,22 @@ mod tests { assert!(!restart_now(true, false, false)); let at = |s: Step| STOP_THEN_WRITE.iter().position(|x| *x == s).unwrap(); assert!(at(Step::Resume) < at(Step::Stop) && at(Step::Stop) < at(Step::Write), "{STOP_THEN_WRITE:?}"); + + let _g = ENSURE.lock().unwrap_or_else(|e| e.into_inner()); + assert_eq!(BUILDS.load(Ordering::Relaxed), 0); + let (restart_first, b1) = claim_for_build(true, 0, true); + assert!(restart_first, "an idle stale builder is restarted before this build marks it busy"); + assert_eq!(BUILDS.load(Ordering::Relaxed), 1); + let (restart_while_busy, b2) = claim_for_build(true, 0, true); + assert!(!restart_while_busy, "a builder another build is using must not be restarted"); + drop((b1, b2)); + assert_eq!(BUILDS.load(Ordering::Relaxed), 0); + let (restart_fresh, b3) = claim_for_build(true, 0, false); + assert!(!restart_fresh, "a fresh builder is not restarted"); + drop(b3); + assert_eq!(BUILDS.load(Ordering::Relaxed), 0); + let (restart_exec_busy, _b4) = claim_for_build(true, 1, true); + assert!(!restart_exec_busy, "a builder with an active buildx exec is not restarted"); } /// `before_exec` re-checks the builder's state under `ENSURE` (so a waiter @@ -1876,8 +2051,82 @@ mod tests { assert_eq!(default_cache(0), 20 * GB); assert_eq!(default_cache(100 * GB), 10 * GB); assert_eq!(default_cache(2000 * GB), 20 * GB); + assert_eq!(cache_limit_from(None, || 100 * GB), 10 * GB); + assert_eq!(cache_limit_from(Some(0), || 100 * GB), 10 * GB); + assert_eq!(cache_limit_from(Some(12), || panic!("disk_total not needed when gb > 0")), 12 * GB); + assert_eq!(cache_limit_from(Some((u64::MAX / GB) + 1), || 100 * GB), u64::MAX); + assert_eq!(cache_limit_from(Some(u64::MAX), || 100 * GB), u64::MAX); assert!(config_toml(8 * GB, "").contains(&format!("maxUsedSpace = {}", 8 * GB))); assert_eq!(failure(&["#5 ERROR: boom".into(), "error: failed to solve: boom".into()], 1), "failed to solve: boom"); assert_eq!(failure(&[], 2), "buildctl exited with code 2"); } + + #[test] + fn sniffs_empty_and_v7_tars_and_bounds_dockerfiles_and_paths() { + let empty = ::tar::Builder::new(Vec::new()).into_inner().unwrap(); + assert_eq!(empty.len(), 1024); + assert_eq!(sniff(&empty[..512]), Context::Tar); + assert_eq!(sniff(&[0u8; 512]), Context::Tar); + assert_eq!(sniff(&[0u8; 64]), Context::Dockerfile); + + // Unsigned-checksum V7 tar header (no `ustar` magic at 257..262). + let mut b = ::tar::Builder::new(Vec::new()); + let mut h = ::tar::Header::new_old(); + h.set_path("sub/Dockerfile.dev").unwrap(); + h.set_size(12); + h.set_mode(0o644); + h.set_cksum(); + b.append(&h, &b"FROM alpine\n"[..]).unwrap(); + let v7 = b.into_inner().unwrap(); + assert_ne!(&v7[257..262], b"ustar"); + assert_eq!(sniff(&v7[..512]), Context::Tar); + + // Signed-checksum V7 tar header (legacy signed-char sum with non-ASCII bytes). + let mut signed_v7 = [0u8; 512]; + let name = "café/Dockerfile".as_bytes(); + signed_v7[..name.len()].copy_from_slice(name); + signed_v7[100..108].copy_from_slice(b"0000644\0"); + signed_v7[124..136].copy_from_slice(b"00000000014\0"); + signed_v7[136..148].copy_from_slice(b"14700000000\0"); + signed_v7[156] = b'0'; + let signed_sum: i32 = signed_v7[..148].iter().chain(&signed_v7[156..512]).map(|&b| i32::from(b as i8)).sum::() + 8 * 32; + assert!(signed_sum > 0); + signed_v7[148..156].copy_from_slice(format!("{signed_sum:06o}\0 ").as_bytes()); + assert_eq!(sniff(&signed_v7), Context::Tar); + + // Corrupted V7 header and raw Dockerfiles with fake or invalid octal text at 148..156. + let mut bad_v7 = v7[..512].to_vec(); + bad_v7[0] ^= 0x01; + assert_eq!(sniff(&bad_v7), Context::Dockerfile); + + let mut fake = b"FROM alpine\n# ".to_vec(); + fake.resize(148, b'a'); + fake.extend_from_slice(b"000777\0 "); + fake.resize(512, b'\n'); + assert_eq!(sniff(&fake), Context::Dockerfile); + + let mut non_octal = fake.clone(); + non_octal[148..156].copy_from_slice(b"000888\0 "); + assert_eq!(sniff(&non_octal), Context::Dockerfile); + + // Raw Dockerfile cap: exact MAX_DOCKERFILE succeeds; MAX_DOCKERFILE + 1 and unbounded streams fail. + assert_eq!(read_dockerfile(vec![b'#'; 512], io::repeat(b'x').take(MAX_DOCKERFILE - 512)).unwrap().len() as u64, MAX_DOCKERFILE); + assert_eq!(read_dockerfile(vec![b'#'; 512], io::repeat(b'x').take(MAX_DOCKERFILE - 511)).unwrap_err(), "the Dockerfile exceeds 8 MiB"); + assert_eq!(read_dockerfile(vec![b'#'; 512], io::repeat(b'x')).unwrap_err(), "the Dockerfile exceeds 8 MiB"); + + // Windows backslash traversal refusals and path normalization. + assert!(Options::parse(&req(&[("dockerfile", r"..\Dockerfile")])).is_err()); + assert!(Options::parse(&req(&[("dockerfile", r"a/b\..\..\..")])).is_err()); + assert!(Options::parse(&req(&[("dockerfile", r"docker\..\Dockerfile")])).is_err()); + + let o = Options::parse(&req(&[("dockerfile", r".\docker\Dockerfile.dev")])).unwrap(); + assert_eq!(o.dockerfile, "docker/Dockerfile.dev"); + let a = o.argv("/d"); + assert!(a.windows(2).any(|w| w == ["--opt", "filename=Dockerfile.dev"])); + assert!(a.windows(2).any(|w| w == ["--local", "dockerfile=/d/context/docker"])); + + let root_df = Options::parse(&req(&[("dockerfile", r".\Dockerfile")])).unwrap(); + assert_eq!(root_df.dockerfile, "Dockerfile"); + assert_eq!(Options::parse(&req(&[("dockerfile", r".\")])).unwrap().dockerfile, "Dockerfile"); + } } diff --git a/crates/kiri/src/daemon/caller.rs b/crates/kiri/src/daemon/caller.rs index 795f879d7..6506f0382 100644 --- a/crates/kiri/src/daemon/caller.rs +++ b/crates/kiri/src/daemon/caller.rs @@ -26,12 +26,23 @@ use std::path::{Path, PathBuf}; /// Who is at the other end of an API connection. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub enum Caller { /// This machine's programs, on the daemon's own socket. Host, /// A container, through the VM's relay or its own socket. Container, + /// Another WSL 2 distro, on `/mnt/wsl/kiri/sockets//docker.sock`. + Wsl(String), +} + +impl Caller { + pub fn wsl_distro(&self) -> Option<&str> { + match self { + Caller::Wsl(distro) => Some(distro), + Caller::Host | Caller::Container => None, + } + } } /// The socket containers that mount the engine's are given, beside the diff --git a/crates/kiri/src/daemon/daemon_json.rs b/crates/kiri/src/daemon/daemon_json.rs index 9c73b0725..12f1c825e 100644 --- a/crates/kiri/src/daemon/daemon_json.rs +++ b/crates/kiri/src/daemon/daemon_json.rs @@ -125,10 +125,16 @@ fn parse(bytes: &[u8]) -> (RegistryConfig, Vec) { (config, problems) } +/// `bytes` past a leading UTF-8 byte order mark, which dockerd skips when it +/// reads daemon.json (Windows PowerShell and older Notepad write one). +fn without_bom(bytes: &[u8]) -> &[u8] { + bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes) +} + /// [`parse`], and every mirror the file lists, the unused ones included. fn parse_all(bytes: &[u8]) -> (RegistryConfig, Vec, Vec) { let mut problems = Problems::default(); - let v: Value = match serde_json::from_slice(bytes) { + let v: Value = match serde_json::from_slice(without_bom(bytes)) { Ok(v @ Value::Object(_)) => v, Ok(_) => return (RegistryConfig::default(), vec!["daemon.json is not a JSON object".into()], Vec::new()), Err(e) => return (RegistryConfig::default(), vec![format!("daemon.json is not valid JSON: {e}")], Vec::new()), @@ -325,8 +331,8 @@ fn set_with(body: &Value, path: &std::path::Path, current: impl Fn() -> Arc Result<(), String> { let existing_mode = std::fs::metadata(path).ok().map(|m| mode_of(&m)); let mut file = match read_limited(path) { - Ok(b) if b.iter().all(u8::is_ascii_whitespace) => Map::new(), - Ok(b) => match serde_json::from_slice::(&b) { + Ok(b) if without_bom(&b).iter().all(u8::is_ascii_whitespace) => Map::new(), + Ok(b) => match serde_json::from_slice::(without_bom(&b)) { Ok(Value::Object(m)) => m, _ => return Err(format!("{} is not a JSON object; fix it or remove it, then save again", path.display())), }, @@ -636,4 +642,23 @@ mod tests { let mirrors = normalize(&json!(["mirror.example.com", "https://mirror.example.com/", "http://mirror.lan:5000"]), MIRRORS, 8, |s| Mirror::parse(s).map(|m| m.as_url())).unwrap(); assert_eq!(mirrors, ["https://mirror.example.com", "http://mirror.lan:5000"]); } + + #[test] + fn a_file_with_a_utf8_bom_is_read_and_saved() { + let (c, problems) = parse(b"\xEF\xBB\xBF{\"insecure-registries\": [\"registry.lan:5000\"], \"registry-mirrors\": [\"https://mirror.example.com\"]}"); + assert!(problems.is_empty(), "{problems:?}"); + assert!(c.is_insecure("registry.lan:5000")); + assert_eq!(c.mirrors.iter().map(Mirror::as_url).collect::>(), ["https://mirror.example.com"]); + + let d = scratch("bom"); + let f = d.join("daemon.json"); + std::fs::write(&f, b"\xEF\xBB\xBF{\"debug\": true}").unwrap(); + save_at(&f, &json!({INSECURE: ["registry.lan:5000"]})).unwrap(); + let saved: Value = serde_json::from_slice(&std::fs::read(&f).unwrap()).unwrap(); + assert_eq!(saved["debug"], json!(true)); + assert_eq!(saved[INSECURE], json!(["registry.lan:5000"])); + std::fs::write(&f, b"\xEF\xBB\xBF\n").unwrap(); + save_at(&f, &json!({INSECURE: ["registry.lan:5000"]})).unwrap(); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/daemon/dns.rs b/crates/kiri/src/daemon/dns.rs index afb5cebf0..d0dde79dc 100644 --- a/crates/kiri/src/daemon/dns.rs +++ b/crates/kiri/src/daemon/dns.rs @@ -122,21 +122,29 @@ fn relay_one(stream: &kiri_vmm::VsockStream) { if conn.read_exact(&mut len).is_err() { return; } - let mut query = vec![0u8; u16::from_be_bytes(len) as usize]; - if conn.read_exact(&mut query).is_err() || !is_query(&query) { + let qlen = usize::from(u16::from_be_bytes(len)); + if !(12..=4096).contains(&qlen) { + return; + } + let mut qbuf = [0u8; 4096]; + let query = &mut qbuf[..qlen]; + if conn.read_exact(query).is_err() || !is_query(query) { return; } static SAID: AtomicBool = AtomicBool::new(false); - if !SAID.swap(true, Ordering::Relaxed) { + if should_warn_gateway_dns(super::ports::shared_nat_active(), &SAID) { crate::diag::warn!("the VM's DNS at its gateway did not answer; container lookups go through the Mac"); } - let name = question_name(&query).unwrap_or_default(); + let name = question_name(query).unwrap_or_default(); let servers = mac_resolvers(&name, Path::new("/etc/resolv.conf"), Path::new("/etc/resolver")); - let reply = relay_query(&query, &servers).unwrap_or_else(|| servfail(&query)); - let mut out = Vec::with_capacity(2 + reply.len()); - out.extend_from_slice(&(reply.len().min(u16::MAX as usize) as u16).to_be_bytes()); - out.extend_from_slice(&reply[..reply.len().min(u16::MAX as usize)]); - let _ = conn.write_all(&out); + let reply = relay_query(query, &servers).unwrap_or_else(|| servfail(query)); + let rlen = reply.len().min(usize::from(u16::MAX)); + let hdr = (rlen as u16).to_be_bytes(); + let _ = conn.write_all(&hdr).and_then(|()| conn.write_all(&reply[..rlen])); +} + +fn should_warn_gateway_dns(shared_nat_active: bool, said: &AtomicBool) -> bool { + shared_nat_active && !said.swap(true, Ordering::Relaxed) } /// Whether `q` is a standard DNS query with one well-formed question: the @@ -183,6 +191,11 @@ fn relay_query(query: &[u8], servers: &[SocketAddr]) -> Option> { let Ok(n) = sock.recv(&mut buf) else { break }; let r = &buf[..n]; if n >= 12 && r[..2] == query[..2] && r[2] & 0x80 != 0 { + if r[2] & 0x02 != 0 + && let Some(full) = relay_tcp(query, *server, until.saturating_duration_since(Instant::now())) + { + return Some(full); + } return Some(r.to_vec()); } } @@ -190,6 +203,29 @@ fn relay_query(query: &[u8], servers: &[SocketAddr]) -> Option> { None } +/// Retries a truncated (`TC=1`) UDP reply over TCP so large responses arrive whole. +fn relay_tcp(query: &[u8], server: SocketAddr, wait: Duration) -> Option> { + if wait.is_zero() { + return None; + } + let mut stream = std::net::TcpStream::connect_timeout(&server, wait).ok()?; + let _ = stream.set_read_timeout(Some(wait)); + let _ = stream.set_write_timeout(Some(wait)); + let len = u16::try_from(query.len()).ok()?.to_be_bytes(); + stream.write_all(&len).ok()?; + stream.write_all(query).ok()?; + let mut rlen = [0u8; 2]; + stream.read_exact(&mut rlen).ok()?; + let n = usize::from(u16::from_be_bytes(rlen)); + if !(12..=65_535).contains(&n) { + return None; + } + let mut buf = vec![0u8; 65_535]; + stream.read_exact(&mut buf[..n]).ok()?; + buf.truncate(n); + (buf[..2] == query[..2] && buf[2] & 0x80 != 0).then_some(buf) +} + /// SERVFAIL for `query`: no resolver on the Mac answered either. fn servfail(query: &[u8]) -> Vec { let end = question_end(query).unwrap_or(12).min(query.len()); @@ -242,6 +278,8 @@ fn question_name(q: &[u8]) -> Option { } } +static SELF_LOOP_WARNED: AtomicBool = AtomicBool::new(false); + /// Where the Mac would send a lookup for `name`: the servers of the /// `/etc/resolver/` file with the longest domain that `name` is in /// (VPNs and tools such as dnsmasq set these up), else `/etc/resolv.conf`'s, @@ -250,6 +288,16 @@ fn question_name(q: &[u8]) -> Option { /// skipped: its server answers 127.0.0.1, the Mac's loopback, which means /// nothing in a container. fn mac_resolvers(name: &str, resolv_conf: &Path, resolver_dir: &Path) -> Vec { + mac_resolvers_with(name, resolv_conf, resolver_dir, super::ports::host_port_53_published(), Some(&SELF_LOOP_WARNED)) +} + +fn mac_resolvers_with( + name: &str, + resolv_conf: &Path, + resolver_dir: &Path, + skip_loopback_53: bool, + warn_once: Option<&AtomicBool>, +) -> Vec { let mut best: Option<(usize, Vec)> = None; for entry in std::fs::read_dir(resolver_dir).into_iter().flatten().flatten() { let Ok(text) = std::fs::read_to_string(entry.path()) else { continue }; @@ -271,7 +319,20 @@ fn mac_resolvers(name: &str, resolv_conf: &Path, resolver_dir: &Path) -> Vec| list.into_iter().map(|s| s.to_string()).collect::>(); + + // When no container publishes port 53, loopback :53 resolvers are preserved. + assert_eq!( + strs(super::mac_resolvers_with("example.com", &conf, &resolvers, false, None)), + ["127.0.0.1:53", "[::1]:53", "192.168.1.1:53"] + ); + assert_eq!( + strs(super::mac_resolvers_with("a.loop53.example", &conf, &resolvers, false, None)), + ["127.0.0.1:53"] + ); + + // When a container publishes port 53, 127.0.0.1:53 and [::1]:53 are skipped + // while non-loopback :53 and loopback high-port resolvers stay usable. + let warned = AtomicBool::new(false); + assert_eq!( + strs(super::mac_resolvers_with("example.com", &conf, &resolvers, true, Some(&warned))), + ["192.168.1.1:53"] + ); + assert!(warned.load(Ordering::Relaxed), "warns once when loopback :53 is filtered"); + assert!(super::mac_resolvers_with("a.loop53.example", &conf, &resolvers, true, Some(&warned)).is_empty()); + assert_eq!( + strs(super::mac_resolvers_with("a.highport.example", &conf, &resolvers, true, Some(&warned))), + ["127.0.0.1:5353"] + ); + + // With only loopback :53 in resolv.conf, filtering returns empty (SERVFAIL) instead of looping. + std::fs::write(&conf, "nameserver 127.0.0.1\nnameserver ::1\n").unwrap(); + assert!(super::mac_resolvers_with("example.com", &conf, &resolvers, true, None).is_empty()); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/domains.rs b/crates/kiri/src/daemon/domains.rs index f98900f90..82c526f7a 100644 --- a/crates/kiri/src/daemon/domains.rs +++ b/crates/kiri/src/daemon/domains.rs @@ -418,10 +418,15 @@ fn route(client: &mut impl ReadWrite, engine: &Engine, scheme: &str) -> io::Resu } }; let text = String::from_utf8_lossy(&head[..end]); - let host = text + let mut hosts = text .lines() - .find_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_owned())) - .unwrap_or_default(); + .skip(1) + .filter_map(|l| l.split_once(':').filter(|(k, _)| k.eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_owned())); + let host = hosts.next().unwrap_or_default(); + if hosts.next().is_some() { + respond(client, 400, "Bad Request", "")?; + return Ok(None); + } let Some(target) = engine.route(&host) else { // The running containers are listed only for this machine's own // names. A page reached through DNS rebinding asks with its own @@ -628,21 +633,42 @@ fn respond(client: &mut impl Write, status: u16, reason: &str, body: &str) -> io ) } +/// Parses a request `Host` header (`[::1]:80`, `127.0.0.1:80`, +/// `web.kiri.local:8080`, `web.kiri.local.`), rejecting malformed or zero +/// ports, non-IPv6 bracketed hosts, and multiple trailing dots. +pub(super) fn parse_host_name(host: &str) -> Option { + let host = host.trim(); + if host.is_empty() { + return None; + } + let valid_port = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) && p.parse::().is_ok_and(|n| n != 0); + if let Some(v6) = host.strip_prefix('[') { + let addr = match v6.split_once(']') { + Some((addr, "")) => addr, + Some((addr, rest)) if rest.strip_prefix(':').is_some_and(valid_port) => addr, + _ => return None, + }; + addr.parse::().ok()?; + return Some(addr.to_ascii_lowercase()); + } + let name = match host.rsplit_once(':') { + Some((name, port)) if !name.contains(':') && valid_port(port) => name, + Some(_) => return None, + None => host, + }; + let name = name.strip_suffix('.').unwrap_or(name); + if name.is_empty() || name.ends_with('.') { + return None; + } + Some(name.to_ascii_lowercase()) +} + /// Whether a request's Host is a name for this machine itself: `localhost`, /// anything under `.localhost` (which always resolves to loopback), a /// `.kiri.local` name, or a loopback address. Another site's domain is not, /// even when its DNS answers with 127.0.0.1. fn local_host(host: &str) -> bool { - let host = host.trim(); - // Without the port: `[::1]:80`, `127.0.0.1:80`, `web.kiri.localhost:8080`. - let name = match host.strip_prefix('[') { - Some(v6) => v6.split(']').next().unwrap_or(""), - None => match host.rsplit_once(':') { - Some((name, port)) if !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) => name, - _ => host, - }, - }; - let name = name.trim_end_matches('.').to_ascii_lowercase(); + let Some(name) = parse_host_name(host) else { return false }; name == "localhost" || name.ends_with(".localhost") || name.ends_with(".kiri.local") || name.parse::().is_ok_and(|ip| ip.is_loopback()) } @@ -674,10 +700,33 @@ mod tests { /// machine's own names only: a rebinding page's Host is its own domain. #[test] fn only_this_machines_names_get_the_container_list() { - for local in ["localhost", "localhost:80", "nope.kiri.localhost", "NOPE.Kiri.Localhost:8080", "web.shop.kiri.local", "api.kiri.local:18780", "127.0.0.1", "127.0.0.1:80", "[::1]", "[::1]:443", "anything.localhost."] { + for local in ["localhost", "localhost:80", "localhost:65535", "nope.kiri.localhost", "NOPE.Kiri.Localhost:8080", "web.shop.kiri.local", "api.kiri.local:18780", "127.0.0.1", "127.0.0.1:80", "[::1]", "[::1]:1", "[::1]:443", "[::1]:65535", "anything.localhost."] { assert!(super::local_host(local), "{local}"); } - for foreign in ["", "rebind.example.com", "rebind.example.com:80", "kiri.localhost.example.com", "localhost.example.com", "192.168.1.10", "10.0.0.1:80", "[2001:db8::1]:80", "notlocalhost", "kiri.local.evil.io"] { + for foreign in [ + "", + "rebind.example.com", + "rebind.example.com:80", + "kiri.localhost.example.com", + "localhost.example.com", + "192.168.1.10", + "10.0.0.1:80", + "[2001:db8::1]:80", + "notlocalhost", + "kiri.local.evil.io", + "[::1]rebind.example.com", + "[::1]:notaport", + "[::1", + "[::1]:0", + "[::1]:65536", + "[::1]:+80", + "[::1]:", + "localhost:0", + "localhost:65536", + "localhost:+80", + "localhost:", + "localhost:abc", + ] { assert!(!super::local_host(foreign), "{foreign}"); } } @@ -714,4 +763,14 @@ mod tests { // Listening elsewhere only: keep the first candidate. assert_eq!(choose(&[3000], Some(&[9229])), 3000); } + + #[test] + fn parse_host_name_trims_trailing_dot_and_rejects_bad_ports() { + assert_eq!(super::parse_host_name("web.kiri.local."), Some("web.kiri.local".into())); + assert_eq!(super::parse_host_name("WEB.KIRI.LOCAL:8080"), Some("web.kiri.local".into())); + assert_eq!(super::parse_host_name("[::1]:8080"), Some("::1".into())); + for bad in ["", "web.kiri.local:0", "web.kiri.local:65536", "web.kiri.local:abc", "web.kiri.local:", "web.kiri.local:+80", "a:b:80", "[web.kiri.local]:80", "[localhost]", "web.kiri.local.."] { + assert_eq!(super::parse_host_name(bad), None, "{bad}"); + } + } } diff --git a/crates/kiri/src/daemon/engine.rs b/crates/kiri/src/daemon/engine.rs index 462b173cb..31cfa286e 100644 --- a/crates/kiri/src/daemon/engine.rs +++ b/crates/kiri/src/daemon/engine.rs @@ -5,7 +5,7 @@ //! ps -a` survives a daemon restart. Every state change notifies one //! condition variable, which is what `wait` blocks on. -use std::collections::{HashMap, VecDeque}; +use std::collections::{HashMap, HashSet, VecDeque}; use std::io; use std::path::PathBuf; use std::sync::mpsc::{self, Receiver, Sender}; @@ -21,55 +21,115 @@ use super::network::Networks; use super::vmlink::{Event, VmLink}; /// Dynamic memory: the VM boots with a ceiling, and the balloon keeps the -/// guest at what it uses plus this much, returning the rest to macOS. -const MEMORY_HEADROOM: u64 = 256 << 20; -const MEMORY_FLOOR: u64 = 256 << 20; +/// guest at what it uses plus proportional headroom, returning the rest to +/// macOS. +const MEMORY_HEADROOM_MIN: u64 = 512 << 20; +const MEMORY_HEADROOM_MAX: u64 = 2 << 30; +const MEMORY_FLOOR_IDLE: u64 = 256 << 20; +const MEMORY_FLOOR_ACTIVE_MIN: u64 = 1 << 30; +const COMMIT_OVERHEAD_MAX: u64 = 4 << 30; /// How much more the guest gets at once when it reports pressure. const MEMORY_GROW: u64 = 1 << 30; -const MEMORY_SHRINK_STEP: u64 = 256 << 20; +const MEMORY_SHRINK_STEP: u64 = 128 << 20; const MEMORY_DEADBAND: u64 = 64 << 20; +/// Hold working-set peak this long after any grow, pressure event, or new peak +/// before decaying it gently. +const SHRINK_COOLDOWN: Duration = Duration::from_secs(60); +const WS_PEAK_DECAY_INTERVAL: Duration = Duration::from_secs(5); +const WS_PEAK_DECAY_STEP: u64 = 64 << 20; + +/// Proportional `MemAvailable` headroom `H(C) = (C / 4).clamp(512 MiB, 2 GiB)`. +fn memory_headroom(ceiling: u64) -> u64 { + (ceiling / 4).clamp(MEMORY_HEADROOM_MIN, MEMORY_HEADROOM_MAX) +} + +/// Active vs idle memory floor `F(C)`, honoring optional `memory_min` (clamped +/// to `0..=ceiling`). +fn memory_floor(ceiling: u64, active_containers: usize, memory_min: u64) -> u64 { + let base = if active_containers > 0 { + (ceiling / 4).max(MEMORY_FLOOR_ACTIVE_MIN).min(ceiling) + } else { + MEMORY_FLOOR_IDLE.min(ceiling) + }; + base.max(memory_min.min(ceiling)) +} + +/// Live non-available guest memory `U_live`, accounting for boot-time kernel +/// reserve, zone watermarks, uncharged kernel memory, and balloon lag. +fn live_memory_need(used: u64, mem_total: u64, mem_available: u64, balloon: Option, ceiling: u64) -> u64 { + let reserved = if mem_total > 0 { ceiling.saturating_sub(mem_total) } else { 0 }; + let floor_need = used.saturating_add(reserved); + match balloon { + Some(b) if mem_total > 0 => ceiling.saturating_sub(b.saturating_add(mem_available)).max(floor_need), + _ => floor_need, + } +} + +/// Committed address-space need `U_commit = min(committed_as, used + min(C / 2, 4 GiB)) + R`. +/// The overhead cap keeps pathological sparse overcommits from pinning 100% of +/// VM RAM indefinitely. +fn committed_memory_need(used: u64, mem_total: u64, committed_as: Option, ceiling: u64) -> u64 { + let Some(committed) = committed_as else { return 0 }; + let reserved = if mem_total > 0 { ceiling.saturating_sub(mem_total) } else { 0 }; + let cap = used.saturating_add((ceiling / 2).min(COMMIT_OVERHEAD_MAX)); + committed.min(cap).saturating_add(reserved) +} + +#[derive(Clone, Copy)] +struct BalloonPolicy { + ceiling: u64, + active_containers: usize, + memory_min: u64, +} + +impl BalloonPolicy { + fn headroom(self) -> u64 { + memory_headroom(self.ceiling) + } + + fn floor(self) -> u64 { + memory_floor(self.ceiling, self.active_containers, self.memory_min) + } +} + +#[derive(Clone, Copy)] +struct MemorySample { + used: u64, + mem_total: u64, + mem_available: u64, + balloon: Option, + committed_as: Option, + ws_peak: u64, +} /// The balloon's next target, in bytes, or None to leave it. /// -/// The guest keeps `MEMORY_HEADROOM` of usable memory (`MemAvailable`) beyond -/// everything Linux cannot hand out: the boot-time kernel reserve (`ceiling` -/// less `MemTotal`, mostly `struct page`), zone reclaim watermarks and -/// `lowmem_reserve`, uncharged kernel memory, container memory and the share -/// of page cache Linux excludes from `MemAvailable` (up to `wmark_low`). On -/// an 8 GiB VM the boot reserve alone is ~173 MiB, and on a 24 GiB VM zone -/// watermarks, `lowmem_reserve` and uncharged kernel memory add another -/// ~265 MiB — enough to leave `MemAvailable` at zero even when idle if only -/// `used` and the boot reserve are counted (#509). +/// The guest keeps proportional `MemAvailable` headroom `H(C)` beyond +/// `need = max(U_live, U_commit, ws_peak)` — covering the boot-time kernel +/// reserve (`ceiling` less `MemTotal`, mostly `struct page`), zone reclaim +/// watermarks and `lowmem_reserve`, uncharged kernel memory, container memory, +/// bounded `Committed_AS`, and the working-set peak (#509, #608, #891). /// /// When the guest reports its live balloon size (`balloon`), `ceiling` less -/// `balloon + mem_available` is that exact non-available total, independent +/// `balloon + mem_available` is the exact live non-available total, independent /// of inflation or deflation lag while `mem_available` stays above zero. -/// Whenever `mem_available` is below `MEMORY_HEADROOM` (such as right after +/// Whenever `mem_available` is below `H(C)` (such as right after /// `grow_memory()`, before the balloon finishes deflating, or with an older -/// agent that reports no balloon size), `target` is never shrunk. Without a -/// balloon reading, fall back to `used + (ceiling - mem_total)` and never -/// shrink past `MEMORY_HEADROOM` of `mem_available`. Shrinks in steps, so the -/// guest's caches go gradually, and grows at once. -fn next_memory_target( - used: u64, - mem_total: u64, - mem_available: u64, - balloon: Option, - ceiling: u64, - target: u64, -) -> Option { - let reserved = if mem_total > 0 { ceiling.saturating_sub(mem_total) } else { 0 }; - let floor_need = used.saturating_add(reserved); - let need = match balloon { - Some(b) if mem_total > 0 => ceiling.saturating_sub(b.saturating_add(mem_available)).max(floor_need), - _ => floor_need, - }; - let want = need.saturating_add(MEMORY_HEADROOM).clamp(MEMORY_FLOOR.min(ceiling), ceiling); - let want = if mem_total > 0 { - let min_target = match balloon { - Some(_) if mem_available < MEMORY_HEADROOM => target.min(ceiling), +/// agent that reports no balloon size), `target` is never shrunk. Shrinks in +/// 128 MiB steps, so the guest's caches go gradually, and grows at once. +fn next_memory_target(sample: MemorySample, policy: BalloonPolicy, target: u64) -> Option { + let ceiling = policy.ceiling; + let headroom = policy.headroom(); + let floor = policy.floor(); + let u_live = live_memory_need(sample.used, sample.mem_total, sample.mem_available, sample.balloon, ceiling); + let u_commit = committed_memory_need(sample.used, sample.mem_total, sample.committed_as, ceiling); + let need = u_live.max(u_commit).max(sample.ws_peak); + let want = need.saturating_add(headroom).clamp(floor, ceiling); + let want = if sample.mem_total > 0 { + let min_target = match sample.balloon { + Some(_) if sample.mem_available < headroom => target.min(ceiling), Some(_) => 0, - None => target.min(ceiling).saturating_sub(mem_available.saturating_sub(MEMORY_HEADROOM)), + None => target.min(ceiling).saturating_sub(sample.mem_available.saturating_sub(headroom)), }; want.max(min_target) } else { @@ -114,75 +174,156 @@ enum PendingFallback { struct BalloonState { last_target: Option, pending: Option, + ws_peak: u64, + hold_until: Option, + last_decay: Option, } impl BalloonState { fn reset(&mut self) { self.last_target = None; self.pending = None; - } - - fn next_target(&mut self, stats: &kiri_proto::Stats, used: u64, ceiling: u64, target: u64) -> Option { + self.ws_peak = 0; + self.hold_until = None; + self.last_decay = None; + } + + fn next_target_at( + &mut self, + stats: &kiri_proto::Stats, + used: u64, + policy: BalloonPolicy, + target: u64, + pressure: bool, + now: std::time::Instant, + ) -> Option { + let ceiling = policy.ceiling; + let headroom = policy.headroom(); let mem_total = stats.mem_total_kib.saturating_mul(1024); let mem_available = stats.mem_available_kib.saturating_mul(1024); let balloon = stats.mem_balloon_kib.map(|k| k.saturating_mul(1024)); + let committed_as = stats.mem_committed_kib.map(|k| k.saturating_mul(1024)); let legacy_fallback = stats.mem_used_kib == 0 && balloon.is_none() && mem_total > 0; + let external_grow = self.last_target.is_some_and(|prev| target > prev); - if !legacy_fallback { - self.pending = None; - let next = next_memory_target(used, mem_total, mem_available, balloon, ceiling, target); - self.last_target = Some(next.unwrap_or(target)); - return next; - } + if legacy_fallback { + // An external grow (e.g. `grow_memory()` on pressure) raised `target` + // since the last poll: wait for deflation to show up in `MemAvailable` + // before allowing the target-derived fallback to grow again. + if external_grow { + self.pending = Some(PendingFallback::Grow { avail: mem_available, peak: mem_available }); + } - // An external grow (e.g. `grow_memory()` on pressure) raised `target` - // since the last poll: wait for deflation to show up in `MemAvailable` - // before allowing the target-derived fallback to grow again. - if self.last_target.is_some_and(|prev| target > prev) { - self.pending = Some(PendingFallback::Grow { avail: mem_available, peak: mem_available }); + match self.pending { + Some(PendingFallback::Grow { avail, mut peak }) => { + if mem_available > peak { + peak = mem_available; + } + let recovered = mem_available >= headroom + || (peak >= avail.saturating_add(MEMORY_DEADBAND) + && mem_available.saturating_add(MEMORY_DEADBAND) <= peak); + self.pending = (!recovered).then_some(PendingFallback::Grow { avail, peak }); + } + Some(PendingFallback::Shrink { avail, expected_avail, ticks }) => { + let settled = mem_available < headroom + || mem_available <= expected_avail.saturating_add(MEMORY_DEADBAND) + || mem_available >= avail.saturating_add(MEMORY_DEADBAND) + || ticks >= FALLBACK_SHRINK_SETTLE_TICKS; + self.pending = (!settled).then_some(PendingFallback::Shrink { + avail, + expected_avail, + ticks: ticks.saturating_add(1), + }); + } + None => {} + } + } else { + self.pending = None; } - match self.pending { - Some(PendingFallback::Grow { avail, mut peak }) => { - if mem_available > peak { - peak = mem_available; + let u_live = live_memory_need(used, mem_total, mem_available, balloon, ceiling).min(ceiling); + let u_commit = committed_memory_need(used, mem_total, committed_as, ceiling); + + // Hold working-set peak for `SHRINK_COOLDOWN` after any grow, pressure + // event, or new peak, then decay gently (at most 64 MiB per 5 s). + // During legacy fallback deflation lag (`PendingFallback::Grow`), + // `used` is temporarily inflated by `ceiling - target`, so don't raise + // `ws_peak` from that lag reading. + let legacy_grow_lag = legacy_fallback && matches!(self.pending, Some(PendingFallback::Grow { .. })); + if external_grow || pressure { + self.ws_peak = self.ws_peak.max(target.min(ceiling).saturating_sub(headroom)); + self.hold_until = Some(now + SHRINK_COOLDOWN); + self.last_decay = None; + } + if !legacy_grow_lag && u_live > self.ws_peak { + self.ws_peak = u_live; + self.hold_until = Some(now + SHRINK_COOLDOWN); + self.last_decay = None; + } + if !legacy_grow_lag && self.ws_peak > u_live { + if let Some(hold_until) = self.hold_until { + if now >= hold_until { + let decay_from = self.last_decay.map_or(hold_until, |t| t.max(hold_until)); + let elapsed = now.saturating_duration_since(decay_from); + let steps = (elapsed.as_nanos() / WS_PEAK_DECAY_INTERVAL.as_nanos()) as u64; + if steps > 0 { + let drop = steps.saturating_mul(WS_PEAK_DECAY_STEP); + if self.ws_peak.saturating_sub(drop) <= u_live { + self.ws_peak = u_live; + self.last_decay = Some(now); + } else { + self.ws_peak -= drop; + let next_anchor = u32::try_from(steps) + .ok() + .and_then(|s| WS_PEAK_DECAY_INTERVAL.checked_mul(s)) + .and_then(|d| decay_from.checked_add(d)) + .unwrap_or(now); + self.last_decay = Some(next_anchor); + } + } } - let recovered = mem_available >= MEMORY_HEADROOM - || (peak >= avail.saturating_add(MEMORY_DEADBAND) - && mem_available.saturating_add(MEMORY_DEADBAND) <= peak); - self.pending = (!recovered).then_some(PendingFallback::Grow { avail, peak }); - } - Some(PendingFallback::Shrink { avail, expected_avail, ticks }) => { - let settled = mem_available < MEMORY_HEADROOM - || mem_available <= expected_avail.saturating_add(MEMORY_DEADBAND) - || mem_available >= avail.saturating_add(MEMORY_DEADBAND) - || ticks >= FALLBACK_SHRINK_SETTLE_TICKS; - self.pending = (!settled).then_some(PendingFallback::Shrink { - avail, - expected_avail, - ticks: ticks.saturating_add(1), - }); } - None => {} } - let next = next_memory_target(used, mem_total, mem_available, None, ceiling, target); - let next = match (next, &self.pending) { - (Some(n), Some(PendingFallback::Grow { .. })) if n > target => None, - (Some(n), Some(PendingFallback::Shrink { .. })) if n < target => None, - (next, _) => next, + let sample = MemorySample { + used, + mem_total, + mem_available, + balloon: if legacy_fallback { None } else { balloon }, + committed_as, + ws_peak: self.ws_peak, + }; + let next = next_memory_target(sample, policy, target); + let next = if legacy_fallback { + match (next, &self.pending) { + (Some(n), Some(PendingFallback::Grow { .. })) if n > target => None, + (Some(n), Some(PendingFallback::Shrink { .. })) if n < target => None, + (next, _) => next, + } + } else { + next }; if let Some(n) = next { - self.pending = if n > target { - Some(PendingFallback::Grow { avail: mem_available, peak: mem_available }) - } else { - Some(PendingFallback::Shrink { - avail: mem_available, - expected_avail: mem_available.saturating_sub(target.saturating_sub(n)), - ticks: 0, - }) - }; + if n > target { + let demand = u_live.max(u_commit).min(ceiling); + if demand.saturating_add(headroom) > target { + self.ws_peak = self.ws_peak.max(demand); + } + self.hold_until = Some(now + SHRINK_COOLDOWN); + self.last_decay = None; + } + if legacy_fallback { + self.pending = if n > target { + Some(PendingFallback::Grow { avail: mem_available, peak: mem_available }) + } else { + Some(PendingFallback::Shrink { + avail: mem_available, + expected_avail: mem_available.saturating_sub(target.saturating_sub(n)), + ticks: 0, + }) + }; + } } self.last_target = Some(next.unwrap_or(target)); next @@ -243,7 +384,7 @@ pub fn max_cpus() -> usize { std::thread::available_parallelism().map_or(2, std::num::NonZero::get) } -/// What Settings → Resources saved, read at each boot: `{"cpus", "memory_mib"}`. +/// What Settings → Resources saved, read at each boot: `{"cpus", "memory_mib", "disk_gb"}`. pub fn resources_path() -> Option { super::state_dir().ok().map(|d| d.join("vm.json")) } @@ -252,6 +393,119 @@ pub fn resources() -> serde_json::Value { resources_path().and_then(|p| std::fs::read(p).ok()).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or(serde_json::Value::Null) } +/// Parses a boolean environment flag (`1`/`on`/`true`/`yes` or `0`/`off`/`false`/`no`). +pub fn parse_bool_env(raw: &str) -> Option { + match raw.trim().to_ascii_lowercase().as_str() { + "1" | "on" | "true" | "yes" => Some(true), + "0" | "off" | "false" | "no" => Some(false), + _ => None, + } +} + +/// Configured `shared_nat` from `vm.json`, if present. +pub fn vm_shared_nat_config() -> Option { + resources()["shared_nat"].as_bool() +} + +/// Explicit `KIRI_SHARED_NAT` override from the environment, if valid. +pub fn shared_nat_env() -> Option { + std::env::var("KIRI_SHARED_NAT").ok().and_then(|v| parse_bool_env(&v)) +} + +pub fn shared_nat_for(env: Option<&str>, configured: Option) -> bool { + env.and_then(parse_bool_env).or(configured).unwrap_or(true) +} + +/// Whether the macOS VM attaches `VZNATNetworkDeviceAttachment` (`KIRI_SHARED_NAT`, +/// else `vm.json`'s `shared_nat`, else `true`). Setting this to `false` avoids +/// starting macOS `InternetSharing` (#383, #350). +pub fn shared_nat() -> bool { + if !cfg!(target_os = "macos") { + return false; + } + let env = std::env::var("KIRI_SHARED_NAT").ok(); + shared_nat_for(env.as_deref(), vm_shared_nat_config()) +} + +/// The most swap Settings → Resources offers, in MiB. +pub const MAX_SWAP_MIB: u64 = 16 << 10; + +/// The VM's swap file on its data disk, in MiB (#326): `KIRI_SWAP_MIB`, +/// else Settings → Resources (`vm.json`'s `swap_mib`), else 1 GiB, as +/// Docker Desktop has. 0 is no swap. +pub fn vm_swap_mib() -> u64 { + swap_mib_for(std::env::var("KIRI_SWAP_MIB").ok().as_deref(), resources()["swap_mib"].as_u64()) +} + +pub fn swap_mib_for(env: Option<&str>, configured: Option) -> u64 { + env.and_then(|v| v.trim().parse().ok()).or(configured).unwrap_or(1024).min(MAX_SWAP_MIB) +} + +/// Configured `balloon` from `vm.json`, if present. +pub fn vm_balloon_config() -> Option { + resources()["balloon"].as_bool() +} + +/// Configured `memory_min_mib` from `vm.json`, if present. +pub fn vm_memory_min_mib_config() -> Option { + resources()["memory_min_mib"].as_u64() +} + +/// Whether dynamic memory ballooning is enabled given `KIRI_NO_BALLOON` and +/// `vm.json`'s `balloon` setting (defaults to `true`). +pub fn balloon_enabled_for(no_balloon_env: Option<&str>, configured: Option) -> bool { + if let Some(raw) = no_balloon_env { + match parse_bool_env(raw) { + Some(no_balloon) => return !no_balloon, + None if !raw.trim().is_empty() => return false, + None => {} + } + } + configured.unwrap_or(true) +} + +/// Whether the macOS VM dynamically adjusts its memory balloon +/// (`KIRI_NO_BALLOON`, else `vm.json`'s `balloon`, else `true`). +pub fn balloon_enabled() -> bool { + if !cfg!(target_os = "macos") { + return false; + } + match std::env::var_os("KIRI_NO_BALLOON") { + Some(v) => match v.to_str() { + Some(s) => balloon_enabled_for(Some(s), vm_balloon_config()), + None => false, + }, + None => balloon_enabled_for(None, vm_balloon_config()), + } +} + +/// Effective minimum memory floor in bytes from optional `memory_min_mib` in +/// `vm.json`, clamped to `0..=ceiling`. +pub fn memory_min_bytes_for(configured_mib: Option, ceiling: u64) -> u64 { + configured_mib.map_or(0, |mib| mib.saturating_mul(1 << 20).min(ceiling)) +} + +/// Effective minimum memory floor in bytes for `ceiling`, read from `vm.json`. +pub fn memory_min_bytes(ceiling: u64) -> u64 { + memory_min_bytes_for(vm_memory_min_mib_config(), ceiling) +} + +/// The VM's persistent data disk size from `vm.json`, if valid. +pub fn vm_disk_gb_config() -> Option { + resources()["disk_gb"] + .as_u64() + .filter(|&gb| crate::guest::disk::size_bytes(gb).is_ok()) +} + +/// The VM's effective data disk size in GiB: `KIRI_DISK_GB`, else +/// Settings → Resources (`vm.json`), else 64 GiB; never below the current +/// `data.img` size. +pub fn vm_disk_gb() -> u64 { + let env_os = std::env::var_os("KIRI_DISK_GB"); + let env_str = env_os.as_ref().and_then(|v| v.to_str()); + crate::guest::disk::effective_gb(env_str, vm_disk_gb_config(), crate::guest::disk::current_gb()) +} + pub fn physical_memory_bytes() -> u64 { physical_memory() } @@ -333,7 +587,7 @@ pub struct RestartPolicy { pub max_retries: u32, } -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Spec { pub image: String, pub image_id: String, @@ -363,9 +617,9 @@ pub struct Spec { /// `-p` bindings. #[serde(default)] pub ports: Vec, - /// TCP ports the image (or `--expose`) declares; picks the domain's port. - #[serde(default)] - pub exposed: Vec, + /// Port/protocol keys the image or `--expose` declares. + #[serde(default, deserialize_with = "deserialize_exposed")] + pub exposed: Vec, /// Bind mounts as the guest takes them: `source\ttarget\tflags`, where /// `source` is a path inside the VM. #[serde(default)] @@ -373,6 +627,11 @@ pub struct Spec { /// For `inspect`: Docker's `Mounts` entries. #[serde(default)] pub mount_info: Vec, + /// For `inspect`: HostConfig's `Binds`, `Mounts` and `Tmpfs` as create + /// gave them, and `Volumes` (Config's, with the image's VOLUME lines). + /// Null for a container saved before they were kept (#610). + #[serde(default)] + pub mount_request: serde_json::Value, /// Named volumes it uses (kept while it exists), and the anonymous ones /// created for it (deleted with it on `--rm` or `rm -v`). #[serde(default)] @@ -467,6 +726,47 @@ pub struct Spec { /// `container:`. #[serde(default)] pub pid_mode: String, + /// WSL 2 distro that created this container (`Caller::Wsl` or the engine's + /// own WSL distro on `Caller::Host`), when created in WSL. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub wsl_distro: Option, +} + +/// Normalizes an ExposedPorts key (`"53"`, `"53/UDP"`, `"132/sctp"`) to +/// `"/"`, ignoring port 0 and malformed entries. +pub(super) fn normalize_exposed_key(key: &str) -> Option { + let (port, proto) = key.split_once('/').unwrap_or((key, "tcp")); + if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + let port: u16 = port.parse().ok()?; + if port == 0 || proto.is_empty() || !proto.bytes().all(|b| b.is_ascii_alphanumeric()) { + return None; + } + Some(format!("{port}/{}", proto.to_ascii_lowercase())) +} + +/// Older containers.json records stored only TCP port numbers. +fn deserialize_exposed<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result, D::Error> { + #[derive(Deserialize)] + #[serde(untagged)] + enum Port { + Key(String), + Tcp(u16), + } + + let mut ports: Vec = Option::>::deserialize(deserializer)? + .unwrap_or_default() + .into_iter() + .filter_map(|port| match port { + Port::Key(key) => normalize_exposed_key(&key), + Port::Tcp(0) => None, + Port::Tcp(port) => Some(format!("{port}/tcp")), + }) + .collect(); + ports.sort_unstable(); + ports.dedup(); + Ok(ports) } /// One `--link name:alias`. @@ -492,9 +792,33 @@ pub struct Limits { /// kernel gets `cpu_weight`. 0 when not set, or saved before 0.2.3. #[serde(default)] pub cpu_shares: u64, + /// `--memory-swap`, as Docker's `HostConfig.MemorySwap`: memory plus + /// swap in bytes, -1 for no swap limit, 0 for none given. + #[serde(default)] + pub memory_swap: i64, } impl Limits { + /// `HostConfig.MemorySwap` as Docker reports it: twice the memory limit + /// when only that was given (containers saved before `memory_swap` too). + pub fn memory_swap(&self) -> i64 { + if self.memory_max > 0 && self.memory_swap == 0 { + i64::try_from(self.memory_max).unwrap_or(i64::MAX).saturating_mul(2) + } else { + self.memory_swap + } + } + + /// The cgroup's `memory.swap.max`: what `memory_swap` allows beyond the + /// memory limit. No memory limit, no swap limit, as with Docker. + fn swap_max(&self) -> u64 { + match self.memory_swap() { + _ if self.memory_max == 0 => kiri_proto::NO_LIMIT, + s if s < 0 => kiri_proto::NO_LIMIT, + s => (s as u64).saturating_sub(self.memory_max), + } + } + pub fn wire(&self) -> kiri_proto::Limits { kiri_proto::Limits { memory_max: self.memory_max, @@ -503,6 +827,7 @@ impl Limits { cpu_weight: self.cpu_weight, pids_max: self.pids_max, shm_size: self.shm_size, + swap_max: self.swap_max(), } } } @@ -514,22 +839,23 @@ impl Spec { self.network_mode == network || (network == "bridge" && matches!(self.network_mode.as_str(), "default" | "")) } - /// Leaves the first network of a container that is not running, as + /// Leaves the first network of a container (running or stopped), as /// `docker network disconnect` does on Docker for any of its networks. /// Kiri keeps the first network apart (`network_mode`, `aliases`, /// `ipv4_address`, `ipv6_address`, `mac_address`) because only it gives /// the default route and the main address, so one of the others takes /// its place, with its own aliases, fixed addresses and MAC: none of the /// left network's settings follow, or a fixed `--ip` would be asked for - /// on a network it does not belong to. The one picked is the one Docker - /// gives the default route to: a network that reaches outside before an - /// `internal` one (which gives no default route), then by name, as - /// libnetwork orders a container's endpoints when none has a gateway - /// priority (Kiri keeps none), and as create picks the primary of - /// several endpoints. `internal` says whether a network is internal. - /// With no other network it is left with none, as with `--network none`. + /// on a network it does not belong to. The one picked is the first + /// remaining network in attachment order that reaches outside (not + /// `internal`), or the first one if every remaining network is + /// `internal`, matching `kiri-init`'s `route_holders` (which keeps the + /// first-plugged non-internal uplink on the default route) and + /// `start_on_vm` (which attaches `network_mode` then `extra_networks` in + /// order). `internal` says whether a network is internal. With no other + /// network it is left with none, as with `--network none`. pub fn leave_first_network(&mut self, internal: impl Fn(&str) -> bool) { - let next = self.extra_networks.iter().enumerate().min_by(|(_, a), (_, b)| internal(&a.name).cmp(&internal(&b.name)).then_with(|| a.name.cmp(&b.name))).map(|(i, _)| i); + let next = self.extra_networks.iter().position(|x| !internal(&x.name)).or_else(|| (!self.extra_networks.is_empty()).then_some(0)); match next { Some(i) => { let x = self.extra_networks.remove(i); @@ -788,6 +1114,11 @@ pub struct Container { pub paused: bool, /// Addresses on `spec.extra_networks` while running, as (network, ip). pub extra_ips: Vec<(String, [u8; 4])>, + /// The interface `spec.network_mode` is plugged in as while running, as + /// `n` for `eth{n}`: `Some(0)` at start on a bridge network, or the + /// promoted network's number after leaving the first; `None` when stopped + /// or after leaving all networks. + pub first_if: Option, /// The interface each extra network is plugged in as while running, /// as (network, n) for `eth{n}`. A disconnect leaves a gap, so the /// number can't be worked out from the network's place in the list. @@ -886,7 +1217,7 @@ fn lock_log(l: &Mutex) -> MutexGuard<'_, super::logfile::Lo } /// What `containers.json` holds for one container. -#[derive(Serialize, Deserialize)] +#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)] struct Saved { id: String, name: String, @@ -907,6 +1238,84 @@ struct Saved { health: Option, } +#[cfg(test)] +impl Saved { + fn from_container(c: &Container, health: Option<&super::health::Health>) -> Self { + Saved { + id: c.id.clone(), + name: c.name.clone(), + spec: c.spec.clone(), + layers: c.layers.clone(), + created_ns: ns(c.created), + status: c.status, + started_ns: c.started.map(ns), + finished_ns: c.finished.map(ns), + exit_code: c.exit_code, + oom_killed: c.oom_killed, + vm_stopped: c.vm_stopped, + stopped_by_user: c.stopped_by_user, + restart_count: c.restart_count, + health: health.cloned(), + } + } +} + +#[cfg(test)] +impl From<&Container> for Saved { + fn from(c: &Container) -> Self { + Self::from_container(c, None) + } +} + +/// Borrowed view of [`Saved`] for zero-clone serialization in [`Engine::save`]. +#[derive(Serialize)] +struct SavedRef<'a> { + id: &'a str, + name: &'a str, + spec: &'a Spec, + layers: &'a [String], + created_ns: u64, + status: Status, + started_ns: Option, + finished_ns: Option, + exit_code: i32, + #[serde(default)] + oom_killed: bool, + #[serde(default)] + vm_stopped: bool, + stopped_by_user: bool, + restart_count: u32, + #[serde(default)] + health: Option<&'a super::health::Health>, +} + +impl<'a> SavedRef<'a> { + fn from_container(c: &'a Container, health: Option<&'a super::health::Health>) -> Self { + SavedRef { + id: &c.id, + name: &c.name, + spec: &c.spec, + layers: &c.layers, + created_ns: ns(c.created), + status: c.status, + started_ns: c.started.map(ns), + finished_ns: c.finished.map(ns), + exit_code: c.exit_code, + oom_killed: c.oom_killed, + vm_stopped: c.vm_stopped, + stopped_by_user: c.stopped_by_user, + restart_count: c.restart_count, + health, + } + } +} + +impl<'a> From<&'a Container> for SavedRef<'a> { + fn from(c: &'a Container) -> Self { + Self::from_container(c, None) + } +} + /// What `load` reads of `containers.json`. struct Records { saved: Vec, @@ -919,6 +1328,53 @@ struct Records { on_disk: Option<(usize, u64)>, } +/// The highest interface `free_eth` will scan to (there is never more than +/// one per network, but a damaged `containers.json` could claim any number: +/// the bound keeps a broken file from a near-u32 scan under the engine lock). +/// The caller turns running out into a Conflict, so `connect` fails, not hangs. +const MAX_ETH_IFS: u32 = 4095; + +/// The lowest unused `eth{n}` interface index at or above `min`; `None` when +/// nothing in the range is free. +fn free_eth(c: &Container, min: u32) -> Option { + (min..=MAX_ETH_IFS).find(|n| c.first_if != Some(*n) && !c.extra_ifs.iter().any(|(_, x)| x == n)) +} + +/// Reconstructs port bindings to target a newly promoted network IP while +/// preserving ephemeral host ports already bound for `0` entries. +fn rebind_bindings(ports: &[super::ports::Binding], bound: &[(super::ports::Binding, String, u16)]) -> Vec { + ports + .iter() + .map(|b| { + let host_port = if b.host_port == 0 { + bound.iter().find(|(bb, ..)| bb == b).map_or(0, |(_, _, p)| *p) + } else { + b.host_port + }; + super::ports::Binding { host_port, ..b.clone() } + }) + .collect() +} + +/// The guest IPv4 address that host-side port forwards for a running container +/// target, or `None` when the container's network mode publishes no host forwards. +/// +/// On macOS (`!host_shares_netns`), a `--network host` container runs inside the +/// Linux VM's network namespace rather than macOS's own kernel, so Mac-side `-p` +/// listeners still bind on the Mac and forward to `127.0.0.1` in the guest (#732). +/// On Linux (`host_shares_netns`), `--network host` is the daemon's own network +/// namespace, so published `PortBindings` are discarded at runtime as Docker does +/// and the container binds its ports directly without `EADDRINUSE` (#764). +fn port_forward_target(network_mode: &str, ip: Option<[u8; 4]>, host_shares_netns: bool) -> Option<[u8; 4]> { + if network_mode == "none" || network_mode.starts_with("container:") { + None + } else if network_mode == "host" { + (!host_shares_netns).then_some([127, 0, 0, 1]) + } else { + ip.filter(|&a| a != [0; 4]) + } +} + /// Length and hash of a file's bytes, enough to tell whether it is the one /// this engine last read or wrote. fn fingerprint(bytes: &[u8]) -> (usize, u64) { @@ -1117,6 +1573,33 @@ struct State { removed: VecDeque<(String, i32)>, /// `State.Health` of containers with a healthcheck, by id. health: HashMap, + /// Unpacked layer digests pinned by in-flight creates (from image lookup + /// until the container is inserted into `containers`), with refcounts so + /// concurrent `prune_layers` never deletes a layer being unpacked (#722). + pinned_layers: HashMap, +} + +/// Keeps layer digests in `retained_layers` until dropped (see `Engine::pin_layers`). +pub(super) struct LayerPin<'a> { + engine: &'a Engine, + digests: Vec, +} + +impl Drop for LayerPin<'_> { + fn drop(&mut self) { + if self.digests.is_empty() { + return; + } + let mut st = self.engine.lock(); + for d in &self.digests { + if let Some(n) = st.pinned_layers.get_mut(d) { + *n -= 1; + if *n == 0 { + st.pinned_layers.remove(d); + } + } + } + } } /// Set while the daemon shuts down: exits then are not restarts. @@ -1216,10 +1699,28 @@ pub struct Engine { ceiling: std::sync::atomic::AtomicU64, /// CPUs the running VM has. cpus: std::sync::atomic::AtomicUsize, + /// Data disk capacity in GiB the running VM booted with (macOS). + disk_gb: std::sync::atomic::AtomicU64, + /// Swap in MiB the running VM booted with (macOS). + swap_mib: std::sync::atomic::AtomicU64, + /// Whether the running macOS VM booted with `VZNATNetworkDeviceAttachment`. + shared_nat: std::sync::atomic::AtomicBool, + /// Whether the running macOS VM dynamically adjusts its memory balloon + /// (`KIRI_NO_BALLOON`, else `vm.json`'s `balloon`, else `true`). + balloon_enabled: std::sync::atomic::AtomicBool, + /// Optional minimum memory floor in bytes (`vm.json`'s `memory_min_mib`, + /// clamped to `0..=ceiling`). + memory_min: std::sync::atomic::AtomicU64, + /// Monotonic count of guest `Event::Pressure` notifications so the balloon + /// loop refreshes its shrink cooldown even when `target == ceiling`. + pressure_events: std::sync::atomic::AtomicU64, memory_target: Mutex, /// What the guest last used, in bytes (0 while asleep): the balloon's /// measure, without the pages the balloon itself holds. memory_used: std::sync::atomic::AtomicU64, + /// The guest's last MemAvailable from /proc/meminfo, in KiB (0 while + /// asleep): the figure behind a memory kill's log line. + mem_available_kib: std::sync::atomic::AtomicU64, /// How starved of memory the guest is: PSI "full avg10" in hundredths /// of a percent (0 while asleep), and processes killed for memory since it booted. memory_stall: std::sync::atomic::AtomicU64, @@ -1229,6 +1730,11 @@ pub struct Engine { cpu_permyriad: std::sync::atomic::AtomicU32, /// `docker events`: recent ones for `--since`, and who is listening. events: Mutex, + /// The op under which each container is being stopped (a restartvm, a + /// recreate, `kiri k8s set`), so its exit is attributed to that + /// operation instead of a memory kill. Cleared on exit, destroy, restart + /// or VM loss. + stopping_ops: Mutex>, /// Kubernetes LoadBalancer services published on the Mac's localhost: /// (port, protocol) → its forward. k8s_lb: Mutex>, @@ -1243,6 +1749,54 @@ pub struct Engine { /// Configs are content-addressed, so an entry never goes stale; entries /// of images no longer stored are dropped on the next listing. image_labels: Mutex>, + /// The running VM's uplink status for `/info` and `kiri diag report` (#435). + uplink: Mutex, + /// Persisted and short-TTL cached volume byte sizes (`GET /kiri/volumes/sizes` + /// and `/volume-sizes.json`), tracking volumes dirtied since the + /// last guest disk measurement while leaving `GET /system/df` live. + volume_sizes_cache: Mutex, +} + +struct VolumeSizesCache { + path: PathBuf, + generation: u64, + measured_at: Option, + sizes: HashMap, + dirty: HashSet, +} + +pub(super) struct VolumeSizesSnapshot { + pub generation: u64, + pub fresh_ttl: bool, + pub sizes: HashMap, + pub dirty: HashSet, +} + +impl VolumeSizesCache { + fn load(root: &std::path::Path, current: &[super::volumes::Volume]) -> VolumeSizesCache { + let path = root.join("volume-sizes.json"); + let mut sizes: HashMap = match std::fs::read(&path) { + Ok(b) => serde_json::from_slice(&b).unwrap_or_default(), + Err(_) => HashMap::new(), + }; + sizes.retain(|k, _| current.iter().any(|v| v.name == *k && v.options.is_empty())); + VolumeSizesCache { + path, + generation: 0, + measured_at: None, + sizes, + dirty: HashSet::new(), + } + } + + fn save(&self) { + if let Ok(json) = serde_json::to_vec(&self.sizes) { + let tmp = self.path.with_extension("json.tmp"); + if let Err(e) = std::fs::write(&tmp, json).and_then(|()| std::fs::rename(&tmp, &self.path)) { + crate::diag::error!("saving volume sizes failed", error = e); + } + } + } } /// k3s's pod and service ranges, which `kiri k8s` leaves at their defaults. @@ -1267,6 +1821,26 @@ struct Events { listeners: Vec>, } +/// Diagnostic classification for a container exit (`Engine::classify_exit`). +#[derive(Debug, PartialEq, Eq)] +enum ExitLog { + MemoryKill { + name: String, + exit_code: i32, + mem_available_mib: u64, + psi_full_avg10: u64, + /// `(target_mib, ceiling_mib)` on macOS after balloon relief; `None` on + /// Linux hosts, which have no balloon. + balloon: Option<(u64, u64)>, + }, + OpStop { + kind: String, + name: String, + exit_code: i32, + op: String, + }, +} + impl std::fmt::Debug for Engine { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Engine") @@ -1279,6 +1853,7 @@ pub enum Error { Conflict(String), BadRequest(String), Unauthorized(String), + Forbidden(String), Io(io::Error), } @@ -1310,7 +1885,9 @@ impl Engine { let records = store.root().join("containers.json"); let ceiling = memory_ceiling(); let networks = Mutex::new(Networks::load(store.root())?); - let volumes = Mutex::new(super::volumes::Volumes::load(store.root())?); + let loaded_volumes = super::volumes::Volumes::load(store.root())?; + let volume_sizes_cache = Mutex::new(VolumeSizesCache::load(store.root(), loaded_volumes.all())); + let volumes = Mutex::new(loaded_volumes); let engine = Arc::new(Engine { volumes, link: Mutex::new(None), @@ -1338,16 +1915,26 @@ impl Engine { parking: std::sync::atomic::AtomicBool::new(false), ceiling: std::sync::atomic::AtomicU64::new(ceiling), cpus: std::sync::atomic::AtomicUsize::new(vm_cpus()), + disk_gb: std::sync::atomic::AtomicU64::new(vm_disk_gb()), + swap_mib: std::sync::atomic::AtomicU64::new(vm_swap_mib()), + shared_nat: std::sync::atomic::AtomicBool::new(shared_nat()), + balloon_enabled: std::sync::atomic::AtomicBool::new(balloon_enabled()), + memory_min: std::sync::atomic::AtomicU64::new(memory_min_bytes(ceiling)), + pressure_events: std::sync::atomic::AtomicU64::new(0), memory_target: Mutex::new(ceiling), memory_used: std::sync::atomic::AtomicU64::new(0), + mem_available_kib: std::sync::atomic::AtomicU64::new(0), memory_stall: std::sync::atomic::AtomicU64::new(0), oom_kills: std::sync::atomic::AtomicU64::new(0), cpu_permyriad: std::sync::atomic::AtomicU32::new(0), events: Mutex::new(Events::default()), + stopping_ops: Mutex::new(HashMap::new()), k8s_lb: Mutex::new(HashMap::new()), k8s_routes: Mutex::new(None), k8s_fwd: Mutex::new(HashMap::new()), image_labels: Mutex::new(HashMap::new()), + uplink: Mutex::new(serde_json::Value::Null), + volume_sizes_cache, }); let _ = engine.me.set(Arc::downgrade(&engine)); engine.start_syncer(); @@ -1367,10 +1954,75 @@ impl Engine { self.records_damage.lock().unwrap_or_else(|e| e.into_inner()).message(&self.records).into_iter().collect() } + /// Actionable error when Kiri's Linux / WSL 2 storage filesystem is + /// mounted read-only (`ST_RDONLY`, `ro`, or ext4 `emergency_ro`, #768). + pub fn storage_readonly(&self) -> Option { + super::rofs::check_daemon_storage(Some(self.store.root())) + } + + /// Whether Kiri's Linux volumes directory sits on ZFS (#607). + pub fn storage_zfs(&self) -> bool { + super::rofs::is_daemon_storage_zfs(Some(self.store.root())) + } + /// What the agent found wrong with a Linux host, for `docker info` - /// (`VmLink::host_warnings`). + /// (`VmLink::host_warnings`), a read-only storage filesystem, or a Mac VM + /// uplink fallback failure. pub fn host_warnings(&self) -> Vec { - self.awake().map(|vm| vm.host_warnings()).unwrap_or_default() + let mut out: Vec = self.storage_readonly().into_iter().collect(); + out.extend(self.awake().map(|vm| vm.host_warnings()).unwrap_or_default()); + if let Some(w) = self.uplink.lock().unwrap_or_else(|e| e.into_inner())["warning"].as_str() { + out.push(w.to_owned()); + } + out + } + + /// The running VM's uplink status for `/info` and `kiri diag report`. + pub fn uplink_info(&self) -> serde_json::Value { + self.uplink.lock().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// Waits up to 2 s for macOS `bootpd` to lease `eth0` in the VM; if DHCP + /// does not answer (e.g. another app bound UDP port 67), configures the + /// VM's uplink directly from the Mac's `vmnet` bridge (#435). + #[cfg(target_os = "macos")] + fn ensure_uplink(&self, vm: &VmLink) { + let deadline = std::time::Instant::now() + Duration::from_secs(2); + loop { + if let Ok((ip, gw)) = vm.uplink() { + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = serde_json::json!({ + "mode": "dhcp", + "ip": std::net::Ipv4Addr::from(ip).to_string(), + "gateway": std::net::Ipv4Addr::from(gw).to_string(), + }); + return; + } + if vm.is_disconnected() { + return; + } + let left = deadline.saturating_duration_since(std::time::Instant::now()); + if left.is_zero() { + break; + } + std::thread::sleep(left.min(Duration::from_millis(100))); + } + let udp67 = super::vmnet::udp67_holder(); + let status = match super::vmnet::discover_uplink(self.store.root()) + .and_then(|(b, ip)| vm.set_uplink(ip, b.prefix, b.gateway, b.gateway).map(|()| (b, ip)).map_err(|e| e.to_string())) + { + Ok((b, addr)) => { + let (ip, gw) = (format!("{}/{}", std::net::Ipv4Addr::from(addr), b.prefix), std::net::Ipv4Addr::from(b.gateway).to_string()); + crate::diag::warn!("VM DHCP did not answer; configured VM uplink directly from Mac", bridge = b.name, ip = ip, gateway = gw, dns = gw, udp67 = udp67.as_deref().unwrap_or("none visible")); + serde_json::json!({"mode": "static-fallback", "bridge": b.name, "ip": ip, "gateway": gw, "dns": gw, "udp67": udp67}) + } + Err(reason) => { + crate::diag::warn!("VM DHCP did not answer and static uplink fallback failed", error = reason, udp67 = udp67.as_deref().unwrap_or("none visible")); + let holder = udp67.as_deref().map(|h| format!(" (UDP port 67 held by {h})")).unwrap_or_default(); + let warning = format!("VM has no IPv4 uplink: DHCP did not answer and static fallback failed: {reason}{holder}"); + serde_json::json!({"mode": "fallback-failed", "reason": reason, "udp67": udp67, "warning": warning}) + } + }; + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = status; } /// Why unpacked layers may belong to images the image list lost, for @@ -1442,9 +2094,15 @@ impl Engine { if recovery && !self.lock().containers.values().any(recover_after_vm_loss) { return Err(io::Error::new(io::ErrorKind::WouldBlock, "VM recovery was canceled")); } - let (ceiling, cpus) = (memory_ceiling(), vm_cpus()); + let (ceiling, cpus, disk_cfg, shared_nat, balloon, swap) = (memory_ceiling(), vm_cpus(), vm_disk_gb_config(), shared_nat(), balloon_enabled(), vm_swap_mib()); + let memory_min = memory_min_bytes(ceiling); self.ceiling.store(ceiling, std::sync::atomic::Ordering::Relaxed); self.cpus.store(cpus, std::sync::atomic::Ordering::Relaxed); + self.swap_mib.store(swap, std::sync::atomic::Ordering::Relaxed); + self.shared_nat.store(shared_nat, std::sync::atomic::Ordering::Relaxed); + self.balloon_enabled.store(balloon, std::sync::atomic::Ordering::Relaxed); + self.memory_min.store(memory_min, std::sync::atomic::Ordering::Relaxed); + super::ports::set_shared_nat_active(Some(shared_nat)); let t0 = std::time::Instant::now(); #[cfg(test)] self.boot_attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst); @@ -1453,9 +2111,20 @@ impl Engine { console_log: crate::diag::console::path().ok(), memory_mib: Some(ceiling >> 20), cpus: Some(cpus), + disk_gb: disk_cfg, + shared_nat: Some(shared_nat), + swap_mib: Some(swap), ..Default::default() }) - .inspect_err(|e| crate::diag::error!("VM did not boot", error = e))?; + .map_err(|e| match self.storage_readonly() { + Some(ro) => io::Error::new(e.kind(), ro), + None => e, + }) + .inspect_err(|e| { + super::ports::set_shared_nat_active(None); + crate::diag::error!("VM did not boot", error = e); + })?; + self.disk_gb.store(crate::guest::disk::current_gb(), std::sync::atomic::Ordering::Relaxed); let (vm, conn) = guest.into_parts(); let me = self.me.get().cloned().unwrap_or_default(); let vm = Arc::new(VmLink::new(vm, conn, move |ev| { @@ -1465,6 +2134,8 @@ impl Engine { })?); // host.docker.internal: the guest dials back for each connection. vm.listen(super::ports::HOST_BOUND_PORT, Box::new(super::ports::serve_host_bound))?; + // Outbound container TCP to VPN tunnel routes or under host egress. + vm.listen(kiri_proto::EGRESS_TCP_PORT, Box::new(super::ports::serve_egress))?; // SSH agent forwarding, for containers that mount /run/host-services/ssh-auth.sock. vm.listen(super::ports::SSH_AGENT_PORT, Box::new(super::ports::serve_ssh_agent))?; // The engine's API, for containers that mount /var/run/docker.sock @@ -1478,6 +2149,17 @@ impl Engine { if cfg!(target_os = "macos") { vm.listen(kiri_proto::DNS_RELAY_PORT, Box::new(super::dns::serve_relay))?; } + // The VM's own NAT subnet, which the host egress dialer must refuse + // (VM only). Without a lease yet the default subnet still covers it, + // and publishing a port learns it again. Skipped when shared NAT is + // disabled (no `VZNATNetworkDeviceAttachment` / `eth0`). + if cfg!(target_os = "macos") && shared_nat { + match vm.uplink() { + Ok((_ip, gateway)) => super::ports::set_vm_subnet(gateway, super::ports::VM_UPLINK_PREFIX), + Err(e) => crate::diag::debug!("VM uplink not known yet", error = e), + } + } + super::ports::sync_egress_routes(&vm); // Everything else on the guest's disk belongs to containers that are // gone, unless the container list was damaged: then a container // missing from it may still be someone's, and so may the layers only @@ -1491,24 +2173,20 @@ impl Engine { // the image list can't be read, rather than deleting everything, and // while a damaged copy of it is kept: images cut from the list may // still be someone's (#440). - let image_damage = self.store.index_damage(); - match self.store.images() { - _ if keep.is_none() => {} - _ if !matches!(image_damage, Ok(None)) => { - crate::diag::warn!("kept every unpacked layer: the image list was damaged", detail = image_damage_message(&image_damage, self.store.root()).unwrap_or_default()); - } - Ok(images) => { - let mut layers: std::collections::BTreeSet = images.iter().flat_map(|i| i.layers.iter().map(|l| l.digest.clone())).collect(); - layers.extend(self.lock().containers.values().flat_map(|c| c.layers.iter().cloned())); - vm.retain_layers(&layers.into_iter().collect::>())?; - } - Err(e) => crate::diag::warn!("kept every unpacked layer: images unreadable", error = e), + if let Some(layers) = self.retained_layers() { + vm.retain_layers(&layers)?; } *self.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = ceiling; self.sleeping.store(false, std::sync::atomic::Ordering::SeqCst); self.lock().vm_booted_at = Some(std::time::Instant::now()); + #[cfg(target_os = "macos")] + if shared_nat { + self.ensure_uplink(&vm); + } else { + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = serde_json::json!({"mode": "host-egress"}); + } *self.link.lock().unwrap_or_else(|e| e.into_inner()) = Some(vm.clone()); - crate::diag::info!("VM booted", ms = t0.elapsed().as_millis(), cpus = cpus, memory_mib = ceiling >> 20); + crate::diag::info!("VM booted", ms = t0.elapsed().as_millis(), cpus = cpus, memory_mib = ceiling >> 20, shared_nat = shared_nat); drop(waking); self.recover_vm(); Ok(vm) @@ -1648,8 +2326,9 @@ impl Engine { /// `kiri k8s`: every LoadBalancer service gets its port on the Mac's /// localhost, as OrbStack and Docker Desktop do. k3s's service load /// balancer already serves the port on the node, so a forward to the - /// node container is all it takes. Checked every few seconds while the - /// cluster runs; forwards go when services or the cluster do. + /// node container is all it takes. Reconciled once on cluster start and + /// then driven by a single `kubectl get svc -A --watch-only` stream so an + /// idle cluster never spawns periodic `/bin/k3s` processes (#989). fn start_k8s_lb(self: &Arc) { let me = Arc::downgrade(self); // `kiri k8s set --lan on` puts them on every interface; a change rebinds them. @@ -1657,58 +2336,120 @@ impl Engine { let _ = std::thread::Builder::new().name("kiri-k8s-lb".into()).spawn(move || loop { std::thread::sleep(Duration::from_secs(3)); let Some(engine) = me.upgrade() else { return }; - let node = engine.lock().containers.values().find(|c| c.status == Status::Running && c.spec.labels.get("dev.kiri.k8s").is_some()).map(|c| (c.id.clone(), c.ip)); + let node = engine.lock().containers.values().find(|c| c.status == Status::Running && is_k8s_node(&c.spec)).map(|c| (c.id.clone(), c.ip)); let Some((id, Some(ip))) = node else { - engine.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); - engine.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); - if let Some((_, via)) = engine.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take() - && let Some(vm) = engine.awake() - { - for (net, bits) in K8S_RANGES { - let _ = vm.route(net, bits, via, false); - } - } + engine.clear_k8s_lb(); continue; }; - engine.route_k8s(ip); - let query = r#"jsonpath={range .items[?(@.spec.type=="LoadBalancer")]}{range .spec.ports[*]}{.port}/{.protocol} {end}{end}"#; - let Ok((0, out)) = engine.exec_capture(&id, &["timeout", "-s", "KILL", "20", "kubectl", "get", "svc", "-A", "-o", query]) else { continue }; - let wanted: Vec<(u16, String)> = out - .split_whitespace() - .filter_map(|p| { - let (port, proto) = p.split_once('/')?; - Some((port.parse().ok()?, proto.to_ascii_lowercase())) - }) - .collect(); - let Some(vm) = engine.awake() else { continue }; - let host_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; - let mut lb = engine.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()); - if vm.is_disconnected() { + if !engine.reconcile_k8s_lb(&id, ip, &mut bound_on) { continue; } - if bound_on != host_ip { - lb.clear(); - bound_on = host_ip.to_owned(); - } - lb.retain(|k, _| wanted.contains(k)); - for (port, proto) in wanted { - if lb.contains_key(&(port, proto.clone())) { - continue; - } - let b = super::ports::Binding { container_port: port, proto: proto.clone(), host_ip: host_ip.into(), host_port: port }; - match super::ports::start(vm.clone(), &format!("lb-{port}-{proto}"), &[b], ip) { - Ok(fw) => { - crate::diag::info!("Kubernetes service published", at = format!("{host_ip}:{port}/{proto}")); - lb.insert((port, proto), fw); + let watch_cfg = ExecConfig { + console_size: None, + argv: ["kubectl", "get", "svc", "-A", "--watch-only", "--no-headers"].map(String::from).to_vec(), + env: Vec::new(), + cwd: "/".into(), + user: String::new(), + tty: false, + stdin: false, + privileged: false, + internal: true, + }; + let Ok(watch_id) = engine.exec_create(&id, watch_cfg) else { continue }; + let Ok((_, rx)) = engine.exec_start(&watch_id) else { + engine.lock().execs.remove(&watch_id); + continue; + }; + loop { + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(_) => { + // Coalesce bursts of service updates into a single reconciliation. + while rx.recv_timeout(Duration::from_millis(150)).is_ok() {} + let Some(engine) = me.upgrade() else { return }; + let still_up = engine.lock().containers.get(&id).is_some_and(|c| c.status == Status::Running && c.ip == Some(ip)); + if !still_up { + engine.clear_k8s_lb(); + break; + } + let _ = engine.reconcile_k8s_lb(&id, ip, &mut bound_on); + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + let Some(engine) = me.upgrade() else { return }; + let still_up = engine.lock().containers.get(&id).is_some_and(|c| c.status == Status::Running && c.ip == Some(ip)); + if !still_up { + engine.clear_k8s_lb(); + break; + } + let want_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; + if bound_on != want_ip { + let _ = engine.reconcile_k8s_lb(&id, ip, &mut bound_on); + } } - Err(e) => crate::diag::warn!("Kubernetes service port not published", port = format!("{port}/{proto}"), error = e), + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, } } + if let Some(engine) = me.upgrade() { + engine.lock().execs.remove(&watch_id); + } else { + return; + } }); } - /// Routes the cluster's pod and service ranges to the node, so the - /// relay can reach a ClusterIP or a pod as it reaches a container: the + fn clear_k8s_lb(&self) { + self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); + if let Some((_, via)) = self.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take() + && let Some(vm) = self.awake() + { + for (net, bits) in K8S_RANGES { + let _ = vm.route(net, bits, via, false); + } + } + } + + fn reconcile_k8s_lb(&self, id: &str, ip: [u8; 4], bound_on: &mut String) -> bool { + self.route_k8s(ip); + let query = r#"jsonpath={range .items[?(@.spec.type=="LoadBalancer")]}{range .spec.ports[*]}{.port}/{.protocol} {end}{end}"#; + let Ok((0, out)) = self.exec_capture(id, &["timeout", "-s", "KILL", "20", "kubectl", "get", "svc", "-A", "-o", query]) else { + return false; + }; + let wanted: Vec<(u16, String)> = out + .split_whitespace() + .filter_map(|p| { + let (port, proto) = p.split_once('/')?; + Some((port.parse().ok()?, proto.to_ascii_lowercase())) + }) + .collect(); + let Some(vm) = self.awake() else { return false }; + let host_ip = if crate::k8s::config().lan { "0.0.0.0" } else { "127.0.0.1" }; + let mut lb = self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()); + if vm.is_disconnected() { + return false; + } + if bound_on != host_ip { + lb.clear(); + *bound_on = host_ip.to_owned(); + } + lb.retain(|k, _| wanted.contains(k)); + for (port, proto) in wanted { + if lb.contains_key(&(port, proto.clone())) { + continue; + } + let b = super::ports::Binding { container_port: port, proto: proto.clone(), host_ip: host_ip.into(), host_port: port }; + match super::ports::start(vm.clone(), &format!("lb-{port}-{proto}"), &[b], ip) { + Ok(fw) => { + crate::diag::info!("Kubernetes service published", at = format!("{host_ip}:{port}/{proto}")); + lb.insert((port, proto), fw); + } + Err(e) => crate::diag::warn!("Kubernetes service port not published", port = format!("{port}/{proto}"), error = e), + } + } + true + } + + /// Routes the cluster's pod and service ranges to the node, so the + /// relay can reach a ClusterIP or a pod as it reaches a container: the /// node's kube-proxy takes it from there. Again after the VM wakes (a new /// VM has none) or the node's address changes. fn route_k8s(&self, node: [u8; 4]) { @@ -1822,8 +2563,14 @@ impl Engine { return false; } let Some(vm) = self.link.lock().unwrap_or_else(|e| e.into_inner()).clone() else { return false }; + if self.volume_list().iter().any(|v| v.options.is_empty()) + && let Some(lines) = vm.usage(Duration::from_secs(15)) + { + self.cache_volume_sizes(None, super::ops::parse_volume_usage(&lines)); + } self.sleeping.store(true, std::sync::atomic::Ordering::SeqCst); self.memory_used.store(0, std::sync::atomic::Ordering::Relaxed); + self.mem_available_kib.store(0, std::sync::atomic::Ordering::Relaxed); self.memory_stall.store(0, std::sync::atomic::Ordering::Relaxed); vm.shutdown(); // Let the guest flush its disk and power off before the VM is dropped. @@ -1864,6 +2611,57 @@ impl Engine { } } + /// Settings → Storage, before the data folder is copied: every container + /// stopped and the VM off, as for a Stop, but without the file that + /// keeps a Stop across restarts; nothing boots the VM again until + /// `resume_after_move`. The container list is written and synced, so + /// the copy has it as it stands. Returns the containers that were + /// running, and whether Kiri was stopped already. + pub fn park_for_move(&self) -> Result<(Vec, bool), Error> { + let running = self.each(|c| (c.status == Status::Running).then(|| c.id.clone())); + let was_stopped = self.stopped.swap(true, std::sync::atomic::Ordering::SeqCst); + if let Err(e) = self.sleep_now() { + self.resume_after_move(was_stopped, running); + return Err(e); + } + self.save(); + self.sync_records(); + Ok((running, was_stopped)) + } + + /// A move that did not finish: Kiri carries on where it was, and the + /// containers that were running start again, held ones first (in the + /// order that starts joined containers after the ones they join). + pub fn resume_after_move(&self, was_stopped: bool, running: Vec) { + if was_stopped { + return; + } + self.stopped.store(false, std::sync::atomic::Ordering::SeqCst); + let mut ids = std::mem::take(&mut *self.held_restarts.lock().unwrap_or_else(|e| e.into_inner())); + for id in running { + if !ids.contains(&id) { + ids.push(id); + } + } + if let Some(me) = self.me.get().and_then(Weak::upgrade) { + std::thread::spawn(move || me.start_again(&ids)); + } + } + + /// Starts `ids` that aren't running: after a move, the containers that + /// ran before it (a restart policy may have started some already). + pub fn start_again(&self, ids: &[String]) { + for id in ids { + let running = self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running); + if running { + continue; + } + if let Err(e) = self.start(id) { + crate::diag::warn!("container did not start again after the move", id = &id[..id.len().min(12)], error = format!("{e:?}")); + } + } + } + /// Starts the held containers (`held_restarts`), one at a time, each /// taken from the list as it starts: Start, or `retry_held` once the VM /// boots. A Stop meanwhile ends it: the rest stay held for the next @@ -1988,15 +2786,34 @@ impl Engine { self.cpus.load(std::sync::atomic::Ordering::Relaxed) } + /// Data disk capacity in GiB the VM has (or will boot with). + pub fn disk_gb(&self) -> u64 { + self.disk_gb.load(std::sync::atomic::Ordering::Relaxed) + } + + /// Swap in MiB the VM has (or will boot with). + pub fn swap_mib(&self) -> u64 { + self.swap_mib.load(std::sync::atomic::Ordering::Relaxed) + } + + /// Whether the running macOS VM booted with `VZNATNetworkDeviceAttachment`. + #[allow(dead_code)] + pub fn shared_nat(&self) -> bool { + self.shared_nat.load(std::sync::atomic::Ordering::Relaxed) + } + /// The Mac folders and files that running containers bind-mount, as - /// the Mac keeps them (the guest sees them under /mnt/mac). + /// the Mac keeps them (the guest sees them under /mnt/mac). Excludes the + /// `kiri-k8s` node container (`dev.kiri.k8s`), which mounts `/Users` and + /// `/Volumes` whole for pod `hostPath` access and would otherwise attach a + /// 50 ms `FSEvents` stream across the entire Mac filesystem (#989). #[cfg(target_os = "macos")] pub fn mac_bind_sources(&self) -> Vec { let mut out: Vec = self .lock() .containers .values() - .filter(|c| c.status == Status::Running) + .filter(|c| watches_host_binds(c)) .flat_map(|c| c.spec.mounts.iter()) .filter_map(|m| m.split('\t').next()?.strip_prefix("/mnt/mac").filter(|p| p.starts_with('/')).map(str::to_owned)) .collect(); @@ -2005,12 +2822,181 @@ impl Engine { out } + /// Active published port bindings across all running containers, for + /// `kiri-win`'s Windows UDP and host-IP port forwarder (`/kiri/win-ports`). + pub fn published_ports(&self) -> Vec { + let st = self.lock(); + let mut out = Vec::new(); + for c in st.containers.values() { + if c.status != Status::Running { + continue; + } + let Some(fw) = &c.forwards else { continue }; + for (b, host_ip, host_port) in &fw.bound { + out.push(super::ports::PublishedPort { + proto: b.proto.clone(), + host_ip: host_ip.clone(), + host_port: *host_port, + }); + } + } + out.sort(); + out.dedup(); + out + } + + /// The WSL drive bind sources (`/mnt/` or `/mnt//...`) of + /// running containers, under `automount_root` (e.g. `/mnt/`). Excludes the + /// `kiri-k8s` node container (`dev.kiri.k8s`), which mounts `/mnt` whole. + pub fn wsl_bind_sources(&self, automount_root: &str) -> Vec { + let mut out: Vec = self + .lock() + .containers + .values() + .filter(|c| watches_host_binds(c)) + .flat_map(|c| c.spec.mounts.iter()) + .filter_map(|m| { + let src = m.split('\t').next()?; + super::binds::is_wsl_drive_path(src, automount_root, true).then(|| src.to_owned()) + }) + .collect(); + out.sort(); + out.dedup(); + out + } + + /// Forwards host file-change lines (`OP\tPATH`) to the running agent + /// without waking a sleeping or stopped VM/agent. + pub fn send_fs_events(&self, lines: &[String]) { + if lines.is_empty() { + return; + } + if let Some(vm) = self.awake() { + for chunk in lines.chunks(512) { + let _ = vm.fs_events(chunk); + } + } + } + /// The VM's link while it runs, without waking it. - #[cfg(target_os = "macos")] pub fn awake_link(&self) -> Option> { self.awake() } + /// Snapshot of persisted + cached volume disk usage, TTL freshness, dirty + /// set, and generation counter. + pub(super) fn volume_sizes_snapshot(&self, ttl: Duration) -> VolumeSizesSnapshot { + let c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + VolumeSizesSnapshot { + generation: c.generation, + fresh_ttl: c.measured_at.is_some_and(|at| at.elapsed() < ttl), + sizes: c.sizes.clone(), + dirty: c.dirty.clone(), + } + } + + /// Stores freshly measured volume sizes and persists `/volume-sizes.json`. + /// When `expected_gen` is `Some(g)`, skips writing if invalidated since `g`. + pub(super) fn cache_volume_sizes(&self, expected_gen: Option, du_volumes: HashMap) { + let volumes = self.volume_list(); + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + if expected_gen.is_some_and(|g| g != c.generation) { + return; + } + let mut next = HashMap::with_capacity(volumes.len()); + for v in &volumes { + if v.options.is_empty() { + next.insert(v.name.clone(), du_volumes.get(&v.name).copied().unwrap_or(0)); + } + } + c.measured_at = Some(std::time::Instant::now()); + c.sizes = next; + c.dirty.clear(); + c.save(); + } + + /// Initializes a newly created local volume's persisted size to `0` (unless + /// already measured) while bumping generation so an earlier in-flight scan + /// cannot clobber it. + fn record_new_volume(&self, v: &super::volumes::Volume) { + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + c.generation = c.generation.wrapping_add(1); + c.measured_at = None; + c.dirty.remove(&v.name); + if v.options.is_empty() { + c.sizes.entry(v.name.clone()).or_insert(0); + c.save(); + } + } + + /// Removes a deleted volume from the persisted size map and bumps generation. + fn forget_volume_size(&self, name: &str) { + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + c.generation = c.generation.wrapping_add(1); + c.measured_at = None; + c.dirty.remove(name); + if c.sizes.remove(name).is_some() { + c.save(); + } + } + + /// Marks mounted local volumes dirty when a container using them starts, + /// exits, is removed, or receives `docker cp` writes. + pub(super) fn mark_volumes_dirty<'a>(&self, names: impl IntoIterator) { + let names: Vec = names.into_iter().cloned().collect(); + if names.is_empty() { + return; + } + let local_set: HashSet = self + .volume_list() + .into_iter() + .filter(|v| v.options.is_empty()) + .map(|v| v.name) + .collect(); + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + let mut any = false; + for name in names { + if local_set.contains(&name) { + c.dirty.insert(name); + any = true; + } + } + if any { + c.generation = c.generation.wrapping_add(1); + c.measured_at = None; + } + } + + #[cfg(test)] + pub(super) fn set_volume_sizes_cache_at(&self, at: std::time::Instant, du_volumes: HashMap) { + let volumes = self.volume_list(); + let mut c = self.volume_sizes_cache.lock().unwrap_or_else(|e| e.into_inner()); + let mut next = HashMap::with_capacity(volumes.len()); + for v in &volumes { + if v.options.is_empty() { + next.insert(v.name.clone(), du_volumes.get(&v.name).copied().unwrap_or(0)); + } + } + c.measured_at = Some(at); + c.sizes = next; + c.dirty.clear(); + c.save(); + } + + /// Queries `(in_use, capacity)` of the guest data disk while the VM is + /// awake without waking a sleeping VM. + #[cfg(target_os = "macos")] + pub fn disk_usage_if_awake(&self) -> Option<(u64, u64)> { + self.awake()?.disk_usage().ok() + } + + /// Wakes the VM if asleep and runs an online `FITRIM` on the guest data + /// disk without stopping containers. Returns `(trimmed, in_use, capacity)`. + #[cfg(target_os = "macos")] + pub fn trim_disk(&self) -> io::Result<(u64, u64, u64)> { + self.vm()?.trim_disk() + } + /// Whether the VM is running right now. pub fn is_awake(&self) -> bool { self.awake().is_some() @@ -2063,6 +3049,7 @@ impl Engine { start_owed: false, paused: false, extra_ips: Vec::new(), + first_if: None, extra_ifs: Vec::new(), ip6: None, extra_ip6s: Vec::new(), @@ -2140,26 +3127,11 @@ impl Engine { } let json = { let st = self.lock(); - let saved: Vec = st + let saved: Vec> = st .containers .values() .filter(|c| !c.spec.auto_remove) - .map(|c| Saved { - id: c.id.clone(), - name: c.name.clone(), - spec: c.spec.clone(), - layers: c.layers.clone(), - created_ns: ns(c.created), - status: c.status, - started_ns: c.started.map(ns), - finished_ns: c.finished.map(ns), - exit_code: c.exit_code, - oom_killed: c.oom_killed, - vm_stopped: c.vm_stopped, - stopped_by_user: c.stopped_by_user, - restart_count: c.restart_count, - health: st.health.get(&c.id).map(|h| h.health.clone()), - }) + .map(|c| SavedRef::from_container(c, st.health.get(&c.id).map(|h| &h.health))) .collect(); serde_json::to_vec(&saved) }; @@ -2288,87 +3260,113 @@ impl Engine { } } Event::Exited { id, code, oom } => { - let mut st = self.lock(); - if let Some(e) = st.execs.get_mut(id) { - e.running = false; - e.exit_code = Some(code); - e.pid = 0; - e.attached.clear(); - let (container, exec_id, internal) = (e.container_id.clone(), e.id.clone(), e.config.internal); - drop(st); - self.changed.notify_all(); - if !internal { - self.emit_container("exec_die", &container, &[("execID", exec_id), ("exitCode", code.to_string())]); - } - return; - } - let mut restart_in = None; - let mut persist = false; - let mut closed_ports = None; - let actor = st.containers.get(id).map(|c| (c.spec.image.clone(), container_attrs(c))); - // Exited before its start made it live: its `start` first. - let start_owed = st.containers.get_mut(id).is_some_and(|c| std::mem::take(&mut c.start_owed)); - // Docker stops a container's healthcheck when it exits. - if let Some(h) = st.health.get_mut(id) { - close_monitor(h); - } - let remove = match st.containers.get_mut(id) { - Some(c) => { - c.status = Status::Exited; - c.exit_code = code; - c.pid = 0; - c.oom_killed = oom; - // Stopped by the daemon's shutdown, not by the app. - c.vm_stopped = SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst); - if oom { - crate::diag::warn!("container killed for memory", name = c.name.clone(), exit_code = code); - } - c.exits += 1; - c.live = false; - if let Some(ip) = c.ip.take() { - self.release_ip(&c.spec.network_mode, ip); + // Drop and unpublish `c.forwards` outside `self.state` BEFORE + // transitioning `c.status` to `Exited` or notifying + // `self.changed`, so a rapid `docker restart` / `stop && start` + // never binds against still-open sockets or has its new DNAT + // rules wiped by a delayed `Forwards::drop` -> `Unpublish` + // (#649). Loop in case a concurrent `start`/`connect`/ + // `set_ports` installed forwards while the lock was released. + let (restart_in, persist, exited_name, actor, start_owed, remove, anon, removed_log, removed_layers, touched_volumes) = loop { + let mut st = self.lock(); + if let Some(e) = st.execs.get_mut(id) { + e.running = false; + e.exit_code = Some(code); + e.pid = 0; + e.attached.clear(); + let (container, exec_id, internal) = (e.container_id.clone(), e.id.clone(), e.config.internal); + drop(st); + self.changed.notify_all(); + if !internal { + self.emit_container("exec_die", &container, &[("execID", exec_id), ("exitCode", code.to_string())]); } - for (net, ip) in std::mem::take(&mut c.extra_ips) { - self.release_ip(&net, ip); + return; + } + if let Some(closed_ports) = st.containers.get_mut(id).and_then(|c| c.forwards.take()) { + drop(st); + // Closing listeners joins their threads: never under the lock. + drop(closed_ports); + continue; + } + let mut restart_in = None; + let mut persist = false; + let mut exited_name = None; + let actor = st.containers.get(id).map(|c| (c.spec.image.clone(), container_attrs(c))); + // Exited before its start made it live: its `start` first. + let start_owed = st.containers.get_mut(id).is_some_and(|c| std::mem::take(&mut c.start_owed)); + // Docker stops a container's healthcheck when it exits. + if let Some(h) = st.health.get_mut(id) { + close_monitor(h); + } + let mut touched_volumes = Vec::new(); + let remove = match st.containers.get_mut(id) { + Some(c) => { + touched_volumes = c.spec.volumes.iter().chain(&c.spec.anon_volumes).cloned().collect(); + c.status = Status::Exited; + c.exit_code = code; + c.pid = 0; + c.oom_killed = oom; + // Stopped by the daemon's shutdown, not by the app. + c.vm_stopped = SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst); + exited_name = Some(c.name.clone()); + c.exits += 1; + c.live = false; + if let Some(ip) = c.ip.take() { + self.release_ip(&c.spec.network_mode, ip); + } + for (net, ip) in std::mem::take(&mut c.extra_ips) { + self.release_ip(&net, ip); + } + c.first_if = None; + c.extra_ifs.clear(); + self.release_ip6s(c); + c.paused = false; + c.finished = Some(SystemTime::now()); + // Dropping the senders ends every attach stream. + c.attached.clear(); + lock_log(&c.log).end_follow(); + persist = !c.spec.auto_remove; + let p = &c.spec.restart; + let wants = match p.name.as_str() { + "always" | "unless-stopped" => !c.stopped_by_user, + "on-failure" => code != 0 && !c.stopped_by_user && (p.max_retries == 0 || c.restart_count < p.max_retries), + _ => false, + }; + // Not for the engine's own stop (Stop, the VM's sleep on + // request): Start brings those back. + let engine_stop = SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst) || self.parking.load(std::sync::atomic::Ordering::SeqCst) || self.is_stopped(); + if wants && !c.spec.auto_remove && !engine_stop { + let backoff = restart_backoff(c.restart_count); + c.restart_count = c.restart_count.saturating_add(1); + c.restart_pending = true; + restart_in = Some(backoff); + } + c.spec.auto_remove } - c.extra_ifs.clear(); - self.release_ip6s(c); - c.paused = false; - closed_ports = c.forwards.take(); - c.finished = Some(SystemTime::now()); - // Dropping the senders ends every attach stream. - c.attached.clear(); - lock_log(&c.log).end_follow(); - persist = !c.spec.auto_remove; - let p = &c.spec.restart; - let wants = match p.name.as_str() { - "always" | "unless-stopped" => !c.stopped_by_user, - "on-failure" => code != 0 && !c.stopped_by_user && (p.max_retries == 0 || c.restart_count < p.max_retries), - _ => false, - }; - // Not for the engine's own stop (Stop, the VM's sleep on - // request): Start brings those back. - let engine_stop = SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst) || self.parking.load(std::sync::atomic::Ordering::SeqCst) || self.is_stopped(); - if wants && !c.spec.auto_remove && !engine_stop { - let backoff = restart_backoff(c.restart_count); - c.restart_count = c.restart_count.saturating_add(1); - c.restart_pending = true; - restart_in = Some(backoff); + None => false, + }; + let mut anon = Vec::new(); + let mut removed_log = None; + let mut removed_layers = Vec::new(); + if remove { + if let Some(c) = st.containers.remove(id) { + anon = c.spec.anon_volumes; + removed_log = Some(c.log); + removed_layers = c.layers; } - c.spec.auto_remove + note_removed(&mut st, id, code); } - None => false, + drop(st); + break (restart_in, persist, exited_name, actor, start_owed, remove, anon, removed_log, removed_layers, touched_volumes); }; - let mut anon = Vec::new(); - let mut removed_log = None; - if remove { - if let Some(c) = st.containers.remove(id) { - anon = c.spec.anon_volumes; - removed_log = Some(c.log); - } - note_removed(&mut st, id, code); + // Relieve the balloon and log the exit outside `self.state` so + // neither `memory_target`, `link` nor `stopping_ops` is ever + // nested under it, and before the exit is reported to waiters. + if let Some(name) = exited_name { + self.log_exit(id, &name, code, oom); + } else { + self.clear_stopping_op(id); } - drop(st); if let Some((image, attrs)) = actor { if start_owed { self.emit_container_with("start", id, &image, attrs.clone(), &[]); @@ -2378,8 +3376,6 @@ impl Engine { self.emit_container_with("destroy", id, &image, attrs, &[]); } } - // Closing listeners joins their threads: never under the lock. - drop(closed_ports); if let Some(log) = removed_log { lock_log(&log).remove(); } @@ -2388,6 +3384,7 @@ impl Engine { // reader), since that asks the VM, and vm() waits for this // reader when the VM was just lost. let forgotten: Vec = self.unshared(anon).into_iter().filter(|v| self.forget_volume(v)).collect(); + self.mark_volumes_dirty(&touched_volumes); if !forgotten.is_empty() && let Some(me) = self.me.get().and_then(Weak::upgrade) { let _ = std::thread::Builder::new().name("kiri-volume-rm".into()).spawn(move || { if let Ok(vm) = me.vm() { @@ -2397,6 +3394,16 @@ impl Engine { } }); } + // If this `--rm` container was the last holder of layers from + // an overwritten image, prune them off the reader thread (#722). + if !removed_layers.is_empty() + && self.has_unlisted_layer(&removed_layers) + && let Some(me) = self.me.get().and_then(Weak::upgrade) + { + let _ = std::thread::Builder::new().name("kiri-layer-gc".into()).spawn(move || { + me.prune_layers(); + }); + } self.changed.notify_all(); if persist { self.save(); @@ -2421,7 +3428,12 @@ impl Engine { }); } } - Event::Pressure => self.grow_memory(), + Event::Pressure { mem_available_kib, mem_stall } => { + self.mem_available_kib.store(mem_available_kib, std::sync::atomic::Ordering::Relaxed); + self.memory_stall.store(mem_stall, std::sync::atomic::Ordering::Relaxed); + self.pressure_events.fetch_add(1, std::sync::atomic::Ordering::Release); + self.grow_memory(); + } Event::Lost => { let end = vm_end(self.sleeping.load(std::sync::atomic::Ordering::SeqCst), SHUTTING_DOWN.load(std::sync::atomic::Ordering::SeqCst)); let crashed = end == VmEnd::Crashed; @@ -2435,6 +3447,7 @@ impl Engine { for (net, ip) in std::mem::take(&mut c.extra_ips) { self.release_ip(&net, ip); } + c.first_if = None; c.extra_ifs.clear(); self.release_ip6s(c); c.paused = false; @@ -2475,9 +3488,12 @@ impl Engine { } drop(st); drop(closed); + self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_lb.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_fwd.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.k8s_routes.lock().unwrap_or_else(|e| e.into_inner()).take(); + *self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = serde_json::Value::Null; + super::ports::set_shared_nat_active(None); self.changed.notify_all(); match end { // sleep_if_idle says why it slept. @@ -2499,54 +3515,184 @@ impl Engine { } } - /// Every second: read what the guest holds and, on the Mac, give it that - /// plus headroom through the balloon, the rest back to macOS. Pressure - /// events grow it at once in between. On a Linux host there is no - /// balloon and nothing to give back: the reading is all, and it takes in - /// this process too, which runs beside the containers there. - fn start_balloon(self: &Arc) { - if std::env::var_os("KIRI_NO_BALLOON").is_some() { + fn active_containers(&self) -> usize { + self.lock().containers.values().filter(|c| c.status == Status::Running).count() + } + + fn balloon_enabled(&self) -> bool { + self.balloon_enabled.load(std::sync::atomic::Ordering::Relaxed) + } + + fn memory_min(&self) -> u64 { + self.memory_min.load(std::sync::atomic::Ordering::Relaxed) + } + + /// Updates memory telemetry from a guest `Stats` sample and, when + /// `apply_balloon` is true, computes and applies the next balloon target. + fn record_balloon_stats( + &self, + balloon_state: &mut BalloonState, + stats: &kiri_proto::Stats, + active_containers: usize, + pressure: bool, + apply_balloon: bool, + now: std::time::Instant, + set_target: impl FnOnce(u64), + ) { + let mut target = self.memory_target.lock().unwrap_or_else(|e| e.into_inner()); + let ceiling = self.ceiling(); + let used = estimate_used(stats, ceiling, *target, if cfg!(target_os = "macos") { 0 } else { self_rss() }); + self.memory_used.store(used, std::sync::atomic::Ordering::Relaxed); + self.mem_available_kib.store(stats.mem_available_kib, std::sync::atomic::Ordering::Relaxed); + self.memory_stall.store(stats.mem_stall, std::sync::atomic::Ordering::Relaxed); + self.oom_kills.store(stats.oom_kills, std::sync::atomic::Ordering::Relaxed); + if !apply_balloon { + balloon_state.reset(); return; } + let policy = BalloonPolicy { ceiling, active_containers, memory_min: self.memory_min() }; + if let Some(next) = balloon_state.next_target_at(stats, used, policy, *target, pressure, now) { + *target = next; + set_target(next); + } + } + + /// Every second: read what the guest holds and, on the Mac (unless + /// ballooning is disabled via `vm.json`'s `"balloon": false` or + /// `KIRI_NO_BALLOON`), give it what it needs plus proportional headroom + /// through the balloon, returning the rest to macOS. Even when ballooning + /// is disabled, stats polling keeps updating `memory_used`, + /// `mem_available_kib`, `memory_stall` and `oom_kills`. Pressure events + /// grow it at once in between. On a Linux host there is no balloon and + /// nothing to give back: the reading is all, and it takes in this process + /// too, which runs beside the containers there. + fn start_balloon(self: &Arc) { let me = Arc::downgrade(self); let _ = std::thread::Builder::new().name("kiri-balloon".into()).spawn(move || { let mut balloon_state = BalloonState::default(); + let mut last_pressure = 0u64; loop { std::thread::sleep(Duration::from_secs(1)); let Some(engine) = me.upgrade() else { return }; let Some(vm) = engine.awake() else { balloon_state.reset(); + last_pressure = engine.pressure_events.load(std::sync::atomic::Ordering::Acquire); continue; }; let Ok(stats) = vm.stats() else { continue }; - let mut target = engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()); - let ceiling = engine.ceiling(); - let used = estimate_used(&stats, ceiling, *target, if cfg!(target_os = "macos") { 0 } else { self_rss() }); - engine.memory_used.store(used, std::sync::atomic::Ordering::Relaxed); - engine.memory_stall.store(stats.mem_stall, std::sync::atomic::Ordering::Relaxed); - engine.oom_kills.store(stats.oom_kills, std::sync::atomic::Ordering::Relaxed); - if !cfg!(target_os = "macos") { - continue; - } - if let Some(next) = balloon_state.next_target(&stats, used, ceiling, *target) { - *target = next; + // Count running containers outside `memory_target` to preserve lock ordering. + let active_containers = engine.active_containers(); + let cur_pressure = engine.pressure_events.load(std::sync::atomic::Ordering::Acquire); + let pressure = cur_pressure != last_pressure; + last_pressure = cur_pressure; + let apply_balloon = cfg!(target_os = "macos") && engine.balloon_enabled(); + engine.record_balloon_stats(&mut balloon_state, &stats, active_containers, pressure, apply_balloon, std::time::Instant::now(), |next| { vm.set_memory_target(next); - } + }); } }); } fn grow_memory(&self) { + if !cfg!(target_os = "macos") || !self.balloon_enabled() { + return; + } + // Take `link` before `memory_target`, matching `start_balloon`. + let vm = self.awake(); let mut target = self.memory_target.lock().unwrap_or_else(|e| e.into_inner()); let next = target.saturating_add(MEMORY_GROW).min(self.ceiling()); if next != *target { *target = next; - if let Some(vm) = self.awake() { + if let Some(vm) = vm { vm.set_memory_target(next); } } } + /// Before a container is reported stopped for memory, give the guest + /// every byte it can have: deflate the balloon so the target equals the + /// ceiling, and log the relief (old and new target). A memory stop is + /// only reported once the log shows target == ceiling. The Mac is the + /// only place with a balloon to deflate; a Linux host never claims one. + fn relieve_memory(&self) { + if !cfg!(target_os = "macos") { + return; + } + let ceiling = self.ceiling(); + let vm = self.awake(); + let old = { + let mut target = self.memory_target.lock().unwrap_or_else(|e| e.into_inner()); + let old = *target; + if old == ceiling { + return; + } + *target = ceiling; + if let Some(vm) = vm { + vm.set_memory_target(ceiling); + } + old + }; + crate::diag::info!("balloon relieved for a memory kill", target_mib_old = old >> 20, target_mib = ceiling >> 20); + } + + /// Classifies a container exit for diagnostic logging, consuming any + /// tracked stopping op and relieving the balloon first on a macOS memory + /// kill. Must not be called while holding `self.state`. + fn classify_exit(&self, id: &str, name: &str, code: i32, oom: bool) -> Option { + let stopping_op = self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + if oom { + // Deflate first: a memory stop is only reported once the target + // equals the ceiling, so the guest had every byte it could have. + self.relieve_memory(); + let mem_available_mib = self.mem_available_kib.load(std::sync::atomic::Ordering::Relaxed) >> 10; + let psi_full_avg10 = self.memory_stall.load(std::sync::atomic::Ordering::Relaxed); + let balloon = cfg!(target_os = "macos").then(|| { + let ceiling_mib = self.ceiling() >> 20; + (ceiling_mib, ceiling_mib) + }); + Some(ExitLog::MemoryKill { name: name.to_owned(), exit_code: code, mem_available_mib, psi_full_avg10, balloon }) + } else if let Some(op) = stopping_op { + // A stop Kiri issued under an operation (a restartvm, a recreate, + // `kiri k8s set`): logged as that operation, not as a memory kill. + let kind = op.split('-').next().filter(|k| !k.is_empty()).unwrap_or("op").to_owned(); + Some(ExitLog::OpStop { kind, name: name.to_owned(), exit_code: code, op }) + } else { + None + } + } + + fn log_exit(&self, id: &str, name: &str, code: i32, oom: bool) { + match self.classify_exit(id, name, code, oom) { + Some(ExitLog::MemoryKill { name, exit_code, mem_available_mib, psi_full_avg10, balloon: Some((target_mib, ceiling_mib)) }) => { + crate::diag::warn!( + "container killed for memory", + name = name, + exit_code = exit_code, + mem_available_mib = mem_available_mib, + target_mib = target_mib, + ceiling_mib = ceiling_mib, + balloon_mib = 0, + psi_full_avg10 = psi_full_avg10, + killed_by = "kernel", + ); + } + Some(ExitLog::MemoryKill { name, exit_code, mem_available_mib, psi_full_avg10, balloon: None }) => { + crate::diag::warn!( + "container killed for memory", + name = name, + exit_code = exit_code, + mem_available_mib = mem_available_mib, + psi_full_avg10 = psi_full_avg10, + killed_by = "kernel", + ); + } + Some(ExitLog::OpStop { kind, name, exit_code, op }) => { + crate::diag::info!(format!("container stopped by {kind}"), name = name, exit_code = exit_code, killed_by = "kiri", op = op); + } + None => {} + } + } + /// (ceiling, current target) in bytes. On a Linux host there is no VM /// of Kiri's to bound: both are the machine's memory (in WSL, the memory /// .wslconfig gives it), so the window shows use against what is there. @@ -2633,6 +3779,18 @@ impl Engine { Ok(image_named(self.store.images()?, name)) } + /// Finds an image by the name a client used, holding every blob it + /// references ([`kiri_image::Store::hold_image`]) before releasing the + /// index lock so a concurrent tag replacement or removal cannot delete + /// them before the caller reads the config or sends layers. + pub fn image_pinned(&self, name: &str) -> io::Result)>> { + self.store.with_images(|images| { + let image = image_named(images.to_vec(), name)?; + let pins = self.store.hold_image(&image); + Some((image, pins)) + }) + } + /// The config Labels of each of `images`, which must be the whole image /// list (`store.images()`): a config is read from disk only the first /// time it is seen, and entries for images not in the list are dropped. @@ -2674,11 +3832,85 @@ impl Engine { Ok(ancestor_ids(&self.store.images()?, values)) } + /// Keeps `digests` in `retained_layers` until the returned guard drops, + /// so a concurrent `prune_layers` cannot delete layers while a container + /// is being created from them (#722). + pub(super) fn pin_layers<'a>(&'a self, digests: impl IntoIterator) -> LayerPin<'a> { + let digests: Vec = digests.into_iter().map(str::to_owned).collect(); + if !digests.is_empty() { + let mut st = self.lock(); + for d in &digests { + *st.pinned_layers.entry(d.clone()).or_insert(0) += 1; + } + } + LayerPin { engine: self, digests } + } + + /// Every layer digest the guest must keep (every image's, every running + /// and stopped container's, and every in-flight create's). `None` when + /// either list is damaged or unreadable: then nothing is deleted (#440). + fn retained_layers(&self) -> Option> { + if self.keeps_everything() { + return None; + } + let image_damage = self.store.index_damage(); + if !matches!(image_damage, Ok(None)) { + crate::diag::warn!( + "kept every unpacked layer: the image list was damaged", + detail = image_damage_message(&image_damage, self.store.root()).unwrap_or_default() + ); + return None; + } + let images = match self.store.images() { + Ok(images) => images, + Err(e) => { + crate::diag::warn!("kept every unpacked layer: images unreadable", error = e); + return None; + } + }; + let mut layers: std::collections::BTreeSet = images + .iter() + .flat_map(|i| i.layers.iter().map(|l| l.digest.clone())) + .collect(); + let st = self.lock(); + layers.extend(st.containers.values().flat_map(|c| c.layers.iter().cloned())); + layers.extend(st.pinned_layers.keys().cloned()); + drop(st); + Some(layers.into_iter().collect()) + } + + /// Whether any digest in `layers` is no longer listed by any image in the + /// store: removing a container that held it may now free the unpacked layer. + fn has_unlisted_layer(&self, layers: &[String]) -> bool { + let Ok(images) = self.store.images() else { return false }; + layers.iter().any(|d| !images.iter().any(|i| i.layers.iter().any(|l| &l.digest == d))) + } + + /// Deletes unpacked layers in the guest that no image, container or + /// in-flight create uses any more (#722). Does not boot a sleeping VM: + /// the next boot runs the same pass (`vm_inner`). Waits for the guest + /// (`ping`), so an immediate `docker system df` or listing of + /// `/var/lib/kiri/layers` sees the space freed. + pub fn prune_layers(&self) { + let Some(vm) = self.awake() else { return }; + if let Err(e) = self.prune_layers_with(|keep| vm.retain_layers(keep).and_then(|()| vm.ping())) { + crate::diag::warn!("unpacked layers left for the next boot", error = e); + } + } + + /// Runs a live `retain_layers` pass serialized with `ensure_layers`. + fn prune_layers_with(&self, send: impl FnOnce(&[String]) -> io::Result<()>) -> io::Result<()> { + let _one_at_a_time = self.layers.lock().unwrap_or_else(|e| e.into_inner()); + let Some(keep) = self.retained_layers() else { return Ok(()) }; + send(&keep) + } + /// Sends the guest every layer of these (digest, media type) it doesn't /// have unpacked, from the blob store. fn ensure_layers<'a>(&self, vm: &VmLink, layers: impl Iterator) -> io::Result<()> { let _one_at_a_time = self.layers.lock().unwrap_or_else(|e| e.into_inner()); for (digest, media_type) in layers { + let _blob_pin = self.store.pin(digest); if !vm.has_layer(digest)? { vm.send_layer(digest, media_type, &self.store.blob_path(digest)?)?; } @@ -2703,20 +3935,26 @@ impl Engine { if missing.is_empty() { return Ok(()); } - let images = self.store.images()?; - let mut wanted = Vec::with_capacity(missing.len()); - for digest in missing { - let Some(l) = images.iter().flat_map(|i| &i.layers).find(|l| &l.digest == digest) else { - return Err(Error::Conflict(format!("layer {digest} is gone from the engine and no image has it any more: remove this container and create it again"))); - }; - wanted.push((l.digest.as_str(), l.media_type.as_str())); - } - Ok(self.ensure_layers(vm, wanted.into_iter())?) + let (wanted, _blob_pins) = self.store.with_images(|images| -> Result<_, Error> { + let mut wanted = Vec::with_capacity(missing.len()); + let mut pins = Vec::with_capacity(missing.len()); + for digest in &missing { + let Some(l) = images.iter().flat_map(|i| &i.layers).find(|l| &l.digest == *digest) else { + return Err(Error::Conflict(format!("layer {digest} is gone from the engine and no image has it any more: remove this container and create it again"))); + }; + pins.push(self.store.pin(&l.digest)); + wanted.push((l.digest.clone(), l.media_type.clone())); + } + Ok((wanted, pins)) + })??; + Ok(self.ensure_layers(vm, wanted.iter().map(|(d, m)| (d.as_str(), m.as_str())))?) } /// Records a container and makes sure its layers are in the guest, so /// `start` has nothing left to do but run it. pub fn create(&self, name: Option, spec: Spec, image: &Image) -> Result { + let _pin = self.pin_layers(image.layers.iter().map(|l| l.digest.as_str())); + let _blob_pins = self.store.hold_image(image); if !image.layers.is_empty() { let vm = self.vm()?; self.ensure_layers(&vm, image.layers.iter().map(|l| (l.digest.as_str(), l.media_type.as_str())))?; @@ -2774,6 +4012,7 @@ impl Engine { start_owed: false, paused: false, extra_ips: Vec::new(), + first_if: None, extra_ifs: Vec::new(), ip6: None, extra_ip6s: Vec::new(), @@ -2936,11 +4175,14 @@ impl Engine { let halted = self.halting(); (out.0, out.1, out.2, out.3, out.4, (out.5.0, out.5.1, earlier, halted)) }; + self.clear_stopping_op(&id); + self.mark_volumes_dirty(spec.volumes.iter().chain(&spec.anon_volumes)); let (gate, exits, earlier, halted_at_claim) = gate; // A bind source that is a link is followed again at every start, as // Docker does: re-pointing it between runs (a `current` release // link) mounts the new target. spec.mounts = super::api::fresh_bind_sources(&spec.mounts, &spec.mount_info); + super::api::refresh_ssh_agent_mounts(&spec.mount_info); let mut hostname = if spec.hostname.is_empty() { id[..12].to_owned() } else { spec.hostname.clone() }; let mut domainname = spec.domainname.clone(); // `--network container:`: that container's namespace, hostname @@ -3000,7 +4242,12 @@ impl Engine { let (bridge, ip, prefix, gateway) = match net.as_ref().map(|n| n.driver.as_str()) { Some("host") => { flags |= run_flags::NET_HOST; - (String::new(), [0; 4], 0, [0; 4]) + // Pass the default bridge's gateway and prefix so the VM's + // agent can bring up kiri0 on demand for host-network DNS + // before any bridged container starts, while keeping `bridge` + // empty so this container is not treated as bridged. + let (prefix, gateway) = self.lock_networks().find("bridge").map_or((0, [0; 4]), |b| (b.prefix, b.gateway)); + (String::new(), [0; 4], prefix, gateway) } Some("bridge") => { let n = net.as_ref().expect("matched"); @@ -3034,6 +4281,9 @@ impl Engine { if n.no_ipv4 { net6_opts.push(format!("{}=1", kiri_proto::net_opts::NO_IPV4)); } + if n.icc_disabled() { + net6_opts.push(format!("{}=1", kiri_proto::net_opts::NO_ICC)); + } net6_opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, n.name)); } Err(e) => { @@ -3080,6 +4330,7 @@ impl Engine { if ip != [0; 4] { if let Some(c) = self.lock().containers.get_mut(&id) { c.ip = Some(ip); + c.first_if = Some(0); } } // A restarted container keeps its writable layer, so only --rm deletes it. @@ -3099,27 +4350,35 @@ impl Engine { flags |= run_flags::INIT; } flags |= spec.security_flags(); - // Every container can reach the Mac, as with Docker Desktop and OrbStack. - // --add-host and links come first: /etc/hosts takes the first match, - // so `--add-host host.docker.internal:IP` overrides Kiri's, as on Docker. + // Every container can reach the Mac (or Windows host on WSL 2), as with + // Docker Desktop and OrbStack. --add-host and links come first: + // /etc/hosts takes the first match, so `--add-host host.docker.internal:IP` + // overrides Kiri's, as on Docker. let mut hosts = spec.extra_hosts.clone(); hosts.extend(links); - hosts.push(format!("{}\thost.docker.internal host.kiri.internal", super::ports::HOST_ADDR)); - hosts.push(format!("{}\tgateway.docker.internal", super::ports::HOST_ADDR)); + let host_ip = if crate::hostrelay::wsl_host_active() { + crate::hostrelay::WSL_HOST_ADDR_STR + } else { + super::ports::HOST_ADDR + }; + hosts.push(format!("{host_ip}\thost.docker.internal host.kiri.internal")); + hosts.push(format!("{host_ip}\tgateway.docker.internal")); let mut opts = net_opts(&spec, joined.as_deref(), &domainname); opts.extend(net6_opts); opts.extend(pid_joined.map(|t| format!("{}={t}", kiri_proto::net_opts::PIDNS))); - let net_args = kiri_proto::Net { bridge: &bridge, ip, prefix, gateway, extra_hosts: &hosts, dns_names: &dns_names, opts: &opts }; // Joining a host-network container is the host's namespace too: its // net.* sysctls would change the whole VM (or Linux host). let joined_host = joined_mode.is_some_and(|m| self.lock_networks().find(&m).is_some_and(|n| n.driver == "host")); - let host_opts = match spec.guest_opts(flags & run_flags::NET_HOST != 0 || joined_host) { + let mut host_opts = match spec.guest_opts(flags & run_flags::NET_HOST != 0 || joined_host) { Ok(o) => o, Err(e) => { self.fail_start(&id, &spec, &e); return Err(e); } }; + if let Some(opt) = k8s_timer_slack_opt(&spec) { + host_opts.push(opt); + } if let Err(e) = self.restore_layers(&vm, &layers) { self.fail_start(&id, &spec, &e); return Err(e); @@ -3153,11 +4412,34 @@ impl Engine { return Err(e); } let cancelled = || gate.0.cancel.load(std::sync::atomic::Ordering::SeqCst); - let started = if cancelled() { + let run_once = || { + let net_args = kiri_proto::Net { bridge: &bridge, ip, prefix, gateway, extra_hosts: &hosts, dns_names: &dns_names, opts: &opts }; + vm.run(&id, &layers, &argv, &spec.env, &spec.cwd, &spec.user, &hostname, flags, net_args, &spec.mounts, &spec.limits.wire(), spec.caps, &host_opts, &seccomp, &gate.0.cancel) + }; + let mut started = if cancelled() { Err(io::Error::other("cancelled before it reached the guest")) } else { - vm.run(&id, &layers, &argv, &spec.env, &spec.cwd, &spec.user, &hostname, flags, net_args, &spec.mounts, &spec.limits.wire(), spec.caps, &host_opts, &seccomp, &gate.0.cancel) + run_once() }; + // `VmLink::layers` avoids redundant `LayerQuery` round-trips on hot starts; + // if an unpacked layer was deleted on the guest's disk while the VM stayed + // up (`start-restores-layer`), evict its cached digests, re-query/re-send + // the missing layer(s), and retry once. + if let Err(ref e) = started + && !cancelled() + && is_missing_unpacked_layer_error(&e.to_string()) + { + vm.forget_layers(&layers); + if let Err(restore_err) = self.restore_layers(&vm, &layers) { + self.fail_start(&id, &spec, &restore_err); + return Err(restore_err); + } + started = if cancelled() { + Err(io::Error::other("cancelled before it reached the guest")) + } else { + run_once() + }; + } if let Ok(pid) = started && let Some(c) = self.lock().containers.get_mut(&id).filter(|c| c.status == Status::Running) { @@ -3188,15 +4470,39 @@ impl Engine { } if flags & (run_flags::NET_HOST | run_flags::NET_NONE) == 0 && joined.is_none() { for (i, extra) in spec.extra_networks.iter().enumerate() { - if let Err(e) = self.attach_extra(&vm, &id, i as u32 + 1, extra) { - crate::diag::warn!("container not attached to a network", id = &id[..12], network = extra.name, error = format!("{e:?}")); + let n = i as u32 + 1; + let sync = self.names_sync(&id); + let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); + match self.attach_network(&vm, &id, n, extra, false) { + Ok((net, ip, ip6)) => { + if let Some(c) = self.lock().containers.get_mut(&id) { + c.extra_ips.push((net.name.clone(), ip)); + c.extra_ifs.push((net.name.clone(), n)); + if let Some(a) = ip6 { + c.extra_ip6s.push((net.name, a)); + } + } + } + Err(e) => crate::diag::warn!("container not attached to a network", id = &id[..12], network = extra.name, error = format!("{e:?}")), } } } // A container that left all its networks keeps its `-p` bindings // but has no address for them, as on Docker, where it publishes none. - if !spec.ports.is_empty() && flags & run_flags::NET_NONE == 0 { - let target = if flags & run_flags::NET_HOST != 0 { [127, 0, 0, 1] } else { ip }; + // On a Linux host, `--network host` is the daemon's own network + // namespace, so published ports are discarded at start as on Docker + // and the container binds them itself (#764); on macOS it runs in the + // VM's network namespace, so the Mac still forwards to 127.0.0.1 there. + let forward_mode = if flags & run_flags::NET_HOST != 0 { + "host" + } else if flags & run_flags::NET_NONE != 0 || joined.is_some() { + "none" + } else { + spec.network_mode.as_str() + }; + if !spec.ports.is_empty() + && let Some(target) = port_forward_target(forward_mode, Some(ip), cfg!(target_os = "linux")) + { match super::ports::start(vm.clone(), &id, &spec.ports, target) { Ok(fw) => { let mut st = self.lock(); @@ -3511,6 +4817,8 @@ impl Engine { for (net, ip) in std::mem::take(&mut c.extra_ips) { self.release_ip(&net, ip); } + c.first_if = None; + c.extra_ifs.clear(); self.release_ip6s(c); } if !spec.auto_remove && st.containers.get(id).is_some_and(|c| c.vm_stopped) { @@ -3611,7 +4919,7 @@ impl Engine { /// Names are the container name, or `.` for Compose /// services. pub fn route(&self, host: &str) -> Option { - let host = host.split(':').next()?.to_ascii_lowercase(); + let host = super::domains::parse_host_name(host)?; let name = host.strip_suffix(".kiri.localhost").or_else(|| host.strip_suffix(".kiri.local"))?.to_owned(); let st = self.lock(); let c = st.containers.values().find(|c| { @@ -3629,19 +4937,63 @@ impl Engine { id: c.id.clone(), label: c.spec.labels.get("dev.kiri.http.port").and_then(|v| v.as_str()).and_then(|p| p.parse().ok()), published: c.spec.ports.iter().filter(|b| b.proto != "udp").map(|b| b.container_port).collect(), - exposed: c.spec.exposed.clone(), + exposed: c.spec.exposed.iter().filter_map(|key| key.strip_suffix("/tcp")?.parse().ok()).collect(), }) } - /// For the Finder view (macOS). - #[cfg_attr(not(target_os = "macos"), allow(dead_code))] - pub fn fs_stat(&self, id: &str, path: &str) -> io::Result { - self.vm()?.fs_stat(id, path) + #[cfg(test)] + pub(super) fn mark_running_for_test(&self, id: &str, ip: [u8; 4]) { + let mut st = self.lock(); + let c = st.containers.get_mut(id).unwrap(); + c.status = Status::Running; + c.ip = Some(ip); + c.first_if = Some(0); } - /// For the Finder view (macOS). - #[cfg_attr(not(target_os = "macos"), allow(dead_code))] - pub fn fs_list(&self, id: &str, path: &str) -> io::Result> { + /// Checks whether a `/proc//cgroup` snapshot belongs to one of this + /// engine's currently running containers under a root-owned `kiri/` + /// cgroup directory (#127). Prevents unprivileged host `unshare -Um` + + /// `newuidmap` processes from impersonating containers on `docker.container.sock`. + #[cfg(target_os = "linux")] + pub fn has_running_container_cgroup(&self, cgroup_text: &str) -> bool { + use std::os::unix::fs::MetadataExt; + for line in cgroup_text.lines() { + let Some((_, rest)) = line.split_once(':') else { continue }; + let Some((_, rel_path)) = rest.split_once(':') else { continue }; + if !rel_path.starts_with('/') { + continue; + } + let segs: Vec<&str> = rel_path.split('/').filter(|s| !s.is_empty()).collect(); + for i in 1..segs.len() { + let id = segs[i]; + if segs[i - 1] != "kiri" || id.len() != 64 || !id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) { + continue; + } + let is_running = self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running); + if !is_running { + continue; + } + let prefix = format!("/sys/fs/cgroup/{}", segs[..=i].join("/")); + let parent = format!("/sys/fs/cgroup/{}", segs[..i].join("/")); + if std::fs::symlink_metadata(&prefix).is_ok_and(|m| m.is_dir() && m.uid() == 0) + && std::fs::symlink_metadata(&parent).is_ok_and(|m| m.is_dir() && m.uid() == 0) + { + return true; + } + } + } + false + } + + /// For the Finder view (macOS). + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub fn fs_stat(&self, id: &str, path: &str) -> io::Result { + self.vm()?.fs_stat(id, path) + } + + /// For the Finder view (macOS). + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub fn fs_list(&self, id: &str, path: &str) -> io::Result> { self.vm()?.fs_list(id, path) } @@ -3651,6 +5003,12 @@ impl Engine { self.vm()?.fs_read(id, path, offset, len) } + /// For the Finder view (macOS). + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + pub fn fs_read_link(&self, id: &str, path: &str) -> io::Result> { + self.vm()?.fs_read_link(id, path) + } + /// A stream into the guest relay towards `ip:port`. pub fn relay_to(&self, ip: [u8; 4], port: u16) -> io::Result { let vm = self.vm()?; @@ -3678,21 +5036,36 @@ impl Engine { /// Opens a `docker cp` session with the guest for a container, running /// or not: the request frame is sent, the caller does the rest. pub fn copy(&self, key: &str, op: u8, path: &str, flags: u32) -> Result { - self.wait_for_start(&self.resolve(key)?); + let use_mounts = matches!(op, kiri_proto::copy_op::IN | kiri_proto::copy_op::OUT | kiri_proto::copy_op::STAT); + let (self_gate, shared_gates) = { + let st = self.lock(); + let id = resolve(&st, key)?; + let c = st.containers.get(&id).expect("resolved"); + let shared = if use_mounts { shared_volume_gates(&st, &id, &c.spec) } else { Vec::new() }; + (c.start_gate.clone(), shared) + }; + self_gate.wait(); + for gate in shared_gates { + gate.wait(); + } // Looked up after the wait: a `--rm` start that failed meanwhile has // removed the container, and a copy must not then write into a // folder made again for a container that no longer exists. - let (id, layers) = { + let (id, layers, spec) = { let st = self.lock(); let id = resolve(&st, key)?; - let layers = st.containers.get(&id).map(|c| c.layers.clone()).unwrap_or_default(); - (id, layers) + let c = st.containers.get(&id).expect("resolved"); + (id, c.layers.clone(), c.spec.clone()) }; + let (mounts, flags) = copy_mounts_and_flags(&spec, op, flags); let vm = self.vm()?; let stream = vm.connect(kiri_proto::COPY_PORT)?; let mut out = Vec::new(); - kiri_proto::encode_copy(&mut out, op, &id, path, flags, &layers); + kiri_proto::encode_copy(&mut out, op, &id, path, flags, &layers, &mounts); std::io::Write::write_all(&mut std::fs::File::from(stream.fd.try_clone()?), &out)?; + if op == kiri_proto::copy_op::IN { + self.mark_volumes_dirty(spec.volumes.iter().chain(&spec.anon_volumes)); + } Ok(stream) } @@ -3712,7 +5085,7 @@ impl Engine { let canonical = self.lock_networks().find(network).map(|n| n.name.clone()).unwrap_or_default(); self.each(|c| { let theirs = self.lock_networks().find(&c.spec.network_mode).map(|n| n.name.clone()).unwrap_or_default(); - if theirs == canonical { + if !c.spec.left_all_networks && theirs == canonical { return Some((c.id.clone(), c.name.clone(), c.ip, c.ip6)); } c.spec.extra_networks.iter().any(|x| x.name == canonical).then(|| { @@ -3853,13 +5226,20 @@ impl Engine { } /// SIGTERM, then SIGKILL after `timeout` if it is still running. - /// Plugs a running container into one more network as `eth{n}`. - fn attach_extra(&self, vm: &VmLink, id: &str, n: u32, extra: &ExtraNetwork) -> Result<(), Error> { - // Held from the name read to the network being recorded, so a rename - // lands before (and the guest then has the new name) or after (and - // renames this network too). - let sync = self.names_sync(id); - let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); + fn release_attached_ips(&self, net_name: &str, ip: Option<[u8; 4]>, ip6: Option<[u8; 16]>) { + if let Some(ip) = ip { + self.release_ip(net_name, ip); + } + if let Some(a) = ip6 { + self.lock_networks().release6(net_name, a); + } + } + + /// Allocates addresses and plugs a running container into `extra` as + /// `eth{n}`. Caller must hold `names_sync` for `id`. Does not mutate + /// container state; returns `(net, ip, ip6)` so the caller can commit them + /// or roll back if the container exited or ports could not be bound. + fn attach_network(&self, vm: &VmLink, id: &str, n: u32, extra: &ExtraNetwork, is_first: bool) -> Result<(super::network::Network, [u8; 4], Option<[u8; 16]>), Error> { let net = { let mut nets = self.lock_networks(); nets.settle(&extra.name).map_err(Error::Conflict)?; @@ -3875,17 +5255,31 @@ impl Engine { self.lock_networks().allocate_avoiding(&net.name, &avoid).ok_or_else(|| Error::Conflict(format!("no free address left on network {}", net.name)))? } }; - let off6 = self.lock().containers.get(id).is_some_and(|c| c.spec.ipv6_disabled(&format!("eth{n}"))); + let (off6, names) = { + let st = self.lock(); + let Some(c) = st.containers.get(id).filter(|c| c.status == Status::Running) else { + drop(st); + self.release_ip(&net.name, ip); + return Err(Error::Conflict(format!("Container {} is not running", &id[..12]))); + }; + let off6 = c.spec.ipv6_disabled(&format!("eth{n}")); + let names = if net.builtin() { + Vec::new() + } else { + let host = if is_first && !c.spec.hostname.is_empty() { c.spec.hostname.clone() } else { c.short_id().to_owned() }; + let mut v = vec![c.name.clone(), host]; + v.extend(extra.aliases.iter().cloned()); + v + }; + (off6, names) + }; let ip6 = match if off6 { Ok(None) } else { self.allocate_ip6(&net, &extra.ipv6_address) } { Ok(a) => a, Err(e) => { - self.lock_networks().release(&net.name, ip); + self.release_ip(&net.name, ip); return Err(e); } }; - let (name, hostname) = self.lock().containers.get(id).map(|c| (c.name.clone(), c.short_id().to_owned())).unwrap_or_default(); - let mut names = vec![name, hostname]; - names.extend(extra.aliases.iter().cloned()); let mut opts: Vec = if extra.mac_address.is_empty() { Vec::new() } else { vec![format!("{}={}", kiri_proto::net_opts::MAC, extra.mac_address)] }; if let (Some(a), Some(v)) = (ip6, &net.v6) { opts.push(format!("{}={}/{}", kiri_proto::net_opts::IP6, super::network::ip6_str(a), v.prefix)); @@ -3897,23 +5291,15 @@ impl Engine { if net.no_ipv4 { opts.push(format!("{}=1", kiri_proto::net_opts::NO_IPV4)); } + if net.icc_disabled() { + opts.push(format!("{}=1", kiri_proto::net_opts::NO_ICC)); + } opts.push(format!("{}={}", kiri_proto::net_opts::NETWORK, net.name)); if let Err(e) = vm.net_attach(id, n, &net.bridge, ip, net.prefix, net.gateway, &names, &opts) { - let mut nets = self.lock_networks(); - nets.release(&net.name, ip); - if let Some(a) = ip6 { - nets.release6(&net.name, a); - } + self.release_attached_ips(&net.name, Some(ip), ip6); return Err(Error::Io(e)); } - if let Some(c) = self.lock().containers.get_mut(id) { - c.extra_ips.push((net.name.clone(), ip)); - c.extra_ifs.push((net.name.clone(), n)); - if let Some(a) = ip6 { - c.extra_ip6s.push((net.name.clone(), a)); - } - } - Ok(()) + Ok((net, ip, ip6)) } /// `docker network connect`. @@ -3921,57 +5307,95 @@ impl Engine { // After the start, as when the guest answered nothing else during // it, so this and the start's own networks are numbered in turn. let id = self.resolve_after_start(key)?; + // Serializes name reads/updates and runtime attachment with disconnect + // and rename so neither overwrites the other's DNS names or state. + let sync = self.names_sync(&id); + let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); let net = self.lock_networks().find(network).cloned().ok_or_else(|| Error::NotFound(format!("network {network} not found")))?; + if net.driver != "bridge" { + return Err(Error::BadRequest(format!("only bridge networks can be connected, not {}", net.driver))); + } if let Some(ip) = super::network::parse_ip(&ipv4_address) { net.check_static(ip).map_err(Error::BadRequest)?; } if let Some(ip) = super::network::parse_ip6(&ipv6_address) { net.check_static6(ip).map_err(Error::BadRequest)?; } - let (n, running) = { + let extra = ExtraNetwork { name: net.name.clone(), aliases, ipv4_address, ipv6_address, mac_address }; + let (n, was_left_all, ports) = { let mut st = self.lock(); let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?; - if c.spec.first_network_is(&net.name) || c.spec.extra_networks.iter().any(|x| x.name == net.name) { + if (!c.spec.left_all_networks && c.spec.first_network_is(&net.name)) || c.spec.extra_networks.iter().any(|x| x.name == net.name) { return Err(Error::Conflict(format!("endpoint with name {} already exists in network {}", c.name, net.name))); } - // It left every network it had: the one it joins becomes its - // first, which a start sets up as such. A running one has only - // loopback and its resolver set for no network, which a plug-in - // alone would not change. - if c.spec.left_all_networks { - if c.status == Status::Running { - return Err(Error::Conflict(format!("Kiri cannot connect a running container that left all its networks to {}; stop the container first", net.name))); + let was_left_all = c.spec.left_all_networks; + if !was_left_all && matches!(c.spec.network_mode.as_str(), "host" | "none") { + return Err(Error::BadRequest(format!("container cannot be connected to {} while on {}", net.name, c.spec.network_mode))); + } + if !was_left_all && c.spec.network_mode.starts_with("container:") { + return Err(Error::BadRequest("container sharing network namespace with another container or host cannot be connected to any other network".into())); + } + if c.status != Status::Running { + if was_left_all { + c.spec.join_first_network(extra); + } else { + c.spec.extra_networks.push(extra); } - c.spec.join_first_network(ExtraNetwork { name: net.name.clone(), aliases, ipv4_address, ipv6_address, mac_address }); drop(st); self.save(); self.emit_network("connect", &net, &id); return Ok(()); } - if matches!(c.spec.network_mode.as_str(), "host" | "none") { - return Err(Error::BadRequest(format!("container cannot be connected to {} while on {}", net.name, c.spec.network_mode))); - } - if c.spec.network_mode.starts_with("container:") { - return Err(Error::BadRequest("container sharing network namespace with another container or host cannot be connected to any other network".into())); + let min = if was_left_all { 0 } else { 1 }; + let Some(n) = free_eth(c, min) else { + return Err(Error::Conflict(format!("container {} has no free interface number left to attach network {}", c.name, net.name))); + }; + let ports = if was_left_all { c.spec.ports.clone() } else { Vec::new() }; + (n, was_left_all, ports) + }; + let vm = self.vm()?; + let (attached_net, ip, ip6) = self.attach_network(&vm, &id, n, &extra, was_left_all)?; + let fw = if was_left_all && !ports.is_empty() { + match super::ports::start(vm.clone(), &id, &ports, ip) { + Ok(fw) => Some(fw), + Err(e) => { + let _ = vm.net_detach(&id, n, &attached_net.bridge, ip); + self.release_attached_ips(&attached_net.name, Some(ip), ip6); + return Err(Error::Conflict(e.to_string())); + } } - c.spec.extra_networks.push(ExtraNetwork { name: net.name.clone(), aliases, ipv4_address, ipv6_address, mac_address }); - // The lowest eth number not in use: a disconnect may have freed - // one below the top. - let n = (1..).find(|n| !c.extra_ifs.iter().any(|(_, x)| x == n)).expect("a free number"); - (n, c.status == Status::Running) + } else { + None }; - self.save(); - if running { - let extra = self.lock().containers.get(&id).and_then(|c| c.spec.extra_networks.last().cloned()).ok_or_else(|| gone(&id))?; - let vm = self.vm()?; - if let Err(e) = self.attach_extra(&vm, &id, n, &extra) { - if let Some(c) = self.lock().containers.get_mut(&id) { - c.spec.extra_networks.retain(|x| x.name != net.name); + { + let mut st = self.lock(); + if let Some(c) = st.containers.get_mut(&id).filter(|c| c.status == Status::Running && !vm.is_disconnected()) { + if was_left_all { + c.spec.join_first_network(extra); + c.ip = Some(ip); + c.ip6 = ip6; + c.first_if = Some(n); + c.forwards = fw; + } else { + c.spec.extra_networks.push(extra); + c.extra_ips.push((attached_net.name.clone(), ip)); + c.extra_ifs.push((attached_net.name.clone(), n)); + if let Some(a) = ip6 { + c.extra_ip6s.push((attached_net.name.clone(), a)); + } } - return Err(e); + } else { + drop(st); + drop(fw); + if !vm.is_disconnected() { + let _ = vm.net_detach(&id, n, &attached_net.bridge, ip); + } + self.release_attached_ips(&attached_net.name, Some(ip), ip6); + return Err(Error::Conflict(format!("Container {} is not running", &id[..12]))); } } - self.emit_network("connect", &net, &id); + self.save(); + self.emit_network("connect", &attached_net, &id); Ok(()) } @@ -3984,7 +5408,22 @@ impl Engine { let sync = self.names_sync(&id); let _order = sync.as_ref().map(|m| m.lock().unwrap_or_else(|e| e.into_inner())); let net = self.lock_networks().find(network).cloned().ok_or_else(|| Error::NotFound(format!("network {network} not found")))?; - let (n, ip) = { + enum Detached { + Extra { + n: Option, + ip: Option<[u8; 4]>, + }, + First { + n: Option, + ip: Option<[u8; 4]>, + ip6: Option<[u8; 16]>, + old_fw: Option, + rebind_ports: Vec, + new_target: Option<[u8; 4]>, + running: bool, + }, + } + let work = { let mut st = self.lock(); let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?; if c.spec.first_network_is(&net.name) && matches!(net.name.as_str(), "host" | "none") { @@ -3994,52 +5433,91 @@ impl Engine { return Err(Error::BadRequest(format!("container cannot be disconnected from {} network", net.name))); } if c.spec.first_network_is(&net.name) { - // A running container's first network holds its default - // route, its main address (which published ports go to) and - // its resolver: moving those to another network while it - // runs needs the guest to do more than unplug it. - if c.status == Status::Running { - return Err(Error::Conflict(format!("Kiri cannot disconnect a running container from its first network ({}); stop the container first", net.name))); - } - let left = (c.ip.take(), c.ip6.take()); + let ip = c.ip.take(); + let ip6 = c.ip6.take(); + let n = c.first_if.take(); let nets = self.lock_networks(); c.spec.leave_first_network(|name| nets.find(name).is_some_and(|n| n.internal)); drop(nets); - drop(st); - // Not running, it holds no address; one left from a run that - // did not hand it back goes back to the pool all the same. - if let Some(ip) = left.0 { - self.release_ip(&net.name, ip); + if !c.spec.left_all_networks { + let promoted = c.spec.network_mode.clone(); + if let Some(i) = c.extra_ips.iter().position(|(x, _)| *x == promoted) { + c.ip = Some(c.extra_ips.remove(i).1); + } + if let Some(i) = c.extra_ip6s.iter().position(|(x, _)| *x == promoted) { + c.ip6 = Some(c.extra_ip6s.remove(i).1); + } + if let Some(i) = c.extra_ifs.iter().position(|(x, _)| *x == promoted) { + c.first_if = Some(c.extra_ifs.remove(i).1); + } } - if let Some(a) = left.1 { + let old_fw = c.forwards.take(); + let new_target = c.ip; + let running = c.status == Status::Running; + let rebind_ports = match &old_fw { + Some(fw) if running && new_target.is_some() && !c.spec.ports.is_empty() => rebind_bindings(&c.spec.ports, &fw.bound), + _ => Vec::new(), + }; + Detached::First { n, ip, ip6, old_fw, rebind_ports, new_target, running } + } else { + let Some(pos) = c.spec.extra_networks.iter().position(|x| x.name == net.name) else { + return Err(Error::NotFound(format!("container {} is not connected to network {}", &id[..12], net.name))); + }; + c.spec.extra_networks.remove(pos); + let ip = c.extra_ips.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ips.remove(i).1); + if let Some(i) = c.extra_ip6s.iter().position(|(x, _)| *x == net.name) { + let (_, a) = c.extra_ip6s.remove(i); self.lock_networks().release6(&net.name, a); } + let n = c.extra_ifs.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ifs.remove(i).1); + Detached::Extra { n, ip } + } + }; + match work { + Detached::Extra { n, ip } => { + self.save(); + if let Some(ip) = ip { + let unplugged = match (self.awake(), n) { + (Some(vm), Some(n)) => vm.net_detach(&id, n, &net.bridge, ip), + _ => Ok(()), + }; + // The network is gone from the container either way: its + // address goes back too, or the network can never be removed. + self.release_ip(&net.name, ip); + unplugged?; + } + } + Detached::First { n, ip, ip6, old_fw, rebind_ports, new_target, running } => { + // Closing listeners joins their threads: never under self.lock(). + drop(old_fw); + let unplugged = match (self.awake(), n, ip) { + (Some(vm), Some(n), Some(ip)) => vm.net_detach(&id, n, &net.bridge, ip), + _ => Ok(()), + }; + self.release_attached_ips(&net.name, ip, ip6); + if unplugged.is_ok() + && running + && !rebind_ports.is_empty() + && let (Some(vm), Some(target)) = (self.awake(), new_target) + { + match super::ports::start(vm.clone(), &id, &rebind_ports, target) { + Ok(fw) => { + let mut st = self.lock(); + if let Some(c) = st.containers.get_mut(&id).filter(|c| c.status == Status::Running && c.ip == Some(target) && !vm.is_disconnected()) { + c.forwards = Some(fw); + } else { + drop(st); + drop(fw); + } + } + Err(e) => crate::diag::warn!("published ports could not be moved after network disconnect", id = &id[..12], error = e), + } + } self.save(); self.emit_network("disconnect", &net, &id); + unplugged?; return Ok(()); } - let Some(pos) = c.spec.extra_networks.iter().position(|x| x.name == net.name) else { - return Err(Error::NotFound(format!("container {} is not connected to network {}", &id[..12], net.name))); - }; - c.spec.extra_networks.remove(pos); - let ip = c.extra_ips.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ips.remove(i).1); - if let Some(i) = c.extra_ip6s.iter().position(|(x, _)| *x == net.name) { - let (_, a) = c.extra_ip6s.remove(i); - self.lock_networks().release6(&net.name, a); - } - let n = c.extra_ifs.iter().position(|(x, _)| *x == net.name).map(|i| c.extra_ifs.remove(i).1); - (n, ip) - }; - self.save(); - if let Some(ip) = ip { - let unplugged = match (self.awake(), n) { - (Some(vm), Some(n)) => vm.net_detach(&id, n, &net.bridge, ip), - _ => Ok(()), - }; - // The network is gone from the container either way: its - // address goes back too, or the network can never be removed. - self.release_ip(&net.name, ip); - unplugged?; } self.emit_network("disconnect", &net, &id); Ok(()) @@ -4089,6 +5567,11 @@ impl Engine { let running = { let mut st = self.lock(); let c = st.containers.get_mut(&id).ok_or_else(|| gone(&id))?; + if c.spec.auto_remove && restart.as_ref().is_some_and(|r| r.name != "no") { + return Err(Error::Conflict(format!( + "Cannot update container {id}: Restart policy cannot be updated because AutoRemove is enabled for the container" + ))); + } c.spec.limits = limits; if let Some(r) = restart { c.spec.restart = r; @@ -4132,8 +5615,10 @@ impl Engine { let mode = self.lock().containers.get(&id).map(|c| c.spec.network_mode.clone()).unwrap_or_default(); let lines = self.vm()?.listening(&id)?; let (reach, local) = super::ports::listening(&lines, mode == "host"); - // With no network at all (or another container's), nothing can be published. - if mode == "none" || mode.starts_with("container:") { + // With no network of its own to forward into (none, another container's, + // or host networking on Linux where the container is already in the + // host's network namespace), nothing can be published. + if mode == "none" || mode.starts_with("container:") || (cfg!(target_os = "linux") && mode == "host") { return Ok((Vec::new(), [reach, local].concat())); } Ok((reach, local)) @@ -4154,28 +5639,44 @@ impl Engine { if c.spec.network_mode.starts_with("container:") && !ports.is_empty() { return Err(Error::BadRequest("conflicting options: port publishing and the container type network mode".into())); } - let target = if c.spec.network_mode == "host" { Some([127, 0, 0, 1]) } else { c.ip }; + let target = port_forward_target(&c.spec.network_mode, c.ip, cfg!(target_os = "linux")); let old = std::mem::replace(&mut c.spec.ports, ports.clone()); (old, c.forwards.take(), c.status == Status::Running, target) }; // Closing listeners joins their threads: never under the lock. drop(old_fw); - if running && !ports.is_empty() { + if running + && !ports.is_empty() + && let Some(target) = target + { let vm = self.vm()?; - let target = target.unwrap_or([127, 0, 0, 1]); match super::ports::start(vm.clone(), &id, &ports, target) { Ok(fw) => { - if let Some(c) = self.lock().containers.get_mut(&id) { - c.forwards = Some(fw); - } + let mut st = self.lock(); + let stale = if let Some(c) = st.containers.get_mut(&id).filter(|c| c.status == Status::Running && !vm.is_disconnected()) { + c.forwards.replace(fw) + } else { + Some(fw) + }; + drop(st); + drop(stale); } Err(e) => { crate::diag::warn!("new ports not published; the old ones are kept", id = &id[..12], error = e); - let back = super::ports::start(vm, &id, &old_ports, target).ok(); - if let Some(c) = self.lock().containers.get_mut(&id) { + let back = (!old_ports.is_empty()).then(|| super::ports::start(vm.clone(), &id, &old_ports, target).ok()).flatten(); + let mut st = self.lock(); + let stale = if let Some(c) = st.containers.get_mut(&id) { c.spec.ports = old_ports; - c.forwards = back; - } + if c.status == Status::Running && !vm.is_disconnected() { + std::mem::replace(&mut c.forwards, back) + } else { + back + } + } else { + back + }; + drop(st); + drop(stale); return Err(Error::Conflict(e.to_string())); } } @@ -4330,10 +5831,14 @@ impl Engine { // "already stopped" (304). return Ok(cancelled || ended_start); } + self.note_stopping_op(&[id.as_str()]); self.emit_container("kill", &id, &[("signal", (libc::SIGTERM).to_string())]); let sig = self.lock().containers.get(&id).and_then(|c| c.spec.stop_signal).unwrap_or(libc::SIGTERM as u32); - if let Some(vm) = self.awake() { - vm.kill(&id, sig)?; + if let Some(vm) = self.awake() + && let Err(e) = vm.kill(&id, sig) + { + self.clear_stopping_op(&id); + return Err(e.into()); } let deadline = std::time::Instant::now() + timeout; let mut st = self.lock(); @@ -4464,9 +5969,13 @@ impl Engine { *killing = killing.wrapping_add(1); self.mark_stopped(&id); } + self.note_stopping_op(&[id.as_str()]); self.emit_container("kill", &id, &[("signal", signal.to_string())]); - if let Some(vm) = self.awake() { - vm.kill(&id, signal)?; + if let Some(vm) = self.awake() + && let Err(e) = vm.kill(&id, signal) + { + self.clear_stopping_op(&id); + return Err(e.into()); } // Like Docker: a SIGKILL returns only once the exit is recorded, so // an immediate inspect, start or rm sees the container stopped. @@ -4499,8 +6008,12 @@ impl Engine { ))); } self.mark_stopped(&id); - if let Some(vm) = self.awake() { - vm.kill(&id, libc::SIGKILL as u32)?; + self.note_stopping_op(&[id.as_str()]); + if let Some(vm) = self.awake() + && let Err(e) = vm.kill(&id, libc::SIGKILL as u32) + { + self.clear_stopping_op(&id); + return Err(e.into()); } let mut st = self.lock(); while st.containers.get(&id).is_some_and(|c| c.status == Status::Running) { @@ -4510,7 +6023,7 @@ impl Engine { *removing = removing.wrapping_add(1); self.emit_container("destroy", &id, &[]); let mut st = self.lock(); - let removed = st.containers.remove(&id); + let mut removed = st.containers.remove(&id); // A `--rm` container that exited while the kill above waited has // removed itself and noted its code (137 when this kill ended it); // noting it again, with no record to read, told its waiters 0. @@ -4519,6 +6032,10 @@ impl Engine { } st.execs.retain(|_, e| e.container_id != id); drop(st); + // Closing listeners joins their threads: never under the lock, and + // before waking waiters or returning to callers that may rebind ports. + drop(removed.as_mut().and_then(|c| c.forwards.take())); + self.clear_stopping_op(&id); self.changed.notify_all(); let anon = self.unshared(removed.as_ref().map(|c| c.spec.anon_volumes.clone()).unwrap_or_default()); if let Some(c) = &removed { @@ -4539,11 +6056,20 @@ impl Engine { { crate::diag::warn!("writable layer left for the next boot", id = id, error = e); } + if let Some(c) = &removed + && !c.layers.is_empty() + && self.has_unlisted_layer(&c.layers) + { + self.prune_layers(); + } if with_volumes { for v in anon { self.delete_volume_data(&v); } } + if let Some(c) = &removed { + self.mark_volumes_dirty(c.spec.volumes.iter().chain(&c.spec.anon_volumes)); + } Ok(()) } @@ -4557,6 +6083,7 @@ impl Engine { let new = self.volume_get(name).is_none(); let v = self.lock_volumes().ensure(name, labels, anonymous).map_err(Error::BadRequest)?; if new { + self.record_new_volume(&v); self.emit_volume("create", name); } Ok(v) @@ -4568,6 +6095,7 @@ impl Engine { let new = self.volume_get(name).is_none(); let v = self.lock_volumes().ensure_with(name, labels, false, options).map_err(Error::BadRequest)?; if new { + self.record_new_volume(&v); self.emit_volume("create", name); } Ok(v) @@ -4588,10 +6116,18 @@ impl Engine { pub fn volume_remove(&self, name: &str, force: bool) -> Result<(), Error> { if self.volume_get(name).is_none() { + // Docker Engine returns 204 No Content for `DELETE /volumes/{name}?force=1` + // when the volume does not exist, and 404 Not Found without `force`. + if force { + return Ok(()); + } return Err(Error::NotFound(format!("get {name}: no such volume"))); } - let users = self.volume_users(name); - if !users.is_empty() && !force { + // A volume a container uses is refused even with `force`, as in Docker: + // `force` only ignores a missing volume and the damaged-list refusal below. + let mut users = self.volume_users(name); + if !users.is_empty() { + users.sort(); return Err(Error::Conflict(format!("remove {name}: volume is in use - [{}]", users.join(", ")))); } if !force && let Some(why) = self.refusal(&format!("Volume {name} was not removed, because the container list may be missing a container that uses it; `docker volume rm --force` removes it anyway")) { @@ -4624,6 +6160,7 @@ impl Engine { fn forget_volume(&self, name: &str) -> bool { let forgot = self.lock_volumes().forget(name); if forgot { + self.forget_volume_size(name); self.emit_volume("destroy", name); } forgot @@ -4671,14 +6208,26 @@ impl Engine { let exec_security; let (container_id, config, env) = { let mut st = self.lock(); - let e = st.execs.get_mut(exec_id).ok_or_else(|| Error::NotFound(format!("No such exec instance: {exec_id}")))?; - if e.running || e.exit_code.is_some() { + let (already_ran, container_id) = { + let e = st.execs.get(exec_id).ok_or_else(|| Error::NotFound(format!("No such exec instance: {exec_id}")))?; + (e.running || e.exit_code.is_some(), e.container_id.clone()) + }; + if already_ran { return Err(Error::Conflict("exec has already run".into())); } + match st.containers.get(&container_id) { + None => return Err(Error::Conflict(format!("container {} is not running", &container_id[..12]))), + Some(c) if c.status != Status::Running => return Err(Error::Conflict(format!("container {} is not running", &container_id[..12]))), + Some(c) if c.paused && !is_builder(c) => { + return Err(Error::Conflict(format!("Container {} is paused, unpause the container before exec", &container_id[..12]))); + } + _ => {} + } + let e = st.execs.get_mut(exec_id).expect("checked above"); e.running = true; // Subscribe before the process exists, so no output is missed. e.attached.push(tx); - let (container_id, config) = (e.container_id.clone(), e.config.clone()); + let config = e.config.clone(); let (security, caps) = st.containers.get(&container_id).map(|c| (c.spec.security_flags() & !run_flags::READONLY_ROOTFS, c.spec.caps)).unwrap_or_default(); // Execs get the container's ulimits and groups, as with runc. let opts = st.containers.get(&container_id).map(|c| c.spec.guest_opts(false).unwrap_or_default()).unwrap_or_default(); @@ -4713,6 +6262,25 @@ impl Engine { flags |= exec_security.0; let console = config.console_size; self.wait_for_start(&container_id); + let conflict = { + let st = self.lock(); + match st.containers.get(&container_id) { + None => Some(format!("container {} is not running", &container_id[..12])), + Some(c) if c.status != Status::Running => Some(format!("container {} is not running", &container_id[..12])), + Some(c) if c.paused && !is_builder(c) => Some(format!("Container {} is paused, unpause the container before exec", &container_id[..12])), + _ => None, + } + }; + if let Some(msg) = conflict { + let mut st = self.lock(); + if let Some(x) = st.execs.get_mut(exec_id) { + x.running = false; + x.attached.clear(); + } + drop(st); + self.changed.notify_all(); + return Err(Error::Conflict(msg)); + } let started = self.vm()?.exec(&container_id, exec_id, &config.argv, &env, &config.cwd, &config.user, flags, exec_security.1, &exec_security.2); if let Ok(pid) = started { if let Some(x) = self.lock().execs.get_mut(exec_id).filter(|x| x.exit_code.is_none()) { @@ -4766,6 +6334,31 @@ impl Engine { self.lock().containers.get(id).is_some_and(|c| c.status == Status::Running) } + /// Remembers the op under which these containers are being stopped, so + /// their exits are attributed to that operation (a restartvm, a recreate, + /// `kiri k8s set`) rather than a memory kill. Clears any earlier op when + /// stopped outside an op, so a stale entry cannot misattribute a later + /// exit. + fn note_stopping_op(&self, ids: &[&str]) { + let mut ops = self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()); + match crate::diag::op() { + Some(op) => { + for id in ids { + ops.insert((*id).to_owned(), op.clone()); + } + } + None => { + for id in ids { + ops.remove(*id); + } + } + } + } + + fn clear_stopping_op(&self, id: &str) { + self.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).remove(id); + } + /// Records a stop asked for by the user. True when that cancelled a /// restart its policy had pending. fn mark_stopped(&self, id: &str) -> bool { @@ -4791,6 +6384,15 @@ impl Engine { self.lock().containers.values().filter_map(&mut f).collect() } + /// Runs `f` over every container alongside the current networks slice, + /// locking container state before networks. + pub fn each_with_networks(&self, mut f: impl FnMut(&Container, &[super::network::Network]) -> Option) -> Vec { + let s = self.lock(); + let net = self.lock_net(); + let networks = net.all(); + s.containers.values().filter_map(|c| f(c, networks)).collect() + } + pub fn with(&self, key: &str, f: impl FnOnce(&Container) -> T) -> Result { let st = self.lock(); let id = resolve(&st, key)?; @@ -5212,7 +6814,13 @@ mod name_in_use_tests { #[cfg(test)] mod memory_target_tests { - use super::{estimate_used, next_memory_target, BalloonState, MEMORY_FLOOR, MEMORY_GROW, MEMORY_HEADROOM}; + use std::time::{Duration, Instant}; + + use super::{ + balloon_enabled_for, boot_without_vm, swap_mib_for, MAX_SWAP_MIB, estimate_used, memory_floor, memory_headroom, memory_min_bytes_for, next_memory_target, BalloonPolicy, + BalloonState, MemorySample, MEMORY_DEADBAND, MEMORY_FLOOR_ACTIVE_MIN, MEMORY_FLOOR_IDLE, MEMORY_GROW, MEMORY_HEADROOM_MAX, + MEMORY_HEADROOM_MIN, MEMORY_SHRINK_STEP, SHRINK_COOLDOWN, WS_PEAK_DECAY_INTERVAL, WS_PEAK_DECAY_STEP, + }; const MIB: u64 = 1 << 20; const GIB: u64 = 1 << 30; @@ -5222,13 +6830,26 @@ mod memory_target_tests { const MEM_TOTAL: u64 = 8_211_244 * 1024; const USED: u64 = 100 * MIB; + fn idle_policy(ceiling: u64) -> BalloonPolicy { + BalloonPolicy { ceiling, active_containers: 0, memory_min: 0 } + } + + fn active_policy(ceiling: u64) -> BalloonPolicy { + BalloonPolicy { ceiling, active_containers: 1, memory_min: 0 } + } + + fn sample(used: u64, mem_total: u64, mem_available: u64, balloon: Option) -> MemorySample { + MemorySample { used, mem_total, mem_available, balloon, committed_as: None, ws_peak: 0 } + } + /// Runs the balloon loop from `target` until it stops moving (older agent - /// without a balloon reading). + /// without a balloon reading, idle VM). fn settle(used: u64, mem_total: u64, mut target: u64) -> u64 { + let policy = idle_policy(CEILING); loop { let balloon = CEILING.saturating_sub(target); let mem_available = mem_total.saturating_sub(balloon).saturating_sub(used); - let Some(next) = next_memory_target(used, mem_total, mem_available, None, CEILING, target) else { + let Some(next) = next_memory_target(sample(used, mem_total, mem_available, None), policy, target) else { return target; }; target = next; @@ -5239,48 +6860,73 @@ mod memory_target_tests { /// bytes of `mem_total` are held by processes, uncharged kernel memory /// and zone reserves (`wmark_low + lowmem_reserve`), and `balloon` tracks /// `ceiling - target`. - fn settle_guest(ceiling: u64, mem_total: u64, used: u64, unavailable: u64) -> u64 { - let mut target = ceiling; + fn settle_guest_with(policy: BalloonPolicy, mem_total: u64, used: u64, unavailable: u64, committed_as: Option) -> u64 { + let mut target = policy.ceiling; loop { - let balloon = ceiling - target; + let balloon = policy.ceiling - target; let mem_available = mem_total.saturating_sub(balloon).saturating_sub(unavailable); - let Some(next) = next_memory_target(used, mem_total, mem_available, Some(balloon), ceiling, target) else { + let s = MemorySample { used, mem_total, mem_available, balloon: Some(balloon), committed_as, ws_peak: 0 }; + let Some(next) = next_memory_target(s, policy, target) else { return target; }; target = next; } } - /// The guest keeps the headroom above what it holds and what its kernel - /// took at boot, so it isn't left below its reclaim watermarks. + fn stats_sample( + mem_total: u64, + mem_available: u64, + mem_used: u64, + balloon: Option, + committed_as: Option, + ) -> kiri_proto::Stats { + kiri_proto::Stats { + uptime_ns: 0, + mem_total_kib: mem_total / 1024, + mem_available_kib: mem_available / 1024, + agent_rss_kib: 0, + mem_used_kib: mem_used / 1024, + mem_stall: 0, + oom_kills: 0, + mem_balloon_kib: balloon.map(|b| b / 1024), + mem_committed_kib: committed_as.map(|c| c / 1024), + } + } + + /// The guest keeps its proportional headroom above what it holds and what + /// its kernel took at boot, so it isn't left below its reclaim watermarks. #[test] fn the_guest_keeps_its_headroom_beyond_its_kernels_reserve() { let target = settle(USED, MEM_TOTAL, CEILING); let reserved = CEILING - MEM_TOTAL; + let headroom = memory_headroom(CEILING); + assert_eq!(headroom, 2 * GIB); assert!(reserved > 150 * MIB, "an 8 GiB guest's kernel keeps about 173 MiB"); - assert_eq!(target, USED + reserved + MEMORY_HEADROOM); + assert_eq!(target, USED + reserved + headroom); // Settled: nothing left to move. - assert_eq!(next_memory_target(USED, MEM_TOTAL, MEMORY_HEADROOM, None, CEILING, target), None); + assert_eq!(next_memory_target(sample(USED, MEM_TOTAL, headroom, None), idle_policy(CEILING), target), None); } /// On a larger VM (24 GiB), zone watermarks, lowmem_reserve (~153 MiB) - /// and uncharged kernel memory (~110 MiB) exceed MEMORY_HEADROOM by - /// themselves. With the guest's live balloon and MemAvailable, the guest - /// still settles with at least MEMORY_HEADROOM of MemAvailable. + /// and uncharged kernel memory (~110 MiB) are accounted for via the guest's + /// live balloon and MemAvailable, settling with at least H(C) of MemAvailable. #[test] fn large_vm_keeps_mem_available_headroom_beyond_zone_reserves() { let ceiling = 24 * GIB; let mem_total = 24_656_160 * 1024; let used = 200 * MIB; + let headroom = memory_headroom(ceiling); + assert_eq!(headroom, 2 * GIB); // cgroup-held memory + zone watermarks & lowmem_reserve (~153 MiB) // + uncharged kernel memory & active file cache (~115 MiB). let unavailable = used + 268 * MIB; - let target = settle_guest(ceiling, mem_total, used, unavailable); + let policy = idle_policy(ceiling); + let target = settle_guest_with(policy, mem_total, used, unavailable, None); let balloon = ceiling - target; let mem_available = mem_total.saturating_sub(balloon).saturating_sub(unavailable); - assert!(mem_available >= MEMORY_HEADROOM, "MemAvailable settled at {} MiB", mem_available / MIB); - assert!(mem_available < MEMORY_HEADROOM + 64 * MIB, "kept too much headroom: {} MiB", mem_available / MIB); - assert_eq!(next_memory_target(used, mem_total, mem_available, Some(balloon), ceiling, target), None); + assert!(mem_available >= headroom, "MemAvailable settled at {} MiB", mem_available / MIB); + assert!(mem_available < headroom + MEMORY_DEADBAND, "kept too much headroom: {} MiB", mem_available / MIB); + assert_eq!(next_memory_target(sample(used, mem_total, mem_available, Some(balloon)), policy, target), None); } /// When the guest's balloon lags behind `ceiling - target` while @@ -5292,31 +6938,34 @@ mod memory_target_tests { let ceiling = 24 * GIB; let mem_total = 24_656_160 * 1024; let unavailable = 300 * MIB; - let target = 2 * GIB; + let target = 6 * GIB; + let policy = idle_policy(ceiling); let caught_up_balloon = ceiling - target; let caught_up_avail = mem_total - caught_up_balloon - unavailable; let shrink_lag_balloon = caught_up_balloon - 180 * MIB; let shrink_lag_avail = mem_total - shrink_lag_balloon - unavailable; let deflate_lag_balloon = caught_up_balloon + 180 * MIB; let deflate_lag_avail = mem_total - deflate_lag_balloon - unavailable; - let expected = next_memory_target(100 * MIB, mem_total, caught_up_avail, Some(caught_up_balloon), ceiling, target); - assert_eq!(expected, next_memory_target(100 * MIB, mem_total, shrink_lag_avail, Some(shrink_lag_balloon), ceiling, target)); - assert_eq!(expected, next_memory_target(100 * MIB, mem_total, deflate_lag_avail, Some(deflate_lag_balloon), ceiling, target)); + let expected = next_memory_target(sample(100 * MIB, mem_total, caught_up_avail, Some(caught_up_balloon)), policy, target); + assert_eq!(expected, Some(target - MEMORY_SHRINK_STEP)); + assert_eq!(expected, next_memory_target(sample(100 * MIB, mem_total, shrink_lag_avail, Some(shrink_lag_balloon)), policy, target)); + assert_eq!(expected, next_memory_target(sample(100 * MIB, mem_total, deflate_lag_avail, Some(deflate_lag_balloon)), policy, target)); } /// Cold page cache is counted in MemAvailable by Linux, so the balloon - /// still reclaims it rather than hoarding gigabytes after a large read. + /// still reclaims it (in 128 MiB steps) rather than hoarding gigabytes + /// after a large read. #[test] fn cold_page_cache_is_reclaimed() { let ceiling = 24 * GIB; let mem_total = 24_656_160 * 1024; - let target = 5 * GIB; + let target = 8 * GIB; let balloon = ceiling - target; - // 300 MiB committed + 4 GiB clean page cache (counted in MemAvailable). + // 300 MiB committed + multi-GiB clean page cache (counted in MemAvailable). let mem_available = mem_total - balloon - 300 * MIB; assert_eq!( - next_memory_target(20 * MIB, mem_total, mem_available, Some(balloon), ceiling, target), - Some(target - 256 * MIB), + next_memory_target(sample(20 * MIB, mem_total, mem_available, Some(balloon)), idle_policy(ceiling), target), + Some(target - MEMORY_SHRINK_STEP), ); } @@ -5325,102 +6974,149 @@ mod memory_target_tests { fn zero_mem_available_under_pressure_grows_target() { let ceiling = 24 * GIB; let mem_total = 24_656_160 * 1024; - let target = GIB; + let target = 2 * GIB; let balloon = ceiling - target; assert_eq!( - next_memory_target(200 * MIB, mem_total, 0, Some(balloon), ceiling, target), - Some(target + MEMORY_HEADROOM), + next_memory_target(sample(200 * MIB, mem_total, 0, Some(balloon)), idle_policy(ceiling), target), + Some(target + memory_headroom(ceiling)), ); } #[test] fn it_shrinks_in_steps_and_grows_at_once() { - assert_eq!(next_memory_target(USED, MEM_TOTAL, MEM_TOTAL - USED, None, CEILING, CEILING), Some(CEILING - 256 * MIB)); + let policy = idle_policy(CEILING); + assert_eq!( + next_memory_target(sample(USED, MEM_TOTAL, MEM_TOTAL - USED, None), policy, CEILING), + Some(CEILING - MEMORY_SHRINK_STEP), + ); + assert_eq!(MEMORY_SHRINK_STEP, 128 * MIB); let target = settle(USED, MEM_TOTAL, CEILING); let more = USED + GIB; - assert_eq!(next_memory_target(more, MEM_TOTAL, 0, None, CEILING, target), Some(more + (CEILING - MEM_TOTAL) + MEMORY_HEADROOM)); + assert_eq!( + next_memory_target(sample(more, MEM_TOTAL, 0, None), policy, target), + Some(more + (CEILING - MEM_TOTAL) + memory_headroom(CEILING)), + ); } #[test] fn small_changes_leave_it_alone() { let target = settle(USED, MEM_TOTAL, CEILING); - assert_eq!(next_memory_target(USED + 32 * MIB, MEM_TOTAL, MEMORY_HEADROOM - 32 * MIB, None, CEILING, target), None); + let headroom = memory_headroom(CEILING); + assert_eq!(next_memory_target(sample(USED + 32 * MIB, MEM_TOTAL, headroom - 32 * MIB, None), idle_policy(CEILING), target), None); } /// No MemTotal (an agent that sent none): no reserve to add. #[test] fn without_a_mem_total_only_the_headroom_is_added() { - assert_eq!(settle(USED, 0, CEILING), USED + MEMORY_HEADROOM); + let expected = USED + memory_headroom(CEILING); + assert_eq!(next_memory_target(sample(USED, 0, 0, None), idle_policy(CEILING), 0), Some(expected)); + let settled = settle(USED, 0, CEILING); + assert!(settled >= expected && settled.abs_diff(expected) < MEMORY_DEADBAND); } #[test] fn it_stays_between_the_floor_and_the_ceiling() { - assert_eq!(settle(0, CEILING, CEILING), MEMORY_FLOOR); + // Proportional headroom H(C) = (C / 4).clamp(512 MiB, 2 GiB). + assert_eq!(memory_headroom(GIB), MEMORY_HEADROOM_MIN); + assert_eq!(memory_headroom(2 * GIB), 512 * MIB); + assert_eq!(memory_headroom(4 * GIB), GIB); + assert_eq!(memory_headroom(8 * GIB), 2 * GIB); + assert_eq!(memory_headroom(12 * GIB), MEMORY_HEADROOM_MAX); + assert_eq!(memory_headroom(24 * GIB), MEMORY_HEADROOM_MAX); + + assert_eq!(settle(0, CEILING, CEILING), memory_headroom(CEILING)); assert_eq!(settle(CEILING, MEM_TOTAL, CEILING / 2), CEILING); - assert_eq!(next_memory_target(u64::MAX, u64::MAX, u64::MAX, Some(u64::MAX), CEILING, CEILING / 2), Some(CEILING)); + assert_eq!( + next_memory_target( + MemorySample { + used: u64::MAX, + mem_total: u64::MAX, + mem_available: u64::MAX, + balloon: Some(u64::MAX), + committed_as: Some(u64::MAX), + ws_peak: u64::MAX, + }, + active_policy(CEILING), + CEILING / 2, + ), + Some(CEILING), + ); } - /// Right after a pressure growth (`MEMORY_GROW`), the balloon is still - /// deflating (`balloon > ceiling - target`) while `MemAvailable` is clamped - /// at zero (or still below headroom). The poll loop must hold `target` - /// steady instead of shrinking it back down and fighting the deflation. + /// Right after a pressure growth, the balloon is still deflating + /// (`balloon > ceiling - target`) while `MemAvailable` is clamped at zero + /// (or still below `H(C)`). The poll loop must hold `target` steady + /// instead of shrinking it back down and fighting the deflation. #[test] fn deflation_lag_after_growth_does_not_shrink_target() { let ceiling = 24 * GIB; let mem_total = 24_656_160 * 1024; + let headroom = memory_headroom(ceiling); + let policy = idle_policy(ceiling); let old_target = GIB; - let target = old_target + MEMORY_GROW; + // Target sits above `old_target + H(C)` so `want < target` while deflating. + let target = old_target + headroom + 512 * MIB; let unstarted_balloon = ceiling - old_target; - assert_eq!(next_memory_target(200 * MIB, mem_total, 0, Some(unstarted_balloon), ceiling, target), None); - // Partial deflation that has not yet restored MEMORY_HEADROOM still holds. - let partial_balloon = unstarted_balloon - 128 * MIB; - assert_eq!(next_memory_target(200 * MIB, mem_total, 64 * MIB, Some(partial_balloon), ceiling, target), None); + assert_eq!(next_memory_target(sample(200 * MIB, mem_total, 0, Some(unstarted_balloon)), policy, target), None); + // Partial deflation that has not yet restored H(C) still holds. + let partial_balloon = unstarted_balloon - GIB; + assert_eq!(next_memory_target(sample(200 * MIB, mem_total, GIB, Some(partial_balloon)), policy, target), None); // Real demand beyond `target` can still grow immediately. - assert!(next_memory_target(2 * GIB, mem_total, 0, Some(unstarted_balloon), ceiling, target).is_some_and(|n| n > target)); - // Once deflation restores ample MemAvailable, normal shrinking resumes. + assert!(next_memory_target(sample(2 * GIB, mem_total, 0, Some(unstarted_balloon)), policy, target).is_some_and(|n| n > target)); + // Once deflation restores ample MemAvailable >= H(C), normal shrinking resumes. let caught_up_balloon = ceiling - target; let caught_up_avail = mem_total - caught_up_balloon - 300 * MIB; + assert!(caught_up_avail >= headroom); assert_eq!( - next_memory_target(200 * MIB, mem_total, caught_up_avail, Some(caught_up_balloon), ceiling, target), - Some(target - 256 * MIB), + next_memory_target(sample(200 * MIB, mem_total, caught_up_avail, Some(caught_up_balloon)), policy, target), + Some(target - MEMORY_SHRINK_STEP), ); } /// An older agent that omits `Balloon` still reports `MemTotal` and /// `MemAvailable`. Even when zone reserves and uncharged kernel memory - /// exceed `MEMORY_HEADROOM`, the balloon must not shrink past - /// `MEMORY_HEADROOM` of `MemAvailable` or undo a pressure growth. + /// are significant, the balloon must not shrink past `H(C)` of + /// `MemAvailable` or undo a pressure growth. #[test] fn missing_balloon_reading_preserves_mem_available_headroom() { let ceiling = 24 * GIB; let mem_total: u64 = 24_656_160 * 1024; + let headroom = memory_headroom(ceiling); + let policy = idle_policy(ceiling); let used = 200 * MIB; let unavailable = used + 268 * MIB; let mut target = ceiling; loop { let balloon = ceiling - target; let mem_available = mem_total.saturating_sub(balloon).saturating_sub(unavailable); - let Some(next) = next_memory_target(used, mem_total, mem_available, None, ceiling, target) else { + let Some(next) = next_memory_target(sample(used, mem_total, mem_available, None), policy, target) else { break; }; target = next; } let mem_available = mem_total.saturating_sub(ceiling - target).saturating_sub(unavailable); - assert!(mem_available >= MEMORY_HEADROOM, "MemAvailable settled at {} MiB", mem_available / MIB); - assert!(mem_available < MEMORY_HEADROOM + 64 * MIB, "kept too much headroom: {} MiB", mem_available / MIB); + assert!(mem_available >= headroom, "MemAvailable settled at {} MiB", mem_available / MIB); + assert!(mem_available < headroom + MEMORY_DEADBAND, "kept too much headroom: {} MiB", mem_available / MIB); // After a pressure growth with MemAvailable still at 0, do not shrink. - assert_eq!(next_memory_target(used, mem_total, 0, None, ceiling, target + MEMORY_GROW), None); + assert_eq!(next_memory_target(sample(used, mem_total, 0, None), policy, target + MEMORY_GROW), None); } - /// A ceiling below MEMORY_FLOOR (e.g. a small KIRI_MEMORY_MIB) must clamp - /// cleanly instead of panicking in `u64::clamp`. + /// A ceiling below floor/headroom (e.g. a small KIRI_MEMORY_MIB) must + /// clamp cleanly instead of panicking in `u64::clamp`. #[test] fn ceiling_below_floor_does_not_panic() { let small_ceiling = 128 * MIB; let small_total = 120 * MIB; - assert_eq!(next_memory_target(32 * MIB, small_total, 64 * MIB, Some(0), small_ceiling, small_ceiling), None); - assert_eq!(next_memory_target(32 * MIB, small_total, 64 * MIB, None, small_ceiling, 0), Some(small_ceiling)); - assert_eq!(next_memory_target(0, 0, 0, None, 0, 0), None); + for policy in [ + idle_policy(small_ceiling), + active_policy(small_ceiling), + BalloonPolicy { ceiling: small_ceiling, active_containers: 1, memory_min: u64::MAX }, + ] { + assert_eq!(next_memory_target(sample(32 * MIB, small_total, 64 * MIB, Some(0)), policy, small_ceiling), None); + assert_eq!(next_memory_target(sample(32 * MIB, small_total, 64 * MIB, None), policy, 0), Some(small_ceiling)); + } + assert_eq!(next_memory_target(sample(0, 0, 0, None), idle_policy(0), 0), None); + assert_eq!(next_memory_target(sample(0, 0, 0, None), active_policy(0), 0), None); } /// An older agent reporting neither `mem_used_kib` nor `mem_balloon_kib` @@ -5432,6 +7128,9 @@ mod memory_target_tests { fn legacy_fallback_does_not_ratchet_or_overshoot_under_lag() { let ceiling = 24 * GIB; let mem_total_kib = 24_656_160; + let headroom = memory_headroom(ceiling); + let policy = idle_policy(ceiling); + let t0 = Instant::now(); let legacy_stats = |mem_available_kib| kiri_proto::Stats { uptime_ns: 0, mem_total_kib, @@ -5441,6 +7140,7 @@ mod memory_target_tests { mem_stall: 0, oom_kills: 0, mem_balloon_kib: None, + mem_committed_kib: None, }; // 1. Deflation lag after a fallback grow: grows once, then holds while @@ -5449,54 +7149,331 @@ mod memory_target_tests { let mut target = GIB; let st = legacy_stats(0); let used = estimate_used(&st, ceiling, target, 0); - let first = state.next_target(&st, used, ceiling, target); - assert_eq!(first, Some(GIB + MEMORY_HEADROOM)); + let first = state.next_target_at(&st, used, policy, target, false, t0); + assert_eq!(first, Some(GIB + headroom)); target = first.unwrap(); - for _ in 0..20 { + for sec in 1..=20 { let used = estimate_used(&st, ceiling, target, 0); - assert_eq!(state.next_target(&st, used, ceiling, target), None); + assert_eq!(state.next_target_at(&st, used, policy, target, false, t0 + Duration::from_secs(sec)), None); } // Partial deflation still below headroom does not double-grow. - let partial = legacy_stats(128 * 1024); + let partial = legacy_stats(GIB / 1024); let used = estimate_used(&partial, ceiling, target, 0); - assert_eq!(state.next_target(&partial, used, ceiling, target), None); - // Once deflation restores ample headroom, normal shrinking resumes. - let recovered = legacy_stats(512 * 1024); + assert_eq!(state.next_target_at(&partial, used, policy, target, false, t0 + Duration::from_secs(21)), None); + // Deflation recovers ample headroom, but target holds through SHRINK_COOLDOWN. + let recovered = legacy_stats((3 * GIB) / 1024); let used = estimate_used(&recovered, ceiling, target, 0); - assert_eq!(state.next_target(&recovered, used, ceiling, target), Some(target - 256 * MIB)); + assert_eq!(state.next_target_at(&recovered, used, policy, target, false, t0 + Duration::from_secs(22)), None); + // After SHRINK_COOLDOWN + decay interval, gentle shrinking resumes. + let used = estimate_used(&recovered, ceiling, target, 0); + assert_eq!( + state.next_target_at(&recovered, used, policy, target, false, t0 + SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL), + Some(target - WS_PEAK_DECAY_STEP), + ); // 2. Deflation lag right after an external `grow_memory()` bump: // zero additional fallback grows while MemAvailable remains 0. let mut state = BalloonState::default(); - let settled = legacy_stats(MEMORY_HEADROOM / 1024); - let used = estimate_used(&settled, ceiling, GIB, 0); - assert_eq!(state.next_target(&settled, used, ceiling, GIB), None); - let grown = GIB + MEMORY_GROW; - for _ in 0..10 { + let settled = legacy_stats(headroom / 1024); + let base_target = 3 * GIB; + let used = estimate_used(&settled, ceiling, base_target, 0); + assert_eq!(state.next_target_at(&settled, used, policy, base_target, false, t0), None); + let grown = base_target + MEMORY_GROW; + for sec in 1..=10 { let used = estimate_used(&st, ceiling, grown, 0); - assert_eq!(state.next_target(&st, used, ceiling, grown), None); + assert_eq!(state.next_target_at(&st, used, policy, grown, sec == 1, t0 + Duration::from_secs(sec)), None); } - // 3. Shrink lag: balloon has not inflated yet after a 256 MiB step, - // so MemAvailable stays at 512 MiB. Must hold until inflation lands - // instead of stepping past equilibrium into MemAvailable == 0. + // 3. Shrink lag: balloon has not inflated yet after a 128 MiB step, + // so MemAvailable stays at H + 128 MiB. Must hold until inflation + // lands instead of stepping past equilibrium into MemAvailable == 0. let mut state = BalloonState::default(); let reserved = ceiling - mem_total_kib * 1024; let unavailable = 300 * MIB; - let eq_target = reserved + unavailable + MEMORY_HEADROOM; - let start = eq_target + 256 * MIB; - let high_avail = legacy_stats((512 * MIB) / 1024); + let eq_target = reserved + unavailable + headroom; + let start = eq_target + MEMORY_SHRINK_STEP; + let high_avail = legacy_stats((headroom + MEMORY_SHRINK_STEP) / 1024); let used = estimate_used(&high_avail, ceiling, start, 0); - let shrunk = state.next_target(&high_avail, used, ceiling, start); + let shrunk = state.next_target_at(&high_avail, used, policy, start, false, t0); assert_eq!(shrunk, Some(eq_target)); // Two lagging polls before the balloon finishes inflating: no overshoot. - for _ in 0..2 { + for sec in 1..=2 { let used = estimate_used(&high_avail, ceiling, eq_target, 0); - assert_eq!(state.next_target(&high_avail, used, ceiling, eq_target), None); + assert_eq!(state.next_target_at(&high_avail, used, policy, eq_target, false, t0 + Duration::from_secs(sec)), None); } - // Once inflation catches up, MemAvailable settles at MEMORY_HEADROOM. + // Once inflation catches up, MemAvailable settles at headroom. let used = estimate_used(&settled, ceiling, eq_target, 0); - assert_eq!(state.next_target(&settled, used, ceiling, eq_target), None); + assert_eq!(state.next_target_at(&settled, used, policy, eq_target, false, t0 + Duration::from_secs(3)), None); + } + + /// Regression for #891: on an 8 GiB VM running SQL Server (~1.05 GiB anon, + /// ~0.35 GiB kernel/watermarks, ~2.0 GiB Committed_AS), the balloon must + /// keep MemAvailable >= 2 GiB (avoiding SQL Server Error 701) while still + /// returning ~3.8 GiB to macOS. + #[test] + fn sql_server_8gib_keeps_mem_available_above_2gib() { + let policy = active_policy(CEILING); + let reserved = CEILING - MEM_TOTAL; + let used = 1075 * MIB; // ~1.05 GiB AnonPages + let unavailable = 1434 * MIB; // ~1.40 GiB (anon + kernel/watermarks) + let committed = 2 * GIB; + + let mut state = BalloonState::default(); + let mut target = CEILING; + let t0 = Instant::now(); + for sec in 0..180u64 { + let balloon = CEILING - target; + let mem_available = MEM_TOTAL.saturating_sub(balloon).saturating_sub(unavailable); + let st = stats_sample(MEM_TOTAL, mem_available, used, Some(balloon), Some(committed)); + let est_used = estimate_used(&st, CEILING, target, 0); + if let Some(next) = state.next_target_at(&st, est_used, policy, target, false, t0 + Duration::from_secs(sec)) { + target = next; + } + } + let balloon = CEILING - target; + let mem_available = MEM_TOTAL.saturating_sub(balloon).saturating_sub(unavailable); + let expected_want = committed + reserved + memory_headroom(CEILING); + assert!( + target.abs_diff(expected_want) < MEMORY_DEADBAND, + "target settled at {} MiB, expected ~{} MiB", + target / MIB, + expected_want / MIB, + ); + assert!(mem_available >= 2 * GIB, "SQL Server needs >= 2 GiB MemAvailable, got {} MiB", mem_available / MIB); + assert!(balloon >= 3500 * MIB, "expected >= 3.5 GiB returned to macOS, got {} MiB", balloon / MIB); + + // Even with an older agent omitting Committed_AS, proportional H(8 GiB) = 2 GiB + // still keeps MemAvailable >= 2 GiB. + let target_no_commit = settle_guest_with(policy, MEM_TOTAL, used, unavailable, None); + let avail_no_commit = MEM_TOTAL.saturating_sub(CEILING - target_no_commit).saturating_sub(unavailable); + assert!(avail_no_commit >= 2 * GIB, "without Committed_AS, MemAvailable settled at {} MiB", avail_no_commit / MIB); + } + + /// Pathological sparse `Committed_AS` (e.g. huge untouched writable mappings) + /// is bounded by `used + min(C / 2, 4 GiB)` so it never pins 100% of VM RAM. + #[test] + fn sparse_committed_as_is_clamped_and_does_not_pin_ram() { + let used = 256 * MIB; + let unavailable = 356 * MIB; + for (ceiling, mem_total, expected_cap_overhead) in [ + (4 * GIB, 4 * GIB - 96 * MIB, 2 * GIB), + (8 * GIB, MEM_TOTAL, 4 * GIB), + (24 * GIB, 24_656_160 * 1024, 4 * GIB), + ] { + let policy = active_policy(ceiling); + let reserved = ceiling - mem_total; + let expected_want = (used + expected_cap_overhead + reserved + memory_headroom(ceiling)).clamp(policy.floor(), ceiling); + for huge_commit in [100 * GIB, u64::MAX] { + let target = settle_guest_with(policy, mem_total, used, unavailable, Some(huge_commit)); + assert!( + target.abs_diff(expected_want) < MEMORY_DEADBAND, + "ceiling {} GiB: target {} MiB vs expected ~{} MiB", + ceiling / GIB, + target / MIB, + expected_want / MIB, + ); + assert!(target < ceiling, "ceiling {} GiB must not pin 100% of RAM", ceiling / GIB); + } + } + } + + /// Working-set peak `ws_peak` is held for `SHRINK_COOLDOWN` (60 s) after + /// a new peak, grow, or `Event::Pressure`, and decays gently (<= 64 MiB + /// per 5 s) afterward. + #[test] + fn working_set_peak_holds_for_shrink_cooldown_then_decays_gently() { + let policy = active_policy(CEILING); + let headroom = memory_headroom(CEILING); + let reserved = CEILING - MEM_TOTAL; + let mut state = BalloonState::default(); + let t0 = Instant::now(); + + // 1. Spike working set: grows immediately and starts 60 s cooldown. + let mut target = 5 * GIB; + let spike_used = 4 * GIB; + let spike_unavail = spike_used + 200 * MIB; + let spike_balloon = CEILING - target; + let spike_avail = MEM_TOTAL.saturating_sub(spike_balloon).saturating_sub(spike_unavail); + assert!(spike_avail > 0); + let spike_stats = stats_sample(MEM_TOTAL, spike_avail, spike_used, Some(spike_balloon), Some(spike_used)); + let grown = state.next_target_at(&spike_stats, spike_used, policy, target, false, t0).expect("must grow on spike"); + let expected_peak_target = spike_unavail + reserved + headroom; + assert_eq!(grown, expected_peak_target); + target = grown; + + // Workload drops sharply to 1 GiB while MemAvailable is plentiful. + let low_used = GIB; + let low_unavail = GIB + 100 * MIB; + let poll_low = |state: &mut BalloonState, target: u64, pressure: bool, at: Instant| { + let balloon = CEILING - target; + let avail = MEM_TOTAL.saturating_sub(balloon).saturating_sub(low_unavail); + let st = stats_sample(MEM_TOTAL, avail, low_used, Some(balloon), Some(low_used)); + state.next_target_at(&st, low_used, policy, target, pressure, at) + }; + + // Must NOT shrink at all during the 60 s cooldown. + for sec in 1..=60 { + assert_eq!(poll_low(&mut state, target, false, t0 + Duration::from_secs(sec)), None, "shrunk early at t={sec}s"); + } + // Less than 5 s after cooldown ends: still no decay step yet. + for sec in 61..=64 { + assert_eq!(poll_low(&mut state, target, false, t0 + Duration::from_secs(sec)), None, "decayed early at t={sec}s"); + } + // At 65 s (5 s after cooldown): decays by exactly 64 MiB (<= 64 MiB per 5 s). + let after_first_decay = poll_low(&mut state, target, false, t0 + SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL) + .expect("should begin gentle decay after cooldown + 5 s"); + assert_eq!(target - after_first_decay, WS_PEAK_DECAY_STEP); + target = after_first_decay; + + // At 70 s: another 64 MiB step. + let after_second_decay = poll_low(&mut state, target, false, t0 + SHRINK_COOLDOWN + 2 * WS_PEAK_DECAY_INTERVAL) + .expect("second gentle decay step"); + assert_eq!(target - after_second_decay, WS_PEAK_DECAY_STEP); + target = after_second_decay; + + // 2. External `grow_memory()` + `Event::Pressure` resets 60 s cooldown. + let t_press = t0 + Duration::from_secs(72); + target = (target + MEMORY_GROW).min(CEILING); + assert_eq!(poll_low(&mut state, target, true, t_press), None); + for sec in 1..=60 { + assert_eq!(poll_low(&mut state, target, false, t_press + Duration::from_secs(sec)), None, "shrunk early after pressure at +{sec}s"); + } + let decayed_after_pressure = poll_low(&mut state, target, false, t_press + SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL) + .expect("should resume gentle decay after pressure cooldown"); + assert!(target - decayed_after_pressure <= WS_PEAK_DECAY_STEP); + + // 3. `Event::Pressure` when `target` is already at ceiling (no external + // target change) still holds ceiling for 60 s before decaying. + let mut ceil_state = BalloonState::default(); + let mut ceil_target = CEILING; + let t_ceil = Instant::now(); + assert_eq!(poll_low(&mut ceil_state, ceil_target, true, t_ceil), None); + for sec in 1..=60 { + assert_eq!(poll_low(&mut ceil_state, ceil_target, false, t_ceil + Duration::from_secs(sec)), None); + } + ceil_target = poll_low(&mut ceil_state, ceil_target, false, t_ceil + SHRINK_COOLDOWN + WS_PEAK_DECAY_INTERVAL) + .expect("should gently decay from ceiling after 60 s pressure cooldown"); + assert_eq!(CEILING - ceil_target, WS_PEAK_DECAY_STEP); + } + + /// Idle VMs (0 active containers) use the 256 MiB idle floor instead of + /// the active container floor `(C / 4).max(1 GiB).min(C)`, and optional + /// `memory_min_mib` in `vm.json` is honored and clamped to `0..=ceiling`. + #[test] + fn idle_zero_containers_uses_256mib_floor_and_honors_memory_min_mib() { + assert_eq!(memory_floor(2 * GIB, 0, 0), MEMORY_FLOOR_IDLE); + assert_eq!(memory_floor(2 * GIB, 1, 0), MEMORY_FLOOR_ACTIVE_MIN); + assert_eq!(memory_floor(4 * GIB, 1, 0), GIB); + assert_eq!(memory_floor(8 * GIB, 1, 0), 2 * GIB); + assert_eq!(memory_floor(24 * GIB, 1, 0), 6 * GIB); + assert_eq!(memory_floor(24 * GIB, 0, 0), MEMORY_FLOOR_IDLE); + + // 2 GiB VM: active floor holds 1 GiB; 0-container idle settles below 1 GiB. + let two_gib = 2 * GIB; + let two_gib_total = two_gib - 64 * MIB; + let active_2g = settle_guest_with(active_policy(two_gib), two_gib_total, 64 * MIB, 128 * MIB, None); + let idle_2g = settle_guest_with(idle_policy(two_gib), two_gib_total, 64 * MIB, 128 * MIB, None); + assert_eq!(active_2g, GIB); + assert!(idle_2g < GIB, "0-container 2 GiB VM should shrink below active 1 GiB floor, got {} MiB", idle_2g / MIB); + + // 24 GiB VM: active floor holds 6 GiB; 0-container idle shrinks well below 6 GiB. + let ceiling_24g = 24 * GIB; + let total_24g = 24_656_160 * 1024; + let active_24g = settle_guest_with(active_policy(ceiling_24g), total_24g, 200 * MIB, 468 * MIB, None); + let idle_24g = settle_guest_with(idle_policy(ceiling_24g), total_24g, 200 * MIB, 468 * MIB, None); + assert_eq!(active_24g, 6 * GIB); + assert!(idle_24g < 3 * GIB + 128 * MIB, "0-container 24 GiB VM should settle near ~3 GiB, got {} MiB", idle_24g / MIB); + + // Transitioning 0 -> 1 -> 0 containers on 24 GiB raises target to 6 GiB + // while active and allows returning toward idle floor once stopped. + let mut state = BalloonState::default(); + let t0 = Instant::now(); + let st_idle = stats_sample(total_24g, total_24g - (ceiling_24g - idle_24g) - 468 * MIB, 200 * MIB, Some(ceiling_24g - idle_24g), None); + let raised = state.next_target_at(&st_idle, 200 * MIB, active_policy(ceiling_24g), idle_24g, false, t0); + assert_eq!(raised, Some(6 * GIB)); + let st_after_exit = stats_sample(total_24g, total_24g - (ceiling_24g - 6 * GIB) - 468 * MIB, 200 * MIB, Some(ceiling_24g - 6 * GIB), None); + let shrinking = state.next_target_at(&st_after_exit, 200 * MIB, idle_policy(ceiling_24g), 6 * GIB, false, t0 + Duration::from_secs(1)); + assert_eq!(shrinking, Some(6 * GIB - MEMORY_SHRINK_STEP)); + + // Optional `memory_min_mib` in vm.json clamped to `0..=ceiling`. + assert_eq!(memory_min_bytes_for(None, CEILING), 0); + assert_eq!(memory_min_bytes_for(Some(0), CEILING), 0); + assert_eq!(memory_min_bytes_for(Some(4096), CEILING), 4 * GIB); + assert_eq!(memory_min_bytes_for(Some(16_384), CEILING), CEILING); + assert_eq!(memory_min_bytes_for(Some(u64::MAX), CEILING), CEILING); + + let pinned_4g = BalloonPolicy { ceiling: CEILING, active_containers: 0, memory_min: memory_min_bytes_for(Some(4096), CEILING) }; + assert_eq!(settle_guest_with(pinned_4g, MEM_TOTAL, USED, 200 * MIB, None), 4 * GIB); + let clamped_ceiling = BalloonPolicy { ceiling: CEILING, active_containers: 0, memory_min: memory_min_bytes_for(Some(16_384), CEILING) }; + assert_eq!(settle_guest_with(clamped_ceiling, MEM_TOTAL, USED, 200 * MIB, None), CEILING); + } + + /// The VM's swap (#326): `KIRI_SWAP_MIB`, else `vm.json`, else 1 GiB + /// as in Docker Desktop, never above the most Settings offers. + #[test] + fn swap_is_the_environment_then_the_setting_then_one_gib() { + assert_eq!(swap_mib_for(None, None), 1024); + assert_eq!(swap_mib_for(None, Some(0)), 0); + assert_eq!(swap_mib_for(None, Some(4096)), 4096); + assert_eq!(swap_mib_for(Some("512"), Some(4096)), 512); + assert_eq!(swap_mib_for(Some(" 0 "), None), 0); + assert_eq!(swap_mib_for(Some("lots"), Some(2048)), 2048, "an unreadable variable is ignored"); + assert_eq!(swap_mib_for(None, Some(1 << 30)), MAX_SWAP_MIB); + } + + /// `"balloon": false` in `vm.json` and `KIRI_NO_BALLOON=1` disable + /// `vm.set_memory_target(...)` while keeping `vm.stats()` telemetry + /// (`memory_used`, `mem_available_kib`, `memory_stall`, `oom_kills`) live. + #[test] + fn balloon_disabled_still_updates_stats_and_skips_target_updates() { + // Config & environment precedence. + assert!(balloon_enabled_for(None, None)); + assert!(balloon_enabled_for(None, Some(true))); + assert!(!balloon_enabled_for(None, Some(false))); + assert!(!balloon_enabled_for(Some("1"), None)); + assert!(!balloon_enabled_for(Some("1"), Some(true))); + assert!(!balloon_enabled_for(Some("true"), Some(true))); + assert!(balloon_enabled_for(Some("0"), Some(false))); + assert!(balloon_enabled_for(Some("false"), Some(false))); + assert!(balloon_enabled_for(Some(""), None)); + assert!(!balloon_enabled_for(Some(""), Some(false))); + + let dir = std::env::temp_dir().join(format!("kiri-balloon-disabled-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = boot_without_vm(&dir); + let ceiling = CEILING; + engine.ceiling.store(ceiling, std::sync::atomic::Ordering::Relaxed); + *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = ceiling; + + let stats = kiri_proto::Stats { + uptime_ns: 42, + mem_total_kib: MEM_TOTAL / 1024, + mem_available_kib: (MEM_TOTAL - 300 * MIB) / 1024, + agent_rss_kib: 1024, + mem_used_kib: (200 * MIB) / 1024, + mem_stall: 125, + oom_kills: 3, + mem_balloon_kib: Some(0), + mem_committed_kib: Some((256 * MIB) / 1024), + }; + + // Balloon disabled: telemetry updates, target stays at ceiling, callback skipped. + let mut state = BalloonState::default(); + let mut applied = Vec::new(); + engine.record_balloon_stats(&mut state, &stats, 0, false, false, Instant::now(), |next| applied.push(next)); + assert!(applied.is_empty(), "balloon: false must skip set_memory_target"); + assert_eq!(*engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()), ceiling); + assert!(engine.memory_used() >= 200 * MIB); + assert_eq!(engine.mem_available_kib.load(std::sync::atomic::Ordering::Relaxed), stats.mem_available_kib); + assert_eq!(engine.memory_trouble(), (1.25, 3)); + + // Balloon enabled: same stats shrink target by 128 MiB and invoke callback. + engine.record_balloon_stats(&mut state, &stats, 0, false, true, Instant::now(), |next| applied.push(next)); + assert_eq!(applied, vec![ceiling - MEMORY_SHRINK_STEP]); + assert_eq!(*engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()), ceiling - MEMORY_SHRINK_STEP); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); } } @@ -5523,9 +7500,26 @@ fn close_monitor(h: &mut HealthRun) { } } +/// Mounts and flags carried on a guest `Copy` frame. Archive ops (`IN`, `OUT`, +/// `STAT`) carry the container's mounts (with refreshed bind sources) and +/// `READONLY_ROOTFS` for `IN`; `EXPORT`, `DIFF`, `COMMIT` and `UPPER` operate +/// on the container's rootfs/layer alone, without mounts. +fn copy_mounts_and_flags(spec: &Spec, op: u8, flags: u32) -> (Vec, u32) { + if !matches!(op, kiri_proto::copy_op::IN | kiri_proto::copy_op::OUT | kiri_proto::copy_op::STAT) { + return (Vec::new(), flags); + } + let mounts = super::api::fresh_bind_sources(&spec.mounts, &spec.mount_info); + let flags = if op == kiri_proto::copy_op::IN && spec.readonly_rootfs { + flags | kiri_proto::copy_flags::READONLY_ROOTFS + } else { + flags + }; + (mounts, flags) +} + fn error_text(e: &Error) -> String { match e { - Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) => m.clone(), + Error::NotFound(m) | Error::Conflict(m) | Error::BadRequest(m) | Error::Unauthorized(m) | Error::Forbidden(m) => m.clone(), Error::Io(e) => e.to_string(), } } @@ -5555,6 +7549,8 @@ impl Engine { fn stop_together(&self, vm: &VmLink, ids: &[String], how: Stopping) -> Vec { let engine = how == Stopping::Engine; let t0 = std::time::Instant::now(); + let id_refs: Vec<&str> = ids.iter().map(String::as_str).collect(); + self.note_stopping_op(&id_refs); // (id, when to SIGKILL it, when it was SIGKILLed) let mut pending: Vec<(String, std::time::Instant, Option)> = Vec::new(); for id in ids { @@ -6485,6 +8481,13 @@ pub fn boot_without_vm(root: &std::path::Path) -> Arc { engine } +#[cfg(test)] +impl Engine { + pub(super) fn set_status(&self, id: &str, status: Status) { + self.lock().containers.get_mut(id).unwrap().status = status; + } +} + #[cfg(test)] mod records_tests { use super::*; @@ -7101,6 +9104,32 @@ mod start_wait_tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn copy_mounts_and_flags_scope_mounts_and_readonly_rootfs() { + let (engine, id, dir) = engine("copy-mounts"); + let mut s = engine.lock().containers[&id].spec.clone(); + s.mounts = vec![ + "/var/lib/kiri/volumes/pg/_data\t/var/lib/postgresql/data\tcreate,copyup".into(), + "tmpfs\t/tmp\ttmpfs,noexec,nosuid,nodev".into(), + ]; + s.readonly_rootfs = true; + let (mounts, flags) = copy_mounts_and_flags(&s, kiri_proto::copy_op::IN, kiri_proto::copy_flags::CHUNKED); + assert_eq!(mounts, s.mounts); + assert_eq!(flags, kiri_proto::copy_flags::CHUNKED | kiri_proto::copy_flags::READONLY_ROOTFS); + for op in [kiri_proto::copy_op::OUT, kiri_proto::copy_op::STAT] { + let (mounts, flags) = copy_mounts_and_flags(&s, op, 0); + assert_eq!(mounts, s.mounts); + assert_eq!(flags, 0); + } + for op in [kiri_proto::copy_op::EXPORT, kiri_proto::copy_op::DIFF, kiri_proto::copy_op::COMMIT, kiri_proto::copy_op::UPPER] { + let (mounts, flags) = copy_mounts_and_flags(&s, op, 0); + assert!(mounts.is_empty(), "op {op} must not mount volumes/binds"); + assert_eq!(flags, 0); + } + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + /// The exit of a container whose start waited for its root can be /// reported before the start ends: it is then not made live (the next /// run's early input would go straight to a guest with no process for @@ -7680,25 +9709,25 @@ mod leave_first_network_tests { done(engine, dir); } - /// With two others, the next first is the one Docker gives the default - /// route to: one that reaches outside before an internal one, then by - /// name, whatever the order they were connected in. The other stays an - /// extra network with its settings. + /// With two others, the next first is the first network in attachment order + /// that reaches outside (not `internal`), falling back to the first + /// attached internal network when none reaches outside. The others stay as + /// extra networks with their settings. #[test] - fn with_two_others_the_first_by_name_that_reaches_outside_takes_its_place() { - let (engine, id, dir) = engine("two", &[("zeta", false), ("alpha", true), ("beta", false)]); - connect(&engine, "zeta", &id, &["z"], "10.98.0.7"); + fn with_two_others_the_first_attached_that_reaches_outside_takes_its_place() { + let (engine, id, dir) = engine("two", &[("alpha", true), ("zeta", false), ("beta", false)]); connect(&engine, "alpha", &id, &["a"], ""); + connect(&engine, "zeta", &id, &["z"], "10.98.1.7"); connect(&engine, "beta", &id, &["b"], "10.98.2.9"); engine.disconnect("bridge", &id).unwrap(); let s = spec(&engine, &id); - assert_eq!(s.network_mode, "beta", "alpha is internal; beta comes before zeta"); - assert_eq!((s.aliases.as_slice(), s.ipv4_address.as_str()), (&["b".to_owned()][..], "10.98.2.9")); - assert_eq!(s.extra_networks.iter().map(|x| (x.name.as_str(), x.ipv4_address.as_str())).collect::>(), [("zeta", "10.98.0.7"), ("alpha", "")]); - // Leaving that one too: zeta reaches outside, alpha does not. - engine.disconnect("beta", &id).unwrap(); - assert_eq!(spec(&engine, &id).network_mode, "zeta"); + assert_eq!(s.network_mode, "zeta", "alpha is internal; zeta was attached before beta"); + assert_eq!((s.aliases.as_slice(), s.ipv4_address.as_str()), (&["z".to_owned()][..], "10.98.1.7")); + assert_eq!(s.extra_networks.iter().map(|x| (x.name.as_str(), x.ipv4_address.as_str())).collect::>(), [("alpha", ""), ("beta", "10.98.2.9")]); + // Leaving that one too: beta reaches outside, alpha does not. engine.disconnect("zeta", &id).unwrap(); + assert_eq!(spec(&engine, &id).network_mode, "beta"); + engine.disconnect("beta", &id).unwrap(); assert_eq!(spec(&engine, &id).network_mode, "alpha", "an internal network when it is the only one left"); done(engine, dir); } @@ -7788,21 +9817,175 @@ mod leave_first_network_tests { done(engine, dir); } - /// A running container is refused, with what to do instead, and - /// nothing changes: moving its default route, address and resolver to - /// another network while it runs is more than an unplug. + /// Disconnecting the first network on a running container removes it, + /// promotes the surviving secondary network's runtime attachment (`ip`, + /// `ip6`, `first_if`), and releases the left network's address. #[test] - fn a_running_container_must_be_stopped_first() { - let (engine, id, dir) = engine("running", &[("probe-net", false)]); - connect(&engine, "probe-net", &id, &[], ""); - engine.lock().containers.get_mut(&id).unwrap().status = Status::Running; - let r = engine.disconnect("bridge", &id); - assert!(matches!(&r, Err(Error::Conflict(m)) if m.contains("stop the container first")), "{r:?}"); - let s = spec(&engine, &id); - assert_eq!(s.network_mode, "bridge"); - assert_eq!(s.extra_networks.len(), 1); - done(engine, dir); - } + fn running_disconnect_from_first_network_promotes_secondary() { + let (engine, id, dir) = engine("running-promote", &[("probe-net", false)]); + let bridge_ip = engine.lock_networks().allocate_avoiding("bridge", &[]).unwrap(); + let probe_ip = engine.lock_networks().reserve("probe-net", [10, 98, 0, 20]).map(|()| [10, 98, 0, 20]).unwrap(); + connect(&engine, "probe-net", &id, &["web"], ""); + { + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Running; + c.ip = Some(bridge_ip); + c.first_if = Some(0); + c.extra_ips.push(("probe-net".into(), probe_ip)); + c.extra_ifs.push(("probe-net".into(), 1)); + } + engine.disconnect("bridge", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert_eq!(c.spec.network_mode, "probe-net"); + assert_eq!(c.spec.aliases, ["web"]); + assert!(!c.spec.left_all_networks); + assert!(c.spec.extra_networks.is_empty()); + assert_eq!(c.ip, Some(probe_ip)); + assert_eq!(c.first_if, Some(1)); + assert!(c.extra_ips.is_empty()); + assert!(c.extra_ifs.is_empty()); + assert_eq!(super::free_eth(c, 0), Some(0), "eth0 was freed"); + assert_eq!(super::free_eth(c, 1), Some(2), "eth1 stays in use by probe-net"); + } + assert_eq!(engine.lock_networks().allocate_avoiding("bridge", &[]), Some(bridge_ip), "left IP returned to pool"); + engine.lock_networks().release("bridge", bridge_ip); + // Leaving the promoted last network leaves no network at all. + engine.disconnect("probe-net", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert!(c.spec.left_all_networks); + assert_eq!(c.spec.network_mode, "none"); + assert_eq!(c.ip, None); + assert_eq!(c.first_if, None); + assert_eq!(super::free_eth(c, 0), Some(0)); + } + engine.lock_networks().reserve("probe-net", probe_ip).expect("promoted IP returned to pool"); + engine.lock_networks().release("probe-net", probe_ip); + done(engine, dir); + } + + /// Every interface number taken (as a damaged `containers.json` could + /// claim): connecting reports a Conflict instead of scanning (or hanging, + /// before the bound) for a free one under the engine lock. + #[test] + fn connecting_with_every_interface_taken_is_a_conflict_not_a_hang() { + let (engine, id, dir) = engine("eths-exhaust", &[("x", false)]); + connect(&engine, "x", &id, &["web"], ""); + { + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Running; + c.first_if = Some(0); + c.extra_ifs = (1..=MAX_ETH_IFS).map(|n| (format!("n{n}"), n)).collect(); + assert_eq!(super::free_eth(c, 0), None); + assert_eq!(super::free_eth(c, 1), None); + } + let ipam = parse_ipam(&serde_json::json!({"Config": [{"Subnet": "10.98.9.0/24"}]})).unwrap(); + engine.lock_networks().create("y", Settings { ipam, ..Default::default() }).unwrap(); + let e = engine.connect("y", &id, Vec::new(), String::new(), String::new(), String::new()).unwrap_err(); + let Error::Conflict(m) = &e else { panic!("a Conflict was expected, got {e:?}") }; + assert!(m.contains("no free interface number"), "got {e:?}"); + done(engine, dir); + } + + /// With three external networks attached in order (`a` on eth0, `zeta` on + /// eth1, `beta` on eth2), disconnecting `a` promotes `zeta` (eth1, its IP + /// and gateway) rather than sorting `beta` ahead of `zeta`, matching + /// `kiri-init`'s `route_holders` and a subsequent `stop`/`start`. + #[test] + fn running_disconnect_with_three_networks_promotes_first_attached_ip_gateway_and_interface() { + let (engine, id, dir) = engine("three-promote", &[("a", false), ("zeta", false), ("beta", false)]); + let a_ip = [10, 98, 0, 10]; + let zeta_ip = [10, 98, 1, 20]; + let beta_ip = [10, 98, 2, 30]; + engine.lock_networks().reserve("a", a_ip).unwrap(); + engine.lock_networks().reserve("zeta", zeta_ip).unwrap(); + engine.lock_networks().reserve("beta", beta_ip).unwrap(); + connect(&engine, "a", &id, &["a-alias"], ""); + engine.disconnect("bridge", &id).unwrap(); + connect(&engine, "zeta", &id, &["z-alias"], ""); + connect(&engine, "beta", &id, &["b-alias"], ""); + { + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Running; + c.ip = Some(a_ip); + c.first_if = Some(0); + c.extra_ips = vec![("zeta".into(), zeta_ip), ("beta".into(), beta_ip)]; + c.extra_ifs = vec![("zeta".into(), 1), ("beta".into(), 2)]; + } + engine.disconnect("a", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert_eq!(c.spec.network_mode, "zeta"); + assert_eq!(c.spec.aliases, ["z-alias"]); + assert_eq!(c.ip, Some(zeta_ip)); + assert_eq!(c.first_if, Some(1), "eth1 matches kiri-init's promoted route holder"); + assert_eq!(c.spec.extra_networks.iter().map(|x| x.name.as_str()).collect::>(), ["beta"]); + assert_eq!(c.extra_ips, [("beta".to_owned(), beta_ip)]); + assert_eq!(c.extra_ifs, [("beta".to_owned(), 2)]); + } + assert_eq!(engine.lock_networks().find("zeta").unwrap().gateway, [10, 98, 1, 1]); + + engine.disconnect("zeta", &id).unwrap(); + { + let st = engine.lock(); + let c = &st.containers[&id]; + assert_eq!(c.spec.network_mode, "beta"); + assert_eq!(c.spec.aliases, ["b-alias"]); + assert_eq!(c.ip, Some(beta_ip)); + assert_eq!(c.first_if, Some(2)); + assert!(c.spec.extra_networks.is_empty()); + assert!(c.extra_ips.is_empty()); + assert!(c.extra_ifs.is_empty()); + } + assert_eq!(engine.lock_networks().find("beta").unwrap().gateway, [10, 98, 2, 1]); + done(engine, dir); + } + + #[test] + fn rebind_bindings_preserves_ephemeral_host_ports() { + let bindings = vec![ + super::super::ports::Binding { container_port: 80, proto: "tcp".into(), host_ip: String::new(), host_port: 0 }, + super::super::ports::Binding { container_port: 443, proto: "tcp".into(), host_ip: "127.0.0.1".into(), host_port: 8443 }, + ]; + let bound = vec![ + (bindings[0].clone(), "0.0.0.0".into(), 49152), + (bindings[0].clone(), "::".into(), 49152), + (bindings[1].clone(), "127.0.0.1".into(), 8443), + ]; + let rebound = super::rebind_bindings(&bindings, &bound); + assert_eq!(rebound.len(), 2); + assert_eq!(rebound[0].host_port, 49152); + assert_eq!(rebound[1].host_port, 8443); + } + + #[test] + fn port_forward_target_skips_host_network_only_on_linux() { + // On Linux (host_shares_netns = true), --network host shares the daemon's + // own network namespace, so published PortBindings are not bound by the + // host relay (#764); on macOS (host_shares_netns = false), --network host + // runs inside the Linux VM's netns so the Mac relay forwards to 127.0.0.1 (#732). + assert_eq!(super::port_forward_target("host", None, true), None); + assert_eq!(super::port_forward_target("host", Some([0; 4]), true), None); + assert_eq!(super::port_forward_target("host", None, false), Some([127, 0, 0, 1])); + assert_eq!(super::port_forward_target("host", Some([0; 4]), false), Some([127, 0, 0, 1])); + + // Bridge and user networks forward to their assigned IPv4 on both platforms. + for linux in [false, true] { + assert_eq!(super::port_forward_target("bridge", Some([172, 17, 0, 2]), linux), Some([172, 17, 0, 2])); + assert_eq!(super::port_forward_target("app-net", Some([10, 88, 0, 3]), linux), Some([10, 88, 0, 3])); + assert_eq!(super::port_forward_target("bridge", None, linux), None); + assert_eq!(super::port_forward_target("bridge", Some([0; 4]), linux), None); + assert_eq!(super::port_forward_target("none", Some([172, 17, 0, 2]), linux), None); + assert_eq!(super::port_forward_target("container:abc", Some([172, 17, 0, 2]), linux), None); + } + } /// Records saved before a container could leave all its networks load, /// as on a network. @@ -7817,6 +10000,180 @@ mod leave_first_network_tests { } } +#[cfg(test)] +mod layer_gc_tests { + use super::*; + + fn hex_digest(c: &str) -> String { + format!("sha256:{}", c.repeat(64)) + } + + fn test_image(name: &str, cfg: &str, layers: &[&str]) -> Image { + Image { + mirror: None, + name: name.into(), + digest: hex_digest(cfg), + index_digest: None, + config_digest: hex_digest(cfg), + layers: layers + .iter() + .map(|d| kiri_image::Layer { digest: (*d).into(), size: 1024, media_type: "application/vnd.oci.image.layer.v1.tar".into() }) + .collect(), + size: layers.len() as u64 * 1024, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + } + } + + fn insert_container(engine: &Engine, id: &str, image_id: &str, layers: Vec, status: Status) { + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": "demo:1", "image_id": image_id, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + })) + .unwrap(); + let mut st = engine.lock(); + st.containers.insert( + id.into(), + Container { + lifecycle: Arc::new(Mutex::new(0)), + names_sync: Arc::default(), + start_gate: Arc::default(), + id: id.into(), + name: format!("c-{id}"), + layers, + spec, + created: SystemTime::now(), + status, + started: None, + finished: None, + exit_code: 0, + oom_killed: false, + vm_stopped: false, + stopped_by_user: false, + restart_count: 0, + restart_pending: false, + exits: 0, + size: None, + ip: None, + pid: 0, + forwards: None, + live: false, + early_input: Vec::new(), + early_close: false, + start_owed: false, + paused: false, + extra_ips: Vec::new(), + first_if: None, + extra_ifs: Vec::new(), + ip6: None, + extra_ip6s: Vec::new(), + log: Arc::new(Mutex::new(super::super::logfile::Log::new( + super::super::logfile::dir(engine.store.root(), id), + &Default::default(), + ))), + attached: Vec::new(), + }, + ); + } + + /// Live layer GC keeps layers referenced by remaining images, running + /// containers, stopped containers and in-flight creates, while dropping + /// layers only a removed or overwritten image used (#722). + #[test] + fn retained_layers_keeps_images_containers_and_in_flight_pins() { + let root = std::env::temp_dir().join(format!("kiri-layer-gc-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let engine = boot_without_vm(&root); + + let (shared, only_a, only_b, stopped_l, running_l, inflight_l) = + (hex_digest("1"), hex_digest("2"), hex_digest("3"), hex_digest("4"), hex_digest("5"), hex_digest("6")); + engine.store.put_image(test_image("a:1", "a", &[&shared, &only_a])).unwrap(); + engine.store.put_image(test_image("b:1", "b", &[&shared, &only_b])).unwrap(); + insert_container(&engine, "stopped1", &hex_digest("c"), vec![stopped_l.clone()], Status::Exited); + insert_container(&engine, "running1", &hex_digest("d"), vec![running_l.clone()], Status::Running); + + // Removing a:1 drops only_a, while shared stays for b:1 and container layers stay. + engine.store.remove_image("a:1").unwrap(); + let mut sent = Vec::new(); + engine.prune_layers_with(|keep| { + sent = keep.to_vec(); + Ok(()) + }).unwrap(); + let mut want = vec![shared.clone(), only_b.clone(), stopped_l.clone(), running_l.clone()]; + want.sort(); + assert_eq!(sent, want); + + // An in-flight create pins its layers across prune_layers even if the + // image disappears before the container is inserted, and overlapping + // pins are reference-counted. + let p1 = engine.pin_layers([inflight_l.as_str()]); + let p2 = engine.pin_layers([inflight_l.as_str()]); + assert!(engine.retained_layers().unwrap().contains(&inflight_l)); + drop(p1); + assert!(engine.retained_layers().unwrap().contains(&inflight_l), "second pin still holds it"); + drop(p2); + assert!(!engine.retained_layers().unwrap().contains(&inflight_l), "gone once last pin drops"); + + // has_unlisted_layer detects when removing a container frees a layer + // whose image was already overwritten or removed, and stays false for + // layers still in store.images(). + assert!(!engine.has_unlisted_layer(&[shared.clone(), only_b.clone()])); + assert!(engine.has_unlisted_layer(&[shared.clone(), stopped_l.clone()])); + + // Removing the stopped container drops stopped_l from the retained set. + engine.remove("stopped1", false, false).unwrap(); + assert!(!engine.retained_layers().unwrap().contains(&stopped_l)); + assert!(engine.retained_layers().unwrap().contains(&running_l)); + + // Overwriting b:1 drops only_b immediately from the retained set. + let fresh = hex_digest("7"); + engine.store.put_image(test_image("b:1", "e", &[&shared, &fresh])).unwrap(); + let kept = engine.retained_layers().unwrap(); + assert!(!kept.contains(&only_b)); + assert!(kept.contains(&shared) && kept.contains(&fresh) && kept.contains(&running_l)); + + drop(engine); + let _ = std::fs::remove_dir_all(&root); + } + + /// Neither live GC nor boot-time GC deletes any layer while either + /// `containers.json` or `images.json` has a `.corrupt-*` copy (#440, #722). + #[test] + fn prune_layers_skips_when_records_or_images_are_damaged() { + let root = std::env::temp_dir().join(format!("kiri-layer-gc-damaged-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("containers.json.corrupt-1-0"), b"[").unwrap(); + let engine = boot_without_vm(&root); + assert!(engine.retained_layers().is_none(), "damaged containers.json must keep every layer"); + let mut called = false; + engine.prune_layers_with(|_| { + called = true; + Ok(()) + }).unwrap(); + assert!(!called); + drop(engine); + let _ = std::fs::remove_dir_all(&root); + + let root2 = std::env::temp_dir().join(format!("kiri-layer-gc-imgdmg-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root2); + std::fs::create_dir_all(&root2).unwrap(); + std::fs::write(root2.join("images.json.corrupt-1-0"), b"[").unwrap(); + let engine2 = boot_without_vm(&root2); + assert!(engine2.retained_layers().is_none(), "damaged images.json must keep every layer"); + let mut called2 = false; + engine2.prune_layers_with(|_| { + called2 = true; + Ok(()) + }).unwrap(); + assert!(!called2); + drop(engine2); + let _ = std::fs::remove_dir_all(&root2); + } +} + #[cfg(all(test, target_os = "linux"))] mod cpu_tests { /// The CPUs `Cpus_allowed_list` of /proc/self/status lists. @@ -7839,3 +10196,706 @@ mod cpu_tests { assert_eq!(super::vm_cpus(), allowed()); } } + +#[cfg(test)] +mod exit_log_tests { + use super::*; + + fn engine_with_container(name: &str) -> (Arc, String, PathBuf) { + let dir = std::env::temp_dir().join(format!("kiri-exit-log-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = boot_without_vm(&dir); + let image = Image { + mirror: None, + name: "test:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + }; + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": "test:local", "image_id": "sha256:test", "entrypoint": [], "cmd": ["sleep", "60"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap(); + let id = engine.create(Some(name.into()), spec, &image).unwrap(); + engine.lock().containers.get_mut(&id).unwrap().status = Status::Running; + (engine, id, dir) + } + + #[test] + fn kernel_oom_logs_memory_readings_relieves_balloon_and_clears_stopping_op() { + let (engine, id, dir) = engine_with_container("oom"); + let ceiling = engine.ceiling(); + let shrunk = ceiling / 2; + *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = shrunk; + // Pressure carries MemAvailable (KiB) and PSI full avg10. + engine.on_event(Event::Pressure { mem_available_kib: 64 * 1024, mem_stall: 842 }); + assert_eq!(engine.mem_available_kib.load(std::sync::atomic::Ordering::Relaxed), 64 * 1024); + assert_eq!(engine.memory_stall.load(std::sync::atomic::Ordering::Relaxed), 842); + // Set target below ceiling again so we directly verify `relieve_memory` on OOM. + *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()) = shrunk; + // Even if a stopping op was recorded earlier, kernel OOM wins and still + // consumes the stale op entry. + { + let _op = crate::diag::enter_op("restartvm-1234".into()); + engine.note_stopping_op(&[id.as_str()]); + } + let expected_balloon = cfg!(target_os = "macos").then_some((ceiling >> 20, ceiling >> 20)); + assert_eq!( + engine.classify_exit(&id, "oom", 137, true), + Some(ExitLog::MemoryKill { + name: "oom".into(), + exit_code: 137, + mem_available_mib: 64, + psi_full_avg10: 842, + balloon: expected_balloon, + }) + ); + let after_target = *engine.memory_target.lock().unwrap_or_else(|e| e.into_inner()); + if cfg!(target_os = "macos") { + assert_eq!(after_target, ceiling, "macOS must deflate balloon to ceiling before reporting a memory kill"); + } else { + assert_eq!(after_target, shrunk, "non-macOS hosts have no balloon to touch"); + } + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty(), "OOM exit cleared stopping_ops"); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn op_stop_attributes_to_op_while_ordinary_sigkill_is_not_misattributed() { + let (engine, id, dir) = engine_with_container("ops"); + // Kiri-initiated stops under `restartvm-...` and `k8s-...` attribute to that op. + for (op, expected_kind) in [("restartvm-a1b2", "restartvm"), ("k8s-c3d4", "k8s"), ("k8sset-e5f6", "k8sset")] { + { + let _guard = crate::diag::enter_op(op.into()); + engine.note_stopping_op(&[id.as_str()]); + } + assert_eq!( + engine.classify_exit(&id, "ops", 137, false), + Some(ExitLog::OpStop { kind: expected_kind.into(), name: "ops".into(), exit_code: 137, op: op.into() }) + ); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + } + // Ordinary SIGKILL (exit 137, oom_killed = false, no op): neither OOM nor op stop. + assert_eq!(engine.classify_exit(&id, "ops", 137, false), None); + + // A stale op from an earlier stop is cleared when a later stop arrives with no op. + { + let _guard = crate::diag::enter_op("restartvm-9999".into()); + engine.note_stopping_op(&[id.as_str()]); + } + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id)); + engine.note_stopping_op(&[id.as_str()]); + assert_eq!(engine.classify_exit(&id, "ops", 137, false), None); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn stopping_ops_are_cleaned_up_on_exit_destroy_and_vm_loss() { + // 1. Real kill under an op + Event::Exited cleans up stopping_ops. + let (engine, id, dir) = engine_with_container("cleanup-exit"); + { + let _op = crate::diag::enter_op("k8sset-1111".into()); + engine.kill(&id, libc::SIGTERM as u32).unwrap(); + } + assert_eq!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).get(&id).map(String::as_str), Some("k8sset-1111")); + engine.on_event(Event::Exited { id: &id, code: 143, oom: false }); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + + // 2. Destroying a stopped container with a stale op cleans it up. + { + let _op = crate::diag::enter_op("restartvm-2222".into()); + engine.note_stopping_op(&[id.as_str()]); + } + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id)); + engine.remove(&id, false, false).unwrap(); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + + // 3. VM loss clears every tracked op. + { + let _op = crate::diag::enter_op("restartvm-3333".into()); + engine.note_stopping_op(&["orphan-a", "orphan-b"]); + } + assert_eq!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).len(), 2); + engine.on_event(Event::Lost); + assert!(engine.stopping_ops.lock().unwrap_or_else(|e| e.into_inner()).is_empty()); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } +} + +#[cfg(test)] +mod volume_remove_tests { + use super::*; + + fn test_image() -> Image { + Image { + mirror: None, + name: "test:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + } + } + + fn container_with_volumes(engine: &Engine, image: &Image, name: &str, volumes: Vec, anon_volumes: Vec) -> String { + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": image.name, "image_id": image.config_digest, "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0}, "volumes": volumes, "anon_volumes": anon_volumes, + })) + .unwrap(); + engine.create(Some(name.into()), spec, image).unwrap() + } + + #[test] + fn volume_remove_refuses_users_across_states_and_force_ignores_missing() { + let dir = std::env::temp_dir().join(format!("kiri-vol-rm-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = boot_without_vm(&dir); + let image = test_image(); + + // Missing volume: 404 without force, 204 (Ok) with force. + assert!(matches!(engine.volume_remove("missing", false), Err(Error::NotFound(m)) if m == "get missing: no such volume")); + engine.volume_remove("missing", true).unwrap(); + + // Volume in use: refused with or without force across Created, Running, Exited. + engine.volume_ensure("used", serde_json::json!({}), false).unwrap(); + engine.volume_ensure("anon-used", serde_json::json!({}), true).unwrap(); + let holder = container_with_volumes(&engine, &image, "holder", vec!["used".into()], Vec::new()); + let anon_holder = container_with_volumes(&engine, &image, "anon-holder", Vec::new(), vec!["anon-used".into()]); + + for status in [Status::Created, Status::Running, Status::Exited] { + engine.lock().containers.get_mut(&holder).unwrap().status = status; + for force in [false, true] { + assert!( + matches!(engine.volume_remove("used", force), Err(Error::Conflict(m)) if m == "remove used: volume is in use - [holder]"), + "status={status:?} force={force}" + ); + assert!(engine.volume_get("used").is_some()); + } + } + + // Multiple holders are sorted deterministically in the conflict message. + let holder2 = container_with_volumes(&engine, &image, "alpha-holder", vec!["used".into()], Vec::new()); + assert!(matches!( + engine.volume_remove("used", true), + Err(Error::Conflict(m)) if m == "remove used: volume is in use - [alpha-holder, holder]" + )); + + // Anonymous volume in use is also refused even with force. + assert!(matches!( + engine.volume_remove("anon-used", true), + Err(Error::Conflict(m)) if m == "remove anon-used: volume is in use - [anon-holder]" + )); + + // Once containers are gone, force and non-force removal succeed. + engine.remove(&holder, false, false).unwrap(); + engine.remove(&holder2, false, false).unwrap(); + engine.remove(&anon_holder, false, false).unwrap(); + engine.volume_remove("used", true).unwrap(); + engine.volume_remove("anon-used", false).unwrap(); + assert!(engine.volume_get("used").is_none()); + assert!(engine.volume_get("anon-used").is_none()); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn saved_ref_matches_saved_byte_for_byte_and_roundtrips() { + use crate::daemon::{health, logfile, ports}; + let dir = std::env::temp_dir().join(format!("kiri-saved-ref-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let spec = Spec { + image: "registry.example.com/team/service:1.2.3".into(), + image_id: "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), + entrypoint: vec!["/usr/local/bin/entrypoint".into(), "--strict".into()], + cmd: vec!["serve".into(), "--port=8080".into()], + env: vec!["RUST_LOG=info".into(), "APP_ENV=production".into()], + cwd: "/srv/service".into(), + user: "1000:1000".into(), + auto_remove: false, + network_mode: "frontend".into(), + labels: serde_json::json!({ + "com.docker.compose.project": "kiri", + "com.docker.compose.service": "api", + }), + tty: true, + open_stdin: true, + restart: RestartPolicy { name: "on-failure".into(), max_retries: 5 }, + console_size: Some((42, 132)), + aliases: vec!["api".into(), "api.internal".into()], + extra_hosts: vec!["10.10.0.5 db.internal".into()], + ports: vec![ + ports::Binding { + container_port: 8080, + proto: "tcp".into(), + host_ip: "127.0.0.1".into(), + host_port: 18080, + }, + ports::Binding { + container_port: 5353, + proto: "udp".into(), + host_ip: String::new(), + host_port: 0, + }, + ], + exposed: vec!["5353/udp".into(), "8080/tcp".into()], + mounts: vec!["/host/data\t/data\trw".into()], + mount_info: vec![serde_json::json!({ + "Type": "bind", + "Source": "/host/data", + "Destination": "/data", + "RW": true, + })], + mount_request: serde_json::json!({ + "Binds": ["/host/data:/data:rw"], + "Mounts": [], + "Tmpfs": {"/run": "rw,noexec,nosuid,size=65536k"}, + "Volumes": {"/var/lib/data": {}}, + }), + volumes: vec!["named-data".into(), "shared-cache".into()], + anon_volumes: vec!["anon-00112233".into()], + privileged: true, + limits: Limits { + memory_max: 512 << 20, + cpu_quota: 150_000, + cpu_period: 100_000, + cpu_weight: 200, + pids_max: 256, + shm_size: 128 << 20, + cpu_shares: 2048, + memory_swap: 1024 << 20, + }, + caps: 0x3fff, + cap_add: vec!["NET_ADMIN".into()], + cap_drop: vec!["MKNOD".into()], + security_opt: vec!["no-new-privileges:true".into()], + readonly_rootfs: true, + hostname: "api-node-1".into(), + stop_signal: Some(15), + stop_timeout: Some(25), + healthcheck: Some(health::Healthcheck { + test: vec!["CMD-SHELL".into(), "curl -fsS http://127.0.0.1:8080/healthz || exit 1".into()], + interval: 10_000_000_000, + timeout: 5_000_000_000, + start_period: 15_000_000_000, + start_interval: 2_000_000_000, + retries: 3, + }), + shell: vec!["/bin/bash".into(), "-o".into(), "pipefail".into(), "-c".into()], + init: Some(true), + extra_networks: vec![ExtraNetwork { + name: "backplane".into(), + aliases: vec!["api-bp".into()], + ipv4_address: "172.28.0.10".into(), + ipv6_address: "fd00:28::10".into(), + mac_address: "02:42:ac:1c:00:0a".into(), + }], + log_config: logfile::LogConfig { + kind: "json-file".into(), + config: std::collections::BTreeMap::from([ + ("max-file".into(), "4".into()), + ("max-size".into(), "20m".into()), + ]), + }, + ipv4_address: "172.20.0.9".into(), + ipv6_address: "fd00:20::9".into(), + mac_address: "02:42:ac:14:00:09".into(), + left_all_networks: true, + dns: vec!["1.1.1.1".into(), "8.8.8.8".into()], + dns_search: vec!["svc.cluster.local".into()], + dns_options: vec!["ndots:2".into(), "timeout:1".into()], + domainname: "example.internal".into(), + links: vec![Link { + id: "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210".into(), + name: "redis".into(), + alias: "cache".into(), + }], + host_opts: serde_json::json!({ + "Sysctls": {"net.core.somaxconn": "1024"}, + "Ulimits": [{"Name": "nofile", "Soft": 4096, "Hard": 8192}], + "GroupAdd": ["wheel"], + }), + volumes_from: vec!["seed-data:ro".into()], + pid_mode: "host".into(), + wsl_distro: Some("Ubuntu".into()), + }; + + let log_dir = dir.join("containers").join("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"); + let c = Container { + lifecycle: Arc::new(Mutex::new(0)), + names_sync: Arc::default(), + start_gate: Arc::default(), + id: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef".into(), + name: "full-container".into(), + log: Arc::new(Mutex::new(logfile::Log::new(log_dir, &spec.log_config))), + spec, + layers: vec![ + "sha256:1111111111111111111111111111111111111111111111111111111111111111".into(), + "sha256:2222222222222222222222222222222222222222222222222222222222222222".into(), + ], + created: UNIX_EPOCH + Duration::from_nanos(1_700_000_000_123_456_789), + status: Status::Exited, + started: Some(UNIX_EPOCH + Duration::from_nanos(1_700_000_010_222_333_444)), + finished: Some(UNIX_EPOCH + Duration::from_nanos(1_700_000_050_555_666_777)), + exit_code: 137, + oom_killed: true, + vm_stopped: true, + stopped_by_user: true, + restart_count: 4, + restart_pending: true, + exits: 4, + size: Some((42, 132)), + ip: Some([172, 20, 0, 9]), + pid: 4321, + forwards: None, + paused: true, + extra_ips: vec![("backplane".into(), [172, 28, 0, 10])], + first_if: Some(0), + extra_ifs: vec![("backplane".into(), 1)], + ip6: Some([0xfd, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9]), + extra_ip6s: vec![("backplane".into(), [0xfd, 0, 0, 0x28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10])], + live: false, + early_input: vec![1, 2, 3], + early_close: true, + start_owed: false, + attached: Vec::new(), + }; + + // 1. Direct From<&Container> (health = None). + assert_eq!(serde_json::to_value(SavedRef::from(&c)).unwrap(), serde_json::to_value(Saved::from(&c)).unwrap()); + assert_eq!(serde_json::to_string(&SavedRef::from(&c)).unwrap(), serde_json::to_string(&Saved::from(&c)).unwrap()); + assert_eq!(serde_json::to_vec(&SavedRef::from(&c)).unwrap(), serde_json::to_vec(&Saved::from(&c)).unwrap()); + + // 2. Populated health state + full round-trip deserialization back into Saved. + let health = health::Health { + status: health::UNHEALTHY.into(), + failing_streak: 3, + log: VecDeque::from([health::Probe { + start: "2026-11-24T10:00:00.000000000Z".into(), + end: "2026-11-24T10:00:01.250000000Z".into(), + exit_code: 1, + output: "probe failed: connection refused\n".into(), + }]), + }; + let saved_ref = SavedRef::from_container(&c, Some(&health)); + let saved_owned = Saved::from_container(&c, Some(&health)); + + assert_eq!(serde_json::to_value(&saved_ref).unwrap(), serde_json::to_value(&saved_owned).unwrap()); + let ref_bytes = serde_json::to_vec(&saved_ref).unwrap(); + let owned_bytes = serde_json::to_vec(&saved_owned).unwrap(); + assert_eq!(ref_bytes, owned_bytes); + + let decoded: Saved = serde_json::from_slice(&ref_bytes).unwrap(); + assert_eq!(decoded, saved_owned); + + let _ = std::fs::remove_dir_all(dir); + } +} + +#[cfg(test)] +mod exit_forwards_tests { + use super::*; + use std::net::TcpListener; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + fn engine_running(name: &str) -> (Arc, String, PathBuf) { + let dir = std::env::temp_dir().join(format!("kiri-exit-fwd-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let engine = Engine::boot(Store::open(&dir).unwrap()).unwrap(); + engine.stopped.store(true, Ordering::SeqCst); + let image = Image { + mirror: None, + name: "test:local".into(), + digest: "sha256:test".into(), + index_digest: None, + config_digest: "sha256:test".into(), + layers: Vec::new(), + size: 0, + platform: "linux/arm64".into(), + created: String::new(), + pulled_at: 0, + config: Default::default(), + }; + let spec: Spec = serde_json::from_value(serde_json::json!({ + "image": "test:local", "image_id": "sha256:test", "entrypoint": [], "cmd": ["sleep", "60"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": {}, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap(); + let id = engine.create(Some(name.into()), spec, &image).unwrap(); + engine.lock().containers.get_mut(&id).unwrap().status = Status::Running; + (engine, id, dir) + } + + /// `Event::Exited` must drop (unpublish + close listeners + join threads) + /// `c.forwards` outside `self.state` BEFORE setting `c.status = Exited` + /// and notifying `self.changed`, so a rapid `docker restart` (`wait("not-running")` + /// -> `start`) never binds against still-open sockets or has its new DNAT + /// rules wiped by a delayed `Forwards::drop` (#649). + #[test] + fn event_exited_drops_forwards_before_marking_exited_or_waking_restart() { + let (engine, id, dir) = engine_running("ordered"); + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let dropped = Arc::new(AtomicBool::new(false)); + let saw_running_on_drop = Arc::new(AtomicBool::new(false)); + let second_dropped = Arc::new(AtomicBool::new(false)); + let drop_count = Arc::new(AtomicUsize::new(0)); + + let fw = { + let engine = engine.clone(); + let id = id.clone(); + let dropped = dropped.clone(); + let saw_running = saw_running_on_drop.clone(); + let second_dropped = second_dropped.clone(); + let drop_count = drop_count.clone(); + super::super::ports::Forwards::test_dummy(Vec::new(), Some(listener), move || { + // Acquiring `engine.lock()` proves `Forwards::drop` runs outside `self.state`. + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + assert!(c.forwards.is_none(), "c.forwards must already be taken"); + saw_running.store(c.status == Status::Running, Ordering::SeqCst); + // Simulate a concurrent start/connect/set_ports installing a second + // `Forwards` while the lock was released: `Event::Exited` must drop + // it too before transitioning to `Exited`. + let count = drop_count.clone(); + let second = second_dropped.clone(); + c.forwards = Some(super::super::ports::Forwards::test_dummy(Vec::new(), None, move || { + count.fetch_add(1, Ordering::SeqCst); + second.store(true, Ordering::SeqCst); + })); + drop(st); + // Widen any window where a racing `wait("not-running")` could wake early. + std::thread::sleep(Duration::from_millis(40)); + drop_count.fetch_add(1, Ordering::SeqCst); + dropped.store(true, Ordering::SeqCst); + }) + }; + engine.lock().containers.get_mut(&id).unwrap().forwards = Some(fw); + + let waiter = { + let (engine, id) = (engine.clone(), id.clone()); + let (dropped, second_dropped) = (dropped.clone(), second_dropped.clone()); + std::thread::spawn(move || { + let code = engine.wait(&id, "not-running").unwrap(); + assert_eq!(code, 0); + // The instant `docker restart`'s `wait("not-running")` wakes up, + // every old `Forwards` has ALREADY finished dropping/unpublishing + // and the bound port is free to rebind immediately. + assert!(dropped.load(Ordering::SeqCst), "old Forwards must drop before wait wakes"); + assert!(second_dropped.load(Ordering::SeqCst), "raced Forwards must also drop before wait wakes"); + let rebound = TcpListener::bind(("127.0.0.1", port)); + assert!(rebound.is_ok(), "port {port} must already be closed when wait returns: {rebound:?}"); + }) + }; + // Let the waiter enter `self.changed.wait`. + std::thread::sleep(Duration::from_millis(30)); + engine.on_event(Event::Exited { id: &id, code: 0, oom: false }); + waiter.join().unwrap(); + + assert!(saw_running_on_drop.load(Ordering::SeqCst), "c.status must still be Running while old Forwards drops"); + assert_eq!(drop_count.load(Ordering::SeqCst), 2); + let st = engine.lock(); + assert_eq!(st.containers[&id].status, Status::Exited); + assert!(st.containers[&id].forwards.is_none()); + drop(st); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + /// `remove()` must also drop any leftover `c.forwards` outside `self.state`. + #[test] + fn remove_drops_forwards_outside_state_lock() { + let (engine, id, dir) = engine_running("rm-outside-lock"); + let dropped = Arc::new(AtomicBool::new(false)); + { + let engine_ref = engine.clone(); + let dropped_ref = dropped.clone(); + let mut st = engine.lock(); + let c = st.containers.get_mut(&id).unwrap(); + c.status = Status::Exited; + c.forwards = Some(super::super::ports::Forwards::test_dummy(Vec::new(), None, move || { + // Must not deadlock: `self.state` is not held when `Forwards` drops. + let _st = engine_ref.lock(); + dropped_ref.store(true, Ordering::SeqCst); + })); + } + engine.remove(&id, false, false).unwrap(); + assert!(dropped.load(Ordering::SeqCst), "remove() must drop leftover Forwards before returning"); + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + /// Refusing `exec_create` and `exec_start` on a paused non-builder container + /// returns 409 Conflict instead of cloning a child into a frozen cgroup (#948). + #[test] + fn exec_create_and_start_refuse_paused_non_builder_container() { + let (engine, id, dir) = engine_running("exec-paused-conflict"); + let cfg = || ExecConfig { + console_size: None, + argv: vec!["true".into()], + env: Vec::new(), + cwd: "/".into(), + user: String::new(), + tty: true, + stdin: false, + privileged: false, + internal: false, + }; + + engine.lock().containers.get_mut(&id).unwrap().paused = true; + match engine.exec_create(&id, cfg()) { + Err(Error::Conflict(msg)) => assert!(msg.contains("is paused, unpause the container before exec"), "{msg}"), + other => panic!("expected Conflict on paused exec_create, got {other:?}"), + } + + engine.lock().containers.get_mut(&id).unwrap().paused = false; + let exec_id = engine.exec_create(&id, cfg()).unwrap(); + engine.lock().containers.get_mut(&id).unwrap().paused = true; + let attempts_before = engine.boot_attempts.load(Ordering::SeqCst); + match engine.exec_start(&exec_id) { + Err(Error::Conflict(msg)) => assert!(msg.contains("is paused, unpause the container before exec"), "{msg}"), + other => panic!("expected Conflict on paused exec_start, got {other:?}"), + } + assert_eq!(engine.boot_attempts.load(Ordering::SeqCst), attempts_before, "paused exec_start must not touch VM"); + assert!(engine.with_exec(&exec_id, |e| !e.running && e.exit_code.is_none()).unwrap()); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn detects_guest_missing_unpacked_layer_error() { + assert!(super::is_missing_unpacked_layer_error( + "run f0991bd92f25: layer sha256:821d9dafb26dc8e4afce2273366520f49e38f8f679a72fc512f2a83e62f442b7 is not unpacked" + )); + assert!(super::is_missing_unpacked_layer_error("layer sha256:0123 is not unpacked")); + assert!(!super::is_missing_unpacked_layer_error("run c1: mount /payload: No space left on device")); + assert!(!super::is_missing_unpacked_layer_error("the VM stopped")); + } + + /// Regression test for #989: `kiri-k8s` (`dev.kiri.k8s`) bind-mounts `/Users` + /// and `/Volumes` on macOS (and `/mnt` on Linux/WSL) for pod `hostPath` + /// access, which must NOT cause `mac_bind_sources` or `wsl_bind_sources` to + /// watch the entire host filesystem, while ordinary containers keep theirs; + /// and `k8s_timer_slack_opt` sets 10 ms timer coalescing only for `kiri-k8s`. + #[test] + fn k8s_node_skips_host_bind_watchers_and_gets_timer_slack() { + let (engine, app_id, dir) = engine_running("k8s-bind-watch"); + { + let mut st = engine.lock(); + let app = st.containers.get_mut(&app_id).unwrap(); + app.spec.mounts = vec![ + "/mnt/mac/Users/alice/app\t/app\t".into(), + "/mnt/c/Users/alice/app\t/win\t".into(), + ]; + assert_eq!(super::k8s_timer_slack_opt(&app.spec), None); + + let mut k8s = Container { + lifecycle: Arc::new(Mutex::new(0)), + names_sync: Arc::default(), + start_gate: Arc::default(), + id: "k8s00000000000000000000000000000".into(), + name: "kiri-k8s".into(), + layers: Vec::new(), + spec: app.spec.clone(), + created: SystemTime::now(), + status: Status::Running, + started: Some(SystemTime::now()), + finished: None, + exit_code: 0, + oom_killed: false, + vm_stopped: false, + stopped_by_user: false, + restart_count: 0, + restart_pending: false, + exits: 0, + size: None, + ip: None, + pid: 42, + forwards: None, + paused: false, + extra_ips: Vec::new(), + first_if: None, + extra_ifs: Vec::new(), + ip6: None, + extra_ip6s: Vec::new(), + live: true, + early_input: Vec::new(), + early_close: false, + start_owed: false, + log: Arc::new(Mutex::new(super::super::logfile::Log::new( + super::super::logfile::dir(engine.store.root(), "k8s00000000000000000000000000000"), + &app.spec.log_config, + ))), + attached: Vec::new(), + }; + k8s.spec.labels = serde_json::json!({"dev.kiri.k8s": "1"}); + k8s.spec.mounts = vec![ + "/mnt/mac/Users\t/Users\t".into(), + "/mnt/mac/Volumes\t/Volumes\t".into(), + "/mnt/c\t/mnt/c\t".into(), + ]; + assert_eq!( + super::k8s_timer_slack_opt(&k8s.spec).as_deref(), + Some("timerslack\t10000000") + ); + st.containers.insert(k8s.id.clone(), k8s); + } + + #[cfg(target_os = "macos")] + assert_eq!(engine.mac_bind_sources(), vec!["/Users/alice/app".to_owned()]); + assert_eq!(engine.wsl_bind_sources("/mnt/"), vec!["/mnt/c/Users/alice/app".to_owned()]); + + // When only `kiri-k8s` runs, no host bind watcher roots remain at all. + engine.lock().containers.get_mut(&app_id).unwrap().status = Status::Exited; + #[cfg(target_os = "macos")] + assert!(engine.mac_bind_sources().is_empty()); + assert!(engine.wsl_bind_sources("/mnt/").is_empty()); + + drop(engine); + let _ = std::fs::remove_dir_all(dir); + } +} + +/// 10 ms timer slack applied to `kiri-k8s` (`dev.kiri.k8s`) so `k3s`'s dozens of +/// staggered 100 ms `watch_progress` / `kine` / `cAdvisor` timers coalesce +/// cleanly instead of waking virtual CPUs thousands of times per second (#989). +const K8S_TIMER_SLACK_NS: u64 = 10_000_000; + +fn is_k8s_node(spec: &Spec) -> bool { + spec.labels.get("dev.kiri.k8s").is_some() +} + +fn watches_host_binds(c: &Container) -> bool { + c.status == Status::Running && !is_k8s_node(&c.spec) +} + +fn k8s_timer_slack_opt(spec: &Spec) -> Option { + is_k8s_node(spec).then(|| format!("timerslack\t{K8S_TIMER_SLACK_NS}")) +} + +/// Whether a guest `Run` error reports that an image layer was missing under +/// `/var/lib/kiri/layers` (`kiri-init`'s `roots::acquire` formats this as +/// `"layer is not unpacked"`). +fn is_missing_unpacked_layer_error(msg: &str) -> bool { + msg.contains("layer sha256:") && msg.ends_with(" is not unpacked") +} diff --git a/crates/kiri/src/daemon/grpc.rs b/crates/kiri/src/daemon/grpc.rs new file mode 100644 index 000000000..1d253b381 --- /dev/null +++ b/crates/kiri/src/daemon/grpc.rs @@ -0,0 +1,2272 @@ +//! Docker's BuildKit endpoints (`POST /grpc` and `POST /session`): lets buildx +//! (including a docker CLI inside a container mounting `/var/run/docker.sock`) +//! use its `docker` driver against Kiri's managed BuildKit container +//! (`buildx_buildkit_kiri-build0`), landing built images directly into Kiri's +//! image store without creating a separate unconfigured `default` builder. +//! +//! Zero external crates: minimal HTTP/2 framing, a passive RFC 7541 HPACK +//! decoder for tracking `Control/Solve` streams, and a wire-preserving +//! protobuf rewriter for `SolveRequest` / `SolveResponse` / `BytesMessage`. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::Shutdown; +use std::os::unix::net::UnixStream; +use std::sync::mpsc::Receiver; +use std::sync::{Arc, Condvar, Mutex, OnceLock}; + +use kiri_image::Reference; +use kiri_proto::Stream; + +use super::api::{self, Next}; +use super::builder; +use super::engine::{Engine, Error}; +use super::http::{self, Request}; +use super::mirror::{self, LoadSession}; + +const H2_PREFACE: &[u8; 24] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + +const FRAME_DATA: u8 = 0x0; +const FRAME_HEADERS: u8 = 0x1; +const FRAME_RST_STREAM: u8 = 0x3; +const FRAME_SETTINGS: u8 = 0x4; +const FRAME_PING: u8 = 0x6; +const FRAME_GOAWAY: u8 = 0x7; +const FRAME_WINDOW_UPDATE: u8 = 0x8; +const FRAME_CONTINUATION: u8 = 0x9; + +const FLAG_END_STREAM: u8 = 0x01; +const FLAG_ACK: u8 = 0x01; +const FLAG_END_HEADERS: u8 = 0x04; +const FLAG_PADDED: u8 = 0x08; +const FLAG_PRIORITY: u8 = 0x20; + +const SETTING_INITIAL_WINDOW_SIZE: u16 = 0x4; +const SETTING_MAX_FRAME_SIZE: u16 = 0x5; + +const DEFAULT_MAX_FRAME_SIZE: usize = 16_384; +const INITIAL_FRAME_CAP: usize = 64 << 10; +const MAX_FRAME_LIMIT: usize = 4 << 20; +const MAX_SOLVE_BODY: usize = 16 << 20; +const MAX_SOLVE_REQ_BYTES: usize = MAX_SOLVE_BODY; +const MAX_TOTAL_SOLVE_REQ_BYTES: usize = 32 << 20; +const MAX_CONCURRENT_SOLVE_STREAMS: usize = 16; +const MAX_CONTINUATION_FRAMES: usize = 32; +const MAX_HEADER_BLOCK: usize = 1 << 20; +const MAX_HPACK_TABLE_SIZE: usize = 1 << 20; +const MAX_DECODED_HEADERS: usize = 2 << 20; +const EXEC_STDIN_CHUNK: usize = 32 * 1024; + +const SOLVE_PATH: &str = "/moby.buildkit.v1.Control/Solve"; +const SESSION_PATH: &str = "/moby.buildkit.v1.Control/Session"; + +fn has_h2c_upgrade(req: &Request) -> bool { + req.header("Upgrade") + .is_some_and(|u| u.split(',').any(|t| t.trim().eq_ignore_ascii_case("h2c"))) +} + +/// `POST /grpc` (`Upgrade: h2c`): proxies BuildKit gRPC to Kiri's managed +/// BuildKit container via `buildctl dial-stdio`, rewriting `moby` exporter +/// solves into Kiri's store (or direct registry pushes when `push=true`). +pub fn grpc(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut BufReader) -> io::Result { + if !has_h2c_upgrade(req) { + api::error(w, Error::BadRequest("POST /grpc requires Upgrade: h2c".into()))?; + return Ok(Next::KeepAlive); + } + http::upgrade_h2c(w)?; + + // buildx's driver priority probe dials `/grpc`, checks for 101, and closes + // immediately without sending any HTTP/2 bytes: wait for the first byte + // before touching the builder so probes never wake or pull BuildKit. + let mut initial = r.buffer().to_vec(); + r.consume(initial.len()); + let mut client_r = r.get_ref().try_clone()?; + if initial.is_empty() { + api::wait_readable(&client_r); + let mut buf = [0u8; 4096]; + match client_r.read(&mut buf) { + Ok(0) | Err(_) => return Ok(Next::Close), + Ok(n) => initial.extend_from_slice(&buf[..n]), + } + } + + let (builder_id, _busy) = match builder::ensure_running(engine, &mut |_| {}) { + Ok(v) => v, + Err(e) => { + let _ = send_goaway(w, &format!("{e:?}")); + return Ok(Next::Close); + } + }; + let host_net = builder::builder_host_net(engine, &builder_id); + let argv = vec!["buildctl".to_owned(), "dial-stdio".to_owned()]; + let exec = match engine.exec_create(&builder_id, builder::internal_exec(&argv, true, Vec::new())) { + Ok(id) => id, + Err(e) => { + let _ = send_goaway(w, &format!("{e:?}")); + return Ok(Next::Close); + } + }; + let (_, rx) = match engine.exec_start(&exec) { + Ok(v) => v, + Err(e) => { + engine.forget_exec(&exec); + let _ = send_goaway(w, &format!("{e:?}")); + return Ok(Next::Close); + } + }; + + let client_reader = PrefixReader::new(initial, PollUnixReader(client_r.try_clone()?)); + let exec_reader = StdoutReader::new(rx); + let exec_writer = ExecStdinWriter { engine: engine.clone(), exec: exec.clone() }; + let _ = proxy_grpc( + client_reader, + w.try_clone()?, + exec_reader, + exec_writer, + engine, + host_net, + || { + let _ = engine.close_stdin(&exec); + }, + || { + let _ = engine.close_stdin(&exec); + let _ = client_r.shutdown(Shutdown::Both); + }, + ); + let _ = engine.close_stdin(&exec); + engine.forget_exec(&exec); + Ok(Next::Close) +} + +/// `POST /session` (`Upgrade: h2c`): bridges BuildKit's reverse h2c session +/// stream into `moby.buildkit.v1.Control/Session` (`BytesMessage`) on Kiri's +/// managed BuildKit container. +pub fn session(req: &Request, engine: &Arc, w: &mut UnixStream, r: &mut BufReader) -> io::Result { + if !has_h2c_upgrade(req) { + api::error(w, Error::BadRequest("POST /session requires Upgrade: h2c".into()))?; + return Ok(Next::KeepAlive); + } + let session_headers: Vec<(String, String)> = req + .headers() + .iter() + .filter(|(k, _)| k.to_ascii_lowercase().starts_with("x-docker-expose-session-")) + .map(|(k, v)| (k.to_ascii_lowercase(), v.clone())) + .collect(); + http::upgrade_h2c(w)?; + + let early = r.buffer().to_vec(); + r.consume(early.len()); + let client_r = r.get_ref().try_clone()?; + + let (builder_id, _busy) = match builder::ensure_running(engine, &mut |_| {}) { + Ok(v) => v, + Err(_) => return Ok(Next::Close), + }; + let argv = vec!["buildctl".to_owned(), "dial-stdio".to_owned()]; + let exec = match engine.exec_create(&builder_id, builder::internal_exec(&argv, true, Vec::new())) { + Ok(id) => id, + Err(_) => return Ok(Next::Close), + }; + let (_, rx) = match engine.exec_start(&exec) { + Ok(v) => v, + Err(_) => { + engine.forget_exec(&exec); + return Ok(Next::Close); + } + }; + + let client_reader = PrefixReader::new(early, PollUnixReader(client_r.try_clone()?)); + let exec_reader = StdoutReader::new(rx); + let exec_writer = ExecStdinWriter { engine: engine.clone(), exec: exec.clone() }; + let _ = bridge_session( + &session_headers, + client_reader, + w.try_clone()?, + exec_reader, + exec_writer, + || { + let _ = engine.close_stdin(&exec); + }, + || { + let _ = engine.close_stdin(&exec); + let _ = client_r.shutdown(Shutdown::Both); + }, + ); + let _ = engine.close_stdin(&exec); + engine.forget_exec(&exec); + Ok(Next::Close) +} + +// --- I/O adapters ------------------------------------------------------------ + +struct PollUnixReader(UnixStream); + +impl Read for PollUnixReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + api::wait_readable(&self.0); + self.0.read(buf) + } +} + +struct PrefixReader { + prefix: Vec, + pos: usize, + inner: R, +} + +impl PrefixReader { + fn new(prefix: Vec, inner: R) -> PrefixReader { + PrefixReader { prefix, pos: 0, inner } + } +} + +impl Read for PrefixReader { + fn read(&mut self, out: &mut [u8]) -> io::Result { + if self.pos < self.prefix.len() { + let n = out.len().min(self.prefix.len() - self.pos); + out[..n].copy_from_slice(&self.prefix[self.pos..self.pos + n]); + self.pos += n; + return Ok(n); + } + self.inner.read(out) + } +} + +struct StdoutReader { + rx: Receiver<(Stream, Vec)>, + buf: Vec, + pos: usize, +} + +impl StdoutReader { + fn new(rx: Receiver<(Stream, Vec)>) -> StdoutReader { + StdoutReader { rx, buf: Vec::new(), pos: 0 } + } +} + +impl Read for StdoutReader { + fn read(&mut self, out: &mut [u8]) -> io::Result { + while self.pos == self.buf.len() { + match self.rx.recv() { + Ok((Stream::Stdout, data)) if !data.is_empty() => { + self.buf = data; + self.pos = 0; + } + Ok((Stream::Stdout, _)) => {} + Ok((Stream::Stderr, data)) => { + let msg = String::from_utf8_lossy(&data); + let msg = msg.trim(); + if !msg.is_empty() { + crate::diag::debug!("buildctl dial-stdio stderr", text = msg); + } + } + Err(_) => return Ok(0), + } + } + let n = out.len().min(self.buf.len() - self.pos); + out[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]); + self.pos += n; + Ok(n) + } +} + +struct ExecStdinWriter { + engine: Arc, + exec: String, +} + +impl Write for ExecStdinWriter { + fn write(&mut self, buf: &[u8]) -> io::Result { + for chunk in buf.chunks(EXEC_STDIN_CHUNK) { + self.engine.input(&self.exec, chunk).map_err(|e| io::Error::new(io::ErrorKind::BrokenPipe, format!("{e:?}")))?; + } + Ok(buf.len()) + } + + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +// --- HTTP/2 framing ---------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Frame { + ty: u8, + flags: u8, + stream_id: u32, + payload: Vec, +} + +fn read_frame(r: &mut impl Read) -> io::Result> { + let mut head = [0u8; 9]; + let mut read = 0; + while read < head.len() { + match r.read(&mut head[read..])? { + 0 if read == 0 => return Ok(None), + 0 => return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "truncated HTTP/2 frame header")), + n => read += n, + } + } + let len = ((head[0] as usize) << 16) | ((head[1] as usize) << 8) | (head[2] as usize); + if len > MAX_FRAME_LIMIT { + return Err(io::Error::new(io::ErrorKind::InvalidData, "HTTP/2 frame exceeds limit")); + } + let ty = head[3]; + let flags = head[4]; + let stream_id = u32::from_be_bytes([head[5] & 0x7f, head[6], head[7], head[8]]); + let mut payload = Vec::with_capacity(len.min(INITIAL_FRAME_CAP)); + let got = r.take(len as u64).read_to_end(&mut payload)?; + if got != len { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "truncated HTTP/2 frame payload")); + } + Ok(Some(Frame { ty, flags, stream_id, payload })) +} + +fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { + let len = f.payload.len(); + if len > 0x00ff_ffff { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "HTTP/2 frame too large")); + } + let mut head = [0u8; 9]; + head[0] = ((len >> 16) & 0xff) as u8; + head[1] = ((len >> 8) & 0xff) as u8; + head[2] = (len & 0xff) as u8; + head[3] = f.ty; + head[4] = f.flags; + head[5..9].copy_from_slice(&(f.stream_id & 0x7fff_ffff).to_be_bytes()); + w.write_all(&head)?; + w.write_all(&f.payload)?; + w.flush() +} + +fn send_goaway(w: &mut impl Write, debug: &str) -> io::Result<()> { + let mut payload = Vec::with_capacity(8 + debug.len().min(256)); + payload.extend_from_slice(&0u32.to_be_bytes()); // last_stream_id = 0 + payload.extend_from_slice(&2u32.to_be_bytes()); // INTERNAL_ERROR + payload.extend_from_slice(&debug.as_bytes()[..debug.len().min(256)]); + write_frame(w, &Frame { ty: FRAME_GOAWAY, flags: 0, stream_id: 0, payload }) +} + +fn window_update_frame(stream_id: u32, inc: u32) -> Frame { + Frame { ty: FRAME_WINDOW_UPDATE, flags: 0, stream_id, payload: (inc & 0x7fff_ffff).to_be_bytes().to_vec() } +} + +fn unpad_data(flags: u8, payload: &[u8]) -> io::Result<&[u8]> { + if flags & FLAG_PADDED == 0 { + return Ok(payload); + } + if payload.is_empty() { + return Err(io::Error::new(io::ErrorKind::InvalidData, "empty padded DATA frame")); + } + let pad = payload[0] as usize; + if 1 + pad > payload.len() { + return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid DATA padding")); + } + Ok(&payload[1..payload.len() - pad]) +} + +fn headers_fragment(flags: u8, payload: &[u8]) -> io::Result<&[u8]> { + let mut start = 0; + let mut end = payload.len(); + if flags & FLAG_PADDED != 0 { + if payload.is_empty() { + return Err(io::Error::new(io::ErrorKind::InvalidData, "empty padded HEADERS frame")); + } + let pad = payload[0] as usize; + start += 1; + if start + pad > end { + return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid HEADERS padding")); + } + end -= pad; + } + if flags & FLAG_PRIORITY != 0 { + if start + 5 > end { + return Err(io::Error::new(io::ErrorKind::InvalidData, "truncated HEADERS priority")); + } + start += 5; + } + Ok(&payload[start..end]) +} + +// --- `/grpc` HTTP/2 proxy ---------------------------------------------------- + +struct SolveRewrite { + session: LoadSession, + orig_name: String, + resp_buf: Vec, + resp_rewritten: bool, +} + +struct GrpcShared { + solve_streams: HashMap>, + server_max_frame_size: usize, +} + +#[allow(clippy::too_many_arguments)] +fn proxy_grpc( + mut client_r: CR, + client_w: CW, + mut server_r: SR, + server_w: SW, + engine: &Arc, + host_net: bool, + on_client_done: impl Fn() + Send + Sync, + on_server_done: impl Fn() + Send + Sync, +) -> io::Result<()> +where + CR: Read + Send, + CW: Write + Send, + SR: Read + Send, + SW: Write + Send, +{ + let mut preface = [0u8; 24]; + client_r.read_exact(&mut preface)?; + if &preface != H2_PREFACE { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad HTTP/2 client preface")); + } + + let client_w = Mutex::new(client_w); + let server_w = Mutex::new(Some(server_w)); + { + let mut guard = server_w.lock().unwrap_or_else(|e| e.into_inner()); + let sw = guard.as_mut().unwrap(); + sw.write_all(&preface)?; + sw.flush()?; + } + let write_server_frame = |f: &Frame| -> io::Result<()> { + let mut guard = server_w.lock().unwrap_or_else(|e| e.into_inner()); + let sw = guard.as_mut().ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "server stdin closed"))?; + write_frame(sw, f) + }; + + let shared = Mutex::new(GrpcShared { + solve_streams: HashMap::new(), + server_max_frame_size: DEFAULT_MAX_FRAME_SIZE, + }); + + std::thread::scope(|scope| { + let c2s = scope.spawn(|| -> io::Result<()> { + let mut hpack = HpackDecoder::new(); + let mut header_stream: Option = None; + let mut header_end_stream = false; + let mut header_continuations = 0usize; + let mut header_block = Vec::new(); + let mut solve_req_bufs: HashMap, usize)> = HashMap::new(); + let mut total_solve_req_bytes = 0usize; + + let res = (|| -> io::Result<()> { + while let Some(frame) = read_frame(&mut client_r)? { + if header_stream.is_some() && frame.ty != FRAME_CONTINUATION { + return Err(io::Error::new(io::ErrorKind::InvalidData, "expected CONTINUATION frame")); + } + match frame.ty { + FRAME_HEADERS | FRAME_CONTINUATION => { + let frag = if frame.ty == FRAME_HEADERS { + header_stream = Some(frame.stream_id); + header_end_stream = frame.flags & FLAG_END_STREAM != 0; + header_continuations = 0; + header_block.clear(); + headers_fragment(frame.flags, &frame.payload)? + } else { + if header_stream != Some(frame.stream_id) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "unexpected CONTINUATION")); + } + header_continuations += 1; + if header_continuations > MAX_CONTINUATION_FRAMES { + return Err(io::Error::new(io::ErrorKind::InvalidData, "too many CONTINUATION frames")); + } + &frame.payload + }; + if header_block.len().saturating_add(frag.len()) > MAX_HEADER_BLOCK { + return Err(io::Error::new(io::ErrorKind::InvalidData, "HPACK header block too large")); + } + header_block.extend_from_slice(frag); + if frame.flags & FLAG_END_HEADERS != 0 { + let headers = hpack.decode(&header_block)?; + if header_end_stream { + if let Some((buf, _)) = solve_req_bufs.remove(&frame.stream_id) { + total_solve_req_bytes = total_solve_req_bytes.saturating_sub(buf.len()); + } + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&frame.stream_id); + } else if headers.iter().any(|(k, v)| k == b":path" && v == SOLVE_PATH.as_bytes()) { + let active_solves = shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.len(); + if !solve_req_bufs.contains_key(&frame.stream_id) + && (solve_req_bufs.len() >= MAX_CONCURRENT_SOLVE_STREAMS || active_solves >= MAX_CONCURRENT_SOLVE_STREAMS) + { + return Err(io::Error::new(io::ErrorKind::InvalidData, "too many concurrent Solve streams")); + } + if let Some((old_buf, _)) = solve_req_bufs.insert(frame.stream_id, (Vec::new(), 0)) { + total_solve_req_bytes = total_solve_req_bytes.saturating_sub(old_buf.len()); + } + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.insert(frame.stream_id, None); + } + header_stream = None; + header_end_stream = false; + header_continuations = 0; + header_block.clear(); + } + write_server_frame(&frame)?; + } + FRAME_DATA if solve_req_bufs.contains_key(&frame.stream_id) => { + let sid = frame.stream_id; + let wire_len = frame.payload.len(); + let unpadded = unpad_data(frame.flags, &frame.payload)?; + let (buf, credited) = solve_req_bufs.get_mut(&sid).unwrap(); + if buf.len().saturating_add(unpadded.len()) > MAX_SOLVE_REQ_BYTES + || total_solve_req_bytes.saturating_add(unpadded.len()) > MAX_TOTAL_SOLVE_REQ_BYTES + { + return Err(io::Error::new(io::ErrorKind::InvalidData, "SolveRequest exceeds limit")); + } + buf.extend_from_slice(unpadded); + total_solve_req_bytes += unpadded.len(); + let end_stream = frame.flags & FLAG_END_STREAM != 0; + if !end_stream { + // Keep client send window open while buffering a multi-frame SolveRequest. + if wire_len > 0 { + let inc = wire_len.min(0x7fff_ffff) as u32; + *credited = credited.saturating_add(inc as usize); + let mut cw = client_w.lock().unwrap_or_else(|e| e.into_inner()); + write_frame(&mut *cw, &window_update_frame(0, inc))?; + write_frame(&mut *cw, &window_update_frame(sid, inc))?; + } + continue; + } + let (raw_grpc, credited) = solve_req_bufs.remove(&sid).unwrap(); + total_solve_req_bytes = total_solve_req_bytes.saturating_sub(raw_grpc.len()); + let orig_len = raw_grpc.len(); + let (out_grpc, rewrite_state) = rewrite_grpc_solve_request(&raw_grpc, engine, host_net)?; + if let Some(rw) = rewrite_state { + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.insert(sid, Some(rw)); + } else { + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&sid); + } + let max_frame = shared.lock().unwrap_or_else(|e| e.into_inner()).server_max_frame_size; + { + let mut guard = server_w.lock().unwrap_or_else(|e| e.into_inner()); + let sw = guard.as_mut().ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "server stdin closed"))?; + write_data_frames(sw, sid, &out_grpc, max_frame, true)?; + } + // If rewriting shrank the payload beyond what was already + // credited on non-final frames, return the difference to the + // client's connection window so long-lived connections never drift. + let returned = out_grpc.len().saturating_add(credited); + if orig_len > returned { + let delta = (orig_len - returned).min(0x7fff_ffff) as u32; + write_frame(&mut *client_w.lock().unwrap_or_else(|e| e.into_inner()), &window_update_frame(0, delta))?; + } + } + FRAME_RST_STREAM => { + if let Some((buf, _)) = solve_req_bufs.remove(&frame.stream_id) { + total_solve_req_bytes = total_solve_req_bytes.saturating_sub(buf.len()); + } + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&frame.stream_id); + write_server_frame(&frame)?; + } + _ => { + write_server_frame(&frame)?; + } + } + } + Ok(()) + })(); + if let Err(ref e) = res { + let _ = send_goaway(&mut *client_w.lock().unwrap_or_else(|e| e.into_inner()), &e.to_string()); + } + let _ = server_w.lock().unwrap_or_else(|e| e.into_inner()).take(); + on_client_done(); + res + }); + + let s2c = scope.spawn(|| -> io::Result<()> { + let res = (|| -> io::Result<()> { + while let Some(frame) = read_frame(&mut server_r)? { + match frame.ty { + FRAME_SETTINGS if frame.flags & FLAG_ACK == 0 => { + for chunk in frame.payload.as_chunks::<6>().0 { + let id = u16::from_be_bytes([chunk[0], chunk[1]]); + let val = u32::from_be_bytes([chunk[2], chunk[3], chunk[4], chunk[5]]); + if id == SETTING_MAX_FRAME_SIZE && (DEFAULT_MAX_FRAME_SIZE..=0x00ff_ffff).contains(&(val as usize)) { + shared.lock().unwrap_or_else(|e| e.into_inner()).server_max_frame_size = (val as usize).min(MAX_FRAME_LIMIT); + } + } + write_frame(&mut *client_w.lock().unwrap_or_else(|e| e.into_inner()), &frame)?; + } + FRAME_DATA => { + let sid = frame.stream_id; + let end_stream = frame.flags & FLAG_END_STREAM != 0; + let action = { + let mut st = shared.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(rw)) = st.solve_streams.get_mut(&sid) { + if rw.resp_rewritten { + None + } else { + let data = unpad_data(frame.flags, &frame.payload)?; + if rw.resp_buf.len() + data.len() > MAX_SOLVE_BODY { + return Err(io::Error::new(io::ErrorKind::InvalidData, "SolveResponse exceeds limit")); + } + rw.resp_buf.extend_from_slice(data); + let ready = end_stream || grpc_frame_complete(&rw.resp_buf); + if ready { + rw.resp_rewritten = true; + let orig = std::mem::take(&mut rw.resp_buf); + let rewritten = rewrite_grpc_solve_response(&orig, &rw.orig_name, rw.session.committed_digest().as_deref())?; + Some(Some((orig.len(), rewritten, end_stream))) + } else { + Some(None) + } + } + } else { + None + } + }; + match action { + Some(None) => {} + Some(Some((orig_len, rewritten, end))) => { + { + let mut cw = client_w.lock().unwrap_or_else(|e| e.into_inner()); + write_data_frames(&mut *cw, sid, &rewritten, DEFAULT_MAX_FRAME_SIZE, end)?; + } + if orig_len > rewritten.len() { + let delta = (orig_len - rewritten.len()).min(0x7fff_ffff) as u32; + let _ = write_server_frame(&window_update_frame(0, delta)); + } + if end { + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&sid); + } + } + None => { + write_frame(&mut *client_w.lock().unwrap_or_else(|e| e.into_inner()), &frame)?; + } + } + } + FRAME_HEADERS if frame.flags & FLAG_END_STREAM != 0 => { + let sid = frame.stream_id; + let leftover = { + let mut st = shared.lock().unwrap_or_else(|e| e.into_inner()); + st.solve_streams + .remove(&sid) + .flatten() + .filter(|rw| !rw.resp_buf.is_empty()) + .map(|rw| rw.resp_buf) + }; + let mut cw = client_w.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(buf) = leftover { + write_data_frames(&mut *cw, sid, &buf, DEFAULT_MAX_FRAME_SIZE, false)?; + } + write_frame(&mut *cw, &frame)?; + } + FRAME_RST_STREAM => { + shared.lock().unwrap_or_else(|e| e.into_inner()).solve_streams.remove(&frame.stream_id); + write_frame(&mut *client_w.lock().unwrap_or_else(|e| e.into_inner()), &frame)?; + } + _ => { + write_frame(&mut *client_w.lock().unwrap_or_else(|e| e.into_inner()), &frame)?; + } + } + } + Ok(()) + })(); + let _ = server_w.lock().unwrap_or_else(|e| e.into_inner()).take(); + on_client_done(); + on_server_done(); + res + }); + + let r1 = c2s.join().unwrap_or(Ok(())); + let r2 = s2c.join().unwrap_or(Ok(())); + r1.and(r2) + }) +} + +fn write_data_frames(w: &mut impl Write, stream_id: u32, data: &[u8], max_frame: usize, end_stream: bool) -> io::Result<()> { + let chunk_size = max_frame.max(1); + if data.is_empty() { + return write_frame(w, &Frame { ty: FRAME_DATA, flags: if end_stream { FLAG_END_STREAM } else { 0 }, stream_id, payload: Vec::new() }); + } + let total = data.len(); + let mut off = 0; + while off < total { + let end = (off + chunk_size).min(total); + let flags = if end_stream && end == total { FLAG_END_STREAM } else { 0 }; + write_frame(w, &Frame { ty: FRAME_DATA, flags, stream_id, payload: data[off..end].to_vec() })?; + off = end; + } + Ok(()) +} + +fn grpc_frame_complete(buf: &[u8]) -> bool { + if buf.len() < 5 { + return false; + } + let msg_len = u32::from_be_bytes([buf[1], buf[2], buf[3], buf[4]]) as usize; + 5usize.checked_add(msg_len).is_some_and(|need| buf.len() >= need) +} + +// --- `/session` <-> `Control/Session` HTTP/2 bridge -------------------------- + +struct SessionFlow { + peer_conn_window: i64, + peer_stream_window: i64, + peer_initial_window: u32, + peer_max_frame_size: usize, + closed: bool, +} + +#[allow(clippy::too_many_arguments)] +fn bridge_session( + session_headers: &[(String, String)], + mut client_r: CR, + mut client_w: CW, + mut server_r: SR, + server_w: SW, + on_client_abort: impl Fn() + Send + Sync, + on_server_done: impl Fn() + Send + Sync, +) -> io::Result<()> +where + CR: Read + Send, + CW: Write + Send, + SR: Read + Send, + SW: Write + Send, +{ + const OUR_INITIAL_WINDOW: u32 = 1 << 20; + const OUR_CONN_WINDOW_INC: u32 = (4 << 20) - 65_535; + const WINDOW_REFILL_THRESHOLD: u32 = 32 * 1024; + + let server_w = Mutex::new(server_w); + { + let mut sw = server_w.lock().unwrap_or_else(|e| e.into_inner()); + sw.write_all(H2_PREFACE)?; + // Client SETTINGS: raise initial stream window to 1 MiB. + let mut settings = Vec::with_capacity(6); + settings.extend_from_slice(&SETTING_INITIAL_WINDOW_SIZE.to_be_bytes()); + settings.extend_from_slice(&OUR_INITIAL_WINDOW.to_be_bytes()); + write_frame(&mut *sw, &Frame { ty: FRAME_SETTINGS, flags: 0, stream_id: 0, payload: settings })?; + write_frame(&mut *sw, &window_update_frame(0, OUR_CONN_WINDOW_INC))?; + + // Open stream 1: POST /moby.buildkit.v1.Control/Session + let mut hdrs: Vec<(&str, &str)> = vec![ + (":method", "POST"), + (":scheme", "http"), + (":path", SESSION_PATH), + (":authority", "localhost"), + ("content-type", "application/grpc"), + ("te", "trailers"), + ]; + for (k, v) in session_headers { + hdrs.push((k.as_str(), v.as_str())); + } + let block = hpack_encode_literal(&hdrs); + let mut off = 0; + let mut first = true; + while off < block.len() || first { + let end = (off + DEFAULT_MAX_FRAME_SIZE).min(block.len()); + let mut flags = 0; + if end == block.len() { + flags |= FLAG_END_HEADERS; + } + let ty = if first { FRAME_HEADERS } else { FRAME_CONTINUATION }; + write_frame(&mut *sw, &Frame { ty, flags, stream_id: 1, payload: block[off..end].to_vec() })?; + off = end; + first = false; + } + } + + let flow = ( + Mutex::new(SessionFlow { + peer_conn_window: 65_535, + peer_stream_window: 65_535, + peer_initial_window: 65_535, + peer_max_frame_size: DEFAULT_MAX_FRAME_SIZE, + closed: false, + }), + Condvar::new(), + ); + + std::thread::scope(|scope| { + // Client raw h2c bytes -> stream 1 gRPC BytesMessage DATA frames. + let c2s = scope.spawn(|| -> io::Result<()> { + let mut buf = vec![0u8; 16 * 1024]; + let res = (|| -> io::Result<()> { + loop { + let n = client_r.read(&mut buf)?; + if n == 0 { + let mut sw = server_w.lock().unwrap_or_else(|e| e.into_inner()); + let _ = write_frame(&mut *sw, &Frame { ty: FRAME_DATA, flags: FLAG_END_STREAM, stream_id: 1, payload: Vec::new() }); + break; + } + let grpc_msg = wrap_grpc_message(&encode_bytes_message(&buf[..n])); + let mut off = 0; + while off < grpc_msg.len() { + let allowed = { + let (mu, cv) = &flow; + let mut st = mu.lock().unwrap_or_else(|e| e.into_inner()); + while !st.closed && (st.peer_conn_window <= 0 || st.peer_stream_window <= 0) { + st = cv.wait(st).unwrap_or_else(|e| e.into_inner()); + } + if st.closed { + return Ok(()); + } + let avail = st.peer_conn_window.min(st.peer_stream_window) as usize; + let take = (grpc_msg.len() - off).min(st.peer_max_frame_size).min(avail).max(1); + st.peer_conn_window -= take as i64; + st.peer_stream_window -= take as i64; + take + }; + let mut sw = server_w.lock().unwrap_or_else(|e| e.into_inner()); + write_frame(&mut *sw, &Frame { ty: FRAME_DATA, flags: 0, stream_id: 1, payload: grpc_msg[off..off + allowed].to_vec() })?; + off += allowed; + } + } + Ok(()) + })(); + if res.is_err() { + // Cancel stream 1 and close the exec stdin so `s2c` never blocks + // waiting for BuildKit after an abrupt client disconnect. + let _ = write_frame( + &mut *server_w.lock().unwrap_or_else(|e| e.into_inner()), + &Frame { ty: FRAME_RST_STREAM, flags: 0, stream_id: 1, payload: 8u32.to_be_bytes().to_vec() }, + ); + on_client_abort(); + } + res + }); + + // Stream 1 gRPC BytesMessage DATA frames -> client raw h2c bytes. + let s2c = scope.spawn(|| -> io::Result<()> { + let mut deframer = Vec::new(); + let mut unacked: u32 = 0; + let res = (|| -> io::Result<()> { + while let Some(frame) = read_frame(&mut server_r)? { + match frame.ty { + FRAME_SETTINGS if frame.flags & FLAG_ACK == 0 => { + { + let (mu, cv) = &flow; + let mut st = mu.lock().unwrap_or_else(|e| e.into_inner()); + for chunk in frame.payload.as_chunks::<6>().0 { + let id = u16::from_be_bytes([chunk[0], chunk[1]]); + let val = u32::from_be_bytes([chunk[2], chunk[3], chunk[4], chunk[5]]); + match id { + SETTING_INITIAL_WINDOW_SIZE => { + let delta = val as i64 - st.peer_initial_window as i64; + st.peer_initial_window = val; + st.peer_stream_window += delta; + cv.notify_all(); + } + SETTING_MAX_FRAME_SIZE if (DEFAULT_MAX_FRAME_SIZE..=0x00ff_ffff).contains(&(val as usize)) => { + st.peer_max_frame_size = (val as usize).min(MAX_FRAME_LIMIT); + } + _ => {} + } + } + } + let mut sw = server_w.lock().unwrap_or_else(|e| e.into_inner()); + write_frame(&mut *sw, &Frame { ty: FRAME_SETTINGS, flags: FLAG_ACK, stream_id: 0, payload: Vec::new() })?; + } + FRAME_PING if frame.flags & FLAG_ACK == 0 && frame.payload.len() == 8 => { + let mut sw = server_w.lock().unwrap_or_else(|e| e.into_inner()); + write_frame(&mut *sw, &Frame { ty: FRAME_PING, flags: FLAG_ACK, stream_id: 0, payload: frame.payload })?; + } + FRAME_WINDOW_UPDATE if frame.payload.len() == 4 => { + let inc = (u32::from_be_bytes([frame.payload[0], frame.payload[1], frame.payload[2], frame.payload[3]]) & 0x7fff_ffff) as i64; + let (mu, cv) = &flow; + let mut st = mu.lock().unwrap_or_else(|e| e.into_inner()); + if frame.stream_id == 0 { + st.peer_conn_window += inc; + cv.notify_all(); + } else if frame.stream_id == 1 { + st.peer_stream_window += inc; + cv.notify_all(); + } + } + FRAME_DATA if frame.stream_id == 1 => { + let wire_len = frame.payload.len() as u32; + unacked = unacked.saturating_add(wire_len); + if unacked >= WINDOW_REFILL_THRESHOLD { + let inc = unacked.min(0x7fff_ffff); + unacked -= inc; + let mut sw = server_w.lock().unwrap_or_else(|e| e.into_inner()); + write_frame(&mut *sw, &window_update_frame(0, inc))?; + write_frame(&mut *sw, &window_update_frame(1, inc))?; + } + let data = unpad_data(frame.flags, &frame.payload)?; + if deframer.len().saturating_add(data.len()) > MAX_FRAME_LIMIT + 65_536 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "session deframer buffer exceeded")); + } + deframer.extend_from_slice(data); + while deframer.len() >= 5 { + let compressed = deframer[0]; + if compressed != 0 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "compressed session gRPC message unsupported")); + } + let msg_len = u32::from_be_bytes([deframer[1], deframer[2], deframer[3], deframer[4]]) as usize; + if msg_len > MAX_FRAME_LIMIT { + return Err(io::Error::new(io::ErrorKind::InvalidData, "session gRPC message too large")); + } + let Some(total) = 5usize.checked_add(msg_len) else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "session gRPC message length overflow")); + }; + if deframer.len() < total { + break; + } + let raw = decode_bytes_message(&deframer[5..total])?; + deframer.drain(..total); + if !raw.is_empty() { + client_w.write_all(&raw)?; + client_w.flush()?; + } + } + if frame.flags & FLAG_END_STREAM != 0 { + break; + } + } + FRAME_HEADERS if frame.stream_id == 1 && frame.flags & FLAG_END_STREAM != 0 => break, + FRAME_RST_STREAM if frame.stream_id == 1 => break, + FRAME_GOAWAY => break, + _ => {} + } + } + Ok(()) + })(); + { + let (mu, cv) = &flow; + mu.lock().unwrap_or_else(|e| e.into_inner()).closed = true; + cv.notify_all(); + } + on_server_done(); + res + }); + + let r1 = c2s.join().unwrap_or(Ok(())); + let r2 = s2c.join().unwrap_or(Ok(())); + r1.and(r2) + }) +} + +// --- SolveRequest / SolveResponse protobuf rewriting ------------------------- + +fn wrap_grpc_message(msg: &[u8]) -> Vec { + wrap_grpc_frame(0, msg) +} + +fn wrap_grpc_frame(flag: u8, msg: &[u8]) -> Vec { + let mut out = Vec::with_capacity(5 + msg.len()); + out.push(flag); + out.extend_from_slice(&(msg.len() as u32).to_be_bytes()); + out.extend_from_slice(msg); + out +} + +fn rewrite_grpc_solve_request(raw_grpc: &[u8], engine: &Arc, host_net: bool) -> io::Result<(Vec, Option)> { + if raw_grpc.len() < 5 || raw_grpc[0] > 1 { + return Ok((raw_grpc.to_vec(), None)); + } + let flag = raw_grpc[0]; + let msg_len = u32::from_be_bytes([raw_grpc[1], raw_grpc[2], raw_grpc[3], raw_grpc[4]]) as usize; + if 5usize.checked_add(msg_len) != Some(raw_grpc.len()) { + return Ok((raw_grpc.to_vec(), None)); + } + let payload = if flag == 1 { + let mut decoded = Vec::new(); + flate2::read::GzDecoder::new(&raw_grpc[5..]) + .take((MAX_SOLVE_REQ_BYTES + 1) as u64) + .read_to_end(&mut decoded)?; + if decoded.len() > MAX_SOLVE_REQ_BYTES { + return Err(io::Error::new(io::ErrorKind::InvalidData, "decompressed SolveRequest exceeds limit")); + } + decoded + } else { + raw_grpc[5..].to_vec() + }; + let (rewritten, state) = rewrite_solve_request(&payload, engine, host_net)?; + let out = if flag == 1 { + let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + enc.write_all(&rewritten)?; + wrap_grpc_frame(1, &enc.finish()?) + } else { + wrap_grpc_message(&rewritten) + }; + Ok((out, state)) +} + +fn rewrite_grpc_solve_response(raw_grpc: &[u8], orig_name: &str, committed_digest: Option<&str>) -> io::Result> { + if raw_grpc.len() < 5 || raw_grpc[0] > 1 { + return Ok(raw_grpc.to_vec()); + } + let flag = raw_grpc[0]; + let msg_len = u32::from_be_bytes([raw_grpc[1], raw_grpc[2], raw_grpc[3], raw_grpc[4]]) as usize; + let Some(end) = 5usize.checked_add(msg_len).filter(|e| *e <= raw_grpc.len()) else { + return Ok(raw_grpc.to_vec()); + }; + let payload = if flag == 1 { + let mut decoded = Vec::new(); + flate2::read::GzDecoder::new(&raw_grpc[5..end]) + .take((MAX_SOLVE_REQ_BYTES + 1) as u64) + .read_to_end(&mut decoded)?; + if decoded.len() > MAX_SOLVE_REQ_BYTES { + return Err(io::Error::new(io::ErrorKind::InvalidData, "decompressed SolveResponse exceeds limit")); + } + decoded + } else { + raw_grpc[5..end].to_vec() + }; + let rewritten = rewrite_solve_response(&payload, orig_name, committed_digest)?; + let mut out = if flag == 1 { + let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + enc.write_all(&rewritten)?; + wrap_grpc_frame(1, &enc.finish()?) + } else { + wrap_grpc_message(&rewritten) + }; + out.extend_from_slice(&raw_grpc[end..]); + Ok(out) +} + +fn parse_go_bool(s: &str) -> bool { + matches!(s, "1" | "t" | "T" | "TRUE" | "true" | "True") +} + +/// Parses `name` from a `moby` exporter attribute (`a:1,b:2`) into Kiri's short +/// normalized image references. +fn parse_export_tags(name: &str) -> io::Result> { + let mut tags = Vec::new(); + let mut seen = HashSet::new(); + for part in name.split(',').map(str::trim).filter(|s| !s.is_empty()) { + let r = Reference::parse(part).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("invalid image name {part:?}: {e}")))?; + if r.is_digest() { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("invalid image tag {part:?}: digest reference"))); + } + let short = r.short(); + if seen.insert(short.clone()) { + tags.push(short); + } + } + Ok(tags) +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct ExporterSpec { + ty: String, + attrs: Vec<(String, String)>, +} + +fn rewrite_exporter( + mut exp: ExporterSpec, + engine: &Arc, + host_net: bool, + load_state: &mut Option, +) -> io::Result { + if exp.ty != "moby" { + return Ok(exp); + } + let push = exp.attrs.iter().rev().find(|(k, _)| k == "push").is_some_and(|(_, v)| parse_go_bool(v)); + if push { + exp.ty = "image".to_owned(); + exp.attrs.retain(|(k, _)| !matches!(k.as_str(), "unpack" | "dangling-name-prefix" | "name-canonical" | "store")); + return Ok(exp); + } + let orig_name = exp.attrs.iter().rev().find(|(k, _)| k == "name").map(|(_, v)| v.clone()).unwrap_or_default(); + let target_tags = parse_export_tags(&orig_name)?; + let endpoint = mirror::upload_endpoint(engine, host_net) + .ok_or_else(|| io::Error::other("Kiri's build image mirror is not running"))?; + let mirror_ref = if let Some(existing) = load_state.as_mut() { + existing.session.add_tags(target_tags); + if !orig_name.is_empty() { + if existing.orig_name.is_empty() { + existing.orig_name = orig_name; + } else if !existing.orig_name.split(',').any(|p| p == orig_name) { + existing.orig_name.push(','); + existing.orig_name.push_str(&orig_name); + } + } + existing.session.repo_ref(&endpoint) + } else { + let session = LoadSession::new(engine.clone(), target_tags); + let r = session.repo_ref(&endpoint); + *load_state = Some(SolveRewrite { session, orig_name, resp_buf: Vec::new(), resp_rewritten: false }); + r + }; + exp.ty = "image".to_owned(); + exp.attrs.retain(|(k, _)| { + !matches!( + k.as_str(), + "name" | "push" | "registry.insecure" | "unpack" | "push-by-digest" | "dangling-name-prefix" | "name-canonical" | "store" + ) + }); + exp.attrs.push(("name".to_owned(), mirror_ref)); + exp.attrs.push(("push".to_owned(), "true".to_owned())); + Ok(exp) +} + +/// Rewrites `moby` exporters inside a protobuf-encoded `SolveRequest`, keeping +/// every other field byte-for-byte untouched. +fn rewrite_solve_request(msg: &[u8], engine: &Arc, host_net: bool) -> io::Result<(Vec, Option)> { + let fields = pb_split_fields(msg)?; + let mut has_exporters = false; + let mut has_moby = false; + let mut dep_type = String::new(); + let mut dep_attrs: Vec<(String, String)> = Vec::new(); + let mut exporters: Vec = Vec::new(); + + for f in &fields { + match (f.num, f.wire) { + (3, 2) => { + dep_type = String::from_utf8_lossy(f.val).into_owned(); + if dep_type == "moby" { + has_moby = true; + } + } + (4, 2) => { + dep_attrs.push(pb_decode_map_entry(f.val)?); + } + (13, 2) => { + has_exporters = true; + let exp = pb_decode_exporter(f.val)?; + if exp.ty == "moby" { + has_moby = true; + } + exporters.push(exp); + } + _ => {} + } + } + if !has_moby { + return Ok((msg.to_vec(), None)); + } + + let mut load_state: Option = None; + let mut new_exporters = Vec::with_capacity(exporters.len()); + for exp in exporters { + new_exporters.push(rewrite_exporter(exp, engine, host_net, &mut load_state)?); + } + let new_dep = if !dep_type.is_empty() { + if has_exporters { + new_exporters.first().cloned() + } else { + Some(rewrite_exporter(ExporterSpec { ty: dep_type, attrs: dep_attrs }, engine, host_net, &mut load_state)?) + } + } else { + None + }; + + let mut out = Vec::with_capacity(msg.len() + 128); + for f in &fields { + if matches!(f.num, 3 | 4 | 13) { + continue; + } + out.extend_from_slice(f.raw); + } + if let Some(dep) = &new_dep { + pb_write_string(&mut out, 3, &dep.ty); + for (k, v) in &dep.attrs { + pb_write_map_entry(&mut out, 4, k, v); + } + } + for exp in &new_exporters { + let encoded = pb_encode_exporter(exp); + pb_write_bytes(&mut out, 13, &encoded); + } + Ok((out, load_state)) +} + +/// Rewrites `SolveResponse.ExporterResponse` so `image.name` names the target +/// tag(s) (never the internal mirror URL) and `containerimage.digest` carries +/// the stored image's ID (`config_digest`). +fn rewrite_solve_response(msg: &[u8], orig_name: &str, committed_digest: Option<&str>) -> io::Result> { + let fields = pb_split_fields(msg)?; + let mut out = Vec::with_capacity(msg.len() + 64); + let mut saw_digest = false; + let mut saw_name = false; + for f in &fields { + if f.num == 1 && f.wire == 2 { + let (k, v) = pb_decode_map_entry(f.val)?; + if k == "image.name" { + saw_name = true; + if !orig_name.is_empty() { + pb_write_map_entry(&mut out, 1, &k, orig_name); + } + } else if k == "containerimage.digest" { + saw_digest = true; + let digest = committed_digest.unwrap_or(&v); + pb_write_map_entry(&mut out, 1, &k, digest); + } else { + pb_write_map_entry(&mut out, 1, &k, &v); + } + } else { + out.extend_from_slice(f.raw); + } + } + if !saw_name && !orig_name.is_empty() { + pb_write_map_entry(&mut out, 1, "image.name", orig_name); + } + if !saw_digest && let Some(digest) = committed_digest { + pb_write_map_entry(&mut out, 1, "containerimage.digest", digest); + } + Ok(out) +} + +// --- Minimal protobuf wire helpers ------------------------------------------- + +struct RawField<'a> { + num: u32, + wire: u8, + raw: &'a [u8], + val: &'a [u8], +} + +fn pb_read_varint(buf: &[u8], pos: &mut usize) -> io::Result { + let mut val = 0u64; + let mut shift = 0u32; + loop { + let &b = buf.get(*pos).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated protobuf varint"))?; + *pos += 1; + val |= u64::from(b & 0x7f) << shift; + if b & 0x80 == 0 { + return Ok(val); + } + shift += 7; + if shift >= 64 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "protobuf varint overflow")); + } + } +} + +fn pb_write_varint(out: &mut Vec, mut v: u64) { + loop { + let mut b = (v & 0x7f) as u8; + v >>= 7; + if v != 0 { + b |= 0x80; + } + out.push(b); + if v == 0 { + break; + } + } +} + +fn pb_split_fields(buf: &[u8]) -> io::Result>> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < buf.len() { + let start = pos; + let tag = pb_read_varint(buf, &mut pos)?; + let num = (tag >> 3) as u32; + let wire = (tag & 7) as u8; + if num == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid protobuf field 0")); + } + let val = match wire { + 0 => { + let s = pos; + let _ = pb_read_varint(buf, &mut pos)?; + &buf[s..pos] + } + 1 => { + let end = pos.checked_add(8).filter(|e| *e <= buf.len()).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated fixed64"))?; + let v = &buf[pos..end]; + pos = end; + v + } + 2 => { + let len = pb_read_varint(buf, &mut pos)? as usize; + let end = pos.checked_add(len).filter(|e| *e <= buf.len()).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated length-delimited field"))?; + let v = &buf[pos..end]; + pos = end; + v + } + 5 => { + let end = pos.checked_add(4).filter(|e| *e <= buf.len()).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated fixed32"))?; + let v = &buf[pos..end]; + pos = end; + v + } + _ => return Err(io::Error::new(io::ErrorKind::InvalidData, format!("unsupported protobuf wire type {wire}"))), + }; + out.push(RawField { num, wire, raw: &buf[start..pos], val }); + } + Ok(out) +} + +fn pb_write_bytes(out: &mut Vec, field: u32, data: &[u8]) { + pb_write_varint(out, (u64::from(field) << 3) | 2); + pb_write_varint(out, data.len() as u64); + out.extend_from_slice(data); +} + +fn pb_write_string(out: &mut Vec, field: u32, s: &str) { + if !s.is_empty() { + pb_write_bytes(out, field, s.as_bytes()); + } +} + +fn pb_write_map_entry(out: &mut Vec, field: u32, k: &str, v: &str) { + let mut entry = Vec::with_capacity(k.len() + v.len() + 8); + pb_write_string(&mut entry, 1, k); + pb_write_string(&mut entry, 2, v); + pb_write_bytes(out, field, &entry); +} + +fn pb_decode_map_entry(buf: &[u8]) -> io::Result<(String, String)> { + let mut k = String::new(); + let mut v = String::new(); + for f in pb_split_fields(buf)? { + match (f.num, f.wire) { + (1, 2) => k = String::from_utf8_lossy(f.val).into_owned(), + (2, 2) => v = String::from_utf8_lossy(f.val).into_owned(), + _ => {} + } + } + Ok((k, v)) +} + +fn pb_decode_exporter(buf: &[u8]) -> io::Result { + let mut ty = String::new(); + let mut attrs = Vec::new(); + for f in pb_split_fields(buf)? { + match (f.num, f.wire) { + (1, 2) => ty = String::from_utf8_lossy(f.val).into_owned(), + (2, 2) => attrs.push(pb_decode_map_entry(f.val)?), + _ => {} + } + } + Ok(ExporterSpec { ty, attrs }) +} + +fn pb_encode_exporter(exp: &ExporterSpec) -> Vec { + let mut out = Vec::new(); + pb_write_string(&mut out, 1, &exp.ty); + for (k, v) in &exp.attrs { + pb_write_map_entry(&mut out, 2, k, v); + } + out +} + +fn encode_bytes_message(data: &[u8]) -> Vec { + let mut out = Vec::with_capacity(data.len() + 8); + if !data.is_empty() { + pb_write_bytes(&mut out, 1, data); + } + out +} + +fn decode_bytes_message(buf: &[u8]) -> io::Result> { + let mut out = Vec::new(); + for f in pb_split_fields(buf)? { + if f.num == 1 && f.wire == 2 { + out.extend_from_slice(f.val); + } + } + Ok(out) +} + +// --- RFC 7541 HPACK encoder (literal) & passive decoder ---------------------- + +fn hpack_encode_int(out: &mut Vec, prefix_bits: u8, first_mask: u8, value: usize) { + let max_prefix = (1usize << prefix_bits) - 1; + if value < max_prefix { + out.push(first_mask | (value as u8)); + return; + } + out.push(first_mask | (max_prefix as u8)); + let mut rem = value - max_prefix; + while rem >= 128 { + out.push(((rem & 0x7f) as u8) | 0x80); + rem >>= 7; + } + out.push(rem as u8); +} + +fn hpack_encode_literal(headers: &[(&str, &str)]) -> Vec { + let mut out = Vec::new(); + for &(k, v) in headers { + // Literal Header Field without Indexing — New Name (RFC 7541 §6.2.2). + out.push(0x00); + hpack_encode_int(&mut out, 7, 0x00, k.len()); + out.extend_from_slice(k.as_bytes()); + hpack_encode_int(&mut out, 7, 0x00, v.len()); + out.extend_from_slice(v.as_bytes()); + } + out +} + +const STATIC_TABLE: [(&str, &str); 61] = [ + (":authority", ""), + (":method", "GET"), + (":method", "POST"), + (":path", "/"), + (":path", "/index.html"), + (":scheme", "http"), + (":scheme", "https"), + (":status", "200"), + (":status", "204"), + (":status", "206"), + (":status", "304"), + (":status", "400"), + (":status", "404"), + (":status", "500"), + ("accept-charset", ""), + ("accept-encoding", "gzip, deflate"), + ("accept-language", ""), + ("accept-ranges", ""), + ("accept", ""), + ("access-control-allow-origin", ""), + ("age", ""), + ("allow", ""), + ("authorization", ""), + ("cache-control", ""), + ("content-disposition", ""), + ("content-encoding", ""), + ("content-language", ""), + ("content-length", ""), + ("content-location", ""), + ("content-range", ""), + ("content-type", ""), + ("cookie", ""), + ("date", ""), + ("etag", ""), + ("expect", ""), + ("expires", ""), + ("from", ""), + ("host", ""), + ("if-match", ""), + ("if-modified-since", ""), + ("if-none-match", ""), + ("if-range", ""), + ("if-unmodified-since", ""), + ("last-modified", ""), + ("link", ""), + ("location", ""), + ("max-forwards", ""), + ("proxy-authenticate", ""), + ("proxy-authorization", ""), + ("range", ""), + ("referer", ""), + ("refresh", ""), + ("retry-after", ""), + ("server", ""), + ("set-cookie", ""), + ("strict-transport-security", ""), + ("transfer-encoding", ""), + ("user-agent", ""), + ("vary", ""), + ("via", ""), + ("www-authenticate", ""), +]; + +/// RFC 7541 Appendix B canonical Huffman code bit lengths (symbols 0..=255). +const HUFFMAN_LEN: [u8; 256] = [ + 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, + 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, + 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, + 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, + 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, + 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, + 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, + 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, + 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, + 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, + 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, + 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, + 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, + 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26, +]; + +#[derive(Clone, Copy)] +struct HuffNode { + child: [u16; 2], + sym: Option, +} + +fn huffman_trie() -> &'static [HuffNode] { + static TRIE: OnceLock> = OnceLock::new(); + TRIE.get_or_init(|| { + let mut syms: Vec<(u8, u8)> = HUFFMAN_LEN.iter().enumerate().map(|(s, &len)| (len, s as u8)).collect(); + syms.sort_unstable(); + let mut nodes = vec![HuffNode { child: [0, 0], sym: None }]; + let mut code = 0u32; + let mut prev_len = 0u8; + for (len, sym) in syms { + if prev_len != 0 { + code = (code + 1) << (len - prev_len); + } + prev_len = len; + let mut cur = 0usize; + for bit_i in (0..len).rev() { + let bit = ((code >> bit_i) & 1) as usize; + let next = nodes[cur].child[bit] as usize; + if next == 0 { + let id = nodes.len() as u16; + nodes.push(HuffNode { child: [0, 0], sym: None }); + nodes[cur].child[bit] = id; + cur = id as usize; + } else { + cur = next; + } + } + nodes[cur].sym = Some(sym); + } + nodes + }) +} + +fn huffman_decode(src: &[u8]) -> io::Result> { + let trie = huffman_trie(); + let mut out = Vec::with_capacity(src.len().min(INITIAL_FRAME_CAP)); + let mut cur = 0usize; + let mut pending_bits = 0u8; + let mut all_ones = true; + for &byte in src { + for bit_i in (0..8).rev() { + let bit = ((byte >> bit_i) & 1) as usize; + let next = trie[cur].child[bit] as usize; + if next == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid HPACK Huffman code")); + } + cur = next; + pending_bits += 1; + all_ones &= bit == 1; + if let Some(sym) = trie[cur].sym { + if out.len() >= MAX_DECODED_HEADERS { + return Err(io::Error::new(io::ErrorKind::InvalidData, "HPACK Huffman string too large")); + } + out.push(sym); + cur = 0; + pending_bits = 0; + all_ones = true; + } + } + } + if cur != 0 && (pending_bits > 7 || !all_ones) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "invalid HPACK Huffman padding")); + } + Ok(out) +} + +struct HpackDecoder { + dynamic: VecDeque<(Vec, Vec)>, + size: usize, + max_size: usize, +} + +impl HpackDecoder { + fn new() -> HpackDecoder { + HpackDecoder { dynamic: VecDeque::new(), size: 0, max_size: 4096 } + } + + fn set_max_size(&mut self, max_size: usize) -> io::Result<()> { + if max_size > MAX_HPACK_TABLE_SIZE { + return Err(io::Error::new(io::ErrorKind::InvalidData, "HPACK dynamic table size exceeds limit")); + } + self.max_size = max_size; + while self.size > self.max_size { + if let Some((k, v)) = self.dynamic.pop_back() { + self.size = self.size.saturating_sub(k.len() + v.len() + 32); + } else { + break; + } + } + Ok(()) + } + + fn insert(&mut self, name: Vec, value: Vec) { + let entry_size = name.len().saturating_add(value.len()).saturating_add(32); + if entry_size > self.max_size { + self.dynamic.clear(); + self.size = 0; + return; + } + while self.size + entry_size > self.max_size { + if let Some((k, v)) = self.dynamic.pop_back() { + self.size = self.size.saturating_sub(k.len() + v.len() + 32); + } else { + break; + } + } + self.size += entry_size; + self.dynamic.push_front((name, value)); + } + + fn lookup(&self, idx: usize) -> io::Result<(Vec, Vec)> { + if idx == 0 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "HPACK index 0")); + } + if idx <= STATIC_TABLE.len() { + let (k, v) = STATIC_TABLE[idx - 1]; + return Ok((k.as_bytes().to_vec(), v.as_bytes().to_vec())); + } + let dyn_idx = idx - STATIC_TABLE.len() - 1; + self.dynamic + .get(dyn_idx) + .cloned() + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("HPACK index {idx} out of range"))) + } + + fn decode(&mut self, block: &[u8]) -> io::Result, Vec)>> { + let mut pos = 0; + let mut out = Vec::new(); + let mut decoded_bytes = 0usize; + let mut push = |out: &mut Vec<(Vec, Vec)>, k: Vec, v: Vec| -> io::Result<()> { + decoded_bytes = decoded_bytes.saturating_add(k.len()).saturating_add(v.len()).saturating_add(32); + if decoded_bytes > MAX_DECODED_HEADERS { + return Err(io::Error::new(io::ErrorKind::InvalidData, "decoded HPACK headers exceed limit")); + } + out.push((k, v)); + Ok(()) + }; + while pos < block.len() { + let b = block[pos]; + if b & 0x80 != 0 { + let idx = decode_int(block, &mut pos, 7)?; + let (k, v) = self.lookup(idx)?; + push(&mut out, k, v)?; + } else if b & 0xc0 == 0x40 { + let idx = decode_int(block, &mut pos, 6)?; + let name = if idx == 0 { decode_str(block, &mut pos)? } else { self.lookup(idx)?.0 }; + let val = decode_str(block, &mut pos)?; + self.insert(name.clone(), val.clone()); + push(&mut out, name, val)?; + } else if b & 0xe0 == 0x20 { + let new_max = decode_int(block, &mut pos, 5)?; + self.set_max_size(new_max)?; + } else { + let idx = decode_int(block, &mut pos, 4)?; + let name = if idx == 0 { decode_str(block, &mut pos)? } else { self.lookup(idx)?.0 }; + let val = decode_str(block, &mut pos)?; + push(&mut out, name, val)?; + } + } + Ok(out) + } +} + +fn decode_int(buf: &[u8], pos: &mut usize, prefix_bits: u8) -> io::Result { + let &first = buf.get(*pos).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated HPACK int"))?; + *pos += 1; + let mask = (1u8 << prefix_bits) - 1; + let mut val = usize::from(first & mask); + if val < usize::from(mask) { + return Ok(val); + } + let mut shift = 0u32; + loop { + let &b = buf.get(*pos).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated HPACK int"))?; + *pos += 1; + let add = usize::from(b & 0x7f) + .checked_shl(shift) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "HPACK int overflow"))?; + val = val.checked_add(add).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "HPACK int overflow"))?; + if b & 0x80 == 0 { + return Ok(val); + } + shift += 7; + if shift >= usize::BITS { + return Err(io::Error::new(io::ErrorKind::InvalidData, "HPACK int overflow")); + } + } +} + +fn decode_str(buf: &[u8], pos: &mut usize) -> io::Result> { + let &first = buf.get(*pos).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated HPACK string"))?; + let huffman = first & 0x80 != 0; + let len = decode_int(buf, pos, 7)?; + let end = pos.checked_add(len).filter(|e| *e <= buf.len()).ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "truncated HPACK string bytes"))?; + let raw = &buf[*pos..end]; + *pos = end; + if huffman { huffman_decode(raw) } else { Ok(raw.to_vec()) } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + fn test_engine(tag: &str) -> (Arc, std::path::PathBuf) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("kiri-grpc-{tag}-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let engine = Engine::boot(store).unwrap(); + mirror::start(&engine); + (engine, dir) + } + + #[test] + fn hpack_decodes_rfc7541_huffman_and_dynamic_table() { + // RFC 7541 Appendix C.4.1: Huffman-encoded `:authority: www.example.com`, + // indexed `:method: GET`, `:scheme: http`, `:path: /`. + let block1: &[u8] = &[ + 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, + ]; + let mut dec = HpackDecoder::new(); + let h1 = dec.decode(block1).unwrap(); + assert_eq!( + h1, + vec![ + (b":method".to_vec(), b"GET".to_vec()), + (b":scheme".to_vec(), b"http".to_vec()), + (b":path".to_vec(), b"/".to_vec()), + (b":authority".to_vec(), b"www.example.com".to_vec()), + ] + ); + // RFC 7541 Appendix C.4.2: reuses dynamic entry 62 (`:authority: www.example.com`) + // and adds `cache-control: no-cache`. + let block2: &[u8] = &[0x82, 0x86, 0x84, 0xbe, 0x58, 0x86, 0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf]; + let h2 = dec.decode(block2).unwrap(); + assert_eq!(h2[3], (b":authority".to_vec(), b"www.example.com".to_vec())); + assert_eq!(h2[4], (b"cache-control".to_vec(), b"no-cache".to_vec())); + // Round-trip our literal encoder for gRPC paths. + let enc = hpack_encode_literal(&[(":method", "POST"), (":path", SOLVE_PATH), ("content-type", "application/grpc")]); + let h3 = dec.decode(&enc).unwrap(); + assert_eq!(h3[1], (b":path".to_vec(), SOLVE_PATH.as_bytes().to_vec())); + } + + #[test] + fn rewrites_moby_solve_request_and_preserves_other_fields() { + let (engine, dir) = test_engine("rewrite"); + + // Build a SolveRequest with Ref (1), ExporterDeprecated (3), + // ExporterAttrsDeprecated (4), Session (5), Frontend (6), Exporters (13). + let mut req = Vec::new(); + pb_write_string(&mut req, 1, "ref-abc"); + pb_write_string(&mut req, 3, "moby"); + pb_write_map_entry(&mut req, 4, "name", "docker.io/library/probe-incontainer:latest"); + pb_write_map_entry(&mut req, 4, "unpack", "true"); + pb_write_string(&mut req, 5, "sess-123"); + pb_write_string(&mut req, 6, "dockerfile.v0"); + let exp = pb_encode_exporter(&ExporterSpec { + ty: "moby".into(), + attrs: vec![ + ("name".into(), "docker.io/library/probe-incontainer:latest".into()), + ("unpack".into(), "true".into()), + ("annotation.foo".into(), "bar".into()), + ], + }); + pb_write_bytes(&mut req, 13, &exp); + + let (rewritten, state) = rewrite_solve_request(&req, &engine, false).unwrap(); + let state = state.expect("moby exporter triggers local LoadSession"); + assert_eq!(state.orig_name, "docker.io/library/probe-incontainer:latest"); + + let fields = pb_split_fields(&rewritten).unwrap(); + // Non-exporter fields stayed intact. + assert!(fields.iter().any(|f| f.num == 1 && f.val == b"ref-abc")); + assert!(fields.iter().any(|f| f.num == 5 && f.val == b"sess-123")); + assert!(fields.iter().any(|f| f.num == 6 && f.val == b"dockerfile.v0")); + // Exporters[0] became image + push=true + mirror URL, without moby-only unpack. + let exp_field = fields.iter().find(|f| f.num == 13).unwrap(); + let decoded = pb_decode_exporter(exp_field.val).unwrap(); + assert_eq!(decoded.ty, "image"); + assert!(decoded.attrs.iter().any(|(k, v)| k == "push" && v == "true")); + assert!(!decoded.attrs.iter().any(|(k, _)| k == "registry.insecure")); + assert!(decoded.attrs.iter().any(|(k, v)| k == "annotation.foo" && v == "bar")); + assert!(!decoded.attrs.iter().any(|(k, _)| k == "unpack")); + let target_name = decoded.attrs.iter().find(|(k, _)| k == "name").map(|(_, v)| v.as_str()).unwrap(); + assert!(target_name.contains("/load/") && target_name.ends_with("/image:out"), "{target_name}"); + + // SolveResponse rewrite restores original name and swaps digest to config_digest. + let mut resp = Vec::new(); + pb_write_map_entry(&mut resp, 1, "image.name", target_name); + pb_write_map_entry(&mut resp, 1, "containerimage.digest", "sha256:manifest000"); + pb_write_map_entry(&mut resp, 1, "containerimage.config.digest", "sha256:config111"); + let fixed = rewrite_solve_response(&resp, &state.orig_name, Some("sha256:config111")).unwrap(); + let resp_map: HashMap = pb_split_fields(&fixed) + .unwrap() + .into_iter() + .filter(|f| f.num == 1) + .map(|f| pb_decode_map_entry(f.val).unwrap()) + .collect(); + assert_eq!(resp_map.get("image.name").map(String::as_str), Some("docker.io/library/probe-incontainer:latest")); + assert_eq!(resp_map.get("containerimage.digest").map(String::as_str), Some("sha256:config111")); + assert_eq!(resp_map.get("containerimage.config.digest").map(String::as_str), Some("sha256:config111")); + + // Moby exporter with push=true rewrites to image exporter keeping the real registry target. + let mut push_req = Vec::new(); + let push_exp = pb_encode_exporter(&ExporterSpec { + ty: "moby".into(), + attrs: vec![("name".into(), "localhost:5000/app:1".into()), ("push".into(), "true".into())], + }); + pb_write_bytes(&mut push_req, 13, &push_exp); + let (push_out, push_state) = rewrite_solve_request(&push_req, &engine, false).unwrap(); + assert!(push_state.is_none(), "direct push does not register a local LoadSession"); + let push_decoded = pb_decode_exporter(pb_split_fields(&push_out).unwrap().iter().find(|f| f.num == 13).unwrap().val).unwrap(); + assert_eq!(push_decoded.ty, "image"); + assert!(push_decoded.attrs.iter().any(|(k, v)| k == "name" && v == "localhost:5000/app:1")); + assert!(push_decoded.attrs.iter().any(|(k, v)| k == "push" && v == "true")); + + // Non-moby exporter (`local`) passes through untouched. + let mut local_req = Vec::new(); + let local_exp = pb_encode_exporter(&ExporterSpec { ty: "local".into(), attrs: vec![("dest".into(), "/out".into())] }); + pb_write_bytes(&mut local_req, 13, &local_exp); + let (local_out, local_state) = rewrite_solve_request(&local_req, &engine, false).unwrap(); + assert!(local_state.is_none()); + assert_eq!(local_out, local_req); + + drop(state); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn proxy_grpc_rewrites_solve_stream_over_http2() { + let (engine, dir) = test_engine("proxy"); + + // Build client -> proxy byte stream: preface + HEADERS(/Control/Solve) + DATA(SolveRequest). + let mut solve_req = Vec::new(); + pb_write_string(&mut solve_req, 1, "r1"); + pb_write_bytes( + &mut solve_req, + 13, + &pb_encode_exporter(&ExporterSpec { + ty: "moby".into(), + attrs: vec![("name".into(), "docker.io/library/demo:v1".into())], + }), + ); + let mut c2p = Vec::new(); + c2p.extend_from_slice(H2_PREFACE); + write_frame(&mut c2p, &Frame { ty: FRAME_SETTINGS, flags: 0, stream_id: 0, payload: Vec::new() }).unwrap(); + let hdr = hpack_encode_literal(&[(":method", "POST"), (":path", SOLVE_PATH), ("content-type", "application/grpc")]); + write_frame(&mut c2p, &Frame { ty: FRAME_HEADERS, flags: FLAG_END_HEADERS, stream_id: 1, payload: hdr }).unwrap(); + write_frame(&mut c2p, &Frame { ty: FRAME_DATA, flags: FLAG_END_STREAM, stream_id: 1, payload: wrap_grpc_message(&solve_req) }).unwrap(); + + // Pair sockets so fake buildkitd receives the rewritten SolveRequest, then replies SolveResponse. + let (mut fake_srv_r, fake_srv_w) = UnixStream::pair().unwrap(); + let (mut client_w_recv, client_w_send) = UnixStream::pair().unwrap(); + let (fake_reply_w, fake_reply_r) = UnixStream::pair().unwrap(); + + let fake_buildkit = std::thread::spawn(move || { + let mut pref = [0u8; 24]; + fake_srv_r.read_exact(&mut pref).unwrap(); + assert_eq!(&pref, H2_PREFACE); + let mut got_req = Vec::new(); + while let Some(f) = read_frame(&mut fake_srv_r).unwrap() { + if f.ty == FRAME_DATA && f.stream_id == 1 { + got_req.extend_from_slice(&f.payload); + if f.flags & FLAG_END_STREAM != 0 { + break; + } + } + } + // Verify the proxy rewrote the exporter to image + push=true + mirror URL. + assert_eq!(got_req[0], 0); + let fields = pb_split_fields(&got_req[5..]).unwrap(); + let exp = pb_decode_exporter(fields.iter().find(|f| f.num == 13).unwrap().val).unwrap(); + assert_eq!(exp.ty, "image"); + let mirror_name = exp.attrs.iter().find(|(k, _)| k == "name").unwrap().1.clone(); + assert!(mirror_name.contains("/load/") && mirror_name.ends_with("/image:out")); + + // Reply with SolveResponse carrying the internal mirror name. + let mut resp_pb = Vec::new(); + pb_write_map_entry(&mut resp_pb, 1, "image.name", &mirror_name); + pb_write_map_entry(&mut resp_pb, 1, "containerimage.digest", "sha256:manifest"); + let mut w = fake_reply_w; + write_frame(&mut w, &Frame { ty: FRAME_HEADERS, flags: FLAG_END_HEADERS, stream_id: 1, payload: hpack_encode_literal(&[(":status", "200")]) }).unwrap(); + write_frame(&mut w, &Frame { ty: FRAME_DATA, flags: 0, stream_id: 1, payload: wrap_grpc_message(&resp_pb) }).unwrap(); + write_frame(&mut w, &Frame { ty: FRAME_HEADERS, flags: FLAG_END_HEADERS | FLAG_END_STREAM, stream_id: 1, payload: hpack_encode_literal(&[("grpc-status", "0")]) }).unwrap(); + let _ = w.shutdown(Shutdown::Write); + }); + + let (mut cli_send_req, cli_recv_req) = UnixStream::pair().unwrap(); + let client_writer = std::thread::spawn(move || { + cli_send_req.write_all(&c2p).unwrap(); + // Keep the connection open until the proxy shuts down or the test ends. + let mut drain = [0u8; 64]; + let _ = cli_send_req.read(&mut drain); + }); + let fake_srv_w_done = fake_srv_w.try_clone().unwrap(); + let client_w_done = client_w_send.try_clone().unwrap(); + let cli_recv_req_done = cli_recv_req.try_clone().unwrap(); + proxy_grpc( + cli_recv_req, + client_w_send, + fake_reply_r, + fake_srv_w, + &engine, + false, + move || { + let _ = fake_srv_w_done.shutdown(Shutdown::Write); + }, + move || { + let _ = client_w_done.shutdown(Shutdown::Write); + let _ = cli_recv_req_done.shutdown(Shutdown::Both); + }, + ) + .unwrap(); + fake_buildkit.join().unwrap(); + client_writer.join().unwrap(); + + // Read client-visible response frames and confirm mirror URL was replaced with original name. + let mut resp_data = Vec::new(); + while let Some(f) = read_frame(&mut client_w_recv).unwrap() { + if f.ty == FRAME_DATA && f.stream_id == 1 { + resp_data.extend_from_slice(&f.payload); + } + } + let resp_map: HashMap = pb_split_fields(&resp_data[5..]) + .unwrap() + .into_iter() + .filter(|f| f.num == 1) + .map(|f| pb_decode_map_entry(f.val).unwrap()) + .collect(); + assert_eq!(resp_map.get("image.name").map(String::as_str), Some("docker.io/library/demo:v1")); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn bridge_session_wraps_and_unwraps_bytes_messages() { + let (mut srv_r, srv_w) = UnixStream::pair().unwrap(); + let (srv_reply_w, srv_reply_r) = UnixStream::pair().unwrap(); + let (mut cli_recv, cli_send) = UnixStream::pair().unwrap(); + + let fake_bk = std::thread::spawn(move || { + let mut pref = [0u8; 24]; + srv_r.read_exact(&mut pref).unwrap(); + assert_eq!(&pref, H2_PREFACE); + let mut dec = HpackDecoder::new(); + let mut saw_headers = Vec::new(); + let mut got_payload = Vec::new(); + while let Some(f) = read_frame(&mut srv_r).unwrap() { + match f.ty { + FRAME_HEADERS if f.stream_id == 1 => { + saw_headers = dec.decode(&f.payload).unwrap(); + } + FRAME_DATA if f.stream_id == 1 => { + if f.payload.len() >= 5 { + got_payload.extend_from_slice(&decode_bytes_message(&f.payload[5..]).unwrap()); + } + if f.flags & FLAG_END_STREAM != 0 { + break; + } + } + _ => {} + } + } + assert!(saw_headers.iter().any(|(k, v)| k == b":path" && v == SESSION_PATH.as_bytes())); + assert!(saw_headers.iter().any(|(k, v)| k == b"x-docker-expose-session-uuid" && v == b"sess-42")); + assert_eq!( + saw_headers.iter().filter(|(k, _)| k == b"x-docker-expose-session-grpc-method").count(), + 2, + "repeated session method headers must be preserved" + ); + assert_eq!(got_payload, b"hello-from-client"); + + let mut w = srv_reply_w; + write_frame(&mut w, &Frame { ty: FRAME_SETTINGS, flags: 0, stream_id: 0, payload: Vec::new() }).unwrap(); + let msg = wrap_grpc_message(&encode_bytes_message(b"hello-from-buildkit")); + write_frame(&mut w, &Frame { ty: FRAME_DATA, flags: FLAG_END_STREAM, stream_id: 1, payload: msg }).unwrap(); + let _ = w.shutdown(Shutdown::Write); + // Keep reading until peer finishes writing SETTINGS ACK. + while read_frame(&mut srv_r).ok().flatten().is_some() {} + }); + + let headers = vec![ + ("x-docker-expose-session-uuid".to_owned(), "sess-42".to_owned()), + ("x-docker-expose-session-grpc-method".to_owned(), "/moby.filesync.v1.Auth/Credentials".to_owned()), + ("x-docker-expose-session-grpc-method".to_owned(), "/fsutil.filesync.FileSync/DiffCopy".to_owned()), + ]; + let cli_send_done = cli_send.try_clone().unwrap(); + bridge_session( + &headers, + Cursor::new(b"hello-from-client".to_vec()), + cli_send, + srv_reply_r, + srv_w, + || {}, + move || { + let _ = cli_send_done.shutdown(Shutdown::Write); + }, + ) + .unwrap(); + fake_bk.join().unwrap(); + + let mut received = Vec::new(); + cli_recv.read_to_end(&mut received).unwrap(); + assert_eq!(received, b"hello-from-buildkit"); + } + + #[test] + fn rewrites_untagged_and_multi_tag_field13_only_solve_requests() { + let (engine, dir) = test_engine("edges"); + + // Modern buildx sends only Exporters (field 13) with no deprecated fields 3/4. + // Untagged build (`docker build .`) omits `name` and sets `dangling-name-prefix`. + let mut untagged = Vec::new(); + pb_write_string(&mut untagged, 1, "ref-untagged"); + pb_write_map_entry(&mut untagged, 7, "target", "builder"); + pb_write_map_entry(&mut untagged, 7, "build-arg:FOO", "bar"); + pb_write_bytes( + &mut untagged, + 13, + &pb_encode_exporter(&ExporterSpec { + ty: "moby".into(), + attrs: vec![ + ("unpack".into(), "true".into()), + ("dangling-name-prefix".into(), "moby-dangling".into()), + ], + }), + ); + let (out, state) = rewrite_solve_request(&untagged, &engine, false).unwrap(); + let state = state.expect("untagged moby triggers LoadSession"); + assert!(state.orig_name.is_empty()); + let fields = pb_split_fields(&out).unwrap(); + assert!(!fields.iter().any(|f| matches!(f.num, 3 | 4)), "must not synthesize deprecated fields when absent"); + assert!(fields.iter().any(|f| f.num == 7 && pb_decode_map_entry(f.val).unwrap() == ("target".into(), "builder".into()))); + assert!(fields.iter().any(|f| f.num == 7 && pb_decode_map_entry(f.val).unwrap() == ("build-arg:FOO".into(), "bar".into()))); + let exp = pb_decode_exporter(fields.iter().find(|f| f.num == 13).unwrap().val).unwrap(); + assert_eq!(exp.ty, "image"); + assert!(!exp.attrs.iter().any(|(k, _)| k == "dangling-name-prefix" || k == "unpack")); + // Untagged SolveResponse strips internal mirror `image.name` and returns committed config_digest. + let mut resp = Vec::new(); + pb_write_map_entry(&mut resp, 1, "image.name", &exp.attrs.iter().find(|(k, _)| k == "name").unwrap().1); + pb_write_map_entry(&mut resp, 1, "containerimage.digest", "sha256:manifest"); + let fixed = rewrite_solve_response(&resp, &state.orig_name, Some("sha256:cfg999")).unwrap(); + let map: HashMap = pb_split_fields(&fixed).unwrap().into_iter().filter(|f| f.num == 1).map(|f| pb_decode_map_entry(f.val).unwrap()).collect(); + assert!(!map.contains_key("image.name"), "untagged response must not leak mirror URL: {map:?}"); + assert_eq!(map.get("containerimage.digest").map(String::as_str), Some("sha256:cfg999")); + drop(state); + + // Multi-tag (`-t probe-a:1 -t probe-b:2`) preserves all tags and rejects digest refs. + assert_eq!( + parse_export_tags("docker.io/library/probe-a:1, docker.io/library/probe-b:2, probe-a:1").unwrap(), + vec!["probe-a:1".to_owned(), "probe-b:2".to_owned()] + ); + assert!(parse_export_tags("alpine@sha256:0000000000000000000000000000000000000000000000000000000000000000").is_err()); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn enforces_frame_and_hpack_bounds() { + // Oversized HTTP/2 frame header (> MAX_FRAME_LIMIT) is rejected before reading payload. + let huge_len = (MAX_FRAME_LIMIT + 1) as u32; + let head = [ + ((huge_len >> 16) & 0xff) as u8, + ((huge_len >> 8) & 0xff) as u8, + (huge_len & 0xff) as u8, + FRAME_DATA, + 0, + 0, + 0, + 0, + 1, + ]; + assert_eq!(read_frame(&mut Cursor::new(head)).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Truncated large-claim frame returns UnexpectedEof without allocating the claimed size. + let claim = (MAX_FRAME_LIMIT - 1) as u32; + let mut trunc = vec![ + ((claim >> 16) & 0xff) as u8, + ((claim >> 8) & 0xff) as u8, + (claim & 0xff) as u8, + FRAME_DATA, + 0, + 0, + 0, + 0, + 1, + ]; + trunc.extend_from_slice(b"short"); + assert_eq!(read_frame(&mut Cursor::new(trunc)).unwrap_err().kind(), io::ErrorKind::UnexpectedEof); + + // HPACK dynamic table size update past MAX_HPACK_TABLE_SIZE is rejected. + let mut dec = HpackDecoder::new(); + let mut bad_update = Vec::new(); + hpack_encode_int(&mut bad_update, 5, 0x20, MAX_HPACK_TABLE_SIZE + 1); + assert_eq!(dec.decode(&bad_update).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // HPACK decompression bomb (repeating a large indexed dynamic entry) is rejected. + let mut bomb = Vec::new(); + // Insert a ~3.5 KiB header into dynamic table (index 62): literal with incremental indexing (0x40), new name. + bomb.push(0x40); + hpack_encode_int(&mut bomb, 7, 0x00, 1); + bomb.push(b'x'); + hpack_encode_int(&mut bomb, 7, 0x00, 3500); + bomb.extend(std::iter::repeat_n(b'a', 3500)); + // Repeat index 62 (0x80 | 62 = 0xbe) 1000 times -> ~3.5 MiB > MAX_DECODED_HEADERS (2 MiB). + bomb.extend(std::iter::repeat_n(0xbe, 1000)); + assert_eq!(dec.decode(&bomb).unwrap_err().kind(), io::ErrorKind::InvalidData); + } + + #[test] + fn bridge_session_aborts_cleanly_on_client_error() { + struct FailReader; + impl Read for FailReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::new(io::ErrorKind::ConnectionReset, "peer reset")) + } + } + let (mut srv_r, srv_w) = UnixStream::pair().unwrap(); + let (srv_reply_w, srv_reply_r) = UnixStream::pair().unwrap(); + let (_cli_recv, cli_send) = UnixStream::pair().unwrap(); + let abort_w = srv_reply_w.try_clone().unwrap(); + let srv_w_close = srv_w.try_clone().unwrap(); + + let drain = std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + while srv_r.read(&mut buf).unwrap_or(0) > 0 {} + }); + let res = bridge_session( + &[], + FailReader, + cli_send, + srv_reply_r, + srv_w, + move || { + // Simulates closing exec stdin so buildctl exits and closes server stdout. + let _ = srv_w_close.shutdown(Shutdown::Write); + let _ = abort_w.shutdown(Shutdown::Write); + }, + || {}, + ); + drop(srv_reply_w); + drain.join().unwrap(); + assert!(res.is_err()); + } + + #[test] + fn grpc_probe_returns_101_without_waking_builder() { + let (engine, dir) = test_engine("probe"); + let (mut client, server) = UnixStream::pair().unwrap(); + let handle = std::thread::spawn({ + let engine = engine.clone(); + move || super::super::api::serve(server, engine, super::super::caller::Caller::Container) + }); + client + .write_all(b"POST /grpc HTTP/1.1\r\nHost: \r\nContent-Length: 0\r\nConnection: Upgrade\r\nUpgrade: h2c\r\n\r\n") + .unwrap(); + // Read the full HTTP/1.1 101 response head, then close immediately as buildx's Priority() probe does. + let mut resp = Vec::new(); + let mut buf = [0u8; 512]; + while !resp.windows(4).any(|w| w == b"\r\n\r\n") { + let n = client.read(&mut buf).unwrap(); + assert!(n > 0, "unexpected EOF before end of 101 headers: {:?}", String::from_utf8_lossy(&resp)); + resp.extend_from_slice(&buf[..n]); + } + let resp = String::from_utf8_lossy(&resp); + assert!(resp.starts_with("HTTP/1.1 101 "), "{resp}"); + assert!(resp.contains("Upgrade: h2c\r\n"), "{resp}"); + drop(client); + handle.join().unwrap().unwrap(); + // No builder container was created by a probe. + assert!(engine.each(|c| Some(c.name.clone())).is_empty()); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn rewrites_gzip_compressed_solve_request() { + let (engine, dir) = test_engine("gzip"); + + let mut solve_req = Vec::new(); + pb_write_string(&mut solve_req, 1, "ref-gzip"); + pb_write_bytes( + &mut solve_req, + 13, + &pb_encode_exporter(&ExporterSpec { + ty: "moby".into(), + attrs: vec![("name".into(), "docker.io/library/gzip-demo:1".into()), ("unpack".into(), "true".into())], + }), + ); + let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + enc.write_all(&solve_req).unwrap(); + let compressed_req = wrap_grpc_frame(1, &enc.finish().unwrap()); + + let (out_grpc, state) = rewrite_grpc_solve_request(&compressed_req, &engine, false).unwrap(); + let state = state.expect("gzipped moby SolveRequest must be rewritten"); + assert_eq!(state.orig_name, "docker.io/library/gzip-demo:1"); + assert_eq!(out_grpc[0], 1, "rewritten frame keeps gRPC compression flag consistent with grpc-encoding: gzip"); + let msg_len = u32::from_be_bytes([out_grpc[1], out_grpc[2], out_grpc[3], out_grpc[4]]) as usize; + assert_eq!(5 + msg_len, out_grpc.len()); + + let mut decompressed = Vec::new(); + flate2::read::GzDecoder::new(&out_grpc[5..]).read_to_end(&mut decompressed).unwrap(); + let fields = pb_split_fields(&decompressed).unwrap(); + let exp = pb_decode_exporter(fields.iter().find(|f| f.num == 13).unwrap().val).unwrap(); + assert_eq!(exp.ty, "image"); + assert!(exp.attrs.iter().any(|(k, v)| k == "push" && v == "true")); + assert!(!exp.attrs.iter().any(|(k, _)| k == "unpack")); + assert!(exp.attrs.iter().any(|(k, v)| k == "name" && v.contains("/load/") && v.ends_with("/image:out"))); + + drop(state); + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn rejects_empty_continuation_flood_and_caps_concurrent_solve_streams() { + let (engine, dir) = test_engine("dos-caps"); + + // 1. Empty CONTINUATION frame flood past MAX_CONTINUATION_FRAMES is rejected. + { + let mut c2p = Vec::new(); + c2p.extend_from_slice(H2_PREFACE); + let hdr = hpack_encode_literal(&[(":method", "POST"), (":path", SOLVE_PATH)]); + write_frame(&mut c2p, &Frame { ty: FRAME_HEADERS, flags: 0, stream_id: 1, payload: hdr }).unwrap(); + for _ in 0..=MAX_CONTINUATION_FRAMES { + write_frame(&mut c2p, &Frame { ty: FRAME_CONTINUATION, flags: 0, stream_id: 1, payload: Vec::new() }).unwrap(); + } + let (_srv_r, srv_w) = UnixStream::pair().unwrap(); + let (reply_w, reply_r) = UnixStream::pair().unwrap(); + let mut client_out = Vec::new(); + let err = proxy_grpc( + Cursor::new(c2p), + &mut client_out, + reply_r, + srv_w, + &engine, + false, + || { let _ = reply_w.shutdown(Shutdown::Both); }, + || {}, + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(err.to_string().contains("CONTINUATION"), "{err}"); + } + + // 2. Empty END_STREAM HEADERS clears solve_req_bufs, while exceeding MAX_CONCURRENT_SOLVE_STREAMS is rejected. + { + let mut c2p = Vec::new(); + c2p.extend_from_slice(H2_PREFACE); + let solve_hdr = hpack_encode_literal(&[(":method", "POST"), (":path", SOLVE_PATH)]); + let empty_end_hdr = hpack_encode_literal(&[("grpc-status", "0")]); + // Open stream 1, then immediately close it via END_STREAM HEADERS so its slot is freed. + write_frame(&mut c2p, &Frame { ty: FRAME_HEADERS, flags: FLAG_END_HEADERS, stream_id: 1, payload: solve_hdr.clone() }).unwrap(); + write_frame(&mut c2p, &Frame { ty: FRAME_HEADERS, flags: FLAG_END_HEADERS | FLAG_END_STREAM, stream_id: 1, payload: empty_end_hdr }).unwrap(); + // Open MAX_CONCURRENT_SOLVE_STREAMS concurrent Solve streams (streams 3..=33), then one more (stream 35) to trigger the cap. + for i in 0..=MAX_CONCURRENT_SOLVE_STREAMS { + let sid = (i as u32 + 1) * 2 + 1; + write_frame(&mut c2p, &Frame { ty: FRAME_HEADERS, flags: FLAG_END_HEADERS, stream_id: sid, payload: solve_hdr.clone() }).unwrap(); + } + let (mut srv_r, srv_w) = UnixStream::pair().unwrap(); + let (reply_w, reply_r) = UnixStream::pair().unwrap(); + let drain = std::thread::spawn(move || { + let mut buf = [0u8; 4096]; + while srv_r.read(&mut buf).unwrap_or(0) > 0 {} + }); + let mut client_out = Vec::new(); + let err = proxy_grpc( + Cursor::new(c2p), + &mut client_out, + reply_r, + srv_w, + &engine, + false, + || { let _ = reply_w.shutdown(Shutdown::Both); }, + || {}, + ) + .unwrap_err(); + drain.join().unwrap(); + assert_eq!(err.kind(), io::ErrorKind::InvalidData); + assert!(err.to_string().contains("concurrent Solve streams"), "{err}"); + } + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/kiri/src/daemon/hostopts.rs b/crates/kiri/src/daemon/hostopts.rs index 51babef9c..764f9bc48 100644 --- a/crates/kiri/src/daemon/hostopts.rs +++ b/crates/kiri/src/daemon/hostopts.rs @@ -1,13 +1,30 @@ //! HostConfig settings the guest applies when a container starts: -//! `--ulimit`, `--sysctl`, `--device`, `--device-cgroup-rule` and -//! `--group-add`. They are kept as the API gave them (for inspect), checked +//! `--ulimit`, `--sysctl`, `--device`, `--device-cgroup-rule`, +//! `--group-add`, `--cgroupns`, `MaskedPaths` and `ReadonlyPaths`. They are kept as the API gave them (for inspect), checked //! at create with Docker's errors, and handed to the guest at every start as //! the `opts` lines of `Run` and `Exec` (see [`kiri_proto::RunSpec::opts`]). use serde_json::{Value, json}; /// The HostConfig keys kept with a container. -const KEYS: [&str; 5] = ["Ulimits", "Sysctls", "Devices", "DeviceCgroupRules", "GroupAdd"]; +const KEYS: [&str; 8] = ["Ulimits", "Sysctls", "Devices", "DeviceCgroupRules", "GroupAdd", "MaskedPaths", "ReadonlyPaths", "CgroupnsMode"]; + +/// Docker's default `MaskedPaths` and `ReadonlyPaths`, as inspect shows them. +const MASKED: [&str; 12] = [ + "/proc/acpi", + "/proc/asound", + "/proc/interrupts", + "/proc/kcore", + "/proc/keys", + "/proc/latency_stats", + "/proc/sched_debug", + "/proc/scsi", + "/proc/timer_list", + "/proc/timer_stats", + "/sys/devices/virtual/powercap", + "/sys/firmware", +]; +const READONLY: [&str; 5] = ["/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger"]; /// `nofile` when the run sets none: what containers get on Docker Desktop /// and on Docker Engine under containerd's `LimitNOFILE=infinity`. Without @@ -46,6 +63,21 @@ pub fn from_host(host: &Value) -> Value { m.insert(k.to_owned(), host[k].clone()); } } + let mut unconfined = host["Privileged"].as_bool().unwrap_or(false); + for opt in strings(&host["SecurityOpt"]) { + if let Some(v) = opt.strip_prefix("systempaths=").or_else(|| opt.strip_prefix("systempaths:")) { + if v == "unconfined" { + unconfined = true; + } else { + m.entry("SecurityOpt".to_owned()).or_insert_with(|| Value::String(opt)); + } + } + } + if unconfined { + for k in ["MaskedPaths", "ReadonlyPaths"] { + m.insert(k.to_owned(), json!([])); + } + } Value::Object(m) } @@ -53,11 +85,25 @@ pub fn from_host(host: &Value) -> Value { pub fn inspect(opts: &Value, key: &str) -> Value { match (&opts[key], key) { (Value::Null, "Ulimits" | "Devices") => json!([]), + (Value::Null, "CgroupnsMode") => json!("private"), + (Value::String(s), "CgroupnsMode") if s.is_empty() => json!("private"), (Value::Null, _) => Value::Null, (v, _) => v.clone(), } } +/// `MaskedPaths` or `ReadonlyPaths` for inspect: empty for a privileged +/// container, else as given or Docker's defaults. +pub fn system_paths(opts: &Value, key: &str, privileged: bool) -> Value { + if privileged { + return json!([]); + } + match &opts[key] { + Value::Null => json!(if key == "MaskedPaths" { &MASKED[..] } else { &READONLY[..] }), + v => v.clone(), + } +} + /// `--gpus` and Compose `deploy.resources.reservations.devices` arrive as /// DeviceRequests. Kiri has no GPU to give, and saying so beats a container /// that silently runs on the CPU. @@ -79,12 +125,15 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> for u in opts["Ulimits"].as_array().into_iter().flatten() { let name = u["Name"].as_str().unwrap_or(""); let res = RLIMITS.iter().find(|(n, _)| *n == name).map(|(_, r)| *r).ok_or_else(|| format!("invalid ulimit type: {name}"))?; - let value = |k: &str| match u[k].as_i64() { - Some(v) if v < 0 => UNLIMITED, - Some(v) => v as u64, - None => u[k].as_u64().unwrap_or(0), + // Docker decodes Soft and Hard as int64: a missing one is 0, and a + // string or fraction is refused rather than read as 0. + let value = |k: &str| match (&u[k], u[k].as_i64()) { + (_, Some(v)) if v < 0 => Ok(UNLIMITED), + (_, Some(v)) => Ok(v as u64), + (Value::Null, None) => Ok(0), + (v, None) => v.as_u64().ok_or_else(|| format!("invalid ulimit {name} {k}: {v} is not an integer")), }; - let (soft, hard) = (value("Soft"), value("Hard")); + let (soft, hard) = (value("Soft")?, value("Hard")?); if soft > hard { return Err(format!("ulimit soft limit must be less than or equal to hard limit: {} > {}", u["Soft"], u["Hard"])); } @@ -131,6 +180,33 @@ pub fn guest_lines(opts: &Value, net_host: bool) -> Result, String> } out.push(format!("group\t{g}")); } + if let Some(opt) = opts["SecurityOpt"].as_str() { + return Err(format!("invalid --security-opt: {opt:?}")); + } + // `--security-opt systempaths=unconfined` and `--privileged` arrive as both set to []. + for (key, kind) in [("MaskedPaths", "masked"), ("ReadonlyPaths", "readonly")] { + let paths = match &opts[key] { + Value::Null => continue, + Value::Array(a) => a + .iter() + .map(|p| { + p.as_str().filter(|p| { + p.starts_with('/') && !p.contains(['\t', '\n', '\r', '\0']) && !p.split('/').any(|c| c == "..") + }) + }) + .collect::>>(), + _ => None, + }; + let paths = paths.ok_or_else(|| format!("invalid {key}: each entry must be an absolute path"))?; + out.push(std::iter::once(kind).chain(paths).collect::>().join("\t")); + } + match &opts["CgroupnsMode"] { + Value::Null => {} + Value::String(m) if m.is_empty() || m == "private" => {} + Value::String(m) if m == "host" => out.push("cgroupns\thost".to_owned()), + Value::String(m) => return Err(format!("invalid cgroup namespace mode: {m}")), + other => return Err(format!("invalid cgroup namespace mode: {other}")), + } Ok(out) } @@ -307,4 +383,64 @@ mod tests { assert_eq!(inspect(&kept, "GroupAdd"), Value::Null); assert_eq!(inspect(&Value::Null, "Ulimits"), json!([])); } + + #[test] + fn masked_and_readonly_paths() { + // Not set: no line, so the guest keeps its defaults. + assert_eq!(guest_lines(&json!({}), false).unwrap().len(), 1); + let kept = from_host(&json!({"MaskedPaths": [], "ReadonlyPaths": []})); + assert_eq!(guest_lines(&kept, false).unwrap()[1..], ["masked", "readonly"]); + for opt in ["systempaths=unconfined", "systempaths:unconfined"] { + let kept = from_host(&json!({"SecurityOpt": [opt], "MaskedPaths": ["/proc/kcore"], "ReadonlyPaths": ["/proc/sys"]})); + assert_eq!(kept, json!({"MaskedPaths": [], "ReadonlyPaths": []})); + assert_eq!(guest_lines(&kept, false).unwrap()[1..], ["masked", "readonly"]); + } + let priv_kept = from_host(&json!({"Privileged": true, "MaskedPaths": ["/proc/kcore"], "ReadonlyPaths": ["/proc/sys"]})); + assert_eq!(priv_kept, json!({"MaskedPaths": [], "ReadonlyPaths": []})); + assert_eq!(guest_lines(&priv_kept, false).unwrap()[1..], ["masked", "readonly"]); + let kept = from_host(&json!({"MaskedPaths": ["/proc/kcore", "/etc/secret"]})); + assert_eq!(guest_lines(&kept, false).unwrap()[1..], ["masked\t/proc/kcore\t/etc/secret"]); + for bad in [json!(["proc/kcore"]), json!(["/../etc"]), json!(["/proc/../etc"]), json!(["/a\tb"]), json!(["/a\rb"]), json!([1]), json!("/proc/kcore")] { + assert!(guest_lines(&json!({"MaskedPaths": bad}), false).is_err(), "{bad}"); + } + assert_eq!( + guest_lines(&from_host(&json!({"SecurityOpt": ["systempaths=bogus"]})), false).unwrap_err(), + "invalid --security-opt: \"systempaths=bogus\"" + ); + assert_eq!(system_paths(&json!({}), "ReadonlyPaths", false), json!(READONLY)); + assert_eq!(system_paths(&json!({}), "MaskedPaths", true), json!([])); + assert_eq!(system_paths(&kept, "MaskedPaths", true), json!([])); + } + + #[test] + fn cgroupns_mode() { + assert_eq!(inspect(&json!({}), "CgroupnsMode"), json!("private")); + assert_eq!(inspect(&from_host(&json!({"CgroupnsMode": Value::Null})), "CgroupnsMode"), json!("private")); + assert_eq!(inspect(&from_host(&json!({"CgroupnsMode": ""})), "CgroupnsMode"), json!("private")); + assert_eq!(inspect(&from_host(&json!({"CgroupnsMode": "private"})), "CgroupnsMode"), json!("private")); + assert_eq!(inspect(&from_host(&json!({"CgroupnsMode": "host"})), "CgroupnsMode"), json!("host")); + assert_eq!(guest_lines(&from_host(&json!({"CgroupnsMode": Value::Null})), false).unwrap(), ["rlimit\t7\t1048576\t1048576"]); + assert_eq!(guest_lines(&from_host(&json!({"CgroupnsMode": ""})), false).unwrap(), ["rlimit\t7\t1048576\t1048576"]); + assert_eq!(guest_lines(&from_host(&json!({"CgroupnsMode": "private"})), false).unwrap(), ["rlimit\t7\t1048576\t1048576"]); + assert_eq!(guest_lines(&from_host(&json!({"CgroupnsMode": "host"})), false).unwrap()[1..], ["cgroupns\thost"]); + for bad in ["bogus", "container:abc", "none"] { + assert_eq!( + guest_lines(&from_host(&json!({"CgroupnsMode": bad})), false).unwrap_err(), + format!("invalid cgroup namespace mode: {bad}") + ); + } + assert!(guest_lines(&from_host(&json!({"CgroupnsMode": 123})), false).is_err()); + assert!(guest_lines(&from_host(&json!({"CgroupnsMode": true})), false).is_err()); + } + + #[test] + fn a_ulimit_that_is_not_an_integer_is_refused() { + let opts = json!({"Ulimits": [{"Name": "nofile", "Soft": "65536", "Hard": "65536"}]}); + assert_eq!(guest_lines(&opts, false).unwrap_err(), "invalid ulimit nofile Soft: \"65536\" is not an integer"); + let opts = json!({"Ulimits": [{"Name": "nproc", "Soft": 10, "Hard": 65536.5}]}); + assert_eq!(guest_lines(&opts, false).unwrap_err(), "invalid ulimit nproc Hard: 65536.5 is not an integer"); + // A missing value is Docker's zero, as before. + let opts = json!({"Ulimits": [{"Name": "core", "Hard": 0}]}); + assert_eq!(guest_lines(&opts, false).unwrap(), ["rlimit\t4\t0\t0", "rlimit\t7\t1048576\t1048576"]); + } } diff --git a/crates/kiri/src/daemon/hostroots.rs b/crates/kiri/src/daemon/hostroots.rs new file mode 100644 index 000000000..a8d59a2f1 --- /dev/null +++ b/crates/kiri/src/daemon/hostroots.rs @@ -0,0 +1,233 @@ +//! A Windows host's root certificates, for the engine in WSL (#303). The +//! daemon runs in a Linux distro there, away from the Windows store, so +//! kiri-win sends the store's roots that the bundled set lacks (a company +//! root, among them) and the ones the administrator distrusted +//! (`PUT /kiri/roots/host`), when the engine starts and every minute. They +//! are kept in `~/.kiri/host-roots.json`, so a pull before the window has +//! sent them (the engine started by the boot command) trusts them too. + +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use kiri_image::roots::{self, Host}; +use serde_json::{Value, json}; + +/// The file's size at most: every certificate past the caps is dropped +/// anyway. +const MAX_FILE: u64 = 8 << 20; + +fn path() -> Option { + super::state_dir().ok().map(|d| d.join("host-roots.json")) +} + +/// The roots in `body` (`{"certs": [hex DER…], "distrusted": [hex DER…]}`). +pub fn parse(body: &Value) -> Host { + let list = |k: &str| body[k].as_array().into_iter().flatten().filter_map(Value::as_str); + Host::from_hex(list("certs"), list("distrusted")) +} + +fn to_json(h: &Host) -> Value { + let list = |l: &[rustls::pki_types::CertificateDer<'static>]| l.iter().map(|c| roots::hex(c)).collect::>(); + json!({"certs": list(&h.certs), "distrusted": list(&h.distrusted)}) +} + +/// Whether this daemon is the engine in WSL: the only place kiri-win's +/// roots belong. A native Linux daemon has its own store, and takes +/// neither the roots nor the file they are kept in. +pub fn in_wsl() -> bool { + super::binds::wsl().is_some() +} + +/// Takes the roots kiri-win sent, keeping them for the next start when +/// they changed. Answers with how many there are. +pub fn set(body: &Value) -> io::Result { + // One save at a time: they share a temp file and serialize disk + memory updates. + static SAVING: Mutex<()> = Mutex::new(()); + let _saving = SAVING.lock().unwrap_or_else(|e| e.into_inner()); + let host = parse(body); + let (certs, distrusted) = (host.certs.len(), host.distrusted.len()); + let same = roots::host().as_ref() == Some(&host); + if !same && let Some(p) = path() { + save_to(&p, &host)?; + } + let changed = roots::set_host(host); + Ok(json!({"certs": certs, "distrusted": distrusted, "changed": changed})) +} + +/// Atomically writes `host` to `p` with mode `0600`, refusing to write through +/// any pre-existing symlink at the temp path or destination. +fn save_to(p: &Path, host: &Host) -> io::Result<()> { + if let Some(dir) = p.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = p.with_extension("json.tmp"); + // A stale temp file, or a link put there, is not written through. + let _ = std::fs::remove_file(&tmp); + let bytes = to_json(host).to_string(); + if let Err(e) = write_private(&tmp, bytes.as_bytes()) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + if let Err(e) = std::fs::rename(&tmp, p) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +/// A new file only this user can read or write, whatever the umask (the +/// daemon's unit may run with 0027, a shell with 022). +fn write_private(path: &Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write; + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + let mut f = std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)?; + f.set_permissions(std::fs::Permissions::from_mode(0o600))?; + f.write_all(bytes)?; + f.sync_all() +} + +/// The kept file's JSON, if it is a regular file (not a symlink or FIFO) of a +/// sane size. +fn read_kept(p: &Path) -> io::Result { + read_kept_limit(p, MAX_FILE) +} + +fn read_kept_limit(p: &Path, limit: u64) -> io::Result { + use std::os::unix::fs::OpenOptionsExt; + // O_NOFOLLOW refuses symlinks; O_NONBLOCK opens a FIFO without waiting for + // a writer so fstat on the open descriptor rejects non-regular files with + // no TOCTOU race. + let f = std::fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_NONBLOCK | libc::O_NOFOLLOW) + .open(p)?; + if !f.metadata()?.is_file() { + return Err(io::Error::other("not a regular file")); + } + let mut text = Vec::new(); + f.take(limit.saturating_add(1)).read_to_end(&mut text)?; + if text.len() as u64 > limit { + return Err(io::Error::other("host-roots.json is too large")); + } + serde_json::from_slice(&text).map_err(io::Error::other) +} + +/// The roots kept from the last time, if any: read at start, before the +/// first pull. +pub fn load() { + if !in_wsl() { + return; + } + let Some(p) = path() else { return }; + // Never over roots kiri-win has sent this run already (checked atomically + // under the host-roots lock). + if let Ok(v) = read_kept(&p) { + roots::set_host_if_unset(parse(&v)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_the_lists_kiri_win_sends_and_writes_them_back_the_same() { + let body = json!({"certs": ["3001", 7, "zz"], "distrusted": ["30020a0b"]}); + + let host = parse(&body); + + assert_eq!(host.certs.len(), 1); + assert_eq!(host.distrusted[0].as_ref(), &[0x30, 0x02, 0x0a, 0x0b]); + assert_eq!(to_json(&host), json!({"certs": ["3001"], "distrusted": ["30020a0b"]})); + } + + #[test] + fn the_kept_roots_are_private_whatever_the_umask() { + use std::os::unix::fs::PermissionsExt; + const CHILD: &str = "KIRI_TEST_HOSTROOTS_UMASK_DIR"; + if let Some(d) = std::env::var_os(CHILD) { + let d = Path::new(&d); + for (i, mask) in [0o000, 0o022, 0o077].into_iter().enumerate() { + let f = d.join(format!("host-roots-{i}.json.tmp")); + // SAFETY: umask only changes this process's file-creation mask, + // and this child process runs this test alone. + unsafe { libc::umask(mask) }; + write_private(&f, b"{}").unwrap(); + } + return; + } + let d = std::env::temp_dir().join(format!("kiri-hostroots-mode-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let name = "daemon::hostroots::tests::the_kept_roots_are_private_whatever_the_umask"; + let child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--test-threads=1"]) + .env(CHILD, &d) + .output() + .unwrap(); + assert!(child.status.success(), "{}", String::from_utf8_lossy(&child.stdout)); + for i in 0..3 { + let f = d.join(format!("host-roots-{i}.json.tmp")); + assert_eq!(std::fs::metadata(&f).unwrap().permissions().mode() & 0o777, 0o600); + } + let _ = std::fs::remove_dir_all(&d); + } + + #[cfg(unix)] + #[test] + fn a_fifo_is_not_opened_as_the_kept_roots() { + let d = std::env::temp_dir().join(format!("kiri-hostroots-fifo-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let fifo = d.join("host-roots.json"); + assert!(std::process::Command::new("mkfifo").arg(&fifo).status().unwrap().success()); + assert!(read_kept(&fifo).unwrap_err().to_string().contains("regular")); + let _ = std::fs::remove_dir_all(&d); + } + + #[cfg(unix)] + #[test] + fn a_symlink_is_not_followed_when_reading_or_writing_kept_roots() { + use std::os::unix::fs::PermissionsExt; + let d = std::env::temp_dir().join(format!("kiri-hostroots-symlink-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let victim = d.join("victim.json"); + std::fs::write(&victim, r#"{"certs":["3001"],"distrusted":[]}"#).unwrap(); + let link = d.join("host-roots.json"); + let tmp_link = d.join("host-roots.json.tmp"); + std::os::unix::fs::symlink(&victim, &link).unwrap(); + std::os::unix::fs::symlink(&victim, &tmp_link).unwrap(); + + // Reading refuses a symlink. + assert!(read_kept(&link).is_err()); + + // Saving removes the temp symlink and atomically replaces the target + // symlink with a 0600 regular file without modifying the victim. + let host = parse(&json!({"certs": ["3002"], "distrusted": []})); + save_to(&link, &host).unwrap(); + assert_eq!(std::fs::read_to_string(&victim).unwrap(), r#"{"certs":["3001"],"distrusted":[]}"#); + let meta = std::fs::symlink_metadata(&link).unwrap(); + assert!(meta.file_type().is_file()); + assert_eq!(meta.permissions().mode() & 0o777, 0o600); + assert_eq!(parse(&read_kept(&link).unwrap()), host); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn an_oversized_kept_roots_file_is_rejected() { + let d = std::env::temp_dir().join(format!("kiri-hostroots-size-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let f = d.join("host-roots.json"); + std::fs::write(&f, format!(r#"{{"certs":["{}"],"distrusted":[]}}"#, "00".repeat(64))).unwrap(); + assert!(read_kept_limit(&f, 64).unwrap_err().to_string().contains("too large")); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_body_without_lists_is_no_roots() { + assert_eq!(parse(&json!({})), Host::default()); + } +} diff --git a/crates/kiri/src/daemon/http.rs b/crates/kiri/src/daemon/http.rs index 1fc1b3fca..70f389a07 100644 --- a/crates/kiri/src/daemon/http.rs +++ b/crates/kiri/src/daemon/http.rs @@ -18,9 +18,20 @@ pub const MIN_API_VERSION: (u32, u32) = (1, 24); /// Largest request body read into memory (container create, etc.). Archives /// and image loads are streamed with [`Body`] instead, at any size. const MAX_BODY: usize = 8 << 20; +/// Cap on upfront buffer reservation for buffered request bodies so headers or +/// a chunk size line alone never pre-allocate [`MAX_BODY`] before bytes arrive. +const INITIAL_BODY_CAP: usize = 64 << 10; /// The request line and headers together may not exceed this: an endless /// header line must not grow memory without bound. const MAX_HEAD: u64 = 64 << 10; +/// Maximum size of a single chunk-size line (hex length plus optional `;ext`). +const MAX_CHUNK_LINE: u64 = 1024; +/// Maximum total bytes in a chunked body's trailer section (including its +/// terminating blank line), so an endless trailer cannot exhaust memory or +/// hold a connection open forever. +const MAX_TRAILERS: u64 = 8 << 10; +/// Maximum number of trailer header lines before the terminating blank line. +const MAX_TRAILER_LINES: usize = 128; /// Most of a streamed body its handler left unread that is read out so the /// connection can serve the next request; past this it closes. Go's /// net/http server, so Docker's, reads out as much. @@ -46,6 +57,9 @@ pub struct Request { /// Sent as HTTP/1.0: its connection closes after the response unless it /// asks to keep it. http10: bool, + /// Whether `HTTP/1.1 100 Continue` still needs to be sent before reading a + /// streamed body (RFC 9110 §10.1.1). Cleared once written. + needs_continue: Cell, /// How much of a streamed body has been read, through [`Body`]. streamed: Cell, } @@ -83,6 +97,11 @@ impl Request { self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(key)).map(|(_, v)| v.as_str()) } + /// All request headers in wire order (preserving repeated header names). + pub fn headers(&self) -> &[(String, String)] { + &self.headers + } + /// The connection closes after this request's response: the client /// sent `Connection: close` (Docker.DotNet does on every request), or /// spoke HTTP/1.0 without `Connection: keep-alive` (RFC 9112 §9.3), as @@ -93,11 +112,23 @@ impl Request { has("close") || (self.http10 && !has("keep-alive")) } + fn expects_continue(&self) -> bool { + self.headers + .iter() + .filter(|(k, _)| k.eq_ignore_ascii_case("expect")) + .any(|(_, v)| v.split(',').any(|t| t.trim().eq_ignore_ascii_case("100-continue"))) + } + /// A request the daemon makes of itself (the managed builder's /// container create), so it goes through the same code as a client's. pub fn internal(method: &str, path: &str, query: &[(&str, &str)], body: Vec) -> Request { let query = query.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); - Request { method: method.to_owned(), path: path.to_owned(), api_version: None, query, headers: Vec::new(), body, http10: false, streamed: Cell::new(Streamed::No) } + Request { method: method.to_owned(), path: path.to_owned(), api_version: None, query, headers: Vec::new(), body, http10: false, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) } + } + + /// Whether a streamed body is still waiting for `HTTP/1.1 100 Continue`. + pub fn needs_continue(&self) -> bool { + self.needs_continue.get() } #[cfg(test)] @@ -107,10 +138,40 @@ impl Request { } } +/// How long an idle or slow connection may sit before the next request head +/// finishes arriving. Cleared as soon as the request is read so long-running +/// streams (`logs -f`, `events`, `wait`, `stats`), streamed uploads (`build`, +/// `load`, `archive`), and hijacked connections (`attach`, `exec`) never time +/// out. +pub const HEADER_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(300); + +/// Reads the next request with `timeout` bounding the read of the request head +/// (and any small buffered body), then clears the socket read timeout before +/// returning `Ok(Some(_))`. +/// +/// `SO_RCVTIMEO` applies to the underlying kernel socket on both Linux and +/// macOS, so clearing it here clears it for cloned handles (`w`, +/// `forward_stdin`, USB passthrough) as well. +pub fn read_request_with_timeout( + r: &mut BufReader, + timeout: std::time::Duration, + stream: impl Fn(&str, &str) -> bool, +) -> io::Result> { + r.get_ref().set_read_timeout(Some(timeout))?; + let res = read_request(r, stream); + if matches!(res, Ok(Some(_))) { + r.get_ref().set_read_timeout(None)?; + } + res +} + /// Reads the next request on a connection. `Ok(None)` is a clean close. /// When `stream(method, path)` is true the body stays unread: the handler /// reads it through [`Body`]. pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) -> bool) -> io::Result> { + SERVING.with(|s| *s.borrow_mut() = (String::new(), String::new())); + CLOSING.with(|c| c.set(false)); + PENDING_CONTINUE.with(|c| c.set(false)); // The request line and headers are read through a cap, so a client // cannot exhaust memory with an endless line. The body is read after. let (method, path, api_version, query, headers, http10) = { @@ -119,13 +180,24 @@ pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) - if head.read_line(&mut line)? == 0 { return Ok(None); } - let mut parts = line.split_whitespace(); - let (Some(method), Some(target)) = (parts.next(), parts.next()) else { + let Some(req_line) = line.strip_suffix('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) else { return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); }; - let http10 = parts.next().is_some_and(|v| v.eq_ignore_ascii_case("HTTP/1.0")); + let mut parts = req_line.split(' '); + let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); + }; + if [method, target, version].iter().any(|p| p.is_empty() || p.chars().any(|c| c.is_ascii_control() || c.is_whitespace())) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); + } + if !version.eq_ignore_ascii_case("HTTP/1.1") && !version.eq_ignore_ascii_case("HTTP/1.0") { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request line")); + } + let http10 = version.eq_ignore_ascii_case("HTTP/1.0"); let method = method.to_owned(); - let (raw_path, raw_query) = target.split_once('?').unwrap_or((target, "")); + let Some((raw_path, raw_query)) = parse_target(target) else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad request target")); + }; // Decoded once, here, so every route that reads a name from the // path — an image's `%2F` repository slash above all — resolves the // name, not its encoding, as Docker's router does. @@ -144,55 +216,241 @@ pub fn read_request(r: &mut BufReader, stream: impl Fn(&str, &str) - loop { line.clear(); if head.read_line(&mut line)? == 0 { - return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "headers too large or cut short")); + let kind = if head.limit() == 0 { io::ErrorKind::InvalidData } else { io::ErrorKind::UnexpectedEof }; + return Err(io::Error::new(kind, "headers too large or cut short")); } - let l = line.trim_end(); + let Some(l) = line.strip_suffix('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) else { + let kind = if head.limit() == 0 { io::ErrorKind::InvalidData } else { io::ErrorKind::UnexpectedEof }; + return Err(io::Error::new(kind, "headers too large or cut short")); + }; if l.is_empty() { break; } - if let Some((k, v)) = l.split_once(':') { - headers.push((k.trim().to_owned(), v.trim().to_owned())); + // RFC 9112 §5.1 / §5.2: reject obs-fold (leading whitespace), + // lines without ':', empty or non-token field-names (including + // whitespace before ':'), and control characters in values. + if l.starts_with([' ', '\t']) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad header")); } + let Some((k, v)) = l.split_once(':') else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad header")); + }; + if k.is_empty() || !k.bytes().all(is_tchar) || v.bytes().any(is_ctl) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad header")); + } + headers.push((k.to_owned(), v.trim_matches([' ', '\t']).to_owned())); } (method, path, api_version, query, headers, http10) }; let streamed = stream(&method, &path); - let mut req = Request { method, path, api_version, query, headers, body: Vec::new(), http10, streamed: Cell::new(Streamed::No) }; + let mut req = Request { method, path, api_version, query, headers, body: Vec::new(), http10, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) }; + let body_framing = framing(&req)?; + if !streamed && matches!(body_framing, Framing::Length(len) if len > MAX_BODY as u64) { + return Ok(Some(too_large(req))); + } + let wants_continue = !req.http10 && req.expects_continue() && !matches!(body_framing, Framing::None); if streamed { - req.streamed.set(Streamed::Unread); + // Defer `100 Continue` until the handler actually reads the streamed + // body (RFC 9110 §10.1.1), so early 4xx rejections close without + // asking the client to upload a multi-GB archive. + req.needs_continue.set(wants_continue); + req.streamed.set(if matches!(body_framing, Framing::None) { Streamed::Done } else { Streamed::Unread }); return Ok(Some(req)); } - if req.header("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) { - let mut line = String::new(); - loop { - line.clear(); - // A chunk-size line is short hex (plus an optional ;extension). - (&mut *r).take(64).read_line(&mut line)?; - let size = line.trim().split(';').next().unwrap_or(""); - let n = usize::from_str_radix(size, 16) - .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; - if n > MAX_BODY || req.body.len().checked_add(n).is_none_or(|t| t > MAX_BODY) { - return Ok(Some(too_large(req))); - } - let start = req.body.len(); - req.body.resize(start + n, 0); - r.read_exact(&mut req.body[start..])?; - let mut crlf = [0u8; 2]; - r.read_exact(&mut crlf)?; + // RFC 9110 §10.1.1: an HTTP/1.1 client sending `Expect: 100-continue` + // waits for `100 Continue` before transmitting the body (as .NET's + // HttpClient and curl do on large uploads). HTTP/1.0 requests, bodiless + // requests, and already-rejected requests must not get a 100 response. + if wants_continue { + let w = r.get_mut(); + w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?; + w.flush()?; + } + match body_framing { + Framing::None => {} + Framing::Chunked => loop { + let n = read_chunk_len(r)?; + // A zero chunk has no data and no CRLF of its own: its line's + // CRLF is already read, and the trailer section follows + // (RFC 9112 §7.1.2). if n == 0 { + read_trailers(r)?; break; } + if n > MAX_BODY as u64 || req.body.len().checked_add(n as usize).is_none_or(|t| t > MAX_BODY) { + return Ok(Some(too_large(req))); + } + let want = n as usize; + req.body.reserve(want.min(INITIAL_BODY_CAP)); + let got = (&mut *r).take(n).read_to_end(&mut req.body)?; + if got != want { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); + } + read_chunk_crlf(r)?; + }, + Framing::Length(len) => { + let want = len as usize; + req.body = Vec::with_capacity(want.min(INITIAL_BODY_CAP)); + let got = (&mut *r).take(len).read_to_end(&mut req.body)?; + if got != want { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); + } } - } else if let Some(len) = req.header("content-length").and_then(|v| v.parse::().ok()) { - if len > MAX_BODY { - return Ok(Some(too_large(req))); - } - req.body.resize(len, 0); - r.read_exact(&mut req.body)?; } Ok(Some(req)) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Framing { + None, + Chunked, + Length(u64), +} + +/// Validates and determines request body framing per RFC 9112 §6.1 & §6.3. +/// Rejects conflicting `Transfer-Encoding` + `Content-Length` headers, +/// unsupported transfer codings, and malformed or conflicting `Content-Length` +/// values with `InvalidData` so the connection answers 400 and closes. +fn framing(req: &Request) -> io::Result { + let mut has_te = false; + let mut te = Vec::new(); + for (_, raw) in req.headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case("transfer-encoding")) { + has_te = true; + for part in raw.split(',') { + let s = part.trim(); + if !s.is_empty() { + te.push(s); + } + } + } + let has_cl = req.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("content-length")); + if has_te { + if has_cl { + return Err(io::Error::new(io::ErrorKind::InvalidData, "conflicting transfer-encoding and content-length")); + } + if req.http10 { + return Err(io::Error::new(io::ErrorKind::InvalidData, "transfer-encoding is not valid in HTTP/1.0")); + } + if te.len() == 1 && te[0].eq_ignore_ascii_case("chunked") { + return Ok(Framing::Chunked); + } + return Err(io::Error::new(io::ErrorKind::InvalidData, "unsupported transfer-encoding")); + } + let mut len: Option = None; + for (_, raw) in req.headers.iter().filter(|(k, _)| k.eq_ignore_ascii_case("content-length")) { + for part in raw.split(',') { + let s = part.trim(); + if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad content-length")); + } + let n = s.parse::().map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad content-length"))?; + if let Some(prev) = len && prev != n { + return Err(io::Error::new(io::ErrorKind::InvalidData, "conflicting content-length")); + } + len = Some(n); + } + } + Ok(match len { + None | Some(0) => Framing::None, + Some(n) => Framing::Length(n), + }) +} + +fn read_chunk_len(r: &mut BufReader) -> io::Result { + let mut line = Vec::new(); + let mut lim = (&mut *r).take(MAX_CHUNK_LINE); + if lim.read_until(b'\n', &mut line)? == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); + } + let Some(raw) = line.strip_suffix(b"\n") else { + let (kind, msg) = if lim.limit() == 0 { + (io::ErrorKind::InvalidData, "chunk size line too large") + } else { + (io::ErrorKind::UnexpectedEof, "request body cut short") + }; + return Err(io::Error::new(kind, msg)); + }; + let Some(raw) = raw.strip_suffix(b"\r") else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk size line")); + }; + // A chunk size may carry extensions after a semicolon (RFC 9112 §7.1.1); + // reject control characters (including NUL and bare CR) in any extension. + let (size, ext) = match raw.iter().position(|&b| b == b';') { + Some(i) => (&raw[..i], Some(&raw[i + 1..])), + None => (raw, None), + }; + if let Some(ext) = ext && ext.iter().any(|&b| is_ctl(b)) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk extension")); + } + let size = &size[..size.iter().rposition(|b| !matches!(b, b' ' | b'\t')).map_or(0, |i| i + 1)]; + if size.is_empty() || !size.iter().all(|b| b.is_ascii_hexdigit()) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk size")); + } + let s = std::str::from_utf8(size).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; + u64::from_str_radix(s, 16).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size")) +} + +fn read_chunk_crlf(r: &mut BufReader) -> io::Result<()> { + let mut crlf = [0u8; 2]; + r.read_exact(&mut crlf)?; + if crlf != *b"\r\n" { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk delimiter")); + } + Ok(()) +} + +fn is_tchar(b: u8) -> bool { + b.is_ascii_alphanumeric() + || matches!(b, b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+' | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~') +} + +/// Control characters disallowed in HTTP field values and chunk extensions: +/// C0 controls except HTAB (`0x09`), plus DEL (`0x7F`). +fn is_ctl(b: u8) -> bool { + (b < 0x20 && b != b'\t') || b == 0x7f +} + +/// Reads out a chunked body's trailer section: trailer header lines until the +/// terminating blank line (RFC 9112 §7.1.2). Bounded in total bytes and line +/// count so an endless trailer section cannot exhaust memory or hang. +fn read_trailers(r: &mut BufReader) -> io::Result<()> { + let mut lim = (&mut *r).take(MAX_TRAILERS); + let mut line = Vec::new(); + let mut count = 0usize; + loop { + line.clear(); + if lim.read_until(b'\n', &mut line)? == 0 { + let (kind, msg) = if lim.limit() == 0 { + (io::ErrorKind::InvalidData, "trailers too large") + } else { + (io::ErrorKind::UnexpectedEof, "trailers cut short") + }; + return Err(io::Error::new(kind, msg)); + } + let Some(raw) = line.strip_suffix(b"\n") else { + let (kind, msg) = if lim.limit() == 0 { + (io::ErrorKind::InvalidData, "trailers too large") + } else { + (io::ErrorKind::UnexpectedEof, "trailers cut short") + }; + return Err(io::Error::new(kind, msg)); + }; + let Some(raw) = raw.strip_suffix(b"\r") else { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad trailer line")); + }; + if raw.is_empty() { + return Ok(()); + } + count += 1; + if count > MAX_TRAILER_LINES { + return Err(io::Error::new(io::ErrorKind::InvalidData, "too many trailer headers")); + } + if !raw.iter().position(|&b| b == b':').is_some_and(|i| i > 0 && raw[..i].iter().all(|&b| is_tchar(b)) && !raw[i + 1..].iter().any(|&b| is_ctl(b))) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad trailer header")); + } + } +} + /// A request whose body is past [`MAX_BODY`]: what was read of it is dropped /// and the rest stays unread, for the connection's [`close`] to read out. fn too_large(mut req: Request) -> Request { @@ -215,17 +473,41 @@ pub fn refuse_too_large(req: &Request, w: &mut UnixStream, r: &mut BufReader, message: &str) -> io::Result<()> { + SERVING.with(|s| *s.borrow_mut() = (String::new(), String::new())); + let sent = error_closing(w, 400, message); + close(w, r); + sent +} + +/// Sends `HTTP/1.1 100 Continue` if this request is still waiting on one, +/// clearing the pending flag so it is emitted at most once. Handlers that +/// stream a final response header before reading [`Body`] (such as `POST /build`) +/// call this right before starting the response. +pub fn send_continue(req: &Request, r: &mut BufReader) -> io::Result<()> { + if req.needs_continue.get() { + let w = r.get_mut(); + w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?; + w.flush()?; + req.needs_continue.set(false); + PENDING_CONTINUE.with(|c| c.set(false)); + } + Ok(()) +} + /// After a streamed request's response: whether the connection can serve /// the client's next request. A body its handler left unread (a pull sent /// with one, as docker-modem sends its options) is read out first, up to /// [`MAX_UNREAD`], or its bytes would be taken for the next request's head. -/// One read partly, too large, or held back for a `100 Continue` the daemon -/// never sends cannot be; the connection closes. +/// One read partly, too large, or waiting on an unsent `100 Continue` cannot +/// be; the connection closes. pub fn finish_body(req: &Request, r: &mut BufReader) -> bool { match req.streamed.get() { Streamed::No | Streamed::Done => true, Streamed::Started | Streamed::TooLarge => false, - Streamed::Unread if req.header("expect").is_some_and(|v| v.eq_ignore_ascii_case("100-continue")) => false, + Streamed::Unread if req.needs_continue.get() => false, Streamed::Unread => { let mut body = Body::new(req, r); io::copy(&mut (&mut body).take(MAX_UNREAD), &mut io::sink()).is_ok() && body.read(&mut [0; 1]).is_ok_and(|n| n == 0) @@ -281,38 +563,64 @@ pub struct Body<'a> { /// Bytes left in the body (or in the current chunk). left: u64, done: bool, + bad: Option, /// The request's record of how far its body was read. progress: &'a Cell, + /// Whether `100 Continue` still needs to be written on first read. + needs_continue: &'a Cell, } impl<'a> Body<'a> { pub fn new(req: &'a Request, r: &'a mut BufReader) -> Body<'a> { - let chunked = req.header("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")); - let left = if chunked { 0 } else { req.header("content-length").and_then(|v| v.parse().ok()).unwrap_or(0) }; - let done = !chunked && left == 0; - req.streamed.set(if done { Streamed::Done } else { Streamed::Started }); - Body { r, chunked, left, done, progress: &req.streamed } + match framing(req) { + Ok(Framing::None) => { + req.streamed.set(Streamed::Done); + Body { r, chunked: false, left: 0, done: true, bad: None, progress: &req.streamed, needs_continue: &req.needs_continue } + } + Ok(Framing::Chunked) => { + Body { r, chunked: true, left: 0, done: false, bad: None, progress: &req.streamed, needs_continue: &req.needs_continue } + } + Ok(Framing::Length(n)) => { + Body { r, chunked: false, left: n, done: false, bad: None, progress: &req.streamed, needs_continue: &req.needs_continue } + } + Err(e) => { + req.streamed.set(Streamed::Started); + Body { r, chunked: false, left: 0, done: false, bad: Some(e.kind()), progress: &req.streamed, needs_continue: &req.needs_continue } + } + } } } impl Read for Body<'_> { fn read(&mut self, buf: &mut [u8]) -> io::Result { + if let Some(kind) = self.bad { + return Err(io::Error::new(kind, "bad request framing")); + } if self.done || buf.is_empty() { return Ok(0); } + self.progress.set(Streamed::Started); + if self.needs_continue.get() { + let w = self.r.get_mut(); + if let Err(e) = w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n").and_then(|()| w.flush()) { + self.bad = Some(e.kind()); + return Err(e); + } + self.needs_continue.set(false); + PENDING_CONTINUE.with(|c| c.set(false)); + } if self.chunked && self.left == 0 { - let mut line = String::new(); - self.r.read_line(&mut line)?; - // A chunk size may carry extensions after a semicolon. - let size = line.trim().split(';').next().unwrap_or(""); - self.left = u64::from_str_radix(size, 16).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; + self.left = match read_chunk_len(self.r) { + Ok(n) => n, + Err(e) => { + self.bad = Some(e.kind()); + return Err(e); + } + }; if self.left == 0 { - // Trailers, then the blank line. - loop { - line.clear(); - if self.r.read_line(&mut line)? == 0 || line.trim().is_empty() { - break; - } + if let Err(e) = read_trailers(self.r) { + self.bad = Some(e.kind()); + return Err(e); } self.done = true; self.progress.set(Streamed::Done); @@ -322,13 +630,16 @@ impl Read for Body<'_> { let want = buf.len().min(self.left.min(usize::MAX as u64) as usize); let n = self.r.read(&mut buf[..want])?; if n == 0 { + self.bad = Some(io::ErrorKind::UnexpectedEof); return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "request body cut short")); } self.left -= n as u64; if self.left == 0 { if self.chunked { - let mut crlf = [0u8; 2]; - self.r.read_exact(&mut crlf)?; + if let Err(e) = read_chunk_crlf(self.r) { + self.bad = Some(e.kind()); + return Err(e); + } } else { self.done = true; self.progress.set(Streamed::Done); @@ -338,6 +649,50 @@ impl Read for Body<'_> { } } +/// Splits an RFC 9112 §3.2.1 `origin-form` or §3.2.2 `absolute-form` +/// request-target into `(path, query)`. Clients such as docker-modem send +/// `GET http://127.0.0.1:2376/containers/json HTTP/1.1` over the Unix socket +/// or named pipe when configured with a default host and port (#757). +fn parse_target(target: &str) -> Option<(&str, &str)> { + if target.contains('#') { + return None; + } + if target.starts_with('/') { + return Some(target.split_once('?').unwrap_or((target, ""))); + } + let (scheme, rest) = target.split_once("://")?; + if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") { + return None; + } + let (authority, tail) = match rest.find(['/', '?']) { + Some(i) => (&rest[..i], &rest[i..]), + None => (rest, ""), + }; + if !valid_authority(authority) { + return None; + } + match tail.strip_prefix('?') { + Some(q) => Some(("/", q)), + None if tail.is_empty() => Some(("/", "")), + None => Some(tail.split_once('?').unwrap_or((tail, ""))), + } +} + +fn valid_authority(authority: &str) -> bool { + let valid_port = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) && p.parse::().is_ok_and(|n| n > 0); + if let Some(rest) = authority.strip_prefix('[') { + let Some((v6, after)) = rest.split_once(']') else { return false }; + return v6.parse::().is_ok() && (after.is_empty() || after.strip_prefix(':').is_some_and(valid_port)); + } + let (host, port) = match authority.split_once(':') { + Some((h, p)) => (h, Some(p)), + None => (authority, None), + }; + !host.is_empty() + && host.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_')) + && port.is_none_or(valid_port) +} + /// `/v1.47/containers/json` → `/containers/json`. fn strip_version(path: &str) -> &str { if let Some(rest) = path.strip_prefix("/v") @@ -394,6 +749,7 @@ fn reason(status: u16) -> &'static str { 204 => "No Content", 304 => "Not Modified", 400 => "Bad Request", + 403 => "Forbidden", 404 => "Not Found", 409 => "Conflict", 413 => "Request Entity Too Large", @@ -409,6 +765,9 @@ thread_local! { /// Whether the connection closes after the request being answered: its /// response then says so (`Connection: close`), as Docker's does. static CLOSING: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Whether the streamed request being answered still has an unsent + /// `100 Continue`: answering before reading the body closes the connection. + static PENDING_CONTINUE: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Notes the request being answered: a failure status written for it is @@ -417,6 +776,7 @@ thread_local! { pub fn serving(req: &Request) { SERVING.with(|s| *s.borrow_mut() = (req.method.clone(), req.path.clone())); CLOSING.with(|c| c.set(req.wants_close())); + PENDING_CONTINUE.with(|c| c.set(req.needs_continue.get())); } /// Engine API failures in the log: 5xx as errors, 4xx as warnings, except @@ -424,20 +784,33 @@ pub fn serving(req: &Request) { fn note_failure(status: u16) { SERVING.with(|s| { let (method, path) = &*s.borrow(); - match status { - 404 => crate::diag::debug!("request failed", method = method, path = path, status = status), - 400..=499 => crate::diag::warn!("request failed", method = method, path = path, status = status), - _ => crate::diag::error!("request failed", method = method, path = path, status = status), + if method.is_empty() && path.is_empty() { + match status { + 404 => crate::diag::debug!("request failed", status = status), + 400..=499 => crate::diag::warn!("request failed", status = status), + _ => crate::diag::error!("request failed", status = status), + } + } else { + match status { + 404 => crate::diag::debug!("request failed", method = method, path = path, status = status), + 400..=499 => crate::diag::warn!("request failed", method = method, path = path, status = status), + _ => crate::diag::error!("request failed", method = method, path = path, status = status), + } } }); } +#[cfg(test)] +pub fn current_serving() -> (String, String) { + SERVING.with(|s| s.borrow().clone()) +} + fn head(w: &mut impl Write, status: u16, extra: &str) -> io::Result<()> { if status >= 400 { note_failure(status); } // A response that names its own Connection (an upgrade, `CLOSE`) keeps it. - let closing = if CLOSING.with(std::cell::Cell::get) && !extra.contains("Connection:") { CLOSE } else { "" }; + let closing = if (CLOSING.with(std::cell::Cell::get) || PENDING_CONTINUE.with(std::cell::Cell::get)) && !extra.contains("Connection:") { CLOSE } else { "" }; write!( w, "HTTP/1.1 {status} {}\r\nApi-Version: {API_VERSION}\r\nDocker-Experimental: false\r\nOstype: linux\r\nServer: Kiri/{} (linux)\r\n{extra}{closing}\r\n", @@ -529,6 +902,13 @@ pub fn upgrade(w: &mut impl Write) -> io::Result<()> { w.flush() } +/// Switches the connection to HTTP/2 cleartext (`h2c`) for BuildKit's `/grpc` +/// and `/session` endpoints. +pub fn upgrade_h2c(w: &mut impl Write) -> io::Result<()> { + head(w, 101, "Connection: Upgrade\r\nUpgrade: h2c\r\n")?; + w.flush() +} + /// Starts the raw stream for Docker's `attach` and `exec` start. As Docker /// does (it checks that the `Upgrade` header is present, not its value), a /// client that asked for the upgrade (the docker CLI) gets `101`; one that did @@ -560,7 +940,7 @@ mod tests { fn with_connection(value: Option<&str>) -> Request { let headers = value.map(|v| vec![("connection".to_owned(), v.to_owned())]).unwrap_or_default(); - Request { method: "POST".to_owned(), path: "/containers/x/start".to_owned(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, streamed: Cell::new(Streamed::No) } + Request { method: "POST".to_owned(), path: "/containers/x/start".to_owned(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) } } /// A request as `read_request` reads it off the wire. @@ -696,13 +1076,100 @@ mod tests { assert_eq!(path_of("/images/100%/json"), "/images/100%/json"); } + /// Clients such as docker-modem send an RFC 9112 §3.2.2 absolute-form + /// request-target over the Unix socket or named pipe when configured with + /// a default host and port (#757). + #[test] + fn reads_absolute_form_request_targets() { + use std::io::Write; + let try_parse = |target: &str| { + let (mut a, b) = UnixStream::pair().unwrap(); + a.write_all(format!("GET {target} HTTP/1.1\r\nHost: 127.0.0.1:2376\r\n\r\n").as_bytes()) + .unwrap(); + drop(a); + read_request(&mut BufReader::new(b), |_, _| false) + }; + + let req = try_parse("http://127.0.0.1:2376/containers/json?all=1").unwrap().unwrap(); + assert_eq!(req.path, "/containers/json"); + assert_eq!(req.api_version, None); + assert_eq!(req.query("all"), Some("1")); + + let req = try_parse("HTTP://[::1]:2375/v1.47/version").unwrap().unwrap(); + assert_eq!(req.path, "/version"); + assert_eq!(req.api_version, Some((1, 47))); + + let req = try_parse("https://docker:2376/_ping").unwrap().unwrap(); + assert_eq!(req.path, "/_ping"); + assert_eq!(req.api_version, None); + + let req = try_parse("http://localhost:2375").unwrap().unwrap(); + assert_eq!(req.path, "/"); + assert!(req.query.is_empty()); + + let req = try_parse("http://localhost:2375?foo=bar").unwrap().unwrap(); + assert_eq!(req.path, "/"); + assert_eq!(req.query("foo"), Some("bar")); + + let req = try_parse("http://127.0.0.1:2376//v1.47/containers/json").unwrap().unwrap(); + assert_eq!(req.path, "//v1.47/containers/json"); + assert_eq!(req.api_version, None); + + let req = try_parse("http://127.0.0.1:2376/v1.44/images/mongodb%2Fmongodb-atlas-local:8.0/json").unwrap().unwrap(); + assert_eq!(req.path, "/images/mongodb/mongodb-atlas-local:8.0/json"); + assert_eq!(req.api_version, Some((1, 44))); + + for bad in [ + "http:///containers/json", + "https:///containers/json", + "http://", + "http://?a=1", + "ftp://127.0.0.1:2376/_ping", + "unix:///var/run/docker.sock", + "http:/containers/json", + "containers/json", + "http://:2376/_ping", + "http://127.0.0.1:/_ping", + "http://127.0.0.1:99999/_ping", + "http://[::1/_ping", + "http://[not-an-ip]/_ping", + "http://user@127.0.0.1:2376/_ping", + "http://127.0.0.1:2376/_ping#frag", + "/_ping#frag", + "http://127.0.0.1:2376/containers/json extra", + "/_ping\u{00a0}extra", + "/_ping\x7f", + ] { + assert!(try_parse(bad).is_err(), "accepted malformed target: {bad}"); + } + + let try_raw = |raw: &str| { + let (mut a, b) = UnixStream::pair().unwrap(); + a.write_all(raw.as_bytes()).unwrap(); + drop(a); + read_request(&mut BufReader::new(b), |_, _| false) + }; + for bad_line in [ + "GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + "GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + " GET http://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + "GET http://127.0.0.1:2376/_ping HTTP/1.1 \r\nHost: d\r\n\r\n", + "GET\thttp://127.0.0.1:2376/_ping HTTP/1.1\r\nHost: d\r\n\r\n", + "GET http://127.0.0.1:2376/_ping\tHTTP/1.1\r\nHost: d\r\n\r\n", + "GET HTTP/1.1\r\nHost: d\r\n\r\n", + "GET /_ping HTTP/2.0\r\nHost: d\r\n\r\n", + ] { + assert!(try_raw(bad_line).is_err(), "accepted malformed request line: {bad_line:?}"); + } + } + /// `attach` and `exec` start answer `101` only to a client that asked to /// upgrade (the docker CLI). docker-java, so Testcontainers, does not, and /// gets `200 OK` with the raw stream as the body, as from Docker. #[test] fn upgrades_only_when_asked() { let reply = |headers: Vec<(String, String)>| { - let req = Request { method: "POST".into(), path: "/exec/x/start".into(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, streamed: Cell::new(Streamed::No) }; + let req = Request { method: "POST".into(), path: "/exec/x/start".into(), api_version: None, query: Vec::new(), headers, body: Vec::new(), http10: false, needs_continue: Cell::new(false), streamed: Cell::new(Streamed::No) }; let mut out = Vec::new(); upgrade_if_asked(&req, &mut out).unwrap(); String::from_utf8(out).unwrap() @@ -717,4 +1184,461 @@ mod tests { assert!(plain.contains("Content-Type: application/vnd.docker.raw-stream\r\n"), "{plain}"); assert!(!plain.contains("Upgrade"), "{plain}"); } + + fn sock(bytes: &[u8]) -> BufReader { + let (mut a, b) = UnixStream::pair().unwrap(); + let data = bytes.to_vec(); + // Write on a helper thread so payloads larger than macOS's 8 KiB + // UnixStream socket buffer never deadlock before the reader starts. + std::thread::spawn(move || { + let _ = a.write_all(&data); + }); + BufReader::new(b) + } + + /// Chunked bodies (both buffered and streamed) consume their full trailer + /// section and closing blank line (RFC 9112 §7.1.2) so pipelined keep-alive + /// requests start at the exact next request line (#745). + #[test] + fn chunked_trailers_preserve_keep_alive_boundaries() { + let head = "POST /containers/create HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n"; + let ping = "GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"; + for tail in [ + "\r\n", + "X-Checksum: 1\r\n\r\n", + "X-Checksum: deadbeef\r\nX-Signature: sig-v1\r\nX-Time: 12:34:56\r\n\r\n", + ] { + let raw = format!("{head}{tail}{ping}"); + let mut r = sock(raw.as_bytes()); + let first = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!(first.body, b"{}", "{tail:?}"); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!((second.method.as_str(), second.path.as_str()), ("GET", "/_ping"), "{tail:?}"); + } + + // Chunk extensions + multiple chunks + multi-line trailers on both + // buffered and streamed endpoints, plus a zero-length chunked body. + let streamed_raw = concat!( + "PUT /containers/abc/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n", + "5;ext=1\r\nhello\r\n", + "6\r\n world\r\n", + "0;last=yes\r\n", + "X-Checksum: sha256:abc\r\n", + "X-Trailer-Two: ok\r\n", + "\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n", + ); + let mut r = sock(streamed_raw.as_bytes()); + let first = read_request(&mut r, |m, p| m == "PUT" && p.ends_with("/archive")).unwrap().unwrap(); + let mut data = Vec::new(); + Body::new(&first, &mut r).read_to_end(&mut data).unwrap(); + assert_eq!(data, b"hello world"); + assert!(finish_body(&first, &mut r)); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!((second.method.as_str(), second.path.as_str()), ("GET", "/_ping")); + + let empty_chunked = "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0\r\nX-Empty: 1\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n"; + let mut r = sock(empty_chunked.as_bytes()); + let first = read_request(&mut r, |_, p| p == "/images/load").unwrap().unwrap(); + let mut data = Vec::new(); + Body::new(&first, &mut r).read_to_end(&mut data).unwrap(); + assert!(data.is_empty()); + assert!(finish_body(&first, &mut r)); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + assert_eq!((second.method.as_str(), second.path.as_str()), ("GET", "/_ping")); + } + + /// Trailer sections and chunk framing are bounded and validated in both + /// buffered and streamed paths so endless, oversized, truncated, or + /// malformed trailers and chunk delimiters fail cleanly (#745). + #[test] + fn chunked_trailers_and_delimiters_are_bounded_and_validated() { + let prefix = "POST /containers/create HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n2\r\n{}\r\n0\r\n"; + + // Single giant trailer line past MAX_TRAILERS -> InvalidData. + let giant = format!("{prefix}X-Big: {}\r\n\r\n", "a".repeat(MAX_TRAILERS as usize + 64)); + assert_eq!(read_request(&mut sock(giant.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Many trailer lines summing past MAX_TRAILERS -> InvalidData. + let mut many_bytes = String::from(prefix); + for i in 0..100 { + many_bytes.push_str(&format!("X-Pad-{i:03}: {}\r\n", "b".repeat(100))); + } + many_bytes.push_str("\r\n"); + assert_eq!(read_request(&mut sock(many_bytes.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Exceeding MAX_TRAILER_LINES even while well under MAX_TRAILERS -> InvalidData. + let mut many_lines = String::from(prefix); + for i in 0..=MAX_TRAILER_LINES { + many_lines.push_str(&format!("X-{i}: 1\r\n")); + } + many_lines.push_str("\r\n"); + assert!(many_lines.len() < MAX_TRAILERS as usize + prefix.len()); + assert_eq!(read_request(&mut sock(many_lines.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + + // Same oversized-trailer rejection on the streamed Body path. + let streamed_big = format!( + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-Big: {}\r\n\r\n", + "z".repeat(MAX_TRAILERS as usize + 16), + ); + let mut r = sock(streamed_big.as_bytes()); + let req = read_request(&mut r, |_, p| p == "/images/load").unwrap().unwrap(); + assert_eq!(Body::new(&req, &mut r).read_to_end(&mut Vec::new()).unwrap_err().kind(), io::ErrorKind::InvalidData); + assert!(!finish_body(&req, &mut r)); + + // Truncated trailers hit UnexpectedEof and prevent keep-alive reuse. + for cut_raw in [ + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-Incomplete: 1", + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nX-Incomplete: 1\r\n", + "POST /images/load HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n", + ] { + let mut r = sock(cut_raw.as_bytes()); + let req = read_request(&mut r, |_, p| p == "/images/load").unwrap().unwrap(); + assert_eq!(Body::new(&req, &mut r).read_to_end(&mut Vec::new()).unwrap_err().kind(), io::ErrorKind::UnexpectedEof, "{cut_raw:?}"); + assert!(!finish_body(&req, &mut r)); + } + + // Malformed trailer headers, bad chunk delimiters, funky-chunk bare LF + // lines, control characters in chunk extensions/trailers, and invalid sizes. + let huge_ext = format!( + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0;{}\r\n\r\n", + "e".repeat(MAX_CHUNK_LINE as usize + 16), + ); + for bad in [ + format!("{prefix}GET /_ping HTTP/1.1\r\n\r\n"), + format!("{prefix}: missing-name\r\n\r\n"), + format!("{prefix}X-T: 1\n\r\n"), + format!("{prefix}\n"), + format!("{prefix}X-T: a\rb\r\n\r\n"), + format!("{prefix}X-T: a\0b\r\n\r\n"), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhelloXX0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n+5\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n 5\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=1\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=a\rb\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext\r\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\0x\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\x01\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\x1f\r\nhello\r\n0\r\n\r\n".to_owned(), + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\x7f\r\nhello\r\n0\r\n\r\n".to_owned(), + huge_ext, + ] { + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData, "buffered: {bad:?}"); + let mut r = sock(bad.as_bytes()); + let req = read_request(&mut r, |_, _| true).unwrap().unwrap(); + assert_eq!(Body::new(&req, &mut r).read_to_end(&mut Vec::new()).unwrap_err().kind(), io::ErrorKind::InvalidData, "streamed: {bad:?}"); + } + + // HTAB in chunk extensions remains valid per RFC 9112 §7.1.1. + let htab_ext = "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5;ext=\t1\r\nhello\r\n0\r\n\r\n"; + let req = read_request(&mut sock(htab_ext.as_bytes()), |_, _| false).unwrap().unwrap(); + assert_eq!(req.body, b"hello"); + + // Truncated buffered Content-Length and chunked bodies return UnexpectedEof. + for short in [ + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 10\r\n\r\nabc", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 8388608\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhel", + ] { + assert_eq!(read_request(&mut sock(short.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::UnexpectedEof, "{short:?}"); + } + } + + /// RFC 9112 §5.1 / §5.2: malformed header lines (obs-fold leading whitespace, + /// missing ':', whitespace before ':', empty or non-token field names, and + /// control characters in values) are rejected with InvalidData. + #[test] + fn rejects_malformed_header_lines() { + for bad in [ + "POST /x HTTP/1.1\r\nHost: d\r\n Transfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\n\tTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding : chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding\t: chunked\r\n\r\n0\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nNoColonHeader\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\n \r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\n: value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nBad Name: value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nBad(Name): value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nBad\0Name: value\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nX-Foo: a\rb\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nX-Foo: a\0b\r\n\r\n", + "GET /_ping HTTP/1.1\r\nHost: d\r\nX-Foo: a\x7fb\r\n\r\n", + ] { + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData, "buffered: {bad:?}"); + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| true).unwrap_err().kind(), io::ErrorKind::InvalidData, "streamed: {bad:?}"); + } + + // Valid headers with OWS tabs/spaces around values and empty values pass. + let ok = parsed("GET /_ping HTTP/1.1\r\nHost: d\r\nX-Empty:\r\nX-Tab: \tval \t\r\n\r\n"); + assert_eq!(ok.header("X-Empty"), Some("")); + assert_eq!(ok.header("X-Tab"), Some("val")); + } + + /// HTTP/1.1 requests with `Expect: 100-continue` receive `HTTP/1.1 100 Continue` + /// eagerly for buffered bodies and lazily on first `Body` read for streamed + /// routes (so early 4xx rejections never ask the client to upload), while + /// HTTP/1.0, bodiless, and oversized requests never receive 100 Continue (#134). + #[test] + fn expect_100_continue_handshakes_before_reading_body() { + use std::sync::mpsc; + use std::time::Duration; + + // 1. Buffered Content-Length: client waits for 100 Continue before writing body. + { + let (mut client, server) = UnixStream::pair().unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let t = std::thread::spawn(move || { + let mut r = BufReader::new(server); + let first = read_request(&mut r, |_, _| false).unwrap().unwrap(); + let second = read_request(&mut r, |_, _| false).unwrap().unwrap(); + (first.body, second.method, second.path) + }); + client.write_all(b"POST /containers/create HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 11\r\n\r\n").unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + client.write_all(b"{\"a\":12345}GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + drop(client); + let (body, m, p) = t.join().unwrap(); + assert_eq!(body, b"{\"a\":12345}"); + assert_eq!((m.as_str(), p.as_str()), ("GET", "/_ping")); + } + + // 2. Streamed chunked upload (as .NET/curl send for PUT /archive) with trailers: + // read_request does NOT emit 100 Continue; Body::read emits it lazily. + { + let (mut client, server) = UnixStream::pair().unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let (head_done_tx, head_done_rx) = mpsc::channel(); + let (go_read_tx, go_read_rx) = mpsc::channel(); + let t = std::thread::spawn(move || { + let mut r = BufReader::new(server); + let req = read_request(&mut r, |m, p| m == "PUT" && p.ends_with("/archive")).unwrap().unwrap(); + assert!(req.needs_continue()); + head_done_tx.send(()).unwrap(); + go_read_rx.recv().unwrap(); + let mut data = Vec::new(); + Body::new(&req, &mut r).read_to_end(&mut data).unwrap(); + assert!(!req.needs_continue()); + assert!(finish_body(&req, &mut r)); + let next = read_request(&mut r, |_, _| false).unwrap().unwrap(); + (data, next.path) + }); + client.write_all(b"PUT /containers/c/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nExpect: 100-Continue\r\nTransfer-Encoding: chunked\r\n\r\n").unwrap(); + head_done_rx.recv().unwrap(); + // Confirm nothing was written before the handler reads Body. + client.set_nonblocking(true).unwrap(); + let mut peek = [0u8; 1]; + assert_eq!(client.read(&mut peek).unwrap_err().kind(), io::ErrorKind::WouldBlock); + client.set_nonblocking(false).unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + go_read_tx.send(()).unwrap(); + let mut interim = [0u8; 25]; + client.read_exact(&mut interim).unwrap(); + assert_eq!(&interim, b"HTTP/1.1 100 Continue\r\n\r\n"); + client.write_all(b"7\r\ntarball\r\n0\r\nX-Hash: abc\r\n\r\nGET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + drop(client); + let (data, next_path) = t.join().unwrap(); + assert_eq!(data, b"tarball"); + assert_eq!(next_path, "/_ping"); + } + + // 3. Streamed unread body with Expect: 100-continue does NOT emit 100 Continue; + // answering adds Connection: close and finish_body closes the connection. + { + let (mut client, server) = UnixStream::pair().unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let t = std::thread::spawn(move || { + let mut w = server.try_clone().unwrap(); + let mut r = BufReader::new(server); + let req = read_request(&mut r, |m, p| m == "PUT" && p.ends_with("/archive")).unwrap().unwrap(); + assert!(req.needs_continue()); + serving(&req); + error(&mut w, 404, "No such container").unwrap(); + assert!(!finish_body(&req, &mut r)); + close(&w, &mut r); + }); + client.write_all(b"PUT /containers/missing/archive?path=/tmp HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 1073741824\r\n\r\n").unwrap(); + let mut reply = Vec::new(); + client.read_to_end(&mut reply).unwrap(); + drop(client); + t.join().unwrap(); + let reply = String::from_utf8_lossy(&reply); + assert!(reply.starts_with("HTTP/1.1 404 Not Found\r\n"), "{reply}"); + assert!(reply.contains("Connection: close\r\n"), "{reply}"); + assert!(!reply.contains("100 Continue"), "{reply}"); + } + + // 4. Oversized buffered body, HTTP/1.0, and bodiless requests must NOT send 100 Continue. + for (raw, check_too_large) in [ + (format!("POST /x HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: {}\r\n\r\n", MAX_BODY + 1), true), + ("POST /x HTTP/1.0\r\nExpect: 100-continue\r\nContent-Length: 2\r\n\r\n{}".to_owned(), false), + ("GET /_ping HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\n\r\n".to_owned(), false), + ("POST /x HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nContent-Length: 0\r\n\r\n".to_owned(), false), + ] { + let (mut client, server) = UnixStream::pair().unwrap(); + client.write_all(raw.as_bytes()).unwrap(); + client.shutdown(std::net::Shutdown::Write).unwrap(); + let req = read_request(&mut BufReader::new(server), |_, _| false).unwrap().unwrap(); + assert_eq!(req.too_large(), check_too_large, "{raw:?}"); + let mut reply = Vec::new(); + client.read_to_end(&mut reply).unwrap(); + assert!(reply.is_empty(), "unexpected 100 Continue for {raw:?}: {:?}", String::from_utf8_lossy(&reply)); + } + } + + /// Ambiguous Transfer-Encoding + Content-Length combinations and malformed + /// or conflicting Content-Length headers are rejected with InvalidData so + /// the server responds 400 Bad Request and closes the connection (#134). + #[test] + fn rejects_ambiguous_transfer_encoding_and_content_length_framing() { + for bad in [ + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\nContent-Length: 0\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: \r\nContent-Length: 5\r\n\r\nhello", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked, chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: gzip, chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: identity\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: \r\n\r\n", + "POST /x HTTP/1.0\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4\r\nContent-Length: 8\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4, 8\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 99999999999999999999999999999\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: -1\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: +4\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: abc\r\n\r\n", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: \r\n\r\n", + ] { + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData, "buffered accepted: {bad:?}"); + assert_eq!(read_request(&mut sock(bad.as_bytes()), |_, _| true).unwrap_err().kind(), io::ErrorKind::InvalidData, "streamed accepted: {bad:?}"); + } + + // TE+CL with Expect: 100-continue must reject without sending 100 Continue. + let (mut client, server) = UnixStream::pair().unwrap(); + client.write_all(b"POST /x HTTP/1.1\r\nHost: d\r\nExpect: 100-continue\r\nTransfer-Encoding: chunked\r\nContent-Length: 5\r\n\r\n").unwrap(); + client.shutdown(std::net::Shutdown::Write).unwrap(); + assert_eq!(read_request(&mut BufReader::new(server), |_, _| false).unwrap_err().kind(), io::ErrorKind::InvalidData); + let mut reply = Vec::new(); + client.read_to_end(&mut reply).unwrap(); + assert!(reply.is_empty()); + + // Identical duplicate Content-Length values remain valid per RFC 9112 §6.3. + for dup in [ + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\nabcd", + "POST /x HTTP/1.1\r\nHost: d\r\nContent-Length: 4, 4\r\n\r\nabcd", + ] { + let req = read_request(&mut sock(dup.as_bytes()), |_, _| false).unwrap().unwrap(); + assert_eq!(req.body, b"abcd", "{dup:?}"); + } + } + + #[test] + fn header_timeout_aborts_idle_and_partial_connections() { + use std::io::Write; + use std::time::{Duration, Instant}; + + let timeout = Duration::from_millis(60); + + // 1. Completely idle connection times out instead of blocking forever. + let (_client_idle, server_idle) = UnixStream::pair().unwrap(); + let mut r = BufReader::new(server_idle); + let t0 = Instant::now(); + let err = read_request_with_timeout(&mut r, timeout, |_, _| false).unwrap_err(); + assert!( + matches!(err.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), + "expected timeout error, got {err:?}" + ); + assert!(t0.elapsed() < Duration::from_secs(2), "idle read took {:?}", t0.elapsed()); + + // 2. Partial header that never finishes also times out. + let (mut client_slow, server_slow) = UnixStream::pair().unwrap(); + client_slow.write_all(b"GET /_ping HTTP/1.1\r\nHost: d\r\n").unwrap(); + let mut r = BufReader::new(server_slow); + let err = read_request_with_timeout(&mut r, timeout, |_, _| false).unwrap_err(); + assert!( + matches!(err.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), + "expected timeout error on partial header, got {err:?}" + ); + } + + #[test] + fn header_timeout_clears_before_streaming_and_hijacked_reads() { + use std::io::Write; + use std::time::Duration; + + let header_timeout = Duration::from_millis(60); + + // 1. Streamed upload (like `POST /build` or `POST /images/load`): + // headers arrive quickly, then the body arrives well after `header_timeout`. + let (mut client, server) = UnixStream::pair().unwrap(); + let writer_handle = server.try_clone().unwrap(); + let mut r = BufReader::new(server); + let peer = std::thread::spawn(move || { + client.write_all(b"POST /build HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n").unwrap(); + // Sleep well past the 60 ms header timeout before sending the streamed body. + std::thread::sleep(Duration::from_millis(160)); + client.write_all(b"5\r\nhello\r\n0\r\n\r\n").unwrap(); + client + }); + + let req = read_request_with_timeout(&mut r, header_timeout, |m, p| m == "POST" && p == "/build") + .unwrap() + .unwrap(); + assert_eq!(req.path, "/build"); + // Clearing SO_RCVTIMEO clears it on the underlying Unix socket for both `r` and clones. + assert_eq!(r.get_ref().read_timeout().unwrap(), None, "reader timeout must be cleared"); + assert_eq!(writer_handle.read_timeout().unwrap(), None, "cloned handle must also have no read timeout"); + + let mut body = Body::new(&req, &mut r); + let mut payload = String::new(); + body.read_to_string(&mut payload).unwrap(); + assert_eq!(payload, "hello"); + let _client = peer.join().unwrap(); + + // 2. Hijacked connection (like `attach` / `exec` + `forward_stdin`): + // a cloned fd reads stdin well after `header_timeout` without timing out. + let (mut client, server) = UnixStream::pair().unwrap(); + let mut r = BufReader::new(server); + let peer = std::thread::spawn(move || { + client + .write_all(b"POST /containers/x/attach?stdin=1 HTTP/1.1\r\nHost: d\r\nUpgrade: tcp\r\nConnection: Upgrade\r\n\r\n") + .unwrap(); + std::thread::sleep(Duration::from_millis(160)); + client.write_all(b"interactive-input\n").unwrap(); + client + }); + + let req = read_request_with_timeout(&mut r, header_timeout, |_, _| false).unwrap().unwrap(); + assert_eq!(req.path, "/containers/x/attach"); + let mut stdin = r.get_ref().try_clone().unwrap(); + assert_eq!(stdin.read_timeout().unwrap(), None, "hijacked clone must have no read timeout"); + let mut line = [0u8; 18]; + stdin.read_exact(&mut line).unwrap(); + assert_eq!(&line, b"interactive-input\n"); + let _client = peer.join().unwrap(); + + // 3. Keep-alive connection: after a completed request, the next idle + // wait re-arms `header_timeout` and times out cleanly. + let (mut client, server) = UnixStream::pair().unwrap(); + let mut r = BufReader::new(server); + client.write_all(b"GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + let req = read_request_with_timeout(&mut r, header_timeout, |_, _| false).unwrap().unwrap(); + assert_eq!(req.path, "/_ping"); + assert_eq!(r.get_ref().read_timeout().unwrap(), None); + // Second read on the idle keep-alive socket must re-arm and time out. + let err = read_request_with_timeout(&mut r, header_timeout, |_, _| false).unwrap_err(); + assert!(matches!(err.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut), "expected idle keep-alive timeout, got {err:?}"); + drop(client); + + // 4. Clearing timeout also succeeds when the peer half-closes right after sending headers. + let (mut client, server) = UnixStream::pair().unwrap(); + client.write_all(b"GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + client.shutdown(std::net::Shutdown::Write).unwrap(); + let mut r = BufReader::new(server); + let req = read_request_with_timeout(&mut r, header_timeout, |_, _| false).unwrap().unwrap(); + assert_eq!(req.path, "/_ping"); + assert_eq!(r.get_ref().read_timeout().unwrap(), None); + } } diff --git a/crates/kiri/src/daemon/localtime.rs b/crates/kiri/src/daemon/localtime.rs new file mode 100644 index 000000000..34fac5300 --- /dev/null +++ b/crates/kiri/src/daemon/localtime.rs @@ -0,0 +1,574 @@ +//! Ensures `/etc/localtime` (and `/etc/timezone`) is a valid timezone file or +//! symlink rather than missing or an empty directory (#938). +//! +//! Pre-0.2.3 Kiri WSL distros were built from Alpine minirootfs without +//! `tzdata`, so `/etc/localtime` did not exist and `-v /etc/localtime:...` +//! created an empty directory there. On WSL startup and before host bind mounts +//! of `/etc/localtime` or `/etc/timezone`, this module heals empty directories +//! (never non-empty directories) and creates either a symlink into +//! `/usr/share/zoneinfo` or a canonical RFC 8536 `TZif2` UTC binary. + +use std::fs::{self, OpenOptions}; +use std::io::{self, Write}; +use std::os::unix::fs::{OpenOptionsExt, PermissionsExt, symlink}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// Canonical RFC 8536 `TZif2` binary for UTC (`UTC0`), 114 bytes: +/// v1 header (44 B) + v1 data (10 B) + v2 header (44 B) + v2 data (10 B) + +/// POSIX TZ footer (`\nUTC0\n`, 6 B). +pub const UTC_TZIF2: [u8; 114] = [ + // V1 header (44 bytes): magic "TZif", version '2', 15 reserved zero bytes, + // isutcnt=0, isstdcnt=0, leapcnt=0, timecnt=0, typecnt=1, charcnt=4. + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V1 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // V2 header (44 bytes): identical counts + b'T', b'Z', b'i', b'f', b'2', + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, // isutcnt = 0 + 0, 0, 0, 0, // isstdcnt = 0 + 0, 0, 0, 0, // leapcnt = 0 + 0, 0, 0, 0, // timecnt = 0 + 0, 0, 0, 1, // typecnt = 1 + 0, 0, 0, 4, // charcnt = 4 + // V2 data (10 bytes): ttinfo(utoff=0, isdst=0, idx=0) + "UTC\0" + 0, 0, 0, 0, 0, 0, + b'U', b'T', b'C', 0, + // POSIX TZ footer (6 bytes): "\nUTC0\n" + b'\n', b'U', b'T', b'C', b'0', b'\n', +]; + +static TMP_SEQ: AtomicU64 = AtomicU64::new(0); + +/// Strict validation for relative IANA zone names from `TZ` (e.g. +/// `"Asia/Shanghai"`, `"America/New_York"`, `"Etc/GMT+5"`): non-empty, no +/// leading or trailing `/`, no `.` or `..` components, no `\` or `\0`, and +/// only ASCII `[A-Za-z0-9_+.-/]`. +pub fn valid_tz_name(tz: &str) -> bool { + if tz.is_empty() || tz.len() > 255 || tz.starts_with('/') || tz.ends_with('/') { + return false; + } + if !tz.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'+' | b'-' | b'.' | b'/')) { + return false; + } + tz.split('/').all(|c| !c.is_empty() && c != "." && c != "..") +} + +/// Checks whether `path` (interpreted within `root`) is a non-empty regular +/// file or a symlink whose target stays confined to `/usr/share/zoneinfo` +/// (or `/etc`) and resolves to a non-empty regular file. +pub fn is_valid_timezone_file_at(root: &Path, path: &Path) -> bool { + let Ok(meta) = fs::symlink_metadata(path) else { + return false; + }; + let ft = meta.file_type(); + if ft.is_file() { + return meta.len() > 0; + } + if ft.is_symlink() { + let zinfo = root.join("usr/share/zoneinfo"); + let etc = root.join("etc"); + return resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path); + } + false +} + +/// Lexically normalizes `rel` beneath `root`, returning `None` if `..` would +/// escape above `root`. +fn join_confined(root: &Path, rel: &Path) -> Option { + use std::path::Component; + let mut stack: Vec = Vec::new(); + for c in rel.components() { + match c { + Component::Normal(p) => stack.push(p.to_owned()), + Component::CurDir | Component::RootDir | Component::Prefix(_) => {} + Component::ParentDir => { + stack.pop()?; + } + } + } + let mut out = root.to_path_buf(); + for s in stack { + out.push(s); + } + Some(out) +} + +/// Resolves symlinks starting at `path` within `root` and returns true iff the +/// final target is a non-empty regular file whose canonical path sits inside +/// one of `allowed_bases`. +fn resolve_confined_file(root: &Path, allowed_bases: &[&Path], path: &Path) -> bool { + let canon_root = fs::canonicalize(root).ok(); + let Some(canon_root_ref) = canon_root.as_deref() else { + return false; + }; + let mut cur = path.to_path_buf(); + for _ in 0..16 { + let Ok(meta) = fs::symlink_metadata(&cur) else { + return false; + }; + let ft = meta.file_type(); + if !ft.is_symlink() { + if !ft.is_file() || meta.len() == 0 { + return false; + } + let Ok(canon_target) = fs::canonicalize(&cur) else { + return false; + }; + if !canon_target.starts_with(canon_root_ref) { + return false; + } + return allowed_bases.iter().any(|base| { + fs::canonicalize(base).is_ok_and(|cb| canon_target.starts_with(&cb)) + }); + } + let Ok(target) = fs::read_link(&cur) else { + return false; + }; + let next = if target.is_absolute() { + if root != Path::new("/") && target.starts_with(root) { + let rel = target.strip_prefix(root).unwrap_or(&target); + join_confined(root, rel) + } else { + let rel = target.strip_prefix("/").unwrap_or(&target); + join_confined(root, rel) + } + } else { + let Some(parent_rel) = cur.parent().and_then(|p| p.strip_prefix(root).ok()) else { + return false; + }; + let combined = parent_rel.join(target); + join_confined(root, &combined) + }; + let Some(n) = next else { + return false; + }; + cur = n; + } + false +} + +fn resolve_symlink_is_file(root: &Path, path: &Path) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let etc = root.join("etc"); + resolve_confined_file(root, &[zinfo.as_path(), etc.as_path()], path) +} + +fn zoneinfo_file_exists(root: &Path, tz: &str) -> bool { + let zinfo = root.join("usr/share/zoneinfo"); + let Some(candidate) = join_confined(&zinfo, Path::new(tz)) else { + return false; + }; + resolve_confined_file(root, &[zinfo.as_path()], &candidate) +} + +fn temp_path_in(dir: &Path, prefix: &str) -> PathBuf { + let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed); + dir.join(format!(".{prefix}.kiri.{}.{seq}.tmp", std::process::id())) +} + +fn atomic_write_file(dest: &Path, bytes: &[u8]) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + let write_res = (|| -> io::Result<()> { + let mut f = OpenOptions::new().write(true).create_new(true).mode(0o644).open(&tmp)?; + f.write_all(bytes)?; + f.set_permissions(fs::Permissions::from_mode(0o644))?; + f.sync_all()?; + Ok(()) + })(); + if let Err(e) = write_res { + let _ = fs::remove_file(&tmp); + return Err(e); + } + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +fn atomic_symlink(target: &str, dest: &Path) -> io::Result<()> { + let dir = dest.parent().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "path has no parent"))?; + fs::create_dir_all(dir)?; + let tmp = temp_path_in(dir, dest.file_name().and_then(|n| n.to_str()).unwrap_or("tz")); + symlink(target, &tmp)?; + if let Err(e) = fs::rename(&tmp, dest) { + let _ = fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +/// Writes `\n` to `/etc/timezone` if it is missing (or an empty +/// directory). Never overwrites an existing valid file or non-empty directory. +fn write_timezone_if_missing(root: &Path, zone: &str) { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) if meta.file_type().is_dir() => { + // Only remove an empty directory; never remove_dir_all. + if fs::remove_dir(&tz_path).is_err() { + return; + } + } + Ok(meta) if meta.file_type().is_file() && meta.len() > 0 => return, + Ok(meta) if meta.file_type().is_symlink() && resolve_symlink_is_file(root, &tz_path) => return, + Ok(meta) if !meta.file_type().is_file() && !meta.file_type().is_symlink() => return, + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(_) => return, + } + let _ = atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()); +} + +/// Ensures `/etc/localtime` on the live root (`/`) is a valid file or symlink. +pub fn ensure_localtime() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_localtime_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/localtime` is a valid timezone file or symlink: +/// 1. If `/etc/localtime` is a directory, removes it ONLY if empty +/// (`remove_dir`, never `remove_dir_all`). +/// 2. If it is already a non-empty regular file or a symlink resolving to a +/// regular file, leaves it untouched. +/// 3. If missing, empty file, or broken symlink: +/// - If `tz_env` is a valid relative zone name and +/// `/usr/share/zoneinfo/` is a regular file, symlinks +/// `/etc/localtime` -> `/usr/share/zoneinfo/` and writes `\n` to +/// `/etc/timezone` if missing. +/// - Else if `/usr/share/zoneinfo/Etc/UTC` is a regular file, symlinks +/// `/etc/localtime` -> `/usr/share/zoneinfo/Etc/UTC` and writes `Etc/UTC\n` +/// to `/etc/timezone` if missing. +/// - Else atomically writes canonical RFC 8536 `UTC_TZIF2` (`0644`) to +/// `/etc/localtime` and writes `UTC\n` to `/etc/timezone` if +/// missing. +pub fn ensure_localtime_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let localtime = root.join("etc/localtime"); + match fs::symlink_metadata(&localtime) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + // ONLY removes an empty directory; non-empty directories return an error. + match fs::remove_dir(&localtime) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &localtime) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + localtime.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + if let Some(tz) = tz_env.filter(|tz| valid_tz_name(tz)) + && zoneinfo_file_exists(root, tz) + { + atomic_symlink(&format!("/usr/share/zoneinfo/{tz}"), &localtime)?; + write_timezone_if_missing(root, tz); + return Ok(()); + } + + if zoneinfo_file_exists(root, "Etc/UTC") { + atomic_symlink("/usr/share/zoneinfo/Etc/UTC", &localtime)?; + write_timezone_if_missing(root, "Etc/UTC"); + return Ok(()); + } + + atomic_write_file(&localtime, &UTC_TZIF2)?; + write_timezone_if_missing(root, "UTC"); + Ok(()) +} + +/// Ensures `/etc/timezone` on the live root (`/`) is a valid file or symlink. +pub fn ensure_timezone() -> io::Result<()> { + let tz = std::env::var("TZ").ok(); + ensure_timezone_at(Path::new("/"), tz.as_deref()) +} + +/// Ensures `/etc/timezone` is a valid timezone name file (never a +/// directory), refusing to delete a non-empty directory. +pub fn ensure_timezone_at(root: &Path, tz_env: Option<&str>) -> io::Result<()> { + let tz_path = root.join("etc/timezone"); + match fs::symlink_metadata(&tz_path) { + Ok(meta) => { + let ft = meta.file_type(); + if ft.is_dir() { + match fs::remove_dir(&tz_path) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + } else if ft.is_file() { + if meta.len() > 0 { + return Ok(()); + } + } else if ft.is_symlink() { + if resolve_symlink_is_file(root, &tz_path) { + return Ok(()); + } + } else { + return Err(io::Error::other(format!( + "{} is not a regular file, symlink, or empty directory", + tz_path.display() + ))); + } + } + Err(e) if e.kind() == io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + + let inferred = fs::read_link(root.join("etc/localtime")) + .ok() + .and_then(|p| p.to_str().map(str::to_owned)) + .and_then(|s| s.split_once("zoneinfo/").map(|(_, z)| z.to_owned())) + .filter(|z| valid_tz_name(z)); + let zone = inferred + .as_deref() + .or_else(|| tz_env.filter(|tz| valid_tz_name(tz))) + .unwrap_or("UTC"); + atomic_write_file(&tz_path, format!("{zone}\n").as_bytes()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn test_root(name: &str) -> PathBuf { + static COUNTER: AtomicU64 = AtomicU64::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("kiri-localtime-{name}-{}-{n}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("etc")).unwrap(); + dir + } + + /// Minimal RFC 8536 TZif2 parser check verifying header counts, v1/v2 data + /// block framing, UTC designation, and POSIX TZ footer. + fn assert_valid_utc_tzif2(bytes: &[u8]) { + assert_eq!(bytes.len(), 114, "canonical UTC TZif2 is 114 bytes"); + assert!(bytes.starts_with(b"TZif2"), "must start with TZif2 magic"); + assert!(bytes.ends_with(b"\nUTC0\n"), "must end with POSIX UTC0 footer"); + let be_u32 = |off: usize| u32::from_be_bytes(bytes[off..off + 4].try_into().unwrap()); + // Verify both v1 (offset 0) and v2 (offset 54) sections. + for base in [0usize, 54usize] { + assert_eq!(&bytes[base..base + 5], b"TZif2"); + assert_eq!(&bytes[base + 5..base + 20], &[0u8; 15]); + assert_eq!(be_u32(base + 20), 0, "isutcnt"); + assert_eq!(be_u32(base + 24), 0, "isstdcnt"); + assert_eq!(be_u32(base + 28), 0, "leapcnt"); + assert_eq!(be_u32(base + 32), 0, "timecnt"); + assert_eq!(be_u32(base + 36), 1, "typecnt"); + assert_eq!(be_u32(base + 40), 4, "charcnt"); + // Local time type record: utoff=0, isdst=0, desigidx=0 + assert_eq!(&bytes[base + 44..base + 50], &[0u8; 6]); + // Abbreviation string table: "UTC\0" + assert_eq!(&bytes[base + 50..base + 54], b"UTC\0"); + } + assert_eq!(&bytes[108..114], b"\nUTC0\n"); + } + + #[test] + fn repairs_empty_localtime_directory_into_valid_tzif2_file() { + let root = test_root("empty-dir"); + let lt = root.join("etc/localtime"); + fs::create_dir(<).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_dir()); + + ensure_localtime_at(&root, None).unwrap(); + + let meta = fs::symlink_metadata(<).unwrap(); + assert!(meta.file_type().is_file(), "repaired /etc/localtime must be a regular file"); + assert_eq!(meta.permissions().mode() & 0o777, 0o644); + let bytes = fs::read(<).unwrap(); + assert_valid_utc_tzif2(&bytes); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "UTC\n"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn refuses_to_delete_non_empty_localtime_directory() { + let root = test_root("non-empty-dir"); + let lt = root.join("etc/localtime"); + fs::create_dir(<).unwrap(); + let keep = lt.join("sentinel.txt"); + fs::write(&keep, b"do-not-delete").unwrap(); + + let err = ensure_localtime_at(&root, None).expect_err("non-empty directory must not be removed"); + assert!(lt.is_dir(), "directory must remain intact after error ({err})"); + assert_eq!(fs::read(&keep).unwrap(), b"do-not-delete"); + + // Same safety invariant for /etc/timezone. + let tz = root.join("etc/timezone"); + fs::create_dir(&tz).unwrap(); + let keep_tz = tz.join("keep"); + fs::write(&keep_tz, b"safe").unwrap(); + assert!(ensure_timezone_at(&root, None).is_err()); + assert_eq!(fs::read(&keep_tz).unwrap(), b"safe"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn preserves_existing_valid_localtime_file_and_symlink() { + let root = test_root("preserve"); + let lt = root.join("etc/localtime"); + let custom = b"TZif2-custom-existing-file"; + fs::write(<, custom).unwrap(); + + // Even with TZ pointing to a valid zoneinfo file, existing valid file is untouched. + let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai"); + fs::create_dir_all(shanghai.parent().unwrap()).unwrap(); + fs::write(&shanghai, &UTC_TZIF2).unwrap(); + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_eq!(fs::read(<).unwrap(), custom); + assert!(!root.join("etc/timezone").exists(), "should not touch /etc/timezone when /etc/localtime is already valid"); + + // Valid symlink resolving inside root is also preserved untouched. + fs::remove_file(<).unwrap(); + let ny = root.join("usr/share/zoneinfo/America/New_York"); + fs::create_dir_all(ny.parent().unwrap()).unwrap(); + fs::write(&ny, &UTC_TZIF2).unwrap(); + symlink("/usr/share/zoneinfo/America/New_York", <).unwrap(); + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert_eq!(fs::read_link(<).unwrap(), Path::new("/usr/share/zoneinfo/America/New_York")); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn links_valid_tz_env_and_rejects_path_traversal() { + let root = test_root("tz-env"); + let shanghai = root.join("usr/share/zoneinfo/Asia/Shanghai"); + fs::create_dir_all(shanghai.parent().unwrap()).unwrap(); + fs::write(&shanghai, &UTC_TZIF2).unwrap(); + let utc = root.join("usr/share/zoneinfo/Etc/UTC"); + fs::create_dir_all(utc.parent().unwrap()).unwrap(); + fs::write(&utc, &UTC_TZIF2).unwrap(); + + // Valid TZ links to /usr/share/zoneinfo/ and populates /etc/timezone. + ensure_localtime_at(&root, Some("Asia/Shanghai")).unwrap(); + assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Asia/Shanghai")); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Asia/Shanghai\n"); + + // Reject path-traversal and invalid TZ strings; fall back to Etc/UTC. + for bad in [ + "../etc/shadow", + "/etc/passwd", + "Asia/../../etc/passwd", + "", + ".", + "..", + "Asia/", + "Asia//Shanghai", + "Asia\\Shanghai", + "Asia/Shanghai\0", + "Asia/Shanghai\n", + ":Asia/Shanghai", + ] { + assert!(!valid_tz_name(bad), "{bad:?} must be rejected"); + let _ = fs::remove_file(root.join("etc/localtime")); + let _ = fs::remove_file(root.join("etc/timezone")); + ensure_localtime_at(&root, Some(bad)).unwrap(); + assert_eq!( + fs::read_link(root.join("etc/localtime")).unwrap(), + Path::new("/usr/share/zoneinfo/Etc/UTC"), + "bad TZ {bad:?} must fall back to Etc/UTC" + ); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Etc/UTC\n"); + } + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn replaces_broken_symlink_and_empty_file() { + let root = test_root("broken-link"); + let lt = root.join("etc/localtime"); + + // Dangling symlink pointing to /usr/share/zoneinfo/Etc/UTC when root has no zoneinfo. + symlink("/usr/share/zoneinfo/Etc/UTC", <).unwrap(); + ensure_localtime_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + // Symlink pointing to a directory is treated as broken. + fs::remove_file(<).unwrap(); + fs::create_dir_all(root.join("usr/share/zoneinfo")).unwrap(); + symlink("/usr/share/zoneinfo", <).unwrap(); + ensure_localtime_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + // 0-byte regular file is repaired into a valid TZif2 file. + fs::write(<, b"").unwrap(); + ensure_localtime_at(&root, None).unwrap(); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn ensures_timezone_file_and_infers_from_localtime_link() { + let root = test_root("timezone"); + let berlin = root.join("usr/share/zoneinfo/Europe/Berlin"); + fs::create_dir_all(berlin.parent().unwrap()).unwrap(); + fs::write(&berlin, &UTC_TZIF2).unwrap(); + symlink("/usr/share/zoneinfo/Europe/Berlin", root.join("etc/localtime")).unwrap(); + fs::create_dir(root.join("etc/timezone")).unwrap(); + + ensure_timezone_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(root.join("etc/timezone")).unwrap().file_type().is_file()); + assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Europe/Berlin\n"); + let _ = fs::remove_dir_all(&root); + } + + #[test] + fn rejects_symlinks_escaping_zoneinfo_or_root() { + let root = test_root("confined"); + let zinfo = root.join("usr/share/zoneinfo"); + fs::create_dir_all(&zinfo).unwrap(); + fs::create_dir_all(root.join("var/secret")).unwrap(); + fs::write(root.join("var/secret/token"), b"secret").unwrap(); + + // A symlink inside zoneinfo escaping to /var/secret/token is rejected for TZ + // and falls back to writing UTC_TZIF2 instead of linking to the secret file. + symlink("../../../var/secret/token", zinfo.join("EvilZone")).unwrap(); + assert!(!super::zoneinfo_file_exists(&root, "EvilZone")); + ensure_localtime_at(&root, Some("EvilZone")).unwrap(); + let lt = root.join("etc/localtime"); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + // An /etc/localtime symlink pointing outside /usr/share/zoneinfo and /etc is + // rejected by is_valid_timezone_file_at and replaced on ensure_localtime_at. + fs::remove_file(<).unwrap(); + symlink("/var/secret/token", <).unwrap(); + assert!(!is_valid_timezone_file_at(&root, <)); + ensure_localtime_at(&root, None).unwrap(); + assert!(fs::symlink_metadata(<).unwrap().file_type().is_file()); + assert_valid_utc_tzif2(&fs::read(<).unwrap()); + + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri/src/daemon/mirror.rs b/crates/kiri/src/daemon/mirror.rs index 9cd4c6fe7..cf5c7a057 100644 --- a/crates/kiri/src/daemon/mirror.rs +++ b/crates/kiri/src/daemon/mirror.rs @@ -4,19 +4,24 @@ //! A read-only registry API on 127.0.0.1, which containers reach at //! host.docker.internal. buildkitd.toml names it as a mirror of every //! registry Kiri has images from; a mirror that answers 404 is skipped, so -//! anything not here comes from the registry itself. Paths carry a secret +//! anything not here comes from the registry itself. A tag a registry +//! published is not answered here even when Kiri holds it: the registry, +//! not this machine, knows which platforms it has (see `lookup`). +//! Paths carry a secret //! (`/v2////…`), so other local users can't read //! images through it. Manifests are made from the store's records (layers, //! config), the same bytes for the same image every time. +use std::collections::{HashMap, HashSet}; use std::io::{self, BufRead, BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; -use std::sync::{Arc, OnceLock, Weak}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, OnceLock, Weak}; use std::time::Duration; use serde_json::{Value, json}; -use kiri_image::{Image, Reference}; +use kiri_image::{Image, Layer, Platform, Reference}; use super::engine::Engine; @@ -24,8 +29,24 @@ use super::engine::Engine; /// finds the mirror its config names. const PORT: u16 = 47_391; const DEV_PORT: u16 = 47_392; +const MAX_MIRROR_WORKERS: usize = 128; -static LISTENING: OnceLock> = OnceLock::new(); +#[derive(Clone, Copy)] +struct MirrorListen { + port: u16, + has_bridge: bool, +} + +static LISTENING: OnceLock> = OnceLock::new(); +static ACTIVE_WORKERS: AtomicUsize = AtomicUsize::new(0); + +struct WorkerGuard; + +impl Drop for WorkerGuard { + fn drop(&mut self) { + ACTIVE_WORKERS.fetch_sub(1, Ordering::AcqRel); + } +} /// The mirror's secret path segment, kept in the state directory so it /// survives restarts (the builder's config keeps naming it). @@ -64,6 +85,10 @@ pub fn start(engine: &Arc) { let listener = TcpListener::bind(("127.0.0.1", wanted)).or_else(|_| TcpListener::bind(("127.0.0.1", 0))).ok()?; let port = listener.local_addr().ok()?.port(); let me = Arc::downgrade(engine); + #[cfg(target_os = "linux")] + let mut has_bridge = false; + #[cfg(not(target_os = "linux"))] + let has_bridge = true; // On a Linux host the builder reaches the mirror at the default // bridge's gateway (mirror_host): containers have no way to the // host's loopback there, so it listens on that address too. @@ -72,14 +97,16 @@ pub fn start(engine: &Arc) { match bind_freely(gateway, port) { Ok(l) => { let me = me.clone(); - let _ = std::thread::Builder::new().name("kiri-build-mirror".into()).spawn(move || serve(l, me)); + if std::thread::Builder::new().name("kiri-build-mirror".into()).spawn(move || serve(l, me)).is_ok() { + has_bridge = true; + } } Err(e) => crate::diag::warn!("image mirror not on the bridge; builds pull from registries", error = e), } } std::thread::Builder::new().name("kiri-build-mirror".into()).spawn(move || serve(listener, me)).ok()?; crate::diag::info!("image mirror for builds", port = port); - Some(port) + Some(MirrorListen { port, has_bridge }) }); } @@ -230,24 +257,35 @@ pub fn unverified(c: &kiri_image::RegistryConfig, names: &[String]) -> Vec String { - let mut tables: Vec<(String, Table)> = Vec::new(); - if let Some(port) = LISTENING.get().copied().flatten() { - let host = format!("{}:{port}", mirror_host(&engine.lock_net())); - let token = token(); - for name in names { - add_mirror(&mut tables, name, format!("{host}/{token}/{name}")); +/// A TOML basic string. A name or a mirror goes into buildkitd.toml, and one +/// with a quote, a backslash or a control character in it would close or +/// break the string: buildkitd would refuse the whole file, so every build +/// would fail, and the image that carried the name is recorded, so it would +/// keep failing. +fn quoted(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for c in s.chars() { + match c { + '"' => out.push_str("\\\""), + '\\' => out.push_str("\\\\"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 || c as u32 == 0x7f => out.push_str(&format!("\\u{:04X}", c as u32)), + c => out.push(c), } - table(&mut tables, &host).http = Some(true); } - registries(&mut tables, c, names); + out.push('"'); + out +} + +fn format_tables(tables: &[(String, Table)]) -> String { let mut out = String::new(); for (registry, t) in tables { - out.push_str(&format!("[registry.\"{registry}\"]\n")); + out.push_str(&format!("[registry.{}]\n", quoted(registry))); if !t.mirrors.is_empty() { - let list = t.mirrors.iter().map(|m| format!("\"{m}\"")).collect::>().join(", "); + let list = t.mirrors.iter().map(|m| quoted(m)).collect::>().join(", "); out.push_str(&format!(" mirrors = [{list}]\n")); } if let Some(http) = t.http { @@ -260,6 +298,37 @@ pub fn config(engine: &Engine, c: &kiri_image::RegistryConfig, names: &[String]) out } +/// The mirror's `host:port` as reached from the builder container (`127.0.0.1` +/// on Linux when the builder uses `--network=host`, else the bridge gateway / +/// VM host address). `None` if the mirror listener for that network mode failed +/// to start. +pub fn upload_endpoint(engine: &Engine, host_net: bool) -> Option { + let listen = LISTENING.get().copied().flatten()?; + if cfg!(target_os = "linux") && !host_net && !listen.has_bridge { + return None; + } + let addr = if cfg!(target_os = "linux") && host_net { "127.0.0.1".to_owned() } else { mirror_host(&engine.lock_net()) }; + Some(format!("{addr}:{}", listen.port)) +} + +/// buildkitd.toml's registry tables, for `c` (daemon.json's settings) and +/// `names` ([`registry_names`]), with `host_net` selecting `127.0.0.1` on +/// Linux when the builder runs in the host network namespace (`--driver-opt +/// network=host`), where the loopback listener is always up even before `kiri0` +/// exists. +pub fn config_for(engine: &Engine, c: &kiri_image::RegistryConfig, names: &[String], host_net: bool) -> String { + let mut tables: Vec<(String, Table)> = Vec::new(); + if let Some(host) = upload_endpoint(engine, host_net) { + let token = token(); + for name in names { + add_mirror(&mut tables, name, format!("{host}/{token}/{name}")); + } + table(&mut tables, &host).http = Some(true); + } + registries(&mut tables, c, names); + format_tables(&tables) +} + /// daemon.json's part of buildkitd.toml, so a build reaches each registry /// the way a pull does. Its Docker Hub mirrors (the usable ones: /// `RegistryConfig::mirror_allowed`) come after Kiri's own mirror, which @@ -321,59 +390,759 @@ fn registries(tables: &mut Vec<(String, Table)>, c: &kiri_image::RegistryConfig, } } +// --- Ephemeral one-shot image load uploads (/v2/load//image/...) ------ + +const MAX_LOAD_UPLOADS: usize = 256; +const MAX_LOAD_CHILD_MANIFESTS: usize = 64; + +struct UploadEntry { + ingest: kiri_image::store::Ingest, + written: u64, +} + +struct LoadSlot { + nonce: String, + engine: Arc, + closed: AtomicBool, + target_tags: Mutex>, + uploads: Mutex>>>>, + child_manifests: Mutex>>, + pins: Mutex>, + newly_ingested: Mutex>, + used_digests: Mutex>, + committed_digest: Mutex>, +} + +impl LoadSlot { + fn close_and_cleanup(&self) { + self.closed.store(true, Ordering::Release); + let uploads = std::mem::take(&mut *self.uploads.lock().unwrap_or_else(|e| e.into_inner())); + for handle in uploads.values() { + if let Ok(mut guard) = handle.try_lock() { + let _ = guard.take(); + } + } + drop(uploads); + self.child_manifests.lock().unwrap_or_else(|e| e.into_inner()).clear(); + let mut pins = self.pins.lock().unwrap_or_else(|e| e.into_inner()); + let newly = std::mem::take(&mut *self.newly_ingested.lock().unwrap_or_else(|e| e.into_inner())); + let used = self.used_digests.lock().unwrap_or_else(|e| e.into_inner()).clone(); + pins.clear(); + drop(pins); + for d in newly { + if !used.contains(&d) { + let _ = self.engine.store.remove_if_unused(&d); + } + } + } + + fn record_blob(&self, pin: kiri_image::store::Pin, newly_ingested: Option) -> bool { + let mut pins = self.pins.lock().unwrap_or_else(|e| e.into_inner()); + if self.closed.load(Ordering::Acquire) { + drop(pins); + drop(pin); + if let Some(d) = newly_ingested { + let _ = self.engine.store.remove_if_unused(&d); + } + return false; + } + pins.push(pin); + if let Some(d) = newly_ingested { + self.newly_ingested.lock().unwrap_or_else(|e| e.into_inner()).push(d); + } + true + } +} + +impl Drop for LoadSlot { + fn drop(&mut self) { + self.close_and_cleanup(); + } +} + +static LOADS: Mutex>>> = Mutex::new(None); + +/// An ephemeral push target in the mirror for one `Solve` call from BuildKit's +/// `docker` driver (`grpc.rs`). Uses a per-build random nonce (never the +/// read-only mirror's secret `token()`), exposes no image reads, and cleans up +/// any uncommitted blobs on drop. +pub struct LoadSession { + nonce: String, + slot: Arc, +} + +impl std::fmt::Debug for LoadSession { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LoadSession").field("nonce", &self.nonce).finish() + } +} + +impl LoadSession { + pub fn new(engine: Arc, target_tags: Vec) -> LoadSession { + let nonce = super::engine::random_hex(16); + let mut deduped = Vec::with_capacity(target_tags.len()); + let mut seen = HashSet::with_capacity(target_tags.len()); + for t in target_tags { + if seen.insert(t.clone()) { + deduped.push(t); + } + } + let slot = Arc::new(LoadSlot { + nonce: nonce.clone(), + engine, + closed: AtomicBool::new(false), + target_tags: Mutex::new(deduped), + uploads: Mutex::new(HashMap::new()), + child_manifests: Mutex::new(HashMap::new()), + pins: Mutex::new(Vec::new()), + newly_ingested: Mutex::new(Vec::new()), + used_digests: Mutex::new(HashSet::new()), + committed_digest: Mutex::new(None), + }); + LOADS + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_or_insert_with(HashMap::new) + .insert(nonce.clone(), slot.clone()); + LoadSession { nonce, slot } + } + + /// Adds extra target tags to this load session (when a solve names multiple + /// `moby` exporters). + pub fn add_tags(&self, extra: Vec) { + let mut tags = self.slot.target_tags.lock().unwrap_or_else(|e| e.into_inner()); + let mut seen: HashSet = tags.iter().cloned().collect(); + for t in extra { + if seen.insert(t.clone()) { + tags.push(t); + } + } + } + + /// Reference passed to BuildKit's `image` exporter (`push=true`). + pub fn repo_ref(&self, endpoint: &str) -> String { + format!("{endpoint}/load/{}/image:out", self.nonce) + } + + /// The stored image's config digest once BuildKit has pushed the manifest. + pub fn committed_digest(&self) -> Option { + self.slot.committed_digest.lock().unwrap_or_else(|e| e.into_inner()).clone() + } +} + +impl Drop for LoadSession { + fn drop(&mut self) { + if let Some(map) = LOADS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + map.remove(&self.nonce); + } + self.slot.close_and_cleanup(); + } +} + +fn is_hex_id(s: &str) -> bool { + s.len() == 32 && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn find_load_slot(nonce: &str) -> Option> { + if !is_hex_id(nonce) { + return None; + } + LOADS.lock().unwrap_or_else(|e| e.into_inner()).as_ref()?.get(nonce).cloned() +} + fn serve(listener: TcpListener, engine: Weak) { for conn in listener.incoming() { let Ok(conn) = conn else { continue }; let Some(engine) = engine.upgrade() else { return }; + if ACTIVE_WORKERS + .fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < MAX_MIRROR_WORKERS).then_some(n + 1)) + .is_err() + { + continue; + } + let guard = WorkerGuard; let _ = std::thread::Builder::new().name("kiri-build-mirror".into()).spawn(move || { + let _guard = guard; let _ = conn.set_read_timeout(Some(Duration::from_secs(30))); let _ = answer(conn, &engine); }); } } +#[derive(Clone, Copy)] +enum BodyFraming { + None, + Length(u64), + Chunked, +} + +fn read_http_body(r: &mut R, framing: BodyFraming, out: &mut W, limit: Option) -> io::Result { + let mut total = 0u64; + let mut buf = [0u8; 32 * 1024]; + let mut copy_exact = |r: &mut R, mut rem: u64, out: &mut W, total: &mut u64| -> io::Result<()> { + while rem > 0 { + let want = buf.len().min(rem as usize); + let n = r.read(&mut buf[..want])?; + if n == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "truncated request body")); + } + *total = total.checked_add(n as u64).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "body overflow"))?; + if limit.is_some_and(|l| *total > l) { + return Err(io::Error::new(io::ErrorKind::FileTooLarge, "request body too large")); + } + out.write_all(&buf[..n])?; + rem -= n as u64; + } + Ok(()) + }; + match framing { + BodyFraming::None => Ok(0), + BodyFraming::Length(n) => { + copy_exact(r, n, out, &mut total)?; + Ok(total) + } + BodyFraming::Chunked => loop { + let mut line = String::new(); + if (&mut *r).take(1024).read_line(&mut line)? == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "truncated chunk header")); + } + if !line.ends_with('\n') { + return Err(io::Error::new(io::ErrorKind::InvalidData, "chunk header too long")); + } + let raw = line.trim_end_matches(['\r', '\n']); + let hex = raw.split(';').next().unwrap_or_default().trim(); + let size = u64::from_str_radix(hex, 16).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "bad chunk size"))?; + if size == 0 { + // Drain bounded trailers until blank line. + for _ in 0..128 { + let mut tr = String::new(); + if (&mut *r).take(4096).read_line(&mut tr)? == 0 || tr == "\r\n" || tr == "\n" { + break; + } + } + return Ok(total); + } + copy_exact(r, size, out, &mut total)?; + let mut crlf = [0u8; 2]; + r.read_exact(&mut crlf)?; + if crlf != *b"\r\n" { + return Err(io::Error::new(io::ErrorKind::InvalidData, "bad chunk delimiter")); + } + }, + } +} + +fn query_param(query: &str, key: &str) -> Option { + for kv in query.split('&').filter(|s| !s.is_empty()) { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + if k == key { + return Some(percent_decode(v)); + } + } + None +} + +fn percent_decode(s: &str) -> String { + let b = s.as_bytes(); + let hex = |c: u8| (c as char).to_digit(16).map(|d| d as u8); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + match b[i] { + b'+' => out.push(b' '), + b'%' if i + 2 < b.len() && hex(b[i + 1]).is_some() && hex(b[i + 2]).is_some() => { + out.push(hex(b[i + 1]).unwrap_or(0) << 4 | hex(b[i + 2]).unwrap_or(0)); + i += 2; + } + c => out.push(c), + } + i += 1; + } + String::from_utf8_lossy(&out).into_owned() +} + /// One request, then the connection closes. fn answer(conn: TcpStream, engine: &Engine) -> io::Result<()> { - let mut r = BufReader::new((&conn).take(16 << 10)); - let mut line = String::new(); - r.read_line(&mut line)?; - let mut parts = line.split_whitespace(); - let (method, target) = (parts.next().unwrap_or_default().to_owned(), parts.next().unwrap_or_default().to_owned()); - loop { - let mut h = String::new(); - if r.read_line(&mut h)? == 0 || h.trim().is_empty() { - break; - } - } - let mut w = &conn; - let head = |w: &mut &TcpStream, status: &str, extra: &str, len: u64| write!(w, "HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: {len}\r\n{extra}\r\n"); + let mut w = conn.try_clone()?; + let mut r = BufReader::new(conn); + answer_stream(&mut r, &mut w, engine) +} + +fn answer_stream(r: &mut R, w: &mut W, engine: &Engine) -> io::Result<()> { + let head = |w: &mut W, status: &str, extra: &str, len: u64| write!(w, "HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: {len}\r\n{extra}\r\n"); + let (method, target, framing, expect_continue) = { + let mut head_reader = (&mut *r).take(16 << 10); + let mut raw_line = Vec::new(); + if head_reader.read_until(b'\n', &mut raw_line)? == 0 { + return Ok(()); + } + let Ok(line) = std::str::from_utf8(&raw_line) else { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + }; + if !line.ends_with('\n') { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + let mut parts = line.split_whitespace(); + let (method, target) = (parts.next().unwrap_or_default().to_owned(), parts.next().unwrap_or_default().to_owned()); + let mut content_length: Option = None; + let mut chunked = false; + let mut expect_continue = false; + let mut saw_end = false; + loop { + let mut raw_h = Vec::new(); + if head_reader.read_until(b'\n', &mut raw_h)? == 0 { + break; + } + let Ok(h) = std::str::from_utf8(&raw_h) else { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + }; + if !h.ends_with('\n') { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + if h.trim().is_empty() { + saw_end = true; + break; + } + if let Some((k, v)) = h.split_once(':') { + let k = k.trim(); + let v = v.trim(); + if k.eq_ignore_ascii_case("content-length") { + let Ok(parsed) = v.parse::() else { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + }; + if content_length.is_some_and(|prev| prev != parsed) { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + content_length = Some(parsed); + } else if k.eq_ignore_ascii_case("transfer-encoding") && v.to_ascii_lowercase().contains("chunked") { + chunked = true; + } else if k.eq_ignore_ascii_case("expect") && v.to_ascii_lowercase().contains("100-continue") { + expect_continue = true; + } + } + } + if !saw_end || (chunked && content_length.is_some()) { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + let framing = if chunked { + BodyFraming::Chunked + } else if let Some(n) = content_length.filter(|n| *n > 0) { + BodyFraming::Length(n) + } else { + BodyFraming::None + }; + (method, target, framing, expect_continue) + }; + let (path, query) = target.split_once('?').unwrap_or((&target, "")); + + // Registry v2 ping (`GET /v2/` / `HEAD /v2/`). + if matches!(method.as_str(), "GET" | "HEAD") && (path == "/v2/" || path == "/v2") { + let body = if method == "GET" { b"{}".as_slice() } else { b"".as_slice() }; + head(w, "200 OK", "Docker-Distribution-Api-Version: registry/2.0\r\nContent-Type: application/json\r\n", body.len() as u64)?; + w.write_all(body)?; + return w.flush(); + } + + // Ephemeral one-shot image upload for BuildKit's `docker` driver. + if let Some(rest) = path.strip_prefix("/v2/load/") { + if let Some((nonce, sub)) = rest.split_once("/image/") { + return handle_load(engine, nonce, sub, &method, query, framing, expect_continue, r, w); + } + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + if method != "GET" && method != "HEAD" { - return head(&mut w, "405 Method Not Allowed", "", 0); + head(w, "405 Method Not Allowed", "", 0)?; + return w.flush(); } - match lookup(engine, target.split('?').next().unwrap_or_default(), &token()) { - Some(Found::Manifest(bytes, digest)) => { - head(&mut w, "200 OK", &format!("Content-Type: application/vnd.oci.image.manifest.v1+json\r\nDocker-Content-Digest: {digest}\r\n"), bytes.len() as u64)?; + match lookup(&engine.store, path, &token()) { + Some(Found::Manifest(bytes, media_type, digest)) => { + head(w, "200 OK", &format!("Content-Type: {media_type}\r\nDocker-Content-Digest: {digest}\r\n"), bytes.len() as u64)?; if method == "GET" { w.write_all(&bytes)?; } } - Some(Found::Blob(path, digest)) => { + Some(Found::Blob(path, digest, _pin)) => { let mut f = std::fs::File::open(&path)?; let len = f.metadata()?.len(); - head(&mut w, "200 OK", &format!("Content-Type: application/octet-stream\r\nDocker-Content-Digest: {digest}\r\n"), len)?; + head(w, "200 OK", &format!("Content-Type: application/octet-stream\r\nDocker-Content-Digest: {digest}\r\n"), len)?; if method == "GET" { - io::copy(&mut f, &mut w)?; + io::copy(&mut f, w)?; } } - None => head(&mut w, "404 Not Found", "", 0)?, + None => head(w, "404 Not Found", "", 0)?, } w.flush() } +#[allow(clippy::too_many_arguments)] +fn handle_load( + engine: &Engine, + nonce: &str, + sub: &str, + method: &str, + query: &str, + framing: BodyFraming, + expect_continue: bool, + r: &mut R, + w: &mut W, +) -> io::Result<()> { + let head = |w: &mut W, status: &str, extra: &str, len: u64| write!(w, "HTTP/1.1 {status}\r\nConnection: close\r\nContent-Length: {len}\r\n{extra}\r\n"); + let Some(slot) = find_load_slot(nonce).filter(|s| !s.closed.load(Ordering::Acquire)) else { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + }; + let send_continue = |w: &mut W| -> io::Result<()> { + if expect_continue { + w.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?; + w.flush()?; + } + Ok(()) + }; + let base = format!("/v2/load/{}/image", slot.nonce); + + // HEAD /blobs/: dedup check for blobs already in Kiri's store. + if method == "HEAD" && let Some(digest) = sub.strip_prefix("blobs/") { + let Ok(hex) = kiri_image::store::digest_hex(digest) else { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + }; + let valid_digest = format!("sha256:{}", hex.to_ascii_lowercase()); + let pin = engine.store.pin(&valid_digest); + if let Ok(path) = engine.store.blob_path(&valid_digest) && let Ok(meta) = std::fs::metadata(&path) && meta.is_file() { + if !slot.record_blob(pin, None) { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + head(w, "200 OK", &format!("Docker-Content-Digest: {valid_digest}\r\n"), meta.len())?; + return w.flush(); + } + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + + // POST /blobs/uploads/ (start chunked upload, cross-repo mount, or monolithic upload). + if method == "POST" && matches!(sub, "blobs/uploads/" | "blobs/uploads") { + if let Some(expected) = query_param(query, "digest") { + let Ok(hex) = kiri_image::store::digest_hex(&expected) else { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + }; + let expected = format!("sha256:{}", hex.to_ascii_lowercase()); + send_continue(w)?; + let existed = engine.store.blob_path(&expected).is_ok_and(|p| p.is_file()); + let mut ingest = engine.store.ingest()?; + read_http_body(r, framing, &mut ingest, None)?; + let (actual, _, pin) = ingest.finish_pinned()?; + if actual != expected { + drop(pin); + let _ = engine.store.remove_if_unused(&actual); + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + if !slot.record_blob(pin, (!existed).then_some(actual)) { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + head(w, "201 Created", &format!("Location: {base}/blobs/{expected}\r\nDocker-Content-Digest: {expected}\r\n"), 0)?; + return w.flush(); + } + if let Some(mount) = query_param(query, "mount") && let Ok(hex) = kiri_image::store::digest_hex(&mount) { + let mount = format!("sha256:{}", hex.to_ascii_lowercase()); + let pin = engine.store.pin(&mount); + if engine.store.blob_path(&mount).is_ok_and(|p| p.is_file()) { + if !slot.record_blob(pin, None) { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + head(w, "201 Created", &format!("Location: {base}/blobs/{mount}\r\nDocker-Content-Digest: {mount}\r\n"), 0)?; + return w.flush(); + } + } + let mut uploads = slot.uploads.lock().unwrap_or_else(|e| e.into_inner()); + if slot.closed.load(Ordering::Acquire) { + drop(uploads); + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + if uploads.len() >= MAX_LOAD_UPLOADS { + drop(uploads); + head(w, "429 Too Many Requests", "", 0)?; + return w.flush(); + } + let uuid = super::engine::random_hex(16); + let entry = UploadEntry { ingest: engine.store.ingest()?, written: 0 }; + uploads.insert(uuid.clone(), Arc::new(Mutex::new(Some(entry)))); + drop(uploads); + head(w, "202 Accepted", &format!("Location: {base}/blobs/uploads/{uuid}\r\nDocker-Upload-UUID: {uuid}\r\nRange: 0-0\r\n"), 0)?; + return w.flush(); + } + + // DELETE /blobs/uploads/: cancel an in-progress upload. + if method == "DELETE" && let Some(uuid) = sub.strip_prefix("blobs/uploads/") && is_hex_id(uuid) { + if slot.uploads.lock().unwrap_or_else(|e| e.into_inner()).remove(uuid).is_some() { + head(w, "204 No Content", "", 0)?; + } else { + head(w, "404 Not Found", "", 0)?; + } + return w.flush(); + } + + // PATCH /blobs/uploads/: stream chunk into an active upload. + if method == "PATCH" && let Some(uuid) = sub.strip_prefix("blobs/uploads/") && is_hex_id(uuid) { + let Some((id, handle)) = slot + .uploads + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get_key_value(uuid) + .map(|(k, v)| (k.clone(), v.clone())) + else { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + }; + send_continue(w)?; + let mut guard = handle.lock().unwrap_or_else(|e| e.into_inner()); + if slot.closed.load(Ordering::Acquire) { + let _ = guard.take(); + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + let Some(entry) = guard.as_mut() else { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + }; + let n = read_http_body(r, framing, &mut entry.ingest, None)?; + entry.written += n; + let end = entry.written.saturating_sub(1); + head(w, "202 Accepted", &format!("Location: {base}/blobs/uploads/{id}\r\nDocker-Upload-UUID: {id}\r\nRange: 0-{end}\r\n"), 0)?; + return w.flush(); + } + + // PUT /blobs/uploads/?digest=sha256:... : finalize upload into blob store. + if method == "PUT" && let Some(uuid) = sub.strip_prefix("blobs/uploads/") && is_hex_id(uuid) { + let Some(expected) = query_param(query, "digest").and_then(|d| { + kiri_image::store::digest_hex(&d).ok().map(|h| format!("sha256:{}", h.to_ascii_lowercase())) + }) else { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + }; + let Some(handle) = slot.uploads.lock().unwrap_or_else(|e| e.into_inner()).remove(uuid) else { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + }; + let mut guard = handle.lock().unwrap_or_else(|e| e.into_inner()); + let Some(mut entry) = guard.take() else { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + }; + drop(guard); + if slot.closed.load(Ordering::Acquire) { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + send_continue(w)?; + read_http_body(r, framing, &mut entry.ingest, None)?; + let existed = engine.store.blob_path(&expected).is_ok_and(|p| p.is_file()); + let (actual, _, pin) = entry.ingest.finish_pinned()?; + if actual != expected { + drop(pin); + let _ = engine.store.remove_if_unused(&actual); + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + if !slot.record_blob(pin, (!existed).then_some(actual)) { + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + head(w, "201 Created", &format!("Location: {base}/blobs/{expected}\r\nDocker-Content-Digest: {expected}\r\n"), 0)?; + return w.flush(); + } + + // HEAD /manifests/: always 404 so BuildKit pushes the final manifest. + if method == "HEAD" && let Some(reference) = sub.strip_prefix("manifests/") && !reference.contains('/') { + let _ = reference; + head(w, "404 Not Found", "", 0)?; + return w.flush(); + } + + // PUT /manifests/: commit image(s) into Kiri's store. + if method == "PUT" && let Some(reference) = sub.strip_prefix("manifests/") && !reference.contains('/') { + send_continue(w)?; + let mut body = Vec::new(); + if let Err(e) = read_http_body(r, framing, &mut body, Some(MAX_MANIFEST)) { + let status = if e.kind() == io::ErrorKind::FileTooLarge { "413 Payload Too Large" } else { "400 Bad Request" }; + head(w, status, "", 0)?; + return w.flush(); + } + let manifest_digest = kiri_image::store::sha256_digest(&body); + if reference.starts_with("sha256:") { + if manifest_digest != reference { + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + let mut children = slot.child_manifests.lock().unwrap_or_else(|e| e.into_inner()); + if children.len() >= MAX_LOAD_CHILD_MANIFESTS && !children.contains_key(&manifest_digest) { + drop(children); + head(w, "429 Too Many Requests", "", 0)?; + return w.flush(); + } + children.insert(manifest_digest.clone(), body); + drop(children); + head(w, "201 Created", &format!("Docker-Content-Digest: {manifest_digest}\r\n"), 0)?; + return w.flush(); + } + match commit_load_manifest(engine, &slot, &body) { + Ok(()) => { + head(w, "201 Created", &format!("Docker-Content-Digest: {manifest_digest}\r\n"), 0)?; + return w.flush(); + } + Err(e) => { + crate::diag::warn!("build mirror image commit failed", error = e); + head(w, "400 Bad Request", "", 0)?; + return w.flush(); + } + } + } + + head(w, "405 Method Not Allowed", "", 0)?; + w.flush() +} + +fn layer_media_type(path: &std::path::Path) -> &'static str { + let mut magic = [0u8; 4]; + let n = std::fs::File::open(path).and_then(|mut f| f.read(&mut magic)).unwrap_or(0); + match &magic[..n] { + [0x1f, 0x8b, ..] => "application/vnd.oci.image.layer.v1.tar+gzip", + [0x28, 0xb5, 0x2f, 0xfd] => "application/vnd.oci.image.layer.v1.tar+zstd", + _ => "application/vnd.oci.image.layer.v1.tar", + } +} + +fn commit_load_manifest(engine: &Engine, slot: &LoadSlot, raw: &[u8]) -> io::Result<()> { + if slot.closed.load(Ordering::Acquire) { + return Err(io::Error::new(io::ErrorKind::BrokenPipe, "load session closed")); + } + let parsed: Value = serde_json::from_slice(raw).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("manifest JSON: {e}")))?; + // If BuildKit pushed an OCI image index (e.g. with attestations), resolve + // the matching platform image manifest from the previously pushed children. + let manifest: Value = if let Some(list) = parsed["manifests"].as_array() { + let host = Platform::host_linux(); + let is_image = |m: &&Value| { + let ref_type = m["annotations"]["vnd.docker.reference.type"].as_str(); + let os = m["platform"]["os"].as_str().unwrap_or("linux"); + let arch = m["platform"]["architecture"].as_str().unwrap_or(""); + ref_type != Some("attestation-manifest") && os != "unknown" && arch != "unknown" + }; + let chosen = list + .iter() + .filter(is_image) + .find(|m| { + m["platform"]["os"].as_str() == Some(host.os.as_str()) + && m["platform"]["architecture"].as_str() == Some(host.architecture.as_str()) + }) + .or_else(|| list.iter().find(is_image)) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "image index contains no runnable manifest"))?; + let digest = chosen["digest"].as_str().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "index entry missing digest"))?; + let children = slot.child_manifests.lock().unwrap_or_else(|e| e.into_inner()); + let child_bytes = children.get(digest).ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("missing child manifest {digest}")))?; + serde_json::from_slice(child_bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("child manifest JSON: {e}")))? + } else { + parsed + }; + + let config_digest = manifest["config"]["digest"] + .as_str() + .filter(|d| kiri_image::store::digest_hex(d).is_ok()) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "manifest missing config digest"))? + .to_owned(); + let mut extra_pins = vec![engine.store.pin(&config_digest)]; + let config_bytes = engine.store.read_config(&config_digest)?; + let config_json: Value = serde_json::from_slice(&config_bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("image config: {e}")))?; + + let mut layers = Vec::new(); + let mut used = vec![config_digest.clone()]; + for l in manifest["layers"].as_array().into_iter().flatten() { + let digest = l["digest"] + .as_str() + .filter(|d| kiri_image::store::digest_hex(d).is_ok()) + .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "layer missing digest"))? + .to_owned(); + extra_pins.push(engine.store.pin(&digest)); + let path = engine.store.blob_path(&digest)?; + let size = std::fs::metadata(&path)?.len(); + let media_type = l["mediaType"] + .as_str() + .filter(|m| !m.is_empty()) + .map(str::to_owned) + .unwrap_or_else(|| layer_media_type(&path).to_owned()); + used.push(digest.clone()); + layers.push(Layer { digest, size, media_type }); + } + + let mut pins = slot.pins.lock().unwrap_or_else(|e| e.into_inner()); + if slot.closed.load(Ordering::Acquire) { + return Err(io::Error::new(io::ErrorKind::BrokenPipe, "load session closed")); + } + let target_tags = slot.target_tags.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let names = if target_tags.is_empty() { vec![config_digest.clone()] } else { target_tags }; + for name in &names { + let img = kiri_image::archive::from_config(name.clone(), &config_digest, &config_json, layers.clone()); + engine.store.put_image(img)?; + if !name.starts_with("sha256:") { + engine.emit_image("tag", &config_digest, name); + } + } + engine.prune_layers(); + pins.extend(extra_pins); + slot.used_digests.lock().unwrap_or_else(|e| e.into_inner()).extend(used); + *slot.committed_digest.lock().unwrap_or_else(|e| e.into_inner()) = Some(config_digest); + Ok(()) +} + +const OCI_MANIFEST: &str = "application/vnd.oci.image.manifest.v1+json"; +const OCI_INDEX: &str = "application/vnd.oci.image.index.v1+json"; +const MAX_MANIFEST: u64 = 4 << 20; + #[derive(Debug)] enum Found { - Manifest(Vec, String), - Blob(std::path::PathBuf, String), + Manifest(Vec, String, String), + Blob(std::path::PathBuf, String, kiri_image::store::Pin), +} + +/// Content-Type for raw manifest or index JSON `bytes`. +fn manifest_media_type(bytes: &[u8]) -> String { + if let Ok(v) = serde_json::from_slice::(bytes) { + if let Some(mt) = v["mediaType"].as_str().map(str::trim).filter(|m| !m.is_empty() && !m.contains(['\r', '\n'])) { + return mt.to_owned(); + } + if v.get("manifests").is_some() { + return OCI_INDEX.to_owned(); + } + } + OCI_MANIFEST.to_owned() +} + +/// Reads a raw upstream manifest or multi-arch index blob saved during `pull`, +/// verifying that its bytes hash to `digest`. +fn stored_manifest(store: &kiri_image::Store, digest: &str) -> Option<(Vec, String)> { + let path = store.blob_path(digest).ok()?; + let len = std::fs::metadata(&path).ok()?.len(); + if len > MAX_MANIFEST { + return None; + } + let bytes = std::fs::read(path).ok()?; + (kiri_image::store::sha256_digest(&bytes) == digest).then(|| { + let media_type = manifest_media_type(&bytes); + (bytes, media_type) + }) } /// An image's manifest as Kiri serves it, and its digest. @@ -381,7 +1150,7 @@ fn manifest(store: &kiri_image::Store, i: &Image) -> Option<(Vec, String)> { let config_size = std::fs::metadata(store.blob_path(&i.config_digest).ok()?).ok()?.len(); let m = json!({ "schemaVersion": 2, - "mediaType": "application/vnd.oci.image.manifest.v1+json", + "mediaType": OCI_MANIFEST, "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": i.config_digest, "size": config_size}, "layers": i.layers.iter().map(|l| json!({"mediaType": l.media_type, "digest": l.digest, "size": l.size})).collect::>(), }); @@ -403,23 +1172,78 @@ fn parse(path: &str, token: &str) -> Option<(String, String, bool, String)> { (!repo.is_empty() && !reference.is_empty() && !reference.contains('/')).then(|| (registry.to_owned(), repo.to_owned(), kind, reference.to_owned())) } -fn lookup(engine: &Engine, path: &str, token: &str) -> Option { +/// Whether the mirror answers for `i` under its tag. It does for an image no +/// registry has (built, loaded, committed: its digest is its config's), which +/// is the one thing a build cannot get anywhere else. An image a registry +/// published is left to that registry, which knows every platform of the tag; +/// answering with the one platform Kiri pulled would hide the rest. +fn serve_tag(i: &Image) -> bool { + i.repo_digest().is_none() +} + +fn lookup(store: &kiri_image::Store, path: &str, token: &str) -> Option { let (registry, repo, is_manifest, reference) = parse(path, token)?; - let images = engine.store.images().ok()?; let in_repo = |i: &&Image| Reference::parse(&i.name).is_ok_and(|n| n.registry == registry && n.repository == repo); if is_manifest { if reference.starts_with("sha256:") { - return images.iter().filter(in_repo).find_map(|i| manifest(&engine.store, i).filter(|(_, d)| *d == reference)).map(|(b, d)| Found::Manifest(b, d)); + // Pin owned raw manifest/index and repo config blobs under the + // index lock so a concurrent `put_image` overwrite cannot delete + // them before `stored_manifest` / `manifest` reads them. + let (raw_pin, repo_images) = store + .with_images(|images| { + let raw_pin = images + .iter() + .filter(in_repo) + .any(|i| i.digest == reference || i.index_digest.as_deref() == Some(reference.as_str())) + .then(|| store.pin(&reference)); + let repo_images: Vec<(Image, kiri_image::store::Pin)> = + images.iter().filter(in_repo).map(|i| (i.clone(), store.pin(&i.config_digest))).collect(); + (raw_pin, repo_images) + }) + .ok()?; + // Serve the exact raw manifest or multi-arch index bytes saved + // during `docker pull` when an image in this repository owns that + // digest, so digest-pinned builds (`FROM repo:tag@sha256:…` or + // `FROM repo@sha256:…`) verify cleanly from Kiri's store (#288, #330). + if raw_pin.is_some() + && let Some((b, mt)) = stored_manifest(store, &reference) + { + return Some(Found::Manifest(b, mt, reference)); + } + return repo_images + .iter() + .find_map(|(i, _)| manifest(store, i).filter(|(_, d)| *d == reference)) + .map(|(b, d)| Found::Manifest(b, OCI_MANIFEST.to_owned(), d)); } let wanted = Reference::parse(&format!("{registry}/{repo}:{reference}")).ok()?.short(); - let i = images.iter().find(|i| i.name == wanted)?; - let (b, d) = manifest(&engine.store, i)?; - return Some(Found::Manifest(b, d)); + // A tag a registry published is the registry's to answer: Kiri holds + // the one platform it pulled, and serving that says the tag has no + // other, so a build for another platform takes these binaries and + // fails on them (issue #57). 404 here makes the builder skip this + // mirror and pull the platform it asked for. + let (i, _pin) = store + .with_images(|images| { + let i = images.iter().find(|i| i.name == wanted && serve_tag(i))?.clone(); + let pin = store.pin(&i.config_digest); + Some((i, pin)) + }) + .ok()??; + let (b, d) = manifest(store, &i)?; + return Some(Found::Manifest(b, OCI_MANIFEST.to_owned(), d)); } - // Only blobs of that repository's images. - let owned = images.iter().filter(in_repo).any(|i| i.config_digest == reference || i.layers.iter().any(|l| l.digest == reference)); - let path = engine.store.blob_path(&reference).ok()?; - (owned && path.is_file()).then_some(Found::Blob(path, reference)) + // Only blobs of that repository's images. Keep the pin inside `Found::Blob` + // until `answer` finishes opening and streaming the file. + let pin = store + .with_images(|images| { + images + .iter() + .filter(in_repo) + .any(|i| i.referenced_digests().any(|d| d == reference)) + .then(|| store.pin(&reference)) + }) + .ok()??; + let path = store.blob_path(&reference).ok()?; + path.is_file().then_some(Found::Blob(path, reference, pin)) } #[cfg(test)] @@ -536,6 +1360,151 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_tag_a_registry_published_is_left_to_it() { + // Pulled: its digest is its manifest's, so a registry has it. + let pulled = Image { name: "alpine:3.20".into(), digest: "sha256:manifest".into(), ..made_here() }; + assert!(!serve_tag(&pulled)); + // Pulled through a configured Docker Hub mirror (#119) or from a multi-arch index. + let mirrored = Image { mirror: Some("mirror.lan:5000".into()), index_digest: Some("sha256:index".into()), ..pulled.clone() }; + assert!(!serve_tag(&mirrored)); + // Another tag in the same repository still carries that repository's digest. + assert!(!serve_tag(&pulled.tagged("alpine:latest".into()))); + // Built, loaded or committed here: nothing else can serve it, platform or not. + assert!(serve_tag(&made_here())); + // Tagged into another repository (docker tag alpine:3.20 mybase:dev): + // that name is not in any registry, so the mirror answers for it. + assert!(serve_tag(&pulled.tagged("mybase:dev".into()))); + } + + #[test] + fn lookup_skips_published_tags_but_serves_local_tags_digests_and_blobs() { + let dir = std::env::temp_dir().join(format!("kiri-mirror-lookup-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let write_blob = |bytes: &[u8]| { + let mut w = store.ingest().unwrap(); + w.write_all(bytes).unwrap(); + w.finish().unwrap() + }; + let cfg = json!({"architecture": "amd64", "os": "linux", "config": {}}); + let (cfg_digest, _) = write_blob(&serde_json::to_vec(&cfg).unwrap()); + let (layer_digest, layer_size) = write_blob(b"layer-bytes"); + let layers = vec![kiri_image::Layer { digest: layer_digest.clone(), size: layer_size, media_type: "application/vnd.oci.image.layer.v1.tar+gzip".into() }]; + + // 1. Registry-pulled image (also when pulled via a #119 mirror): tag + // lookup returns None (404) so BuildKit falls through to the configured + // mirror or upstream registry, while digest and blob lookups still hit + // the local store so cached layers are not re-downloaded. + let pulled = Image { + name: "alpine:3.20".into(), + digest: format!("sha256:{}", "a".repeat(64)), + index_digest: Some(format!("sha256:{}", "b".repeat(64))), + mirror: Some("mirror.lan:5000".into()), + ..kiri_image::archive::from_config("alpine:3.20".into(), &cfg_digest, &cfg, layers.clone()) + }; + let (_, pulled_manifest_digest) = manifest(&store, &pulled).unwrap(); + store.put_image(pulled.clone()).unwrap(); + + assert!(lookup(&store, "/v2/tok/docker.io/library/alpine/manifests/3.20", "tok").is_none()); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/alpine/manifests/{pulled_manifest_digest}"), "tok"), + Some(Found::Manifest(_, _, d)) if d == pulled_manifest_digest + )); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/alpine/blobs/{layer_digest}"), "tok"), + Some(Found::Blob(_, d, _)) if d == layer_digest + )); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/alpine/blobs/{cfg_digest}"), "tok"), + Some(Found::Blob(_, d, _)) if d == cfg_digest + )); + // Another repository cannot read alpine's blobs. + assert!(lookup(&store, &format!("/v2/tok/docker.io/library/other/blobs/{layer_digest}"), "tok").is_none()); + + // 2. Retagged into a local repository (`docker tag alpine:3.20 mybase:dev`): + // served by tag and by blob under the new repository. + store.put_image(pulled.tagged("mybase:dev".into())).unwrap(); + assert!(matches!( + lookup(&store, "/v2/tok/docker.io/library/mybase/manifests/dev", "tok"), + Some(Found::Manifest(_, _, d)) if d == pulled_manifest_digest + )); + assert!(matches!( + lookup(&store, &format!("/v2/tok/docker.io/library/mybase/blobs/{layer_digest}"), "tok"), + Some(Found::Blob(_, d, _)) if d == layer_digest + )); + + // 3. Built, loaded or committed here: served by tag until pushed to a registry. + let local = kiri_image::archive::from_config("localhost:5000/myapp:dev".into(), &cfg_digest, &cfg, layers.clone()); + store.put_image(local).unwrap(); + assert!(matches!(lookup(&store, "/v2/tok/localhost:5000/myapp/manifests/dev", "tok"), Some(Found::Manifest(..)))); + store.set_pushed("localhost:5000/myapp:dev", &cfg_digest, &format!("sha256:{}", "c".repeat(64))).unwrap(); + assert!(lookup(&store, "/v2/tok/localhost:5000/myapp/manifests/dev", "tok").is_none()); + + // 4. Digest-pinned multi-arch pull (`docker pull oven/bun:1-alpine@sha256:`): + // raw index and platform manifest bytes are served verbatim with their + // upstream Content-Type so BuildKit's SHA-256 verification succeeds (#288, #330). + let raw_manifest = format!( + "{{\n \"schemaVersion\": 2,\n \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\",\n \"config\": {{\"mediaType\": \"application/vnd.docker.container.image.v1+json\", \"size\": 42, \"digest\": \"{cfg_digest}\"}},\n \"layers\": [{{\"mediaType\": \"application/vnd.docker.image.rootfs.diff.tar.gzip\", \"size\": {layer_size}, \"digest\": \"{layer_digest}\"}}]\n}}" + ); + let (raw_man_digest, _) = write_blob(raw_manifest.as_bytes()); + let raw_index = format!( + "{{\n \"schemaVersion\": 2,\n \"mediaType\": \"application/vnd.oci.image.index.v1+json\",\n \"manifests\": [\n {{\"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\", \"size\": {}, \"digest\": \"{raw_man_digest}\", \"platform\": {{\"architecture\": \"amd64\", \"os\": \"linux\"}}}},\n {{\"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\", \"size\": 999, \"digest\": \"sha256:{}\", \"platform\": {{\"architecture\": \"arm64\", \"os\": \"linux\"}}}}\n ]\n}}", + raw_manifest.len(), + "e".repeat(64) + ); + let (raw_idx_digest, _) = write_blob(raw_index.as_bytes()); + let pinned = Image { + name: format!("oven/bun@{raw_idx_digest}"), + digest: raw_man_digest.clone(), + index_digest: Some(raw_idx_digest.clone()), + ..kiri_image::archive::from_config(format!("oven/bun@{raw_idx_digest}"), &cfg_digest, &cfg, layers) + }; + store.put_image(pinned).unwrap(); + match lookup(&store, &format!("/v2/tok/docker.io/oven/bun/manifests/{raw_idx_digest}"), "tok") { + Some(Found::Manifest(b, mt, d)) => { + assert_eq!(b, raw_index.as_bytes(), "exact upstream index bytes"); + assert_eq!(kiri_image::store::sha256_digest(&b), raw_idx_digest); + assert_eq!(mt, "application/vnd.oci.image.index.v1+json"); + assert_eq!(d, raw_idx_digest); + } + other => panic!("expected raw index manifest, got {other:?}"), + } + match lookup(&store, &format!("/v2/tok/docker.io/oven/bun/manifests/{raw_man_digest}"), "tok") { + Some(Found::Manifest(b, mt, d)) => { + assert_eq!(b, raw_manifest.as_bytes(), "exact upstream platform manifest bytes"); + assert_eq!(kiri_image::store::sha256_digest(&b), raw_man_digest); + assert_eq!(mt, "application/vnd.docker.distribution.manifest.v2+json"); + assert_eq!(d, raw_man_digest); + } + other => panic!("expected raw platform manifest, got {other:?}"), + } + // Unpulled platform digest returns None (404) so BuildKit falls back to the registry. + assert!(lookup(&store, &format!("/v2/tok/docker.io/oven/bun/manifests/sha256:{}", "e".repeat(64)), "tok").is_none()); + // Cross-repo isolation holds for raw manifests too. + assert!(lookup(&store, &format!("/v2/tok/docker.io/library/other/manifests/{raw_idx_digest}"), "tok").is_none()); + + let _ = std::fs::remove_dir_all(&dir); + } + + /// An image built here: no registry has it. + fn made_here() -> Image { + let config_digest = "sha256:config".to_owned(); + Image { + name: "myapp:dev".into(), + digest: config_digest.clone(), + index_digest: None, + config_digest, + layers: Vec::new(), + size: 0, + platform: "linux/amd64".into(), + created: String::new(), + pulled_at: 0, + config: kiri_image::RunConfig::default(), + mirror: None, + } + } + #[test] fn token_file_is_private_from_the_start() { use std::os::unix::fs::PermissionsExt; @@ -548,4 +1517,183 @@ mod tests { assert_eq!(std::fs::read_to_string(&p).unwrap(), "0123456789abcdef0123456789abcdef"); let _ = std::fs::remove_file(&p); } + + /// A registry name from an image reaches buildkitd.toml. A quote, a + /// backslash or a newline in it must not close the string or inject a + /// table: buildkitd refuses the whole file, and every build fails until + /// the image is removed (#746). + #[test] + fn names_are_quoted_for_toml() { + assert_eq!(super::quoted("registry.corp"), "\"registry.corp\""); + assert_eq!(super::quoted("evil\".com"), "\"evil\\\".com\""); + assert_eq!(super::quoted("a\\b"), "\"a\\\\b\""); + assert_eq!(super::quoted("a\nb\rc\td"), "\"a\\nb\\rc\\td\""); + assert_eq!(super::quoted("a\u{7}b\u{7f}c"), "\"a\\u0007b\\u007Fc\""); + let mut tables = Vec::new(); + add_mirror(&mut tables, "evil\"].com\n[worker.oci]", "127.0.0.1:47391/tok/evil\"].com\n[worker.oci]".into()); + let toml = super::format_tables(&tables); + assert_eq!( + toml, + "[registry.\"evil\\\"].com\\n[worker.oci]\"]\n mirrors = [\"127.0.0.1:47391/tok/evil\\\"].com\\n[worker.oci]\"]\n" + ); + // A name that could have carried one is not a reference any more. + for bad in ["evil\".com/x:1", "evil\\com/x:1", "host/x:ta\"g", "host/x?y:1", "h#x/y:1"] { + assert!(kiri_image::Reference::parse(bad).is_err(), "{bad:?}"); + } + } + + #[test] + fn load_session_accepts_oci_push_and_cleans_up_aborted_blobs() { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("kiri-mirror-load-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + let engine = Engine::boot(store).unwrap(); + + let send = |req: &[u8]| -> String { + let mut r = BufReader::new(io::Cursor::new(req)); + let mut w = Vec::new(); + answer_stream(&mut r, &mut w, &engine).unwrap(); + String::from_utf8(w).unwrap() + }; + + // /v2/ ping answers 200. + assert!(send(b"GET /v2/ HTTP/1.1\r\nHost: d\r\n\r\n").starts_with("HTTP/1.1 200 OK")); + + // Seed an existing base layer to test HEAD dedup. + let mut bw = engine.store.ingest().unwrap(); + bw.write_all(b"base-layer").unwrap(); + let (base_digest, _) = bw.finish().unwrap(); + + let session = LoadSession::new(engine.clone(), vec!["probe-incontainer:latest".into(), "probe-alias:1".into()]); + let prefix = format!("/v2/load/{}/image", session.nonce); + + // HEAD for existing base blob -> 200; missing blob -> 404. + let head_ok = send(format!("HEAD {prefix}/blobs/{base_digest} HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()); + assert!(head_ok.starts_with("HTTP/1.1 200 OK"), "{head_ok}"); + let missing = format!("sha256:{}", "0".repeat(64)); + assert!(send(format!("HEAD {prefix}/blobs/{missing} HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()).starts_with("HTTP/1.1 404 ")); + + // Push a new layer via POST + PATCH (chunked) + PUT with percent-encoded digest. + let new_layer = b"hello-new-layer"; + let new_digest = kiri_image::store::sha256_digest(new_layer); + let started = send(format!("POST {prefix}/blobs/uploads/ HTTP/1.1\r\nHost: d\r\nContent-Length: 0\r\n\r\n").as_bytes()); + assert!(started.starts_with("HTTP/1.1 202 Accepted"), "{started}"); + let loc = started.lines().find_map(|l| l.strip_prefix("Location: ")).unwrap().trim().to_owned(); + let patch_req = format!( + "PATCH {loc} HTTP/1.1\r\nHost: d\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nhello-\r\n0\r\n\r\n" + ); + let patched = send(patch_req.as_bytes()); + assert!(patched.starts_with("HTTP/1.1 202 Accepted"), "{patched}"); + let enc_digest = new_digest.replace(':', "%3A"); + let mut put_req = format!("PUT {loc}?digest={enc_digest} HTTP/1.1\r\nHost: d\r\nContent-Length: 9\r\n\r\n").into_bytes(); + put_req.extend_from_slice(b"new-layer"); + let finished = send(&put_req); + assert!(finished.starts_with("HTTP/1.1 201 Created"), "{finished}"); + + // Push image config via monolithic POST ?digest=... + let cfg = serde_json::to_vec(&json!({ + "os": "linux", + "architecture": "amd64", + "created": "2026-11-24T00:00:00Z", + "config": {"Cmd": ["sh"]}, + "rootfs": {"type": "layers", "diff_ids": [base_digest, new_digest]} + })) + .unwrap(); + let cfg_digest = kiri_image::store::sha256_digest(&cfg); + let mut cfg_req = format!( + "POST {prefix}/blobs/uploads/?digest={} HTTP/1.1\r\nHost: d\r\nContent-Length: {}\r\n\r\n", + cfg_digest.replace(':', "%3A"), + cfg.len() + ) + .into_bytes(); + cfg_req.extend_from_slice(&cfg); + assert!(send(&cfg_req).starts_with("HTTP/1.1 201 Created")); + + // Push child platform manifest by digest, then OCI index with an attestation entry. + let child = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "mediaType": OCI_MANIFEST, + "config": {"mediaType": "application/vnd.oci.image.config.v1+json", "digest": cfg_digest, "size": cfg.len()}, + "layers": [ + {"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": base_digest, "size": 10}, + {"mediaType": "application/vnd.oci.image.layer.v1.tar", "digest": new_digest, "size": new_layer.len()}, + ] + })) + .unwrap(); + let child_digest = kiri_image::store::sha256_digest(&child); + let mut child_req = format!("PUT {prefix}/manifests/{child_digest} HTTP/1.1\r\nHost: d\r\nContent-Length: {}\r\n\r\n", child.len()).into_bytes(); + child_req.extend_from_slice(&child); + assert!(send(&child_req).starts_with("HTTP/1.1 201 Created")); + + let index = serde_json::to_vec(&json!({ + "schemaVersion": 2, + "mediaType": OCI_INDEX, + "manifests": [ + {"mediaType": OCI_MANIFEST, "digest": child_digest, "size": child.len(), "platform": {"os": "linux", "architecture": "amd64"}}, + {"mediaType": OCI_MANIFEST, "digest": missing, "size": 12, "platform": {"os": "unknown", "architecture": "unknown"}, "annotations": {"vnd.docker.reference.type": "attestation-manifest"}}, + ] + })) + .unwrap(); + let mut idx_req = format!("PUT {prefix}/manifests/out HTTP/1.1\r\nHost: d\r\nContent-Length: {}\r\n\r\n", index.len()).into_bytes(); + idx_req.extend_from_slice(&index); + assert!(send(&idx_req).starts_with("HTTP/1.1 201 Created")); + + assert_eq!(session.committed_digest().as_deref(), Some(cfg_digest.as_str())); + let img1 = engine.store.find("probe-incontainer:latest").unwrap().expect("tagged image stored"); + let img2 = engine.store.find("probe-alias:1").unwrap().expect("second tag stored"); + assert_eq!(img1.config_digest, cfg_digest); + assert_eq!(img2.config_digest, cfg_digest); + assert!(serve_tag(&img1), "locally built image must be served by mirror for subsequent FROM"); + drop(session); + + // Nonce is invalid after drop. + assert!(send(format!("HEAD {prefix}/blobs/{base_digest} HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()).starts_with("HTTP/1.1 404 ")); + + // Aborted session cleans up its uncommitted uploaded blob on drop. + let aborted = LoadSession::new(engine.clone(), vec!["never-committed:1".into()]); + let aprefix = format!("/v2/load/{}/image", aborted.nonce); + let orphan = b"orphan-uncommitted-blob"; + let orphan_digest = kiri_image::store::sha256_digest(orphan); + let mut oreq = format!( + "POST {aprefix}/blobs/uploads/?digest={} HTTP/1.1\r\nHost: d\r\nContent-Length: {}\r\n\r\n", + orphan_digest.replace(':', "%3A"), + orphan.len() + ) + .into_bytes(); + oreq.extend_from_slice(orphan); + assert!(send(&oreq).starts_with("HTTP/1.1 201 Created")); + assert!(engine.store.blob_path(&orphan_digest).unwrap().is_file()); + drop(aborted); + assert!(!engine.store.blob_path(&orphan_digest).unwrap().exists(), "aborted session blob must be removed on drop"); + + // Untagged LoadSession stores image under its config_digest, DELETE cancels upload, + // and invalid digests / path-traversal / conflicting framing are rejected. + let untagged = LoadSession::new(engine.clone(), Vec::new()); + let uprefix = format!("/v2/load/{}/image", untagged.nonce); + // Invalid digests and path-traversal attempts on HEAD are rejected with 400 (never touch filesystem). + assert!(send(format!("HEAD {uprefix}/blobs/sha256:../../etc/passwd HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()).starts_with("HTTP/1.1 400 ")); + assert!(send(format!("HEAD {uprefix}/blobs/notadigest HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()).starts_with("HTTP/1.1 400 ")); + // Conflicting Content-Length and Transfer-Encoding is rejected with 400. + assert!( + send(format!("POST {uprefix}/blobs/uploads/ HTTP/1.1\r\nHost: d\r\nContent-Length: 5\r\nTransfer-Encoding: chunked\r\n\r\n").as_bytes()) + .starts_with("HTTP/1.1 400 ") + ); + // DELETE cancels an active upload. + let started2 = send(format!("POST {uprefix}/blobs/uploads/ HTTP/1.1\r\nHost: d\r\nContent-Length: 0\r\n\r\n").as_bytes()); + let loc2 = started2.lines().find_map(|l| l.strip_prefix("Location: ")).unwrap().trim().to_owned(); + assert!(send(format!("DELETE {loc2} HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()).starts_with("HTTP/1.1 204 ")); + assert!(send(format!("DELETE {loc2} HTTP/1.1\r\nHost: d\r\n\r\n").as_bytes()).starts_with("HTTP/1.1 404 ")); + // Commit single-platform manifest directly into untagged session. + let mut ureq = format!("PUT {uprefix}/manifests/out HTTP/1.1\r\nHost: d\r\nContent-Length: {}\r\n\r\n", child.len()).into_bytes(); + ureq.extend_from_slice(&child); + assert!(send(&ureq).starts_with("HTTP/1.1 201 Created")); + assert_eq!(untagged.committed_digest().as_deref(), Some(cfg_digest.as_str())); + assert!(engine.store.find(&cfg_digest).unwrap().is_some(), "untagged image stored under config digest"); + drop(untagged); + + drop(engine); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/daemon/mod.rs b/crates/kiri/src/daemon/mod.rs index 497bc2051..c58dc4050 100644 --- a/crates/kiri/src/daemon/mod.rs +++ b/crates/kiri/src/daemon/mod.rs @@ -5,7 +5,7 @@ #[cfg(target_os = "linux")] pub mod access; mod api; -mod binds; +pub(crate) mod binds; mod builder; mod caller; mod daemon_json; @@ -13,11 +13,18 @@ pub mod dns; pub mod tls; pub mod proxy; mod domains; -mod engine; +pub(crate) mod engine; mod filters; +mod grpc; mod health; mod hostetc; +// A Windows host's roots, for the engine in WSL. +#[cfg(any(target_os = "linux", test))] +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +mod hostroots; mod hostopts; +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) mod localtime; mod mirror; mod http; mod logfile; @@ -28,14 +35,18 @@ pub(crate) mod nfs; mod ops; pub(crate) mod ports; mod pulls; +pub(crate) mod rofs; mod seccomp; mod seccomp_names; +mod storage; pub mod time; mod top; +mod treecopy; #[cfg(target_os = "macos")] mod usb; mod vmcpu; mod vmlink; +pub(crate) mod vmnet; mod volumes; #[cfg(target_os = "macos")] mod watch; @@ -56,15 +67,38 @@ pub fn state_dir() -> io::Result { Ok(home.join(crate::flavor::STATE.get())) } -/// `~/.kiri/run/docker.sock`, beside OrbStack's `~/.orbstack/run/docker.sock`. +static BOUND_SOCKET: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Root on Linux uses `/run/kiri/docker.sock`; other users use `~/.kiri/run/docker.sock`, +/// beside OrbStack's `~/.orbstack/run/docker.sock`. pub fn socket_path() -> io::Result { - if let Some(s) = std::env::var_os("KIRI_SOCKET") { - return Ok(PathBuf::from(s)); + if let Some(s) = BOUND_SOCKET.get() { + return Ok(s.clone()); } - let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; + // SAFETY: geteuid cannot fail. + let linux_root = cfg!(target_os = "linux") && unsafe { libc::geteuid() } == 0; + socket_path_for(std::env::var_os("KIRI_SOCKET").as_deref(), linux_root, std::env::var_os("HOME").as_deref()) +} + +pub(crate) fn home_socket_path() -> io::Result { + home_socket_path_for(std::env::var_os("HOME").as_deref()) +} + +fn home_socket_path_for(home: Option<&std::ffi::OsStr>) -> io::Result { + let home = home.map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; Ok(home.join(crate::flavor::STATE.get()).join("run/docker.sock")) } +fn socket_path_for(override_path: Option<&std::ffi::OsStr>, linux_root: bool, home: Option<&std::ffi::OsStr>) -> io::Result { + if let Some(s) = override_path { + return Ok(PathBuf::from(s)); + } + if linux_root { + return Ok(PathBuf::from("/run/kiri/docker.sock")); + } + home_socket_path_for(home) +} + /// Raises the soft open-file limit to the hard one, as Go does for dockerd. /// launchd starts the daemon with 256, and each relayed connection holds /// four or five descriptors: a LAN client opening ~60 connections to a @@ -85,7 +119,62 @@ fn raise_open_files() { } } +#[cfg(any(target_os = "linux", test))] +fn ensure_linux_root(euid: u32) -> io::Result<()> { + if euid != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "on Linux, Kiri runs containers on this machine's kernel and needs root: run `sudo kiri host-access $USER` (or `sudo kiri daemon`)", + )); + } + Ok(()) +} + +#[cfg(any(target_os = "linux", test))] +fn sudo_uid_from(raw: Option<&std::ffi::OsStr>) -> Option { + let uid: u32 = raw?.to_str()?.parse().ok()?; + (uid != 0 && uid != u32::MAX).then_some(uid) +} + +#[cfg(target_os = "linux")] +const RUN_DOCKER_SOCK: &str = "/run/docker.sock"; +#[cfg(target_os = "linux")] +const VAR_RUN_DOCKER_SOCK: &str = "/var/run/docker.sock"; + +#[cfg(any(target_os = "linux", test))] +fn path_occupied(path: &std::path::Path) -> bool { + match std::fs::symlink_metadata(path) { + Ok(_) => true, + Err(e) => e.kind() != io::ErrorKind::NotFound, + } +} + +/// Best-effort links `/run/docker.sock -> /run/kiri/docker.sock` when neither +/// `/run/docker.sock` nor `/var/run/docker.sock` exists (no file, socket, or +/// symlink), matching `kiri.service`'s `ExecStartPost`. +#[cfg(any(target_os = "linux", test))] +fn maybe_link_docker_sock(run_link: &std::path::Path, var_run_link: &std::path::Path, target: &std::path::Path) { + if path_occupied(run_link) || path_occupied(var_run_link) { + return; + } + let _ = std::os::unix::fs::symlink(target, run_link); +} + +/// Removes `/run/docker.sock` on clean shutdown only if it still symlinks to +/// `/run/kiri/docker.sock`, matching `kiri.service`'s `ExecStopPost`. +#[cfg(any(target_os = "linux", test))] +fn cleanup_docker_sock_symlink(link: &std::path::Path, target: &std::path::Path) { + if std::fs::read_link(link).ok().as_deref() == Some(target) { + let _ = std::fs::remove_file(link); + } +} + pub fn run(_args: &[String]) -> io::Result<()> { + // On Linux, fail fast before binding any socket when invoked without root + // (inside a rootless user namespace such as `unshare -r`, geteuid() == 0). + // SAFETY: geteuid cannot fail. + #[cfg(target_os = "linux")] + ensure_linux_root(unsafe { libc::geteuid() })?; let t0 = Instant::now(); raise_open_files(); // SIGINT/SIGTERM shut down cleanly: power the guest off, remove the socket. @@ -103,24 +192,56 @@ pub fn run(_args: &[String]) -> io::Result<()> { libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut()); set }; - let socket = socket_path()?; + #[cfg_attr(not(target_os = "linux"), allow(unused_mut))] + let mut socket = socket_path()?; + #[cfg(target_os = "linux")] + let mut extra_home_socket = if std::env::var_os("KIRI_SOCKET").is_none() { + home_socket_path().ok().filter(|p| p != &socket) + } else { + None + }; if UnixStream::connect(&socket).is_ok() { - // Not an error: launchd (KeepAlive on failure) must not retry it. - diag::info!("engine already running", socket = socket.display()); - return Ok(()); + #[cfg(target_os = "linux")] + if let Some(home_sock) = extra_home_socket.take() + && UnixStream::connect(&home_sock).is_err() + { + socket = home_sock; + } else { + // Not an error: launchd (KeepAlive on failure) must not retry it. + diag::info!("engine already running", socket = socket.display()); + return Ok(()); + } + #[cfg(not(target_os = "linux"))] + { + // Not an error: launchd (KeepAlive on failure) must not retry it. + diag::info!("engine already running", socket = socket.display()); + return Ok(()); + } } - if let Some(dir) = socket.parent() { - std::fs::create_dir_all(dir)?; + let _ = BOUND_SOCKET.set(socket.clone()); + #[cfg(target_os = "linux")] + if rofs::is_wsl() + && let Err(e) = localtime::ensure_localtime() + { + diag::warn!("could not repair /etc/localtime", error = e); } - let _ = std::fs::remove_file(&socket); // stale, from a daemon that died - let listener = UnixListener::bind(&socket)?; - std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600))?; + if let Some(ref msg) = rofs::check_daemon_storage(None) { + diag::error!("storage filesystem is read-only", detail = msg); + } + let enrich_rofs = |e: io::Error, store_root: Option<&std::path::Path>| -> io::Error { + if let Some(msg) = rofs::check_daemon_storage(store_root) { + diag::error!("engine did not start", error = &msg); + return io::Error::new(e.kind(), msg); + } + e + }; // 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. + // Without an explicit group, root on Linux uses ordinary 0660 Unix + // group access (`docker` when present), so containerized SDK clients + // whose numeric uid has no host account can connect via socket gid. let access_group = std::env::var_os("KIRI_SOCKET_GROUP"); - if let Some(group) = &access_group { - socket_group(&socket, group)?; - } + let listener = bind_daemon_socket(&socket, access_group.as_deref()).map_err(|e| enrich_rofs(e, None))?; // On a Linux host (and WSL) containers that mount the engine's socket // are given this one instead (binds.rs), so the API knows their // connections by where they arrive (caller.rs). Made as the daemon's @@ -129,21 +250,27 @@ pub fn run(_args: &[String]) -> io::Result<()> { #[cfg(target_os = "linux")] let for_containers = { let path = caller::container_socket(&socket); - let _ = std::fs::remove_file(&path); - let listener = UnixListener::bind(&path)?; - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; - if let Some(group) = &access_group { - socket_group(&path, group)?; - } + let listener = bind_daemon_socket(&path, access_group.as_deref()).map_err(|e| enrich_rofs(e, None))?; (listener, path) }; + #[cfg(target_os = "linux")] + let extra_home = extra_home_socket.and_then(|path| { + if UnixStream::connect(&path).is_ok() { + return None; + } + bind_daemon_socket(&path, access_group.as_deref()).ok().map(|l| (l, path)) + }); // 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.as_path(), for_containers.1.as_path()], group)?; + let mut gated = vec![socket.as_path(), for_containers.1.as_path()]; + if let Some((_, ref home_path)) = extra_home { + gated.push(home_path.as_path()); + } + let gate = access::Gate::new(&gated, 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), @@ -151,13 +278,38 @@ pub fn run(_args: &[String]) -> io::Result<()> { gate.clone().watch()?; Some(gate) } - None => None, + None => { + if let Some(uid) = sudo_uid_from(std::env::var_os("SUDO_UID").as_deref()) { + access::grant_uid(&[socket.as_path(), for_containers.1.as_path()], uid); + } + None + } }; kiri_image::store::set_error_log(|message| diag::error!("image store", detail = message)); - let store = kiri_image::Store::open(kiri_image::Store::default_root()?)?; - let engine = engine::Engine::boot(store).inspect_err(|e| diag::error!("engine did not start", error = e))?; + let root = match kiri_image::Store::default_root() { + Ok(root) => root, + Err(e) => match kiri_image::storage::unavailable(&e) { + Some(missing) => { + return unavailable( + &listener, + socket, + set, + missing.to_owned(), + #[cfg(target_os = "linux")] + &gate, + ); + } + None => return Err(e), + }, + }; + let store = kiri_image::Store::open(&root).map_err(|e| enrich_rofs(e, Some(&root)))?; + let engine = engine::Engine::boot(store) + .map_err(|e| enrich_rofs(e, Some(&root))) + .inspect_err(|e| diag::error!("engine did not start", error = e))?; diag::info!("engine ready", version = env!("CARGO_PKG_VERSION"), ms = t0.elapsed().as_millis(), socket = format!("unix://{}", socket.display())); + // Settings → Storage moved the data and started this daemon on it. + storage::after_restart(&engine); // Crash files from earlier runs, if the person said they may go. diag::report::spawn_crash_sender(Duration::from_secs(30), Some(Duration::from_secs(6 * 3600))); // Container files in Finder, at ~/Kiri. A Linux host has them on its @@ -169,6 +321,15 @@ pub fn run(_args: &[String]) -> io::Result<()> { // daemon.json's insecure-registries and registry-mirrors, read again // whenever the file changes. kiri_image::set_config_source(daemon_json::current); + // The system's root certificates are read once, here while nothing + // waits for them, and not by the first pull: asking the macOS keychain + // about each of its certificates takes a moment (#303). + let _ = std::thread::Builder::new().name("kiri-tls-roots".into()).spawn(|| { + // In WSL, the Windows roots kiri-win sent last time (#303). + #[cfg(target_os = "linux")] + hostroots::load(); + let _ = kiri_image::roots::trusted(); + }); // The managed BuildKit stops itself when builds have been idle a while. builder::watch(engine.clone()); // A Kubernetes node the engine restarted gets its kubectl context. @@ -199,7 +360,30 @@ pub fn run(_args: &[String]) -> io::Result<()> { } } - watch_own_app(engine.clone(), socket.clone()); + #[cfg(target_os = "linux")] + let manage_docker_sock = std::env::var_os("KIRI_SOCKET").is_none() && socket == std::path::Path::new(crate::client::SERVICE_SOCKET); + #[cfg(target_os = "linux")] + if manage_docker_sock { + maybe_link_docker_sock( + std::path::Path::new(RUN_DOCKER_SOCK), + std::path::Path::new(VAR_RUN_DOCKER_SOCK), + std::path::Path::new(crate::client::SERVICE_SOCKET), + ); + } + + #[cfg(target_os = "linux")] + let extra_sock = extra_home.as_ref().map(|(_, p)| p.clone()); + #[cfg(not(target_os = "linux"))] + let extra_sock: Option = None; + watch_own_app( + engine.clone(), + socket.clone(), + extra_sock.clone(), + #[cfg(target_os = "linux")] + manage_docker_sock, + ); + + init_wsl_sockets(engine.clone()); let on_signal = engine.clone(); let sock = socket.clone(); @@ -210,8 +394,18 @@ pub fn run(_args: &[String]) -> io::Result<()> { diag::info!("engine shutting down", signal = sig); #[cfg(target_os = "macos")] nfs::unmount(); + #[cfg(target_os = "linux")] + if manage_docker_sock { + cleanup_docker_sock_symlink(std::path::Path::new(RUN_DOCKER_SOCK), std::path::Path::new(crate::client::SERVICE_SOCKET)); + } let _ = std::fs::remove_file(&sock); let _ = std::fs::remove_file(caller::container_socket(&sock)); + if let Some(ref extra) = extra_sock { + let _ = std::fs::remove_file(extra); + } + if let Some(ws) = WSL_SOCKETS.get() { + ws.remove_socket_files(); + } on_signal.shutdown(); // Give the guest a moment to power off before the VM is released. std::thread::sleep(std::time::Duration::from_millis(50)); @@ -220,6 +414,10 @@ pub fn run(_args: &[String]) -> io::Result<()> { #[cfg(target_os = "linux")] { + if let Some((extra_listener, _)) = extra_home { + let (engine_extra, gate_extra) = (engine.clone(), gate.clone()); + std::thread::Builder::new().name("kiri-api-home".into()).spawn(move || accept(&extra_listener, &engine_extra, &gate_extra, caller::Caller::Host))?; + } let (engine2, gate2) = (engine.clone(), gate.clone()); std::thread::Builder::new().name("kiri-api-containers".into()).spawn(move || accept(&for_containers.0, &engine2, &gate2, caller::Caller::Container))?; accept(&listener, &engine, &gate, caller::Caller::Host); @@ -229,30 +427,231 @@ pub fn run(_args: &[String]) -> io::Result<()> { Ok(()) } +#[cfg(target_os = "linux")] +#[cfg(test)] +fn admit_connection(gate: &Option>, conn: &UnixStream) -> Result, ()> { + admit_connection_for(gate, conn, None, &None) +} + +#[cfg(target_os = "linux")] +fn admit_connection_for( + gate: &Option>, + conn: &UnixStream, + pinned: Option, + container_engine: &Option>, +) -> Result, ()> { + match gate { + Some(gate) => { + let seat = match container_engine { + Some(eng) => gate.admit_container(conn, pinned, |cg| eng.has_running_container_cgroup(cg)), + None => gate.admit(conn), + }; + seat.map(Some).ok_or(()) + } + None => Ok(None), + } +} + /// Serves each connection `listener` takes, as `who`'s, on a thread of its own. fn accept( listener: &UnixListener, engine: &std::sync::Arc, #[cfg(target_os = "linux")] gate: &Option>, who: caller::Caller, +) { + let cap = open_conns_for(&who); + #[cfg(target_os = "linux")] + let container_engine = matches!(who, caller::Caller::Container).then(|| engine.clone()); + let engine = engine.clone(); + serve_each_inner( + listener, + cap, + #[cfg(target_os = "linux")] + gate, + #[cfg(target_os = "linux")] + container_engine, + std::sync::Arc::new(move |conn| { + let _ = api::serve(conn, engine.clone(), who.clone()); + }), + ); +} + +/// Maximum concurrent open client connections from host or WSL callers, kept +/// separate from [`MAX_CONTAINER_OPEN_CONNS`] so a container mounting +/// `/var/run/docker.sock` can never starve host UI `/events`, `docker ps`, +/// `exec`, or `kiri stop`. +const MAX_HOST_OPEN_CONNS: usize = 512; + +/// Maximum concurrent open client connections from containers mounting the +/// engine socket (`docker.container.sock` on Linux and the guest vsock relay +/// in `ports::serve_engine_api` on macOS). +const MAX_CONTAINER_OPEN_CONNS: usize = 128; + +/// Shared cap on concurrent client connections. Each accepted connection holds +/// a [`ConnPermit`] until its handler exits (or until dropped if thread +/// creation fails), so slots are never leaked. +pub(super) struct ConnCap { + open: std::sync::atomic::AtomicUsize, + limit: usize, + pool: &'static str, + last_warn: std::sync::Mutex>, +} + +pub(super) struct ConnPermit(std::sync::Arc); + +impl Drop for ConnPermit { + fn drop(&mut self) { + self.0.open.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + } +} + +impl ConnCap { + fn new(pool: &'static str, limit: usize) -> Self { + ConnCap { + open: std::sync::atomic::AtomicUsize::new(0), + limit, + pool, + last_warn: std::sync::Mutex::new(None), + } + } + + fn try_acquire(self: &std::sync::Arc) -> Option { + self.open + .fetch_update( + std::sync::atomic::Ordering::AcqRel, + std::sync::atomic::Ordering::Acquire, + |n| (n < self.limit).then_some(n + 1), + ) + .ok() + .map(|_| ConnPermit(self.clone())) + } + + fn warn_full(&self) { + let mut last = self.last_warn.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + if last.is_none_or(|t| t.elapsed() >= Duration::from_secs(5)) { + *last = Some(Instant::now()); + diag::warn!("too many open connections; the new one was not served", pool = self.pool, limit = self.limit); + } + } + + #[cfg(test)] + pub(super) fn open(&self) -> usize { + self.open.load(std::sync::atomic::Ordering::Acquire) + } + + #[cfg(test)] + pub(super) fn for_test(limit: usize) -> std::sync::Arc { + std::sync::Arc::new(Self::new("test", limit)) + } + + #[cfg(test)] + pub(super) fn try_acquire_for_test(self: &std::sync::Arc) -> Option { + self.try_acquire() + } +} + +fn host_open_conns() -> &'static std::sync::Arc { + static HOST_OPEN_CONNS: std::sync::OnceLock> = std::sync::OnceLock::new(); + HOST_OPEN_CONNS.get_or_init(|| std::sync::Arc::new(ConnCap::new("host", MAX_HOST_OPEN_CONNS))) +} + +fn container_open_conns() -> &'static std::sync::Arc { + static CONTAINER_OPEN_CONNS: std::sync::OnceLock> = std::sync::OnceLock::new(); + CONTAINER_OPEN_CONNS.get_or_init(|| std::sync::Arc::new(ConnCap::new("container", MAX_CONTAINER_OPEN_CONNS))) +} + +fn open_conns_for(who: &caller::Caller) -> &'static std::sync::Arc { + match who { + caller::Caller::Container => container_open_conns(), + caller::Caller::Host | caller::Caller::Wsl(_) => host_open_conns(), + } +} + +fn try_acquire_from(cap: &std::sync::Arc) -> Option { + let permit = cap.try_acquire(); + if permit.is_none() { + cap.warn_full(); + } + permit +} + +pub(super) fn try_acquire_host_conn() -> Option { + try_acquire_from(host_open_conns()) +} + +pub(super) fn try_acquire_container_conn() -> Option { + try_acquire_from(container_open_conns()) +} + +/// Hands each host connection `listener` takes to `serve`, on a thread of its own. +fn serve_each( + listener: &UnixListener, + #[cfg(target_os = "linux")] gate: &Option>, + serve: std::sync::Arc, +) { + serve_each_with( + listener, + host_open_conns(), + #[cfg(target_os = "linux")] + gate, + serve, + ); +} + +fn serve_each_with( + listener: &UnixListener, + cap: &std::sync::Arc, + #[cfg(target_os = "linux")] gate: &Option>, + serve: std::sync::Arc, +) { + serve_each_inner( + listener, + cap, + #[cfg(target_os = "linux")] + gate, + #[cfg(target_os = "linux")] + None, + serve, + ); +} + +fn serve_each_inner( + listener: &UnixListener, + cap: &std::sync::Arc, + #[cfg(target_os = "linux")] gate: &Option>, + #[cfg(target_os = "linux")] container_engine: Option>, + serve: std::sync::Arc, ) { for conn in listener.incoming() { let Ok(conn) = conn else { continue }; - let engine = engine.clone(); + let Some(permit) = cap.try_acquire() else { + cap.warn_full(); + drop(conn); + continue; + }; + // Capture `/proc/` credentials + cgroup synchronously at `accept()` + // before spawning `kiri-api`, preventing short-lived client exit races + // and PID-reuse TOCTOU (#127). + #[cfg(target_os = "linux")] + let pinned = if gate.is_some() && container_engine.is_some() { + access::PinnedPeer::capture(&conn) + } else { + None + }; + let serve = serve.clone(); #[cfg(target_os = "linux")] let gate = gate.clone(); + #[cfg(target_os = "linux")] + let container_engine = container_engine.clone(); let spawned = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { + let _permit = permit; // 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 Ok(_seat) = admit_connection_for(&gate, &conn, pinned, &container_engine) else { + return; }; - let _ = api::serve(conn, engine, who); + serve(conn); }); if let Err(e) = spawned { diag::error!("cannot start a connection thread", error = e); @@ -260,10 +659,47 @@ fn accept( } } +/// The data folder chosen in Settings → Storage isn't there (its drive +/// isn't connected): no empty store is made in its place, and the daemon +/// stays up rather than exiting (launchd and systemd would only start it +/// again and again), answering what Settings → Storage needs to say so +/// and offer Retry or Reset to default (storage::serve_unavailable). +fn unavailable( + listener: &UnixListener, + socket: PathBuf, + set: libc::sigset_t, + missing: PathBuf, + #[cfg(target_os = "linux")] gate: &Option>, +) -> io::Result<()> { + diag::error!("Kiri's data folder isn't available: the engine waits for it, or for Settings → Storage", folder = missing.display()); + std::thread::Builder::new().name("kiri-signals".into()).spawn(move || { + let mut sig = 0; + // SAFETY: waits on the blocked set; writes the signal number to `sig`. + unsafe { libc::sigwait(&set, &mut sig) }; + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(caller::container_socket(&socket)); + std::process::exit(0); + })?; + serve_each( + listener, + #[cfg(target_os = "linux")] + gate, + std::sync::Arc::new(move |conn| { + let _ = storage::serve_unavailable(conn, &missing); + }), + ); + Ok(()) +} + /// When the app this daemon runs from is deleted (appwatch.rs): docker /// build handed back (buildwith.rs: what was there before; the choice /// stays, so the app taken up again takes it again), and the engine stops. -fn watch_own_app(engine: std::sync::Arc, socket: std::path::PathBuf) { +fn watch_own_app( + engine: std::sync::Arc, + socket: std::path::PathBuf, + extra_socket: Option, + #[cfg(target_os = "linux")] manage_docker_sock: bool, +) { crate::appwatch::watch(move |exe| { diag::error!("the app this engine runs from was deleted; stopping and handing docker build back", path = exe.display()); if let Err(e) = crate::buildwith::places().and_then(|p| p.give_back()) { @@ -271,8 +707,15 @@ fn watch_own_app(engine: std::sync::Arc, socket: std::path::Path } #[cfg(target_os = "macos")] nfs::unmount(); + #[cfg(target_os = "linux")] + if manage_docker_sock { + cleanup_docker_sock_symlink(std::path::Path::new(RUN_DOCKER_SOCK), std::path::Path::new(crate::client::SERVICE_SOCKET)); + } let _ = std::fs::remove_file(&socket); let _ = std::fs::remove_file(caller::container_socket(&socket)); + if let Some(ref extra) = extra_socket { + let _ = std::fs::remove_file(extra); + } engine.shutdown(); std::thread::sleep(Duration::from_millis(50)); // 0: launchd restarts the engine on failure only, and there is @@ -295,12 +738,67 @@ fn finder(engine: &std::sync::Arc) { } } -/// Gives `group` read-write access to the socket. -fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result<()> { +fn bind_daemon_socket(socket: &std::path::Path, access_group: Option<&std::ffi::OsStr>) -> io::Result { + if let Some(dir) = socket.parent() { + std::fs::create_dir_all(dir)?; + if dir == std::path::Path::new("/run/kiri") { + std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o755))?; + } + } + let _ = std::fs::remove_file(socket); // stale, from a daemon that died + let _ = std::fs::remove_dir(socket); // empty directory left by a pre-0.2.3 bind mount + let listener = UnixListener::bind(socket)?; + std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))?; + if let Some(group) = access_group { + socket_group(socket, group)?; + } else { + default_socket_access(socket)?; + } + Ok(listener) +} + +/// Docker-compatible permissions for a root-run Linux daemon when no explicit +/// `KIRI_SOCKET_GROUP` is configured: mode 0660 (never world-writable), with +/// the `docker` group when present, else `kiri` when present, else root's group. +fn default_socket_access(socket: &std::path::Path) -> io::Result<()> { + // SAFETY: geteuid cannot fail. + let linux_root = cfg!(target_os = "linux") && unsafe { libc::geteuid() } == 0; + default_socket_access_with(socket, linux_root, lookup_group_gid, apply_socket_gid) +} + +fn default_socket_access_with( + socket: &std::path::Path, + linux_root: bool, + mut lookup_gid: impl FnMut(&std::ffi::OsStr) -> io::Result, + mut apply_gid: impl FnMut(&std::path::Path, Option) -> io::Result<()>, +) -> io::Result<()> { + if !linux_root { + return Ok(()); + } + let gid = lookup_gid(std::ffi::OsStr::new("docker")).or_else(|_| lookup_gid(std::ffi::OsStr::new("kiri"))); + match gid { + Ok(gid) => match apply_gid(socket, Some(gid)) { + Ok(()) => Ok(()), + // In a single-user namespace where the host's group gid is not + // mapped, chown returns EINVAL: keep the socket's group at 0660. + Err(e) if e.raw_os_error() == Some(libc::EINVAL) => apply_gid(socket, None), + Err(e) => Err(e), + }, + // When `KIRI_SOCKET_GROUP` is unset, `docker` and `kiri` are optional: + // Alpine / BusyBox `getent group ...` exits 1 (`ErrorKind::Other`) when + // absent, while glibc exits 2 (`ErrorKind::NotFound`). Keep root's + // group at 0660 rather than refusing to start the daemon. + Err(_) => apply_gid(socket, None), + } +} + +fn lookup_group_gid(group: &std::ffi::OsStr) -> io::Result { #[cfg(target_os = "linux")] - let gid = access::group_gid(group)?; + { + access::group_gid(group) + } #[cfg(not(target_os = "linux"))] - let gid = { + { let name = std::ffi::CString::new(std::os::unix::ffi::OsStrExt::as_bytes(group)).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; // SAFETY: getgrnam with a valid C string; the result is read at once. unsafe { @@ -308,9 +806,672 @@ fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result if g.is_null() { return Err(io::Error::new(io::ErrorKind::NotFound, format!("no group {}", group.to_string_lossy()))); } - (*g).gr_gid + Ok((*g).gr_gid) } - }; - std::os::unix::fs::chown(socket, None, Some(gid))?; + } +} + +fn apply_socket_gid(socket: &std::path::Path, gid: Option) -> io::Result<()> { + if let Some(gid) = gid { + std::os::unix::fs::chown(socket, None, Some(gid))?; + } std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o660)) } + +/// Gives `group` read-write access to the socket. +fn socket_group(socket: &std::path::Path, group: &std::ffi::OsStr) -> io::Result<()> { + let gid = lookup_group_gid(group)?; + apply_socket_gid(socket, Some(gid)) +} + +/// One WSL 2 distro enabled for WSL integration: its name and socket group GID. +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct WslDistroConfig { + pub name: String, + pub gid: u32, +} + +#[derive(Default, serde::Serialize, serde::Deserialize)] +struct WslConfigFile { + #[serde(default)] + distros: Vec, +} + +struct ActiveWslSocket { + gid: u32, + dir: PathBuf, + socket: PathBuf, + stop: std::sync::Arc, +} + +/// Manages per-distro Unix sockets under `/mnt/wsl/kiri/sockets//docker.sock`. +/// Each socket has a `0750` parent directory and a `0660` socket file owned by +/// `0:`, tagging accepted HTTP requests with `Caller::Wsl("")`. +pub struct WslSockets { + base: PathBuf, + active: std::sync::Mutex>, + serve: std::sync::Arc, +} + +static WSL_SOCKETS: std::sync::OnceLock = std::sync::OnceLock::new(); + +fn wsl_base_dir() -> PathBuf { + PathBuf::from(binds::wsl_kiri_dir()) +} + +fn init_wsl_sockets(engine: std::sync::Arc) { + let ws = WSL_SOCKETS.get_or_init(|| { + WslSockets::new(wsl_base_dir(), move |conn, distro| { + let _ = api::serve(conn, engine.clone(), caller::Caller::Wsl(distro)); + }) + }); + if let Err(e) = ws.load_config() { + diag::warn!("WSL integration sockets not loaded", error = e); + } +} + +pub fn wsl_report() -> serde_json::Value { + let distros = WSL_SOCKETS.get().map_or_else(Vec::new, WslSockets::list); + serde_json::json!({ "distros": distros }) +} + +pub fn sync_wsl_sockets(distros: &[WslDistroConfig]) -> io::Result<()> { + let Some(ws) = WSL_SOCKETS.get() else { + return Err(io::Error::other("WSL socket manager is not initialized")); + }; + ws.sync(distros) +} + +fn chown_gid(path: &std::path::Path, gid: u32) -> io::Result<()> { + // SAFETY: geteuid only reads this process's effective user ID. + let uid = if unsafe { libc::geteuid() } == 0 { Some(0) } else { None }; + std::os::unix::fs::chown(path, uid, Some(gid)) +} + +impl WslSockets { + pub fn new(base: PathBuf, serve: impl Fn(UnixStream, String) + Send + Sync + 'static) -> Self { + WslSockets { + base, + active: std::sync::Mutex::new(std::collections::HashMap::new()), + serve: std::sync::Arc::new(serve), + } + } + + pub fn load_config(&self) -> io::Result<()> { + let cfg_path = self.base.join("config.json"); + if !cfg_path.is_file() { + return Ok(()); + } + let bytes = std::fs::read(&cfg_path)?; + let cfg: WslConfigFile = serde_json::from_slice(&bytes) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("invalid {}: {e}", cfg_path.display())))?; + self.sync(&cfg.distros) + } + + pub fn list(&self) -> Vec { + let active = self.active.lock().unwrap_or_else(|e| e.into_inner()); + let mut out: Vec = active + .iter() + .map(|(name, a)| WslDistroConfig { name: name.clone(), gid: a.gid }) + .collect(); + out.sort_by(|a, b| a.name.cmp(&b.name)); + out + } + + pub fn remove_socket_files(&self) { + let active = self.active.lock().unwrap_or_else(|e| e.into_inner()); + for a in active.values() { + a.stop.store(true, std::sync::atomic::Ordering::SeqCst); + let _ = std::fs::remove_file(&a.socket); + let _ = std::fs::remove_dir(&a.dir); + } + } + + pub fn sync(&self, distros: &[WslDistroConfig]) -> io::Result<()> { + for d in distros { + if !binds::valid_distro_name(&d.name) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("invalid WSL distro name: {}", d.name), + )); + } + } + let mut active = self.active.lock().unwrap_or_else(|e| e.into_inner()); + let wanted: std::collections::HashMap<&str, u32> = distros.iter().map(|d| (d.name.as_str(), d.gid)).collect(); + let remove_names: Vec = active + .iter() + .filter(|(name, a)| wanted.get(name.as_str()) != Some(&a.gid) || !a.socket.exists()) + .map(|(name, _)| name.clone()) + .collect(); + for name in remove_names { + if let Some(old) = active.remove(&name) { + old.stop.store(true, std::sync::atomic::Ordering::SeqCst); + let _ = UnixStream::connect(&old.socket); + let _ = std::fs::remove_file(&old.socket); + let _ = std::fs::remove_dir(&old.dir); + } + } + let sockets_dir = self.base.join("sockets"); + if let Ok(entries) = std::fs::read_dir(&sockets_dir) { + for entry in entries.flatten() { + let name = entry.file_name(); + let Some(name_str) = name.to_str() else { continue }; + if !wanted.contains_key(name_str) { + let p = entry.path(); + let _ = std::fs::remove_file(p.join("docker.sock")); + let _ = std::fs::remove_dir(&p); + } + } + } + if !distros.is_empty() { + let roots_dir = self.base.join("roots"); + for d in [&self.base, &sockets_dir, &roots_dir] { + std::fs::create_dir_all(d)?; + std::fs::set_permissions(d, std::fs::Permissions::from_mode(0o755))?; + } + } + for d in distros { + let dir = sockets_dir.join(&d.name); + let sock = dir.join("docker.sock"); + if active.contains_key(&d.name) { + chown_gid(&sock, d.gid)?; + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660))?; + chown_gid(&dir, d.gid)?; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o750))?; + continue; + } + std::fs::create_dir_all(&dir)?; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?; + let _ = std::fs::remove_file(&sock); + let listener = UnixListener::bind(&sock)?; + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600))?; + chown_gid(&sock, d.gid)?; + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o660))?; + chown_gid(&dir, d.gid)?; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o750))?; + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let stop_loop = stop.clone(); + let serve = self.serve.clone(); + let distro_name = d.name.clone(); + std::thread::Builder::new().name("kiri-api-wsl".into()).spawn(move || { + for conn in listener.incoming() { + if stop_loop.load(std::sync::atomic::Ordering::SeqCst) { + break; + } + let Ok(conn) = conn else { continue }; + if stop_loop.load(std::sync::atomic::Ordering::SeqCst) { + break; + } + let Some(permit) = try_acquire_host_conn() else { + drop(conn); + continue; + }; + let serve = serve.clone(); + let distro_name = distro_name.clone(); + if let Err(e) = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { + let _permit = permit; + serve(conn, distro_name); + }) { + diag::error!("cannot start a connection thread", error = e); + } + } + })?; + active.insert( + d.name.clone(), + ActiveWslSocket { + gid: d.gid, + dir, + socket: sock, + stop, + }, + ); + } + if self.base.exists() { + let cfg_path = self.base.join("config.json"); + let tmp_path = self.base.join("config.json.tmp"); + let data = serde_json::to_vec(&WslConfigFile { distros: distros.to_vec() }).unwrap_or_default(); + if std::fs::write(&tmp_path, data).is_ok() { + let _ = std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600)); + let _ = std::fs::rename(&tmp_path, &cfg_path); + } + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsStr; + use std::io::{Read, Write}; + use std::os::unix::fs::MetadataExt; + + #[test] + fn root_linux_default_socket_and_overrides() { + assert_eq!(socket_path_for(None, true, Some(OsStr::new("/root"))).unwrap(), PathBuf::from("/run/kiri/docker.sock")); + assert_eq!(socket_path_for(None, true, None).unwrap(), PathBuf::from("/run/kiri/docker.sock")); + assert_eq!( + socket_path_for(Some(OsStr::new("/custom/kiri.sock")), true, Some(OsStr::new("/root"))).unwrap(), + PathBuf::from("/custom/kiri.sock") + ); + assert_eq!( + socket_path_for(None, false, Some(OsStr::new("/home/alice"))).unwrap(), + PathBuf::from("/home/alice").join(crate::flavor::STATE.get()).join("run/docker.sock") + ); + } + + #[test] + fn default_socket_access_uses_0660_never_world_writable_and_selects_docker_group() { + let dir = std::env::temp_dir().join(format!("kiri-daemon-sock-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("docker.sock"); + let _listener = UnixListener::bind(&sock).unwrap(); + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + + let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o7777; + + // Non-root / macOS default keeps 0600 and is never world-writable. + default_socket_access_with(&sock, false, |_| unreachable!(), apply_socket_gid).unwrap(); + assert_eq!(mode(&sock), 0o600); + assert_eq!(mode(&sock) & 0o002, 0, "socket must never be world-writable"); + + // Root on Linux with `docker` group present selects `docker` group and 0660 (never 0666). + // SAFETY: getegid cannot fail. + let my_gid = unsafe { libc::getegid() }; + let mut applied_gid = None; + default_socket_access_with( + &sock, + true, + |g| { + assert_eq!(g, OsStr::new("docker")); + Ok(my_gid) + }, + |p, gid| { + applied_gid = gid; + apply_socket_gid(p, gid) + }, + ) + .unwrap(); + assert_eq!(applied_gid, Some(my_gid)); + assert_eq!(mode(&sock), 0o660); + assert_eq!(mode(&sock) & 0o007, 0, "socket must forbid world access (never 0666)"); + assert_eq!(std::fs::metadata(&sock).unwrap().gid(), my_gid); + + // Root on Linux without `docker` but with `kiri` group selects `kiri` and 0660 (never 0666). + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut looked_up = Vec::new(); + let mut kiri_applied_gid = None; + default_socket_access_with( + &sock, + true, + |g| { + looked_up.push(g.to_os_string()); + if g == OsStr::new("kiri") { + Ok(my_gid) + } else { + Err(io::Error::new(io::ErrorKind::NotFound, "no group docker")) + } + }, + |p, gid| { + kiri_applied_gid = gid; + apply_socket_gid(p, gid) + }, + ) + .unwrap(); + assert_eq!(looked_up, vec![OsStr::new("docker"), OsStr::new("kiri")]); + assert_eq!(kiri_applied_gid, Some(my_gid)); + assert_eq!(mode(&sock), 0o660); + assert_eq!(mode(&sock) & 0o007, 0, "socket must forbid world access (never 0666)"); + + // Root on Linux without `docker` or `kiri` group keeps existing group and sets 0660 (never 0666). + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut fallback_gid = Some(99999); + default_socket_access_with( + &sock, + true, + |_| Err(io::Error::new(io::ErrorKind::NotFound, "no group")), + |p, gid| { + fallback_gid = gid; + apply_socket_gid(p, gid) + }, + ) + .unwrap(); + assert_eq!(fallback_gid, None); + assert_eq!(mode(&sock), 0o660); + assert_eq!(mode(&sock) & 0o007, 0, "socket must forbid world access (never 0666)"); + + // Unmapped gid in a user namespace (EINVAL) also falls back cleanly to 0660. + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + let mut attempts = Vec::new(); + default_socket_access_with( + &sock, + true, + |_| Ok(999), + |p, gid| { + attempts.push(gid); + if gid.is_some() { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); + } + apply_socket_gid(p, None) + }, + ) + .unwrap(); + assert_eq!(attempts, vec![Some(999), None]); + assert_eq!(mode(&sock), 0o660); + + // BusyBox `getent group docker` exits 1 (`ErrorKind::Other`) when absent: must still start at 0660. + std::fs::set_permissions(&sock, std::fs::Permissions::from_mode(0o600)).unwrap(); + default_socket_access_with( + &sock, + true, + |_| Err(io::Error::other("getent group docker: exit status: 1")), + apply_socket_gid, + ) + .unwrap(); + assert_eq!(mode(&sock), 0o660); + + // Explicit KIRI_SOCKET_GROUP fails closed when the group does not exist. + assert_eq!(socket_group(&sock, OsStr::new("kiri-no-such-group-127")).unwrap_err().kind(), io::ErrorKind::NotFound); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn peer_authorization_allows_container_uid_when_unmanaged_and_denies_without_gid_or_when_managed() { + // Container-only numeric UID 54321 must not exist in the host's /etc/passwd. + #[cfg(target_os = "linux")] + const PROBE_ID: u32 = 54321; + let has_host_entry = std::fs::read_to_string("/etc/passwd") + .unwrap_or_default() + .lines() + .any(|l| l.split(':').nth(2) == Some("54321")); + assert!(!has_host_entry, "54321 must not be a host account"); + + let dir = std::env::temp_dir().join(format!("kiri-peer-auth-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap(); + let sock = dir.join("docker.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + // SAFETY: getegid cannot fail. + let sock_gid = unsafe { libc::getegid() }; + default_socket_access_with(&sock, true, |_| Ok(sock_gid), apply_socket_gid).unwrap(); + + let m = std::fs::metadata(&sock).unwrap(); + let mode = m.permissions().mode() & 0o7777; + assert_eq!(mode, 0o660); + // Group rw (0o060) lets a container UID with supplementary `sock_gid` connect; + // other is 0 (0o007 == 0) so the kernel denies any UID/GID lacking `sock_gid` with EACCES. + assert_eq!(mode & 0o070, 0o060); + assert_eq!(mode & 0o007, 0); + + #[cfg(target_os = "linux")] + { + let (_client, server) = UnixStream::pair().unwrap(); + // 1. When KIRI_SOCKET_GROUP is unset (`gate` is `None`), a connected peer that + // passed the kernel's 0660 group check is admitted without requiring an `/etc/passwd` entry. + assert!(admit_connection(&None, &server).is_ok()); + + // 2. When KIRI_SOCKET_GROUP IS explicitly set, managed account-membership check is + // enforced: container-only numeric `uid=54321` is not a member of that managed group and is DENIED. + let gate = access::Gate::new(&[sock.as_path()], OsStr::new("root")).unwrap(); + assert!(!gate.allowed_for_test(PROBE_ID).unwrap(), "non-NSS peer must be denied by managed KIRI_SOCKET_GROUP gate"); + + // SAFETY: geteuid cannot fail. + if unsafe { libc::geteuid() } == 0 { + let try_connect = |with_sock_gid: bool| -> io::ErrorKind { + // SAFETY: fork in a test; the child only drops privileges, connects and exits with raw errno. + unsafe { + let pid = libc::fork(); + if pid == 0 { + let rc = if with_sock_gid { + let gids = [sock_gid as libc::gid_t]; + libc::setgroups(1, gids.as_ptr()) + } else { + libc::setgroups(0, std::ptr::null()) + }; + if rc != 0 || libc::setgid(PROBE_ID) != 0 || libc::setuid(PROBE_ID) != 0 { + libc::_exit(126); + } + match UnixStream::connect(&sock) { + Ok(_) => libc::_exit(0), + Err(e) => libc::_exit(e.raw_os_error().unwrap_or(1).clamp(1, 125)), + } + } + let mut status = 0; + libc::waitpid(pid, &mut status, 0); + let code = libc::WEXITSTATUS(status); + if code == 0 { + io::ErrorKind::Other + } else { + io::Error::from_raw_os_error(code).kind() + } + } + }; + // Denied by kernel 0660 when lacking `sock_gid`. + assert_eq!(try_connect(false), io::ErrorKind::PermissionDenied); + // Allowed by kernel 0660 when carrying supplementary `sock_gid`, and admitted when KIRI_SOCKET_GROUP is unset. + assert_eq!(try_connect(true), io::ErrorKind::Other); + let (accepted, _) = listener.accept().unwrap(); + assert!(admit_connection(&None, &accepted).is_ok()); + // Denied by managed `KIRI_SOCKET_GROUP` gate even after kernel 0660 connect. + assert!(admit_connection(&Some(gate), &accepted).is_err()); + } + } + let _ = listener; + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn per_distro_wsl_sockets_have_0660_permissions_and_clean_teardown_on_disable() { + let base = std::env::temp_dir().join(format!("kiri-wsl-sockets-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + // SAFETY: getegid only reads this process's effective group ID. + let gid = unsafe { libc::getegid() }; + let ws = WslSockets::new(base.clone(), |mut conn, distro| { + let _ = conn.write_all(distro.as_bytes()); + }); + ws.sync(&[WslDistroConfig { name: "Ubuntu".into(), gid }]).unwrap(); + + let dir = base.join("sockets/Ubuntu"); + let sock = dir.join("docker.sock"); + assert!(sock.exists()); + let dir_mode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777; + let sock_mode = std::fs::metadata(&sock).unwrap().permissions().mode() & 0o777; + assert_eq!(dir_mode, 0o750, "parent directory must be 0750, got {dir_mode:o}"); + assert_eq!(sock_mode, 0o660, "socket must be 0660, got {sock_mode:o}"); + assert_ne!(sock_mode, 0o666, "socket must never be 0666"); + + let mut client = UnixStream::connect(&sock).unwrap(); + let mut tagged = String::new(); + client.read_to_string(&mut tagged).unwrap(); + assert_eq!(tagged, "Ubuntu"); + + // Disabling removes the socket and its parent directory cleanly. + ws.sync(&[]).unwrap(); + assert!(!sock.exists(), "socket must be removed when disabled"); + assert!(!dir.exists(), "parent dir must be removed when disabled"); + + // Path-traversal distro names are rejected. + assert!(ws.sync(&[WslDistroConfig { name: "../evil".into(), gid }]).is_err()); + + let _ = std::fs::remove_dir_all(&base); + } + + #[test] + fn linux_root_check_sudo_uid_and_docker_sock_symlink() { + // Non-root fails immediately with actionable error; root / rootless userns (euid 0) succeeds. + assert!(ensure_linux_root(0).is_ok()); + let err = ensure_linux_root(1000).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied); + assert_eq!( + err.to_string(), + "on Linux, Kiri runs containers on this machine's kernel and needs root: run `sudo kiri host-access $USER` (or `sudo kiri daemon`)" + ); + + // SUDO_UID parsing accepts valid non-zero uids only. + assert_eq!(sudo_uid_from(None), None); + assert_eq!(sudo_uid_from(Some(OsStr::new(""))), None); + assert_eq!(sudo_uid_from(Some(OsStr::new("0"))), None); + assert_eq!(sudo_uid_from(Some(OsStr::new("4294967295"))), None); + assert_eq!(sudo_uid_from(Some(OsStr::new("abc"))), None); + assert_eq!(sudo_uid_from(Some(OsStr::new("-1"))), None); + assert_eq!(sudo_uid_from(Some(OsStr::new("1000"))), Some(1000)); + + // /run/docker.sock symlink creation and clean shutdown removal. + let dir = std::env::temp_dir().join(format!("kiri-docker-sock-link-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("run/kiri")).unwrap(); + std::fs::create_dir_all(dir.join("var/run")).unwrap(); + let target = dir.join("run/kiri/docker.sock"); + let run_link = dir.join("run/docker.sock"); + let var_run_link = dir.join("var/run/docker.sock"); + std::fs::write(&target, "").unwrap(); + + // Creates symlink when neither path is occupied, and removes it when pointing to target. + maybe_link_docker_sock(&run_link, &var_run_link, &target); + assert_eq!(std::fs::read_link(&run_link).unwrap(), target); + cleanup_docker_sock_symlink(&run_link, &target); + assert!(!path_occupied(&run_link)); + + // Does not overwrite an existing /var/run/docker.sock (file, socket, or dangling symlink). + std::os::unix::fs::symlink("/mnt/wsl/kiri/sockets/Ubuntu/docker.sock", &var_run_link).unwrap(); + maybe_link_docker_sock(&run_link, &var_run_link, &target); + assert!(!path_occupied(&run_link)); + std::fs::remove_file(&var_run_link).unwrap(); + + // Does not overwrite or delete a /run/docker.sock owned by another engine. + let other = dir.join("other.sock"); + std::os::unix::fs::symlink(&other, &run_link).unwrap(); + maybe_link_docker_sock(&run_link, &var_run_link, &target); + assert_eq!(std::fs::read_link(&run_link).unwrap(), other); + cleanup_docker_sock_symlink(&run_link, &target); + assert_eq!(std::fs::read_link(&run_link).unwrap(), other); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn connection_cap_enforces_limit_and_releases_on_drop() { + let cap = std::sync::Arc::new(ConnCap::new("test", 2)); + let p1 = cap.try_acquire().expect("first slot"); + let p2 = cap.try_acquire().expect("second slot"); + assert_eq!(cap.open(), 2); + assert!(cap.try_acquire().is_none(), "third slot must be rejected at cap"); + assert_eq!(cap.open(), 2, "rejected acquire must never exceed limit"); + + drop(p1); + assert_eq!(cap.open(), 1); + let p3 = cap.try_acquire().expect("slot freed after drop"); + assert_eq!(cap.open(), 2); + assert!(cap.try_acquire().is_none()); + + drop(p2); + drop(p3); + assert_eq!(cap.open(), 0); + } + + #[test] + fn host_and_container_connection_caps_are_isolated() { + // Host and WSL callers share the host pool; containers use a separate smaller pool. + assert!(std::sync::Arc::ptr_eq(open_conns_for(&caller::Caller::Host), host_open_conns())); + assert!(std::sync::Arc::ptr_eq(open_conns_for(&caller::Caller::Wsl("Ubuntu".into())), host_open_conns())); + assert!(std::sync::Arc::ptr_eq(open_conns_for(&caller::Caller::Container), container_open_conns())); + assert!(!std::sync::Arc::ptr_eq(host_open_conns(), container_open_conns())); + assert_eq!(host_open_conns().limit, MAX_HOST_OPEN_CONNS); + assert_eq!(container_open_conns().limit, MAX_CONTAINER_OPEN_CONNS); + + // Exhausting every container slot must never starve host or WSL connections. + let mut container_permits = Vec::with_capacity(MAX_CONTAINER_OPEN_CONNS); + while let Some(p) = try_acquire_container_conn() { + container_permits.push(p); + } + assert_eq!(container_open_conns().open(), MAX_CONTAINER_OPEN_CONNS); + assert!(try_acquire_container_conn().is_none(), "container pool must reject once full"); + + let host_permit = try_acquire_host_conn().expect("host pool must stay available when container pool is full"); + drop(host_permit); + drop(container_permits); + assert_eq!(container_open_conns().open(), 0); + } + + #[test] + fn serve_each_enforces_connection_cap_and_reclaims_slots() { + let dir = std::env::temp_dir().join(format!("kiri-conn-cap-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let sock = dir.join("docker.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + + let cap = std::sync::Arc::new(ConnCap::new("test", 2)); + let (entered_tx, entered_rx) = std::sync::mpsc::channel::<()>(); + let cap_srv = cap.clone(); + std::thread::spawn(move || { + serve_each_with( + &listener, + &cap_srv, + #[cfg(target_os = "linux")] + &None, + std::sync::Arc::new(move |mut conn| { + let _ = entered_tx.send(()); + // Wait until the client writes a byte or closes, then reply "ok". + let mut b = [0u8; 1]; + if conn.read(&mut b).is_ok_and(|n| n > 0) { + let _ = conn.write_all(b"ok"); + } + }), + ); + }); + + let mut c1 = UnixStream::connect(&sock).unwrap(); + let mut c2 = UnixStream::connect(&sock).unwrap(); + entered_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + entered_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + assert_eq!(cap.open(), 2); + + // Third concurrent connection is dropped immediately without entering handler. + let mut c3 = UnixStream::connect(&sock).unwrap(); + c3.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let mut buf = [0u8; 8]; + match c3.read(&mut buf) { + Ok(0) => {} + Err(e) if matches!(e.kind(), io::ErrorKind::ConnectionReset | io::ErrorKind::BrokenPipe) => {} + other => panic!("expected immediate close at cap, got {other:?}"), + } + assert!(entered_rx.try_recv().is_err(), "capped connection must not invoke handler"); + assert_eq!(cap.open(), 2); + + // Finishing c1 releases its slot so a new connection c4 is served. + c1.write_all(b"x").unwrap(); + let mut reply = [0u8; 2]; + c1.read_exact(&mut reply).unwrap(); + assert_eq!(&reply, b"ok"); + drop(c1); + + let deadline = Instant::now() + Duration::from_secs(2); + while cap.open() >= 2 && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(cap.open(), 1, "closing first connection must release its slot"); + + let mut c4 = UnixStream::connect(&sock).unwrap(); + entered_rx.recv_timeout(Duration::from_secs(2)).unwrap(); + c4.write_all(b"y").unwrap(); + c4.read_exact(&mut reply).unwrap(); + assert_eq!(&reply, b"ok"); + drop(c4); + + c2.write_all(b"z").unwrap(); + c2.read_exact(&mut reply).unwrap(); + assert_eq!(&reply, b"ok"); + drop(c2); + + let deadline = Instant::now() + Duration::from_secs(2); + while cap.open() > 0 && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(cap.open(), 0, "all connection slots must be released"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/kiri/src/daemon/network.rs b/crates/kiri/src/daemon/network.rs index 63d9c7d4e..703b6d8a7 100644 --- a/crates/kiri/src/daemon/network.rs +++ b/crates/kiri/src/daemon/network.rs @@ -97,7 +97,12 @@ pub fn parse_ip6(s: &str) -> Option<[u8; 16]> { } fn mask6(prefix: u8) -> u128 { - if prefix == 0 { 0 } else { u128::MAX << (128 - prefix as u32) } + match prefix { + // Not parsed this way (and never serialized), but `networks.json` + // holds plain bytes and a bad one must not panic the shifts. + 0 | 129.. => 0, + p => u128::MAX << (128 - p as u32), + } } pub fn in_subnet6(ip: [u8; 16], subnet: [u8; 16], prefix: u8) -> bool { @@ -139,8 +144,13 @@ impl V6 { let base = u128::from_be_bytes(self.subnet); let (first, last) = match self.ip_range { Some((r, p)) => { - let start = u128::from_be_bytes(r) - base; - (start.max(1), (start + !mask6(p)).min(self.last())) + // `wrapping_sub` and `saturating_add` because `networks.json` + // holds plain bytes: an ip-range outside the subnet, or a span + // past the top of the address space, must not panic or wrap + // into a wrong range (the request path checks both; an old or + // hand-edited file may not). + let start = u128::from_be_bytes(r).wrapping_sub(base); + (start.max(1), start.saturating_add(!mask6(p)).min(self.last())) } None => (1, self.last()), }; @@ -150,7 +160,7 @@ impl V6 { if h > last { return None; } - let ip = (base + h).to_be_bytes(); + let ip = base.checked_add(h)?.to_be_bytes(); if !self.used.contains(&h) && !self.reserved(ip) && !avoid.contains(&ip) { self.used.insert(h); return Some(ip); @@ -170,6 +180,12 @@ impl Network { matches!(self.name.as_str(), "bridge" | "host" | "none") } + /// `--opt com.docker.network.bridge.enable_icc=false`: containers on + /// this network cannot reach each other (#213). + pub fn icc_disabled(&self) -> bool { + self.options.get(ENABLE_ICC_OPT).and_then(|v| v.as_str()).and_then(parse_go_bool) == Some(false) + } + /// Docker's `"172.17.0.0/16"`. pub fn subnet_str(&self) -> String { format!("{}/{}", ip_str(self.subnet), self.prefix) @@ -193,18 +209,30 @@ impl Network { /// The next free address, skipping the network, broadcast, gateway and /// auxiliary addresses and `avoid`; only from `--ip-range` when one is set. fn allocate_avoiding(&mut self, avoid: &[[u8; 4]]) -> Option<[u8; 4]> { - let base = u32::from_be_bytes(self.subnet); - let size = 1u32 << (32 - self.prefix as u32); + let base = u32::from_be_bytes(self.subnet) as u64; + // In `u64`, with the size clamped, because `networks.json` holds plain + // bytes: a prefix past /32 (or the /0 the request path refuses) must + // not panic the shift, and a subnet too small for host parts must run + // out of addresses, not underflow. The request path already checks + // both (`parse_ipam`, /8..=/30). + let size = 1u64 << (32 - self.prefix.min(32) as u32); + let max_host = size.saturating_sub(2).min((u32::MAX as u64).saturating_sub(base)); let (first, last) = match self.ip_range { Some((r, p)) => { - let start = u32::from_be_bytes(r) - base; - (start.max(1), (start + (1u32 << (32 - p as u32)) - 1).min(size - 2)) + let start = (u32::from_be_bytes(r).wrapping_sub(base as u32)) as u64; + (start.max(1), (start + (1u64 << (32 - p.min(32) as u32)) - 1).min(max_host)) } - None => (1, size - 2), + None => (1, max_host), }; - let host = (first..=last).find(|h| !self.used.contains(h) && !self.reserved((base + h).to_be_bytes()) && !avoid.contains(&(base + h).to_be_bytes()))?; + let host = (first..=last).find(|h| { + // An address past the end of the space (`base + h` over u32) is no + // address to hand out. + let Ok(ip) = u32::try_from(base + h).map(|a| a.to_be_bytes()) else { return false }; + !self.used.contains(&(*h as u32)) && !self.reserved(ip) && !avoid.contains(&ip) + })?; + let host = u32::try_from(host).ok()?; self.used.insert(host); - Some((base + host).to_be_bytes()) + u32::try_from(base + host as u64).ok().map(|a| a.to_be_bytes()) } /// Whether a container may ask for `ip` here (`--ip`, Compose @@ -220,8 +248,8 @@ impl Network { if !self.user_subnet { return Err("user specified IP address is supported only when connecting to networks with user configured subnets".into()); } - let size = 1u32 << (32 - self.prefix as u32); - let host = u32::from_be_bytes(ip).wrapping_sub(u32::from_be_bytes(self.subnet)); + let size = 1u64 << (32 - self.prefix.min(32) as u32); + let host = u32::from_be_bytes(ip).wrapping_sub(u32::from_be_bytes(self.subnet)) as u64; if !self.contains(ip) || host == 0 || host == size - 1 { return Err(format!("no configured subnet or ip-range contain the IP address {}", ip_str(ip))); } @@ -261,7 +289,7 @@ impl Network { /// Takes `ip` for a container that asked for it. fn reserve(&mut self, ip: [u8; 4]) -> Result<(), String> { self.check_static(ip)?; - let host = u32::from_be_bytes(ip) - u32::from_be_bytes(self.subnet); + let host = u32::from_be_bytes(ip).wrapping_sub(u32::from_be_bytes(self.subnet)); if self.reserved(ip) || !self.used.insert(host) { return Err(format!("Address already in use: {}", ip_str(ip))); } @@ -349,10 +377,31 @@ fn builtin(name: &str, driver: &str, bridge: &str, subnet: [u8; 4], gateway: [u8 /// than reported and not applied. pub const BRIDGE_NAME_OPT: &str = "com.docker.network.bridge.name"; +/// `--opt com.docker.network.bridge.enable_icc=false`: no traffic between +/// the network's containers, enforced by isolating each one's bridge port. +pub const ENABLE_ICC_OPT: &str = "com.docker.network.bridge.enable_icc"; + +/// A boolean as Go's `strconv.ParseBool` reads it, as Docker reads bridge +/// options. +fn parse_go_bool(s: &str) -> Option { + match s { + "1" | "t" | "T" | "true" | "TRUE" | "True" => Some(true), + "0" | "f" | "F" | "false" | "FALSE" | "False" => Some(false), + _ => None, + } +} + /// The options a network keeps, or why one of them cannot be applied. An -/// empty bridge name is Docker's "unset" and is dropped. +/// empty bridge name is Docker's "unset" and is dropped. An `enable_icc` +/// that is not a boolean is refused, as Docker does, rather than left to +/// mean the containers may reach each other. fn checked_options(options: serde_json::Value) -> Result { let serde_json::Value::Object(mut map) = options else { return Ok(serde_json::json!({})) }; + if let Some(v) = map.get(ENABLE_ICC_OPT) + && v.as_str().and_then(parse_go_bool).is_none() + { + return Err(format!("invalid value {v} for the network option {ENABLE_ICC_OPT}: expected true or false")); + } match map.get(BRIDGE_NAME_OPT).map(|v| v.as_str().unwrap_or("?")) { None => {} Some("") => { @@ -418,7 +467,9 @@ pub struct Ipam { } pub fn in_subnet(ip: [u8; 4], subnet: [u8; 4], prefix: u8) -> bool { - let mask = if prefix == 0 { 0 } else { u32::MAX << (32 - prefix as u32) }; + // `min(32)` because `networks.json` holds plain bytes; a prefix past /32 + // must not panic the shift (the request path already refuses one). + let mask = if prefix == 0 { 0 } else { u32::MAX << (32 - prefix.min(32) as u32) }; u32::from_be_bytes(ip) & mask == u32::from_be_bytes(subnet) } @@ -527,10 +578,11 @@ pub fn parse_ipam_both(v: &serde_json::Value) -> Result<(Option, Option Result<(Option, Option 30 || prefix < 8 { return Err(format!("invalid subnet {subnet}: Kiri supports prefixes from /8 to /30")); } @@ -748,9 +800,7 @@ impl Networks { used: BTreeSet::new(), }) } else { - if s.ipam6.is_some() { - return Err("invalid network config: an IPv6 subnet needs IPv6 enabled (--ipv6, Compose enable_ipv6: true)".into()); - } + // An IPv6 IPAM entry without --ipv6 is ignored, as Docker does (#433). None }; let index = (1..).find(|i| !self.list.iter().any(|n| n.bridge == format!("kiri{i}"))).expect("unbounded"); @@ -867,21 +917,29 @@ fn free_subnet_with(taken: &[([u8; 4], u8)], default_bridge: bool, host: &[HostN /// A subnet the host itself is on, outside Kiri's bridges: an on-link route /// or an interface's address, and the interface it is on. Or one Docker /// will take back when it starts (`docker_saved`): not on the host now. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, Eq)] struct HostNet { net: u32, mask: u32, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] + addr: [u8; 4], dev: String, saved: bool, } +impl PartialEq for HostNet { + fn eq(&self, other: &Self) -> bool { + (self.net, self.mask, &self.dev, self.saved) == (other.net, other.mask, &other.dev, other.saved) + } +} + fn mask4(prefix: u8) -> u32 { - if prefix == 0 { 0 } else { u32::MAX << (32 - prefix as u32) } + if prefix == 0 { 0 } else { u32::MAX << (32 - prefix.min(32) as u32) } } impl HostNet { fn new(dev: &str, addr: [u8; 4], mask: u32) -> HostNet { - HostNet { net: u32::from_be_bytes(addr) & mask, mask, dev: dev.to_owned(), saved: false } + HostNet { net: u32::from_be_bytes(addr) & mask, mask, addr, dev: dev.to_owned(), saved: false } } /// Shares any address with `subnet`: a new subnet keeps clear of it. @@ -1039,6 +1097,16 @@ fn host_networks() -> Vec { Vec::new() } +#[cfg(target_os = "linux")] +pub(super) fn host_interface_ipv4() -> Vec<(String, std::net::Ipv4Addr)> { + host_addrs().into_iter().map(|h| (h.dev, std::net::Ipv4Addr::from(h.addr))).collect() +} + +#[cfg(not(target_os = "linux"))] +pub(super) fn host_interface_ipv4() -> Vec<(String, std::net::Ipv4Addr)> { + Vec::new() +} + /// The subnets this machine's interfaces have addresses on, outside Kiri's /// bridges and loopback. An address stays on an interface whose route is /// gone (a `noprefixroute` one) or not yet there, so this catches what the @@ -1170,6 +1238,106 @@ mod tests { assert!(bad(serde_json::json!({"Subnet": "10.5.0.0/24", "IPRange": "10.5.0.0/16"})).contains("ip-range")); assert!(bad(serde_json::json!({"Subnet": "10.5.0.0/24", "AuxiliaryAddresses": {"a": "10.9.0.1"}})).contains("auxiliary address a")); assert!(parse_ipam(&serde_json::json!({"Driver": "other"})).is_err()); + // A subnet too small for the arithmetic (a /0 could panic the size + // shift; a /31 or /32 has no room for a gateway and a container) and + // an ip-range outside the subnet are refused, as Docker does. + assert_eq!(bad(serde_json::json!({"Subnet": "0.0.0.0/0"})), "invalid subnet 0.0.0.0/0: Kiri supports prefixes from /8 to /30"); + assert_eq!(bad(serde_json::json!({"Subnet": "10.5.0.0/31"})), "invalid subnet 10.5.0.0/31: Kiri supports prefixes from /8 to /30"); + assert_eq!(bad(serde_json::json!({"Subnet": "10.5.0.0/32"})), "invalid subnet 10.5.0.0/32: Kiri supports prefixes from /8 to /30"); + assert!(bad(serde_json::json!({"Subnet": "10.5.0.0/24", "IPRange": "10.6.0.0/24"})).contains("parent subnet 10.5.0.0/24 does not contain ip-range")); + } + + /// A /30, the smallest user subnet the request path takes, still creates + /// and hands out its one container address; its `--ip-range` picks it. + #[test] + fn the_smallest_allowed_subnet_still_creates_and_allocates() { + let (mut n, dir) = nets(); + let ipam = parse_ipam(&serde_json::json!({"Config": [{"Subnet": "10.6.0.0/30", "IPRange": "10.6.0.2/32"}]})).unwrap().unwrap(); + let net = n.create("tiny", Settings { ipam: Some(ipam), ..Default::default() }).unwrap(); + assert_eq!((net.subnet, net.prefix), ([10, 6, 0, 0], 30)); + assert!(net.check_static([10, 6, 0, 2]).is_ok()); + assert!(net.check_static([10, 6, 0, 0]).is_err()); + assert!(net.check_static([10, 6, 0, 3]).is_err()); + assert_eq!(n.allocate_avoiding("tiny", &[]), Some([10, 6, 0, 2])); + assert_eq!(n.allocate_avoiding("tiny", &[]), None); + let _ = std::fs::remove_dir_all(dir); + } + + /// Malformed or hand-edited `networks.json` records (prefixes at 0 or past + /// /32 and /128, out-of-subnet `ip_range`s, or unaligned subnets near + /// `u32::MAX` / `u128::MAX`) never panic shifts or wrap into bad addresses. + #[test] + fn malformed_saved_network_fields_do_not_panic_or_hand_out_bad_ips() { + assert_eq!(mask6(0), 0); + assert_eq!(mask6(64), u128::MAX << 64); + assert_eq!(mask6(128), u128::MAX); + assert_eq!(mask6(129), 0); + assert_eq!(mask6(255), 0); + assert!(!in_subnet6([0xfd, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0xfd, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 200)); + + assert!(in_subnet([10, 5, 0, 1], [10, 5, 0, 1], 33)); + assert!(!in_subnet([10, 5, 0, 2], [10, 5, 0, 1], 200)); + assert_eq!(mask4(200), u32::MAX); + + // IPv4: prefixes /31, /32, /33, /255 never underflow `size - 2` or panic shifts. + for bad_prefix in [31u8, 32, 33, 255] { + let mut n = net(Some(Ipam { subnet: [10, 5, 0, 0], prefix: 24, gateway: None, ip_range: None, aux: BTreeMap::new() })); + n.prefix = bad_prefix; + assert_eq!(n.allocate_avoiding(&[]), None, "prefix /{bad_prefix}"); + assert!(n.check_static([10, 5, 0, 0]).is_err(), "prefix /{bad_prefix}"); + assert!(n.check_static([10, 5, 0, 1]).is_err(), "prefix /{bad_prefix}"); + } + + // IPv4: /0 and unaligned subnet near `u32::MAX` never panic, wrap, or spin. + let mut slash0 = net(Some(Ipam { subnet: [0, 0, 0, 0], prefix: 24, gateway: Some([0, 0, 0, 1]), ip_range: None, aux: BTreeMap::new() })); + slash0.subnet = [0, 0, 0, 0]; + slash0.prefix = 0; + assert_eq!(slash0.allocate_avoiding(&[]), Some([0, 0, 0, 2])); + assert!(slash0.check_static([0, 0, 0, 0]).is_err()); + assert!(slash0.check_static([255, 255, 255, 255]).is_err()); + assert!(slash0.check_static([0, 0, 0, 2]).is_ok()); + + let mut high4 = net(Some(Ipam { subnet: [10, 5, 0, 0], prefix: 24, gateway: None, ip_range: None, aux: BTreeMap::new() })); + high4.subnet = [255, 255, 255, 253]; + high4.gateway = [255, 255, 255, 254]; + high4.prefix = 0; + assert_eq!(high4.allocate_avoiding(&[]), Some([255, 255, 255, 255])); + assert_eq!(high4.allocate_avoiding(&[]), None, "stops at u32::MAX without wrapping or spinning"); + + // IPv4: `ip_range` below or above `subnet`, or with prefix > 32. + for range in [([10, 4, 0, 0], 24), ([10, 6, 0, 0], 24)] { + let mut n = net(Some(Ipam { subnet: [10, 5, 0, 0], prefix: 24, gateway: None, ip_range: Some(range), aux: BTreeMap::new() })); + assert_eq!(n.allocate_avoiding(&[]), None, "{range:?}"); + } + let mut bad_rp = net(Some(Ipam { subnet: [10, 5, 0, 0], prefix: 24, gateway: None, ip_range: Some(([10, 5, 0, 9], 200)), aux: BTreeMap::new() })); + assert_eq!(bad_rp.allocate_avoiding(&[]), Some([10, 5, 0, 9])); + assert_eq!(bad_rp.allocate_avoiding(&[]), None); + + // IPv6: `ip_range` outside `subnet` (below and above, including /0 and /200) + // and unaligned `subnet` near `u128::MAX` (`base.checked_add(h)` guard). + let mk_v6 = |subnet: [u8; 16], prefix: u8, gateway: [u8; 16], ip_range: Option<([u8; 16], u8)>| V6 { + subnet, + prefix, + gateway, + user_subnet: true, + ip_range, + aux: BTreeMap::new(), + used: BTreeSet::new(), + }; + let s5 = parse_ip6("fd00:5::").unwrap(); + let g5 = parse_ip6("fd00:5::1").unwrap(); + let s4 = parse_ip6("fd00:4::").unwrap(); + let s6 = parse_ip6("fd00:6::").unwrap(); + assert_eq!(mk_v6(s5, 128, g5, None).allocate_avoiding(&[]), None); + assert_eq!(mk_v6(s5, 64, g5, Some((s4, 64))).allocate_avoiding(&[]), None); + assert_eq!(mk_v6(s5, 0, g5, Some((s4, 64))).allocate_avoiding(&[]), None); + assert_eq!(mk_v6(s5, 200, g5, Some((s4, 200))).allocate_avoiding(&[]), None); + assert_eq!(mk_v6(s5, 64, g5, Some((s6, 64))).allocate_avoiding(&[]), None); + + let mut near_max = mk_v6((u128::MAX - 2).to_be_bytes(), 64, (u128::MAX - 1).to_be_bytes(), None); + assert_eq!(near_max.allocate_avoiding(&[]), Some(u128::MAX.to_be_bytes())); + assert_eq!(near_max.allocate_avoiding(&[]), None, "checked_add stops past u128::MAX"); + assert_eq!(mk_v6([0xff; 16], 64, [0; 16], None).allocate_avoiding(&[]), None); } #[test] @@ -1238,6 +1406,23 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + /// `enable_icc` reads as Docker reads it: false in any of Go's + /// spellings turns container-to-container traffic off, and a value + /// that is no boolean is refused instead of leaving it on (#213). + #[test] + fn enable_icc_false_is_read_and_a_bad_value_refused() { + let (mut n, dir) = nets(); + let opts = |v: &str| Settings { options: serde_json::json!({ENABLE_ICC_OPT: v}), ..Default::default() }; + assert!(n.create("iccoff", opts("false")).unwrap().icc_disabled()); + assert!(n.create("iccoff0", opts("0")).unwrap().icc_disabled()); + assert!(!n.create("iccon", opts("true")).unwrap().icc_disabled()); + assert!(!n.create("plain", Settings::default()).unwrap().icc_disabled()); + let e = n.create("iccbad", opts("no")).unwrap_err(); + assert!(e.contains("invalid value \"no\" for the network option com.docker.network.bridge.enable_icc"), "{e}"); + assert!(n.find("iccbad").is_none(), "nothing made"); + let _ = std::fs::remove_dir_all(dir); + } + fn v6(ipam6: Option) -> Settings { Settings { labels: serde_json::json!({}), ipv6: true, ipam6, ..Default::default() } } @@ -1284,9 +1469,9 @@ mod tests { assert_eq!(kv.subnet_str(), "fc00:f853:ccd:e793::/64"); assert_eq!(ip6_str(kv.gateway), "fc00:f853:ccd:e793::1"); assert!(n.create("again", v6(ipam("fc00:f853:ccd:e793::/80"))).unwrap_err().contains("Pool overlaps")); - // A subnet without --ipv6 is refused, not dropped. - let no = Settings { ipam6: ipam("fd00:9::/64"), ..Default::default() }; - assert!(n.create("no", no).unwrap_err().contains("IPv6 enabled")); + // A subnet without --ipv6 is ignored, not refused (#433). + let no = n.create("no", Settings { ipam6: ipam("fd00:9::/64"), ..Default::default() }).unwrap(); + assert!(no.v6.is_none()); // Fixed addresses: in the subnet, free, not the gateway. let want = parse_ip6("fc00:f853:ccd:e793::10"); assert_eq!(n.allocate6("kind", want, &[]), Ok(want)); @@ -1311,6 +1496,64 @@ mod tests { let _ = std::fs::remove_dir_all(dir); } + #[test] + fn ipv6_ipam_subnet_is_ignored_when_ipv6_disabled() { + let (mut n, dir) = nets(); + // 1. mailcow-dockerized shape: EnableIPv6=false with IPv4 + IPv6 subnets. + let (ipam, ipam6) = parse_ipam_both(&serde_json::json!({ + "Driver": "default", + "Config": [ + {"Subnet": "172.22.1.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"}, + ] + })) + .unwrap(); + let mailcow = n.create("mailcow", Settings { ipam, ipam6, ipv6: false, ..Default::default() }).unwrap(); + assert_eq!(mailcow.subnet_str(), "172.22.1.0/24"); + assert_eq!(ip_str(mailcow.gateway), "172.22.1.1"); + assert!(mailcow.user_subnet); + assert!(mailcow.v6.is_none()); + + // 2. EnableIPv6=false with ONLY an IPv6 subnet: auto-allocates IPv4 from pool. + let (ipam, ipam6) = parse_ipam_both(&serde_json::json!({ + "Config": [{"Subnet": "fd4d:6169:6c63:6f77::/64"}] + })) + .unwrap(); + assert!(ipam.is_none() && ipam6.is_some()); + let auto = n.create("v6only-config-off", Settings { ipam, ipam6, ipv6: false, ..Default::default() }).unwrap(); + assert!(auto.v6.is_none()); + assert!(!auto.user_subnet); + assert_ne!(auto.subnet, [0; 4]); + assert!(auto.contains(auto.gateway)); + assert!(!overlaps((auto.subnet, auto.prefix), (mailcow.subnet, mailcow.prefix))); + + // 3. Malformed IPv6/non-IP subnet strings are still rejected as invalid CIDRs. + for cfg in [ + serde_json::json!({"Config": [{"Subnet": "fd4d::not-a-cidr"}]}), + serde_json::json!({"Config": [{"Subnet": "172.22.1.0/24"}, {"Subnet": "fd4d::not-a-cidr"}]}), + serde_json::json!({"Config": [{"Subnet": "not-an-ip/64"}]}), + serde_json::json!({"Config": [{"Subnet": "172.22.1.0/24"}, {"Subnet": "not-an-ip/64"}]}), + ] { + let err = parse_ipam_both(&cfg).unwrap_err(); + assert!(err.contains("invalid CIDR block notation"), "{cfg} -> {err}"); + } + + // 4. EnableIPv6=true with the same IPv6 subnet still works (was not claimed above). + let (ipam, ipam6) = parse_ipam_both(&serde_json::json!({ + "Config": [ + {"Subnet": "172.22.2.0/24"}, + {"Subnet": "fd4d:6169:6c63:6f77::/64"}, + ] + })) + .unwrap(); + let enabled = n.create("mailcow-v6", Settings { ipam, ipam6, ipv6: true, ..Default::default() }).unwrap(); + assert_eq!(enabled.subnet_str(), "172.22.2.0/24"); + let kv = enabled.v6.unwrap(); + assert_eq!(kv.subnet_str(), "fd4d:6169:6c63:6f77::/64"); + assert_eq!(ip6_str(kv.gateway), "fd4d:6169:6c63:6f77::1"); + let _ = std::fs::remove_dir_all(dir); + } + fn host(dev: &str, addr: [u8; 4], prefix: u8) -> HostNet { HostNet::new(dev, addr, mask4(prefix)) } diff --git a/crates/kiri/src/daemon/nfs.rs b/crates/kiri/src/daemon/nfs.rs index 7d87c1a2d..a5714699f 100644 --- a/crates/kiri/src/daemon/nfs.rs +++ b/crates/kiri/src/daemon/nfs.rs @@ -40,10 +40,10 @@ const NOENT: u32 = 2; const IO: u32 = 5; const ACCES: u32 = 13; const NOTDIR: u32 = 20; +const INVAL: u32 = 22; const ROFS: u32 = 30; const STALE: u32 = 70; const BADHANDLE: u32 = 10001; -const NOTSUPP: u32 = 10004; /// The export's filesystem id, `KIRI`. const FSID: u64 = 0x4b49_5249; @@ -126,8 +126,9 @@ pub fn mount(socket: &Path) -> io::Result { // ticotsord with socket paths: mount_nfs's local transport ("<>" is the // host). noac: attributes are never reused, so every read sees the // current file. soft: if the daemon is gone, Finder gets an error - // instead of hanging. - let opts = format!("vers=3,proto=ticotsord,port={socket},mountport={socket},rdonly,nolocks,soft,intr,timeo=10,retrans=2,noac"); + // instead of hanging. nobrowse: open ~/Kiri directly without Finder's + // automatic "<" entry for the Unix socket mount. + let opts = format!("vers=3,proto=ticotsord,port={socket},mountport={socket},rdonly,nobrowse,nolocks,soft,intr,timeo=10,retrans=2,noac"); let status = std::process::Command::new("/sbin/mount_nfs").args(["-o", &opts, "<>:/"]).arg(&dir).status()?; if !status.success() { return Err(io::Error::other(format!("mount_nfs failed: {status}"))); @@ -558,9 +559,8 @@ impl Server<'_> { } } 5 => { - // Links are followed inside the container, so none are shown. - a.opaque()?; - o.u32(NOTSUPP).bool(false); + let fh = a.opaque()?; + self.read_link(fh, o); } 6 => { let fh = a.opaque()?; @@ -768,6 +768,34 @@ impl Server<'_> { } } + /// READLINK. Links are served as links (#648), pointing where they do + /// inside the container: see `in_container`. + fn read_link(&self, fh: &[u8], o: &mut Out) { + let at = match self.attr(fh) { + Ok(a) => a, + Err(e) => { + o.u32(e).bool(false); + return; + } + }; + let (Ok(Node::File { id, path }), true) = (self.node(fh), at.link) else { + o.u32(INVAL); + at.post_op(o); + return; + }; + match self.engine.fs_read_link(&id, &path) { + Ok(target) => { + o.u32(OK); + at.post_op(o); + o.opaque(in_container(&path, &String::from_utf8_lossy(&target)).as_bytes()); + } + Err(e) => { + o.u32(errno(e)); + at.post_op(o); + } + } + } + fn readdir(&mut self, fh: &[u8; 16], cookie: u64, count: u32, plus: bool, o: &mut Out) { let dir_attr = match self.attr(fh) { Ok(a) => a, @@ -840,6 +868,30 @@ impl Server<'_> { } } +/// The link at `link`'s `target`, made relative so that the Mac resolves it +/// inside the container's folder: `/` in a link is the container's root, +/// not the Mac's, and `..` stops at that root, as in the container. A link +/// to `/etc/hosts` at `/usr/x` reads `../etc/hosts`. +fn in_container(link: &str, target: &str) -> String { + let target = target.split('\0').next().unwrap_or(""); + let depth = link.split('/').filter(|c| !c.is_empty()).count().saturating_sub(1); + let (mut up, mut down) = if target.starts_with('/') { (depth, Vec::new()) } else { (0, Vec::new()) }; + for c in target.split('/') { + match c { + "" | "." => {} + ".." => { + if down.pop().is_none() && up < depth { + up += 1; + } + } + c => down.push(c), + } + } + let mut out = vec![".."; up]; + out.extend(down); + if out.is_empty() { ".".into() } else { out.join("/") } +} + fn garbage(xid: u32) -> Vec { let mut o = Out::default(); o.u32(xid).u32(1).u32(0).u32(0).u32(0).u32(4); // GARBAGE_ARGS @@ -892,6 +944,75 @@ mod tests { assert!(allowed(&a)); } + /// A link resolves inside its container's folder, never into the Mac's. + #[test] + fn links_point_inside_the_container() { + assert_eq!(in_container("/usr/bin/X11", "."), "."); + assert_eq!(in_container("/bin", "usr/bin"), "usr/bin"); + assert_eq!(in_container("/usr/x", "/etc/hosts"), "../etc/hosts"); + assert_eq!(in_container("/lib64", "/"), "."); + assert_eq!(in_container("/a/b/c", "/"), "../.."); + assert_eq!(in_container("/sys/bus/virtio/devices/virtio5/subsystem", "../../../bus/virtio"), "../../../bus/virtio"); + // Above the root is the root, as in the container. + assert_eq!(in_container("/etc/x", "../../../../etc/passwd"), "../etc/passwd"); + assert_eq!(in_container("/etc/x", "/../../etc/passwd"), "../etc/passwd"); + assert_eq!(in_container("/a/l", "b/../../../c"), "../c"); + assert_eq!(in_container("/l", "a/../../../.."), "."); + assert_eq!(in_container("/a/b/l", "///Users/victim/.ssh/id_rsa"), "../../Users/victim/.ssh/id_rsa"); + assert_eq!(in_container("/a/b/l", "../../../../Users/victim/.ssh"), "../../Users/victim/.ssh"); + assert_eq!(in_container("/a/l", "/a/b/../c"), "../a/c"); + assert_eq!(in_container("/a/l", "sub/.."), "."); + assert_eq!(in_container("/l", ""), "."); + assert_eq!(in_container("/a/l", "..\0/../../etc/passwd"), ".."); + assert_eq!(in_container("/a/l", &String::from_utf8_lossy(b"/etc/\xff/hosts")), "../etc/\u{fffd}/hosts"); + let long = format!("/{}", "a/".repeat(1024)); + assert_eq!(in_container("/usr/l", &long), format!("../{}", vec!["a"; 1024].join("/"))); + + // Chained symlinks evaluated by the Mac's VFS from ~/Kiri/ + // never step above ~/Kiri/. + let links = HashMap::from([ + ("/dir1", "."), + ("/a/b", ".."), + ("/a/root", "/"), + ("/a/c/up", "../../../.."), + ("/a/escape1", "b/../../../../Users/victim/.ssh"), + ("/a/escape2", "root/../../../../etc/passwd"), + ("/a/c/escape3", "up/../../.."), + ("/escape4", "dir1/../../.."), + ("/escape5", "a/b/../.."), + ]); + let host_root = ["Users", "victim", "Kiri", "ctr"]; + for (&start_link, &raw_target) in &links { + let parent_parts: Vec<&str> = start_link.split('/').filter(|c| !c.is_empty()).collect(); + let mut cur: Vec = host_root.iter().chain(&parent_parts[..parent_parts.len() - 1]).map(|s| (*s).to_owned()).collect(); + let rewritten = in_container(start_link, raw_target); + let mut queue: std::collections::VecDeque = rewritten.split('/').map(str::to_owned).collect(); + let mut hops = 0; + while let Some(comp) = queue.pop_front() { + match comp.as_str() { + "" | "." => {} + ".." => { + cur.pop(); + } + name => { + cur.push(name.to_owned()); + assert!(cur.iter().map(String::as_str).ge(host_root), "{start_link} -> {raw_target} ({rewritten}) escaped to {cur:?}"); + let cpath = format!("/{}", cur[host_root.len()..].join("/")); + if let Some(&next_target) = links.get(cpath.as_str()) { + hops += 1; + assert!(hops <= 16, "symlink loop"); + cur.pop(); // resolve relative to the symlink's parent directory + for step in in_container(&cpath, next_target).split('/').rev() { + queue.push_front(step.to_owned()); + } + } + } + } + assert!(cur.len() >= host_root.len() && cur[..host_root.len()] == host_root, "{start_link} -> {raw_target} ({rewritten}) escaped to {cur:?}"); + } + } + } + #[test] fn xdr_opaque_is_padded() { let mut o = Out::default(); diff --git a/crates/kiri/src/daemon/ops.rs b/crates/kiri/src/daemon/ops.rs index e60ac71d3..c5067350c 100644 --- a/crates/kiri/src/daemon/ops.rs +++ b/crates/kiri/src/daemon/ops.rs @@ -12,6 +12,7 @@ use std::time::Duration; use serde_json::{Value, json}; use super::api::{Next, copy_error, error, filters, guest_frame, reply}; +use super::caller::Caller; use super::engine::{Engine, Error, Status}; use super::http::{self, Request}; use super::time; @@ -20,12 +21,13 @@ use super::time; const TICK_NS: u64 = 10_000_000; /// Routes the requests this module serves; `None` if it serves none. -pub fn route(req: &Request, engine: &Arc, w: &mut UnixStream) -> Option> { +pub fn route(req: &Request, engine: &Arc, caller: &Caller, w: &mut UnixStream) -> Option> { let p = req.path.as_str(); let m = req.method.as_str(); Some(match (m, p) { ("GET", "/events") => events(req, engine, w), ("GET", "/system/df") => reply(w, system_df(engine), 200), + ("GET", "/kiri/volumes/sizes") => reply(w, volume_sizes(engine), 200), ("POST", "/containers/prune") => reply(w, container_prune(req, engine), 200), ("POST", "/images/prune") => reply(w, image_prune(req, engine), 200), ("GET", "/images/search") => reply(w, search(req), 200), @@ -41,7 +43,7 @@ pub fn route(req: &Request, engine: &Arc, w: &mut UnixStream) -> Option< ("POST", "rename") => reply(w, engine.rename(id, req.query("name").unwrap_or_default()).map(|()| Value::Null), 204), ("POST", "update") => reply(w, update(req, engine, id), 200), ("GET", "changes") => reply(w, changes(engine, id), 200), - ("GET", "export") => export(engine, id, w), + ("GET", "export") => export(engine, id, caller, w), _ => return None, }); } @@ -78,7 +80,11 @@ fn stats_json(id: &str, name: &str, s: &kiri_proto::ContainerStats, pre: Option< "cpu_usage": {"total_usage": s.cpu_usage_usec * 1000, "usage_in_kernelmode": s.cpu_system_usec * 1000, "usage_in_usermode": s.cpu_user_usec * 1000}, "system_cpu_usage": s.system_ticks * TICK_NS, "online_cpus": s.online_cpus, - "throttling_data": {"periods": 0, "throttled_periods": 0, "throttled_time": 0}, + "throttling_data": { + "periods": s.cpu_periods, + "throttled_periods": s.cpu_throttled_periods, + "throttled_time": s.cpu_throttled_usec.saturating_mul(1000), + }, }) }; let read = time::rfc3339(std::time::SystemTime::now()); @@ -147,18 +153,20 @@ fn top(req: &Request, engine: &Engine, key: &str) -> Result { fn update(req: &Request, engine: &Engine, key: &str) -> Result { let b = body(req)?; let base = engine.with(key, |c| c.spec.limits)?; - let limits = super::api::limits_from(&b, base); - let restart = b["RestartPolicy"]["Name"].as_str().filter(|n| !n.is_empty()).map(|n| super::engine::RestartPolicy { - name: n.to_owned(), - max_retries: b["RestartPolicy"]["MaximumRetryCount"].as_u64().unwrap_or(0) as u32, - }); + let limits = super::api::limits_from(&b, base)?; + let policy = &b["RestartPolicy"]; + let has_name = !policy["Name"].as_str().unwrap_or_default().is_empty(); + let restart = (has_name || policy["MaximumRetryCount"].as_i64().unwrap_or(0) != 0) + .then(|| super::api::restart_policy(policy, false)) + .transpose()? + .filter(|_| has_name); engine.update(key, limits, restart)?; Ok(json!({"Warnings": []})) } /// Starts a copy-service job and checks it accepted: `CopyDone` first. -fn layer_job(engine: &Engine, key: &str, op: u8) -> Result<(kiri_vmm::VsockStream, std::fs::File), Error> { - let stream = engine.copy(key, op, "/", 0)?; +fn layer_job(engine: &Engine, key: &str, op: u8, flags: u32) -> Result<(kiri_vmm::VsockStream, std::fs::File), Error> { + let stream = engine.copy(key, op, "/", flags)?; let mut f = std::fs::File::from(stream.fd.try_clone()?); let frame = guest_frame(&mut f)?; match kiri_proto::decode(&frame) { @@ -170,7 +178,7 @@ fn layer_job(engine: &Engine, key: &str, op: u8) -> Result<(kiri_vmm::VsockStrea /// `docker diff`: Kind 0 changed, 1 added, 2 deleted. fn changes(engine: &Engine, key: &str) -> Result { - let (_stream, mut f) = layer_job(engine, key, kiri_proto::copy_op::DIFF)?; + let (_stream, mut f) = layer_job(engine, key, kiri_proto::copy_op::DIFF, 0)?; let mut text = String::new(); f.read_to_string(&mut text)?; let list: Vec = text @@ -186,23 +194,18 @@ fn changes(engine: &Engine, key: &str) -> Result { Some(json!({"Path": path, "Kind": kind})) }) .collect(); - Ok(if list.is_empty() { Value::Null } else { Value::Array(list) }) + Ok(Value::Array(list)) } -fn export(engine: &Engine, key: &str, w: &mut UnixStream) -> io::Result { - let (stream, mut f) = match layer_job(engine, key, kiri_proto::copy_op::EXPORT) { +fn export(engine: &Engine, key: &str, caller: &Caller, w: &mut UnixStream) -> io::Result { + let paced = super::api::use_paced_copy(caller); + let flags = if paced { kiri_proto::copy_flags::PACED } else { 0 }; + let (stream, mut f) = match layer_job(engine, key, kiri_proto::copy_op::EXPORT, flags) { Ok(v) => v, Err(e) => return reply(w, Err(e), 200), }; http::begin_stream(w, 200, "application/x-tar")?; - let mut buf = vec![0u8; 256 * 1024]; - loop { - let n = f.read(&mut buf)?; - if n == 0 { - break; - } - http::chunk(w, &buf[..n])?; - } + super::api::stream_copy_out(&mut f, w, paced)?; http::end(w)?; drop(stream); Ok(Next::KeepAlive) @@ -265,13 +268,19 @@ pub(super) fn apply_change(cfg: &mut Value, line: &str) -> Result<(), Error> { fn commit(req: &Request, engine: &Engine) -> Result { let key = req.query("container").unwrap_or_default(); let (id, spec, running) = engine.with(key, |c| (c.id.clone(), c.spec.clone(), c.status == Status::Running))?; - let base = engine + let (base, cfg_pin, _base_layer_pins) = engine .store - .images()? - .into_iter() - .find(|i| i.config_digest == spec.image_id) + .with_images(|images| { + let base = images.iter().find(|i| i.config_digest == spec.image_id)?.clone(); + let cfg_pin = engine.store.pin(&base.config_digest); + let layer_pins: Vec<_> = base.layers.iter().map(|l| engine.store.pin(&l.digest)).collect(); + Some((base, cfg_pin, layer_pins)) + })? .ok_or_else(|| Error::NotFound(format!("the image of container {} is gone", &id[..12])))?; let mut cfg: Value = serde_json::from_slice(&engine.store.read_config(&base.config_digest)?).map_err(|e| Error::Io(io::Error::other(e)))?; + // Release the old config blob before `put_image` so committing back onto + // the base tag frees its unreferenced config blob. + drop(cfg_pin); // What the container ran with becomes the image's config. cfg["config"]["Cmd"] = json!(spec.cmd); cfg["config"]["Entrypoint"] = if spec.entrypoint.is_empty() { Value::Null } else { json!(spec.entrypoint) }; @@ -301,17 +310,17 @@ fn commit(req: &Request, engine: &Engine) -> Result { if pause { engine.pause(&id, true)?; } - let layer = (|| -> Result<(String, u64), Error> { - let (_stream, mut f) = layer_job(engine, &id, kiri_proto::copy_op::COMMIT)?; + let layer = (|| -> Result<(String, u64, kiri_image::store::Pin), Error> { + let (_stream, mut f) = layer_job(engine, &id, kiri_proto::copy_op::COMMIT, 0)?; let mut w = engine.store.ingest()?; io::copy(&mut f, &mut w)?; - Ok(w.finish()?) + Ok(w.finish_pinned()?) })(); if pause { let _ = engine.pause(&id, false); } // An uncompressed layer: its digest is its diff id. - let (digest, size) = layer?; + let (digest, size, _layer_pin) = layer?; if !cfg["rootfs"]["diff_ids"].is_array() { cfg["rootfs"] = json!({"type": "layers", "diff_ids": []}); } @@ -328,7 +337,7 @@ fn commit(req: &Request, engine: &Engine) -> Result { let bytes = serde_json::to_vec(&cfg).map_err(|e| Error::Io(io::Error::other(e)))?; let mut w = engine.store.ingest()?; io::Write::write_all(&mut w, &bytes)?; - let (config_digest, _) = w.finish()?; + let (config_digest, _, _config_pin) = w.finish_pinned()?; let mut layers = base.layers.clone(); layers.push(kiri_image::Layer { digest, size, media_type: "application/vnd.oci.image.layer.v1.tar".into() }); let repo = req.query("repo").unwrap_or_default(); @@ -340,6 +349,7 @@ fn commit(req: &Request, engine: &Engine) -> Result { }; let image = kiri_image::archive::from_config(name, &config_digest, &cfg, layers); engine.store.put_image(image)?; + engine.prune_layers(); engine.emit_container("commit", &id, &[]); Ok(json!({"Id": config_digest})) } @@ -373,7 +383,10 @@ fn container_prune(req: &Request, engine: &Engine) -> Result { let doomed = engine.each(|c| { let labels = if c.spec.labels.is_object() { c.spec.labels.clone() } else { json!({}) }; let created = c.created.duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs_f64()).unwrap_or(0.0); - (c.status != Status::Running && f.labels(&labels) && before(until, created)).then(|| c.id.clone()) + // A `kiri machine` keeps its work in its writable layer: a stopped one + // stays, as on OrbStack; `kiri machine delete` or `docker rm` removes it. + let machine = labels.get(crate::machine::LABEL).is_some(); + (c.status != Status::Running && !machine && f.labels(&labels) && before(until, created)).then(|| c.id.clone()) }); let mut deleted = Vec::new(); for id in doomed { @@ -396,6 +409,7 @@ fn image_prune(req: &Request, engine: &Engine) -> Result { let until = prune_until(&f, "until")?; let used: Vec = engine.each(|c| Some(c.spec.image_id.clone())); let mut deleted = Vec::new(); + let mut any_deleted = false; let mut reclaimed = 0u64; for i in engine.store.images()? { if used.contains(&i.config_digest) || (dangling_only && !i.name.starts_with("sha256:")) { @@ -414,11 +428,15 @@ fn image_prune(req: &Request, engine: &Engine) -> Result { deleted.push(json!({"Untagged": i.name})); engine.emit_image("untag", &i.config_digest, &i.name); if !engine.store.images()?.iter().any(|o| o.config_digest == i.config_digest) { + any_deleted = true; deleted.push(json!({"Deleted": i.config_digest})); engine.emit_image("delete", &i.config_digest, &i.name); } } } + if any_deleted { + engine.prune_layers(); + } Ok(json!({"ImagesDeleted": if deleted.is_empty() { Value::Null } else { Value::Array(deleted) }, "SpaceReclaimed": reclaimed})) } @@ -459,6 +477,9 @@ fn system_df(engine: &Engine) -> Result { let used: Vec = engine.each(|c| Some(c.spec.image_id.clone())); let measured = engine.vm().ok().and_then(|vm| vm.usage(std::time::Duration::from_secs(120))); let du = measured.as_deref().map(DiskUsage::parse); + if let Some(d) = &du { + engine.cache_volume_sizes(None, d.volumes.clone()); + } let layer_size = |l: &kiri_image::Layer| du.as_ref().and_then(|d| d.layers.get(l.digest.trim_start_matches("sha256:")).copied()).unwrap_or(l.size); // How many images use each layer, for each image's shared size. let mut users: HashMap<&str, usize> = HashMap::new(); @@ -471,7 +492,7 @@ fn system_df(engine: &Engine) -> Result { } // Every image layer once, as `layer_size` counts it; with the guest's // numbers, plus the rest of the layer store: layers only stopped - // containers still use, and leftovers the next VM start clears. + // containers still use, and any leftovers the next VM start clears. let mut seen = HashSet::new(); let mut layers_size: u64 = images.iter().flat_map(|i| &i.layers).filter(|l| seen.insert(l.digest.trim_start_matches("sha256:"))).map(layer_size).sum(); if let Some(d) = &du { @@ -535,10 +556,102 @@ fn system_df(engine: &Engine) -> Result { Ok(json!({"LayersSize": layers_size, "Images": image_rows, "Containers": containers, "Volumes": volumes, "BuildCache": super::builder::cache(engine)})) } +/// How long `GET /kiri/volumes/sizes` reuses guest-measured volume sizes while +/// the VM is awake so tab switches do not re-walk the guest disk (`GET /system/df` +/// stays live). +const VOLUME_SIZES_TTL: Duration = Duration::from_secs(30); + +pub(super) fn parse_volume_usage(lines: &[String]) -> HashMap { + DiskUsage::parse(lines).volumes +} + +fn volume_sizes_map( + volumes: &[super::volumes::Volume], + du: &HashMap, + dirty: &HashSet, + complete_scan: bool, +) -> serde_json::Map { + let mut out = serde_json::Map::with_capacity(volumes.len()); + for v in volumes { + if !v.options.is_empty() { + // Backed by driver options (NFS/bind/tmpfs): not on the guest data disk. + out.insert(v.name.clone(), json!(-1)); + continue; + } + if !complete_scan && dirty.contains(&v.name) { + continue; + } + match du.get(&v.name) { + Some(&b) => { + out.insert(v.name.clone(), json!(i64::try_from(b).unwrap_or(i64::MAX))); + } + // A plain local volume never mounted yet has no directory in the + // guest and takes 0 bytes. + None if complete_scan => { + out.insert(v.name.clone(), json!(0)); + } + None => {} + } + } + out +} + +/// Each volume's size in bytes for the Volumes view (`GET /kiri/volumes/sizes`). +/// Uses persisted `/volume-sizes.json` across VM sleep and daemon +/// restarts without waking the VM unless an active (`!is_stopped()`) engine has +/// dirty or unmeasured local volumes. +fn volume_sizes(engine: &Engine) -> Result { + volume_sizes_with_ttl(engine, VOLUME_SIZES_TTL) +} + +fn volume_sizes_with_ttl(engine: &Engine, ttl: Duration) -> Result { + let volumes = engine.volume_list(); + if volumes.is_empty() { + return Ok(json!({"sizes": {}})); + } + let snap = engine.volume_sizes_snapshot(ttl); + let any_missing_or_dirty = volumes + .iter() + .any(|v| v.options.is_empty() && (snap.dirty.contains(&v.name) || !snap.sizes.contains_key(&v.name))); + + if let Some(vm) = engine.awake_link() { + if snap.fresh_ttl && !any_missing_or_dirty { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &snap.sizes, &snap.dirty, false)})); + } + let Some(measured) = vm.usage(Duration::from_secs(120)) else { + return Ok(json!({"sizes": {}})); + }; + let du = DiskUsage::parse(&measured); + engine.cache_volume_sizes(Some(snap.generation), du.volumes.clone()); + let current = engine.volume_list(); + return Ok(json!({"sizes": volume_sizes_map(¤t, &du.volumes, &HashSet::new(), true)})); + } + + if !any_missing_or_dirty { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &snap.sizes, &snap.dirty, false)})); + } + if !engine.is_stopped() + && let Some(measured) = engine.vm().ok().and_then(|vm| vm.usage(Duration::from_secs(120))) + { + let du = DiskUsage::parse(&measured); + engine.cache_volume_sizes(Some(snap.generation), du.volumes.clone()); + let current = engine.volume_list(); + return Ok(json!({"sizes": volume_sizes_map(¤t, &du.volumes, &HashSet::new(), true)})); + } + + let has_any_clean_local = volumes + .iter() + .any(|v| v.options.is_empty() && !snap.dirty.contains(&v.name) && snap.sizes.contains_key(&v.name)); + if has_any_clean_local { + return Ok(json!({"sizes": volume_sizes_map(&volumes, &snap.sizes, &snap.dirty, false)})); + } + Ok(json!({"sizes": {}})) +} + /// `docker history`: the config's history, newest first, with each /// layer-making step's size. fn history(engine: &Engine, name: &str) -> Result { - let i = engine.image(name)?.ok_or_else(|| Error::NotFound(format!("No such image: {name}")))?; + let (i, _blob_pins) = engine.image_pinned(name)?.ok_or_else(|| Error::NotFound(format!("No such image: {name}")))?; let cfg: Value = serde_json::from_slice(&engine.store.read_config(&i.config_digest)?).unwrap_or(Value::Null); let mut layers = i.layers.iter(); let mut rows: Vec = cfg["history"] @@ -640,7 +753,31 @@ pub(super) fn gone(w: &UnixStream) -> bool { r == 0 || pfd.revents & (libc::POLLHUP | libc::POLLERR) != 0 } -/// `docker events`: kept events since `since`, then live ones until `until`. +fn event_time(ev: &Value) -> f64 { + ev["timeNano"].as_u64().map_or(0.0, |n| n as f64 / 1e9) +} + +/// The kept events a subscription replays first: those inside the bounds. +fn replayed<'a>( + recent: &'a [Value], + f: &super::filters::Filters, + since: Option, + until: Option, +) -> Vec<&'a Value> { + if since.is_none() && until.is_none() { + return Vec::new(); + } + recent + .iter() + .filter(|ev| { + since.is_none_or(|s| event_time(ev) >= s) + && until.is_none_or(|u| event_time(ev) <= u) + && event_matches(f, ev) + }) + .collect() +} + +/// `docker events`: kept events inside the bounds, then live ones until `until`. fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result { let f = match filters(req, &["type", "event", "container", "image", "network", "volume", "label", "label!", "daemon", "scope"]) { Ok(f) => f, @@ -655,11 +792,8 @@ fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result io::Result<()> { http::chunk(w, format!("{ev}\n").as_bytes()) }; - let at = |ev: &Value| ev["timeNano"].as_u64().map_or(0.0, |n| n as f64 / 1e9); - if let Some(s) = since { - for ev in recent.iter().filter(|ev| at(ev) >= s && until.is_none_or(|u| at(ev) <= u) && event_matches(&f, ev)) { - send(w, ev)?; - } + for ev in replayed(&recent, &f, since, until) { + send(w, ev)?; } loop { if until.is_some_and(|u| now() >= u) { @@ -667,7 +801,7 @@ fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result { - if until.is_some_and(|u| at(&ev) > u) { + if until.is_some_and(|u| event_time(&ev) > u) { break; } if event_matches(&f, &ev) { @@ -686,6 +820,40 @@ fn events(req: &Request, engine: &Engine, w: &mut UnixStream) -> io::Result Value { + json!({"Type": "container", "Action": "create", "Actor": {"ID": format!("c{secs}"), "Attributes": {}}, "timeNano": secs * 1_000_000_000}) + } + + fn ids(v: Vec<&Value>) -> Vec<&str> { + v.into_iter() + .map(|e| e["Actor"]["ID"].as_str().unwrap()) + .collect() + } + + /// `docker events --until` alone replays the kept events up to it, as + /// Docker does; both bounds are inclusive and no bounds replays nothing. + #[test] + fn events_until_without_since_replays_matching_history() { + let recent = [ev(1), ev(2), ev(3)]; + let all = Filters::default(); + assert_eq!(ids(replayed(&recent, &all, None, Some(2.5))), ["c1", "c2"]); + assert_eq!(ids(replayed(&recent, &all, Some(1.5), None)), ["c2", "c3"]); + assert_eq!(ids(replayed(&recent, &all, Some(1.5), Some(2.5))), ["c2"]); + assert!(replayed(&recent, &all, None, None).is_empty()); + assert_eq!(ids(replayed(&recent, &all, None, Some(2.0))), ["c1", "c2"]); + assert_eq!(ids(replayed(&recent, &all, Some(2.0), Some(2.0))), ["c2"]); + let only_c3 = Filters::parse(Some(r#"{"container":["c3"]}"#)).unwrap(); + assert!(replayed(&recent, &only_c3, None, Some(2.5)).is_empty()); + assert_eq!(ids(replayed(&recent, &only_c3, None, Some(3.0))), ["c3"]); + } +} + #[cfg(test)] mod disk_usage_tests { use super::DiskUsage; @@ -714,6 +882,38 @@ mod disk_usage_tests { let _ = std::fs::remove_dir_all(root); } + /// `docker container prune` (and `system prune`) keeps a stopped + /// `kiri machine` and removes a stopped plain container (#975). + #[test] + fn container_prune_keeps_machines() { + use super::Request; + use serde_json::json; + let root = std::env::temp_dir().join(format!("kiri-container-prune-machines-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + let image = kiri_image::Image { mirror: None, + name: "local:1".into(), digest: "sha256:0123".into(), index_digest: None, config_digest: "sha256:0123".into(), + layers: Vec::new(), size: 0, platform: "linux/arm64".into(), created: String::new(), pulled_at: 0, config: Default::default(), + }; + let spec = |labels| -> super::super::engine::Spec { + serde_json::from_value(json!({ + "image": "local:1", "image_id": "sha256:0123", "entrypoint": [], "cmd": ["true"], + "env": [], "cwd": "/", "user": "", "auto_remove": false, "network_mode": "none", "labels": labels, + "restart": {"name": "no", "max_retries": 0} + })) + .unwrap() + }; + let machine = engine.create(Some("machine-dev".into()), spec(json!({crate::machine::LABEL: "dev"})), &image).unwrap(); + let plain = engine.create(Some("plain".into()), spec(json!({})), &image).unwrap(); + let out = super::container_prune(&Request::internal("POST", "/containers/prune", &[], Vec::new()), &engine).unwrap(); + assert_eq!(out["ContainersDeleted"], json!([plain])); + let left: Vec = engine.each(|c| Some(c.id.clone())); + assert_eq!(left, [machine]); + drop(engine); + let _ = std::fs::remove_dir_all(root); + } + /// Image prune keeps what Docker keeps: an image's config labels must /// match `label` and not `label!`, and `until` keeps newer images. #[test] @@ -792,4 +992,108 @@ mod disk_usage_tests { assert_eq!(du.volumes.get("data"), Some(&12288)); assert_eq!((du.layers.len(), du.containers.len(), du.volumes.len()), (1, 1, 1)); } + + #[test] + fn volume_sizes_persists_across_sleep_and_restart_without_waking_vm() { + use serde_json::json; + use std::collections::{BTreeMap, HashMap}; + use std::time::{Duration, Instant}; + + let root = std::env::temp_dir().join(format!("kiri-vol-sizes-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(&root).unwrap(); + let engine = super::super::engine::boot_without_vm(&root); + + engine.volume_ensure("pg_data", json!({}), false).unwrap(); + engine.volume_ensure("empty_vol", json!({}), false).unwrap(); + let mut nfs_opts = BTreeMap::new(); + nfs_opts.insert("type".into(), "nfs".into()); + nfs_opts.insert("device".into(), ":/export".into()); + engine.volume_ensure_with("nfs_vol", json!({}), nfs_opts).unwrap(); + + let initial = super::volume_sizes(&engine).unwrap(); + assert_eq!(initial, json!({"sizes": {"pg_data": 0, "empty_vol": 0, "nfs_vol": -1}})); + assert!(!engine.is_awake()); + + let mut measured = HashMap::new(); + measured.insert("pg_data".into(), 807_700_000u64); + let gen_before = engine.volume_sizes_snapshot(Duration::from_secs(30)).generation; + engine.cache_volume_sizes(Some(gen_before), measured.clone()); + assert!(root.join("volume-sizes.json").is_file(), "volume-sizes.json persisted"); + + engine.set_volume_sizes_cache_at(Instant::now() - Duration::from_secs(31), measured.clone()); + let after_ttl = super::volume_sizes_with_ttl(&engine, Duration::from_secs(30)).unwrap(); + assert_eq!(after_ttl, json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "nfs_vol": -1}})); + + engine.cache_volume_sizes(None, measured.clone()); + let old_gen = engine.volume_sizes_snapshot(Duration::from_secs(30)).generation; + engine.volume_ensure("new_vol", json!({}), false).unwrap(); + assert!(!engine.volume_sizes_snapshot(Duration::from_secs(30)).fresh_ttl); + let mut stale = HashMap::new(); + stale.insert("pg_data".into(), 1u64); + engine.cache_volume_sizes(Some(old_gen), stale); + assert_eq!( + super::volume_sizes(&engine).unwrap(), + json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "new_vol": 0, "nfs_vol": -1}}), + "stale generation write ignored and new_vol initialized to 0" + ); + + engine.volume_remove("new_vol", false).unwrap(); + let saved_raw: HashMap = + serde_json::from_slice(&std::fs::read(root.join("volume-sizes.json")).unwrap()).unwrap(); + assert!(!saved_raw.contains_key("new_vol")); + assert_eq!(saved_raw.get("pg_data"), Some(&807_700_000)); + + engine.mark_volumes_dirty([&"pg_data".to_owned()]); + assert_eq!(super::volume_sizes(&engine).unwrap(), json!({"sizes": {"empty_vol": 0, "nfs_vol": -1}})); + + engine.cache_volume_sizes(None, measured); + drop(engine); + + let asleep_engine = super::super::engine::Engine::boot(kiri_image::store::Store::open(&root).unwrap()).unwrap(); + assert!(!asleep_engine.is_stopped(), "engine is asleep, not stopped"); + assert!(!asleep_engine.is_awake(), "VM starts asleep"); + let asleep_sizes = super::volume_sizes(&asleep_engine).unwrap(); + assert_eq!(asleep_sizes, json!({"sizes": {"pg_data": 807_700_000, "empty_vol": 0, "nfs_vol": -1}})); + assert!(!asleep_engine.is_awake(), "persisted volume sizes returned without waking asleep VM"); + + drop(asleep_engine); + let _ = std::fs::remove_dir_all(root); + } +} + +#[cfg(test)] +mod stats_tests { + use super::stats_json; + use kiri_proto::ContainerStats; + use serde_json::json; + + #[test] + fn throttling_data_matches_cgroup_counters_in_docker_units() { + let prev = ContainerStats { + cpu_periods: 4, + cpu_throttled_periods: 2, + cpu_throttled_usec: 1000, + ..Default::default() + }; + let sample = ContainerStats { + cpu_periods: 11, + cpu_throttled_periods: 9, + cpu_throttled_usec: 4321, + ..Default::default() + }; + let value = stats_json("id", "work", &sample, Some(&prev), 0); + assert_eq!( + value["cpu_stats"]["throttling_data"], + json!({ + "periods": 11, "throttled_periods": 9, "throttled_time": 4_321_000, + }) + ); + assert_eq!( + value["precpu_stats"]["throttling_data"], + json!({ + "periods": 4, "throttled_periods": 2, "throttled_time": 1_000_000, + }) + ); + } } diff --git a/crates/kiri/src/daemon/ports.rs b/crates/kiri/src/daemon/ports.rs index dc9c558d1..a747061f3 100644 --- a/crates/kiri/src/daemon/ports.rs +++ b/crates/kiri/src/daemon/ports.rs @@ -15,11 +15,11 @@ //! CPUs; through the bridge alone, one CPU carried it all and the port //! ran at about half of Docker's speed on 127.0.0.1. -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::io::{self, Read, Write}; use std::net::{IpAddr, Shutdown, SocketAddr, TcpListener, TcpStream, UdpSocket}; use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; use std::thread::JoinHandle; use std::time::{Duration, Instant}; @@ -39,6 +39,9 @@ const RELAY_FRAMED_PORT: u32 = 1030; static NO_FRAMED_RELAY: AtomicBool = AtomicBool::new(false); /// A UDP client quiet this long has its session closed, as conntrack does. const UDP_IDLE: Duration = Duration::from_secs(60); +/// Port-53 DNS queries churn many short-lived client ports, so reap faster +/// to avoid filling the 1024-session cap (#760). +const UDP_DNS_IDLE: Duration = Duration::from_secs(10); /// A TCP peer that takes none of the relay's bytes for this long is given up /// on. Quiet is not stuck: nothing limits how long a connection may idle, /// as with docker-proxy (#388). @@ -77,6 +80,59 @@ static NAT_DOWN_UNTIL: Mutex> = Mutex::new(None); static NAT_TIMEOUTS: AtomicUsize = AtomicUsize::new(0); /// Set once this run has warned that the NAT network is unreachable. static NAT_WARNED: AtomicBool = AtomicBool::new(false); +/// Running VM's shared NAT state on macOS (`0` = not booted / read config, +/// `1` = booted without `VZNATNetworkDeviceAttachment`, `2` = booted with it). +static SHARED_NAT_STATE: AtomicU8 = AtomicU8::new(0); + +pub fn set_shared_nat_active(active: Option) { + let val = match active { + None => 0, + Some(false) => 1, + Some(true) => 2, + }; + SHARED_NAT_STATE.store(val, Ordering::Relaxed); +} + +pub fn shared_nat_active() -> bool { + match SHARED_NAT_STATE.load(Ordering::Relaxed) { + 1 => false, + 2 => true, + _ => super::engine::shared_nat(), + } +} + +static HOST_PORT_53_BINDS: AtomicUsize = AtomicUsize::new(0); + +struct HostPort53Guard; + +impl HostPort53Guard { + fn acquire() -> Self { + HOST_PORT_53_BINDS.fetch_add(1, Ordering::Relaxed); + Self + } +} + +impl Drop for HostPort53Guard { + fn drop(&mut self) { + HOST_PORT_53_BINDS.fetch_sub(1, Ordering::Relaxed); + } +} + +/// True while at least one container publishes host port 53 on loopback or +/// wildcard, so `dns::mac_resolvers` skips `127.0.0.1:53` / `[::1]:53` (#760). +pub fn host_port_53_published() -> bool { + HOST_PORT_53_BINDS.load(Ordering::Relaxed) > 0 +} + +fn binds_host_dns_port(bound: &[(Binding, String, u16)]) -> bool { + bound.iter().any(|(_, ip, port)| { + *port == 53 + && (ip.is_empty() + || ip == "0.0.0.0" + || ip == "::" + || ip.parse::().is_ok_and(|a| a.is_loopback())) + }) +} /// New connections over the NAT network: a burst of `NAT_BURST`, then /// `NAT_RATE` a second; the rest go over vsock, which takes thousands a /// second (bulk transfers are what the NAT network is for). Each connection @@ -197,6 +253,234 @@ pub struct Binding { pub host_port: u16, } +/// One active published port binding reported to `kiri-win` (`/kiri/win-ports`). +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub struct PublishedPort { + pub proto: String, + pub host_ip: String, + pub host_port: u16, +} + +static WINDOWS_HOST_IPS: Mutex>> = Mutex::new(None); +static LAST_IPCONFIG_PROBE: Mutex> = Mutex::new(None); + +/// Parses a bare or bracketed IPv4/IPv6 host address, stripping any `%scope` +/// suffix and canonicalizing IPv4-mapped IPv6 addresses. +pub fn parse_host_ip(s: &str) -> Option { + let bare = s.trim().strip_prefix('[').and_then(|i| i.strip_suffix(']')).unwrap_or(s.trim()); + let bare = bare.split('%').next().unwrap_or(bare); + bare.parse::().ok().map(|a| a.to_canonical()) +} + +/// Records the Windows host interface IPs pushed by `kiri-win` and persists +/// them in the daemon state directory when the list changes so container +/// starts after a daemon restart still recognize Windows interface addresses. +pub fn set_windows_host_ips(ips: &[String]) { + let mut set = BTreeSet::from([ + IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + ]); + for s in ips { + if let Some(ip) = parse_host_ip(s) + && !ip.is_unspecified() + && !ip.is_multicast() + { + set.insert(ip); + } + } + { + let mut guard = WINDOWS_HOST_IPS.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = load_persisted_windows_host_ips(); + } + if guard.as_ref() == Some(&set) { + return; + } + *guard = Some(set.clone()); + } + if let Ok(dir) = super::state_dir() { + let list: Vec = set.iter().map(ToString::to_string).collect(); + if let Ok(bytes) = serde_json::to_vec(&list) { + let tmp = dir.join("win-host-ips.json.tmp"); + let path = dir.join("win-host-ips.json"); + if std::fs::write(&tmp, bytes).is_ok() { + let _ = std::fs::rename(&tmp, &path); + } + } + } +} + +fn load_persisted_windows_host_ips() -> Option> { + let path = super::state_dir().ok()?.join("win-host-ips.json"); + let bytes = std::fs::read(path).ok()?; + let list: Vec = serde_json::from_slice(&bytes).ok()?; + let mut set = BTreeSet::from([ + IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + ]); + for s in &list { + if let Some(ip) = parse_host_ip(s) + && !ip.is_unspecified() + && !ip.is_multicast() + { + set.insert(ip); + } + } + Some(set) +} + +/// Extracts Windows host interface IPv4 and IPv6 addresses from `ipconfig.exe` +/// output in a locale-independent way: in every Windows locale, each adapter's +/// IPv4 address line is immediately followed by its `255.x.x.x` subnet mask +/// line, whereas the default gateway comes after the subnet mask. +pub fn parse_ipconfig_addrs(output: &str) -> BTreeSet { + let mut set = BTreeSet::from([ + IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), + IpAddr::V6(std::net::Ipv6Addr::LOCALHOST), + ]); + let mut pending_v4: Option = None; + let mut seen_mask_in_section = false; + for raw_line in output.lines() { + let line = raw_line.trim(); + if line.is_empty() { + continue; + } + // Adapter section header (e.g. `Ethernet adapter vEthernet (WSL):`). + if line.ends_with(':') && !line.contains(". :") && !line.contains(" : ") { + pending_v4 = None; + seen_mask_in_section = false; + continue; + } + let val = match line.split_once(": ") { + Some((_, right)) => right.trim(), + None => match line.strip_suffix(':') { + Some(_) => continue, + None => line, + }, + }; + let token = val.split(['(', '%', ' ']).next().unwrap_or("").trim(); + if token.is_empty() { + continue; + } + if let Ok(v4) = token.parse::() { + if v4.octets()[0] == 255 { + seen_mask_in_section = true; + if let Some(interface_ip) = pending_v4.take() + && !interface_ip.is_unspecified() + && !interface_ip.is_multicast() + { + set.insert(IpAddr::V4(interface_ip)); + } + } else { + pending_v4 = Some(v4); + } + } else if !seen_mask_in_section + && let Some(IpAddr::V6(v6)) = parse_host_ip(token) + && !v6.is_unspecified() + && !v6.is_multicast() + { + set.insert(IpAddr::V6(v6)); + } + } + set +} + +fn probe_windows_host_ips_from_wsl() -> Option> { + let wsl = super::binds::wsl()?; + { + let mut last = LAST_IPCONFIG_PROBE.lock().unwrap_or_else(|e| e.into_inner()); + if last.is_some_and(|t| t.elapsed() < Duration::from_secs(2)) { + return None; + } + *last = Some(Instant::now()); + } + let ipconfig = format!("{}c/Windows/System32/ipconfig.exe", wsl.root); + let out = std::process::Command::new(ipconfig) + .stderr(std::process::Stdio::null()) + .output() + .ok()?; + let text = String::from_utf8_lossy(&out.stdout); + let parsed = parse_ipconfig_addrs(&text); + (parsed.len() > 2).then_some(parsed) +} + +/// Whether `ip` is a valid interface address on the Windows host when running +/// inside WSL 2. +pub fn is_windows_host_ip(ip: &str) -> bool { + let Some(addr) = parse_host_ip(ip) else { + return false; + }; + if addr.is_unspecified() || addr.is_multicast() { + return false; + } + { + let mut guard = WINDOWS_HOST_IPS.lock().unwrap_or_else(|e| e.into_inner()); + if guard.is_none() { + *guard = load_persisted_windows_host_ips(); + } + if let Some(set) = guard.as_ref() + && set.contains(&addr) + { + return true; + } + } + if let Some(probed) = probe_windows_host_ips_from_wsl() { + let mut guard = WINDOWS_HOST_IPS.lock().unwrap_or_else(|e| e.into_inner()); + let set = guard.get_or_insert_with(BTreeSet::new); + set.extend(probed); + return set.contains(&addr); + } + false +} + +/// The WSL 2 distro's primary internal IPv4 address (`eth0` / default route +/// interface), which `kiri-win` on Windows forwards TCP and UDP ports to. +pub fn wsl_ipv4() -> Option { + let default_iface = std::fs::read_to_string("/proc/net/route") + .ok() + .and_then(|routes| { + routes.lines().skip(1).find_map(|l| { + let mut f = l.split_whitespace(); + let iface = f.next()?; + let dst = f.next()?; + (dst == "00000000").then(|| iface.to_owned()) + }) + }); + let addrs: Vec<(String, std::net::Ipv4Addr)> = super::network::host_interface_ipv4() + .into_iter() + .filter(|(_, ip)| !ip.is_loopback() && !ip.is_unspecified()) + .collect(); + if let Some(def) = default_iface.as_deref() + && let Some((_, ip)) = addrs.iter().find(|(n, _)| n == def) + { + return Some(*ip); + } + if let Some((_, ip)) = addrs.iter().find(|(n, _)| n == "eth0") { + return Some(*ip); + } + addrs + .into_iter() + .find(|(n, _)| { + !n.starts_with("lo") + && !n.starts_with("kiri") + && !n.starts_with("veth") + && !n.starts_with("docker") + && !n.starts_with("br-") + && !n.starts_with("cni") + && !n.starts_with("flannel") + }) + .map(|(_, ip)| ip) +} + +/// Monotonic generation tagging each `Forwards` publish batch so a stale +/// `Forwards::drop` -> `Msg::Unpublish` can never wipe the DNAT rules of a +/// newly restarted container with the same ID (#649). +static PUBLISH_GEN: AtomicU64 = AtomicU64::new(1); + +fn publish_key(id: &str) -> String { + format!("{id}:{}", PUBLISH_GEN.fetch_add(1, Ordering::Relaxed)) +} + /// A running forward for one container; dropping it closes every listener. pub struct Forwards { wake: Vec, @@ -207,8 +491,51 @@ pub struct Forwards { /// In the VM: the guest ports its kernel forwards for these listeners; /// dropping tells the agent to stop, then frees the ports. nat: Option<(Arc, String, Vec)>, + /// In the VM: the ports also published on the VM's own loopback, for + /// `--network host` containers (`loopback_ports`); dropping tells the + /// agent to stop if `nat` didn't already unpublish the container. + loopback: Option<(Arc, String)>, + /// Tracks an active host port-53 binding while these forwards stay up (#760). + host_port_53: Option, /// What was actually bound: (binding, host address, host port). pub bound: Vec<(Binding, String, u16)>, + #[cfg(test)] + on_drop: Option>, +} + +#[cfg(test)] +impl Forwards { + /// Test helper: builds a `Forwards` that runs `on_drop` (after joining any + /// listener thread and closing any bound socket) when dropped. + pub(super) fn test_dummy(bound: Vec<(Binding, String, u16)>, listener: Option, on_drop: impl FnOnce() + Send + 'static) -> Forwards { + let mut wake = Vec::new(); + let mut threads = Vec::new(); + if let Some(l) = listener { + let (wake_r, wake_w) = pipe().unwrap(); + wake.push(wake_w); + threads.push( + std::thread::Builder::new() + .name("kiri-test-port".into()) + .spawn(move || { + let _keep = l; + let mut pfd = libc::pollfd { fd: wake_r.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + // SAFETY: polling a single owned pipe descriptor until its write end closes. + unsafe { libc::poll(&mut pfd, 1, -1) }; + }) + .unwrap(), + ); + } + Forwards { + wake, + threads, + kernel: None, + nat: None, + loopback: None, + host_port_53: None, + bound, + on_drop: Some(Box::new(on_drop)), + } + } } impl std::fmt::Debug for Forwards { @@ -219,17 +546,29 @@ impl std::fmt::Debug for Forwards { impl Drop for Forwards { fn drop(&mut self) { + let mut unpublished = false; if let Some((vm, id, ..)) = self.kernel.take() { let _ = vm.unpublish(&id); + unpublished = true; } if let Some((vm, id, _ports)) = self.nat.take() { let _ = vm.unpublish(&id); + unpublished = true; + } + if let Some((vm, id)) = self.loopback.take() + && !unpublished + { + let _ = vm.unpublish(&id); } // Closing the write ends wakes every listener thread. self.wake.clear(); for t in self.threads.drain(..) { let _ = t.join(); } + #[cfg(test)] + if let Some(f) = self.on_drop.take() { + f(); + } } } @@ -272,10 +611,38 @@ fn relays_too(ip: &str) -> bool { !kernel_forwards(ip) || kernel_host_ip(ip) == Some([0; 4]) } +#[cfg(target_os = "macos")] +fn bind_loopback_interface(fd: std::os::fd::RawFd, is_ipv6: bool) -> io::Result<()> { + // SAFETY: `c"lo0"` is a static NUL-terminated C string. + let idx = unsafe { libc::if_nametoindex(c"lo0".as_ptr()) }; + if idx == 0 { + return Err(io::Error::last_os_error()); + } + let (level, opt) = if is_ipv6 { + (libc::IPPROTO_IPV6, libc::IPV6_BOUND_IF) + } else { + (libc::IPPROTO_IP, libc::IP_BOUND_IF) + }; + // SAFETY: `idx` is a `c_uint` interface index matching `setsockopt`. + if unsafe { libc::setsockopt(fd, level, opt, (&idx as *const libc::c_uint).cast(), std::mem::size_of::() as libc::socklen_t) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + +#[cfg(not(target_os = "macos"))] +fn bind_loopback_interface(_fd: std::os::fd::RawFd, _is_ipv6: bool) -> io::Result<()> { + Ok(()) +} + /// A socket bound to `addr`; an IPv6 one with IPV6_V6ONLY, so `[::]:port` /// sits beside `0.0.0.0:port` (as Docker binds both) instead of clashing /// with it, and serves IPv6 alone. fn bind_socket(addr: SocketAddr, udp: bool) -> io::Result { + bind_socket_on_if(addr, udp, false) +} + +fn bind_socket_on_if(addr: SocketAddr, udp: bool, bind_lo0: bool) -> io::Result { let (family, ty) = (if addr.is_ipv6() { libc::AF_INET6 } else { libc::AF_INET }, if udp { libc::SOCK_DGRAM } else { libc::SOCK_STREAM }); // SAFETY: plain socket creation; owned at once. let fd = unsafe { libc::socket(family, ty, 0) }; @@ -296,6 +663,9 @@ fn bind_socket(addr: SocketAddr, udp: bool) -> io::Result { if addr.is_ipv6() && set(libc::IPPROTO_IPV6, libc::IPV6_V6ONLY) != 0 { return Err(io::Error::last_os_error()); } + if cfg!(target_os = "macos") && bind_lo0 { + bind_loopback_interface(sock.as_raw_fd(), addr.is_ipv6())?; + } // SAFETY: the sockaddr storage is filled for `addr`'s family and sized to match. let (storage, len) = sockaddr_of(addr); if unsafe { libc::bind(sock.as_raw_fd(), (&storage as *const libc::sockaddr_storage).cast(), len) } != 0 { @@ -362,7 +732,7 @@ fn listen_addrs(b: &Binding) -> Vec<(String, bool)> { /// an engine left running beside Kiri (the one containers were imported /// from) or a server on the Mac holds the port, and "already allocated" /// alone reads as if Kiri had lost track of its own containers. None when -/// Kiri itself has it, or when lsof says nothing. +/// Kiri itself has it, or when neither `lsof` nor `netstat -anv` finds a holder. #[cfg(target_os = "macos")] fn holder(port: u16, udp: bool) -> Option { let spec = if udp { format!("-iUDP:{port}") } else { format!("-iTCP:{port}") }; @@ -371,8 +741,18 @@ fn holder(port: u16, udp: bool) -> Option { if !udp { cmd.arg("-sTCP:LISTEN"); } - let out = cmd.stderr(std::process::Stdio::null()).output().ok()?; - holder_in(&String::from_utf8_lossy(&out.stdout)) + if let Ok(out) = cmd.stderr(std::process::Stdio::null()).output() + && let Some(name) = holder_in(&String::from_utf8_lossy(&out.stdout)) + { + return Some(name); + } + let proto = if udp { "udp" } else { "tcp" }; + let out = std::process::Command::new("/usr/sbin/netstat") + .args(["-anv", "-p", proto]) + .stderr(std::process::Stdio::null()) + .output() + .ok()?; + holder_in_netstat(&String::from_utf8_lossy(&out.stdout), port, udp, std::process::id(), super::vmnet::process_name) } #[cfg(not(target_os = "macos"))] @@ -387,11 +767,223 @@ fn holder_in(lsof: &str) -> Option { lsof.lines().filter_map(|l| l.strip_prefix('c')).map(str::trim).find(|c| !c.is_empty() && !c.to_ascii_lowercase().starts_with("kiri")).map(str::to_owned) } +/// Fallback holder lookup from `netstat -anv` when unprivileged `lsof` cannot +/// inspect root-owned sockets (e.g. `mDNSResponder` on port 53, #760). +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn holder_in_netstat( + netstat: &str, + port: u16, + udp: bool, + self_pid: u32, + mut resolve_pid: impl FnMut(u32) -> Option, +) -> Option { + for (name, pid) in super::vmnet::parse_netstat_listeners(netstat, port, udp) { + if pid == self_pid { + continue; + } + let Some(resolved) = name.or_else(|| resolve_pid(pid)) else { continue }; + let trimmed = resolved.trim(); + if !trimmed.is_empty() && !trimmed.to_ascii_lowercase().starts_with("kiri") { + return Some(trimmed.to_owned()); + } + } + None +} + +fn is_non_default_ipv4_loopback(ip: &str) -> bool { + ip.parse::().is_ok_and(|v4| v4.is_loopback() && v4 != std::net::Ipv4Addr::LOCALHOST) +} + +fn format_bind_error( + e: io::Error, + shown_ip: &str, + bare_ip: &str, + host_port: u16, + holder_name: Option<&str>, + is_macos: bool, + shared_nat_active: bool, +) -> io::Error { + if e.kind() == io::ErrorKind::AddrInUse { + let by = holder_name.map(|name| format!(" (in use by {name})")).unwrap_or_default(); + let mut msg = format!("Bind for {shown_ip}:{host_port} failed: port is already allocated{by}"); + if is_macos && host_port == 53 && (shared_nat_active || holder_name.is_some_and(|n| n.eq_ignore_ascii_case("mDNSResponder"))) { + msg.push_str("; macOS shared NAT uses port 53 (mDNSResponder): run `kiri vm set --shared-nat off` and restart Kiri, or bind a high port with `/etc/resolver/` (`port `)"); + } + return io::Error::new(e.kind(), msg); + } + if is_macos + && (e.kind() == io::ErrorKind::AddrNotAvailable || e.raw_os_error() == Some(libc::EADDRNOTAVAIL)) + && is_non_default_ipv4_loopback(bare_ip) + { + return io::Error::new( + e.kind(), + format!("Bind for {shown_ip}:{host_port} failed: address is not assigned on macOS (run `sudo ifconfig lo0 alias {bare_ip}` or use `127.0.0.1`)"), + ); + } + e +} + +fn wildcard_of(addr: SocketAddr) -> SocketAddr { + let ip = if addr.is_ipv6() { + IpAddr::V6(std::net::Ipv6Addr::UNSPECIFIED) + } else { + IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED) + }; + SocketAddr::new(ip, addr.port()) +} + +/// Whether `peer` may use a listener or UDP socket: when a macOS low-port +/// loopback binding (`127.0.0.1:` or `[::1]:`, `port < 1024`) fell +/// back to the wildcard address (`loopback_only`), only loopback peers +/// (`127.0.0.0/8`, `::1`, `::ffff:127.0.0.0/104`) are accepted (#473). +fn peer_allowed(peer: IpAddr, loopback_only: bool) -> bool { + !loopback_only || peer.to_canonical().is_loopback() +} + +fn bind_with_macos_low_loopback( + addr: SocketAddr, + port: u16, + is_udp: bool, + step_aside: impl FnMut(u16) -> bool, +) -> io::Result<(OwnedFd, bool)> { + let bind = |a: SocketAddr, u: bool| { + let bind_lo0 = addr.ip().is_loopback() && a.ip().is_unspecified(); + bind_socket_on_if(a, u, bind_lo0) + }; + bind_with_macos_low_loopback_with(addr, port, is_udp, cfg!(target_os = "macos"), bind, step_aside) +} + +fn bind_with_macos_low_loopback_with( + addr: SocketAddr, + port: u16, + is_udp: bool, + is_macos: bool, + mut bind: impl FnMut(SocketAddr, bool) -> io::Result, + mut step_aside: impl FnMut(u16) -> bool, +) -> io::Result<(T, bool)> { + let mut try_bind = |a: SocketAddr| { + bind(a, is_udp).or_else(|e| { + if e.kind() == io::ErrorKind::AddrInUse && !is_udp && port != 0 && step_aside(port) { + bind(a, false) + } else { + Err(e) + } + }) + }; + match try_bind(addr) { + Ok(s) => Ok((s, false)), + // On macOS XNU, unprivileged processes get EACCES (`PermissionDenied`) + // when binding `127.0.0.1:` or `[::1]:` for `port < 1024`, + // even though XNU lets unprivileged processes bind `0.0.0.0:` and + // `[::]:` (#473). Fall back to the wildcard of the same family + // (stepping the container-domain router aside on AddrInUse via + // `try_bind`) and filter non-loopback peers in `accept_loop`/`udp_loop`. + Err(e) + if is_macos + && e.kind() == io::ErrorKind::PermissionDenied + && addr.ip().is_loopback() + && (1..1024).contains(&port) => + { + try_bind(wildcard_of(addr)).map(|s| (s, true)) + } + Err(e) => Err(e), + } +} + +/// Result of attempting Linux-host kernel DNAT publication for a container's +/// bound sockets (`publish_linux_host`). +struct LinuxPublish { + any_published: bool, + kernel_bound: Vec<(Binding, String, u16)>, + kernel_tcp: Vec, + kernel_udp: Vec, + relay_tcp: Vec<(Binding, Option, String, u16, bool, T)>, + relay_udp: Vec<(Binding, Option, String, u16, bool, U)>, + fallback_error: Option, +} + +/// Linux host: installs kernel DNAT rules for every non-loopback IPv4 binding +/// and separates kernel-only sockets (kept bound to reserve the ports) from +/// user-space relayed ones (`relay_direct` / `udp_loop`). If any `publish` +/// fails — notably when the host firewall blocks kernel `FORWARD` (#649) — +/// unpublishes `publish_id` and leaves every socket in the user-space relay +/// lists so remote connections are accepted on `INPUT` via `relay_direct` +/// instead of being blackholed by `prerouting` DNAT. +fn publish_linux_host( + publish_id: &str, + target_ip: [u8; 4], + tcp: Vec<(Binding, Option, String, u16, bool, T)>, + udp: Vec<(Binding, Option, String, u16, bool, U)>, + mut publish: impl FnMut(kiri_proto::Publish<'_>) -> io::Result<()>, + mut unpublish: impl FnMut(&str), +) -> LinuxPublish { + let all = udp + .iter() + .map(|(b, _, bind_ip, port, _, _)| (b, bind_ip, *port, true)) + .chain(tcp.iter().map(|(b, _, bind_ip, port, _, _)| (b, bind_ip, *port, false))); + let mut published = Ok(false); + for (b, bind_ip, port, is_udp) in all.filter(|(_, bind_ip, ..)| kernel_forwards(bind_ip)) { + let p = kiri_proto::Publish { + id: publish_id, + udp: is_udp, + host_ip: kernel_host_ip(bind_ip).expect("checked IPv4 binding"), + host_port: port, + to_ip: target_ip, + to_port: b.container_port, + }; + published = publish(p).map(|()| true); + if published.is_err() { + break; + } + } + match published { + Ok(any_published) => { + // Sockets only the kernel serves stay bound, so the ports read as taken. + let (kernel_udp, relay_udp): (Vec<_>, Vec<_>) = udp.into_iter().partition(|(_, _, bind_ip, ..)| !relays_too(bind_ip)); + let (kernel_tcp, relay_tcp): (Vec<_>, Vec<_>) = tcp.into_iter().partition(|(_, _, bind_ip, ..)| !relays_too(bind_ip)); + let mut kernel_bound = Vec::with_capacity(kernel_udp.len() + kernel_tcp.len()); + kernel_bound.extend(kernel_udp.iter().filter_map(|(b, rep_ip, _, port, _, _)| rep_ip.as_ref().map(|ip| (b.clone(), ip.clone(), *port)))); + kernel_bound.extend(kernel_tcp.iter().filter_map(|(b, rep_ip, _, port, _, _)| rep_ip.as_ref().map(|ip| (b.clone(), ip.clone(), *port)))); + LinuxPublish { + any_published, + kernel_bound, + kernel_tcp: kernel_tcp.into_iter().map(|(.., s)| s).collect(), + kernel_udp: kernel_udp.into_iter().map(|(.., s)| s).collect(), + relay_tcp, + relay_udp, + fallback_error: None, + } + } + Err(e) => { + unpublish(publish_id); + LinuxPublish { + any_published: false, + kernel_bound: Vec::new(), + kernel_tcp: Vec::new(), + kernel_udp: Vec::new(), + relay_tcp: tcp, + relay_udp: udp, + fallback_error: Some(e), + } + } + } +} + /// Binds every port first (so a clash fails the start cleanly), then starts /// one accept thread per listener. pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4]) -> io::Result { - let mut listeners = Vec::with_capacity(bindings.len()); - let mut udp = Vec::new(); + let in_wsl = super::binds::wsl().is_some(); + // In WSL 2 NAT mode, `wsl_ipv4()` is WSL's dedicated internal `eth0` IP. + // In mirrored/bridged mode, `wsl_ipv4()` is itself one of the Windows host + // interface IPs; filter it out so we never bind an extra LAN socket for a + // loopback-only (`-p 127.0.0.1:port/udp`) binding. + let wsl_eth0 = if in_wsl { + wsl_ipv4().filter(|ip| !is_windows_host_ip(&ip.to_string())) + } else { + None + }; + let mut listeners: Vec<(Binding, Option, String, u16, bool, TcpListener)> = Vec::with_capacity(bindings.len()); + let mut udp: Vec<(Binding, Option, String, u16, bool, UdpSocket)> = Vec::new(); for b in bindings { // A port picked by the kernel (0) is picked once: the `::` listener // takes the one 0.0.0.0 got. @@ -399,20 +991,40 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] for (ip, required) in listen_addrs(b) { let addr = host_addr(&ip, port)?; let taken = |e: io::Error| { - if e.kind() == io::ErrorKind::AddrInUse { - let shown = if addr.is_ipv6() { format!("[{ip}]") } else { ip.clone() }; - // Docker's words, then who has the port when it is not Kiri. - let by = holder(b.host_port, b.proto == "udp").map(|name| format!(" (in use by {name})")).unwrap_or_default(); - io::Error::new(e.kind(), format!("Bind for {shown}:{} failed: port is already allocated{by}", b.host_port)) - } else { - e + let shown = if addr.is_ipv6() { format!("[{ip}]") } else { ip.clone() }; + // Docker's words, then who has the port when it is not Kiri. + let by = (e.kind() == io::ErrorKind::AddrInUse).then(|| holder(b.host_port, b.proto == "udp")).flatten(); + format_bind_error(e, &shown, &ip, b.host_port, by.as_deref(), cfg!(target_os = "macos"), shared_nat_active()) + }; + let is_udp = b.proto == "udp"; + let (bound, bind_ip, loopback_only) = match bind_with_macos_low_loopback(addr, port, is_udp, super::domains::step_aside) { + Ok((s, true)) => (Ok(s), wildcard_of(addr).ip().to_string(), true), + Ok((s, false)) => (Ok(s), ip.clone(), false), + // In WSL 2, a Windows host interface IP (`-p :port:cport`) + // is not assigned inside the Linux VM (`EADDRNOTAVAIL` / os error 99). + // When the IP belongs to a Windows host interface and WSL has a + // distinct internal `eth0` IPv4 address, bind WSL's `eth0` address + // (never 0.0.0.0, which would make wslrelay.exe expose 127.0.0.1:port + // on Windows) while `kiri-win` binds `:port` on Windows and + // forwards to `:`. + Err(e) + if in_wsl + && (e.kind() == io::ErrorKind::AddrNotAvailable || e.raw_os_error() == Some(libc::EADDRNOTAVAIL)) + && is_windows_host_ip(&ip) => + { + if let Some(fallback_ip) = wsl_eth0 { + let fallback_addr = SocketAddr::new(IpAddr::V4(fallback_ip), port); + ( + bind_with_macos_low_loopback(fallback_addr, port, is_udp, super::domains::step_aside).map(|(s, _)| s), + fallback_ip.to_string(), + false, + ) + } else { + (Err(e), ip.clone(), false) + } } + Err(e) => (Err(e), ip.clone(), false), }; - // Kiri's own container-domain router on this port lets it go - // (domains::step_aside), and the bind goes again. - let bound = bind_socket(addr, b.proto == "udp").or_else(|e| { - if e.kind() == io::ErrorKind::AddrInUse && b.proto == "tcp" && port != 0 && super::domains::step_aside(port) { bind_socket(addr, false) } else { Err(e) } - }); let sock = match bound { Ok(s) => s, Err(e) if required => return Err(taken(e)), @@ -423,93 +1035,167 @@ pub fn start(vm: Arc, id: &str, bindings: &[Binding], target_ip: [u8; 4] continue; } }; - if b.proto == "udp" { + if is_udp { let s = UdpSocket::from(sock); s.set_nonblocking(true)?; port = s.local_addr()?.port(); - udp.push((b.clone(), ip, port, s)); + udp.push((b.clone(), Some(ip), bind_ip.clone(), port, loopback_only, s)); + // WSL 2's localhostForwarding never forwards UDP, so `kiri-win` + // forwards Windows UDP ports (including 127.0.0.1:port/udp) to + // `:/udp`. Ensure `:/udp` is + // also bound/DNATed inside WSL when the primary bind was loopback + // or IPv6-only. + if let Some(eth0) = wsl_eth0 { + let eth0_str = eth0.to_string(); + if bind_ip != "0.0.0.0" + && bind_ip != eth0_str + && !udp.iter().any(|(_, _, bip, p, _, _)| *p == port && (bip == "0.0.0.0" || bip == ð0_str)) + && let Ok(aux_fd) = bind_socket(SocketAddr::new(IpAddr::V4(eth0), port), true) + { + let aux = UdpSocket::from(aux_fd); + let _ = aux.set_nonblocking(true); + udp.push((b.clone(), None, eth0_str, port, false, aux)); + } + } continue; } let l = TcpListener::from(sock); l.set_nonblocking(true)?; port = l.local_addr()?.port(); - listeners.push((b.clone(), ip, port, l)); + listeners.push((b.clone(), Some(ip.clone()), bind_ip.clone(), port, loopback_only, l)); + if let Some(eth0) = wsl_eth0 { + let eth0_str = eth0.to_string(); + if ip == "::" + && !listeners.iter().any(|(_, _, bip, p, _, _)| *p == port && (bip == "0.0.0.0" || bip == ð0_str)) + && let Ok(aux_fd) = bind_socket(SocketAddr::new(IpAddr::V4(eth0), port), false) + { + let aux = TcpListener::from(aux_fd); + let _ = aux.set_nonblocking(true); + listeners.push((b.clone(), None, eth0_str, port, false, aux)); + } + } } } - let mut fw = Forwards { wake: Vec::new(), threads: Vec::new(), kernel: None, nat: None, bound: Vec::new() }; + let publish_id = publish_key(id); + let mut fw = Forwards { + wake: Vec::new(), + threads: Vec::new(), + kernel: None, + nat: None, + loopback: None, + host_port_53: None, + bound: Vec::new(), + #[cfg(test)] + on_drop: None, + }; // On a Linux host the daemon shares the kernel with the containers, so // the kernel can rewrite the packets (nftables DNAT) instead of two // user-space relays copying every byte; that serves every address but - // loopback. The listeners below relay the rest. A target on loopback (a - // --network host container) stays relayed: that is a local socket. + // loopback. The listeners below relay the rest (and everything when the + // host firewall blocks kernel FORWARD, #649). if cfg!(target_os = "linux") && target_ip != [127, 0, 0, 1] { - let all = udp.iter().map(|(b, ip, port, _)| (b, ip, *port, true)).chain(listeners.iter().map(|(b, ip, port, _)| (b, ip, *port, false))); - let mut published = Ok(false); - for (b, ip, port, is_udp) in all.filter(|(_, ip, ..)| kernel_forwards(ip)) { - let p = kiri_proto::Publish { id, udp: is_udp, host_ip: kernel_host_ip(ip).expect("checked IPv4 binding"), host_port: port, to_ip: target_ip, to_port: b.container_port }; - published = vm.publish(p).map(|()| true); - if published.is_err() { - break; - } - } - match published { - Ok(any) => { - // Sockets only the kernel serves stay bound, so the ports read as taken. - let (kernel_udp, relay_udp): (Vec<_>, Vec<_>) = udp.into_iter().partition(|(_, ip, ..)| !relays_too(ip)); - let (kernel_tcp, relay_tcp): (Vec<_>, Vec<_>) = listeners.into_iter().partition(|(_, ip, ..)| !relays_too(ip)); - fw.bound.extend(kernel_udp.iter().map(|(b, ip, port, _)| (b.clone(), ip.clone(), *port))); - fw.bound.extend(kernel_tcp.iter().map(|(b, ip, port, _)| (b.clone(), ip.clone(), *port))); - if any { - fw.kernel = Some((vm.clone(), id.to_owned(), kernel_tcp.into_iter().map(|(.., s)| s).collect(), kernel_udp.into_iter().map(|(.., s)| s).collect())); - } - udp = relay_udp; - listeners = relay_tcp; - } - Err(e) => { - let _ = vm.unpublish(id); - crate::diag::warn!("kernel port forwarding failed; relaying in user space", id = &id[..id.len().min(12)], error = e); + let res = publish_linux_host( + &publish_id, + target_ip, + listeners, + udp, + |p| vm.publish(p), + |pid| { + let _ = vm.unpublish(pid); + }, + ); + if let Some(e) = res.fallback_error { + crate::diag::warn!("kernel port forwarding failed; relaying in user space", id = &id[..id.len().min(12)], error = e); + } else { + fw.bound.extend(res.kernel_bound); + if res.any_published { + fw.kernel = Some((vm.clone(), publish_id.clone(), res.kernel_tcp, res.kernel_udp)); } } + udp = res.relay_udp; + listeners = res.relay_tcp; } - for (b, ip, port, sock) in udp { + for (b, rep_ip, _bind_ip, port, loopback_only, sock) in udp { let (wake_r, wake_w) = pipe()?; fw.wake.push(wake_w); let vm = vm.clone(); let container_port = b.container_port; fw.threads.push(std::thread::Builder::new().name(format!("kiri-udp-{port}")).spawn(move || { - udp_loop(&sock, &wake_r, &vm, target_ip, container_port); + udp_loop(&sock, &wake_r, &vm, target_ip, container_port, loopback_only); })?); - fw.bound.push((b, ip, port)); + if let Some(ip) = rep_ip { + fw.bound.push((b, ip, port)); + } } // In the VM: the guest kernel forwards each TCP binding from a port of - // its own on the NAT network. A target on loopback stays relayed. + // its own on the NAT network. A target on loopback (or a VM booted without + // shared NAT) stays relayed over vsock. let mut nat = vec![None; listeners.len()]; - if cfg!(target_os = "macos") && target_ip != [127, 0, 0, 1] && !listeners.is_empty() { - match publish_nat(&vm, id, &listeners.iter().map(|(b, ..)| b.container_port).collect::>(), target_ip) { + if cfg!(target_os = "macos") && shared_nat_active() && target_ip != [127, 0, 0, 1] && !listeners.is_empty() { + match publish_nat(&vm, &publish_id, &listeners.iter().map(|(b, ..)| b.container_port).collect::>(), target_ip) { Ok((addrs, ports)) => { nat = addrs.into_iter().map(Some).collect(); - fw.nat = Some((vm.clone(), id.to_owned(), ports)); + fw.nat = Some((vm.clone(), publish_id.clone(), ports)); } Err(e) => crate::diag::warn!("NAT port forwarding unavailable; relaying over vsock", id = &id[..id.len().min(12)], error = e), } } - for ((b, ip, port, listener), nat) in listeners.into_iter().zip(nat) { + // In the VM: a `--network host` container shares the VM's network, not + // the Mac's, so the VM's 127.0.0.1 has none of these ports. Each TCP + // port the Mac has on its loopback is published there too: the agent + // sends the VM's own connections to it through the host relay, to this + // listener. As on Docker, where a published port is bound in the host's + // namespace. A target on loopback is itself a host-network container. + if cfg!(target_os = "macos") && target_ip != [127, 0, 0, 1] { + let ports = loopback_ports(listeners.iter().filter_map(|(b, rep_ip, _, port, _, _)| rep_ip.as_deref().map(|ip| (b.container_port, ip, *port)))); + let mut published = false; + for (to_port, host_port) in ports { + let p = kiri_proto::Publish { id: &publish_id, udp: false, host_ip: [127, 0, 0, 1], host_port, to_ip: target_ip, to_port }; + match vm.publish(p) { + Ok(()) => published = true, + Err(e) => crate::diag::warn!("published port not reachable from host-network containers", port = host_port, error = e), + } + } + if published { + fw.loopback = Some((vm.clone(), publish_id.clone())); + } + } + for ((b, rep_ip, _bind_ip, port, loopback_only, listener), nat) in listeners.into_iter().zip(nat) { let (wake_r, wake_w) = pipe()?; fw.wake.push(wake_w); let vm = vm.clone(); let container_port = b.container_port; fw.threads.push(std::thread::Builder::new().name(format!("kiri-port-{port}")).spawn(move || { - accept_loop(&listener, &wake_r, &vm, target_ip, container_port, nat); + accept_loop(&listener, &wake_r, &vm, target_ip, container_port, nat, loopback_only); })?); - fw.bound.push((b, ip, port)); + if let Some(ip) = rep_ip { + fw.bound.push((b, ip, port)); + } + } + if binds_host_dns_port(&fw.bound) { + fw.host_port_53 = Some(HostPort53Guard::acquire()); } Ok(fw) } +/// The TCP ports (container port, port bound on the Mac) that are on the +/// Mac's loopback: bound on 127.0.0.1 or on every IPv4 address, once each. +/// A port on one other address, or on IPv6 only, is not. +fn loopback_ports<'a>(bound: impl Iterator) -> Vec<(u16, u16)> { + let mut out: Vec<(u16, u16)> = Vec::new(); + for (container_port, ip, port) in bound { + if matches!(ip, "" | "0.0.0.0" | "127.0.0.1") && !out.iter().any(|(_, p)| *p == port) { + out.push((container_port, port)); + } + } + out +} + /// Asks the agent to forward a guest port to each container port, from the /// Mac only; returns the address the Mac dials for each. All or nothing. fn publish_nat(vm: &VmLink, id: &str, container_ports: &[u16], target_ip: [u8; 4]) -> io::Result<(Vec, Vec)> { - let (guest_ip, _gateway) = vm.uplink()?; + let (guest_ip, gateway) = vm.uplink()?; + set_vm_subnet(gateway, VM_UPLINK_PREFIX); let mut addrs = Vec::with_capacity(container_ports.len()); let mut ports = Vec::with_capacity(container_ports.len()); for &to_port in container_ports { @@ -534,7 +1220,7 @@ struct UdpSession { last: Instant, reader: JoinHandle<()>, // Keeps the connection open until the session ends. - _guest: kiri_vmm::VsockStream, + _guest: Option, } impl UdpSession { @@ -545,9 +1231,31 @@ impl UdpSession { } } +fn udp_idle_timeout(host_port: u16, container_port: u16) -> Duration { + if host_port == 53 || container_port == 53 { UDP_DNS_IDLE } else { UDP_IDLE } +} + /// Datagrams from each client go to the container over its own session; /// replies come back to that client. Quiet sessions close. -fn udp_loop(sock: &UdpSocket, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], port: u16) { +fn udp_loop(sock: &UdpSocket, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], port: u16, loopback_only: bool) { + let host_port = sock.local_addr().map(|a| a.port()).unwrap_or(0); + udp_loop_with(sock, wake, loopback_only, udp_idle_timeout(host_port, port), |s, peer| { + open_udp_session(s, vm, ip, port, peer) + }); +} + +fn udp_loop_with( + sock: &UdpSocket, + wake: &OwnedFd, + loopback_only: bool, + idle: Duration, + mut open_session: impl FnMut(&UdpSocket, SocketAddr) -> io::Result, +) { + if cfg!(target_os = "macos") && loopback_only { + let is_v6 = sock.local_addr().is_ok_and(|a| a.is_ipv6()); + let _ = bind_loopback_interface(sock.as_raw_fd(), is_v6); + } + let poll_ms = (idle.as_millis() / 2).clamp(100, 5_000) as libc::c_int; let mut sessions: std::collections::HashMap = std::collections::HashMap::new(); let mut buf = vec![0u8; 65_536]; loop { @@ -564,7 +1272,7 @@ fn udp_loop(sock: &UdpSocket, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], por }, ]; // SAFETY: polling two descriptors we own; wake up now and then to reap. - let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, 5_000) }; + let n = unsafe { libc::poll(fds.as_mut_ptr(), 2, poll_ms) }; if n < 0 && io::Error::last_os_error().kind() != io::ErrorKind::Interrupted { break; } @@ -572,6 +1280,9 @@ fn udp_loop(sock: &UdpSocket, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], por break; // the container stopped } while let Ok((len, peer)) = sock.recv_from(&mut buf) { + if !peer_allowed(peer.ip(), loopback_only) { + continue; + } if !sessions.contains_key(&peer) { // Cap sessions so a source-spoofing flood cannot exhaust // threads and guest connections; drop the oldest to make room. @@ -582,7 +1293,7 @@ fn udp_loop(sock: &UdpSocket, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], por } } } - match open_udp_session(sock, vm, ip, port, peer) { + match open_session(sock, peer) { Ok(s) => { sessions.insert(peer, s); } @@ -600,8 +1311,8 @@ fn udp_loop(sock: &UdpSocket, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], por } } } - let idle: Vec = sessions.iter().filter(|(_, s)| s.last.elapsed() >= UDP_IDLE || s.reader.is_finished()).map(|(a, _)| *a).collect(); - for a in idle { + let idle_peers: Vec = sessions.iter().filter(|(_, s)| s.last.elapsed() >= idle || s.reader.is_finished()).map(|(a, _)| *a).collect(); + for a in idle_peers { if let Some(s) = sessions.remove(&a) { s.close(); } @@ -638,11 +1349,11 @@ fn open_udp_session(sock: &UdpSocket, vm: &VmLink, ip: [u8; 4], port: u16, peer: to_guest, last: Instant::now(), reader, - _guest: guest, + _guest: Some(guest), }) } -fn accept_loop(listener: &TcpListener, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], port: u16, nat: Option) { +fn accept_loop(listener: &TcpListener, wake: &OwnedFd, vm: &Arc, ip: [u8; 4], port: u16, nat: Option, loopback_only: bool) { loop { let mut fds = [ libc::pollfd { @@ -667,6 +1378,11 @@ fn accept_loop(listener: &TcpListener, wake: &OwnedFd, vm: &Arc, ip: [u8 return; // the container stopped } while let Ok((client, from)) = listener.accept() { + if !peer_allowed(from.ip(), loopback_only) + || (loopback_only && !client.local_addr().is_ok_and(|a| peer_allowed(a.ip(), true))) + { + continue; + } let Some(permit) = tcp_permit(from.ip()) else { continue; }; @@ -718,7 +1434,7 @@ fn relay(client: TcpStream, vm: &VmLink, ip: [u8; 4], port: u16, nat: Option { NAT_TIMEOUTS.store(0, Ordering::Relaxed); @@ -964,7 +1680,8 @@ pub const HOST_ADDR: &str = "198.19.248.254"; pub const HOST_BOUND_PORT: u32 = 1026; /// One host-bound connection from a container: the guest sends -/// `ip[4] port[2]` (always 127.0.0.1 today), and we connect there on the Mac. +/// `ip[4] port[2]` (always 127.0.0.1 today), and we connect to the Mac's +/// loopback at that port. pub fn serve_host_bound(stream: kiri_vmm::VsockStream) { let _ = std::thread::Builder::new().name("kiri-host-bound".into()).spawn(move || { let _ = host_bound(stream); @@ -983,7 +1700,7 @@ fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { } // Refused or unreachable: dropping closes the container's connection, // which is what it would see from a real host too. - let target = TcpStream::connect((ip, port))?; + let target = dial_loopback(port)?; target.set_nodelay(true)?; let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); let mut target_read = target.try_clone()?; @@ -1000,6 +1717,11 @@ fn host_bound(stream: kiri_vmm::VsockStream) -> io::Result<()> { Ok(()) } +/// The Mac's loopback at `port`: IPv4, then IPv6 for a server on `::1` only (#258). +fn dial_loopback(port: u16) -> io::Result { + TcpStream::connect((std::net::Ipv4Addr::LOCALHOST, port)).or_else(|e| TcpStream::connect((std::net::Ipv6Addr::LOCALHOST, port)).map_err(|_| e)) +} + /// The guest's relay only ever asks for the Mac's loopback; anything else is /// a guest process speaking the protocol itself. A router's port is refused /// too: it serves this Mac, and would take a container to any container. @@ -1007,90 +1729,1767 @@ fn host_bound_allowed(ip: std::net::Ipv4Addr, port: u16, router: impl Fn(u16) -> ip == std::net::Ipv4Addr::LOCALHOST && !router(port) } -/// vsock port the guest dials for SSH agent connections. -pub const SSH_AGENT_PORT: u32 = 1027; +/// How long an outbound host-dialed TCP connection waits to connect. +const EGRESS_CONNECT: Duration = Duration::from_secs(10); +/// Default macOS `VZNATNetworkDeviceAttachment` (`bridge100`) subnet. +pub const DEFAULT_VM_SUBNET: ([u8; 4], u8) = ([192, 168, 64, 0], 24); +/// RFC 2544 benchmarking range used as a synthetic Fake-IP pool by macOS +/// security network extensions (#367). +pub const FAKE_IP_CIDR: ([u8; 4], u8) = ([198, 18, 0, 0], 15); +/// Prefix of the VM's NAT uplink: `VZNATNetworkDeviceAttachment` leases a /24. +pub const VM_UPLINK_PREFIX: u8 = 24; +/// Additional VM NAT bridge subnets learned at runtime (`bridge100`, guest +/// uplink), via `set_vm_subnet`. +static VM_SUBNETS: Mutex> = Mutex::new(Vec::new()); + +pub fn ipv4_mask(prefix: u8) -> u32 { + let p = prefix.min(32); + if p == 0 { 0 } else { u32::MAX << (32 - p) } +} + +pub fn mask_ipv4(ip: [u8; 4], prefix: u8) -> [u8; 4] { + (u32::from_be_bytes(ip) & ipv4_mask(prefix)).to_be_bytes() +} + +pub fn cidr_contains(net: [u8; 4], prefix: u8, ip: [u8; 4]) -> bool { + let mask = ipv4_mask(prefix); + (u32::from_be_bytes(ip) & mask) == (u32::from_be_bytes(net) & mask) +} -/// The Mac's SSH agent socket: `$SSH_AUTH_SOCK`, or launchd's if the daemon -/// was not started from a shell that has it. -fn ssh_auth_sock() -> Option { - if let Some(p) = std::env::var_os("SSH_AUTH_SOCK") { - return Some(p.into()); +/// Whether the host egress dialer may connect to `ip:port` on behalf of a +/// container. Rejects loopback (`127.0.0.0/8`), unspecified (`0.0.0.0/8`), +/// link-local (`169.254.0.0/16`), multicast and reserved (`224.0.0.0/4`, +/// `240.0.0.0/4`, broadcast), `host.docker.internal` (`198.19.248.254`), +/// port 0, and the VM's own NAT bridge subnet (`192.168.64.0/24` and any +/// subnet in `vm_subnets`). +pub fn egress_allowed(ip: std::net::Ipv4Addr, port: u16, vm_subnets: &[([u8; 4], u8)]) -> bool { + let o = ip.octets(); + if port == 0 + || o[0] == 0 + || o[0] == 127 + || (o[0] == 169 && o[1] == 254) + || o[0] >= 224 + || o == [198, 19, 248, 254] + || cidr_contains(DEFAULT_VM_SUBNET.0, DEFAULT_VM_SUBNET.1, o) + || vm_subnets.iter().any(|&(net, prefix)| cidr_contains(net, prefix, o)) + { + return false; } - let out = std::process::Command::new("/bin/launchctl").args(["getenv", "SSH_AUTH_SOCK"]).output().ok()?; - let p = String::from_utf8_lossy(&out.stdout).trim().to_owned(); - (!p.is_empty()).then(|| p.into()) + true } -/// One container connection to the SSH agent, relayed to the Mac's agent. -pub fn serve_ssh_agent(stream: kiri_vmm::VsockStream) { - let _ = std::thread::Builder::new().name("kiri-ssh-agent".into()).spawn(move || { - let Some(path) = ssh_auth_sock() else { return }; - let Ok(agent) = std::os::unix::net::UnixStream::connect(path) else { - return; - }; - let (Ok(mut agent_read), Ok(from_guest), Ok(to_guest)) = (agent.try_clone(), stream.fd.try_clone(), stream.fd.try_clone()) else { - return; - }; - let mut from_guest = std::fs::File::from(from_guest); - let mut to_guest = std::fs::File::from(to_guest); - let mut agent_write = agent; - let down = std::thread::spawn(move || { - let _ = copy(&mut agent_read, &mut to_guest); - // SAFETY: half-closing a socket we own. - unsafe { libc::shutdown(to_guest.as_raw_fd(), libc::SHUT_WR) }; - }); - let _ = copy(&mut from_guest, &mut agent_write); - let _ = agent_write.shutdown(Shutdown::Write); - let _ = down.join(); - drop(stream); - }); +/// Records the VM's NAT uplink subnet, learned from the agent's `Uplink` +/// (its gateway is the Mac's side of the NAT network), so the host egress +/// dialer refuses it as it does `DEFAULT_VM_SUBNET` even when macOS picked +/// another bridge subnet. +pub fn set_vm_subnet(gateway: [u8; 4], prefix: u8) { + let prefix = prefix.min(32); + let net = (mask_ipv4(gateway, prefix), prefix); + let mut subnets = VM_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()); + if !subnets.contains(&net) { + subnets.push(net); + } } -/// vsock port the guest dials for the engine's API: containers that mount -/// the docker socket (crates/kiri/src/daemon/binds.rs). -pub const ENGINE_API_PORT: u32 = 1036; +fn current_vm_subnets() -> Vec<([u8; 4], u8)> { + VM_SUBNETS.lock().unwrap_or_else(|e| e.into_inner()).clone() +} -/// One container connection to the engine's API, served like any other -/// client's, marked as a container's. -pub fn serve_engine_api(stream: kiri_vmm::VsockStream, engine: std::sync::Weak) { - let _ = std::thread::Builder::new().name("kiri-engine-api".into()).spawn(move || { - // Served here rather than through the daemon's socket, so the API - // knows these requests are a container's (caller.rs). - let Some(engine) = engine.upgrade() else { return }; - let Ok((api, ours)) = std::os::unix::net::UnixStream::pair() else { return }; - let served = std::thread::Builder::new().name("kiri-api".into()).spawn(move || { - let _ = super::api::serve(ours, engine, super::caller::Caller::Container); - }); - if served.is_err() { - return; - } - let (Ok(mut api_read), Ok(from_guest), Ok(to_guest)) = (api.try_clone(), stream.fd.try_clone(), stream.fd.try_clone()) else { - return; - }; - let mut from_guest = std::fs::File::from(from_guest); - let mut to_guest = std::fs::File::from(to_guest); - let mut api_write = api; - let down = std::thread::spawn(move || { - let _ = copy(&mut api_read, &mut to_guest); - // SAFETY: half-closing a socket we own. - unsafe { libc::shutdown(to_guest.as_raw_fd(), libc::SHUT_WR) }; - }); - let _ = copy(&mut from_guest, &mut api_write); - let _ = api_write.shutdown(Shutdown::Write); - let _ = down.join(); - drop(stream); +/// Whether the host egress dialer may connect to `ip:port` now, given the VM +/// NAT subnets learned so far. +fn egress_target_allowed(ip: std::net::Ipv4Addr, port: u16) -> bool { + egress_allowed(ip, port, ¤t_vm_subnets()) +} + +/// One outbound TCP connection redirected from a container to the host +/// dialer (`kiri_proto::EGRESS_TCP_PORT`): the guest sends `ip[4] port[2]`, +/// and the daemon dials it from the host process so macOS split-tunnel VPN +/// routes (`utun*`, `ipsec*`, `ppp*`, #319) and NetworkExtension socket +/// filters (#367, #616) carry the connection. +pub fn serve_egress(stream: kiri_vmm::VsockStream) { + let Some(permit) = tcp_permit(IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)) else { + return; + }; + let _ = std::thread::Builder::new().name("kiri-egress".into()).spawn(move || { + let _permit = permit; + let _ = egress(stream); }); } -/// The TCP ports in a container's `/proc/net/tcp` and `tcp6` lines that are -/// listening: those a published port reaches, then those it does not. The -/// relay dials the container's IPv4 address, so a socket bound to loopback -/// alone, or to one IPv6 address, is out of its reach; with host networking -/// it dials 127.0.0.1, so loopback is in reach there. Each port once, sorted. -pub fn listening>(lines: &[S], host_network: bool) -> (Vec, Vec) { - use std::collections::BTreeSet; - use std::net::{Ipv4Addr, Ipv6Addr}; - let v4_reach = |ip: Ipv4Addr| !ip.is_loopback() || host_network; +fn egress(stream: kiri_vmm::VsockStream) -> io::Result<()> { + vsock_stall(stream.fd.as_raw_fd())?; + let mut from_guest = std::fs::File::from(stream.fd.try_clone()?); + let mut header = [0u8; 6]; + from_guest.read_exact(&mut header)?; + let ip = std::net::Ipv4Addr::new(header[0], header[1], header[2], header[3]); + let port = u16::from_be_bytes([header[4], header[5]]); + if !egress_target_allowed(ip, port) { + crate::diag::warn!("refused an outbound egress connection to a restricted address", to = format!("{ip}:{port}")); + return Err(io::Error::new(io::ErrorKind::PermissionDenied, "egress target not allowed")); + } + let target = TcpStream::connect_timeout(&SocketAddr::from((ip, port)), EGRESS_CONNECT)?; + relayed_tcp(&target)?; + let mut to_guest = std::fs::File::from(stream.fd.try_clone()?); + let mut target_read = target.try_clone()?; + let mut target_write = target; + let down = std::thread::Builder::new().name("kiri-egress-down".into()).spawn(move || { + let how = match pass_on(copy(&mut target_read, &mut to_guest)) { + Shutdown::Write => libc::SHUT_WR, + _ => libc::SHUT_RDWR, + }; + // SAFETY: shutting down a socket we own. + unsafe { libc::shutdown(to_guest.as_raw_fd(), how) }; + })?; + let up = copy(&mut from_guest, &mut target_write); + let _ = target_write.shutdown(pass_on(up)); + let _ = down.join(); + drop(stream); + Ok(()) +} + +/// Whether `name` is a tunnel interface that macOS `InternetSharing` does not +/// NAT `bridge100` out of (`utun*`, `ipsec*`, `ppp*`, `gpd*`, `feth*`). +pub fn is_tunnel_iface(name: &str) -> bool { + ["utun", "ipsec", "ppp", "gpd", "feth"] + .iter() + .any(|prefix| name.strip_prefix(prefix).is_some_and(|rest| !rest.is_empty() && rest.bytes().all(|b| b.is_ascii_digit()))) +} + +/// Collapses a set of IPv4 CIDRs, removing duplicates, sub-prefixes already +/// covered by a broader prefix, and merging aligned sibling halves (such as +/// OpenVPN `def1`'s `0.0.0.0/1` + `128.0.0.0/1` → `0.0.0.0/0`). +pub fn collapse_cidrs(cidrs: impl IntoIterator) -> Vec<([u8; 4], u8)> { + let mut list: Vec<([u8; 4], u8)> = cidrs + .into_iter() + .map(|(ip, prefix)| { + let p = prefix.min(32); + (mask_ipv4(ip, p), p) + }) + .collect(); + list.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + list.dedup(); + let mut disjoint: Vec<([u8; 4], u8)> = Vec::with_capacity(list.len()); + for (net, prefix) in list { + if !disjoint.iter().any(|&(broader_net, broader_prefix)| broader_prefix <= prefix && cidr_contains(broader_net, broader_prefix, net)) { + disjoint.push((net, prefix)); + } + } + disjoint.sort_by_key(|&(net, prefix)| (u32::from_be_bytes(net), prefix)); + let mut merged: Vec<(u32, u8)> = Vec::with_capacity(disjoint.len()); + for (net, prefix) in disjoint { + let mut cur = (u32::from_be_bytes(net), prefix); + while let Some(&(prev_net, prev_prefix)) = merged.last() { + if prev_prefix != cur.1 || prev_prefix == 0 { + break; + } + let parent_prefix = prev_prefix - 1; + let parent_mask = ipv4_mask(parent_prefix); + if (prev_net & parent_mask) == (cur.0 & parent_mask) { + merged.pop(); + cur = (prev_net & parent_mask, parent_prefix); + } else { + break; + } + } + merged.push(cur); + } + let mut out: Vec<([u8; 4], u8)> = merged.into_iter().map(|(net, prefix)| (net.to_be_bytes(), prefix)).collect(); + out.sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0))); + out +} + +/// An active (`IFF_UP | IFF_RUNNING`) macOS tunnel interface (`utun*`, +/// `ipsec*`, `ppp*`, `gpd*`, `feth*`) carrying a non-loopback, non-link-local +/// IPv4 address (distinguishing active VPN tunnels from macOS's dormant +/// IDS/iCloud `utun*` interfaces, which only carry `fe80::` link-local IPv6). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ActiveTunnel { + pub name: String, + pub ip: [u8; 4], + pub prefix: u8, + pub peer: Option<[u8; 4]>, + pub point_to_point: bool, +} + +fn is_routable_tunnel_ipv4(ip: [u8; 4]) -> bool { + ip[0] != 0 && ip[0] != 127 && !(ip[0] == 169 && ip[1] == 254) && ip[0] < 224 +} + +fn is_tunnel_route_skippable(dst: [u8; 4], prefix: u8) -> bool { + dst[0] == 127 + || (dst[0] == 169 && dst[1] == 254) + || dst[0] >= 224 + || (dst == [0, 0, 0, 0] && prefix == 32) +} + +/// Parses a macOS `sysctl([CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0])` +/// binary routing table buffer and returns the collapsed IPv4 CIDR prefixes +/// whose outgoing interface is a tunnel (`is_tunnel_iface`), skipping +/// loopback, link-local and multicast/reserved destinations. +#[cfg(test)] +pub fn parse_macos_routes(buf: &[u8], ifname_of: impl Fn(u16) -> Option) -> Vec<([u8; 4], u8)> { + parse_macos_routes_with_tunnels(buf, ifname_of, &[]) +} + +/// Parses a macOS `NET_RT_DUMP` buffer together with active IPv4 tunnel +/// interfaces (`active_tunnels` from `getifaddrs`), returning the collapsed +/// IPv4 CIDR prefixes that must route through the host egress dialer (#932): +/// - Unscoped routes on any tunnel interface (`is_tunnel_iface`) are kept. +/// - `RTF_IFSCOPE` routes on non-tunnel interfaces and dormant tunnels +/// without an IPv4 address are ignored. +/// - On an active IPv4 tunnel, non-default `RTF_IFSCOPE` split routes are +/// kept, and an `RTF_IFSCOPE` default route (`0.0.0.0/0`) is promoted when +/// that tunnel has no explicit non-endpoint narrower routes (catching +/// macOS 15+ `includeAllNetworks` / built-in IKEv2 / IPSec / PPP full +/// tunnels without misclassifying split-tunnel OpenVPN/Tailscale/WireGuard). +/// - An active IPv4 tunnel with no explicit non-endpoint routes in the route +/// table contributes `0.0.0.0/0` when it is a `/32` (or `/0`) +/// point-to-point tunnel (NECP policy-routed VPN), or its own subnet when +/// it has a `1..=31` netmask. +pub fn parse_macos_routes_with_tunnels( + buf: &[u8], + ifname_of: impl Fn(u16) -> Option, + active_tunnels: &[ActiveTunnel], +) -> Vec<([u8; 4], u8)> { + const RTM_HDR_LEN: usize = 92; + const RTM_VERSION: u8 = 5; + const RTF_UP: i32 = 0x1; + const RTF_HOST: i32 = 0x4; + const RTF_LLINFO: i32 = 0x400; + const RTF_WASCLONED: i32 = 0x20000; + const RTF_IFSCOPE: i32 = 0x1000000; + const AF_INET_U8: u8 = libc::AF_INET as u8; + + #[cfg(target_os = "macos")] + const _: () = assert!(std::mem::size_of::() == RTM_HDR_LEN); + + let mut entries: Vec<([u8; 4], u8, String, bool)> = Vec::new(); + let mut off = 0; + while off + RTM_HDR_LEN <= buf.len() { + let msglen = u16::from_ne_bytes([buf[off], buf[off + 1]]) as usize; + if msglen < RTM_HDR_LEN || off + msglen > buf.len() { + break; + } + let msg = &buf[off..off + msglen]; + off += msglen; + + let version = msg[2]; + if version != RTM_VERSION { + continue; + } + let ifindex = u16::from_ne_bytes([msg[4], msg[5]]); + let flags = i32::from_ne_bytes([msg[8], msg[9], msg[10], msg[11]]); + let addrs = i32::from_ne_bytes([msg[12], msg[13], msg[14], msg[15]]); + if flags & RTF_UP == 0 || flags & (RTF_WASCLONED | RTF_LLINFO) != 0 || addrs & 0x1 == 0 { + continue; + } + let is_ifscope = flags & RTF_IFSCOPE != 0; + let mut pos = RTM_HDR_LEN; + let mut dst: Option<[u8; 4]> = None; + let mut mask_prefix: Option = None; + let mut ok = true; + for bit in 0..8 { + if addrs & (1 << bit) == 0 { + continue; + } + if pos + 2 > msg.len() { + ok = false; + break; + } + let sa_len = msg[pos]; + let sa_family = msg[pos + 1]; + let step = if sa_len == 0 { 4 } else { ((sa_len as usize) + 3) & !3 }; + if bit == 0 { + if sa_family != AF_INET_U8 || sa_len < 8 || pos + 8 > msg.len() { + ok = false; + break; + } + dst = Some([msg[pos + 4], msg[pos + 5], msg[pos + 6], msg[pos + 7]]); + } else if bit == 2 { + let mut mask = [0u8; 4]; + let avail = (sa_len as usize).min(msg.len().saturating_sub(pos)).saturating_sub(4).min(4); + if avail > 0 { + mask[..avail].copy_from_slice(&msg[pos + 4..pos + 4 + avail]); + } + mask_prefix = Some(u32::from_be_bytes(mask).leading_ones() as u8); + } + if pos + step > msg.len() { + break; + } + pos += step; + } + if !ok { + continue; + } + let Some(dst_ip) = dst else { continue }; + let prefix = if flags & RTF_HOST != 0 { + 32 + } else { + mask_prefix.unwrap_or(0) + }; + let Some(ifname) = ifname_of(ifindex).filter(|s| !s.is_empty()) else { continue }; + if !is_tunnel_iface(&ifname) { + continue; + } + let net = mask_ipv4(dst_ip, prefix); + if is_tunnel_route_skippable(net, prefix) { + continue; + } + entries.push((net, prefix, ifname, is_ifscope)); + } + + let is_active_tunnel = |name: &str| active_tunnels.iter().any(|t| t.name == name && is_tunnel_iface(&t.name) && is_routable_tunnel_ipv4(t.ip)); + let mut routes = Vec::new(); + for &(dst, prefix, ref ifname, is_ifscope) in &entries { + if !is_ifscope || (prefix > 0 && is_active_tunnel(ifname)) { + routes.push((dst, prefix)); + } + } + for t in active_tunnels { + if !is_tunnel_iface(&t.name) || !is_routable_tunnel_ipv4(t.ip) { + continue; + } + let is_endpoint = |dst: [u8; 4], prefix: u8| prefix == 32 && (dst == t.ip || t.peer == Some(dst)); + let mut has_unscoped_default = false; + let mut has_ifscope_default = false; + let mut has_explicit_narrower = false; + for &(dst, prefix, ref ifname, is_ifscope) in &entries { + if ifname != &t.name { + continue; + } + if prefix == 0 { + if is_ifscope { + has_ifscope_default = true; + } else { + has_unscoped_default = true; + } + } else if !is_endpoint(dst, prefix) { + has_explicit_narrower = true; + } + } + if has_unscoped_default { + continue; + } + if has_ifscope_default && !has_explicit_narrower { + routes.push(([0, 0, 0, 0], 0)); + } else if !has_explicit_narrower { + if t.point_to_point && (t.prefix == 0 || t.prefix == 32) { + routes.push(([0, 0, 0, 0], 0)); + } else if (1..=31).contains(&t.prefix) { + let net = mask_ipv4(t.ip, t.prefix); + if !is_tunnel_route_skippable(net, t.prefix) { + routes.push((net, t.prefix)); + } + } + } + } + collapse_cidrs(routes) +} + +/// Whether `identifier` is a split-tunnel/mesh packet-tunnel extension known to +/// coexist cleanly with macOS `vmnet` NAT via standard unscoped kernel subnet +/// routes on `utun*` (Tailscale, WireGuard). All other activated third-party +/// `networkextension` SystemExtensions — including enterprise SASE / VPN +/// `com.apple.networkextension.packet-tunnel` extensions (GlobalProtect, +/// Zscaler, Netskope, Cisco Secure Client, Cloudflare WARP, FortiClient, +/// Jamf Trust, Twingate) whose tunnels use `RTF_IFSCOPE` routes or sub-1500 +/// MTUs that break `vmnet` PMTUD / TLS 1.3 ClientHello (#350, #932) — enable +/// host egress relay. +fn is_pure_packet_tunnel_ext(identifier: &str) -> bool { + identifier.starts_with("io.tailscale.") || identifier.starts_with("com.wireguard.") +} + +fn is_network_ext_category(cat: &str) -> bool { + matches!( + cat, + "com.apple.system_extension.network_extension" | "com.apple.developer.networking.networkextension" + ) +} + +/// Parses `/Library/SystemExtensions/db.plist` (either XML plist or `bplist00` +/// binary plist) and returns true when an active (`activated_enabled`) +/// third-party macOS NetworkExtension content filter, transparent proxy or +/// DNS proxy is enabled (#367, #616). +pub fn has_active_network_extension(plist: &[u8]) -> bool { + if plist.starts_with(b"bplist00") { + has_active_network_extension_bplist(plist) + } else if let Ok(xml) = std::str::from_utf8(plist) { + has_active_network_extension_xml(xml) + } else { + false + } +} + +fn has_active_network_extension_xml(xml: &str) -> bool { + // Walk top-level entries inside extensions... + // (or any if the snippet is not wrapped in extensions). + let scope = match xml.find("extensions") { + Some(idx) => &xml[idx..], + None => xml, + }; + for dict in xml_extension_dicts(scope) { + let Some(id) = xml_key_string(dict, "identifier") else { continue }; + let Some(state) = xml_key_string(dict, "state") else { continue }; + if state != "activated_enabled" || id.is_empty() || id.starts_with("com.apple.") { + continue; + } + let has_net_cat = dict.contains("com.apple.system_extension.network_extension") + || dict.contains("com.apple.developer.networking.networkextension"); + if !has_net_cat { + continue; + } + if is_pure_packet_tunnel_ext(id) { + continue; + } + return true; + } + false +} + +/// Extracts each extension `...` block from `xml`, tracking +/// nested `` depth so sub-dictionaries (`bundleVersion`, `container`, +/// `stagedBundleURL`) stay inside their parent extension block. +fn xml_extension_dicts(xml: &str) -> Vec<&str> { + let mut out = Vec::new(); + let base_depth = if xml.trim_start().starts_with("extensions") { 1 } else { 2 }; + let mut depth = 0usize; + let mut start: Option = None; + let mut i = 0; + let bytes = xml.as_bytes(); + while i < bytes.len() { + if bytes[i] == b'<' { + if xml[i..].starts_with("") || xml[i..].starts_with("") { + if depth == base_depth + && let Some(s) = start.take() + { + out.push(&xml[s..i + 7]); + } + depth = depth.saturating_sub(1); + i += 7; + continue; + } + } + i += 1; + } + if out.is_empty() && base_depth == 2 { + // Fallback for a bare `...` fixture at depth 1. + return xml_extension_dicts_at(xml, 1); + } + out +} + +fn xml_extension_dicts_at(xml: &str, target_depth: usize) -> Vec<&str> { + let mut out = Vec::new(); + let mut depth = 0usize; + let mut start: Option = None; + let mut i = 0; + let bytes = xml.as_bytes(); + while i < bytes.len() { + if bytes[i] == b'<' { + if xml[i..].starts_with("") || xml[i..].starts_with("") { + if depth == target_depth + && let Some(s) = start.take() + { + out.push(&xml[s..i + 7]); + } + depth = depth.saturating_sub(1); + i += 7; + continue; + } + } + i += 1; + } + out +} + +fn xml_key_string<'a>(dict: &'a str, key: &str) -> Option<&'a str> { + let pattern = format!("{key}"); + let idx = dict.find(&pattern)?; + let rest = dict[idx + pattern.len()..].trim_start(); + let rest = rest.strip_prefix("")?; + let end = rest.find("")?; + Some(rest[..end].trim()) +} + +#[derive(Debug)] +enum BplistObj<'a> { + Str(&'a str), + Array(Vec), + Dict(Vec<(usize, usize)>), + Other, +} + +fn read_be_uint(b: &[u8]) -> Option { + if b.is_empty() || b.len() > 8 { + return None; + } + let mut v = 0usize; + for &byte in b { + v = (v << 8) | (byte as usize); + } + Some(v) +} + +fn bplist_len(buf: &[u8], pos: usize, low: u8) -> Option<(usize, usize)> { + if low != 0x0f { + return Some((low as usize, pos)); + } + let marker = *buf.get(pos)?; + if (marker >> 4) != 0x1 { + return None; + } + let nbytes = 1usize << (marker & 0x0f); + let end = pos.checked_add(1)?.checked_add(nbytes)?; + let len = read_be_uint(buf.get(pos + 1..end)?)?; + Some((len, end)) +} + +fn parse_bplist(buf: &[u8]) -> Option<(usize, Vec>)> { + if buf.len() < 40 || !buf.starts_with(b"bplist00") { + return None; + } + let trailer = &buf[buf.len() - 32..]; + let offset_size = trailer[6] as usize; + let ref_size = trailer[7] as usize; + if !(1..=8).contains(&offset_size) || !(1..=8).contains(&ref_size) { + return None; + } + let num_objects = read_be_uint(&trailer[8..16])?; + let top_object = read_be_uint(&trailer[16..24])?; + let offset_table = read_be_uint(&trailer[24..32])?; + if num_objects == 0 || num_objects > 65_536 || top_object >= num_objects { + return None; + } + let table_end = offset_table.checked_add(num_objects.checked_mul(offset_size)?)?; + if table_end > buf.len() - 32 { + return None; + } + let mut objs = Vec::with_capacity(num_objects); + for i in 0..num_objects { + let off_pos = offset_table + i * offset_size; + let obj_off = read_be_uint(buf.get(off_pos..off_pos + offset_size)?)?; + let marker = *buf.get(obj_off)?; + let kind = marker >> 4; + let low = marker & 0x0f; + let obj = match kind { + 0x4 => { + let (len, start) = bplist_len(buf, obj_off + 1, low)?; + let _ = buf.get(start..start.checked_add(len)?)?; + BplistObj::Other + } + 0x5 => { + let (len, start) = bplist_len(buf, obj_off + 1, low)?; + let s = std::str::from_utf8(buf.get(start..start.checked_add(len)?)?).ok()?; + BplistObj::Str(s) + } + 0xa => { + let (count, start) = bplist_len(buf, obj_off + 1, low)?; + if count > 65_536 { + return None; + } + let mut items = Vec::with_capacity(count); + for j in 0..count { + let p = start.checked_add(j.checked_mul(ref_size)?)?; + items.push(read_be_uint(buf.get(p..p.checked_add(ref_size)?)?)?); + } + BplistObj::Array(items) + } + 0xd => { + let (count, start) = bplist_len(buf, obj_off + 1, low)?; + if count > 65_536 { + return None; + } + let vals_start = start.checked_add(count.checked_mul(ref_size)?)?; + let mut pairs = Vec::with_capacity(count); + for j in 0..count { + let kp = start + j * ref_size; + let vp = vals_start + j * ref_size; + let k = read_be_uint(buf.get(kp..kp.checked_add(ref_size)?)?)?; + let v = read_be_uint(buf.get(vp..vp.checked_add(ref_size)?)?)?; + pairs.push((k, v)); + } + BplistObj::Dict(pairs) + } + _ => BplistObj::Other, + }; + objs.push(obj); + } + Some((top_object, objs)) +} + +fn has_active_network_extension_bplist(buf: &[u8]) -> bool { + let Some((top, objs)) = parse_bplist(buf) else { return false }; + let get_dict_field = |pairs: &[(usize, usize)], key: &str| -> Option { + pairs.iter().find_map(|&(k, v)| match objs.get(k) { + Some(BplistObj::Str(s)) if *s == key => Some(v), + _ => None, + }) + }; + let get_str = |idx: usize| -> Option<&str> { + match objs.get(idx) { + Some(BplistObj::Str(s)) => Some(*s), + _ => None, + } + }; + let Some(BplistObj::Dict(root)) = objs.get(top) else { return false }; + let Some(ext_idx) = get_dict_field(root, "extensions") else { return false }; + let Some(BplistObj::Array(items)) = objs.get(ext_idx) else { return false }; + for &item in items { + let Some(BplistObj::Dict(pairs)) = objs.get(item) else { continue }; + let Some(id) = get_dict_field(pairs, "identifier").and_then(get_str) else { continue }; + let Some(state) = get_dict_field(pairs, "state").and_then(get_str) else { continue }; + if state != "activated_enabled" || id.is_empty() || id.starts_with("com.apple.") { + continue; + } + let has_net_cat = get_dict_field(pairs, "categories").is_some_and(|cidx| match objs.get(cidx) { + Some(BplistObj::Array(cats)) => cats.iter().any(|&c| get_str(c).is_some_and(is_network_ext_category)), + _ => false, + }); + if !has_net_cat { + continue; + } + if is_pure_packet_tunnel_ext(id) { + continue; + } + return true; + } + false +} + +fn parse_cidr_str(s: &str) -> Option<([u8; 4], u8)> { + let (ip, prefix) = s.trim().split_once('/')?; + let ip = ip.parse::().ok()?.octets(); + let prefix: u8 = prefix.parse().ok().filter(|&p| p <= 32)?; + Some((mask_ipv4(ip, prefix), prefix)) +} + +/// Computes the egress CIDR strings to send to the guest given: +/// - `env_mode`: `KIRI_HOST_EGRESS` (`auto`, `always`, `off`, or comma-separated CIDRs) +/// - `shared_nat`: whether the macOS VM attached `VZNATNetworkDeviceAttachment` +/// - `has_net_ext`: whether an active third-party macOS NetworkExtension filter/proxy is enabled +/// - `tunnel_routes`: IPv4 prefixes routed over tunnel interfaces (`utun*`, `ipsec*`, `ppp*`, `gpd*`, `feth*`) +/// - `is_macos`: whether the host is macOS +pub fn host_egress_routes_with_nat( + env_mode: Option<&str>, + shared_nat: bool, + has_net_ext: bool, + tunnel_routes: &[([u8; 4], u8)], + is_macos: bool, +) -> Vec { + let mode = env_mode.map(str::trim).unwrap_or("auto"); + if mode.eq_ignore_ascii_case("off") || mode.eq_ignore_ascii_case("0") || mode.eq_ignore_ascii_case("false") || mode.eq_ignore_ascii_case("no") { + return Vec::new(); + } + if mode.eq_ignore_ascii_case("always") || mode.eq_ignore_ascii_case("1") || mode.eq_ignore_ascii_case("true") || mode.eq_ignore_ascii_case("all") { + return vec!["0.0.0.0/0".into()]; + } + if mode.contains('/') { + let parsed: Vec<([u8; 4], u8)> = mode.split(',').filter_map(parse_cidr_str).collect(); + return collapse_cidrs(parsed) + .into_iter() + .map(|(ip, p)| format!("{}.{}.{}.{}/{p}", ip[0], ip[1], ip[2], ip[3])) + .collect(); + } + if !is_macos { + return Vec::new(); + } + if !shared_nat || has_net_ext { + return vec!["0.0.0.0/0".into()]; + } + let mut all = tunnel_routes.to_vec(); + all.push(FAKE_IP_CIDR); + collapse_cidrs(all) + .into_iter() + .map(|(ip, p)| format!("{}.{}.{}.{}/{p}", ip[0], ip[1], ip[2], ip[3])) + .collect() +} + +#[cfg(test)] +pub fn host_egress_routes_for( + env_mode: Option<&str>, + has_net_ext: bool, + tunnel_routes: &[([u8; 4], u8)], + is_macos: bool, +) -> Vec { + host_egress_routes_with_nat(env_mode, true, has_net_ext, tunnel_routes, is_macos) +} + +#[cfg(target_os = "macos")] +fn dump_macos_route_table() -> Option> { + let mut mib = [libc::CTL_NET, libc::PF_ROUTE, 0, libc::AF_INET, libc::NET_RT_DUMP, 0]; + let mut len: libc::size_t = 0; + // SAFETY: sysctl with null oldp queries the required buffer size. + if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, std::ptr::null_mut(), &mut len, std::ptr::null_mut(), 0) } != 0 || len == 0 { + return None; + } + // Add headroom in case a route is added between the two calls. + len = len.saturating_add(4096); + let mut buf = vec![0u8; len]; + // SAFETY: sysctl writes at most `len` bytes into `buf`. + if unsafe { libc::sysctl(mib.as_mut_ptr(), 6, buf.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0) } != 0 { + return None; + } + buf.truncate(len); + Some(buf) +} + +#[cfg(target_os = "macos")] +fn macos_ifname(index: u16) -> Option { + let mut buf = [0 as libc::c_char; libc::IFNAMSIZ]; + // SAFETY: `buf` is IFNAMSIZ bytes, as if_indextoname requires. + let ptr = unsafe { libc::if_indextoname(index as libc::c_uint, buf.as_mut_ptr()) }; + if ptr.is_null() { + return None; + } + // SAFETY: if_indextoname NUL-terminates `buf` on success. + Some(unsafe { std::ffi::CStr::from_ptr(ptr) }.to_string_lossy().into_owned()) +} + +#[cfg(target_os = "macos")] +fn macos_active_ipv4_tunnels() -> Vec { + let mut list: *mut libc::ifaddrs = std::ptr::null_mut(); + // SAFETY: getifaddrs allocates `list`, freed below. + if unsafe { libc::getifaddrs(&mut list) } != 0 { + return Vec::new(); + } + let mut out = Vec::new(); + let mut cur = list; + while !cur.is_null() { + // SAFETY: `cur` is a valid node from `getifaddrs`. + let ifa = unsafe { &*cur }; + cur = ifa.ifa_next; + if ifa.ifa_name.is_null() || ifa.ifa_addr.is_null() { + continue; + } + let flags = ifa.ifa_flags as i32; + if flags & (libc::IFF_UP | libc::IFF_RUNNING) != (libc::IFF_UP | libc::IFF_RUNNING) + || flags & libc::IFF_LOOPBACK != 0 + { + continue; + } + // SAFETY: `ifa_addr` is non-null. + if i32::from(unsafe { (*ifa.ifa_addr).sa_family }) != libc::AF_INET { + continue; + } + // SAFETY: `ifa_name` is NUL-terminated by `getifaddrs`. + let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }.to_string_lossy().into_owned(); + if !is_tunnel_iface(&name) { + continue; + } + // SAFETY: `sa_family == AF_INET` guarantees a `sockaddr_in`. + let ip = unsafe { (*(ifa.ifa_addr as *const libc::sockaddr_in)).sin_addr.s_addr }.to_ne_bytes(); + if !is_routable_tunnel_ipv4(ip) { + continue; + } + let prefix = if !ifa.ifa_netmask.is_null() { + // SAFETY: `ifa_netmask` is non-null; `sa_len` gives its valid byte length. + let sa_len = unsafe { (*ifa.ifa_netmask).sa_len } as usize; + let sa_family = i32::from(unsafe { (*ifa.ifa_netmask).sa_family }); + if sa_family == libc::AF_INET || sa_family == 0 { + let avail = sa_len.saturating_sub(4).min(4); + let mut mask = [0u8; 4]; + if avail > 0 { + // SAFETY: `4 + avail <= sa_len`, within the kernel-allocated sockaddr. + let bytes = unsafe { std::slice::from_raw_parts(ifa.ifa_netmask.cast::(), sa_len) }; + mask[..avail].copy_from_slice(&bytes[4..4 + avail]); + } + u32::from_be_bytes(mask).leading_ones() as u8 + } else { + 32 + } + } else { + 32 + }; + let point_to_point = flags & libc::IFF_POINTOPOINT != 0; + let peer = if point_to_point && !ifa.ifa_dstaddr.is_null() { + // SAFETY: `ifa_dstaddr` is non-null. + let sa_family = i32::from(unsafe { (*ifa.ifa_dstaddr).sa_family }); + let sa_len = unsafe { (*ifa.ifa_dstaddr).sa_len } as usize; + if sa_family == libc::AF_INET && sa_len >= 8 { + // SAFETY: `sa_family == AF_INET` and `sa_len >= 8` guarantees `sin_addr` is readable. + let bytes = unsafe { std::slice::from_raw_parts(ifa.ifa_dstaddr.cast::(), 8) }; + Some([bytes[4], bytes[5], bytes[6], bytes[7]]) + } else { + None + } + } else { + None + }; + let tunnel = ActiveTunnel { name, ip, prefix, peer, point_to_point }; + if !out.contains(&tunnel) { + out.push(tunnel); + } + } + // SAFETY: `list` came from `getifaddrs` and is freed once. + unsafe { libc::freeifaddrs(list) }; + out +} + +pub fn current_egress_routes() -> Vec { + let env_mode = std::env::var("KIRI_HOST_EGRESS").ok(); + #[cfg(target_os = "macos")] + let (has_ext, tunnel_routes) = { + let ext = std::fs::read("/Library/SystemExtensions/db.plist") + .ok() + .is_some_and(|b| has_active_network_extension(&b)); + let active_tunnels = macos_active_ipv4_tunnels(); + let dump = dump_macos_route_table().unwrap_or_default(); + let routes = parse_macos_routes_with_tunnels(&dump, macos_ifname, &active_tunnels); + (ext, routes) + }; + #[cfg(not(target_os = "macos"))] + let (has_ext, tunnel_routes) = (false, Vec::new()); + host_egress_routes_with_nat(env_mode.as_deref(), shared_nat_active(), has_ext, &tunnel_routes, cfg!(target_os = "macos")) +} + +/// Sends the initial egress routes to `vm` and, on macOS, watches `PF_ROUTE` +/// for routing table changes (a VPN connecting or disconnecting while Kiri +/// runs) so `Msg::SetEgressRoutes` stays current without restarting the VM. +pub fn sync_egress_routes(vm: &Arc) { + let initial = current_egress_routes(); + if !initial.is_empty() { + let _ = vm.set_egress_routes(&initial); + } + #[cfg(target_os = "macos")] + { + let weak = Arc::downgrade(vm); + let _ = std::thread::Builder::new().name("kiri-route-watch".into()).spawn(move || { + watch_macos_routes(weak, initial); + }); + } +} + +#[cfg(target_os = "macos")] +fn watch_macos_routes(weak: std::sync::Weak, mut last: Vec) { + // SAFETY: opening a raw PF_ROUTE socket to hear kernel routing changes. + let fd = unsafe { libc::socket(libc::PF_ROUTE, libc::SOCK_RAW, libc::AF_UNSPEC) }; + let sock = if fd >= 0 { + // SAFETY: `fd` is a fresh descriptor owned only here. + unsafe { + libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC); + let tv = libc::timeval { tv_sec: 2, tv_usec: 0 }; + libc::setsockopt( + fd, + libc::SOL_SOCKET, + libc::SO_RCVTIMEO, + (&tv as *const libc::timeval).cast(), + std::mem::size_of::() as libc::socklen_t, + ); + Some(OwnedFd::from_raw_fd(fd)) + } + } else { + None + }; + let mut buf = [0u8; 4096]; + loop { + match &sock { + Some(s) => { + // SAFETY: reading into a local buffer with SO_RCVTIMEO set. + let n = unsafe { libc::read(s.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + // Drain any burst of route messages before dumping once. + // SAFETY: non-blocking recv into a local buffer. + while unsafe { libc::recv(s.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len(), libc::MSG_DONTWAIT) } > 0 {} + } + } + None => std::thread::sleep(Duration::from_secs(2)), + } + let Some(vm) = weak.upgrade().filter(|v| !v.is_disconnected()) else { + return; + }; + let next = current_egress_routes(); + if next != last { + last = next; + let _ = vm.set_egress_routes(&last); + } + } +} + +/// vsock port the guest dials for SSH agent connections. +pub const SSH_AGENT_PORT: u32 = 1027; + +/// Host SSH agent socket last bind-mounted explicitly by a host-side create +/// (or restored at start from a strict user agent mount) on macOS. Validated +/// before storing (canonicalized, owned Unix socket, allowed SSH agent path, +/// never Kiri's own socket) and re-checked on every connection. +static PREFERRED_SSH_AUTH_SOCK: Mutex> = Mutex::new(None); + +/// Normalizes an absolute path lexically (`//`, `/./`, `/../`) without +/// touching the filesystem. +fn lexical_clean_path(p: &str) -> String { + let mut out: Vec<&str> = Vec::new(); + for c in p.split('/') { + match c { + "" | "." => {} + ".." => { + out.pop(); + } + c => out.push(c), + } + } + format!("/{}", out.join("/")) +} + +/// Whether `path` is Apple launchd's default per-session SSH agent socket: +/// `/private/tmp/com.apple.launchd./Listeners`, +/// `/tmp/com.apple.launchd./Listeners`, +/// `/private/var/run/com.apple.launchd./Listeners`, or +/// `/var/run/com.apple.launchd./Listeners`. +pub(crate) fn is_launchd_ssh_sock(path: &std::path::Path) -> bool { + let Some(s) = path.to_str() else { return false }; + if !s.starts_with('/') { + return false; + } + let clean = lexical_clean_path(s); + const PREFIXES: &[&str] = &["/private/tmp/", "/tmp/", "/private/var/run/", "/var/run/"]; + let Some(rest) = PREFIXES.iter().find_map(|p| clean.strip_prefix(p)) else { + return false; + }; + let Some(dir) = rest.strip_suffix("/Listeners") else { + return false; + }; + dir.starts_with("com.apple.launchd.") + && !dir.contains('/') + && dir.len() > "com.apple.launchd.".len() +} + +/// Whether `path` exists as a Unix domain socket owned by this process's +/// effective UID (follows symlinks, matching `UnixStream::connect`). +pub(crate) fn is_owned_unix_socket(path: &std::path::Path) -> bool { + use std::os::unix::fs::{FileTypeExt, MetadataExt}; + let Ok(meta) = std::fs::metadata(path) else { + return false; + }; + // SAFETY: geteuid only reads this process's effective user ID. + meta.file_type().is_socket() && meta.uid() == unsafe { libc::geteuid() } +} + +fn is_kiri_run_dir(dir: &std::path::Path) -> bool { + match dir.file_name().and_then(|n| n.to_str()) { + Some("kiri") => true, + Some("run") => dir + .parent() + .and_then(|p| p.file_name()) + .and_then(|n| n.to_str()) + .is_some_and(|n| n.starts_with(".kiri") || n == "kiri"), + _ => false, + } +} + +/// Whether `path` is Kiri's own daemon socket or sits inside Kiri's runtime +/// socket directory (`~/.kiri*/run/` or `/run/kiri/`). Never allowed as an SSH +/// agent upstream. +pub(crate) fn is_kiri_socket_path(path: &std::path::Path) -> bool { + let Some(s) = path.to_str() else { return false }; + if super::binds::engine_socket(s).is_some() { + return true; + } + let clean = std::path::PathBuf::from(lexical_clean_path(s)); + let canon = std::fs::canonicalize(path).unwrap_or_else(|_| clean.clone()); + for own in [super::socket_path().ok(), super::home_socket_path().ok()].into_iter().flatten() { + let own_clean = std::path::PathBuf::from(lexical_clean_path(&own.to_string_lossy())); + let own_canon = std::fs::canonicalize(&own).unwrap_or_else(|_| own_clean.clone()); + if canon == own_canon || clean == own_clean { + return true; + } + if let Some(dir) = own_canon.parent() + && is_kiri_run_dir(dir) + && canon.starts_with(dir) + { + return true; + } + if let Some(dir) = own_clean.parent() + && is_kiri_run_dir(dir) + && clean.starts_with(dir) + { + return true; + } + } + false +} + +/// Whether `path` (already canonicalized when on disk, or lexically cleaned +/// otherwise) names a well-known macOS SSH agent socket: +/// - Apple launchd's `com.apple.launchd.*/Listeners` +/// - GnuPG's `S.gpg-agent.ssh` under a Mac user or temp share +/// - 1Password's `~/.1password/agent.sock` or +/// `~/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock` +pub(crate) fn is_known_mac_ssh_agent_sock_path(path: &std::path::Path) -> bool { + if is_launchd_ssh_sock(path) { + return true; + } + let Some(s) = path.to_str() else { return false }; + if !s.starts_with('/') { + return false; + } + let clean = lexical_clean_path(s); + if clean.ends_with("/S.gpg-agent.ssh") { + const SHARES: &[&str] = &[ + "/Users/", + "/Volumes/", + "/private/tmp/", + "/tmp/", + "/private/var/folders/", + "/var/folders/", + ]; + if SHARES.iter().any(|p| clean.starts_with(p)) { + return true; + } + for var in ["HOME", "GNUPGHOME"] { + if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()) { + let base = lexical_clean_path(&dir.to_string_lossy()); + if clean.strip_prefix(&base).is_some_and(|r| r.starts_with('/')) { + return true; + } + } + } + return false; + } + const ONE_PASSWORD_SUFFIXES: &[&str] = &[ + "/.1password/agent.sock", + "/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock", + ]; + for suffix in ONE_PASSWORD_SUFFIXES { + if let Some(prefix) = clean.strip_suffix(suffix) { + if prefix.starts_with("/Users/") || prefix.starts_with("/Volumes/") { + return true; + } + if let Some(home) = std::env::var_os("HOME").filter(|v| !v.is_empty()) + && prefix == lexical_clean_path(&home.to_string_lossy()) + { + return true; + } + } + } + false +} + +/// Strict allowlist used when restoring a preferred SSH agent socket on +/// container start (without caller context): only permits launchd's +/// `Listeners`, 1Password's `agent.sock` directly under the user's `$HOME`, +/// or GnuPG's `S.gpg-agent.ssh` inside `~/.gnupg`, `$GNUPGHOME`, or +/// `gpgconf --list-dirs agent-ssh-socket`. +fn is_strict_mac_ssh_agent_sock_path_for( + path: &std::path::Path, + home: Option<&std::path::Path>, + gnupg_home: Option<&std::path::Path>, + gpgconf_sock: Option<&std::path::Path>, +) -> bool { + if is_launchd_ssh_sock(path) { + return true; + } + let Some(s) = path.to_str() else { return false }; + if !s.starts_with('/') { + return false; + } + let clean = lexical_clean_path(s); + let same = |candidate: std::path::PathBuf| -> bool { + let cand_clean = lexical_clean_path(&candidate.to_string_lossy()); + if clean == cand_clean { + return true; + } + std::fs::canonicalize(&candidate) + .ok() + .and_then(|c| c.to_str().map(lexical_clean_path)) + .is_some_and(|c| c == clean) + }; + if let Some(h) = home { + for rel in [ + ".gnupg/S.gpg-agent.ssh", + ".1password/agent.sock", + "Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock", + ] { + if same(h.join(rel)) { + return true; + } + } + } + if let Some(g) = gnupg_home + && same(g.join("S.gpg-agent.ssh")) + { + return true; + } + if let Some(sock) = gpgconf_sock + && same(sock.to_path_buf()) + { + return true; + } + false +} + +/// Whether a `gpg-agent.conf` file enables SSH agent support via an +/// uncommented `enable-ssh-support` directive. +fn gpg_agent_ssh_enabled(conf: &str) -> bool { + let mut enabled = false; + for line in conf.lines() { + let line = line.split('#').next().unwrap_or("").trim(); + if line.is_empty() { + continue; + } + match line.split_whitespace().next() { + Some("enable-ssh-support") => enabled = true, + Some("no-enable-ssh-support") => enabled = false, + _ => {} + } + } + enabled +} + +fn launchctl_getenv(var: &str) -> Option { + if !cfg!(target_os = "macos") { + return None; + } + let out = std::process::Command::new("/bin/launchctl") + .args(["getenv", var]) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let p = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + (!p.is_empty()).then(|| p.into()) +} + +fn gpgconf_candidates() -> Vec { + let mut out = Vec::new(); + if let Some(path) = std::env::var_os("PATH") { + for dir in std::env::split_paths(&path) { + if !dir.as_os_str().is_empty() { + out.push(dir.join("gpgconf")); + } + } + } + for fallback in [ + "/opt/homebrew/bin/gpgconf", + "/usr/local/bin/gpgconf", + "/usr/local/MacGPG2/bin/gpgconf", + ] { + let p = std::path::PathBuf::from(fallback); + if !out.contains(&p) { + out.push(p); + } + } + out +} + +fn is_executable_file(path: &std::path::Path) -> bool { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(path).is_ok_and(|m| m.is_file() && (m.permissions().mode() & 0o111 != 0)) +} + +fn gpgconf_agent_ssh_socket(gnupg_home: Option<&std::path::Path>) -> Option { + let bin = gpgconf_candidates().into_iter().find(|p| is_executable_file(p))?; + let mut cmd = std::process::Command::new(bin); + cmd.args(["--list-dirs", "agent-ssh-socket"]) + .stdin(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()); + if let Some(dir) = gnupg_home { + cmd.env("GNUPGHOME", dir); + } + let out = cmd.output().ok()?; + if !out.status.success() { + return None; + } + let s = String::from_utf8_lossy(&out.stdout).trim().to_owned(); + (!s.is_empty()).then(|| std::path::PathBuf::from(s)) +} + +/// Checks whether GPG SSH support is enabled in `$GNUPGHOME/gpg-agent.conf` +/// (when `GNUPGHOME` is set) or `~/.gnupg/gpg-agent.conf`, and if so returns +/// candidate GPG SSH agent socket paths in preference order. +fn gather_gpg_ssh_info( + gnupg_home: Option<&std::path::Path>, + home: Option<&std::path::Path>, + gpgconf_sock: impl FnOnce(Option<&std::path::Path>) -> Option, +) -> (bool, Vec) { + let conf_dir = gnupg_home.map(std::path::Path::to_path_buf).or_else(|| home.map(|h| h.join(".gnupg"))); + let enabled = conf_dir + .as_deref() + .and_then(|d| std::fs::read_to_string(d.join("gpg-agent.conf")).ok()) + .is_some_and(|text| gpg_agent_ssh_enabled(&text)); + if !enabled { + return (false, Vec::new()); + } + let mut socks = Vec::new(); + let mut push_unique = |p: std::path::PathBuf| { + if !p.as_os_str().is_empty() && !socks.contains(&p) { + socks.push(p); + } + }; + if let Some(g) = gnupg_home { + push_unique(g.join("S.gpg-agent.ssh")); + } + if let Some(s) = gpgconf_sock(gnupg_home) { + push_unique(s); + } + if let Some(h) = home { + push_unique(h.join(".gnupg/S.gpg-agent.ssh")); + } + (true, socks) +} + +/// Inputs to [`resolve_ssh_auth_sock_candidates`], factored out so the macOS +/// resolution order can be unit-tested without touching process environment or +/// spawning `launchctl`/`gpgconf`. +#[derive(Default)] +struct SshAuthInputs { + preferred: Option, + env_sock: Option, + launchctl_sock: Option, + gpg_ssh_enabled: bool, + gpg_sockets: Vec, +} + +/// Orders live host SSH agent socket candidates on macOS: +/// 1. Explicit host SSH agent socket recorded from a Mac bind mount. +/// 2. Explicit non-launchd `$SSH_AUTH_SOCK` in this process's environment. +/// 3. Explicit non-launchd `launchctl getenv SSH_AUTH_SOCK`. +/// 4. GnuPG's `S.gpg-agent.ssh` when `gpg-agent.conf` has `enable-ssh-support`. +/// 5. Fallback to launchd's default `com.apple.launchd.*/Listeners` socket. +fn resolve_ssh_auth_sock_candidates( + inputs: &SshAuthInputs, + is_live: impl Fn(&std::path::Path) -> bool, +) -> Vec { + let mut out = Vec::new(); + let mut push_unique = |p: &std::path::Path| { + if !p.as_os_str().is_empty() && !out.iter().any(|existing: &std::path::PathBuf| existing == p) { + out.push(p.to_path_buf()); + } + }; + // 1) Explicit host SSH agent socket recorded from a Mac bind mount. + if let Some(p) = inputs.preferred.as_deref() + && is_live(p) + { + push_unique(p); + } + // 2) Explicit non-launchd $SSH_AUTH_SOCK from daemon environment. + if let Some(p) = inputs.env_sock.as_deref() + && !is_launchd_ssh_sock(p) + && is_live(p) + { + push_unique(p); + } + // 3) Explicit non-launchd `launchctl getenv SSH_AUTH_SOCK`. + if let Some(p) = inputs.launchctl_sock.as_deref() + && !is_launchd_ssh_sock(p) + && is_live(p) + { + push_unique(p); + } + // 4) GPG SSH agent socket when `enable-ssh-support` is configured. + if inputs.gpg_ssh_enabled { + for p in &inputs.gpg_sockets { + if is_live(p) { + push_unique(p); + } + } + } + // 5) Fallback to launchd's Listeners socket from env or launchctl. + for p in [inputs.env_sock.as_deref(), inputs.launchctl_sock.as_deref()].into_iter().flatten() { + if is_live(p) { + push_unique(p); + } + } + out +} + +#[cfg(test)] +fn resolve_ssh_auth_sock( + inputs: &SshAuthInputs, + is_live: impl Fn(&std::path::Path) -> bool, +) -> Option { + resolve_ssh_auth_sock_candidates(inputs, is_live).into_iter().next() +} + +fn gather_ssh_auth_inputs(include_preferred: bool) -> SshAuthInputs { + let preferred = if include_preferred { + PREFERRED_SSH_AUTH_SOCK.lock().unwrap_or_else(|e| e.into_inner()).clone() + } else { + None + }; + let env_sock = std::env::var_os("SSH_AUTH_SOCK") + .filter(|v| !v.is_empty()) + .map(std::path::PathBuf::from); + if !cfg!(target_os = "macos") { + return SshAuthInputs { + preferred: None, + env_sock, + launchctl_sock: None, + gpg_ssh_enabled: false, + gpg_sockets: Vec::new(), + }; + } + let launchctl_sock = launchctl_getenv("SSH_AUTH_SOCK"); + let home = std::env::var_os("HOME") + .filter(|v| !v.is_empty()) + .map(std::path::PathBuf::from); + let gnupg_home = std::env::var_os("GNUPGHOME") + .filter(|v| !v.is_empty()) + .map(std::path::PathBuf::from) + .or_else(|| launchctl_getenv("GNUPGHOME")); + let (gpg_ssh_enabled, gpg_sockets) = gather_gpg_ssh_info( + gnupg_home.as_deref(), + home.as_deref(), + gpgconf_agent_ssh_socket, + ); + SshAuthInputs { + preferred, + env_sock, + launchctl_sock, + gpg_ssh_enabled, + gpg_sockets, + } +} + +fn ssh_auth_sock_candidates_for(include_preferred: bool) -> Vec { + let inputs = gather_ssh_auth_inputs(include_preferred); + if cfg!(target_os = "macos") { + resolve_ssh_auth_sock_candidates(&inputs, is_owned_unix_socket) + } else { + // On Linux the daemon may run as root while $SSH_AUTH_SOCK belongs + // to a non-root user, so keep the existing env behavior. + inputs.env_sock.into_iter().collect() + } +} + +/// The host's discovered SSH agent socket, ignoring any previously recorded +/// bind-mount preference (so bind-mount validation cannot bootstrap itself). +pub(crate) fn default_ssh_auth_sock() -> Option { + ssh_auth_sock_candidates_for(false).into_iter().next() +} + +/// Whether `canon` (already canonicalized) matches the daemon's discovered +/// host SSH agent socket (`default_ssh_auth_sock()`). +pub(crate) fn matches_default_ssh_auth_sock(canon: &std::path::Path) -> bool { + let Some(default) = default_ssh_auth_sock() else { return false }; + let default_canon = std::fs::canonicalize(&default).unwrap_or(default); + canon == default_canon +} + +fn set_preferred_ssh_auth_sock_inner(path: &std::path::Path, strict: bool) -> bool { + let Ok(canon) = std::fs::canonicalize(path) else { + return false; + }; + if !is_owned_unix_socket(&canon) || is_kiri_socket_path(&canon) { + return false; + } + let allowed = if strict { + let home = std::env::var_os("HOME") + .filter(|v| !v.is_empty()) + .map(std::path::PathBuf::from); + let gnupg_home = std::env::var_os("GNUPGHOME") + .filter(|v| !v.is_empty()) + .map(std::path::PathBuf::from) + .or_else(|| launchctl_getenv("GNUPGHOME")); + let gpgconf_sock = canon + .file_name() + .is_some_and(|n| n == "S.gpg-agent.ssh") + .then(|| gpgconf_agent_ssh_socket(gnupg_home.as_deref())) + .flatten(); + is_strict_mac_ssh_agent_sock_path_for(&canon, home.as_deref(), gnupg_home.as_deref(), gpgconf_sock.as_deref()) + || matches_default_ssh_auth_sock(&canon) + } else { + is_known_mac_ssh_agent_sock_path(&canon) || matches_default_ssh_auth_sock(&canon) + }; + if !allowed { + return false; + } + *PREFERRED_SSH_AUTH_SOCK.lock().unwrap_or_else(|e| e.into_inner()) = Some(canon); + true +} + +/// Records an explicitly bind-mounted Mac SSH agent socket (from a host +/// caller) as the preferred upstream for `serve_ssh_agent`, after verifying +/// canonical path, Unix socket type, current-UID ownership, allowlist, and +/// that it is never Kiri's own daemon socket. +pub(crate) fn set_preferred_ssh_auth_sock(path: &std::path::Path) -> bool { + set_preferred_ssh_auth_sock_inner(path, false) +} + +/// Strict variant used on container start (when caller identity is no longer +/// present): only records sockets under the user's own GPG/1Password/launchd +/// locations or matching `default_ssh_auth_sock()`. +pub(crate) fn set_preferred_ssh_auth_sock_strict(path: &std::path::Path) -> bool { + set_preferred_ssh_auth_sock_inner(path, true) +} + +#[cfg(test)] +pub(crate) static PREFERRED_SSH_TEST_LOCK: Mutex<()> = Mutex::new(()); + +#[cfg(test)] +pub(crate) fn current_preferred_ssh_auth_sock() -> Option { + PREFERRED_SSH_AUTH_SOCK.lock().unwrap_or_else(|e| e.into_inner()).clone() +} + +#[cfg(test)] +pub(crate) fn clear_preferred_ssh_auth_sock() { + *PREFERRED_SSH_AUTH_SOCK.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +/// One container connection to the SSH agent, relayed to the Mac's agent. +pub fn serve_ssh_agent(stream: kiri_vmm::VsockStream) { + let _ = std::thread::Builder::new().name("kiri-ssh-agent".into()).spawn(move || { + let Some(agent) = ssh_auth_sock_candidates_for(true) + .into_iter() + .find_map(|path| std::os::unix::net::UnixStream::connect(path).ok()) + else { + return; + }; + let (Ok(mut agent_read), Ok(from_guest), Ok(to_guest)) = (agent.try_clone(), stream.fd.try_clone(), stream.fd.try_clone()) else { + return; + }; + let mut from_guest = std::fs::File::from(from_guest); + let mut to_guest = std::fs::File::from(to_guest); + let mut agent_write = agent; + let down = std::thread::spawn(move || { + let _ = copy(&mut agent_read, &mut to_guest); + // SAFETY: half-closing a socket we own. + unsafe { libc::shutdown(to_guest.as_raw_fd(), libc::SHUT_WR) }; + }); + let _ = copy(&mut from_guest, &mut agent_write); + let _ = agent_write.shutdown(Shutdown::Write); + let _ = down.join(); + drop(stream); + }); +} + +/// vsock port the guest dials for the engine's API: containers that mount +/// the docker socket (crates/kiri/src/daemon/binds.rs). +pub const ENGINE_API_PORT: u32 = 1036; + +/// One container connection to the engine's API, served like any other +/// client's, marked as a container's. +pub fn serve_engine_api(stream: kiri_vmm::VsockStream, engine: std::sync::Weak) { + let Some(permit) = super::try_acquire_container_conn() else { + drop(stream); + return; + }; + let _ = std::thread::Builder::new().name("kiri-engine-api".into()).spawn(move || { + let _permit = permit; + // Served here rather than through the daemon's socket, so the API + // knows these requests are a container's (caller.rs). + let Some(engine) = engine.upgrade() else { return }; + let _ = relay_engine_api(&stream.fd, move |ours| { + let _ = super::api::serve(ours, engine, super::caller::Caller::Container); + }); + drop(stream); + }); +} + +fn set_nonblocking_cloexec(fd: std::os::fd::RawFd) -> io::Result<()> { + // SAFETY: fcntl on a descriptor we own. + if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } != 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: F_GETFL takes no extra args on a descriptor we own. + let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) }; + if flags < 0 { + return Err(io::Error::last_os_error()); + } + if flags & libc::O_NONBLOCK == 0 { + // SAFETY: F_SETFL with O_NONBLOCK on a descriptor we own. + if unsafe { libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } != 0 { + return Err(io::Error::last_os_error()); + } + } + #[cfg(target_os = "macos")] + { + let one: libc::c_int = 1; + // SAFETY: best-effort SO_NOSIGPIPE on a descriptor we own. + unsafe { libc::setsockopt(fd, libc::SOL_SOCKET, libc::SO_NOSIGPIPE, (&one as *const libc::c_int).cast(), std::mem::size_of::() as libc::socklen_t) }; + } + Ok(()) +} + +fn shutdown_fd(fd: std::os::fd::RawFd, how: libc::c_int) { + // SAFETY: caller owns or keeps `fd` alive for the duration of the relay. + unsafe { libc::shutdown(fd, how) }; +} + +/// Non-blocking drain into `buf` up to `cap`; returns `Ok(true)` on EOF. +fn drain_nonblock(fd: std::os::fd::RawFd, buf: &mut VecDeque, cap: usize, tmp: &mut [u8]) -> io::Result { + while buf.len() < cap { + let want = (cap - buf.len()).min(tmp.len()); + // SAFETY: `tmp` has at least `want` writable bytes and `fd` is open. + let n = unsafe { libc::read(fd, tmp.as_mut_ptr().cast(), want) }; + if n > 0 { + buf.extend(&tmp[..n as usize]); + } else if n == 0 { + return Ok(true); + } else { + let e = io::Error::last_os_error(); + match e.raw_os_error() { + Some(libc::EINTR) => continue, + Some(c) if c == libc::EAGAIN || c == libc::EWOULDBLOCK => return Ok(false), + _ => return Err(e), + } + } + } + Ok(false) +} + +/// Non-blocking flush from `buf` (`<= chunk_cap` per write); returns bytes written. +fn flush_nonblock(fd: std::os::fd::RawFd, buf: &mut VecDeque, chunk_cap: usize) -> io::Result { + let mut wrote = 0; + while !buf.is_empty() { + let (head, _) = buf.as_slices(); + if head.is_empty() { + buf.make_contiguous(); + continue; + } + let want = head.len().min(chunk_cap); + // SAFETY: `head` has at least `want` readable bytes and `fd` is open. + let n = unsafe { libc::write(fd, head.as_ptr().cast(), want) }; + if n > 0 { + let n = n as usize; + buf.drain(..n); + wrote += n; + } else if n == 0 { + return Err(io::Error::from(io::ErrorKind::WriteZero)); + } else { + let e = io::Error::last_os_error(); + match e.raw_os_error() { + Some(libc::EINTR) => continue, + Some(c) if c == libc::EAGAIN || c == libc::EWOULDBLOCK => break, + _ => return Err(e), + } + } + } + Ok(wrote) +} + +/// Relays one guest engine-API stream to `serve` over a local `UnixStream` +/// pair using a single-thread `O_NONBLOCK` `poll()` state machine (no `dup()` +/// of `VZVirtioSocketConnection`, bounded 64 KiB buffers each way). Once +/// `serve` exits (after `HEADER_TIMEOUT`, `Connection: close`, 400, 403, 413, +/// or EOF) and any buffered response drains (or stalls past `TCP_STALL`), +/// both directions of `guest` are shut down (`SHUT_RDWR`) so a half-open +/// guest connection can never leave a relay blocked or pin a container permit. +fn relay_engine_api( + guest: &OwnedFd, + serve: impl FnOnce(std::os::unix::net::UnixStream) + Send + 'static, +) -> io::Result<()> { + relay_engine_api_with(guest, TCP_STALL, serve) +} + +fn relay_engine_api_with( + guest: &OwnedFd, + stall: Duration, + serve: impl FnOnce(std::os::unix::net::UnixStream) + Send + 'static, +) -> io::Result<()> { + struct DoneSignal { + ours: std::os::unix::net::UnixStream, + _done_w: OwnedFd, + } + impl Drop for DoneSignal { + fn drop(&mut self) { + let _ = self.ours.shutdown(Shutdown::Write); + } + } + + const CAP: usize = 64 * 1024; + let guest_fd = guest.as_raw_fd(); + set_nonblocking_cloexec(guest_fd)?; + let (api, ours) = std::os::unix::net::UnixStream::pair()?; + let api_fd = api.as_raw_fd(); + set_nonblocking_cloexec(api_fd)?; + let (done_r, done_w) = pipe()?; + set_nonblocking_cloexec(done_r.as_raw_fd())?; + let signal = DoneSignal { + ours: ours.try_clone()?, + _done_w: done_w, + }; + let served = match std::thread::Builder::new().name("kiri-api".into()).spawn(move || { + let _signal = signal; + serve(ours); + }) { + Ok(t) => t, + Err(e) => { + shutdown_fd(guest_fd, libc::SHUT_RDWR); + return Err(e); + } + }; + + let mut g2a: VecDeque = VecDeque::with_capacity(CAP); + let mut a2g: VecDeque = VecDeque::with_capacity(CAP); + let mut g_eof = false; + let mut a_eof = false; + let mut g_shut_wr = false; + let mut a_shut_wr = false; + let mut a_write_closed = false; + let mut done_closed = false; + let mut a2g_stall: Option = None; + let mut tmp = [0u8; 32 * 1024]; + + loop { + if a_eof && a2g.is_empty() && done_closed { + break; + } + if !a2g.is_empty() + && let Some(since) = a2g_stall + && since.elapsed() >= stall + { + break; + } + + let mut g_ev: libc::c_short = 0; + if !g_eof && !a_write_closed && g2a.len() < CAP { + g_ev |= libc::POLLIN; + } + if !a2g.is_empty() { + g_ev |= libc::POLLOUT; + } + + let mut a_ev: libc::c_short = 0; + if !a_eof && a2g.len() < CAP { + a_ev |= libc::POLLIN; + } + if !g2a.is_empty() && !a_write_closed { + a_ev |= libc::POLLOUT; + } + + let timeout_ms: libc::c_int = if !a2g.is_empty() + && let Some(since) = a2g_stall + { + let rem = stall.saturating_sub(since.elapsed()); + if rem.is_zero() { + break; + } + rem.as_millis().clamp(1, 5_000) as libc::c_int + } else { + -1 + }; + + let mut fds = [ + libc::pollfd { + fd: if g_ev != 0 { guest_fd } else { -1 }, + events: g_ev, + revents: 0, + }, + libc::pollfd { + fd: if a_ev != 0 { api_fd } else { -1 }, + events: a_ev, + revents: 0, + }, + libc::pollfd { + fd: if done_closed { -1 } else { done_r.as_raw_fd() }, + events: libc::POLLIN, + revents: 0, + }, + ]; + // SAFETY: polling descriptors we own (or -1 to skip). + let n = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::nfds_t, timeout_ms) }; + if n < 0 { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::Interrupted { + continue; + } + break; + } + + if fds[2].revents != 0 { + let mut b = [0u8; 16]; + // SAFETY: draining `done_r` we own to observe pipe closure. + let r = unsafe { libc::read(done_r.as_raw_fd(), b.as_mut_ptr().cast(), b.len()) }; + if r == 0 || (fds[2].revents & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0) { + done_closed = true; + } + } + + let mut guest_dead = false; + let mut pushed_g2a = false; + let mut pushed_a2g = false; + + if !g_eof && !a_write_closed && g2a.len() < CAP && fds[0].revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { + let before = g2a.len(); + match drain_nonblock(guest_fd, &mut g2a, CAP, &mut tmp) { + Ok(eof) => { + g_eof = eof; + pushed_g2a = g2a.len() > before; + } + Err(_) => guest_dead = true, + } + } + + if !a_eof && a2g.len() < CAP && fds[1].revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { + let before = a2g.len(); + match drain_nonblock(api_fd, &mut a2g, CAP, &mut tmp) { + Ok(eof) => { + a_eof = eof; + pushed_a2g = a2g.len() > before; + } + Err(_) => a_eof = true, + } + } + + if !g2a.is_empty() && !a_write_closed && (pushed_g2a || fds[1].revents & (libc::POLLOUT | libc::POLLHUP | libc::POLLERR) != 0) { + if flush_nonblock(api_fd, &mut g2a, CAP).is_err() { + a_write_closed = true; + g2a.clear(); + } + } + + if !guest_dead && !a2g.is_empty() && (pushed_a2g || fds[0].revents & (libc::POLLOUT | libc::POLLHUP | libc::POLLERR) != 0) { + match flush_nonblock(guest_fd, &mut a2g, CAP) { + Ok(wrote) => { + if a2g.is_empty() { + a2g_stall = None; + } else if wrote > 0 || a2g_stall.is_none() { + a2g_stall = Some(Instant::now()); + } + } + Err(_) => guest_dead = true, + } + } + + if guest_dead { + break; + } + + if g_eof && g2a.is_empty() && !a_shut_wr && !a_write_closed { + shutdown_fd(api_fd, libc::SHUT_WR); + a_shut_wr = true; + } + if a_eof && a2g.is_empty() && !g_shut_wr { + shutdown_fd(guest_fd, libc::SHUT_WR); + g_shut_wr = true; + } + } + + // Close `api` before joining `served`: on macOS XNU, `shutdown(SHUT_RDWR)` + // alone does not wake a peer thread blocked writing to `ours`; closing `api` + // wakes both blocked reads and blocked writes on `ours` immediately. + drop(api); + shutdown_fd(guest_fd, libc::SHUT_RDWR); + let _ = served.join(); + Ok(()) +} + +/// The TCP ports in a container's `/proc/net/tcp` and `tcp6` lines that are +/// listening: those a published port reaches, then those it does not. The +/// relay dials the container's IPv4 address, so a socket bound to loopback +/// alone, or to one IPv6 address, is out of its reach; with host networking +/// it dials 127.0.0.1, so loopback is in reach there. Each port once, sorted. +pub fn listening>(lines: &[S], host_network: bool) -> (Vec, Vec) { + use std::collections::BTreeSet; + use std::net::{Ipv4Addr, Ipv6Addr}; + let v4_reach = |ip: Ipv4Addr| !ip.is_loopback() || host_network; let (mut reach, mut local) = (BTreeSet::new(), BTreeSet::new()); for line in lines { let f: Vec<&str> = line.as_ref().split_whitespace().collect(); @@ -1121,7 +3520,7 @@ pub fn listening>(lines: &[S], host_network: bool) -> (Vec, V #[cfg(test)] mod tests { - use super::{MAX_PEER_SESSIONS, MAX_REMOTE_SESSIONS, MAX_TCP_SESSIONS, NAT_PORTS, REMOTE_SESSIONS, TCP_SESSIONS, host_bound_allowed, kernel_forwards, kernel_host_ip, listening, nat_port, relays_too, tcp_permit}; + use super::{MAX_PEER_SESSIONS, MAX_REMOTE_SESSIONS, MAX_TCP_SESSIONS, NAT_PORTS, REMOTE_SESSIONS, TCP_SESSIONS, dial_loopback, host_bound_allowed, kernel_forwards, kernel_host_ip, listening, nat_port, relays_too, tcp_permit}; use std::net::IpAddr; use std::sync::atomic::Ordering; @@ -1138,6 +3537,19 @@ mod tests { assert!(!host_bound_allowed(std::net::Ipv4Addr::new(10, 0, 0, 1), 5432, router), "loopback only"); } + /// A Mac server on `::1` only (Node's `localhost`) is reached; one on + /// both loopbacks is reached on 127.0.0.1, as before (#258). + #[test] + fn host_docker_internal_reaches_a_server_on_either_loopback() { + let v6 = std::net::TcpListener::bind("[::1]:0").unwrap(); + let port = v6.local_addr().unwrap().port(); + assert_eq!(dial_loopback(port).unwrap().peer_addr().unwrap().ip(), IpAddr::from(std::net::Ipv6Addr::LOCALHOST)); + let v4 = std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(); + assert_eq!(dial_loopback(port).unwrap().peer_addr().unwrap().ip(), IpAddr::from(std::net::Ipv4Addr::LOCALHOST)); + drop((v4, v6)); + assert_eq!(dial_loopback(port).unwrap_err().kind(), std::io::ErrorKind::ConnectionRefused); + } + /// A clash names the other program holding the port, never Kiri itself. #[test] fn a_taken_port_names_the_program_that_has_it() { @@ -1321,6 +3733,12 @@ mod tests { assert_eq!(out, b"HTTP/1"); } + #[test] + fn loopback_ports_are_the_ones_on_the_macs_loopback() { + let bound = [(80, "0.0.0.0", 8080), (80, "::", 8080), (81, "", 8081), (5000, "127.0.0.1", 5999), (5000, "127.0.0.1", 5999), (443, "192.168.1.5", 8443), (53, "::1", 5353)]; + assert_eq!(super::loopback_ports(bound.into_iter()), vec![(80, 8080), (81, 8081), (5000, 5999)]); + } + #[test] fn nat_ports_are_the_lowest_free_and_released() { let a = nat_port().expect("free port"); @@ -1334,4 +3752,1254 @@ mod tests { let c = nat_port().expect("free port"); assert_eq!(c.0, freed); } + + #[test] + fn host_egress_dialer_rejects_ssrf_and_allows_vpn_and_public_targets() { + use super::egress_allowed; + use std::net::Ipv4Addr; + let extra = [([192, 168, 105, 0], 24)]; + // Loopback, unspecified, link-local (cloud metadata), multicast, broadcast, + // host.docker.internal, port 0, and the VM NAT bridge subnets are rejected. + for bad in [ + Ipv4Addr::new(127, 0, 0, 1), + Ipv4Addr::new(127, 0, 0, 53), + Ipv4Addr::new(127, 255, 255, 254), + Ipv4Addr::new(0, 0, 0, 0), + Ipv4Addr::new(0, 1, 2, 3), + Ipv4Addr::new(169, 254, 169, 254), + Ipv4Addr::new(169, 254, 0, 1), + Ipv4Addr::new(224, 0, 0, 1), + Ipv4Addr::new(239, 255, 255, 250), + Ipv4Addr::new(240, 0, 0, 1), + Ipv4Addr::new(255, 255, 255, 255), + Ipv4Addr::new(198, 19, 248, 254), + Ipv4Addr::new(192, 168, 64, 1), + Ipv4Addr::new(192, 168, 64, 18), + Ipv4Addr::new(192, 168, 105, 1), + ] { + assert!(!egress_allowed(bad, 443, &extra), "{bad} must be rejected"); + } + assert!(!egress_allowed(Ipv4Addr::new(10, 0, 5, 10), 0, &extra), "port 0 must be rejected"); + + // Split-tunnel VPN RFC1918 targets, Tailscale CGNAT, NetworkExtension + // Fake-IP (198.18.0.0/15), and public internet targets are allowed. + for ok in [ + Ipv4Addr::new(10, 0, 5, 10), + Ipv4Addr::new(172, 16, 4, 20), + Ipv4Addr::new(192, 168, 1, 50), + Ipv4Addr::new(100, 64, 1, 2), + Ipv4Addr::new(198, 18, 2, 3), + Ipv4Addr::new(35, 190, 46, 17), + Ipv4Addr::new(1, 1, 1, 1), + ] { + assert!(egress_allowed(ok, 443, &extra), "{ok} must be allowed"); + } + } + + #[test] + fn host_egress_dialer_rejects_the_learned_vm_subnet() { + use std::net::Ipv4Addr; + // macOS picked another NAT bridge subnet than the default one. + let inside = Ipv4Addr::new(192, 168, 205, 7); + let gateway = Ipv4Addr::new(192, 168, 205, 1); + let outside = Ipv4Addr::new(192, 168, 206, 7); + assert!(super::egress_target_allowed(inside, 443), "not learned yet"); + super::set_vm_subnet(gateway.octets(), super::VM_UPLINK_PREFIX); + super::set_vm_subnet(gateway.octets(), super::VM_UPLINK_PREFIX); + assert_eq!(super::current_vm_subnets().iter().filter(|&&s| s == ([192, 168, 205, 0], 24)).count(), 1); + assert!(!super::egress_target_allowed(inside, 443), "{inside} is in the VM's NAT subnet"); + assert!(!super::egress_target_allowed(gateway, 443), "{gateway} is the Mac's side of the NAT"); + assert!(super::egress_target_allowed(outside, 443), "{outside} is outside it"); + } + + /// Builds a BSD `rt_msghdr` (92 bytes) followed by `RTA_DST`, optional + /// `RTA_GATEWAY`, and optional truncated `RTA_NETMASK` sockaddrs, matching + /// macOS `sysctl([CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0])`. + fn bsd_rtm(ifindex: u16, flags: i32, dst: [u8; 4], mask: Option<&[u8]>) -> Vec { + let mut msg = vec![0u8; 92]; + msg[2] = 5; // RTM_VERSION + msg[3] = 4; // RTM_GET + msg[4..6].copy_from_slice(&ifindex.to_ne_bytes()); + msg[8..12].copy_from_slice(&flags.to_ne_bytes()); + let mut addrs: i32 = 0x1 | 0x2; // RTA_DST | RTA_GATEWAY + if mask.is_some() { + addrs |= 0x4; // RTA_NETMASK + } + msg[12..16].copy_from_slice(&addrs.to_ne_bytes()); + // RTA_DST: sockaddr_in (16 bytes) + let mut sa_dst = [0u8; 16]; + sa_dst[0] = 16; + sa_dst[1] = libc::AF_INET as u8; + sa_dst[4..8].copy_from_slice(&dst); + msg.extend_from_slice(&sa_dst); + // RTA_GATEWAY: sockaddr_in (16 bytes) + let mut sa_gw = [0u8; 16]; + sa_gw[0] = 16; + sa_gw[1] = libc::AF_INET as u8; + sa_gw[4..8].copy_from_slice(&[192, 168, 1, 1]); + msg.extend_from_slice(&sa_gw); + // RTA_NETMASK: BSD radix-tree variable-length sockaddr + if let Some(m) = mask { + if m.is_empty() { + // sa_len = 0 (/0 default route mask) occupies 4 rounded bytes. + msg.extend_from_slice(&[0, 0, 0, 0]); + } else { + let sa_len = (4 + m.len()) as u8; + let padded = ((sa_len as usize) + 3) & !3; + let mut sa_mask = vec![0u8; padded]; + sa_mask[0] = sa_len; + sa_mask[1] = libc::AF_INET as u8; + sa_mask[4..4 + m.len()].copy_from_slice(m); + msg.extend_from_slice(&sa_mask); + } + } + let msglen = msg.len() as u16; + msg[0..2].copy_from_slice(&msglen.to_ne_bytes()); + msg + } + + #[test] + fn macos_net_rt_dump_extracts_vpn_tunnel_prefixes_and_skips_ifscope_and_cloned() { + const RTF_UP: i32 = 0x1; + const RTF_GATEWAY: i32 = 0x2; + const RTF_HOST: i32 = 0x4; + const RTF_LLINFO: i32 = 0x400; + const RTF_STATIC: i32 = 0x800; + const RTF_WASCLONED: i32 = 0x20000; + const RTF_IFSCOPE: i32 = 0x1000000; + + let mut dump = Vec::new(); + // Primary default route on en0 (index 1): 0.0.0.0/0 + dump.extend_from_slice(&bsd_rtm(1, RTF_UP | RTF_GATEWAY | RTF_STATIC, [0, 0, 0, 0], Some(&[]))); + // Interface-scoped default route on utun4 (index 2): must be ignored! + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_IFSCOPE, [0, 0, 0, 0], Some(&[]))); + // OpenVPN split-tunnel route 10.0.5.0/24 on utun4 (index 2), truncated 3-byte radix mask + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_STATIC, [10, 0, 5, 0], Some(&[255, 255, 255]))); + // Redundant /32 host route inside 10.0.5.0/24 on utun4: collapsed into 10.0.5.0/24 + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_HOST, [10, 0, 5, 10], None)); + // Corporate /16 route on ipsec0 (index 3), truncated 2-byte radix mask + dump.extend_from_slice(&bsd_rtm(3, RTF_UP | RTF_STATIC, [172, 20, 0, 0], Some(&[255, 255]))); + // Tailscale CGNAT 100.64.0.0/10 on utun5 (index 4), truncated 2-byte radix mask + dump.extend_from_slice(&bsd_rtm(4, RTF_UP | RTF_STATIC, [100, 64, 0, 0], Some(&[255, 192]))); + // Multicast 224.0.0.0/4 and loopback on utun4: must be ignored + dump.extend_from_slice(&bsd_rtm(2, RTF_UP, [224, 0, 0, 0], Some(&[240]))); + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_HOST, [127, 0, 0, 1], None)); + // Cloned ARP entry on utun4 and regular LAN route on en0: must be ignored + dump.extend_from_slice(&bsd_rtm(2, RTF_UP | RTF_WASCLONED | RTF_LLINFO, [10, 99, 0, 1], None)); + dump.extend_from_slice(&bsd_rtm(1, RTF_UP, [192, 168, 1, 0], Some(&[255, 255, 255]))); + + let ifname = |idx: u16| match idx { + 1 => Some("en0".into()), + 2 => Some("utun4".into()), + 3 => Some("ipsec0".into()), + 4 => Some("utun5".into()), + _ => None, + }; + let routes = super::parse_macos_routes(&dump, ifname); + assert_eq!( + routes, + vec![ + ([100, 64, 0, 0], 10), + ([172, 20, 0, 0], 16), + ([10, 0, 5, 0], 24), + ] + ); + } + + #[test] + fn system_extensions_plist_detects_active_security_extensions_and_ignores_inactive_or_tailscale() { + let active_kaspersky_and_forticlient = br#" + + + + extensions + + + bundleVersion + + CFBundleShortVersionString + 26.0.0 + + categories + + com.apple.system_extension.network_extension + + identifier + com.kaspersky.kav.sysext + state + activated_enabled + + + categories + + com.apple.developer.networking.networkextension + + identifier + com.fortinet.forticlient.macos.vpn.nwextension + state + terminated_waiting_to_uninstall_on_reboot + + + +"#; + assert!(super::has_active_network_extension(active_kaspersky_and_forticlient)); + + let deactivated_or_tailscale = br#" + + + extensions + + + categories + + com.apple.developer.networking.networkextension + + identifier + com.fortinet.forticlient.macos.vpn.nwextension + state + terminated_waiting_to_uninstall_on_reboot + + + categories + + com.apple.system_extension.network_extension + + identifier + io.tailscale.ipn.macsys.network-extension + state + activated_enabled + + + categories + + com.apple.system_extension.endpoint_security + + identifier + com.example.edr.esext + state + activated_enabled + + + +"#; + assert!(!super::has_active_network_extension(deactivated_or_tailscale)); + + assert_eq!( + super::host_egress_routes_for(Some("auto"), false, &[([10, 0, 5, 0], 24)], true), + vec!["198.18.0.0/15", "10.0.5.0/24"] + ); + assert_eq!( + super::host_egress_routes_for(Some("auto"), true, &[([10, 0, 5, 0], 24)], true), + vec!["0.0.0.0/0"] + ); + assert_eq!( + super::host_egress_routes_for(Some("always"), false, &[], false), + vec!["0.0.0.0/0"] + ); + assert!(super::host_egress_routes_for(Some("off"), true, &[([10, 0, 5, 0], 24)], true).is_empty()); + assert_eq!( + super::host_egress_routes_for(Some("10.254.99.0/24"), false, &[], false), + vec!["10.254.99.0/24"] + ); + } + + #[test] + fn ipconfig_parser_extracts_windows_interface_ips_and_excludes_gateways_and_masks() { + let sample = "\ +Windows IP Configuration\r\n\ +\r\n\ +Ethernet adapter vEthernet (WSL):\r\n\ +\r\n\ + Connection-specific DNS Suffix . : \r\n\ + Link-local IPv6 Address . . . . . : fe80::1234:5678:9abc:def0%42\r\n\ + IPv4 Address. . . . . . . . . . . : 198.51.100.1\r\n\ + Subnet Mask . . . . . . . . . . . : 255.255.240.0\r\n\ + Default Gateway . . . . . . . . . : \r\n\ +\r\n\ +Wireless LAN adapter Wi-Fi:\r\n\ +\r\n\ + Connection-specific DNS Suffix . : lan\r\n\ + IPv6 Address. . . . . . . . . . . : 2001:db8::42(Preferred)\r\n\ + Link-local IPv6 Address . . . . . : fe80::abcd:ef01:2345:6789%18\r\n\ + IPv4 Address. . . . . . . . . . . : 192.0.2.50(Preferred)\r\n\ + Subnet Mask . . . . . . . . . . . : 255.255.255.0\r\n\ + Default Gateway . . . . . . . . . : fe80::1%18\r\n\ + 192.0.2.1\r\n"; + let ips = super::parse_ipconfig_addrs(sample); + assert!(ips.contains(&"127.0.0.1".parse().unwrap())); + assert!(ips.contains(&"::1".parse().unwrap())); + assert!(ips.contains(&"198.51.100.1".parse().unwrap())); + assert!(ips.contains(&"192.0.2.50".parse().unwrap())); + assert!(ips.contains(&"2001:db8::42".parse().unwrap())); + // Subnet masks, default gateways, and arbitrary bogus IPs must not match. + assert!(!ips.contains(&"255.255.255.0".parse().unwrap())); + assert!(!ips.contains(&"255.255.240.0".parse().unwrap())); + assert!(!ips.contains(&"192.0.2.1".parse().unwrap())); + assert!(!ips.contains(&"fe80::1".parse().unwrap())); + assert!(!ips.contains(&"203.0.113.99".parse().unwrap())); + } + + #[test] + fn engine_api_relay_tears_down_half_open_guest_and_releases_permit() { + use std::io::{BufReader, Read, Write}; + use std::os::fd::OwnedFd; + use std::os::unix::net::UnixStream; + use std::time::{Duration, Instant}; + + let cap = super::super::ConnCap::for_test(1); + + // 1. Idle guest that never sends and never closes: when `api::serve` + // exits after HEADER_TIMEOUT, both directions shut down promptly and + // the container permit is released. + { + let permit = cap.try_acquire_for_test().unwrap(); + let (mut guest_client, guest_server) = UnixStream::pair().unwrap(); + guest_client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let guest_fd = OwnedFd::from(guest_server); + let t0 = Instant::now(); + let t = std::thread::spawn(move || { + let _permit = permit; + super::relay_engine_api(&guest_fd, |ours| { + let mut r = BufReader::new(ours); + let _ = super::super::http::read_request_with_timeout(&mut r, Duration::from_millis(60), |_, _| false); + }) + .unwrap(); + }); + // Keep `guest_client` open (half-open) until the relay finishes. + let mut reply = Vec::new(); + guest_client.read_to_end(&mut reply).unwrap(); + t.join().unwrap(); + assert!(reply.is_empty()); + assert!(t0.elapsed() < Duration::from_secs(2), "idle relay hung for {:?}", t0.elapsed()); + assert_eq!(cap.open(), 0, "container permit must be released after timeout"); + drop(guest_client); + } + + // 2. Guest sends a request that ends the connection (403 / Next::Close) + // and keeps its write side open: guest still receives the full 403 + // response, and the relay exits promptly without pinning the permit. + { + let permit = cap.try_acquire_for_test().unwrap(); + let (mut guest_client, guest_server) = UnixStream::pair().unwrap(); + guest_client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let guest_fd = OwnedFd::from(guest_server); + let t0 = Instant::now(); + let t = std::thread::spawn(move || { + let _permit = permit; + super::relay_engine_api(&guest_fd, |ours| { + let mut w = ours.try_clone().unwrap(); + let mut r = BufReader::new(ours); + let req = super::super::http::read_request_with_timeout(&mut r, Duration::from_secs(2), |_, _| false) + .unwrap() + .unwrap(); + super::super::http::serving(&req); + super::super::http::error(&mut w, 403, "forbidden").unwrap(); + }) + .unwrap(); + }); + guest_client.write_all(b"POST /kiri/stop HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + // Intentionally do NOT shut down guest_client's write half. + let mut reply = Vec::new(); + guest_client.read_to_end(&mut reply).unwrap(); + t.join().unwrap(); + let text = String::from_utf8_lossy(&reply); + assert!(text.starts_with("HTTP/1.1 403 Forbidden\r\n"), "{text}"); + assert!(text.contains("forbidden"), "{text}"); + assert!(t0.elapsed() < Duration::from_secs(2), "403 relay hung for {:?}", t0.elapsed()); + assert_eq!(cap.open(), 0, "container permit must be released after 403"); + drop(guest_client); + } + + // 3. Guest sends a 413 Too Large request with `http::close` linger while + // keeping its write side open: guest receives the full 413 response + // and the relay finishes after linger instead of hanging forever. + { + let permit = cap.try_acquire_for_test().unwrap(); + let (mut guest_client, guest_server) = UnixStream::pair().unwrap(); + guest_client.set_read_timeout(Some(Duration::from_secs(3))).unwrap(); + let guest_fd = OwnedFd::from(guest_server); + let t0 = Instant::now(); + let t = std::thread::spawn(move || { + let _permit = permit; + super::relay_engine_api(&guest_fd, |ours| { + let mut w = ours.try_clone().unwrap(); + let mut r = BufReader::new(ours); + let req = super::super::http::read_request_with_timeout(&mut r, Duration::from_secs(2), |_, _| false) + .unwrap() + .unwrap(); + assert!(req.too_large()); + let _ = super::super::http::refuse_too_large(&req, &mut w, &mut r); + }) + .unwrap(); + }); + guest_client + .write_all(b"POST /containers/create HTTP/1.1\r\nHost: d\r\nContent-Length: 100000000\r\n\r\n") + .unwrap(); + // Intentionally do NOT close guest_client's write half. + let mut reply = Vec::new(); + guest_client.read_to_end(&mut reply).unwrap(); + t.join().unwrap(); + let text = String::from_utf8_lossy(&reply); + assert!(text.starts_with("HTTP/1.1 413 Request Entity Too Large\r\n"), "{text}"); + assert!(t0.elapsed() < Duration::from_secs(3), "413 relay hung for {:?}", t0.elapsed()); + assert_eq!(cap.open(), 0, "container permit must be released after 413"); + drop(guest_client); + } + + // 4. Normal guest half-close (`SHUT_WR` after sending request) still + // receives the full HTTP response cleanly. + { + let permit = cap.try_acquire_for_test().unwrap(); + let (mut guest_client, guest_server) = UnixStream::pair().unwrap(); + guest_client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + let guest_fd = OwnedFd::from(guest_server); + let t = std::thread::spawn(move || { + let _permit = permit; + super::relay_engine_api(&guest_fd, |ours| { + let mut w = ours.try_clone().unwrap(); + let mut r = BufReader::new(ours); + let req = super::super::http::read_request_with_timeout(&mut r, Duration::from_secs(2), |_, _| false) + .unwrap() + .unwrap(); + super::super::http::serving(&req); + super::super::http::respond(&mut w, 200, "text/plain", b"OK").unwrap(); + assert!(super::super::http::read_request_with_timeout(&mut r, Duration::from_secs(2), |_, _| false).unwrap().is_none()); + }) + .unwrap(); + }); + guest_client.write_all(b"GET /_ping HTTP/1.1\r\nHost: d\r\n\r\n").unwrap(); + guest_client.shutdown(std::net::Shutdown::Write).unwrap(); + let mut reply = Vec::new(); + guest_client.read_to_end(&mut reply).unwrap(); + t.join().unwrap(); + let text = String::from_utf8_lossy(&reply); + assert!(text.starts_with("HTTP/1.1 200 OK\r\n") && text.ends_with("\r\n\r\nOK"), "{text}"); + assert_eq!(cap.open(), 0); + } + } + + #[test] + fn ssh_auth_sock_resolution_prefers_gpg_over_launchd_and_honors_explicit_overrides() { + use std::path::{Path, PathBuf}; + let p = PathBuf::from; + let launchd_tmp = p("/private/tmp/com.apple.launchd.abc123/Listeners"); + let launchd_var = p("/var/run/com.apple.launchd.xyz789/Listeners"); + let gpg = p("/Users/alice/.gnupg/S.gpg-agent.ssh"); + let onepass = p("/Users/alice/.1password/agent.sock"); + let custom = p("/Users/alice/.ssh/custom-agent.sock"); + let all_live = |_: &Path| true; + + // 1) GPG with enable-ssh-support wins over launchd Listeners (both /private/tmp and /var/run forms). + for launchd in [&launchd_tmp, &launchd_var] { + let inputs = super::SshAuthInputs { + preferred: None, + env_sock: Some(launchd.clone()), + launchctl_sock: Some(launchd.clone()), + gpg_ssh_enabled: true, + gpg_sockets: vec![gpg.clone()], + }; + assert_eq!(super::resolve_ssh_auth_sock(&inputs, all_live), Some(gpg.clone()), "{launchd:?}"); + // Launchd remains as fallback candidate behind GPG if GPG's socket is stale. + assert_eq!(super::resolve_ssh_auth_sock_candidates(&inputs, all_live), vec![gpg.clone(), launchd.clone()]); + } + + // 2) Without enable-ssh-support, launchd stays selected even if S.gpg-agent.ssh exists. + let disabled_gpg = super::SshAuthInputs { + preferred: None, + env_sock: Some(launchd_tmp.clone()), + launchctl_sock: Some(launchd_tmp.clone()), + gpg_ssh_enabled: false, + gpg_sockets: vec![gpg.clone()], + }; + assert_eq!(super::resolve_ssh_auth_sock(&disabled_gpg, all_live), Some(launchd_tmp.clone())); + + // 3) Explicit non-launchd `launchctl getenv SSH_AUTH_SOCK` wins over launchd env and GPG. + let launchctl_override = super::SshAuthInputs { + preferred: None, + env_sock: Some(launchd_var.clone()), + launchctl_sock: Some(onepass.clone()), + gpg_ssh_enabled: true, + gpg_sockets: vec![gpg.clone()], + }; + assert_eq!(super::resolve_ssh_auth_sock(&launchctl_override, all_live), Some(onepass.clone())); + + // 4) Explicit non-launchd process env `$SSH_AUTH_SOCK` wins over launchctl and GPG. + let env_override = super::SshAuthInputs { + preferred: None, + env_sock: Some(custom.clone()), + launchctl_sock: Some(onepass.clone()), + gpg_ssh_enabled: true, + gpg_sockets: vec![gpg.clone()], + }; + assert_eq!(super::resolve_ssh_auth_sock(&env_override, all_live), Some(custom.clone())); + + // 5) Recorded bind-mount `preferred` wins over everything when live, + // and falls through cleanly when missing/dead. + let with_preferred = super::SshAuthInputs { + preferred: Some(gpg.clone()), + env_sock: Some(custom.clone()), + launchctl_sock: Some(onepass.clone()), + gpg_ssh_enabled: true, + gpg_sockets: vec![gpg.clone()], + }; + assert_eq!(super::resolve_ssh_auth_sock(&with_preferred, all_live), Some(gpg.clone())); + assert_eq!( + super::resolve_ssh_auth_sock(&with_preferred, |cand| cand != gpg.as_path()), + Some(custom.clone()) + ); + + // 6) Dead explicit env_sock falls through to live GPG socket. + let dead_env = super::SshAuthInputs { + preferred: None, + env_sock: Some(custom.clone()), + launchctl_sock: Some(launchd_tmp.clone()), + gpg_ssh_enabled: true, + gpg_sockets: vec![gpg.clone()], + }; + assert_eq!( + super::resolve_ssh_auth_sock(&dead_env, |cand| cand != custom.as_path()), + Some(gpg) + ); + } + + #[test] + fn gpg_agent_conf_parsing_and_socket_discovery() { + use std::path::PathBuf; + assert!(super::gpg_agent_ssh_enabled("enable-ssh-support\n")); + assert!(super::gpg_agent_ssh_enabled(" enable-ssh-support # for git\n")); + assert!(super::gpg_agent_ssh_enabled("default-cache-ttl 600\nenable-ssh-support\n")); + assert!(!super::gpg_agent_ssh_enabled("# enable-ssh-support\n")); + assert!(!super::gpg_agent_ssh_enabled("#enable-ssh-support\n")); + assert!(!super::gpg_agent_ssh_enabled(" # enable-ssh-support\n")); + assert!(!super::gpg_agent_ssh_enabled("enable-ssh-support-extra\n")); + assert!(!super::gpg_agent_ssh_enabled("enable-ssh-support\nno-enable-ssh-support\n")); + assert!(!super::gpg_agent_ssh_enabled("")); + + let root = std::env::temp_dir().join(format!("kiri-gpg-conf-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let home = root.join("home"); + let custom_gnupg = root.join("custom-gnupg"); + std::fs::create_dir_all(home.join(".gnupg")).unwrap(); + std::fs::create_dir_all(&custom_gnupg).unwrap(); + + // Commented-out enable-ssh-support does NOT enable GPG discovery or run gpgconf. + std::fs::write(home.join(".gnupg/gpg-agent.conf"), "# enable-ssh-support\n").unwrap(); + let (enabled, socks) = super::gather_gpg_ssh_info(None, Some(&home), |_| panic!("gpgconf must not be called when disabled")); + assert!(!enabled); + assert!(socks.is_empty()); + + // Uncommented enable-ssh-support under ~/.gnupg discovers gpgconf socket then ~/.gnupg/S.gpg-agent.ssh. + std::fs::write(home.join(".gnupg/gpg-agent.conf"), "default-cache-ttl 300\nenable-ssh-support # on\n").unwrap(); + let gpgconf_path = PathBuf::from("/private/var/folders/aa/bb/T/gnupg/S.gpg-agent.ssh"); + let (enabled, socks) = super::gather_gpg_ssh_info(None, Some(&home), |_| Some(gpgconf_path.clone())); + assert!(enabled); + assert_eq!(socks, vec![gpgconf_path.clone(), home.join(".gnupg/S.gpg-agent.ssh")]); + + // Custom GNUPGHOME takes precedence over ~/.gnupg and orders $GNUPGHOME -> gpgconf -> ~/.gnupg. + std::fs::write(custom_gnupg.join("gpg-agent.conf"), "enable-ssh-support\n").unwrap(); + let (enabled, socks) = super::gather_gpg_ssh_info(Some(&custom_gnupg), Some(&home), |dir| { + assert_eq!(dir, Some(custom_gnupg.as_path())); + Some(gpgconf_path.clone()) + }); + assert!(enabled); + assert_eq!(socks, vec![custom_gnupg.join("S.gpg-agent.ssh"), gpgconf_path, home.join(".gnupg/S.gpg-agent.ssh")]); + + // Custom GNUPGHOME without enable-ssh-support does NOT silently inherit ~/.gnupg/gpg-agent.conf. + std::fs::write(custom_gnupg.join("gpg-agent.conf"), "# enable-ssh-support\n").unwrap(); + let (enabled, socks) = super::gather_gpg_ssh_info(Some(&custom_gnupg), Some(&home), |_| panic!("should not run gpgconf")); + assert!(!enabled); + assert!(socks.is_empty()); + + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn mac_ssh_agent_socket_allowlist_and_preferred_security() { + use std::os::unix::net::UnixListener; + use std::path::Path; + + // Launchd detection covers both /tmp and /var/run (+ /private/*) layouts. + for ok in [ + "/private/tmp/com.apple.launchd.abc123/Listeners", + "/tmp/com.apple.launchd.abc123/Listeners", + "/private/var/run/com.apple.launchd.oQTvCAtcQS/Listeners", + "/var/run/com.apple.launchd.oQTvCAtcQS/Listeners", + "/var/run//com.apple.launchd.abc/Listeners", + ] { + assert!(super::is_launchd_ssh_sock(Path::new(ok)), "{ok}"); + assert!(super::is_known_mac_ssh_agent_sock_path(Path::new(ok)), "{ok}"); + } + for bad in [ + "/tmp/com.apple.launchd./Listeners", + "/tmp/com.apple.launchd.abc/sub/Listeners", + "/Users/alice/com.apple.launchd.abc/Listeners", + "/var/run/docker.sock", + "tmp/com.apple.launchd.abc/Listeners", + ] { + assert!(!super::is_launchd_ssh_sock(Path::new(bad)), "{bad}"); + } + + // Known Mac agent socket paths vs rejected non-SSH paths. + for ok in [ + "/Users/alice/.gnupg/S.gpg-agent.ssh", + "/Users/alice/.config/gnupg/S.gpg-agent.ssh", + "/Users/alice/.1password/agent.sock", + "/Users/alice/Library/Group Containers/2BUA8C4S2C.com.1password/t/agent.sock", + ] { + assert!(super::is_known_mac_ssh_agent_sock_path(Path::new(ok)), "{ok}"); + } + for bad in [ + "/Users/alice/.kiri/run/docker.sock", + "/var/run/docker.sock", + "/tmp/postgres.sock", + "/etc/S.gpg-agent.ssh", + "/Users/alice/S.gpg-agent", + ] { + assert!(!super::is_known_mac_ssh_agent_sock_path(Path::new(bad)), "{bad}"); + } + + // Strict path allowlist only permits user's own GPG/1Password/launchd paths. + let fake_home = Path::new("/Users/alice"); + let fake_gnupg = Path::new("/Users/alice/.config/gnupg"); + let fake_gpgconf = Path::new("/private/var/folders/aa/bb/T/d.1234/S.gpg-agent.ssh"); + assert!(super::is_strict_mac_ssh_agent_sock_path_for(Path::new("/Users/alice/.gnupg/S.gpg-agent.ssh"), Some(fake_home), None, None)); + assert!(super::is_strict_mac_ssh_agent_sock_path_for(Path::new("/Users/alice/.config/gnupg/S.gpg-agent.ssh"), Some(fake_home), Some(fake_gnupg), None)); + assert!(super::is_strict_mac_ssh_agent_sock_path_for(fake_gpgconf, Some(fake_home), None, Some(fake_gpgconf))); + assert!(super::is_strict_mac_ssh_agent_sock_path_for(Path::new("/Users/alice/.1password/agent.sock"), Some(fake_home), None, None)); + assert!(!super::is_strict_mac_ssh_agent_sock_path_for(Path::new("/tmp/untrusted/S.gpg-agent.ssh"), Some(fake_home), None, None)); + assert!(!super::is_strict_mac_ssh_agent_sock_path_for(Path::new("/Users/alice/.kiri/run/docker.sock"), Some(fake_home), None, None)); + + // Live Unix socket security checks for set_preferred_ssh_auth_sock. + let _guard = super::PREFERRED_SSH_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + super::clear_preferred_ssh_auth_sock(); + + let dir = std::env::temp_dir().join(format!("kiri-ssh-pref-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Regular file named S.gpg-agent.ssh is rejected (not a socket). + let reg = dir.join("reg"); + std::fs::create_dir_all(®).unwrap(); + let reg_file = reg.join("S.gpg-agent.ssh"); + std::fs::write(®_file, b"not a socket").unwrap(); + assert!(!super::set_preferred_ssh_auth_sock(®_file)); + assert!(super::current_preferred_ssh_auth_sock().is_none()); + + // Arbitrary socket named docker.sock is rejected, AND a symlink named + // S.gpg-agent.ssh pointing to docker.sock is ALSO rejected after canonicalize. + let docker_sock = dir.join("docker.sock"); + let _docker_listener = UnixListener::bind(&docker_sock).unwrap(); + assert!(!super::set_preferred_ssh_auth_sock(&docker_sock)); + let evil_link_dir = dir.join("evil"); + std::fs::create_dir_all(&evil_link_dir).unwrap(); + let evil_link = evil_link_dir.join("S.gpg-agent.ssh"); + std::os::unix::fs::symlink(&docker_sock, &evil_link).unwrap(); + assert!(!super::set_preferred_ssh_auth_sock(&evil_link), "symlink to docker.sock must be rejected"); + assert!(super::current_preferred_ssh_auth_sock().is_none()); + + // A real owned S.gpg-agent.ssh Unix socket is accepted by set_preferred_ssh_auth_sock + // (for host callers), while set_preferred_ssh_auth_sock_strict rejects temp paths + // outside ~/.gnupg / $GNUPGHOME / gpgconf. + let gpg_sock = dir.join("S.gpg-agent.ssh"); + let _gpg_listener = UnixListener::bind(&gpg_sock).unwrap(); + assert!(!super::set_preferred_ssh_auth_sock_strict(&gpg_sock)); + assert!(super::current_preferred_ssh_auth_sock().is_none()); + assert!(super::set_preferred_ssh_auth_sock(&gpg_sock)); + assert_eq!(super::current_preferred_ssh_auth_sock(), Some(std::fs::canonicalize(&gpg_sock).unwrap())); + + super::clear_preferred_ssh_auth_sock(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn macos_low_loopback_fallback_and_step_aside() { + use std::io; + use std::net::SocketAddr; + + let eacces = || io::Error::from(io::ErrorKind::PermissionDenied); + let eaddrinuse = || io::Error::from(io::ErrorKind::AddrInUse); + + // 1. macOS 127.0.0.1:80 EACCES -> falls back to 0.0.0.0:80 with loopback_only = true. + let mut tried = Vec::new(); + let (bound, lo_only) = super::bind_with_macos_low_loopback_with( + "127.0.0.1:80".parse().unwrap(), + 80, + false, + true, + |a, udp| { + tried.push((a, udp)); + if a == "127.0.0.1:80".parse::().unwrap() { Err(eacces()) } else { Ok(a) } + }, + |_| panic!("should not step aside when wildcard is free"), + ) + .unwrap(); + assert_eq!(bound, "0.0.0.0:80".parse().unwrap()); + assert!(lo_only); + assert_eq!(tried, vec![("127.0.0.1:80".parse().unwrap(), false), ("0.0.0.0:80".parse().unwrap(), false)]); + + // 2. macOS 127.0.0.1:80 EACCES, then 0.0.0.0:80 EADDRINUSE (domain router) -> + // steps router aside and retries 0.0.0.0:80 cleanly. + let mut stepped = Vec::new(); + let mut wildcard_attempts = 0usize; + let (bound, lo_only) = super::bind_with_macos_low_loopback_with( + "127.0.0.1:80".parse().unwrap(), + 80, + false, + true, + |a, _| { + if a.ip().is_loopback() { + Err(eacces()) + } else { + wildcard_attempts += 1; + if wildcard_attempts == 1 { Err(eaddrinuse()) } else { Ok(a) } + } + }, + |p| { + stepped.push(p); + true + }, + ) + .unwrap(); + assert_eq!(bound, "0.0.0.0:80".parse().unwrap()); + assert!(lo_only); + assert_eq!(stepped, vec![80]); + assert_eq!(wildcard_attempts, 2); + + // 3. macOS [::1]:443 EACCES -> falls back to [::]:443 with loopback_only = true. + let (bound, lo_only) = super::bind_with_macos_low_loopback_with( + "[::1]:443".parse().unwrap(), + 443, + false, + true, + |a, _| if a.ip().is_loopback() { Err(eacces()) } else { Ok(a) }, + |_| false, + ) + .unwrap(); + assert_eq!(bound, "[::]:443".parse().unwrap()); + assert!(lo_only); + + // 4. macOS 127.0.0.1:53 UDP EACCES -> falls back to 0.0.0.0:53 UDP. + let (bound, lo_only) = super::bind_with_macos_low_loopback_with( + "127.0.0.1:53".parse().unwrap(), + 53, + true, + true, + |a, udp| { + assert!(udp); + if a.ip().is_loopback() { Err(eacces()) } else { Ok(a) } + }, + |_| panic!("UDP must never step aside TCP domain router"), + ) + .unwrap(); + assert_eq!(bound, "0.0.0.0:53".parse().unwrap()); + assert!(lo_only); + + // 5. High port (>= 1024), non-loopback IP, port 0, and non-macOS do NOT fall back. + for (addr, port, is_macos) in [ + ("127.0.0.1:1024", 1024, true), + ("127.0.0.1:8080", 8080, true), + ("127.0.0.1:0", 0, true), + ("192.168.1.5:80", 80, true), + ("127.0.0.1:80", 80, false), + ] { + let mut calls = 0usize; + let err = super::bind_with_macos_low_loopback_with( + addr.parse().unwrap(), + port, + false, + is_macos, + |_, _| { + calls += 1; + Err::(eacces()) + }, + |_| false, + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::PermissionDenied, "{addr} mac={is_macos}"); + assert_eq!(calls, 1, "must not retry wildcard for {addr} mac={is_macos}"); + } + + // 6. Direct bind succeeding keeps loopback_only = false. + let (bound, lo_only) = super::bind_with_macos_low_loopback_with( + "127.0.0.1:81".parse().unwrap(), + 81, + false, + true, + |a, _| Ok(a), + |_| false, + ) + .unwrap(); + assert_eq!(bound, "127.0.0.1:81".parse().unwrap()); + assert!(!lo_only); + } + + #[test] + fn peer_allowed_enforces_loopback_only_when_fallback_active() { + for lo in ["127.0.0.1", "127.0.0.2", "::1", "::ffff:127.0.0.1", "::ffff:127.0.0.2"] { + let ip: IpAddr = lo.parse().unwrap(); + assert!(super::peer_allowed(ip, true), "loopback {lo} must be allowed"); + assert!(super::peer_allowed(ip, false), "loopback {lo} must be allowed without filter"); + } + for remote in ["192.168.1.10", "10.0.0.5", "0.0.0.0", "2001:db8::1", "fe80::1", "::", "::ffff:192.168.1.10", "::ffff:10.0.0.1"] { + let ip: IpAddr = remote.parse().unwrap(); + assert!(!super::peer_allowed(ip, true), "non-loopback {remote} must be rejected under loopback_only"); + assert!(super::peer_allowed(ip, false), "non-loopback {remote} must be allowed when not loopback_only"); + } + } + + #[test] + fn shared_nat_disabled_forces_full_host_egress_and_tracks_state() { + use super::super::engine::{parse_bool_env, shared_nat_for}; + + for t in ["1", "on", "ON", "true", "True", "yes", " yes "] { + assert_eq!(parse_bool_env(t), Some(true), "{t}"); + } + for f in ["0", "off", "OFF", "false", "False", "no", " no "] { + assert_eq!(parse_bool_env(f), Some(false), "{f}"); + } + for bad in ["", "maybe", "2", "auto"] { + assert_eq!(parse_bool_env(bad), None, "{bad}"); + } + + // Env overrides vm.json, vm.json overrides default (true), invalid env falls back. + assert!(shared_nat_for(None, None)); + assert!(!shared_nat_for(None, Some(false))); + assert!(shared_nat_for(None, Some(true))); + assert!(!shared_nat_for(Some("0"), Some(true))); + assert!(shared_nat_for(Some("on"), Some(false))); + assert!(!shared_nat_for(Some("bogus"), Some(false))); + assert!(shared_nat_for(Some("bogus"), None)); + + // When shared_nat is false on macOS, auto mode routes all IPv4 TCP through host egress. + assert_eq!( + super::host_egress_routes_with_nat(None, false, false, &[], true), + vec!["0.0.0.0/0"] + ); + assert_eq!( + super::host_egress_routes_with_nat(Some("auto"), false, false, &[([10, 0, 5, 0], 24)], true), + vec!["0.0.0.0/0"] + ); + assert_eq!( + super::host_egress_routes_with_nat(Some("auto"), true, false, &[([10, 0, 5, 0], 24)], true), + vec!["198.18.0.0/15", "10.0.5.0/24"] + ); + assert!(super::host_egress_routes_with_nat(Some("off"), false, false, &[], true).is_empty()); + assert!(super::host_egress_routes_with_nat(None, false, false, &[], false).is_empty()); + + super::set_shared_nat_active(Some(false)); + assert!(!super::shared_nat_active()); + super::set_shared_nat_active(Some(true)); + assert!(super::shared_nat_active()); + super::set_shared_nat_active(None); + } + + #[test] + fn engine_api_relay_bidirectional_saturation_never_deadlocks_and_releases_permit() { + use std::io::{Read, Write}; + use std::os::fd::{AsRawFd, OwnedFd}; + use std::os::unix::net::UnixStream; + use std::time::{Duration, Instant}; + + const UP_BYTES: usize = 4 << 20; + const DOWN_BYTES: usize = 16 << 20; + + let shrink_bufs = |fd: std::os::fd::RawFd| { + let small: libc::c_int = 4096; + for opt in [libc::SO_SNDBUF, libc::SO_RCVBUF] { + // SAFETY: shrinking socket buffer on a descriptor we own for saturation testing. + unsafe { libc::setsockopt(fd, libc::SOL_SOCKET, opt, (&small as *const libc::c_int).cast(), std::mem::size_of::() as libc::socklen_t) }; + } + }; + + let cap = super::super::ConnCap::for_test(1); + let permit = cap.try_acquire_for_test().unwrap(); + let (mut guest_client_r, guest_server) = UnixStream::pair().unwrap(); + shrink_bufs(guest_client_r.as_raw_fd()); + shrink_bufs(guest_server.as_raw_fd()); + guest_client_r.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); + guest_client_r.set_write_timeout(Some(Duration::from_secs(10))).unwrap(); + let mut guest_client_w = guest_client_r.try_clone().unwrap(); + + let guest_fd = OwnedFd::from(guest_server); + let t0 = Instant::now(); + let relay = std::thread::spawn(move || { + let _permit = permit; + super::relay_engine_api(&guest_fd, move |mut ours_w| { + shrink_bufs(ours_w.as_raw_fd()); + let mut ours_r = ours_w.try_clone().unwrap(); + let reader = std::thread::spawn(move || { + let mut buf = vec![0u8; 32 * 1024]; + let mut got = 0usize; + loop { + let n = ours_r.read(&mut buf).unwrap(); + if n == 0 { + break; + } + for &b in &buf[..n] { + assert_eq!(b, ((got % 251) as u8), "upload byte mismatch at {got}"); + got += 1; + } + } + assert_eq!(got, UP_BYTES); + }); + let down_chunk: Vec = (0..(64 * 1024)).map(|i| ((i * 7) % 253) as u8).collect(); + let mut sent = 0usize; + while sent < DOWN_BYTES { + let take = (DOWN_BYTES - sent).min(down_chunk.len()); + ours_w.write_all(&down_chunk[..take]).unwrap(); + sent += take; + } + let _ = ours_w.shutdown(std::net::Shutdown::Write); + reader.join().unwrap(); + }) + .unwrap(); + }); + + let uploader = std::thread::spawn(move || { + let mut chunk = vec![0u8; 32 * 1024]; + let mut sent = 0usize; + while sent < UP_BYTES { + let take = (UP_BYTES - sent).min(chunk.len()); + for (i, b) in chunk[..take].iter_mut().enumerate() { + *b = ((sent + i) % 251) as u8; + } + guest_client_w.write_all(&chunk[..take]).unwrap(); + sent += take; + } + guest_client_w.shutdown(std::net::Shutdown::Write).unwrap(); + }); + + let mut buf = vec![0u8; 32 * 1024]; + let mut got_down = 0usize; + loop { + let n = guest_client_r.read(&mut buf).unwrap(); + if n == 0 { + break; + } + for &b in &buf[..n] { + let expected = (((got_down % (64 * 1024)) * 7) % 253) as u8; + assert_eq!(b, expected, "download byte mismatch at {got_down}"); + got_down += 1; + } + } + assert_eq!(got_down, DOWN_BYTES); + uploader.join().unwrap(); + relay.join().unwrap(); + assert!(t0.elapsed() < Duration::from_secs(10), "bidirectional saturation took {:?}", t0.elapsed()); + assert_eq!(cap.open(), 0, "container permit must be released after bidirectional saturation"); + } + + #[test] + fn engine_api_relay_tears_down_stalled_half_open_guest() { + use std::io::Write; + use std::os::fd::OwnedFd; + use std::os::unix::net::UnixStream; + use std::time::{Duration, Instant}; + + let cap = super::super::ConnCap::for_test(1); + let permit = cap.try_acquire_for_test().unwrap(); + let (guest_client, guest_server) = UnixStream::pair().unwrap(); + let guest_fd = OwnedFd::from(guest_server); + let t0 = Instant::now(); + let t = std::thread::spawn(move || { + let _permit = permit; + super::relay_engine_api_with(&guest_fd, Duration::from_millis(80), |mut ours| { + // Flood past socket + 64 KiB relay buffers while guest never reads. + let payload = vec![0x41u8; 512 * 1024]; + for _ in 0..8 { + if ours.write_all(&payload).is_err() { + break; + } + } + }) + .unwrap(); + }); + t.join().unwrap(); + assert!(t0.elapsed() < Duration::from_secs(2), "stalled guest relay hung for {:?}", t0.elapsed()); + assert_eq!(cap.open(), 0, "container permit must be released after stall teardown"); + drop(guest_client); + } + + #[test] + fn netstat_holder_fallback_and_port53_bind_guidance() { + use std::io; + + let udp_netstat = "\ +Proto Recv-Q Send-Q Local Address Foreign Address (state) rhiwat shiwat process:pid state\n\ +udp4 0 0 *.5353 *.* 786896 9216 mDNSResponder:111 0x0000\n\ +udp4 0 0 *.53 *.* 786896 9216 kiri-daemon:222 0x0000\n\ +udp4 0 0 192.168.64.1.53 *.* 786896 9216 mDNSResponder:333 0x0000\n"; + assert_eq!(super::holder_in_netstat(udp_netstat, 53, true, 999, |_| None).as_deref(), Some("mDNSResponder")); + assert_eq!(super::holder_in_netstat(udp_netstat, 53, true, 333, |_| None), None, "skips self pid and kiri*"); + + let tcp_netstat = "\ +Proto Recv-Q Send-Q Local Address Foreign Address (state) rhiwat shiwat pid epid state\n\ +tcp4 0 0 127.0.0.1.53 127.0.0.1.51234 ESTABLISHED 131072 131072 444 0 0x0102\n\ +tcp4 0 0 *.53 *.* LISTEN 131072 131072 555 0 0x0100\n"; + assert_eq!( + super::holder_in_netstat(tcp_netstat, 53, false, 999, |pid| (pid == 555).then(|| "mDNSResponder".to_owned())).as_deref(), + Some("mDNSResponder") + ); + + let e_in_use = || io::Error::from(io::ErrorKind::AddrInUse); + let msg_shared = super::format_bind_error(e_in_use(), "0.0.0.0", "0.0.0.0", 53, None, true, true).to_string(); + assert!(msg_shared.contains("kiri vm set --shared-nat off"), "{msg_shared}"); + assert!(msg_shared.contains("/etc/resolver/"), "{msg_shared}"); + + let msg_mdns = super::format_bind_error(e_in_use(), "127.0.0.1", "127.0.0.1", 53, Some("mDNSResponder"), true, false).to_string(); + assert!(msg_mdns.contains("(in use by mDNSResponder)"), "{msg_mdns}"); + assert!(msg_mdns.contains("kiri vm set --shared-nat off"), "{msg_mdns}"); + + let msg_other = super::format_bind_error(e_in_use(), "127.0.0.1", "127.0.0.1", 53, Some("dnsmasq"), true, false).to_string(); + assert!(msg_other.contains("(in use by dnsmasq)"), "{msg_other}"); + assert!(!msg_other.contains("--shared-nat off"), "{msg_other}"); + + let msg_linux = super::format_bind_error(e_in_use(), "0.0.0.0", "0.0.0.0", 53, None, false, true).to_string(); + assert!(!msg_linux.contains("--shared-nat off"), "{msg_linux}"); + + let e_notavail = || io::Error::from_raw_os_error(libc::EADDRNOTAVAIL); + let msg_alias = super::format_bind_error(e_notavail(), "127.0.0.53", "127.0.0.53", 53, None, true, false).to_string(); + assert!(msg_alias.contains("sudo ifconfig lo0 alias 127.0.0.53"), "{msg_alias}"); + assert!(msg_alias.contains("127.0.0.1"), "{msg_alias}"); + + let err_plain = super::format_bind_error(e_notavail(), "192.168.1.99", "192.168.1.99", 53, None, true, false); + assert_eq!(err_plain.raw_os_error(), Some(libc::EADDRNOTAVAIL)); + } + + #[test] + fn macos_loopback_only_udp_binds_lo0_interface_and_uses_short_dns_idle() { + use std::time::Duration; + + assert_eq!(super::udp_idle_timeout(53, 53), Duration::from_secs(10)); + assert_eq!(super::udp_idle_timeout(53, 8053), Duration::from_secs(10)); + assert_eq!(super::udp_idle_timeout(5353, 53), Duration::from_secs(10)); + assert_eq!(super::udp_idle_timeout(8080, 80), Duration::from_secs(60)); + + assert!(super::binds_host_dns_port(&[(super::Binding { host_ip: String::new(), host_port: 53, container_port: 53, proto: "udp".into() }, "0.0.0.0".into(), 53)])); + assert!(super::binds_host_dns_port(&[(super::Binding { host_ip: "127.0.0.1".into(), host_port: 53, container_port: 53, proto: "udp".into() }, "127.0.0.1".into(), 53)])); + assert!(super::binds_host_dns_port(&[(super::Binding { host_ip: "::1".into(), host_port: 53, container_port: 53, proto: "udp".into() }, "::1".into(), 53)])); + assert!(!super::binds_host_dns_port(&[(super::Binding { host_ip: "192.168.1.5".into(), host_port: 53, container_port: 53, proto: "udp".into() }, "192.168.1.5".into(), 53)])); + assert!(!super::binds_host_dns_port(&[(super::Binding { host_ip: "127.0.0.1".into(), host_port: 5353, container_port: 53, proto: "udp".into() }, "127.0.0.1".into(), 5353)])); + + let before = super::HOST_PORT_53_BINDS.load(Ordering::Relaxed); + let guard = super::HostPort53Guard::acquire(); + assert!(super::host_port_53_published()); + assert_eq!(super::HOST_PORT_53_BINDS.load(Ordering::Relaxed), before + 1); + drop(guard); + assert_eq!(super::HOST_PORT_53_BINDS.load(Ordering::Relaxed), before); + + #[cfg(target_os = "macos")] + { + use std::net::UdpSocket; + use std::os::fd::AsRawFd; + + let lo0 = unsafe { libc::if_nametoindex(c"lo0".as_ptr()) }; + assert_ne!(lo0, 0); + + let bound_if = |fd: std::os::fd::RawFd, is_v6: bool| -> libc::c_uint { + let mut val: libc::c_uint = 0; + let mut len = std::mem::size_of::() as libc::socklen_t; + let (lvl, opt) = if is_v6 { (libc::IPPROTO_IPV6, libc::IPV6_BOUND_IF) } else { (libc::IPPROTO_IP, libc::IP_BOUND_IF) }; + // SAFETY: reading an int socket option from a descriptor we own. + assert_eq!(unsafe { libc::getsockopt(fd, lvl, opt, (&mut val as *mut libc::c_uint).cast(), &mut len) }, 0); + val + }; + + let fd_lo = super::bind_socket_on_if("0.0.0.0:0".parse().unwrap(), true, true).unwrap(); + assert_eq!(bound_if(fd_lo.as_raw_fd(), false), lo0); + drop(fd_lo); + + let fd_any = super::bind_socket_on_if("0.0.0.0:0".parse().unwrap(), true, false).unwrap(); + assert_eq!(bound_if(fd_any.as_raw_fd(), false), 0); + drop(fd_any); + + if let Ok(fd_v6) = super::bind_socket_on_if("[::]:0".parse().unwrap(), true, true) { + assert_eq!(bound_if(fd_v6.as_raw_fd(), true), lo0); + } + + // Calling `udp_loop_with` with `loopback_only = true` also enforces `IP_BOUND_IF = lo0`, + // serves loopback peers, and reaps idle DNS sessions after `idle`. + let sock = UdpSocket::bind("0.0.0.0:0").unwrap(); + sock.set_nonblocking(true).unwrap(); + let port = sock.local_addr().unwrap().port(); + assert_eq!(bound_if(sock.as_raw_fd(), false), 0); + let (wake_r, wake_w) = super::pipe().unwrap(); + let sock_ref = sock.try_clone().unwrap(); + let (closed_tx, closed_rx) = std::sync::mpsc::channel::<()>(); + let t = std::thread::spawn(move || { + super::udp_loop_with(&sock_ref, &wake_r, true, Duration::from_millis(120), |s, peer| { + use std::os::unix::net::UnixStream; + let (a, b) = UnixStream::pair()?; + let to_guest = std::fs::File::from(std::os::fd::OwnedFd::from(a)); + let mut from_guest = std::fs::File::from(std::os::fd::OwnedFd::from(b)); + let reply = s.try_clone()?; + let closed_tx = closed_tx.clone(); + let reader = std::thread::spawn(move || { + use std::io::Read as _; + let mut len = [0u8; 2]; + let mut data = vec![0u8; 65_536]; + while from_guest.read_exact(&mut len).is_ok() { + let n = u16::from_be_bytes(len) as usize; + if from_guest.read_exact(&mut data[..n]).is_err() { + break; + } + let _ = reply.send_to(&data[..n], peer); + } + let _ = closed_tx.send(()); + }); + Ok(super::UdpSession { + to_guest, + last: std::time::Instant::now(), + reader, + _guest: None, + }) + }); + }); + let deadline = std::time::Instant::now() + Duration::from_secs(2); + while bound_if(sock.as_raw_fd(), false) != lo0 && std::time::Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(bound_if(sock.as_raw_fd(), false), lo0); + let client = UdpSocket::bind("127.0.0.1:0").unwrap(); + client.set_read_timeout(Some(Duration::from_secs(2))).unwrap(); + client.send_to(b"dns-q", ("127.0.0.1", port)).unwrap(); + let mut reply_buf = [0u8; 16]; + let (rn, _) = client.recv_from(&mut reply_buf).unwrap(); + assert_eq!(&reply_buf[..rn], b"dns-q"); + closed_rx.recv_timeout(Duration::from_secs(2)).expect("idle DNS UDP session should be reaped"); + drop(wake_w); + t.join().unwrap(); + } + } + + #[test] + fn linux_host_publish_falls_back_to_user_space_relay_when_forwarding_blocked() { + use super::{Binding, publish_key, publish_linux_host}; + use std::io; + + let tcp_entry = |host_ip: &str, host_port: u16, container_port: u16, tag: &'static str| { + let b = Binding { container_port, proto: "tcp".into(), host_ip: host_ip.into(), host_port }; + (b, Some(host_ip.to_owned()), host_ip.to_owned(), host_port, false, tag) + }; + let udp_entry = |host_ip: &str, host_port: u16, container_port: u16, tag: &'static str| { + let b = Binding { container_port, proto: "udp".into(), host_ip: host_ip.into(), host_port }; + (b, Some(host_ip.to_owned()), host_ip.to_owned(), host_port, false, tag) + }; + + // 1. Open forwarding: wildcard stays relayed (for loopback) + published, + // specific LAN IP moves to kernel-only, loopback & IPv6 stay relayed only. + let mut published = Vec::new(); + let mut unpublished = Vec::new(); + let open = publish_linux_host( + "cid:1", + [172, 17, 0, 2], + vec![ + tcp_entry("0.0.0.0", 8080, 80, "tcp-any"), + tcp_entry("192.168.1.5", 8443, 443, "tcp-lan"), + tcp_entry("127.0.0.1", 9000, 90, "tcp-lo"), + tcp_entry("::", 8080, 80, "tcp-v6"), + ], + vec![ + udp_entry("0.0.0.0", 5353, 53, "udp-any"), + udp_entry("192.168.1.5", 5354, 54, "udp-lan"), + ], + |p| { + published.push((p.id.to_owned(), p.udp, p.host_ip, p.host_port, p.to_ip, p.to_port)); + Ok(()) + }, + |id| unpublished.push(id.to_owned()), + ); + assert!(open.fallback_error.is_none()); + assert!(open.any_published); + assert!(unpublished.is_empty()); + assert_eq!(published.len(), 4, "only non-loopback IPv4 bindings are DNATed"); + assert!(published.iter().all(|(id, ..)| id == "cid:1")); + assert_eq!(open.kernel_tcp, vec!["tcp-lan"]); + assert_eq!(open.kernel_udp, vec!["udp-lan"]); + assert_eq!(open.relay_tcp.iter().map(|t| t.5).collect::>(), vec!["tcp-any", "tcp-lo", "tcp-v6"]); + assert_eq!(open.relay_udp.iter().map(|u| u.5).collect::>(), vec!["udp-any"]); + assert_eq!(open.kernel_bound.len(), 2); + + // 2. Host firewall blocks kernel FORWARD (#649): agent rejects publish, + // unpublish rolls back, and EVERY socket (including specific LAN IP) + // stays in user-space relay lists (`relay_direct` / `udp_loop`). + let mut unpublished = Vec::new(); + let blocked = publish_linux_host( + "cid:2", + [172, 17, 0, 2], + vec![ + tcp_entry("0.0.0.0", 8080, 80, "tcp-any"), + tcp_entry("192.168.1.5", 8443, 443, "tcp-lan"), + tcp_entry("127.0.0.1", 9000, 90, "tcp-lo"), + ], + vec![udp_entry("192.168.1.5", 5354, 54, "udp-lan")], + |_| Err(io::Error::other("kernel forwarding is blocked by host firewall")), + |id| unpublished.push(id.to_owned()), + ); + assert!(blocked.fallback_error.is_some()); + assert!(!blocked.any_published); + assert_eq!(unpublished, vec!["cid:2"]); + assert!(blocked.kernel_tcp.is_empty()); + assert!(blocked.kernel_udp.is_empty()); + assert!(blocked.kernel_bound.is_empty()); + assert_eq!(blocked.relay_tcp.iter().map(|t| t.5).collect::>(), vec!["tcp-any", "tcp-lan", "tcp-lo"]); + assert_eq!(blocked.relay_udp.iter().map(|u| u.5).collect::>(), vec!["udp-lan"]); + + // 3. Partial multi-binding failure rolls back the first publish too. + let mut calls = 0usize; + let mut unpublished = Vec::new(); + let partial = publish_linux_host( + "cid:3", + [172, 17, 0, 2], + vec![tcp_entry("0.0.0.0", 8080, 80, "tcp-1"), tcp_entry("192.168.1.5", 8443, 443, "tcp-2")], + Vec::<(Binding, Option, String, u16, bool, &'static str)>::new(), + |_| { + calls += 1; + if calls == 1 { Ok(()) } else { Err(io::Error::other("nftables error")) } + }, + |id| unpublished.push(id.to_owned()), + ); + assert!(partial.fallback_error.is_some()); + assert_eq!(unpublished, vec!["cid:3"]); + assert_eq!(partial.relay_tcp.iter().map(|t| t.5).collect::>(), vec!["tcp-1", "tcp-2"]); + + // 4. Restarting the same container gets a distinct publish key so a stale + // `Unpublish` can never wipe the restarted container's DNAT rules. + let k1 = publish_key("same-container"); + let k2 = publish_key("same-container"); + assert_ne!(k1, k2); + assert!(k1.starts_with("same-container:") && k2.starts_with("same-container:")); + } + + #[test] + fn enterprise_packet_tunnel_and_ifscope_vpn_routes_trigger_host_egress() { + use super::{ActiveTunnel, collapse_cidrs, has_active_network_extension, parse_macos_routes_with_tunnels}; + + // 1. OpenVPN `def1` sibling halves `0.0.0.0/1` + `128.0.0.0/1` collapse to `0.0.0.0/0`. + assert_eq!(collapse_cidrs([([0, 0, 0, 0], 1), ([128, 0, 0, 0], 1)]), vec![([0, 0, 0, 0], 0)]); + + // 2. Enterprise packet-tunnel SystemExtensions (GlobalProtect, Cloudflare WARP, Zscaler) + // enable host egress relay, while Tailscale / WireGuard stay route-driven (#932). + let make_xml = |id: &str| format!( + "extensions\ + identifier{id}\ + stateactivated_enabled\ + categoriescom.apple.system_extension.network_extension\ + additionalLaunchdPlistEntriescom.apple.networkextension.packet-tunnel\ + " + ); + assert!(has_active_network_extension(make_xml("com.paloaltonetworks.GlobalProtect.client.extension").as_bytes())); + assert!(has_active_network_extension(make_xml("com.cloudflare.1dot1dot1dot1.macos.warp.extension").as_bytes())); + assert!(has_active_network_extension(make_xml("com.zscaler.zenith.tunnel").as_bytes())); + assert!(!has_active_network_extension(make_xml("io.tailscale.ipn.macsys.network-extension").as_bytes())); + assert!(!has_active_network_extension(make_xml("com.wireguard.macos.network-extension").as_bytes())); + + // 3. Active IPv4 point-to-point tunnel (`utun7`) with NECP policy routing or `RTF_IFSCOPE` + // default route promotes `0.0.0.0/0`, whereas a split-tunnel with an explicit subnet + // only routes its subnet, and dormant system `utun` without IPv4 contributes nothing. + let p2p = ActiveTunnel { name: "utun7".into(), ip: [10, 66, 0, 2], prefix: 32, peer: Some([10, 66, 0, 1]), point_to_point: true }; + assert_eq!(parse_macos_routes_with_tunnels(&[], |_| None, &[p2p]), vec![([0, 0, 0, 0], 0)]); + let sub = ActiveTunnel { name: "utun8".into(), ip: [100, 64, 1, 5], prefix: 10, peer: None, point_to_point: false }; + assert_eq!(parse_macos_routes_with_tunnels(&[], |_| None, &[sub]), vec![([100, 64, 0, 0], 10)]); + } } diff --git a/crates/kiri/src/daemon/rofs.rs b/crates/kiri/src/daemon/rofs.rs new file mode 100644 index 000000000..f977d13b1 --- /dev/null +++ b/crates/kiri/src/daemon/rofs.rs @@ -0,0 +1,394 @@ +//! Detection and actionable diagnostics when Kiri's Linux or WSL 2 storage +//! filesystem is mounted read-only (`ST_RDONLY`, `ro`, or ext4 `emergency_ro` +//! after an unclean shutdown or journal abort, #768). + +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] + +use std::path::Path; + +/// Why a storage filesystem is read-only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReadOnlyKind { + /// Linux ext4 aborted its journal (`errors=remount-ro`) and added `emergency_ro`. + EmergencyRo, + /// Mounted read-only (`ro` / `ST_RDONLY`). + ReadOnly, +} + +impl ReadOnlyKind { + pub fn merge(self, other: Self) -> Self { + if self == Self::EmergencyRo || other == Self::EmergencyRo { + Self::EmergencyRo + } else { + Self::ReadOnly + } + } +} + +/// Unescapes `/proc/mounts` and `/proc/self/mountinfo` octal escapes (`\040`, `\011`, `\012`, `\134`). +pub fn unescape_mount_path(raw: &str) -> String { + let bytes = raw.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'\\' + && i + 3 < bytes.len() + && bytes[i + 1..i + 4].iter().all(|b| (b'0'..=b'7').contains(b)) + { + let val = ((bytes[i + 1] - b'0') << 6) | ((bytes[i + 2] - b'0') << 3) | (bytes[i + 3] - b'0'); + out.push(val); + i += 4; + } else { + out.push(bytes[i]); + i += 1; + } + } + String::from_utf8_lossy(&out).into_owned() +} + +fn norm_mount_path(p: &str) -> &str { + let trimmed = p.trim_end_matches('/'); + if trimmed.is_empty() { "/" } else { trimmed } +} + +fn mount_covers(mp: &str, target: &str) -> bool { + let mp = norm_mount_path(mp); + let target = norm_mount_path(target); + mp == "/" || target == mp || (target.starts_with(mp) && target.as_bytes().get(mp.len()) == Some(&b'/')) +} + +/// Parses comma-separated mount options (`rw,...,emergency_ro` or `ro,...`) +/// into `ReadOnlyKind`, ignoring substrings such as `errors=remount-ro`. +pub fn parse_opts_readonly(opts: &str) -> Option { + let mut ro = false; + for opt in opts.split(',') { + match opt.trim() { + "emergency_ro" => return Some(ReadOnlyKind::EmergencyRo), + "ro" => ro = true, + _ => {} + } + } + ro.then_some(ReadOnlyKind::ReadOnly) +} + +/// Inspects `/proc/mounts` text for the active mount covering `target`. +/// Picks the longest ancestor mountpoint, with later lines winning ties (overmounts). +pub fn proc_mounts_readonly(proc_mounts: &str, target: &Path) -> Option { + let target_str = target.to_string_lossy(); + let mut best: Option<(usize, Option)> = None; + for line in proc_mounts.lines() { + let mut fields = line.split_whitespace(); + let (Some(_spec), Some(mp_raw), Some(_fstype), Some(opts)) = + (fields.next(), fields.next(), fields.next(), fields.next()) + else { + continue; + }; + let mp = unescape_mount_path(mp_raw); + let mp_norm = norm_mount_path(&mp); + if mount_covers(mp_norm, &target_str) && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + best = Some((mp_norm.len(), parse_opts_readonly(opts))); + } + } + best.and_then(|(_, kind)| kind) +} + +/// Inspects `/proc/self/mountinfo` text for the active mount covering `target`. +pub fn mountinfo_readonly(mountinfo: &str, target: &Path) -> Option { + let target_str = target.to_string_lossy(); + let mut best: Option<(usize, Option)> = None; + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let mut b = before.split_whitespace(); + let (Some(_id), Some(_parent), Some(_dev), Some(_root), Some(mp_raw), Some(mopts)) = + (b.next(), b.next(), b.next(), b.next(), b.next(), b.next()) + else { + continue; + }; + let mut a = after.split_whitespace(); + let (Some(_fstype), Some(_src), Some(sopts)) = (a.next(), a.next(), a.next()) else { continue }; + let mp = unescape_mount_path(mp_raw); + let mp_norm = norm_mount_path(&mp); + if mount_covers(mp_norm, &target_str) && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + let kind = match (parse_opts_readonly(mopts), parse_opts_readonly(sopts)) { + (Some(a), Some(b)) => Some(a.merge(b)), + (Some(a), None) | (None, Some(a)) => Some(a), + (None, None) => None, + }; + best = Some((mp_norm.len(), kind)); + } + } + best.and_then(|(_, kind)| kind) +} + +/// OpenZFS's `ZFS_SUPER_MAGIC` (`zpl_super.c`). +pub const ZFS_SUPER_MAGIC: i64 = 0x2fc1_2fc1; + +/// Inspects `/proc/self/mountinfo` text for the filesystem type of the active +/// mount covering `target` (longest ancestor mountpoint, with later lines +/// winning ties for overmounts). +pub fn mountinfo_fstype<'a>(mountinfo: &'a str, target: &Path) -> Option<&'a str> { + let target_str = target.to_string_lossy(); + let mut best: Option<(usize, &'a str)> = None; + for line in mountinfo.lines() { + let Some((before, after)) = line.split_once(" - ") else { continue }; + let Some(mp_raw) = before.split_whitespace().nth(4) else { continue }; + let Some(fstype) = after.split_whitespace().next() else { continue }; + let mp = unescape_mount_path(mp_raw); + let mp_norm = norm_mount_path(&mp); + if mount_covers(mp_norm, &target_str) && best.is_none_or(|(len, _)| mp_norm.len() >= len) { + best = Some((mp_norm.len(), fstype)); + } + } + best.map(|(_, fstype)| fstype) +} + +/// Whether `/proc/self/mountinfo` reports fstype `"zfs"` for the active mount covering `target`. +pub fn is_zfs_mountinfo(mountinfo: &str, target: &Path) -> bool { + mountinfo_fstype(mountinfo, target) == Some("zfs") +} + +/// Pure helper testing whether `osrelease` or WSL interop markers indicate WSL. +pub fn is_wsl_env(osrelease: &str, interop_exists: bool) -> bool { + if interop_exists { + return true; + } + let lower = osrelease.to_ascii_lowercase(); + lower.contains("microsoft") || lower.contains("wsl") +} + +/// Actionable diagnostic message for a read-only storage filesystem on WSL 2 or Linux. +pub fn format_readonly_error(kind: ReadOnlyKind, wsl: bool) -> String { + if wsl { + let state = match kind { + ReadOnlyKind::EmergencyRo => "was remounted read-only by Linux (emergency_ro)", + ReadOnlyKind::ReadOnly => "is mounted read-only (emergency_ro)", + }; + format!( + "Kiri's WSL2 disk (ext4.vhdx) {state} after an unclean shutdown or filesystem error. \ + To recover: 1) run `wsl --shutdown` in PowerShell; \ + 2) attach the disk bare with `wsl --mount \\ext4.vhdx --vhd --bare` (default `%LOCALAPPDATA%\\Kiri\\wsl\\kiri\\ext4.vhdx`); \ + 3) from another Linux distro in WSL, find the device with `lsblk` and run `sudo e2fsck -f -y -D /dev/`, then `wsl --unmount`; \ + or move/recreate storage in Settings -> Storage." + ) + } else { + match kind { + ReadOnlyKind::EmergencyRo => { + "Kiri's container storage filesystem (/var/lib/kiri) was remounted read-only by Linux (emergency_ro) after a filesystem error: check `dmesg` and run `fsck` to repair the filesystem, then restart Kiri.".to_owned() + } + ReadOnlyKind::ReadOnly => { + "Kiri's container storage filesystem (/var/lib/kiri) is mounted read-only: check `dmesg` and mount options, or run `fsck` to repair the filesystem, then restart Kiri.".to_owned() + } + } + } +} + +#[cfg(target_os = "linux")] +pub fn is_wsl() -> bool { + static WSL: std::sync::OnceLock = std::sync::OnceLock::new(); + *WSL.get_or_init(|| { + let interop = Path::new("/proc/sys/fs/binfmt_misc/WSLInterop").exists() + || Path::new("/proc/sys/fs/binfmt_misc/WSLInterop-late").exists() + || Path::new("/run/WSL").is_dir(); + let osrelease = std::fs::read_to_string("/proc/sys/kernel/osrelease").unwrap_or_default(); + is_wsl_env(&osrelease, interop) + }) +} + +#[cfg(target_os = "linux")] +fn is_statvfs_readonly(path: &Path) -> bool { + use std::os::unix::ffi::OsStrExt; + let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { return false }; + // SAFETY: `st` is plain zero-initialized data; `c` is a valid C string. + let mut st: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: statvfs writes into `st`. + unsafe { libc::statvfs(c.as_ptr(), &mut st) == 0 && (st.f_flag as u64) & (libc::ST_RDONLY as u64) != 0 } +} + +#[cfg(target_os = "linux")] +pub fn detect_path_readonly(path: &Path) -> Option { + let existing = path.ancestors().find(|p| !p.as_os_str().is_empty() && p.exists())?; + let stat_ro = is_statvfs_readonly(existing); + let canon = existing.canonicalize().ok(); + let targets = [canon.as_deref(), Some(existing)]; + let mut found: Option = stat_ro.then_some(ReadOnlyKind::ReadOnly); + if let Ok(mi) = std::fs::read_to_string("/proc/self/mountinfo") { + for t in targets.into_iter().flatten() { + if let Some(k) = mountinfo_readonly(&mi, t) { + found = Some(found.map_or(k, |prev| prev.merge(k))); + } + } + } + if let Ok(pm) = std::fs::read_to_string("/proc/mounts") { + for t in targets.into_iter().flatten() { + if let Some(k) = proc_mounts_readonly(&pm, t) { + found = Some(found.map_or(k, |prev| prev.merge(k))); + } + } + } + found +} + +#[cfg(target_os = "linux")] +fn is_statfs_zfs(path: &Path) -> bool { + use std::os::unix::ffi::OsStrExt; + let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { return false }; + // SAFETY: `st` is plain zero-initialized data; `c` is a valid C string. + let mut st: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: statfs writes into `st`. + unsafe { libc::statfs(c.as_ptr(), &mut st) == 0 && st.f_type as i64 == ZFS_SUPER_MAGIC } +} + +#[cfg(target_os = "linux")] +pub fn detect_path_zfs(path: &Path) -> bool { + let Some(existing) = path.ancestors().find(|p| !p.as_os_str().is_empty() && p.exists()) else { + return false; + }; + if is_statfs_zfs(existing) { + return true; + } + let Ok(mi) = std::fs::read_to_string("/proc/self/mountinfo") else { + return false; + }; + let canon = existing.canonicalize().ok(); + is_zfs_mountinfo(&mi, canon.as_deref().unwrap_or(existing)) +} + +#[cfg(target_os = "linux")] +fn resolve_agent_path(store_root: Option<&Path>) -> std::path::PathBuf { + let default_root = kiri_image::Store::os_default_root().ok(); + let owned_root; + let root = match store_root { + Some(r) => Some(r), + None => { + owned_root = kiri_image::Store::default_root().ok(); + owned_root.as_deref() + } + }; + match (root, default_root.as_deref()) { + (Some(r), Some(def)) => super::storage::agent_dir(r, def).unwrap_or_else(|| std::path::PathBuf::from("/var/lib/kiri")), + _ => std::path::PathBuf::from("/var/lib/kiri"), + } +} + +#[cfg(target_os = "linux")] +pub fn is_daemon_storage_zfs(store_root: Option<&Path>) -> bool { + let volumes = resolve_agent_path(store_root).join("volumes"); + detect_path_zfs(&volumes) +} + +#[cfg(not(target_os = "linux"))] +pub fn is_daemon_storage_zfs(_store_root: Option<&Path>) -> bool { + false +} + +#[cfg(target_os = "linux")] +pub fn check_daemon_storage(store_root: Option<&Path>) -> Option { + let owned_root; + let root = match store_root { + Some(r) => Some(r), + None => { + owned_root = kiri_image::Store::default_root().ok(); + owned_root.as_deref() + } + }; + let agent_path = resolve_agent_path(root); + let state = super::state_dir().ok(); + let mut kind: Option = None; + for p in [Some(agent_path.as_path()), root, state.as_deref()].into_iter().flatten() { + if let Some(k) = detect_path_readonly(p) { + kind = Some(kind.map_or(k, |prev| prev.merge(k))); + } + } + kind.map(|k| format_readonly_error(k, is_wsl())) +} + +#[cfg(not(target_os = "linux"))] +pub fn check_daemon_storage(_store_root: Option<&Path>) -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_proc_mounts_emergency_ro_and_ro_without_false_matching_remount_ro() { + // Healthy WSL 2 ext4 mount with errors=remount-ro must NOT be flagged read-only. + let healthy = "\ +/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered 0 0 +tmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0 +"; + assert_eq!(proc_mounts_readonly(healthy, Path::new("/var/lib/kiri")), None); + assert_eq!(proc_mounts_readonly(healthy, Path::new("/")), None); + + // Issue #768 exact /proc/mounts state: VFS mount flag still says `rw`, ext4 superblock added `emergency_ro`. + let emergency = "\ +/dev/sdd / ext4 rw,relatime,discard,errors=remount-ro,data=ordered,emergency_ro 0 0 +tmpfs /run tmpfs rw,nosuid,nodev,mode=755 0 0 +"; + assert_eq!(proc_mounts_readonly(emergency, Path::new("/var/lib/kiri")), Some(ReadOnlyKind::EmergencyRo)); + assert_eq!(proc_mounts_readonly(emergency, Path::new("/var/lib/kiri/containers/abc")), Some(ReadOnlyKind::EmergencyRo)); + // /run is a separate writable tmpfs mount, so /run/kiri is NOT read-only. + assert_eq!(proc_mounts_readonly(emergency, Path::new("/run/kiri")), None); + + // Separate /var/lib/kiri mounted `ro` while `/` is `rw`, plus space-escaped paths and overmounts. + let separate_ro = "\ +/dev/sda1 / ext4 rw,relatime 0 0 +/dev/sdb1 /var/lib/kiri ext4 ro,relatime 0 0 +/dev/sdc1 /mnt/data\\040disk ext4 rw,relatime 0 0 +/dev/sdc1 /mnt/data\\040disk ext4 ro,relatime 0 0 +"; + assert_eq!(proc_mounts_readonly(separate_ro, Path::new("/var/lib/kiri/containers/123")), Some(ReadOnlyKind::ReadOnly)); + assert_eq!(proc_mounts_readonly(separate_ro, Path::new("/var/lib/kiri2")), None); + assert_eq!(proc_mounts_readonly(separate_ro, Path::new("/mnt/data disk/kiri")), Some(ReadOnlyKind::ReadOnly)); + } + + #[test] + fn parses_mountinfo_superblock_emergency_ro_and_overmounts() { + let mountinfo = "\ +25 1 8:48 / / rw,relatime - ext4 /dev/sdd rw,discard,errors=remount-ro,data=ordered,emergency_ro +26 25 0:24 / /run rw,nosuid,nodev - tmpfs tmpfs rw,mode=755 +40 25 0:55 / /var/lib/kiri/containers/c1/rootfs ro,relatime - overlay overlay ro,lowerdir=abc,upperdir=/var/lib/kiri/containers/c1/upper,workdir=/var/lib/kiri/containers/c1/work,index=off +"; + assert_eq!(mountinfo_readonly(mountinfo, Path::new("/var/lib/kiri/containers/c1")), Some(ReadOnlyKind::EmergencyRo)); + assert_eq!(mountinfo_readonly(mountinfo, Path::new("/var/lib/kiri/containers/c1/rootfs")), Some(ReadOnlyKind::ReadOnly)); + assert_eq!(mountinfo_readonly(mountinfo, Path::new("/run/kiri")), None); + } + + #[test] + fn detects_wsl_from_interop_or_kernel_release_and_formats_recovery_steps() { + assert!(is_wsl_env("6.6.87.2-microsoft-standard-WSL2\n", false)); + // Custom WSL kernel without "microsoft" in osrelease (as in #768: 6.18.58.1-1) detected via WSLInterop. + assert!(is_wsl_env("6.18.58.1-1\n", true)); + assert!(!is_wsl_env("6.18.58.1-1-generic\n", false)); + + let wsl_msg = format_readonly_error(ReadOnlyKind::EmergencyRo, true); + assert!(wsl_msg.contains("ext4.vhdx") && wsl_msg.contains("emergency_ro"), "{wsl_msg}"); + assert!(wsl_msg.contains("wsl --shutdown") && wsl_msg.contains("wsl --mount") && wsl_msg.contains("e2fsck -f -y -D"), "{wsl_msg}"); + assert!(wsl_msg.contains("Settings -> Storage"), "{wsl_msg}"); + + let linux_msg = format_readonly_error(ReadOnlyKind::EmergencyRo, false); + assert!(linux_msg.contains("/var/lib/kiri") && linux_msg.contains("emergency_ro") && linux_msg.contains("dmesg") && linux_msg.contains("fsck"), "{linux_msg}"); + } + + #[test] + fn parses_mountinfo_zfs_and_loopback_ext4_overmounts() { + let zfs_root = "\ +25 1 0:30 / / rw,relatime shared:1 - zfs rpool/ROOT/ubuntu_wuq1tk rw,xattr,posixacl,casesensitive +26 25 0:31 / /var/lib rw,relatime shared:2 - zfs rpool/ROOT/ubuntu_wuq1tk/var/lib rw,xattr,posixacl,casesensitive +91 26 7:3 / /var/lib/kiri/volumes/kiri-k8s/_data rw,relatime - ext4 /dev/loop3 rw,noinit_itable +92 25 0:40 / /mnt/zfs\\040pool rw,relatime - zfs tank/pool rw,xattr,posixacl +"; + assert_eq!(mountinfo_fstype(zfs_root, Path::new("/var/lib/kiri/volumes")), Some("zfs")); + assert!(is_zfs_mountinfo(zfs_root, Path::new("/var/lib/kiri/volumes"))); + assert!(is_zfs_mountinfo(zfs_root, Path::new("/var/lib/kiri/volumes/kiri-k8s"))); + assert!(is_zfs_mountinfo(zfs_root, Path::new("/mnt/zfs pool/kiri/volumes"))); + // Loopback ext4 overmounted onto kiri-k8s/_data wins over parent ZFS dataset. + assert_eq!(mountinfo_fstype(zfs_root, Path::new("/var/lib/kiri/volumes/kiri-k8s/_data")), Some("ext4")); + assert!(!is_zfs_mountinfo(zfs_root, Path::new("/var/lib/kiri/volumes/kiri-k8s/_data"))); + + let ext4_root = "25 1 8:1 / / rw,relatime - ext4 /dev/nvme0n1p2 rw\n"; + assert_eq!(mountinfo_fstype(ext4_root, Path::new("/var/lib/kiri/volumes")), Some("ext4")); + assert!(!is_zfs_mountinfo(ext4_root, Path::new("/var/lib/kiri/volumes"))); + } +} diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs new file mode 100644 index 000000000..07f7dca78 --- /dev/null +++ b/crates/kiri/src/daemon/storage.rs @@ -0,0 +1,1404 @@ +//! Settings → Storage on a Mac and a Linux host: where Kiri keeps its +//! images, containers and volumes, and moving them to another folder (an +//! external drive, say). Windows moves its WSL distro instead +//! (crates/kiri-win/src/storage.rs). +//! +//! `GET /kiri/storage` says where the data is, what it takes and what is +//! free there, and how a move goes. `POST /kiri/storage/check` checks a +//! folder; `POST /kiri/storage` moves the data there: +//! +//! 1. Every container stops (those that ran are noted) and the VM powers +//! off (`Engine::park_for_move`). +//! 2. The data is copied into `/.kiri-moving`, keeping holes +//! (treecopy.rs), and the copy is checked: blobs by digest, every file +//! by size. +//! 3. The copy is renamed into place and the marker written +//! (kiri_image::storage::MARKER). +//! 4. `~/.kiri/storage.json` is written: the commit point. Up to here any +//! failure removes what was made and Kiri carries on where it was. +//! 5. The daemon starts itself again on the new folder and starts the +//! containers that ran. The old folder is kept until Remove old data. +//! +//! On a Linux host the agent's layers, containers and volumes move too: +//! from /var/lib/kiri to the chosen folder's `agent` folder, which the +//! agent mounts at /var/lib/kiri when it starts (KIRI_AGENT_DATA). +//! +//! A chosen folder without its marker (a drive that isn't connected) gets +//! no empty store made in it: the daemon stays up with nothing but +//! `serve_unavailable`, which offers Retry and Reset to default. + +use std::io::{self, BufReader}; +use std::os::unix::net::UnixStream; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use kiri_image::storage::{self as chosen, Choice, MARKER}; + +use super::engine::{Engine, Error}; +use super::http::{self, Request}; +use super::treecopy; + +/// On a Linux host, where the agent keeps layers, containers and volumes +/// while the data folder is the default one. +#[cfg(target_os = "linux")] +const AGENT_DATA: &str = "/var/lib/kiri"; + +/// The staging folder of a move, inside the folder moved to. +const MOVING: &str = ".kiri-moving"; +/// Kiri data that was in the folder moved to, set aside until the commit. +const REPLACED: &str = ".kiri-replaced"; +/// What a folder may hold besides Kiri's data and still count as empty. +const IGNORED: &[&str] = &[".DS_Store", "lost+found", MOVING, REPLACED, MARKER]; +/// Set on the daemon a move starts again: the containers to start. +const RESTART_ENV: &str = "KIRI_STORAGE_RESTART"; + +/// What other requests get while the data moves. +const MOVING_TEXT: &str = "Kiri is moving its data to another folder: try again when Settings → Storage says it's done"; + +/// The agent's folder on this system, if it has one apart from the data +/// folder. +fn agent_default() -> Option<&'static Path> { + #[cfg(target_os = "linux")] + return Some(Path::new(AGENT_DATA)); + #[cfg(not(target_os = "linux"))] + None +} + +/// The agent's data folder for the data folder `root` on a Linux host: +/// /var/lib/kiri for the default folder, else `/agent`. None +/// elsewhere. `guest.rs` hands a chosen one to the agent. +pub fn agent_dir(root: &Path, default: &Path) -> Option { + agent_default().map(|agent| if root == default { agent.to_owned() } else { root.join("agent") }) +} + +/// One folder a move copies: `from` into `to`, leaving out `skip` (names +/// at its top that another part moves). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Part { + pub from: PathBuf, + pub to: PathBuf, + pub skip: Vec<&'static str>, +} + +/// What moving the data folder `current` to `target` copies, where +/// `default` is the folder without a choice and `agent` the agent's own +/// folder for it (a Linux host's /var/lib/kiri). +pub fn parts(current: &Path, target: &Path, default: &Path, agent: Option<&Path>) -> Vec { + let Some(agent) = agent else { + return vec![Part { from: current.to_owned(), to: target.to_owned(), skip: Vec::new() }]; + }; + let agent_of = |root: &Path| if root == default { agent.to_owned() } else { root.join("agent") }; + vec![ + Part { from: current.to_owned(), to: target.to_owned(), skip: vec!["agent"] }, + Part { from: agent_of(current), to: agent_of(target), skip: Vec::new() }, + ] +} + +/// A folder that passed [`check`]: what the data needs there, what is +/// free, and whether Kiri data already there is replaced. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Checked { + pub needed: u64, + pub free: u64, + pub replaces: bool, +} + +/// `path` with its links resolved as far as it exists. +fn real(path: &Path) -> PathBuf { + let Some(near) = treecopy::existing_ancestor(path) else { return path.to_owned() }; + let rest = path.strip_prefix(near).unwrap_or(Path::new("")); + near.canonicalize().unwrap_or_else(|_| near.to_owned()).join(rest) +} + +/// "12.3 GB". +fn size(bytes: u64) -> String { + format!("{:.1} GB", bytes as f64 / 1e9) +} + +/// Room left over beside the data: a tenth more, and 1 GB. +fn headroom(bytes: u64) -> u64 { + bytes / 10 + 1_000_000_000 +} + +/// Whether the folders can take the data: full paths, apart from where +/// the data is now, empty (or holding Kiri data from before), writable, +/// not FAT or exFAT, with room for what the data takes plus a margin. +#[cfg(test)] +pub fn check(parts: &[Part]) -> Result { + check_with(parts, true) +} + +/// Like [`check`], but when `copy` is false (`Start fresh`), only checks +/// that the target has baseline headroom (1 GB) rather than the current +/// store's allocated size. +pub fn check_with(parts: &[Part], copy: bool) -> Result { + let mut replaces = false; + // Per filesystem: a folder on it, and the bytes moving there. + let mut needs: Vec<(u64, PathBuf, u64)> = Vec::new(); + for p in parts { + let to = &p.to; + if !to.is_absolute() || to.components().any(|c| matches!(c, Component::ParentDir)) { + return Err(format!("{} isn't a full path: choose a folder", to.display())); + } + for q in parts { + let (from, dest) = (real(&q.from), real(to)); + if from == dest { + return Err(format!("Kiri's data is already in {}", to.display())); + } + if dest.starts_with(&from) { + return Err(format!("{} is inside Kiri's data folder {}: choose a folder outside it", to.display(), q.from.display())); + } + if from.starts_with(&dest) { + return Err(format!("Kiri's data folder {} is inside {}: choose another folder", q.from.display(), to.display())); + } + } + if to.symlink_metadata().is_ok() { + if !to.is_dir() { + return Err(format!("{} isn't a folder", to.display())); + } + let others = std::fs::read_dir(to) + .map_err(|e| format!("{}: {e}", to.display()))? + .flatten() + .any(|e| !IGNORED.iter().any(|n| e.file_name() == *n) && !p.skip.iter().any(|n| e.file_name() == *n)); + if chosen::has_marker(to) { + replaces |= others; + } else if others { + return Err(format!("{} isn't empty and doesn't hold Kiri's data: choose an empty folder, or make a new one", to.display())); + } + } + let near = treecopy::existing_ancestor(to).ok_or_else(|| format!("{} isn't on any disk", to.display()))?; + let fs = treecopy::fs_name(near).map_err(|e| format!("{}: {e}", near.display()))?; + if treecopy::refused_fs(&fs) { + let name = if fs == "exfat" { "exFAT" } else { "FAT" }; + return Err(format!("{} is on a {name} drive, which can't hold Kiri's data (no sparse files, owners or links): choose a folder on another drive", to.display())); + } + treecopy::probe_writable(near).map_err(|e| format!("Kiri can't write in {}: {e}", near.display()))?; + let bytes = if copy { treecopy::allocated(&p.from, &p.skip) } else { 0 }; + let dev = treecopy::device(near).map_err(|e| format!("{}: {e}", near.display()))?; + match needs.iter_mut().find(|(d, _, _)| *d == dev) { + Some(n) => n.2 += bytes, + None => needs.push((dev, near.to_owned(), bytes)), + } + } + let (mut needed, mut free) = (0, u64::MAX); + for (_, near, bytes) in &needs { + let want = bytes + headroom(*bytes); + let have = treecopy::free_space(near).map_err(|e| format!("{}: {e}", near.display()))?; + if have < want { + return Err(format!("{} has {} free, and Kiri's data needs {} there", near.display(), size(have), size(want))); + } + needed += want; + free = free.min(have); + } + Ok(Checked { needed, free, replaces }) +} + +/// The steps of [`migrate`] the progress callback is told about. +pub const COPYING: &str = "copying"; +pub const VERIFYING: &str = "verifying"; +pub const SWITCHING: &str = "switching"; + +/// One part put in place: what to undo if a later step fails. +struct Placed { + to: PathBuf, + moved_in: Vec, + set_aside: Vec, + had_marker: bool, +} + +/// Steps 2 to 4 of a move: each part copied into `/.kiri-moving` and +/// checked, put in place with the marker, then `choice` written to +/// `config`, the commit. A failure before the commit undoes everything: +/// what was copied goes, Kiri data that was in the way comes back, and +/// the folders the data is in now are as they were (apart from the marker, +/// which says they hold Kiri data). `step` hears each step's bytes; an +/// error from it stops the move. +pub fn migrate(parts: &[Part], config: &Path, choice: &Choice, step: &mut dyn FnMut(&'static str, u64) -> io::Result<()>) -> io::Result<()> { + let parts: Vec<&Part> = parts.iter().filter(|p| p.from.is_dir()).collect(); + let made: Vec = parts.iter().map(|p| !p.to.exists()).collect(); + let mut placed: Vec = Vec::new(); + let result = (|| -> io::Result<()> { + for p in &parts { + // Recognisable as Kiri's later: the old folder is a valid + // target for a move back. + chosen::write_marker(&p.from)?; + std::fs::create_dir_all(&p.to)?; + let staging = p.to.join(MOVING); + let _ = std::fs::remove_dir_all(&staging); + treecopy::copy_tree(&p.from, &staging, &p.skip, &mut |n| step(COPYING, n))?; + } + for p in &parts { + treecopy::verify_tree(&p.from, &p.to.join(MOVING), &p.skip, &mut |n| step(VERIFYING, n))?; + } + step(SWITCHING, 0)?; + for p in &parts { + placed.push(place(p)?); + } + chosen::write_at(config, choice) + })(); + match result { + Ok(()) => { + for p in &placed { + let _ = std::fs::remove_dir_all(p.to.join(REPLACED)); + } + Ok(()) + } + Err(e) => { + for p in placed.iter().rev() { + undo(p); + } + for (p, made) in parts.iter().zip(made).rev() { + let _ = std::fs::remove_dir_all(p.to.join(MOVING)); + if made { + let _ = std::fs::remove_file(p.to.join(MARKER)); + let _ = std::fs::remove_dir(&p.to); + } + } + Err(e) + } + } +} + +/// Switches `config` to an empty store in `parts` (`Start fresh`): marks +/// the old folders so Remove old data works, prepares empty target folders +/// with the marker (setting aside any prior Kiri data until commit), and +/// commits `choice` atomically. A failure before commit restores everything. +pub fn migrate_fresh(parts: &[Part], config: &Path, choice: &Choice, step: &mut dyn FnMut(&'static str, u64) -> io::Result<()>) -> io::Result<()> { + let made: Vec = parts.iter().map(|p| !p.to.exists()).collect(); + let mut placed: Vec = Vec::new(); + let result = (|| -> io::Result<()> { + step(SWITCHING, 0)?; + for p in parts { + if p.from.is_dir() { + chosen::write_marker(&p.from)?; + } + std::fs::create_dir_all(&p.to)?; + // Recorded before anything is set aside, so a failure partway + // through this folder is undone along with the ones before it. + placed.push(Placed { to: p.to.clone(), moved_in: Vec::new(), set_aside: Vec::new(), had_marker: chosen::has_marker(&p.to) }); + let done = placed.last_mut().expect("just pushed"); + for e in std::fs::read_dir(&p.to)? { + let name = e?.file_name(); + if IGNORED.iter().any(|n| name == *n) || p.skip.iter().any(|n| name == *n) { + continue; + } + std::fs::create_dir_all(p.to.join(REPLACED))?; + std::fs::rename(p.to.join(&name), p.to.join(REPLACED).join(&name))?; + done.set_aside.push(name); + } + chosen::write_marker(&p.to)?; + } + chosen::write_at(config, choice) + })(); + match result { + Ok(()) => { + for p in &placed { + let _ = std::fs::remove_dir_all(p.to.join(REPLACED)); + } + Ok(()) + } + Err(e) => { + for p in placed.iter().rev() { + undo(p); + } + for (p, made) in parts.iter().zip(made).rev() { + if made { + let _ = std::fs::remove_file(p.to.join(MARKER)); + let _ = std::fs::remove_dir(&p.to); + } + } + Err(e) + } + } +} + +/// Renames a part's copy into place: what was there (Kiri data from +/// before) into `.kiri-replaced`, then the copy, then the marker. +fn place(p: &Part) -> io::Result { + let staging = p.to.join(MOVING); + let mut done = Placed { to: p.to.clone(), moved_in: Vec::new(), set_aside: Vec::new(), had_marker: chosen::has_marker(&p.to) }; + let mut step = || -> io::Result<()> { + for e in std::fs::read_dir(&p.to)? { + let name = e?.file_name(); + if IGNORED.iter().any(|n| name == *n) || p.skip.iter().any(|n| name == *n) { + continue; + } + std::fs::create_dir_all(p.to.join(REPLACED))?; + std::fs::rename(p.to.join(&name), p.to.join(REPLACED).join(&name))?; + done.set_aside.push(name); + } + for e in std::fs::read_dir(&staging)? { + let name = e?.file_name(); + if name == MARKER { + continue; + } + std::fs::rename(staging.join(&name), p.to.join(&name))?; + done.moved_in.push(name); + } + std::fs::remove_dir_all(&staging)?; + chosen::write_marker(&p.to) + }; + match step() { + Ok(()) => Ok(done), + Err(e) => { + undo(&done); + Err(e) + } + } +} + +/// Takes a placed part back out: the copy removed, what was set aside +/// back where it was. +fn undo(p: &Placed) { + for name in &p.moved_in { + let path = p.to.join(name); + let _ = std::fs::remove_dir_all(&path).or_else(|_| std::fs::remove_file(&path)); + } + for name in &p.set_aside { + let _ = std::fs::rename(p.to.join(REPLACED).join(name), p.to.join(name)); + } + let _ = std::fs::remove_dir(p.to.join(REPLACED)); + if !p.had_marker { + let _ = std::fs::remove_file(p.to.join(MARKER)); + } +} + +/// How a move goes, for `GET /kiri/storage`. +#[derive(Default)] +struct Moving { + to: Option, + phase: &'static str, + done: u64, + total: u64, + /// Why the last move failed; Kiri stayed where it was. + error: Option, +} + +static MOVE: Mutex = Mutex::new(Moving { to: None, phase: "", done: 0, total: 0, error: None }); +static ACTIVE: AtomicBool = AtomicBool::new(false); +static USED_CACHE: Mutex> = Mutex::new(None); +#[cfg(target_os = "macos")] +static LAST_IN_USE: Mutex> = Mutex::new(None); +#[cfg(target_os = "macos")] +static LAST_CAPACITY: Mutex> = Mutex::new(None); +#[cfg(target_os = "macos")] +static RECLAIMING: AtomicBool = AtomicBool::new(false); + +/// Persisted non-trimmable VM disk allocation (`/vm/disk-overhead`), +/// measured right after `FITRIM` so ext4's own journal, bitmaps, and +/// initialized inode tables (up to ~2.5% of disk size, excluded from +/// `statvfs.f_blocks`) are counted as in-use VM disk rather than promised as +/// reclaimable space that `FITRIM` can never free. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +const DISK_OVERHEAD_FILE: &str = "vm/disk-overhead"; + +/// Reclaimable bytes under this threshold (64 MiB) are reported as 0 so +/// filesystem metadata slack does not prompt pointless trims. +pub const RECLAIM_THRESHOLD: u64 = 64 << 20; + +/// Reclaimable bytes from host-allocated disk size vs in-use bytes inside the +/// VM, applying [`RECLAIM_THRESHOLD`]. +pub fn reclaimable_bytes(disk_host: Option, disk_in_use: Option) -> Option { + let diff = disk_host?.saturating_sub(disk_in_use?); + Some(if diff > RECLAIM_THRESHOLD { diff } else { 0 }) +} + +/// Allocated bytes (`st_blocks * 512`) and logical byte length (`st_size`) of +/// `/vm/data.img`, if present. +pub fn data_img_stats(root: &Path) -> Option<(u64, u64)> { + use std::os::unix::fs::MetadataExt; + let m = std::fs::metadata(root.join("vm/data.img")).ok()?; + Some((m.blocks().saturating_mul(512), m.len())) +} + +/// Allocated bytes of `/vm/data.img` (`st_blocks * 512`), if present. +pub fn data_img_allocated(root: &Path) -> Option { + data_img_stats(root).map(|(alloc, _)| alloc) +} + +/// Upper bound on ext4's static metadata overhead (`logical_len - capacity`: +/// superblocks, group descriptors, bitmaps, journal, and inode tables), capped +/// to 1/16th of `capacity` + 512 MiB so an online-grown `data.img` whose guest +/// filesystem has not resized yet never treats the unmounted tail as overhead. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn max_ext4_overhead(logical_len: u64, capacity: u64) -> u64 { + if capacity == 0 || logical_len <= capacity { + return 0; + } + let cap = (capacity >> 4).saturating_add(512 << 20); + logical_len.saturating_sub(capacity).min(cap) +} + +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn read_disk_overhead(root: &Path) -> Option { + std::fs::read_to_string(root.join(DISK_OVERHEAD_FILE)) + .ok()? + .trim() + .parse::() + .ok() +} + +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn write_disk_overhead(root: &Path, bytes: u64) { + let path = root.join(DISK_OVERHEAD_FILE); + let tmp = root.join("vm/disk-overhead.tmp"); + if std::fs::write(&tmp, format!("{bytes}\n")).is_ok() { + let _ = std::fs::rename(&tmp, &path); + } +} + +/// Effective bytes in use inside `data.img`, combining occupied filesystem +/// data blocks (`raw_in_use`) with allocated non-trimmable ext4 metadata so +/// `reclaimable_bytes(disk_host, effective_in_use)` matches what `FITRIM` can +/// actually return to macOS. +#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))] +fn effective_vm_in_use( + disk_host: Option, + logical_len: Option, + raw_in_use: Option, + capacity: Option, + recorded_overhead: Option, +) -> (Option, Option) { + let Some(raw) = raw_in_use else { + return (None, None); + }; + let ext4_meta = match (logical_len, capacity) { + (Some(len), Some(cap)) => max_ext4_overhead(len, cap), + _ => 0, + }; + let overhead = match recorded_overhead { + Some(saved) => match disk_host { + // If host allocation minus used data shrank below the saved floor + // (e.g. newly written files reused previously-allocated blocks), + // clamp downward and update the saved floor. + Some(host) => saved.min(host.saturating_sub(raw)), + None => saved, + }, + None => { + // Before the first explicit reclaim records an exact post-FITRIM + // floor: a fresh disk (< 1 GiB of files) has near-zero initialized + // inode tables, whereas a mature populated disk (>= 1 GiB of files) + // has already completed `ext4lazyinit` across its block groups. + if raw >= (1 << 30) { + match disk_host { + Some(host) => ext4_meta.min(host.saturating_sub(raw)), + None => ext4_meta, + } + } else { + 0 + } + } + }; + let clamped_update = recorded_overhead.filter(|&saved| overhead < saved).map(|_| overhead); + (Some(raw.saturating_add(overhead)), clamped_update) +} + +#[cfg(target_os = "linux")] +fn statvfs_usage(path: &Path) -> Option<(u64, u64)> { + use std::os::unix::ffi::OsStrExt; + let c = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?; + // SAFETY: statvfs fills a zeroed struct for a valid NUL-terminated path. + let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 { + return None; + } + let frsize = if s.f_frsize > 0 { s.f_frsize as u64 } else { s.f_bsize as u64 }; + let blocks = s.f_blocks as u64; + let bavail = s.f_bavail as u64; + Some((blocks.saturating_sub(bavail).saturating_mul(frsize), blocks.saturating_mul(frsize))) +} + +#[derive(Default)] +struct DiskInfo { + disk_host: Option, + disk_in_use: Option, + disk_limit: Option, + reclaimable: Option, + #[cfg(target_os = "linux")] + fs_in_use: Option, + #[cfg(target_os = "linux")] + fs_capacity: Option, +} + +fn moving_state() -> std::sync::MutexGuard<'static, Moving> { + MOVE.lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Whether the data is moving: requests that change anything wait. +pub fn moving() -> bool { + ACTIVE.load(Ordering::SeqCst) +} + +/// The refusal while it moves. +pub fn refuse_while_moving(w: &mut UnixStream) -> io::Result<()> { + http::error(w, 503, MOVING_TEXT) +} + +#[cfg(target_os = "macos")] +fn invalidate_used_cache() { + *USED_CACHE.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +/// What the data folder takes, kept 30 s: walking a Linux host's layers +/// takes a while. +fn used(root: &Path) -> u64 { + let mut cached = USED_CACHE.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((p, at, n)) = cached.as_ref() + && p == root + && at.elapsed() < Duration::from_secs(30) + { + return *n; + } + let default = kiri_image::Store::os_default_root().unwrap_or_default(); + let n = treecopy::allocated(root, &["agent"]) + agent_dir(root, &default).map_or(0, |a| treecopy::allocated(&a, &[])); + *cached = Some((root.to_owned(), Instant::now(), n)); + n +} + +/// `GET /kiri/storage`: for the data folder `root`, or for the chosen +/// folder `missing` that isn't there. +fn status(root: &Path, missing: bool) -> Value { + status_with(root, missing, DiskInfo::default()) +} + +fn status_with(root: &Path, missing: bool, disk: DiskInfo) -> Value { + let default = kiri_image::Store::os_default_root().ok(); + let choice = chosen::read().ok().flatten(); + let custom = choice.as_ref().is_some_and(|c| Some(&c.path) != default.as_ref()); + let old = choice.and_then(|c| c.previous).filter(|p| p != root && p.is_dir()); + let active = moving(); + let m = moving_state(); + let near = treecopy::existing_ancestor(root); + let mut out = json!({ + "path": root, + "default": default, + "custom": custom, + "env": std::env::var_os("KIRI_DATA_DIR").is_some(), + "state": if missing { "unavailable" } else if active { "moving" } else { "ok" }, + "used": (!missing && !active).then(|| used(root)), + "free": if missing { None } else { near.and_then(|p| treecopy::free_space(p).ok()) }, + "fs": if missing { None } else { near.and_then(|p| treecopy::fs_name(p).ok()) }, + "disk_host": if missing || active { None } else { disk.disk_host }, + "disk_in_use": if missing || active { None } else { disk.disk_in_use }, + "disk_limit": if missing || active { None } else { disk.disk_limit }, + "reclaimable": if missing || active { None } else { disk.reclaimable }, + "moving": m.to.as_ref().filter(|_| active).map(|to| json!({"to": to, "phase": m.phase, "done": m.done, "total": m.total})), + "error": m.error, + "old": old, + }); + #[cfg(target_os = "linux")] + if !missing && !active { + if let Some(u) = disk.fs_in_use { + out["fs_in_use"] = json!(u); + } + if let Some(c) = disk.fs_capacity { + out["fs_capacity"] = json!(c); + } + } + out +} + +/// `GET /kiri/storage`. +pub fn report(engine: &Engine) -> Value { + let root = engine.store.root(); + #[cfg(target_os = "macos")] + let disk = { + let stats = data_img_stats(root); + let (disk_host, logical_len) = (stats.map(|(a, _)| a), stats.map(|(_, l)| l)); + let (raw_in_use, capacity) = match engine.disk_usage_if_awake() { + Some((in_use, cap)) => { + *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(in_use); + *LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()) = Some(cap); + (Some(in_use), Some(cap)) + } + None => ( + *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()), + *LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()), + ), + }; + let recorded = read_disk_overhead(root); + let (disk_in_use, clamped) = effective_vm_in_use(disk_host, logical_len, raw_in_use, capacity, recorded); + if let Some(updated) = clamped { + write_disk_overhead(root, updated); + } + let disk_limit = Some(super::engine::vm_disk_gb().saturating_mul(1 << 30)); + let reclaimable = reclaimable_bytes(disk_host, disk_in_use); + DiskInfo { disk_host, disk_in_use, disk_limit, reclaimable } + }; + #[cfg(target_os = "linux")] + let disk = { + let probe = Path::new(AGENT_DATA); + let target = if probe.is_dir() { probe } else { root }; + let (fs_in_use, fs_capacity) = match statvfs_usage(target) { + Some((u, c)) => (Some(u), Some(c)), + None => (None, None), + }; + DiskInfo { disk_host: None, disk_in_use: None, disk_limit: None, reclaimable: None, fs_in_use, fs_capacity } + }; + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + let disk = DiskInfo::default(); + status_with(root, false, disk) +} + +/// `POST /kiri/storage/reclaim`: trims unused blocks in the VM data disk and +/// reports host `data.img` allocated bytes before and after. +#[cfg(target_os = "macos")] +pub fn reclaim(engine: &Engine) -> Result { + if RECLAIMING.swap(true, Ordering::SeqCst) { + return Err(Error::Conflict("Disk reclaim is already running".into())); + } + struct Guard; + impl Drop for Guard { + fn drop(&mut self) { + RECLAIMING.store(false, Ordering::SeqCst); + } + } + let _guard = Guard; + let t0 = Instant::now(); + let root = engine.store.root(); + let before = data_img_allocated(root).unwrap_or(0); + let (trimmed, raw_in_use, capacity) = engine.trim_disk().map_err(Error::Io)?; + // Flush pending VirtioBlock DISCARD hole-punches through XNU/APFS before + // sampling `st_blocks` so `after` reflects every reclaimed block immediately. + if let Ok(f) = std::fs::File::open(root.join("vm/data.img")) { + let _ = f.sync_all(); + } + *LAST_IN_USE.lock().unwrap_or_else(|e| e.into_inner()) = Some(raw_in_use); + *LAST_CAPACITY.lock().unwrap_or_else(|e| e.into_inner()) = Some(capacity); + let after = data_img_allocated(root).unwrap_or(0); + let overhead = after.saturating_sub(raw_in_use); + write_disk_overhead(root, overhead); + let in_use = raw_in_use.saturating_add(overhead); + invalidate_used_cache(); + let reclaimed = before.saturating_sub(after); + let elapsed_ms = t0.elapsed().as_millis() as u64; + crate::diag::info!( + "reclaimed VM disk space", + before = before, + after = after, + reclaimed = reclaimed, + trimmed = trimmed, + in_use = in_use, + raw_in_use = raw_in_use, + overhead = overhead, + elapsed_ms = elapsed_ms + ); + Ok(json!({ + "before": before, + "after": after, + "reclaimed": reclaimed, + "in_use": in_use, + "reclaimable": 0, + "elapsed_ms": elapsed_ms, + })) +} + +/// `POST /kiri/storage/reclaim` on native Linux: no VM disk image to trim. +#[cfg(not(target_os = "macos"))] +pub fn reclaim(_engine: &Engine) -> Result { + Ok(json!({ + "before": 0, + "after": 0, + "reclaimed": 0, + "in_use": Value::Null, + "elapsed_ms": 0, + "native": true, + "message": "Native Linux uses the host filesystem directly — deleted images and volumes free space immediately.", + })) +} + +/// The folder a request names (none or empty: the default one), and the +/// parts moving there would copy. +fn plan(root: &Path, requested: Option<&str>) -> Result<(PathBuf, Vec), Error> { + if let Some(dir) = std::env::var_os("KIRI_DATA_DIR") { + return Err(Error::Conflict(format!("KIRI_DATA_DIR sets Kiri's data folder ({}): change it there", Path::new(&dir).display()))); + } + let default = kiri_image::Store::os_default_root()?; + let target: PathBuf = match requested.map(str::trim).filter(|s| !s.is_empty()) { + Some(p) => Path::new(p).components().collect(), + None => default.clone(), + }; + if target == root { + return Err(Error::BadRequest(format!("Kiri's data is already in {}", root.display()))); + } + let parts = parts(root, &target, &default, agent_default()); + Ok((target, parts)) +} + +fn requested(req: &Request) -> Result<(Option, bool), Error> { + if req.body.is_empty() { + return Ok((None, false)); + } + let body: Value = serde_json::from_slice(&req.body).map_err(|e| Error::BadRequest(format!("invalid JSON: {e}")))?; + Ok((body["path"].as_str().map(str::to_owned), body["fresh"].as_bool().unwrap_or(false))) +} + +/// `POST /kiri/storage/check {"path": …, "fresh": …}`: whether the data can move there. +pub fn check_request(req: &Request, engine: &Engine) -> Result { + let (path, fresh) = requested(req)?; + let (target, parts) = plan(engine.store.root(), path.as_deref())?; + let c = check_with(&parts, !fresh).map_err(Error::BadRequest)?; + Ok(json!({"path": target, "needed": c.needed, "free": c.free, "replaces": c.replaces})) +} + +/// `POST /kiri/storage {"path": …, "fresh": …}` (none or empty: back to the +/// default folder): checks the folder, then moves the data there on a thread +/// of its own. `GET /kiri/storage` follows it. +pub fn start(req: &Request, engine: &Arc) -> Result { + let (path, fresh) = requested(req)?; + start_to(path.as_deref(), fresh, engine) +} + +/// `POST /kiri/storage/reset`: the data back to the default folder. +pub fn start_reset(engine: &Arc) -> Result { + start_to(None, false, engine) +} + +fn start_to(requested: Option<&str>, fresh: bool, engine: &Arc) -> Result { + let root = engine.store.root().to_owned(); + let (target, parts) = plan(&root, requested)?; + check_with(&parts, !fresh).map_err(Error::BadRequest)?; + if ACTIVE.swap(true, Ordering::SeqCst) { + return Err(Error::Conflict("Kiri's data is moving already".into())); + } + let total = if fresh { 0 } else { parts.iter().map(|p| treecopy::allocated(&p.from, &p.skip)).sum() }; + *moving_state() = Moving { to: Some(target.clone()), phase: "stopping", done: 0, total, error: None }; + let answer = status(&root, false); + let engine = engine.clone(); + std::thread::Builder::new().name("kiri-storage-move".into()).spawn(move || run_move(&engine, &root, &target, &parts, fresh))?; + Ok(answer) +} + +fn run_move(engine: &Engine, root: &Path, target: &Path, parts: &[Part], fresh: bool) { + crate::diag::info!("moving Kiri's data", from = root.display(), to = target.display(), fresh = fresh); + let fail = |e: String, resume: Option<(Vec, bool)>| { + crate::diag::error!("Kiri's data did not move; it stays where it was", to = target.display(), error = &e); + { + let mut m = moving_state(); + m.to = None; + m.error = Some(e); + } + ACTIVE.store(false, Ordering::SeqCst); + if let Some((running, was_stopped)) = resume { + engine.resume_after_move(was_stopped, running); + } + }; + let (running, was_stopped) = match engine.park_for_move() { + Ok(r) => r, + Err(e) => return fail(format!("the containers did not stop: {e:?}"), None), + }; + // The agent has stopped: a chosen folder's mount at /var/lib/kiri + // comes off, so a move back writes to /var/lib/kiri itself. A move that + // fails leaves storage.json as it was, and the agent mounts it again. + #[cfg(target_os = "linux")] + if kiri_image::Store::os_default_root().is_ok_and(|d| d != root) { + unmount_agent_data(); + } + let config = match chosen::config_path() { + Ok(c) => c, + Err(e) => return fail(e.to_string(), Some((running, was_stopped))), + }; + let choice = Choice { path: target.to_owned(), previous: Some(root.to_owned()) }; + let mut on_step = |phase: &'static str, n: u64| { + let mut m = moving_state(); + if m.phase != phase { + m.phase = phase; + m.done = 0; + } + m.done += n; + Ok(()) + }; + let moved = if fresh { + migrate_fresh(parts, &config, &choice, &mut on_step) + } else { + migrate(parts, &config, &choice, &mut on_step) + }; + if let Err(e) = moved { + return fail(e.to_string(), Some((running, was_stopped))); + } + moving_state().phase = "restarting"; + let restart_ids = if fresh { Vec::new() } else { running }; + crate::diag::info!("Kiri's data moved; the engine starts again on it", to = target.display(), containers = restart_ids.len()); + after_commit(root); + let e = restart(&restart_ids); + crate::diag::error!("the engine did not start again after the move; it exits for launchd or systemd to start it", error = e); + std::process::exit(1); +} + +/// After the commit, before the restart: what still points into the old +/// folder. +fn after_commit(old: &Path) { + // Kiri Lite's docker link and plugin folder are in the data folder. + #[cfg(target_os = "macos")] + if let Err(e) = crate::setup::relink_cli(old) { + crate::diag::warn!("docker's links into the data folder were not updated", error = e); + } + // The old agent data comes out from under the new folder's mount, + // into the old folder, so Remove old data finds it there. + #[cfg(target_os = "linux")] + if kiri_image::Store::os_default_root().is_ok_and(|d| d == old) { + stash_agent_data(old); + } + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + let _ = old; +} + +/// Moves what is in /var/lib/kiri into `/agent`. Only a rename: when +/// they are on different filesystems it stays, under the mount, until a +/// move back. +#[cfg(target_os = "linux")] +fn stash_agent_data(old: &Path) { + let to = old.join("agent"); + let result = (|| -> io::Result<()> { + std::fs::create_dir_all(&to)?; + for e in std::fs::read_dir(AGENT_DATA)? { + let name = e?.file_name(); + if name == MARKER { + continue; + } + std::fs::rename(Path::new(AGENT_DATA).join(&name), to.join(&name))?; + } + let _ = std::fs::remove_file(Path::new(AGENT_DATA).join(MARKER)); + Ok(()) + })(); + if let Err(e) = result { + crate::diag::warn!("the old agent data stays in /var/lib/kiri", error = e); + } +} + +/// Takes a chosen folder's mount off /var/lib/kiri. +#[cfg(target_os = "linux")] +fn unmount_agent_data() { + // SAFETY: a valid NUL-terminated path; MNT_DETACH needs nothing else. + if unsafe { libc::umount2(c"/var/lib/kiri".as_ptr(), libc::MNT_DETACH) } != 0 { + let e = io::Error::last_os_error(); + if e.raw_os_error() != Some(libc::EINVAL) { + crate::diag::warn!("/var/lib/kiri did not unmount", error = e); + } + } +} + +/// Starts this daemon again in its place (the same process, so launchd +/// and systemd keep it), on the data folder storage.json now names, with +/// the containers to start again. Returns only if that failed. +fn restart(running: &[String]) -> io::Error { + use std::os::unix::process::CommandExt; + #[cfg(target_os = "macos")] + super::nfs::unmount(); + if let Ok(socket) = super::socket_path() { + let _ = std::fs::remove_file(&socket); + let _ = std::fs::remove_file(super::caller::container_socket(&socket)); + } + match std::env::current_exe() { + Ok(exe) => { + let mut cmd = std::process::Command::new(exe); + cmd.arg("daemon"); + if running.is_empty() { + cmd.env_remove(RESTART_ENV); + } else { + cmd.env(RESTART_ENV, running.join(",")); + } + cmd.exec() + } + Err(e) => e, + } +} + +/// On the daemon a move started again: the containers that ran before it +/// start again. +pub fn after_restart(engine: &Arc) { + let Ok(list) = std::env::var(RESTART_ENV) else { return }; + let ids: Vec = list.split(',').filter(|s| !s.is_empty()).map(str::to_owned).collect(); + crate::diag::info!("Kiri's data is in its new folder", folder = engine.store.root().display(), containers = ids.len()); + if !ids.is_empty() { + let engine = engine.clone(); + std::thread::spawn(move || engine.start_again(&ids)); + } +} + +/// `DELETE /kiri/storage/old`: removes the folder the data was moved from. +pub fn remove_old(engine: &Engine) -> Result { + if moving() { + return Err(Error::Conflict(MOVING_TEXT.into())); + } + let root = engine.store.root(); + let mut choice = chosen::read()?.ok_or_else(|| Error::Conflict("there is no old data to remove".into()))?; + let old = choice.previous.clone().ok_or_else(|| Error::Conflict("there is no old data to remove".into()))?; + remove_old_folder(&old, root).map_err(Error::Conflict)?; + choice.previous = None; + if kiri_image::Store::os_default_root().is_ok_and(|d| d == choice.path) { + chosen::clear()?; + } else { + chosen::write(&choice)?; + } + Ok(report(engine)) +} + +/// Removes `old`, the folder data moved away from, if it is safe to: not +/// the data folder `root`, not around or inside it, and holding the marker +/// a move leaves. +fn remove_old_folder(old: &Path, root: &Path) -> Result<(), String> { + let (o, r) = (real(old), real(root)); + if o == r || o.starts_with(&r) || r.starts_with(&o) { + return Err(format!("{} holds Kiri's data now", old.display())); + } + if !old.exists() { + return Ok(()); + } + if !chosen::has_marker(old) { + return Err(format!("{} doesn't look like Kiri's old data; remove it yourself if you're sure", old.display())); + } + std::fs::remove_dir_all(old).map_err(|e| format!("{}: {e}", old.display())) +} + +/// The daemon's API while the chosen data folder `missing` isn't there: +/// `GET /kiri/storage` says so, `POST /kiri/storage/retry` starts again +/// once it is back, `POST /kiri/storage/reset` forgets the choice and +/// starts again on the default folder, and `POST /kiri/storage[/check]` +/// lets the user point to another folder (a drive mounted elsewhere, or +/// a fresh folder). Everything else says why it can't. +pub fn serve_unavailable(stream: UnixStream, missing: &Path) -> io::Result<()> { + use std::io::Write as _; + let mut w = stream.try_clone()?; + let mut r = BufReader::new(stream); + let unavailable = chosen::Unavailable(missing.to_owned()).to_string(); + loop { + let req = match http::read_request_with_timeout(&mut r, http::HEADER_TIMEOUT, |_, _| false) { + Ok(Some(req)) => req, + Ok(None) => break, + Err(e) if e.kind() == io::ErrorKind::InvalidData => { + return http::refuse_bad_request(&mut w, &mut r, &e.to_string()).or(Ok(())); + } + Err(e) => return Err(e), + }; + if req.too_large() { + return http::refuse_too_large(&req, &mut w, &mut r).or(Ok(())); + } + http::serving(&req); + match (req.method.as_str(), req.path.as_str()) { + ("GET" | "HEAD", "/_ping") => http::respond(&mut w, 200, "text/plain; charset=utf-8", if req.method == "HEAD" { b"" } else { b"OK" })?, + ("GET", "/version") => http::json(&mut w, 200, &super::api::version().to_string())?, + ("GET", "/kiri/storage") => http::json(&mut w, 200, &status(missing, true).to_string())?, + ("POST", "/kiri/storage/check") => match check_unavailable(&req, missing) { + Ok(v) => http::json(&mut w, 200, &v.to_string())?, + Err(e) => http::error(&mut w, 400, &e)?, + }, + ("POST", "/kiri/storage") => match switch_unavailable(&req, missing) { + Ok(v) => { + http::json(&mut w, 202, &v.to_string())?; + let _ = w.flush(); + restart_soon(); + } + Err(e) => http::error(&mut w, 400, &e)?, + }, + ("POST", "/kiri/storage/retry") if chosen::has_marker(missing) => { + http::empty(&mut w, 204)?; + let _ = w.flush(); + restart_soon(); + } + ("POST", "/kiri/storage/retry") => http::error(&mut w, 409, &unavailable)?, + ("POST", "/kiri/storage/reset") => { + chosen::clear()?; + crate::diag::info!("storage choice forgotten: the engine starts on the default folder", was = missing.display()); + http::empty(&mut w, 204)?; + let _ = w.flush(); + restart_soon(); + } + _ => http::error(&mut w, 503, &unavailable)?, + } + if req.wants_close() || !http::finish_body(&req, &mut r) { + http::close(&w, &mut r); + return Ok(()); + } + } + Ok(()) +} + +/// Restarts the daemon after a brief pause so the HTTP response finishes +/// writing to the client before `exec()` tears down the listening socket. +fn restart_soon() { + std::thread::spawn(|| { + std::thread::sleep(Duration::from_millis(80)); + let _ = restart(&[]); + }); +} + +fn check_unavailable(req: &Request, missing: &Path) -> Result { + let (path, _) = requested(req).map_err(|e| format!("{e:?}"))?; + let (target, parts) = plan(missing, path.as_deref()).map_err(|e| match e { + Error::BadRequest(s) | Error::Conflict(s) => s, + other => format!("{other:?}"), + })?; + let c = check_with(&parts, false)?; + Ok(json!({"path": target, "needed": 0, "free": c.free, "replaces": c.replaces})) +} + +fn switch_unavailable(req: &Request, missing: &Path) -> Result { + let (path, _) = requested(req).map_err(|e| format!("{e:?}"))?; + let (target, parts) = plan(missing, path.as_deref()).map_err(|e| match e { + Error::BadRequest(s) | Error::Conflict(s) => s, + other => format!("{other:?}"), + })?; + check_with(&parts, false)?; + for p in &parts { + std::fs::create_dir_all(&p.to).map_err(|e| format!("{}: {e}", p.to.display()))?; + if !chosen::has_marker(&p.to) { + chosen::write_marker(&p.to).map_err(|e| format!("{}: {e}", p.to.display()))?; + } + } + if kiri_image::Store::os_default_root().is_ok_and(|d| d == target) { + chosen::clear().map_err(|e| e.to_string())?; + } else { + chosen::write(&Choice { path: target.clone(), previous: None }).map_err(|e| e.to_string())?; + } + Ok(status(&target, false)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-storage-move-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.canonicalize().unwrap() + } + + /// A data folder as the daemon leaves it: an image index, a blob, the + /// VM's disk (sparse) and its address. + fn data(root: &Path) { + use sha2::Digest as _; + std::fs::create_dir_all(root.join("blobs/sha256")).unwrap(); + std::fs::create_dir_all(root.join("vm")).unwrap(); + std::fs::write(root.join("images.json"), b"[]").unwrap(); + let hex: String = sha2::Sha256::digest(b"x").iter().map(|b| format!("{b:02x}")).collect(); + std::fs::write(root.join("blobs/sha256").join(hex), b"x").unwrap(); + std::fs::File::create(root.join("vm/data.img")).unwrap().set_len(64 << 20).unwrap(); + std::fs::write(root.join("vm/mac"), b"02:00:00:00:00:01").unwrap(); + } + + fn one(from: &Path, to: &Path) -> Vec { + vec![Part { from: from.to_owned(), to: to.to_owned(), skip: Vec::new() }] + } + + #[test] + fn a_relative_path_is_refused() { + let d = scratch("relative"); + data(&d.join("kiri")); + let e = check(&one(&d.join("kiri"), Path::new("External/kiri"))).unwrap_err(); + assert!(e.contains("isn't a full path"), "{e}"); + let e = check(&one(&d.join("kiri"), &d.join("a/../kiri2"))).unwrap_err(); + assert!(e.contains("isn't a full path"), "{e}"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_folder_inside_the_data_or_around_it_is_refused() { + let d = scratch("nested"); + let root = d.join("kiri"); + data(&root); + let e = check(&one(&root, &root.join("vm/elsewhere"))).unwrap_err(); + assert!(e.contains("is inside Kiri's data folder"), "{e}"); + let e = check(&one(&root, &d)).unwrap_err(); + assert!(e.contains("is inside"), "{e}"); + let e = check(&one(&root, &root)).unwrap_err(); + assert!(e.contains("already in"), "{e}"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn a_folder_with_other_files_is_refused_and_kiri_data_is_replaced() { + let d = scratch("nonempty"); + let root = d.join("kiri"); + data(&root); + let other = d.join("photos"); + std::fs::create_dir_all(&other).unwrap(); + std::fs::write(other.join("cat.jpg"), b"meow").unwrap(); + let e = check(&one(&root, &other)).unwrap_err(); + assert!(e.contains("isn't empty"), "{e}"); + // Empty, or with only what a system puts there: fine. + let empty = d.join("empty"); + std::fs::create_dir_all(&empty).unwrap(); + std::fs::write(empty.join(".DS_Store"), b"").unwrap(); + assert!(!check(&one(&root, &empty)).unwrap().replaces); + // Kiri data from before (the marker): replaced, and said so. + let before = d.join("before"); + data(&before); + chosen::write_marker(&before).unwrap(); + assert!(check(&one(&root, &before)).unwrap().replaces); + let _ = std::fs::remove_dir_all(&d); + } + + /// A move copies the data, puts the marker there and commits the + /// choice; the old folder stays until Remove old data, which then + /// removes it. + #[test] + fn a_move_copies_marks_and_commits() { + let d = scratch("move"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + let mut copied = 0; + migrate(&one(&root, &target), &config, &choice, &mut |phase, n| { + if phase == COPYING { + copied += n; + } + Ok(()) + }) + .unwrap(); + assert_eq!(chosen::read_at(&config).unwrap(), Some(choice)); + assert!(chosen::has_marker(&target) && !target.join(MOVING).exists() && !target.join(REPLACED).exists()); + assert_eq!(std::fs::read(target.join("vm/mac")).unwrap(), b"02:00:00:00:00:01"); + assert!(std::os::unix::fs::MetadataExt::blocks(&std::fs::metadata(target.join("vm/data.img")).unwrap()) * 512 < 1 << 20, "the VM's disk stays sparse"); + assert!(copied < 1 << 20, "only data was copied: {copied}"); + assert!(root.join("images.json").is_file(), "the old folder is kept"); + assert!(remove_old_folder(&target, &target).is_err(), "never the data folder itself"); + remove_old_folder(&root, &target).unwrap(); + assert!(!root.exists()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A copy that fails before the commit leaves the data where it was, + /// storage.json unwritten, and nothing in the folder moved to. + #[test] + fn a_failed_copy_leaves_the_store_where_it_was() { + let d = scratch("fail"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + let before = treecopy::sha256(&root.join("vm/mac")).unwrap(); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + let e = migrate(&one(&root, &target), &config, &choice, &mut |_, _| Err(io::Error::other("the drive went away"))).unwrap_err(); + assert!(e.to_string().contains("went away")); + assert!(!target.join(MOVING).exists() && !target.exists(), "the staging folder and the folder made for it are gone"); + assert_eq!(chosen::read_at(&config).unwrap(), None, "no commit"); + assert_eq!(treecopy::sha256(&root.join("vm/mac")).unwrap(), before); + assert!(root.join("images.json").is_file() && root.join("blobs/sha256").read_dir().unwrap().next().is_some()); + let _ = std::fs::remove_dir_all(&d); + } + + /// A commit that fails (storage.json can't be written) undoes the + /// placing too: Kiri data that was in the folder comes back. + #[test] + fn a_failed_commit_puts_back_what_was_there() { + let d = scratch("commit"); + let (root, target) = (d.join("kiri"), d.join("before")); + data(&root); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("images.json"), b"[\"old\"]").unwrap(); + chosen::write_marker(&target).unwrap(); + // A file where storage.json's folder would be. + std::fs::write(d.join("state"), b"").unwrap(); + let config = d.join("state/storage.json"); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + assert!(migrate(&one(&root, &target), &config, &choice, &mut |_, _| Ok(())).is_err()); + assert_eq!(std::fs::read(target.join("images.json")).unwrap(), b"[\"old\"]"); + assert!(!target.join("vm").exists() && !target.join(REPLACED).exists() && !target.join(MOVING).exists()); + assert!(chosen::has_marker(&target), "it held Kiri data before, and still does"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A Linux host moves the agent's folder too: /var/lib/kiri for the + /// default data folder, `/agent` for a chosen one. + #[test] + fn a_linux_host_moves_the_agent_folder_too() { + let (def, ext, agent) = (Path::new("/var/lib/kiri-daemon/.local/share/kiri"), Path::new("/media/ssd/kiri"), Path::new("/var/lib/kiri")); + let p = parts(def, ext, def, Some(agent)); + assert_eq!(p[0], Part { from: def.into(), to: ext.into(), skip: vec!["agent"] }); + assert_eq!(p[1], Part { from: agent.into(), to: ext.join("agent"), skip: vec![] }); + let back = parts(ext, def, def, Some(agent)); + assert_eq!(back[1], Part { from: ext.join("agent"), to: agent.into(), skip: vec![] }); + assert_eq!(parts(def, ext, def, None), vec![Part { from: def.into(), to: ext.into(), skip: vec![] }]); + } + + /// Starting fresh writes the marker and commits without copying old + /// blobs, while keeping the old folder until Remove old data; a commit + /// failure rolls back cleanly. + #[test] + fn start_fresh_switches_without_copying_and_rolls_back_on_error() { + let d = scratch("fresh"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + migrate_fresh(&one(&root, &target), &config, &choice, &mut |_, _| Ok(())).unwrap(); + assert_eq!(chosen::read_at(&config).unwrap(), Some(choice)); + assert!(chosen::has_marker(&target)); + assert!(!target.join("images.json").exists(), "fresh target has no copied data"); + assert!(chosen::has_marker(&root) && root.join("images.json").is_file(), "old folder kept and marked"); + remove_old_folder(&root, &target).unwrap(); + assert!(!root.exists()); + // Failed commit on an existing fresh target rolls back cleanly. + let target2 = d.join("fresh2"); + std::fs::write(d.join("blocked"), b"").unwrap(); + let bad_cfg = d.join("blocked/storage.json"); + let choice2 = Choice { path: target2.clone(), previous: Some(target.clone()) }; + assert!(migrate_fresh(&one(&target, &target2), &bad_cfg, &choice2, &mut |_, _| Ok(())).is_err()); + assert!(!target2.exists(), "newly made fresh folder is removed on rollback"); + let _ = std::fs::remove_dir_all(&d); + } + + /// Starting fresh in a folder that holds earlier Kiri data sets that data + /// aside; when setting one entry aside fails, the ones already set aside + /// come back. + #[test] + fn start_fresh_failing_partway_brings_back_what_it_set_aside() { + let d = scratch("fresh-partial"); + let (root, target, config) = (d.join("kiri"), d.join("external/kiri"), d.join("state/storage.json")); + data(&root); + data(&target); + // In the order migrate_fresh will meet them. + let names: Vec<_> = std::fs::read_dir(&target).unwrap().map(|e| e.unwrap().file_name()).collect(); + let last = names.last().unwrap(); + // What an interrupted earlier move left set aside under that name. + std::fs::create_dir_all(target.join(REPLACED).join(last).join("left")).unwrap(); + let choice = Choice { path: target.clone(), previous: Some(root.clone()) }; + assert!(migrate_fresh(&one(&root, &target), &config, &choice, &mut |_, _| Ok(())).is_err()); + for n in &names { + assert!(target.join(n).exists(), "{n:?} not brought back"); + } + assert!(!config.exists(), "nothing committed"); + let _ = std::fs::remove_dir_all(&d); + } + + /// A broken symlink or regular file at the target path is refused. + #[test] + fn non_directory_and_broken_symlink_targets_are_refused() { + let d = scratch("nondir"); + let root = d.join("kiri"); + data(&root); + let file = d.join("afile"); + std::fs::write(&file, b"hi").unwrap(); + assert!(check(&one(&root, &file)).unwrap_err().contains("isn't a folder")); + let broken = d.join("broken"); + std::os::unix::fs::symlink(d.join("missing"), &broken).unwrap(); + assert!(check(&one(&root, &broken)).unwrap_err().contains("isn't a folder")); + let _ = std::fs::remove_dir_all(&d); + } + + /// A chosen folder whose drive isn't connected is reported unavailable, + /// with nothing made there. + #[test] + fn a_missing_marker_reports_storage_unavailable() { + let d = scratch("unavailable"); + let gone = d.join("Volumes/External/kiri"); + let e = chosen::resolve(Some(Choice { path: gone.clone(), previous: None }), d.join("default")).unwrap_err(); + assert_eq!(chosen::unavailable(&e), Some(gone.as_path())); + let s = status(&gone, true); + assert_eq!(s["state"], "unavailable"); + assert_eq!(s["path"], gone.to_string_lossy().as_ref()); + assert!(s["used"].is_null() && s["free"].is_null()); + assert!(!gone.exists()); + let _ = std::fs::remove_dir_all(&d); + } + + /// Requests refused with 503 while storage is unavailable record their + /// HTTP method and path on the connection thread so failure logs carry + /// `method=GET path=/containers/json status=503` instead of empty fields. + #[test] + fn serve_unavailable_populates_method_and_path_on_503() { + use std::io::{Read, Write}; + let d = scratch("unavailable-503"); + let gone = d.join("Volumes/External/kiri"); + let (mut client, server) = UnixStream::pair().unwrap(); + client + .write_all(b"GET /v1.47/containers/json HTTP/1.1\r\nHost: docker\r\nConnection: close\r\n\r\n") + .unwrap(); + serve_unavailable(server, &gone).unwrap(); + assert_eq!(http::current_serving(), ("GET".to_owned(), "/containers/json".to_owned())); + let mut resp = String::new(); + client.read_to_string(&mut resp).unwrap(); + assert!(resp.starts_with("HTTP/1.1 503 "), "{resp}"); + assert!(resp.contains("Connection: close\r\n"), "{resp}"); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn reclaimable_threshold_and_data_img_allocated_bytes() { + assert_eq!(reclaimable_bytes(None, Some(100)), None); + assert_eq!(reclaimable_bytes(Some(100), None), None); + assert_eq!(reclaimable_bytes(Some(100), Some(200)), Some(0)); + assert_eq!(reclaimable_bytes(Some(100 + RECLAIM_THRESHOLD), Some(100)), Some(0)); + assert_eq!( + reclaimable_bytes(Some(100 + RECLAIM_THRESHOLD + 1), Some(100)), + Some(RECLAIM_THRESHOLD + 1) + ); + let d = scratch("reclaim-alloc"); + assert_eq!(data_img_allocated(&d), None); + data(&d); + let alloc = data_img_allocated(&d).unwrap(); + assert!(alloc < 1 << 20, "sparse data.img should allocate < 1 MiB, got {alloc}"); + let s = status_with( + &d, + false, + DiskInfo { + disk_host: Some(29_400_000_000), + disk_in_use: Some(17_300_000_000), + disk_limit: Some(64 << 30), + reclaimable: reclaimable_bytes(Some(29_400_000_000), Some(17_300_000_000)), + #[cfg(target_os = "linux")] + fs_in_use: None, + #[cfg(target_os = "linux")] + fs_capacity: None, + }, + ); + assert_eq!(s["disk_host"], 29_400_000_000u64); + assert_eq!(s["disk_in_use"], 17_300_000_000u64); + assert_eq!(s["disk_limit"], 64u64 << 30); + assert_eq!(s["reclaimable"], 12_100_000_000u64); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn ext4_metadata_overhead_is_excluded_from_reclaimable_space() { + // Mature 128 GiB disk (`137.44 GB` logical, `134.15 GB` statvfs capacity -> + // `3.29 GB` ext4 journal + inode table overhead): `104.0 GB` on macOS with + // `98.4 GB` of files promises only the `2.31 GB` that FITRIM can free, and + // reports 0 reclaimable once `101.69 GB` remains after FITRIM. + let logical = 128u64 << 30; + let capacity = logical - 3_290_000_000; + let raw_used = 98_400_000_000u64; + let (in_use_before, clamped) = effective_vm_in_use( + Some(104_000_000_000), + Some(logical), + Some(raw_used), + Some(capacity), + None, + ); + assert_eq!(clamped, None); + assert_eq!(in_use_before, Some(101_690_000_000)); + assert_eq!(reclaimable_bytes(Some(104_000_000_000), in_use_before), Some(2_310_000_000)); + + // After FITRIM leaves `101.69 GB` on host, recorded overhead is `3.29 GB` and reclaimable is 0. + let d = scratch("reclaim-overhead"); + std::fs::create_dir_all(d.join("vm")).unwrap(); + write_disk_overhead(&d, 3_290_000_000); + assert_eq!(read_disk_overhead(&d), Some(3_290_000_000)); + let (in_use_after, _) = effective_vm_in_use( + Some(101_690_000_000), + Some(logical), + Some(raw_used), + Some(capacity), + read_disk_overhead(&d), + ); + assert_eq!(reclaimable_bytes(Some(101_690_000_000), in_use_after), Some(0)); + + // Fresh sparse disk (< 1 GiB of files) before first trim does not over-subtract lazy overhead. + let (fresh_used, _) = effective_vm_in_use( + Some(2_020_000_000), + Some(logical), + Some(20_000_000), + Some(capacity), + None, + ); + assert_eq!(fresh_used, Some(20_000_000)); + assert_eq!(reclaimable_bytes(Some(2_020_000_000), fresh_used), Some(2_000_000_000)); + + // Online-grown un-resized disk (`logical >> capacity`) caps static overhead safely. + assert!(max_ext4_overhead(256 << 30, 64 << 30) <= (4 << 30) + (512 << 20)); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri/src/daemon/time.rs b/crates/kiri/src/daemon/time.rs index 716e41002..addaa28dc 100644 --- a/crates/kiri/src/daemon/time.rs +++ b/crates/kiri/src/daemon/time.rs @@ -215,6 +215,26 @@ fn days_from_civil(y: i64, m: i64, d: i64) -> i64 { era * 146_097 + doe - 719_468 } +/// Docker's wording for how long ago something happened (go-units `HumanDuration`). +/// Seconds and minutes truncate, hours round half up, years count whole hours. +pub fn human_duration(secs: u64) -> String { + let minutes = secs / 60; + let hours = secs / 3600 + u64::from(secs % 3600 >= 1800); + match secs { + 0 => "Less than a second".to_owned(), + 1 => "1 second".to_owned(), + 2..=59 => format!("{secs} seconds"), + _ if minutes == 1 => "About a minute".to_owned(), + _ if minutes < 60 => format!("{minutes} minutes"), + _ if hours == 1 => "About an hour".to_owned(), + _ if hours < 48 => format!("{hours} hours"), + _ if hours < 24 * 7 * 2 => format!("{} days", hours / 24), + _ if hours < 24 * 30 * 2 => format!("{} weeks", hours / 24 / 7), + _ if hours < 24 * 365 * 2 => format!("{} months", hours / 24 / 30), + _ => format!("{} years", secs / 3600 / 24 / 365), + } +} + #[cfg(test)] mod tests { use super::*; @@ -256,4 +276,44 @@ mod tests { assert_eq!(ts(bad), None, "{bad}"); } } + + #[test] + fn status_durations_read_like_docker() { + const H: u64 = 3600; + const D: u64 = 86_400; + for (secs, want) in [ + (0, "Less than a second"), + (1, "1 second"), + (2, "2 seconds"), + (59, "59 seconds"), + (60, "About a minute"), + (119, "About a minute"), + (120, "2 minutes"), + (3599, "59 minutes"), + (H, "About an hour"), + (H + 1799, "About an hour"), + (H + 1800, "2 hours"), + (D - 1, "24 hours"), + (D, "24 hours"), + (47 * H, "47 hours"), + (48 * H - 1801, "47 hours"), + (48 * H - 1800, "2 days"), + (48 * H, "2 days"), + (13 * D, "13 days"), + (14 * D - 1801, "13 days"), + (14 * D - 1800, "2 weeks"), + (14 * D, "2 weeks"), + (60 * D - 1801, "8 weeks"), + (60 * D - 1800, "2 months"), + (60 * D, "2 months"), + (365 * D, "12 months"), + (730 * D - 1801, "24 months"), + (730 * D - 1800, "1 years"), + (730 * D - 1, "1 years"), + (730 * D, "2 years"), + (u64::MAX, "584942417355 years"), + ] { + assert_eq!(human_duration(secs), want, "{secs} s"); + } + } } diff --git a/crates/kiri/src/daemon/tls.rs b/crates/kiri/src/daemon/tls.rs index aa0e12420..d35eab712 100644 --- a/crates/kiri/src/daemon/tls.rs +++ b/crates/kiri/src/daemon/tls.rs @@ -8,7 +8,6 @@ use std::collections::HashMap; use std::io; -use std::ops::Not; use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -62,9 +61,41 @@ fn err(e: rcgen::Error) -> io::Error { io::Error::other(e.to_string()) } +fn valid_ca_der(der: &[u8], key: &KeyPair) -> bool { + if der.len() < 4 || der[0] != 0x30 { + return false; + } + let total = match der[1] { + n if n < 0x80 => 2 + n as usize, + 0x81 => 3 + *der.get(2).unwrap_or(&0) as usize, + 0x82 if der.len() >= 4 => 4 + u16::from_be_bytes([der[2], der[3]]) as usize, + 0x83 if der.len() >= 5 => 5 + u32::from_be_bytes([0, der[2], der[3], der[4]]) as usize, + _ => return false, + }; + let Some(spki) = pem_to_der(&key.public_key_pem()) else { return false }; + total == der.len() && !spki.is_empty() && der.windows(spki.len()).any(|w| w == &*spki) +} + +fn write_private_atomic(path: &std::path::Path, bytes: &[u8]) -> io::Result<()> { + use std::io::Write as _; + use std::os::unix::fs::OpenOptionsExt; + let tmp = path.with_extension("tmp"); + let _ = std::fs::remove_file(&tmp); + std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(&tmp)?.write_all(bytes)?; + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + /// The authority: loaded from `~/.kiri/tls`, or made there the first time. fn authority() -> io::Result<(Issuer<'static, KeyPair>, CertificateDer<'static>)> { let dir = dir().ok_or_else(|| io::Error::other("HOME is not set"))?; + authority_in(&dir) +} + +fn authority_in(dir: &std::path::Path) -> io::Result<(Issuer<'static, KeyPair>, CertificateDer<'static>)> { let (cert_path, key_path) = (dir.join("ca.pem"), dir.join("ca-key.pem")); // The authority's format version: 2 added the exclusion of IP addresses // from its name constraints. An older authority is replaced (the user @@ -72,28 +103,37 @@ fn authority() -> io::Result<(Issuer<'static, KeyPair>, CertificateDer<'static>) // that already had one. const CA_VERSION: &str = "2"; let version_path = dir.join("ca.version"); - if key_path.is_file() && std::fs::read_to_string(&version_path).is_ok_and(|v| v.trim() == CA_VERSION).not() { - let _ = std::fs::remove_file(&key_path); - let _ = std::fs::remove_file(&cert_path); - } - let key = match std::fs::read_to_string(&key_path) { - Ok(pem) if cert_path.is_file() => KeyPair::from_pem(&pem).map_err(err)?, - _ => { - std::fs::create_dir_all(&dir)?; - std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; + let loaded = std::fs::read_to_string(&version_path) + .ok() + .filter(|v| v.trim() == CA_VERSION) + .and_then(|_| std::fs::read_to_string(&key_path).ok()) + .and_then(|pem| KeyPair::from_pem(&pem).ok()) + .and_then(|key| { + let pem = std::fs::read_to_string(&cert_path).ok()?; + let der = pem_to_der(&pem)?; + valid_ca_der(&der, &key).then_some((key, der)) + }); + let (key, der) = match loaded { + Some(pair) => pair, + None => { + std::fs::create_dir_all(dir)?; + std::fs::set_permissions(dir, std::os::unix::fs::PermissionsExt::from_mode(0o700))?; + let _ = std::fs::remove_file(&key_path); + let _ = std::fs::remove_file(&cert_path); + let _ = std::fs::remove_file(&version_path); let key = KeyPair::generate().map_err(err)?; let cert = ca_params().map_err(err)?.self_signed(&key).map_err(err)?; - let tmp = key_path.with_extension("tmp"); - std::fs::write(&tmp, key.serialize_pem())?; - std::fs::set_permissions(&tmp, std::os::unix::fs::PermissionsExt::from_mode(0o600))?; - std::fs::rename(&tmp, &key_path)?; - std::fs::write(&cert_path, cert.pem())?; + let cert_pem = cert.pem(); + let der = pem_to_der(&cert_pem).ok_or_else(|| io::Error::other("ca.pem is not a certificate"))?; + write_private_atomic(&key_path, key.serialize_pem().as_bytes())?; + let cert_tmp = cert_path.with_extension("pem.tmp"); + let _ = std::fs::remove_file(&cert_tmp); + std::fs::write(&cert_tmp, cert_pem)?; + std::fs::rename(&cert_tmp, &cert_path)?; std::fs::write(&version_path, CA_VERSION)?; - key + (key, der) } }; - let pem = std::fs::read_to_string(&cert_path)?; - let der = pem_to_der(&pem).ok_or_else(|| io::Error::other("ca.pem is not a certificate"))?; Ok((Issuer::new(ca_params().map_err(err)?, key), der)) } @@ -117,8 +157,19 @@ fn civil(days: i64) -> (i32, u8, u8) { /// Whether `host` is a name this authority may vouch for. pub fn ours(host: &str) -> bool { - let h = host.trim_end_matches('.').to_ascii_lowercase(); - SUFFIXES.iter().any(|s| h.ends_with(&format!(".{s}"))) && h.split('.').all(|l| !l.is_empty() && l.len() <= 63) + let h = host.strip_suffix('.').unwrap_or(host); + if h.is_empty() || h.len() > 253 { + return false; + } + let h = h.to_ascii_lowercase(); + SUFFIXES.iter().any(|s| h.ends_with(&format!(".{s}"))) + && h.split('.').all(|l| { + !l.is_empty() + && l.len() <= 63 + && !l.starts_with('-') + && !l.ends_with('-') + && l.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + }) } /// Certificates for container names, made on first use and kept while the @@ -431,9 +482,69 @@ mod tests { #[test] fn only_kiri_names() { assert!(super::ours("myapp.kiri.local")); + assert!(super::ours("myapp.kiri.local.")); assert!(super::ours("web.shop.kiri.localhost")); assert!(!super::ours("kiri.local")); assert!(!super::ours("example.com")); assert!(!super::ours("evil.kiri.local.example.com")); + for bad in [ + "*.kiri.local", + "-bad.kiri.local", + "bad-.kiri.local", + "foo/bar.kiri.local", + "myapp.kiri.local..", + &format!("{}.{}.{}.{}.kiri.localhost", "a".repeat(63), "b".repeat(63), "c".repeat(63), "d".repeat(47)), + ] { + assert!(!super::ours(bad), "{bad}"); + } + } + + #[test] + fn authority_regenerates_damaged_or_mismatched_files_privately() { + use std::os::unix::fs::PermissionsExt; + let base = std::env::temp_dir().join(format!("kiri-tls-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&base); + let dir = base.join("tls"); + std::fs::create_dir_all(&dir).unwrap(); + let sentinel = base.join("sentinel.txt"); + std::fs::write(&sentinel, "untouched").unwrap(); + std::os::unix::fs::symlink(&sentinel, dir.join("ca-key.tmp")).unwrap(); + + let (_, first_der) = super::authority_in(&dir).unwrap(); + assert_eq!(std::fs::read_to_string(&sentinel).unwrap(), "untouched"); + assert_eq!(std::fs::metadata(dir.join("ca-key.pem")).unwrap().permissions().mode() & 0o777, 0o600); + let (_, same_der) = super::authority_in(&dir).unwrap(); + assert_eq!(first_der.as_ref(), same_der.as_ref()); + + // Mismatched ca-key.pem with existing ca.pem + ca.version regenerates cleanly. + let other_key = rcgen::KeyPair::generate().unwrap(); + std::fs::write(dir.join("ca-key.pem"), other_key.serialize_pem()).unwrap(); + let (issuer, rotated_der) = super::authority_in(&dir).unwrap(); + assert_ne!(first_der.as_ref(), rotated_der.as_ref()); + + // Verify leaf certificate signed by `issuer` chains validly to `rotated_der`. + let leaf_key = rcgen::KeyPair::generate().unwrap(); + let leaf_params = rcgen::CertificateParams::new(vec!["myapp.kiri.local".into()]).unwrap(); + let leaf = leaf_params.signed_by(&leaf_key, &issuer).unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(rotated_der).unwrap(); + let provider = std::sync::Arc::new(rustls::crypto::ring::default_provider()); + let verifier = rustls::client::WebPkiServerVerifier::builder_with_provider(std::sync::Arc::new(roots), provider).build().unwrap(); + rustls::client::danger::ServerCertVerifier::verify_server_cert( + &*verifier, + leaf.der(), + &[], + &rustls::pki_types::ServerName::try_from("myapp.kiri.local").unwrap(), + &[], + rustls::pki_types::UnixTime::now(), + ) + .unwrap(); + + // Empty ca.pem regenerates cleanly as well. + std::fs::write(dir.join("ca.pem"), "").unwrap(); + let (_, healed_der) = super::authority_in(&dir).unwrap(); + assert!(!healed_der.is_empty()); + + let _ = std::fs::remove_dir_all(&base); } } diff --git a/crates/kiri/src/daemon/treecopy.rs b/crates/kiri/src/daemon/treecopy.rs new file mode 100644 index 000000000..3681a3d76 --- /dev/null +++ b/crates/kiri/src/daemon/treecopy.rs @@ -0,0 +1,582 @@ +//! Copying Kiri's data folder to another place (Settings → Storage). +//! +//! `std::fs::copy` writes a sparse file out whole when it crosses volumes: +//! the VM's 64 GiB `data.img`, of which a few GB hold data, would take all +//! 64 GiB on the new drive. [`copy_sparse`] copies only the file's data +//! (`SEEK_DATA`/`SEEK_HOLE`, or skipping runs of zeros where the system +//! can't say where the holes are), so it stays as small as it was. +//! [`copy_tree`] copies a whole folder that way, keeping what a Linux +//! host's layers need: owners, modes, hard links, device nodes (overlay +//! whiteouts) and extended attributes (`trusted.overlay.opaque`). + +use std::collections::HashMap; +use std::ffi::CString; +use std::fs::{self, File, Metadata, OpenOptions}; +use std::io::{self, Read}; +use std::os::fd::AsRawFd; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::fs::{FileExt, FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +/// How much is read at a time. +const CHUNK: usize = 1 << 20; +/// Zeros are skipped in runs of this size, at this alignment: what is left +/// unwritten stays a hole on any filesystem with blocks up to 64 KiB. +const BLOCK: usize = 64 << 10; + +/// Told the bytes just copied; an error it returns stops the copy. +pub type Progress<'a> = dyn FnMut(u64) -> io::Result<()> + 'a; + +/// Copies the file `src` to `dst`, which must not exist, writing only its +/// data: holes stay holes, and so do runs of zeros. Returns once the copy +/// is on disk. Permissions and owner are the caller's ([`copy_tree`]). +pub fn copy_sparse(src: &Path, dst: &Path, progress: &mut Progress<'_>) -> io::Result<()> { + let from = File::open(src)?; + let len = from.metadata()?.len(); + let to = OpenOptions::new().write(true).create_new(true).mode(0o600).open(dst)?; + let written = match copy_extents(&from, &to, len, progress) { + // No SEEK_DATA here (an older filesystem): every byte is read, and + // the zeros are left out. + Err(e) if unsupported(&e) => { + to.set_len(0)?; + copy_range(&from, &to, 0, len, progress)? + } + r => r?, + }; + finish_sparse(&to, len, &written) +} + +/// Sets `to`'s length to `len`, punches any unwritten gaps on macOS APFS +/// (where `pwrite` + `ftruncate` + `fsync` can otherwise allocate leading +/// or short trailing zero blocks), and syncs to disk. +fn finish_sparse(to: &File, len: u64, written: &[(u64, u64)]) -> io::Result<()> { + to.set_len(len)?; + let mut cursor = 0u64; + for &(start, end) in written { + if start > cursor { + punch_hole(to, cursor, start - cursor); + } + cursor = cursor.max(end); + } + if len > cursor { + punch_hole(to, cursor, len - cursor); + } + to.sync_all() +} + +/// Punches `[offset, offset + len)` as a sparse hole on macOS APFS. +/// Best-effort: filesystems that do not support `F_PUNCHHOLE` ignore it. +#[cfg(target_os = "macos")] +fn punch_hole(f: &File, offset: u64, len: u64) { + let (Ok(offset), Ok(len)) = (libc::off_t::try_from(offset), libc::off_t::try_from(len)) else { return }; + if len <= 0 { + return; + } + let hole = libc::fpunchhole_t { fp_flags: 0, reserved: 0, fp_offset: offset, fp_length: len }; + // SAFETY: `f` is an open writable file descriptor and `hole` matches F_PUNCHHOLE's struct. + unsafe { libc::fcntl(f.as_raw_fd(), libc::F_PUNCHHOLE, &hole) }; +} + +#[cfg(not(target_os = "macos"))] +fn punch_hole(_f: &File, _offset: u64, _len: u64) {} + +fn unsupported(e: &io::Error) -> bool { + let code = e.raw_os_error(); + code == Some(libc::EINVAL) || code == Some(libc::ENOTSUP) || code == Some(libc::EOPNOTSUPP) +} + +/// Copies each run of data `SEEK_DATA` finds. Returns sorted written ranges. +fn copy_extents(from: &File, to: &File, len: u64, progress: &mut Progress<'_>) -> io::Result> { + let mut pos = 0; + let mut written = Vec::new(); + while pos < len { + let data = match seek(from, pos, libc::SEEK_DATA) { + Ok(at) if at < len => at, + Ok(_) => break, + // Only a hole from here to the end. + Err(e) if e.raw_os_error() == Some(libc::ENXIO) => break, + Err(e) => return Err(e), + }; + let hole = seek(from, data, libc::SEEK_HOLE)?.min(len); + if hole <= data { + break; + } + written.extend(copy_range(from, to, data, hole, progress)?); + pos = hole; + } + Ok(written) +} + +fn seek(f: &File, at: u64, whence: libc::c_int) -> io::Result { + let at = libc::off_t::try_from(at).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + // SAFETY: lseek on a descriptor `f` owns; it only moves its offset. + let r = unsafe { libc::lseek(f.as_raw_fd(), at, whence) }; + if r < 0 { Err(io::Error::last_os_error()) } else { Ok(r as u64) } +} + +/// Copies bytes `start..end`, leaving out blocks that are all zeros (the +/// new file reads zeros there anyway). Returns coalesced written ranges. +fn copy_range(from: &File, to: &File, start: u64, end: u64, progress: &mut Progress<'_>) -> io::Result> { + let mut buf = vec![0u8; CHUNK]; + let mut at = start; + let mut written: Vec<(u64, u64)> = Vec::new(); + while at < end { + let want = usize::try_from(end - at).unwrap_or(CHUNK).min(CHUNK); + let n = from.read_at(&mut buf[..want], at)?; + if n == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "the file got shorter while it was copied")); + } + let mut off = 0; + while off < n { + // Up to the next BLOCK boundary of the file, so holes line up. + let file_off = at + off as u64; + let step = (BLOCK - (file_off % BLOCK as u64) as usize).min(n - off); + let piece = &buf[off..off + step]; + if piece.iter().any(|&b| b != 0) { + to.write_all_at(piece, file_off)?; + let piece_end = file_off + step as u64; + match written.last_mut() { + Some((_, last_end)) if *last_end == file_off => *last_end = piece_end, + _ => written.push((file_off, piece_end)), + } + } + off += step; + } + at += n as u64; + progress(n as u64)?; + } + Ok(written) +} + +/// Copies the folder `src` to `dst`, which must not exist, leaving out the +/// entries of `src` named in `skip`. Sockets are left out (whoever listens +/// makes them again). A folder on another filesystem than `src` (something +/// still mounted) stops the copy rather than copying what is mounted there. +pub fn copy_tree(src: &Path, dst: &Path, skip: &[&str], progress: &mut Progress<'_>) -> io::Result<()> { + let meta = fs::symlink_metadata(src)?; + // SAFETY: geteuid cannot fail. + let as_root = unsafe { libc::geteuid() } == 0; + let mut c = Copier { progress, links: HashMap::new(), dev: meta.dev(), as_root }; + fs::create_dir(dst)?; + c.contents(src, dst, skip)?; + c.finish(&meta, src, dst) +} + +struct Copier<'a, 'b> { + progress: &'a mut Progress<'b>, + /// Files with more than one name: the first copy of each, by device + /// and inode, which later names link to. + links: HashMap<(u64, u64), PathBuf>, + dev: u64, + as_root: bool, +} + +impl Copier<'_, '_> { + fn contents(&mut self, src: &Path, dst: &Path, skip: &[&str]) -> io::Result<()> { + for entry in fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + if skip.iter().any(|s| name == *s) { + continue; + } + self.entry(&entry.path(), &dst.join(&name))?; + } + Ok(()) + } + + fn entry(&mut self, src: &Path, dst: &Path) -> io::Result<()> { + let m = fs::symlink_metadata(src)?; + let kind = m.file_type(); + if kind.is_dir() { + if m.dev() != self.dev { + return Err(io::Error::other(format!("{} is a mount point: stop what uses it and try again", src.display()))); + } + fs::create_dir(dst)?; + self.contents(src, dst, &[])?; + } else if kind.is_file() { + if m.nlink() > 1 { + if let Some(first) = self.links.get(&(m.dev(), m.ino())) { + return fs::hard_link(first, dst); + } + self.links.insert((m.dev(), m.ino()), dst.to_owned()); + } + copy_sparse(src, dst, self.progress)?; + } else if kind.is_symlink() { + std::os::unix::fs::symlink(fs::read_link(src)?, dst)?; + } else if kind.is_socket() { + return Ok(()); + } else { + // A FIFO or a device node: an overlay whiteout is a 0/0 one. + let path = c_path(dst)?; + // SAFETY: a valid NUL-terminated path; mode and device as stat gave them. + if unsafe { libc::mknod(path.as_ptr(), m.mode() as libc::mode_t, m.rdev() as libc::dev_t) } != 0 { + return Err(io::Error::last_os_error()); + } + } + self.finish(&m, src, dst) + } + + /// The owner (when copying as root), extended attributes, mode and + /// times of `src` on `dst`. The mode after the owner: a change of + /// owner clears set-user-ID. + fn finish(&self, m: &Metadata, src: &Path, dst: &Path) -> io::Result<()> { + if self.as_root { + std::os::unix::fs::lchown(dst, Some(m.uid()), Some(m.gid()))?; + } + copy_xattrs(src, dst)?; + let link = m.file_type().is_symlink(); + if !link { + fs::set_permissions(dst, fs::Permissions::from_mode(m.mode() & 0o7777))?; + } + let times = [ + libc::timespec { tv_sec: m.atime() as _, tv_nsec: m.atime_nsec() as _ }, + libc::timespec { tv_sec: m.mtime() as _, tv_nsec: m.mtime_nsec() as _ }, + ]; + let path = c_path(dst)?; + // SAFETY: a valid NUL-terminated path and two timespecs. + if unsafe { libc::utimensat(libc::AT_FDCWD, path.as_ptr(), times.as_ptr(), libc::AT_SYMLINK_NOFOLLOW) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } +} + +fn c_path(p: &Path) -> io::Result { + CString::new(p.as_os_str().as_bytes()).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput)) +} + +/// A Linux host's layers keep overlay attributes (`trusted.overlay.*`) +/// and file capabilities (`security.capability`). The SELinux label is the +/// new place's policy's to give. +#[cfg(target_os = "linux")] +fn copy_xattrs(src: &Path, dst: &Path) -> io::Result<()> { + let (s, d) = (c_path(src)?, c_path(dst)?); + // SAFETY: llistxattr with a null buffer asks for the size of the list. + let size = unsafe { libc::llistxattr(s.as_ptr(), std::ptr::null_mut(), 0) }; + if size < 0 { + let e = io::Error::last_os_error(); + return if unsupported(&e) { Ok(()) } else { Err(e) }; + } + if size == 0 { + return Ok(()); + } + let mut names = vec![0u8; size as usize]; + // SAFETY: the buffer is `names.len()` bytes. + let size = unsafe { libc::llistxattr(s.as_ptr(), names.as_mut_ptr().cast(), names.len()) }; + if size < 0 { + return Err(io::Error::last_os_error()); + } + for name in names[..size as usize].split(|&b| b == 0).filter(|n| !n.is_empty() && *n != b"security.selinux") { + let key = CString::new(name).map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; + // SAFETY: a null buffer asks for the value's size. + let len = unsafe { libc::lgetxattr(s.as_ptr(), key.as_ptr(), std::ptr::null_mut(), 0) }; + if len < 0 { + return Err(io::Error::last_os_error()); + } + let mut value = vec![0u8; len as usize]; + // SAFETY: the buffer is `value.len()` bytes. + let len = unsafe { libc::lgetxattr(s.as_ptr(), key.as_ptr(), value.as_mut_ptr().cast(), value.len()) }; + if len < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: valid strings and a buffer of `len` bytes. + if unsafe { libc::lsetxattr(d.as_ptr(), key.as_ptr(), value.as_ptr().cast(), len as usize, 0) } != 0 { + return Err(io::Error::other(format!("{}: {}: {}", dst.display(), String::from_utf8_lossy(name), io::Error::last_os_error()))); + } + } + Ok(()) +} + +/// A Mac's data folder needs none: Finder's and the quarantine's own +/// attributes aren't Kiri's. +#[cfg(not(target_os = "linux"))] +fn copy_xattrs(_src: &Path, _dst: &Path) -> io::Result<()> { + Ok(()) +} + +/// Checks that `dst` holds what `src` does (leaving out `skip` at the top): +/// every file there with the same size, small files with the same bytes, +/// and every blob (`blobs/sha256/`) matching its digest. +pub fn verify_tree(src: &Path, dst: &Path, skip: &[&str], progress: &mut Progress<'_>) -> io::Result<()> { + for entry in fs::read_dir(src)? { + let entry = entry?; + let name = entry.file_name(); + if skip.iter().any(|s| name == *s) { + continue; + } + let (s, d) = (entry.path(), dst.join(&name)); + let m = fs::symlink_metadata(&s)?; + if m.file_type().is_socket() { + // `copy_tree` leaves sockets out. + continue; + } + let differs = |what: &str| io::Error::other(format!("the copy of {} {what}", s.display())); + let got = fs::symlink_metadata(&d).map_err(|_| differs("is missing"))?; + if m.is_dir() { + if !got.is_dir() { + return Err(differs("isn't a folder")); + } + verify_tree(&s, &d, &[], progress)?; + } else if m.is_file() { + if !got.is_file() || got.len() != m.len() { + return Err(differs("has another size")); + } + let blob = s.parent().is_some_and(|p| p.ends_with("blobs/sha256")); + let hex = name.to_str().filter(|n| n.len() == 64 && n.bytes().all(|b| b.is_ascii_hexdigit())); + if let (true, Some(hex)) = (blob, hex) { + if sha256(&d)? != hex { + return Err(differs("doesn't match its digest")); + } + progress(m.len())?; + } else if m.len() <= CHUNK as u64 && fs::read(&s)? != fs::read(&d)? { + return Err(differs("has other contents")); + } + } else if m.file_type().is_symlink() && fs::read_link(&s)? != fs::read_link(&d).map_err(|_| differs("isn't a link"))? { + return Err(differs("points elsewhere")); + } + } + Ok(()) +} + +/// The SHA-256 of a file, in hex. +pub fn sha256(path: &Path) -> io::Result { + use sha2::Digest as _; + let mut f = File::open(path)?; + let mut h = sha2::Sha256::new(); + let mut buf = vec![0u8; CHUNK]; + loop { + let n = f.read(&mut buf)?; + if n == 0 { + break; + } + h.update(&buf[..n]); + } + Ok(h.finalize().iter().map(|b| format!("{b:02x}")).collect()) +} + +/// What the folder `dir` takes on its disk (blocks in use, a hard-linked +/// file once), leaving out `skip` at the top. What can't be read counts as +/// nothing. +pub fn allocated(dir: &Path, skip: &[&str]) -> u64 { + fn walk(dir: &Path, skip: &[&str], dev: u64, seen: &mut std::collections::HashSet<(u64, u64)>) -> u64 { + let Ok(entries) = fs::read_dir(dir) else { return 0 }; + let mut total = 0; + for entry in entries.flatten() { + if skip.iter().any(|s| entry.file_name() == *s) { + continue; + } + let Ok(m) = entry.metadata() else { continue }; + if m.nlink() > 1 && !m.is_dir() && !seen.insert((m.dev(), m.ino())) { + continue; + } + total += m.blocks() * 512; + if m.is_dir() && m.dev() == dev { + total += walk(&entry.path(), &[], dev, seen); + } + } + total + } + let Ok(m) = fs::symlink_metadata(dir) else { return 0 }; + walk(dir, skip, m.dev(), &mut std::collections::HashSet::new()) +} + +/// The nearest folder of `path` that exists: `path` itself, or the one a +/// new folder there would be made in. +pub fn existing_ancestor(path: &Path) -> Option<&Path> { + path.ancestors().find(|p| p.is_dir()) +} + +/// The filesystem's name: `apfs`, `msdos`, `exfat` (macOS's names), or on +/// Linux the name of its magic number when it is one Kiri knows. +pub fn fs_name(path: &Path) -> io::Result { + let c = c_path(path)?; + // SAFETY: statfs is plain data, filled in by the call. + let mut s: libc::statfs = unsafe { std::mem::zeroed() }; + // SAFETY: a valid path and a statfs to fill. + if unsafe { libc::statfs(c.as_ptr(), &mut s) } != 0 { + return Err(io::Error::last_os_error()); + } + #[cfg(target_os = "macos")] + { + // SAFETY: f_fstypename is a NUL-terminated C string the call filled. + Ok(unsafe { std::ffi::CStr::from_ptr(s.f_fstypename.as_ptr()) }.to_string_lossy().into_owned()) + } + #[cfg(not(target_os = "macos"))] + { + Ok(linux_fs_name(s.f_type as u64)) + } +} + +#[cfg(not(target_os = "macos"))] +fn linux_fs_name(magic: u64) -> String { + match magic { + 0xEF53 => "ext4".into(), + 0x5846_5342 => "xfs".into(), + 0x9123_683E => "btrfs".into(), + 0x0102_1994 => "tmpfs".into(), + 0x794C_7630 => "overlay".into(), + 0x2FC1_2FC1 => "zfs".into(), + 0x6969 => "nfs".into(), + 0x4d44 => "msdos".into(), + 0x2011_BAB0 => "exfat".into(), + 0x5346_544E => "ntfs".into(), + 0x6573_5546 => "fuseblk".into(), + m => format!("{m:#x}"), + } +} + +/// FAT and exFAT can't hold Kiri's data: no sparse files (the VM's disk +/// would take its whole 64 GiB, and FAT32 stops at 4 GiB a file), no owners +/// or permissions, no links. +pub fn refused_fs(name: &str) -> bool { + matches!(name, "msdos" | "vfat" | "exfat") +} + +/// Bytes free for this user on the filesystem of `path`. +pub fn free_space(path: &Path) -> io::Result { + let c = c_path(path)?; + // SAFETY: statvfs is plain data, filled in by the call. + let mut s: libc::statvfs = unsafe { std::mem::zeroed() }; + // SAFETY: a valid path and a statvfs to fill. + if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(s.f_bavail as u64 * s.f_frsize as u64) +} + +/// The device a path is on. +pub fn device(path: &Path) -> io::Result { + Ok(fs::metadata(path)?.dev()) +} + +/// Writes a file into `dir`, syncs it and removes it: whether Kiri can +/// really write there (a read-only volume, or one this user may not write). +pub fn probe_writable(dir: &Path) -> io::Result<()> { + let probe = dir.join(format!(".kiri-probe-{}", std::process::id())); + let result = (|| { + let f = OpenOptions::new().write(true).create_new(true).open(&probe)?; + f.write_all_at(b"kiri", 0)?; + f.sync_all() + })(); + let _ = fs::remove_file(&probe); + result +} + +#[cfg(test)] +mod tests { + use super::*; + + fn scratch(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-treecopy-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + fn none(_: u64) -> io::Result<()> { + Ok(()) + } + + /// A 128 MiB file with two 64 KiB islands of data copies byte for byte + /// and stays sparse: well under 2 MiB on disk, not 128 MiB (#355: a + /// 2 GiB file using 16 KB took 2 GiB with std::fs::copy across volumes). + #[test] + fn a_sparse_file_stays_sparse() { + let d = scratch("sparse"); + let (src, dst) = (d.join("data.img"), d.join("copy.img")); + let f = File::create(&src).unwrap(); + f.set_len(128 << 20).unwrap(); + let island: Vec = (0..64 << 10).map(|i: u32| (i % 251) as u8 | 1).collect(); + f.write_all_at(&island, 10 << 20).unwrap(); + f.write_all_at(&island, 100 << 20).unwrap(); + f.sync_all().unwrap(); + drop(f); + let mut copied = 0; + copy_sparse(&src, &dst, &mut |n| { + copied += n; + Ok(()) + }) + .unwrap(); + assert_eq!(sha256(&src).unwrap(), sha256(&dst).unwrap(), "the copy has the same bytes"); + let m = fs::metadata(&dst).unwrap(); + assert_eq!(m.len(), 128 << 20); + assert!(m.blocks() * 512 < 2 << 20, "the copy takes {} bytes on disk, not under 2 MiB", m.blocks() * 512); + assert!(copied < 128 << 20, "only the data was read: {copied} bytes"); + let _ = fs::remove_dir_all(&d); + } + + /// Without SEEK_DATA the zeros are still left out. + #[test] + fn runs_of_zeros_are_left_out() { + let d = scratch("zeros"); + let (src, dst) = (d.join("a"), d.join("b")); + let mut bytes = vec![0u8; 8 << 20]; + bytes[3 << 20] = 7; + fs::write(&src, &bytes).unwrap(); + let (from, to) = (File::open(&src).unwrap(), OpenOptions::new().write(true).create_new(true).open(&dst).unwrap()); + let written = copy_range(&from, &to, 0, bytes.len() as u64, &mut none).unwrap(); + finish_sparse(&to, bytes.len() as u64, &written).unwrap(); + assert_eq!(fs::read(&dst).unwrap(), bytes); + assert!(fs::metadata(&dst).unwrap().blocks() * 512 < 1 << 20); + let _ = fs::remove_dir_all(&d); + } + + /// A folder comes over whole: files, links, modes, a hard link as one + /// file, and nothing of what `skip` names; the check passes, and finds + /// a changed blob. + #[test] + fn a_folder_copies_and_checks_whole() { + let d = scratch("tree"); + let src = d.join("src"); + let hex = sha256_of(b"layer"); + fs::create_dir_all(src.join("blobs/sha256")).unwrap(); + fs::create_dir_all(src.join("vm")).unwrap(); + fs::write(src.join("blobs/sha256").join(&hex), b"layer").unwrap(); + fs::write(src.join("images.json"), b"[]").unwrap(); + fs::write(src.join("vm/mac"), b"02:00:00:00:00:01").unwrap(); + fs::set_permissions(src.join("vm/mac"), fs::Permissions::from_mode(0o640)).unwrap(); + fs::hard_link(src.join("images.json"), src.join("images.link")).unwrap(); + std::os::unix::fs::symlink("images.json", src.join("current")).unwrap(); + fs::create_dir_all(src.join(".kiri-moving")).unwrap(); + let dst = d.join("dst"); + copy_tree(&src, &dst, &[".kiri-moving"], &mut none).unwrap(); + assert_eq!(fs::read(dst.join("blobs/sha256").join(&hex)).unwrap(), b"layer"); + assert_eq!(fs::metadata(dst.join("vm/mac")).unwrap().permissions().mode() & 0o777, 0o640); + assert_eq!(fs::metadata(dst.join("images.json")).unwrap().ino(), fs::metadata(dst.join("images.link")).unwrap().ino()); + assert_eq!(fs::read_link(dst.join("current")).unwrap(), Path::new("images.json")); + assert!(!dst.join(".kiri-moving").exists()); + verify_tree(&src, &dst, &[".kiri-moving"], &mut none).unwrap(); + fs::write(dst.join("blobs/sha256").join(&hex), b"LAYER").unwrap(); + assert!(verify_tree(&src, &dst, &[".kiri-moving"], &mut none).unwrap_err().to_string().contains("digest")); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn a_socket_is_left_out_of_the_copy_and_its_check() { + let d = scratch("socket"); + let src = d.join("src"); + fs::create_dir_all(src.join("run")).unwrap(); + fs::write(src.join("images.json"), b"[]").unwrap(); + let _listening = std::os::unix::net::UnixListener::bind(src.join("run/app.sock")).unwrap(); + let dst = d.join("dst"); + copy_tree(&src, &dst, &[], &mut none).unwrap(); + assert!(fs::symlink_metadata(dst.join("run/app.sock")).is_err()); + verify_tree(&src, &dst, &[], &mut none).unwrap(); + fs::remove_file(dst.join("images.json")).unwrap(); + assert!(verify_tree(&src, &dst, &[], &mut none).unwrap_err().to_string().contains("missing")); + let _ = fs::remove_dir_all(&d); + } + + fn sha256_of(b: &[u8]) -> String { + use sha2::Digest as _; + sha2::Sha256::digest(b).iter().map(|x| format!("{x:02x}")).collect() + } + + #[test] + fn fat_and_exfat_are_refused() { + assert!(refused_fs("msdos") && refused_fs("exfat") && refused_fs("vfat")); + assert!(!refused_fs("apfs") && !refused_fs("ext4")); + #[cfg(not(target_os = "macos"))] + assert_eq!((linux_fs_name(0x4d44), linux_fs_name(0x2011_BAB0)), ("msdos".to_owned(), "exfat".to_owned())); + } +} diff --git a/crates/kiri/src/daemon/vmlink.rs b/crates/kiri/src/daemon/vmlink.rs index e2e81ea18..fb2bc8974 100644 --- a/crates/kiri/src/daemon/vmlink.rs +++ b/crates/kiri/src/daemon/vmlink.rs @@ -10,7 +10,7 @@ use std::collections::{HashMap, VecDeque}; use std::fs::File; -use std::io::{self, Read, Write}; +use std::io::{self, Read}; use std::path::Path; use std::sync::mpsc::{self, SyncSender}; use std::sync::{Arc, Condvar, Mutex}; @@ -37,6 +37,8 @@ pub enum Reply { Listening(Vec), UsbNodes(Vec), Uplink([u8; 4], [u8; 4]), + DiskUsage { in_use: u64, capacity: u64 }, + DiskTrimmed { trimmed: u64, in_use: u64, capacity: u64 }, Error(String), } @@ -63,28 +65,27 @@ pub enum Event<'a> { Output { id: &'a str, stream: Stream, data: &'a [u8] }, /// `oom` when the kernel killed a process in it for memory. Exited { id: &'a str, code: i32, oom: bool }, - /// The guest is short of memory right now. - Pressure, + /// The guest is short of memory right now, and what it can see: the + /// readings that go with a memory kill. + Pressure { mem_available_kib: u64, mem_stall: u64 }, /// The connection is gone: the VM stopped. Lost, } +const WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +const FAST_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); +const LONG_CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(600); + pub struct VmLink { - writer: Mutex, - /// Stdin credit per running process; see `input`. - windows: Arc, - /// The guest's latest `Usage` lines, for `usage`. - usage: Arc, - pending: Arc>>>, + rpc: Channel, + /// Layer digests confirmed unpacked in this guest instance, avoiding + /// repeated `LayerQuery` round-trips across `create` and `start`. + layers: Mutex>, /// Kept so the VM lives as long as the link. Behind a mutex only so the /// link can be shared between threads; nothing touches it after boot. _vm: Mutex, /// Opens vsock streams without that mutex, so connects run side by side. connector: kiri_vmm::Connector, - /// A copy of the connection, shut down when the agent process exits - /// (see `new`); only while the link lives. - #[cfg(target_os = "linux")] - _stop_conn: Arc, /// The agent's folder on a Linux host, where it leaves what `docker /// info` should warn about (`host_warnings`). #[cfg(target_os = "linux")] @@ -97,13 +98,74 @@ impl std::fmt::Debug for VmLink { } } +/// Transport state and reader loop for the single guest control stream, +/// separated from `kiri_vmm::Vm` so socket timeout and FIFO loss invariants +/// can be unit-tested over a `UnixStream` pair. +struct Channel { + writer: Mutex, + /// Duplicate of the stream socket used to `shutdown(SHUT_RDWR)` without + /// acquiring `writer` when a call times out or (on Linux) the agent exits. + abort_conn: Arc, + /// Stdin credit per running process; see `input`. + windows: Arc, + /// The guest's latest `Usage` lines, for `usage`. + usage: Arc, + pending: Arc>>>, + fast_timeout: std::time::Duration, + long_timeout: std::time::Duration, + /// Count of long RPCs (`send_layer`, `run`, `AwaitStart`, `trim_disk`) + /// currently in flight so concurrent fast RPCs queued behind them on the + /// single-threaded guest do not time out prematurely. + long_in_flight: std::sync::atomic::AtomicUsize, +} + +struct LongCallGuard<'a>(&'a std::sync::atomic::AtomicUsize); + +impl Drop for LongCallGuard<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, std::sync::atomic::Ordering::Release); + } +} + struct Writer { conn: File, out: Vec, blob: Vec, + write_timeout: std::time::Duration, } impl Writer { + fn new(conn: File, write_timeout: std::time::Duration) -> Writer { + use std::os::fd::AsRawFd; + let fd = conn.as_raw_fd(); + // SAFETY: setting O_NONBLOCK on the stream socket so `write_all_timeout` + // never blocks indefinitely in the kernel (macOS XNU ignores MSG_DONTWAIT + // on blocking AF_UNIX/AF_VSOCK sockets); `read_frame` polls POLLIN on + // the reader's dup. + unsafe { + let flags = libc::fcntl(fd, libc::F_GETFL); + if flags >= 0 { + libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK); + } + } + #[cfg(target_os = "macos")] + { + let one: libc::c_int = 1; + // SAFETY: sets SO_NOSIGPIPE on a descriptor we own so writes return + // EPIPE instead of raising SIGPIPE when the peer is gone. + unsafe { + libc::setsockopt( + fd, + libc::SOL_SOCKET, + libc::SO_NOSIGPIPE, + (&one as *const libc::c_int).cast(), + std::mem::size_of::() as libc::socklen_t, + ); + } + } + Writer { conn, out: Vec::with_capacity(4096), blob: vec![0; 256 * 1024], write_timeout } + } + /// Whether the encoded request is within the agent's frame limit: one /// over it ends the agent, and every container with it, so it fails /// here alone, before anything is queued or sent. @@ -129,7 +191,9 @@ impl Writer { } fn write_request(&mut self, body: Option<(File, u64)>) -> io::Result<()> { - self.conn.write_all(&self.out)?; + use std::os::fd::AsRawFd; + let fd = self.conn.as_raw_fd(); + write_all_timeout(fd, &self.out, self.write_timeout)?; if let Some((mut file, size)) = body { let mut left = size; while left > 0 { @@ -138,7 +202,7 @@ impl Writer { if n == 0 { return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "layer blob shrank while sending")); } - self.conn.write_all(&self.blob[..n])?; + write_all_timeout(fd, &self.blob[..n], self.write_timeout)?; left -= n as u64; } } @@ -146,6 +210,68 @@ impl Writer { } } +/// Writes `buf` to non-blocking stream socket `fd`, bounding any single stall +/// with `chunk_timeout` so `Writer`'s mutex can never be held forever when the +/// guest agent wedges (#948). +fn write_all_timeout(fd: std::os::fd::RawFd, mut buf: &[u8], chunk_timeout: std::time::Duration) -> io::Result<()> { + let mut deadline = std::time::Instant::now() + chunk_timeout; + let mut polled_would_block = false; + while !buf.is_empty() { + let step = buf.len().min(64 * 1024); + #[cfg(target_os = "linux")] + // SAFETY: `fd` is a live stream socket owned by `Writer`; `buf` is valid. + let n = unsafe { libc::send(fd, buf.as_ptr().cast(), step, libc::MSG_NOSIGNAL) }; + #[cfg(not(target_os = "linux"))] + // SAFETY: `fd` is a live non-blocking socket owned by `Writer`; `buf` is valid. + let n = unsafe { libc::write(fd, buf.as_ptr().cast(), step) }; + if n > 0 { + buf = &buf[n as usize..]; + polled_would_block = false; + if !buf.is_empty() { + deadline = std::time::Instant::now() + chunk_timeout; + } + continue; + } + if n == 0 { + return Err(io::Error::new(io::ErrorKind::WriteZero, "failed to write whole buffer")); + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::Interrupted => continue, + io::ErrorKind::WouldBlock => { + let now = std::time::Instant::now(); + if now >= deadline { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out writing to guest agent")); + } + if polled_would_block { + std::thread::sleep((deadline - now).min(std::time::Duration::from_millis(1))); + } + let timeout_ms = deadline + .saturating_duration_since(std::time::Instant::now()) + .as_micros() + .div_ceil(1000) + .min(i32::MAX as u128) as i32; + let mut pfd = libc::pollfd { fd, events: libc::POLLOUT, revents: 0 }; + // SAFETY: one valid pollfd. + let ready = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; + if ready == 0 { + return Err(io::Error::new(io::ErrorKind::TimedOut, "timed out writing to guest agent")); + } + if ready < 0 { + let pe = io::Error::last_os_error(); + if pe.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(pe); + } + polled_would_block = true; + } + _ => return Err(e), + } + } + Ok(()) +} + /// How much stdin each running process may still be sent before the guest /// reports some of it consumed. An entry exists from `run`/`exec` until /// `Exited`; `input` for a process without one is discarded. @@ -227,21 +353,17 @@ struct UsageSlot { arrived: Condvar, } -impl VmLink { - pub fn is_lost(&self) -> bool { - self.windows.is_lost() - } - - /// Observes disconnection without waiting for the reader's cleanup. - pub fn is_disconnected(&self) -> bool { - self.windows.lock().lost - } - - /// Starts the reader thread. `on_event` runs on that thread, so it must - /// not block for long: it holds up every reply behind it. - pub fn new(vm: Vm, conn: File, on_event: impl Fn(Event<'_>) + Send + 'static) -> io::Result { +impl Channel { + fn new( + conn: File, + write_timeout: std::time::Duration, + fast_timeout: std::time::Duration, + long_timeout: std::time::Duration, + on_event: impl Fn(Event<'_>) + Send + 'static, + ) -> io::Result { let pending: Arc>>> = Arc::new(Mutex::new(VecDeque::new())); let mut reader = conn.try_clone()?; + let abort_conn = Arc::new(conn.try_clone()?); let queue = pending.clone(); let windows = Arc::new(Windows::default()); let wins = windows.clone(); @@ -275,8 +397,8 @@ impl VmLink { wins.add(id, bytes as usize); continue; } - Ok(Msg::MemoryPressure) => { - on_event(Event::Pressure); + Ok(Msg::MemoryPressure(p)) => { + on_event(Event::Pressure { mem_available_kib: p.mem_available_kib, mem_stall: p.mem_stall }); continue; } Ok(Msg::LayerStatus(have)) => Reply::LayerStatus(have), @@ -297,6 +419,8 @@ impl VmLink { Ok(Msg::Listening(lines)) => Reply::Listening(lines.iter().map(str::to_owned).collect()), Ok(Msg::UsbNodes(lines)) => Reply::UsbNodes(lines.iter().map(str::to_owned).collect()), Ok(Msg::Uplink { ip, gateway }) => Reply::Uplink(ip, gateway), + Ok(Msg::DiskUsage { in_use, capacity }) => Reply::DiskUsage { in_use, capacity }, + Ok(Msg::DiskTrimmed { trimmed, in_use, capacity }) => Reply::DiskTrimmed { trimmed, in_use, capacity }, Ok(Msg::Error(e)) => Reply::Error(e.to_owned()), Ok(other) => Reply::Error(format!("unexpected message from guest: {other:?}")), Err(e) => Reply::Error(format!("bad frame from guest: {e:?}")), @@ -314,47 +438,47 @@ impl VmLink { on_event(Event::Lost); wins.finish_loss(); })?; - // On a Linux host the connection is a socket the agent process - // shares with its children: one that hung before closing its copy - // kept it open after the agent was gone, so the reader never saw - // the end, nothing waiting for a reply ever got one, and the agent - // was never restarted. Its exit ends the connection here instead. - // (A VM's vsock ends with the VM.) - #[cfg(target_os = "linux")] - let stop_conn = { - let stop_conn = Arc::new(conn.try_clone()?); - let weak = Arc::downgrade(&stop_conn); - vm.on_stop(Box::new(move || { - if let Some(c) = weak.upgrade() { - use std::os::fd::AsRawFd; - // SAFETY: shutdown on a socket this link still owns. - unsafe { libc::shutdown(c.as_raw_fd(), libc::SHUT_RDWR) }; - } - })); - stop_conn - }; - Ok(VmLink { - #[cfg(target_os = "linux")] - _stop_conn: stop_conn, - #[cfg(target_os = "linux")] - agent_dir: vm.agent_dir().to_owned(), - writer: Mutex::new(Writer { conn, out: Vec::with_capacity(4096), blob: vec![0; 256 * 1024] }), - pending, + Ok(Channel { + writer: Mutex::new(Writer::new(conn, write_timeout)), + abort_conn, windows, usage, - connector: vm.connector(), - _vm: Mutex::new(vm), + pending, + fast_timeout, + long_timeout, + long_in_flight: std::sync::atomic::AtomicUsize::new(0), }) } - /// Sends one request and waits for its reply. - /// A body is opened by the caller, before anything is sent: a blob that - /// can't be read fails this call alone, not the connection (a request - /// cut off after its header can't be taken back, and loses the VM). - fn call(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + /// Marks the link lost and shuts down the socket without locking `writer`, + /// waking `kiri-vm-reader` (and any stalled writer) so `pending` drains and + /// `Event::Lost` fires. + fn disconnect(&self) { + self.windows.lose(); + use std::os::fd::AsRawFd; + // SAFETY: `abort_conn` owns a live stream socket for the lifetime of `Channel`. + unsafe { + libc::shutdown(self.abort_conn.as_raw_fd(), libc::SHUT_RDWR); + } + } + + fn call_with( + &self, + timeout: std::time::Duration, + is_long: bool, + encode: impl FnOnce(&mut Vec), + body: Option<(File, u64)>, + ) -> io::Result { + let _long = is_long.then(|| { + self.long_in_flight.fetch_add(1, std::sync::atomic::Ordering::AcqRel); + LongCallGuard(&self.long_in_flight) + }); let (tx, rx) = mpsc::sync_channel(1); { let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner()); + if self.windows.lock().lost { + return Err(io::Error::other("the VM stopped")); + } w.out.clear(); encode(&mut w.out); // Too large: refused before a reply slot is queued for it. @@ -369,35 +493,133 @@ impl VmLink { } w.write(&self.windows, body)?; } - match rx.recv() { - Ok(Reply::Error(e)) => Err(io::Error::other(e)), - Ok(r) => Ok(r), - Err(_) => Err(io::Error::other("the VM stopped")), + let began = std::time::Instant::now(); + let mut deadline = began + timeout; + loop { + let wait = deadline.saturating_duration_since(std::time::Instant::now()); + match rx.recv_timeout(wait) { + Ok(Reply::Error(e)) => return Err(io::Error::other(e)), + Ok(r) => return Ok(r), + Err(mpsc::RecvTimeoutError::Disconnected) => return Err(io::Error::other("the VM stopped")), + Err(mpsc::RecvTimeoutError::Timeout) => { + let extended = began + self.long_timeout; + if !is_long + && self.long_in_flight.load(std::sync::atomic::Ordering::Acquire) > 0 + && std::time::Instant::now() < extended + { + deadline = deadline.max(extended); + continue; + } + // `pending` is a positional FIFO: never leave the stream + // open after abandoning a reply slot (#948). + self.disconnect(); + return Err(io::Error::new(io::ErrorKind::TimedOut, "guest agent timed out")); + } + } } } - /// Sends a message that has no reply. + fn call(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.call_with(self.fast_timeout, false, encode, body) + } + + fn call_long(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.call_with(self.long_timeout, true, encode, body) + } + fn send(&self, encode: impl FnOnce(&mut Vec)) -> io::Result<()> { let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner()); + if self.windows.lock().lost { + return Err(io::Error::other("the VM stopped")); + } w.out.clear(); encode(&mut w.out); w.write(&self.windows, None) } +} + +impl VmLink { + pub fn is_lost(&self) -> bool { + self.rpc.windows.is_lost() + } + + /// Observes disconnection without waiting for the reader's cleanup. + pub fn is_disconnected(&self) -> bool { + self.rpc.windows.lock().lost + } + + /// Starts the reader thread. `on_event` runs on that thread, so it must + /// not block for long: it holds up every reply behind it. + pub fn new(vm: Vm, conn: File, on_event: impl Fn(Event<'_>) + Send + 'static) -> io::Result { + let rpc = Channel::new(conn, WRITE_TIMEOUT, FAST_CALL_TIMEOUT, LONG_CALL_TIMEOUT, on_event)?; + // On a Linux host the connection is a socket the agent process + // shares with its children: one that hung before closing its copy + // kept it open after the agent was gone, so the reader never saw + // the end, nothing waiting for a reply ever got one, and the agent + // was never restarted. Its exit ends the connection here instead. + // (A VM's vsock ends with the VM.) + #[cfg(target_os = "linux")] + { + let weak = Arc::downgrade(&rpc.abort_conn); + vm.on_stop(Box::new(move || { + if let Some(c) = weak.upgrade() { + use std::os::fd::AsRawFd; + // SAFETY: shutdown on a socket this link still owns. + unsafe { libc::shutdown(c.as_raw_fd(), libc::SHUT_RDWR) }; + } + })); + } + Ok(VmLink { + #[cfg(target_os = "linux")] + agent_dir: vm.agent_dir().to_owned(), + rpc, + layers: Mutex::new(std::collections::HashSet::new()), + connector: vm.connector(), + _vm: Mutex::new(vm), + }) + } + + /// Sends one fast request and waits up to `FAST_CALL_TIMEOUT` for its reply. + /// A body is opened by the caller, before anything is sent: a blob that + /// can't be read fails this call alone, not the connection (a request + /// cut off after its header can't be taken back, and loses the VM). + fn call(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.rpc.call(encode, body) + } + + /// Sends a potentially long-running request (`send_layer`, `run`, + /// `AwaitStart`, `trim_disk`) with `LONG_CALL_TIMEOUT`. + fn call_long(&self, encode: impl FnOnce(&mut Vec), body: Option<(File, u64)>) -> io::Result { + self.rpc.call_long(encode, body) + } + + /// Sends a message that has no reply. + fn send(&self, encode: impl FnOnce(&mut Vec)) -> io::Result<()> { + self.rpc.send(encode) + } /// What the guest's layers, containers and volumes take on disk: the /// `KIND NAME BYTES` lines of `Msg::Usage`, or None if they don't come /// within `wait` or the VM stops. pub fn usage(&self, wait: std::time::Duration) -> Option> { - let asked = self.usage.lines.lock().unwrap_or_else(|e| e.into_inner()).0; + let asked = self.rpc.usage.lines.lock().unwrap_or_else(|e| e.into_inner()).0; self.send(|o| Msg::UsageQuery.encode(o)).ok()?; - let g = self.usage.lines.lock().unwrap_or_else(|e| e.into_inner()); - let (g, _) = self.usage.arrived.wait_timeout_while(g, wait, |g| g.0 == asked).unwrap_or_else(|e| e.into_inner()); + let g = self.rpc.usage.lines.lock().unwrap_or_else(|e| e.into_inner()); + let (g, _) = self.rpc.usage.arrived.wait_timeout_while(g, wait, |g| g.0 == asked).unwrap_or_else(|e| e.into_inner()); if g.0 == asked { None } else { g.1.clone() } } pub fn has_layer(&self, digest: &str) -> io::Result { + if self.layers.lock().unwrap_or_else(|e| e.into_inner()).contains(digest) { + return Ok(true); + } match self.call(|o| Msg::LayerQuery(digest).encode(o), None)? { - Reply::LayerStatus(have) => Ok(have), + Reply::LayerStatus(have) => { + if have { + self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned()); + } + Ok(have) + } other => Err(io::Error::other(format!("expected LayerStatus, got {other:?}"))), } } @@ -407,8 +629,9 @@ impl VmLink { // fails here rather than half-way through the request. let file = File::open(blob)?; let size = file.metadata()?.len(); - self.call(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size))) - .map(drop) + self.call_long(|o| Msg::LayerBegin(LayerBegin { digest, media_type, size }).encode(o), Some((file, size)))?; + self.layers.lock().unwrap_or_else(|e| e.into_inner()).insert(digest.to_owned()); + Ok(()) } #[allow(clippy::too_many_arguments)] @@ -430,13 +653,13 @@ impl VmLink { seccomp: &[u8], cancel: &std::sync::atomic::AtomicBool, ) -> io::Result { - self.windows.open(id); + self.rpc.windows.open(id); // Its process runs, but its root may not be in place yet (a new // volume is being filled): the agent answered at once rather than // stall every other container meanwhile. The start is reported only // once an exec can enter it (#311), or fails as a start. let r = self - .call(|o| kiri_proto::encode_run(o, id, layers, argv, env, cwd, user, hostname, flags, net, mounts, limits, caps, opts, seccomp), None) + .call_long(|o| kiri_proto::encode_run(o, id, layers, argv, env, cwd, user, hostname, flags, net, mounts, limits, caps, opts, seccomp), None) .and_then(started) .and_then(|(pid, starting)| { if starting { @@ -449,14 +672,14 @@ impl VmLink { told = true; self.cancel_start(id)?; } - self.call(|o| Msg::AwaitStart { id }.encode(o), None) + self.call_long(|o| Msg::AwaitStart { id }.encode(o), None) }; wait_started(ask, std::thread::sleep)?; } Ok(pid) }); if r.is_err() { - self.windows.close(id); + self.rpc.windows.close(id); } r } @@ -536,10 +759,10 @@ impl VmLink { #[allow(clippy::too_many_arguments)] pub fn exec(&self, container_id: &str, exec_id: &str, argv: &[String], env: &[String], cwd: &str, user: &str, flags: u32, caps: u64, opts: &[String]) -> io::Result { - self.windows.open(exec_id); + self.rpc.windows.open(exec_id); let r = self.call(|o| kiri_proto::encode_exec(o, container_id, exec_id, argv, env, cwd, user, flags, caps, opts), None).and_then(started).map(|(pid, _)| pid); if r.is_err() { - self.windows.close(exec_id); + self.rpc.windows.close(exec_id); } r } @@ -550,7 +773,7 @@ impl VmLink { pub fn input(&self, id: &str, data: &[u8]) -> io::Result<()> { // Frames are bounded, so large writes go in pieces. for piece in data.chunks(kiri_proto::MAX_OUTPUT_CHUNK) { - if !self.windows.take(id, piece.len())? { + if !self.rpc.windows.take(id, piece.len())? { return Ok(()); } self.send(|o| Msg::Input { id, data: piece }.encode(o))?; @@ -576,6 +799,12 @@ impl VmLink { } } + /// Configures the VM's uplink (`eth0`) directly when macOS DHCP did not + /// answer. Ignored by the guest if it already obtained a DHCP lease. + pub fn set_uplink(&self, ip: [u8; 4], prefix: u8, gateway: [u8; 4], dns: [u8; 4]) -> io::Result<()> { + self.ack(|o| Msg::SetUplink { ip, prefix, gateway, dns }.encode(o)) + } + /// Forwards a published port in the kernel (on a Linux host; in the VM, /// from the NAT network). `Err` means the agent could not; the caller /// falls back to relaying. @@ -607,6 +836,12 @@ impl VmLink { self.send(|o| kiri_proto::encode_fs_events(o, lines)) } + /// Sets the IPv4 CIDR prefixes (`a.b.c.d/prefix`) whose outbound container + /// TCP connections the guest redirects to the host egress dialer. No reply. + pub fn set_egress_routes>(&self, routes: &[S]) -> io::Result<()> { + self.send(|o| kiri_proto::encode_set_egress_routes(o, routes)) + } + /// The Mac's wall clock, for the guest. Sent at boot, and again while it /// runs: the VM's clock stops while the Mac sleeps. pub fn set_time(&self) -> io::Result<()> { @@ -619,11 +854,34 @@ impl VmLink { self.send(|o| kiri_proto::encode_retain(o, ids)) } + /// Evicts `digests` from the in-memory unpacked-layer cache so the next + /// `has_layer` asks the guest directly (used when `run` reports a layer + /// missing on disk inside a running guest). + pub fn forget_layers(&self, digests: &[String]) { + let mut cached = self.layers.lock().unwrap_or_else(|e| e.into_inner()); + for d in digests { + cached.remove(d.as_str()); + } + } + /// Tells the guest which unpacked layers are still used; it deletes the rest. pub fn retain_layers(&self, digests: &[String]) -> io::Result<()> { + { + let keep: std::collections::HashSet<&str> = digests.iter().map(String::as_str).collect(); + self.layers.lock().unwrap_or_else(|e| e.into_inner()).retain(|d| keep.contains(d.as_str())); + } self.send(|o| kiri_proto::encode_retain_layers(o, digests)) } + /// Waits for every earlier no-reply frame (such as `retain_layers`) to + /// finish on the guest: the agent processes frames in order. + pub fn ping(&self) -> io::Result<()> { + match self.call(|o| Msg::Ping(0).encode(o), None)? { + Reply::Pong => Ok(()), + other => Err(io::Error::other(format!("expected Pong, got {other:?}"))), + } + } + pub fn kill(&self, id: &str, signal: u32) -> io::Result<()> { self.send(|o| Msg::Kill { id, signal }.encode(o)) } @@ -674,6 +932,13 @@ impl VmLink { } } + pub fn fs_read_link(&self, id: &str, path: &str) -> io::Result> { + match self.call(|o| Msg::FsReadLink { id, path }.encode(o), None)? { + Reply::FsData(d) => Ok(d), + other => Err(io::Error::other(format!("expected FsData, got {other:?}"))), + } + } + pub fn stats(&self) -> io::Result { match self.call(|o| Msg::StatsRequest.encode(o), None)? { Reply::Stats(s) => Ok(s), @@ -681,6 +946,20 @@ impl VmLink { } } + pub fn disk_usage(&self) -> io::Result<(u64, u64)> { + match self.call(|o| Msg::DiskUsageQuery.encode(o), None)? { + Reply::DiskUsage { in_use, capacity } => Ok((in_use, capacity)), + other => Err(io::Error::other(format!("expected DiskUsage, got {other:?}"))), + } + } + + pub fn trim_disk(&self) -> io::Result<(u64, u64, u64)> { + match self.call_long(|o| Msg::TrimDisk.encode(o), None)? { + Reply::DiskTrimmed { trimmed, in_use, capacity } => Ok((trimmed, in_use, capacity)), + other => Err(io::Error::other(format!("expected DiskTrimmed, got {other:?}"))), + } + } + /// What the agent on a Linux host found wrong with the host for `docker /// info`: a firewall that drops the containers' traffic and that Kiri /// may not change (an nftables.conf's chain), with the rules that let @@ -777,13 +1056,46 @@ fn wait_started(mut ask: impl FnMut() -> io::Result, mut sleep: impl FnMu unreachable!("the backoff never ends") } +fn read_exact_blocking(fd: std::os::fd::RawFd, mut buf: &mut [u8]) -> io::Result<()> { + while !buf.is_empty() { + // SAFETY: `fd` is a valid descriptor and `buf` is owned mutable memory. + let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), buf.len()) }; + if n > 0 { + buf = &mut buf[n as usize..]; + continue; + } + if n == 0 { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "failed to fill whole buffer")); + } + let e = io::Error::last_os_error(); + match e.kind() { + io::ErrorKind::Interrupted => continue, + io::ErrorKind::WouldBlock => { + let mut pfd = libc::pollfd { fd, events: libc::POLLIN, revents: 0 }; + // SAFETY: one valid pollfd; wakes on incoming bytes or SHUT_RDWR/EOF. + let ready = unsafe { libc::poll(&mut pfd, 1, -1) }; + if ready < 0 { + let pe = io::Error::last_os_error(); + if pe.kind() != io::ErrorKind::Interrupted { + return Err(pe); + } + } + } + _ => return Err(e), + } + } + Ok(()) +} + fn read_frame(conn: &mut File, buf: &mut Vec) -> io::Result<()> { + use std::os::fd::AsRawFd; + let fd = conn.as_raw_fd(); buf.resize(4, 0); - conn.read_exact(&mut buf[..4])?; + read_exact_blocking(fd, &mut buf[..4])?; let len = kiri_proto::frame_len(buf[..4].try_into().expect("4 bytes")) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{e:?}")))?; buf.resize(len.max(HEADER), 0); - conn.read_exact(&mut buf[4..]) + read_exact_blocking(fd, &mut buf[4..]) } #[cfg(test)] @@ -813,7 +1125,8 @@ mod tests { fn a_failed_write_disconnects_before_the_reader_accounts_loss() { let (socket, peer) = UnixStream::pair().unwrap(); socket.shutdown(std::net::Shutdown::Write).unwrap(); - let mut writer = Writer { conn: std::os::fd::OwnedFd::from(socket).into(), out: vec![1], blob: vec![0; 16] }; + let mut writer = Writer::new(std::os::fd::OwnedFd::from(socket).into(), std::time::Duration::from_millis(50)); + writer.out = vec![1]; let windows = Windows::default(); assert!(writer.write(&windows, None).is_err()); assert!(windows.lock().lost, "a writer failure must publish loss before a start can record an ordinary failure"); @@ -832,7 +1145,8 @@ mod tests { // Never blocks on a peer that does not read: a request that were // sent fills the socket and fails with WouldBlock instead. socket.set_nonblocking(true).unwrap(); - let mut writer = Writer { conn: std::os::fd::OwnedFd::from(socket).into(), out: vec![0; kiri_proto::MAX_FRAME + 1], blob: vec![0; 16] }; + let mut writer = Writer::new(std::os::fd::OwnedFd::from(socket).into(), std::time::Duration::from_millis(50)); + writer.out = vec![0; kiri_proto::MAX_FRAME + 1]; let windows = Windows::default(); let e = writer.write(&windows, None).unwrap_err(); assert!(e.to_string().contains("too large"), "{e}"); @@ -850,9 +1164,139 @@ mod tests { #[test] fn a_request_at_the_agents_frame_limit_fits() { let (socket, _peer) = UnixStream::pair().unwrap(); - let mut writer = Writer { conn: std::os::fd::OwnedFd::from(socket).into(), out: vec![0; kiri_proto::MAX_FRAME], blob: vec![0; 16] }; + let mut writer = Writer::new(std::os::fd::OwnedFd::from(socket).into(), std::time::Duration::from_millis(50)); + writer.out = vec![0; kiri_proto::MAX_FRAME]; assert!(writer.fits().is_ok()); writer.out.push(0); assert!(writer.fits().is_err()); } + + /// Regression test for #948(a): when the peer reads a request frame and + /// never replies, `call` times out instead of blocking forever, shuts down + /// the socket (preserving the positional `pending` FIFO invariant), marks + /// `windows.lost`, wakes `kiri-vm-reader` to emit `Event::Lost`, and wakes + /// any concurrent callers without deadlocking. + #[test] + fn wedged_peer_that_never_replies_times_out_and_closes_transport() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::{Duration, Instant}; + + let (socket, peer) = UnixStream::pair().unwrap(); + let mut peer_file: File = std::os::fd::OwnedFd::from(peer).into(); + let lost_events = Arc::new(AtomicUsize::new(0)); + let lost_events_cb = lost_events.clone(); + let channel = Arc::new( + Channel::new( + std::os::fd::OwnedFd::from(socket).into(), + Duration::from_millis(200), + Duration::from_millis(60), + Duration::from_millis(250), + move |ev| { + if matches!(ev, Event::Lost) { + lost_events_cb.fetch_add(1, Ordering::SeqCst); + } + }, + ) + .unwrap(), + ); + + let reader_peer = std::thread::spawn(move || { + let mut frame = Vec::new(); + read_frame(&mut peer_file, &mut frame).unwrap(); + assert!(matches!(kiri_proto::decode(&frame), Ok(Msg::Ping(0)))); + let mut sink = [0u8; 64]; + while peer_file.read(&mut sink).unwrap() > 0 {} + }); + + let ch2 = channel.clone(); + let second = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(10)); + ch2.call_with(Duration::from_secs(5), false, |o| Msg::StatsRequest.encode(o), None) + }); + + let began = Instant::now(); + let err = channel.call(|o| Msg::Ping(0).encode(o), None).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}"); + assert!(began.elapsed() < Duration::from_secs(2)); + assert!(channel.windows.lock().lost, "timeout must mark windows.lost immediately"); + + let second_err = second.join().unwrap().unwrap_err(); + assert!( + second_err.to_string().contains("the VM stopped"), + "second caller woken by pending drain without waiting 5s: {second_err}" + ); + assert!(began.elapsed() < Duration::from_secs(2)); + reader_peer.join().unwrap(); + assert!(channel.windows.is_lost(), "reader finished loss accounting without deadlock"); + assert_eq!(lost_events.load(Ordering::SeqCst), 1, "Event::Lost emitted exactly once"); + } + + /// Regression test for #948(b): when the socket send buffer is full and + /// the peer never reads, `Writer::write` fails within `write_timeout` + /// instead of holding `Channel::writer` mutex forever and piling up + /// hundreds of `kiri-api` threads. + #[test] + fn full_socket_buffer_times_out_write_and_releases_writer_mutex() { + use std::time::{Duration, Instant}; + + let (socket, _peer) = UnixStream::pair().unwrap(); + let channel = Arc::new( + Channel::new( + std::os::fd::OwnedFd::from(socket).into(), + Duration::from_millis(50), + Duration::from_millis(200), + Duration::from_millis(400), + |_| {}, + ) + .unwrap(), + ); + + { + use std::os::fd::AsRawFd; + let fd = channel.abort_conn.as_raw_fd(); + let chunk = [0xabu8; 4096]; + loop { + // SAFETY: valid buffer and non-blocking stream socket fd. + let n = unsafe { libc::write(fd, chunk.as_ptr().cast(), chunk.len()) }; + if n <= 0 { + break; + } + } + } + + let ch2 = channel.clone(); + let contender = std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(10)); + ch2.send(|o| Msg::Ping(1).encode(o)) + }); + + let began = Instant::now(); + let big = vec![b'x'; 256 * 1024]; + let err = channel.send(|o| Msg::Input { id: "c1", data: &big }.encode(o)).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::TimedOut, "{err}"); + assert!(began.elapsed() < Duration::from_secs(2), "writer mutex released promptly"); + assert!(channel.windows.lock().lost, "stalled write marks link lost"); + + let contender_err = contender.join().unwrap().unwrap_err(); + assert!(contender_err.to_string().contains("the VM stopped") || contender_err.kind() == io::ErrorKind::TimedOut, "{contender_err}"); + assert!(channel.windows.is_lost(), "reader exited after SHUT_RDWR"); + } + + #[test] + fn forget_layers_evicts_only_requested_digests() { + let layers = Mutex::new(std::collections::HashSet::from([ + "sha256:aaa".to_owned(), + "sha256:bbb".to_owned(), + "sha256:ccc".to_owned(), + ])); + { + let mut cached = layers.lock().unwrap(); + for d in &["sha256:aaa".to_owned(), "sha256:ccc".to_owned()] { + cached.remove(d.as_str()); + } + } + let left = layers.into_inner().unwrap(); + assert_eq!(left.len(), 1); + assert!(left.contains("sha256:bbb")); + } } diff --git a/crates/kiri/src/daemon/vmnet.rs b/crates/kiri/src/daemon/vmnet.rs new file mode 100644 index 000000000..951ea4273 --- /dev/null +++ b/crates/kiri/src/daemon/vmnet.rs @@ -0,0 +1,328 @@ +//! macOS `vmnet` (`VZNATNetworkDeviceAttachment`) network discovery and IP +//! selection for the VM uplink fallback (#435). + +#![cfg_attr(not(target_os = "macos"), allow(dead_code))] + +use std::collections::HashSet; +use std::net::Ipv4Addr; +use std::path::Path; + +/// A host bridge interface serving Apple's shared NAT network (`bridge100`, …). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Bridge { + pub name: String, + pub gateway: [u8; 4], + pub prefix: u8, +} + +pub fn mask_to_prefix(mask: [u8; 4]) -> Option { + let bits = u32::from_be_bytes(mask); + let ones = bits.leading_ones(); + ((1..=30).contains(&ones) && bits == (u32::MAX << (32 - ones))).then_some(ones as u8) +} + +fn mask_from_prefix(prefix: u8) -> u32 { + if prefix == 0 { 0 } else { u32::MAX << (32 - u32::from(prefix)) } +} + +fn parse_ipv4(s: &str) -> Option<[u8; 4]> { + s.trim().parse::().ok().map(|a| a.octets()) +} + +pub fn parse_mac(s: &str) -> Option<[u8; 6]> { + let mut mac = [0u8; 6]; + let mut parts = s.trim().split(':'); + for b in &mut mac { + let p = parts.next().filter(|p| !p.is_empty() && p.len() <= 2)?; + *b = u8::from_str_radix(p, 16).ok()?; + } + parts.next().is_none().then_some(mac) +} + +fn usable_gateway(ip: [u8; 4]) -> bool { + ip != [0; 4] && ip[0] != 127 && !(ip[0] == 169 && ip[1] == 254) +} + +/// Extracts `Shared_Net_Address` and `Shared_Net_Mask` from `com.apple.vmnet.plist`. +pub fn parse_vmnet_plist(xml: &str) -> Option<([u8; 4], u8)> { + let val = |k: &str| { + let after = xml.split_once(&format!("{k}"))?.1.trim_start(); + after.strip_prefix("")?.split_once("").map(|(v, _)| v.trim()).filter(|v| !v.is_empty()) + }; + let addr = parse_ipv4(val("Shared_Net_Address")?).filter(|&a| usable_gateway(a))?; + let prefix = match val("Shared_Net_Mask") { + Some(m) => mask_to_prefix(parse_ipv4(m)?)?, + None => 24, + }; + let (mask, raw) = (mask_from_prefix(prefix), u32::from_be_bytes(addr)); + Some((if raw & !mask == 0 { (raw | 1).to_be_bytes() } else { addr }, prefix)) +} + +/// Parses macOS `/var/db/dhcpd_leases` blocks into `(ip, mac)` pairs. +pub fn parse_dhcpd_leases(text: &str) -> Vec<([u8; 4], Option<[u8; 6]>)> { + let (mut out, mut in_block, mut ip, mut mac) = (Vec::new(), false, None, None); + for raw in text.lines() { + match raw.trim() { + "{" => (in_block, ip, mac) = (true, None, None), + "}" => { + if in_block && let Some(a) = ip.take() { + out.push((a, mac)); + } + in_block = false; + } + line if in_block => match line.split_once('=') { + Some((k, v)) if k.trim() == "ip_address" => ip = parse_ipv4(v), + Some((k, v)) if k.trim() == "hw_address" => mac = parse_mac(v.trim().split_once(',').map_or(v.trim(), |(_, r)| r)), + _ => {} + }, + _ => {} + } + } + out +} + +/// Parses `netstat -anv -p udp` or `-p tcp` output for listeners bound to `port`. +pub fn parse_netstat_listeners(netstat: &str, port: u16, udp: bool) -> Vec<(Option, u32)> { + let suffix = format!(".{port}"); + let (mut out, mut pid_col) = (Vec::new(), None); + for line in netstat.lines().map(str::trim).filter(|l| !l.is_empty()) { + if let Some((_, after)) = line.split_once("(state)") { + pid_col = after.split_whitespace().position(|c| c == "pid" || c == "process:pid"); + continue; + } + let f: Vec<&str> = line.split_whitespace().collect(); + let proto_ok = if udp { + matches!(f.first().copied(), Some("udp4" | "udp46" | "udp6")) + } else { + matches!(f.first().copied(), Some("tcp4" | "tcp46" | "tcp6")) && f.get(5) == Some(&"LISTEN") + }; + if !proto_ok || f.len() < if udp { 6 } else { 7 } || !f[3].ends_with(&suffix) { + continue; + } + let named = |t: &str| { + let (n, p) = t.rsplit_once(':')?; + (!n.is_empty() && !n.starts_with("0x") && !n.contains(':')).then(|| p.parse::().ok().filter(|&p| p > 0))?.map(|p| (Some(n.to_owned()), p)) + }; + let tail = if udp { &f[5..] } else { &f[6..] }; + let entry = pid_col + .and_then(|i| tail.get(i).copied()) + .and_then(|t| named(t).or_else(|| t.parse::().ok().filter(|&p| p > 0).map(|p| (None, p)))) + .or_else(|| tail.iter().copied().find_map(named)); + if let Some(e) = entry && !out.contains(&e) { + out.push(e); + } + } + out +} + +/// Parses `netstat -anv -p udp` output for listeners bound to UDP port 67. +pub fn parse_udp67_listeners(netstat: &str) -> Vec<(Option, u32)> { + parse_netstat_listeners(netstat, 67, true) +} + +/// Picks the host bridge backing Apple's shared NAT network (`bridge100+`). +pub fn pick_bridge(ifaces: &[Bridge], plist: Option<([u8; 4], u8)>) -> Option { + let num = |n: &str| n.strip_prefix("bridge")?.parse::().ok(); + let valid: Vec<&Bridge> = ifaces.iter().filter(|b| b.name.starts_with("bridge") && (8..=30).contains(&b.prefix) && usable_gateway(b.gateway)).collect(); + if let Some((p_gw, p_prefix)) = plist { + let p_mask = mask_from_prefix(p_prefix); + let p_net = u32::from_be_bytes(p_gw) & p_mask; + if let Some(b) = valid.iter().copied().filter(|b| (u32::from_be_bytes(b.gateway) & p_mask) == p_net).min_by_key(|b| (b.name != "bridge100", num(&b.name).unwrap_or(u32::MAX))) { + return Some(b.clone()); + } + } + valid + .into_iter() + .filter(|b| num(&b.name).is_some_and(|n| n >= 100)) + .min_by_key(|b| (b.name != "bridge100", num(&b.name).unwrap_or(u32::MAX))) + .cloned() + .or_else(|| plist.map(|(gateway, prefix)| Bridge { name: "bridge100".into(), gateway, prefix })) +} + +/// Picks an IPv4 host address inside `gateway/prefix` avoiding the network, +/// gateway, broadcast, and other hosts' leases in `/var/db/dhcpd_leases`. +pub fn pick_ip(gateway: [u8; 4], prefix: u8, our_mac: Option<[u8; 6]>, leases: &[([u8; 4], Option<[u8; 6]>)]) -> Option<[u8; 4]> { + if !(1..=30).contains(&prefix) || !usable_gateway(gateway) { + return None; + } + let (mask, gw) = (mask_from_prefix(prefix), u32::from_be_bytes(gateway)); + let (net, bcast) = (gw & mask, (gw & mask) | !mask); + let in_sub = |ip: [u8; 4]| { + let v = u32::from_be_bytes(ip); + v > net && v < bcast && v != gw + }; + let other: HashSet<[u8; 4]> = leases.iter().filter(|&&(ip, mac)| in_sub(ip) && (our_mac.is_none() || mac != our_mac)).map(|&(ip, _)| ip).collect(); + if let Some(m) = our_mac + && let Some(&(ip, _)) = leases.iter().find(|&&(ip, mac)| mac == Some(m) && in_sub(ip) && !other.contains(&ip)) + { + return Some(ip); + } + ((net + 1)..bcast).filter(|&h| h != gw).map(u32::to_be_bytes).find(|ip| !other.contains(ip)) +} + +pub fn format_udp67_summary(listeners: &[(Option, u32)]) -> Option { + let mut items: Vec<(bool, String)> = Vec::new(); + for (name, pid) in listeners { + let label = name.as_ref().map_or_else(|| format!("pid {pid}"), |n| format!("{n} (pid {pid})")); + let sys = name.as_deref().is_some_and(|n| matches!(n, "bootpd" | "launchd")); + if !items.iter().any(|(_, s)| s == &label) { + items.push((sys, label)); + } + } + items.sort_by_key(|(sys, _)| *sys); + (!items.is_empty()).then(|| items.into_iter().map(|(_, s)| s).collect::>().join(", ")) +} + +/// Extracts the IPv4 octets (`sin_addr`, bytes `4..8` of BSD `sockaddr_in`) +/// from a raw BSD `sockaddr` slice (`raw[0] == sa_len`), zero-padding +/// truncated netmasks (`sa_len` 5..8 on macOS) without reading past `sa_len`. +pub fn parse_bsd_sockaddr_ipv4(raw: &[u8], min_len: usize) -> Option<[u8; 4]> { + let len = usize::from(*raw.first()?).min(raw.len()); + if len < min_len || len <= 4 { + return None; + } + let mut out = [0u8; 4]; + let n = (len - 4).min(4); + out[..n].copy_from_slice(&raw[4..4 + n]); + Some(out) +} + +#[cfg(target_os = "macos")] +unsafe fn sockaddr_ipv4(sa: *const libc::sockaddr, min_len: usize) -> Option<[u8; 4]> { + if sa.is_null() { + return None; + } + let len = usize::from(unsafe { (*sa).sa_len }); + // SAFETY: `getifaddrs` allocates at least `sa_len` bytes at `sa`. + parse_bsd_sockaddr_ipv4(unsafe { std::slice::from_raw_parts(sa as *const u8, len) }, min_len) +} + +#[cfg(target_os = "macos")] +fn live_bridges() -> Vec { + let mut list: *mut libc::ifaddrs = std::ptr::null_mut(); + // SAFETY: getifaddrs fills `list`, freed below; entries are read only while it lives. + if unsafe { libc::getifaddrs(&mut list) } != 0 { + return Vec::new(); + } + let (mut out, mut p) = (Vec::new(), list); + while let Some(ifa) = unsafe { p.as_ref() } { + let up = (ifa.ifa_flags as i32) & libc::IFF_UP != 0; + if up && !ifa.ifa_name.is_null() && !ifa.ifa_addr.is_null() && i32::from(unsafe { (*ifa.ifa_addr).sa_family }) == libc::AF_INET { + let name = unsafe { std::ffi::CStr::from_ptr(ifa.ifa_name) }.to_string_lossy().into_owned(); + if name.starts_with("bridge") + && let (Some(gateway), Some(mask)) = (unsafe { sockaddr_ipv4(ifa.ifa_addr, 8) }, unsafe { sockaddr_ipv4(ifa.ifa_netmask, 5) }) + && let Some(prefix) = mask_to_prefix(mask) + { + out.push(Bridge { name, gateway, prefix }); + } + } + p = ifa.ifa_next; + } + // SAFETY: freed once for the list returned by getifaddrs. + unsafe { libc::freeifaddrs(list) }; + out +} + +#[cfg(target_os = "macos")] +pub fn current_bridge() -> Option { + let plist = std::fs::read_to_string("/Library/Preferences/SystemConfiguration/com.apple.vmnet.plist").ok().and_then(|s| parse_vmnet_plist(&s)); + pick_bridge(&live_bridges(), plist) +} + +#[cfg(not(target_os = "macos"))] +pub fn current_bridge() -> Option { + None +} + +#[cfg(target_os = "macos")] +pub fn discover_uplink(store_root: &Path) -> Result<(Bridge, [u8; 4]), String> { + let bridge = current_bridge().ok_or_else(|| "no macOS vmnet bridge interface (bridge100) found".to_owned())?; + let vm_mac = std::fs::read_to_string(store_root.join("vm/mac")).ok().and_then(|s| parse_mac(&s)); + let leases = std::fs::read_to_string("/var/db/dhcpd_leases").map(|t| parse_dhcpd_leases(&t)).unwrap_or_default(); + let ip = pick_ip(bridge.gateway, bridge.prefix, vm_mac, &leases) + .ok_or_else(|| format!("no free IPv4 address left on {} ({}/{})", bridge.name, Ipv4Addr::from(bridge.gateway), bridge.prefix))?; + Ok((bridge, ip)) +} + +#[cfg(not(target_os = "macos"))] +pub fn discover_uplink(_store_root: &Path) -> Result<(Bridge, [u8; 4]), String> { + Err("vmnet uplink discovery is only available on macOS".into()) +} + +#[cfg(target_os = "macos")] +pub fn process_name(pid: u32) -> Option { + std::process::Command::new("/bin/ps") + .args(["-p", &pid.to_string(), "-o", "comm="]) + .stderr(std::process::Stdio::null()) + .output() + .ok() + .and_then(|o| { + let raw = String::from_utf8_lossy(&o.stdout).trim().to_owned(); + (!raw.is_empty()).then(|| Path::new(&raw).file_name().and_then(|f| f.to_str()).unwrap_or(&raw).to_owned()) + }) +} + +#[cfg(target_os = "macos")] +pub fn udp67_holder() -> Option { + let out = std::process::Command::new("/usr/sbin/netstat").args(["-anv", "-p", "udp"]).stderr(std::process::Stdio::null()).output().ok()?; + let mut listeners = parse_udp67_listeners(&String::from_utf8_lossy(&out.stdout)); + for (name, pid) in &mut listeners { + if name.is_none() { + *name = process_name(*pid); + } + } + format_udp67_summary(&listeners) +} + +#[cfg(not(target_os = "macos"))] +pub fn udp67_holder() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_vmnet_plist_and_picks_bridge() { + let xml = "Shared_Net_Address192.168.64.1Shared_Net_Mask255.255.255.0"; + assert_eq!(parse_vmnet_plist(xml), Some(([192, 168, 64, 1], 24))); + assert_eq!(parse_vmnet_plist("Shared_Net_Address10.20.30.0"), Some(([10, 20, 30, 1], 24))); + assert_eq!(parse_vmnet_plist("Shared_Net_Address127.0.0.1"), None); + let (tb, b100, b101) = ( + Bridge { name: "bridge0".into(), gateway: [10, 0, 0, 1], prefix: 24 }, + Bridge { name: "bridge100".into(), gateway: [192, 168, 64, 1], prefix: 24 }, + Bridge { name: "bridge101".into(), gateway: [192, 168, 65, 1], prefix: 24 }, + ); + assert_eq!(pick_bridge(&[tb.clone(), b101.clone(), b100.clone()], None), Some(b100.clone())); + assert_eq!(pick_bridge(std::slice::from_ref(&tb), None), None); + assert_eq!(pick_bridge(&[b100, b101.clone()], Some(([192, 168, 65, 1], 24))), Some(b101)); + } + + #[test] + fn parses_leases_and_picks_collision_free_ip() { + let leases = parse_dhcpd_leases("{\n\tip_address=192.168.64.2\n\thw_address=1,2:48:44:4d:d8:13\n}\n{\n\tip_address=192.168.64.28\n\thw_address=1,f6:49:47:3e:68:51\n}\n"); + let our_mac = [0xf6, 0x49, 0x47, 0x3e, 0x68, 0x51]; + assert_eq!(pick_ip([192, 168, 64, 1], 24, Some(our_mac), &leases), Some([192, 168, 64, 28])); + assert_eq!(pick_ip([192, 168, 64, 1], 24, None, &leases[..1]), Some([192, 168, 64, 3])); + assert_eq!(pick_ip([192, 168, 64, 1], 30, None, &leases[..1]), None); + } + + #[test] + fn parses_udp67_listeners_from_netstat() { + let netstat = "Proto Recv-Q Send-Q Local Address Foreign Address (state) rhiwat shiwat process:pid state\n\ + udp4 0 0 *.67 *.* 786896 9216 kavd:412 0x0000\n\ + udp4 0 0 192.168.64.1.67 *.* 786896 9216 bootpd:510 0x0000\n"; + assert_eq!(format_udp67_summary(&parse_udp67_listeners(netstat)).as_deref(), Some("kavd (pid 412), bootpd (pid 510)")); + } + + #[test] + fn decodes_truncated_bsd_netmask_sockaddrs() { + assert_eq!(parse_bsd_sockaddr_ipv4(&[4, 2, 0, 0], 5), None); + assert_eq!(parse_bsd_sockaddr_ipv4(&[7, 2, 0, 0, 255, 255, 255], 8), None); + assert_eq!(parse_bsd_sockaddr_ipv4(&[5, 2, 0, 0, 255], 5).and_then(mask_to_prefix), Some(8)); + assert_eq!(parse_bsd_sockaddr_ipv4(&[7, 2, 0, 0, 255, 255, 255], 5).and_then(mask_to_prefix), Some(24)); + assert_eq!(parse_bsd_sockaddr_ipv4(&[8, 2, 0, 0, 255, 255, 255, 252], 5).and_then(mask_to_prefix), Some(30)); + assert_eq!(parse_bsd_sockaddr_ipv4(&[16, 2, 0, 0, 192, 168, 64, 1, 0, 0, 0, 0, 0, 0, 0, 0], 8), Some([192, 168, 64, 1])); + } +} diff --git a/crates/kiri/src/daemon/volumes.rs b/crates/kiri/src/daemon/volumes.rs index 4ddf78f01..7ccad2097 100644 --- a/crates/kiri/src/daemon/volumes.rs +++ b/crates/kiri/src/daemon/volumes.rs @@ -82,6 +82,10 @@ impl Volumes { if let Some(v) = self.get(name) { return Ok(v.clone()); } + // Docker's local driver refuses a new one-character name. + if name.len() == 1 { + return Err("volume name is too short, names should be at least two alphanumeric characters".into()); + } let v = Volume { name: name.to_owned(), created_ns: SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map(|d| d.as_nanos() as u64).unwrap_or(0), @@ -209,7 +213,9 @@ pub fn guest_mount_fields(options: &BTreeMap, host_path: impl Fn } else { device }; - if kind.starts_with("nfs") { + // Docker resolves `addr=` for nfs and cifs alike; the kernel takes only + // an address there. + if kind.starts_with("nfs") || kind == "cifs" { data = data .split(',') .map(|w| match w.strip_prefix("addr=") { @@ -288,4 +294,36 @@ mod tests { "\tcifs\t//10.0.0.9/share\t0\tusername=u,password=p" ); } + + #[test] + fn a_cifs_addr_is_resolved_like_an_nfs_one() { + let opts = |v: serde_json::Value| local_options(&v).unwrap(); + let dns = |h: &str| (h == "nas.local").then(|| "10.0.0.9".to_owned()); + assert_eq!( + guest_mount_fields(&opts(json!({"type": "cifs", "device": "//nas.local/share", "o": "addr=nas.local,username=u,password=p"})), str::to_owned, dns), + "\tcifs\t//10.0.0.9/share\t0\taddr=10.0.0.9,username=u,password=p" + ); + assert_eq!( + guest_mount_fields(&opts(json!({"type": "cifs", "device": "//10.0.0.9/share", "o": "addr=gone,username=u"})), str::to_owned, dns), + "\tcifs\t//10.0.0.9/share\t0\taddr=gone,username=u" + ); + } + + #[test] + fn a_new_one_character_name_is_refused_as_docker_does() { + let d = std::env::temp_dir().join(format!("kiri-volumes-short-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + let mut v = Volumes::load(&d).unwrap(); + assert_eq!(v.ensure("a", json!({}), false).unwrap_err(), "volume name is too short, names should be at least two alphanumeric characters"); + assert!(v.get("a").is_none()); + v.ensure("ab", json!({}), false).unwrap(); + // One made before this rule keeps working. + let file = d.join("volumes.json"); + let saved = std::fs::read_to_string(&file).unwrap().replace("\"ab\"", "\"a\""); + std::fs::write(&file, saved).unwrap(); + let mut v = Volumes::load(&d).unwrap(); + assert_eq!(v.ensure("a", json!({}), false).unwrap().name, "a"); + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rs index efc4af7e9..82af388ca 100644 --- a/crates/kiri/src/diag/report.rs +++ b/crates/kiri/src/diag/report.rs @@ -62,11 +62,17 @@ const CRASHES: usize = 5; /// Log lines a crash upload carries: its part's last ones before it. const CRASH_LOG_LINES: usize = 200; const CRASH_BUDGET: usize = 48 << 10; +#[cfg(any(target_os = "macos", test))] const MAC_REPORTS: usize = 3; +#[cfg(any(target_os = "macos", test))] const MAC_REPORT_BUDGET: usize = 24 << 10; pub fn run(args: &[String]) -> io::Result<()> { match args.first().map(String::as_str) { + Some("-h" | "--help" | "help") => { + println!("{USAGE}"); + Ok(()) + } Some("logs") => logs_cli(&args[1..]), Some("report") => report_cli(&args[1..]), _ => Err(io::Error::other(USAGE)), @@ -173,6 +179,10 @@ pub fn render(v: &Value, utc: bool, color: bool) -> String { } fn logs_cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } let (mut parts, mut follow, mut errors, mut n, mut op) = (Vec::new(), false, false, 50usize, None); let mut it = args.iter(); while let Some(a) = it.next() { @@ -253,23 +263,62 @@ pub struct Facts { pub created: SystemTime, /// The container list, when the person ticked it in the window. pub containers: Option, + /// VM uplink / DHCP status and (on macOS) bridge & UDP port 67 summary. + pub vm_network: Option, + /// Read-only / `emergency_ro` storage warning when detected (#768). + pub storage_warning: Option, } -/// The engine as the report describes it, asked without waking the VM. -fn engine_line() -> String { +/// The engine as the report describes it (plus its `/info` payload), asked +/// without waking the VM. +fn engine_facts() -> (String, Option) { if !crate::client::alive() { - return "not running".into(); + return ("not running".into(), None); } let version = crate::client::get_background("/version").unwrap_or_default(); let info = crate::client::get_background("/info").unwrap_or_default(); - format!( + let line = format!( "running (engine {}, VM {}, {} of {} containers running, {} images)", crate::client::kiri_version(&version).unwrap_or("?"), if info["KiriVmAwake"] == true { "awake" } else { "asleep" }, info["ContainersRunning"].as_u64().unwrap_or(0), info["Containers"].as_u64().unwrap_or(0), info["Images"].as_u64().unwrap_or(0), - ) + ); + (line, Some(info)) +} + +/// Formats the VM uplink / DHCP fallback and host UDP port 67 lines for the +/// report. Returns `None` when there is nothing to report (e.g. Linux host). +pub fn vm_network_summary(info: Option<&Value>, bridge: Option<&crate::daemon::vmnet::Bridge>, udp67: Option<&str>) -> Option { + let (mut lines, mut dhcp_failed, mut recorded_udp67) = (Vec::new(), false, None); + if let Some(u) = info.and_then(|i| i.get("KiriVmUplink")).filter(|v| v.is_object()) { + recorded_udp67 = u["udp67"].as_str(); + let (ip, gw) = (u["ip"].as_str().unwrap_or("?"), u["gateway"].as_str().unwrap_or("?")); + match u["mode"].as_str().unwrap_or("") { + "dhcp" => lines.push(format!("VM uplink: DHCP ({ip} via {gw})")), + "host-egress" => lines.push("VM uplink: host egress over vsock (shared NAT disabled)".into()), + "static-fallback" => { + dhcp_failed = true; + let (br, dns) = (u["bridge"].as_str().unwrap_or("bridge100"), u["dns"].as_str().unwrap_or("?")); + lines.push(format!("VM uplink: static fallback on {br} ({ip} via {gw}, dns {dns}) — DHCP did not answer")); + } + "fallback-failed" => { + dhcp_failed = true; + lines.push(format!("VM uplink: no uplink — DHCP did not answer and fallback failed ({})", u["reason"].as_str().unwrap_or("unknown"))); + } + _ => {} + } + } + if let Some(b) = bridge { + lines.push(format!("Host vmnet bridge: {} ({}/{})", b.name, std::net::Ipv4Addr::from(b.gateway), b.prefix)); + } + if let Some(holder) = udp67.or(recorded_udp67) { + lines.push(format!("Host UDP port 67: {holder}")); + } else if dhcp_failed { + lines.push("Host UDP port 67: none visible".into()); + } + (!lines.is_empty()).then(|| lines.join("\n")) } /// The engine's containers, one a line: name, image and status. Nothing @@ -352,16 +401,50 @@ fn crash_name(name: &str) -> Option<(u64, Part)> { Some((secs, part)) } -/// The report's text, redacted. `home` holds `Library/Logs/DiagnosticReports`; -/// `state` is `~/.kiri`. +#[cfg(any(target_os = "macos", test))] +fn append_macos_crash_reports(s: &mut String, home: &Path) { + // What macOS wrote down itself: crashes our hook can't see (a signal, a + // hang the system killed, an abort inside a framework). + let reports = home.join("Library/Logs/DiagnosticReports"); + let month = SystemTime::now() - Duration::from_secs(30 * 86_400); + let ips: Vec<_> = newest(&reports, |n| n.to_ascii_lowercase().starts_with("kiri") && n.ends_with(".ips")).into_iter().filter(|(_, t)| *t >= month).collect(); + let _ = writeln!(s, "\n==== macOS crash reports ({}, last 30 days: {}) ====", reports.display(), ips.len()); + for (path, _) in ips.iter().take(MAC_REPORTS) { + let text = String::from_utf8_lossy(&std::fs::read(path).unwrap_or_default()).into_owned(); + let _ = writeln!(s, "--- {} ---", path.file_name().unwrap_or_default().to_string_lossy()); + s.push_str(&first_bytes(&text, MAC_REPORT_BUDGET)); + s.push('\n'); + } +} + +/// The report's text, redacted. `home` holds `Library/Logs/DiagnosticReports` +/// on macOS; `state` is `~/.kiri`. pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) -> String { + #[cfg(target_os = "macos")] + return assemble_inner(home, state, facts, redactor, true); + #[cfg(not(target_os = "macos"))] + { + let _ = home; + assemble_inner(home, state, facts, redactor, false) + } +} + +fn assemble_inner(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor, include_macos_reports: bool) -> String { let mut s = String::new(); let _ = writeln!(s, "Kiri diagnostics report"); let _ = writeln!(s, "Created: {}", time::rfc3339(facts.created)); let _ = writeln!(s, "App: {} {} ({}), made by the {}", crate::flavor::APP, env!("CARGO_PKG_VERSION"), crate::flavor::CONTEXT, super::part().name()); let _ = writeln!(s, "System: {}", super::system().line()); let _ = writeln!(s, "Engine: {}", facts.engine); + if let Some(ro) = &facts.storage_warning { + let _ = writeln!(s, "Storage: {ro}"); + } let _ = writeln!(s, "Crash reports: {}", if facts.crash_reports { "sent automatically" } else { "not sent automatically" }); + if let Some(net) = &facts.vm_network { + for line in net.lines() { + let _ = writeln!(s, "{line}"); + } + } for (part, title) in [(Part::Daemon, "engine"), (Part::Ui, "window"), (Part::Cli, "command line")] { let path = log_file(state, part); @@ -374,15 +457,20 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - } } - // The engine's own stderr, as launchd (or the window) keeps it. - let raw = state.join("daemon.log"); - let _ = writeln!(s, "\n==== Engine output ({}) ====", raw.display()); - let text = tail(&raw, LOG_BUDGET as u64); - let lines: Vec<&str> = text.lines().collect(); - if lines.is_empty() { - let _ = writeln!(s, "(empty)"); - } else { - let _ = writeln!(s, "{}", lines[lines.len().saturating_sub(200)..].join("\n")); + // The engine's own stderr, as launchd (or the window) keeps it, and the + // VM's console log (kiri-init messages, kernel boot, DHCP fallback). + for (title, path, always) in [("Engine output", state.join("daemon.log"), true), ("Guest console", state.join("logs/guest-console.log"), false)] { + if !always && !path.is_file() { + continue; + } + let _ = writeln!(s, "\n==== {title} ({}) ====", path.display()); + let text = tail(&path, LOG_BUDGET as u64); + let lines: Vec<&str> = text.lines().collect(); + if lines.is_empty() { + let _ = writeln!(s, "(empty)"); + } else { + let _ = writeln!(s, "{}", lines[lines.len().saturating_sub(200)..].join("\n")); + } } if let Some(list) = &facts.containers { @@ -399,18 +487,12 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - s.push_str(&first_bytes(&text, CRASH_BUDGET)); } - // What macOS wrote down itself: crashes our hook can't see (a signal, a - // hang the system killed, an abort inside a framework). - let reports = home.join("Library/Logs/DiagnosticReports"); - let month = SystemTime::now() - Duration::from_secs(30 * 86_400); - let ips: Vec<_> = newest(&reports, |n| n.to_ascii_lowercase().starts_with("kiri") && n.ends_with(".ips")).into_iter().filter(|(_, t)| *t >= month).collect(); - let _ = writeln!(s, "\n==== macOS crash reports ({}, last 30 days: {}) ====", reports.display(), ips.len()); - for (path, _) in ips.iter().take(MAC_REPORTS) { - let text = String::from_utf8_lossy(&std::fs::read(path).unwrap_or_default()).into_owned(); - let _ = writeln!(s, "--- {} ---", path.file_name().unwrap_or_default().to_string_lossy()); - s.push_str(&first_bytes(&text, MAC_REPORT_BUDGET)); - s.push('\n'); + #[cfg(any(target_os = "macos", test))] + if include_macos_reports { + append_macos_crash_reports(&mut s, home); } + #[cfg(not(any(target_os = "macos", test)))] + let _ = (home, include_macos_reports); redactor.apply(&s) } @@ -419,7 +501,22 @@ pub fn assemble(home: &Path, state: &Path, facts: &Facts, redactor: &Redactor) - pub fn report_text(containers: bool) -> io::Result { let home = std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set"))?; let state = home.join(crate::flavor::STATE.get()); - let facts = Facts { engine: engine_line(), crash_reports: crash_reports_on(), created: SystemTime::now(), containers: containers.then(container_lines) }; + let (engine, info) = engine_facts(); + let bridge = crate::daemon::vmnet::current_bridge(); + let udp67 = crate::daemon::vmnet::udp67_holder(); + let vm_network = vm_network_summary(info.as_ref(), bridge.as_ref(), udp67.as_deref()); + let storage_warning = info + .as_ref() + .and_then(|i| i["KiriStorageReadOnly"].as_str().map(str::to_owned)) + .or_else(|| crate::daemon::rofs::check_daemon_storage(None)); + let facts = Facts { + engine, + crash_reports: crash_reports_on(), + created: SystemTime::now(), + containers: containers.then(container_lines), + vm_network, + storage_warning, + }; Ok(assemble(&home, &state, &facts, &Redactor::for_user())) } @@ -432,12 +529,28 @@ fn default_out() -> io::Result { Ok(if desktop.is_dir() { desktop } else { home }.join(format!("kiri-report-{stamp}.txt"))) } +/// Resolves an explicit `--out` path (translating a Windows drive path like +/// `C:\Temp\report.txt` to `/mnt/c/Temp/report.txt` when running inside WSL 2) +/// or falls back to `default_out()`. +fn resolve_out_path(out: Option, wsl: Option<&crate::daemon::binds::Wsl>) -> io::Result { + let Some(p) = out else { + return default_out(); + }; + if let (Some(w), Some(s)) = (wsl, p.to_str()) + && (s.contains('\\') || s.as_bytes().get(1) == Some(&b':')) + && let Ok(mapped) = crate::daemon::binds::source(s, w) + { + return Ok(PathBuf::from(mapped)); + } + Ok(p) +} + /// Writes the report, readable only by this user. Returns where. pub fn save_report(text: &str, out: Option) -> io::Result { - let path = match out { - Some(p) => p, - None => default_out()?, - }; + let path = resolve_out_path(out, crate::daemon::binds::wsl())?; + if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { + let _ = std::fs::create_dir_all(parent); + } let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&path)?; f.write_all(text.as_bytes())?; Ok(path) @@ -451,6 +564,10 @@ pub fn reveal(path: &Path) { } fn report_cli(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } let (mut out, mut send_it) = (None, false); let mut it = args.iter(); while let Some(a) = it.next() { @@ -882,8 +999,9 @@ mod tests { std::fs::write(state.join("crashes/1792700000-ui.sent.txt"), "Kiri crash report\nMessage: older\n").unwrap(); std::fs::write(reports.join("kiri-2026-10-28-094107.ips"), format!("{{\"app_name\":\"kiri\",\"crashReporterKey\":\"ABCD-1234\"}}\n{{\"procPath\":\"{h}/Applications/Kiri.app\"}}")).unwrap(); std::fs::write(reports.join("Safari-2026-10-28-094107.ips"), "not ours").unwrap(); - let facts = Facts { engine: "not running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: Some("web nginx:alpine Up 2 hours\n".into()) }; - let text = assemble(&home, &state, &facts, &Redactor::new(Some(h.clone()), Vec::new())); + let facts = Facts { engine: "not running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: Some("web nginx:alpine Up 2 hours\n".into()), vm_network: None, storage_warning: None }; + let redactor = Redactor::new(Some(h.clone()), Vec::new()); + let text = assemble(&home, &state, &facts, &redactor); assert!(text.starts_with("Kiri diagnostics report\nCreated: 2026-10-24T00:00:00"), "{text}"); assert!(text.contains("Engine: not running") && text.contains("Crash reports: not sent automatically")); @@ -895,7 +1013,16 @@ mod tests { assert!(text.contains("==== Containers (names, images and status only) ====\nweb nginx:alpine Up 2 hours\n")); assert!(text.contains("2 in all") && text.contains("--- 1792800000-daemon.txt ---") && text.contains("boom with Bearer [redacted]")); assert!(text.find("1792800000-daemon").unwrap() < text.find("1792700000-ui").unwrap(), "newest crash first"); - assert!(text.contains("--- kiri-2026-10-28-094107.ips ---") && text.contains("~/Applications/Kiri.app") && !text.contains("Safari")); + let mac_text = assemble_inner(&home, &state, &facts, &redactor, true); + assert!(mac_text.contains("--- kiri-2026-10-28-094107.ips ---") && mac_text.contains("~/Applications/Kiri.app") && !mac_text.contains("Safari")); + assert!(!mac_text.contains("ABCD-1234") && !mac_text.contains(&h), "{mac_text}"); + let non_mac_text = assemble_inner(&home, &state, &facts, &redactor, false); + assert!(!non_mac_text.contains("macOS crash reports") && !non_mac_text.contains("DiagnosticReports") && !non_mac_text.contains(".ips"), "{non_mac_text}"); + if cfg!(target_os = "macos") { + assert!(text.contains("==== macOS crash reports") && text.contains("--- kiri-2026-10-28-094107.ips ---"), "{text}"); + } else { + assert!(!text.contains("macOS crash reports") && !text.contains("DiagnosticReports") && !text.contains(".ips"), "{text}"); + } assert!(!text.contains("ABCD-1234") && !text.contains(&h), "{text}"); assert!(text.len() < MAX_BODY); let _ = std::fs::remove_dir_all(&home); @@ -966,4 +1093,51 @@ mod tests { assert!(pending(&home, 1_792_800_001).is_empty()); let _ = std::fs::remove_dir_all(&home); } + + #[test] + fn report_includes_vm_uplink_dhcp_fallback_udp67_and_guest_console() { + let bridge = crate::daemon::vmnet::Bridge { name: "bridge100".into(), gateway: [192, 168, 64, 1], prefix: 24 }; + let fallback_info = json!({"KiriVmUplink": {"mode": "static-fallback", "bridge": "bridge100", "ip": "192.168.64.2/24", "gateway": "192.168.64.1", "dns": "192.168.64.1", "udp67": "kavd (pid 412)"}}); + let summary = vm_network_summary(Some(&fallback_info), Some(&bridge), Some("kavd (pid 412)")).unwrap(); + assert!(summary.contains("VM uplink: static fallback on bridge100 (192.168.64.2/24 via 192.168.64.1, dns 192.168.64.1) — DHCP did not answer"), "{summary}"); + assert!(summary.contains("Host vmnet bridge: bridge100 (192.168.64.1/24)") && summary.contains("Host UDP port 67: kavd (pid 412)"), "{summary}"); + + let ok = vm_network_summary(Some(&json!({"KiriVmUplink": {"mode": "dhcp", "ip": "192.168.64.28", "gateway": "192.168.64.1"}})), Some(&bridge), None).unwrap(); + assert!(ok.contains("VM uplink: DHCP (192.168.64.28 via 192.168.64.1)") && !ok.contains("UDP port 67"), "{ok}"); + + let host_egress = vm_network_summary(Some(&json!({"KiriVmUplink": {"mode": "host-egress"}})), None, None).unwrap(); + assert!(host_egress.contains("VM uplink: host egress over vsock (shared NAT disabled)") && !host_egress.contains("UDP port 67"), "{host_egress}"); + + let fail = vm_network_summary(Some(&json!({"KiriVmUplink": {"mode": "fallback-failed", "reason": "no bridge100"}})), None, None).unwrap(); + assert!(fail.contains("DHCP did not answer and fallback failed (no bridge100)") && fail.contains("Host UDP port 67: none visible"), "{fail}"); + assert_eq!(vm_network_summary(None, None, None), None); + + let home = temp_home("vm-net"); + let state = home.join(".kiri"); + std::fs::create_dir_all(state.join("logs")).unwrap(); + std::fs::write(state.join("logs/guest-console.log"), "kiri-init: DHCP did not answer; configured eth0 statically as 192.168.64.2/24 via 192.168.64.1 from host\n").unwrap(); + let facts = Facts { engine: "running".into(), crash_reports: false, created: UNIX_EPOCH + Duration::from_secs(1_792_800_000), containers: None, vm_network: Some(summary), storage_warning: Some("Kiri's WSL2 disk (ext4.vhdx) was remounted read-only by Linux (emergency_ro)".into()) }; + let text = assemble(&home, &state, &facts, &Redactor::new(Some(home.display().to_string()), Vec::new())); + assert!(text.contains("Storage: Kiri's WSL2 disk (ext4.vhdx) was remounted read-only by Linux (emergency_ro)"), "{text}"); + assert!(text.contains("VM uplink: static fallback on bridge100") && text.contains("Host UDP port 67: kavd (pid 412)"), "{text}"); + assert!(text.contains("==== Guest console (~/.kiri/logs/guest-console.log) ====") && text.contains("configured eth0 statically as 192.168.64.2/24"), "{text}"); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn resolves_windows_out_path_in_wsl() { + let wsl = crate::daemon::binds::Wsl { root: "/mnt/".into(), distro: Some("kiri".into()) }; + assert_eq!( + resolve_out_path(Some(PathBuf::from(r"C:\Temp\kiri-test-report.txt")), Some(&wsl)).unwrap(), + PathBuf::from("/mnt/c/Temp/kiri-test-report.txt") + ); + assert_eq!( + resolve_out_path(Some(PathBuf::from("D:/reports/out.txt")), Some(&wsl)).unwrap(), + PathBuf::from("/mnt/d/reports/out.txt") + ); + assert_eq!( + resolve_out_path(Some(PathBuf::from("/tmp/kiri-report.txt")), Some(&wsl)).unwrap(), + PathBuf::from("/tmp/kiri-report.txt") + ); + } } diff --git a/crates/kiri/src/docker.rs b/crates/kiri/src/docker.rs index 499770929..53d7fce00 100644 --- a/crates/kiri/src/docker.rs +++ b/crates/kiri/src/docker.rs @@ -21,7 +21,7 @@ pub const COMMANDS: &[&str] = &[ /// `kiri update` is two commands. Alone or with `--check` it updates Kiri; /// with anything else it is Docker's `update`, which always names a /// container (`kiri update --memory 256m web`). -#[cfg(any(target_os = "macos", test))] +#[cfg(any(target_os = "macos", target_os = "linux", test))] pub fn is_container_update(args: &[String]) -> bool { args.iter().any(|a| !matches!(a.as_str(), "--check" | "-h" | "--help")) } @@ -36,9 +36,7 @@ pub fn handles(command: &str) -> bool { pub fn run(args: &[String]) -> io::Result<()> { let docker = client::docker_cli().ok_or_else(|| io::Error::other("no docker CLI found; open Kiri once to set it up"))?; let socket = client::socket()?; - if !client::alive() { - return Err(io::Error::other("Kiri isn't running. Open Kiri, or start it with `kiri daemon`")); - } + client::check_alive()?; let mut cmd = std::process::Command::new(docker); cmd.args(args).env("DOCKER_HOST", format!("unix://{}", socket.display())).env_remove("DOCKER_CONTEXT"); // With DOCKER_HOST and no context, buildx would pick the endpoint's own @@ -57,6 +55,7 @@ pub fn run(args: &[String]) -> io::Result<()> { /// Exits with docker's exit code. #[cfg(windows)] pub fn run(args: &[String]) -> io::Result<()> { + crate::setup_win::heal_quietly(); let beside = std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join("docker.exe"))).filter(|d| d.is_file()); let status = std::process::Command::new(beside.unwrap_or_else(|| "docker.exe".into())) .args(["--context", crate::flavor::CONTEXT.get()]) diff --git a/crates/kiri/src/dockerctx.rs b/crates/kiri/src/dockerctx.rs new file mode 100644 index 000000000..b77850b7b --- /dev/null +++ b/crates/kiri/src/dockerctx.rs @@ -0,0 +1,829 @@ +//! Which engine plain `docker` reaches, and who has docker's default +//! endpoint, for the window's status bar and Settings → Network on every +//! system (#369, #577). +//! +//! Plain `docker` uses Kiri only through Kiri's context, or through the +//! default endpoint (`/var/run/docker.sock`, `\\.\pipe\docker_engine` on +//! Windows) while Kiri serves it. Another engine's context +//! (`desktop-linux`, `orbstack`, `colima`) is that engine, whatever Kiri +//! serves. Shared with kiri-win by path, so std and serde_json only. + +use std::ffi::OsString; +use std::io; +use std::path::{Path, PathBuf}; + +use serde_json::{Value, json}; + +/// Who serves docker's default endpoint. +#[derive(Debug, Clone, PartialEq)] +pub enum Endpoint { + Kiri, + /// Another engine: its name, or the path the endpoint leads to (empty + /// when nothing says which program it is). + Taken(String), + Free, +} + +/// What plain `docker` uses, picked as the docker CLI picks it. +#[derive(Debug, PartialEq)] +pub struct Cli { + /// Its context: "default" for the default endpoint, and for DOCKER_HOST. + pub context: String, + /// The environment variable that decides it, when one does: switching + /// docker's context changes nothing then. + pub pinned: Option<&'static str>, + /// Whether that reaches Kiri. + pub kiri: bool, +} + +impl Cli { + /// The context for the status bar: Kiri's own when docker reaches Kiri + /// another way (the default endpoint Kiri serves), as the page compares + /// it with Kiri's. + pub fn shown<'a>(&'a self, ours: &'a str) -> &'a str { + if self.kiri { ours } else { &self.context } + } + + /// The variable to name in the window: only while docker misses Kiri. + pub fn pinned_shown(&self) -> Option<&'static str> { + self.pinned.filter(|_| !self.kiri) + } +} + +/// What the docker CLI reads to pick its endpoint. +#[derive(Debug, Default)] +pub struct Env<'a> { + /// DOCKER_HOST. + pub host: Option<&'a str>, + /// DOCKER_CONTEXT. + pub context: Option<&'a str>, + /// config.json as read; None when there is none. + pub config: Option<&'a [u8]>, +} + +/// docker's default endpoints, as DOCKER_HOST may name them. +const DEFAULT_HOSTS: [&str; 3] = ["unix:///var/run/docker.sock", "unix:///run/docker.sock", "npipe:////./pipe/docker_engine"]; + +/// The context `docker` uses, in the docker CLI's order: DOCKER_HOST, then +/// DOCKER_CONTEXT, then config.json's `currentContext`, else "default". A +/// config.json that isn't JSON counts as empty, as the CLI warns and goes +/// on without it. `ours` is Kiri's context and `our_hosts` its endpoints. +pub fn cli(env: &Env, ours: &str, our_hosts: &[&str], endpoint: &Endpoint) -> Cli { + let set = |v: Option<&str>| v.map(str::trim).filter(|v| !v.is_empty()).map(str::to_owned); + if let Some(host) = set(env.host) { + let served = *endpoint == Endpoint::Kiri && DEFAULT_HOSTS.iter().any(|h| same_host(h, &host)); + let kiri = served || our_hosts.iter().any(|h| same_host(h, &host)); + return Cli { context: "default".into(), pinned: Some("DOCKER_HOST"), kiri }; + } + let (context, pinned) = match set(env.context) { + Some(c) => (c, Some("DOCKER_CONTEXT")), + None => (current(env.config).unwrap_or_else(|| "default".into()), None), + }; + let kiri = if context == "default" { *endpoint == Endpoint::Kiri } else { context == ours }; + Cli { context, pinned, kiri } +} + +fn strip_bom(bytes: &[u8]) -> &[u8] { + bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes) +} + +/// config.json's `currentContext`, when it names one. +fn current(config: Option<&[u8]>) -> Option { + let cfg: Value = serde_json::from_slice(strip_bom(config?)).ok()?; + cfg["currentContext"].as_str().map(str::trim).filter(|c| !c.is_empty()).map(str::to_owned) +} + +/// Two docker hosts that are the same endpoint: `npipe:////./pipe/x` and +/// `npipe://./pipe/x`, any case, are one pipe. +fn same_host(a: &str, b: &str) -> bool { + let norm = |h: &str| match h.split_once(':') { + Some((scheme, rest)) if scheme.eq_ignore_ascii_case("npipe") => { + format!("npipe:{}", rest.replace('\\', "/").trim_matches('/').to_ascii_lowercase()) + } + Some((scheme, rest)) => format!("{}:{}", scheme.to_ascii_lowercase(), rest.trim_end_matches('/')), + None => h.trim_end_matches('/').to_owned(), + }; + norm(a) == norm(b) +} + +/// `cli` for this process: its environment and docker's config.json. +pub fn current_cli(ours: &str, our_hosts: &[&str], endpoint: &Endpoint) -> Cli { + let host = std::env::var("DOCKER_HOST").ok(); + let context = std::env::var("DOCKER_CONTEXT").ok(); + let config = docker_dir().and_then(|d| std::fs::read(d.join("config.json")).ok()); + cli(&Env { host: host.as_deref(), context: context.as_deref(), config: config.as_deref() }, ours, our_hosts, endpoint) +} + +/// The engine a socket's path, or a Windows process, belongs to, when it +/// is one Kiri knows. +pub fn engine_name(target: &str) -> Option<&'static str> { + let t = target.replace('\\', "/").to_ascii_lowercase(); + const KNOWN: [(&str, &str); 9] = [ + ("/.orbstack/", "OrbStack"), + ("/.docker/", "Docker Desktop"), + ("docker desktop", "Docker Desktop"), + ("com.docker.", "Docker Desktop"), + ("/.rd/", "Rancher Desktop"), + ("rancher desktop", "Rancher Desktop"), + ("colima", "Colima"), + ("podman", "Podman"), + ("dockerd", "dockerd"), + ]; + KNOWN.iter().find(|(k, _)| t.contains(k)).map(|(_, name)| *name) +} + +/// Settings → Network's Docker socket row: who has `path`, the DOCKER_HOST +/// that points a tool at Kiri instead (`ours`), and whether the window can +/// take it now (`take`: the Mac, while it is free). +pub fn sock_event(path: &str, endpoint: &Endpoint, ours: &str, take: bool) -> Value { + let (owner, engine, target) = match endpoint { + Endpoint::Kiri => ("kiri", None, None), + Endpoint::Free => ("free", None, None), + Endpoint::Taken(t) => ("other", engine_name(t), Some(t.as_str()).filter(|t| !t.is_empty())), + }; + json!({"type": "dockersock", "path": path, "owner": owner, "engine": engine, "target": target, "hint": format!("DOCKER_HOST={ours}"), "take": take && *endpoint == Endpoint::Free}) +} + +/// The window's "status" event: build version, app flavor, and what plain +/// `docker` uses (including `pinned` when DOCKER_HOST or DOCKER_CONTEXT +/// overrides config.json and misses Kiri). +pub fn status_event(version: &str, dev: bool, app: &str, ours: &str, cli: &Cli) -> Value { + json!({"type": "status", "version": version, "dev": dev, "share": true, "app": app, "ours": ours, "context": cli.shown(ours), "pinned": cli.pinned_shown()}) +} + +/// Who owns a Unix docker socket path (`path`): Kiri (`ours`), another +/// engine (a socket, plain file, or link to an installed engine in +/// `engines`), or nobody (`Free`, including a dangling link left behind by +/// an engine that was removed). +#[cfg(unix)] +pub fn sock_at(path: &Path, ours: &Path, engines: &[PathBuf]) -> Endpoint { + let Ok(meta) = std::fs::symlink_metadata(path) else { return Endpoint::Free }; + if meta.file_type().is_symlink() { + let Ok(target) = std::fs::read_link(path) else { return Endpoint::Taken(path.display().to_string()) }; + let resolved = if target.is_relative() { path.parent().map_or_else(|| target.clone(), |p| p.join(&target)) } else { target.clone() }; + if target == ours || resolved == ours { + return Endpoint::Kiri; + } + if resolved.exists() { + if let (Ok(a), Ok(b)) = (std::fs::canonicalize(&resolved), std::fs::canonicalize(ours)) + && a == b + { + return Endpoint::Kiri; + } + return Endpoint::Taken(target.display().to_string()); + } + if engines.iter().any(|e| target.starts_with(e) || resolved.starts_with(e)) { + return Endpoint::Taken(target.display().to_string()); + } + // Left behind by an engine that has been removed. + return Endpoint::Free; + } + // A socket (or anything else) of its own: an engine's, serving or not. + Endpoint::Taken(path.display().to_string()) +} + +/// docker's config folder: DOCKER_CONFIG, else `.docker` in the home +/// folder (HOME, or USERPROFILE on Windows). +pub fn docker_dir() -> Option { + dir_in(std::env::var_os("DOCKER_CONFIG"), std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })) +} + +fn dir_in(config: Option, home: Option) -> Option { + config.filter(|c| !c.is_empty()).map(PathBuf::from).or_else(|| home.filter(|h| !h.is_empty()).map(|h| Path::new(&h).join(".docker"))) +} + +pub fn read_json(path: &Path) -> io::Result { + match std::fs::read(path) { + Ok(b) => serde_json::from_slice(strip_bom(&b)).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display()))), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(json!({})), + Err(e) => Err(e), + } +} + +/// Writes JSON through a temporary file, so a crash never leaves half a config. +pub fn write_json(path: &Path, v: &Value) -> io::Result<()> { + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); + std::fs::create_dir_all(dir)?; + let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config.json"); + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{file}.kiri-tmp-{}-{seq}", std::process::id())); + let bytes = serde_json::to_vec_pretty(v).map_err(io::Error::other)?; + let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path)); + if res.is_err() { + let _ = std::fs::remove_file(&tmp); + } + res +} + +/// A context's meta.json, as `docker context create NAME --docker +/// host=HOST` writes it, in `meta`: contexts/meta/ and the SHA-256 of its +/// name, which the caller works out. +pub fn write_context(meta: &Path, name: &str, description: &str, host: &str) -> io::Result<()> { + let v = json!({ + "Name": name, + "Metadata": {"Description": description}, + "Endpoints": {"docker": {"Host": host, "SkipTLSVerify": false}}, + }); + write_json(&meta.join("meta.json"), &v) +} + +/// Makes `name` the context in `config` (config.json); "default" takes +/// `currentContext` out. Every other key (registry logins, credential +/// helpers, plugin folders) stays as it was, and a file that isn't a JSON +/// object is left alone, with an error that says so. +pub fn set_current(config: &Path, name: &str) -> io::Result<()> { + let mut cfg = read_json(config)?; + let Some(o) = cfg.as_object_mut() else { return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", config.display()))) }; + if name == "default" { + o.remove("currentContext"); + } else { + o.insert("currentContext".into(), name.into()); + } + write_json(config, &cfg) +} + +/// Kiri's context as docker's current one, made first if it's missing (a +/// context someone removed). `dir` is docker's config folder, `meta` the +/// context's folder in it, `host` Kiri's endpoint. +pub fn use_ours(dir: &Path, meta: &Path, name: &str, description: &str, host: &str) -> io::Result<()> { + if !meta.join("meta.json").is_file() { + write_context(meta, name, description, host)?; + } + set_current(&dir.join("config.json"), name) +} + +/// Validates a docker context name so it cannot escape `contexts/meta/`. +pub fn valid_name(name: &str) -> bool { + !name.is_empty() && name != "." && name != ".." && name.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.-".contains(&b)) +} + +/// Makes `name` the current context in `dir/config.json`: `ours` (created in +/// `meta` first if missing), `"default"`, or another context whose +/// `meta.json` lives in `meta`. +pub fn switch(dir: &Path, meta: &Path, name: &str, ours: &str, description: &str, host: &str) -> io::Result<()> { + if !valid_name(name) { + return Err(io::Error::other("not a context name")); + } + if name == ours { + return use_ours(dir, meta, name, description, host); + } + if name != "default" && !meta.join("meta.json").is_file() { + return Err(io::Error::other(format!("there is no docker context `{name}`"))); + } + set_current(&dir.join("config.json"), name) +} + +/// Lowercase hex SHA-256 of `data`, using `std` only so `dockerctx` stays +/// dependency-free across `kiri`, `kiri-win`, and host-side tests. +pub fn sha256_hex(data: &[u8]) -> String { + const K: [u32; 64] = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, + ]; + let mut h: [u32; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, + 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]; + let bit_len = (data.len() as u64).wrapping_mul(8); + let mut msg = Vec::with_capacity((data.len() + 9).next_multiple_of(64)); + msg.extend_from_slice(data); + msg.push(0x80); + while msg.len() % 64 != 56 { + msg.push(0); + } + msg.extend_from_slice(&bit_len.to_be_bytes()); + for chunk in msg.as_chunks::<64>().0 { + let mut w = [0u32; 64]; + for (i, word) in chunk.as_chunks::<4>().0.iter().enumerate() { + w[i] = u32::from_be_bytes(*word); + } + for i in 16..64 { + let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3); + let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10); + w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1); + } + let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h; + for i in 0..64 { + let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25); + let ch = (e & f) ^ ((!e) & g); + let temp1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]); + let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22); + let maj = (a & b) ^ (a & c) ^ (b & c); + let temp2 = s0.wrapping_add(maj); + hh = g; + g = f; + f = e; + e = d.wrapping_add(temp1); + d = c; + c = b; + b = a; + a = temp1.wrapping_add(temp2); + } + for (dst, add) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) { + *dst = dst.wrapping_add(add); + } + } + let mut out = String::with_capacity(64); + for word in h { + use std::fmt::Write as _; + let _ = write!(out, "{word:08x}"); + } + out +} + +/// The docker CLI's directory for a named context (`contexts/meta/`). +pub fn context_meta(dir: &Path, name: &str) -> PathBuf { + dir.join("contexts/meta").join(sha256_hex(name.as_bytes())) +} + +/// Candidate Windows `cli-plugins` folders for Kiri (`cli-plugins` beside +/// `kiri.exe`, `bin\cli-plugins` beside `kiri-win.exe`, `%LOCALAPPDATA%\Kiri\bin\cli-plugins`, +/// and `%LOCALAPPDATA%\Programs\Kiri\cli-plugins`), returning the first existing directory. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub fn find_windows_cli_plugins(exe: Option<&Path>, local_app_data: Option<&Path>) -> Option { + let mut candidates = Vec::new(); + if let Some(exe_dir) = exe.and_then(Path::parent) { + candidates.push(exe_dir.join("cli-plugins")); + candidates.push(exe_dir.join("bin").join("cli-plugins")); + } + if let Some(local) = local_app_data { + candidates.push(local.join("Kiri").join("bin").join("cli-plugins")); + candidates.push(local.join("Kiri").join("cli-plugins")); + candidates.push(local.join("Programs").join("Kiri").join("bin").join("cli-plugins")); + candidates.push(local.join("Programs").join("Kiri").join("cli-plugins")); + } + candidates.into_iter().find(|p| p.is_dir()) +} + +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +fn same_windows_dir(a: &str, b: &str) -> bool { + let norm = |s: &str| s.replace('\\', "/").trim_end_matches('/').to_ascii_lowercase(); + norm(a) == norm(b) +} + +/// What [`repair_windows_config`] changed in `%USERPROFILE%\.docker`. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +#[derive(Debug, Default, PartialEq, Eq)] +pub struct WindowsRepair { + pub context_written: bool, + pub plugins_added: bool, + pub current_context_set: bool, +} + +/// Options for [`repair_windows_config`]. +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +#[derive(Debug, Clone, Copy)] +pub struct WindowsRepairOpts<'a> { + pub ours: &'a str, + pub description: &'a str, + pub host: &'a str, + pub plugins_dir: Option<&'a Path>, + /// Always rewrite `contexts/meta//meta.json` (used by `kiri setup`). + pub force_context_write: bool, + /// Set `currentContext` to `ours` whenever `currentContext` is empty (`kiri setup`). + pub set_current_if_empty: bool, + /// Unconditionally set `currentContext` to `ours` (`kiri setup --use`). + pub force_use: bool, + /// Whether Docker Desktop (`Docker Desktop.exe`) is still installed on this PC. + pub desktop_installed: bool, +} + +/// Ensures Kiri's Windows Docker configuration in `dir` (`%USERPROFILE%\.docker`): +/// - writes `contexts/meta//meta.json` when missing (or when `force_context_write`), +/// - ensures `cliPluginsExtraDirs` in `config.json` includes `plugins_dir` (preserving logins, +/// credential helpers, aliases, and other plugin dirs), and +/// - sets `currentContext` to `ours` when `force_use` is set, when `currentContext` names a +/// non-existent context (such as a removed `desktop-linux`), when `currentContext` is empty and +/// `set_current_if_empty` is set, or when `config.json` was missing and Docker Desktop is not +/// installed (#984). +#[cfg_attr(not(any(windows, test)), allow(dead_code))] +pub fn repair_windows_config(dir: &Path, opts: WindowsRepairOpts<'_>) -> io::Result { + let config_path = dir.join("config.json"); + let config_existed = config_path.exists(); + let mut cfg = read_json(&config_path)?; + if !cfg.is_object() { + return Err(io::Error::new(io::ErrorKind::InvalidData, format!("{}: not a JSON object", config_path.display()))); + } + let mut out = WindowsRepair::default(); + let meta = context_meta(dir, opts.ours); + if opts.force_context_write || !meta.join("meta.json").is_file() { + write_context(&meta, opts.ours, opts.description, opts.host)?; + out.context_written = true; + } + let mut cfg_changed = false; + if let Some(plugins) = opts.plugins_dir { + let want = plugins.to_string_lossy().into_owned(); + let mut dirs: Vec = cfg.get("cliPluginsExtraDirs").and_then(Value::as_array).cloned().unwrap_or_default(); + if !dirs.iter().any(|d| d.as_str().is_some_and(|s| same_windows_dir(s, &want))) { + dirs.push(Value::String(want)); + cfg["cliPluginsExtraDirs"] = Value::Array(dirs); + out.plugins_added = true; + cfg_changed = true; + } + } + let cur = cfg.get("currentContext").and_then(Value::as_str).map(str::trim).unwrap_or("").to_owned(); + let dangling = !cur.is_empty() + && cur != "default" + && cur != opts.ours + && (!valid_name(&cur) + || !context_meta(dir, &cur).join("meta.json").is_file() + || (cur == "desktop-linux" && !opts.desktop_installed)); + let want_ours = opts.force_use + || dangling + || (cur.is_empty() && (opts.set_current_if_empty || (!config_existed && !opts.desktop_installed))); + if want_ours && cur != opts.ours { + cfg["currentContext"] = Value::String(opts.ours.to_owned()); + out.current_context_set = true; + cfg_changed = true; + } + if cfg_changed { + write_json(&config_path, &cfg)?; + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + const OURS: &str = "kiri"; + const KIRI_HOST: &str = "unix:///Users/me/.kiri/run/docker.sock"; + + fn with_config(config: Option<&str>, endpoint: &Endpoint) -> Cli { + cli(&Env { config: config.map(str::as_bytes), ..Env::default() }, OURS, &[KIRI_HOST], endpoint) + } + + #[test] + fn another_engines_context_is_never_kiri() { + // #369: Docker Desktop's context, while Kiri holds docker_engine or + // /var/run/docker.sock: docker talks to Docker Desktop. + let desktop = Endpoint::Taken("Docker Desktop".into()); + for ctx in ["desktop-linux", "orbstack", "colima"] { + for endpoint in [Endpoint::Kiri, desktop.clone(), Endpoint::Free] { + let c = with_config(Some(&format!(r#"{{"currentContext": "{ctx}", "auths": {{}}}}"#)), &endpoint); + assert_eq!(c, Cli { context: ctx.into(), pinned: None, kiri: false }, "{ctx} with {endpoint:?}"); + assert_eq!(c.shown(OURS), ctx); + } + } + } + + #[test] + fn kiris_context_is_kiri_whoever_has_the_default_endpoint() { + for endpoint in [Endpoint::Kiri, Endpoint::Taken("Docker Desktop".into()), Endpoint::Free] { + let c = with_config(Some(r#"{"currentContext": "kiri"}"#), &endpoint); + assert!(c.kiri, "{endpoint:?}"); + assert_eq!(c.shown(OURS), "kiri"); + } + } + + #[test] + fn the_default_context_is_kiri_only_while_kiri_serves_the_endpoint() { + // Unset, "default", no config.json, or one docker can't read (it + // warns and goes on with none): all the default endpoint. + let configs = [Some(r#"{"currentContext": "default"}"#), Some(r#"{"auths": {}}"#), Some(r#"{"currentContext": ""}"#), None, Some("{not json")]; + for config in configs { + let c = with_config(config, &Endpoint::Kiri); + assert_eq!((c.context.as_str(), c.kiri, c.shown(OURS)), ("default", true, "kiri"), "{config:?}"); + for endpoint in [Endpoint::Taken("Docker Desktop".into()), Endpoint::Free] { + let c = with_config(config, &endpoint); + assert_eq!((c.context.as_str(), c.kiri, c.shown(OURS)), ("default", false, "default"), "{config:?} with {endpoint:?}"); + } + } + } + + #[test] + fn the_environment_comes_before_config_json() { + let config = Some(r#"{"currentContext": "kiri"}"#.as_bytes()); + // DOCKER_CONTEXT over currentContext. + let c = cli(&Env { context: Some("desktop-linux"), config, ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Kiri); + assert_eq!(c, Cli { context: "desktop-linux".into(), pinned: Some("DOCKER_CONTEXT"), kiri: false }); + assert_eq!(c.pinned_shown(), Some("DOCKER_CONTEXT")); + // DOCKER_HOST over both: Kiri only when it leads to Kiri. + let host = |h: &'static str, endpoint: &Endpoint| cli(&Env { host: Some(h), context: Some("kiri"), config }, OURS, &[KIRI_HOST, "npipe:////./pipe/kiri"], endpoint); + let desktop = Endpoint::Taken("Docker Desktop".into()); + assert!(!host("npipe:////./pipe/dockerDesktopLinuxEngine", &Endpoint::Kiri).kiri); + assert_eq!(host("npipe:////./pipe/dockerDesktopLinuxEngine", &Endpoint::Kiri).pinned_shown(), Some("DOCKER_HOST")); + assert!(host(KIRI_HOST, &desktop).kiri); + assert!(host(r"npipe://./pipe/KIRI", &desktop).kiri, "the same pipe, written another way"); + assert_eq!(host(KIRI_HOST, &desktop).pinned_shown(), None, "nothing to say while docker reaches Kiri"); + assert!(host("unix:///var/run/docker.sock", &Endpoint::Kiri).kiri); + assert!(!host("unix:///var/run/docker.sock", &desktop).kiri); + assert!(host("npipe:////./pipe/docker_engine", &Endpoint::Kiri).kiri); + // Empty variables are unset. + let c = cli(&Env { host: Some(""), context: Some(" "), config }, OURS, &[KIRI_HOST], &Endpoint::Free); + assert_eq!(c, Cli { context: "kiri".into(), pinned: None, kiri: true }); + } + + #[test] + fn names_the_engine_behind_an_endpoint() { + assert_eq!(engine_name("/Users/me/.orbstack/run/docker.sock"), Some("OrbStack")); + assert_eq!(engine_name("/Users/me/.docker/run/docker.sock"), Some("Docker Desktop")); + assert_eq!(engine_name("/Users/me/.colima/default/docker.sock"), Some("Colima")); + assert_eq!(engine_name("/Users/me/.rd/docker.sock"), Some("Rancher Desktop")); + assert_eq!(engine_name("Docker Desktop.exe"), Some("Docker Desktop")); + assert_eq!(engine_name("com.docker.backend.exe"), Some("Docker Desktop")); + assert_eq!(engine_name("Rancher Desktop.exe"), Some("Rancher Desktop")); + assert_eq!(engine_name("dockerd.exe"), Some("dockerd")); + assert_eq!(engine_name("/var/run/docker.sock"), None); + } + + #[test] + fn the_socket_rows_event() { + let e = sock_event("/var/run/docker.sock", &Endpoint::Taken("/Users/me/.orbstack/run/docker.sock".into()), KIRI_HOST, true); + assert_eq!(e["owner"], "other"); + assert_eq!(e["engine"], "OrbStack"); + assert_eq!(e["target"], "/Users/me/.orbstack/run/docker.sock"); + assert_eq!(e["hint"], format!("DOCKER_HOST={KIRI_HOST}")); + assert_eq!(e["take"], false, "another engine's socket is never taken"); + let e = sock_event("/var/run/docker.sock", &Endpoint::Free, KIRI_HOST, true); + assert_eq!((e["owner"].as_str(), e["take"].as_bool()), (Some("free"), Some(true))); + let e = sock_event(r"\\.\pipe\docker_engine", &Endpoint::Taken(String::new()), "npipe:////./pipe/kiri", false); + assert_eq!((e["owner"].as_str(), e["engine"].is_null(), e["target"].is_null()), (Some("other"), true, true)); + assert_eq!(sock_event("/var/run/docker.sock", &Endpoint::Kiri, KIRI_HOST, true)["take"], false); + } + + /// A home folder of its own for each test, as HOME or USERPROFILE. + fn scratch_home(name: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("kiri-dockerctx-test-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn docker_dir_is_docker_config_or_the_homes() { + let home = scratch_home("dir"); + assert_eq!(dir_in(None, Some(home.clone().into())), Some(home.join(".docker"))); + assert_eq!(dir_in(Some("".into()), Some(home.clone().into())), Some(home.join(".docker"))); + assert_eq!(dir_in(Some("/elsewhere".into()), Some(home.into())), Some(PathBuf::from("/elsewhere"))); + assert_eq!(dir_in(None, None), None); + let _ = std::fs::remove_dir_all(scratch_home("dir")); + } + + #[test] + fn switching_to_kiri_keeps_logins_helpers_and_plugins() { + let home = scratch_home("switch"); + let dir = dir_in(None, Some(home.clone().into())).unwrap(); + let meta = dir.join("contexts/meta").join("abc123"); + std::fs::create_dir_all(&dir).unwrap(); + let before = json!({ + "auths": {"ghcr.io": {"auth": "c2VjcmV0"}}, + "credHelpers": {"123.dkr.ecr.eu-west-1.amazonaws.com": "ecr-login"}, + "cliPluginsExtraDirs": ["/Applications/Kiri.app/Contents/Resources/bin/cli-plugins"], + "currentContext": "desktop-linux", + }); + write_json(&dir.join("config.json"), &before).unwrap(); + use_ours(&dir, &meta, "kiri", "Kiri (WSL2)", "npipe:////./pipe/kiri").unwrap(); + let after = read_json(&dir.join("config.json")).unwrap(); + assert_eq!(after["currentContext"], "kiri"); + for k in ["auths", "credHelpers", "cliPluginsExtraDirs"] { + assert_eq!(after[k], before[k], "{k}"); + } + // The context Kiri made, as `docker context create` does. + let m = read_json(&meta.join("meta.json")).unwrap(); + assert_eq!((m["Name"].as_str(), m["Endpoints"]["docker"]["Host"].as_str()), (Some("kiri"), Some("npipe:////./pipe/kiri"))); + // docker's choice now, from what was written. + let config = std::fs::read(dir.join("config.json")).unwrap(); + assert!(cli(&Env { config: Some(&config), ..Env::default() }, "kiri", &[], &Endpoint::Taken("Docker Desktop".into())).kiri); + // A context already there (setup made it on another pipe) stays. + write_context(&meta, "kiri", "Kiri (WSL2)", "npipe:////./pipe/kiri-2").unwrap(); + use_ours(&dir, &meta, "kiri", "Kiri (WSL2)", "npipe:////./pipe/kiri").unwrap(); + assert_eq!(read_json(&meta.join("meta.json")).unwrap()["Endpoints"]["docker"]["Host"], "npipe:////./pipe/kiri-2"); + // Back to the default endpoint: currentContext goes, the rest stays. + set_current(&dir.join("config.json"), "default").unwrap(); + let back = read_json(&dir.join("config.json")).unwrap(); + assert!(back.get("currentContext").is_none()); + assert_eq!(back["auths"], before["auths"]); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn switching_without_a_config_makes_one_and_never_overwrites_a_broken_one() { + let home = scratch_home("broken"); + let dir = dir_in(Some(home.join("docker-config").into()), None).unwrap(); + let meta = dir.join("contexts/meta").join("abc123"); + use_ours(&dir, &meta, "kiri", "Kiri", KIRI_HOST).unwrap(); + assert_eq!(read_json(&dir.join("config.json")).unwrap(), json!({"currentContext": "kiri"})); + for broken in ["{\"auths\": {", "[1, 2]"] { + std::fs::write(dir.join("config.json"), broken).unwrap(); + let e = set_current(&dir.join("config.json"), "kiri").unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::InvalidData, "{broken}"); + assert_eq!(std::fs::read_to_string(dir.join("config.json")).unwrap(), broken, "left as it was"); + } + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn switch_validates_names_and_existing_contexts() { + let home = scratch_home("switch-ctx"); + let dir = dir_in(Some(home.join("cfg").into()), None).unwrap(); + let meta = |n: &str| dir.join("contexts/meta").join(n); + assert!(switch(&dir, &meta(""), "", "kiri", "Kiri", KIRI_HOST).is_err()); + assert!(switch(&dir, &meta(".."), "../etc", "kiri", "Kiri", KIRI_HOST).is_err()); + assert!(switch(&dir, &meta("orbstack"), "orbstack", "kiri", "Kiri", KIRI_HOST).is_err()); + write_context(&meta("orbstack"), "orbstack", "OrbStack", "unix:///tmp/orb.sock").unwrap(); + switch(&dir, &meta("orbstack"), "orbstack", "kiri", "Kiri", KIRI_HOST).unwrap(); + assert_eq!(read_json(&dir.join("config.json")).unwrap()["currentContext"], "orbstack"); + switch(&dir, &meta("kiri"), "kiri", "kiri", "Kiri", KIRI_HOST).unwrap(); + assert_eq!(read_json(&dir.join("config.json")).unwrap()["currentContext"], "kiri"); + switch(&dir, &meta("default"), "default", "kiri", "Kiri", KIRI_HOST).unwrap(); + assert!(read_json(&dir.join("config.json")).unwrap().get("currentContext").is_none()); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn status_event_reports_pinned_only_when_not_kiri() { + let c = cli(&Env { host: Some("unix:///tmp/other.sock"), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Free); + let s = status_event("0.1.4", false, "Kiri", OURS, &c); + assert_eq!((s["context"].as_str(), s["pinned"].as_str()), (Some("default"), Some("DOCKER_HOST"))); + let k = cli(&Env { host: Some(KIRI_HOST), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Free); + let sk = status_event("0.1.4", false, "Kiri", OURS, &k); + assert_eq!((sk["context"].as_str(), sk["pinned"].is_null()), (Some("kiri"), true)); + } + + #[test] + fn reads_bom_configs_normalizes_host_schemes_and_isolates_temp_files() { + let mut bom_cfg = vec![0xEF, 0xBB, 0xBF]; + bom_cfg.extend_from_slice(br#"{"currentContext":"desktop-linux","auths":{"ghcr.io":{}}}"#); + let c = cli(&Env { config: Some(&bom_cfg), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Kiri); + assert_eq!((c.context.as_str(), c.kiri), ("desktop-linux", false)); + + let home = scratch_home("bom-tmp"); + let cfg_path = home.join("config.json"); + std::fs::write(&cfg_path, &bom_cfg).unwrap(); + set_current(&cfg_path, "kiri").unwrap(); + assert_eq!(read_json(&cfg_path).unwrap()["currentContext"], "kiri"); + + write_json(&home.join("ctx.one"), &json!({"n": 1})).unwrap(); + write_json(&home.join("ctx.two"), &json!({"n": 2})).unwrap(); + assert_eq!(read_json(&home.join("ctx.one")).unwrap()["n"], 1); + assert_eq!(read_json(&home.join("ctx.two")).unwrap()["n"], 2); + assert_eq!(std::fs::read_dir(&home).unwrap().count(), 3); + + for h in ["UNIX:///var/run/docker.sock", "NPIPE:////./PIPE/DOCKER_ENGINE/", r"npipe://\\.\pipe\docker_engine\"] { + assert!(cli(&Env { host: Some(h), ..Env::default() }, OURS, &[KIRI_HOST], &Endpoint::Kiri).kiri, "{h}"); + } + assert!(cli(&Env { host: Some("npipe:////./pipe/kiri/"), ..Env::default() }, OURS, &["npipe:////./pipe/kiri"], &Endpoint::Free).kiri); + let _ = std::fs::remove_dir_all(&home); + } + + #[test] + fn sha256_hex_matches_known_vectors_and_docker_context_dir() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + assert_eq!( + sha256_hex(b"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"), + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" + ); + assert_eq!( + sha256_hex(b"kiri"), + "80d7688032dda428a5d1e0eea7ad434d219b770b7d3a0646fd58695e40107755" + ); + } + + #[test] + fn windows_config_repair_heals_wiped_config_plugins_and_dangling_desktop_context() { + let root = scratch_home("win-repair"); + let docker = root.join(".docker"); + let exe_dir = root.join("Kiri/bin"); + let plugins = exe_dir.join("cli-plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + let exe = exe_dir.join("kiri.exe"); + std::fs::write(&exe, b"").unwrap(); + assert_eq!(find_windows_cli_plugins(Some(&exe), None).as_deref(), Some(plugins.as_path())); + + // 1. Docker Desktop uninstalled and wiped `%USERPROFILE%\.docker\config.json`: + // startup self-heal restores `kiri` context, `cliPluginsExtraDirs`, and `currentContext = "kiri"`. + let r = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert_eq!( + r, + WindowsRepair { context_written: true, plugins_added: true, current_context_set: true } + ); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "kiri"); + assert_eq!(cfg["cliPluginsExtraDirs"], json!([plugins.to_string_lossy()])); + // Idempotent on subsequent starts (no redundant writes). + let r2 = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert_eq!(r2, WindowsRepair::default()); + + // 2. Dangling `desktop-linux` context (meta removed or Docker Desktop uninstalled) is healed, + // preserving registry logins, credHelpers, and aliases. + write_json( + &docker.join("config.json"), + &json!({ + "auths": {"ghcr.io": {"auth": "c2VjcmV0"}}, + "credHelpers": {"ecr": "ecr-login"}, + "aliases": {"builder": "buildx"}, + "currentContext": "desktop-linux", + }), + ) + .unwrap(); + let r3 = repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: false, + }, + ) + .unwrap(); + assert!(r3.plugins_added && r3.current_context_set); + let after = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(after["currentContext"], "kiri"); + assert_eq!(after["auths"]["ghcr.io"]["auth"], "c2VjcmV0"); + assert_eq!(after["credHelpers"]["ecr"], "ecr-login"); + assert_eq!(after["aliases"]["builder"], "buildx"); + + // 3. Corrupt config.json is never overwritten. + std::fs::write(docker.join("config.json"), "{broken").unwrap(); + assert_eq!( + repair_windows_config( + &docker, + WindowsRepairOpts { + ours: "kiri", + description: "Kiri (WSL2)", + host: "npipe:////./pipe/kiri", + plugins_dir: Some(&plugins), + force_context_write: true, + set_current_if_empty: true, + force_use: true, + desktop_installed: false, + }, + ) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + assert_eq!(std::fs::read_to_string(docker.join("config.json")).unwrap(), "{broken"); + let _ = std::fs::remove_dir_all(&root); + } + + #[cfg(unix)] + #[test] + fn sock_at_detects_kiri_taken_and_free() { + let d = scratch_home("sock-at"); + let ours_dir = d.join("kiri/run"); + std::fs::create_dir_all(&ours_dir).unwrap(); + let ours = ours_dir.join("docker.sock"); + let link = d.join("docker.sock"); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Free); + std::os::unix::fs::symlink(&ours, &link).unwrap(); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Kiri); + std::fs::remove_file(&link).unwrap(); + // Relative symlink when target exists resolves canonically to Kiri. + std::fs::write(&ours, "").unwrap(); + std::os::unix::fs::symlink("kiri/run/docker.sock", &link).unwrap(); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Kiri); + std::fs::remove_file(&link).unwrap(); + // Dangling symlink to an installed engine dir stays Taken; without dir, Free. + let orb = d.join(".orbstack/run/docker.sock"); + std::os::unix::fs::symlink(&orb, &link).unwrap(); + assert_eq!(sock_at(&link, &ours, &[d.join(".orbstack")]), Endpoint::Taken(orb.display().to_string())); + assert_eq!(sock_at(&link, &ours, &[]), Endpoint::Free); + let _ = std::fs::remove_dir_all(&d); + } +} diff --git a/crates/kiri/src/doctor.rs b/crates/kiri/src/doctor.rs new file mode 100644 index 000000000..625a23b75 --- /dev/null +++ b/crates/kiri/src/doctor.rs @@ -0,0 +1,1139 @@ +//! `kiri doctor`: whether this installation works, one line per part, and +//! what to run for a part that doesn't (#747). It asks what the window and +//! `kiri diag report` already ask, as the window's own background requests +//! (they neither wake the VM nor count as use), and changes nothing: each +//! fix stays its own command. +//! +//! On Windows the engine's lines come from the `kiri` in WSL, asked without +//! `kiri-start` so a stopped engine stays stopped, and the docker line from +//! the user's own `docker.exe`. + +use std::io::{self, Read}; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; + +use crate::flavor::CONTEXT; + +const USAGE: &str = "usage: kiri doctor [--json] whether Kiri works here, and what to run when a part doesn't (exit 1 on a failure)"; + +/// How long the engine gets for all its answers, and docker for its. +const ENGINE_WAIT: Duration = Duration::from_secs(10); +const DOCKER_WAIT: Duration = Duration::from_secs(10); + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Status { + Ok, + /// Works, but not all the way: names, a router moved aside, docker elsewhere. + Warn, + /// Kiri can't be used until it is put right: the exit code says so. + Fail, +} + +impl Status { + fn word(self) -> &'static str { + match self { + Status::Ok => "ok", + Status::Warn => "warn", + Status::Fail => "fail", + } + } + + #[cfg(any(windows, test))] + fn from_word(w: &str) -> Option { + [Status::Ok, Status::Warn, Status::Fail] + .into_iter() + .find(|s| s.word() == w) + } +} + +#[derive(Debug, PartialEq)] +struct Check { + name: String, + status: Status, + detail: String, +} + +fn check(name: impl Into, status: Status, detail: impl Into) -> Check { + Check { + name: name.into(), + status, + detail: detail.into(), + } +} + +pub fn run(args: &[String]) -> io::Result<()> { + let json = match args + .iter() + .map(String::as_str) + .collect::>() + .as_slice() + { + [] => false, + ["--json"] => true, + ["-h" | "--help" | "help"] => { + println!("{USAGE}"); + return Ok(()); + } + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + }; + let checks = checks(); + if json { + println!("{}", to_json(&checks)); + } else { + print!("{}", render(&checks)); + } + if checks.iter().any(|c| c.status == Status::Fail) { + // The lines said what is wrong; a `kiri: …` line after them would only repeat it. + std::process::exit(1); + } + Ok(()) +} + +// ---- the engine (Mac, Linux, and WSL for Windows) ---- + +#[cfg(any(unix, test))] +/// An answer from the engine: its JSON, or the error's kind and text. `None` +/// in its slot means no answer within `ENGINE_WAIT`. +type Answer = Option>; + +#[cfg(unix)] +/// What the engine is asked, in order: once /_ping fails nothing else is. +const ASKED: [&str; 4] = ["/_ping", "/version", "/info", "/kiri/domains"]; + +#[cfg(unix)] +fn checks() -> Vec { + // Set by Windows' `kiri doctor`, which checks docker on its own side. + let forwarded = std::env::var_os("KIRI_DOCTOR_FORWARDED").is_some(); + let socket = crate::client::socket() + .map(|p| p.display().to_string()) + .unwrap_or_else(|_| "?".into()); + let got = engine_answers(); + // Down, the engine can't say; a read-only disk is what keeps it down (#768). + let local = if matches!(got[0], Some(Ok(_))) { + None + } else { + crate::daemon::rofs::check_daemon_storage(None) + }; + let mut out = engine_checks(&got, &socket, forwarded, local); + if !forwarded { + let create = format!( + "docker context create {c} --docker host=unix://{socket} && docker context use {c}", + c = CONTEXT.get() + ); + out.insert(1, docker(&ours_unix, &create)); + } + #[cfg(target_os = "macos")] + out.push(names(crate::daemon::dns::installed())); + out +} + +/// The engine's answers, each as soon as it comes, for at most `ENGINE_WAIT` +/// in all: an engine that is hung, or answers a byte at a time, would +/// otherwise keep this waiting (the client's limit is per read). +#[cfg(unix)] +fn engine_answers() -> [Answer; 4] { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + for (i, path) in ASKED.into_iter().enumerate() { + let r = crate::client::get_background(path).map_err(|e| { + // Nothing there, or a socket this user can't open: say it as other commands do. + let gone = !matches!( + e.kind(), + io::ErrorKind::Other | io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut + ); + let e = if i == 0 && gone { + crate::client::check_alive().err().unwrap_or(e) + } else { + e + }; + (e.kind(), e.to_string()) + }); + let stop = i == 0 && r.is_err(); + if tx.send((i, r)).is_err() || stop { + return; + } + } + }); + let until = Instant::now() + ENGINE_WAIT; + let mut got: [Answer; 4] = Default::default(); + while let Ok((i, r)) = rx.recv_timeout(until.saturating_duration_since(Instant::now())) { + got[i] = Some(r); + } + got +} + +#[cfg(any(unix, test))] +/// The engine's lines from its answers: engine, http, https, storage. +fn engine_checks( + got: &[Answer; 4], + socket: &str, + forwarded: bool, + local_storage: Option, +) -> Vec { + let mut out = Vec::new(); + let engine = match &got[0] { + None => check( + "engine", + Status::Fail, + format!( + "{socket} took the connection but answered nothing in 10 s: the engine may be hung (kiri diag logs --engine)" + ), + ), + Some(Err((io::ErrorKind::Other, m))) => check( + "engine", + Status::Fail, + format!("the engine answers, with an error: {m}"), + ), + Some(Err((io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut, _))) => check( + "engine", + Status::Fail, + format!( + "{socket} took the connection but answered nothing: the engine may be hung (kiri diag logs --engine)" + ), + ), + Some(Err((io::ErrorKind::PermissionDenied, m))) => check("engine", Status::Fail, m.clone()), + Some(Err(_)) if forwarded => check( + "engine", + Status::Fail, + "the engine isn't running in Kiri's WSL distro: kiri start", + ), + Some(Err((_, m))) => check("engine", Status::Fail, m.clone()), + Some(Ok(_)) => engine_line(&got[1], &got[2], socket), + }; + out.push(engine); + if !matches!(got[0], Some(Ok(_))) { + out.extend(local_storage.map(|m| check("storage", Status::Fail, m))); + return out; + } + out.extend(domains(&got[3])); + out.extend(storage(&got[2])); + out +} + +#[cfg(any(unix, test))] +fn engine_line(version: &Answer, info: &Answer, socket: &str) -> Check { + let mut c = match version { + None => check( + "engine", + Status::Warn, + "answers /_ping but not /version within 10 s: it may be busy or hung", + ), + Some(Err((_, m))) => check( + "engine", + Status::Warn, + format!("answers /_ping, but /version failed: {m}"), + ), + // A Docker engine of another kind behind KIRI_SOCKET. + Some(Ok(v)) if v["Platform"]["Name"].as_str().is_some_and(|n| n != "Kiri") => check( + "engine", + Status::Warn, + format!( + "{socket} is {}, not Kiri", + v["Platform"]["Name"].as_str().unwrap_or("?") + ), + ), + // KiriVersion, or Version from an engine older than that field (client::kiri_version). + Some(Ok(v)) => check( + "engine", + Status::Ok, + format!( + "Kiri {}, socket {socket}", + v["KiriVersion"] + .as_str() + .or_else(|| v["Version"].as_str()) + .unwrap_or("?") + ), + ), + }; + if matches!(info, Some(Ok(i)) if i["KiriStopped"] == true) { + c.status = Status::Warn; + c.detail + .push_str("; stopped (Stop in the window or tray): kiri start starts it"); + } + c +} + +#[cfg(any(unix, test))] +/// The `*.kiri.local` routers, from the engine's `/kiri/domains`. +fn domains(answer: &Answer) -> Vec { + let both = |status, detail: String| { + vec![ + check("http", status, detail.clone()), + check("https", status, detail), + ] + }; + let report = match answer { + None => return both(Status::Warn, "the engine didn't say within 10 s".into()), + Some(Err((_, m))) => return both(Status::Warn, format!("the engine didn't say: {m}")), + Some(Ok(r)) if r["http"].is_object() && r["https"].is_object() => r, + Some(Ok(_)) => return both(Status::Warn, "the engine's answer wasn't readable".into()), + }; + ["http", "https"] + .into_iter() + .map(|key| { + let r = &report[key]; + let port = r["port"].as_u64().map_or_else(|| "?".into(), |p| p.to_string()); + // A port set by the environment can't be moved here (domains.rs refuses it). + let (by, fix) = match r["env"].as_str() { + Some(var) => (format!(" (set by {var})"), format!("change or unset {var}")), + None => (String::new(), format!("kiri domains set --{key} N")), + }; + match (r["running"] == true, r["serving"] != false) { + (true, true) => check(key, Status::Ok, format!("port {port}{by}")), + (true, false) => check(key, Status::Warn, format!("port {port}{by}: a container has the port for now; {fix} moves the router")), + (false, _) => check(key, Status::Warn, format!("off, port {port}{by}: names under kiri.local don't answer over {key}; {fix} tries another port")), + } + }) + .collect() +} + +#[cfg(any(unix, test))] +/// The engine's storage: read-only means nothing can be written (#768). An +/// engine that predates the field says nothing, and nor does this. +fn storage(info: &Answer) -> Option { + match info { + None => Some(check( + "storage", + Status::Warn, + "the engine didn't say within 10 s", + )), + Some(Err((_, m))) => Some(check( + "storage", + Status::Warn, + format!("the engine didn't say: {m}"), + )), + Some(Ok(i)) => match i.get("KiriStorageReadOnly") { + Some(Value::String(why)) => Some(check("storage", Status::Fail, why.clone())), + Some(_) => Some(check("storage", Status::Ok, "writable")), + None => None, + }, + } +} + +/// macOS sends `*.kiri.local` lookups to Kiri only with its resolver file. +#[cfg(any(target_os = "macos", test))] +fn names(installed: bool) -> Check { + if installed { + check("names", Status::Ok, "*.kiri.local resolves to Kiri") + } else { + check( + "names", + Status::Warn, + "*.kiri.local doesn't resolve (/etc/resolver/kiri.local is missing; *.kiri.localhost works): kiri setup --domains", + ) + } +} + +// ---- docker ---- + +/// Whether a docker host is this Kiri's socket: `Some(false)` only when +/// both are local sockets and resolve to different files (another Kiri, +/// such as the installed one next to Kiri Dev). On Linux, a root daemon +/// without `KIRI_SOCKET` binds both `/run/kiri/docker.sock` and +/// `~/.kiri/run/docker.sock`, so both belong to this Kiri. +#[cfg(unix)] +fn ours_unix(host: &str) -> Option { + let raw = std::path::Path::new(host.strip_prefix("unix://")?); + let theirs = std::fs::canonicalize(raw).ok()?; + let ours = std::fs::canonicalize(crate::client::socket().ok()?).ok()?; + if theirs == ours { + return Some(true); + } + #[cfg(target_os = "linux")] + if std::env::var_os("KIRI_SOCKET").is_none() { + use std::os::unix::fs::{FileTypeExt, MetadataExt}; + if let Ok(home_sock) = crate::daemon::home_socket_path() + && let Ok(md) = std::fs::symlink_metadata(&home_sock) + && !md.file_type().is_symlink() + && md.file_type().is_socket() + && md.uid() == 0 + && std::fs::symlink_metadata(crate::client::SERVICE_SOCKET) + .is_ok_and(|smd| !smd.file_type().is_symlink() && smd.file_type().is_socket() && smd.uid() == 0) + && std::fs::canonicalize(&home_sock).ok().as_ref() == Some(&theirs) + { + return Some(true); + } + } + Some(false) +} + +enum Reached { + /// The server's platform name ("" from an engine that has none). + Server(String), + Failed, + TimedOut, +} + +/// Which engine plain `docker` reaches, asked of docker itself, so a +/// context, DOCKER_HOST and a packaged wrapper count as they do for the user. +fn docker(ours: &dyn Fn(&str) -> Option, create: &str) -> Check { + let until = Instant::now() + DOCKER_WAIT; + let docker = || { + let mut c = Command::new("docker"); + c.env_remove("KIRI_DOCTOR_FORWARDED"); + c + }; + let version = match run_for( + docker().args(["version", "--format", "{{.Server.Platform.Name}}"]), + until, + ) { + Err(e) if e.kind() == io::ErrorKind::NotFound => { + return check("docker", Status::Warn, "no `docker` command found on PATH"); + } + Err(e) => { + return check( + "docker", + Status::Warn, + format!("`docker` couldn't be run: {e}"), + ); + } + Ok(r) => r, + }; + let (reached, why) = match &version { + None => (Reached::TimedOut, String::new()), + Some(r) if r.ok => ( + Reached::Server(first_line(&text(&r.out)).to_owned()), + String::new(), + ), + // docker's own error is its last line; Docker Desktop's WSL shim says why on stdout, first. + Some(r) => { + let err = text(&r.err); + let why = match err.lines().rev().find(|l| !l.trim().is_empty()) { + Some(last) => first_line(last).to_owned(), + None => first_line(&text(&r.out)).to_owned(), + }; + (Reached::Failed, why) + } + }; + let context = run_for( + docker().args([ + "context", + "inspect", + "--format", + "{{.Name}}\t{{.Endpoints.docker.Host}}", + ]), + Instant::now() + Duration::from_secs(2), + ) + .ok() + .flatten() + .filter(|r| r.ok) + .and_then(|r| { + text(&r.out) + .lines() + .next() + .and_then(|l| l.split_once('\t')) + .map(|(n, h)| (n.to_owned(), h.to_owned())) + }); + let env_host = std::env::var("DOCKER_HOST").ok().filter(|s| !s.is_empty()); + let pinned = if env_host.is_some() { + Some("DOCKER_HOST") + } else if std::env::var_os("DOCKER_CONTEXT").is_some_and(|s| !s.is_empty()) { + Some("DOCKER_CONTEXT") + } else { + None + }; + let (name, ctx_host) = context + .as_ref() + .map_or((None, None), |(n, h)| (Some(n.as_str()), Some(h.as_str()))); + let host = env_host.as_deref().or(ctx_host); + let ours = host.and_then(ours); + let have_ours = || { + run_for( + docker().args(["context", "inspect", CONTEXT.get()]), + Instant::now() + Duration::from_secs(2), + ) + .ok() + .flatten() + .is_some_and(|r| r.ok) + }; + let fix = match pinned { + Some(var) => format!("unset {var}, or point it at Kiri"), + // At this Kiri already: nothing to say, and no time spent asking. + None if ours != Some(false) && matches!(reached, Reached::Server(ref n) if n == "Kiri") => { + String::new() + } + None if have_ours() => format!("docker context use {}", CONTEXT.get()), + None => create.to_owned(), + }; + docker_verdict(&reached, &why, name, host, pinned, ours, &fix) +} + +fn docker_verdict( + reached: &Reached, + why: &str, + context: Option<&str>, + host: Option<&str>, + pinned: Option<&str>, + ours: Option, + fix: &str, +) -> Check { + let how = match (pinned, context) { + (Some(var), _) => format!("{var} is set"), + (None, Some(c)) => format!("context `{c}`"), + (None, None) => "context unknown".into(), + }; + // Already pointed at Kiri: no answer then is the engine's trouble, not docker's. + let at_kiri = ours == Some(true) || (pinned.is_none() && context == Some(CONTEXT.get())); + match reached { + Reached::Server(n) if n == "Kiri" && ours == Some(false) => check( + "docker", + Status::Warn, + format!( + "`docker` reaches another Kiri ({how}, {}): {fix}", + host.unwrap_or("?") + ), + ), + Reached::Server(n) if n == "Kiri" => check( + "docker", + Status::Ok, + format!("`docker` reaches Kiri ({how})"), + ), + Reached::Server(n) if !n.is_empty() => check( + "docker", + Status::Warn, + format!("`docker` reaches {n}, not Kiri ({how}): {fix}"), + ), + Reached::Server(_) => check( + "docker", + Status::Warn, + format!("`docker` reaches an engine that isn't Kiri ({how}): {fix}"), + ), + Reached::Failed | Reached::TimedOut if at_kiri => check( + "docker", + Status::Warn, + format!("`docker` is set to Kiri ({how}) but gets no answer: see the engine line"), + ), + Reached::Failed => check( + "docker", + Status::Warn, + format!( + "`docker` reaches no engine ({how}): {}; {fix}", + if why.is_empty() { "no answer" } else { why } + ), + ), + Reached::TimedOut => check( + "docker", + Status::Warn, + format!("`docker` got no answer in 10 s ({how}): {fix}"), + ), + } +} + +/// A line of a tool's output fit for one line here: its first non-empty +/// one, cut at 200 characters. +fn first_line(s: &str) -> &str { + let l = s + .lines() + .map(str::trim) + .find(|l| !l.is_empty()) + .unwrap_or(""); + l.char_indices().nth(200).map_or(l, |(i, _)| &l[..i]) +} + +fn text(b: &[u8]) -> String { + String::from_utf8_lossy(b).into_owned() +} + +struct Ran { + ok: bool, + out: Vec, + err: Vec, +} + +/// Runs `cmd` until `until` at the latest, its output read as it comes (so +/// a full pipe never stalls it). Past `until` it is killed with what it +/// started, and the answer is `None`. +fn run_for(cmd: &mut Command, until: Instant) -> io::Result> { + cmd.stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(cmd, 0); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(cmd, 0x0800_0000); + let mut child = cmd.spawn()?; + let (out, err) = (reader(child.stdout.take()), reader(child.stderr.take())); + let status = loop { + if let Some(s) = child.try_wait()? { + break s; + } + if Instant::now() >= until { + kill_tree(&mut child); + return Ok(None); + } + std::thread::sleep(Duration::from_millis(20)); + }; + // A process it left holding the pipes doesn't hold this up past `until`. + let grace = until + .saturating_duration_since(Instant::now()) + .max(Duration::from_millis(200)); + let take = |rx: mpsc::Receiver>| rx.recv_timeout(grace).unwrap_or_default(); + Ok(Some(Ran { + ok: status.success(), + out: take(out), + err: take(err), + })) +} + +fn reader(r: Option) -> mpsc::Receiver> { + let (tx, rx) = mpsc::channel(); + std::thread::spawn(move || { + let mut b = Vec::new(); + if let Some(mut r) = r { + let _ = r.read_to_end(&mut b); + } + let _ = tx.send(b); + }); + rx +} + +/// Kills `child` and every process it started (its process group; on +/// Windows, its tree). +fn kill_tree(child: &mut std::process::Child) { + #[cfg(unix)] + if let Ok(pid) = i32::try_from(child.id()) { + // SAFETY: a plain signal to the group this child leads (`process_group(0)`). + unsafe { + libc::killpg(pid, libc::SIGKILL); + } + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt as _; + let _ = Command::new("taskkill") + .args(["/F", "/T", "/PID", &child.id().to_string()]) + .creation_flags(0x0800_0000) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + let _ = child.kill(); + let _ = child.wait(); +} + +// ---- Windows ---- + +/// The engine's own `kiri doctor` in WSL, without kiri-start (which would +/// start a stopped engine) and without its docker line. +#[cfg(any(windows, test))] +const FORWARD_SCRIPT: &str = r#"export HOME=/var/lib/kiri-daemon KIRI_DOCTOR_FORWARDED=1; exec /usr/local/bin/kiri doctor --json"#; + +#[cfg(windows)] +fn checks() -> Vec { + let mut out = engine_from_wsl(); + out.insert( + 1.min(out.len()), + docker( + &|_| None, + &format!( + "docker context use {} (Kiri creates it at start)", + CONTEXT.get() + ), + ), + ); + out +} + +#[cfg(windows)] +fn engine_from_wsl() -> Vec { + let stopped = |why: String| { + vec![check( + "engine", + Status::Warn, + format!("stopped{why}: kiri start starts it"), + )] + }; + let local = std::env::var_os("LOCALAPPDATA").map(std::path::PathBuf::from); + if local + .as_ref() + .is_some_and(|d| crate::wsl::stopped_marker_in(d).exists()) + { + return stopped(" (Stop in the window or tray)".into()); + } + let Some(distro) = crate::wsl::distro() else { + return vec![check( + "engine", + Status::Fail, + "Kiri isn't set up yet: open Kiri from the Start menu", + )]; + }; + let system = std::env::var_os("SystemRoot").map_or_else( + || std::path::PathBuf::from(r"C:\Windows"), + std::path::PathBuf::from, + ); + let wsl = system.join("System32").join("wsl.exe"); + // Asking a distro that isn't running would boot it, and the engine with it. + if let Ok(Some(r)) = run_for( + Command::new(&wsl).args(["--list", "--running", "--quiet"]), + Instant::now() + ENGINE_WAIT, + ) && r.ok + && !running_distros(&r.out) + .iter() + .any(|d| d.eq_ignore_ascii_case(&distro)) + { + return stopped(format!(" (its WSL distro {distro} isn't running)")); + } + match run_for(Command::new(&wsl).args(["-d", &distro, "-u", "root", "-e", "sh", "-c", FORWARD_SCRIPT]), Instant::now() + ENGINE_WAIT * 3) { + Ok(Some(r)) => from_forwarded(&text(&r.out)).unwrap_or_else(|| { + let err = text(&r.err); + let detail = match first_line(&err) { + // A kiri from before `kiri doctor` prints its usage. + why if why.is_empty() || why.starts_with("usage: kiri") => "the engine's kiri in WSL has no `kiri doctor` (it is older than this one): update Kiri".to_owned(), + why => format!("the engine's kiri in WSL gave no doctor answer: {why}"), + }; + vec![check("engine", Status::Fail, detail)] + }), + Ok(None) => vec![check("engine", Status::Fail, "the engine's kiri in WSL didn't answer in 30 s")], + Err(e) => vec![check("engine", Status::Fail, format!("could not run wsl.exe ({e})"))], + } +} + +/// `wsl --list --quiet` writes UTF-16, one distro a line. +#[cfg(any(windows, test))] +fn running_distros(out: &[u8]) -> Vec { + let s = if out.contains(&0) { + String::from_utf16_lossy( + &out.as_chunks::<2>() + .0 + .iter() + .map(|c| u16::from_le_bytes(*c)) + .collect::>(), + ) + } else { + text(out) + }; + s.lines() + .map(|l| { + l.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}') + .to_owned() + }) + .filter(|l| !l.is_empty()) + .collect() +} + +/// The checks from the WSL side's `--json`. +#[cfg(any(windows, test))] +fn from_forwarded(out: &str) -> Option> { + let v: Value = serde_json::from_str(out.trim()).ok()?; + v["checks"] + .as_array()? + .iter() + .map(|c| { + Some(check( + c["name"].as_str()?, + Status::from_word(c["status"].as_str()?)?, + c["detail"].as_str()?, + )) + }) + .collect() +} + +// ---- output ---- + +fn render(checks: &[Check]) -> String { + checks + .iter() + .map(|c| format!("{:<13} {:<5} {}\n", c.name, c.status.word(), c.detail)) + .collect() +} + +fn to_json(checks: &[Check]) -> Value { + json!({ + "ok": !checks.iter().any(|c| c.status == Status::Fail), + "checks": checks.iter().map(|c| json!({"name": c.name, "status": c.status.word(), "detail": c.detail})).collect::>(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ok(v: Value) -> Answer { + Some(Ok(v)) + } + fn err(kind: io::ErrorKind, m: &str) -> Answer { + Some(Err((kind, m.into()))) + } + const SOCK: &str = "/run/kiri/docker.sock"; + fn healthy() -> [Answer; 4] { + [ + ok(Value::Null), + ok(json!({"KiriVersion": "0.2.3", "Platform": {"Name": "Kiri"}})), + ok(json!({"KiriStorageReadOnly": null, "KiriStopped": false})), + ok( + json!({"http": {"port": 80, "running": true, "serving": true, "env": null}, "https": {"port": 443, "running": true, "serving": true, "env": null}}), + ), + ] + } + fn names_of(c: &[Check]) -> Vec<&str> { + c.iter().map(|c| c.name.as_str()).collect() + } + + #[test] + fn a_healthy_engine_gives_four_ok_lines() { + let c = engine_checks(&healthy(), SOCK, false, None); + assert_eq!(names_of(&c), ["engine", "http", "https", "storage"]); + assert!(c.iter().all(|c| c.status == Status::Ok), "{c:?}"); + assert_eq!(c[0].detail, "Kiri 0.2.3, socket /run/kiri/docker.sock"); + } + + #[test] + fn an_engine_that_is_down_hung_or_erroring_says_which() { + let mut got: [Answer; 4] = Default::default(); + let down = engine_checks(&got, SOCK, false, None); + assert_eq!((down.len(), down[0].status), (1, Status::Fail)); + assert!( + down[0].detail.contains("answered nothing in 10 s"), + "{down:?}" + ); + got[0] = err(io::ErrorKind::Other, "Internal Server Error"); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0].detail, + "the engine answers, with an error: Internal Server Error" + ); + got[0] = err(io::ErrorKind::NotConnected, "Kiri isn't running. Open Kiri"); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0].detail, + "Kiri isn't running. Open Kiri" + ); + assert_eq!( + engine_checks(&got, SOCK, true, None)[0].detail, + "the engine isn't running in Kiri's WSL distro: kiri start" + ); + got[0] = err( + io::ErrorKind::PermissionDenied, + "permission denied. Run `sudo kiri host-access $USER`", + ); + assert!( + engine_checks(&got, SOCK, true, None)[0] + .detail + .starts_with("permission denied") + ); + // Down because the disk went read-only: that is the line that says why. + let ro = engine_checks(&got, SOCK, false, Some("Kiri's disk is read-only".into())); + assert_eq!( + ro[1], + check("storage", Status::Fail, "Kiri's disk is read-only") + ); + } + + #[test] + fn a_stopped_or_foreign_or_slow_engine_is_not_ok() { + let mut got = healthy(); + got[2] = ok(json!({"KiriStorageReadOnly": null, "KiriStopped": true})); + let c = engine_checks(&got, SOCK, false, None); + assert_eq!(c[0].status, Status::Warn); + assert!( + c[0].detail + .ends_with("stopped (Stop in the window or tray): kiri start starts it"), + "{}", + c[0].detail + ); + got = healthy(); + got[1] = + ok(json!({"Version": "27.3.1", "Platform": {"Name": "Docker Engine - Community"}})); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0].detail, + "/run/kiri/docker.sock is Docker Engine - Community, not Kiri" + ); + got[1] = ok(json!({"Version": "0.1.9"})); + assert_eq!( + engine_checks(&got, SOCK, false, None)[0], + check( + "engine", + Status::Ok, + "Kiri 0.1.9, socket /run/kiri/docker.sock" + ) + ); + got[1] = None; + got[2] = None; + got[3] = None; + let slow = engine_checks(&got, SOCK, false, None); + assert_eq!(names_of(&slow), ["engine", "http", "https", "storage"]); + assert!(slow.iter().all(|c| c.status == Status::Warn), "{slow:?}"); + } + + #[test] + fn each_router_is_ok_moved_aside_off_or_unreadable() { + let r = |http: Value| { + ok(json!({"http": http, "https": {"port": 443, "running": true, "serving": true}})) + }; + assert_eq!( + domains(&r(json!({"port": 80, "running": true})))[0], + check("http", Status::Ok, "port 80") + ); + let moved = &domains(&r(json!({"port": 80, "running": true, "serving": false})))[0]; + assert_eq!( + moved.detail, + "port 80: a container has the port for now; kiri domains set --http N moves the router" + ); + let pinned = &domains(&r( + json!({"port": 18780, "running": false, "env": "KIRI_HTTP_PORT"}), + ))[0]; + assert!( + pinned + .detail + .starts_with("off, port 18780 (set by KIRI_HTTP_PORT)") + && pinned + .detail + .ends_with("change or unset KIRI_HTTP_PORT tries another port"), + "{}", + pinned.detail + ); + for bad in [ + ok(json!({})), + ok(Value::Null), + ok(json!({"http": 1, "https": 2})), + err( + io::ErrorKind::Other, + "Kiri does not support GET /kiri/domains yet", + ), + None, + ] { + let c = domains(&bad); + assert_eq!(names_of(&c), ["http", "https"]); + assert!( + c.iter() + .all(|c| c.status == Status::Warn && !c.detail.contains("tries another port")), + "{c:?}" + ); + } + } + + #[test] + fn storage_says_only_what_the_engine_said() { + assert_eq!( + storage(&ok( + json!({"KiriStorageReadOnly": "the store is read-only"}) + )), + Some(check("storage", Status::Fail, "the store is read-only")) + ); + assert_eq!( + storage(&ok(json!({"KiriStorageReadOnly": null}))), + Some(check("storage", Status::Ok, "writable")) + ); + assert_eq!(storage(&ok(json!({"Containers": 3}))), None); + assert_eq!( + storage(&err(io::ErrorKind::Other, "boom")).unwrap().status, + Status::Warn + ); + assert_eq!(storage(&None).unwrap().status, Status::Warn); + } + + #[test] + fn docker_is_ok_only_at_this_kiri_and_its_advice_fits_the_case() { + let ctx = CONTEXT.get(); + let kiri = Reached::Server("Kiri".into()); + assert_eq!( + docker_verdict( + &kiri, + "", + Some(ctx), + Some("unix:///x"), + None, + Some(true), + "" + ) + .status, + Status::Ok + ); + let other_kiri = docker_verdict( + &kiri, + "", + Some("default"), + Some("unix:///var/run/docker.sock"), + None, + Some(false), + "docker context use kiri", + ); + assert!( + other_kiri.status == Status::Warn && other_kiri.detail.contains("another Kiri"), + "{other_kiri:?}" + ); + let desktop = docker_verdict( + &Reached::Server("Docker Desktop 4.40.0 (187762)".into()), + "", + Some("desktop-linux"), + None, + None, + None, + "docker context use kiri", + ); + assert_eq!( + desktop.detail, + "`docker` reaches Docker Desktop 4.40.0 (187762), not Kiri (context `desktop-linux`): docker context use kiri" + ); + assert!( + docker_verdict( + &Reached::Server(String::new()), + "", + Some("default"), + None, + None, + None, + "x" + ) + .detail + .contains("isn't Kiri") + ); + // On Kiri's context and nothing answers: the engine is the trouble, not the context. + let down = docker_verdict( + &Reached::Failed, + "Cannot connect", + Some(ctx), + None, + None, + None, + "docker context use kiri", + ); + assert_eq!( + down.detail, + format!( + "`docker` is set to Kiri (context `{ctx}`) but gets no answer: see the engine line" + ) + ); + let pinned = docker_verdict( + &Reached::Failed, + "Cannot connect to the Docker daemon at tcp://10.0.0.9:2375.", + Some("default"), + None, + Some("DOCKER_HOST"), + None, + "unset DOCKER_HOST, or point it at Kiri", + ); + assert_eq!( + pinned.detail, + "`docker` reaches no engine (DOCKER_HOST is set): Cannot connect to the Docker daemon at tcp://10.0.0.9:2375.; unset DOCKER_HOST, or point it at Kiri" + ); + assert!( + docker_verdict( + &Reached::TimedOut, + "", + Some("remote"), + None, + None, + None, + "f" + ) + .detail + .starts_with("`docker` got no answer in 10 s") + ); + } + + #[test] + fn a_tools_message_is_one_line() { + let shim = "\nThe command 'docker' could not be found in this WSL 2 distro.\nWe recommend to activate the WSL integration in Docker Desktop settings.\n"; + assert_eq!( + first_line(shim), + "The command 'docker' could not be found in this WSL 2 distro." + ); + assert_eq!(first_line(&"x".repeat(500)).len(), 200); + assert_eq!(first_line("é".repeat(300).as_str()).chars().count(), 200); + } + + /// A tool that floods its pipes, or hangs leaving a child behind, is + /// read or stopped within the time it was given. + #[cfg(unix)] + #[test] + fn a_tool_is_read_as_it_writes_and_stopped_with_its_children() { + let big = run_for( + Command::new("sh").args(["-c", "head -c 300000 /dev/zero | tr '\\0' x >&2; echo Kiri"]), + Instant::now() + Duration::from_secs(5), + ) + .unwrap() + .unwrap(); + assert!(big.ok && big.err.len() == 300_000 && text(&big.out).trim() == "Kiri"); + let marker = format!("kiri-doctor-hang-{}", std::process::id()); + let t = Instant::now(); + let hung = run_for( + Command::new("sh").args(["-c", &format!("sh -c 'exec sleep 30 {marker}' & sleep 30")]), + Instant::now() + Duration::from_millis(300), + ) + .unwrap(); + assert!( + hung.is_none() && t.elapsed() < Duration::from_secs(3), + "{:?}", + t.elapsed() + ); + let left = Command::new("pgrep") + .args(["-f", &marker]) + .output() + .unwrap(); + assert!( + left.stdout.is_empty(), + "left running: {}", + text(&left.stdout) + ); + assert_eq!( + run_for( + &mut Command::new("kiri-doctor-no-such-tool"), + Instant::now() + Duration::from_secs(1) + ) + .err() + .map(|e| e.kind()), + Some(io::ErrorKind::NotFound) + ); + } + + #[test] + fn windows_reads_the_wsl_sides_answer() { + let out = r#"{"checks":[{"detail":"Kiri 0.2.3","name":"engine","status":"ok"},{"detail":"read-only","name":"storage","status":"fail"}],"ok":false}"#; + assert_eq!( + from_forwarded(out).unwrap(), + vec![ + check("engine", Status::Ok, "Kiri 0.2.3"), + check("storage", Status::Fail, "read-only") + ] + ); + for bad in [ + "", + "kiri: usage: kiri COMMAND", + r#"{"checks":[{"name":"engine","status":"maybe","detail":""}]}"#, + ] { + assert!(from_forwarded(bad).is_none(), "{bad}"); + } + let utf16: Vec = "Kiri\r\nUbuntu\r\n" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + assert_eq!(running_distros(&utf16), ["Kiri", "Ubuntu"]); + assert!(!FORWARD_SCRIPT.contains("kiri-start")); + } + + #[test] + fn only_a_failure_makes_it_not_ok() { + let warn_only = [check("http", Status::Warn, "off"), names(false)]; + assert_eq!(to_json(&warn_only)["ok"], true); + let failed = [ + check("engine", Status::Ok, "Kiri 0.2.3"), + check("storage", Status::Fail, "the store is read-only"), + ]; + let j = to_json(&failed); + assert_eq!(j["ok"], false); + assert_eq!( + j["checks"][1], + json!({"name": "storage", "status": "fail", "detail": "the store is read-only"}) + ); + assert_eq!( + render(&failed), + "engine ok Kiri 0.2.3\nstorage fail the store is read-only\n" + ); + } + + #[test] + fn refuses_what_it_does_not_take() { + for bad in [&["--fix"][..], &["--json", "--json"], &["engine"]] { + let args: Vec = bad.iter().map(|s| s.to_string()).collect(); + assert_eq!( + run(&args).unwrap_err().kind(), + io::ErrorKind::InvalidInput, + "{bad:?}" + ); + } + assert!(!crate::docker::handles("doctor")); + } +} diff --git a/crates/kiri/src/domains_cli.rs b/crates/kiri/src/domains_cli.rs index 5ffd12c72..a077c0b17 100644 --- a/crates/kiri/src/domains_cli.rs +++ b/crates/kiri/src/domains_cli.rs @@ -10,7 +10,8 @@ use crate::client; const USAGE: &str = "usage: kiri domains the routers' ports, and whether each runs kiri domains set [--http N] [--https N] move them (no restart) - kiri domains reset back to the ports a start gives (a test copy's: off)"; + kiri domains reset back to the ports a start gives (a test copy's: off) + --json, with any of them, prints the engine's answer as one line of JSON"; #[derive(Debug, PartialEq)] enum Cmd { @@ -76,7 +77,23 @@ fn answer(r: client::Response) -> io::Result { } pub fn run(args: &[String]) -> io::Result<()> { - let v = match parse(args).map_err(io::Error::other)? { + run_with(args, client::alive) +} + +fn run_with(args: &[String], alive: impl FnOnce() -> bool) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let json = args.iter().any(|a| a == "--json"); + let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); + let cmd = parse(&args).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + if !alive() { + return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); + } + let v = match cmd { Cmd::Show => client::get("/kiri/domains")?, Cmd::Set { http, https } => { let now = if http.is_none() || https.is_none() { client::get("/kiri/domains")? } else { Value::Null }; @@ -86,14 +103,19 @@ pub fn run(args: &[String]) -> io::Result<()> { } Cmd::Reset => answer(client::request("DELETE", "/kiri/domains", None)?)?, }; - print!("{}", format(&v)); + if json { + println!("{v}"); + } else { + print!("{}", format(&v)); + } Ok(()) } #[cfg(test)] mod tests { - use super::{Cmd, format, parse}; + use super::{Cmd, format, parse, run_with}; use serde_json::json; + use std::io; fn args(s: &str) -> Vec { s.split_whitespace().map(String::from).collect() @@ -130,4 +152,27 @@ mod tests { let moved = json!({"http": {"port": 18780, "running": true, "serving": false, "env": "KIRI_HTTP_PORT"}, "https": {"port": 18743, "running": true, "serving": true, "env": null}}); assert_eq!(format(&moved), "HTTP 18780 on, a container has the port for now (set by KIRI_HTTP_PORT)\nHTTPS 18743 on\n"); } + + #[test] + fn help_succeeds_without_touching_the_socket() { + for h in ["--help", "-h", "help", "set --help", "reset -h"] { + run_with(&args(h), || panic!("help must not check daemon: {h}")).unwrap(); + } + } + + #[test] + fn bad_arguments_fail_before_touching_the_socket() { + for bad in ["set --http nope", "set --http 0", "set --https 70000", "set --http", "set", "set --port 80", "reset now", "show", "--unknown", "--json show"] { + let err = run_with(&args(bad), || panic!("checked daemon before arguments: {bad}")).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad}: {err}"); + } + } + + #[test] + fn says_when_the_daemon_is_not_running() { + for cmd in ["", "--json", "set --http 8080 --https 8443", "set --http 8080 --json", "reset"] { + let err = run_with(&args(cmd), || false).unwrap_err(); + assert_eq!(err.to_string(), "kiri daemon is not running: open Kiri or run `kiri daemon`", "{cmd}"); + } + } } diff --git a/crates/kiri/src/engine_cli.rs b/crates/kiri/src/engine_cli.rs new file mode 100644 index 000000000..fa76c94bb --- /dev/null +++ b/crates/kiri/src/engine_cli.rs @@ -0,0 +1,733 @@ +//! `kiri engine start | stop | restart | status [--json]`: start, stop, restart +//! and inspect Kiri's engine from the terminal (#983). +//! +//! `status` uses background requests (`X-Kiri-Background: 1`, and on Windows +//! checks `%LOCALAPPDATA%\Kiri\stopped` and `wsl --list --running --quiet` +//! before querying WSL without `kiri-start`), so inspecting engine status never +//! wakes a sleeping VM or boots a stopped WSL distro. Exits 0 when the engine +//! is `running` or `asleep`, and exits 1 when `stopped` or `not_running`. + +use std::io; + +use serde::Serialize; +use serde_json::Value; + +use crate::client; + +pub const USAGE: &str = "\ +usage: kiri engine start start Kiri's engine (waking the VM and held containers) + kiri engine stop stop containers and Kiri's engine until `kiri engine start` + kiri engine restart restart Kiri's engine (applying updated VM settings) + kiri engine status [--json] inspect engine state without waking a sleeping VM (exit 1 when stopped or not running)"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum Action { + Help, + Start, + Stop, + Restart, + Status { json: bool }, +} + +pub(crate) fn parse_args(args: &[String]) -> io::Result { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + return Ok(Action::Help); + } + let words: Vec<&str> = args.iter().map(String::as_str).collect(); + match words.as_slice() { + ["start"] => Ok(Action::Start), + ["stop"] => Ok(Action::Stop), + ["restart"] => Ok(Action::Restart), + ["status"] => Ok(Action::Status { json: false }), + ["status", "--json"] => Ok(Action::Status { json: true }), + _ => Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum EngineState { + Running, + Asleep, + Stopped, + NotRunning, +} + +impl EngineState { + pub(crate) fn is_healthy(self) -> bool { + matches!(self, EngineState::Running | EngineState::Asleep) + } + + pub(crate) fn label(self) -> &'static str { + match self { + EngineState::Running => "running", + EngineState::Asleep => "asleep", + EngineState::Stopped => "stopped", + EngineState::NotRunning => "not running", + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub(crate) struct StatusReport { + pub state: EngineState, + pub awake: bool, + pub stopped: bool, + pub version: Option, + pub api_version: Option, + pub cpus: Option, + pub memory_bytes: Option, + pub containers_running: Option, + pub containers_stopped: Option, + pub socket: String, +} + +impl StatusReport { + pub(crate) fn not_running(socket: impl Into) -> Self { + Self { + state: EngineState::NotRunning, + awake: false, + stopped: false, + version: None, + api_version: None, + cpus: None, + memory_bytes: None, + containers_running: None, + containers_stopped: None, + socket: socket.into(), + } + } + + pub(crate) fn stopped_offline(socket: impl Into) -> Self { + Self { + state: EngineState::Stopped, + awake: false, + stopped: true, + version: None, + api_version: None, + cpus: None, + memory_bytes: None, + containers_running: None, + containers_stopped: None, + socket: socket.into(), + } + } + + pub(crate) fn from_daemon(socket: impl Into, info: &Value, version: Option<&Value>) -> Self { + let stopped = info["KiriStopped"].as_bool().unwrap_or(false); + let awake = !stopped && info["KiriVmAwake"].as_bool().unwrap_or(true); + let state = if stopped { + EngineState::Stopped + } else if awake { + EngineState::Running + } else { + EngineState::Asleep + }; + let kiri_ver = info["KiriVersion"] + .as_str() + .or_else(|| version.and_then(client::kiri_version)) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let api_ver = version + .and_then(|v| v["ApiVersion"].as_str()) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let mem = info["KiriMemoryCeiling"] + .as_u64() + .filter(|&n| n > 0) + .or_else(|| info["MemTotal"].as_u64().filter(|&n| n > 0)); + Self { + state, + awake, + stopped, + version: kiri_ver, + api_version: api_ver, + cpus: info["NCPU"].as_u64().filter(|&n| n > 0), + memory_bytes: mem, + containers_running: info["ContainersRunning"].as_u64(), + containers_stopped: info["ContainersStopped"].as_u64(), + socket: socket.into(), + } + } + + pub(crate) fn format_human(&self) -> String { + let mut head = format!("Kiri engine: {}", self.state.label()); + match self.state { + EngineState::Asleep => head.push_str(" (VM idle; wakes on next request)"), + EngineState::Stopped => head.push_str(" (run `kiri engine start` to start)"), + EngineState::NotRunning => head.push_str(" (run `kiri engine start` or open Kiri)"), + EngineState::Running => {} + } + let mut lines = vec![head]; + if let Some(ver) = &self.version { + match &self.api_version { + Some(api) => lines.push(format!("Version: {ver} (Docker API {api})")), + None => lines.push(format!("Version: {ver}")), + } + } + if let Some(cpus) = self.cpus { + match self.memory_bytes { + Some(bytes) => lines.push(format!("Resources: {cpus} CPUs, {}", format_memory(bytes))), + None => lines.push(format!("Resources: {cpus} CPUs")), + } + } + if let (Some(running), Some(stopped)) = (self.containers_running, self.containers_stopped) { + lines.push(format!("Containers: {running} running, {stopped} stopped")); + } + lines.push(format!("Socket: {}", self.socket)); + lines.join("\n") + } +} + +fn format_memory(bytes: u64) -> String { + const GIB: f64 = (1u64 << 30) as f64; + const MIB: u64 = 1u64 << 20; + if bytes >= (1u64 << 30) && bytes.is_multiple_of(1u64 << 30) { + format!("{} GiB", bytes >> 30) + } else if bytes >= (1u64 << 30) { + format!("{:.1} GiB", bytes as f64 / GIB) + } else { + format!("{} MiB", bytes / MIB.max(1)) + } +} + +pub fn run(args: &[String]) -> io::Result<()> { + match parse_args(args)? { + Action::Help => { + println!("{USAGE}"); + Ok(()) + } + Action::Start => { + start_silent()?; + println!("Kiri engine started"); + Ok(()) + } + Action::Stop => { + if stop_silent()? { + println!("Kiri engine stopped"); + } else { + println!("Kiri engine is already stopped"); + } + Ok(()) + } + Action::Restart => { + restart_silent()?; + println!("Kiri engine restarted"); + Ok(()) + } + Action::Status { json } => { + let report = collect_status()?; + if json { + println!("{}", serde_json::to_string(&report).map_err(io::Error::other)?); + } else { + println!("{}", report.format_human()); + } + if !report.state.is_healthy() { + std::process::exit(1); + } + Ok(()) + } + } +} + +/// `kiri start`: keeps the existing `"Kiri is started"` message for compatibility. +#[cfg(unix)] +pub fn start_legacy() -> io::Result<()> { + start_silent()?; + println!("Kiri is started"); + Ok(()) +} + +// ---- Unix implementation (macOS, Linux, and WSL daemon) ---- + +#[cfg(unix)] +fn start_not_running_message() -> &'static str { + #[cfg(target_os = "macos")] + { + "Kiri's engine isn't running. Open Kiri, or start it with `kiri daemon`" + } + #[cfg(not(target_os = "macos"))] + { + client::not_running_message() + } +} + +#[cfg(unix)] +fn start_silent() -> io::Result<()> { + #[cfg(target_os = "macos")] + if !client::alive() { + if let Ok(d) = crate::daemon::state_dir() { + let _ = std::fs::remove_file(d.join("stopped")); + } + crate::update::start_engine()?; + } + client::check_alive_with(start_not_running_message())?; + let r = client::request("POST", "/kiri/wake", None)?; + if !r.ok() && r.status != 404 { + return Err(io::Error::other(r.error())); + } + Ok(()) +} + +/// Stops containers and Kiri's engine. Returns `Ok(true)` when a running/active +/// engine was stopped, or `Ok(false)` when it was already stopped/not running. +#[cfg(unix)] +fn stop_silent() -> io::Result { + let sock = client::socket()?; + match client::probe_socket(&sock) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(e), + Err(_) => { + #[cfg(target_os = "macos")] + if let Ok(d) = crate::daemon::state_dir() { + let _ = std::fs::create_dir_all(&d); + let _ = std::fs::write(d.join("stopped"), b""); + } + return Ok(false); + } + } + let was_stopped = client::get_background_at(&sock, "/info") + .ok() + .and_then(|v| v["KiriStopped"].as_bool()) + .unwrap_or(false); + let mut r = client::request("POST", "/kiri/stop", None)?; + if r.status == 404 { + r = client::request("POST", "/kiri/sleep", None)?; + } + if !r.ok() { + return Err(io::Error::other(r.error())); + } + Ok(!was_stopped) +} + +#[cfg(unix)] +fn restart_silent() -> io::Result<()> { + #[cfg(target_os = "macos")] + if !client::alive() { + return start_silent(); + } + client::check_alive_with(start_not_running_message())?; + let sleep = client::request("POST", "/kiri/sleep", None)?; + if !sleep.ok() && sleep.status != 404 { + return Err(io::Error::other(sleep.error())); + } + let wake = client::request("POST", "/kiri/wake", None)?; + if !wake.ok() && wake.status != 404 { + return Err(io::Error::other(wake.error())); + } + Ok(()) +} + +#[cfg(unix)] +fn collect_status() -> io::Result { + let sock = client::socket()?; + #[cfg(target_os = "macos")] + let stopped_marker = crate::daemon::state_dir().ok().map(|d| d.join("stopped")); + #[cfg(not(target_os = "macos"))] + let stopped_marker: Option = None; + collect_status_at(&sock, stopped_marker.as_deref()) +} + +#[cfg(unix)] +pub(crate) fn collect_status_at(sock: &std::path::Path, stopped_marker: Option<&std::path::Path>) -> io::Result { + let sock_str = sock.display().to_string(); + match client::probe_socket(sock) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(e), + Err(_) => { + if stopped_marker.is_some_and(std::path::Path::is_file) { + return Ok(StatusReport::stopped_offline(sock_str)); + } + return Ok(StatusReport::not_running(sock_str)); + } + } + let info = client::get_background_at(sock, "/info")?; + let ver = client::get_background_at(sock, "/version").ok(); + Ok(StatusReport::from_daemon(sock_str, &info, ver.as_ref())) +} + +// ---- Windows implementation (`kiri-win` pipe + WSL 2) ---- + +#[cfg(windows)] +fn wsl_exe() -> std::path::PathBuf { + let system = std::env::var_os("SystemRoot") + .map_or_else(|| std::path::PathBuf::from(r"C:\Windows"), std::path::PathBuf::from); + system.join("System32").join("wsl.exe") +} + +#[cfg(windows)] +fn running_wsl_distros() -> Option> { + let out = std::process::Command::new(wsl_exe()) + .args(["--list", "--running", "--quiet"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + Some(parse_wsl_list(&out.stdout)) +} + +#[cfg(any(windows, test))] +fn parse_wsl_list(out: &[u8]) -> Vec { + let s = if out.contains(&0) { + let words: Vec = out.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect(); + String::from_utf16_lossy(&words) + } else { + String::from_utf8_lossy(out).into_owned() + }; + s.lines() + .map(|l| l.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}').to_owned()) + .filter(|l| !l.is_empty()) + .collect() +} + +/// Checks whether a Windows named pipe server exists without opening a client +/// handle (opening `\\.\pipe\kiri` while not stopped would spawn `wsl.exe`). +#[cfg(windows)] +fn pipe_server_listening(pipe_name: &str) -> bool { + use std::os::windows::ffi::OsStrExt; + unsafe extern "system" { + fn WaitNamedPipeW(lpNamedPipeName: *const u16, nTimeOut: u32) -> i32; + } + let wide: Vec = std::ffi::OsStr::new(pipe_name).encode_wide().chain(std::iter::once(0)).collect(); + // SAFETY: `wide` is a valid NUL-terminated UTF-16 string. + unsafe { WaitNamedPipeW(wide.as_ptr(), 1) != 0 } +} + +#[cfg(windows)] +fn start_silent() -> io::Result<()> { + let pipe = client::pipe(); + if let Some(res) = crate::wsl::wake_via_pipe(&pipe) { + match res { + Ok(()) => { + crate::wsl::clear_stopped_marker(); + return Ok(()); + } + Err(e) if !matches!(e.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::BrokenPipe) => { + return Err(e); + } + Err(_) => {} + } + } + crate::wsl::clear_stopped_marker(); + let distro = crate::wsl::distro().ok_or_else(|| io::Error::other("Kiri isn't set up yet. Open Kiri from the Start menu first"))?; + let args = vec!["engine".to_owned(), "start".to_owned()]; + let status = std::process::Command::new(wsl_exe()) + .args(crate::wsl::wsl_command_args(&distro, &args)) + .stdout(std::process::Stdio::null()) + .status() + .map_err(|e| io::Error::other(format!("could not run wsl.exe ({e})")))?; + if !status.success() { + return Err(io::Error::other("could not start Kiri's engine in WSL")); + } + Ok(()) +} + +#[cfg(windows)] +fn stop_silent() -> io::Result { + let was_marked_stopped = std::env::var_os("LOCALAPPDATA") + .map(std::path::PathBuf::from) + .is_some_and(|d| crate::wsl::stopped_marker_in(&d).is_file()); + let pipe = client::pipe(); + if let Some(res) = crate::wsl::stop_via_pipe(&pipe) { + match res { + Ok(()) => { + crate::wsl::write_stopped_marker(); + return Ok(!was_marked_stopped); + } + Err(e) if !matches!(e.kind(), io::ErrorKind::UnexpectedEof | io::ErrorKind::BrokenPipe) => { + return Err(e); + } + Err(_) => {} + } + } + crate::wsl::write_stopped_marker(); + let Some(distro) = crate::wsl::distro() else { + return Ok(false); + }; + let is_running = running_wsl_distros() + .map(|list| list.iter().any(|d| d.eq_ignore_ascii_case(&distro))) + .unwrap_or(false); + if !is_running { + return Ok(false); + } + let _ = std::process::Command::new(wsl_exe()) + .args([ + "-d", + &distro, + "-u", + "root", + "-e", + "sh", + "-c", + "export HOME=/var/lib/kiri-daemon; /usr/local/bin/kiri engine stop >/dev/null 2>&1 || true", + ]) + .status(); + if distro == "kiri" { + let _ = std::process::Command::new(wsl_exe()).args(["--terminate", &distro]).status(); + } + Ok(!was_marked_stopped) +} + +#[cfg(windows)] +fn restart_silent() -> io::Result<()> { + let _ = stop_silent()?; + start_silent() +} + +#[cfg(windows)] +fn collect_status() -> io::Result { + let pipe = client::pipe(); + if std::env::var_os("LOCALAPPDATA") + .map(std::path::PathBuf::from) + .is_some_and(|d| crate::wsl::stopped_marker_in(&d).is_file()) + { + return Ok(StatusReport::stopped_offline(pipe)); + } + let Some(distro) = crate::wsl::distro() else { + return Ok(StatusReport::not_running(pipe)); + }; + let distro_running = running_wsl_distros() + .map(|list| list.iter().any(|d| d.eq_ignore_ascii_case(&distro))) + .unwrap_or(false); + if !distro_running { + if pipe_server_listening(&pipe) { + return Ok(StatusReport { + state: EngineState::Asleep, + awake: false, + stopped: false, + version: None, + api_version: None, + cpus: None, + memory_bytes: None, + containers_running: None, + containers_stopped: None, + socket: pipe, + }); + } + return Ok(StatusReport::not_running(pipe)); + } + let out = std::process::Command::new(wsl_exe()) + .args([ + "-d", + &distro, + "-u", + "root", + "-e", + "sh", + "-c", + "export HOME=/var/lib/kiri-daemon; exec /usr/local/bin/kiri engine status --json", + ]) + .output() + .map_err(|e| io::Error::other(format!("could not run wsl.exe ({e})")))?; + if let Ok(mut v) = serde_json::from_slice::(&out.stdout) { + let state = match v["state"].as_str() { + Some("running") => EngineState::Running, + Some("asleep") => EngineState::Asleep, + Some("stopped") => EngineState::Stopped, + _ => EngineState::NotRunning, + }; + v["socket"] = Value::String(pipe.clone()); + return Ok(StatusReport { + state, + awake: v["awake"].as_bool().unwrap_or(false), + stopped: v["stopped"].as_bool().unwrap_or(false), + version: v["version"].as_str().map(str::to_owned), + api_version: v["api_version"].as_str().map(str::to_owned), + cpus: v["cpus"].as_u64(), + memory_bytes: v["memory_bytes"].as_u64(), + containers_running: v["containers_running"].as_u64(), + containers_stopped: v["containers_stopped"].as_u64(), + socket: pipe, + }); + } + Ok(StatusReport::not_running(pipe)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn vec_s(words: &[&str]) -> Vec { + words.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn parses_subcommands_help_and_rejects_unknown_arguments() { + assert_eq!(parse_args(&vec_s(&["start"])).unwrap(), Action::Start); + assert_eq!(parse_args(&vec_s(&["stop"])).unwrap(), Action::Stop); + assert_eq!(parse_args(&vec_s(&["restart"])).unwrap(), Action::Restart); + assert_eq!(parse_args(&vec_s(&["status"])).unwrap(), Action::Status { json: false }); + assert_eq!(parse_args(&vec_s(&["status", "--json"])).unwrap(), Action::Status { json: true }); + + for h in [ + &["--help"][..], + &["-h"], + &["help"], + &["start", "--help"], + &["stop", "-h"], + &["restart", "--help"], + &["status", "--help"], + &["status", "--json", "-h"], + ] { + assert_eq!(parse_args(&vec_s(h)).unwrap(), Action::Help, "{h:?}"); + } + + for bad in [&[][..], &["unknown"], &["start", "extra"], &["status", "--bogus"]] { + let err = parse_args(&vec_s(bad)).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput, "{bad:?}"); + assert_eq!(err.to_string(), USAGE); + } + } + + #[test] + fn status_report_classifies_running_asleep_stopped_and_not_running() { + let ver = json!({"KiriVersion": "0.2.3", "ApiVersion": "1.47"}); + + // 1. Running (awake VM). + let running = StatusReport::from_daemon( + "/Users/test/.kiri/run/docker.sock", + &json!({ + "KiriStopped": false, + "KiriVmAwake": true, + "KiriVersion": "0.2.3", + "NCPU": 4, + "KiriMemoryCeiling": 8_589_934_592u64, + "ContainersRunning": 2, + "ContainersStopped": 1 + }), + Some(&ver), + ); + assert_eq!(running.state, EngineState::Running); + assert!(running.state.is_healthy()); + assert!(running.awake && !running.stopped); + assert_eq!(running.version.as_deref(), Some("0.2.3")); + assert_eq!(running.api_version.as_deref(), Some("1.47")); + assert_eq!(running.cpus, Some(4)); + assert_eq!(running.memory_bytes, Some(8_589_934_592)); + assert_eq!(running.containers_running, Some(2)); + assert_eq!(running.containers_stopped, Some(1)); + let human = running.format_human(); + assert!(human.contains("Kiri engine: running"), "{human}"); + assert!(human.contains("4 CPUs, 8 GiB"), "{human}"); + assert!(human.contains("2 running, 1 stopped"), "{human}"); + + // 2. Asleep (daemon up, VM idle-sleeping): healthy (exit 0). + let asleep = StatusReport::from_daemon( + "/Users/test/.kiri/run/docker.sock", + &json!({ + "KiriStopped": false, + "KiriVmAwake": false, + "KiriVersion": "0.2.3", + "NCPU": 2, + "KiriMemoryCeiling": 4_294_967_296u64, + "ContainersRunning": 0, + "ContainersStopped": 3 + }), + Some(&ver), + ); + assert_eq!(asleep.state, EngineState::Asleep); + assert!(asleep.state.is_healthy()); + assert!(!asleep.awake && !asleep.stopped); + assert!(asleep.format_human().contains("VM idle; wakes on next request")); + + // 3. Explicitly stopped: unhealthy (exit 1). + let stopped = StatusReport::from_daemon( + "/Users/test/.kiri/run/docker.sock", + &json!({ + "KiriStopped": true, + "KiriVmAwake": false, + "KiriVersion": "0.2.3" + }), + Some(&ver), + ); + assert_eq!(stopped.state, EngineState::Stopped); + assert!(!stopped.state.is_healthy()); + assert!(!stopped.awake && stopped.stopped); + let j: Value = serde_json::to_value(&stopped).unwrap(); + assert_eq!(j["state"], "stopped"); + assert_eq!(j["stopped"], true); + assert_eq!(j["awake"], false); + + // 4. Not running: unhealthy (exit 1). + let down = StatusReport::not_running("/run/kiri/docker.sock"); + assert_eq!(down.state, EngineState::NotRunning); + assert!(!down.state.is_healthy()); + let j_down: Value = serde_json::to_value(&down).unwrap(); + assert_eq!(j_down["state"], "not_running"); + } + + #[test] + fn parses_utf16_and_utf8_wsl_running_lists() { + let utf16: Vec = "\u{feff}Ubuntu\r\nkiri\r\n" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + assert_eq!(parse_wsl_list(&utf16), vec!["Ubuntu", "kiri"]); + assert_eq!(parse_wsl_list(b"Debian\nkiri\n"), vec!["Debian", "kiri"]); + } + + #[cfg(unix)] + #[test] + fn collect_status_sends_background_header_and_respects_offline_stopped_marker() { + use std::io::{Read, Write}; + use std::os::unix::net::UnixListener; + + let dir = std::env::temp_dir().join(format!("kiri-engine-cli-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let missing = dir.join("missing.sock"); + let marker = dir.join("stopped"); + assert_eq!(collect_status_at(&missing, Some(&marker)).unwrap().state, EngineState::NotRunning); + std::fs::write(&marker, b"").unwrap(); + let offline_stopped = collect_status_at(&missing, Some(&marker)).unwrap(); + assert_eq!(offline_stopped.state, EngineState::Stopped); + assert!(offline_stopped.stopped); + + // Live mock socket: every request (`/_ping`, `/info`, `/version`) must carry `X-Kiri-Background: 1`. + let sock = dir.join("docker.sock"); + let listener = UnixListener::bind(&sock).unwrap(); + let handle = std::thread::spawn(move || { + for expected in ["/_ping", "/info", "/version"] { + let (mut conn, _) = listener.accept().unwrap(); + let mut req = Vec::new(); + let mut buf = [0u8; 512]; + while !req.windows(4).any(|w| w == b"\r\n\r\n") { + match conn.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => req.extend_from_slice(&buf[..n]), + } + } + let text = String::from_utf8_lossy(&req); + assert!(text.starts_with(&format!("GET {expected} HTTP/1.1\r\n")), "unexpected request: {text}"); + assert!(text.to_ascii_lowercase().contains("\r\nx-kiri-background: 1\r\n"), "missing background header: {text}"); + let body = match expected { + "/_ping" => "OK".to_owned(), + "/info" => json!({"KiriStopped": false, "KiriVmAwake": false, "KiriVersion": "0.2.3", "NCPU": 6, "KiriMemoryCeiling": 12_884_901_888u64, "ContainersRunning": 0, "ContainersStopped": 1}).to_string(), + "/version" => json!({"KiriVersion": "0.2.3", "ApiVersion": "1.47"}).to_string(), + _ => unreachable!(), + }; + write!( + conn, + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ) + .unwrap(); + } + }); + + let got = collect_status_at(&sock, None).unwrap(); + handle.join().unwrap(); + assert_eq!(got.state, EngineState::Asleep); + assert!(!got.awake && !got.stopped); + assert_eq!(got.cpus, Some(6)); + assert_eq!(got.version.as_deref(), Some("0.2.3")); + assert_eq!(got.api_version.as_deref(), Some("1.47")); + + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/crates/kiri/src/guest.rs b/crates/kiri/src/guest.rs index d83bfbaf2..e7a454585 100644 --- a/crates/kiri/src/guest.rs +++ b/crates/kiri/src/guest.rs @@ -12,6 +12,8 @@ use std::time::{Duration, Instant}; use kiri_proto::{HEADER, Hello, LayerBegin, Msg, Stream}; use kiri_vmm::{Config, Event, Vm}; +pub mod disk; + /// The virtiofs tag the guest mounts the Mac's folders under: `/mnt/mac`. pub const MAC_TAG: &str = "kiri-mac"; @@ -68,6 +70,15 @@ pub struct BootOptions { pub memory_mib: Option, /// The VM's CPUs; 2 if not set. pub cpus: Option, + /// The VM's persistent data disk size in GiB (`vm.json`'s `disk_gb`); + /// `KIRI_DISK_GB` overrides this when set. + pub disk_gb: Option, + /// Whether to attach `VZNATNetworkDeviceAttachment` (`InternetSharing`) on + /// macOS (`None` reads `KIRI_SHARED_NAT` / `vm.json`'s `shared_nat`). + pub shared_nat: Option, + /// The swap file the guest keeps on the data disk, in MiB; 0 removes + /// it, and `None` leaves it as it is. + pub swap_mib: Option, } fn console_output(opts: &BootOptions) -> io::Result> { @@ -150,7 +161,7 @@ impl Guest { cmdline: String::new(), console: console_output(opts)?, agent_port: kiri_proto::HOST_PORT, - disk: None, + disk: if opts.data_disk { linux_agent_data()? } else { None }, share: None, rosetta_tag: None, nat_mac: None, @@ -173,6 +184,11 @@ impl Guest { // Keep warnings and oopses even in release builds. cmdline.push_str(" quiet loglevel=4"); } + // How much swap the agent keeps on the data disk (#326). + if let Some(mib) = opts.swap_mib.filter(|_| opts.data_disk) { + cmdline.push_str(&format!(" kiri.swap={mib}")); + } + let shared_nat = opts.shared_nat.unwrap_or_else(crate::daemon::engine::shared_nat); let cfg = Config { cpus: opts.cpus.unwrap_or(2), memory_mib: opts.memory_mib.unwrap_or(1024), @@ -181,8 +197,8 @@ impl Guest { cmdline, console: console_output(opts)?, agent_port: kiri_proto::HOST_PORT, - disk: if opts.data_disk { Some(data_disk(&dir)?) } else { None }, - nat_mac: if opts.data_disk { Some(mac_address()?) } else { None }, + disk: if opts.data_disk { Some(data_disk(&dir, opts.disk_gb)?) } else { None }, + nat_mac: if opts.data_disk && shared_nat { Some(mac_address()?) } else { None }, // The Mac's folders a bind mount may name: /mnt/mac in the guest. share: opts.data_disk.then(mac_share), rosetta_tag: opts.data_disk.then(|| "rosetta".to_owned()), @@ -376,6 +392,19 @@ fn unexpected(wanted: &str, got: &Msg<'_>) -> io::Error { io::Error::other(format!("expected {wanted}, got {got:?}")) } +/// The agent's data folder on a Linux host when Settings → Storage moved it +/// off the default location: `/agent`, which `kiri-init` bind-mounts +/// onto `/var/lib/kiri`. None when using the default folder or `KIRI_DATA_DIR`. +#[cfg(target_os = "linux")] +fn linux_agent_data() -> io::Result> { + if std::env::var_os("KIRI_DATA_DIR").is_some() { + return Ok(None); + } + let root = kiri_image::Store::default_root()?; + let default = kiri_image::Store::os_default_root()?; + Ok((root != default).then(|| root.join("agent"))) +} + /// The agent on a Linux host: `KIRI_AGENT`, else `kiri-init` beside `kiri`. #[cfg(target_os = "linux")] fn agent_binary() -> PathBuf { @@ -388,7 +417,8 @@ fn agent_binary() -> PathBuf { #[cfg(target_os = "macos")] /// The guest's data disk, copied from the empty template on first use. On /// APFS the copy is a clone: instant, and it takes no space until written. -fn data_disk(guest_dir: &std::path::Path) -> io::Result { +fn data_disk(guest_dir: &std::path::Path, configured_gb: Option) -> io::Result { + let requested = disk::requested_size(configured_gb)?; let vm = kiri_image::Store::default_root()?.join("vm"); std::fs::create_dir_all(&vm)?; let disk = vm.join("data.img"); @@ -416,6 +446,7 @@ fn data_disk(guest_dir: &std::path::Path) -> io::Result { } std::fs::rename(tmp, &disk)?; } + disk::grow(&disk, requested)?; Ok(disk) } diff --git a/crates/kiri/src/guest/disk.rs b/crates/kiri/src/guest/disk.rs new file mode 100644 index 000000000..5f9c77977 --- /dev/null +++ b/crates/kiri/src/guest/disk.rs @@ -0,0 +1,271 @@ +//! Grow the Mac's sparse backing file before attaching it to the VM. + +use std::fs::OpenOptions; +use std::io; +use std::path::{Path, PathBuf}; + +/// Default template data disk size in GiB (`cargo xtask disk` makes a 64 GiB +/// sparse ext4 template). +pub const DEFAULT_GB: u64 = 64; +/// Default upper bound for the Settings → Resources disk slider in GiB. +pub const MAX_UI_GB: u64 = 1024; +const GIB: u64 = 1 << 30; + +fn invalid_size() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidInput, + "KIRI_DISK_GB must be a positive whole number of GiB that fits the disk image", + ) +} + +/// Converts a positive GiB count to bytes, rejecting zero and values that +/// overflow `u64` or exceed `i64::MAX`. +pub fn size_bytes(gb: u64) -> io::Result { + if gb == 0 { + return Err(invalid_size()); + } + gb.checked_mul(GIB) + .filter(|&bytes| bytes <= i64::MAX as u64) + .ok_or_else(invalid_size) +} + +pub fn parse_size_gb(value: &str) -> io::Result { + let gb = value.parse::().map_err(|_| invalid_size())?; + size_bytes(gb)?; + Ok(gb) +} + +pub fn parse_size(value: &str) -> io::Result { + size_bytes(parse_size_gb(value)?) +} + +/// Resolves the requested disk size in bytes: `KIRI_DISK_GB` takes precedence +/// over a persistent `vm.json` `"disk_gb"` value. An invalid `KIRI_DISK_GB` +/// returns `InvalidInput` rather than silently falling back. +pub fn resolve_requested_size( + env_val: Option<&str>, + configured_gb: Option, +) -> io::Result> { + if let Some(value) = env_val { + return parse_size(value).map(Some); + } + configured_gb.map(size_bytes).transpose() +} + +/// Resolves the requested disk size from `KIRI_DISK_GB` in the process +/// environment, falling back to `configured_gb` from `vm.json`. +pub fn requested_size(configured_gb: Option) -> io::Result> { + let env_os = std::env::var_os("KIRI_DISK_GB"); + let env_str = env_os.as_ref().map(|v| v.to_str().unwrap_or_default()); + resolve_requested_size(env_str, configured_gb) +} + +/// Resolves the effective disk size in GiB for Settings and status reporting: +/// `KIRI_DISK_GB` (if valid), else `vm.json`'s `disk_gb` (if valid), else +/// `DEFAULT_GB`, and never smaller than the existing `data.img` (`current_gb`). +pub fn effective_gb(env_val: Option<&str>, configured_gb: Option, current_gb: u64) -> u64 { + let min_gb = current_gb.max(DEFAULT_GB); + let wanted = env_val + .and_then(|v| parse_size_gb(v).ok()) + .or_else(|| configured_gb.filter(|&gb| size_bytes(gb).is_ok())) + .unwrap_or(DEFAULT_GB); + wanted.max(min_gb) +} + +/// The path to the VM's data disk backing file (`/vm/data.img`). +pub fn data_disk_path() -> Option { + kiri_image::Store::default_root() + .ok() + .map(|root| root.join("vm/data.img")) +} + +/// Current size in GiB of an existing backing file, or `DEFAULT_GB` when the +/// file does not exist yet or is smaller than the template size. +pub fn current_gb_at(path: &Path) -> u64 { + std::fs::metadata(path) + .ok() + .map(|m| m.len().div_ceil(GIB)) + .unwrap_or(DEFAULT_GB) + .max(DEFAULT_GB) +} + +/// Current size in GiB of the default data disk file. +pub fn current_gb() -> u64 { + data_disk_path() + .map(|p| current_gb_at(&p)) + .unwrap_or(DEFAULT_GB) +} + +/// Allowed `(min_gb, max_gb)` range for Settings → Resources: never shrinks +/// below the current disk image size (or 64 GiB), and expands up to at least +/// `MAX_UI_GB` (1024 GiB). +pub fn ui_bounds(current_gb: u64, effective_gb: u64) -> (u64, u64) { + let min_gb = current_gb.max(DEFAULT_GB); + let max_gb = MAX_UI_GB.max(min_gb).max(effective_gb); + (min_gb, max_gb) +} + +/// Grows the sparse backing file to `requested` bytes if it is currently +/// smaller. Never shrinks an existing file. +pub fn grow(path: &Path, requested: Option) -> io::Result<()> { + let Some(bytes) = requested else { + return Ok(()); + }; + let file = OpenOptions::new().read(true).write(true).open(path)?; + if file.metadata()?.len() < bytes { + // Extending creates holes, rather than allocating the requested + // capacity. The agent grows ext4 after mounting it at the next boot. + file.set_len(bytes).map_err(|e| { + io::Error::new(e.kind(), format!("grow data disk {}: {e}", path.display())) + })?; + file.sync_all()?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Read; + use std::os::unix::fs::MetadataExt; + + #[test] + fn sizes_are_gib_and_invalid_or_overflowing_values_are_rejected() { + assert_eq!(parse_size("64").unwrap(), 64 << 30); + assert_eq!(parse_size("128").unwrap(), 128 << 30); + assert_eq!(size_bytes(1024).unwrap(), 1024 << 30); + assert_eq!( + size_bytes(0).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + size_bytes(8_589_934_592).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + size_bytes(u64::MAX).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + for value in [ + "", + "0", + "-1", + "1.5", + "128GB", + "18446744073709551615", + "8589934592", + ] { + assert_eq!( + parse_size(value).unwrap_err().kind(), + io::ErrorKind::InvalidInput, + "expected InvalidInput for {value:?}" + ); + } + } + + #[test] + fn env_precedence_over_vm_json_and_invalid_env_is_rejected() { + // KIRI_DISK_GB wins over vm.json. + assert_eq!( + resolve_requested_size(Some("256"), Some(128)).unwrap(), + Some(256 << 30) + ); + // Even a smaller KIRI_DISK_GB wins in resolution (grow() then refuses to shrink). + assert_eq!( + resolve_requested_size(Some("96"), Some(256)).unwrap(), + Some(96 << 30) + ); + // Without KIRI_DISK_GB, vm.json's disk_gb is used. + assert_eq!( + resolve_requested_size(None, Some(128)).unwrap(), + Some(128 << 30) + ); + // Neither set means keep template/current size. + assert_eq!(resolve_requested_size(None, None).unwrap(), None); + // Invalid KIRI_DISK_GB fails loudly rather than silently falling back to vm.json. + assert_eq!( + resolve_requested_size(Some("0"), Some(128)) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert_eq!( + resolve_requested_size(Some("128GB"), Some(128)) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + } + + #[test] + fn effective_size_and_ui_bounds_never_shrink() { + // Default 64 GiB when neither env nor vm.json is set. + assert_eq!(effective_gb(None, None, 64), 64); + assert_eq!(effective_gb(None, None, 32), 64); + // vm.json applies when larger than current. + assert_eq!(effective_gb(None, Some(128), 64), 128); + // Env overrides vm.json. + assert_eq!(effective_gb(Some("256"), Some(128), 64), 256); + // Lowering vm.json or env below current disk size never reports a smaller disk. + assert_eq!(effective_gb(None, Some(96), 128), 128); + assert_eq!(effective_gb(Some("64"), Some(96), 128), 128); + assert_eq!(effective_gb(Some("32"), None, 64), 64); + // Bounds never allow shrinking below current disk size or 64 GiB. + assert_eq!(ui_bounds(64, 64), (64, 1024)); + assert_eq!(ui_bounds(128, 256), (128, 1024)); + assert_eq!(ui_bounds(64, 2048), (64, 2048)); + assert_eq!(ui_bounds(1536, 1536), (1536, 1536)); + } + + #[test] + fn growth_preserves_data_and_holes_and_never_shrinks() { + let path = std::env::temp_dir().join(format!( + "kiri-disk-grow-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos() + )); + let file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .unwrap(); + drop(file); + std::fs::write(&path, b"keep").unwrap(); + grow(&path, None).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().len(), 4); + // Below 64 GiB template floor still reports 64 GiB for UI. + assert_eq!(current_gb_at(&path), 64); + + grow(&path, Some(128 << 20)).unwrap(); + grow(&path, Some(64 << 20)).unwrap(); + grow(&path, None).unwrap(); + let metadata = std::fs::metadata(&path).unwrap(); + assert_eq!(metadata.len(), 128 << 20); + assert!(metadata.blocks() * 512 < 1 << 20); + let mut contents = [0; 8]; + std::fs::File::open(&path) + .unwrap() + .read_exact(&mut contents) + .unwrap(); + assert_eq!(&contents, b"keep\0\0\0\0"); + + // Sparse growth to 128 GiB keeps existing bytes, stays sparse, and reports 128 GiB. + grow(&path, Some(128 << 30)).unwrap(); + grow(&path, Some(64 << 30)).unwrap(); + let big = std::fs::metadata(&path).unwrap(); + assert_eq!(big.len(), 128 << 30); + assert!(big.blocks() * 512 < 1 << 20); + assert_eq!(current_gb_at(&path), 128); + let mut head = [0; 4]; + std::fs::File::open(&path) + .unwrap() + .read_exact(&mut head) + .unwrap(); + assert_eq!(&head, b"keep"); + + std::fs::remove_file(path).unwrap(); + } +} diff --git a/crates/kiri/src/hostaccess.rs b/crates/kiri/src/hostaccess.rs index ef7a58d93..01cbc08ad 100644 --- a/crates/kiri/src/hostaccess.rs +++ b/crates/kiri/src/hostaccess.rs @@ -127,12 +127,23 @@ fn run_with( } } +const USAGE: &str = "usage: kiri host-access [--restart] USER"; + pub fn run(args: &[String]) -> io::Result { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(0); + } let (restart, args) = match args { [flag, rest @ ..] if flag == "--restart" => (true, rest), _ => (false, args), }; - let [user] = args else { return Err(io::Error::other("usage: kiri host-access [--restart] USER")) }; + let [user] = args else { return Err(io::Error::other(USAGE)) }; + if user.starts_with('-') { + return Err(io::Error::other(USAGE)); + } // SAFETY: geteuid has no preconditions. if unsafe { libc::geteuid() } != 0 { return Err(io::Error::other(format!("needs root: sudo kiri host-access {}{user}", if restart { "--restart " } else { "" }))); @@ -262,7 +273,7 @@ mod tests { assert!(v == "'C'" || v == "C" || v == "\"C\"", "unexpected LC_ALL: {line}"); saw_lc_all = true; } - "PWD" | "SHLVL" | "_" => {} + "PWD" | "OLDPWD" | "SHLVL" | "_" => {} _ => panic!("unexpected inherited env var in usermod: {line}"), } } diff --git a/crates/kiri/src/hostrelay.rs b/crates/kiri/src/hostrelay.rs index ad3a4565c..2ccd5cc13 100644 --- a/crates/kiri/src/hostrelay.rs +++ b/crates/kiri/src/hostrelay.rs @@ -1,16 +1,20 @@ -//! `kiri hostrelay`: lets Kiri's engine in WSL2 reach a proxy on Windows' own -//! loopback, `127.0.0.1:7892`, where most Windows proxy apps listen. In +//! `kiri hostrelay`: lets Kiri's engine and containers in WSL2 reach services +//! on Windows' own loopback (`127.0.0.1` / `[::1]`): both Windows loopback +//! proxies (`127.0.0.1:7892`, where most Windows proxy apps listen) and +//! `host.docker.internal` / `host.kiri.internal` (`192.168.65.254`). In //! WSL's default NAT networking the distro's 127.0.0.1 is its own, and //! Windows' firewall keeps the WSL network away from Windows' ports, so a -//! proxy the browser uses was refused to every image pull. +//! service or proxy on Windows' loopback was unreachable from WSL and +//! containers. //! //! The connections take the way kiri-win already talks to WSL: a wsl.exe //! process's stdin and stdout. kiri-win (crates/kiri-win/src/relay.rs) -//! starts this and asks it to LISTEN for each proxy port; it listens on the -//! distro's 127.0.0.1 and sends each connection to it back as frames, and -//! kiri-win dials the proxy on Windows. kiri-win dials only the ports it -//! asked for, so nothing in WSL can reach any other Windows port this way. -//! The engine pulls through `127.0.0.1:` (daemon/proxy.rs). +//! starts this and asks it to LISTEN for static proxy ports (on the distro's +//! 127.0.0.1) and LISTEN_HOST for the dynamic `192.168.65.254` catch-all +//! host-gateway listener (using `SO_ORIGINAL_DST` with nftables DNAT on +//! `iifname "kiri*"` and local `OUTPUT` for TCP ports != 53). Each connection +//! goes back as frames, and kiri-win dials Windows' loopback (`127.0.0.1`, +//! falling back to `[::1]` on `ConnectionRefused`). //! //! Both ends share this file. Frames are the bridge's (crates/kiri/src/bridge.rs): //! kind, connection id (u32 BE), length (u32 BE), then the data. @@ -27,7 +31,7 @@ use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; -/// WSL → Windows: a connection to the proxy on the port in the data (u16 BE). +/// WSL → Windows: a connection to the proxy or host-gateway on the port in the data (u16 BE). pub const OPEN: u8 = 1; pub const DATA: u8 = 2; /// No more data from this side (a half-close). @@ -39,6 +43,111 @@ pub const LISTEN: u8 = 6; /// WSL → Windows: the Windows port, then the distro's port that leads to /// it (both u16 BE); 0 when it could not listen. pub const LISTENING: u8 = 7; +/// Windows → WSL: start the dynamic `192.168.65.254` catch-all host-gateway +/// listener (empty data, or 4-byte IPv4 override). +pub const LISTEN_HOST: u8 = 8; +/// WSL → Windows: the distro's catch-all host-gateway port (u16 BE), or 0 +/// when it could not listen or configure nftables. +pub const LISTENING_HOST: u8 = 9; + +/// What `host.docker.internal`, `host.kiri.internal`, and `host-gateway` +/// resolve to inside WSL 2 containers when the Windows host relay is active, +/// matching Docker Desktop. +pub const WSL_HOST_ADDR: [u8; 4] = [192, 168, 65, 254]; +pub const WSL_HOST_ADDR_STR: &str = "192.168.65.254"; + +/// True when running under Microsoft's WSL 2 kernel. +pub fn is_wsl() -> bool { + #[cfg(target_os = "linux")] + { + static WSL: std::sync::OnceLock = std::sync::OnceLock::new(); + *WSL.get_or_init(|| { + std::fs::read_to_string("/proc/sys/kernel/osrelease") + .is_ok_and(|r| r.to_ascii_lowercase().contains("microsoft")) + }) + } + #[cfg(not(target_os = "linux"))] + { + false + } +} + +#[cfg(unix)] +const HOST_LOCK_FILE: &str = "/run/kiri-hostrelay.lock"; +#[cfg(unix)] +const HOST_PID_FILE: &str = "/run/kiri-hostrelay.pid"; + +/// Checks whether a Linux `/proc//cmdline` (NUL-separated argv) belongs +/// to `kiri hostrelay` (empty cmdline also excludes unreaped zombies). +fn is_hostrelay_cmdline(cmdline: &[u8]) -> bool { + let mut args = cmdline.split(|&b| b == 0); + let Some(argv0) = args.next() else { return false }; + let Some(argv1) = args.next() else { return false }; + !argv0.is_empty() && argv1 == b"hostrelay" +} + +#[cfg(unix)] +fn read_pid_file(path: &std::path::Path) -> Option { + std::fs::read_to_string(path).ok()?.trim().parse::().ok().filter(|&p| p > 0) +} + +#[cfg(unix)] +fn write_pid_file(path: &std::path::Path, pid: u32) -> io::Result<()> { + use std::os::unix::fs::OpenOptionsExt; + let mut tmp = path.as_os_str().to_os_string(); + tmp.push(format!(".{pid}.tmp")); + let tmp = std::path::PathBuf::from(tmp); + let mut file = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o644).open(&tmp)?; + if let Err(e) = file.write_all(format!("{pid}\n").as_bytes()).and_then(|()| file.flush()) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + drop(file); + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +#[cfg(unix)] +fn pid_is_alive(pid: u32) -> bool { + let Ok(pid) = libc::pid_t::try_from(pid) else { + return false; + }; + if pid <= 0 { + return false; + } + // SAFETY: signal 0 checks process existence without sending a signal. + if unsafe { libc::kill(pid, 0) } == 0 { + return true; + } + io::Error::last_os_error().raw_os_error() == Some(libc::EPERM) +} + +#[cfg(unix)] +fn pid_file_alive(path: &std::path::Path, verify: impl FnOnce(u32) -> bool) -> bool { + read_pid_file(path).is_some_and(|pid| pid_is_alive(pid) && verify(pid)) +} + +#[cfg(target_os = "linux")] +fn hostrelay_pid_matches(pid: u32) -> bool { + std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|c| is_hostrelay_cmdline(&c)) +} + +/// True when running on WSL 2 with a live `kiri hostrelay` process owning +/// `192.168.65.254` (verified via `/run/kiri-hostrelay.pid`, `kill(pid, 0)`, +/// and `/proc//cmdline`, catching unclean exits without `getifaddrs()`). +pub fn wsl_host_active() -> bool { + #[cfg(target_os = "linux")] + { + is_wsl() && pid_file_alive(std::path::Path::new(HOST_PID_FILE), hostrelay_pid_matches) + } + #[cfg(not(target_os = "linux"))] + { + false + } +} /// Neither end sends more data than this in a frame; a longer one is refused /// before it is allocated. @@ -95,20 +204,66 @@ struct Entry { stream: Option, } +#[derive(Default)] +struct State { + closed: bool, + entries: HashMap, +} + /// The connections open through one relay, by id. #[derive(Default)] -pub struct Conns(Mutex>); +pub struct Conns(Mutex); + +struct CloseAll(Arc); + +impl Drop for CloseAll { + fn drop(&mut self) { + self.0.close_all(); + } +} impl Conns { - fn map(&self) -> std::sync::MutexGuard<'_, HashMap> { + fn state(&self) -> std::sync::MutexGuard<'_, State> { self.0.lock().unwrap_or_else(PoisonError::into_inner) } /// A new connection: what arrives for it waits here until it is made. - fn open(&self, id: u32) -> Receiver { + fn open(&self, id: u32) -> Option> { let (tx, rx) = sync_channel(QUEUE); - self.map().insert(id, Entry { tx, stream: None }); - rx + let prev = { + let mut s = self.state(); + if s.closed { + return None; + } + s.entries.insert(id, Entry { tx, stream: None }) + }; + if let Some(prev) = prev + && let Some(stream) = prev.stream + { + let _ = stream.shutdown(Shutdown::Both); + } + Some(rx) + } + + fn close(&self, id: u32) -> bool { + let Some(e) = self.state().entries.remove(&id) else { return false }; + if let Some(s) = e.stream { + let _ = s.shutdown(Shutdown::Both); + } + true + } + + fn close_all(&self) { + let entries = { + let mut s = self.state(); + s.closed = true; + std::mem::take(&mut s.entries) + }; + for (_, e) in entries { + if let Some(s) = e.stream { + let _ = s.shutdown(Shutdown::Both); + } + } } /// A frame for one of the connections. @@ -117,22 +272,17 @@ impl Conns { DATA => Op::Data(data), EOF => Op::Eof, CLOSE => { - if let Some(e) = self.map().remove(&id) - && let Some(s) = e.stream - { - let _ = s.shutdown(Shutdown::Both); - } + self.close(id); return; } _ => return, }; // Sent outside the lock: a full queue waits for its own writer only. - let tx = self.map().get(&id).map(|e| e.tx.clone()); + let tx = self.state().entries.get(&id).map(|e| e.tx.clone()); if let Some(tx) = tx { let _ = tx.send(op); } } - } /// Joins `stream` to connection `id`: what it reads goes to the other end @@ -140,17 +290,23 @@ impl Conns { fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpStream) { let _ = stream.set_nodelay(true); let (Ok(reader), Ok(writer)) = (stream.try_clone(), stream.try_clone()) else { - conns.map().remove(&id); + conns.close(id); let _ = send(out, CLOSE, id, &[]); return; }; - match conns.map().get_mut(&id) { - Some(e) => e.stream = Some(stream), - // Closed while it was being made. - None => { - let _ = stream.shutdown(Shutdown::Both); - return; + let (attached, to_shutdown) = { + let mut s = conns.state(); + match s.entries.get_mut(&id) { + Some(e) => (true, e.stream.replace(stream)), + // Closed while it was being made. + None => (false, Some(stream)), } + }; + if let Some(s) = to_shutdown { + let _ = s.shutdown(Shutdown::Both); + } + if !attached { + return; } // Each half that ends counts; the second one forgets the connection. let halves = Arc::new(AtomicU8::new(0)); @@ -159,7 +315,7 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS let halves = halves.clone(); move || { if halves.fetch_add(1, Ordering::SeqCst) == 1 { - conns.map().remove(&id); + conns.close(id); } } }; @@ -172,7 +328,7 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS Op::Data(d) => { if writer.write_all(&d).is_err() { let _ = writer.shutdown(Shutdown::Both); - c.map().remove(&id); + c.close(id); let _ = send(&o, CLOSE, id, &[]); return; } @@ -193,18 +349,21 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS loop { match reader.read(&mut buf) { Ok(0) => { - let _ = send(&o, EOF, id, &[]); + if send(&o, EOF, id, &[]).is_err() { + c.close(id); + } break; } Ok(n) => { if send(&o, DATA, id, &buf[..n]).is_err() { + c.close(id); break; } } Err(e) if e.kind() == io::ErrorKind::Interrupted => {} Err(_) => { // Gone while the other end may still be sending: say so. - if c.map().remove(&id).is_some() { + if c.close(id) { let _ = send(&o, CLOSE, id, &[]); } break; @@ -218,33 +377,63 @@ fn attach(conns: &Arc, out: &Out, id: u32, rx: Receiver, stream: TcpS /// The WSL end (`kiri hostrelay`): listens as kiri-win asks and sends each /// connection over `out`, until kiri-win goes, and the listeners with it. pub fn listen_side(input: impl Read, out: &Out) -> io::Result<()> { + // Declared before `_close` so open connections drop (freeing FDs) before + // `HostGateway::drop` acquires the teardown lock. + #[cfg(target_os = "linux")] + let mut host_gateway: Option = None; let conns = Arc::new(Conns::default()); + let _close = CloseAll(conns.clone()); let next = Arc::new(AtomicU32::new(1)); let mut listening: HashMap = HashMap::new(); let mut r = BufReader::with_capacity(CHUNK, input); while let Some((kind, id, data)) = read_frame(&mut r)? { - if kind != LISTEN { - conns.dispatch(kind, id, data); - continue; - } - let Some(target) = port_of(&data, 0) else { continue }; - let local = match listening.get(&target) { - Some(&p) => p, - None => { - let p = listen(target, &conns, out, &next).unwrap_or(0); - if p != 0 { - listening.insert(target, p); - } - p + match kind { + LISTEN => { + let Some(target) = port_of(&data, 0) else { continue }; + let local = match listening.get(&target) { + Some(&p) => p, + None => { + let p = listen(target, &conns, out, &next).unwrap_or(0); + if p != 0 { + listening.insert(target, p); + } + p + } + }; + let mut reply = target.to_be_bytes().to_vec(); + reply.extend_from_slice(&local.to_be_bytes()); + send(out, LISTENING, 0, &reply)?; } - }; - let mut reply = target.to_be_bytes().to_vec(); - reply.extend_from_slice(&local.to_be_bytes()); - send(out, LISTENING, 0, &reply)?; + LISTEN_HOST => { + #[cfg(target_os = "linux")] + let port = match &host_gateway { + Some(hg) => hg.port, + None => { + let addr: [u8; 4] = data.get(..4).and_then(|b| b.try_into().ok()).unwrap_or(WSL_HOST_ADDR); + match start_host_gateway(addr, &conns, out, &next) { + Ok(hg) => { + let p = hg.port; + host_gateway = Some(hg); + p + } + Err(_) => 0, + } + } + }; + #[cfg(not(target_os = "linux"))] + let port: u16 = 0; + send(out, LISTENING_HOST, 0, &port.to_be_bytes())?; + } + _ => conns.dispatch(kind, id, data), + } } Ok(()) } +/// Backoff on transient `accept()` errors (such as `EMFILE` / `ENFILE`) so +/// listener threads never busy-spin. +const ACCEPT_ERR_BACKOFF: Duration = Duration::from_millis(50); + /// Listens on the distro's loopback for `target`; its port. fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> io::Result { let l = TcpListener::bind(("127.0.0.1", 0))?; @@ -252,10 +441,23 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> let (conns, out, next) = (conns.clone(), out.clone(), next.clone()); std::thread::spawn(move || { for s in l.incoming() { - let Ok(s) = s else { continue }; + let s = match s { + Ok(s) => s, + Err(e) => { + if e.kind() != io::ErrorKind::Interrupted { + std::thread::sleep(ACCEPT_ERR_BACKOFF); + } + continue; + } + }; let id = next.fetch_add(1, Ordering::SeqCst); - let rx = conns.open(id); + let Some(rx) = conns.open(id) else { + let _ = s.shutdown(Shutdown::Both); + return; + }; if send(&out, OPEN, id, &target.to_be_bytes()).is_err() { + conns.close(id); + let _ = s.shutdown(Shutdown::Both); return; } attach(&conns, &out, id, rx, s); @@ -264,26 +466,557 @@ fn listen(target: u16, conns: &Arc, out: &Out, next: &Arc) -> Ok(port) } +/// Acquires an exclusive `flock` on `lock_path` (never unlinked so concurrent +/// setup and teardown always synchronize on the same inode). +#[cfg(unix)] +fn lock_host_gateway(lock_path: &std::path::Path) -> io::Result { + use std::os::fd::AsRawFd; + let file = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lock_path)?; + loop { + // SAFETY: `file` owns a valid open descriptor. + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX) } == 0 { + return Ok(file); + } + let err = io::Error::last_os_error(); + if err.kind() != io::ErrorKind::Interrupted { + return Err(err); + } + } +} + +/// Serializes host-gateway setup under `lock_path`, publishing `pid` to +/// `pid_path` only after `setup` succeeds and rolling back if publishing fails. +#[cfg(unix)] +fn acquire_host_gateway( + lock_path: &std::path::Path, + pid_path: &std::path::Path, + pid: u32, + setup: impl FnOnce() -> io::Result, + rollback: impl FnOnce(T), +) -> io::Result { + let _lock = lock_host_gateway(lock_path)?; + let val = setup()?; + if let Err(e) = write_pid_file(pid_path, pid) { + if read_pid_file(pid_path) == Some(pid) { + let _ = std::fs::remove_file(pid_path); + } + rollback(val); + return Err(e); + } + Ok(val) +} + +/// Serializes host-gateway teardown under `lock_path`, removing `pid_path` and +/// running `teardown` only after verifying `pid` is still the active owner. +#[cfg(unix)] +fn release_host_gateway(lock_path: &std::path::Path, pid_path: &std::path::Path, pid: u32, teardown: impl FnOnce()) { + let Ok(_lock) = lock_host_gateway(lock_path) else { return }; + if read_pid_file(pid_path) == Some(pid) { + let _ = std::fs::remove_file(pid_path); + teardown(); + } +} + +/// Active catch-all host-gateway state on Linux (WSL 2): keeps `192.168.65.254/32` +/// on `lo` and `table ip kiri_host` alive until `listen_side` ends, then cleans +/// them up if no newer `kiri hostrelay` has taken ownership. +#[cfg(target_os = "linux")] +struct HostGateway { + addr: [u8; 4], + port: u16, + pid: u32, +} + +#[cfg(target_os = "linux")] +impl Drop for HostGateway { + fn drop(&mut self) { + // Serialize with any concurrent `start_host_gateway` so an exiting + // relay can never tear down a newer relay's `lo` address or nftables. + release_host_gateway( + std::path::Path::new(HOST_LOCK_FILE), + std::path::Path::new(HOST_PID_FILE), + self.pid, + || { + let _ = host_net::remove_nft(); + let _ = host_net::del_lo_addr(self.addr); + }, + ); + } +} + +/// Checks whether `SO_ORIGINAL_DST` returned a valid host-gateway target port +/// destined to `host_addr` (non-zero and not TCP port 53). +fn host_gateway_target(dst_ip: [u8; 4], dst_port: u16, host_addr: [u8; 4]) -> Option { + (dst_ip == host_addr && dst_port != 0 && dst_port != 53).then_some(dst_port) +} + +#[cfg(target_os = "linux")] +fn original_dst_port(fd: std::os::fd::RawFd, host_addr: [u8; 4]) -> Option { + const SO_ORIGINAL_DST: libc::c_int = 80; + // SAFETY: `SO_ORIGINAL_DST` fills `sockaddr_in` with the pre-DNAT destination. + unsafe { + let mut dst: libc::sockaddr_in = std::mem::zeroed(); + let mut len = std::mem::size_of::() as libc::socklen_t; + if libc::getsockopt(fd, libc::SOL_IP, SO_ORIGINAL_DST, (&mut dst as *mut libc::sockaddr_in).cast(), &mut len) != 0 { + return None; + } + host_gateway_target(dst.sin_addr.s_addr.to_ne_bytes(), u16::from_be(dst.sin_port), host_addr) + } +} + +/// Assigns `addr/32` to `lo`, binds a catch-all TCP listener on `addr:0`, +/// installs `table ip kiri_host` nftables DNAT + input guard rules, and spawns +/// the accept loop that extracts each connection's target port via +/// `SO_ORIGINAL_DST`. +#[cfg(target_os = "linux")] +fn start_host_gateway(addr: [u8; 4], conns: &Arc, out: &Out, next: &Arc) -> io::Result { + use std::os::fd::AsRawFd; + let pid = std::process::id(); + let (listener, port, added) = acquire_host_gateway( + std::path::Path::new(HOST_LOCK_FILE), + std::path::Path::new(HOST_PID_FILE), + pid, + || { + let added = host_net::add_lo_addr(addr)?; + let listener = match TcpListener::bind((std::net::Ipv4Addr::from(addr), 0)) { + Ok(l) => l, + Err(e) => { + if added { + let _ = host_net::del_lo_addr(addr); + } + return Err(e); + } + }; + let port = match listener.local_addr() { + Ok(a) => a.port(), + Err(e) => { + if added { + let _ = host_net::del_lo_addr(addr); + } + return Err(e); + } + }; + if let Err(e) = host_net::install_nft(addr, port) { + if added { + let _ = host_net::del_lo_addr(addr); + } + return Err(e); + } + Ok((listener, port, added)) + }, + |(_listener, _port, added)| { + let _ = host_net::remove_nft(); + if added { + let _ = host_net::del_lo_addr(addr); + } + }, + )?; + let (conns, out, next) = (conns.clone(), out.clone(), next.clone()); + if let Err(e) = std::thread::Builder::new().name("kiri-hostrelay-gw".into()).spawn(move || { + for s in listener.incoming() { + let s = match s { + Ok(s) => s, + Err(e) => { + if e.kind() != io::ErrorKind::Interrupted { + std::thread::sleep(ACCEPT_ERR_BACKOFF); + } + continue; + } + }; + let Some(target) = original_dst_port(s.as_raw_fd(), addr) else { + let _ = s.shutdown(Shutdown::Both); + continue; + }; + let id = next.fetch_add(1, Ordering::SeqCst); + let Some(rx) = conns.open(id) else { + let _ = s.shutdown(Shutdown::Both); + return; + }; + if send(&out, OPEN, id, &target.to_be_bytes()).is_err() { + conns.close(id); + let _ = s.shutdown(Shutdown::Both); + return; + } + attach(&conns, &out, id, rx, s); + } + }) { + release_host_gateway( + std::path::Path::new(HOST_LOCK_FILE), + std::path::Path::new(HOST_PID_FILE), + pid, + || { + let _ = host_net::remove_nft(); + if added { + let _ = host_net::del_lo_addr(addr); + } + }, + ); + return Err(e); + } + Ok(HostGateway { addr, port, pid }) +} + +/// Minimal rtnetlink and nf_tables netlink helpers for WSL 2's catch-all +/// `192.168.65.254` host-gateway listener (`kiri hostrelay` runs in minimal +/// WSL distros with neither `ip` nor `nft` binaries). +#[cfg(target_os = "linux")] +mod host_net { + use std::io; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + + const NLMSG_ERROR: u16 = 2; + const NLMSG_DONE: u16 = 3; + const NLM_F_REQUEST: u16 = 0x1; + const NLM_F_ACK: u16 = 0x4; + const NLM_F_EXCL: u16 = 0x200; + const NLM_F_CREATE: u16 = 0x400; + const NLM_F_APPEND: u16 = 0x800; + + const RTM_NEWADDR: u16 = 20; + const RTM_DELADDR: u16 = 21; + const IFA_ADDRESS: u16 = 1; + const IFA_LOCAL: u16 = 2; + + const NFNL_SUBSYS_NFTABLES: u16 = 10; + const NFNL_MSG_BATCH_BEGIN: u16 = 0x10; + const NFNL_MSG_BATCH_END: u16 = 0x11; + const NFT_MSG_NEWTABLE: u16 = 0; + const NFT_MSG_DELTABLE: u16 = 2; + const NFT_MSG_NEWCHAIN: u16 = 3; + const NFT_MSG_NEWRULE: u16 = 6; + + pub const TABLE: &str = "kiri_host"; + const BRIDGE_PREFIX: &[u8] = b"kiri"; + /// Runs after conntrack (-200) and before `table ip kiri` (-100) so + /// host-gateway traffic is never caught by published-port DNAT rules. + const NAT_PRIORITY: i32 = -110; + + pub struct Msg { + pub buf: Vec, + nests: Vec, + } + + fn pad(buf: &mut Vec) { + while buf.len() % 4 != 0 { + buf.push(0); + } + } + + impl Msg { + fn new(ty: u16, flags: u16) -> Self { + let mut buf = vec![0u8; 16]; + buf[4..6].copy_from_slice(&ty.to_ne_bytes()); + buf[6..8].copy_from_slice(&(flags | NLM_F_REQUEST).to_ne_bytes()); + Self { buf, nests: Vec::new() } + } + + fn raw(&mut self, bytes: &[u8]) -> &mut Self { + self.buf.extend_from_slice(bytes); + pad(&mut self.buf); + self + } + + fn attr(&mut self, ty: u16, data: &[u8]) -> &mut Self { + self.buf.extend_from_slice(&((4 + data.len()) as u16).to_ne_bytes()); + self.buf.extend_from_slice(&ty.to_ne_bytes()); + self.buf.extend_from_slice(data); + pad(&mut self.buf); + self + } + + fn attr_str(&mut self, ty: u16, s: &str) -> &mut Self { + let mut v = s.as_bytes().to_vec(); + v.push(0); + self.attr(ty, &v) + } + + fn attr_be32(&mut self, ty: u16, v: u32) -> &mut Self { + self.attr(ty, &v.to_be_bytes()) + } + + fn nest(&mut self, ty: u16) -> &mut Self { + self.nests.push(self.buf.len()); + self.buf.extend_from_slice(&[0, 0]); + self.buf.extend_from_slice(&(ty | 0x8000).to_ne_bytes()); + self + } + + fn end(&mut self) -> &mut Self { + let start = self.nests.pop().expect("nest() before end()"); + let len = (self.buf.len() - start) as u16; + self.buf[start..start + 2].copy_from_slice(&len.to_ne_bytes()); + self + } + + fn finish(&mut self, seq: u32) -> &[u8] { + let len = self.buf.len() as u32; + self.buf[0..4].copy_from_slice(&len.to_ne_bytes()); + self.buf[8..12].copy_from_slice(&seq.to_ne_bytes()); + &self.buf + } + } + + struct Netlink { + fd: OwnedFd, + seq: u32, + buf: Vec, + } + + impl Netlink { + fn open(protocol: i32) -> io::Result { + // SAFETY: plain socket creation; owned immediately. + let fd = unsafe { libc::socket(libc::AF_NETLINK, libc::SOCK_RAW | libc::SOCK_CLOEXEC, protocol) }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: `fd` is a fresh descriptor owned only here. + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + Ok(Self { fd, seq: 1, buf: vec![0u8; 16 * 1024] }) + } + + fn request(&mut self, msgs: &mut [Msg]) -> io::Result<()> { + let mut out = Vec::new(); + let first = self.seq; + for m in msgs.iter_mut() { + out.extend_from_slice(m.finish(self.seq)); + self.seq += 1; + } + // SAFETY: sending our own buffer on our own socket. + if unsafe { libc::send(self.fd.as_raw_fd(), out.as_ptr().cast(), out.len(), 0) } < 0 { + return Err(io::Error::last_os_error()); + } + let mut acked = 0; + let want = msgs.iter().filter(|m| u16::from_ne_bytes([m.buf[6], m.buf[7]]) & NLM_F_ACK != 0).count(); + while acked < want { + // SAFETY: receiving into our own buffer on our own socket. + let n = unsafe { libc::recv(self.fd.as_raw_fd(), self.buf.as_mut_ptr().cast(), self.buf.len(), 0) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + let n = n as usize; + let mut off = 0; + while off + 16 <= n { + let len = u32::from_ne_bytes(self.buf[off..off + 4].try_into().expect("4")) as usize; + let ty = u16::from_ne_bytes(self.buf[off + 4..off + 6].try_into().expect("2")); + let seq = u32::from_ne_bytes(self.buf[off + 8..off + 12].try_into().expect("4")); + if len < 16 || off + len > n { + break; + } + if ty == NLMSG_ERROR && seq >= first && seq < self.seq { + let code = i32::from_ne_bytes(self.buf[off + 16..off + 20].try_into().expect("4")); + acked += 1; + if code != 0 { + return Err(io::Error::from_raw_os_error(-code)); + } + } else if ty == NLMSG_DONE { + acked = want; + } + off += (len + 3) & !3; + } + } + Ok(()) + } + } + + fn lo_index() -> io::Result { + // SAFETY: valid NUL-terminated static C string. + let i = unsafe { libc::if_nametoindex(c"lo".as_ptr()) }; + if i == 0 { + return Err(io::Error::new(io::ErrorKind::NotFound, "no lo interface")); + } + Ok(i) + } + + fn lo_addr_msg(ty: u16, flags: u16, index: u32, addr: [u8; 4]) -> Msg { + let mut m = Msg::new(ty, flags); + let mut ifa = [0u8; 8]; + ifa[0] = libc::AF_INET as u8; + ifa[1] = 32; + ifa[3] = libc::RT_SCOPE_HOST; + ifa[4..8].copy_from_slice(&index.to_ne_bytes()); + m.raw(&ifa).attr(IFA_LOCAL, &addr).attr(IFA_ADDRESS, &addr); + m + } + + /// Adds `addr/32` to `lo`. Returns `Ok(true)` if added, `Ok(false)` if already present. + pub fn add_lo_addr(addr: [u8; 4]) -> io::Result { + let index = lo_index()?; + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + let msg = lo_addr_msg(RTM_NEWADDR, NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL, index, addr); + match nl.request(&mut [msg]) { + Ok(()) => Ok(true), + Err(e) if e.raw_os_error() == Some(libc::EEXIST) => Ok(false), + Err(e) => Err(e), + } + } + + /// Removes `addr/32` from `lo`; already absent is fine. + pub fn del_lo_addr(addr: [u8; 4]) -> io::Result<()> { + let index = lo_index()?; + let mut nl = Netlink::open(libc::NETLINK_ROUTE)?; + let msg = lo_addr_msg(RTM_DELADDR, NLM_F_ACK, index, addr); + match nl.request(&mut [msg]) { + Ok(()) => Ok(()), + Err(e) if e.raw_os_error() == Some(libc::EADDRNOTAVAIL) => Ok(()), + Err(e) => Err(e), + } + } + + fn nfgen(family: u8, res_id: u16) -> [u8; 4] { + let mut b = [0u8; 4]; + b[0] = family; + b[2..4].copy_from_slice(&res_id.to_be_bytes()); + b + } + + fn nft(msg: u16, flags: u16) -> Msg { + let mut m = Msg::new((NFNL_SUBSYS_NFTABLES << 8) | msg, flags); + m.raw(&nfgen(libc::NFPROTO_IPV4 as u8, 0)); + m + } + + /// Linux 3.13+ compatible table clear: add (no-op if present), then delete. + fn clear_table() -> [Msg; 2] { + let mut add = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); + add.attr_str(1, TABLE); + let mut delete = nft(NFT_MSG_DELTABLE, NLM_F_ACK); + delete.attr_str(1, TABLE); + [add, delete] + } + + fn chain(name: &str, hook: u32, priority: i32, kind: &str) -> Msg { + let mut c = nft(NFT_MSG_NEWCHAIN, NLM_F_ACK | NLM_F_CREATE); + c.attr_str(1, TABLE).attr_str(3, name); + c.nest(4).attr_be32(1, hook).attr_be32(2, priority as u32).end(); + c.attr_be32(5, libc::NF_ACCEPT as u32).attr_str(7, kind); + c + } + + /// `[iifname "kiri*"] ip daddr tcp dport != 53 dnat to :`. + pub fn dnat_rule(chain: &str, addr: [u8; 4], port: u16, from_bridges: bool) -> Msg { + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | NLM_F_APPEND); + rule.attr_str(1, TABLE).attr_str(2, chain); + rule.nest(4); + if from_bridges { + // meta iifname (6) => reg 1; cmp eq "kiri" prefix + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + } + // payload network header + 16 (daddr), 4 bytes => reg 1; cmp eq addr + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + // meta l4proto (16) => reg 1; cmp eq tcp + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 16).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &[libc::IPPROTO_TCP as u8]).end().end().end(); + // payload transport header + 2 (dport), 2 bytes => reg 1; cmp neq 53 + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 2).attr_be32(3, 2).attr_be32(4, 2).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &53u16.to_be_bytes()).end().end().end(); + // immediate reg 1 = addr, reg 2 = port; nat dnat ip addr reg 1 proto reg 2 + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 1).nest(2).attr(1, &addr).end().end().end(); + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 2).nest(2).attr(1, &port.to_be_bytes()).end().end().end(); + rule.nest(1).attr_str(1, "nat").nest(2).attr_be32(1, 1).attr_be32(2, libc::AF_INET as u32).attr_be32(3, 1).attr_be32(5, 2).attr_be32(7, 2).end().end(); + rule.end(); + rule + } + + /// `ip daddr iifname != "kiri*" iifname != "lo" drop`: keeps + /// external LAN / non-container interfaces off the host-gateway relay. + pub fn input_guard_rule(addr: [u8; 4]) -> Msg { + let mut lo_full = [0u8; 16]; + lo_full[..2].copy_from_slice(b"lo"); + let mut rule = nft(NFT_MSG_NEWRULE, NLM_F_ACK | NLM_F_CREATE | NLM_F_APPEND); + rule.attr_str(1, TABLE).attr_str(2, "input"); + rule.nest(4); + // payload network header + 16 (daddr), 4 bytes => reg 1; cmp eq addr + rule.nest(1).attr_str(1, "payload").nest(2).attr_be32(1, 1).attr_be32(2, 1).attr_be32(3, 16).attr_be32(4, 4).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 0).nest(3).attr(1, &addr).end().end().end(); + // meta iifname (6) => reg 1; cmp neq "kiri" prefix + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, BRIDGE_PREFIX).end().end().end(); + // meta iifname (6) => reg 1; cmp neq "lo" exact (16-byte NUL-padded) + rule.nest(1).attr_str(1, "meta").nest(2).attr_be32(1, 1).attr_be32(2, 6).end().end(); + rule.nest(1).attr_str(1, "cmp").nest(2).attr_be32(1, 1).attr_be32(2, 1).nest(3).attr(1, &lo_full).end().end().end(); + // verdict DROP + rule.nest(1).attr_str(1, "immediate").nest(2).attr_be32(1, 0).nest(2).nest(2).attr_be32(1, libc::NF_DROP as u32).end().end().end().end(); + rule.end(); + rule + } + + pub fn install_batch(addr: [u8; 4], port: u16) -> Vec { + let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); + begin.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + let [add, delete] = clear_table(); + let mut table = nft(NFT_MSG_NEWTABLE, NLM_F_ACK | NLM_F_CREATE); + table.attr_str(1, TABLE); + let pre = chain("prerouting", 0, NAT_PRIORITY, "nat"); + let out = chain("output", 3, NAT_PRIORITY, "nat"); + let input = chain("input", 1, 0, "filter"); + let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); + end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + vec![ + begin, + add, + delete, + table, + pre, + out, + input, + dnat_rule("prerouting", addr, port, true), + dnat_rule("output", addr, port, false), + input_guard_rule(addr), + end, + ] + } + + pub fn install_nft(addr: [u8; 4], port: u16) -> io::Result<()> { + let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; + nl.request(&mut install_batch(addr, port)) + } + + pub fn remove_nft() -> io::Result<()> { + let mut nl = Netlink::open(libc::NETLINK_NETFILTER)?; + let mut begin = Msg::new(NFNL_MSG_BATCH_BEGIN, 0); + begin.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + let [add, delete] = clear_table(); + let mut end = Msg::new(NFNL_MSG_BATCH_END, 0); + end.raw(&nfgen(libc::AF_UNSPEC as u8, NFNL_SUBSYS_NFTABLES)); + nl.request(&mut [begin, add, delete, end]) + } +} + /// The Windows end: dials the proxy for each connection the WSL end sends, /// on the ports `allowed` names, and hands LISTENING replies to `listening`. pub fn dial_side(input: impl Read, out: &Out, allowed: impl Fn(u16) -> bool, listening: impl Fn(u16, u16)) -> io::Result<()> { + dial_side_with_host(input, out, allowed, listening, |_| {}) +} + +/// Like [`dial_side`], also delivering `LISTENING_HOST` replies (the WSL +/// catch-all host-gateway relay port, or 0 on failure) to `listening_host`. +pub fn dial_side_with_host( + input: impl Read, + out: &Out, + allowed: impl Fn(u16) -> bool, + listening: impl Fn(u16, u16), + listening_host: impl Fn(u16), +) -> io::Result<()> { let conns = Arc::new(Conns::default()); + let _close = CloseAll(conns.clone()); let mut r = BufReader::with_capacity(CHUNK, input); while let Some((kind, id, data)) = read_frame(&mut r)? { match kind { OPEN => { - let target = port_of(&data, 0).filter(|&p| allowed(p)); + let target = port_of(&data, 0).filter(|&p| p != 0 && allowed(p)); let Some(target) = target else { send(out, CLOSE, id, &[])?; continue; }; // Data that arrives while it dials waits in the queue. - let rx = conns.open(id); + let Some(rx) = conns.open(id) else { continue }; let (c, o) = (conns.clone(), out.clone()); std::thread::spawn(move || match dial(target) { Ok(s) => attach(&c, &o, id, rx, s), Err(_) => { - c.map().remove(&id); + c.close(id); let _ = send(&o, CLOSE, id, &[]); } }); @@ -293,16 +1026,29 @@ pub fn dial_side(input: impl Read, out: &Out, allowed: impl Fn(u16) -> bool, lis listening(target, local); } } + LISTENING_HOST => { + if let Some(local) = port_of(&data, 0) { + listening_host(local); + } + } _ => conns.dispatch(kind, id, data), } } Ok(()) } -/// This machine's loopback at `port`: IPv4, then IPv6. +/// This machine's loopback at `port`: `127.0.0.1` first, falling back to +/// `[::1]` on `ConnectionRefused` (for IPv6-only localhost servers such as +/// Node/Vite on Windows). fn dial(port: u16) -> io::Result { let wait = Duration::from_secs(5); - TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), wait).or_else(|e| TcpStream::connect_timeout(&(std::net::Ipv6Addr::LOCALHOST, port).into(), wait).map_err(|_| e)) + match TcpStream::connect_timeout(&([127, 0, 0, 1], port).into(), wait) { + Ok(s) => Ok(s), + Err(e) if matches!(e.kind(), io::ErrorKind::ConnectionRefused | io::ErrorKind::AddrNotAvailable) => { + TcpStream::connect_timeout(&(std::net::Ipv6Addr::LOCALHOST, port).into(), wait).map_err(|_| e) + } + Err(e) => Err(e), + } } /// Where in a proxy address its host and port are, when the host is this @@ -453,4 +1199,393 @@ mod tests { let mut buf = [0u8; 1]; assert!(matches!(c.read(&mut buf), Ok(0) | Err(_))); } + + fn assert_closed(conn: &mut TcpStream) { + conn.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); + let mut buf = [0u8; 1]; + let res = conn.read(&mut buf); + assert!( + matches!(res, Ok(0)) + || matches!(res, Err(ref e) if !matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)), + "expected closed socket, got {res:?}" + ); + } + + #[test] + fn ending_the_relay_closes_its_open_connections() { + // dial_side: open proxy socket closes when the frame stream hits EOF. + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let h = std::thread::spawn(move || dial_side(in_rx, &o, move |p| p == port, |_, _| {})); + + send(&in_out, OPEN, 1, &port.to_be_bytes()).unwrap(); + let (mut conn, _) = proxy.accept().unwrap(); + conn.write_all(b"x").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"x".to_vec()))); + + drop(in_out); + h.join().unwrap().unwrap(); + drop(dial_out); + assert_closed(&mut conn); + + // listen_side: open client socket closes when the frame stream hits EOF. + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let listen_out: Out = Arc::new(Mutex::new(out_tx)); + let o = listen_out.clone(); + let h = std::thread::spawn(move || listen_side(in_rx, &o)); + + send(&in_out, LISTEN, 0, &port.to_be_bytes()).unwrap(); + let Some((LISTENING, 0, reply)) = read_frame(&mut out_rx).unwrap() else { panic!("expected LISTENING") }; + let local = port_of(&reply, 2).unwrap(); + let mut client = TcpStream::connect(("127.0.0.1", local)).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((OPEN, 1, port.to_be_bytes().to_vec()))); + client.write_all(b"y").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"y".to_vec()))); + + drop(in_out); + h.join().unwrap().unwrap(); + drop(listen_out); + assert_closed(&mut client); + } + + #[test] + fn ending_the_relay_with_a_full_queue_tears_down_without_deadlocking() { + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let h = std::thread::spawn(move || dial_side(in_rx, &o, move |p| p == port, |_, _| {})); + + send(&in_out, OPEN, 1, &port.to_be_bytes()).unwrap(); + let (mut conn, _) = proxy.accept().unwrap(); + conn.write_all(b"x").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"x".to_vec()))); + + // Fill the socket send buffer and the sync_channel(QUEUE) buffer without reading from conn. + let chunk = vec![b'a'; CHUNK * 4]; + for _ in 0..QUEUE { + send(&in_out, DATA, 1, &chunk).unwrap(); + } + + drop(in_out); + h.join().unwrap().unwrap(); + drop(dial_out); + // Drain any kernel-buffered bytes and confirm the socket was shut down. + conn.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); + let mut buf = vec![0u8; CHUNK * 4]; + loop { + match conn.read(&mut buf) { + Ok(0) => break, + Ok(_) => continue, + Err(e) => { + assert!( + !matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock), + "expected closed socket after full queue EOF, got {e:?}" + ); + break; + } + } + } + + // Also verify teardown when all QUEUE slots of sync_channel(QUEUE) are 100% full (TrySendError::Full). + let conns = Arc::new(Conns::default()); + let (_out_rx, out_tx) = io::pipe().unwrap(); + let out: Out = Arc::new(Mutex::new(out_tx)); + let rx = conns.open(1).unwrap(); + let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (mut peer, _) = proxy.accept().unwrap(); + attach(&conns, &out, 1, rx, client); + let tx = conns.state().entries.get(&1).unwrap().tx.clone(); + while tx.try_send(Op::Data(chunk.clone())).is_ok() { + std::thread::sleep(Duration::from_millis(1)); + } + assert!(matches!(tx.try_send(Op::Data(vec![b'z'])), Err(std::sync::mpsc::TrySendError::Full(_)))); + drop(tx); + conns.close_all(); + assert!(conns.state().entries.is_empty()); + assert!(conns.open(2).is_none()); + peer.set_read_timeout(Some(Duration::from_millis(500))).unwrap(); + loop { + match peer.read(&mut buf) { + Ok(0) => break, + Ok(_) => continue, + Err(e) => { + assert!(!matches!(e.kind(), io::ErrorKind::TimedOut | io::ErrorKind::WouldBlock)); + break; + } + } + } + } + + #[test] + fn broken_frame_output_pipe_cleans_up_the_connection() { + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let h = std::thread::spawn(move || dial_side(in_rx, &o, move |p| p == port, |_, _| {})); + + send(&in_out, OPEN, 1, &port.to_be_bytes()).unwrap(); + let (mut conn, _) = proxy.accept().unwrap(); + conn.write_all(b"x").unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 1, b"x".to_vec()))); + + // Break the output pipe while the input stream stays open. + drop(out_rx); + let _ = conn.write_all(b"y"); + assert_closed(&mut conn); + + drop(in_out); + h.join().unwrap().unwrap(); + + // Direct Conns check: a broken output pipe removes the entry from Conns. + let conns = Arc::new(Conns::default()); + let (out_rx, out_tx) = io::pipe().unwrap(); + drop(out_rx); + let out: Out = Arc::new(Mutex::new(out_tx)); + let rx = conns.open(1).unwrap(); + let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (mut peer, _) = proxy.accept().unwrap(); + attach(&conns, &out, 1, rx, client); + assert!(conns.state().entries.contains_key(&1)); + peer.write_all(b"z").unwrap(); + assert_closed(&mut peer); + assert!(conns.state().entries.is_empty()); + } + + #[test] + fn connections_attaching_or_arriving_after_close_all_are_shut_down() { + let proxy = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = proxy.local_addr().unwrap().port(); + let (_out_rx, out_tx) = io::pipe().unwrap(); + let out: Out = Arc::new(Mutex::new(out_tx)); + + // 1. An in-flight connection opened before close_all() that reaches attach() after close_all(). + let conns = Arc::new(Conns::default()); + let rx = conns.open(1).unwrap(); + conns.close_all(); + let client = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let (mut peer, _) = proxy.accept().unwrap(); + attach(&conns, &out, 1, rx, client); + assert_closed(&mut peer); + assert!(conns.state().entries.is_empty()); + + // 2. A new TCP connection arriving at listen_side's listener after listen_side has torn down. + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let listen_out: Out = Arc::new(Mutex::new(out_tx)); + let o = listen_out.clone(); + let h = std::thread::spawn(move || listen_side(in_rx, &o)); + + send(&in_out, LISTEN, 0, &port.to_be_bytes()).unwrap(); + let Some((LISTENING, 0, reply)) = read_frame(&mut out_rx).unwrap() else { panic!("expected LISTENING") }; + let local = port_of(&reply, 2).unwrap(); + + drop(in_out); + h.join().unwrap().unwrap(); + drop(listen_out); + + if let Ok(mut late) = TcpStream::connect(("127.0.0.1", local)) { + assert_closed(&mut late); + } + assert!(read_frame(&mut out_rx).unwrap().is_none(), "no OPEN frame emitted after teardown"); + } + + #[test] + fn host_gateway_target_validates_ip_and_port() { + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 17433, WSL_HOST_ADDR), Some(17433)); + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 80, WSL_HOST_ADDR), Some(80)); + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 0, WSL_HOST_ADDR), None, "port 0 rejected"); + assert_eq!(host_gateway_target(WSL_HOST_ADDR, 53, WSL_HOST_ADDR), None, "DNS port 53 excluded"); + assert_eq!(host_gateway_target([172, 17, 0, 1], 17433, WSL_HOST_ADDR), None, "wrong IP rejected"); + assert_eq!(host_gateway_target([127, 0, 0, 1], 17433, WSL_HOST_ADDR), None, "loopback rejected"); + } + + #[test] + fn dial_side_with_host_allows_dynamic_ipv4_and_ipv6_ports_and_rejects_port_zero() { + let srv4 = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port4 = srv4.local_addr().unwrap().port(); + std::thread::spawn(move || { + if let Ok((mut s, _)) = srv4.accept() { + let _ = s.write_all(b"v4-ok"); + } + }); + let srv6 = TcpListener::bind((std::net::Ipv6Addr::LOCALHOST, 0)).ok(); + let port6 = srv6.as_ref().map(|l| l.local_addr().unwrap().port()); + if let Some(l) = srv6 { + std::thread::spawn(move || { + if let Ok((mut s, _)) = l.accept() { + let _ = s.write_all(b"v6-ok"); + } + }); + } + let (in_rx, in_tx) = io::pipe().unwrap(); + let (mut out_rx, out_tx) = io::pipe().unwrap(); + let in_out: Out = Arc::new(Mutex::new(in_tx)); + let dial_out: Out = Arc::new(Mutex::new(out_tx)); + let o = dial_out.clone(); + let got_host = Arc::new(std::sync::atomic::AtomicU16::new(0)); + let gh = got_host.clone(); + let h = std::thread::spawn(move || { + dial_side_with_host(in_rx, &o, |_| true, |_, _| {}, move |p| gh.store(p, Ordering::SeqCst)) + }); + + // LISTENING_HOST delivers the reported relay port. + send(&in_out, LISTENING_HOST, 0, &41234u16.to_be_bytes()).unwrap(); + // Port 0 is always refused even when `allowed` returns true. + send(&in_out, OPEN, 1, &0u16.to_be_bytes()).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((CLOSE, 1, vec![]))); + assert_eq!(got_host.load(Ordering::SeqCst), 41234); + + // IPv4 loopback server reachable dynamically without prior LISTEN. + send(&in_out, OPEN, 2, &port4.to_be_bytes()).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 2, b"v4-ok".to_vec()))); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((EOF, 2, vec![]))); + + // IPv6-only loopback server reachable via ConnectionRefused fallback. + if let Some(p6) = port6 { + send(&in_out, OPEN, 3, &p6.to_be_bytes()).unwrap(); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((DATA, 3, b"v6-ok".to_vec()))); + assert_eq!(read_frame(&mut out_rx).unwrap(), Some((EOF, 3, vec![]))); + } + + drop(in_out); + h.join().unwrap().unwrap(); + } + + #[test] + fn host_gateway_lock_serializes_setup_and_teardown_and_checks_owner_pid() { + let dir = std::env::temp_dir().join(format!("kiri-hostrelay-lock-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let lock = dir.join("kiri-hostrelay.lock"); + let pid_path = dir.join("kiri-hostrelay.pid"); + + // 1. Failed setup never creates a stale pidfile. + let err = acquire_host_gateway(&lock, &pid_path, 111, || Err::<(), _>(io::Error::other("boom")), |_| panic!("rollback on setup err")); + assert!(err.is_err()); + assert!(!pid_path.exists(), "failed setup must not leave a pidfile"); + + // 2. Relay 1 acquires; a concurrent failed start of relay 2 must not clobber relay 1's pidfile. + acquire_host_gateway(&lock, &pid_path, 111, || Ok(()), |_| {}).unwrap(); + assert_eq!(read_pid_file(&pid_path), Some(111)); + assert!(acquire_host_gateway(&lock, &pid_path, 222, || Err::<(), _>(io::Error::other("bind failed")), |_| {}).is_err()); + assert_eq!(read_pid_file(&pid_path), Some(111)); + + // 3. Rollback fires if writing the pidfile fails (e.g., pid_path is a directory). + let bad_pid = dir.join("pid-dir"); + std::fs::create_dir_all(&bad_pid).unwrap(); + let rolled_back = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let rb = rolled_back.clone(); + assert!(acquire_host_gateway(&lock, &bad_pid, 333, || Ok(42u32), move |v| { + assert_eq!(v, 42); + rb.store(true, Ordering::SeqCst); + }) + .is_err()); + assert!(rolled_back.load(Ordering::SeqCst)); + + // 4. Simulate the Drop race: relay 2 holds the flock while taking over; + // relay 1's Drop waits on the flock, then sees relay 2's PID and does NOT tear down. + let guard = lock_host_gateway(&lock).unwrap(); + let lock2 = lock.clone(); + let pid2 = pid_path.clone(); + let old_tore_down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let otd = old_tore_down.clone(); + let drop_thread = std::thread::spawn(move || { + release_host_gateway(&lock2, &pid2, 111, move || otd.store(true, Ordering::SeqCst)); + }); + std::thread::sleep(Duration::from_millis(30)); + assert!(!old_tore_down.load(Ordering::SeqCst), "old Drop must wait for the flock"); + write_pid_file(&pid_path, 222).unwrap(); + drop(guard); + drop_thread.join().unwrap(); + assert!(!old_tore_down.load(Ordering::SeqCst), "old Drop must not tear down newer relay"); + assert_eq!(read_pid_file(&pid_path), Some(222), "newer relay's pidfile preserved"); + + // 5. When relay 2 itself drops, it is the active owner so it removes the pidfile and tears down. + let new_tore_down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let ntd = new_tore_down.clone(); + release_host_gateway(&lock, &pid_path, 222, move || ntd.store(true, Ordering::SeqCst)); + assert!(new_tore_down.load(Ordering::SeqCst)); + assert!(!pid_path.exists()); + + // 6. A missing pidfile must NEVER trigger teardown for a stale Drop. + let ghost_tore_down = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let gtd = ghost_tore_down.clone(); + release_host_gateway(&lock, &pid_path, 111, move || gtd.store(true, Ordering::SeqCst)); + assert!(!ghost_tore_down.load(Ordering::SeqCst)); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn host_gateway_liveness_detects_live_and_dead_pids_and_cmdline() { + let dir = std::env::temp_dir().join(format!("kiri-hostrelay-live-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let pid_path = dir.join("kiri-hostrelay.pid"); + + // Missing or invalid pidfile -> inactive. + assert!(!pid_file_alive(&pid_path, |_| true)); + std::fs::write(&pid_path, "not-a-pid\n").unwrap(); + assert!(!pid_file_alive(&pid_path, |_| true)); + std::fs::write(&pid_path, "0\n").unwrap(); + assert!(!pid_file_alive(&pid_path, |_| true)); + + // Live PID (current test process) -> active iff cmdline verifier passes. + write_pid_file(&pid_path, std::process::id()).unwrap(); + assert!(pid_file_alive(&pid_path, |_| true)); + assert!(!pid_file_alive(&pid_path, |_| false)); + + // Dead PID (exited & reaped child, simulating kill -9 leaving stale pidfile) -> inactive. + let mut child = std::process::Command::new("/bin/sh").args(["-c", "exit 0"]).spawn().unwrap(); + let dead_pid = child.id(); + let _ = child.wait().unwrap(); + write_pid_file(&pid_path, dead_pid).unwrap(); + assert!(!pid_file_alive(&pid_path, |_| true), "dead PID must be treated as inactive"); + + // Cmdline matching: accepts `kiri hostrelay`, rejects zombies and reused PIDs. + assert!(is_hostrelay_cmdline(b"/usr/local/bin/kiri\0hostrelay\0")); + assert!(is_hostrelay_cmdline(b"kiri\0hostrelay")); + assert!(!is_hostrelay_cmdline(b"/usr/local/bin/kiri\0daemon\0")); + assert!(!is_hostrelay_cmdline(b"/bin/sh\0-c\0hostrelay\0")); + assert!(!is_hostrelay_cmdline(b"")); + assert!(!is_hostrelay_cmdline(b"\0hostrelay\0")); + + let _ = std::fs::remove_dir_all(&dir); + } + + #[cfg(target_os = "linux")] + #[test] + fn host_gateway_nft_batch_matches_bridges_output_and_guards_input() { + let batch = host_net::install_batch(WSL_HOST_ADDR, 45678); + assert_eq!(batch.len(), 11); + let has = |m: &host_net::Msg, needle: &[u8]| m.buf.windows(needle.len()).any(|w| w == needle); + let pre = &batch[7]; + let out = &batch[8]; + let guard = &batch[9]; + // prerouting DNAT matches iifname "kiri*", daddr 192.168.65.254, tcp dport != 53 -> :45678 + assert!(has(pre, b"kiri_host\0") && has(pre, b"prerouting\0")); + assert!(has(pre, b"kiri") && has(pre, &WSL_HOST_ADDR) && has(pre, &53u16.to_be_bytes()) && has(pre, &45678u16.to_be_bytes())); + // output DNAT has no bridge iifname match, still skips port 53 + assert!(has(out, b"output\0") && has(out, &WSL_HOST_ADDR) && has(out, &53u16.to_be_bytes()) && has(out, &45678u16.to_be_bytes())); + // input guard drops non-kiri*, non-lo traffic to 192.168.65.254 + let mut lo_full = [0u8; 16]; + lo_full[..2].copy_from_slice(b"lo"); + assert!(has(guard, b"input\0") && has(guard, &WSL_HOST_ADDR) && has(guard, &lo_full)); + } } diff --git a/crates/kiri/src/images.rs b/crates/kiri/src/images.rs index 0c9ef1b16..9973df841 100644 --- a/crates/kiri/src/images.rs +++ b/crates/kiri/src/images.rs @@ -15,7 +15,15 @@ fn invalid(msg: impl Into) -> io::Error { } pub fn pull(args: &[String]) -> io::Result<()> { - let name = args.first().ok_or_else(|| invalid("usage: kiri raw pull "))?; + const USAGE: &str = "usage: kiri raw pull "; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if args.len() != 1 || args[0].starts_with('-') { + return Err(invalid(USAGE)); + } + let name = &args[0]; let reference = Reference::parse(name).map_err(|e| invalid(e.to_string()))?; let store = store()?; let platform = Platform::host_linux(); @@ -54,7 +62,15 @@ pub fn pull(args: &[String]) -> io::Result<()> { Ok(()) } -pub fn list(_args: &[String]) -> io::Result<()> { +pub fn list(args: &[String]) -> io::Result<()> { + const USAGE: &str = "usage: kiri raw images"; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if !args.is_empty() { + return Err(invalid(USAGE)); + } let mut images = store()?.images()?; images.sort_by(|a, b| a.name.cmp(&b.name)); let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); @@ -74,8 +90,13 @@ pub fn list(_args: &[String]) -> io::Result<()> { } pub fn remove(args: &[String]) -> io::Result<()> { - if args.is_empty() { - return Err(invalid("usage: kiri raw rmi ...")); + const USAGE: &str = "usage: kiri raw rmi ..."; + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) { + println!("{USAGE}"); + return Ok(()); + } + if args.is_empty() || args.iter().any(|a| a.starts_with('-')) { + return Err(invalid(USAGE)); } let store = store()?; for name in args { diff --git a/crates/kiri/src/import.rs b/crates/kiri/src/import.rs index 71f12d964..097f16606 100644 --- a/crates/kiri/src/import.rs +++ b/crates/kiri/src/import.rs @@ -1,10 +1,13 @@ //! Moving to Kiri from OrbStack or Docker Desktop: images, volumes and //! containers, copied through the docker CLI so each engine speaks its own //! API. The source is only read: `docker save` for images, `inspect` for -//! containers, and for a volume `docker cp` out of a container that mounts -//! it read-only, is never started and is removed after (that keeps file -//! owners, which a copy through the Finder would lose). Containers arrive -//! stopped. +//! containers, and for a volume a short-lived official GNU tar helper that +//! mounts it read-only and is removed after (keeping file owners and `user.*` +//! extended attributes, which `docker cp` or a copy through the Finder would +//! lose; falling back to `docker cp` when offline without GNU tar). +//! Containers arrive stopped, with the files they wrote outside their +//! volumes: what `docker diff` lists, read path by path with `docker cp` +//! into the container's writable layer in Kiri (#410). use std::io::{self, Read, Write}; use std::path::PathBuf; @@ -31,6 +34,7 @@ fn cli() -> io::Result { let mut cmd = Command::new(docker()?); #[cfg(windows)] std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); + cmd.env_remove("DOCKER_HOST").env_remove("DOCKER_CONTEXT"); Ok(cmd) } @@ -174,7 +178,14 @@ fn has(ctx: &str, kind: &str, name: &str) -> bool { /// `from` piped through `retar` (in this process) into `to`, both docker /// commands already set up; the first failure that explains the others. -fn pipe(mut from: Command, mut to: Command, from_ctx: &str, retar: impl FnOnce(&mut dyn Read, &mut dyn Write) -> io::Result<()>) -> io::Result<()> { +fn pipe(from: Command, to: Command, from_ctx: &str, retar: impl FnOnce(&mut dyn Read, &mut dyn Write) -> io::Result<()>) -> io::Result<()> { + pipe_with(from, to, from_ctx, false, retar) +} + +/// [`pipe`]; when `allow_file_changed` is set (`--force` with GNU tar), GNU +/// tar's exit status 1 ("file changed as we read it") is accepted once the +/// tar stream itself reached its end and the writer succeeded. +fn pipe_with(mut from: Command, mut to: Command, from_ctx: &str, allow_file_changed: bool, retar: impl FnOnce(&mut dyn Read, &mut dyn Write) -> io::Result<()>) -> io::Result<()> { let mut from = from.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; let mut out = from.stdout.take().ok_or_else(|| io::Error::other("no output from docker"))?; let mut to = match to.stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::piped()).spawn() { @@ -205,7 +216,8 @@ fn pipe(mut from: Command, mut to: Command, from_ctx: &str, retar: impl FnOnce(& } drop((out, into)); let written = to.wait()?.success(); - let read = from.wait()?.success(); + let from_status = from.wait()?; + let read = from_status.success() || (allow_file_changed && copied.is_ok() && from_status.code() == Some(1)); let to_said = to_said.join().unwrap_or_default(); let from_said = from_said.join().unwrap_or_default(); // A writer that stopped reading breaks the reader's pipe: its reason first. @@ -262,8 +274,12 @@ fn put_number(field: &mut [u8], v: u64) { /// A tar number field as written: octal, or base-256. fn get_number(field: &[u8]) -> Option { - if field[0] & 0x80 != 0 { - return Some(field[1..].iter().fold(0u64, |n, b| n << 8 | u64::from(*b))); + if field.first().copied()? & 0x80 != 0 { + let val = &field[1..]; + if field[0] != 0x80 || val[..val.len().saturating_sub(8)].iter().any(|b| *b != 0) { + return None; + } + return Some(val[val.len().saturating_sub(8)..].iter().fold(0u64, |n, b| n << 8 | u64::from(*b))); } let text = String::from_utf8_lossy(field.split(|c| *c == 0).next().unwrap_or_default()).trim().to_owned(); if text.is_empty() { Some(0) } else { u64::from_str_radix(&text, 8).ok() } @@ -286,6 +302,52 @@ fn pax_records(data: &[u8]) -> Vec<(String, String)> { out } +fn pax_record(k: &str, v: &str) -> Vec { + let rest = k.len() + v.len() + 3; + let mut n = rest + 1; + while rest + n.to_string().len() != n { + n = rest + n.to_string().len(); + } + format!("{n} {k}={v}\n").into_bytes() +} + +/// Rewrites `size` records in `data` to `new_size`, keeping every other pax +/// record's raw bytes unchanged (including binary `SCHILY.xattr.*` values). +fn rewrite_pax_size(data: &[u8], new_size: &str) -> Vec { + let mut out = Vec::with_capacity(data.len() + 16); + let mut rest = data; + let mut replaced = false; + while let Some(sp) = rest.iter().position(|b| *b == b' ') { + let Some(len) = std::str::from_utf8(&rest[..sp]).ok().and_then(|l| l.parse::().ok()).filter(|l| *l > sp + 1 && *l <= rest.len()) else { break }; + let record = &rest[sp + 1..len]; + let record = record.strip_suffix(b"\n").unwrap_or(record); + if record.iter().position(|b| *b == b'=').is_some_and(|eq| &record[..eq] == b"size") { + out.extend_from_slice(&pax_record("size", new_size)); + replaced = true; + } else { + out.extend_from_slice(&rest[..len]); + } + rest = &rest[len..]; + } + out.extend_from_slice(rest); + if !replaced { + out.extend_from_slice(&pax_record("size", new_size)); + } + out +} + +fn update_checksum(h: &mut [u8; 512]) { + h[148..156].fill(b' '); + let sum: u32 = h.iter().map(|b| u32::from(*b)).sum(); + h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); +} + +fn write_small(to: &mut impl Write, h: &[u8; 512], data: &[u8]) -> io::Result<()> { + to.write_all(h)?; + to.write_all(data)?; + to.write_all(&[0u8; 512][..data.len().next_multiple_of(512) - data.len()]) +} + /// Passes a tar stream from `from` to `to`, entry by entry. A pax header's /// size, uid and gid are written into the next entry's own header as well: /// `docker cp` puts a size of 8 GiB or more and an owner above 2097151 only @@ -300,37 +362,63 @@ fn retar(mut from: impl Read, mut to: impl Write, name: Option<&str>) -> io::Res let mut h = [0u8; 512]; // What a pax header said, for the entry after it. let mut pax: Vec<(String, String)> = Vec::new(); + let mut pax_bytes = 0usize; + let mut pending_pax: Option<([u8; 512], Vec)> = None; loop { from.read_exact(&mut h).map_err(cut("a header, before the archive's end"))?; if h.iter().all(|b| *b == 0) { + if let Some((px_h, px_data)) = pending_pax.take() { + write_small(&mut to, &px_h, &px_data)?; + } to.write_all(&h)?; io::copy(&mut from, &mut to)?; return to.flush(); } + if h[156] == b'x' { + if let Some((px_h, px_data)) = pending_pax.take() { + write_small(&mut to, &px_h, &px_data)?; + } + let size = get_number(&h[124..136]).ok_or_else(|| bad("a damaged header"))?; + let padded = size.checked_next_multiple_of(512).ok_or_else(|| bad("a damaged header"))?; + if size > 16 << 20 || pax_bytes.saturating_add(size as usize) > 16 << 20 { + return Err(bad("a header or manifest.json too large")); + } + let mut data = vec![0u8; padded as usize]; + from.read_exact(&mut data).map_err(cut("a pax header"))?; + data.truncate(size as usize); + pax_bytes += data.len(); + pax.extend(pax_records(&data)); + pending_pax = Some((h, data)); + continue; + } let mut changed = false; for (key, at) in [("size", 124..136), ("uid", 108..116), ("gid", 116..124)] { - if let Some(v) = pax.iter().find(|(k, _)| k == key).and_then(|(_, v)| v.parse::().ok()) { + if let Some(v) = pax.iter().rfind(|(k, _)| k == key).and_then(|(_, v)| v.parse::().ok()) { put_number(&mut h[at], v); changed = true; } } - pax.clear(); + let pax_path = pax.iter().rfind(|(k, _)| k == "path").map(|(_, v)| v.clone()); let size = get_number(&h[124..136]).ok_or_else(|| bad("a damaged header"))?; - let padded = size.div_ceil(512) * 512; - let manifest = name.is_some() && matches!(h[156], b'0' | 0) && text(&h[345..500]).is_empty() && text(&h[..100]).trim_start_matches("./") == "manifest.json"; - let small = manifest || h[156] == b'x'; - if small && size > 16 << 20 { + let padded = size.checked_next_multiple_of(512).ok_or_else(|| bad("a damaged header"))?; + let entry_path = match pax_path { + Some(p) => p, + None => match text(&h[345..500]) { + prefix if &h[257..263] == b"ustar\0" && !prefix.is_empty() => format!("{prefix}/{}", text(&h[..100])), + _ if text(&h[345..500]).is_empty() || &h[257..265] == b"ustar \0" => text(&h[..100]), + _ => String::new(), + }, + }; + let manifest = name.is_some() && matches!(h[156], b'0' | 0) && entry_path.trim_start_matches("./") == "manifest.json"; + if manifest && size > 16 << 20 { return Err(bad("a header or manifest.json too large")); } let mut data = Vec::new(); - if small { + if manifest { data = vec![0u8; padded as usize]; - from.read_exact(&mut data).map_err(cut(if manifest { "manifest.json" } else { "a pax header" }))?; + from.read_exact(&mut data).map_err(cut("manifest.json"))?; data.truncate(size as usize); } - if h[156] == b'x' { - pax = pax_records(&data); - } if let (true, Some(name)) = (manifest, name) { let mut m: Value = serde_json::from_slice(&data).map_err(|e| bad(&format!("manifest.json: {e}")))?; for e in m.as_array_mut().into_iter().flatten().filter_map(Value::as_object_mut) { @@ -343,26 +431,63 @@ fn retar(mut from: impl Read, mut to: impl Write, name: Option<&str>) -> io::Res data = serde_json::to_vec(&m).map_err(io::Error::other)?; put_number(&mut h[124..136], data.len() as u64); changed = true; + if let Some((mut px_h, mut px_data)) = pending_pax.take() { + let new_size = data.len().to_string(); + if pax.iter().any(|(k, v)| k == "size" && v != &new_size) { + px_data = rewrite_pax_size(&px_data, &new_size); + put_number(&mut px_h[124..136], px_data.len() as u64); + update_checksum(&mut px_h); + } + write_small(&mut to, &px_h, &px_data)?; + } + } + pax.clear(); + pax_bytes = 0; + if let Some((px_h, px_data)) = pending_pax.take() { + write_small(&mut to, &px_h, &px_data)?; } if changed { - h[148..156].fill(b' '); - let sum: u32 = h.iter().map(|b| u32::from(*b)).sum(); - h[148..156].copy_from_slice(format!("{sum:06o}\0 ").as_bytes()); + update_checksum(&mut h); } - to.write_all(&h)?; - if small { - to.write_all(&data)?; - to.write_all(&vec![0u8; data.len().div_ceil(512) * 512 - data.len()])?; - } else if io::copy(&mut (&mut from).take(padded), &mut to)? != padded { - return Err(bad("cut off inside a file's body")); + if manifest { + write_small(&mut to, &h, &data)?; + } else { + to.write_all(&h)?; + if io::copy(&mut (&mut from).take(padded), &mut to)? != padded { + return Err(bad("cut off inside a file's body")); + } } } } -/// Official images with `tar` and `sh`: one of these does Kiri's half of a -/// volume copy. +/// Official images with `tar` and `sh`: any of these can inspect volumes or +/// unpack when offline; the GNU tar ones ([`GNU_TAR_IMAGES`]) preserve +/// extended attributes on both ends of a volume copy (#485). const TAR_IMAGES: [&str; 4] = ["alpine", "busybox", "debian", "ubuntu"]; +/// BusyBox tar (alpine, busybox) silently drops `user.*` xattrs, which is +/// where Supabase Storage keeps object metadata: reads then fail with +/// ENODATA. Both ends of a volume copy use an official GNU tar image (#485). +const GNU_TAR_IMAGES: [&str; 2] = ["debian", "ubuntu"]; + +/// xattrs travel as pax records: the format and `--xattrs` are both needed +/// when writing them, and `--numeric-owner` keeps raw UID/GID across +/// differing `/etc/passwd` tables. Passed as argv, so `*` is literal. +const STORE_XATTRS: [&str; 4] = ["--numeric-owner", "--format=pax", "--xattrs", "--xattrs-include=*"]; + +/// Only `user.*` is portable to apply on the other engine; system-defined +/// namespaces (security, trusted) are not (GNU tar's extraction default). +/// `--numeric-owner` keeps raw UID/GID across differing `/etc/passwd` tables. +const RESTORE_XATTRS: &str = "--numeric-owner --xattrs '--xattrs-include=user.*'"; + +/// Whether an official image name is one of [`GNU_TAR_IMAGES`]. An +/// official digest for the very same repository is checked separately in +/// [`pick_helper_matching`], so a look-alike still cannot be run (#506). +fn gnu_tar(name: &str) -> bool { + let repo = name.rsplit_once(':').filter(|(_, tag)| !tag.contains('/')).map_or(name, |(r, _)| r); + GNU_TAR_IMAGES.iter().any(|base| repo == *base || repo.ends_with(&format!("/{base}"))) +} + /// Whether a `RepoDigests` entry shows the engine pulled the image from an /// official repository of [`TAR_IMAGES`]: Docker Hub's, or one of its two /// public mirrors, by digest. A name or a tag says nothing (anyone can give @@ -377,55 +502,142 @@ fn official(repo_digest: &str) -> bool { homes.iter().any(|home| repo.strip_prefix(home).is_some_and(|base| TAR_IMAGES.contains(&base))) } -/// The name to run Kiri's half of a volume copy by: a `repo:tag` of the -/// first of `images` (Kiri's image list: `RepoTags`, `RepoDigests`) whose +/// A `repo:tag` of the first of `images` (`RepoTags`, `RepoDigests`) whose /// own record shows it was pulled under that name from an official -/// repository ([`official`]). Run by that name, it is that record. -fn pick_helper(images: &[Value]) -> Option { +/// repository ([`official`]). When `only_gnu` is set, only [`GNU_TAR_IMAGES`] +/// qualify. +fn pick_helper_matching(images: &[Value], only_gnu: bool) -> Option { let strings = |v: &Value| v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect::>(); images.iter().find_map(|i| { let digests = strings(&i["RepoDigests"]); strings(&i["RepoTags"]).into_iter().find(|name| { let Some((repo, _)) = name.rsplit_once(':').filter(|(_, tag)| !tag.is_empty() && !tag.contains('/')) else { return false }; - digests.iter().any(|d| official(d) && d.split_once('@').is_some_and(|(r, _)| r == repo)) + (!only_gnu || gnu_tar(name)) && digests.iter().any(|d| official(d) && d.split_once('@').is_some_and(|(r, _)| r == repo)) }) }) } -/// [`pick_helper`] of the images Kiri has, read once from its API. -fn helper_in_kiri() -> io::Result> { +/// Official GNU tar helper (`debian`, `ubuntu`), verified by digest (#506). +fn pick_gnu_helper(images: &[Value]) -> Option { + pick_helper_matching(images, true) +} + +/// The name to run a volume helper by: an official GNU tar image when +/// present, else any official [`TAR_IMAGES`] image (for volume inspection or +/// offline fallback). +fn pick_helper(images: &[Value]) -> Option { + pick_gnu_helper(images).or_else(|| pick_helper_matching(images, false)) +} + +/// Kiri's image records (`RepoTags`, `RepoDigests`), read once from its API. +fn kiri_images() -> io::Result> { let r = client::request("GET", "/images/json", None)?; if !r.ok() { return Err(io::Error::other(format!("kiri: {}", r.error()))); } - Ok(r.json().as_array().and_then(|images| pick_helper(images))) + Ok(r.json().as_array().cloned().unwrap_or_default()) +} + +/// [`pick_helper`] of the images Kiri has (GNU tar preferred, else +/// alpine/busybox). +fn helper_in_kiri() -> io::Result> { + Ok(pick_helper(&kiri_images()?)) +} + +/// [`pick_gnu_helper`] of the images Kiri has (official debian/ubuntu only). +fn gnu_helper_in_kiri() -> io::Result> { + Ok(pick_gnu_helper(&kiri_images()?)) +} + +/// Pull an official GNU tar image (`debian:trixie`) into `ctx`, preferring +/// public mirrors over Docker Hub and never overwriting an existing local +/// `debian:trixie` tag. +fn pull_gnu_image(ctx: &str) -> bool { + let pull = |name: &str| { + cli().is_ok_and(|mut c| { + c.args(["--context", ctx, "pull", "-q", name]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + }) + }; + pull("mirror.gcr.io/library/debian:trixie") + || pull("public.ecr.aws/docker/library/debian:trixie") + || (!has(ctx, "image", "debian:trixie") && pull("debian:trixie")) } -/// When Kiri last failed to fetch a helper: tried once per import, not -/// once per volume. +/// When Kiri last failed to fetch a GNU tar helper: tried once per import, +/// not once per volume. static PULL_FAILED: std::sync::Mutex> = std::sync::Mutex::new(None); -/// [`helper_in_kiri`], else busybox fetched by Kiri: from the public mirror, -/// else from Docker Hub when no image of the person's is called that. -/// Nothing is taken from the source. +/// [`gnu_helper_in_kiri`], else Debian fetched by Kiri: from a public mirror, +/// else from Docker Hub when no image of the person's is called that. When +/// offline, falls back to an official `alpine`/`busybox` already in Kiri so +/// volume import still works without xattrs (#376). Nothing is taken from +/// the source. fn helper() -> io::Result { - if let Some(name) = helper_in_kiri()? { + if let Some(name) = gnu_helper_in_kiri()? { return Ok(name); } - let none = || io::Error::other("Kiri needs one small official image to unpack volumes with: pull alpine or busybox in Kiri (docker pull alpine) and import again. A re-tagged or loaded copy does not count"); + let none = || io::Error::other("Kiri needs one official GNU tar image to unpack volumes with: pull debian in Kiri (docker pull debian:trixie) and import again. A re-tagged or loaded copy does not count"); let mut failed = PULL_FAILED.lock().unwrap_or_else(|e| e.into_inner()); if failed.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(60)) { - return Err(none()); + return helper_in_kiri()?.ok_or_else(none); } let kiri = crate::flavor::CONTEXT.get(); - let pull = |name: &str| cli().is_ok_and(|mut c| c.args(["--context", kiri, "pull", "-q", name]).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success())); - if (pull("mirror.gcr.io/library/busybox") || (!has(kiri, "image", "busybox:latest") && pull("busybox"))) - && let Some(name) = helper_in_kiri()? + if pull_gnu_image(kiri) + && let Some(name) = gnu_helper_in_kiri()? { return Ok(name); } *failed = Some(std::time::Instant::now()); - Err(none()) + helper_in_kiri()?.ok_or_else(none) +} + +/// Official GNU tar image already present on the source engine `ctx`, +/// verified by `RepoDigests` just like Kiri's helper (#506). +fn gnu_helper_in_source(ctx: &str) -> io::Result> { + let rows = json_lines(ctx, &["image", "ls", "--no-trunc", "--format", "{{json .}}"])?; + let mut ids: Vec = Vec::new(); + for v in &rows { + let repo = v["Repository"].as_str().unwrap_or(""); + let id = v["ID"].as_str().unwrap_or(""); + if !id.is_empty() && gnu_tar(repo) && !ids.iter().any(|x| x == id) { + ids.push(id.to_owned()); + } + } + if ids.is_empty() { + return Ok(None); + } + let mut args = vec!["image", "inspect", "--format", r#"{"RepoTags":{{json .RepoTags}},"RepoDigests":{{json .RepoDigests}}}"#]; + let id_refs: Vec<&str> = ids.iter().map(String::as_str).collect(); + args.extend(id_refs); + let inspected = json_lines_found(ctx, &args)?; + Ok(pick_gnu_helper(&inspected)) +} + +/// When pulling the source's GNU tar helper last failed: `(context, when)`. +static SRC_PULL_FAILED: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// An official GNU tar image on `ctx`, pulled if needed and verified by +/// `RepoDigests` (#485, #506). Returns `None` when offline or unable to pull, +/// so volume copy falls back to `docker cp` instead of failing (#376). +fn source_gnu_helper(ctx: &str) -> io::Result> { + if let Some(name) = gnu_helper_in_source(ctx)? { + return Ok(Some(name)); + } + let mut failed = SRC_PULL_FAILED.lock().unwrap_or_else(|e| e.into_inner()); + if failed.as_ref().is_some_and(|(c, t)| c == ctx && t.elapsed() < std::time::Duration::from_secs(60)) { + return Ok(None); + } + if pull_gnu_image(ctx) + && let Some(name) = gnu_helper_in_source(ctx)? + { + return Ok(Some(name)); + } + *failed = Some((ctx.to_owned(), std::time::Instant::now())); + Ok(None) } /// The label on the containers an import makes for itself. @@ -544,8 +756,8 @@ pub fn volume_with(source: &str, name: &str, force: bool) -> io::Result<()> { return Err(io::Error::other(why)); } let img = match kiri_img { - Some(img) => img, - None => helper()?, + Some(img) if gnu_tar(&img) => img, + _ => helper()?, }; if state.is_none() { state = Some(kiri_states(&[name.to_owned()], &img)?[0].1); @@ -569,61 +781,111 @@ pub fn volume_with(source: &str, name: &str, force: bool) -> io::Result<()> { return Err(io::Error::other(why)); } } - // Nothing runs on the source: a container that is made and never - // started mounts the volume read-only (`volume-nocopy`: its image's - // files don't go in), from any image there and never pulled, and - // `docker cp` reads it as an archive with owners, modes and links as - // they are. It goes after, with any anonymous volume its image made; - // one an import that was stopped left behind goes first. - let names = image_names(ctx)?; - let reader_image = match names.first() { - Some(n) => n.clone(), - None => json_lines(ctx, &["image", "ls", "--format", "{{json .ID}}"])? - .first() - .and_then(|v| v.as_str().map(str::to_owned)) - .ok_or_else(|| io::Error::other(format!("{ctx} has no image to read volumes through; pull any image there and import again")))?, - }; + let src_gnu = if gnu_tar(&img) { source_gnu_helper(ctx)? } else { None }; let reader = format!("kiri-import-{name}"); let leftover = json_lines(ctx, &["inspect", "--type", "container", "--format", "{{json .Config.Labels}}", &reader]).unwrap_or_default(); if leftover.first().is_some_and(|l| l["dev.kiri.import-helper"] == "1") { let _ = cli()?.args(["--context", ctx, "rm", "-fv", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); } - // At a path no image can have a VOLUME of its own at or under. - use std::hash::BuildHasher; - let at = format!("/kiri-import-{:016x}", std::collections::hash_map::RandomState::new().hash_one(name)); - let mount = format!("type=volume,src={name},dst={at},readonly,volume-nocopy"); - let made = cli()? - .args(["--context", ctx, "create", "--name", &reader, "--pull", "never", "--network", "none", "--label", HELPER, "--entrypoint", &at, "--mount", &mount, &reader_image]) - .stdout(Stdio::null()) - .stderr(Stdio::piped()) - .output()?; - if !made.status.success() { - return Err(io::Error::other(format!("{ctx}: {}", String::from_utf8_lossy(&made.stderr).trim()))); - } - let copied = copy_volume(ctx, &format!("{reader}:{at}/."), name, &img); - let _ = cli()?.args(["--context", ctx, "rm", "-v", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + let copied = if let Some(src_img) = src_gnu { + // GNU tar in an official helper on the source reads the volume + // read-only (`volume-nocopy`: no image files go in) and puts numeric + // owners and `user.*` xattrs in the stream; `docker cp` leaves xattrs + // out (#485). + let mount = format!("type=volume,src={name},dst=/from,readonly,volume-nocopy"); + let mut read = cli()?; + read.args(volume_reader_args(ctx, &reader, &mount, &src_img)); + let r = copy_volume(read, ctx, name, &img, force); + if r.is_err() { + let _ = cli()?.args(["--context", ctx, "rm", "-fv", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + } + r + } else { + // Offline / no official GNU tar helper on both engines: fall back to + // a stopped reader + `docker cp` so volume import still works (#376) + // without running any unverified image on the source (#506). + eprintln!("kiri: importing volume {name} without extended attributes (no official Debian or Ubuntu image available on both engines)"); + let names = image_names(ctx)?; + let reader_image = match names.first() { + Some(n) => n.clone(), + None => json_lines(ctx, &["image", "ls", "--format", "{{json .ID}}"])? + .first() + .and_then(|v| v.as_str().map(str::to_owned)) + .ok_or_else(|| io::Error::other(format!("{ctx} has no image to read volumes through; pull any image there and import again")))?, + }; + // At a path no image can have a VOLUME of its own at or under. + use std::hash::BuildHasher; + let at = format!("/kiri-import-{:016x}", std::collections::hash_map::RandomState::new().hash_one(name)); + let mount = format!("type=volume,src={name},dst={at},readonly,volume-nocopy"); + let made = cli()? + .args(["--context", ctx, "create", "--name", &reader, "--pull", "never", "--network", "none", "--label", HELPER, "--entrypoint", &at, "--mount", &mount, &reader_image]) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .output()?; + if !made.status.success() { + return Err(io::Error::other(format!("{ctx}: {}", String::from_utf8_lossy(&made.stderr).trim()))); + } + let mut read = cli()?; + read.args(["--context", ctx, "cp", &format!("{reader}:{at}/."), "-"]); + let r = copy_volume(read, ctx, name, &img, false); + let _ = cli()?.args(["--context", ctx, "rm", "-v", &reader]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + r + }; copied.map_err(|e| io::Error::other(format!("{e}; {name} is unfinished in Kiri: the next import empties it and copies it again, replacing what is in it then"))) } -/// `docker cp` out of the reader on the source, through [`retar`], untarred -/// into the volume by a helper on Kiri that removes itself. The helper -/// marks the volume unfinished first (emptying what an unfinished copy -/// left), and the mark goes only once every part of the copy succeeded. -fn copy_volume(ctx: &str, from: &str, name: &str, img: &str) -> io::Result<()> { +/// GNU tar in an official helper on the source, streaming the volume with +/// numeric owners and xattrs. `--entrypoint tar` guarantees the image's own +/// entrypoint never runs instead of `tar`. +fn volume_reader_args<'a>(ctx: &'a str, reader: &'a str, mount: &'a str, img: &'a str) -> Vec<&'a str> { + let mut args = vec![ + "--context", + ctx, + "run", + "--rm", + "--name", + reader, + "--network", + "none", + "--label", + HELPER, + "--pull", + "never", + "--mount", + mount, + "--entrypoint", + "tar", + img, + ]; + args.extend(STORE_XATTRS); + args.extend(["-C", "/from", "-cf", "-", "."]); + args +} + +/// Shell script run in Kiri's helper container to clear an unfinished copy, +/// mark the volume unfinished, and unpack the tar stream from stdin. +fn restore_script(with_gnu_tar: bool) -> String { + let flags = if with_gnu_tar { format!(" {RESTORE_XATTRS}") } else { String::new() }; + format!( + r#"set -e; cd /to; if [ -e {m} ]; then find . -mindepth 1 -maxdepth 1 ! -name {m} -exec rm -rf -- {{}} + || true; for f in .[!.]* ..?* *; do if [ "$f" != {m} ] && {{ [ -e "$f" ] || [ -L "$f" ]; }}; then echo "could not empty the volume: $f is left" >&2; exit 1; fi; done; fi; touch {m}; tar{flags} -xpf -"#, + m = UNFINISHED + ) +} + +/// A tar stream out of the reader on the source, through [`retar`], untarred +/// into the volume by a helper on Kiri that removes itself. The helper marks +/// the volume unfinished first (emptying what an unfinished copy left), and +/// the mark goes only once every part of the copy succeeded. +fn copy_volume(read: Command, ctx: &str, name: &str, img: &str, allow_file_changed: bool) -> io::Result<()> { let kiri = crate::flavor::CONTEXT.get(); let dst_mount = format!("{name}:/to"); - let mut read = cli()?; - read.args(["--context", ctx, "cp", from, "-"]); let mut write = cli()?; // Emptied in one pass, all but the mark (a folder by that name counts as // it); anything still there after, hidden names too, stops the copy with // the mark left on. - let script = format!( - r#"set -e; cd /to; if [ -e {m} ]; then find . -mindepth 1 -maxdepth 1 ! -name {m} -exec rm -rf -- {{}} + || true; for f in .[!.]* ..?* *; do if [ "$f" != {m} ] && {{ [ -e "$f" ] || [ -L "$f" ]; }}; then echo "could not empty the volume: $f is left" >&2; exit 1; fi; done; fi; touch {m}; tar -xpf -"#, - m = UNFINISHED - ); + let script = restore_script(gnu_tar(img)); write.args(["--context", kiri, "run", "--rm", "-i", "--network", "none", "--label", HELPER, "-v", &dst_mount, "--pull", "never", "--entrypoint", "sh", img, "-c", &script]); - pipe(read, write, ctx, |from, to| retar(from, to, None))?; + pipe_with(read, write, ctx, allow_file_changed, |from, to| retar(from, to, None))?; let done = cli()?.args(["--context", kiri, "run", "--rm", "--network", "none", "--label", HELPER, "-v", &dst_mount, "--pull", "never", "--entrypoint", "rm", img, "-rf", "--", &format!("/to/{UNFINISHED}")]).stdout(Stdio::null()).stderr(Stdio::piped()).output()?; if !done.status.success() { return Err(io::Error::other(format!("kiri: {}", String::from_utf8_lossy(&done.stderr).trim()))); @@ -663,7 +925,7 @@ pub fn container_with(source: &str, name: &str, force: bool, joining: &[&str]) - let info = json_lines(ctx, &["inspect", "--type", "container", "--format", "{{json .}}", name])?.into_iter().next().ok_or_else(|| io::Error::other(format!("{name}: not found in {ctx}")))?; let image = info["Config"]["Image"].as_str().unwrap_or("").to_owned(); if !has(kiri, "image", &image) { - self::image(source, &image)?; + self::image(source, &image).map_err(|e| io::Error::other(format!("image {image}: {e}")))?; } // Else create would make them in Kiri, empty. for v in volumes_of(&info) { @@ -699,11 +961,618 @@ pub fn container_with(source: &str, name: &str, force: bool, joining: &[&str]) - } let r = client::request("POST", &format!("/containers/create?name={name}"), Some(&create_body(&info, &mode, networks.into())))?; if !r.ok() { - return Err(io::Error::other(r.error())); + return Err(io::Error::other(create_error(r.status, &r.error()))); + } + if let Err(e) = writable_layer(ctx, &info, name) { + // Without the files it wrote, the container is not the one it was: + // it goes again, and the reason is said. Its volumes stay. + let _ = client::request("DELETE", &format!("/containers/{name}?force=1"), None); + return Err(io::Error::other(format!("its writable layer: {e}"))); + } + Ok(()) +} + +/// The engine's own files, which each engine makes and mounts over the +/// container's for itself: never carried over. +const ENGINE_FILES: [&str; 4] = ["/etc/hosts", "/etc/hostname", "/etc/resolv.conf", "/.dockerenv"]; + +/// The kernel's filesystems and the engine's `/dev`, mounted in every +/// container: nothing at or under them is carried over. +const KERNEL_TREES: [&str; 3] = ["/proc", "/sys", "/dev"]; + +/// How many `docker cp` run at once to read the paths a layer changed. +const READERS: usize = 8; + +/// A file up to this size is read ahead, in parallel, while the paths +/// before it are written; a bigger one is read when its turn comes. +const READ_AHEAD_FILE: u64 = 1 << 20; + +/// What the files read ahead may hold at once, all together. +const READ_AHEAD_TOTAL: u64 = 64 << 20; + +/// The container's writable layer on the source (#410): the files it wrote +/// outside its volumes, its changes to the image's files and what it +/// deleted of them, as `docker diff` lists them, become the writable layer +/// of the container just made as `name` in Kiri, before it first runs. +/// Nothing is made on the source: each path is read with `docker cp`, only +/// what changed, never the image's unchanged files, and nothing at or under +/// the container's mounts (volumes are copied as volumes, binds stay where +/// they are). A container that changed nothing costs one `docker diff`. +fn writable_layer(ctx: &str, info: &Value, name: &str) -> io::Result<()> { + let id = info["Id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| io::Error::other("the source gave no container id"))?; + let out = cli()?.args(["--context", ctx, "container", "diff", id]).stdin(Stdio::null()).stderr(Stdio::piped()).output()?; + if !out.status.success() { + return Err(io::Error::other(format!("{ctx}: docker diff: {}", String::from_utf8_lossy(&out.stderr).trim()))); + } + let plan = plan_layer(&parse_diff(&String::from_utf8_lossy(&out.stdout)), &mount_points(info)); + if plan.is_empty() { + return Ok(()); + } + let r = client::post_stream(&format!("/kiri/containers/{name}/upper"), "application/x-tar", |w| write_layer(ctx, id, &plan, w))?; + if !r.ok() { + return Err(io::Error::other(create_error(r.status, &r.error()))); + } + Ok(()) +} + +/// `docker diff`'s lines as (kind, path): `A` added, `C` changed, `D` +/// deleted. A line that is none of these, or names a path that is not +/// absolute and plain (no `.`, `..` or empty steps), is left out. +fn parse_diff(text: &str) -> Vec<(char, String)> { + text.lines() + .filter_map(|l| { + let (kind, path) = l.strip_suffix('\r').unwrap_or(l).split_once(' ')?; + let kind = match kind { + "A" => 'A', + "C" => 'C', + "D" => 'D', + _ => return None, + }; + let plain = path.len() > 1 && path.starts_with('/') && path[1..].split('/').all(|c| !matches!(c, "" | "." | "..")); + plain.then(|| (kind, path.to_owned())) + }) + .collect() +} + +/// Where the container has something mounted on the source: volumes, binds +/// and tmpfs, as absolute paths without a trailing `/`. +fn mount_points(info: &Value) -> Vec { + let hc = &info["HostConfig"]; + let mut found: Vec<&str> = info["Mounts"].as_array().into_iter().flatten().filter_map(|m| m["Destination"].as_str()).collect(); + found.extend(hc["Mounts"].as_array().into_iter().flatten().filter_map(|m| m["Target"].as_str())); + found.extend(hc["Tmpfs"].as_object().into_iter().flatten().map(|(k, _)| k.as_str())); + let mut points: Vec = Vec::new(); + for p in found { + let clean = format!("/{}", p.split('/').filter(|c| !c.is_empty() && *c != ".").collect::>().join("/")); + if clean != "/" && !points.contains(&clean) { + points.push(clean); + } + } + points +} + +/// Whether `path` is `top` or under it. +fn at_or_under(path: &str, top: &str) -> bool { + path == top || below(path, top) +} + +/// Whether `path` is under `top` (not `top` itself). +fn below(path: &str, top: &str) -> bool { + path.strip_prefix(top).is_some_and(|rest| rest.starts_with('/')) +} + +/// Paths in the order a layer lists them: each directory right before +/// what is under it. +fn path_order(a: &str, b: &str) -> std::cmp::Ordering { + a.split('/').cmp(b.split('/')) +} + +/// What of a container's writable layer is carried over, from what `docker +/// diff` lists. `docker diff` names every path the layer holds (an added +/// directory's contents too) and the directories they are in, so each is +/// read on its own; only a new directory with nothing mounted under it is +/// read whole, in one go. +#[derive(Debug, Default, PartialEq)] +struct LayerPlan { + /// Deleted on the source: a whiteout each, unless the path is there + /// again (a directory deleted and made again, which turns opaque). + deleted: Vec, + /// Carried over by their own entry: a file whole, a directory with its + /// mode, owner and time and none of what is in it, which is listed (or + /// unchanged in the image) on its own. `/etc` changed because a file was + /// added to it brings that file and `/etc`'s own entry, not all of `/etc`. + entries: Vec, + /// New directories, not in the image, carried over whole. + trees: Vec, +} + +impl LayerPlan { + fn is_empty(&self) -> bool { + self.deleted.is_empty() && self.entries.is_empty() && self.trees.is_empty() + } +} + +/// The plan for `changes` (`docker diff`'s lines) of a container with +/// `mounts`: nothing at or under a mount, the engine's own files or the +/// kernel's filesystems; a directory listed only for those is left out; +/// every directory a path is in comes too, so the layer keeps its mode +/// and owner. +fn plan_layer(changes: &[(char, String)], mounts: &[String]) -> LayerPlan { + let left_out = |p: &str| ENGINE_FILES.contains(&p) || KERNEL_TREES.iter().copied().chain(mounts.iter().map(String::as_str)).any(|t| at_or_under(p, t)); + let mut sorted: Vec<&(char, String)> = changes.iter().collect(); + sorted.sort_by(|a, b| path_order(&a.1, &b.1)); + sorted.dedup_by(|a, b| a.1 == b.1); + let mut plan = LayerPlan::default(); + let mut i = 0; + while i < sorted.len() { + let (kind, path) = (sorted[i].0, sorted[i].1.as_str()); + let end = sorted[i + 1..].iter().position(|(_, p)| !below(p, path)).map_or(sorted.len(), |n| i + 1 + n); + let inside = &sorted[i + 1..end]; + i += 1; + if left_out(path) { + continue; + } + match kind { + 'D' => plan.deleted.push(path.to_owned()), + 'A' if !inside.is_empty() && inside.iter().all(|(k, p)| *k == 'A' && !left_out(p)) => { + plan.trees.push(path.to_owned()); + i = end; + } + 'C' if !inside.is_empty() && inside.iter().all(|(_, p)| left_out(p)) => {} + _ => plan.entries.push(path.to_owned()), + } + } + let mut have: std::collections::HashSet = plan.deleted.iter().chain(&plan.entries).chain(&plan.trees).cloned().collect(); + let mut parents = Vec::new(); + for p in plan.deleted.iter().chain(&plan.entries).chain(&plan.trees) { + let mut at = p.as_str(); + while let Some((parent, _)) = at.rsplit_once('/').filter(|(parent, _)| !parent.is_empty()) { + if have.insert(parent.to_owned()) { + parents.push(parent.to_owned()); + } + at = parent; + } + } + plan.entries.extend(parents); + plan.entries.sort_by(|a, b| path_order(a, b)); + plan +} + +/// One path the layer brings, read on its own ahead of its turn. +enum Read1 { + /// Not there (gone since `docker diff`), or nothing a tar can hold (a socket). + Missing, + /// A directory's own entry. + Dir(Vec), + /// Anything else, whole. + Whole(Vec), + /// A file too big to read ahead: read when its turn comes. + Later, +} + +/// Writes the layer `plan` names as an OCI layer tar (whiteouts as `.wh.` +/// files, opaque directories with `.wh..wh..opq`), each path read from the +/// source container `id` with `docker cp`. What the writer refuses keeps +/// its error kind: `client::post_stream` then reads the daemon's reason. +fn write_layer(ctx: &str, id: &str, plan: &LayerPlan, out: &mut dyn Write) -> io::Result<()> { + let ahead: Vec<&str> = plan.entries.iter().chain(&plan.deleted).map(String::as_str).collect(); + let mut read = read_ahead(ctx, id, &ahead)?.into_iter(); + let mut got: std::collections::HashMap<&str, Read1> = ahead.iter().map(|p| (*p, read.next().unwrap_or(Read1::Later))).collect(); + let mut steps: Vec<(&str, u8)> = plan.entries.iter().map(|p| (p.as_str(), b'e')).collect(); + steps.extend(plan.deleted.iter().map(|p| (p.as_str(), b'd'))); + steps.extend(plan.trees.iter().map(|p| (p.as_str(), b't'))); + steps.sort_by(|a, b| path_order(a.0, b.0)); + for (path, step) in steps { + if step == b't' { + read_paths(ctx, id, path, out, true)?; + continue; + } + match (got.remove(path).unwrap_or(Read1::Later), step) { + (Read1::Missing, b'd') => write_marker(out, &whiteout_name(path))?, + (Read1::Missing, _) => {} + // Deleted, and a directory there again: what the image had in it is gone. + (Read1::Dir(bytes), b'd') => { + out.write_all(&bytes)?; + write_marker(out, &format!("{}/.wh..wh..opq", &path[1..]))?; + } + (Read1::Dir(bytes) | Read1::Whole(bytes), _) => out.write_all(&bytes)?, + (Read1::Later, _) => read_paths(ctx, id, path, out, false)?, + } + } + out.write_all(&[0u8; 1024]) +} + +/// The name of the whiteout that deletes `path`: `.wh.` and its name, in +/// its directory. +fn whiteout_name(path: &str) -> String { + let (dir, base) = path.rsplit_once('/').unwrap_or(("", path)); + format!("{}.wh.{base}", if dir.is_empty() { String::new() } else { format!("{}/", &dir[1..]) }) +} + +/// Reads `paths` from the source container, [`READERS`] at a time: each +/// one's entry, in the order given, ready to write. +fn read_ahead(ctx: &str, id: &str, paths: &[&str]) -> io::Result> { + use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; + let next = AtomicUsize::new(0); + let held = AtomicU64::new(0); + let failed = AtomicBool::new(false); + let slots: Vec>>> = paths.iter().map(|_| std::sync::Mutex::new(None)).collect(); + std::thread::scope(|s| { + for _ in 0..READERS.min(paths.len()) { + s.spawn(|| { + while !failed.load(Ordering::Relaxed) { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(path) = paths.get(i) else { break }; + let r = read_one(ctx, id, path, &held); + failed.fetch_or(r.is_err(), Ordering::Relaxed); + *slots[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + } + }); + } + }); + slots.into_iter().map(|s| s.into_inner().unwrap_or_else(|e| e.into_inner()).unwrap_or(Ok(Read1::Later))).collect() +} + +/// One path's own entry, read ahead: a directory's without what is in it, +/// a small file's whole; a big one is left for later, so what is read +/// ahead stays under [`READ_AHEAD_TOTAL`] (`held`). +fn read_one(ctx: &str, id: &str, path: &str, held: &std::sync::atomic::AtomicU64) -> io::Result { + use std::sync::atomic::Ordering; + let mut cp = Cp::start(ctx, id, path)?; + let entry = match read_entry(&mut cp.out) { + Ok(Some(e)) => e, + Ok(None) => return cp.finish().map(|_| Read1::Missing), + Err(e) => return cp.failed(e).map(|()| Read1::Missing), + }; + let mut bytes = Vec::new(); + write_renamed(&mut bytes, &entry, path)?; + if entry.header[156] == b'5' { + cp.stop(); + return Ok(Read1::Dir(bytes)); + } + if entry.size > READ_AHEAD_FILE { + cp.stop(); + return Ok(Read1::Later); + } + let padded = entry.size.next_multiple_of(512); + if held.fetch_add(padded, Ordering::Relaxed).saturating_add(padded) > READ_AHEAD_TOTAL { + cp.stop(); + return Ok(Read1::Later); + } + if let Err(e) = copy_body(&mut cp.out, &mut bytes, padded) { + return cp.failed(e).map(|()| Read1::Missing); + } + cp.stop(); + Ok(Read1::Whole(bytes)) +} + +/// Writes `path` read from the source container now: its own entry (a +/// directory's without what is in it), or with `whole` everything under +/// it. Gone since `docker diff` (a running container), it is left out. +fn read_paths(ctx: &str, id: &str, path: &str, out: &mut dyn Write, whole: bool) -> io::Result<()> { + let mut cp = Cp::start(ctx, id, path)?; + loop { + let entry = match read_entry(&mut cp.out) { + Ok(Some(e)) => e, + Ok(None) => return cp.finish().map(|_| ()), + Err(e) => return cp.failed(e), + }; + write_renamed(out, &entry, path)?; + if !whole && entry.header[156] == b'5' { + cp.stop(); + return Ok(()); + } + let padded = entry.size.checked_next_multiple_of(512).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "tar stream: a damaged header"))?; + let mut body = (&mut cp.out).take(padded); + let copied = io::copy(&mut body, out)?; + if copied != padded { + return cp.failed(io::Error::new(io::ErrorKind::UnexpectedEof, "cut off inside a file's body")); + } + if !whole { + cp.stop(); + return Ok(()); + } + } +} + +/// `docker cp` of one path out of the source container, as a tar stream. +struct Cp { + child: std::process::Child, + out: std::process::ChildStdout, + said: Option>, + path: String, +} + +impl Cp { + fn start(ctx: &str, id: &str, path: &str) -> io::Result { + let mut child = cli()?.args(["--context", ctx, "cp", &format!("{id}:{path}"), "-"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?; + let out = child.stdout.take().ok_or_else(|| io::Error::other("no output from docker"))?; + // Read meanwhile: a full pipe would stop it. + let said = child.stderr.take().map(|mut e| { + std::thread::spawn(move || { + let mut text = String::new(); + let _ = e.read_to_string(&mut text); + text.trim().to_owned() + }) + }); + Ok(Cp { child, out, said, path: path.to_owned() }) + } + + /// Stops it: all that was wanted of it is read. + fn stop(self) { + drop(self); + } + + /// Waits for it to end. `Ok(false)` when the path is not there. + fn finish(mut self) -> io::Result { + let _ = io::copy(&mut self.out, &mut io::sink()); + let status = self.child.wait()?; + let said = self.said.take().and_then(|t| t.join().ok()).unwrap_or_default(); + if status.success() { + return Ok(true); + } + if gone(&said) { + return Ok(false); + } + Err(io::Error::other(format!("docker cp {}: {}", self.path, if said.is_empty() { "failed" } else { &said }))) + } + + /// After reading its output failed with `e`: `Ok` when the path is + /// simply not there, else what docker said, or `e`. + fn failed(mut self, e: io::Error) -> io::Result<()> { + self.end(); + let said = self.said.take().and_then(|t| t.join().ok()).unwrap_or_default(); + if gone(&said) { + return Ok(()); + } + let why = if said.is_empty() { e.to_string() } else { said }; + Err(io::Error::new(if e.kind() == io::ErrorKind::BrokenPipe { io::ErrorKind::Other } else { e.kind() }, format!("docker cp {}: {why}", self.path))) + } +} + +impl Cp { + fn end(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// One stopped early, or left when writing failed, ends with it. +impl Drop for Cp { + fn drop(&mut self) { + self.end(); + } +} + +/// Whether `docker cp` said the path is not there. +fn gone(said: &str) -> bool { + let said = said.to_ascii_lowercase(); + said.contains("could not find the file") || said.contains("no such container:path") +} + +/// A tar entry as read: its header, its pax records (`path` and +/// `linkpath` taken out into `name` and `link`), and its body's size. +struct TarEntry { + header: [u8; 512], + pax: Vec<(String, String)>, + name: String, + link: String, + size: u64, +} + +/// The next entry's headers in a tar stream, its body still to read; +/// `None` at the archive's end. Pax and GNU long-name headers are folded +/// into the entry they come before. +fn read_entry(r: &mut dyn Read) -> io::Result> { + let bad = |what: &str| io::Error::new(io::ErrorKind::InvalidData, format!("tar stream: {what}")); + let text = |b: &[u8]| String::from_utf8_lossy(b.split(|c| *c == 0).next().unwrap_or_default()).into_owned(); + let mut pax: Vec<(String, String)> = Vec::new(); + let (mut long_name, mut long_link) = (None, None); + loop { + let mut h = [0u8; 512]; + r.read_exact(&mut h).map_err(|e| if e.kind() == io::ErrorKind::UnexpectedEof { bad("cut off before the archive's end") } else { e })?; + if h.iter().all(|b| *b == 0) { + return Ok(None); + } + let size = get_number(&h[124..136]).ok_or_else(|| bad("a damaged header"))?; + if matches!(h[156], b'x' | b'g' | b'L' | b'K') { + if size > 16 << 20 { + return Err(bad("a header too large")); + } + let mut data = vec![0u8; size.next_multiple_of(512) as usize]; + r.read_exact(&mut data).map_err(|e| if e.kind() == io::ErrorKind::UnexpectedEof { bad("cut off inside a header") } else { e })?; + data.truncate(size as usize); + match h[156] { + b'x' => pax.extend(pax_records(&data)), + b'L' => long_name = Some(text(&data)), + b'K' => long_link = Some(text(&data)), + // A global header says nothing about this entry. + _ => {} + } + continue; + } + let posix = &h[257..263] == b"ustar\0"; + let mut name = long_name.unwrap_or_else(|| match text(&h[345..500]) { + prefix if posix && !prefix.is_empty() => format!("{prefix}/{}", text(&h[..100])), + _ => text(&h[..100]), + }); + let mut link = long_link.unwrap_or_else(|| text(&h[157..257])); + let mut size = size; + pax.retain(|(k, v)| match k.as_str() { + "path" => { + name.clone_from(v); + false + } + "linkpath" => { + link.clone_from(v); + false + } + "size" => { + size = v.parse().unwrap_or(size); + true + } + _ => true, + }); + size.checked_next_multiple_of(512).ok_or_else(|| bad("a damaged header"))?; + return Ok(Some(TarEntry { header: h, pax, name, link, size })); + } +} + +/// Writes `e`, which `docker cp` of `path` named from `path`'s last step +/// (`hosts2` for `/etc/hosts2`), under its path in the layer instead +/// (`etc/hosts2`); a hard link's target likewise. Anything else under +/// that name is not what was asked for. +fn write_renamed(out: &mut dyn Write, e: &TarEntry, path: &str) -> io::Result<()> { + let base = path.rsplit('/').next().unwrap_or_default(); + let rebase = |name: &str| -> Option { + let rest = name.trim_start_matches("./").trim_start_matches('/').strip_prefix(base)?; + (rest.is_empty() || rest.starts_with('/')).then(|| format!("{}{rest}", &path[1..])) + }; + let name = rebase(&e.name).ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, format!("docker cp {path}: an entry named {:?}", e.name)))?; + let link = if e.header[156] == b'1' { rebase(&e.link).unwrap_or_else(|| e.link.clone()) } else { e.link.clone() }; + write_entry(out, e, &name, &link) +} + +/// Writes `e`'s headers as `name` (and `link`): in the header where they +/// fit, else in a pax header before it, which also keeps the records it +/// came with, less overlayfs's own attributes. Size, owner and group a pax +/// record gives go in the header too, as [`retar`] puts them. +fn write_entry(out: &mut dyn Write, e: &TarEntry, name: &str, link: &str) -> io::Result<()> { + let mut pax: Vec<(String, String)> = e.pax.iter().filter(|(k, _)| !k.starts_with("SCHILY.xattr.trusted.overlay.")).cloned().collect(); + if name.len() > 100 { + pax.push(("path".into(), name.into())); + } + if link.len() > 100 { + pax.push(("linkpath".into(), link.into())); + } + let mut h = e.header; + put_text(&mut h[..100], name); + put_text(&mut h[157..257], link); + if &h[257..263] == b"ustar\0" { + h[345..500].fill(0); + } + for (key, at) in [("size", 124..136), ("uid", 108..116), ("gid", 116..124)] { + if let Some(v) = pax.iter().rfind(|(k, _)| k == key).and_then(|(_, v)| v.parse::().ok()) { + put_number(&mut h[at], v); + } + } + put_checksum(&mut h); + if !pax.is_empty() { + let mut data = Vec::new(); + for (k, v) in &pax { + data.extend_from_slice(&pax_record(k, v)); + } + let mut x = plain_header(b'x', "././@PaxHeader", data.len() as u64, 0o644); + put_checksum(&mut x); + out.write_all(&x)?; + data.resize(data.len().next_multiple_of(512), 0); + out.write_all(&data)?; + } + out.write_all(&h) +} + +/// An empty file named `name`, owned by root: a whiteout or opaque mark. +fn write_marker(out: &mut dyn Write, name: &str) -> io::Result<()> { + let e = TarEntry { header: plain_header(b'0', "", 0, 0o644), pax: Vec::new(), name: name.to_owned(), link: String::new(), size: 0 }; + write_entry(out, &e, name, "") +} + +/// A ustar header of kind `kind`, owned by root, with a time of 0. +fn plain_header(kind: u8, name: &str, size: u64, mode: u32) -> [u8; 512] { + let mut h = [0u8; 512]; + put_text(&mut h[..100], name); + put_number(&mut h[100..108], u64::from(mode)); + put_number(&mut h[108..116], 0); + put_number(&mut h[116..124], 0); + put_number(&mut h[124..136], size); + put_number(&mut h[136..148], 0); + h[156] = kind; + h[257..263].copy_from_slice(b"ustar\0"); + h[263..265].copy_from_slice(b"00"); + h +} + +/// A text field: as much of `s` as fits, the rest NUL. +fn put_text(field: &mut [u8], s: &str) { + field.fill(0); + let n = s.len().min(field.len()); + field[..n].copy_from_slice(&s.as_bytes()[..n]); +} + +fn put_checksum(h: &mut [u8; 512]) { + update_checksum(h); +} + +/// An entry's body, padded to whole blocks, from `from` to `to`. +fn copy_body(from: &mut dyn Read, to: &mut Vec, padded: u64) -> io::Result<()> { + if (&mut *from).take(padded).read_to_end(to)? as u64 != padded { + return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "cut off inside a file's body")); } Ok(()) } +/// Non-empty reason for a failed `/containers/create` call, falling back to +/// the HTTP status if the daemon returned an empty body (#411). +fn create_error(status: u16, msg: &str) -> String { + let trimmed = msg.trim(); + if trimmed.is_empty() { format!("HTTP {status}") } else { trimmed.to_owned() } +} + +/// Translates Docker Desktop's VM-internal host-mount paths to host paths Kiri +/// can bind directly (#411): +/// - macOS Docker Desktop: `/host_mnt/` -> `/` +/// - Windows Docker Desktop: `/run/desktop/mnt/host//` and +/// `/host_mnt//` -> `:/` +/// +/// Bare prefixes (`/host_mnt`, `/host_mnt/`, `/run/desktop/mnt/host/`), +/// look-alike prefixes (`/host_mnt_other/...`), and paths containing `..` +/// segments stay unchanged so normalization never collapses to `/` or +/// traverses outside the intended path. +fn translate_bind_source_for(src: &str, windows: bool) -> String { + let has_dotdot = |p: &str| p.split('/').any(|s| s == ".."); + let drive_path = |rest: &str| -> Option { + let trimmed = rest.trim_start_matches('/'); + if trimmed.is_empty() || has_dotdot(trimmed) { + return None; + } + let (drive, tail) = trimmed.split_once('/').unwrap_or((trimmed, "")); + if drive.len() != 1 || !drive.as_bytes()[0].is_ascii_alphabetic() { + return None; + } + let tail = tail.trim_start_matches('/'); + if tail.is_empty() { Some(format!("{}:/", drive.to_ascii_uppercase())) } else { Some(format!("{}:/{tail}", drive.to_ascii_uppercase())) } + }; + if windows { + if let Some(rest) = src.strip_prefix("/run/desktop/mnt/host/") { + return drive_path(rest).unwrap_or_else(|| src.to_owned()); + } + if let Some(rest) = src.strip_prefix("/host_mnt/") { + return drive_path(rest).unwrap_or_else(|| src.to_owned()); + } + return src.to_owned(); + } + if let Some(rest) = src.strip_prefix("/host_mnt/") { + let trimmed = rest.trim_start_matches('/'); + if !has_dotdot(trimmed) && trimmed.split('/').any(|s| !s.is_empty() && s != ".") { + return format!("/{trimmed}"); + } + } + src.to_owned() +} + +/// Translates the source side of a `HostConfig.Binds` entry (`SRC:DST[:OPTS]`), +/// preserving the destination and any mount options (`:ro`, `:delegated`, etc.). +fn translate_bind_spec_for(spec: &str, windows: bool) -> String { + let Some((src, rest)) = spec.split_once(':') else { + return spec.to_owned(); + }; + if !rest.starts_with('/') { + return spec.to_owned(); + } + let translated = translate_bind_source_for(src, windows); + if translated == src { spec.to_owned() } else { format!("{translated}:{rest}") } +} + /// The volumes a container has on the source, named and anonymous. fn volumes_of(info: &Value) -> Vec { let mut names: Vec = Vec::new(); @@ -723,6 +1592,10 @@ fn volumes_of(info: &Value) -> Vec { /// new empty ones. Beside `container:` mode, what Docker and Kiri refuse /// there is left out: the source fills some of it in itself (#375). fn create_body(info: &Value, mode: &str, networks: Value) -> Value { + create_body_for(info, mode, networks, cfg!(windows)) +} + +fn create_body_for(info: &Value, mode: &str, networks: Value, windows: bool) -> Value { let (cfg, hc) = (&info["Config"], &info["HostConfig"]); let anon: Vec<(&str, &str, bool)> = info["Mounts"] .as_array() @@ -732,12 +1605,29 @@ fn create_body(info: &Value, mode: &str, networks: Value) -> Value { .filter_map(|m| Some((m["Name"].as_str().filter(|n| anonymous(n))?, m["Destination"].as_str()?, m["RW"] != false))) .collect(); let mut mounts = hc["Mounts"].clone(); - for m in mounts.as_array_mut().into_iter().flatten().filter(|m| m["Type"] == "volume" && m["Source"].as_str().unwrap_or("").is_empty()) { - if let Some((n, _, _)) = anon.iter().find(|(_, d, _)| m["Target"].as_str() == Some(d)) { - m["Source"] = (*n).into(); + for m in mounts.as_array_mut().into_iter().flatten() { + if m["Type"] == "volume" && m["Source"].as_str().unwrap_or("").is_empty() { + if let Some((n, _, _)) = anon.iter().find(|(_, d, _)| m["Target"].as_str() == Some(d)) { + m["Source"] = (*n).into(); + } + } else if m["Type"].as_str().unwrap_or("bind") == "bind" + && let Some(src) = m["Source"].as_str() + { + let translated = translate_bind_source_for(src, windows); + if translated != src { + m["Source"] = translated.into(); + } } } let mut binds = hc["Binds"].clone(); + for b in binds.as_array_mut().into_iter().flatten() { + if let Some(spec) = b.as_str() { + let translated = translate_bind_spec_for(spec, windows); + if translated != spec { + *b = translated.into(); + } + } + } for (n, d, rw) in &anon { if !mounts.as_array().into_iter().flatten().any(|m| m["Target"].as_str() == Some(d)) { let bind = format!("{n}:{d}{}", if *rw { "" } else { ":ro" }); @@ -754,6 +1644,7 @@ fn create_body(info: &Value, mode: &str, networks: Value) -> Value { "NanoCpus": hc["NanoCpus"], "ShmSize": hc["ShmSize"], "PublishAllPorts": hc["PublishAllPorts"], "Devices": hc["Devices"], "DeviceCgroupRules": hc["DeviceCgroupRules"], "GroupAdd": hc["GroupAdd"], "Ulimits": hc["Ulimits"], "Sysctls": hc["Sysctls"], "Dns": hc["Dns"], "DnsSearch": hc["DnsSearch"], "DnsOptions": hc["DnsOptions"], "PidMode": hc["PidMode"], + "CgroupnsMode": hc["CgroupnsMode"], "Init": hc["Init"], "LogConfig": hc["LogConfig"], "AutoRemove": hc["AutoRemove"], "CpuShares": hc["CpuShares"], "CpuQuota": hc["CpuQuota"], "CpuPeriod": hc["CpuPeriod"], "PidsLimit": hc["PidsLimit"], }); @@ -808,13 +1699,28 @@ fn pick(given: Option<&str>, answers: impl Fn(&str) -> bool) -> io::Result<&'sta } const KINDS: [&str; 3] = ["image", "volume", "container"]; -const USAGE: &str = "usage: kiri import [orbstack|desktop-linux] [--list | [--force] [image|volume|container NAME]]"; +#[cfg(windows)] +const USAGE: &str = "usage: kiri import [desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]"; +#[cfg(not(windows))] +const USAGE: &str = "usage: kiri import [orbstack|desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]"; + +/// Which resource kinds a bulk `kiri import` or `kiri import --list` includes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct KindFilter { + images: bool, + volumes: bool, + containers: bool, +} + +impl KindFilter { + const ALL: Self = Self { images: true, volumes: true, containers: true }; +} /// What `kiri import` was asked to do. #[derive(Debug, PartialEq)] enum Ask<'a> { - Everything, - List, + Everything(KindFilter), + List(KindFilter), One(&'a str, &'a str), } @@ -825,38 +1731,80 @@ enum Ask<'a> { fn parse<'a>(args: &[&'a str]) -> io::Result<(Option<&'a str>, Ask<'a>, bool)> { let usage = || io::Error::other(USAGE); let (mut list, mut force) = (false, false); + let (mut f_images, mut f_volumes, mut f_containers) = (false, false, false); let mut words = Vec::new(); for a in args { match *a { "--list" => list = true, "--force" => force = true, + "--images" => f_images = true, + "--volumes" => f_volumes = true, + "--containers" => f_containers = true, f if f.starts_with('-') => return Err(usage()), w => words.push(w), } } + let explicit_filter = f_images || f_volumes || f_containers; + let filter = if explicit_filter { + KindFilter { images: f_images, volumes: f_volumes, containers: f_containers } + } else { + KindFilter::ALL + }; let (given, rest) = match words.split_first() { Some((first, rest)) if !KINDS.contains(first) => (Some(*first), rest), _ => (None, &words[..]), }; let ask = match (rest, list) { - ([], false) => Ask::Everything, - ([], true) if !force => Ask::List, - ([kind, name], false) if KINDS.contains(kind) => Ask::One(kind, name), + ([], false) => Ask::Everything(filter), + ([], true) if !force => Ask::List(filter), + ([kind, name], false) if !explicit_filter && KINDS.contains(kind) => Ask::One(kind, name), _ => return Err(usage()), }; Ok((given, ask, force)) } -/// `kiri import [orbstack|desktop-linux] [--list | [--force] [image|volume|container NAME]]`: +#[cfg(windows)] +fn ensure_windows_kiri_context() { + let Some(dir) = crate::dockerctx::docker_dir() else { return }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = crate::dockerctx::find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles") + .is_some_and(|p| std::path::Path::new(&p).join(r"Docker\Docker\Docker Desktop.exe").is_file()); + let host = format!("npipe:{}", client::pipe().replace('\\', "/")); + let _ = crate::dockerctx::repair_windows_config( + &dir, + crate::dockerctx::WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ); +} + +/// `kiri import [orbstack|desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]`: /// one item, or every image, named volume and container Kiri lacks. +#[cfg_attr(not(any(target_os = "macos", windows)), allow(dead_code))] pub fn run(args: &[String]) -> io::Result<()> { - if args.iter().any(|a| a == "-h" || a == "--help") { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { println!("{USAGE}"); return Ok(()); } let args: Vec<&str> = args.iter().map(String::as_str).collect(); let (given, ask, force) = parse(&args)?; + #[cfg(windows)] + ensure_windows_kiri_context(); let source = pick(given, answers)?; + if !matches!(ask, Ask::List(_)) { + client::check_alive()?; + } if given.is_none() { println!("from {} ({source})", label(source)); } @@ -870,8 +1818,11 @@ pub fn run(args: &[String]) -> io::Result<()> { } let inv = inventory(source)?; let list = |k: &str| inv[k].as_array().cloned().unwrap_or_default(); - if ask == Ask::List { - for k in ["images", "volumes", "containers"] { + if let Ask::List(filter) = ask { + for (k, on) in [("images", filter.images), ("volumes", filter.volumes), ("containers", filter.containers)] { + if !on { + continue; + } println!("{k}:"); for v in list(k) { println!(" {}{}", v["name"].as_str().unwrap_or(""), if v["have"] == true { " (already in Kiri)" } else { "" }); @@ -879,30 +1830,66 @@ pub fn run(args: &[String]) -> io::Result<()> { } return Ok(()); } - let mut failed = 0; - let mut step = |what: &str, name: &str, r: io::Result<()>| match r { + let Ask::Everything(filter) = ask else { unreachable!() }; + let mut failures: Vec<(&str, String, String)> = Vec::new(); + let mut step = |what: &'static str, name: &str, r: io::Result<()>| match r { Ok(()) => println!("{what} {name}: done"), Err(e) => { - failed += 1; - println!("{what} {name}: {e}"); + let reason = e.to_string(); + let why = if reason.trim().is_empty() { "unknown error" } else { reason.trim() }; + println!("{what} {name}: skipped ({why})"); + failures.push((what, name.to_owned(), why.to_owned())); } }; - for v in list("images").iter().filter(|v| v["have"] != true) { - let n = v["name"].as_str().unwrap_or(""); - step("image", n, image(source, n)); - } - for v in list("volumes").iter().filter(|v| v["have"] != true && v["anonymous"] != true) { - let n = v["name"].as_str().unwrap_or(""); - step("volume", n, volume_with(source, n, force)); - } - for v in list("containers").iter().filter(|v| v["have"] != true) { - let n = v["name"].as_str().unwrap_or(""); - // Already brought as the one another joins the network of. - if !has(crate::flavor::CONTEXT.get(), "container", n) { + if filter.images { + for v in list("images").iter().filter(|v| v["have"] != true) { + let n = v["name"].as_str().unwrap_or(""); + step("image", n, image(source, n)); + } + } + if filter.volumes { + for v in list("volumes").iter().filter(|v| v["have"] != true && v["anonymous"] != true) { + let n = v["name"].as_str().unwrap_or(""); + step("volume", n, volume_with(source, n, force)); + } + } + if filter.containers { + for v in list("containers") { + let n = v["name"].as_str().unwrap_or(""); + let already_had = v["have"] == true; + let already_imported = !already_had && has(crate::flavor::CONTEXT.get(), "container", n); + if let Some(why) = container_skip_reason(already_had, already_imported) { + println!("container {n}: skipped ({why})"); + continue; + } step("container", n, container_with(source, n, force, &[])); } } - if failed > 0 { Err(io::Error::other(format!("{failed} items could not be imported"))) } else { Ok(()) } + if !failures.is_empty() { Err(io::Error::other(format_failures(&failures))) } else { Ok(()) } +} + +/// Why a container in `kiri import` is skipped without calling `container_with` (#411). +fn container_skip_reason(already_had: bool, already_imported: bool) -> Option<&'static str> { + if already_had { + Some("already in Kiri") + } else if already_imported { + Some("already imported as a network target") + } else { + None + } +} + +/// Summary returned when one or more items could not be imported, naming each +/// item and its reason so nothing is skipped silently (#411). +fn format_failures(failures: &[(&str, String, String)]) -> String { + let n = failures.len(); + let items = if n == 1 { "item" } else { "items" }; + let mut out = format!("{n} {items} could not be imported:"); + for (kind, name, reason) in failures { + let why = if reason.trim().is_empty() { "unknown error" } else { reason.trim() }; + out.push_str(&format!("\n {kind} {name}: {why}")); + } + out } #[cfg(test)] @@ -913,6 +1900,132 @@ mod tests { assert!(!super::anonymous("pgdata")); } + /// #410: what of a container's writable layer `kiri import` reads. `/etc` + /// changed because a file was added to it brings that file and `/etc`'s + /// own entry, never the rest of `/etc`; a new directory comes whole in + /// one read, unless something is mounted under it; nothing at or under a + /// mount, the engine's own files or the kernel's filesystems; every + /// directory a path is in comes too. + #[test] + fn plans_only_what_the_writable_layer_changed() { + let diff = "C /etc\nA /etc/hosts2\nC /etc/hosts\nA /app\nA /app/x\nA /app/sub\nA /app/sub/y\nA /srv\nA /srv/cache\nA /srv/keep\nA /data\n\ + C /usr\nC /usr/share\nD /usr/share/doc\nC /opt\nD /opt/again\nA /opt/again/new\nA /var/lib/x\nC /proc\nA /dev/shm/x\n\ + C /run\nA /run/tmp\nA /.dockerenv\n"; + let mounts = ["/data".to_owned(), "/srv/cache".to_owned(), "/run/tmp".to_owned()]; + let plan = super::plan_layer(&super::parse_diff(diff), &mounts); + let v = |s: &[&str]| s.iter().map(|p| (*p).to_owned()).collect::>(); + assert_eq!( + plan, + super::LayerPlan { + deleted: v(&["/opt/again", "/usr/share/doc"]), + entries: v(&["/etc", "/etc/hosts2", "/opt", "/opt/again/new", "/srv", "/srv/keep", "/usr", "/usr/share", "/var", "/var/lib", "/var/lib/x"]), + trees: v(&["/app"]), + } + ); + // Nothing changed, or only what each engine makes for itself: one + // `docker diff`, and nothing sent. + assert!(super::plan_layer(&[], &mounts).is_empty()); + assert!(super::plan_layer(&super::parse_diff("C /etc\nA /etc/hostname\nC /etc/resolv.conf\nA /data\n"), &mounts).is_empty()); + // A changed directory alone (its mode, say) is its own entry. + assert_eq!(super::plan_layer(&super::parse_diff("C /tmp\n"), &[]).entries, v(&["/tmp"])); + } + + #[test] + fn reads_docker_diff_lines() { + let got = super::parse_diff("C /etc\r\nA /etc/a b\nX /x\nA relative\nA /a/../b\nA /a//b\nA /\nD /gone\n\n"); + assert_eq!(got, [('C', "/etc".to_owned()), ('A', "/etc/a b".to_owned()), ('D', "/gone".to_owned())]); + } + + #[test] + fn finds_where_a_container_has_mounts() { + let info = serde_json::json!({ + "Mounts": [{"Type": "volume", "Destination": "/data/"}, {"Type": "bind", "Destination": "/src"}], + "HostConfig": {"Mounts": [{"Type": "tmpfs", "Target": "/cache"}, {"Target": "/src"}], "Tmpfs": {"/run/tmp": "size=1m"}}, + }); + assert_eq!(super::mount_points(&info), ["/data", "/src", "/cache", "/run/tmp"]); + } + + /// `docker cp ctr:/srv/app -` names its entries from `app`: each is + /// written under its path in the layer, a hard link's target too, a + /// symlink's target as it is; long names go in pax; owners and + /// attributes stay, but overlayfs's own; a stream cut short is an error. + #[test] + fn writes_what_docker_cp_read_under_its_path_in_the_layer() { + use std::io::Read; + let entry = |kind: u8, name: &str, link: &str, size: u64, pax: &[(&str, &str)]| { + let mut header = super::plain_header(kind, "", size, if kind == b'5' { 0o750 } else { 0o640 }); + super::put_number(&mut header[108..116], 1000); + super::put_number(&mut header[116..124], 1001); + let pax = pax.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); + super::TarEntry { header, pax, name: name.to_owned(), link: link.to_owned(), size } + }; + let long = format!("app/{}", "n".repeat(120)); + let mut src = Vec::new(); + for (e, body) in [ + (entry(b'5', "app/", "", 0, &[]), &b""[..]), + (entry(b'0', "app/f", "", 5, &[("SCHILY.xattr.trusted.overlay.redirect", "/x"), ("SCHILY.xattr.user.k", "v")]), b"hello"), + (entry(b'2', "app/l", "f", 0, &[]), b""), + (entry(b'1', "app/h", "app/f", 0, &[]), b""), + (entry(b'0', &long, "", 0, &[]), b""), + ] { + super::write_entry(&mut src, &e, &e.name.clone(), &e.link.clone()).unwrap(); + src.extend_from_slice(body); + src.resize(src.len().div_ceil(512) * 512, 0); + } + src.extend_from_slice(&[0u8; 1024]); + + let mut out = Vec::new(); + let mut r = &src[..]; + while let Some(e) = super::read_entry(&mut r).unwrap() { + super::write_renamed(&mut out, &e, "/srv/app").unwrap(); + let padded = e.size.div_ceil(512) * 512; + std::io::copy(&mut (&mut r).take(padded), &mut out).unwrap(); + } + out.extend_from_slice(&[0u8; 1024]); + + let mut r = &out[..]; + let mut got = Vec::new(); + for block in out.chunks(512).filter(|b| b.iter().any(|c| *c != 0) && (b[257..263] == *b"ustar\0")) { + let mut h: [u8; 512] = block.try_into().unwrap(); + let sum = h[148..156].to_vec(); + super::put_checksum(&mut h); + assert_eq!(sum, h[148..156], "a valid checksum"); + } + while let Some(e) = super::read_entry(&mut r).unwrap() { + let mut body = vec![0u8; (e.size.div_ceil(512) * 512) as usize]; + r.read_exact(&mut body).unwrap(); + body.truncate(e.size as usize); + let owner = (super::get_number(&e.header[108..116]), super::get_number(&e.header[116..124])); + got.push((e.name.clone(), e.link.clone(), e.pax.clone(), String::from_utf8(body).unwrap(), owner)); + } + let none: Vec<(String, String)> = Vec::new(); + let owner = (Some(1000), Some(1001)); + assert_eq!(got[0], ("srv/app/".to_owned(), String::new(), none.clone(), String::new(), owner)); + assert_eq!(got[1], ("srv/app/f".to_owned(), String::new(), vec![("SCHILY.xattr.user.k".to_owned(), "v".to_owned())], "hello".to_owned(), owner)); + assert_eq!(got[2], ("srv/app/l".to_owned(), "f".to_owned(), none.clone(), String::new(), owner)); + assert_eq!(got[3], ("srv/app/h".to_owned(), "srv/app/f".to_owned(), none.clone(), String::new(), owner)); + assert_eq!(got[4].0, format!("srv/{long}")); + assert_eq!(got.len(), 5); + + // Only what was asked for: an entry by another name is an error. + let mut sink = Vec::new(); + assert!(super::write_renamed(&mut sink, &entry(b'0', "apples", "", 0, &[]), "/srv/app").is_err()); + assert!(super::write_renamed(&mut sink, &entry(b'0', "app", "", 0, &[]), "/srv/app").is_ok()); + // Cut short, inside a header or before the archive's end. + assert!(super::read_entry(&mut &src[..300]).is_err()); + assert!(super::read_entry(&mut &src[..0]).is_err()); + } + + #[test] + fn names_whiteouts_beside_what_they_delete() { + assert_eq!(super::whiteout_name("/etc/gone"), "etc/.wh.gone"); + assert_eq!(super::whiteout_name("/gone"), ".wh.gone"); + let mut out = Vec::new(); + super::write_marker(&mut out, &format!("d/{}/.wh..wh..opq", "x".repeat(100))).unwrap(); + let e = super::read_entry(&mut &out[..]).unwrap().unwrap(); + assert_eq!((e.name, e.size, e.header[156]), (format!("d/{}/.wh..wh..opq", "x".repeat(100)), 0, b'0')); + } + // #266: a fresh machine with neither engine gets a plain answer, not // docker's "context not found"; with no source named, the first that // answers is used, and only as many engines are asked as needed. @@ -945,17 +2058,31 @@ mod tests { // everything"; the source may be left out before a kind. #[test] fn parses_what_to_import() { - use super::{Ask, parse}; - assert_eq!(parse(&[]).unwrap(), (None, Ask::Everything, false)); - assert_eq!(parse(&["orbstack"]).unwrap(), (Some("orbstack"), Ask::Everything, false)); - assert_eq!(parse(&["--list"]).unwrap(), (None, Ask::List, false)); - assert_eq!(parse(&["orbstack", "--list"]).unwrap(), (Some("orbstack"), Ask::List, false)); + use super::{Ask, KindFilter, parse}; + let all = KindFilter::ALL; + assert_eq!(parse(&[]).unwrap(), (None, Ask::Everything(all), false)); + assert_eq!(parse(&["orbstack"]).unwrap(), (Some("orbstack"), Ask::Everything(all), false)); + assert_eq!(parse(&["--list"]).unwrap(), (None, Ask::List(all), false)); + assert_eq!(parse(&["orbstack", "--list"]).unwrap(), (Some("orbstack"), Ask::List(all), false)); assert_eq!(parse(&["image", "nginx"]).unwrap(), (None, Ask::One("image", "nginx"), false)); assert_eq!(parse(&["desktop-linux", "volume", "pg"]).unwrap(), (Some("desktop-linux"), Ask::One("volume", "pg"), false)); // #345: --force copies volumes running containers use, one or all. assert_eq!(parse(&["orbstack", "volume", "pg", "--force"]).unwrap(), (Some("orbstack"), Ask::One("volume", "pg"), true)); assert_eq!(parse(&["--force", "container", "db"]).unwrap(), (None, Ask::One("container", "db"), true)); - assert_eq!(parse(&["orbstack", "--force"]).unwrap(), (Some("orbstack"), Ask::Everything, true)); + assert_eq!(parse(&["orbstack", "--force"]).unwrap(), (Some("orbstack"), Ask::Everything(all), true)); + // #984: --images, --volumes, --containers filter bulk import and --list. + assert_eq!( + parse(&["desktop-linux", "--images"]).unwrap(), + (Some("desktop-linux"), Ask::Everything(KindFilter { images: true, volumes: false, containers: false }), false) + ); + assert_eq!( + parse(&["--volumes", "--containers"]).unwrap(), + (None, Ask::Everything(KindFilter { images: false, volumes: true, containers: true }), false) + ); + assert_eq!( + parse(&["--list", "--containers"]).unwrap(), + (None, Ask::List(KindFilter { images: false, volumes: false, containers: true }), false) + ); for bad in [ &["orbstack", "image"][..], &["image"], @@ -965,21 +2092,24 @@ mod tests { &["--list", "image", "nginx"], &["image", "nginx", "--list"], &["--list", "--force"], + &["--images", "image", "nginx"], // An unknown flag must not start a full import. &["--dry-run"], &["orbstack", "-l"], ] { assert!(parse(bad).unwrap_err().to_string().starts_with("usage:"), "{bad:?}"); } - assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything, false)); + assert_eq!(parse(&["podman"]).unwrap(), (Some("podman"), Ask::Everything(all), false)); } - // Kiri's half of a volume copy runs only an image the engine pulled - // from an official repository, as its repo digests show: never one - // that only has a name like one, wherever it came from. + // Volume helpers run only an image the engine pulled from an official + // repository, as its repo digests show: never one that only has a name + // like one, wherever it came from (#506). GNU tar helpers (debian, ubuntu) + // are preferred over alpine/busybox (#485); alpine/busybox remain a + // fallback for inspection or offline use (#376). #[test] fn only_an_official_image_helps() { - use super::{official, pick_helper}; + use super::{official, pick_gnu_helper, pick_helper}; use serde_json::json; let d = format!("@sha256:{}", "ab12".repeat(16)); for good in ["busybox", "library/alpine", "docker.io/library/debian", "mirror.gcr.io/library/ubuntu", "public.ecr.aws/docker/library/busybox"] { @@ -988,8 +2118,10 @@ mod tests { let look_alikes = [ "ghcr.io/x/library/busybox", "localhost:5000/library/alpine", + "localhost:5000/debian", "localhost/x/library/busybox", "evil/alpine", + "evil/debian", "docker.io/evil/alpine", "mirror.gcr.io/evil/library/alpine", "public.ecr.aws/x/library/alpine", @@ -1003,26 +2135,160 @@ mod tests { for bad in ["busybox", "busybox:1", "busybox@sha256:abc", &format!("busybox@sha512:{}", "a".repeat(64)), &format!("busybox@sha256:{}", "A".repeat(64))] { assert!(!official(bad), "{bad}"); } - // Kiri's image list: one record per name, each with its own digests. + // Image list: one record per name, each with its own digests. let rec = |name: &str, digests: &[String]| json!({"Id": format!("sha256:{}", "c".repeat(64)), "RepoTags": [name], "RepoDigests": digests}); let records = [ // Untagged: a load or build without a name. rec(&format!("sha256:{}", "c".repeat(64)), &[]), rec("localhost/imp-x/library/busybox:9", &[]), - // Re-tagged from the official one: no digest of its own. + // Re-tagged from an official image: no digest of its own. rec("alpine:latest", &[]), - // Called busybox, its digest another repository's. + rec("debian:trixie", &[]), + // Called busybox/debian, its digest another repository's. rec("busybox:1", &[format!("evil/tools{d}")]), + rec("debian:1", &[format!("evil/debian{d}")]), // An official digest under a name of another repository. rec("evil/alpine:1", &[format!("alpine{d}")]), + rec("evil/debian:1", &[format!("debian{d}")]), rec("ghcr.io/x/library/busybox:1", &[format!("ghcr.io/x/library/busybox{d}")]), rec("mirror.gcr.io/library/alpine:latest", &[format!("mirror.gcr.io/library/alpine{d}")]), rec("busybox:latest", &[format!("busybox{d}")]), + // Official GNU tar images: preferred over alpine/busybox. + rec("mirror.gcr.io/library/debian:latest", &[format!("mirror.gcr.io/library/debian{d}")]), + rec("ubuntu:latest", &[format!("ubuntu{d}")]), ]; - assert_eq!(pick_helper(&records), Some("mirror.gcr.io/library/alpine:latest".into())); - assert_eq!(pick_helper(&records[..6]), None); - assert_eq!(pick_helper(&records[7..]), Some("busybox:latest".into())); - assert_eq!(pick_helper(&[json!({"RepoTags": null, "RepoDigests": [format!("busybox{d}")]})]), None); + assert_eq!(pick_helper(&records), Some("mirror.gcr.io/library/debian:latest".into())); + assert_eq!(pick_gnu_helper(&records), Some("mirror.gcr.io/library/debian:latest".into())); + assert_eq!(pick_helper(&records[..9]), None); + assert_eq!(pick_gnu_helper(&records[..11]), None); + // Offline fallback: alpine/busybox still work for pick_helper when no GNU tar image is present. + assert_eq!(pick_helper(&records[..11]), Some("mirror.gcr.io/library/alpine:latest".into())); + assert_eq!(pick_helper(&records[10..11]), Some("busybox:latest".into())); + assert_eq!(pick_gnu_helper(&records[12..]), Some("ubuntu:latest".into())); + assert_eq!(pick_helper(&[json!({"RepoTags": null, "RepoDigests": [format!("debian{d}")]})]), None); + } + + // #485: both ends of a volume copy carry xattrs and numeric owners when + // using GNU tar helpers, pass `--entrypoint tar` on the source, and fall + // back to plain `tar -xpf -` when an offline helper is alpine/busybox. + #[test] + fn volume_copy_keeps_xattrs() { + assert!(super::gnu_tar("debian:trixie")); + assert!(super::gnu_tar("debian")); + assert!(super::gnu_tar("mirror.gcr.io/library/ubuntu:24.04")); + assert!(super::gnu_tar("public.ecr.aws/docker/library/debian:trixie")); + assert!(super::gnu_tar("localhost:5000/debian")); + assert!(!super::gnu_tar("alpine:latest")); + assert!(!super::gnu_tar("busybox:latest")); + assert!(!super::gnu_tar("mydebian:latest")); + let args = super::volume_reader_args("desktop-linux", "kiri-import-pg", "type=volume,src=pg,dst=/from,readonly,volume-nocopy", "debian:trixie"); + let ep = args.iter().position(|a| *a == "--entrypoint").expect("missing --entrypoint"); + assert_eq!(args.get(ep + 1), Some(&"tar")); + assert_eq!(args.get(ep + 2), Some(&"debian:trixie")); + for flag in super::STORE_XATTRS { + assert!(args.contains(&flag), "missing {flag}"); + } + assert!(args.contains(&"--numeric-owner")); + assert!(args.contains(&"--network")); + assert!(args.contains(&"none")); + assert!(args.contains(&"--pull")); + assert!(args.contains(&"never")); + let gnu_script = super::restore_script(true); + assert!(gnu_script.contains("--numeric-owner"), "{gnu_script}"); + assert!(gnu_script.contains("--xattrs"), "{gnu_script}"); + assert!(gnu_script.contains("'--xattrs-include=user.*'"), "{gnu_script}"); + assert!(gnu_script.ends_with(" -xpf -"), "{gnu_script}"); + let fallback_script = super::restore_script(false); + assert!(!fallback_script.contains("--xattrs"), "{fallback_script}"); + assert!(fallback_script.ends_with("tar -xpf -"), "{fallback_script}"); + } + + // #485: `retar` passes `SCHILY.xattr.*` pax records through byte-for-byte + // (including JSON, empty and binary values) while still propagating high + // uid/gid into the ustar header. + #[cfg(not(windows))] + #[test] + fn retar_preserves_xattr_pax_records() { + let mut b = tar::Builder::new(Vec::new()); + let json_meta = br#"{"contentType":"image/png","cacheControl":"max-age=3600"}"#; + b.append_pax_extensions([ + ("SCHILY.xattr.user.test", &b"hello-xattr"[..]), + ("SCHILY.xattr.user.metadata", json_meta.as_slice()), + ("SCHILY.xattr.user.empty", &b""[..]), + ("uid", &b"3000000"[..]), + ("gid", &b"3000001"[..]), + ]) + .unwrap(); + let mut h = tar::Header::new_ustar(); + h.set_size(5); + h.set_mode(0o640); + h.set_uid(0); + h.set_gid(0); + h.set_cksum(); + b.append_data(&mut h, "obj", &b"hello"[..]).unwrap(); + // Second entry with a binary xattr value containing NUL, high bytes + // and a newline followed by `size=99` (must not spoof the entry size). + let bin_val = b"\x00\xff\nsize=99"; + b.append_pax_extensions([("SCHILY.xattr.user.bin", bin_val.as_slice()), ("uid", &b"1234"[..])]).unwrap(); + let mut h2 = tar::Header::new_ustar(); + h2.set_size(2); + h2.set_mode(0o600); + h2.set_cksum(); + b.append_data(&mut h2, "bin", &b"ok"[..]).unwrap(); + let input = b.into_inner().unwrap(); + let mut out = Vec::new(); + super::retar(input.as_slice(), &mut out, None).unwrap(); + assert_eq!(out.len(), input.len()); + // The pax blocks pass through byte-for-byte unchanged, including binary values. + assert_eq!(out[..1024], input[..1024]); + assert!(out.windows(bin_val.len()).any(|w| w == bin_val)); + let mut ar = tar::Archive::new(out.as_slice()); + let mut e = ar.entries().unwrap().next().unwrap().unwrap(); + assert_eq!(e.header().uid().unwrap(), 3_000_000); + assert_eq!(e.header().gid().unwrap(), 3_000_001); + let exts: Vec<(String, Vec)> = e + .pax_extensions() + .unwrap() + .unwrap() + .map(|r| { + let r = r.unwrap(); + (r.key().unwrap().to_owned(), r.value_bytes().to_vec()) + }) + .collect(); + assert!(exts.contains(&("SCHILY.xattr.user.test".into(), b"hello-xattr".to_vec())), "{exts:?}"); + assert!(exts.contains(&("SCHILY.xattr.user.metadata".into(), json_meta.to_vec())), "{exts:?}"); + assert!(exts.contains(&("SCHILY.xattr.user.empty".into(), Vec::new())), "{exts:?}"); + } + + // Source tar failures fail the import rather than silently importing a + // partial volume; only `--force` (`allow_file_changed`) tolerates GNU tar + // exit code 1 after a complete, valid archive. + #[cfg(not(windows))] + #[test] + fn pipe_propagates_reader_and_writer_errors() { + use std::process::Command; + let sh = |script: &str| { + let mut c = Command::new("sh"); + c.args(["-c", script]); + c + }; + let empty_tar = "dd if=/dev/zero bs=1024 count=1 2>/dev/null"; + let sink = "cat >/dev/null"; + // Clean stream, both exit 0: ok. + super::pipe_with(sh(empty_tar), sh(sink), "orbstack", false, |r, w| super::retar(r, w, None)).unwrap(); + // Source exits 1 without allow_file_changed: error. + let err = super::pipe_with(sh(&format!("{empty_tar}; echo changed >&2; exit 1")), sh(sink), "orbstack", false, |r, w| super::retar(r, w, None)).unwrap_err(); + assert!(err.to_string().contains("changed"), "{err}"); + // Source exits 1 WITH allow_file_changed and complete tar: ok. + super::pipe_with(sh(&format!("{empty_tar}; echo changed >&2; exit 1")), sh(sink), "orbstack", true, |r, w| super::retar(r, w, None)).unwrap(); + // Source exits 1 WITH allow_file_changed but truncated/empty output: error. + assert!(super::pipe_with(sh("echo boom >&2; exit 1"), sh(sink), "orbstack", true, |r, w| super::retar(r, w, None)).is_err()); + // Source exits 2 (fatal tar error) even WITH allow_file_changed: error. + let err = super::pipe_with(sh(&format!("{empty_tar}; echo fatal >&2; exit 2")), sh(sink), "orbstack", true, |r, w| super::retar(r, w, None)).unwrap_err(); + assert!(err.to_string().contains("fatal"), "{err}"); + // Writer exits non-zero: error. + let err = super::pipe_with(sh(empty_tar), sh("cat >/dev/null; echo diskfull >&2; exit 1"), "orbstack", false, |r, w| super::retar(r, w, None)).unwrap_err(); + assert!(err.to_string().contains("diskfull"), "{err}"); } // #377: an image only pinned by digest is listed by that reference. @@ -1076,7 +2342,7 @@ mod tests { "Healthcheck": {"Test": ["CMD", "true"], "Interval": 1_000_000_000_u64}, "Domainname": "lan", "StopTimeout": 5}, "HostConfig": {"NetworkMode": mode, "PortBindings": {"80/tcp": [{"HostPort": "8080"}]}, "Dns": ["1.1.1.1"], "ExtraHosts": ["h:1.2.3.4"], "Devices": [{"PathOnHost": "/dev/net/tun", "PathInContainer": "/dev/net/tun", "CgroupPermissions": "rwm"}], - "GroupAdd": ["audio"], "PidMode": "", "CapAdd": ["NET_ADMIN"], "Binds": null, "Mounts": null, "Ulimits": [{"Name": "nofile", "Soft": 1024, "Hard": 2048}]}, + "GroupAdd": ["audio"], "PidMode": "", "CgroupnsMode": "host", "CapAdd": ["NET_ADMIN"], "Binds": null, "Mounts": null, "Ulimits": [{"Name": "nofile", "Soft": 1024, "Hard": 2048}]}, "Mounts": [] }) }; @@ -1090,6 +2356,7 @@ mod tests { assert_eq!(joined["HostConfig"]["NetworkMode"], "container:vpn"); assert_eq!(joined["HostConfig"]["Devices"][0]["PathOnHost"], "/dev/net/tun"); assert_eq!(joined["HostConfig"]["GroupAdd"], json!(["audio"])); + assert_eq!(joined["HostConfig"]["CgroupnsMode"], "host"); assert_eq!(joined["HostConfig"]["CapAdd"], json!(["NET_ADMIN"])); assert_eq!(joined["Healthcheck"]["Test"], json!(["CMD", "true"])); assert_eq!(joined["Domainname"], "lan"); @@ -1315,4 +2582,434 @@ mod tests { assert_eq!(seen, [("odd size=5 name".to_owned(), 3_000_000, body), ("next".to_owned(), 0, b"abc".to_vec())]); } + // #411: Docker Desktop's `/host_mnt/` bind-mount sources map to + // `/` on macOS in both HostConfig.Binds (keeping mount options) and + // HostConfig.Mounts, while non-/host_mnt binds and edge cases stay intact. + #[test] + fn translates_docker_desktop_host_mnt_binds() { + use serde_json::json; + let info = json!({ + "Config": {"Image": "postgres:16"}, + "HostConfig": { + "Binds": [ + "/host_mnt/Users/alice/project/docker/volumes/db/data:/var/lib/postgresql/data", + "/Users/alice/project/docker/volumes/db/pooler.sql:/docker-entrypoint-initdb.d/99-pooler.sql:ro", + "/host_mnt/Users/alice/app:/app:delegated", + "/host_mnt/private/tmp/x:/tmp/x:rw,cached", + "/host_mnt/Users/alice/cfg:/cfg:ro", + "/host_mnt/Users/alice/rw:/rw:rw", + "/host_mnt/Users/alice/selinux:/selinux:z", + "/host_mnt/Users/alice/selinux2:/selinux2:Z", + "/host_mnt/Users/alice/dir..name/file:/file", + "/host_mnt//Users/alice/double:/double", + "/host_mnt:/bare", + "/host_mnt/:/bare-slash", + "/host_mnt///:/bare-slashes", + "/host_mnt/.:/bare-dot", + "/host_mnt/..:/dotdot", + "/host_mnt/../etc:/escape", + "/host_mnt/Users/../etc:/mid-dotdot", + "/host_mnt_other/Users/alice:/other", + "pgdata:/pgdata" + ], + "Mounts": [ + {"Type": "bind", "Source": "/host_mnt/Users/alice/data", "Target": "/data", "ReadOnly": true}, + {"Type": "bind", "Source": "/Users/alice/plain", "Target": "/plain"}, + {"Type": "bind", "Source": "/host_mnt", "Target": "/m-bare"}, + {"Type": "bind", "Source": "/host_mnt/", "Target": "/m-slash"}, + {"Type": "bind", "Source": "/host_mnt/.", "Target": "/m-dot"}, + {"Type": "bind", "Source": "/host_mnt/..", "Target": "/m-dotdot"}, + {"Type": "bind", "Source": "/host_mnt_other/x", "Target": "/m-other"}, + {"Type": "volume", "Source": "pgvol", "Target": "/vol"} + ] + }, + "Mounts": [] + }); + let body = super::create_body_for(&info, "bridge", json!({}), false); + assert_eq!( + body["HostConfig"]["Binds"], + json!([ + "/Users/alice/project/docker/volumes/db/data:/var/lib/postgresql/data", + "/Users/alice/project/docker/volumes/db/pooler.sql:/docker-entrypoint-initdb.d/99-pooler.sql:ro", + "/Users/alice/app:/app:delegated", + "/private/tmp/x:/tmp/x:rw,cached", + "/Users/alice/cfg:/cfg:ro", + "/Users/alice/rw:/rw:rw", + "/Users/alice/selinux:/selinux:z", + "/Users/alice/selinux2:/selinux2:Z", + "/Users/alice/dir..name/file:/file", + "/Users/alice/double:/double", + "/host_mnt:/bare", + "/host_mnt/:/bare-slash", + "/host_mnt///:/bare-slashes", + "/host_mnt/.:/bare-dot", + "/host_mnt/..:/dotdot", + "/host_mnt/../etc:/escape", + "/host_mnt/Users/../etc:/mid-dotdot", + "/host_mnt_other/Users/alice:/other", + "pgdata:/pgdata" + ]) + ); + assert_eq!( + body["HostConfig"]["Mounts"], + json!([ + {"Type": "bind", "Source": "/Users/alice/data", "Target": "/data", "ReadOnly": true}, + {"Type": "bind", "Source": "/Users/alice/plain", "Target": "/plain"}, + {"Type": "bind", "Source": "/host_mnt", "Target": "/m-bare"}, + {"Type": "bind", "Source": "/host_mnt/", "Target": "/m-slash"}, + {"Type": "bind", "Source": "/host_mnt/.", "Target": "/m-dot"}, + {"Type": "bind", "Source": "/host_mnt/..", "Target": "/m-dotdot"}, + {"Type": "bind", "Source": "/host_mnt_other/x", "Target": "/m-other"}, + {"Type": "volume", "Source": "pgvol", "Target": "/vol"} + ]) + ); + } + + // #411: Windows Docker Desktop bind sources under `/run/desktop/mnt/host//...` + // and `/host_mnt//...` translate to `:/...` so Kiri's WSL bind + // parser maps them to the active automount root; `/mnt/wsl/...`, look-alikes, + // non-drive prefixes and `..` traversals stay unchanged. + #[test] + fn translates_windows_docker_desktop_binds() { + use serde_json::json; + let info = json!({ + "Config": {"Image": "alpine"}, + "HostConfig": { + "Binds": [ + "/run/desktop/mnt/host/c/Users/alice/app:/app:ro", + "/run/desktop/mnt/host/d/work/db:/data:delegated", + "/run/desktop/mnt/host/c:/drive-root", + "/host_mnt/c/Users/alice/legacy:/legacy:rw", + "C:\\Users\\alice\\native:/native", + "/mnt/wsl/shared:/shared", + "/run/desktop/mnt/host:/bare", + "/run/desktop/mnt/host/:/bare-slash", + "/run/desktop/mnt/host/..:/dotdot", + "/run/desktop/mnt/host/c/../d/secret:/escape", + "/run/desktop/mnt/host/wsl/foo:/not-drive", + "/run/desktop/mnt/host_other/c/foo:/lookalike", + "/host_mnt/Users/alice:/non-drive-host-mnt", + "/host_mnt_other/c/foo:/host-mnt-lookalike" + ], + "Mounts": [ + {"Type": "bind", "Source": "/run/desktop/mnt/host/c/Users/alice/cfg", "Target": "/cfg", "ReadOnly": true}, + {"Type": "bind", "Source": "/host_mnt/e/files", "Target": "/files"}, + {"Type": "bind", "Source": "/run/desktop/mnt/host/c/../x", "Target": "/bad"}, + {"Type": "bind", "Source": "/mnt/wsl/shared", "Target": "/shared2"} + ] + }, + "Mounts": [] + }); + let body = super::create_body_for(&info, "bridge", json!({}), true); + assert_eq!( + body["HostConfig"]["Binds"], + json!([ + "C:/Users/alice/app:/app:ro", + "D:/work/db:/data:delegated", + "C:/:/drive-root", + "C:/Users/alice/legacy:/legacy:rw", + "C:\\Users\\alice\\native:/native", + "/mnt/wsl/shared:/shared", + "/run/desktop/mnt/host:/bare", + "/run/desktop/mnt/host/:/bare-slash", + "/run/desktop/mnt/host/..:/dotdot", + "/run/desktop/mnt/host/c/../d/secret:/escape", + "/run/desktop/mnt/host/wsl/foo:/not-drive", + "/run/desktop/mnt/host_other/c/foo:/lookalike", + "/host_mnt/Users/alice:/non-drive-host-mnt", + "/host_mnt_other/c/foo:/host-mnt-lookalike" + ]) + ); + assert_eq!( + body["HostConfig"]["Mounts"], + json!([ + {"Type": "bind", "Source": "C:/Users/alice/cfg", "Target": "/cfg", "ReadOnly": true}, + {"Type": "bind", "Source": "E:/files", "Target": "/files"}, + {"Type": "bind", "Source": "/run/desktop/mnt/host/c/../x", "Target": "/bad"}, + {"Type": "bind", "Source": "/mnt/wsl/shared", "Target": "/shared2"} + ]) + ); + } + + // #411: every container not imported has an explicit reason (never dropped + // silently or left with a blank error). + #[test] + fn reports_skip_and_failure_reasons() { + assert_eq!(super::container_skip_reason(true, false), Some("already in Kiri")); + assert_eq!(super::container_skip_reason(false, true), Some("already imported as a network target")); + assert_eq!(super::container_skip_reason(false, false), None); + assert_eq!(super::create_error(400, "bind source path does not exist"), "bind source path does not exist"); + assert_eq!(super::create_error(500, " "), "HTTP 500"); + assert_eq!( + super::format_failures(&[("container", "db".into(), "bind source path does not exist".into())]), + "1 item could not be imported:\n container db: bind source path does not exist" + ); + assert_eq!( + super::format_failures(&[ + ("container", "db".into(), "missing bind".into()), + ("container", "web".into(), "".into()), + ]), + "2 items could not be imported:\n container db: missing bind\n container web: unknown error" + ); + } + + #[test] + fn updates_pax_size_for_manifest_and_keeps_raw_pax_when_unchanged() { + let name = "ghcr.io/o/r@sha256:49dbca2bb9fc8e48bfc2cc5e039c0e867ca32012f6c739d07b8b0ad603b0d9c8"; + let manifest = br#"[{"Config":"blobs/sha256/cc","RepoTags":null,"Layers":["blobs/sha256/aa"]}]"#; + let entry = |prefix: &[u8], path: &[u8], typeflag: u8, body: &[u8]| { + let mut h = [0u8; 512]; + h[..path.len()].copy_from_slice(path); + h[345..345 + prefix.len()].copy_from_slice(prefix); + super::put_number(&mut h[100..108], 0o644); + super::put_number(&mut h[124..136], body.len() as u64); + h[156] = typeflag; + h[257..263].copy_from_slice(b"ustar\0"); + h[263..265].copy_from_slice(b"00"); + super::update_checksum(&mut h); + let mut out = Vec::new(); + super::write_small(&mut out, &h, body).unwrap(); + out + }; + let assert_valid_checksums = |tar_bytes: &[u8]| { + for block in tar_bytes.chunks_exact(512).filter(|b| b.iter().any(|c| *c != 0) && &b[257..263] == b"ustar\0") { + let mut check: [u8; 512] = block.try_into().unwrap(); + let got = check[148..156].to_vec(); + super::update_checksum(&mut check); + assert_eq!(got, check[148..156]); + } + }; + + // 1. PAX header with `size`, `mtime`, `path=./manifest.json`, and raw binary xattr: + // rewrites `size` + header size + checksum while keeping binary xattr bytes intact, + // and leaves the following `index.json` entry aligned. + let bin_xattr = b"29 SCHILY.xattr.user.bin=\x00\xff\xfe\n"; + assert_eq!(bin_xattr.len(), 29); + let mut pax = Vec::new(); + pax.extend_from_slice(&super::pax_record("mtime", "1700000000.5")); + pax.extend_from_slice(bin_xattr); + pax.extend_from_slice(&super::pax_record("path", "./manifest.json")); + pax.extend_from_slice(&super::pax_record("size", &manifest.len().to_string())); + let mut input = entry(b"", b"PaxHeader/manifest", b'x', &pax); + input.extend_from_slice(&entry(b"", b"truncated_name", b'0', manifest)); + input.extend_from_slice(&entry(b"", b"index.json", b'0', b"{}")); + input.extend_from_slice(&[0u8; 1024]); + + let mut out = Vec::new(); + super::retar(input.as_slice(), &mut out, Some(name)).unwrap(); + assert_valid_checksums(&out); + + let pax_len = super::get_number(&out[124..136]).unwrap() as usize; + let pax_payload = &out[512..512 + pax_len]; + assert!(pax_payload.windows(bin_xattr.len()).any(|w| w == bin_xattr), "raw binary xattr preserved"); + assert!(out[512 + pax_len..1024].iter().all(|b| *b == 0)); + let recs = super::pax_records(pax_payload); + let pax_size: usize = recs.iter().rfind(|(k, _)| k == "size").unwrap().1.parse().unwrap(); + let ustar_size = super::get_number(&out[1024 + 124..1024 + 136]).unwrap() as usize; + assert_eq!(pax_size, ustar_size); + assert!(pax_size > manifest.len()); + let m: serde_json::Value = serde_json::from_slice(&out[1536..1536 + pax_size]).unwrap(); + assert_eq!(m[0]["RepoTags"], serde_json::json!([name])); + let next_hdr = 1536 + pax_size.next_multiple_of(512); + assert_eq!(&out[next_hdr..next_hdr + 11], b"index.json\0"); + assert_eq!(&out[next_hdr + 512..next_hdr + 514], b"{}"); + + #[cfg(not(windows))] + { + let mut seen = Vec::new(); + for e in tar::Archive::new(out.as_slice()).entries().unwrap() { + let mut e = e.unwrap(); + let p = e.path().unwrap().to_string_lossy().into_owned(); + let mut body = Vec::new(); + std::io::Read::read_to_end(&mut e, &mut body).unwrap(); + seen.push((p, body)); + } + assert_eq!(seen.len(), 2); + assert_eq!(seen[0].0.trim_start_matches("./"), "manifest.json"); + let parsed: serde_json::Value = serde_json::from_slice(&seen[0].1).unwrap(); + assert_eq!(parsed[0]["RepoTags"], serde_json::json!([name])); + assert_eq!(seen[1], ("index.json".to_owned(), b"{}".to_vec())); + } + + // 2. PAX header WITHOUT `size` on `manifest.json` (matched via USTAR prefix `.` + `manifest.json` + // when no PAX `path` is set): raw PAX header & payload stay byte-for-byte unchanged. + let mut pax_no_size = Vec::new(); + pax_no_size.extend_from_slice(&super::pax_record("mtime", "1700000000.25")); + pax_no_size.extend_from_slice(bin_xattr); + let raw_pax_blocks = entry(b"", b"PaxHeader/manifest.json", b'x', &pax_no_size); + let mut input2 = raw_pax_blocks.clone(); + input2.extend_from_slice(&entry(b".", b"manifest.json", b'0', manifest)); + input2.extend_from_slice(&[0u8; 1024]); + let mut out2 = Vec::new(); + super::retar(input2.as_slice(), &mut out2, Some(name)).unwrap(); + assert_eq!(&out2[..raw_pax_blocks.len()], raw_pax_blocks.as_slice(), "PAX header untouched when no size record"); + let ustar_size2 = super::get_number(&out2[1024 + 124..1024 + 136]).unwrap() as usize; + let m2: serde_json::Value = serde_json::from_slice(&out2[1536..1536 + ustar_size2]).unwrap(); + assert_eq!(m2[0]["RepoTags"], serde_json::json!([name])); + + // 3. PAX `size` already matches rewritten `manifest.json` length: raw PAX bytes stay untouched. + let already = serde_json::to_vec(&serde_json::json!([{"Config":"blobs/sha256/cc","Layers":["blobs/sha256/aa"],"RepoTags":[name]}])).unwrap(); + let mut pax_same = Vec::new(); + pax_same.extend_from_slice(bin_xattr); + pax_same.extend_from_slice(&super::pax_record("size", &already.len().to_string())); + let same_pax_blocks = entry(b"", b"PaxHeader/manifest.json", b'x', &pax_same); + let mut input3 = same_pax_blocks.clone(); + input3.extend_from_slice(&entry(b"", b"manifest.json", b'0', &already)); + input3.extend_from_slice(&[0u8; 1024]); + let mut out3 = Vec::new(); + super::retar(input3.as_slice(), &mut out3, Some(name)).unwrap(); + assert_eq!(&out3[..same_pax_blocks.len()], same_pax_blocks.as_slice(), "PAX header untouched when size unchanged"); + } + + #[test] + fn pax_rfind_precedence_and_consecutive_x_headers() { + let name = "ghcr.io/o/r@sha256:49dbca2bb9fc8e48bfc2cc5e039c0e867ca32012f6c739d07b8b0ad603b0d9c8"; + let manifest = br#"[{"Config":"blobs/sha256/cc","RepoTags":null,"Layers":["blobs/sha256/aa"]}]"#; + let entry = |path: &[u8], typeflag: u8, size_override: Option, body: &[u8]| { + let mut h = [0u8; 512]; + h[..path.len()].copy_from_slice(path); + super::put_number(&mut h[100..108], 0o644); + super::put_number(&mut h[124..136], size_override.unwrap_or(body.len() as u64)); + h[156] = typeflag; + h[257..263].copy_from_slice(b"ustar\0"); + h[263..265].copy_from_slice(b"00"); + super::update_checksum(&mut h); + let mut out = Vec::new(); + super::write_small(&mut out, &h, body).unwrap(); + out + }; + + // 1. Duplicate keys in one PAX header: last `size`, `uid`, `gid`, and `path` win (`rfind`). + let mut dup_pax = Vec::new(); + dup_pax.extend_from_slice(&super::pax_record("size", "99999")); + dup_pax.extend_from_slice(&super::pax_record("size", "5")); + dup_pax.extend_from_slice(&super::pax_record("uid", "111")); + dup_pax.extend_from_slice(&super::pax_record("uid", "3000000")); + dup_pax.extend_from_slice(&super::pax_record("gid", "222")); + dup_pax.extend_from_slice(&super::pax_record("gid", "3000001")); + dup_pax.extend_from_slice(&super::pax_record("path", "manifest.json")); + dup_pax.extend_from_slice(&super::pax_record("path", "sub/manifest.json")); + let mut input = entry(b"manifest.json", b'x', None, &dup_pax); + // Even though USTAR says `manifest.json` and the first PAX `path` said `manifest.json`, + // the last PAX `path` is `sub/manifest.json`, so `retar` must NOT parse `hello` as JSON. + input.extend_from_slice(&entry(b"manifest.json", b'0', Some(0), b"hello")); + input.extend_from_slice(&[0u8; 1024]); + let mut out = Vec::new(); + super::retar(input.as_slice(), &mut out, Some(name)).unwrap(); + let file_hdr = &out[1024..1536]; + assert_eq!(super::get_number(&file_hdr[124..136]), Some(5)); + assert_eq!(super::get_number(&file_hdr[108..116]), Some(3_000_000)); + assert_eq!(super::get_number(&file_hdr[116..124]), Some(3_000_001)); + assert_eq!(&out[1536..1541], b"hello"); + + // 2. Consecutive `'x'` headers before `manifest.json`, plus trailing `'x'` before EOF: + // first `'x'` carries `path` + `size` + `uid=100`, second `'x'` overrides `uid=3000002` + // and has no `size` of its own; both `'x'` headers are emitted and the second gets the + // updated `size` so downstream PAX readers see the rewritten manifest length. + let mut pax1 = Vec::new(); + pax1.extend_from_slice(&super::pax_record("path", "other.txt")); + pax1.extend_from_slice(&super::pax_record("path", "manifest.json")); + pax1.extend_from_slice(&super::pax_record("uid", "100")); + pax1.extend_from_slice(&super::pax_record("gid", "3000005")); + pax1.extend_from_slice(&super::pax_record("size", &manifest.len().to_string())); + let mut pax2 = Vec::new(); + pax2.extend_from_slice(&super::pax_record("uid", "3000002")); + pax2.extend_from_slice(&super::pax_record("mtime", "1700000001")); + let orphan_pax = super::pax_record("comment", "trailing-before-eof"); + + let x1 = entry(b"PaxHeader/1", b'x', None, &pax1); + let x2 = entry(b"PaxHeader/2", b'x', None, &pax2); + let x_eof = entry(b"PaxHeader/eof", b'x', None, &orphan_pax); + let mut input2 = Vec::new(); + input2.extend_from_slice(&x1); + input2.extend_from_slice(&x2); + input2.extend_from_slice(&entry(b"ignored", b'0', Some(0), manifest)); + input2.extend_from_slice(&x_eof); + input2.extend_from_slice(&[0u8; 1024]); + + let mut out2 = Vec::new(); + super::retar(input2.as_slice(), &mut out2, Some(name)).unwrap(); + // First `'x'` flushed intact at offset 0. + assert_eq!(&out2[..1024], x1.as_slice()); + // Second `'x'` at offset 1024 carries the updated `size` overriding `x1`. + let pax2_len = super::get_number(&out2[1024 + 124..1024 + 136]).unwrap() as usize; + let recs2 = super::pax_records(&out2[1536..1536 + pax2_len]); + let updated_size: usize = recs2.iter().rfind(|(k, _)| k == "size").unwrap().1.parse().unwrap(); + // Manifest USTAR header at offset 2048 has overridden uid from `x2`, gid from `x1`, and updated size. + let mh = &out2[2048..2560]; + assert_eq!(super::get_number(&mh[108..116]), Some(3_000_002)); + assert_eq!(super::get_number(&mh[116..124]), Some(3_000_005)); + assert_eq!(super::get_number(&mh[124..136]), Some(updated_size as u64)); + let m: serde_json::Value = serde_json::from_slice(&out2[2560..2560 + updated_size]).unwrap(); + assert_eq!(m[0]["RepoTags"], serde_json::json!([name])); + // Orphan `'x'` before EOF is flushed intact right before the 1024-byte zero trailer. + let orphan_off = 2560 + updated_size.next_multiple_of(512); + assert_eq!(&out2[orphan_off..orphan_off + 1024], x_eof.as_slice()); + assert_eq!(&out2[orphan_off + 1024..], &[0u8; 1024]); + + // Also verify `read_entry` resolves consecutive `'x'` headers + rewritten `size` cleanly. + let mut reader = out2.as_slice(); + let e = super::read_entry(&mut reader).unwrap().unwrap(); + assert_eq!(e.name, "manifest.json"); + assert_eq!(e.size, updated_size as u64); + } + + #[test] + fn rejects_malformed_base256_and_overflow_tar_headers() { + assert_eq!(super::get_number(&[]), None); + assert_eq!(super::get_number(&[0x80, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), Some(u64::MAX)); + assert_eq!(super::get_number(&[0x80, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00]), Some(u64::MAX - 511)); + for bad_num in [ + [0xff; 12], + [0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0x81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], + [0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [0x80, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0], + [0x80, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + ] { + assert_eq!(super::get_number(&bad_num), None, "{bad_num:?}"); + } + + // Damaged / overflowing base-256 sizes on both `'0'` and `'x'` headers fail cleanly + // without wrapping `padded` to 0. + for typeflag in [b'0', b'x'] { + for bad in [ + // u64::MAX and u64::MAX - 510: valid u64, overflows `checked_next_multiple_of(512)` + [0x80, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], + [0x80, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x01], + // Negative base-256 (`field[0] != 0x80`) + [0xff; 12], + [0x81, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + // >64-bit positive base-256 + [0x80, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0], + ] { + let mut raw = vec![0u8; 1536]; + raw[..4].copy_from_slice(b"bad\0"); + raw[124..136].copy_from_slice(&bad); + raw[156] = typeflag; + raw[257..263].copy_from_slice(b"ustar\0"); + raw[263..265].copy_from_slice(b"00"); + super::update_checksum(raw[..512].as_mut().try_into().unwrap()); + let err = super::retar(raw.as_slice(), &mut Vec::new(), None).unwrap_err(); + assert_eq!(err.kind(), std::io::ErrorKind::InvalidData, "{typeflag:?} {bad:?}: {err}"); + let mut r = raw.as_slice(); + assert!(super::read_entry(&mut r).is_err(), "read_entry {typeflag:?} {bad:?}"); + } + } + + // Overflowing size supplied via a PAX `size` record (`u64::MAX`) is also rejected. + let pax_overflow = super::pax_record("size", &u64::MAX.to_string()); + let mut px_h = super::plain_header(b'x', "PaxHeader/overflow", pax_overflow.len() as u64, 0o644); + super::update_checksum(&mut px_h); + let mut f_h = super::plain_header(b'0', "overflow.bin", 0, 0o644); + super::update_checksum(&mut f_h); + let mut stream = Vec::new(); + super::write_small(&mut stream, &px_h, &pax_overflow).unwrap(); + stream.extend_from_slice(&f_h); + stream.extend_from_slice(&[0u8; 1024]); + assert_eq!(super::retar(stream.as_slice(), &mut Vec::new(), None).unwrap_err().kind(), std::io::ErrorKind::InvalidData); + let mut sr = stream.as_slice(); + assert!(super::read_entry(&mut sr).is_err()); + } + } diff --git a/crates/kiri/src/k8s.rs b/crates/kiri/src/k8s.rs index 6c7684ad1..7f1eef43a 100644 --- a/crates/kiri/src/k8s.rs +++ b/crates/kiri/src/k8s.rs @@ -14,6 +14,8 @@ use crate::client; use crate::flavor::CONTEXT; const IMAGE: (&str, &str) = ("rancher/k3s", "v1.37.1-k3s1"); +/// Default k3s image tag shown in Settings → Kubernetes. +pub(crate) const DEFAULT_VERSION: &str = IMAGE.1; /// The node container; the window reads the cluster through it. pub(crate) const NAME: &str = "kiri-k8s"; const VOLUME: &str = "kiri-k8s"; @@ -24,10 +26,12 @@ fn home() -> io::Result { /// The cluster's settings, in `~/.kiri/k8s.json`: whether its API server /// (and, through the daemon, its LoadBalancer services) answers on every -/// interface rather than 127.0.0.1, and extra names for its certificate. -/// They are applied when the node container is created, so `kiri k8s set` -/// recreates it; the cluster's state is in the volume and stays. -#[derive(Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +/// interface rather than 127.0.0.1, extra names for its certificate, its API +/// server port, an optional custom k3s image tag, and optional extra arguments +/// passed to `k3s server`. They are applied when the node container is +/// created, so `kiri k8s set` recreates it; the cluster's state is in the +/// volume and stays. +#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub(crate) struct Config { #[serde(default)] pub lan: bool, @@ -37,17 +41,40 @@ pub(crate) struct Config { /// taken the node takes the next free one; `port` in its container says which. #[serde(default, skip_serializing_if = "Option::is_none")] pub port: Option, + /// Custom k3s image tag (`rancher/k3s:`), or `None` for `IMAGE.1`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub version: Option, + /// Extra arguments appended to `k3s server`. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub k3s_args: Vec, } /// The API server's port in the node, and the Mac port it is published on by default. pub(crate) const API_PORT: u16 = 6443; /// How many ports after the asked-for one a start tries before giving up. const PORT_TRIES: u16 = 20; +/// Maximum byte length of a single custom `--k3s-arg` value. +const MAX_K3S_ARG_LEN: usize = 512; +/// Maximum number of custom `--k3s-arg` values. +const MAX_K3S_ARGS: usize = 64; +/// Maximum size in bytes of an auto-deployed manifest in `~/.kiri/k8s-manifests`. +const MAX_MANIFEST_BYTES: u64 = 4 << 20; + +const USAGE_SET: &str = "usage: kiri k8s set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]"; +const USAGE_K8S: &str = "usage: kiri k8s start [--use] | stop | status [--json] | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]"; impl Config { pub(crate) fn api_port(&self) -> u16 { self.port.unwrap_or(API_PORT) } + + pub(crate) fn version_tag(&self) -> &str { + self.version.as_deref().filter(|v| valid_version(v)).unwrap_or(IMAGE.1) + } + + pub(crate) fn image(&self) -> String { + format!("{}:{}", IMAGE.0, self.version_tag()) + } } /// The label that keeps the Mac port a node was made with, for while it's stopped. @@ -90,8 +117,47 @@ fn config_path() -> io::Result { Ok(home()?.join(crate::flavor::STATE.get()).join("k8s.json")) } +pub(crate) fn manifests_dir() -> io::Result { + Ok(home()?.join(crate::flavor::STATE.get()).join("k8s-manifests")) +} + +fn load_config_from(path: &std::path::Path) -> Config { + std::fs::read(path).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() +} + +/// The settings `kiri k8s set` changes and saves back. Only a missing file is +/// the defaults: one that can't be read or parsed is an error, not replaced. +fn load_config_for_edit(path: &std::path::Path) -> io::Result { + let bytes = match std::fs::read(path) { + Ok(b) => b, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Config::default()), + Err(e) => { + return Err(io::Error::new( + e.kind(), + format!("cannot read {}: {e}", path.display()), + )); + } + }; + serde_json::from_slice(&bytes).map_err(|e| { + io::Error::new( + io::ErrorKind::InvalidData, + format!( + "{} is not valid Kubernetes settings ({e}); fix or remove it", + path.display() + ), + ) + }) +} + +fn save_config_to(path: &std::path::Path, cfg: &Config) -> io::Result<()> { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + std::fs::write(path, serde_json::to_vec(cfg).map_err(io::Error::other)?) +} + pub(crate) 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() + config_path().ok().map(|p| load_config_from(&p)).unwrap_or_default() } /// An extra certificate name: an IP address or a DNS name (`*.` allowed). @@ -102,45 +168,254 @@ fn valid_san(name: &str) -> bool { && name.trim_start_matches("*.").split('.').all(|l| !l.is_empty() && l.len() <= 63 && !l.starts_with('-') && l.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-'))) } -/// `kiri k8s set [--lan on|off] [--tls-san a,b] [--port N]`: saves the settings and, if -/// the cluster exists and they changed, recreates its node with them. -fn set(args: &[String]) -> io::Result<()> { - let mut cfg = config(); - let before = (cfg.lan, cfg.tls_san.clone(), cfg.api_port()); +/// A k3s image tag for `rancher/k3s:`: 1..=128 ASCII letters, digits, +/// `.`, `_` or `-`, starting with a letter or digit, with no `..`, spaces, +/// slashes, `@`, `:`, or control characters. +pub(crate) fn valid_version(tag: &str) -> bool { + !tag.is_empty() + && tag.len() <= 128 + && !tag.eq_ignore_ascii_case("default") + && !tag.contains("..") + && tag.as_bytes()[0].is_ascii_alphanumeric() + && tag.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) +} + +/// An extra argument for `k3s server`: non-empty, bounded length, and free of +/// NUL or control characters. +pub(crate) fn valid_k3s_arg(arg: &str) -> bool { + !arg.trim().is_empty() + && arg.len() <= MAX_K3S_ARG_LEN + && !arg.bytes().any(|b| b < 0x20 || b == 0x7f) + && !arg.chars().any(char::is_control) +} + +/// Applies `kiri k8s set` CLI flags to `cfg` without mutating `cfg` on error. +pub(crate) fn apply_set_args(cfg: &mut Config, args: &[String]) -> io::Result<()> { + let mut next = cfg.clone(); + let mut custom_args: Option> = None; let mut it = args.iter(); while let Some(a) = it.next() { - match a.as_str() { - "--lan" => cfg.lan = matches!(it.next().map(String::as_str), Some("on" | "true" | "1")), - "--tls-san" => { - let list: Vec = it.next().map(String::as_str).unwrap_or("").split(',').map(|n| n.trim().to_owned()).filter(|n| !n.is_empty()).collect(); - if let Some(bad) = list.iter().find(|n| !valid_san(n)) { - return Err(io::Error::other(format!("not an IP address or domain name: {bad}"))); - } - cfg.tls_san = list; + let s = a.as_str(); + if s == "--lan" || s.starts_with("--lan=") { + let Some(raw) = s.strip_prefix("--lan=").or_else(|| it.next().map(String::as_str)) else { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE_SET)); + }; + next.lan = matches!(raw, "on" | "true" | "1"); + } else if s == "--tls-san" || s.starts_with("--tls-san=") { + let raw = s.strip_prefix("--tls-san=").or_else(|| it.next().map(String::as_str)).unwrap_or(""); + let list: Vec = raw.split(',').map(|n| n.trim().to_owned()).filter(|n| !n.is_empty()).collect(); + if let Some(bad) = list.iter().find(|n| !valid_san(n)) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("not an IP address or domain name: {bad}"))); + } + next.tls_san = list; + } else if s == "--port" || s.starts_with("--port=") { + let raw = s.strip_prefix("--port=").or_else(|| it.next().map(String::as_str)).unwrap_or(""); + let Some(port) = valid_port(raw) else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("the API server port must be a number from 1024 to 65535, not `{raw}`"), + )); + }; + next.port = (port != API_PORT).then_some(port); + } else if s == "--version" || s.starts_with("--version=") { + let Some(raw) = s.strip_prefix("--version=").or_else(|| it.next().map(String::as_str)) else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "--version requires a k3s image tag (for example `v1.31.4-k3s1`, or `default` to reset)", + )); + }; + if raw.is_empty() || raw.eq_ignore_ascii_case("default") { + next.version = None; + } else if valid_version(raw) { + next.version = Some(raw.to_owned()); + } else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("invalid k3s version tag `{raw}`: expected a clean image tag such as `v1.31.4-k3s1`, or `default`"), + )); + } + } else if s == "--k3s-arg" || s.starts_with("--k3s-arg=") { + let Some(raw) = s.strip_prefix("--k3s-arg=").or_else(|| it.next().map(String::as_str)) else { + return Err(io::Error::new(io::ErrorKind::InvalidInput, "--k3s-arg requires a k3s server argument")); + }; + if !valid_k3s_arg(raw) { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("invalid --k3s-arg `{raw}`: arguments must be non-empty, free of control characters, and at most {MAX_K3S_ARG_LEN} bytes"), + )); } - "--port" => { - let raw = it.next().map(String::as_str).unwrap_or(""); - let Some(port) = valid_port(raw) else { - return Err(io::Error::other(format!("the API server port must be a number from 1024 to 65535, not `{raw}`"))); - }; - cfg.port = (port != API_PORT).then_some(port); + let list = custom_args.get_or_insert_with(Vec::new); + if list.len() >= MAX_K3S_ARGS { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("too many --k3s-arg values (at most {MAX_K3S_ARGS})"), + )); } - _ => return Err(io::Error::other("usage: kiri k8s set [--lan on|off] [--tls-san NAME,…] [--port N]")), + list.push(raw.to_owned()); + } else if s == "--clear-k3s-args" { + custom_args = Some(Vec::new()); + } else { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE_SET)); } } + if let Some(args) = custom_args { + next.k3s_args = args; + } + *cfg = next; + Ok(()) +} + +/// Extra kubelet `root-dir` flag passed on Linux ZFS hosts (#607) so kubelet +/// (`nodefs`) lives inside the loopback-ext4 `/var/lib/rancher/k3s` volume +/// alongside containerd (`imagefs`) rather than on the ZFS container rootfs. +pub(crate) const ZFS_KUBELET_ROOT_ARG: &str = "--kubelet-arg=root-dir=/var/lib/rancher/k3s/kubelet"; + +/// Label recorded on the `kiri-k8s` volume when backed by a loopback ext4 image on ZFS. +const ZFS_BACKING_LABEL: &str = "dev.kiri.k8s.backing"; + +/// Maximum trailing container log lines included when `kiri-k8s` exits during startup. +const CRASH_LOG_LINES: usize = 15; + +/// Whether custom `k3s_args` already specify kubelet's `root-dir`. +pub(crate) fn has_kubelet_root_dir(args: &[String]) -> bool { + args.iter().filter(|a| valid_k3s_arg(a)).any(|a| { + let s = a.trim(); + s.contains("root-dir=") + || s == "root-dir" + || s == "--root-dir" + || s.ends_with("=root-dir") + || s.ends_with("=--root-dir") + }) +} + +/// Reads `KiriStorageZfs` from a daemon `/info` response. +pub(crate) fn storage_zfs_from_info(info: &serde_json::Value) -> Option { + info["KiriStorageZfs"].as_bool() +} + +/// Whether the running daemon's volumes directory sits on ZFS (#607). +fn daemon_storage_zfs() -> bool { + client::get("/info") + .ok() + .and_then(|info| storage_zfs_from_info(&info)) + .unwrap_or_else(|| crate::daemon::rofs::is_daemon_storage_zfs(None)) +} + +/// Builds the `k3s server` command vector for the node container. +#[cfg(test)] +pub(crate) fn server_cmd(cfg: &Config) -> Vec { + server_cmd_for(cfg, false) +} + +/// Builds the `k3s server` command vector, adding `--kubelet-arg=root-dir=…` +/// on Linux ZFS hosts (#607) unless custom `k3s_args` already configure `root-dir`. +pub(crate) fn server_cmd_for(cfg: &Config, zfs: bool) -> Vec { + let mut cmd: Vec = [ + "server", + "--disable", + "traefik", + "--tls-san", + "127.0.0.1", + "--tls-san", + "localhost", + "--write-kubeconfig-mode", + "644", + ] + .map(String::from) + .to_vec(); + for name in cfg.tls_san.iter().filter(|n| valid_san(n)) { + cmd.extend(["--tls-san".to_owned(), name.clone()]); + } + if zfs && !has_kubelet_root_dir(&cfg.k3s_args) { + cmd.push(ZFS_KUBELET_ROOT_ARG.to_owned()); + } + for arg in cfg.k3s_args.iter().filter(|a| valid_k3s_arg(a)) { + cmd.push(arg.clone()); + } + cmd +} + +/// Formats the cluster's saved settings line printed by `kiri k8s set`. +pub(crate) fn format_settings(cfg: &Config) -> String { + let port = cfg.api_port(); + let host = if cfg.lan { "every interface" } else { "127.0.0.1" }; + let san = if cfg.tls_san.is_empty() { "none".to_owned() } else { cfg.tls_san.join(", ") }; + let version = match cfg.version.as_deref().filter(|v| valid_version(v)) { + Some(v) => format!("{v} (custom)"), + None => format!("{} (default)", IMAGE.1), + }; + let args = if cfg.k3s_args.is_empty() { "none".to_owned() } else { cfg.k3s_args.join(" ") }; + format!("API server on {host}:{port}; extra certificate names: {san}; k3s version: {version}; extra k3s args: {args}") +} + +/// Formats the status summary line printed by `kiri k8s status`. +pub(crate) fn format_status(info: Option<&serde_json::Value>, cfg: &Config) -> String { + let Some(info) = info else { + let mut out = format!("Kubernetes: not created (kiri k8s start), k3s {}", cfg.version_tag()); + if !cfg.k3s_args.is_empty() { + out.push_str(&format!(", k3s args: {}", cfg.k3s_args.join(" "))); + } + return out; + }; + let state = info["State"]["Status"].as_str().unwrap_or("unknown"); + let port = bound_port(info).unwrap_or(API_PORT); + let want = cfg.api_port(); + let moved = if port != want { format!(" ({want} was in use)") } else { String::new() }; + let version = node_version(info, cfg); + let mut out = format!("Kubernetes: {state}, k3s {version}, API on 127.0.0.1:{port}{moved}"); + if !cfg.k3s_args.is_empty() { + out.push_str(&format!(", k3s args: {}", cfg.k3s_args.join(" "))); + } + out +} + +/// The k3s a running node runs (its image's tag), else the one a start runs. +fn node_version<'a>(info: &'a serde_json::Value, cfg: &'a Config) -> &'a str { + if info["State"]["Status"] == "running" { + info["Config"]["Image"].as_str().and_then(|img| img.split_once(':').map(|(_, tag)| tag)).unwrap_or_else(|| cfg.version_tag()) + } else { + cfg.version_tag() + } +} + +/// `kiri k8s status --json`: what `format_status` says, as one object. A +/// cluster not created has `state` null and no `port` yet. +pub(crate) fn status_json(info: Option<&serde_json::Value>, cfg: &Config) -> serde_json::Value { + serde_json::json!({ + "state": info.map(|i| i["State"]["Status"].as_str().unwrap_or("unknown")), + "version": info.map_or_else(|| cfg.version_tag(), |i| node_version(i, cfg)), + "port": info.map(|i| bound_port(i).unwrap_or(API_PORT)), + "requested_port": cfg.api_port(), + "lan": cfg.lan, + "tls_san": cfg.tls_san, + "k3s_args": cfg.k3s_args, + "context": CONTEXT.get(), + }) +} + +/// `kiri k8s set [--lan on|off] [--tls-san a,b] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]`: +/// saves the settings and, if the cluster exists and they changed, recreates its node with them. +fn set(args: &[String]) -> io::Result<()> { + let path = config_path()?; + let mut cfg = load_config_for_edit(&path)?; + let before = cfg.clone(); + apply_set_args(&mut cfg, args)?; ensure_daemon()?; let node = if exists()? { Some(client::get(&format!("/containers/{NAME}/json"))?) } else { None }; // A port asked for that the node doesn't already hold must be free now. let port = cfg.api_port(); - if port != before.2 && node.as_ref().and_then(bound_port) != Some(port) && !port_free(port, cfg.lan) { + if port != before.api_port() && node.as_ref().and_then(bound_port) != Some(port) && !port_free(port, cfg.lan) { return Err(io::Error::other(format!("port {port} is in use on this Mac; choose another"))); } - let path = config_path()?; - std::fs::create_dir_all(path.parent().expect("has a parent"))?; - std::fs::write(&path, serde_json::to_vec(&cfg).map_err(io::Error::other)?)?; - println!("API server on {}:{port}; extra certificate names: {}", if cfg.lan { "every interface" } else { "127.0.0.1" }, if cfg.tls_san.is_empty() { "none".to_owned() } else { cfg.tls_san.join(", ") }); - let Some(node) = node else { return Ok(()) }; - if (cfg.lan, cfg.tls_san.clone(), port) == before { + save_config_to(&path, &cfg)?; + println!("{}", format_settings(&cfg)); + let Some(node) = node else { + if cfg != before { + println!("they apply when the cluster next starts"); + } + return Ok(()); + }; + if cfg == before { return Ok(()); } if node["State"]["Running"] != true { @@ -159,8 +434,19 @@ const CONFIG_LABEL: &str = "dev.kiri.k8s.config"; /// 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. +#[cfg(test)] fn made_with(cfg: &Config) -> String { - serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), host_folders())).unwrap_or_default() + made_with_for(cfg, false) +} + +fn made_with_for(cfg: &Config, zfs: bool) -> String { + if !zfs && cfg.version.is_none() && cfg.k3s_args.is_empty() { + serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), host_folders())).unwrap_or_default() + } else if !zfs { + serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), host_folders(), cfg.version_tag(), &cfg.k3s_args)).unwrap_or_default() + } else { + serde_json::to_string(&(cfg.lan, &cfg.tls_san, cfg.api_port(), host_folders(), cfg.version_tag(), &cfg.k3s_args, "zfs-ext4")).unwrap_or_default() + } } /// The folders of this computer the node sees at their own paths, so a pod's @@ -175,8 +461,33 @@ fn host_folders() -> Vec<&'static str> { } /// The node's binds: its state, then the host folders. +#[cfg(test)] fn binds() -> Vec { - std::iter::once(format!("{VOLUME}:/var/lib/rancher/k3s")).chain(host_folders().into_iter().map(|d| format!("{d}:{d}"))).collect() + binds_for(false) +} + +/// The node's binds for the active storage backend: on ZFS, `:nocopy` skips +/// cloning the container rootfs for initial volume copy-up while `kiri-init` +/// loop-mounts the sparse `ext4.img` onto `/var/lib/kiri/volumes/kiri-k8s/_data`. +pub(crate) fn binds_for(zfs: bool) -> Vec { + let vol_bind = if zfs { + format!("{VOLUME}:/var/lib/rancher/k3s:nocopy") + } else { + format!("{VOLUME}:/var/lib/rancher/k3s") + }; + std::iter::once(vol_bind).chain(host_folders().into_iter().map(|d| format!("{d}:{d}"))).collect() +} + +/// `POST /volumes/create` body for the `kiri-k8s` volume: keeps `DriverOpts` +/// empty so `kiri-init`'s `volmount::ensure_k8s_ext4` backs `_data` with a +/// sparse loopback `ext4` image when `/var/lib/kiri/volumes` sits on ZFS (#607). +pub(crate) fn volume_create_body(zfs: bool) -> serde_json::Value { + let labels = if zfs { + json!({"dev.kiri.k8s": "1", ZFS_BACKING_LABEL: "ext4-loop"}) + } else { + json!({"dev.kiri.k8s": "1"}) + }; + json!({"Name": VOLUME, "Driver": "local", "Labels": labels}) } fn ensure_daemon() -> io::Result<()> { @@ -193,7 +504,15 @@ fn ok(r: io::Result) -> io::Result { pub fn run(args: &[String]) -> io::Result<()> { let what = args.first().map(String::as_str).unwrap_or(""); + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) || what == "help" { + println!("{}", if what == "set" { USAGE_SET } else { USAGE_K8S }); + return Ok(()); + } let logged = matches!(what, "start" | "stop" | "delete" | "set"); + // A recreate from the command line (`kiri k8s set`) is attributed to this + // op, so the node's stop is logged as `k8s set`, not as a memory kill. A + // child the window started already has its own op (KIRI_OP). + let _op = (logged && crate::diag::op().is_none()).then(|| crate::diag::enter_op(crate::diag::new_op(&format!("k8s{what}")))); if logged { crate::diag::info!(format!("Kubernetes {what}")); } @@ -219,10 +538,10 @@ fn run_inner(args: &[String]) -> io::Result<()> { println!("Kubernetes stopped (its state is kept; `kiri k8s start` resumes it)"); Ok(()) } - Some("status") => status(), + Some("status") => status(flag("--json")), Some("delete") => delete(), Some("set") => set(&args[1..]), - _ => Err(io::Error::other("usage: kiri k8s start [--use] | stop | status | delete | set [--lan on|off] [--tls-san NAME,…] [--port N]")), + _ => Err(io::Error::other(USAGE_K8S)), } } @@ -230,26 +549,168 @@ fn exists() -> io::Result { Ok(client::request("GET", &format!("/containers/{NAME}/json"), None)?.ok()) } +/// Returns `Some(exit_code)` when `/containers/kiri-k8s/json` shows that the +/// node container is no longer running (`State.Running == false` / +/// `State.Status == "exited"`) or has already crashed and been restarted by its +/// `unless-stopped` policy (`RestartCount > initial_restarts`). +pub(crate) fn node_exit_code(info: &serde_json::Value, initial_restarts: Option) -> Option { + let state = &info["State"]; + let exit_code = state["ExitCode"].as_i64().unwrap_or(1); + let running = state["Running"].as_bool(); + let status = state["Status"].as_str(); + if running == Some(false) || matches!(status, Some("exited" | "dead" | "created")) { + return Some(exit_code); + } + if let (Some(base), Some(cur)) = (initial_restarts, info["RestartCount"].as_u64()) + && cur > base + { + return Some(exit_code); + } + None +} + +/// Extracts the last `keep` non-empty lines from `/containers/{id}/logs` output, +/// stripping Docker's 8-byte multiplexed stream headers when `!tty`. +pub(crate) fn decode_log_lines(body: &[u8], tty: bool, keep: usize) -> Vec { + let mut text = Vec::with_capacity(body.len()); + if tty { + text.extend_from_slice(body); + } else { + let mut rest = body; + while !rest.is_empty() { + if rest.len() >= 8 && rest[0] <= 2 && rest[1..4] == [0, 0, 0] { + let len = u32::from_be_bytes([rest[4], rest[5], rest[6], rest[7]]) as usize; + let end = (8 + len).min(rest.len()); + text.extend_from_slice(&rest[8..end]); + rest = &rest[end..]; + } else { + text.extend_from_slice(rest); + break; + } + } + } + let decoded = String::from_utf8_lossy(&text); + let all: Vec = decoded + .split('\n') + .map(|l| l.trim_end_matches('\r').to_owned()) + .filter(|l| !l.trim().is_empty()) + .collect(); + all[all.len().saturating_sub(keep)..].to_vec() +} + +/// Formats an immediate startup crash error with the exit code and last log lines. +pub(crate) fn format_node_crash_error(exit_code: i64, log_lines: &[String]) -> String { + let base = format!( + "the node ({NAME}) exited before becoming ready (exit code {exit_code}); see `docker --context {CONTEXT} logs {NAME}`" + ); + if log_lines.is_empty() { + base + } else { + format!("{base}:\n {}", log_lines.join("\n ")) + } +} + +/// Polls until `check_kubectl_ready` succeeds, failing fast with the container's +/// last log lines if `inspect` reports that `kiri-k8s` exited or crash-looped. +pub(crate) fn wait_for_ready_with( + initial_restarts: Option, + timeout: Duration, + poll_interval: Duration, + mut inspect: impl FnMut() -> io::Result, + mut check_kubectl_ready: impl FnMut() -> bool, + mut fetch_tail_logs: impl FnMut(bool) -> Vec, + mut on_crash: impl FnMut(), +) -> io::Result<()> { + let deadline = Instant::now() + timeout; + let mut base_restarts = initial_restarts; + loop { + if let Ok(info) = inspect() { + let base = *base_restarts.get_or_insert_with(|| info["RestartCount"].as_u64().unwrap_or(0)); + if let Some(code) = node_exit_code(&info, Some(base)) { + let tty = info["Config"]["Tty"].as_bool().unwrap_or(false); + let lines = fetch_tail_logs(tty); + on_crash(); + return Err(io::Error::other(format_node_crash_error(code, &lines))); + } + } + if check_kubectl_ready() { + return Ok(()); + } + if let Ok(info) = inspect() { + let base = *base_restarts.get_or_insert_with(|| info["RestartCount"].as_u64().unwrap_or(0)); + if let Some(code) = node_exit_code(&info, Some(base)) { + let tty = info["Config"]["Tty"].as_bool().unwrap_or(false); + let lines = fetch_tail_logs(tty); + on_crash(); + return Err(io::Error::other(format_node_crash_error(code, &lines))); + } + } + if Instant::now() > deadline { + return Err(io::Error::other(format!( + "the node was not ready after 3 minutes; see `docker --context {CONTEXT} logs {NAME}`" + ))); + } + std::thread::sleep(poll_interval); + } +} + +fn node_tail_logs(tty: bool) -> Vec { + client::request( + "GET", + &format!("/containers/{NAME}/logs?stdout=1&stderr=1&tail={CRASH_LOG_LINES}"), + None, + ) + .ok() + .filter(|r| r.ok()) + .map(|r| decode_log_lines(&r.body, tty, CRASH_LOG_LINES)) + .unwrap_or_default() +} + +fn wait_for_ready(initial_restarts: Option) -> io::Result<()> { + wait_for_ready_with( + initial_restarts, + Duration::from_secs(180), + Duration::from_secs(1), + || client::get(&format!("/containers/{NAME}/json")), + || { + matches!( + client::exec(NAME, &["timeout", "-s", "KILL", "20", "kubectl", "get", "nodes", "--no-headers"]), + Ok((0, out)) if out.split_whitespace().nth(1) == Some("Ready") + ) + }, + node_tail_logs, + || { + let _ = client::request("POST", &format!("/containers/{NAME}/stop"), None); + }, + ) +} + fn start(use_context: bool) -> io::Result<()> { ensure_daemon()?; let t0 = Instant::now(); let cfg = config(); + let zfs = daemon_storage_zfs(); let want = cfg.api_port(); // A stopped node keeps its port unless something else has taken it since; // then it is made again (its state is in the volume) on a free one. let mut moved_to = None; if exists()? { let info = client::get(&format!("/containers/{NAME}/json"))?; - if info["State"]["Running"] != true { - // Settings changed while it was stopped (a node from before the label: its port). - let stale = match info["Config"]["Labels"][CONFIG_LABEL].as_str() { - Some(made) => made != made_with(&cfg), - None => bound_port(&info) != Some(want), + let made_label = info["Config"]["Labels"][CONFIG_LABEL].as_str(); + let want_made = made_with_for(&cfg, zfs); + if info["State"]["Running"] != true || (zfs && made_label != Some(want_made.as_str())) { + // Settings changed while it was stopped (a node from before the label: its port), + // or a ZFS node made without ext4 loopback + kubelet root-dir support. + let stale = match made_label { + Some(made) => made != want_made, + None => zfs || bound_port(&info) != Some(want), }; if stale { println!("applying the changed settings (the cluster's state is kept)…"); ok(client::request("DELETE", &format!("/containers/{NAME}?force=1"), None))?; - } else if let Some(held) = bound_port(&info).filter(|&p| !port_free(p, cfg.lan)) { + } else if info["State"]["Running"] != true + && let Some(held) = bound_port(&info).filter(|&p| !port_free(p, cfg.lan)) + { let port = pick_port(want, cfg.lan)?; println!("port {held} is in use now; moving the API server to {port}…"); ok(client::request("DELETE", &format!("/containers/{NAME}?force=1"), None))?; @@ -265,26 +726,25 @@ fn start(use_context: bool) -> io::Result<()> { if port != want { println!("port {want} is in use; the API server takes {port}"); } - let (repo, tag) = IMAGE; + let repo = IMAGE.0; + let tag = cfg.version_tag(); println!("pulling {repo}:{tag}…"); let pulled = ok(client::request("POST", &format!("/images/create?fromImage={repo}&tag={tag}"), None))?; if let Some(e) = String::from_utf8_lossy(&pulled.body).lines().filter_map(|l| serde_json::from_str::(l).ok()).find_map(|v| v["error"].as_str().map(str::to_owned)) { return Err(io::Error::other(e)); } - let mut cmd: Vec = ["server", "--disable", "traefik", "--tls-san", "127.0.0.1", "--tls-san", "localhost", "--write-kubeconfig-mode", "644"].map(String::from).to_vec(); - for name in cfg.tls_san.iter().filter(|n| valid_san(n)) { - cmd.extend(["--tls-san".to_owned(), name.clone()]); - } + ok(client::request("POST", "/volumes/create", Some(&volume_create_body(zfs))))?; + let cmd = server_cmd_for(&cfg, zfs); let body = json!({ - "Image": format!("{repo}:{tag}"), + "Image": cfg.image(), "Cmd": cmd, "Hostname": "kiri", - "Labels": {"dev.kiri.k8s": "1", PORT_LABEL: port.to_string(), CONFIG_LABEL: made_with(&cfg)}, + "Labels": {"dev.kiri.k8s": "1", PORT_LABEL: port.to_string(), CONFIG_LABEL: made_with_for(&cfg, zfs)}, "ExposedPorts": {"6443/tcp": {}}, "HostConfig": { "Privileged": true, "Tmpfs": {"/run": "", "/var/run": ""}, - "Binds": binds(), + "Binds": binds_for(zfs), "PortBindings": {"6443/tcp": [{"HostIp": if cfg.lan { "0.0.0.0" } else { "127.0.0.1" }, "HostPort": port.to_string()}]}, "RestartPolicy": {"Name": "unless-stopped"}, }, @@ -295,24 +755,25 @@ fn start(use_context: bool) -> io::Result<()> { if !started.ok() && started.status != 304 { return Err(io::Error::other(started.error())); } - // Early, so a new cluster's CoreDNS can start with it. - let host_names_written = host_names().unwrap_or_else(|e| { - println!("pods may not resolve host.docker.internal: {e}"); - false - }); - println!("waiting for the node…"); - let deadline = Instant::now() + Duration::from_secs(180); - loop { - if let Ok((0, out)) = client::exec(NAME, &["timeout", "-s", "KILL", "20", "kubectl", "get", "nodes", "--no-headers"]) { - if out.split_whitespace().nth(1) == Some("Ready") { - break; + let initial_info = client::get(&format!("/containers/{NAME}/json")).ok(); + let initial_restarts = initial_info.as_ref().and_then(|v| v["RestartCount"].as_u64()); + let mut host_names_written = false; + if initial_info.as_ref().is_none_or(|v| node_exit_code(v, None).is_none()) { + // Early, so a new cluster's CoreDNS and user manifests (e.g. a custom CNI) apply right away. + host_names_written = host_names().unwrap_or_else(|e| { + if client::get(&format!("/containers/{NAME}/json")).ok().is_none_or(|v| node_exit_code(&v, initial_restarts).is_none()) { + println!("pods may not resolve host.docker.internal: {e}"); } + false + }); + if let Err(e) = sync_user_manifests() + && client::get(&format!("/containers/{NAME}/json")).ok().is_none_or(|v| node_exit_code(&v, initial_restarts).is_none()) + { + println!("user manifests from ~/.kiri/k8s-manifests were not synced: {e}"); } - if Instant::now() > deadline { - return Err(io::Error::other(format!("the node was not ready after 3 minutes; see `docker --context kiri logs {NAME}`"))); - } - std::thread::sleep(Duration::from_secs(1)); } + println!("waiting for the node…"); + wait_for_ready(initial_restarts)?; if host_names_written { if let Err(e) = restart_coredns() { println!("pods may not resolve host.docker.internal until CoreDNS restarts: {e}"); @@ -344,6 +805,96 @@ const HOST_NAMES: [&str; 3] = ["host.docker.internal", "host.kiri.internal", "ga /// and k3s upgrades (they replace only k3s' own manifests). const MANIFESTS: &str = "/var/lib/rancher/k3s/server/manifests"; const HOST_MANIFEST: &str = "kiri-host-names.yaml"; +/// Isolated subdirectory under k3s's manifests folder for user manifests from +/// `~/.kiri/k8s-manifests`, so syncing user manifests never hides or clobbers +/// k3s's own built-in manifests (`coredns.yaml`, `local-storage.yaml`, etc.) +/// or `kiri-host-names.yaml`. +const USER_MANIFESTS: &str = "/var/lib/rancher/k3s/server/manifests/kiri-user"; + +/// A safe filename in `~/.kiri/k8s-manifests`: `*.yaml`, `*.yml`, or `*.json` +/// with only ASCII letters, digits, `.`, `_`, or `-`, not starting with `.` or `-`. +pub(crate) fn valid_manifest_name(name: &str) -> bool { + if name.is_empty() || name.len() > 128 || name.starts_with('.') || name.starts_with('-') || name.contains("..") { + return false; + } + if !name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-')) { + return false; + } + let lower = name.to_ascii_lowercase(); + lower.ends_with(".yaml") || lower.ends_with(".yml") || lower.ends_with(".json") +} + +/// Reads valid manifest files (`*.yaml`, `*.yml`, `*.json`) from `dir`, sorted by filename. +pub(crate) fn collect_user_manifests(dir: &std::path::Path) -> io::Result> { + if !dir.exists() { + return Ok(Vec::new()); + } + let mut out = Vec::new(); + for entry in std::fs::read_dir(dir)? { + let entry = entry?; + let ft = entry.file_type()?; + if !ft.is_file() { + continue; + } + let Some(name) = entry.file_name().to_str().map(str::to_owned) else { + continue; + }; + if !valid_manifest_name(&name) { + continue; + } + if entry.metadata()?.len() > MAX_MANIFEST_BYTES { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("manifest `{name}` exceeds {} MiB", MAX_MANIFEST_BYTES >> 20), + )); + } + let body = std::fs::read_to_string(entry.path())?; + out.push((name, body)); + } + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(out) +} + +/// Syncs `~/.kiri/k8s-manifests` into `/var/lib/rancher/k3s/server/manifests/kiri-user` +/// inside the running k3s node container without touching k3s's built-in manifests. +fn sync_user_manifests() -> io::Result<()> { + let dir = manifests_dir()?; + let items = collect_user_manifests(&dir)?; + if items.is_empty() { + let (code, out) = client::exec(NAME, &["rm", "-rf", USER_MANIFESTS])?; + if code != 0 { + return Err(io::Error::other(format!("could not clean {USER_MANIFESTS}: {}", out.trim()))); + } + return Ok(()); + } + // Remove any previous user manifests not in the current list, then write changed ones atomically. + let clean_script = format!( + "set -e; d={USER_MANIFESTS}; mkdir -p \"$d\"; \ + for f in \"$d\"/*; do [ -e \"$f\" ] || continue; b=$(basename \"$f\"); keep=0; \ + for w in \"$@\"; do [ \"$b\" = \"$w\" ] && keep=1 && break; done; \ + [ \"$keep\" = 1 ] || rm -f \"$f\"; done" + ); + let mut clean_cmd: Vec<&str> = vec!["sh", "-c", &clean_script, "sh"]; + for (name, _) in &items { + clean_cmd.push(name.as_str()); + } + let (code, out) = client::exec(NAME, &clean_cmd)?; + if code != 0 { + return Err(io::Error::other(format!("could not prepare {USER_MANIFESTS}: {}", out.trim()))); + } + let write_script = format!( + "set -e; d={USER_MANIFESTS}; f=\"$d/$1\"; t=\"$d/.$1.tmp\"; \ + printf '%s' \"$2\" > \"$t\"; \ + if cmp -s \"$t\" \"$f\"; then rm -f \"$t\"; else mv \"$t\" \"$f\"; fi" + ); + for (name, body) in &items { + let (code, out) = client::exec(NAME, &["sh", "-c", &write_script, "sh", name.as_str(), body.as_str()])?; + if code != 0 { + return Err(io::Error::other(format!("could not write {USER_MANIFESTS}/{name}: {}", out.trim()))); + } + } + Ok(()) +} /// k3s' CoreDNS imports `*.server` from the `coredns-custom` ConfigMap as /// server blocks of their own: one for the host's names answers them with @@ -351,7 +902,11 @@ const HOST_MANIFEST: &str = "kiri-host-names.yaml"; /// everything else resolves as before. A `hosts` block in a `.override` /// would clash with the NodeHosts one k3s' Corefile already has. fn host_manifest() -> String { - let addr = crate::daemon::ports::HOST_ADDR; + let addr = if crate::hostrelay::wsl_host_active() { + crate::hostrelay::WSL_HOST_ADDR_STR + } else { + crate::daemon::ports::HOST_ADDR + }; let zones: Vec = HOST_NAMES.iter().map(|n| format!("{n}:53")).collect(); format!( "# Written by Kiri at each `kiri k8s start`: pods resolve the host's names, as containers do.\n\ @@ -430,9 +985,11 @@ fn kubeconfig(use_context: bool, port: u16) -> io::Result { /// certificate changed. Nothing when there is no running node. pub(crate) fn sync(wait: Duration) -> io::Result { let r = client::request("GET", &format!("/containers/{NAME}/json"), None)?; - if !r.ok() || r.json()["State"]["Running"] != true { + let initial = r.json(); + if !r.ok() || initial["State"]["Running"] != true { return Ok(false); } + let initial_restarts = initial["RestartCount"].as_u64(); // A cluster made by an older Kiri gets it here too, at the engine's start. let host_names_written = host_names().unwrap_or_else(|e| { crate::diag::warn!("host names manifest not written", error = e); @@ -440,6 +997,11 @@ pub(crate) fn sync(wait: Duration) -> io::Result { }); let deadline = Instant::now() + wait; while k3s_yaml().is_err() { + if let Ok(info) = client::get(&format!("/containers/{NAME}/json")) + && node_exit_code(&info, initial_restarts).is_some() + { + return Err(io::Error::other("the node exited before writing its kubeconfig")); + } if Instant::now() > deadline { return Err(io::Error::other("the cluster's kubeconfig was not there in time")); } @@ -488,18 +1050,24 @@ pub(crate) fn forget() { } } -fn status() -> io::Result<()> { +fn status(json: bool) -> io::Result<()> { ensure_daemon()?; + let cfg = config(); if !exists()? { - println!("Kubernetes: not created (kiri k8s start)"); + println!("{}", if json { status_json(None, &cfg).to_string() } else { format_status(None, &cfg) }); return Ok(()); } let info = client::get(&format!("/containers/{NAME}/json"))?; let state = info["State"]["Status"].as_str().unwrap_or("unknown").to_owned(); - let port = bound_port(&info).unwrap_or(API_PORT); - let want = config().api_port(); - let moved = if port != want { format!(" ({want} was in use)") } else { String::new() }; - println!("Kubernetes: {state}, API on 127.0.0.1:{port}{moved}"); + if json { + // The context is put right as below, quietly: the line stays JSON. + if state == "running" { + let _ = sync(Duration::ZERO); + } + println!("{}", status_json(Some(&info), &cfg)); + return Ok(()); + } + println!("{}", format_status(Some(&info), &cfg)); if state == "running" { // A context missing or out of date (written by an older Kiri, or not at all) is put right. if let Err(e) = sync(Duration::ZERO) { @@ -530,6 +1098,41 @@ fn delete() -> io::Result<()> { #[cfg(test)] mod tests { + #[test] + fn editing_rejects_malformed_settings() { + let dir = std::env::temp_dir().join(format!("kiri-k8s-edit-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("k8s.json"); + let bad = br#"{"lan":true,"port":6445,"tls_san":["#; + std::fs::write(&path, bad).unwrap(); + let err = super::load_config_for_edit(&path) + .expect_err("malformed settings must not load as defaults"); + assert!( + err.to_string().contains(&path.display().to_string()), + "{err}" + ); + assert_eq!(std::fs::read(&path).unwrap(), bad); + + // No file yet: the defaults, so a first `kiri k8s set` still saves. + std::fs::remove_file(&path).unwrap(); + assert_eq!( + super::load_config_for_edit(&path).unwrap(), + super::Config::default() + ); + + std::fs::write( + &path, + br#"{"lan":true,"port":6445,"tls_san":["k8s.example"]}"#, + ) + .unwrap(); + let cfg = super::load_config_for_edit(&path).unwrap(); + assert_eq!( + (cfg.port, cfg.tls_san), + (Some(6445), vec!["k8s.example".to_owned()]) + ); + let _ = std::fs::remove_dir_all(&dir); + } + #[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"}}}); @@ -586,4 +1189,390 @@ mod tests { assert!(!super::valid_san(bad), "{bad}"); } } + + #[test] + fn k3s_version_tags_are_strictly_validated() { + for ok in ["v1.31.4-k3s1", "v1.21.14-k3s1", "v1.37.1-k3s1", "v1.31.4-rc1-k3s1", "1.31.4-k3s1", "v1.30.0_k3s1"] { + assert!(super::valid_version(ok), "{ok}"); + } + let too_long = format!("v{}", "1".repeat(128)); + for bad in [ + "", + "default", + "DEFAULT", + "v1.31.4 k3s1", + " v1.31.4-k3s1", + "v1.31.4-k3s1 ", + "v1.31.4/k3s1", + "rancher/k3s:v1.31.4-k3s1", + "v1.31.4:k3s1", + "v1.31.4@sha256:1234", + "v1.31.4?tag=evil", + "v1.31.4&fromImage=evil", + "v1.31.4#frag", + "-v1.31.4-k3s1", + ".v1.31.4-k3s1", + "_v1.31.4-k3s1", + "v1..31-k3s1", + "v1.31.4\n", + "v1.31.4\0", + "v1.31.4\x1b[31m", + too_long.as_str(), + ] { + assert!(!super::valid_version(bad), "{bad:?}"); + } + } + + #[test] + fn k3s_server_args_reject_empty_control_and_overlong_values() { + for ok in [ + "--flannel-backend=none", + "--disable=traefik", + "--disable-network-policy", + "--cluster-cidr=10.42.0.0/16", + "--kube-apiserver-arg=enable-admission-plugins=NodeRestriction", + ] { + assert!(super::valid_k3s_arg(ok), "{ok}"); + } + let max_ok = format!("--{}", "a".repeat(super::MAX_K3S_ARG_LEN - 2)); + assert!(super::valid_k3s_arg(&max_ok)); + let too_long = format!("--{}", "a".repeat(super::MAX_K3S_ARG_LEN - 1)); + for bad in ["", " ", "\t", "--arg\0evil", "--arg\nevil", "--arg\revil", "--arg\tevil", "--arg\x7f", "--arg\x1b[31m", too_long.as_str()] { + assert!(!super::valid_k3s_arg(bad), "{bad:?}"); + } + } + + #[test] + fn set_parses_persists_resets_and_builds_k3s_server_command() { + let s = |items: &[&str]| items.iter().map(|x| (*x).to_owned()).collect::>(); + let mut cfg = super::Config::default(); + assert_eq!(cfg.version_tag(), super::IMAGE.1); + assert_eq!(cfg.image(), format!("rancher/k3s:{}", super::IMAGE.1)); + + // Configure custom version and repeatable --k3s-arg flags. + super::apply_set_args( + &mut cfg, + &s(&[ + "--version", + "v1.31.4-k3s1", + "--k3s-arg", + "--flannel-backend=none", + "--k3s-arg", + "--disable-network-policy", + "--tls-san", + "192.168.1.20", + "--port", + "6445", + "--lan", + "on", + ]), + ) + .unwrap(); + assert_eq!(cfg.version.as_deref(), Some("v1.31.4-k3s1")); + assert_eq!(cfg.version_tag(), "v1.31.4-k3s1"); + assert_eq!(cfg.image(), "rancher/k3s:v1.31.4-k3s1"); + assert_eq!(cfg.k3s_args, vec!["--flannel-backend=none", "--disable-network-policy"]); + assert!(cfg.lan); + assert_eq!(cfg.api_port(), 6445); + + let cmd = super::server_cmd(&cfg); + assert_eq!( + cmd, + vec![ + "server", + "--disable", + "traefik", + "--tls-san", + "127.0.0.1", + "--tls-san", + "localhost", + "--write-kubeconfig-mode", + "644", + "--tls-san", + "192.168.1.20", + "--flannel-backend=none", + "--disable-network-policy", + ] + ); + assert_ne!(super::made_with(&cfg), super::made_with(&super::Config::default())); + + // Persistence round-trip through k8s.json. + let dir = std::env::temp_dir().join(format!("kiri-k8s-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let path = dir.join("k8s.json"); + super::save_config_to(&path, &cfg).unwrap(); + let loaded = super::load_config_from(&path); + assert_eq!(loaded, cfg); + + // Updating another flag preserves version and k3s_args. + let mut updated = loaded; + super::apply_set_args(&mut updated, &s(&["--lan", "off"])).unwrap(); + assert!(!updated.lan); + assert_eq!(updated.version.as_deref(), Some("v1.31.4-k3s1")); + assert_eq!(updated.k3s_args, vec!["--flannel-backend=none", "--disable-network-policy"]); + + // Invalid input does not partially mutate config. + let snapshot = updated.clone(); + assert!(super::apply_set_args(&mut updated, &s(&["--version", "v1.31.4-k3s1", "--k3s-arg", ""])).is_err()); + assert_eq!(updated, snapshot); + assert!(super::apply_set_args(&mut updated, &s(&["--version", "bad/tag"])).is_err()); + assert!(super::apply_set_args(&mut updated, &s(&["--version"])).is_err()); + assert!(super::apply_set_args(&mut updated, &s(&["--k3s-arg"])).is_err()); + + // Exceeding MAX_K3S_ARGS is rejected. + let mut many = Vec::new(); + for i in 0..=super::MAX_K3S_ARGS { + many.push("--k3s-arg".to_owned()); + many.push(format!("--arg-{i}")); + } + assert!(super::apply_set_args(&mut updated, &many).is_err()); + + // Reset version with "default" and "", and clear custom k3s args with --clear-k3s-args. + super::apply_set_args(&mut updated, &s(&["--version", "default", "--clear-k3s-args"])).unwrap(); + assert_eq!(updated.version, None); + assert_eq!(updated.version_tag(), super::IMAGE.1); + assert!(updated.k3s_args.is_empty()); + + super::apply_set_args(&mut updated, &s(&["--version=v1.30.2-k3s1", "--k3s-arg=--disable=servicelb"])).unwrap(); + assert_eq!(updated.version.as_deref(), Some("v1.30.2-k3s1")); + assert_eq!(updated.k3s_args, vec!["--disable=servicelb"]); + + super::apply_set_args(&mut updated, &s(&["--version", ""])).unwrap(); + assert_eq!(updated.version, None); + + super::apply_set_args(&mut updated, &s(&["--version=v1.30.2-k3s1"])).unwrap(); + super::apply_set_args(&mut updated, &s(&["--version="])).unwrap(); + assert_eq!(updated.version, None); + + super::save_config_to(&path, &super::Config::default()).unwrap(); + let raw_json = std::fs::read_to_string(&path).unwrap(); + assert!(!raw_json.contains("version") && !raw_json.contains("k3s_args"), "{raw_json}"); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn formats_settings_and_status_with_version_and_k3s_args() { + let mut cfg = super::Config::default(); + assert_eq!( + super::format_settings(&cfg), + format!("API server on 127.0.0.1:6443; extra certificate names: none; k3s version: {} (default); extra k3s args: none", super::IMAGE.1) + ); + assert_eq!( + super::format_status(None, &cfg), + format!("Kubernetes: not created (kiri k8s start), k3s {}", super::IMAGE.1) + ); + + cfg.version = Some("v1.31.4-k3s1".into()); + cfg.k3s_args = vec!["--flannel-backend=none".into(), "--disable=traefik".into()]; + assert_eq!( + super::format_settings(&cfg), + "API server on 127.0.0.1:6443; extra certificate names: none; k3s version: v1.31.4-k3s1 (custom); extra k3s args: --flannel-backend=none --disable=traefik" + ); + let running = serde_json::json!({ + "State": {"Status": "running"}, + "Config": {"Image": "rancher/k3s:v1.31.4-k3s1", "Labels": {"dev.kiri.k8s.port": "6443"}}, + "NetworkSettings": {"Ports": {"6443/tcp": [{"HostIp": "127.0.0.1", "HostPort": "6443"}]}} + }); + assert_eq!( + super::format_status(Some(&running), &cfg), + "Kubernetes: running, k3s v1.31.4-k3s1, API on 127.0.0.1:6443, k3s args: --flannel-backend=none --disable=traefik" + ); + let j = super::status_json(Some(&running), &cfg); + assert_eq!((&j["state"], &j["version"], &j["port"], &j["requested_port"]), (&"running".into(), &"v1.31.4-k3s1".into(), &6443.into(), &6443.into())); + assert_eq!(j["k3s_args"], serde_json::json!(["--flannel-backend=none", "--disable=traefik"])); + let none = super::status_json(None, &super::Config::default()); + assert!(none["state"].is_null() && none["port"].is_null(), "{none}"); + assert_eq!(none["version"], super::IMAGE.1); + } + + #[test] + fn collects_user_manifests_without_clobbering_builtin_manifests() { + assert_eq!(super::USER_MANIFESTS, "/var/lib/rancher/k3s/server/manifests/kiri-user"); + assert_ne!(super::USER_MANIFESTS, super::MANIFESTS); + for ok in ["cilium.yaml", "01-cni.yml", " policy_v1.json".trim()] { + assert!(super::valid_manifest_name(ok), "{ok}"); + } + for bad in ["", ".hidden.yaml", "-flag.yaml", "../evil.yaml", "a/b.yaml", "notes.txt", "a b.yaml"] { + assert!(!super::valid_manifest_name(bad), "{bad}"); + } + + let dir = std::env::temp_dir().join(format!("kiri-k8s-manifests-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert_eq!(super::collect_user_manifests(&dir).unwrap(), Vec::<(String, String)>::new()); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("b-app.yml"), "kind: Service\n").unwrap(); + std::fs::write(dir.join("a-cilium.yaml"), "kind: DaemonSet\n").unwrap(); + std::fs::write(dir.join(".ignored.yaml"), "ignored\n").unwrap(); + std::fs::write(dir.join("README.md"), "ignored\n").unwrap(); + + let items = super::collect_user_manifests(&dir).unwrap(); + assert_eq!( + items, + vec![ + ("a-cilium.yaml".to_owned(), "kind: DaemonSet\n".to_owned()), + ("b-app.yml".to_owned(), "kind: Service\n".to_owned()), + ] + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn zfs_mode_wires_kubelet_root_dir_and_loopback_ext4_volume_options() { + // /info KiriStorageZfs parsing. + assert_eq!(super::storage_zfs_from_info(&serde_json::json!({"KiriStorageZfs": true})), Some(true)); + assert_eq!(super::storage_zfs_from_info(&serde_json::json!({"KiriStorageZfs": false})), Some(false)); + assert_eq!(super::storage_zfs_from_info(&serde_json::json!({})), None); + + // Volume create payload keeps DriverOpts empty (so kiri-init's volmount::ensure_k8s_ext4 + // runs on /var/lib/kiri/volumes/kiri-k8s/_data) and marks ZFS loopback backing in Labels. + let std_vol = super::volume_create_body(false); + assert_eq!(std_vol["Name"], "kiri-k8s"); + assert_eq!(std_vol["Driver"], "local"); + assert!(std_vol.get("DriverOpts").is_none()); + assert!(std_vol["Labels"].get(super::ZFS_BACKING_LABEL).is_none()); + + let zfs_vol = super::volume_create_body(true); + assert_eq!(zfs_vol["Name"], "kiri-k8s"); + assert_eq!(zfs_vol["Driver"], "local"); + assert!(zfs_vol.get("DriverOpts").is_none()); + assert_eq!(zfs_vol["Labels"][super::ZFS_BACKING_LABEL], "ext4-loop"); + + // Binds use :nocopy on ZFS and plain volume bind otherwise. + assert_eq!(super::binds_for(false)[0], "kiri-k8s:/var/lib/rancher/k3s"); + assert_eq!(super::binds_for(true)[0], "kiri-k8s:/var/lib/rancher/k3s:nocopy"); + + // Default ZFS server_cmd adds --kubelet-arg=root-dir=/var/lib/rancher/k3s/kubelet + // so kubelet (nodefs) sits on the ext4 loop device instead of ZFS rootfs (#607). + let mut cfg = super::Config::default(); + assert!(!super::server_cmd_for(&cfg, false).contains(&super::ZFS_KUBELET_ROOT_ARG.to_owned())); + let zfs_cmd = super::server_cmd_for(&cfg, true); + assert!(zfs_cmd.contains(&super::ZFS_KUBELET_ROOT_ARG.to_owned()), "{zfs_cmd:?}"); + + // Custom user args come after ZFS kubelet root-dir when they don't set root-dir. + cfg.k3s_args = vec!["--flannel-backend=none".into()]; + let zfs_with_extra = super::server_cmd_for(&cfg, true); + let root_pos = zfs_with_extra.iter().position(|a| a == super::ZFS_KUBELET_ROOT_ARG).unwrap(); + let extra_pos = zfs_with_extra.iter().position(|a| a == "--flannel-backend=none").unwrap(); + assert!(root_pos < extra_pos, "{zfs_with_extra:?}"); + + // User-supplied root-dir in k3s_args is respected and not duplicated. + for user_args in [ + vec!["--kubelet-arg=root-dir=/custom/kubelet".to_owned()], + vec!["--kubelet-arg=--root-dir=/custom/kubelet".to_owned()], + vec!["--kubelet-arg".to_owned(), "root-dir=/custom/kubelet".to_owned()], + vec!["--kubelet-arg=root-dir".to_owned(), "/custom/kubelet".to_owned()], + ] { + cfg.k3s_args = user_args.clone(); + assert!(super::has_kubelet_root_dir(&cfg.k3s_args), "{user_args:?}"); + let cmd = super::server_cmd_for(&cfg, true); + assert!(!cmd.contains(&super::ZFS_KUBELET_ROOT_ARG.to_owned()), "{cmd:?}"); + } + + // made_with_for distinguishes ZFS from non-ZFS so pre-fix ZFS nodes are recreated, + // while keeping non-ZFS made_with identical. + let plain = super::Config::default(); + assert_eq!(super::made_with(&plain), super::made_with_for(&plain, false)); + assert_ne!(super::made_with_for(&plain, true), super::made_with_for(&plain, false)); + } + + #[test] + fn readiness_wait_fails_fast_when_container_exits_or_crash_loops() { + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::time::{Duration, Instant}; + + fn docker_frame(stream: u8, line: &str) -> Vec { + let mut out = vec![stream, 0, 0, 0]; + out.extend_from_slice(&(line.len() as u32).to_be_bytes()); + out.extend_from_slice(line.as_bytes()); + out + } + + // Multiplexed Docker log decoding + tail truncation. + let mut raw_logs = docker_frame(1, "time=\"2026-11-24T17:00:00Z\" level=info msg=\"Starting k3s\"\n"); + raw_logs.extend(docker_frame( + 2, + "F1124 17:00:01.123456 1 server.go:123] Failed to start ContainerManager: cannot find filesystem info for device \"rpool/ROOT/ubuntu\"\r\n\n", + )); + let decoded = super::decode_log_lines(&raw_logs, false, 15); + assert_eq!(decoded.len(), 2); + assert!(decoded[1].contains("cannot find filesystem info for device \"rpool/ROOT/ubuntu\"")); + assert_eq!(super::decode_log_lines(&raw_logs, false, 1), vec![decoded[1].clone()]); + assert_eq!(super::decode_log_lines(b"tty line 1\r\ntty line 2\n", true, 5), vec!["tty line 1", "tty line 2"]); + + // 1) Immediate container exit (State.Running == false, State.Status == "exited") fails fast (< 500ms, not 180s). + let crashed_stops = AtomicUsize::new(0); + let t0 = Instant::now(); + let err = super::wait_for_ready_with( + Some(0), + Duration::from_secs(180), + Duration::from_secs(5), + || { + Ok(serde_json::json!({ + "State": {"Status": "exited", "Running": false, "ExitCode": 1}, + "RestartCount": 0, + "Config": {"Tty": false} + })) + }, + || false, + |tty| super::decode_log_lines(&raw_logs, tty, 15), + || { + crashed_stops.fetch_add(1, Ordering::SeqCst); + }, + ) + .unwrap_err(); + assert!(t0.elapsed() < Duration::from_millis(500), "took {:?}", t0.elapsed()); + assert_eq!(crashed_stops.load(Ordering::SeqCst), 1); + let msg = err.to_string(); + assert!(msg.contains("exit code 1"), "{msg}"); + assert!(msg.contains("cannot find filesystem info for device"), "{msg}"); + // Last line is the fatal k3s log line so ui/k8s.rs surfaces it directly. + assert!(msg.lines().last().unwrap().contains("cannot find filesystem info for device"), "{msg}"); + + // 2) Crash-loop under `RestartPolicy: unless-stopped` (Running == true again, RestartCount > initial_restarts). + let loop_stops = AtomicUsize::new(0); + let err_loop = super::wait_for_ready_with( + Some(2), + Duration::from_secs(180), + Duration::from_secs(5), + || { + Ok(serde_json::json!({ + "State": {"Status": "running", "Running": true, "ExitCode": 255}, + "RestartCount": 3, + "Config": {"Tty": true} + })) + }, + || false, + |_| vec!["Error: unknown flag: --bad-k3s-arg".into()], + || { + loop_stops.fetch_add(1, Ordering::SeqCst); + }, + ) + .unwrap_err(); + assert_eq!(loop_stops.load(Ordering::SeqCst), 1); + assert!(err_loop.to_string().contains("exit code 255") && err_loop.to_string().contains("--bad-k3s-arg")); + + // 3) Healthy startup polls until kubectl reports Ready without false-failing on prior RestartCount. + let polls = AtomicUsize::new(0); + let healthy_stops = AtomicUsize::new(0); + super::wait_for_ready_with( + Some(2), + Duration::from_secs(5), + Duration::from_millis(1), + || { + Ok(serde_json::json!({ + "State": {"Status": "running", "Running": true, "ExitCode": 0}, + "RestartCount": 2, + "Config": {"Tty": false} + })) + }, + || polls.fetch_add(1, Ordering::SeqCst) >= 2, + |_| Vec::new(), + || { + healthy_stops.fetch_add(1, Ordering::SeqCst); + }, + ) + .unwrap(); + assert_eq!(healthy_stops.load(Ordering::SeqCst), 0); + assert!(polls.load(Ordering::SeqCst) >= 3); + } } diff --git a/crates/kiri/src/kubeconfig.rs b/crates/kiri/src/kubeconfig.rs index 5b1d7bb33..abfee778b 100644 --- a/crates/kiri/src/kubeconfig.rs +++ b/crates/kiri/src/kubeconfig.rs @@ -106,6 +106,7 @@ fn read(path: &Path) -> io::Result> { /// The new text by a temporary file and a rename, 0600; the one before it /// kept as `config.bak.kiri`. fn write(path: &Path, before: Option<&str>, text: &str) -> io::Result<()> { + static TMP_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let dir = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new(".")); std::fs::create_dir_all(dir)?; let file = path.file_name().and_then(|n| n.to_str()).unwrap_or("config"); @@ -114,7 +115,8 @@ fn write(path: &Path, before: Option<&str>, text: &str) -> io::Result<()> { std::fs::write(&backup, before)?; private(&backup)?; } - let tmp = dir.join(format!(".{file}.kiri-{}", std::process::id())); + let seq = TMP_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = dir.join(format!(".{file}.kiri-{}-{seq}", std::process::id())); let done = std::fs::write(&tmp, text).and_then(|()| private(&tmp)).and_then(|()| std::fs::rename(&tmp, path)); if done.is_err() { let _ = std::fs::remove_file(&tmp); @@ -149,16 +151,52 @@ fn blank(l: &str) -> bool { t.is_empty() || t.starts_with('#') } -fn tops(text: &str) -> Vec> { +/// Strips a YAML `#` comment starting at index 0 or preceded by whitespace. +fn uncomment(s: &str) -> &str { + let bytes = s.as_bytes(); + for (i, &b) in bytes.iter().enumerate() { + if b == b'#' && (i == 0 || matches!(bytes[i - 1], b' ' | b'\t')) { + return &s[..i]; + } + } + s +} + +fn is_doc_marker(l: &str, marker: &str) -> bool { + uncomment(l).trim_end() == marker +} + +fn tops(text: &str) -> Result>, String> { + let text = text.strip_prefix('\u{feff}').unwrap_or(text); let mut tops = vec![Top { key: "", lines: Vec::new() }]; + let mut seen_content = false; + let mut seen_end = false; for l in text.lines() { + if seen_end && !blank(l) { + return Err("a multi-document kubeconfig; not changing it".into()); + } + if is_doc_marker(l, "---") { + if seen_content { + return Err("a multi-document kubeconfig; not changing it".into()); + } + tops.last_mut().expect("there is one").lines.push(l); + continue; + } + if is_doc_marker(l, "...") { + seen_end = true; + tops.push(Top { key: "...", lines: vec![l] }); + continue; + } + if !blank(l) { + seen_content = true; + } let top = !l.starts_with([' ', '\t', '-', '#']) && !l.trim().is_empty(); match l.split_once(':').filter(|_| top) { Some((key, _)) => tops.push(Top { key: key.trim(), lines: vec![l] }), None => tops.last_mut().expect("there is one").lines.push(l), } } - tops + Ok(tops) } /// The lines before a list's first item, its items (each its lines), and their indent. @@ -166,7 +204,7 @@ type Items<'a> = (Vec<&'a str>, Vec>, usize); /// A list's items; an error for a list that isn't a block list. fn items<'a>(top: &Top<'a>) -> Result, String> { - let value = top.lines[0].split_once(':').map_or("", |(_, v)| v).split(" #").next().unwrap_or("").trim(); + let value = uncomment(top.lines[0].split_once(':').map_or("", |(_, v)| v)).trim(); if !matches!(value, "" | "[]" | "null" | "~") { return Err(format!("`{}` is not a list kubectl writes; not changing it", top.key)); } @@ -185,13 +223,25 @@ fn items<'a>(top: &Top<'a>) -> Result, String> { Ok((body[..at].to_vec(), items, dash)) } -/// An item's `name`, the key at the column after its dash. +/// An item's `name`, the key at the column after its dash (or on the lines below a bare `-`). fn item_name<'a>(item: &[&'a str], dash: usize) -> Option<&'a str> { let rest = &item[0][dash + 1..]; - let col = dash + 1 + indent(rest); let first = rest.trim_start(); - let line = if first.starts_with("name:") { Some(first) } else { item[1..].iter().find(|l| indent(l) == col && l.trim_start().starts_with("name:")).map(|l| l.trim_start()) }; - line.map(|l| scalar(&l["name:".len()..])) + let has_inline_key = !blank(rest); + let col = if has_inline_key { + dash + 1 + indent(rest) + } else { + item[1..].iter().find(|l| !blank(l)).map(|l| indent(l)).filter(|&c| c > dash)? + }; + let match_name = |s: &'a str| { + s.strip_prefix("name:") + .filter(|after| after.is_empty() || after.starts_with([' ', '\t', '#'])) + .map(scalar) + }; + if has_inline_key && let Some(n) = match_name(first) { + return Some(n); + } + item[1..].iter().filter(|l| indent(l) == col).find_map(|l| match_name(l.trim_start())) } /// A plain or quoted YAML scalar, without a trailing comment. @@ -202,11 +252,11 @@ fn scalar(v: &str) -> &str { return inner; } } - v.split(" #").next().unwrap_or("").trim() + uncomment(v).trim() } fn not_json(text: &str) -> Result<(), String> { - if text.trim_start().starts_with('{') { + if text.strip_prefix('\u{feff}').unwrap_or(text).trim_start().starts_with('{') { return Err("a JSON kubeconfig; not changing it".into()); } Ok(()) @@ -232,7 +282,7 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul return Ok(ours.to_owned()); } // Ours, per list: the item called `name`, its lines from its dash on. - let theirs = tops(ours); + let theirs = tops(ours)?; let mut new: Vec<(&str, Vec)> = Vec::new(); for list in LISTS { let Some(top) = theirs.iter().find(|t| t.key == list) else { continue }; @@ -243,9 +293,14 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul } let nl = newline(existing); let mut out: Vec = Vec::new(); + let mut doc_end: Vec = Vec::new(); let mut seen: Vec<&str> = Vec::new(); let mut current = false; - for top in tops(existing) { + for top in tops(existing)? { + if top.key == "..." { + doc_end.extend(top.lines.iter().map(|l| l.to_string())); + continue; + } if top.key == "current-context" && use_context { out.push(format!("current-context: {name}")); out.extend(top.lines[1..].iter().map(|l| l.to_string())); @@ -259,7 +314,8 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul seen.push(top.key); let (before, items, dash) = items(&top)?; let dash = if items.is_empty() { 0 } else { dash }; - out.push(format!("{}:", top.key)); + let header_val = uncomment(top.lines[0].split_once(':').map_or("", |(_, v)| v)).trim(); + out.push(if header_val.is_empty() { top.lines[0].to_owned() } else { format!("{}:", top.key) }); out.extend(before.iter().map(|l| l.to_string())); let kept: Vec<&Vec<&str>> = items.iter().filter(|i| item_name(i, dash) != Some(name)).collect(); let mut body: Vec = kept.iter().flat_map(|i| i.iter().map(|l| l.to_string())).collect(); @@ -279,6 +335,7 @@ pub fn merge(existing: &str, ours: &str, name: &str, use_context: bool) -> Resul if use_context && !current { out.push(format!("current-context: {name}")); } + out.extend(doc_end); Ok(join(&out, nl)) } @@ -291,7 +348,7 @@ pub fn remove(existing: &str, name: &str) -> Result { } let mut out: Vec = Vec::new(); let mut changed = false; - for top in tops(existing) { + for top in tops(existing)? { if top.key == "current-context" && scalar(top.lines[0].split_once(':').map_or("", |(_, v)| v)) == name { out.push("current-context: \"\"".into()); out.extend(top.lines[1..].iter().map(|l| l.to_string())); @@ -383,7 +440,7 @@ users: "; fn names(text: &str, list: &str) -> Vec { - let tops = tops(text); + let tops = tops(text).unwrap(); let top = tops.iter().find(|t| t.key == list).unwrap(); let (_, items, dash) = items(top).unwrap(); items.iter().map(|i| item_name(i, dash).unwrap().to_owned()).collect() @@ -495,4 +552,26 @@ users: assert_eq!(std::fs::read_dir(dir.join(".kube")).unwrap().count(), 2); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn handles_bare_dashes_document_markers_and_comments() { + let ours = from_k3s(K3S, "kiri", 6445); + let bare_dash = "apiVersion: v1\nclusters:\n-\n cluster:\n server: https://127.0.0.1:6443\n name: kiri\n-\n cluster:\n server: https://prod\n name: prod\ncontexts:\n-\n context:\n cluster: kiri\n user: kiri\n name: kiri\n-\n context:\n cluster: prod\n user: prod\n name: prod\ncurrent-context: prod\nkind: Config\nusers:\n-\n name: kiri\n user: {}\n-\n name: prod\n user: {}\n"; + let merged = merge(bare_dash, &ours, "kiri", false).unwrap(); + assert_eq!(merged.matches("name: kiri").count(), 3); + assert!(merged.contains("https://127.0.0.1:6445")); + let removed = remove(&merged, "kiri").unwrap(); + assert!(!removed.contains("name: kiri")); + assert_eq!(removed.matches("name: prod").count(), 3); + + let markers = "\u{feff}---\napiVersion: v1\nclusters:\t# managed\n- cluster:\n server: https://x\n name: prod\ncontexts:# ctxs\n- context:\n cluster: prod\n user: prod\n name: prod\nkind: Config\n...\n"; + let merged_doc = merge(markers, &ours, "kiri", true).unwrap(); + assert!(merged_doc.trim_end().ends_with("\n..."), "{merged_doc:?}"); + assert!(merged_doc.contains("clusters:\t# managed\n")); + assert!(merged_doc.contains("contexts:# ctxs\n")); + assert!(merged_doc.contains("users:\n- name: kiri\n")); + assert!(merged_doc.contains("current-context: kiri\n")); + + assert!(merge("apiVersion: v1\nclusters: []\n---\napiVersion: v1\n", &ours, "kiri", false).is_err()); + } } diff --git a/crates/kiri/src/machine.rs b/crates/kiri/src/machine.rs index 5d722e9d9..ec15973b3 100644 --- a/crates/kiri/src/machine.rs +++ b/crates/kiri/src/machine.rs @@ -13,7 +13,7 @@ use serde_json::json; use crate::client; -const LABEL: &str = "dev.kiri.machine"; +pub(crate) const LABEL: &str = "dev.kiri.machine"; /// `kiri machine create NAME --distro ubuntu` picks one of these. const DISTROS: [(&str, &str); 7] = [ @@ -35,19 +35,42 @@ fn ok(r: io::Result) -> io::Result { if r.ok() { Ok(r) } else { Err(io::Error::other(r.error())) } } +pub(crate) const USAGE: &str = "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list [--json] | shell NAME [-- CMD...] | start | stop | restart | delete NAME"; + +/// True when `args` asks for `kiri machine`'s own help rather than passing +/// `--help` to a command inside `kiri machine shell NAME -- --help`. +pub(crate) fn wants_help(args: &[String]) -> bool { + if matches!(args.first().map(String::as_str), Some("help")) { + return true; + } + let scan_end = if args.first().map(String::as_str) == Some("shell") { + args.iter().position(|a| a == "--").unwrap_or(args.len()) + } else { + args.len() + }; + args[..scan_end].iter().any(|a| matches!(a.as_str(), "-h" | "--help")) +} + pub fn run(args: &[String]) -> io::Result<()> { + if wants_help(args) { + println!("{USAGE}"); + return Ok(()); + } + if args.is_empty() { + return Err(io::Error::other(USAGE)); + } if !client::alive() { return Err(io::Error::other("kiri daemon is not running: open Kiri.app or run `kiri daemon`")); } let name = args.get(1).map(String::as_str).unwrap_or_default(); - let need_name = || if name.is_empty() { Err(io::Error::other("name a machine")) } else { Ok(()) }; + let need_name = || if name.is_empty() || name.starts_with('-') { Err(io::Error::other("name a machine")) } else { Ok(()) }; match args.first().map(String::as_str) { Some("create") => { need_name()?; let pick = args.iter().position(|a| a == "--distro" || a == "--image").and_then(|i| args.get(i + 1)).map_or("ubuntu", String::as_str); create(name, pick, args.iter().any(|a| a == "--systemd")) } - Some("list" | "ls") => list(), + Some("list" | "ls") => list(args.iter().any(|a| a == "--json")), Some("shell") => { need_name()?; let cmd: Vec<&str> = args.iter().position(|a| a == "--").map(|i| args[i + 1..].iter().map(String::as_str).collect()).unwrap_or_default(); @@ -69,9 +92,7 @@ pub fn run(args: &[String]) -> io::Result<()> { println!("deleted machine {name}"); Ok(()) } - _ => Err(io::Error::other( - "usage: kiri machine create NAME [--distro ubuntu|debian|alpine|fedora|arch|rocky|opensuse | --image IMAGE] [--systemd]\n kiri machine list | shell NAME [-- CMD...] | start | stop | restart | delete NAME", - )), + _ => Err(io::Error::other(USAGE)), } } @@ -93,22 +114,86 @@ fn home(user: &str) -> String { if user == "root" { "/root".to_owned() } else { format!("{HOMES}/{user}") } } -fn create(name: &str, pick: &str, systemd: bool) -> io::Result<()> { - if !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') || name.starts_with('-') { - return Err(io::Error::other("a machine name is letters, digits and dashes")); +/// A parsed image reference for `kiri machine create`: the full reference +/// passed to `/images/{ref}/json` and `POST /containers/create`, plus the +/// `fromImage` and `tag` query values for `POST /images/create` when pulling. +#[derive(Debug, Clone, PartialEq, Eq)] +struct MachineImage { + full: String, + from_image: String, + tag: String, +} + +impl MachineImage { + fn inspect_path(&self) -> String { + format!("/images/{}/json", percent_encode_image_ref(&self.full)) + } + + fn pull_path(&self) -> String { + format!("/images/create?fromImage={}&tag={}", urlish(&self.from_image), urlish(&self.tag)) } +} + +fn percent_encode_image_ref(reference: &str) -> String { + urlish(reference) +} + +fn parse_machine_image(pick: &str) -> MachineImage { let image = DISTROS.iter().find(|(d, _)| *d == pick).map_or(pick, |(_, i)| *i); + if let Some((repo, digest)) = image.split_once('@').filter(|(_, d)| d.starts_with("sha256:")) { + // Strip an optional `:tag` label before `@sha256:...` for `fromImage`, + // keeping any registry `:port` before the last `/`. + let from_image = match repo.rsplit_once(':') { + Some((r, t)) if !t.contains('/') && !t.is_empty() => r, + _ => repo, + }; + return MachineImage { + full: image.to_owned(), + from_image: from_image.to_owned(), + tag: digest.to_owned(), + }; + } let (repo, tag) = match image.rsplit_once(':') { - Some((r, t)) if !t.contains('/') => (r, t), + Some((r, t)) if !t.contains('/') && !t.is_empty() => (r, t), _ => (image, "latest"), }; - println!("pulling {repo}:{tag}…"); - let pulled = ok(client::request("POST", &format!("/images/create?fromImage={repo}&tag={tag}"), None))?; - if let Some(e) = String::from_utf8_lossy(&pulled.body).lines().filter_map(|l| serde_json::from_str::(l).ok()).find_map(|v| v["error"].as_str().map(str::to_owned)) { + MachineImage { + full: format!("{repo}:{tag}"), + from_image: repo.to_owned(), + tag: tag.to_owned(), + } +} + +/// Ensures `image` is present in the daemon's image store, matching +/// `docker run --pull=missing`: probes `GET /images/{ref}/json` first and only +/// pulls via `POST /images/create` on `404`. Returns `Ok(true)` if it pulled, +/// or `Ok(false)` if the image was already local. +fn ensure_machine_image_with(image: &MachineImage, mut req: F, mut on_pull: P) -> io::Result +where + F: FnMut(&str, &str, Option<&serde_json::Value>) -> io::Result, + P: FnMut(&str), +{ + let probe = req("GET", &image.inspect_path(), None)?; + if probe.status == 200 { + return Ok(false); + } + if probe.status != 404 { + return Err(io::Error::other(probe.error())); + } + on_pull(&image.full); + let pulled = ok(req("POST", &image.pull_path(), None))?; + if let Some(e) = String::from_utf8_lossy(&pulled.body) + .lines() + .filter_map(|l| serde_json::from_str::(l).ok()) + .find_map(|v| v["error"].as_str().map(str::to_owned)) + { return Err(io::Error::other(e)); } - let (user, uid, gid) = user(); - let home = home(&user); + Ok(true) +} + +fn create_body_for(name: &str, image: &str, user: &str, uid: u32, gid: u32, systemd: bool) -> serde_json::Value { + let home = home(user); // The host user, made once; every distro has one of these tools. An // image user that already has the uid (Ubuntu's `ubuntu` is 1000, the // first user's uid on most Linux hosts) is renamed to the host user. @@ -132,7 +217,7 @@ command -v sudo >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=nonint } ); let mut body = json!({ - "Image": format!("{repo}:{tag}"), + "Image": image, "Cmd": ["/bin/sh", "-c", init], "Hostname": name, "Labels": {LABEL: name}, @@ -143,28 +228,62 @@ command -v sudo >/dev/null 2>&1 || (apt-get update -qq && DEBIAN_FRONTEND=nonint }, }); if systemd { - // systemd needs its own cgroup tree, tmpfs /run and /tmp, and stops - // on SIGRTMIN+3. + // systemd needs its own cgroup tree, tmpfs /run and /tmp (with exec so + // scripts and helpers in /tmp and /run can run instead of inheriting + // Docker's default noexec tmpfs flag), and stops on SIGRTMIN+3. body["StopSignal"] = "SIGRTMIN+3".into(); body["Env"] = json!(["container=docker"]); body["HostConfig"]["Privileged"] = true.into(); - body["HostConfig"]["Tmpfs"] = json!({"/run": "", "/run/lock": "", "/tmp": ""}); + body["HostConfig"]["Tmpfs"] = json!({"/run": "exec", "/run/lock": "", "/tmp": "exec"}); + } + body +} + +fn create_with( + name: &str, + pick: &str, + systemd: bool, + (user, uid, gid): (&str, u32, u32), + mut req: Req, + mut exec: Exec, + on_pull: OnPull, +) -> io::Result +where + Req: FnMut(&str, &str, Option<&serde_json::Value>) -> io::Result, + Exec: FnMut(&str, &[&str]) -> io::Result<(i64, String)>, + OnPull: FnMut(&str), +{ + if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') || name.starts_with('-') { + return Err(io::Error::other("a machine name is letters, digits and dashes")); } - ok(client::request("POST", &format!("/containers/create?name={}", container(name)), Some(&body)))?; - ok(client::request("POST", &format!("/containers/{}/start", container(name)), None))?; + let image = parse_machine_image(pick); + ensure_machine_image_with(&image, &mut req, on_pull)?; + let body = create_body_for(name, &image.full, user, uid, gid, systemd); + ok(req("POST", &format!("/containers/create?name={}", container(name)), Some(&body)))?; + ok(req("POST", &format!("/containers/{}/start", container(name)), None))?; // The user is made by the machine's own first command: wait for it, or // a `machine shell` straight after was "unknown user" (seen on Fedora). let wait = format!("for i in $(seq 300); do id -u {user} >/dev/null 2>&1 && exit 0; sleep 0.1; done; exit 1"); - if client::exec(&container(name), &["sh", "-c", &wait])?.0 != 0 { + if exec(&container(name), &["sh", "-c", &wait])?.0 != 0 { return Err(io::Error::other(format!("machine {name} is running, but the user {user} could not be added to it"))); } + Ok(image.full) +} + +fn create(name: &str, pick: &str, systemd: bool) -> io::Result<()> { + let (user, uid, gid) = user(); + let image = create_with(name, pick, systemd, (&user, uid, gid), client::request, client::exec, |img| println!("pulling {img}…"))?; println!("machine {name} ({image}) is running: kiri machine shell {name}"); Ok(()) } -fn list() -> io::Result<()> { +fn list(json: bool) -> io::Result<()> { let filters = format!("{{\"label\":[\"{LABEL}\"]}}"); let rows = client::get(&format!("/containers/json?all=1&filters={}", urlish(&filters)))?; + if json { + println!("{}", list_json(&rows)); + return Ok(()); + } println!("{:<16} {:<28} {}", "NAME", "IMAGE", "STATE"); for c in rows.as_array().into_iter().flatten() { println!("{:<16} {:<28} {}", c["Labels"][LABEL].as_str().unwrap_or("?"), c["Image"].as_str().unwrap_or(""), c["Status"].as_str().unwrap_or("")); @@ -172,6 +291,16 @@ fn list() -> io::Result<()> { Ok(()) } +/// `kiri machine list --json`: each machine's name, image, state (Docker's +/// `running`, `exited`…) and status (`Up 2 hours`…). +fn list_json(rows: &serde_json::Value) -> serde_json::Value { + rows.as_array() + .into_iter() + .flatten() + .map(|c| json!({"name": c["Labels"][LABEL], "image": c["Image"], "state": c["State"], "status": c["Status"]})) + .collect() +} + fn urlish(s: &str) -> String { s.bytes().map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }).collect() } @@ -205,3 +334,276 @@ fn shell(name: &str, cmd: &[&str]) -> io::Result<()> { } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + fn resp(status: u16, body: &[u8]) -> client::Response { + client::Response { status, body: body.to_vec() } + } + + #[test] + fn parse_machine_image_handles_distros_tags_ports_and_digests() { + let digest = format!("sha256:{}", "a".repeat(64)); + let cases = [ + ("ubuntu", "ubuntu:24.04", "ubuntu", "24.04", "/images/ubuntu%3A24.04/json", "/images/create?fromImage=ubuntu&tag=24.04"), + ( + "opensuse", + "opensuse/tumbleweed:latest", + "opensuse/tumbleweed", + "latest", + "/images/opensuse%2Ftumbleweed%3Alatest/json", + "/images/create?fromImage=opensuse%2Ftumbleweed&tag=latest", + ), + ("pmb-copy", "pmb-copy:latest", "pmb-copy", "latest", "/images/pmb-copy%3Alatest/json", "/images/create?fromImage=pmb-copy&tag=latest"), + ("pmb-copy:latest", "pmb-copy:latest", "pmb-copy", "latest", "/images/pmb-copy%3Alatest/json", "/images/create?fromImage=pmb-copy&tag=latest"), + ( + "ghcr.io/org/devbox:1", + "ghcr.io/org/devbox:1", + "ghcr.io/org/devbox", + "1", + "/images/ghcr.io%2Forg%2Fdevbox%3A1/json", + "/images/create?fromImage=ghcr.io%2Forg%2Fdevbox&tag=1", + ), + ( + "localhost:5000/pmb:latest", + "localhost:5000/pmb:latest", + "localhost:5000/pmb", + "latest", + "/images/localhost%3A5000%2Fpmb%3Alatest/json", + "/images/create?fromImage=localhost%3A5000%2Fpmb&tag=latest", + ), + ( + "localhost:5000/pmb", + "localhost:5000/pmb:latest", + "localhost:5000/pmb", + "latest", + "/images/localhost%3A5000%2Fpmb%3Alatest/json", + "/images/create?fromImage=localhost%3A5000%2Fpmb&tag=latest", + ), + ]; + for (pick, full, from, tag, inspect, pull) in cases { + let parsed = parse_machine_image(pick); + assert_eq!(parsed.full, full, "{pick}"); + assert_eq!(parsed.from_image, from, "{pick}"); + assert_eq!(parsed.tag, tag, "{pick}"); + assert_eq!(parsed.inspect_path(), inspect, "{pick}"); + assert_eq!(parsed.pull_path(), pull, "{pick}"); + assert!(kiri_image::Reference::parse(&parsed.full).is_ok(), "{pick}"); + } + + // Digest references: bare repo@sha256:..., tag+digest, and registry:port@sha256:... + let digest_cases = [ + (format!("org/box@{digest}"), "org/box"), + (format!("ghcr.io/org/box:v1@{digest}"), "ghcr.io/org/box"), + (format!("localhost:5000/org/box@{digest}"), "localhost:5000/org/box"), + ]; + for (pick, expected_from) in digest_cases { + let parsed = parse_machine_image(&pick); + assert_eq!(parsed.full, pick); + assert_eq!(parsed.from_image, expected_from); + assert_eq!(parsed.tag, digest); + assert_eq!(parsed.inspect_path(), format!("/images/{}/json", urlish(&pick))); + assert_eq!(parsed.pull_path(), format!("/images/create?fromImage={}&tag={}", urlish(expected_from), urlish(&digest))); + assert!(kiri_image::Reference::parse(&parsed.full).is_ok(), "{pick}"); + // Matches daemon/api.rs `pull()` reconstruction for `sha256:` tags. + let daemon_pull_name = format!("{}@{}", parsed.from_image, parsed.tag); + assert!(kiri_image::Reference::parse(&daemon_pull_name).is_ok(), "{daemon_pull_name}"); + } + } + + #[test] + fn local_image_skips_pull_and_creates_container_immediately() { + let digest = format!("sha256:{}", "b".repeat(64)); + let digest_ref = format!("org/box@{digest}"); + let digest_inspect = format!("/images/{}/json", urlish(&digest_ref)); + for (pick, expected_image, expected_inspect) in [ + ("pmb-copy:latest", "pmb-copy:latest", "/images/pmb-copy%3Alatest/json"), + ("pmb-copy", "pmb-copy:latest", "/images/pmb-copy%3Alatest/json"), + ("ghcr.io/org/devbox:1", "ghcr.io/org/devbox:1", "/images/ghcr.io%2Forg%2Fdevbox%3A1/json"), + ("localhost:5000/pmb:latest", "localhost:5000/pmb:latest", "/images/localhost%3A5000%2Fpmb%3Alatest/json"), + (digest_ref.as_str(), digest_ref.as_str(), digest_inspect.as_str()), + ] { + let mut calls: Vec<(String, String, Option)> = Vec::new(); + let mut pulled_notices: Vec = Vec::new(); + let created_image = create_with( + "devbox", + pick, + true, + ("alice", 1000, 1000), + |method, path, body| { + calls.push((method.to_owned(), path.to_owned(), body.cloned())); + match (method, path) { + ("GET", p) if p == expected_inspect => Ok(resp(200, br#"{"Id":"sha256:local"}"#)), + ("POST", "/containers/create?name=machine-devbox") => Ok(resp(201, br#"{"Id":"c1"}"#)), + ("POST", "/containers/machine-devbox/start") => Ok(resp(204, b"")), + other => panic!("unexpected daemon call for {pick}: {other:?}"), + } + }, + |cname, _| { + assert_eq!(cname, "machine-devbox"); + Ok((0, String::new())) + }, + |img| pulled_notices.push(img.to_owned()), + ) + .unwrap(); + + assert_eq!(created_image, expected_image); + assert!(pulled_notices.is_empty(), "must not announce pulling when image is local: {pick}"); + assert!(!calls.iter().any(|(m, p, _)| m == "POST" && p.starts_with("/images/create")), "must skip /images/create: {calls:?}"); + assert_eq!(calls.len(), 3, "{calls:?}"); + assert_eq!((calls[0].0.as_str(), calls[0].1.as_str()), ("GET", expected_inspect)); + assert_eq!((calls[1].0.as_str(), calls[1].1.as_str()), ("POST", "/containers/create?name=machine-devbox")); + let create_body = calls[1].2.as_ref().unwrap(); + assert_eq!(create_body["Image"], expected_image); + assert_eq!(create_body["HostConfig"]["Tmpfs"], json!({"/run": "exec", "/run/lock": "", "/tmp": "exec"})); + assert_eq!((calls[2].0.as_str(), calls[2].1.as_str()), ("POST", "/containers/machine-devbox/start")); + } + } + + #[test] + fn missing_image_pulls_on_404_and_surfaces_errors() { + // 1. 404 -> pulls via POST /images/create and creates container. + let image = parse_machine_image("ghcr.io/org/devbox:1"); + let mut calls = Vec::new(); + let mut pulled_notices = Vec::new(); + let pulled = ensure_machine_image_with( + &image, + |method, path, _| { + calls.push((method.to_owned(), path.to_owned())); + match (method, path) { + ("GET", "/images/ghcr.io%2Forg%2Fdevbox%3A1/json") => Ok(resp(404, br#"{"message":"No such image"}"#)), + ("POST", "/images/create?fromImage=ghcr.io%2Forg%2Fdevbox&tag=1") => { + Ok(resp(200, b"{\"status\":\"Pulling from org/devbox\"}\n{\"status\":\"Status: Downloaded newer image\"}\n")) + } + other => panic!("unexpected call: {other:?}"), + } + }, + |img| pulled_notices.push(img.to_owned()), + ) + .unwrap(); + assert!(pulled); + assert_eq!(pulled_notices, vec!["ghcr.io/org/devbox:1"]); + assert_eq!( + calls, + vec![ + ("GET".to_owned(), "/images/ghcr.io%2Forg%2Fdevbox%3A1/json".to_owned()), + ("POST".to_owned(), "/images/create?fromImage=ghcr.io%2Forg%2Fdevbox&tag=1".to_owned()), + ] + ); + + // 2. Pull stream JSON error is surfaced. + let err = ensure_machine_image_with( + &image, + |method, _, _| match method { + "GET" => Ok(resp(404, br#"{"message":"No such image"}"#)), + "POST" => Ok(resp(200, b"{\"status\":\"Pulling\"}\n{\"error\":\"pull access denied for ghcr.io/org/devbox\"}\n")), + _ => unreachable!(), + }, + |_| {}, + ) + .unwrap_err(); + assert_eq!(err.to_string(), "pull access denied for ghcr.io/org/devbox"); + + // 3. Non-2xx pull HTTP error is surfaced. + let err = ensure_machine_image_with( + &image, + |method, _, _| match method { + "GET" => Ok(resp(404, br#"{"message":"No such image"}"#)), + "POST" => Ok(resp(400, br#"{"message":"invalid image reference"}"#)), + _ => unreachable!(), + }, + |_| {}, + ) + .unwrap_err(); + assert_eq!(err.to_string(), "invalid image reference"); + + // 4. Transport error on GET fails immediately without pulling. + let mut pull_called = false; + let err = ensure_machine_image_with( + &image, + |method, _, _| { + assert_eq!(method, "GET"); + Err(io::Error::new(io::ErrorKind::ConnectionRefused, "daemon gone")) + }, + |_| pull_called = true, + ) + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::ConnectionRefused); + assert!(!pull_called); + + // 5. Unexpected non-404 status on GET fails without attempting to pull. + let err = ensure_machine_image_with( + &image, + |method, _, _| { + assert_eq!(method, "GET"); + Ok(resp(500, br#"{"message":"image store unreadable"}"#)) + }, + |_| pull_called = true, + ) + .unwrap_err(); + assert_eq!(err.to_string(), "image store unreadable"); + assert!(!pull_called); + } + + #[test] + fn systemd_create_body_sets_exec_tmpfs_and_systemd_options() { + let sd = create_body_for("dev", "ubuntu:24.04", "alice", 1000, 1000, true); + assert_eq!(sd["Image"], "ubuntu:24.04"); + assert_eq!(sd["Hostname"], "dev"); + assert_eq!(sd["Labels"], json!({LABEL: "dev"})); + assert_eq!(sd["StopSignal"], "SIGRTMIN+3"); + assert_eq!(sd["Env"], json!(["container=docker"])); + assert_eq!(sd["HostConfig"]["Privileged"], true); + assert_eq!(sd["HostConfig"]["Tmpfs"], json!({"/run": "exec", "/run/lock": "", "/tmp": "exec"})); + assert_eq!(sd["HostConfig"]["Binds"], json!([format!("{HOMES}:{HOMES}")])); + assert_eq!(sd["HostConfig"]["CapAdd"], json!(["NET_ADMIN", "SYS_PTRACE"])); + assert!(sd["Cmd"][2].as_str().unwrap().contains("/lib/systemd/systemd")); + + let plain = create_body_for("dev", "ubuntu:24.04", "alice", 1000, 1000, false); + assert!(plain["StopSignal"].is_null()); + assert!(plain["Env"].is_null()); + assert!(plain["HostConfig"]["Privileged"].is_null()); + assert!(plain["HostConfig"]["Tmpfs"].is_null()); + assert!(plain["Cmd"][2].as_str().unwrap().contains("sleep 3600")); + } + + #[test] + fn create_with_rejects_invalid_names_before_talking_to_daemon() { + for bad in ["", "-leading", "bad_name!", "with space"] { + let err = create_with( + bad, + "ubuntu", + false, + ("alice", 1000, 1000), + |_, _, _| panic!("daemon must not be called for invalid name {bad:?}"), + |_, _| panic!("exec must not be called"), + |_| panic!("pull must not be called"), + ) + .unwrap_err(); + assert_eq!(err.to_string(), "a machine name is letters, digits and dashes"); + } + } + + #[test] + fn wants_help_stops_at_double_dash_for_shell_commands() { + let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::>(); + assert!(super::wants_help(&s(&["--help"]))); + assert!(super::wants_help(&s(&["-h"]))); + assert!(super::wants_help(&s(&["help"]))); + assert!(super::wants_help(&s(&["create", "--help"]))); + assert!(super::wants_help(&s(&["shell", "--help"]))); + assert!(super::wants_help(&s(&["shell", "dev", "-h"]))); + assert!(!super::wants_help(&s(&["shell", "dev", "--", "ls", "--help"]))); + assert!(!super::wants_help(&s(&["shell", "dev", "--", "-h"]))); + assert!(!super::wants_help(&s(&[]))); + } + + #[test] + fn list_json_has_each_machines_name_image_and_state() { + let rows = json!([{"Labels": {(super::LABEL): "dev"}, "Image": "ubuntu:24.04", "State": "running", "Status": "Up 2 hours"}]); + assert_eq!(super::list_json(&rows), json!([{"name": "dev", "image": "ubuntu:24.04", "state": "running", "status": "Up 2 hours"}])); + assert_eq!(super::list_json(&json!([])), json!([])); + } +} diff --git a/crates/kiri/src/main.rs b/crates/kiri/src/main.rs index 69bea5477..7ca1dea45 100644 --- a/crates/kiri/src/main.rs +++ b/crates/kiri/src/main.rs @@ -1,5 +1,9 @@ //! The `kiri` command. +// Share's roots, aliased at the crate root so its crate::roots::trusted() +// resolves; kiri-win mounts the same file by #[path] instead. +#[cfg(any(unix, windows))] +use kiri_image::roots; use std::process::ExitCode; #[cfg(target_os = "macos")] @@ -9,7 +13,7 @@ mod boot; // builds, cli_pins, scan and tools on Linux too: the daemon reads an // image's layers and scans it for kiri-win, whose window can't reach the // store inside WSL (daemon/api.rs). -#[cfg(unix)] +#[cfg(any(unix, windows))] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod builds; // The engine stops when its app is deleted under it (kiri-win includes it @@ -17,7 +21,7 @@ mod builds; #[cfg(unix)] mod appwatch; // Which builder plain `docker build` uses: Docker's or Kiri's. -#[cfg(unix)] +#[cfg(any(unix, windows))] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod buildwith; // Linux only, but its tests run anywhere with unix sockets. @@ -29,24 +33,43 @@ mod bridge; mod hostrelay; #[cfg(unix)] mod cli_pins; -#[cfg(unix)] +#[cfg(any(unix, windows))] mod client; #[cfg(unix)] mod daemon; +#[cfg(windows)] +#[path = "daemon/time.rs"] +#[allow(dead_code)] +mod daemon_time; +#[cfg(windows)] +mod daemon { + pub(crate) use super::daemon_time as time; +} #[cfg(unix)] mod diag; #[cfg(any(unix, windows))] mod docker; +#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window"), windows, test))] +#[cfg_attr(not(any(target_os = "macos", all(target_os = "linux", feature = "window"))), allow(dead_code))] +mod dockerctx; +// `kiri doctor`: whether this installation works (Windows: docker here, the engine in WSL). +#[cfg(any(unix, windows))] +mod doctor; +// `kiri engine`: start, stop, restart and inspect Kiri's engine (#983). +#[cfg(any(unix, windows))] +mod engine_cli; // `kiri domains`: the container-domain routers' ports (Windows: in WSL). #[cfg(unix)] mod domains_cli; mod flavor; +#[cfg(unix)] mod images; #[cfg(unix)] mod guest; #[cfg(target_os = "linux")] mod hostaccess; -#[cfg(target_os = "macos")] +#[cfg(any(target_os = "macos", windows))] +#[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod import; #[cfg(unix)] mod k8s; @@ -62,13 +85,22 @@ mod run; #[cfg(unix)] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod scan; +// `kiri scan`: vulnerability scanning from the terminal (Windows: in WSL). +#[cfg(unix)] +mod scan_cli; #[cfg(target_os = "macos")] mod setup; +#[cfg(any(windows, test))] +mod setup_win; #[cfg(unix)] mod usb; #[cfg(unix)] mod stale; -#[cfg(windows)] +#[cfg(unix)] +mod storage_cli; +#[cfg(target_os = "macos")] +mod vm_cli; +#[cfg(any(windows, test))] mod wsl; #[cfg(any(unix, windows))] mod share; @@ -77,132 +109,422 @@ mod ui; #[cfg(unix)] #[cfg_attr(not(target_os = "macos"), allow(dead_code))] mod tools; -#[cfg(target_os = "macos")] +#[cfg(any(target_os = "macos", target_os = "linux"))] mod update; -const USAGE: &str = "\ -usage: kiri COMMAND docker's commands, on Kiri: kiri run, ps, exec, - logs, stop, rm, images, pull, build, compose… - kiri start start Kiri after a Stop (the window's Start) - kiri daemon - kiri bridge [--socket PATH] (WSL2: the end of kiri-win.exe) - kiri ui [--start] [--view containers|images|volumes|networks] - kiri setup [--use] [--no-agent] | kiri setup --uninstall - kiri build-with [docker|kiri] which builder docker build uses - kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports - kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors - kiri update [--check] update Kiri (with a container: docker's update) - kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [-n N] - kiri diag report [--out PATH] [--send] (a file to send us, tokens taken out) - kiri PORT [NAME] share a local port on the internet (same as kiri share PORT) - kiri share PORT|CONTAINER [--name N] | share login | logout | status - kiri k8s start [--use] | stop | status | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] - kiri usb [list] | attach DEVICE | detach DEVICE USB devices for containers, beta (Mac: pass through to the VM) - kiri machine create NAME [--distro D] | list | shell NAME | stop | delete NAME - kiri import [orbstack | desktop-linux] [--list | [--force] [image|volume|container NAME]] - kiri bench [--runs N] [--image IMAGE] [--network none|bridge] - kiri boot [--console] [--pings N] - kiri raw run [--rm] [-e KEY=VALUE]... IMAGE [COMMAND...] (its own guest, no daemon) - kiri raw pull | raw images | raw rmi ..."; +const USAGE_LINES: &[&str] = &[ + "usage: kiri COMMAND docker's commands, on Kiri: kiri run, ps, exec,", + " logs, stop, rm, images, pull, build, compose…", + " kiri start start Kiri after a Stop (the window's Start)", + " kiri engine start | stop | restart | status [--json] start, stop, restart or inspect Kiri's engine", + #[cfg(unix)] + " kiri daemon", + #[cfg(target_os = "linux")] + " kiri bridge [--socket PATH] (WSL2: the end of kiri-win.exe)", + #[cfg(any(target_os = "macos", target_os = "linux"))] + " kiri ui [--start] [--view containers|images|volumes|networks|builds]", + #[cfg(target_os = "macos")] + " kiri setup [--use] [--no-agent] [--no-profiles] | kiri setup --uninstall", + #[cfg(windows)] + " kiri setup [--use] ensure Kiri's docker context and CLI plugins in ~/.docker", + #[cfg(any(unix, windows))] + " kiri build-with [docker|kiri|status] which builder docker build uses", + " kiri domains [set [--http N] [--https N] | reset] the *.kiri.local routers' ports", + " kiri storage [status | reclaim] storage location, disk usage, and reclaiming VM disk space", + " kiri registry [insecure|mirror] [list | add X... | remove X...] daemon.json's insecure registries and Docker Hub mirrors", + " kiri scan [--json] [--history] known vulnerabilities in an image, found by Grype", + #[cfg(target_os = "macos")] + " kiri update [--check] update Kiri (with a container: docker's update)", + #[cfg(target_os = "linux")] + " kiri update --check check for a newer Kiri (with a container: docker's update)", + " kiri doctor [--json] whether Kiri works here, and what to run when a part doesn't", + " kiri diag logs [-f] [--ui|--engine|--cli] [--errors] [-n N]", + " kiri diag report [--out PATH] [--send] (a file to send us, tokens taken out)", + " kiri PORT [NAME] share a local port on the internet (same as kiri share PORT)", + " kiri share PORT|CONTAINER [--name N] | share login | logout | status", + " kiri k8s start [--use] | stop | status | delete | set [--lan on|off] [--tls-san NAME,…] [--port N] [--version TAG|default] [--k3s-arg ARG]… [--clear-k3s-args]", + " kiri usb [list] | attach DEVICE | detach DEVICE USB devices for containers, beta (Mac: pass through to the VM)", + " kiri machine create NAME [--distro D] | list | shell NAME | stop | delete NAME", + #[cfg(target_os = "macos")] + " kiri vm [status | set --shared-nat on|off] VM networking (off avoids macOS InternetSharing)", + #[cfg(target_os = "macos")] + " kiri import [orbstack | desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]", + #[cfg(windows)] + " kiri import [desktop-linux] [--images] [--volumes] [--containers] [--list | [--force] [image|volume|container NAME]]", + #[cfg(target_os = "macos")] + " kiri bench [--runs N] [--image IMAGE] [--network none|bridge]", + #[cfg(target_os = "macos")] + " kiri boot [--console] [--pings N]", + #[cfg(unix)] + " kiri raw run [--rm] [-e KEY=VALUE]... IMAGE [COMMAND...] (its own guest, no daemon)", + #[cfg(unix)] + " kiri raw pull | raw images | raw rmi ...", +]; + +fn usage() -> String { + USAGE_LINES.join("\n") +} + +#[cfg(any(windows, test))] +const WINDOWS_DAEMON_ERROR: &str = "on Windows, Kiri's engine runs in WSL without `kiri daemon`: run `kiri start` or open Kiri"; + +const START_USAGE: &str = "usage: kiri start start Kiri after a Stop (the window's Start)"; +#[cfg(unix)] +const DAEMON_USAGE: &str = "usage: kiri daemon"; +#[cfg(unix)] +const RAW_USAGE: &str = "usage: kiri raw run [--rm] [-e KEY=VALUE]... [-u USER] [-w DIR] [--timings] IMAGE [COMMAND...]\n kiri raw pull | raw images | raw rmi ..."; +#[cfg(any(target_os = "macos", target_os = "linux", test))] +const UI_USAGE: &str = "usage: kiri ui [--start] [--view containers|images|volumes|networks|builds]"; + +#[cfg(any(target_os = "macos", target_os = "linux", test))] +fn parse_ui_args(rest: &[String]) -> std::io::Result)>> { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + return Ok(None); + } + let mut start = false; + let mut view = None; + let mut it = rest.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--start" => start = true, + "--view" => { + let v = it + .next() + .filter(|s| !s.is_empty() && !s.starts_with('-')) + .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, UI_USAGE))?; + view = Some(v.clone()); + } + _ => return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, UI_USAGE)), + } + } + Ok(Some((start, view))) +} + +#[derive(Debug, PartialEq, Eq)] +enum Command<'a> { + Help, + Version, + Daemon(&'a [String]), + #[cfg(target_os = "linux")] + Bridge(&'a [String]), + #[cfg(target_os = "linux")] + HostRelay(&'a [String]), + #[cfg(target_os = "linux")] + HostAccess(&'a [String]), + #[cfg(unix)] + RawHelp, + #[cfg(unix)] + RawInvalid, + #[cfg(unix)] + RawRun(&'a [String]), + #[cfg(unix)] + RawPull(&'a [String]), + #[cfg(unix)] + RawImages(&'a [String]), + #[cfg(unix)] + RawRmi(&'a [String]), + #[cfg(target_os = "macos")] + Bench(&'a [String]), + #[cfg(target_os = "macos")] + Boot(&'a [String]), + #[cfg(any(target_os = "macos", windows))] + Setup(&'a [String]), + #[cfg(any(unix, windows))] + Share(&'a [String]), + Start(&'a [String]), + #[cfg(any(unix, windows))] + Engine(&'a [String]), + #[cfg(any(unix, windows))] + BuildWith(&'a [String]), + #[cfg(unix)] + Domains(&'a [String]), + #[cfg(any(unix, windows))] + Doctor(&'a [String]), + #[cfg(unix)] + Storage(&'a [String]), + #[cfg(unix)] + Registry(&'a [String]), + #[cfg(unix)] + Scan(&'a [String]), + #[cfg(unix)] + K8s(&'a [String]), + #[cfg(unix)] + Machine(&'a [String]), + #[cfg(unix)] + Usb(&'a [String]), + #[cfg(any(target_os = "macos", windows))] + Import(&'a [String]), + #[cfg(target_os = "macos")] + Vm(&'a [String]), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Update(&'a [String]), + #[cfg(unix)] + Diag(&'a [String]), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Ui(&'a [String]), + #[cfg(any(unix, windows))] + Docker(&'a [String]), + #[cfg(windows)] + Wsl(&'a [String]), +} + +impl<'a> Command<'a> { + fn parse(args: &'a [String]) -> Option> { + match args.first().map(String::as_str) { + Some("-h" | "--help" | "help") => Some(Command::Help), + Some("--version" | "-V" | "-v") if args.len() == 1 => Some(Command::Version), + Some("daemon") => Some(Command::Daemon(&args[1..])), + #[cfg(target_os = "linux")] + Some("bridge") => Some(Command::Bridge(&args[1..])), + #[cfg(target_os = "linux")] + Some("hostrelay") => Some(Command::HostRelay(&args[1..])), + #[cfg(target_os = "linux")] + Some("host-access") => Some(Command::HostAccess(&args[1..])), + #[cfg(unix)] + Some("raw") => match args.get(1).map(String::as_str) { + Some("run") => Some(Command::RawRun(&args[2..])), + Some("pull") => Some(Command::RawPull(&args[2..])), + Some("images") => Some(Command::RawImages(&args[2..])), + Some("rmi") => Some(Command::RawRmi(&args[2..])), + Some("-h" | "--help" | "help") => Some(Command::RawHelp), + _ => Some(Command::RawInvalid), + }, + #[cfg(target_os = "macos")] + Some("bench") => Some(Command::Bench(&args[1..])), + #[cfg(target_os = "macos")] + Some("boot") => Some(Command::Boot(&args[1..])), + #[cfg(any(target_os = "macos", windows))] + Some("setup") => Some(Command::Setup(&args[1..])), + #[cfg(any(unix, windows))] + Some("share") => Some(Command::Share(&args[1..])), + // `kiri 3000`: share a port straight away. + #[cfg(any(unix, windows))] + Some(a) if share::is_shorthand(a) => Some(Command::Share(args)), + // Bare (or `-h`/`--help`): the window's Start (`kiri start NAME` is docker's start). + #[cfg(unix)] + Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(&args[1..])), + // On Windows, by the `kiri` in WSL, once kiri-start has the daemon up. + #[cfg(windows)] + Some("start") if args[1..].iter().all(|a| matches!(a.as_str(), "-h" | "--help")) => Some(Command::Start(args)), + #[cfg(any(unix, windows))] + Some("engine") => Some(Command::Engine(&args[1..])), + #[cfg(any(unix, windows))] + Some("build-with") => Some(Command::BuildWith(&args[1..])), + #[cfg(unix)] + Some("domains") => Some(Command::Domains(&args[1..])), + #[cfg(any(unix, windows))] + Some("doctor") => Some(Command::Doctor(&args[1..])), + #[cfg(unix)] + Some("storage") => Some(Command::Storage(&args[1..])), + #[cfg(unix)] + Some("registry") => Some(Command::Registry(&args[1..])), + #[cfg(unix)] + Some("scan") => Some(Command::Scan(&args[1..])), + #[cfg(unix)] + Some("k8s") => Some(Command::K8s(&args[1..])), + #[cfg(unix)] + Some("machine") => Some(Command::Machine(&args[1..])), + #[cfg(unix)] + Some("usb") => Some(Command::Usb(&args[1..])), + #[cfg(any(target_os = "macos", windows))] + Some("import") => Some(Command::Import(&args[1..])), + #[cfg(target_os = "macos")] + Some("vm") => Some(Command::Vm(&args[1..])), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Some("update") if !docker::is_container_update(&args[1..]) => Some(Command::Update(&args[1..])), + #[cfg(unix)] + Some("diag") => Some(Command::Diag(&args[1..])), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Some("ui") => Some(Command::Ui(args)), + #[cfg(any(unix, windows))] + Some(c) if docker::handles(c) => Some(Command::Docker(args)), + // Windows: the engine's commands, by the `kiri` in WSL. + #[cfg(windows)] + Some(c) if wsl::COMMANDS.contains(&c) => Some(Command::Wsl(args)), + _ => None, + } + } +} fn main() -> ExitCode { flavor::init(); let args: Vec = std::env::args().skip(1).collect(); + let parsed = Command::parse(&args); + match parsed { + Some(Command::Help) => { + println!("{}", usage()); + return ExitCode::SUCCESS; + } + Some(Command::Version) => { + println!("kiri {}", env!("CARGO_PKG_VERSION")); + return ExitCode::SUCCESS; + } + _ => {} + } // Which process this is, for its log and crash reports. #[cfg(unix)] - diag::init(match args.first().map(String::as_str) { - Some("daemon") => diag::Part::Daemon, - // Only a build with the window: elsewhere `kiri ui` is a plain - // command whose message must reach the terminal, not the log's pipe. - #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some("ui") => diag::Part::Ui, - #[cfg(target_os = "macos")] - None if setup::launched_from_app() => diag::Part::Ui, - _ => diag::Part::Cli, - }); - let result: std::io::Result<()> = match args.first().map(String::as_str) { + { + let asking_help = args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.get(1).map(String::as_str), Some("help")); + diag::init(match args.first().map(String::as_str) { + Some("daemon") if !asking_help && args.len() == 1 => diag::Part::Daemon, + // Only a build with the window: elsewhere `kiri ui` is a plain + // command whose message must reach the terminal, not the log's pipe. + #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] + Some("ui") if !asking_help => diag::Part::Ui, + #[cfg(target_os = "macos")] + None if setup::launched_from_app() => diag::Part::Ui, + _ => diag::Part::Cli, + }); + } + let result: std::io::Result<()> = match parsed { + Some(Command::Help | Command::Version) => unreachable!(), #[cfg(unix)] - Some("daemon") => daemon::run(&args[1..]), + Some(Command::Daemon(rest)) => { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{DAEMON_USAGE}"); + Ok(()) + } else if !rest.is_empty() { + Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, DAEMON_USAGE)) + } else { + daemon::run(rest) + } + } + #[cfg(windows)] + Some(Command::Daemon(rest)) => { + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{START_USAGE}"); + Ok(()) + } else { + Err(std::io::Error::other(WINDOWS_DAEMON_ERROR)) + } + } #[cfg(target_os = "linux")] - Some("bridge") => bridge::run(&args[1..]), + Some(Command::Bridge(rest)) => bridge::run(rest), #[cfg(target_os = "linux")] - Some("hostrelay") => hostrelay::run(), + Some(Command::HostRelay(rest)) => { + const HOSTRELAY_USAGE: &str = "usage: kiri hostrelay"; + if rest.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(rest.first().map(String::as_str), Some("help")) + { + println!("{HOSTRELAY_USAGE}"); + Ok(()) + } else if !rest.is_empty() { + Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, HOSTRELAY_USAGE)) + } else { + hostrelay::run() + } + } // Linux hosts: what the window's onboarding needs root for (through pkexec). #[cfg(target_os = "linux")] - Some("host-access") => match hostaccess::run(&args[1..]) { + Some(Command::HostAccess(rest)) => match hostaccess::run(rest) { Ok(code) => return ExitCode::from(code), Err(e) => Err(e), }, #[cfg(unix)] - Some("raw") => match args.get(1).map(String::as_str) { - Some("run") => run::run(&args[2..]), - Some("pull") => images::pull(&args[2..]), - Some("images") => images::list(&args[2..]), - Some("rmi") => images::remove(&args[2..]), - _ => { - eprintln!("{USAGE}"); - return ExitCode::FAILURE; - } - }, + Some(Command::RawHelp) => { + println!("{RAW_USAGE}"); + Ok(()) + } + #[cfg(unix)] + Some(Command::RawInvalid) => Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, RAW_USAGE)), + #[cfg(unix)] + Some(Command::RawRun(rest)) => run::run(rest), + #[cfg(unix)] + Some(Command::RawPull(rest)) => images::pull(rest), + #[cfg(unix)] + Some(Command::RawImages(rest)) => images::list(rest), + #[cfg(unix)] + Some(Command::RawRmi(rest)) => images::remove(rest), #[cfg(target_os = "macos")] - Some("bench") => bench::run(&args[1..]), + Some(Command::Bench(rest)) => bench::run(rest), #[cfg(target_os = "macos")] - Some("boot") => boot::run(&args[1..]), + Some(Command::Boot(rest)) => boot::run(rest), #[cfg(target_os = "macos")] - Some("setup") => setup::run(&args[1..]), - #[cfg(any(unix, windows))] - Some("share") => share::run(&args[1..]), - // `kiri 3000`: share a port straight away. + Some(Command::Setup(rest)) => setup::run(rest), + #[cfg(windows)] + Some(Command::Setup(rest)) => setup_win::run(rest), #[cfg(any(unix, windows))] - Some(a) if share::is_shorthand(a) => share::run(&args), - // Bare: the window's Start (`kiri start NAME` is docker's start). + Some(Command::Share(rest)) => share::run(rest), #[cfg(unix)] - Some("start") if args.len() == 1 => engine_start(), - // On Windows, by the `kiri` in WSL, once kiri-start has the daemon up. + Some(Command::Start(rest)) => { + if !rest.is_empty() { + println!("{START_USAGE}"); + Ok(()) + } else { + engine_cli::start_legacy() + } + } #[cfg(windows)] - Some("start") if args.len() == 1 => wsl::run(&args), + Some(Command::Start(all)) => wsl::run(all), + #[cfg(any(unix, windows))] + Some(Command::Engine(rest)) => engine_cli::run(rest), + #[cfg(any(unix, windows))] + Some(Command::BuildWith(rest)) => buildwith::cli(rest), #[cfg(unix)] - Some("build-with") => buildwith::cli(&args[1..]), + Some(Command::Domains(rest)) => domains_cli::run(rest), + #[cfg(any(unix, windows))] + Some(Command::Doctor(rest)) => doctor::run(rest), #[cfg(unix)] - Some("domains") => domains_cli::run(&args[1..]), + Some(Command::Storage(rest)) => storage_cli::run(rest), #[cfg(unix)] - Some("registry") => registry_cli::run(&args[1..]), + Some(Command::Registry(rest)) => registry_cli::run(rest), #[cfg(unix)] - Some("k8s") => k8s::run(&args[1..]), + Some(Command::Scan(rest)) => scan_cli::run(rest), #[cfg(unix)] - Some("machine") => machine::run(&args[1..]), + Some(Command::K8s(rest)) => k8s::run(rest), #[cfg(unix)] - Some("usb") => usb::run(&args[1..]), - #[cfg(target_os = "macos")] - Some("import") => import::run(&args[1..]), - #[cfg(target_os = "macos")] - Some("update") if !docker::is_container_update(&args[1..]) => update::run(&args[1..]), + Some(Command::Machine(rest)) => machine::run(rest), #[cfg(unix)] - Some("diag") => diag::run(&args[1..]), - // Opening Kiri.app: set up on first launch, then the window. + Some(Command::Usb(rest)) => usb::run(rest), + #[cfg(any(target_os = "macos", windows))] + Some(Command::Import(rest)) => import::run(rest), #[cfg(target_os = "macos")] - None if setup::launched_from_app() => { - setup::first_launch(); - ui::run(true, None) - } + Some(Command::Vm(rest)) => vm_cli::run(rest), + #[cfg(any(target_os = "macos", target_os = "linux"))] + Some(Command::Update(rest)) => update::run(rest), + #[cfg(unix)] + Some(Command::Diag(rest)) => diag::run(rest), #[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))] - Some("ui") => ui::run( - args.iter().any(|a| a == "--start"), - args.iter().position(|a| a == "--view").and_then(|i| args.get(i + 1)).cloned(), - ), + Some(Command::Ui(all)) => match parse_ui_args(&all[1..]) { + Ok(None) => { + println!("{UI_USAGE}"); + Ok(()) + } + Ok(Some((start, view))) => ui::run(start, view), + Err(e) => Err(e), + }, // The static engine has no window: the package's own build of it. #[cfg(all(target_os = "linux", not(feature = "window")))] - Some("ui") => window(&args), + Some(Command::Ui(all)) => match parse_ui_args(&all[1..]) { + Ok(None) => { + println!("{UI_USAGE}"); + Ok(()) + } + Ok(Some(_)) => window(all), + Err(e) => Err(e), + }, #[cfg(any(unix, windows))] - Some(c) if docker::handles(c) => { + Some(Command::Docker(all)) => { engine_version_check(); - docker::run(&args) + docker::run(all) } - // Windows: the engine's commands, by the `kiri` in WSL. #[cfg(windows)] - Some(c) if wsl::COMMANDS.contains(&c) => wsl::run(&args), - _ => { - eprintln!("{USAGE}"); + Some(Command::Wsl(all)) => wsl::run(all), + // Opening Kiri.app: set up on first launch, then the window. + #[cfg(target_os = "macos")] + None if args.is_empty() && setup::launched_from_app() => { + setup::first_launch(); + ui::run(true, None) + } + None => { + eprintln!("{}", usage()); return ExitCode::FAILURE; } }; @@ -240,23 +562,6 @@ fn window(args: &[String]) -> std::io::Result<()> { Err(std::process::Command::new(WINDOW).args(args).exec()) } -/// `kiri start`: Kiri on again after a Stop (the window's, the tray's or -/// the menu bar's), as the window's Start does; the containers Stop held -/// come back. On an engine that wasn't stopped it only wakes the VM. -#[cfg(unix)] -fn engine_start() -> std::io::Result<()> { - if !client::alive() { - return Err(std::io::Error::other("Kiri's engine isn't running. Open Kiri, or start it with `kiri daemon`")); - } - let r = client::request("POST", "/kiri/wake", None)?; - // 404: a Linux host's engine, which has no VM to wake and no Stop. - if !r.ok() && r.status != 404 { - return Err(std::io::Error::other(r.error())); - } - println!("Kiri is started"); - Ok(()) -} - #[cfg(not(unix))] fn engine_version_check() {} @@ -275,3 +580,321 @@ fn engine_version_check() { eprintln!("kiri: this kiri ({exe}) is {me}, but the engine runs {engine}. Restart the engine to use one version (Kiri → Restart engine), or remove the older kiri."); } } + +#[cfg(test)] +mod tests { + use super::{Command, usage}; + + fn parse(words: &[&str]) -> Option> { + let args: Vec = words.iter().map(|s| (*s).to_owned()).collect(); + Command::parse(&args)?; + Some(args) + } + + fn advertised_subcommands(help: &str) -> Vec<&str> { + help.lines() + .filter_map(|line| line.strip_prefix("usage: ").unwrap_or(line).trim_start().strip_prefix("kiri ")) + .filter_map(|rest| rest.split_whitespace().next()) + .collect() + } + + #[test] + fn usage_lists_scan_command() { + let help = usage(); + assert!(help.contains("kiri scan [--json] [--history] ")); + assert!(!help.ends_with('\n')); + } + + #[test] + fn usage_lists_only_commands_for_this_os() { + let help = usage(); + let cmds = advertised_subcommands(&help); + for common in ["COMMAND", "start", "engine", "doctor", "domains", "storage", "registry", "scan", "diag", "PORT", "share", "k8s", "usb", "machine"] { + assert!(cmds.contains(&common), "help missing `{common}`:\n{help}"); + } + assert!(help.contains("kiri storage [status | reclaim]"), "help missing `kiri storage`:\n{help}"); + #[cfg(unix)] + { + for unix_cmd in ["daemon", "ui", "build-with", "update", "raw"] { + assert!(cmds.contains(&unix_cmd), "unix help missing `{unix_cmd}`:\n{help}"); + } + assert!( + help.contains("kiri ui [--start] [--view containers|images|volumes|networks|builds]"), + "unix help missing `kiri ui` views (including builds):\n{help}" + ); + } + #[cfg(target_os = "macos")] + { + for mac_cmd in ["setup", "update", "vm", "import", "bench", "boot"] { + assert!(cmds.contains(&mac_cmd), "macOS help missing `{mac_cmd}`:\n{help}"); + } + assert!( + help.contains("kiri setup [--use] [--no-agent] [--no-profiles] | kiri setup --uninstall"), + "macOS help missing `kiri setup` flags:\n{help}" + ); + assert!(help.contains("kiri update [--check]"), "macOS help missing `kiri update [--check]`:\n{help}"); + assert!(!cmds.contains(&"bridge"), "macOS help must not list Linux-only `bridge`:\n{help}"); + } + #[cfg(target_os = "linux")] + { + assert!(cmds.contains(&"bridge"), "Linux help missing `bridge`:\n{help}"); + assert!(cmds.contains(&"update"), "Linux help missing `update`:\n{help}"); + assert!(help.contains("kiri update --check"), "Linux help missing `kiri update --check`:\n{help}"); + assert!(!help.contains("kiri update [--check]"), "Linux help must not list macOS `kiri update [--check]`:\n{help}"); + for mac_cmd in ["setup", "vm", "import", "bench", "boot"] { + assert!(!cmds.contains(&mac_cmd), "Linux help must not list macOS-only `{mac_cmd}`:\n{help}"); + } + } + #[cfg(windows)] + { + for win_cmd in ["setup", "build-with", "import"] { + assert!(cmds.contains(&win_cmd), "Windows help missing `{win_cmd}`:\n{help}"); + } + assert!( + help.contains("kiri import [desktop-linux] [--images] [--volumes] [--containers]"), + "Windows help missing `kiri import [desktop-linux] [--images] [--volumes] [--containers]`:\n{help}" + ); + for unix_or_mac in ["daemon", "bridge", "ui", "update", "vm", "bench", "boot", "raw"] { + assert!(!cmds.contains(&unix_or_mac), "Windows help must not list `{unix_or_mac}`:\n{help}"); + } + } + } + + #[test] + fn every_advertised_command_dispatches_in_main() { + let help = usage(); + let mut count = 0; + for line in help.lines() { + let Some(rest) = line.strip_prefix("usage: ").unwrap_or(line).trim_start().strip_prefix("kiri ") else { + continue; + }; + let mut words = rest.split_whitespace(); + let subcmd = words.next().expect("subcommand after `kiri `"); + count += 1; + match subcmd { + "COMMAND" => { + let args = ["run".to_owned()]; + assert!(matches!(Command::parse(&args), Some(Command::Docker(_)))); + } + "PORT" => { + let args = ["3000".to_owned()]; + assert!(matches!(Command::parse(&args), Some(Command::Share(_)))); + } + "raw" => { + for part in rest.split('|') { + let mut p = part.split_whitespace(); + if p.next() == Some("raw") { + let verb = p.next().expect("verb after `raw`"); + let args = ["raw".to_owned(), verb.to_owned()]; + let parsed = Command::parse(&args); + assert!( + parsed.is_some() && !matches!(parsed, Some(Command::Docker(_))), + "`kiri raw {verb}` advertised in usage has no dispatch arm in main" + ); + } + } + } + other => { + let args = [other.to_owned()]; + let parsed = Command::parse(&args); + assert!( + parsed.is_some() && !matches!(parsed, Some(Command::Docker(_))), + "`kiri {other}` advertised in usage has no dispatch arm in main" + ); + } + } + } + assert!(count > 0); + for h in ["--help", "-h", "help"] { + assert_eq!(Command::parse(&[h.to_owned()]), Some(Command::Help), "{h}"); + } + for v in ["--version", "-V", "-v"] { + assert_eq!(Command::parse(&[v.to_owned()]), Some(Command::Version), "{v}"); + } + // `kiri version` (without leading dash) remains Docker's `version` passthrough. + assert!(matches!(Command::parse(&["version".to_owned()]), Some(Command::Docker(_)))); + // `kiri start --help` / `-h` dispatches to Kiri's Start, while `kiri start web --help` stays Docker's. + assert!(matches!(Command::parse(&["start".to_owned(), "--help".to_owned()]), Some(Command::Start(_)))); + assert!(matches!(Command::parse(&["start".to_owned(), "-h".to_owned()]), Some(Command::Start(_)))); + assert!(matches!(Command::parse(&["engine".to_owned(), "status".to_owned()]), Some(Command::Engine(_)))); + assert!(matches!(Command::parse(&["engine".to_owned(), "--help".to_owned()]), Some(Command::Engine(_)))); + assert!(matches!(Command::parse(&["start".to_owned(), "web".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); + assert!(matches!(Command::parse(&["run".to_owned(), "alpine".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); + assert!(matches!(Command::parse(&["ps".to_owned(), "--help".to_owned()]), Some(Command::Docker(_)))); + + #[cfg(unix)] + { + assert_eq!(Command::parse(&["raw".to_owned(), "--help".to_owned()]), Some(Command::RawHelp)); + assert_eq!(Command::parse(&["raw".to_owned(), "-h".to_owned()]), Some(Command::RawHelp)); + assert_eq!(Command::parse(&["raw".to_owned()]), Some(Command::RawInvalid)); + } + + #[cfg(any(target_os = "macos", target_os = "linux"))] + for args in [ + vec!["update".to_owned()], + vec!["update".to_owned(), "--check".to_owned()], + vec!["update".to_owned(), "--help".to_owned()], + vec!["update".to_owned(), "-h".to_owned()], + ] { + assert!(matches!(Command::parse(&args), Some(Command::Update(_))), "expected Command::Update for {args:?}"); + } + let container_update = ["update".to_owned(), "--memory".to_owned(), "256m".to_owned(), "web".to_owned()]; + assert!(matches!(Command::parse(&container_update), Some(Command::Docker(_)))); + #[cfg(target_os = "macos")] + assert!(parse(&["bridge"]).is_none()); + #[cfg(target_os = "linux")] + for mac_cmd in ["setup", "vm", "import", "bench", "boot"] { + assert!(parse(&[mac_cmd]).is_none(), "`kiri {mac_cmd}` should not dispatch on Linux"); + } + #[cfg(windows)] + { + for unix_cmd in ["bridge", "ui", "vm", "bench", "boot", "raw"] { + assert!(parse(&[unix_cmd]).is_none(), "`kiri {unix_cmd}` should not dispatch on Windows"); + } + for win_cmd in ["setup", "build-with", "import"] { + assert!(parse(&[win_cmd]).is_some(), "`kiri {win_cmd}` must dispatch on Windows"); + } + let daemon_args = ["daemon".to_owned()]; + assert_eq!(Command::parse(&daemon_args), Some(Command::Daemon(&[]))); + } + assert_eq!( + super::WINDOWS_DAEMON_ERROR, + "on Windows, Kiri's engine runs in WSL without `kiri daemon`: run `kiri start` or open Kiri" + ); + } + + #[test] + fn parse_ui_args_handles_help_views_and_invalid_flags() { + let s = |v: &[&str]| v.iter().map(|x| (*x).to_owned()).collect::>(); + assert_eq!(super::parse_ui_args(&s(&["--help"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&["-h"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&["--start", "--help"])).unwrap(), None); + assert_eq!(super::parse_ui_args(&s(&[])).unwrap(), Some((false, None))); + assert_eq!( + super::parse_ui_args(&s(&["--start", "--view", "containers"])).unwrap(), + Some((true, Some("containers".into()))) + ); + assert!(super::parse_ui_args(&s(&["--view"])).is_err()); + assert!(super::parse_ui_args(&s(&["--bogus"])).is_err()); + } + + #[test] + fn cli_help_and_version_exit_zero_on_stdout_without_side_effects() { + let Some(bin) = option_env!("CARGO_BIN_EXE_kiri").map(std::path::PathBuf::from).or_else(|| { + // In `cargo test --bin kiri`, the `kiri` binary sits in the parent of `deps/`. + let test_exe = std::env::current_exe().ok()?; + let dir = test_exe.parent()?.parent()?; + let name = if cfg!(windows) { "kiri.exe" } else { "kiri" }; + Some(dir.join(name)).filter(|p| p.is_file()) + }) else { + return; + }; + let run_kiri = |args: &[&str]| { + std::process::Command::new(&bin) + .args(args) + .env("KIRI_SOCKET", "/nonexistent/kiri-test.sock") + .output() + .expect("spawn kiri") + }; + + // Bare `kiri` prints usage to stderr and exits 1. + let bare = run_kiri(&[]); + assert!(!bare.status.success()); + assert!(bare.stdout.is_empty()); + assert!(String::from_utf8_lossy(&bare.stderr).starts_with("usage: kiri COMMAND")); + + // Top-level help flags print usage to stdout and exit 0. + for flag in ["--help", "-h", "help"] { + let out = run_kiri(&[flag]); + assert!(out.status.success(), "`kiri {flag}` failed: {:?}", String::from_utf8_lossy(&out.stderr)); + assert!(out.stderr.is_empty(), "`kiri {flag}` wrote stderr: {:?}", String::from_utf8_lossy(&out.stderr)); + assert_eq!(String::from_utf8_lossy(&out.stdout).trim_end(), usage()); + } + + // Top-level version flags print `kiri ` to stdout and exit 0. + for flag in ["--version", "-V", "-v"] { + let out = run_kiri(&[flag]); + assert!(out.status.success(), "`kiri {flag}` failed"); + assert!(out.stderr.is_empty()); + assert_eq!(String::from_utf8_lossy(&out.stdout), format!("kiri {}\n", env!("CARGO_PKG_VERSION"))); + } + + // Every Kiri subcommand prints usage to stdout and exits 0 on `--help` and `-h` with zero side effects. + let mut subcommands: Vec<&[&str]> = vec![ + &["daemon"], + &["start"], + &["share"], + &["3000"], + &["build-with"], + &["domains"], + &["doctor"], + &["storage"], + &["storage", "reclaim"], + &["registry"], + &["registry", "insecure"], + &["scan"], + &["k8s"], + &["k8s", "set"], + &["machine"], + &["machine", "create"], + &["machine", "shell"], + &["usb"], + &["usb", "attach"], + &["diag"], + &["diag", "logs"], + &["diag", "report"], + ]; + #[cfg(any(target_os = "macos", target_os = "linux"))] + { + subcommands.extend([&["ui"][..], &["update"]]); + } + #[cfg(unix)] + { + subcommands.extend([ + &["raw"][..], + &["raw", "run"], + &["raw", "pull"], + &["raw", "images"], + &["raw", "rmi"], + ]); + } + #[cfg(any(target_os = "macos", windows))] + { + subcommands.extend([&["setup"][..], &["import"]]); + } + #[cfg(target_os = "macos")] + { + subcommands.extend([&["vm"][..], &["vm", "set"], &["bench"], &["boot"]]); + } + #[cfg(target_os = "linux")] + { + subcommands.extend([&["bridge"][..], &["hostrelay"], &["host-access"]]); + } + for sub in subcommands { + for flag in ["--help", "-h"] { + let mut argv: Vec<&str> = sub.to_vec(); + argv.push(flag); + let out = run_kiri(&argv); + assert!( + out.status.success(), + "`kiri {}` exited {:?}, stderr: {}", + argv.join(" "), + out.status.code(), + String::from_utf8_lossy(&out.stderr) + ); + assert!( + out.stderr.is_empty(), + "`kiri {}` wrote unexpected stderr: {}", + argv.join(" "), + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!( + stdout.starts_with("usage: kiri "), + "`kiri {}` stdout did not start with usage: {stdout:?}", + argv.join(" ") + ); + } + } + } +} diff --git a/crates/kiri/src/registry_cli.rs b/crates/kiri/src/registry_cli.rs index 581c1f61f..74432d17d 100644 --- a/crates/kiri/src/registry_cli.rs +++ b/crates/kiri/src/registry_cli.rs @@ -26,7 +26,9 @@ usage: kiri registry both lists and the file th registries without a verified certificate (self-signed or plain HTTP): registry.lan:5000, 10.0.0.0/8 kiri registry mirror [list] | add URL... | remove URL... - Docker Hub mirrors, tried in order before Docker Hub"; + Docker Hub mirrors, tried in order before Docker Hub + --json, with any of them: one line of JSON, the daemon's report for + `kiri registry`, the list itself for the others"; /// Checks an entry and writes it the way daemon.json keeps it. type Check = fn(&str) -> Result; @@ -35,16 +37,20 @@ const INSECURE: &str = "insecure-registries"; const MIRRORS: &str = "registry-mirrors"; pub fn run(args: &[String]) -> io::Result<()> { - let arg = |i: usize| args.get(i).map(String::as_str); - if matches!(arg(0), Some("-h" | "--help" | "help")) { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { println!("{USAGE}"); return Ok(()); } + let json = args.iter().any(|a| a == "--json"); + let args: Vec = args.iter().filter(|a| *a != "--json").cloned().collect(); + let arg = |i: usize| args.get(i).map(String::as_str); if !client::alive() { return Err(io::Error::other("kiri daemon is not running: open Kiri or run `kiri daemon`")); } let (key, check): (&str, Check) = match arg(0) { - None => return show(&client::get("/kiri/registries")?), + None => return show(&client::get("/kiri/registries")?, json), Some("insecure") => (INSECURE, |s| Insecure::parse(s).map(|e| e.as_string())), Some("mirror" | "mirrors") => (MIRRORS, |s| Mirror::parse(s).map(|m| m.as_url())), _ => return Err(io::Error::other(USAGE)), @@ -59,7 +65,7 @@ pub fn run(args: &[String]) -> io::Result<()> { match arg(1) { Some("list" | "ls") | None => { let now = client::get("/kiri/registries")?; - list(key, &strings(&now[key])); + list(key, &strings(&now[key]), json); problems(&now); Ok(()) } @@ -70,7 +76,7 @@ pub fn run(args: &[String]) -> io::Result<()> { now.push(n); } } - save(key, &now) + save(key, &now, json) } Some("remove" | "rm") => { let mut now = strings(&client::get("/kiri/registries")?[key]); @@ -81,7 +87,7 @@ pub fn run(args: &[String]) -> io::Result<()> { return Err(io::Error::other(format!("{n} is not in {key}"))); } } - save(key, &now) + save(key, &now, json) } _ => Err(io::Error::other(USAGE)), } @@ -91,7 +97,11 @@ fn strings(v: &Value) -> Vec { v.as_array().into_iter().flatten().filter_map(|s| s.as_str()).map(str::to_owned).collect() } -fn list(key: &str, entries: &[String]) { +fn list(key: &str, entries: &[String], json: bool) { + if json { + println!("{}", json!(entries)); + return; + } match (key, entries.is_empty()) { (INSECURE, true) => println!("no insecure registries: every registry is reached over verified HTTPS"), (INSECURE, false) => println!("insecure registries (no verified certificate; HTTPS first, then plain HTTP):"), @@ -109,9 +119,13 @@ fn problems(report: &Value) { } } -fn show(report: &Value) -> io::Result<()> { - list(INSECURE, &strings(&report[INSECURE])); - list(MIRRORS, &strings(&report[MIRRORS])); +fn show(report: &Value, json: bool) -> io::Result<()> { + if json { + println!("{report}"); + return Ok(()); + } + list(INSECURE, &strings(&report[INSECURE]), false); + list(MIRRORS, &strings(&report[MIRRORS]), false); if let Some(p) = report["path"].as_str() { println!("in {p}"); } @@ -119,12 +133,12 @@ fn show(report: &Value) -> io::Result<()> { Ok(()) } -fn save(key: &str, entries: &[String]) -> io::Result<()> { +fn save(key: &str, entries: &[String], json: bool) -> io::Result<()> { let r = client::request("POST", "/kiri/registries", Some(&json!({ key: entries })))?; if !r.ok() { return Err(io::Error::other(r.error())); } let now = client::get("/kiri/registries")?; - list(key, &strings(&now[key])); + list(key, &strings(&now[key]), json); Ok(()) } diff --git a/crates/kiri/src/run.rs b/crates/kiri/src/run.rs index e1b5694c8..b86b2a51e 100644 --- a/crates/kiri/src/run.rs +++ b/crates/kiri/src/run.rs @@ -14,7 +14,7 @@ const USAGE: &str = "usage: kiri raw run [--rm] [-e KEY=VALUE]... [-u USER] [-w Containers get their own network namespace with only loopback for now (like docker run --network none); bridged networking comes next."; -#[derive(Debug, Default)] +#[derive(Debug, Default, PartialEq, Eq)] struct Options { remove: bool, env: Vec, @@ -25,7 +25,7 @@ struct Options { command: Vec, } -fn parse(args: &[String]) -> io::Result { +fn parse(args: &[String]) -> io::Result> { let bad = |m: String| io::Error::new(io::ErrorKind::InvalidInput, format!("{m}\n\n{USAGE}")); let mut o = Options::default(); let mut it = args.iter(); @@ -43,7 +43,14 @@ fn parse(args: &[String]) -> io::Result { return Err(bad(format!("--network {v} is not supported yet; only none"))); } } - "-h" | "--help" => return Err(bad(String::new())), + "-h" | "--help" => return Ok(None), + "--" => { + if let Some(img) = it.next() { + o.image = img.clone(); + o.command = it.cloned().collect(); + } + break; + } s if s.starts_with('-') => return Err(bad(format!("unknown option {s}"))), _ => { o.image = a.clone(); @@ -55,22 +62,27 @@ fn parse(args: &[String]) -> io::Result { if o.image.is_empty() { return Err(bad("no image given".into())); } - Ok(o) + Ok(Some(o)) } -/// Finds the image locally, pulling it first if needed. -pub fn image(store: &Store, name: &str) -> io::Result { +/// Finds the image locally, pulling it first if needed, and holds every blob +/// it references ([`Store::hold_image`]) so a concurrent tag replacement or +/// removal cannot delete them before layers are sent to the guest. +pub fn image(store: &Store, name: &str) -> io::Result<(Image, Vec)> { let reference = Reference::parse(name).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?; - if let Some(i) = store.find(&reference.short())? { - return Ok(i); + if let Some(found) = store.find_pinned(&reference.short())? { + return Ok(found); } eprintln!("Unable to find image '{}' locally; pulling", reference.short()); - Client::new().pull(store, &reference, &Platform::host_linux(), &|_| {}).map_err(io::Error::other) + let pulled = Client::new().pull(store, &reference, &Platform::host_linux(), &|_| {}).map_err(io::Error::other)?; + let pins = store.hold_image(&pulled); + Ok((pulled, pins)) } /// Makes sure every layer of `image` is unpacked in the guest. Returns how /// many had to be sent. pub fn ensure_layers(guest: &mut Guest, store: &Store, image: &Image) -> io::Result { + let _held = store.hold_image(image); let mut sent = 0; for layer in &image.layers { if !guest.has_layer(&layer.digest)? { @@ -104,10 +116,13 @@ pub fn new_id() -> String { } pub fn run(args: &[String]) -> io::Result<()> { - let o = parse(args)?; + let Some(o) = parse(args)? else { + println!("{USAGE}"); + return Ok(()); + }; let t0 = Instant::now(); let store = Store::open(Store::default_root()?)?; - let image = image(&store, &o.image)?; + let (image, _blob_pins) = image(&store, &o.image)?; let argv = argv(&image, &o.command); if argv.is_empty() { return Err(io::Error::new(io::ErrorKind::InvalidInput, format!("{} has no default command; give one", image.name))); @@ -158,3 +173,37 @@ pub fn run(args: &[String]) -> io::Result<()> { } std::process::exit(r.code); } + +#[cfg(test)] +mod tests { + use super::{Options, parse}; + + fn s(words: &[&str]) -> Vec { + words.iter().map(|w| (*w).to_owned()).collect() + } + + #[test] + fn help_before_image_returns_none_while_help_after_image_stays_in_command() { + assert_eq!(parse(&s(&["--help"])).unwrap(), None); + assert_eq!(parse(&s(&["-h"])).unwrap(), None); + assert_eq!(parse(&s(&["--rm", "--help"])).unwrap(), None); + + let with_cmd_help = parse(&s(&["--rm", "alpine:latest", "ls", "--help"])).unwrap().unwrap(); + assert!(with_cmd_help.remove); + assert_eq!(with_cmd_help.image, "alpine:latest"); + assert_eq!(with_cmd_help.command, s(&["ls", "--help"])); + + let direct_help = parse(&s(&["alpine", "--help"])).unwrap().unwrap(); + assert_eq!(direct_help.image, "alpine"); + assert_eq!(direct_help.command, s(&["--help"])); + + let double_dash = parse(&s(&["--", "alpine", "-h"])).unwrap().unwrap(); + assert_eq!( + double_dash, + Options { image: "alpine".into(), command: s(&["-h"]), ..Options::default() } + ); + + assert!(parse(&[]).is_err()); + assert!(parse(&s(&["--unknown", "alpine"])).is_err()); + } +} diff --git a/crates/kiri/src/scan.rs b/crates/kiri/src/scan.rs index 3c90150c3..f73430c91 100644 --- a/crates/kiri/src/scan.rs +++ b/crates/kiri/src/scan.rs @@ -42,16 +42,37 @@ fn root() -> io::Result { kiri_image::Store::default_root() } -fn grype() -> io::Result { - Ok(root()?.join("scanner/grype")) +fn grype_in(root: &Path) -> PathBuf { + root.join("scanner/grype") } /// Scans kept per image. const KEEP: usize = 20; /// An image's scans, one folder each: Grype's JSON report, the SBOM and a summary. -fn scan_dir(config_digest: &str) -> io::Result { - Ok(root()?.join("scans").join(kiri_image::store::digest_hex(config_digest)?)) +fn scan_dir_in(root: &Path, config_digest: &str) -> io::Result { + Ok(root.join("scans").join(kiri_image::store::digest_hex(config_digest)?)) +} + +/// Strips ANSI CSI escape sequences (`\x1b[...`) from a line. +pub(crate) fn strip_ansi(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\u{1b}' { + if chars.peek() == Some(&'[') { + chars.next(); + for n in chars.by_ref() { + if ('@'..='~').contains(&n) { + break; + } + } + } + } else { + out.push(c); + } + } + out } /// The image's scans, newest first, by their time. A scan kept before there @@ -74,10 +95,10 @@ fn scan_times(dir: &Path) -> Vec { } /// Grype's environment: its own database folder, no update nag, Kiri's proxy. -fn command(args: &[&str]) -> io::Result { - let mut c = Command::new(grype()?); +fn command_in(root: &Path, args: &[&str]) -> Command { + let mut c = Command::new(grype_in(root)); c.args(args) - .env("GRYPE_DB_CACHE_DIR", root()?.join("scanner/db")) + .env("GRYPE_DB_CACHE_DIR", root.join("scanner/db")) .env("GRYPE_CHECK_FOR_APP_UPDATE", "false"); let p = crate::daemon::proxy::effective(); if let Some(u) = &p.https { @@ -89,7 +110,7 @@ fn command(args: &[&str]) -> io::Result { if !p.no_proxy.is_empty() { c.env("NO_PROXY", p.no_proxy.join(",")); } - Ok(c) + c } fn run(mut c: Command, what: &str) -> io::Result<()> { @@ -98,14 +119,19 @@ fn run(mut c: Command, what: &str) -> io::Result<()> { return Ok(()); } let err = String::from_utf8_lossy(&out.stderr); - // Grype's log lines carry colour codes; keep the last plain line. - let line = err.lines().rev().map(|l| l.replace('\u{1b}', "")).map(|l| l.trim_start_matches(|c: char| c == '[' || c.is_ascii_digit() || c == ';' || c == 'm').to_string()).find(|l| !l.trim().is_empty()).unwrap_or_default(); - Err(io::Error::other(format!("{what}: {}", line.trim()))) + // Grype's log lines carry colour codes; keep the last plain line, redacted. + let line = err.lines().rev().map(strip_ansi).find(|l| !l.trim().is_empty()).unwrap_or_default(); + let msg = crate::diag::redact::Redactor::home_only().apply(line.trim()); + if msg.is_empty() { + Err(io::Error::other(what.to_owned())) + } else { + Err(io::Error::other(format!("{what}: {msg}"))) + } } /// Downloads Grype if it isn't there yet, checked against its pinned SHA-256. -fn ensure_grype(progress: &mut dyn FnMut(u8)) -> io::Result<()> { - let dest = grype()?; +fn ensure_grype_in(root: &Path, progress: &mut dyn FnMut(u8)) -> io::Result<()> { + let dest = grype_in(root); if dest.is_file() { return Ok(()); } @@ -134,6 +160,7 @@ fn ensure_grype(progress: &mut dyn FnMut(u8)) -> io::Result<()> { /// The image as an OCI layout Grype can read: hard links to the store's /// blobs (a copy if they can't be linked) and a manifest written for it. fn layout(store: &kiri_image::Store, i: &kiri_image::Image, to: &Path) -> io::Result<()> { + let _held = store.hold_image(i); let blobs = to.join("blobs/sha256"); std::fs::create_dir_all(&blobs)?; let put = |digest: &str| -> io::Result { @@ -168,8 +195,12 @@ fn layout(store: &kiri_image::Store, i: &kiri_image::Image, to: &Path) -> io::Re /// Scans the image (a name or an ID). `progress(phase, percent)`, with phase /// "scanner" (downloading Grype), "database" or "scanning". pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { - let store = kiri_image::Store::open(root()?)?; - let (i, ..) = crate::builds::stored(&store, name)?; + scan_in(&root()?, name, progress) +} + +fn scan_in(root: &Path, name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { + let store = kiri_image::Store::open(root)?; + let (i, _, _, _blob_pins) = crate::builds::stored_pinned(&store, name)?; { let mut r = RUNNING.lock().unwrap(); if !r.get_or_insert_with(HashSet::new).insert(i.config_digest.clone()) { @@ -177,19 +208,19 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result } } let result = (|| { - ensure_grype(&mut |pct| progress("scanner", pct))?; + ensure_grype_in(root, &mut |pct| progress("scanner", pct))?; progress("database", 0); - let has_db = root()?.join("scanner/db").read_dir().is_ok_and(|mut d| d.next().is_some()); + let has_db = root.join("scanner/db").read_dir().is_ok_and(|mut d| d.next().is_some()); // Offline with a database already here: scan with what's here, and // Grype says so itself if it's too old. - if let Err(e) = run(command(&["db", "update", "-q"])?, "Could not update the vulnerability database") { - if !has_db { - return Err(e); - } + if let Err(e) = run(command_in(root, &["db", "update", "-q"]), "Could not update the vulnerability database") + && !has_db + { + return Err(e); } progress("scanning", 0); let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); - let dir = scan_dir(&i.config_digest)?.join(at.to_string()); + let dir = scan_dir_in(root, &i.config_digest)?.join(at.to_string()); std::fs::create_dir_all(&dir)?; let tmp = store.root().join("tmp").join(format!("scan-{}-{}", std::process::id(), kiri_image::store::digest_hex(&i.config_digest)?)); let _ = std::fs::remove_dir_all(&tmp); @@ -197,11 +228,9 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result let report = dir.join("grype.json.part"); let sbom = dir.join("sbom.cdx.json.part"); let target = format!("oci-dir:{}", tmp.display()); - let out = (|| { - let mut c = command(&["-q", &target, "-o", &format!("json={}", report.display()), "-o", &format!("cyclonedx-json={}", sbom.display())])?; - c.env("GRYPE_DB_AUTO_UPDATE", "false"); - run(c, "The scan failed") - })(); + let mut c = command_in(root, &["-q", &target, "-o", &format!("json={}", report.display()), "-o", &format!("cyclonedx-json={}", sbom.display())]); + c.env("GRYPE_DB_AUTO_UPDATE", "false"); + let out = run(c, "The scan failed"); let _ = std::fs::remove_dir_all(&tmp); if let Err(e) = out { let _ = std::fs::remove_dir_all(&dir); @@ -209,12 +238,14 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result } std::fs::rename(&report, dir.join("grype.json"))?; std::fs::rename(&sbom, dir.join("sbom.cdx.json"))?; + // Invalidate any cached summary if a second scan ran in the same second. + let _ = std::fs::remove_file(dir.join("summary.json")); // Only the newest KEEP. - let all = scan_dir(&i.config_digest)?; + let all = scan_dir_in(root, &i.config_digest)?; for old in scan_times(&all).into_iter().skip(KEEP) { let _ = std::fs::remove_dir_all(all.join(old.to_string())); } - open(name, Some(at))?.ok_or_else(|| io::Error::other("the scan wrote no report")) + open_in(root, name, Some(at))?.ok_or_else(|| io::Error::other("the scan wrote no report")) })(); RUNNING.lock().unwrap().as_mut().map(|r| r.remove(&i.config_digest)); result @@ -223,16 +254,20 @@ pub fn scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result /// The image's scans for the history list, newest first: when, the count /// per severity, how many have a fix. Each summary is worked out once and kept. pub fn history(name: &str) -> io::Result { - let store = kiri_image::Store::open(root()?)?; + history_in(&root()?, name) +} + +fn history_in(root: &Path, name: &str) -> io::Result { + let store = kiri_image::Store::open(root)?; let (i, ..) = crate::builds::stored(&store, name)?; - let all = scan_dir(&i.config_digest)?; + let all = scan_dir_in(root, &i.config_digest)?; let mut list = Vec::new(); for at in scan_times(&all) { let path = all.join(at.to_string()).join("summary.json"); let summary = match std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::(&b).ok()) { Some(v) => v, None => { - let Some(full) = open(name, Some(at))? else { continue }; + let Some(full) = open_in(root, name, Some(at))? else { continue }; let mut counts = serde_json::Map::new(); for v in full["vulns"].as_array().into_iter().flatten() { let k = v["severity"].as_str().unwrap_or("Unknown").to_owned(); @@ -254,9 +289,13 @@ pub fn history(name: &str) -> io::Result { /// One of the image's scans in full (the newest when `at` is None), or None /// if it has none. pub fn open(name: &str, at: Option) -> io::Result> { - let store = kiri_image::Store::open(root()?)?; + open_in(&root()?, name, at) +} + +fn open_in(root: &Path, name: &str, at: Option) -> io::Result> { + let store = kiri_image::Store::open(root)?; let (i, manifest, config) = crate::builds::stored(&store, name)?; - let all = scan_dir(&i.config_digest)?; + let all = scan_dir_in(root, &i.config_digest)?; let Some(when) = at.or_else(|| scan_times(&all).first().copied()) else { return Ok(None) }; let dir = all.join(when.to_string()); let Ok(raw) = std::fs::read(dir.join("grype.json")) else { return Ok(None) }; @@ -313,9 +352,10 @@ fn summarize(report: &Value, lines: &[Value], config: &Value) -> Value { /// One scan's SBOM, where it's kept. pub fn sbom(name: &str, at: u64) -> io::Result { - let store = kiri_image::Store::open(root()?)?; + let root = root()?; + let store = kiri_image::Store::open(&root)?; let (i, ..) = crate::builds::stored(&store, name)?; - let from = scan_dir(&i.config_digest)?.join(at.to_string()).join("sbom.cdx.json"); + let from = scan_dir_in(&root, &i.config_digest)?.join(at.to_string()).join("sbom.cdx.json"); if !from.is_file() { return Err(io::Error::other("scan the image first")); } @@ -368,6 +408,160 @@ mod tests { assert_eq!((v[1]["layer"].as_u64(), v[1]["base"].as_bool(), v[1]["fixed"].as_array().map(Vec::len)), (Some(0), Some(true), Some(0))); } + #[test] + fn grype_pins_and_urls_cover_macos_and_linux() { + for (v, sum) in [GRYPE, cli_pins::LINUX_GRYPE, cli_pins::LINUX_ARM64_GRYPE] { + assert!(!v.is_empty()); + assert_eq!(sum.len(), 64); + assert!(sum.bytes().all(|b| b.is_ascii_hexdigit())); + } + assert!(grype_url(GRYPE.0).starts_with("https://github.com/anchore/grype/releases/download/v")); + assert_eq!( + cli_pins::linux_grype_url("0.120.1", "amd64"), + "https://github.com/anchore/grype/releases/download/v0.120.1/grype_0.120.1_linux_amd64.tar.gz" + ); + assert_eq!( + cli_pins::linux_grype_url("0.120.1", "arm64"), + "https://github.com/anchore/grype/releases/download/v0.120.1/grype_0.120.1_linux_arm64.tar.gz" + ); + } + + #[test] + fn strips_ansi_and_redacts_failed_grype_output() { + assert_eq!(strip_ansi("\x1b[31merror:\x1b[0m failed to fetch \x1b[1mdb\x1b[0m"), "error: failed to fetch db"); + let mut c = Command::new("/bin/sh"); + c.args(["-c", "printf '\\033[31mproxy failed: http://bob:hunter2@proxy.example:3128\\033[0m\\n' >&2; exit 1"]); + let err = run(c, "The scan failed").unwrap_err().to_string(); + assert!(err.starts_with("The scan failed: "), "{err}"); + assert!(!err.contains("hunter2"), "secret leaked: {err}"); + assert!(!err.contains('\x1b'), "ANSI leaked: {err}"); + assert!(err.contains("http://[redacted]@proxy.example:3128"), "{err}"); + } + + #[test] + fn scan_open_and_history_end_to_end_with_mock_grype() { + use std::os::unix::fs::PermissionsExt; + + let dir = std::env::temp_dir().join(format!("kiri-scan-test-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = kiri_image::Store::open(&dir).unwrap(); + + let layer_bytes = b"fake-layer-tar-bytes"; + let layer_digest = kiri_image::store::sha256_digest(layer_bytes); + std::fs::write(store.blob_path(&layer_digest).unwrap(), layer_bytes).unwrap(); + + let config_bytes = serde_json::to_vec(&json!({ + "architecture": "arm64", + "os": "linux", + "created": "2026-11-16T20:00:00Z", + "rootfs": {"type": "layers", "diff_ids": ["sha256:diff0"]}, + "history": [{"created": "2026-11-16T20:00:00Z", "created_by": "ADD rootfs /"}] + })) + .unwrap(); + let config_digest = kiri_image::store::sha256_digest(&config_bytes); + std::fs::write(store.blob_path(&config_digest).unwrap(), &config_bytes).unwrap(); + + store + .put_image(kiri_image::Image { + name: "demo:1".to_owned(), + digest: config_digest.clone(), + index_digest: None, + config_digest: config_digest.clone(), + layers: vec![kiri_image::Layer { + digest: layer_digest, + size: layer_bytes.len() as u64, + media_type: "application/vnd.oci.image.layer.v1.tar+gzip".to_owned(), + }], + size: layer_bytes.len() as u64, + platform: "linux/arm64".to_owned(), + created: "2026-11-16T20:00:00Z".to_owned(), + pulled_at: 1_794_859_620, + config: kiri_image::RunConfig::default(), + mirror: None, + }) + .unwrap(); + + let scanner = dir.join("scanner"); + std::fs::create_dir_all(scanner.join("db")).unwrap(); + let mock = scanner.join("grype"); + let script = r#"#!/bin/sh +set -eu +if [ "${1:-}" = "db" ] && [ "${2:-}" = "update" ]; then + exit 0 +fi +oci="" +json_out="" +sbom_out="" +while [ $# -gt 0 ]; do + case "$1" in + oci-dir:*) oci="${1#oci-dir:}" ;; + -o) + shift + case "$1" in + json=*) json_out="${1#json=}" ;; + cyclonedx-json=*) sbom_out="${1#cyclonedx-json=}" ;; + esac + ;; + esac + shift +done +[ -f "$oci/oci-layout" ] && [ -f "$oci/index.json" ] +cat > "$json_out" <<'EOF' +{ + "descriptor": {"db": {"status": {"built": "2026-11-16T00:00:00Z"}}}, + "matches": [ + { + "vulnerability": {"id": "CVE-2026-1001", "severity": "Critical", "fix": {"state": "fixed", "versions": ["3.1.1"]}, "dataSource": "https://nvd.nist.gov/vuln/detail/CVE-2026-1001", "description": "critical bug"}, + "artifact": {"name": "openssl", "version": "3.1.0", "type": "apk", "locations": [{"layerID": "sha256:diff0"}]} + }, + { + "vulnerability": {"id": "CVE-2026-1002", "severity": "Negligible", "fix": {"state": "not-fixed"}, "dataSource": "https://nvd.nist.gov/vuln/detail/CVE-2026-1002", "description": "minor"}, + "artifact": {"name": "musl", "version": "1.2.4", "type": "apk", "locations": [{"layerID": "sha256:diff0"}]} + } + ] +} +EOF +cat > "$sbom_out" <<'EOF' +{"components": [{"name": "openssl"}, {"name": "musl"}, {"name": "busybox"}]} +EOF +"#; + std::fs::write(&mock, script).unwrap(); + std::fs::set_permissions(&mock, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let mut phases = Vec::new(); + let report = scan_in(&dir, "demo:1", &mut |phase, pct| phases.push((phase.to_owned(), pct))).unwrap(); + assert!(phases.iter().any(|(p, _)| p == "database"), "{phases:?}"); + assert!(phases.iter().any(|(p, _)| p == "scanning"), "{phases:?}"); + + // `--json` output from `scan` must match `GET /kiri/images/scan` (`open`). + let opened = open_in(&dir, "demo:1", None).unwrap().unwrap(); + assert_eq!(report, opened); + assert_eq!(report["id"], config_digest); + assert_eq!(report["packages"], 3); + assert_eq!(report["db"], "2026-11-16T00:00:00Z"); + assert_eq!(report["grype"], GRYPE.0); + assert_eq!(report["vulns"].as_array().unwrap().len(), 2); + + let table = crate::scan_cli::format_report("demo:1", &report).unwrap(); + assert!(table.contains("demo:1: 3 packages, 2 findings, 1 with a fix available, database built 2026-11-16T00:00:00Z"), "{table}"); + assert!(table.contains("1 Critical, 1 Negligible"), "{table}"); + assert!(table.contains("fixed in 3.1.1"), "{table}"); + + let hist = history_in(&dir, "demo:1").unwrap(); + assert_eq!(hist["id"], config_digest); + assert_eq!(hist["scans"].as_array().unwrap().len(), 1); + let hist_table = crate::scan_cli::format_history(&hist).unwrap(); + assert!(hist_table.contains("1 Critical, 1 Negligible"), "{hist_table}"); + + // Missing image gives a clear error. + let missing = scan_in(&dir, "no-such-image:latest", &mut |_, _| {}).unwrap_err().to_string(); + assert_eq!(missing, "no image no-such-image:latest in Kiri"); + let missing_hist = history_in(&dir, "no-such-image:latest").unwrap_err().to_string(); + assert_eq!(missing_hist, "no image no-such-image:latest in Kiri"); + + let _ = std::fs::remove_dir_all(&dir); + } + /// A real scan of an image in a real store, Grype and its database downloaded on first use: /// `KIRI_LIVE_IMAGE=alpine:latest KIRI_DATA_DIR=... cargo test -p kiri scan_live -- --ignored --nocapture`. #[test] diff --git a/crates/kiri/src/scan_cli.rs b/crates/kiri/src/scan_cli.rs new file mode 100644 index 000000000..fff4f1d82 --- /dev/null +++ b/crates/kiri/src/scan_cli.rs @@ -0,0 +1,490 @@ +//! `kiri scan `: scan an image in Kiri's store for known +//! vulnerabilities from the terminal. The same scan the window's Security +//! tab runs (`crate::scan`): Grype reads the image through an OCI layout of +//! the store's own blobs, so the VM isn't woken and nothing is uploaded. +//! The first scan downloads Grype and its database (about 230 MB, 3 GB +//! unpacked), kept for every scan after. +//! +//! On Windows this runs inside WSL by the engine's own `kiri` (`wsl.rs`). +//! On a Linux host running the `kiri` system service (`/run/kiri/docker.sock`), +//! a user without direct access to `/var/lib/kiri-daemon` scans through the +//! daemon's `/kiri/images/scan` and `/kiri/images/scans` endpoints. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::io; +use std::time::{Duration, UNIX_EPOCH}; + +use serde_json::{Map, Value}; + +const USAGE: &str = "usage: kiri scan [--json] [--history] "; + +const SEVERITIES: [&str; 6] = ["Critical", "High", "Medium", "Low", "Negligible", "Unknown"]; + +#[derive(Debug, PartialEq, Eq)] +enum Action { + Help, + Scan { image: String, json: bool }, + History { image: String, json: bool }, +} + +fn invalid(msg: impl Into) -> io::Error { + io::Error::new(io::ErrorKind::InvalidInput, msg.into()) +} + +fn parse(args: &[String]) -> Result { + let mut json = false; + let mut history = false; + let mut names: Vec = Vec::new(); + for a in args { + match a.as_str() { + "--json" => json = true, + "--history" => history = true, + "-h" | "--help" => return Ok(Action::Help), + s if s.starts_with('-') => return Err(format!("unknown flag {s}; {USAGE}")), + s if s.trim().is_empty() => return Err(USAGE.to_owned()), + s => names.push(s.to_owned()), + } + } + let Some(image) = names.first().cloned() else { + return Err(USAGE.to_owned()); + }; + if names.len() > 1 { + return Err(format!("one image at a time; {USAGE}")); + } + if history { + Ok(Action::History { image, json }) + } else { + Ok(Action::Scan { image, json }) + } +} + +/// Strips ANSI CSI escape sequences and control characters from untrusted +/// image metadata before printing to a terminal. +fn sanitize(s: &str) -> String { + let stripped = crate::scan::strip_ansi(s); + let mut out = String::with_capacity(stripped.len()); + for c in stripped.chars() { + if c == '\r' || c == '\n' || c == '\t' { + out.push(' '); + } else if !c.is_control() { + out.push(c); + } + } + out +} + +/// When a scan was run, in UTC for the history table: `2026-11-16 20:07 UTC`. +fn stamp(at: u64) -> String { + let Some(t) = UNIX_EPOCH.checked_add(Duration::from_secs(at)) else { + return at.to_string(); + }; + let r = crate::daemon::time::rfc3339(t); + match r.get(..16) { + Some(prefix) => format!("{} UTC", prefix.replace('T', " ")), + None => r, + } +} + +/// Formats severity counts worst-first (`1 Critical, 3 Medium`) or +/// `no vulnerabilities found` when none are present. +fn format_counts(mut counts: BTreeMap) -> String { + let mut parts = Vec::new(); + for s in SEVERITIES { + if let Some(n) = counts.remove(s).filter(|&n| n > 0) { + parts.push(format!("{n} {s}")); + } + } + // Any severity Grype may add later, sorted after the known list. + for (s, n) in counts { + if n > 0 { + parts.push(format!("{n} {}", sanitize(&s))); + } + } + if parts.is_empty() { + "no vulnerabilities found".to_owned() + } else { + parts.join(", ") + } +} + +/// The severity counts from a report's `vulns` list, worst first. +fn count_line(vulns: &[Value]) -> String { + let mut counts = BTreeMap::new(); + for v in vulns { + let s = v["severity"].as_str().unwrap_or("Unknown").to_owned(); + *counts.entry(s).or_insert(0u64) += 1; + } + format_counts(counts) +} + +/// The severity counts from a saved history summary's `counts` object, worst first. +fn count_line_from_map(map: Option<&Map>) -> String { + let mut counts = BTreeMap::new(); + if let Some(obj) = map { + for (k, v) in obj { + if let Some(n) = v.as_u64() + && n > 0 + { + *counts.entry(k.clone()).or_insert(0u64) += n; + } + } + } + format_counts(counts) +} + +/// Formats `scan::history`'s output as a table, newest scan first. +pub(crate) fn format_history(h: &Value) -> io::Result { + let scans = h["scans"].as_array().ok_or_else(|| io::Error::other("no scans"))?; + if scans.is_empty() { + return Ok("no scans yet\n".to_owned()); + } + let rows: Vec<(String, String, u64, u64, u64)> = scans + .iter() + .map(|s| { + ( + stamp(s["scanned"].as_u64().unwrap_or(0)), + count_line_from_map(s["counts"].as_object()), + s["vulns"].as_u64().unwrap_or(0), + s["fixable"].as_u64().unwrap_or(0), + s["packages"].as_u64().unwrap_or(0), + ) + }) + .collect(); + let w_scanned = rows.iter().map(|r| r.0.len()).max().unwrap_or(0).max("scanned".len()); + let w_found = rows.iter().map(|r| r.1.len()).max().unwrap_or(0).max("found".len()); + let mut out = String::new(); + let _ = writeln!(out, "{:6} {:>7} {:>8}", "scanned", "found", "vulns", "fixable", "packages"); + for (when, counts, vulns, fixable, packages) in rows { + let _ = writeln!(out, "{when:6} {fixable:>7} {packages:>8}"); + } + Ok(out) +} + +/// Formats `scan::scan`'s report: summary counts first, then one aligned row +/// per finding, worst severity first as `crate::scan` ordered them. +pub(crate) fn format_report(name: &str, report: &Value) -> io::Result { + let vulns = report["vulns"].as_array().ok_or_else(|| io::Error::other("the scan wrote no report"))?; + let packages = report["packages"].as_u64().unwrap_or(0); + let fixable = vulns.iter().filter(|v| v["fixed"].as_array().is_some_and(|f| !f.is_empty())).count(); + let db = sanitize(report["db"].as_str().unwrap_or("")); + let display_name = sanitize(name); + let mut out = String::new(); + let _ = write!( + out, + "{display_name}: {packages} package{}, {} finding{}, {fixable} with a fix available", + if packages == 1 { "" } else { "s" }, + vulns.len(), + if vulns.len() == 1 { "" } else { "s" }, + ); + if !db.is_empty() { + let _ = write!(out, ", database built {db}"); + } + out.push('\n'); + let _ = writeln!(out, "{}", count_line(vulns)); + if vulns.is_empty() { + return Ok(out); + } + let rows: Vec<[String; 5]> = vulns + .iter() + .map(|v| { + let sev = sanitize(v["severity"].as_str().unwrap_or("Unknown")); + let id = sanitize(v["id"].as_str().unwrap_or("")); + let pkg = sanitize(v["package"].as_str().unwrap_or("")); + let kind = sanitize(v["kind"].as_str().unwrap_or("")); + let package = if kind.is_empty() { pkg } else { format!("{pkg} ({kind})") }; + let version = sanitize(v["version"].as_str().unwrap_or("")); + let fixed: Vec = v["fixed"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .map(sanitize) + .filter(|s| !s.is_empty()) + .collect(); + let fix = if fixed.is_empty() { "-".to_owned() } else { format!("fixed in {}", fixed.join(", ")) }; + [sev, id, package, version, fix] + }) + .collect(); + let w0 = rows.iter().map(|r| r[0].len()).max().unwrap_or(0).max("severity".len()); + let w1 = rows.iter().map(|r| r[1].len()).max().unwrap_or(0).max("vulnerability".len()); + let w2 = rows.iter().map(|r| r[2].len()).max().unwrap_or(0).max("package".len()); + let w3 = rows.iter().map(|r| r[3].len()).max().unwrap_or(0).max("version".len()); + out.push('\n'); + let _ = writeln!(out, "{: bool { + std::env::var_os("KIRI_DATA_DIR").is_none() + && std::env::var_os("KIRI_SOCKET").is_none() + && std::env::var_os("HOME").as_deref() != Some(std::ffi::OsStr::new("/var/lib/kiri-daemon")) + && std::path::Path::new(crate::client::SERVICE_SOCKET).exists() + && crate::client::alive() +} + +#[cfg(target_os = "linux")] +fn query_escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + let _ = write!(out, "%{b:02X}"); + } + } + out +} + +#[cfg(target_os = "linux")] +fn daemon_history(name: &str) -> io::Result { + crate::client::get(&format!("/kiri/images/scans?name={}", query_escape(name))) +} + +#[cfg(target_os = "linux")] +fn daemon_scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { + let mut end = None; + let status = crate::client::post_lines_unbounded(&format!("/kiri/images/scan?name={}", query_escape(name)), |v| { + if let Some(phase) = v["phase"].as_str() { + progress(phase, v["pct"].as_u64().unwrap_or(0).min(100) as u8); + } else if let Some(e) = v["error"].as_str() { + end = Some(Err(io::Error::other(e.to_owned()))); + } else if let Some(m) = v["message"].as_str() { + end = Some(Err(io::Error::other(m.to_owned()))); + } else if v.get("result").is_some() { + end = Some(Ok(v["result"].clone())); + } + })?; + if !(200..300).contains(&status) { + return Err(io::Error::other(format!("scan failed (HTTP {status})"))); + } + end.unwrap_or_else(|| Err(io::Error::other("the scan stopped before it finished"))) +} + +fn run_history(name: &str) -> io::Result { + #[cfg(target_os = "linux")] + if use_service_daemon() { + return daemon_history(name); + } + crate::scan::history(name) +} + +fn run_scan(name: &str, progress: &mut dyn FnMut(&str, u8)) -> io::Result { + #[cfg(target_os = "linux")] + if use_service_daemon() { + return daemon_scan(name, progress); + } + crate::scan::scan(name, progress) +} + +/// Runs `kiri scan [--json] [--history] `. +pub fn run(args: &[String]) -> io::Result<()> { + match parse(args).map_err(invalid)? { + Action::Help => { + println!( + "{USAGE}\n --json the full report, as JSON\n --history the image's kept scans, newest first, without scanning again" + ); + Ok(()) + } + Action::History { image, json } => { + let h = run_history(&image)?; + if json { + println!("{}", serde_json::to_string_pretty(&h).map_err(io::Error::other)?); + return Ok(()); + } + print!("{}", format_history(&h)?); + Ok(()) + } + Action::Scan { image, json } => { + let mut last = (String::new(), 255u8); + let report = run_scan(&image, &mut |phase, pct| { + if (pct == 0 || pct == 100) && (phase, pct) != (last.0.as_str(), last.1) { + last = (phase.to_owned(), pct); + eprintln!("{phase} {pct}%"); + } + })?; + if json { + println!("{}", serde_json::to_string_pretty(&report).map_err(io::Error::other)?); + return Ok(()); + } + print!("{}", format_report(&image, &report)?); + Ok(()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn argv(s: &str) -> Vec { + s.split_whitespace().map(String::from).collect() + } + + #[test] + fn parses_scan_flags_and_image() { + assert_eq!(parse(&argv("alpine:latest")), Ok(Action::Scan { image: "alpine:latest".into(), json: false })); + assert_eq!(parse(&argv("--json alpine:latest")), Ok(Action::Scan { image: "alpine:latest".into(), json: true })); + assert_eq!(parse(&argv("alpine:latest --json")), Ok(Action::Scan { image: "alpine:latest".into(), json: true })); + assert_eq!(parse(&argv("--history alpine:latest")), Ok(Action::History { image: "alpine:latest".into(), json: false })); + assert_eq!(parse(&argv("--history --json alpine:latest")), Ok(Action::History { image: "alpine:latest".into(), json: true })); + assert_eq!(parse(&argv("alpine --json --history")), Ok(Action::History { image: "alpine".into(), json: true })); + assert_eq!(parse(&argv("-h")), Ok(Action::Help)); + assert_eq!(parse(&argv("--help")), Ok(Action::Help)); + } + + #[test] + fn rejects_invalid_flags_and_missing_or_extra_images() { + assert_eq!(parse(&[]).unwrap_err(), USAGE); + assert_eq!(parse(&argv("--json")).unwrap_err(), USAGE); + assert_eq!(parse(&argv("--history")).unwrap_err(), USAGE); + assert_eq!(parse(&["".to_owned()]).unwrap_err(), USAGE); + assert_eq!(parse(&[" ".to_owned()]).unwrap_err(), USAGE); + + let bad_flag = parse(&argv("--bogus alpine")).unwrap_err(); + assert!(bad_flag.starts_with("unknown flag --bogus;"), "{bad_flag}"); + assert!(bad_flag.contains(USAGE), "{bad_flag}"); + + let short_flag = parse(&argv("-q alpine")).unwrap_err(); + assert!(short_flag.starts_with("unknown flag -q;"), "{short_flag}"); + + let extra = parse(&argv("alpine nginx")).unwrap_err(); + assert!(extra.starts_with("one image at a time;"), "{extra}"); + } + + #[test] + fn not_a_docker_command() { + assert!(!crate::docker::handles("scan")); + } + + #[test] + fn counts_worst_first_and_empty() { + let vulns = json!([ + {"severity": "Negligible"}, + {"severity": "Medium"}, + {"severity": "Critical"}, + {"severity": "Low"}, + {"severity": "Medium"}, + {"severity": "High"}, + {"severity": "Unknown"}, + ]); + assert_eq!( + count_line(vulns.as_array().unwrap()), + "1 Critical, 1 High, 2 Medium, 1 Low, 1 Negligible, 1 Unknown" + ); + assert_eq!(count_line(&[]), "no vulnerabilities found"); + } + + #[test] + fn formats_report_table_all_severities_with_and_without_fixes() { + let report = json!({ + "id": "sha256:0000000000000000000000000000000000000000000000000000000000000001", + "scanned": 1_794_859_620u64, + "packages": 14, + "db": "2026-11-16T00:00:00Z", + "grype": "0.120.1", + "vulns": [ + {"id": "CVE-2026-0001", "severity": "Critical", "package": "openssl", "kind": "apk", "version": "3.1.0-r0", "fixed": ["3.1.1-r0"]}, + {"id": "CVE-2026-0002", "severity": "High", "package": "zlib", "kind": "apk", "version": "1.3.0", "fixed": ["1.3.1", "1.3.2"]}, + {"id": "CVE-2026-0003", "severity": "Medium", "package": "busybox", "kind": "apk", "version": "1.36.1", "fixed": []}, + {"id": "CVE-2026-0004", "severity": "Low", "package": "curl", "kind": "", "version": "8.4.0", "fixed": ["8.5.0"]}, + {"id": "CVE-2026-0005", "severity": "Negligible", "package": "musl", "kind": "apk", "version": "1.2.4", "fixed": []}, + ] + }); + let out = format_report("alpine:3.21", &report).unwrap(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!( + lines[0], + "alpine:3.21: 14 packages, 5 findings, 3 with a fix available, database built 2026-11-16T00:00:00Z" + ); + assert_eq!(lines[1], "1 Critical, 1 High, 1 Medium, 1 Low, 1 Negligible"); + assert_eq!(lines[2], ""); + assert!(lines[3].starts_with("severity"), "{}", lines[3]); + assert!(lines[4].contains("Critical") && lines[4].contains("CVE-2026-0001") && lines[4].contains("openssl (apk)") && lines[4].ends_with("fixed in 3.1.1-r0")); + assert!(lines[5].contains("High") && lines[5].ends_with("fixed in 1.3.1, 1.3.2")); + assert!(lines[6].contains("Medium") && lines[6].ends_with(" -")); + assert!(lines[7].contains("Low") && lines[7].contains("curl") && !lines[7].contains("curl ()") && lines[7].ends_with("fixed in 8.5.0")); + assert!(lines[8].contains("Negligible") && lines[8].ends_with(" -")); + } + + #[test] + fn formats_clean_report_and_singular_counts() { + let report = json!({ + "packages": 1, + "db": "", + "vulns": [] + }); + let out = format_report("scratch:latest", &report).unwrap(); + assert_eq!(out, "scratch:latest: 1 package, 0 findings, 0 with a fix available\nno vulnerabilities found\n"); + } + + #[test] + fn sanitizes_control_and_ansi_sequences_in_table() { + let report = json!({ + "packages": 1, + "db": "2026-11-16\x1b[31m", + "vulns": [{ + "id": "CVE-1\nFAKE", + "severity": "High", + "package": "\x1b[31mevil\x1b[0m", + "kind": "apk", + "version": "1.0\r", + "fixed": ["1.1\x07"] + }] + }); + let out = format_report("img\x1b[2J:1", &report).unwrap(); + assert!(!out.contains('\x1b'), "escape sequence leaked: {out:?}"); + assert!(!out.contains('\r'), "CR leaked: {out:?}"); + assert!(!out.contains('\x07'), "BEL leaked: {out:?}"); + assert!(out.contains("CVE-1 FAKE"), "newline not flattened: {out}"); + assert!(out.contains("evil (apk)"), "ANSI not stripped: {out}"); + } + + #[test] + fn formats_history_worst_first_and_empty() { + let empty = json!({"id": "sha256:0", "scans": []}); + assert_eq!(format_history(&empty).unwrap(), "no scans yet\n"); + + let history = json!({ + "id": "sha256:0", + "scans": [ + { + "scanned": 1_794_859_620u64, + "counts": {"Low": 1, "Critical": 2, "Medium": 3, "High": 1}, + "vulns": 7, + "fixable": 4, + "packages": 20 + }, + { + "scanned": 1_794_773_220u64, + "counts": {}, + "vulns": 0, + "fixable": 0, + "packages": 20 + } + ] + }); + let out = format_history(&history).unwrap(); + let lines: Vec<&str> = out.lines().collect(); + assert_eq!(lines.len(), 3, "{out}"); + assert!(lines[0].contains("scanned") && lines[0].contains("found") && lines[0].contains("packages")); + // Worst-first order: Critical before High before Medium before Low (not alphabetical!). + assert!(lines[1].contains("2026-11-16 20:07 UTC"), "{}", lines[1]); + assert!(lines[1].contains("2 Critical, 1 High, 3 Medium, 1 Low"), "{}", lines[1]); + assert!(lines[2].contains("no vulnerabilities found"), "{}", lines[2]); + } + + #[test] + fn stamp_never_panics_on_extreme_values() { + assert_eq!(stamp(0), "1970-01-01 00:00 UTC"); + assert_eq!(stamp(u64::MAX), u64::MAX.to_string()); + } +} diff --git a/crates/kiri/src/setup.rs b/crates/kiri/src/setup.rs index 1cce7122b..c98c3886a 100644 --- a/crates/kiri/src/setup.rs +++ b/crates/kiri/src/setup.rs @@ -5,8 +5,9 @@ //! - a LaunchAgent that starts `kiri daemon` at login (`--no-agent` skips it) //! - the app's bundled `docker`, Compose and buildx, when run from Kiri.app //! - `docker` and `kiri` in `~/.kiri/bin`, which a marked line in the shell -//! profiles (zsh's, bash's, and fish's if used) adds to the end of PATH, -//! so a docker CLI already installed keeps priority; and +//! profiles (zsh's, bash's, and fish's if used) adds to the end of PATH +//! once (`--no-profiles` skips the profile edits and takes back any Kiri +//! added), so a docker CLI already installed keeps priority; and //! `/usr/local/bin/kiri` when that directory is the user's //! - on a Mac with no other Docker engine, `kiri` as docker's default context //! - a buildx builder, `kiri-build`, that loads what it builds into Kiri, @@ -33,7 +34,7 @@ use std::io; use std::path::{Path, PathBuf}; use std::process::Command; -use serde_json::{Value, json}; +use serde_json::Value; // The bundle identifier (`APP_ID`) named in the LaunchAgent makes macOS // say "Kiri" in Login Items, rather than the name on the signing @@ -48,15 +49,14 @@ fn bin_dir() -> io::Result { Ok(home()?.join(crate::flavor::STATE.get()).join("bin")) } +use crate::dockerctx::{Endpoint, read_json, write_json}; + fn home() -> io::Result { std::env::var_os("HOME").map(PathBuf::from).ok_or_else(|| io::Error::other("HOME is not set")) } fn docker_dir() -> io::Result { - match std::env::var_os("DOCKER_CONFIG") { - Some(d) => Ok(PathBuf::from(d)), - None => Ok(home()?.join(".docker")), - } + crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("HOME is not set")) } /// The docker CLI's directory for a context: named by the SHA-256 of its name. @@ -65,24 +65,6 @@ fn context_dir(name: &str) -> io::Result { Ok(docker_dir()?.join("contexts/meta").join(digest.trim_start_matches("sha256:"))) } -fn read_json(path: &Path) -> io::Result { - match std::fs::read(path) { - Ok(b) => serde_json::from_slice(&b).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}: {e}", path.display()))), - Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(json!({})), - Err(e) => Err(e), - } -} - -/// Writes JSON through a temporary file, so a crash never leaves half a config. -fn write_json(path: &Path, v: &Value) -> io::Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("kiri-tmp"); - std::fs::write(&tmp, serde_json::to_vec_pretty(v).map_err(io::Error::other)?)?; - std::fs::rename(tmp, path) -} - /// Kiri.app's `Contents`, when this binary runs from the app. fn bundle_contents() -> Option { let exe = std::env::current_exe().ok()?.canonicalize().ok()?; @@ -112,7 +94,13 @@ pub fn first_launch() { false }); if set_up { - // Set up by an older Kiri: make sure the commands are there too. + // Set up by an older Kiri: make sure the commands are there too, + // without re-adding shell profile lines the user removed (#556). + if !dev() + && let Ok(h) = home() + { + mark_profiles_configured(&h); + } if let Some(contents) = bundle_contents() { let _ = bundled_cli(&contents); } @@ -182,7 +170,23 @@ fn step(what: &'static str) -> impl Fn(io::Error) -> io::Error { move |e| io::Error::new(e.kind(), format!("{what}: {e}")) } +const USAGE: &str = "usage: kiri setup [--use] [--no-agent] [--no-profiles] [--no-domains]\n kiri setup --domains | --docker-socket | --uninstall"; + pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + for a in args { + if !matches!( + a.as_str(), + "--uninstall" | "--domains" | "--docker-socket" | "--use" | "--no-profiles" | "--no-agent" | "--no-domains" + ) { + return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)); + } + } let flag = |f: &str| args.iter().any(|a| a == f); if flag("--uninstall") { return uninstall(); @@ -208,6 +212,15 @@ pub fn run(args: &[String]) -> io::Result<()> { write_json(&path, &cfg).map_err(step("making kiri docker's current context"))?; println!("docker now uses Kiri by default (`docker context use default` to switch back)"); } + if !dev() { + let h = home().map_err(step("setting up the kiri and docker commands"))?; + let z = zdotdir(&h); + if flag("--no-profiles") { + opt_out_shell_path(&h, &z).map_err(step("setting up the kiri and docker commands"))?; + } else if bundle_contents().is_some() { + shell_path(&h, &z).map_err(step("setting up the kiri and docker commands"))?; + } + } first_step("commands")?; if !flag("--no-agent") { first_step("login")?; @@ -280,13 +293,23 @@ const DOCKER_SOCK: &str = "/var/run/docker.sock"; const SOCKET_LABEL: &str = "dev.kiri.docker-socket"; const SOCKET_DAEMON: &str = "/Library/LaunchDaemons/dev.kiri.docker-socket.plist"; -/// Who has /var/run/docker.sock. -#[derive(Debug, PartialEq)] -enum DockerSock { - Kiri, - Free, - /// Another engine: what it points at. - Taken(String), +/// Who has `/var/run/docker.sock`. +pub fn docker_sock() -> Endpoint { + let Ok(ours) = crate::daemon::socket_path() else { return Endpoint::Free }; + docker_sock_at_ours(&ours) +} + +fn docker_sock_at_ours(ours: &Path) -> Endpoint { + crate::dockerctx::sock_at(Path::new(DOCKER_SOCK), ours, &other_engine_dirs()) +} + +/// Settings → Network's Docker socket row for the Mac. +pub fn docker_sock_event() -> Value { + let (endpoint, hint) = match crate::daemon::socket_path() { + Ok(ours) => (docker_sock_at_ours(&ours), format!("unix://{}", ours.display())), + Err(_) => (Endpoint::Free, format!("unix://~/{}/run/docker.sock", crate::flavor::STATE.get())), + }; + crate::dockerctx::sock_event(DOCKER_SOCK, &endpoint, &hint, !dev()) } /// The engines whose links stay theirs while the app is installed, running @@ -300,27 +323,6 @@ fn other_engine_dirs() -> Vec { .collect() } -fn docker_sock(ours: &Path) -> DockerSock { - docker_sock_at(Path::new(DOCKER_SOCK), ours, &other_engine_dirs()) -} - -fn docker_sock_at(path: &Path, ours: &Path, engines: &[PathBuf]) -> DockerSock { - let Ok(meta) = std::fs::symlink_metadata(path) else { return DockerSock::Free }; - if meta.file_type().is_symlink() { - let Ok(target) = std::fs::read_link(path) else { return DockerSock::Taken(path.display().to_string()) }; - if target == ours { - return DockerSock::Kiri; - } - if target.exists() || engines.iter().any(|e| target.starts_with(e)) { - return DockerSock::Taken(target.display().to_string()); - } - // Left behind by an engine that has been removed. - return DockerSock::Free; - } - // A socket (or anything else) of its own: an engine's, serving or not. - DockerSock::Taken(path.display().to_string()) -} - /// `'…'` for sh. fn sh_quote(s: &str) -> String { format!("'{}'", s.replace('\'', "'\\''")) @@ -344,7 +346,7 @@ impl std::fmt::Display for LinkScript { /// Kiri's already or another engine's, or for Kiri Dev. fn docker_socket_script() -> io::Result> { let ours = crate::daemon::socket_path()?; - if dev() || docker_sock(&ours) != DockerSock::Free { + if dev() || docker_sock_at_ours(&ours) != Endpoint::Free { return Ok(None); } let esc = |s: &str| s.replace('&', "&").replace('<', "<"); @@ -389,16 +391,16 @@ pub fn docker_socket() -> io::Result<()> { /// `~/.testcontainers.properties` for when /var/run/docker.sock is not /// Kiri's but could be (a declined password, not yet asked). fn docker_socket_fallback(ours: &Path) -> String { - match docker_sock(ours) { - DockerSock::Kiri => { + match docker_sock_at_ours(ours) { + Endpoint::Kiri => { let _ = testcontainers(ours, false); format!("{DOCKER_SOCK} → Kiri (docker-py, Testcontainers and other tools that ignore docker contexts)") } - DockerSock::Taken(t) => { + Endpoint::Taken(t) => { let _ = testcontainers(ours, false); format!("{DOCKER_SOCK} is another engine's ({t}) and stays so; DOCKER_HOST=unix://{} points a tool at Kiri", ours.display()) } - DockerSock::Free => match testcontainers(ours, true) { + Endpoint::Free => match testcontainers(ours, true) { Ok(true) => format!("{DOCKER_SOCK} is not Kiri's yet (`kiri setup --docker-socket` asks for the password); Testcontainers finds Kiri through ~/.testcontainers.properties"), _ => format!("{DOCKER_SOCK} is not Kiri's yet (`kiri setup --docker-socket` asks for the password); until then DOCKER_HOST=unix://{} points a tool at Kiri", ours.display()), }, @@ -450,8 +452,8 @@ fn testcontainers_at(path: &Path, ours: &Path, on: bool) -> io::Result { /// went, if it is not Kiri's. pub fn docker_socket_note() -> Option { let ours = crate::daemon::socket_path().ok()?; - match docker_sock(&ours) { - DockerSock::Free if !dev() => Some(docker_socket_fallback(&ours)), + match docker_sock_at_ours(&ours) { + Endpoint::Free if !dev() => Some(docker_socket_fallback(&ours)), _ => None, } } @@ -461,7 +463,7 @@ pub fn docker_socket_note() -> Option { fn remove_docker_socket() -> io::Result<()> { let ours = crate::daemon::socket_path()?; let _ = testcontainers(&ours, false); - let linked = docker_sock(&ours) == DockerSock::Kiri; + let linked = docker_sock_at_ours(&ours) == Endpoint::Kiri; if !linked && !Path::new(SOCKET_DAEMON).exists() { return Ok(()); } @@ -531,33 +533,52 @@ pub fn after_tools() -> io::Result<()> { builder().map(drop) } +/// After Settings → Storage moved the data folder from `old`: Kiri Lite's +/// docker link (`~/.kiri/bin/docker`) and docker's plugin folder, which +/// point into the data folder, point into the new one. +pub fn relink_cli(old: &Path) -> io::Result<()> { + let new = kiri_image::Store::default_root()?; + let link = bin_dir()?.join("docker"); + if let Some(to) = std::fs::read_link(&link).ok().and_then(|t| moved(&t, old, &new)) { + std::fs::remove_file(&link)?; + std::os::unix::fs::symlink(to, &link)?; + } + let path = docker_dir()?.join("config.json"); + let mut cfg = read_json(&path)?; + if repoint_plugin_dirs(&mut cfg, old, &new) { + write_json(&path, &cfg)?; + } + Ok(()) +} + +/// `path` under `new` instead of `old`, if it was under `old`. +fn moved(path: &Path, old: &Path, new: &Path) -> Option { + path.strip_prefix(old).ok().map(|rest| new.join(rest)) +} + +/// Moves docker's plugin folders under `old` to `new`; whether any moved. +fn repoint_plugin_dirs(cfg: &mut Value, old: &Path, new: &Path) -> bool { + let mut changed = false; + for d in cfg["cliPluginsExtraDirs"].as_array_mut().into_iter().flatten() { + if let Some(to) = d.as_str().and_then(|s| moved(Path::new(s), old, new)) { + *d = to.to_string_lossy().into_owned().into(); + changed = true; + } + } + changed +} + /// The context, as `docker context create kiri --docker host=…` writes it. fn context(socket: &Path) -> io::Result<()> { - let meta = json!({ - "Name": CONTEXT.get(), - "Metadata": {"Description": crate::flavor::APP.get()}, - "Endpoints": {"docker": {"Host": format!("unix://{}", socket.display()), "SkipTLSVerify": false}}, - }); - write_json(&context_dir(CONTEXT.get())?.join("meta.json"), &meta) + crate::dockerctx::write_context(&context_dir(CONTEXT.get())?, CONTEXT.get(), crate::flavor::APP.get(), &format!("unix://{}", socket.display())) } /// Makes `name` the context plain `docker` uses: Kiri's own (made first if /// missing), "default", or another context that exists, to switch back to. pub fn use_context(name: &str) -> io::Result<()> { - if name == CONTEXT.get() { - context(&crate::daemon::socket_path()?)?; - } else if name != "default" && !context_dir(name)?.join("meta.json").is_file() { - return Err(io::Error::other(format!("there is no docker context `{name}`"))); - } - let path = docker_dir()?.join("config.json"); - let mut cfg = read_json(&path)?; - match cfg.as_object_mut() { - Some(o) if name == "default" => { - o.remove("currentContext"); - } - _ => cfg["currentContext"] = name.into(), - } - write_json(&path, &cfg) + let dir = docker_dir()?; + let host = format!("unix://{}", crate::daemon::socket_path()?.display()); + crate::dockerctx::switch(&dir, &context_dir(name)?, name, CONTEXT.get(), crate::flavor::APP.get(), &host) } /// Links `kiri` and the app's `docker` into `~/.kiri/bin`, puts that @@ -570,14 +591,18 @@ fn bundled_cli(contents: &Path) -> io::Result<()> { let ours = bin_dir()?; std::fs::create_dir_all(&ours)?; // `kiri` itself, for `kiri k8s`, `kiri machine`, `kiri import`… + let app_kiri = contents.join("MacOS/kiri"); let kiri = ours.join("kiri"); let _ = std::fs::remove_file(&kiri); - std::os::unix::fs::symlink(contents.join("MacOS/kiri"), &kiri)?; + std::os::unix::fs::symlink(&app_kiri, &kiri)?; + let brew_linked = !dev() && homebrew_links_this_app(&app_kiri); // Kiri Dev's commands are run by path: ~/.kiri-dev/bin/kiri. - if !dev() { + // When Homebrew's cask `binary` stanza already links `kiri` on PATH to + // this app (#733), leave shell profiles and Homebrew's symlink untouched. + if !dev() && !brew_linked { let h = home()?; - shell_path(&h, &zdotdir(&h))?; - system_link(&kiri); + shell_path_once(&h, &zdotdir(&h))?; + system_link(&kiri, &app_kiri); } let mut bin = contents.join("Resources/bin"); if !bin.join("docker").is_file() { @@ -605,21 +630,65 @@ fn bundled_cli(contents: &Path) -> io::Result<()> { } cfg["cliPluginsExtraDirs"] = dirs.into(); write_json(&path, &cfg)?; - println!("docker and kiri commands: {} (on PATH in new terminal windows)", ours.display()); + if brew_linked || home().is_ok_and(|h| no_profiles_file(&h).exists()) { + println!("docker and kiri commands: {}", ours.display()); + } else { + println!("docker and kiri commands: {} (on PATH in new terminal windows)", ours.display()); + } Ok(()) } +/// Candidate Homebrew `bin/kiri` symlink paths on Apple silicon, Intel Macs, +/// and custom `$HOMEBREW_PREFIX` installations (#733). +fn homebrew_kiri_candidates(homebrew_prefix: Option<&std::ffi::OsStr>) -> Vec { + let mut out = vec![PathBuf::from("/opt/homebrew/bin/kiri"), PathBuf::from(SYSTEM_LINK)]; + if let Some(prefix) = homebrew_prefix.filter(|p| !p.is_empty()) { + let cand = PathBuf::from(prefix).join("bin/kiri"); + if !out.contains(&cand) { + out.push(cand); + } + } + out +} + +/// True when any candidate symlink points directly to `app_kiri` (rather than +/// going through `~/.kiri/bin/kiri`, which `system_link` makes on Intel Macs). +fn homebrew_links_app_in(candidates: &[PathBuf], app_kiri: &Path) -> bool { + let Ok(ours) = std::fs::canonicalize(app_kiri) else { return false }; + let state_bin = format!("/{}/bin/", crate::flavor::STATE.get()); + candidates.iter().any(|cand| { + let Ok(raw) = std::fs::read_link(cand) else { return false }; + let raw_str = raw.to_string_lossy(); + if raw_str.contains("/.kiri/bin/") || raw_str.contains(&state_bin) { + return false; + } + std::fs::canonicalize(cand).is_ok_and(|real| real == ours) + }) +} + +fn homebrew_links_this_app(app_kiri: &Path) -> bool { + homebrew_links_app_in(&homebrew_kiri_candidates(std::env::var_os("HOMEBREW_PREFIX").as_deref()), app_kiri) +} + /// `/usr/local/bin/kiri`, when the user can write there (Homebrew on Intel /// Macs makes it theirs). That directory is on every shell's PATH already, /// so `kiri` works even in a terminal opened before Kiri was. A `kiri` -/// there that isn't Kiri's is left alone. +/// there that isn't Kiri's (or that Homebrew's cask already linked directly to +/// this app) is left alone. const SYSTEM_LINK: &str = "/usr/local/bin/kiri"; -fn system_link(kiri: &Path) { - let link = Path::new(SYSTEM_LINK); +fn system_link(kiri: &Path, app_kiri: &Path) { + system_link_at(Path::new(SYSTEM_LINK), kiri, app_kiri); +} + +fn system_link_at(link: &Path, kiri: &Path, app_kiri: &Path) { // Missing, or a link an older Kiri left (to a Kiri.app or ~/.kiri/bin - // that moved, or to nothing): made again to this one. Anything else there - // isn't Kiri's to replace; stale::stale_kiri() names it. + // that moved, or to nothing): made again to this one. If Homebrew's cask + // already linked `/usr/local/bin/kiri` directly to `app_kiri`, keep + // Homebrew's link so `brew uninstall` owns it (#733). + if homebrew_links_app_in(&[link.to_path_buf()], app_kiri) { + return; + } let replace = match std::fs::read_link(link) { Ok(target) => target != kiri && (kiri_link(&target) || !link.exists()), Err(_) => link.symlink_metadata().is_err(), @@ -707,11 +776,39 @@ fn zdotdir(home: &Path) -> PathBuf { std::env::var_os("ZDOTDIR").filter(|d| !d.is_empty()).map_or_else(|| home.to_path_buf(), PathBuf::from) } -/// Puts ~/.kiri/bin on the shell's PATH in each profile. A profile that -/// can't be written is passed over (and logged), not the end of setup: a -/// link to a dotfiles folder that moved made the app's first launch quit -/// with only "No such file or directory" (#250). +/// Recorded in `~/.kiri` once Kiri has edited shell profiles on initial setup, +/// so subsequent app launches leave removed lines removed (#556). +const PROFILES_CONFIGURED: &str = "profiles-configured"; + +/// Recorded in `~/.kiri` by `kiri setup --no-profiles` so Kiri never edits +/// shell profiles (#556). +const NO_PROFILES: &str = "no-profiles"; + +fn profiles_configured_file(home: &Path) -> PathBuf { + home.join(crate::flavor::STATE.get()).join(PROFILES_CONFIGURED) +} + +fn no_profiles_file(home: &Path) -> PathBuf { + home.join(crate::flavor::STATE.get()).join(NO_PROFILES) +} + +fn mark_profiles_configured(home: &Path) { + let path = profiles_configured_file(home); + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = std::fs::write(path, ""); +} + +/// Puts ~/.kiri/bin on the shell's PATH in each profile, unless the user has +/// opted out with `kiri setup --no-profiles` or a profile already references +/// `.kiri/bin` (#556). A profile that can't be written is passed over (and +/// logged), not the end of setup: a link to a dotfiles folder that moved made +/// the app's first launch quit with only "No such file or directory" (#250). fn shell_path(home: &Path, zdotdir: &Path) -> io::Result<()> { + if no_profiles_file(home).exists() { + return Ok(()); + } for (file, line) in profiles(home, zdotdir) { // A link to nothing (or to a place Kiri can't reach): writing // through it fails when the target's folder is gone (#250), or makes @@ -731,7 +828,7 @@ fn shell_path(home: &Path, zdotdir: &Path) -> io::Result<()> { continue; } }; - if text.contains(PROFILE_MARK) { + if text.contains(PROFILE_MARK) || text.contains(".kiri/bin") { continue; } let sep = if text.is_empty() || text.ends_with('\n') { "" } else { "\n" }; @@ -740,9 +837,68 @@ fn shell_path(home: &Path, zdotdir: &Path) -> io::Result<()> { crate::diag::warn!("shell profile skipped", file = file.display(), error = e); } } + mark_profiles_configured(home); Ok(()) } +/// Edits shell profiles only on the initial setup: once `profiles-configured` +/// or `no-profiles` is recorded in `~/.kiri`, subsequent app launches leave +/// the user's profiles untouched (#556). +fn shell_path_once(home: &Path, zdotdir: &Path) -> io::Result<()> { + if profiles_configured_file(home).exists() || no_profiles_file(home).exists() { + return Ok(()); + } + shell_path(home, zdotdir) +} + +/// `kiri setup --no-profiles`: removes any profile lines Kiri added and +/// records `no-profiles` in `~/.kiri` so future launches and `kiri setup` +/// runs leave shell profiles alone (#556). +fn opt_out_shell_path(home: &Path, zdotdir: &Path) -> io::Result<()> { + remove_shell_path(home, zdotdir)?; + let path = no_profiles_file(home); + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(path, "") +} + +/// Whether `~/.kiri/bin` is currently managed in the user's shell profiles +/// (Settings → Appearance → Command-line tools in shell, #556). +pub(crate) fn shell_path_enabled() -> bool { + let Ok(h) = home() else { return false }; + shell_path_enabled_in(&h, &zdotdir(&h)) +} + +fn shell_path_enabled_in(home: &Path, zdotdir: &Path) -> bool { + if no_profiles_file(home).exists() { + return false; + } + if profiles_configured_file(home).exists() { + return true; + } + profiles(home, zdotdir).into_iter().any(|(file, _)| { + std::fs::read_to_string(&file).is_ok_and(|t| t.contains(PROFILE_MARK) || t.contains(".kiri/bin")) + }) +} + +/// Turns shell profile management on (`shell_path`) or off (`opt_out_shell_path`, +/// equivalent to `kiri setup --no-profiles`) from Settings → Appearance (#556). +pub(crate) fn set_shell_path(enabled: bool) -> io::Result<()> { + let h = home()?; + let z = zdotdir(&h); + set_shell_path_in(&h, &z, enabled) +} + +fn set_shell_path_in(home: &Path, zdotdir: &Path, enabled: bool) -> io::Result<()> { + if enabled { + let _ = std::fs::remove_file(no_profiles_file(home)); + shell_path(home, zdotdir) + } else { + opt_out_shell_path(home, zdotdir) + } +} + fn remove_shell_path(home: &Path, zdotdir: &Path) -> io::Result<()> { for (file, line) in profiles(home, zdotdir) { let Ok(text) = std::fs::read_to_string(&file) else { continue }; @@ -759,6 +915,8 @@ fn remove_shell_path(home: &Path, zdotdir: &Path) -> io::Result<()> { std::fs::write(&file, kept)?; } } + let _ = std::fs::remove_file(profiles_configured_file(home)); + let _ = std::fs::remove_file(no_profiles_file(home)); Ok(()) } @@ -768,7 +926,7 @@ fn default_context() -> io::Result<()> { let h = home()?; // Kiri's own /var/run/docker.sock is not another engine. let ours = crate::daemon::socket_path()?; - let system = !matches!(docker_sock(&ours), DockerSock::Kiri) && Path::new(DOCKER_SOCK).exists(); + let system = !matches!(docker_sock_at_ours(&ours), Endpoint::Kiri) && Path::new(DOCKER_SOCK).exists(); let other = system || [h.join(".orbstack/run/docker.sock"), h.join(".docker/run/docker.sock")].iter().any(|p| p.exists()) || Path::new("/Applications/OrbStack.app").exists() @@ -793,13 +951,12 @@ fn uid() -> u32 { unsafe { libc::getuid() } } -/// A LaunchAgent for `kiri daemon`: started at login, restarted if it -/// crashes, never restarted after a clean exit. -fn agent() -> io::Result { - let exe = std::env::current_exe()?.canonicalize()?; - let log = home()?.join(crate::flavor::STATE.get()).join("daemon.log"); +/// A LaunchAgent for `kiri daemon`: started at login when `run_at_load` is +/// true, restarted if it crashes, never restarted after a clean exit. +pub(crate) fn agent_plist_xml(exe: &Path, log: &Path, run_at_load: bool) -> String { let esc = |p: &Path| p.to_string_lossy().replace('&', "&").replace('<', "<"); - let plist = format!( + let run = if run_at_load { "true" } else { "false" }; + format!( r#" @@ -807,7 +964,7 @@ fn agent() -> io::Result { Label{AGENT} AssociatedBundleIdentifiers{APP_ID} ProgramArguments{}daemon - RunAtLoad + RunAtLoad<{run}/> KeepAliveSuccessfulExit ProcessTypeInteractive StandardOutPath{} @@ -815,10 +972,95 @@ fn agent() -> io::Result { "#, - esc(&exe), - esc(&log), - esc(&log) - ); + esc(exe), + esc(log), + esc(log) + ) +} + +/// Reads `RunAtLoad` from a LaunchAgent plist. +pub(crate) fn plist_run_at_load(xml: &str) -> Option { + let rest = xml.split_once("RunAtLoad")?.1.trim_start(); + if rest.starts_with("") { + Some(true) + } else if rest.starts_with("") { + Some(false) + } else { + None + } +} + +/// Flips `RunAtLoad` in a LaunchAgent plist between `` and ``. +pub(crate) fn set_plist_run_at_load(xml: &str, on: bool) -> Option { + let key = "RunAtLoad"; + let at = xml.find(key)? + key.len(); + let after = &xml[at..]; + let ws = after.len() - after.trim_start().len(); + let tag_at = at + ws; + let old_tag = if xml[tag_at..].starts_with("") { + "" + } else if xml[tag_at..].starts_with("") { + "" + } else { + return None; + }; + let new_tag = if on { "" } else { "" }; + let mut out = String::with_capacity(xml.len() + 1); + out.push_str(&xml[..tag_at]); + out.push_str(new_tag); + out.push_str(&xml[tag_at + old_tag.len()..]); + Some(out) +} + +/// Whether the LaunchAgent is set to start Kiri at sign-in (`RunAtLoad`). +pub fn start_at_login() -> bool { + agent_plist() + .ok() + .and_then(|p| std::fs::read_to_string(p).ok()) + .and_then(|xml| plist_run_at_load(&xml)) + .unwrap_or(true) +} + +/// Updates `RunAtLoad` in `path` (or writes a valid LaunchAgent plist when missing). +pub(crate) fn set_start_at_login_at(path: &Path, exe: &Path, log: &Path, on: bool) -> io::Result<()> { + if let Ok(xml) = std::fs::read_to_string(path) + && let Some(updated) = set_plist_run_at_load(&xml, on) + { + return std::fs::write(path, updated); + } + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + if let Some(dir) = log.parent() { + std::fs::create_dir_all(dir)?; + } + std::fs::write(path, agent_plist_xml(exe, log, on)) +} + +/// Settings → Appearance → Start Kiri at sign-in: updates `RunAtLoad` in the +/// LaunchAgent plist while keeping the plist valid for on-demand launchd. +pub fn set_start_at_login(on: bool) -> io::Result<()> { + let path = agent_plist()?; + let exe = std::env::current_exe()?.canonicalize()?; + let log = home()?.join(crate::flavor::STATE.get()).join("daemon.log"); + set_start_at_login_at(&path, &exe, &log, on) +} + +/// Unloads the LaunchAgent from launchd, stopping `kiri daemon` if launchd runs it. +pub fn bootout_agent() { + let _ = Command::new("/bin/launchctl") + .args(["bootout", &format!("gui/{}/{AGENT}", uid())]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status(); +} + +/// A LaunchAgent for `kiri daemon`: started at login, restarted if it +/// crashes, never restarted after a clean exit. +fn agent() -> io::Result { + let exe = std::env::current_exe()?.canonicalize()?; + let log = home()?.join(crate::flavor::STATE.get()).join("daemon.log"); + let plist = agent_plist_xml(&exe, &log, true); let path = agent_plist()?; if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; @@ -858,12 +1100,15 @@ pub fn start_agent() -> io::Result { if kicked { return Ok(true); } - // Not loaded: bootstrap it, and RunAtLoad starts it. + // Not loaded: bootstrap it, then kickstart it (when RunAtLoad is false, + // bootstrap loads the job without starting it). let loaded = Command::new("/bin/launchctl").args(["bootstrap", &format!("gui/{}", uid())]).arg(agent_plist()?).stderr(std::process::Stdio::null()).status()?.success(); if !loaded { crate::diag::info!("the LaunchAgent would not load; starting the engine directly"); + return Ok(false); } - Ok(loaded) + let _ = Command::new("/bin/launchctl").args(["kickstart", &job]).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()).status(); + Ok(true) } /// Whether the LaunchAgent starts this copy of Kiri. One left by another @@ -980,13 +1225,26 @@ mod tests { d } + /// Settings → Storage moved the data folder: Kiri Lite's plugin folder + /// follows it, and other plugin folders stay. + #[test] + fn plugin_folders_follow_the_data_folder() { + use std::path::Path; + let (old, new) = (Path::new("/Users/u/Library/Application Support/Kiri"), Path::new("/Volumes/External/kiri")); + let mut cfg = serde_json::json!({"cliPluginsExtraDirs": ["/opt/homebrew/lib/docker/cli-plugins", "/Users/u/Library/Application Support/Kiri/cli/cli-plugins"]}); + assert!(super::repoint_plugin_dirs(&mut cfg, old, new)); + assert_eq!(cfg["cliPluginsExtraDirs"], serde_json::json!(["/opt/homebrew/lib/docker/cli-plugins", "/Volumes/External/kiri/cli/cli-plugins"])); + assert!(!super::repoint_plugin_dirs(&mut cfg, old, new), "nothing left to move"); + assert_eq!(super::moved(Path::new("/elsewhere/docker"), old, new), None); + } + #[test] fn docker_sock_owner() { - use super::DockerSock::*; + use crate::dockerctx::Endpoint::*; let d = scratch("sock"); let ours = d.join("kiri/run/docker.sock"); let link = d.join("docker.sock"); - let at = |engines: &[std::path::PathBuf]| super::docker_sock_at(&link, &ours, engines); + let at = |engines: &[std::path::PathBuf]| crate::dockerctx::sock_at(&link, &ours, engines); assert_eq!(at(&[]), Free); std::os::unix::fs::symlink(&ours, &link).unwrap(); assert_eq!(at(&[]), Kiri, "Kiri's link, even with the daemon stopped"); @@ -1109,6 +1367,131 @@ mod tests { assert_eq!(read(".profile").trim_end(), "export B=2"); assert_eq!(read(".zshrc").trim(), ""); assert!(!read(".bashrc").contains("kiri")); + assert!(!super::profiles_configured_file(&h).exists()); + assert!(!super::no_profiles_file(&h).exists()); + let _ = std::fs::remove_dir_all(&h); + } + + // #556: initial setup records `profiles-configured` in `~/.kiri` so + // subsequent app launches (`shell_path_once`) do not re-append Kiri's + // block after the user or a dotfiles manager removes it, until + // `kiri setup --uninstall` resets state. + #[test] + fn first_launch_edits_shell_profiles_only_once() { + let h = scratch("once"); + std::fs::write(h.join(".zprofile"), "export A=1\n").unwrap(); + std::fs::write(h.join(".zshrc"), "export B=2\n").unwrap(); + + super::shell_path_once(&h, &h).unwrap(); + assert!(super::profiles_configured_file(&h).is_file()); + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + assert!(std::fs::read_to_string(h.join(".zshrc")).unwrap().contains(super::PROFILE_MARK)); + + // The user or a dotfiles manager restores the profiles without Kiri's block. + std::fs::write(h.join(".zprofile"), "export A=1\n").unwrap(); + std::fs::write(h.join(".zshrc"), "export B=2\n").unwrap(); + + // Subsequent app launches leave the cleaned-up profiles untouched. + super::shell_path_once(&h, &h).unwrap(); + assert_eq!(std::fs::read_to_string(h.join(".zprofile")).unwrap(), "export A=1\n"); + assert_eq!(std::fs::read_to_string(h.join(".zshrc")).unwrap(), "export B=2\n"); + + // Explicit `kiri setup` from the CLI still adds the lines when asked. + super::shell_path(&h, &h).unwrap(); + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + assert!(std::fs::read_to_string(h.join(".zshrc")).unwrap().contains(super::PROFILE_MARK)); + + // Uninstall removes the lines and clears the marker so a fresh install sets up again. + super::remove_shell_path(&h, &h).unwrap(); + assert!(!super::profiles_configured_file(&h).exists()); + std::fs::write(h.join(".zprofile"), "export A=1\n").unwrap(); + std::fs::write(h.join(".zshrc"), "export B=2\n").unwrap(); + super::shell_path_once(&h, &h).unwrap(); + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + assert!(std::fs::read_to_string(h.join(".zshrc")).unwrap().contains(super::PROFILE_MARK)); + + let _ = std::fs::remove_dir_all(&h); + } + + // #556: a profile that already puts `~/.kiri/bin` on PATH without Kiri's + // marker comment (such as a dotfiles-managed profile) is not given a + // duplicate block even on the first setup, and uninstall leaves the user's + // line alone. + #[test] + fn profile_already_referencing_kiri_bin_is_not_duplicated() { + let h = scratch("dotfiles-path"); + let custom_zsh = "export PATH=\"$HOME/.kiri/bin:$PATH\"\n"; + let custom_bash = "path_prepend ~/.kiri/bin\n"; + let custom_fish = "fish_add_path ~/.kiri/bin\n"; + std::fs::write(h.join(".zshrc"), custom_zsh).unwrap(); + std::fs::write(h.join(".bashrc"), custom_bash).unwrap(); + std::fs::create_dir_all(h.join(".config/fish/conf.d")).unwrap(); + std::fs::write(h.join(".config/fish/conf.d/kiri.fish"), custom_fish).unwrap(); + + super::shell_path_once(&h, &h).unwrap(); + + // Profiles that already reference `.kiri/bin` are untouched. + assert_eq!(std::fs::read_to_string(h.join(".zshrc")).unwrap(), custom_zsh); + assert_eq!(std::fs::read_to_string(h.join(".bashrc")).unwrap(), custom_bash); + assert_eq!(std::fs::read_to_string(h.join(".config/fish/conf.d/kiri.fish")).unwrap(), custom_fish); + // Profiles without `.kiri/bin` still get the block on initial setup. + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + + // Uninstall removes only Kiri's marked block and preserves the user's own `.kiri/bin` lines. + super::remove_shell_path(&h, &h).unwrap(); + assert_eq!(std::fs::read_to_string(h.join(".zshrc")).unwrap(), custom_zsh); + assert_eq!(std::fs::read_to_string(h.join(".bashrc")).unwrap(), custom_bash); + assert_eq!(std::fs::read_to_string(h.join(".config/fish/conf.d/kiri.fish")).unwrap(), custom_fish); + assert_eq!(std::fs::read_to_string(h.join(".zprofile")).unwrap().trim(), ""); + + let _ = std::fs::remove_dir_all(&h); + } + + // #556: `kiri setup --no-profiles` removes any existing Kiri block, records + // `no-profiles` in `~/.kiri` so neither subsequent launches nor `kiri setup` + // touch shell profiles, and `kiri setup --uninstall` clears the opt-out. + #[test] + fn no_profiles_opt_out_removes_existing_lines_and_persists_until_uninstall() { + let h = scratch("no-profiles"); + std::fs::write(h.join(".zprofile"), "export A=1\n").unwrap(); + std::fs::write(h.join(".zshrc"), "export B=2\n").unwrap(); + + // Initial setup adds Kiri's lines. + super::shell_path_once(&h, &h).unwrap(); + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + assert!(std::fs::read_to_string(h.join(".zshrc")).unwrap().contains(super::PROFILE_MARK)); + + // Opting out with `kiri setup --no-profiles` removes Kiri's lines and persists `no-profiles`. + super::opt_out_shell_path(&h, &h).unwrap(); + assert!(!super::shell_path_enabled_in(&h, &h)); + assert!(super::no_profiles_file(&h).is_file()); + assert!(!super::profiles_configured_file(&h).exists()); + assert_eq!(std::fs::read_to_string(h.join(".zprofile")).unwrap().trim_end(), "export A=1"); + assert_eq!(std::fs::read_to_string(h.join(".zshrc")).unwrap().trim_end(), "export B=2"); + + // Neither subsequent app launches nor explicit `kiri setup` edit profiles while opted out. + super::shell_path_once(&h, &h).unwrap(); + super::shell_path(&h, &h).unwrap(); + assert_eq!(std::fs::read_to_string(h.join(".zprofile")).unwrap().trim_end(), "export A=1"); + assert_eq!(std::fs::read_to_string(h.join(".zshrc")).unwrap().trim_end(), "export B=2"); + + // Settings → Appearance toggling On re-enables profiles and clears `no-profiles`; Off opts out again. + super::set_shell_path_in(&h, &h, true).unwrap(); + assert!(super::shell_path_enabled_in(&h, &h)); + assert!(!super::no_profiles_file(&h).exists()); + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + super::set_shell_path_in(&h, &h, false).unwrap(); + assert!(!super::shell_path_enabled_in(&h, &h)); + assert!(super::no_profiles_file(&h).is_file()); + + // Uninstall clears `no-profiles` so a fresh install after uninstall sets up profiles again. + super::remove_shell_path(&h, &h).unwrap(); + assert!(!super::no_profiles_file(&h).exists()); + super::shell_path_once(&h, &h).unwrap(); + assert!(std::fs::read_to_string(h.join(".zprofile")).unwrap().contains(super::PROFILE_MARK)); + assert!(std::fs::read_to_string(h.join(".zshrc")).unwrap().contains(super::PROFILE_MARK)); + + let _ = std::fs::remove_dir_all(&h); } #[test] @@ -1122,4 +1505,87 @@ mod tests { .unwrap(); assert_eq!(String::from_utf8_lossy(&out.stdout), "/usr/bin:/bin:/h/.kiri/bin"); } + + #[test] + fn launch_agent_plist_run_at_load_generates_parses_and_toggles() { + let d = scratch("plist"); + let exe = std::path::Path::new("/Applications/Kiri.app/Contents/MacOS/kiri"); + let log = d.join(".kiri/daemon.log"); + let plist_path = d.join("Library/LaunchAgents/dev.kiri.daemon.plist"); + + let xml_on = super::agent_plist_xml(exe, &log, true); + assert_eq!(super::plist_run_at_load(&xml_on), Some(true)); + assert!(xml_on.contains("RunAtLoad")); + + let xml_off = super::agent_plist_xml(exe, &log, false); + assert_eq!(super::plist_run_at_load(&xml_off), Some(false)); + assert!(xml_off.contains("RunAtLoad")); + + let flipped_off = super::set_plist_run_at_load(&xml_on, false).unwrap(); + assert_eq!(flipped_off, xml_off); + assert_eq!(super::plist_run_at_load(&flipped_off), Some(false)); + + let flipped_on = super::set_plist_run_at_load(&flipped_off, true).unwrap(); + assert_eq!(flipped_on, xml_on); + assert_eq!(super::plist_run_at_load(&flipped_on), Some(true)); + + // File creation and in-place toggling keep the rest of the plist valid. + super::set_start_at_login_at(&plist_path, exe, &log, true).unwrap(); + assert_eq!(super::plist_run_at_load(&std::fs::read_to_string(&plist_path).unwrap()), Some(true)); + super::set_start_at_login_at(&plist_path, exe, &log, false).unwrap(); + let saved = std::fs::read_to_string(&plist_path).unwrap(); + assert_eq!(super::plist_run_at_load(&saved), Some(false)); + assert!(saved.contains("/Applications/Kiri.app/Contents/MacOS/kiridaemon")); + super::set_start_at_login_at(&plist_path, exe, &log, true).unwrap(); + assert_eq!(super::plist_run_at_load(&std::fs::read_to_string(&plist_path).unwrap()), Some(true)); + + let _ = std::fs::remove_dir_all(&d); + } + + // #733: when Homebrew's cask `binary` stanza links `$(brew --prefix)/bin/kiri` + // directly to `Kiri.app/Contents/MacOS/kiri`, setup recognizes it, skips + // shell profile edits, and preserves Homebrew's `/usr/local/bin/kiri` link, + // while Kiri's own `~/.kiri/bin/kiri` indirect link is not mistaken for Homebrew's. + #[test] + fn homebrew_cask_binary_link_is_detected_and_preserved() { + let d = scratch("homebrew-link"); + let app_kiri = d.join("Applications/Kiri.app/Contents/MacOS/kiri"); + let other_app = d.join("Downloads/Kiri.app/Contents/MacOS/kiri"); + let our_bin_kiri = d.join(".kiri/bin/kiri"); + let opt_brew_kiri = d.join("opt/homebrew/bin/kiri"); + let usr_local_kiri = d.join("usr/local/bin/kiri"); + for p in [&app_kiri, &other_app, &our_bin_kiri, &opt_brew_kiri, &usr_local_kiri] { + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + } + std::fs::write(&app_kiri, "#!/bin/sh\n").unwrap(); + std::fs::write(&other_app, "#!/bin/sh\n").unwrap(); + std::os::unix::fs::symlink(&app_kiri, &our_bin_kiri).unwrap(); + + // No Homebrew link yet. + assert!(!super::homebrew_links_app_in(&[opt_brew_kiri.clone(), usr_local_kiri.clone()], &app_kiri)); + + // Kiri's own `system_link` (`/usr/local/bin/kiri -> ~/.kiri/bin/kiri`) is NOT a Homebrew cask link. + super::system_link_at(&usr_local_kiri, &our_bin_kiri, &app_kiri); + assert_eq!(std::fs::read_link(&usr_local_kiri).unwrap(), our_bin_kiri); + assert!(!super::homebrew_links_app_in(&[opt_brew_kiri.clone(), usr_local_kiri.clone()], &app_kiri)); + + // Homebrew cask link on Apple silicon (`/opt/homebrew/bin/kiri -> .../Kiri.app/Contents/MacOS/kiri`). + std::os::unix::fs::symlink(&app_kiri, &opt_brew_kiri).unwrap(); + assert!(super::homebrew_links_app_in(&[opt_brew_kiri.clone()], &app_kiri)); + assert!(!super::homebrew_links_app_in(&[opt_brew_kiri.clone()], &other_app)); + + // Homebrew cask link on Intel (`/usr/local/bin/kiri -> .../Kiri.app/Contents/MacOS/kiri`) is preserved by `system_link_at`. + std::fs::remove_file(&usr_local_kiri).unwrap(); + std::os::unix::fs::symlink(&app_kiri, &usr_local_kiri).unwrap(); + assert!(super::homebrew_links_app_in(&[usr_local_kiri.clone()], &app_kiri)); + super::system_link_at(&usr_local_kiri, &our_bin_kiri, &app_kiri); + assert_eq!(std::fs::read_link(&usr_local_kiri).unwrap(), app_kiri, "Homebrew's direct cask link stays untouched"); + + // Custom `$HOMEBREW_PREFIX` adds `/bin/kiri` without duplicating standard prefixes. + let cands = super::homebrew_kiri_candidates(Some(std::ffi::OsStr::new("/custom/brew"))); + assert!(cands.contains(&std::path::PathBuf::from("/custom/brew/bin/kiri"))); + assert_eq!(super::homebrew_kiri_candidates(Some(std::ffi::OsStr::new("/opt/homebrew"))).len(), 2); + + let _ = std::fs::remove_dir_all(&d); + } } diff --git a/crates/kiri/src/setup_win.rs b/crates/kiri/src/setup_win.rs new file mode 100644 index 000000000..4b3266471 --- /dev/null +++ b/crates/kiri/src/setup_win.rs @@ -0,0 +1,310 @@ +//! `kiri setup` on Windows: ensures `%USERPROFILE%\.docker\config.json` has +//! Kiri's `cli-plugins` folder (`docker compose`, `docker buildx`), writes the +//! `kiri` Docker context (`npipe:////./pipe/kiri`), and sets `currentContext` +//! to `kiri` when `--use` is given or when `currentContext` is empty or points +//! at a removed engine such as `desktop-linux` after uninstalling Docker +//! Desktop (#984). + +#![cfg_attr(not(windows), allow(dead_code))] + +use std::io; +use std::path::{Path, PathBuf}; + +use crate::dockerctx::{ + WindowsRepair, WindowsRepairOpts, find_windows_cli_plugins, repair_windows_config, +}; + +const USAGE: &str = "usage: kiri setup [--use]"; + +fn npipe_host(pipe: &str) -> String { + format!("npipe:{}", pipe.replace('\\', "/")) +} + +/// Best-effort background self-heal of `%USERPROFILE%\.docker\config.json` and +/// Kiri's `kiri` Docker context before invoking `docker.exe --context kiri` on +/// Windows (#984). +#[cfg(windows)] +pub fn heal_quietly() { + let Some(dir) = crate::dockerctx::docker_dir() else { + return; + }; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| { + Path::new(&p) + .join(r"Docker\Docker\Docker Desktop.exe") + .is_file() + }); + let host = npipe_host(&crate::client::pipe()); + let _ = repair_windows_config( + &dir, + WindowsRepairOpts { + ours: crate::flavor::CONTEXT.get(), + description: "Kiri (WSL2)", + host: &host, + plugins_dir: plugins.as_deref(), + force_context_write: false, + set_current_if_empty: false, + force_use: false, + desktop_installed: desktop, + }, + ); +} + +pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } + let mut force_use = false; + for a in args { + match a.as_str() { + "--use" => force_use = true, + _ => return Err(io::Error::new(io::ErrorKind::InvalidInput, USAGE)), + } + } + let dir = + crate::dockerctx::docker_dir().ok_or_else(|| io::Error::other("USERPROFILE is not set"))?; + let exe = std::env::current_exe().ok(); + let local = std::env::var_os("LOCALAPPDATA").map(PathBuf::from); + let plugins = find_windows_cli_plugins(exe.as_deref(), local.as_deref()); + let desktop = std::env::var_os("ProgramFiles").is_some_and(|p| { + Path::new(&p) + .join(r"Docker\Docker\Docker Desktop.exe") + .is_file() + }); + #[cfg(windows)] + let host = npipe_host(&crate::client::pipe()); + #[cfg(not(windows))] + let host = "npipe:////./pipe/kiri".to_owned(); + + let mut out = Vec::new(); + run_in( + &dir, + &host, + plugins.as_deref(), + force_use, + desktop, + &mut out, + )?; + print!("{}", String::from_utf8_lossy(&out)); + + #[cfg(windows)] + if crate::client::alive() { + match crate::builds::builder() { + Ok(true) => match crate::buildwith::places().map(|p| p.saved()) { + Ok(Some(crate::buildwith::With::Kiri)) => { + println!( + "docker build uses BuildKit in Kiri (builder `{}`)", + crate::builds::BUILDER + ); + } + _ => println!( + "docker build follows docker's context, and builds on Kiri when docker uses Kiri (`kiri build-with kiri` sends every build to Kiri)" + ), + }, + Ok(false) => {} + Err(e) => println!( + "docker build: the `{}` builder comes later ({e})", + crate::builds::BUILDER + ), + } + } + Ok(()) +} + +fn run_in( + dir: &Path, + host: &str, + plugins: Option<&Path>, + force_use: bool, + desktop_installed: bool, + out: &mut impl io::Write, +) -> io::Result { + let ours = crate::flavor::CONTEXT.get(); + let r = repair_windows_config( + dir, + WindowsRepairOpts { + ours, + description: "Kiri (WSL2)", + host, + plugins_dir: plugins, + force_context_write: true, + set_current_if_empty: true, + force_use, + desktop_installed, + }, + )?; + writeln!(out, "docker context `{ours}` → {host}")?; + if r.current_context_set || force_use { + writeln!( + out, + "docker now uses Kiri by default (`docker context use default` to switch back)" + )?; + } + if let Some(p) = plugins { + writeln!(out, "docker cli-plugins → {}", p.display())?; + } + Ok(r) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::dockerctx::{context_meta, read_json, write_context, write_json}; + use serde_json::json; + + fn scratch(tag: &str) -> PathBuf { + static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let d = std::env::temp_dir().join(format!( + "kiri-setup-win-{tag}-{}-{}", + std::process::id(), + SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + )); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn help_and_invalid_flags_have_no_side_effects() { + for h in [&["--help"][..], &["-h"], &["help"], &["--use", "--help"]] { + let v: Vec = h.iter().map(|s| (*s).to_owned()).collect(); + run(&v).unwrap(); + } + for bad in [&["--bogus"][..], &["--uninstall"], &["extra"]] { + let v: Vec = bad.iter().map(|s| (*s).to_owned()).collect(); + let err = run(&v).unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::InvalidInput); + assert_eq!(err.to_string(), USAGE); + } + } + + #[test] + fn repairs_wiped_docker_config_and_dangling_desktop_linux_context() { + let root = scratch("repair"); + let docker = root.join(".docker"); + let plugins = root.join("Kiri/bin/cli-plugins"); + std::fs::create_dir_all(&plugins).unwrap(); + + // 1. Fresh / wiped config.json after Docker Desktop uninstall: creates `kiri` context, + // registers cliPluginsExtraDirs, and sets currentContext = "kiri". + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + false, + &mut out, + ) + .unwrap(); + assert_eq!( + r, + WindowsRepair { + context_written: true, + plugins_added: true, + current_context_set: true + } + ); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "kiri"); + assert_eq!( + cfg["cliPluginsExtraDirs"], + json!([plugins.to_string_lossy()]) + ); + let meta = read_json(&context_meta(&docker, "kiri").join("meta.json")).unwrap(); + assert_eq!(meta["Endpoints"]["docker"]["Host"], "npipe:////./pipe/kiri"); + let printed = String::from_utf8(out).unwrap(); + assert!( + printed.contains("docker context `kiri` → npipe:////./pipe/kiri"), + "{printed}" + ); + assert!( + printed.contains("docker now uses Kiri by default"), + "{printed}" + ); + assert!(printed.contains("docker cli-plugins →"), "{printed}"); + + // 2. Existing config with logins and an active `desktop-linux` context while Docker Desktop + // is still installed: keeps `desktop-linux` without `--use`, switches with `--use`. + write_context( + &context_meta(&docker, "desktop-linux"), + "desktop-linux", + "Docker Desktop", + "npipe:////./pipe/dockerDesktopLinuxEngine", + ) + .unwrap(); + write_json( + &docker.join("config.json"), + &json!({ + "auths": {"ghcr.io": {"auth": "dG9rZW4="}}, + "currentContext": "desktop-linux", + }), + ) + .unwrap(); + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + true, + &mut out, + ) + .unwrap(); + assert!(!r.current_context_set); + let cfg = read_json(&docker.join("config.json")).unwrap(); + assert_eq!(cfg["currentContext"], "desktop-linux"); + assert_eq!(cfg["auths"]["ghcr.io"]["auth"], "dG9rZW4="); + assert_eq!( + cfg["cliPluginsExtraDirs"], + json!([plugins.to_string_lossy()]) + ); + + // Docker Desktop uninstalled (`desktop_installed = false`), leaving stale `desktop-linux`: + // `kiri setup` heals `currentContext` to `kiri` automatically! + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + false, + false, + &mut out, + ) + .unwrap(); + assert!(r.current_context_set); + assert_eq!( + read_json(&docker.join("config.json")).unwrap()["currentContext"], + "kiri" + ); + + // With Docker Desktop installed and `--use`: explicitly switches to `kiri`. + write_json( + &docker.join("config.json"), + &json!({"currentContext": "desktop-linux"}), + ) + .unwrap(); + let mut out = Vec::new(); + let r = run_in( + &docker, + "npipe:////./pipe/kiri", + Some(&plugins), + true, + true, + &mut out, + ) + .unwrap(); + assert!(r.current_context_set); + assert_eq!( + read_json(&docker.join("config.json")).unwrap()["currentContext"], + "kiri" + ); + + let _ = std::fs::remove_dir_all(&root); + } +} diff --git a/crates/kiri/src/share.rs b/crates/kiri/src/share.rs index e69614a7e..009faf769 100644 --- a/crates/kiri/src/share.rs +++ b/crates/kiri/src/share.rs @@ -30,7 +30,7 @@ use std::net::{Shutdown, TcpStream, ToSocketAddrs}; use std::path::PathBuf; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc; -use std::sync::{Arc, Condvar, Mutex}; +use std::sync::{Arc, Condvar, Mutex, PoisonError}; use std::thread::JoinHandle; use std::time::{Duration, Instant, SystemTime}; @@ -101,10 +101,22 @@ struct TrafficFile { url: Mutex, counts: [AtomicU64; 3], dirty: AtomicBool, - done: AtomicBool, + /// Serializes writes to `path` and `Event::Ended` teardown; once `true`, + /// neither a timer tick nor a late event can recreate `path` after removal. + ended: Mutex, } impl TrafficFile { + fn new(path: PathBuf) -> Self { + TrafficFile { + path, + url: Mutex::new(String::new()), + counts: [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)], + dirty: AtomicBool::new(false), + ended: Mutex::new(false), + } + } + fn start() -> Option> { let dir = traffic_dir().ok()?; std::fs::create_dir_all(&dir).ok()?; @@ -114,18 +126,12 @@ impl TrafficFile { let _ = std::fs::remove_file(e.path()); } } - let f = Arc::new(TrafficFile { - path: dir.join(format!("{}.json", std::process::id())), - url: Mutex::new(String::new()), - counts: [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)], - dirty: AtomicBool::new(false), - done: AtomicBool::new(false), - }); + let f = Arc::new(TrafficFile::new(dir.join(format!("{}.json", std::process::id())))); let w = f.clone(); std::thread::spawn(move || { - while !w.done.load(Ordering::SeqCst) { + while !*w.ended.lock().unwrap_or_else(PoisonError::into_inner) { std::thread::sleep(Duration::from_secs(2)); - if w.dirty.swap(false, Ordering::SeqCst) && !w.done.load(Ordering::SeqCst) { + if w.dirty.swap(false, Ordering::SeqCst) { w.write(); } } @@ -134,18 +140,25 @@ impl TrafficFile { } fn write(&self) { - let [r, i, o] = &self.counts; - let v = json!({"url": *self.url.lock().unwrap(), "requests": r.load(Ordering::Relaxed), "in": i.load(Ordering::Relaxed), "out": o.load(Ordering::Relaxed)}); - let tmp = self.path.with_extension("tmp"); - if std::fs::write(&tmp, v.to_string()).is_ok() { - let _ = std::fs::rename(&tmp, &self.path); + let ended = self.ended.lock().unwrap_or_else(PoisonError::into_inner); + if *ended { + return; } + let [r, i, o] = &self.counts; + let v = json!({ + "url": *self.url.lock().unwrap_or_else(PoisonError::into_inner), + "requests": r.load(Ordering::Relaxed), + "in": i.load(Ordering::Relaxed), + "out": o.load(Ordering::Relaxed), + }); + // The file holds a shared URL's traffic; readable only by this user. + let _ = write_private_atomic(&self.path, v.to_string().as_bytes(), false); } fn on(&self, e: &Event) { match e { Event::Live { url, .. } => { - *self.url.lock().unwrap() = url.clone(); + *self.url.lock().unwrap_or_else(PoisonError::into_inner) = url.clone(); self.write(); } Event::Request(r) => { @@ -155,7 +168,8 @@ impl TrafficFile { self.dirty.store(true, Ordering::SeqCst); } Event::Ended { .. } => { - self.done.store(true, Ordering::SeqCst); + let mut ended = self.ended.lock().unwrap_or_else(PoisonError::into_inner); + *ended = true; let _ = std::fs::remove_file(&self.path); } _ => {} @@ -283,24 +297,83 @@ pub fn read_config() -> Config { cfg } -/// Writes the config atomically, readable only by this user (it holds the token). -pub fn save(cfg: &Config) -> io::Result<()> { - let path = config_path()?; - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - let tmp = path.with_extension("json.tmp"); +static ATOMIC_TMP_SEQ: AtomicU64 = AtomicU64::new(0); + +fn next_tmp_path(path: &std::path::Path) -> PathBuf { + let mut name = path + .file_name() + .map(std::ffi::OsString::from) + .unwrap_or_else(|| std::ffi::OsString::from("file")); + let seq = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed); + name.push(format!(".{}.{}.tmp", std::process::id(), seq)); + path.with_file_name(name) +} + +/// Writes `bytes` to a unique sibling temp file opened with `create_new(true)` +/// and mode `0600` (so it never follows symlinks or races on a shared `.tmp` +/// filename), cleaning up the temp file on any write or rename error. +fn write_private_atomic(path: &std::path::Path, bytes: &[u8], sync: bool) -> io::Result<()> { + write_private_atomic_with(path, bytes, sync, || next_tmp_path(path)) +} + +fn write_private_atomic_with( + path: &std::path::Path, + bytes: &[u8], + sync: bool, + mut next_tmp: impl FnMut() -> PathBuf, +) -> io::Result<()> { let mut options = std::fs::OpenOptions::new(); - options.write(true).create(true).truncate(true); + options.write(true).create_new(true); #[cfg(unix)] { use std::os::unix::fs::OpenOptionsExt; options.mode(0o600); } - let mut f = options.open(&tmp)?; - f.write_all(serde_json::to_string_pretty(cfg).map_err(io::Error::other)?.as_bytes())?; - f.sync_all()?; - std::fs::rename(&tmp, &path) + let mut opened = None; + for _ in 0..64 { + let candidate = next_tmp(); + match options.open(&candidate) { + Ok(f) => { + opened = Some((candidate, f)); + break; + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e), + } + } + let (tmp, mut f) = opened.ok_or_else(|| io::Error::new(io::ErrorKind::AlreadyExists, "could not create unique temporary file"))?; + let write_res = (|| -> io::Result<()> { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + f.set_permissions(std::fs::Permissions::from_mode(0o600))?; + } + f.write_all(bytes)?; + if sync { + f.sync_all()?; + } + Ok(()) + })(); + drop(f); + if let Err(e) = write_res { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + if let Err(e) = std::fs::rename(&tmp, path) { + let _ = std::fs::remove_file(&tmp); + return Err(e); + } + Ok(()) +} + +/// Writes the config atomically, readable only by this user (it holds the token). +pub fn save(cfg: &Config) -> io::Result<()> { + let path = config_path()?; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let data = serde_json::to_string_pretty(cfg).map_err(io::Error::other)?; + write_private_atomic(&path, data.as_bytes(), true) } // ---------------------------------------------------------------- the edge @@ -328,15 +401,60 @@ fn server(cfg: &Config) -> Server { Server { host, port, dial } } -fn tls_config(alpn: &[u8]) -> io::Result> { +/// Largest `KIRI_SHARE_CA` PEM file accepted (2 MiB) and most certificates +/// read from it, bounding memory even on hostile or misconfigured paths. +const MAX_SHARE_CA_BYTES: u64 = 2 << 20; +const MAX_SHARE_CA_CERTS: usize = 1024; + +/// The roots a Share tunnel verifies against: the system's roots merged +/// with webpki's (like the registry client, #303), plus `share_ca` +/// (`KIRI_SHARE_CA`), skipping any certificate rustls refuses to add — +/// the same quiet skip as `platform_certs()` skipping load errors. The +/// merged list comes from places the user doesn't curate (the keychain, +/// `/etc/ssl`), so one anchor rustls won't take shouldn't take every +/// tunnel down. `share_ca`, unlike the merged roots, is chosen on +/// purpose: an explicit CA that doesn't parse is a misconfiguration +/// worth reporting. +fn root_store( + trusted: &[rustls::pki_types::CertificateDer<'static>], + share_ca: Option<&std::path::Path>, +) -> io::Result { let mut roots = rustls::RootCertStore::empty(); - roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); - if let Some(ca) = std::env::var_os("KIRI_SHARE_CA") { - let certs = rustls::pki_types::CertificateDer::pem_file_iter(&ca).map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?; - for c in certs { - roots.add(c.map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?).map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?; + roots.add_parsable_certificates(trusted.to_vec()); + if let Some(ca) = share_ca { + use std::io::Read as _; + let f = std::fs::File::open(ca).map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?; + if !f.metadata().map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?.is_file() { + return Err(io::Error::other("KIRI_SHARE_CA: not a regular file")); + } + let mut bytes = Vec::new(); + f.take(MAX_SHARE_CA_BYTES + 1) + .read_to_end(&mut bytes) + .map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?; + if bytes.len() as u64 > MAX_SHARE_CA_BYTES { + return Err(io::Error::other(format!( + "KIRI_SHARE_CA: file exceeds {} MiB", + MAX_SHARE_CA_BYTES >> 20 + ))); + } + for (i, c) in rustls::pki_types::CertificateDer::pem_slice_iter(&bytes).enumerate() { + if i >= MAX_SHARE_CA_CERTS { + return Err(io::Error::other(format!( + "KIRI_SHARE_CA: more than {MAX_SHARE_CA_CERTS} certificates" + ))); + } + roots + .add(c.map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?) + .map_err(|e| io::Error::other(format!("KIRI_SHARE_CA: {e}")))?; } } + Ok(roots) +} + +fn tls_config(alpn: &[u8]) -> io::Result> { + // KIRI_SHARE_CA, if set, is added on top of the merged roots, last. + let share_ca = std::env::var_os("KIRI_SHARE_CA").map(std::path::PathBuf::from); + let roots = root_store(&crate::roots::trusted(), share_ca.as_deref())?; let provider = Arc::new(rustls::crypto::ring::default_provider()); let mut c = rustls::ClientConfig::builder_with_provider(provider) .with_safe_default_protocol_versions() @@ -752,6 +870,41 @@ pub fn is_shorthand(arg: &str) -> bool { port_or_addr(arg).is_some() } +fn is_local_ip(ip: std::net::IpAddr) -> bool { + match ip { + std::net::IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(), + std::net::IpAddr::V6(v6) => { + v6.is_loopback() + || v6.is_unspecified() + || v6.to_ipv4_mapped().is_some_and(|v4| v4.is_loopback() || v4.is_unspecified()) + } + } +} + +/// A target that isn't one of this machine's own loopback or unspecified names +/// or addresses. Sharing it puts a public URL in front of a service that lives +/// elsewhere on the machine's network, so the tunnel warns about it. +fn target_is_global(t: &Target) -> bool { + let Some((host, _)) = t.addr.rsplit_once(':') else { return false }; + let host = host.trim_start_matches('[').trim_end_matches(']'); + if host.trim_end_matches('.').eq_ignore_ascii_case("localhost") { + return false; + } + match host.parse::() { + Ok(ip) => !is_local_ip(ip), + Err(_) => true, + } +} + +fn non_local_warning(t: &Target) -> Option { + target_is_global(t).then(|| { + format!( + "`{}` is not localhost: the public URL reaches it, whoever has the link.", + t.display + ) + }) +} + fn port_or_addr(arg: &str) -> Option { if !arg.is_empty() && arg.len() <= 5 && arg.bytes().all(|b| b.is_ascii_digit()) { let port: u16 = arg.parse().ok().filter(|p| *p > 0)?; @@ -936,13 +1089,13 @@ struct Stopper { impl Stopper { fn is_stopped(&self) -> bool { - *self.stopped.lock().unwrap() + *self.stopped.lock().unwrap_or_else(PoisonError::into_inner) } /// Sleeps up to `d`; returns true if stopped meanwhile. fn sleep(&self, d: Duration) -> bool { - let g = self.stopped.lock().unwrap(); - let (g, _) = self.cv.wait_timeout_while(g, d, |s| !*s).unwrap(); + let g = self.stopped.lock().unwrap_or_else(PoisonError::into_inner); + let (g, _) = self.cv.wait_timeout_while(g, d, |s| !*s).unwrap_or_else(PoisonError::into_inner); *g } } @@ -958,9 +1111,9 @@ impl Handle { } fn signal(&self) { - *self.stop.stopped.lock().unwrap() = true; + *self.stop.stopped.lock().unwrap_or_else(PoisonError::into_inner) = true; self.stop.cv.notify_all(); - if let Some(s) = self.stop.sock.lock().unwrap().as_ref() { + if let Some(s) = self.stop.sock.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { let _ = s.shutdown(Shutdown::Both); } } @@ -1054,11 +1207,22 @@ fn run_tunnel(srv: Server, token: String, who: Who, opts: Options, stop: Arc { if let Some(issued) = issued { @@ -1142,7 +1306,7 @@ impl Lanes { /// The lane with the least queued, or None when streams send `Data`. fn pick(&self) -> Option> { - let list = self.list.lock().unwrap(); + let list = self.list.lock().unwrap_or_else(PoisonError::into_inner); if list.is_empty() { return None; } @@ -1152,8 +1316,8 @@ impl Lanes { fn end(&self) { self.over.store(true, Ordering::Release); - self.list.lock().unwrap().clear(); - for s in self.socks.lock().unwrap().drain(..) { + self.list.lock().unwrap_or_else(PoisonError::into_inner).clear(); + for s in self.socks.lock().unwrap_or_else(PoisonError::into_inner).drain(..) { let _ = s.shutdown(Shutdown::Both); } } @@ -1169,7 +1333,7 @@ impl Lane { /// Writes `bytes` to a TLS connection, whole. fn write_all_tls(tls: &Mutex, sock: &TcpStream, mut bytes: &[u8]) -> io::Result<()> { - let mut c = tls.lock().unwrap(); + let mut c = tls.lock().unwrap_or_else(PoisonError::into_inner); let mut sock = sock; while !bytes.is_empty() { let n = c.writer().write(bytes)?; @@ -1200,7 +1364,7 @@ impl Stream { fn kill(&self) { self.reset.store(true, Ordering::Release); self.cv.notify_all(); - if let Some(s) = self.local.lock().unwrap().as_ref() { + if let Some(s) = self.local.lock().unwrap_or_else(PoisonError::into_inner).as_ref() { let _ = s.shutdown(Shutdown::Both); } } @@ -1241,7 +1405,7 @@ impl Session { } }); if spawned.is_ok() && !self.lanes.over.load(Ordering::Acquire) { - self.lanes.list.lock().unwrap().push(lane); + self.lanes.list.lock().unwrap_or_else(PoisonError::into_inner).push(lane); } } @@ -1267,7 +1431,7 @@ impl Session { if self.lanes.over.load(Ordering::Acquire) { return; } - self.lanes.socks.lock().unwrap().push(keep); + self.lanes.socks.lock().unwrap_or_else(PoisonError::into_inner).push(keep); let _ = reader.set_read_timeout(Some(IDLE)); let conn = Arc::new((Mutex::new(conn), sock)); let mut join = Vec::new(); @@ -1284,7 +1448,7 @@ impl Session { _ => break, }; { - let mut c = conn.0.lock().unwrap(); + let mut c = conn.0.lock().unwrap_or_else(PoisonError::into_inner); let mut input = &raw[..n]; while !input.is_empty() { if c.read_tls(&mut input).is_err() || c.process_new_packets().is_err() { @@ -1337,7 +1501,7 @@ impl Session { fn end_all(&self) { self.lanes.end(); - for (_, s) in self.streams.lock().unwrap().drain() { + for (_, s) in self.streams.lock().unwrap_or_else(PoisonError::into_inner).drain() { s.kill(); let _ = s.to_local.send(None); } @@ -1364,30 +1528,30 @@ impl Session { Msg::Refused(r) => return Some(End::Final(r.to_owned())), Msg::Open { stream, .. } => self.open(stream), Msg::Data { stream, data } => { - let s = self.streams.lock().unwrap().get(&stream).cloned(); + let s = self.streams.lock().unwrap_or_else(PoisonError::into_inner).get(&stream).cloned(); if let Some(s) = s { s.bytes_in.fetch_add(data.len() as u64, Ordering::Relaxed); if s.to_local.send(Some(data.to_vec())).is_err() { - self.streams.lock().unwrap().remove(&stream); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&stream); s.kill(); let _ = self.send(Msg::Reset { stream }); } } } Msg::Window { stream, credit } => { - if let Some(s) = self.streams.lock().unwrap().get(&stream) { - let mut c = s.credit.lock().unwrap(); + if let Some(s) = self.streams.lock().unwrap_or_else(PoisonError::into_inner).get(&stream) { + let mut c = s.credit.lock().unwrap_or_else(PoisonError::into_inner); *c = c.saturating_add(credit).min(self.lanes.window()); s.cv.notify_all(); } } Msg::Close { stream } => { - if let Some(s) = self.streams.lock().unwrap().get(&stream) { + if let Some(s) = self.streams.lock().unwrap_or_else(PoisonError::into_inner).get(&stream) { let _ = s.to_local.send(None); } } Msg::Reset { stream } => { - if let Some(s) = self.streams.lock().unwrap().remove(&stream) { + if let Some(s) = self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&stream) { s.kill(); let _ = s.to_local.send(None); } @@ -1433,11 +1597,11 @@ impl Session { request: Mutex::new(None), status: Mutex::new(0), }); - self.streams.lock().unwrap().insert(id, stream.clone()); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).insert(id, stream.clone()); let sess = self.clone(); let spawned = std::thread::Builder::new().name("share-stream".into()).spawn(move || sess.carry(id, stream, rx)); if spawned.is_err() { - self.streams.lock().unwrap().remove(&id); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); let _ = self.send(Msg::Reset { stream: id }); } } @@ -1461,7 +1625,7 @@ impl Session { let local = match self.connect_local() { Ok(s) => s, Err(e) => { - self.streams.lock().unwrap().remove(&id); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); let _ = self.send(Msg::Reset { stream: id }); // The request line has usually arrived by now; log it as unanswered. if let Ok(Some(first)) = rx.recv_timeout(Duration::from_millis(200)) @@ -1469,7 +1633,7 @@ impl Session { { (self.on_event)(Event::Request(Request { method, path, status: 0, ms: started.elapsed().as_millis() as u64, bytes_in: first.len() as u64, bytes_out: 0, at })); } - let mut last = self.offline_notice.lock().unwrap(); + let mut last = self.offline_notice.lock().unwrap_or_else(PoisonError::into_inner); if last.is_none_or(|t| t.elapsed() > Duration::from_secs(5)) { *last = Some(Instant::now()); (self.on_event)(Event::Notice(format!("nothing is answering on {} ({e})", self.target.addr))); @@ -1479,11 +1643,11 @@ impl Session { }; let _ = local.set_nodelay(true); let (Ok(writer_sock), Ok(handle)) = (local.try_clone(), local.try_clone()) else { - self.streams.lock().unwrap().remove(&id); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); let _ = self.send(Msg::Reset { stream: id }); return; }; - *stream.local.lock().unwrap() = Some(handle); + *stream.local.lock().unwrap_or_else(PoisonError::into_inner) = Some(handle); if stream.reset.load(Ordering::Acquire) { let _ = local.shutdown(Shutdown::Both); } @@ -1499,9 +1663,9 @@ impl Session { let mut seq = 0u32; loop { let allow = { - let mut c = stream.credit.lock().unwrap(); + let mut c = stream.credit.lock().unwrap_or_else(PoisonError::into_inner); while *c == 0 && !stream.reset.load(Ordering::Acquire) { - c = stream.cv.wait(c).unwrap(); + c = stream.cv.wait(c).unwrap_or_else(PoisonError::into_inner); } if stream.reset.load(Ordering::Acquire) { break; @@ -1525,7 +1689,7 @@ impl Session { Ok(n) => n, Err(_) => { if !stream.reset.swap(true, Ordering::AcqRel) { - self.streams.lock().unwrap().remove(&id); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); let _ = self.send(Msg::Reset { stream: id }); } break; @@ -1534,10 +1698,13 @@ impl Session { if first { first = false; if let Some(code) = parse_status_line(&buf[..n]) { - *stream.status.lock().unwrap() = code; + *stream.status.lock().unwrap_or_else(PoisonError::into_inner) = code; } } - *stream.credit.lock().unwrap() -= n as u32; + { + let mut c = stream.credit.lock().unwrap_or_else(PoisonError::into_inner); + *c = c.saturating_sub(n as u32); + } let sent = match self.lanes.pick() { Some(lane) => { let mut frame = Vec::with_capacity(proto::CHUNK_HEADER + n); @@ -1562,13 +1729,13 @@ impl Session { if let Ok(w) = writer { let _ = w.join(); } - self.streams.lock().unwrap().remove(&id); - let request = stream.request.lock().unwrap().take(); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); + let request = stream.request.lock().unwrap_or_else(PoisonError::into_inner).take(); if let Some((method, path)) = request { (self.on_event)(Event::Request(Request { method, path, - status: *stream.status.lock().unwrap(), + status: *stream.status.lock().unwrap_or_else(PoisonError::into_inner), ms: started.elapsed().as_millis() as u64, bytes_in: stream.bytes_in.load(Ordering::Relaxed), bytes_out: stream.bytes_out.load(Ordering::Relaxed), @@ -1588,11 +1755,11 @@ impl Session { }; if first { first = false; - *stream.request.lock().unwrap() = parse_request_line(&data); + *stream.request.lock().unwrap_or_else(PoisonError::into_inner) = parse_request_line(&data); } if local.write_all(&data).is_err() { if !stream.reset.swap(true, Ordering::AcqRel) { - self.streams.lock().unwrap().remove(&id); + self.streams.lock().unwrap_or_else(PoisonError::into_inner).remove(&id); let _ = self.send(Msg::Reset { stream: id }); } stream.kill(); @@ -1623,7 +1790,7 @@ fn session(srv: &Server, token: &str, who: &Who, name: &str, target: &Target, st } let mut reader = sock.try_clone()?; reader.set_read_timeout(Some(IDLE))?; - *stop.sock.lock().unwrap() = Some(sock.try_clone()?); + *stop.sock.lock().unwrap_or_else(PoisonError::into_inner) = Some(sock.try_clone()?); if stop.is_stopped() { let _ = sock.shutdown(Shutdown::Both); } @@ -1656,7 +1823,7 @@ fn session(srv: &Server, token: &str, who: &Who, name: &str, target: &Target, st let end = read_loop(&sess, &mut reader, &mut welcomed); sess.end_all(); let _ = sess.sock.shutdown(Shutdown::Both); - *stop.sock.lock().unwrap() = None; + *stop.sock.lock().unwrap_or_else(PoisonError::into_inner) = None; Ok((end, welcomed)) } @@ -1672,7 +1839,7 @@ fn read_loop(sess: &Arc, reader: &mut TcpStream, welcomed: &mut Option< }; let mut closed = false; { - let mut c = sess.tls.lock().unwrap(); + let mut c = sess.tls.lock().unwrap_or_else(PoisonError::into_inner); let mut input = &raw[..n]; while !input.is_empty() { if let Err(e) = c.read_tls(&mut input) { @@ -1831,7 +1998,7 @@ fn printer(target: String) -> impl Fn(Event) + Send + Sync + 'static { } } Event::Live { url, rate, remaining, warning, domains } => { - let mut shown = shown_url.lock().unwrap(); + let mut shown = shown_url.lock().unwrap_or_else(PoisonError::into_inner); if shown.as_deref() == Some(url.as_str()) { println!(" {} {}", p.accent("●"), p.dim("back online")); return; @@ -1876,8 +2043,14 @@ fn printer(target: String) -> impl Fn(Event) + Send + Sync + 'static { } pub fn run(args: &[String]) -> io::Result<()> { + if args.iter().any(|a| matches!(a.as_str(), "-h" | "--help")) + || matches!(args.first().map(String::as_str), Some("help")) + { + println!("{USAGE}"); + return Ok(()); + } match args.first().map(String::as_str) { - None | Some("-h" | "--help" | "help") => Err(io::Error::other(USAGE)), + None => Err(io::Error::other(USAGE)), Some("login") => login_cli(&args[1..]), Some("logout") => { logout()?; @@ -1966,7 +2139,7 @@ pub fn run(args: &[String]) -> io::Result<()> { let traffic = TrafficFile::start(); let handle = start(Options { target, name, app: false }, move |e| { if let Event::Ended { reason, error: true } = &e { - *f.lock().unwrap() = Some(reason.clone()); + *f.lock().unwrap_or_else(PoisonError::into_inner) = Some(reason.clone()); } if let Some(t) = &traffic { t.on(&e); @@ -1982,7 +2155,7 @@ pub fn run(args: &[String]) -> io::Result<()> { Err(e) => return Err(e), }; handle.wait(); - match failed.lock().unwrap().take() { + match failed.lock().unwrap_or_else(PoisonError::into_inner).take() { Some(_) => Err(io::Error::other("the tunnel closed")), None => Ok(()), } @@ -2125,8 +2298,9 @@ mod tests { #[test] fn a_kiri_share_writes_its_traffic_for_the_window() { let dir = std::env::temp_dir().join(format!("kiri-traffic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - let f = TrafficFile { path: dir.join("1.json"), url: Mutex::new(String::new()), counts: [AtomicU64::new(0), AtomicU64::new(0), AtomicU64::new(0)], dirty: AtomicBool::new(false), done: AtomicBool::new(false) }; + let f = TrafficFile::new(dir.join("1.json")); f.on(&Event::Live { url: "https://dock-4k.runkiri.cloud".into(), rate: 0, remaining: 0, warning: false, domains: Vec::new() }); let req = |i, o| Event::Request(Request { method: "GET".into(), path: "/".into(), status: 200, ms: 1, bytes_in: i, bytes_out: o, at: SystemTime::now() }); f.on(&req(100, 2000)); @@ -2135,6 +2309,11 @@ mod tests { assert_eq!(traffic_in(&dir).get("https://dock-4k.runkiri.cloud"), Some(&[2, 150, 2048])); f.on(&Event::Ended { reason: "stopped".into(), error: false }); assert!(traffic_in(&dir).is_empty(), "removed when it ends"); + // A late timer tick or event after `Ended` must never resurrect the traffic file. + f.write(); + f.on(&Event::Live { url: "https://dock-4k.runkiri.cloud".into(), rate: 0, remaining: 0, warning: false, domains: Vec::new() }); + assert!(traffic_in(&dir).is_empty(), "must not resurrect after Ended"); + assert!(!f.path.exists()); let _ = std::fs::remove_dir_all(&dir); } @@ -2188,6 +2367,60 @@ mod tests { assert_eq!(parse_server("localhost:"), ("localhost:".into(), 443)); } + /// A malformed anchor in the trusted list is skipped, not fatal: the + /// store still holds every certificate that parses. + #[test] + fn merged_roots_skip_a_cert_that_fails_to_add() { + // The bundled set, not this machine's store: every one of them + // parses, where a store may hold one rustls skips already. + let certs = crate::roots::bundled().to_vec(); + let mut with_bad = certs.clone(); + let good: &[u8] = certs[0].as_ref(); + let bad = rustls::pki_types::CertificateDer::from(good[..good.len() / 2].to_vec()); + with_bad.push(bad); + let no_ca = None; + let roots = root_store(&with_bad, no_ca).unwrap(); + assert_eq!( + roots.len(), + certs.len(), + "the truncated cert is skipped, the rest land" + ); + assert_eq!(roots.len(), with_bad.len() - 1); + } + + /// KIRI_SHARE_CA stays loud: a PEM section that doesn't decode fails + /// `root_store` (what `tls_config` builds from the variable), a + /// parseable CA is added and passes. (A file with no PEM sections at + /// all iterates as empty upstream, pki-types 1.15.) `root_store` is + /// called with the file, not through the variable: setting one races + /// every other test reading the environment. + #[test] + fn kiri_share_ca_fails_loud_but_a_valid_ca_is_added() { + let dir = std::env::temp_dir(); + let bad = dir.join(format!("kiri-share-ca-bad-{}.pem", std::process::id())); + std::fs::write( + &bad, + "-----BEGIN CERTIFICATE-----\n!!!!\n-----END CERTIFICATE-----\n", + ) + .unwrap(); + let ca_params = rcgen::CertificateParams::new(Vec::::new()).unwrap(); + let key = rcgen::KeyPair::generate().unwrap(); + let ca = ca_params.self_signed(&key).unwrap(); + let good = dir.join(format!("kiri-share-ca-good-{}.pem", std::process::id())); + std::fs::write(&good, ca.pem()).unwrap(); + let oversized = dir.join(format!("kiri-share-ca-big-{}.pem", std::process::id())); + std::fs::write(&oversized, vec![b'A'; MAX_SHARE_CA_BYTES as usize + 1]).unwrap(); + let loud = root_store(&[], Some(&bad)).is_err(); + let added = root_store(&[], Some(&good)).is_ok_and(|r| r.len() == 1); + let too_big = root_store(&[], Some(&oversized)).is_err(); + let _ = std::fs::remove_file(&bad); + let _ = std::fs::remove_file(&good); + let _ = std::fs::remove_file(&oversized); + assert!(loud, "an undecodable KIRI_SHARE_CA fails loudly"); + assert!(added, "a parseable KIRI_SHARE_CA is added"); + assert!(too_big, "an oversized KIRI_SHARE_CA is refused"); + } + #[test] fn targets() { assert_eq!(port_or_addr("3000").unwrap().addr, "localhost:3000"); @@ -2312,4 +2545,110 @@ mod tests { // A hostile expires_in neither panics nor waits more than an hour. assert_eq!(device_code_deadline(now, u64::MAX), now + Duration::from_secs(MAX_DEVICE_CODE_SECS)); } + + #[test] + fn remote_share_targets_are_flagged() { + for remote in ["10.0.0.5:6379", "169.254.169.254:80", "nas.home.arpa:445", "[fd00::1]:8080"] { + let t = port_or_addr(remote).unwrap(); + assert!(target_is_global(&t), "{remote} should be flagged as non-localhost"); + let msg = non_local_warning(&t).unwrap(); + assert!(msg.contains("not localhost") && msg.contains(&t.display), "{msg}"); + } + for local in [ + "3000", + "localhost:3000", + "LOCALHOST:3000", + "127.0.0.1:5173", + "127.0.0.2:8080", + "[::1]:3000", + "0.0.0.0:3000", + "[::]:3000", + "[::ffff:127.0.0.1]:3000", + ] { + let t = port_or_addr(local).unwrap(); + assert!(!target_is_global(&t), "{local} should be treated as local"); + assert!(non_local_warning(&t).is_none()); + } + } + + #[test] + fn traffic_and_state_files_are_user_only_0600() { + let dir = std::env::temp_dir().join(format!("kiri-traffic-mode-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + let f = TrafficFile::new(dir.join("t.json")); + *f.url.lock().unwrap() = "https://demo.runkiri.cloud".into(); + f.counts[0].store(1, Ordering::Relaxed); + f.counts[1].store(2, Ordering::Relaxed); + f.counts[2].store(3, Ordering::Relaxed); + f.write(); + assert!(f.path.is_file()); + let leftover_tmp = || { + std::fs::read_dir(&dir) + .unwrap() + .flatten() + .any(|e| e.path().extension().is_some_and(|x| x == "tmp")) + }; + assert!(!leftover_tmp(), "no .tmp files left behind after atomic write"); + + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = |p: &std::path::Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode(&f.path), 0o600); + + // Atomic write uses create_new on a unique temp file and atomically + // replaces the target without following a pre-existing symlink. + let victim = dir.join("victim"); + std::fs::write(&victim, b"untouched").unwrap(); + let state_path = dir.join("share.json"); + std::os::unix::fs::symlink(&victim, &state_path).unwrap(); + write_private_atomic(&state_path, b"{\"device\":\"abc\"}", true).unwrap(); + assert!(!std::fs::symlink_metadata(&state_path).unwrap().file_type().is_symlink()); + assert_eq!(std::fs::read(&victim).unwrap(), b"untouched"); + assert_eq!(std::fs::read(&state_path).unwrap(), b"{\"device\":\"abc\"}"); + assert_eq!(mode(&state_path), 0o600); + assert!(!leftover_tmp()); + + // Pre-existing symlink at a candidate temp filename is skipped + // (never followed) thanks to `create_new(true)`. + let colliding_tmp = dir.join("colliding.tmp"); + let fallback_tmp = dir.join("fallback.tmp"); + std::os::unix::fs::symlink(&victim, &colliding_tmp).unwrap(); + let mut candidates = [colliding_tmp.clone(), fallback_tmp.clone()].into_iter(); + write_private_atomic_with(&state_path, b"{\"device\":\"def\"}", true, || candidates.next().unwrap()).unwrap(); + assert!(candidates.next().is_none(), "colliding symlink must be skipped to fallback candidate"); + assert_eq!(std::fs::read(&victim).unwrap(), b"untouched"); + assert_eq!(std::fs::read(&state_path).unwrap(), b"{\"device\":\"def\"}"); + assert_eq!(mode(&state_path), 0o600); + let _ = std::fs::remove_file(&colliding_tmp); + assert!(!leftover_tmp()); + } + + // Rename error (target is a directory) cleans up its temporary file. + let dir_target = dir.join("not-a-file"); + std::fs::create_dir_all(&dir_target).unwrap(); + assert!(write_private_atomic(&dir_target, b"data", false).is_err()); + assert!(!leftover_tmp(), "temp file must be removed when rename fails"); + + // Concurrent TrafficFile writes and `Event::Ended` never leave a + // resurrected traffic file or stray temp files behind. + for i in 0..32 { + let tf = Arc::new(TrafficFile::new(dir.join(format!("race-{i}.json")))); + *tf.url.lock().unwrap() = "https://race.runkiri.cloud".into(); + let writer = tf.clone(); + let t = std::thread::spawn(move || { + for _ in 0..20 { + writer.write(); + } + }); + tf.on(&Event::Ended { reason: "stopped".into(), error: false }); + t.join().unwrap(); + assert!(!tf.path.exists(), "race-{i}.json resurrected after Ended"); + } + assert!(!leftover_tmp()); + + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/kiri/src/storage_cli.rs b/crates/kiri/src/storage_cli.rs new file mode 100644 index 000000000..29cdb490d --- /dev/null +++ b/crates/kiri/src/storage_cli.rs @@ -0,0 +1,273 @@ +//! `kiri storage`: show storage location, VM disk usage, and reclaim unused VM +//! disk space back to the host (`kiri storage reclaim`, #879). + +use std::io; + +use serde_json::Value; + +use crate::client; + +const USAGE: &str = "\ +usage: kiri storage [status] show storage location, disk usage, and reclaimable space + kiri storage reclaim reclaim unused VM disk space back to the host"; + +#[derive(Debug, PartialEq, Eq)] +enum Cmd { + Help, + Status, + Reclaim, +} + +fn parse(args: &[String]) -> Result { + match args.first().map(String::as_str) { + None => Ok(Cmd::Status), + Some("status") if args.len() == 1 => Ok(Cmd::Status), + Some("reclaim") if args.len() == 1 => Ok(Cmd::Reclaim), + Some("-h" | "--help" | "help") if args.len() == 1 => Ok(Cmd::Help), + Some("reclaim") if args.len() == 2 && matches!(args[1].as_str(), "-h" | "--help") => Ok(Cmd::Help), + Some("status") if args.len() == 2 && matches!(args[1].as_str(), "-h" | "--help") => Ok(Cmd::Help), + _ => Err(USAGE.into()), + } +} + +fn format_bytes(bytes: u64) -> String { + const GB: f64 = 1e9; + const MB: f64 = 1e6; + const KB: f64 = 1e3; + let b = bytes as f64; + if b >= GB { + format!("{:.1} GB", b / GB) + } else if b >= MB { + format!("{:.1} MB", b / MB) + } else if b >= KB { + format!("{:.1} KB", b / KB) + } else { + format!("{bytes} B") + } +} + +fn format_limit(bytes: u64) -> String { + const GIB: u64 = 1 << 30; + if bytes > 0 && bytes % GIB == 0 { + format!("{} GB", bytes / GIB) + } else { + format_bytes(bytes) + } +} + +fn host_label() -> &'static str { + if cfg!(target_os = "macos") { + "macOS" + } else if cfg!(windows) { + "Windows" + } else { + "host" + } +} + +fn format_status(v: &Value, host: &str) -> String { + let mut out = String::new(); + let path = v["path"].as_str().unwrap_or(""); + let state = v["state"].as_str().unwrap_or("ok"); + let mut tags = Vec::new(); + if v["env"] == true { + tags.push("KIRI_DATA_DIR".to_owned()); + } else if v["custom"] == true { + tags.push("custom".to_owned()); + } else { + tags.push("default".to_owned()); + } + if let Some(fs) = v["fs"].as_str().filter(|s| !s.is_empty()) { + let pretty = if fs.eq_ignore_ascii_case("apfs") { + "APFS".to_owned() + } else if fs.eq_ignore_ascii_case("ntfs") { + "NTFS".to_owned() + } else { + fs.to_owned() + }; + tags.push(pretty); + } + if state == "unavailable" { + out.push_str(&format!("Location {path} (unavailable)\n")); + return out; + } + out.push_str(&format!("Location {path} ({})\n", tags.join(", "))); + if let Some(limit) = v["disk_limit"].as_u64() { + out.push_str(&format!("Disk limit {}\n", format_limit(limit))); + } + if let Some(disk_host) = v["disk_host"].as_u64() { + if let Some(in_use) = v["disk_in_use"].as_u64() { + out.push_str(&format!("Used in VM {}\n", format_bytes(in_use))); + } else { + out.push_str("Used in VM asleep (run `kiri storage reclaim` to trim)\n"); + } + let taken_label = format!("Taken on {host}"); + let detail = match (v["reclaimable"].as_u64(), v["disk_in_use"].as_u64()) { + (Some(r), _) if r > 0 => format!(" {} reclaimable", format_bytes(r)), + (Some(0), Some(_)) => " nothing to reclaim".to_owned(), + _ => String::new(), + }; + out.push_str(&format!("{taken_label:<17}{}{detail}\n", format_bytes(disk_host))); + } else { + if let Some(used) = v["used"].as_u64() { + out.push_str(&format!("Used {}\n", format_bytes(used))); + } + if let Some(free) = v["free"].as_u64() { + out.push_str(&format!("Free {}\n", format_bytes(free))); + } + } + out +} + +fn format_reclaim(v: &Value, host: &str) -> String { + if v["native"] == true { + let msg = v["message"] + .as_str() + .unwrap_or("Native Linux uses the host filesystem directly — deleted images and volumes free space immediately."); + return format!("{msg}\n"); + } + let before = v["before"].as_u64().unwrap_or(0); + let after = v["after"].as_u64().unwrap_or(0); + let reclaimed = v["reclaimed"].as_u64().unwrap_or_else(|| before.saturating_sub(after)); + let elapsed_s = v["elapsed_ms"].as_u64().unwrap_or(0) as f64 / 1000.0; + if reclaimed > 0 { + format!( + "Reclaimed {} in {:.1} s ({} → {} on {host}).\n", + format_bytes(reclaimed), + elapsed_s, + format_bytes(before), + format_bytes(after) + ) + } else { + format!( + "Nothing to reclaim ({} on {host}, checked in {:.1} s).\n", + format_bytes(after), + elapsed_s + ) + } +} + +pub fn run(args: &[String]) -> io::Result<()> { + let cmd = parse(args).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?; + if cmd == Cmd::Help { + println!("{USAGE}"); + return Ok(()); + } + client::check_alive()?; + match cmd { + Cmd::Help => unreachable!(), + Cmd::Status => { + let v = client::get_background("/kiri/storage")?; + print!("{}", format_status(&v, host_label())); + Ok(()) + } + Cmd::Reclaim => { + let r = client::request("POST", "/kiri/storage/reclaim", None)?; + if !r.ok() { + return Err(io::Error::other(r.error())); + } + print!("{}", format_reclaim(&r.json(), host_label())); + Ok(()) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn args(s: &str) -> Vec { + s.split_whitespace().map(String::from).collect() + } + + #[test] + fn parses_status_reclaim_and_help() { + assert_eq!(parse(&[]), Ok(Cmd::Status)); + assert_eq!(parse(&args("status")), Ok(Cmd::Status)); + assert_eq!(parse(&args("reclaim")), Ok(Cmd::Reclaim)); + assert_eq!(parse(&args("--help")), Ok(Cmd::Help)); + assert_eq!(parse(&args("-h")), Ok(Cmd::Help)); + assert_eq!(parse(&args("help")), Ok(Cmd::Help)); + assert_eq!(parse(&args("reclaim --help")), Ok(Cmd::Help)); + assert_eq!(parse(&args("status -h")), Ok(Cmd::Help)); + for bad in ["bogus", "status extra", "reclaim --now"] { + assert!(parse(&args(bad)).unwrap_err().starts_with("usage:"), "{bad}"); + } + } + + #[test] + fn not_a_docker_command() { + assert!(!crate::docker::handles("storage")); + } + + #[test] + fn formats_macos_and_linux_status_and_reclaim() { + let mac = format_status( + &json!({ + "path": "/Users/me/.kiri/data", + "custom": false, + "env": false, + "state": "ok", + "fs": "apfs", + "disk_limit": 64u64 << 30, + "disk_host": 29_400_000_000u64, + "disk_in_use": 17_300_000_000u64, + "reclaimable": 12_100_000_000u64, + }), + "macOS", + ); + assert!(mac.contains("Location /Users/me/.kiri/data (default, APFS)"), "{mac}"); + assert!(mac.contains("Disk limit 64 GB"), "{mac}"); + assert!(mac.contains("Used in VM 17.3 GB"), "{mac}"); + assert!(mac.contains("Taken on macOS 29.4 GB 12.1 GB reclaimable"), "{mac}"); + + let clean = format_status( + &json!({ + "path": "/Users/me/.kiri/data", + "custom": false, + "env": false, + "state": "ok", + "fs": "apfs", + "disk_host": 17_400_000_000u64, + "disk_in_use": 17_300_000_000u64, + "reclaimable": 0u64, + }), + "macOS", + ); + assert!(clean.contains("nothing to reclaim"), "{clean}"); + + let linux = format_status( + &json!({ + "path": "/var/lib/kiri", + "custom": false, + "env": false, + "state": "ok", + "fs": "ext4", + "used": 4_200_000_000u64, + "free": 120_000_000_000u64, + }), + "host", + ); + assert!(linux.contains("Location /var/lib/kiri (default, ext4)"), "{linux}"); + assert!(linux.contains("Used 4.2 GB"), "{linux}"); + + let freed = format_reclaim( + &json!({"before": 29_400_000_000u64, "after": 17_300_000_000u64, "reclaimed": 12_100_000_000u64, "in_use": 17_300_000_000u64, "elapsed_ms": 800}), + "macOS", + ); + assert_eq!(freed, "Reclaimed 12.1 GB in 0.8 s (29.4 GB → 17.3 GB on macOS).\n"); + + let zero = format_reclaim( + &json!({"before": 17_300_000_000u64, "after": 17_300_000_000u64, "reclaimed": 0, "in_use": 17_300_000_000u64, "elapsed_ms": 200}), + "macOS", + ); + assert_eq!(zero, "Nothing to reclaim (17.3 GB on macOS, checked in 0.2 s).\n"); + + let native = format_reclaim( + &json!({"native": true, "message": "Native Linux uses the host filesystem directly."}), + "host", + ); + assert_eq!(native, "Native Linux uses the host filesystem directly.\n"); + } +} diff --git a/crates/kiri/src/tools.rs b/crates/kiri/src/tools.rs index 2771986cf..99f43fc1f 100644 --- a/crates/kiri/src/tools.rs +++ b/crates/kiri/src/tools.rs @@ -33,10 +33,19 @@ pub fn lite() -> bool { .is_some_and(|r| r.join("guest/Image").is_file() && !r.join("bin/docker").is_file()) } +/// The longest one read may sit silent, the same guard the registry client +/// (`kiri-image/src/connect.rs`) puts on pulls: a server that stops sending +/// mid-download fails the download instead of hanging it forever. +const STALL: Duration = Duration::from_secs(60); + pub(crate) fn agent() -> ureq::Agent { let mut cfg = ureq::Agent::config_builder() .timeout_connect(Some(Duration::from_secs(15))) - .user_agent(concat!("kiri/", env!("CARGO_PKG_VERSION"))); + .timeout_per_read(Some(STALL)) + .user_agent(concat!("kiri/", env!("CARGO_PKG_VERSION"))) + // The system's roots merged with webpki's, like the registry client + // (#303); downloads run behind the same corporate proxies. + .tls_config(kiri_image::tls_config(&kiri_image::roots::trusted())); let e = crate::daemon::proxy::effective(); if let Some(p) = e.https.or(e.http).and_then(|u| ureq::Proxy::new(&u).ok()) { cfg = cfg.proxy(Some(p)); diff --git a/crates/kiri/src/ui/compose.rs b/crates/kiri/src/ui/compose.rs index c43828d3f..3fde6a0e3 100644 --- a/crates/kiri/src/ui/compose.rs +++ b/crates/kiri/src/ui/compose.rs @@ -120,14 +120,13 @@ pub const NO_FILE: &str = "Kiri can't find this project's compose file"; /// `\\server\share\x` (as the `dunce` crate does); any other is as it is. pub fn plain_path(p: PathBuf) -> PathBuf { let s = p.to_string_lossy(); - if let Some(rest) = s.strip_prefix(r"\\?\UNC\") { - return PathBuf::from(format!(r"\\{rest}")); - } - if let Some(rest) = s.strip_prefix(r"\\?\") - && rest.as_bytes().get(1) == Some(&b':') - && rest.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) - { - return PathBuf::from(rest); + if let Some(rest) = s.strip_prefix(r"\\?\") { + if rest.len() >= 4 && rest[..4].eq_ignore_ascii_case(r"UNC\") { + return PathBuf::from(format!(r"\\{}", &rest[4..])); + } + if rest.as_bytes().get(1) == Some(&b':') && rest.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) { + return PathBuf::from(rest); + } } p } @@ -144,9 +143,252 @@ pub fn valid_file(f: &str) -> Option { valid_file_from(f, false) } +/// Whether `name` is a single valid WSL distro path segment. +pub fn valid_wsl_distro(name: &str) -> bool { + !name.is_empty() + && !name.starts_with('.') + && !name.ends_with(['.', ' ']) + && !name.contains(['/', '\\', '\0', ':', '*', '?', '"', '<', '>', '|', '@']) + && !name.bytes().any(|b| b.is_ascii_control() || b.is_ascii_whitespace()) +} + +/// Parses a local WSL Plan9 loopback share (`\\wsl.localhost\\…`, +/// `\\wsl$\\…`, or `\\?\UNC\wsl.localhost\\…`, with `\` or `/`) +/// into `(distro, lexical_linux_path)` when `` is a single valid +/// distro segment and `..` never climbs above ``. +pub fn wsl_unc(f: &str) -> Option<(String, String)> { + if f.bytes().any(|b| b.is_ascii_control()) { + return None; + } + let rest = if let Some(after_q) = f.strip_prefix(r"\\?\") { + if f.contains('/') || after_q.len() < 4 || !after_q[..4].eq_ignore_ascii_case(r"UNC\") { + return None; + } + after_q[4..].to_owned() + } else { + let s = f.replace('/', "\\"); + if s.starts_with(r"\\?\") || s.starts_with(r"\\.\") { + return None; + } + s.strip_prefix(r"\\")?.to_owned() + }; + let (host, after_host) = rest.split_once('\\')?; + if !(host.eq_ignore_ascii_case("wsl.localhost") || host.eq_ignore_ascii_case("wsl$")) { + return None; + } + let (distro, inner) = after_host.split_once('\\').unwrap_or((after_host, "")); + if !valid_wsl_distro(distro) { + return None; + } + let mut parts: Vec<&str> = Vec::new(); + for seg in inner.split('\\') { + match seg { + "" | "." => {} + ".." => { + parts.pop()?; + } + seg if seg.contains(':') => return None, + seg => parts.push(seg), + } + } + let rel = if parts.is_empty() { "/".to_owned() } else { format!("/{}", parts.join("/")) }; + Some((distro.to_owned(), rel)) +} + +/// Whether two resolved file paths name the same file, including local WSL +/// UNC spellings (`\\wsl.localhost\Ubuntu\…` and `\\wsl$\ubuntu\…`). +pub fn same_file_path(a: &Path, b: &Path) -> bool { + if a == b { + return true; + } + if let (Some((da, ia)), Some((db, ib))) = (wsl_unc(&a.to_string_lossy()), wsl_unc(&b.to_string_lossy())) { + return da.eq_ignore_ascii_case(&db) && ia == ib; + } + false +} + +/// `[automount] root` from `/etc/wsl.conf` text, normalized to start and end with `/`. +#[cfg(any(windows, test))] +pub fn wsl_automount_root(conf: &str) -> String { + let mut section = String::new(); + let mut root = None; + for line in conf.lines() { + let line = line.split('#').next().unwrap_or("").trim(); + if let Some(s) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + section = s.trim().to_ascii_lowercase(); + continue; + } + let Some((key, value)) = line.split_once('=') else { continue }; + if section == "automount" && key.trim().eq_ignore_ascii_case("root") { + let value = value.trim().trim_matches(['"', '\'']).trim(); + if value.starts_with('/') && !value.contains(['\\', ':', '\0']) && !value.bytes().any(|b| b.is_ascii_control()) { + root = Some(lexical(value)); + } + } + } + let mut root = root.unwrap_or_else(|| "/mnt/".to_owned()); + if !root.ends_with('/') { + root.push('/'); + } + root +} + +/// Translates an absolute Linux path from a container's Compose labels inside +/// WSL `distro` to the Windows path that reaches the same file or folder: +/// - `[/…]` -> `:\[…]` +/// - `/mnt/wsl/kiri/roots/[/…]` -> `\\wsl.localhost\\[…]` +/// - any other `/…` -> `\\wsl.localhost\\[…]` +#[cfg(any(windows, test))] +pub fn wsl_to_windows(path: &str, distro: &str, automount_root: &str) -> Option { + if !path.starts_with('/') || path.starts_with("//") { + return None; + } + if path.contains(['\\', ':', '\0']) || path.bytes().any(|b| b.is_ascii_control()) { + return None; + } + let clean = lexical(path); + if clean == "/mnt/wsl/kiri" || clean.starts_with("/mnt/wsl/kiri/") { + let rest = clean.strip_prefix("/mnt/wsl/kiri/roots/")?; + let (d, inner) = rest.split_once('/').unwrap_or((rest, "")); + if !valid_wsl_distro(d) { + return None; + } + return if inner.is_empty() { + Some(format!(r"\\wsl.localhost\{d}\")) + } else { + Some(format!(r"\\wsl.localhost\{d}\{}", inner.replace('/', "\\"))) + }; + } + let mut root = if automount_root.starts_with('/') { automount_root.to_owned() } else { "/mnt/".to_owned() }; + if !root.ends_with('/') { + root.push('/'); + } + if let Some(after) = clean.strip_prefix(&root) { + let b = after.as_bytes(); + if b.len() == 1 && b[0].is_ascii_alphabetic() { + return Some(format!("{}:\\", (b[0] as char).to_ascii_uppercase())); + } + if b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b'/' { + let rest = &after[2..]; + let drive = (b[0] as char).to_ascii_uppercase(); + return if rest.is_empty() { + Some(format!("{drive}:\\")) + } else { + Some(format!("{drive}:\\{}", rest.replace('/', "\\"))) + }; + } + } + if !valid_wsl_distro(distro) { + return None; + } + if clean == "/" { + Some(format!(r"\\wsl.localhost\{distro}\")) + } else { + Some(format!(r"\\wsl.localhost\{distro}{}", clean.replace('/', "\\"))) + } +} + +#[cfg(any(windows, test))] +fn distro_from_mounts(c: &Value) -> Option { + for m in c["Mounts"].as_array().into_iter().flatten() { + let Some(src) = m["Source"].as_str() else { continue }; + if let Some(rest) = src.strip_prefix("/mnt/wsl/kiri/roots/") { + let d = rest.split('/').next().unwrap_or(rest); + if valid_wsl_distro(d) { + return Some(d.to_owned()); + } + } + } + None +} + +/// [`projects`], translating Linux Compose label paths on Windows to the +/// owning WSL distro (`\\wsl.localhost\\…`) or Windows drive (`C:\…`). +#[cfg(any(windows, test))] +pub fn wsl_projects( + containers: &Value, + distros: &[String], + automount: impl Fn(&str) -> String, + exists: impl Fn(&str) -> bool, +) -> Vec { + let has_linux = |s: &str| s.starts_with('/') && !s.starts_with("//"); + let mut by_linux_label: HashMap = HashMap::new(); + let mut by_any: HashMap = HashMap::new(); + for c in containers.as_array().into_iter().flatten() { + let label = |k: &str| c["Labels"][k].as_str().unwrap_or_default(); + let name = label(PROJECT); + if name.is_empty() { + continue; + } + let Some(d) = c["KiriWslDistro"].as_str().filter(|d| valid_wsl_distro(d)).map(str::to_owned).or_else(|| distro_from_mounts(c)) else { + continue; + }; + let created = c["Created"].as_i64().unwrap_or_default(); + if by_any.get(name).is_none_or(|(t, _)| created >= *t) { + by_any.insert(name.to_owned(), (created, d.clone())); + } + let linux_labelled = has_linux(label(WORKDIR)) + || label(FILES).split(',').map(str::trim).any(has_linux) + || label(ENV_FILES).split(',').map(str::trim).any(has_linux); + if linux_labelled && by_linux_label.get(name).is_none_or(|(t, _)| created >= *t) { + by_linux_label.insert(name.to_owned(), (created, d)); + } + } + let candidates: Vec<&str> = distros.iter().map(String::as_str).filter(|d| valid_wsl_distro(d)).collect(); + let mut list = projects(containers); + for p in &mut list { + if !has_linux(&p.dir) && !p.files.iter().any(|f| has_linux(f)) && !p.env_files.iter().any(|e| has_linux(e)) { + continue; + } + let chosen = by_linux_label + .get(&p.name) + .or_else(|| by_any.get(&p.name)) + .map(|(_, d)| d.clone()) + .or_else(|| match candidates.as_slice() { + [] => None, + [only] => Some((*only).to_owned()), + many => { + let probe = p.files.iter().find(|f| has_linux(f)).map(String::as_str).or_else(|| has_linux(&p.dir).then_some(p.dir.as_str())); + probe + .and_then(|lp| { + many.iter().copied().find(|d| { + let mnt = automount(d); + wsl_to_windows(lp, d, &mnt).is_some_and(|w| exists(&w)) + }) + }) + .or(Some(many[0])) + .map(str::to_owned) + } + }); + let Some(distro) = chosen else { continue }; + let mnt = automount(&distro); + if has_linux(&p.dir) + && let Some(w) = wsl_to_windows(&p.dir, &distro, &mnt) + { + p.dir = w; + } + for f in &mut p.files { + if has_linux(f) + && let Some(w) = wsl_to_windows(f, &distro, &mnt) + { + *f = w; + } + } + for e in &mut p.env_files { + if has_linux(e) + && let Some(w) = wsl_to_windows(e, &distro, &mnt) + { + *e = w; + } + } + } + list +} + /// A network path (`\\host\share\x`, `//host/share/x`, `\\?\UNC\…`, a /// `\\.\` device, the Mac's `/net//…`): reading one makes the system -/// contact another host. +/// contact another host. Local WSL Plan9 loopback shares +/// (`\\wsl.localhost\\…`, `\\wsl$\\…`) stay on this machine. pub fn remote_path(f: &str) -> bool { // macOS mounts another host's exports under /net// on first look: // checked on the path with `.` and `..` resolved as written (never by @@ -155,12 +397,14 @@ pub fn remote_path(f: &str) -> bool { if n.starts_with("/net/") || n == "/net" { return true; } - let f = f.replace('/', "\\"); + if wsl_unc(f).is_some() { + return false; + } if let Some(rest) = f.strip_prefix(r"\\?\") { let b = rest.as_bytes(); - return !(b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':'); + return !(b.len() >= 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b.len() == 2 || b[2] == b'\\')); } - f.starts_with(r"\\") + f.replace('/', "\\").starts_with(r"\\") } /// An absolute `/` path with `.`, `..` and repeated `/` resolved by its @@ -495,7 +739,7 @@ static BEFORE: LazyLock> = LazyLock::new(|| Mutex::new(HashMap::ne fn remember_before(name: &str, path: &str, disk: Vec, wrote: &str) { let mut before = BEFORE.lock().unwrap_or_else(|e| e.into_inner()); match before.get_mut(name) { - Some((f, _, w)) if f == path && *w == file_hash(&disk) => *w = wrote.to_owned(), + Some((f, _, w)) if same_file_path(Path::new(f), Path::new(path)) && *w == file_hash(&disk) => *w = wrote.to_owned(), _ => { before.insert(name.to_owned(), (path.to_owned(), disk, wrote.to_owned())); } @@ -1904,7 +2148,7 @@ fn run_ran(mut cmd: Command, input: Option<&str>, secs: u64) -> Ran { /// Kills `child` and every process it started (its own process group; on /// Windows, its tree). -fn kill_tree(child: &mut std::process::Child) { +fn kill_group(child: &mut std::process::Child) { #[cfg(unix)] if let Ok(pid) = i32::try_from(child.id()) { // SAFETY: a plain signal to the group this child leads (`process_group(0)`). @@ -1918,6 +2162,10 @@ fn kill_tree(child: &mut std::process::Child) { let _ = Command::new("taskkill").args(["/F", "/T", "/PID", &child.id().to_string()]).creation_flags(0x0800_0000).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).status(); } let _ = child.kill(); +} + +fn kill_tree(child: &mut std::process::Child) { + kill_group(child); let _ = child.wait(); } @@ -1948,8 +2196,61 @@ pub fn merge(mut ran: Vec, opened: Vec) -> Vec { ran } +#[cfg(windows)] +fn host_wsl_distros() -> Vec { + static DEFAULT: std::sync::OnceLock = std::sync::OnceLock::new(); + let engine = super::distro().filter(|d| valid_wsl_distro(d)).or_else(|| { + if let Some(d) = DEFAULT.get() { + return Some(d.clone()); + } + let d = crate::setup::distros()?.into_iter().find(|d| valid_wsl_distro(d))?; + let _ = DEFAULT.set(d.clone()); + Some(d) + }); + let mut out = Vec::new(); + if let Some(d) = engine.as_deref().filter(|d| !d.eq_ignore_ascii_case("kiri")) { + out.push(d.to_owned()); + } + for d in crate::wslconfig::enabled_distros() { + if valid_wsl_distro(&d) && !out.iter().any(|x| x.eq_ignore_ascii_case(&d)) { + out.push(d); + } + } + if let Some(d) = engine.filter(|d| !out.iter().any(|x| x.eq_ignore_ascii_case(d))) { + out.push(d); + } + out +} + +#[cfg(windows)] +fn host_wsl_automount(distro: &str) -> String { + static ROOTS: LazyLock>> = LazyLock::new(|| Mutex::new(HashMap::new())); + let key = distro.to_ascii_lowercase(); + if let Some(r) = ROOTS.lock().unwrap_or_else(|e| e.into_inner()).get(&key) { + return r.clone(); + } + let etc = format!(r"\\wsl.localhost\{distro}\etc"); + match std::fs::read_to_string(format!(r"{etc}\wsl.conf")) { + Ok(conf) => { + let root = wsl_automount_root(&conf); + ROOTS.lock().unwrap_or_else(|e| e.into_inner()).insert(key, root.clone()); + root + } + Err(_) if Path::new(&etc).is_dir() => { + let root = "/mnt/".to_owned(); + ROOTS.lock().unwrap_or_else(|e| e.into_inner()).insert(key, root.clone()); + root + } + Err(_) => "/mnt/".to_owned(), + } +} + fn all_projects(containers: &Value, store: Store) -> Vec { - merge(projects(containers), opened(store)) + #[cfg(windows)] + let ran = wsl_projects(containers, &host_wsl_distros(), host_wsl_automount, |p| Path::new(p).exists()); + #[cfg(not(windows))] + let ran = projects(containers); + merge(ran, opened(store)) } /// Saves the opened list: `keep` decides what stays of what was there. @@ -2008,7 +2309,7 @@ pub fn open_file(cli: Cli, store: Store, path: &Path) -> String { if let Some(dir) = clash(&p, &all_projects(&containers, store)) { return Err(format!("A project named {} already runs from {dir}", p.name)); } - save_opened(store, |n, f| n != p.name && f != file, Some((&p.name, &file))).map_err(|e| e.to_string())?; + save_opened(store, |n, f| n != p.name && !same_file_path(Path::new(f), Path::new(&file)), Some((&p.name, &file))).map_err(|e| e.to_string())?; Ok(p.name) })(); match r { @@ -2107,7 +2408,7 @@ fn flow_keys(text: &str) -> Vec { /// from), when it isn't this file's: two files are never shown as one. pub fn clash(p: &Project, known: &[Project]) -> Option { let k = known.iter().find(|k| k.name == p.name)?; - let same = |f: &String| p.files.iter().any(|g| valid_file(f).zip(valid_file(g)).is_some_and(|(a, b)| a == b)); + let same = |f: &String| p.files.iter().any(|g| valid_file(f).zip(valid_file(g)).is_some_and(|(a, b)| same_file_path(&a, &b))); let file_gone = k.members.is_empty() && valid_file(&k.files[0]).is_none(); (!k.files.iter().any(same) && !file_gone).then(|| if k.dir.is_empty() { k.files.first().cloned().unwrap_or_default() } else { k.dir.clone() }) } @@ -2311,7 +2612,12 @@ impl std::fmt::Display for CfgErr { /// [`YamlAt`] of Compose's error `e`, from its shape only. fn yaml_at(e: &str, p: &Project, full: bool) -> Option { let (path, n) = yaml_place(e)?; - let top = |f: &str| p.files.first().is_some_and(|t| Path::new(t) == Path::new(f) || std::fs::canonicalize(t).ok().is_some_and(|c| std::fs::canonicalize(f).ok() == Some(c))); + let top = |f: &str| { + p.files.first().is_some_and(|t| { + same_file_path(Path::new(t), Path::new(f)) + || std::fs::canonicalize(t).ok().zip(std::fs::canonicalize(f).ok()).is_some_and(|(a, b)| same_file_path(&plain_path(a), &plain_path(b))) + }) + }; match path { None | Some("-") => Some(YamlAt::Top(n)), Some(f) if top(f) => Some(YamlAt::Top(n)), @@ -2321,7 +2627,8 @@ fn yaml_at(e: &str, p: &Project, full: bool) -> Option { /// `path` relative to `dir` (`../x/compose.yaml` outside it). fn relative(dir: &Path, path: &Path) -> String { - let (d, f) = (std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_owned()), std::fs::canonicalize(path).unwrap_or_else(|_| path.to_owned())); + // Plain on both sides: on Windows a canonical path is `\\?\C:\…`, one that isn't there stays `C:\…`. + let (d, f) = (real_path(dir).unwrap_or_else(|_| dir.to_owned()), real_path(path).unwrap_or_else(|_| path.to_owned())); let (a, b): (Vec<_>, Vec<_>) = (d.components().collect(), f.components().collect()); let same = a.iter().zip(&b).take_while(|(x, y)| x == y).count(); let mut out = PathBuf::new(); @@ -3458,7 +3765,7 @@ fn member_view(m: &Member) -> Value { /// whether this reading is the one that found it put back so. fn still_before(name: &str, path: &str, hash: &str) -> (bool, bool) { let mut before = BEFORE.lock().unwrap_or_else(|e| e.into_inner()); - let back = before.get(name).is_some_and(|(f, b, _)| f == path && file_hash(b) == hash); + let back = before.get(name).is_some_and(|(f, b, _)| same_file_path(Path::new(f), Path::new(path)) && file_hash(b) == hash); if back { before.remove(name); } @@ -3527,7 +3834,7 @@ pub fn plan_event(cli: Cli, store: Store, name: &str, draft: &str, seq: &Value) // A project that has never run: every service is new. After an Apply // that saved the file but failed, what runs came from the file before // it, so what changed is told against that one. - let before = BEFORE.lock().unwrap_or_else(|e| e.into_inner()).get(name).filter(|(f, _, _)| *f == p.files[0]).map(|(_, b, _)| String::from_utf8_lossy(b).into_owned()); + let before = BEFORE.lock().unwrap_or_else(|e| e.into_inner()).get(name).filter(|(f, _, _)| same_file_path(Path::new(f), Path::new(&p.files[0]))).map(|(_, b, _)| String::from_utf8_lossy(b).into_owned()); let old = if p.members.is_empty() { json!({}) } else if let Some(b) = before { @@ -3844,9 +4151,10 @@ static UPS: LazyLock>> = LazyLock::new(|| Mutex::new(H pub fn cancel(name: &str) -> bool { let mut ups = UPS.lock().unwrap_or_else(|e| e.into_inner()); let Some(up) = ups.get_mut(name) else { return false }; - up.cancelled = true; - if let Some(c) = up.child.as_mut() { - let _ = c.kill(); + if !std::mem::replace(&mut up.cancelled, true) + && let Some(c) = up.child.as_mut() + { + kill_group(c); } true } @@ -3891,8 +4199,7 @@ struct Applying(String); impl Drop for Applying { fn drop(&mut self) { if let Some(mut c) = UPS.lock().unwrap_or_else(|e| e.into_inner()).remove(&self.0).and_then(|u| u.child) { - let _ = c.kill(); - let _ = c.wait(); + kill_tree(&mut c); } } } @@ -3902,7 +4209,7 @@ impl Drop for Applying { pub fn restore(name: &str, store: Store) -> Result<(), String> { let p = find_checked(name, store)?; let (file, bytes, wrote) = BEFORE.lock().unwrap_or_else(|e| e.into_inner()).get(name).cloned().ok_or("Kiri has nothing to put back")?; - if file != p.files[0] { + if !same_file_path(Path::new(&file), Path::new(&p.files[0])) { return Err(NO_FILE.into()); } write_over(Path::new(&file), &bytes, &wrote).map_err(|e| if changed(&e) { "The file changed outside Kiri since Apply saved it".to_owned() } else { e.to_string() })?; @@ -3910,6 +4217,23 @@ pub fn restore(name: &str, store: Store) -> Result<(), String> { Ok(()) } +fn spawn_up(mut cmd: Command, name: &str) -> io::Result<(Option, Option)> { + cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = cmd.spawn()?; + let out = child.stdout.take(); + let err = child.stderr.take(); + let mut ups = UPS.lock().unwrap_or_else(|e| e.into_inner()); + let up = ups.entry(name.to_owned()).or_default(); + // Cancel came while the file was being saved: `up` stops at once. + if up.cancelled { + kill_group(&mut child); + } + up.child = Some(child); + Ok((out, err)) +} + /// Apply: checks the draft, saves it, and runs `docker compose up -d /// --remove-orphans`, sending its progress lines as /// `{type: "composeapply", name, line}` and then `{…, done: true, ok, error, @@ -4008,22 +4332,11 @@ pub fn apply(cli: Cli, store: Store, name: &str, draft: &str, base: Option<&str> Ok(c) => c, Err(e) => return done(false, own(&e.to_string()), true, &hidden, Some(&hash)), }; - cmd.args(project_args(&p, None)).args(profile_args(&profs)).args(["--progress", "plain", "up", "-d", "--remove-orphans"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()); - let mut child = match cmd.spawn() { - Ok(c) => c, + cmd.args(project_args(&p, None)).args(profile_args(&profs)).args(["--progress", "plain", "up", "-d", "--remove-orphans"]); + let (out, err) = match spawn_up(cmd, name) { + Ok(pipes) => pipes, Err(e) => return done(false, own(&format!("couldn't run docker compose: {e}")), true, &hidden, Some(&hash)), }; - let out = child.stdout.take(); - let err = child.stderr.take(); - { - let mut ups = UPS.lock().unwrap_or_else(|e| e.into_inner()); - let up = ups.entry(name.to_owned()).or_default(); - // Cancel came while the file was being saved: `up` stops at once. - if up.cancelled { - let _ = child.kill(); - } - up.child = Some(child); - } let reader = std::thread::spawn(move || { let mut s = String::new(); if let Some(mut o) = out { @@ -5563,12 +5876,24 @@ mod tests { /// The docker CLI with no engine to reach (`config --environment` needs /// none) and an environment of its own, so a test sees only its `.env`. fn dcli() -> io::Result { - let mut c = Command::new(client::docker_cli().expect("a docker CLI")); + Ok(bare(Command::new(client::docker_cli().expect("a docker CLI")))) + } + + /// `c` with only what the docker CLI needs of this environment, and no + /// engine to reach. + fn bare(mut c: Command) -> Command { c.env_clear().env("PATH", std::env::var_os("PATH").unwrap_or_default()).env("HOME", std::env::var_os("HOME").unwrap_or_default()).env("DOCKER_HOST", "unix:///nonexistent/kiri-test.sock"); - if let Some(d) = std::env::var_os("DOCKER_CONFIG") { - c.env("DOCKER_CONFIG", d); + // On Windows the CLI finds its plugins (compose) under USERPROFILE, and + // its network needs SystemRoot; HOME is not set there. + for k in ["DOCKER_CONFIG", "USERPROFILE", "SystemRoot"] { + if let Some(v) = std::env::var_os(k) { + c.env(k, v); + } } - Ok(c) + // As the app's own CLI: no console window for each of the tests' many runs. + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut c, 0x0800_0000); + c } fn dproj(d: &Path) -> Project { @@ -5832,7 +6157,7 @@ mod tests { let d = std::env::temp_dir().join(format!("kiri-compose-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&d); std::fs::create_dir_all(&d).unwrap(); - std::fs::canonicalize(&d).unwrap() + real_path(&d).unwrap() } #[test] @@ -5976,7 +6301,7 @@ mod tests { fn outside(p: &Path) { std::fs::write(p, "services: {}\n# theirs\n").unwrap(); } - *BETWEEN.lock().unwrap() = Some((std::fs::canonicalize(&f).unwrap(), outside)); + *BETWEEN.lock().unwrap() = Some((real_path(&f).unwrap(), outside)); let r = save(&f, "services:\n a: {}\n", &base); *BETWEEN.lock().unwrap() = None; assert!(r.as_ref().is_err_and(changed), "{r:?}"); @@ -6028,6 +6353,77 @@ mod tests { assert!(!cancelled("c1") && !UPS.lock().unwrap().contains_key("c1"), "gone once Apply ends"); } + #[test] + fn cancelling_apply_stops_the_compose_plugin_tree() { + if let Ok(addr) = std::env::var("KIRI_T_PLUGIN_GATE") { + let mut conn = std::net::TcpStream::connect(addr).unwrap(); + let _ = writeln!(io::stderr(), " Container celtree-web-1 Creating "); + let _ = io::stderr().flush(); + let mut b = [0u8; 1]; + if io::Read::read_exact(&mut conn, &mut b).is_ok() && b[0] == b'P' { + let _ = conn.write_all(b"A"); + let _ = conn.flush(); + let _ = io::Read::read(&mut conn, &mut b); + } + std::process::exit(1); + } + let wrapper = |gate: &str| { + let exe = std::env::current_exe().unwrap(); + #[cfg(unix)] + let mut c = { + let mut c = Command::new("sh"); + c.args(["-c", "\"$KIRI_T_EXE\" cancelling_apply_stops_the_compose_plugin_tree --nocapture; exit $?", "sh"]); + c + }; + #[cfg(windows)] + let mut c = { + use std::os::windows::process::CommandExt as _; + let mut c = Command::new("cmd"); + c.args(["/d", "/c"]).raw_arg("\"%KIRI_T_EXE%\" cancelling_apply_stops_the_compose_plugin_tree --nocapture"); + c + }; + c.env("KIRI_T_EXE", exe).env("KIRI_T_PLUGIN_GATE", gate); + c + }; + + // 1. Cancel during `up`: kills wrapper and plugin child, closing inherited pipes immediately. + let gate = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = gate.local_addr().unwrap().to_string(); + UPS.lock().unwrap().insert("celtree".into(), Up::default()); + let applying = Applying("celtree".into()); + let (out, err) = spawn_up(wrapper(&addr), "celtree").unwrap(); + let (mut conn, _) = gate.accept().unwrap(); + let mut lines = io::BufReader::new(err.unwrap()).lines(); + assert_eq!(lines.next().unwrap().unwrap(), " Container celtree-web-1 Creating "); + assert!(cancel("celtree")); + assert!(cancel("celtree")); + let _ = conn.write_all(b"P"); + let _ = conn.flush(); + let mut ack = [0u8; 1]; + assert!(!(io::Read::read_exact(&mut conn, &mut ack).is_ok() && ack[0] == b'A'), "compose plugin survived cancel"); + drop(conn); + assert!(lines.next().is_none(), "stderr pipe closed once plugin tree stopped"); + let mut stdout_rest = String::new(); + let _ = io::Read::read_to_string(&mut out.unwrap(), &mut stdout_rest); + let child = UPS.lock().unwrap().get_mut("celtree").and_then(|u| u.child.take()); + assert!(child.unwrap().wait().is_ok()); + drop(applying); + assert!(!cancel("celtree")); + + // 2. Cancel arrived while saving (before `spawn_up` registers `child`): stops tree at once. + let gate2 = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr2 = gate2.local_addr().unwrap().to_string(); + UPS.lock().unwrap().insert("celtree2".into(), Up { child: None, cancelled: true }); + let applying2 = Applying("celtree2".into()); + let (out2, err2) = spawn_up(wrapper(&addr2), "celtree2").unwrap(); + let mut rest_err = String::new(); + let mut rest_out = String::new(); + let _ = io::Read::read_to_string(&mut err2.unwrap(), &mut rest_err); + let _ = io::Read::read_to_string(&mut out2.unwrap(), &mut rest_out); + drop(applying2); + assert!(!cancel("celtree2")); + } + #[test] fn project_actions_go_by_name_in_composes_order_and_remove_its_network() { assert_eq!(action_args("shop", "start").unwrap(), ["compose", "--ansi", "never", "-p", "shop", "start"]); @@ -6061,6 +6457,17 @@ mod tests { assert!(!a.iter().any(|x| x.starts_with(r"\\?\")), "{a:?}"); } + #[test] + fn relative_names_a_file_inside_or_outside_an_existing_folder() { + let d = tdir("rel"); + std::fs::create_dir_all(d.join("sub")).unwrap(); + std::fs::write(d.join("sub/compose.yaml"), "services: {}\n").unwrap(); + assert_eq!(relative(&d, &d.join("sub/compose.yaml")), "sub/compose.yaml"); + assert_eq!(relative(&d, &d.join("../up.yaml")), "../up.yaml"); + assert_eq!(relative(&d, &d.parent().unwrap().join("up.yaml")), "../up.yaml"); + let _ = std::fs::remove_dir_all(&d); + } + #[test] fn only_compose_files_open() { assert!(compose_text("name: x\nservices:\n web:\n image: nginx\n")); @@ -6868,7 +7275,7 @@ mod tests { let m = config(dcli, &p, Some(draft), &[]).unwrap(); let v = service_view("x", &m["services"]["x"]); assert_eq!(v["ports"], json!(["8080:80"])); - assert!(v["volumes"][0].as_str().unwrap().ends_with("certs/server.key:/k"), "{v}"); + assert!(v["volumes"][0].as_str().unwrap().replace('\\', "/").ends_with("certs/server.key:/k"), "{v}"); let _ = std::fs::remove_dir_all(&d); } @@ -7228,7 +7635,8 @@ mod tests { assert_eq!(m["services"]["inc"]["image"], "reg/app:${DB_PASSWORD}"); assert_eq!(m["services"]["deep"]["image"], "reg/deep:${DEEP_TOKEN}"); assert_eq!(m["services"]["long"]["image"], "reg/long:${API_SECRET}"); - assert!(text.contains("/sub/data/${DB_PASSWORD}"), "{text}"); + // On Windows a JSON string's `\` is `\\`. + assert!(text.replace(r"\\", "/").contains("/sub/data/${DB_PASSWORD}"), "{text}"); // An error that quotes the value names the variable. std::fs::write(d.join("sub/compose.yaml"), "services:\n inc:\n image: alpine\n ports: [\"${DB_PASSWORD}:80\"]\n").unwrap(); let e = config(dcli, &p, None, &[]).unwrap_err(); @@ -8055,8 +8463,8 @@ mod tests { fn hangs() -> io::Result { let docker = client::docker_cli().expect("a docker CLI"); let script = format!("case \"$*\" in *'config --quiet'*) sleep 5; exit 1;; esac; exec '{}' \"$@\"", std::path::Path::new(&docker).display()); - let mut c = Command::new("sh"); - c.env_clear().env("PATH", std::env::var_os("PATH").unwrap_or_default()).env("HOME", std::env::var_os("HOME").unwrap_or_default()).env("DOCKER_HOST", "unix:///nonexistent/kiri-test.sock").args(["-c", &script, "sh"]); + let mut c = bare(Command::new("sh")); + c.args(["-c", &script, "sh"]); Ok(c) } let d = tdir("realslow"); @@ -8311,8 +8719,8 @@ mod tests { let docker = client::docker_cli().expect("a docker CLI"); let log = std::env::temp_dir().join(format!("kiri-compose-count-{}", std::process::id())); let script = format!("echo \"$*\" >> '{}'; exec '{}' \"$@\"", log.display(), std::path::Path::new(&docker).display()); - let mut c = Command::new("sh"); - c.env_clear().env("PATH", std::env::var_os("PATH").unwrap_or_default()).env("HOME", std::env::var_os("HOME").unwrap_or_default()).env("DOCKER_HOST", "unix:///nonexistent/kiri-test.sock").args(["-c", &script, "sh"]); + let mut c = bare(Command::new("sh")); + c.args(["-c", &script, "sh"]); Ok(c) } @@ -8516,4 +8924,182 @@ mod tests { assert_ne!(stamp(&p), before); let _ = std::fs::remove_dir_all(&d); } + + #[test] + fn local_wsl_shares_are_accepted_while_remote_unc_paths_stay_refused() { + for bad in [ + r"\\evil.com\share\compose.yaml", + "//evil.com/share/compose.yaml", + r"\\10.0.0.1\share\compose.yaml", + "//10.0.0.1/share/compose.yaml", + r"\\?\UNC\evil.com\share\compose.yaml", + r"\\?\unc\10.0.0.1\share\compose.yaml", + "//?/UNC/wsl.localhost/Ubuntu/compose.yaml", + "//?/C:/w/compose.yaml", + r"\\.\pipe\docker_engine", + r"\\.\UNC\wsl.localhost\Ubuntu\compose.yaml", + r"\\wsl.localhost.evil.com\Ubuntu\compose.yaml", + r"\\wsl.localhost@SSL\Ubuntu\compose.yaml", + r"\\wsl.localhost", + r"\\wsl.localhost\", + r"\\wsl$\", + r"\\wsl.localhost\.\compose.yaml", + r"\\wsl.localhost\..\compose.yaml", + r"\\wsl.localhost\...\compose.yaml", + r"\\wsl.localhost\.hidden\compose.yaml", + r"\\wsl.localhost\Ubuntu.\compose.yaml", + r"\\wsl.localhost\Ubuntu \compose.yaml", + r"\\wsl.localhost\my distro\compose.yaml", + r"\\wsl.localhost\\Ubuntu\compose.yaml", + r"\\wsl.localhost\Ubuntu\..\..\Debian\compose.yaml", + r"\\wsl.localhost\Ubuntu@SSL\compose.yaml", + r"\\wsl.localhost\Ubuntu:stream\compose.yaml", + r"\\wsl.localhost\Ubuntu\compose.yaml:Zone.Identifier", + ] { + assert_eq!(wsl_unc(bad), None, "{bad} must not parse as local WSL UNC"); + assert!(remote_path(bad), "{bad} must be rejected by remote_path"); + assert_eq!(valid_file(bad), None, "{bad} must not pass valid_file"); + } + + for (ok, distro, inner) in [ + (r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml", "Ubuntu", "/home/simone/services/docker-compose.yml"), + (r"\\wsl$\Ubuntu-24.04\home\simone\services\docker-compose.yml", "Ubuntu-24.04", "/home/simone/services/docker-compose.yml"), + ("//wsl.localhost/Debian/srv/app/compose.yaml", "Debian", "/srv/app/compose.yaml"), + (r"\\?\UNC\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml", "Ubuntu", "/home/simone/services/docker-compose.yml"), + (r"\\?\unc\wsl$\NixOS\etc\compose\compose.yaml", "NixOS", "/etc/compose/compose.yaml"), + (r"\\wsl.localhost\Ubuntu\home\simone\a\..\services\.\docker-compose.yml", "Ubuntu", "/home/simone/services/docker-compose.yml"), + (r"\\wsl.localhost\Ubuntu", "Ubuntu", "/"), + (r"\\wsl.localhost\Ubuntu\", "Ubuntu", "/"), + ] { + assert_eq!(wsl_unc(ok), Some((distro.to_owned(), inner.to_owned())), "{ok}"); + assert!(!remote_path(ok), "{ok} stays on this machine"); + } + + assert_eq!( + plain_path(PathBuf::from(r"\\?\UNC\wsl.localhost\Ubuntu\home\simone\compose.yaml")), + PathBuf::from(r"\\wsl.localhost\Ubuntu\home\simone\compose.yaml") + ); + assert_eq!( + plain_path(PathBuf::from(r"\\?\unc\wsl$\Ubuntu\home\simone\compose.yaml")), + PathBuf::from(r"\\wsl$\Ubuntu\home\simone\compose.yaml") + ); + + assert!(same_file_path( + Path::new(r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml"), + Path::new(r"\\wsl$\ubuntu\home\simone\services\docker-compose.yml") + )); + assert!(same_file_path( + Path::new(r"\\?\UNC\wsl.localhost\UBUNTU\home\simone\services\docker-compose.yml"), + Path::new(r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml") + )); + assert!(!same_file_path( + Path::new(r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml"), + Path::new(r"\\wsl.localhost\Debian\home\simone\services\docker-compose.yml") + )); + assert!(!same_file_path( + Path::new(r"\\wsl.localhost\Ubuntu\home\Simone\services\docker-compose.yml"), + Path::new(r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml") + )); + } + + #[test] + fn wsl_compose_labels_map_to_windows_paths_across_legacy_integrated_and_mounted_drives() { + assert_eq!(wsl_automount_root(""), "/mnt/"); + assert_eq!(wsl_automount_root("[automount]\nroot = /windows # custom\n"), "/windows/"); + assert_eq!(wsl_automount_root("[Automount]\nroot = \"/\"\n"), "/"); + assert_eq!(wsl_automount_root("[network]\nroot = /bad\n"), "/mnt/"); + + assert_eq!( + wsl_to_windows("/home/simone/services/docker-compose.yml", "Ubuntu", "/mnt/"), + Some(r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml".into()) + ); + assert_eq!(wsl_to_windows("/home/simone/services", "Ubuntu", "/mnt/"), Some(r"\\wsl.localhost\Ubuntu\home\simone\services".into())); + assert_eq!(wsl_to_windows("/", "Ubuntu", "/mnt/"), Some(r"\\wsl.localhost\Ubuntu\".into())); + assert_eq!(wsl_to_windows("/mnt/c/Users/simone/app/compose.yaml", "Ubuntu", "/mnt/"), Some(r"C:\Users\simone\app\compose.yaml".into())); + assert_eq!(wsl_to_windows("/mnt/c", "Ubuntu", "/mnt/"), Some(r"C:\".into())); + assert_eq!(wsl_to_windows("/c/Users/simone/app/compose.yaml", "Ubuntu", "/"), Some(r"C:\Users\simone\app\compose.yaml".into())); + assert_eq!( + wsl_to_windows("/mnt/wsl/kiri/roots/Debian/home/dev/compose.yaml", "kiri", "/mnt/"), + Some(r"\\wsl.localhost\Debian\home\dev\compose.yaml".into()) + ); + for bad in ["compose.yaml", "//evil/share/compose.yaml", "/home/a:b/compose.yaml", "/home/a\\b/compose.yaml", "/mnt/wsl/kiri/sockets/Ubuntu/docker.sock"] { + assert_eq!(wsl_to_windows(bad, "Ubuntu", "/mnt/"), None, "{bad}"); + } + assert_eq!(wsl_to_windows("/home/simone/compose.yaml", "../evil", "/mnt/"), None); + + // 1. Pre-existing 0.2.1/0.2.2 container (no KiriWslDistro, no bind mounts) in engine distro Ubuntu. + let legacy_ubuntu = json!([{ + "Id": "mongo1", "Names": ["/services-mongo-1"], "Image": "mongo:7", "State": "running", "Status": "Up", "Created": 10, + "Labels": { + PROJECT: "services", SERVICE: "mongo", + WORKDIR: "/home/simone/services", + FILES: "/home/simone/services/docker-compose.yml", + ENV_FILES: "/home/simone/services/prod.env", + }, + "Mounts": [{"Type": "volume", "Name": "services_data", "Destination": "/data/db"}], + }]); + let got = wsl_projects(&legacy_ubuntu, &["Ubuntu".into()], |_| "/mnt/".into(), |_| false); + assert_eq!(got.len(), 1); + assert_eq!(got[0].dir, r"\\wsl.localhost\Ubuntu\home\simone\services"); + assert_eq!(got[0].files, [r"\\wsl.localhost\Ubuntu\home\simone\services\docker-compose.yml"]); + assert_eq!(got[0].env_files, [r"\\wsl.localhost\Ubuntu\home\simone\services\prod.env"]); + + // 2. Pre-existing 0.2.2 containers across multiple distros: inferred from bind mount or probed on disk. + let legacy_multi = json!([ + { + "Id": "wp1", "Names": ["/wp-db-1"], "Image": "mysql:8", "State": "running", "Status": "Up", "Created": 10, + "Labels": {PROJECT: "wordpress", SERVICE: "db", WORKDIR: "/home/simone/wordpress", FILES: "/home/simone/wordpress/docker-compose.yml"}, + "Mounts": [{"Type": "bind", "Source": "/mnt/wsl/kiri/roots/Ubuntu-24.04/home/simone/wordpress/html", "Destination": "/var/www/html"}], + }, + { + "Id": "api1", "Names": ["/api-web-1"], "Image": "node:22", "State": "running", "Status": "Up", "Created": 12, + "Labels": {PROJECT: "api", SERVICE: "web", WORKDIR: "/home/dev/api", FILES: "/home/dev/api/compose.yaml"}, + "Mounts": [], + } + ]); + let got = wsl_projects( + &legacy_multi, + &["Ubuntu-24.04".into(), "Debian".into()], + |_| "/mnt/".into(), + |p| p == r"\\wsl.localhost\Debian\home\dev\api\compose.yaml", + ); + let by = |n: &str| got.iter().find(|p| p.name == n).unwrap().clone(); + assert_eq!(by("wordpress").files, [r"\\wsl.localhost\Ubuntu-24.04\home\simone\wordpress\docker-compose.yml"]); + assert_eq!(by("api").files, [r"\\wsl.localhost\Debian\home\dev\api\compose.yaml"]); + + // 3. Integrated WSL distro (`KiriWslDistro`), `/mnt/c/...` mount path, and post-Apply Windows UNC container. + let mixed = json!([ + { + "Id": "deb1", "Names": ["/deb-app-1"], "Image": "alpine", "State": "running", "Status": "Up", "Created": 20, + "KiriWslDistro": "Debian", + "Labels": {PROJECT: "debproj", SERVICE: "app", WORKDIR: "/srv/debproj", FILES: "/srv/debproj/compose.yaml"}, + }, + { + "Id": "drv1", "Names": ["/shop-web-1"], "Image": "nginx", "State": "running", "Status": "Up", "Created": 25, + "KiriWslDistro": "Ubuntu", + "Labels": {PROJECT: "shop", SERVICE: "web", WORKDIR: "/mnt/c/Users/simone/shop", FILES: "/mnt/c/Users/simone/shop/compose.yaml"}, + }, + { + "Id": "old1", "Names": ["/svc-db-1"], "Image": "postgres:16", "State": "running", "Status": "Up", "Created": 30, + "KiriWslDistro": "Ubuntu", + "Labels": {PROJECT: "svc", SERVICE: "db", WORKDIR: "/home/simone/svc", FILES: "/home/simone/svc/compose.yaml"}, + }, + { + "Id": "new1", "Names": ["/svc-web-1"], "Image": "nginx", "State": "running", "Status": "Up", "Created": 40, + "KiriWslDistro": "Ubuntu", + "Labels": { + PROJECT: "svc", SERVICE: "web", + WORKDIR: r"\\wsl.localhost\Ubuntu\home\simone\svc", + FILES: r"\\wsl.localhost\Ubuntu\home\simone\svc\compose.yaml", + }, + } + ]); + let got = wsl_projects(&mixed, &["kiri".into()], |_| "/mnt/".into(), |_| false); + let by = |n: &str| got.iter().find(|p| p.name == n).unwrap().clone(); + assert_eq!(by("debproj").files, [r"\\wsl.localhost\Debian\srv\debproj\compose.yaml"]); + assert_eq!(by("shop").dir, r"C:\Users\simone\shop"); + assert_eq!(by("shop").files, [r"C:\Users\simone\shop\compose.yaml"]); + assert_eq!(by("svc").dir, r"\\wsl.localhost\Ubuntu\home\simone\svc"); + assert_eq!(by("svc").files, [r"\\wsl.localhost\Ubuntu\home\simone\svc\compose.yaml"]); + } } diff --git a/crates/kiri/src/ui/gtk.rs b/crates/kiri/src/ui/gtk.rs index d630ab87d..4604c8ddc 100644 --- a/crates/kiri/src/ui/gtk.rs +++ b/crates/kiri/src/ui/gtk.rs @@ -3,10 +3,16 @@ //! `webkit.messageHandlers.kiri`, which WebKitGTK has too, and gets events //! through `kiri.on(...)`. //! -//! The window keeps the desktop's own title bar, as on Windows. Closing it -//! quits the window only: the engine is a system service and keeps running. +//! The window keeps the desktop's own title bar, as on Windows. While a +//! `StatusNotifierWatcher` is on the session bus (`sni.rs`), closing the +//! window hides it behind the tray icon (or, with Settings → Appearance → +//! Closing the window → Close, lets go of its WebKit view too so WebKit's +//! helper processes end). With no tray host on the desktop, closing the +//! window quits `kiri ui` as before. Either way the engine is a system +//! service and keeps running. use std::cell::RefCell; +use std::ffi::{CStr, c_char, c_int, c_void}; use std::io; use std::sync::mpsc; @@ -22,12 +28,18 @@ thread_local! { /// The page and its window. Only ever touched on GTK's main thread. static WEBVIEW: RefCell> = const { RefCell::new(None) }; static WINDOW: RefCell> = const { RefCell::new(None) }; + /// Where a page made again (after the window let go of its own) sends + /// its messages. + static PAGE_TX: RefCell>> = const { RefCell::new(None) }; + /// Scripts for a page made again, kept until it says `ready`: the tray + /// menu's container items show the window and send at once. + static QUEUED: RefCell>> = const { RefCell::new(None) }; } /// Before the page's own scripts: which system this is. const SHIM: &str = r#"window.KIRI_OS = "linux";"#; -const ICON_PNG: &[u8] = include_bytes!("../../../../brand/icon/png/kiri-app-icon-512.png"); +pub(super) const ICON_PNG: &[u8] = include_bytes!("../../../../brand/icon/png/kiri-app-icon-512.png"); /// `autostart` starts the engine as soon as the page has loaded; `view` picks /// the sidebar section to open on. @@ -39,6 +51,8 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { let (tx, rx) = mpsc::channel(); let engine_tx = tx.clone(); let engine = std::thread::Builder::new().name("kiri-engine".into()).spawn(move || engine(rx, engine_tx))?; + PAGE_TX.with(|t| *t.borrow_mut() = Some(tx.clone())); + super::sni::start(tx.clone(), ICON_PNG); let window = gtk::Window::new(gtk::WindowType::Toplevel); window.set_title(crate::flavor::APP.get()); @@ -55,13 +69,45 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { window.set_size_request(760, 480); window.set_position(gtk::WindowPosition::Center); + let webview = make_webview(tx.clone(), autostart, view); + 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; + window.connect_delete_event(move |window, _| { + if super::sni::tray_available() { + window.hide(); + release_page(window); + return glib::Propagation::Stop; + } + let _ = quit_tx.send(Cmd::Quit); + gtk::main_quit(); + glib::Propagation::Proceed + }); + window.show_all(); + WINDOW.with(|v| *v.borrow_mut() = Some(window)); + gtk::main(); + let _ = engine.join(); + Ok(()) +} + +/// The page, in a new WebKitGTK view. +fn make_webview(tx: mpsc::Sender, autostart: bool, view: Option) -> WebView { let content = UserContentManager::new(); content.add_script(&UserScript::new(SHIM, UserContentInjectedFrames::TopFrame, UserScriptInjectionTime::Start, &[], &[])); content.register_script_message_handler("kiri"); - let page_tx = tx.clone(); content.connect_script_message_received(Some("kiri"), move |_, message| { if let Some(text) = message.js_value().map(|v| v.to_str()) { - super::handle(&text, &page_tx, autostart, view.as_deref()); + let text = text.to_string(); + // A page made again has loaded: what was sent meanwhile goes in now. + if serde_json::from_str::(&text).is_ok_and(|m| m["cmd"] == "ready") { + for js in QUEUED.with(|q| q.borrow_mut().take()).unwrap_or_default() { + eval(js); + } + } + super::handle(&text, &tx, autostart, view.as_deref()); } }); let webview = WebView::with_user_content_manager(&content); @@ -72,25 +118,120 @@ pub fn run(autostart: bool, view: Option) -> io::Result<()> { // animation, which cost 26% of a core idle where there is no GPU // (a VM; software GL), against under 1.5% without it. settings.set_hardware_acceleration_policy(webkit2gtk::HardwareAccelerationPolicy::Never); + whole_frames(&settings); settings.set_enable_write_console_messages_to_stdout(cfg!(debug_assertions)); } + let dark = match prefs()["theme"].as_str().unwrap_or("system") { + "dark" => true, + "light" => false, + _ => desktop_dark(), + }; + webview.set_background_color(&page_background(dark)); webview.load_html(&super::assemble::page(PAGE, super::prefs()["lang"].as_str()), None); - window.add(&webview); - // Before set_appearance, which gives it its background. - WEBVIEW.with(|v| *v.borrow_mut() = Some(webview)); + webview +} - set_appearance(prefs()["theme"].as_str().unwrap_or("system")); - let quit_tx = tx; - window.connect_delete_event(move |_, _| { - let _ = quit_tx.send(Cmd::Quit); - gtk::main_quit(); - glib::Propagation::Proceed - }); - window.show_all(); - WINDOW.with(|v| *v.borrow_mut() = Some(window)); - gtk::main(); - let _ = engine.join(); - Ok(()) +/// The window closed with Settings → Closing the window → Close while the tray +/// is up: it lets go of its WebKitGTK view, freeing `WebKitWebProcess` and +/// `WebKitNetworkProcess`. The tray and the engine thread stay; [`show`] makes +/// the page again. +fn release_page(window: >k::Window) { + if prefs()["closeButton"] != "close" { + return; + } + let Some(webview) = WEBVIEW.with(|v| v.borrow_mut().take()) else { return }; + QUEUED.with(|q| *q.borrow_mut() = None); + window.remove(&webview); + // SAFETY: `webview` was just removed from `window` and taken out of + // `WEBVIEW`, so nothing queries it after `gtk_widget_destroy`. + unsafe { webview.destroy() }; + drop(webview); + super::page_gone(); +} + +/// Turns off WebKit's `PropagateDamagingInformation`. With it on and no GPU +/// compositing (see `run`), WebKitGTK 2.52 and 2.54 hand GTK only each frame's +/// repainted rectangles, and GTK 3 clears the rest of the view to the +/// window's own background: hover a row and the main pane goes blank, +/// leaving only the strip and the status bar. An opaque view background +/// (`page_background`) did not stop it. With propagation off WebKit marks the +/// whole view as changed in every frame, which costs next to nothing here +/// since the CPU is already drawing the frame. +/// +/// The feature API is WebKitGTK 2.42 and the bindings stop at 2.40, so it is +/// looked up at run time: on an older WebKit, or one without the feature, +/// this does nothing. +fn whole_frames(settings: &webkit2gtk::Settings) { + let (Some(all), Some(len), Some(get), Some(id), Some(set), Some(unref)) = ( + sym(c"webkit_settings_get_all_features"), + sym(c"webkit_feature_list_get_length"), + sym(c"webkit_feature_list_get"), + sym(c"webkit_feature_get_identifier"), + sym(c"webkit_settings_set_feature_enabled"), + sym(c"webkit_feature_list_unref"), + ) else { + return; + }; + // SAFETY: the symbols have the signatures WebKitGTK 2.42 documents; the + // list is ours until unref, and its features live as long as it does. + unsafe { + let api = FeatureApi { + all: std::mem::transmute::<*mut c_void, AllFeatures>(all), + len: std::mem::transmute::<*mut c_void, ListLen>(len), + get: std::mem::transmute::<*mut c_void, ListGet>(get), + id: std::mem::transmute::<*mut c_void, Identifier>(id), + set: std::mem::transmute::<*mut c_void, SetEnabled>(set), + unref: std::mem::transmute::<*mut c_void, Unref>(unref), + }; + api.disable_damage_propagation(settings.as_ptr().cast()); + } +} + +type AllFeatures = unsafe extern "C" fn() -> *mut c_void; +type ListLen = unsafe extern "C" fn(*mut c_void) -> usize; +type ListGet = unsafe extern "C" fn(*mut c_void, usize) -> *mut c_void; +type Identifier = unsafe extern "C" fn(*mut c_void) -> *const c_char; +type SetEnabled = unsafe extern "C" fn(*mut c_void, *mut c_void, c_int); +type Unref = unsafe extern "C" fn(*mut c_void); + +struct FeatureApi { + all: AllFeatures, + len: ListLen, + get: ListGet, + id: Identifier, + set: SetEnabled, + unref: Unref, +} + +impl FeatureApi { + /// # Safety + /// `self` must hold functions matching WebKitGTK 2.42's `WebKitFeatureList` + /// C ABI, and `settings` must be a valid `WebKitSettings *` for `self.set`. + unsafe fn disable_damage_propagation(&self, settings: *mut c_void) { + // SAFETY: caller guarantees the function pointers and settings pointer. + unsafe { + let list = (self.all)(); + if list.is_null() { + return; + } + for i in 0..(self.len)(list) { + let feature = (self.get)(list, i); + if !feature.is_null() { + let name = (self.id)(feature); + if !name.is_null() && CStr::from_ptr(name) == c"PropagateDamagingInformation" { + (self.set)(settings, feature, 0); + } + } + } + (self.unref)(list); + } + } +} + +fn sym(name: &CStr) -> Option<*mut c_void> { + // SAFETY: a lookup by name in the already-loaded process symbols. + let p = unsafe { libc::dlsym(libc::RTLD_DEFAULT, name.as_ptr()) }; + (!p.is_null()).then_some(p) } fn icon() -> Option { @@ -107,6 +248,14 @@ pub(super) fn relang() {} pub(super) fn eval(js: String) { glib::MainContext::default().invoke(move || { + let js = QUEUED.with(|q| match q.borrow_mut().as_mut() { + Some(queued) => { + queued.push(js); + None + } + None => Some(js), + }); + let Some(js) = js else { return }; WEBVIEW.with(|v| { if let Some(webview) = v.borrow().as_ref() { webview.evaluate_javascript(&js, None, None, None::<>k::gio::Cancellable>, |_| {}); @@ -115,14 +264,49 @@ pub(super) fn eval(js: String) { }); } -/// Closes the window, from any thread. -pub(super) fn quit() { +/// Shows the window again (from the tray's click or Open Kiri), making the +/// page again if closing the window let go of it. +pub(super) fn show() { glib::MainContext::default().invoke(|| { WINDOW.with(|v| { if let Some(window) = v.borrow().as_ref() { - window.close(); + if WEBVIEW.with(|w| w.borrow().is_none()) + && let Some(tx) = PAGE_TX.with(|t| t.borrow().clone()) + { + let webview = make_webview(tx, false, None); + QUEUED.with(|q| *q.borrow_mut() = Some(Vec::new())); + window.add(&webview); + webview.show(); + WEBVIEW.with(|w| *w.borrow_mut() = Some(webview)); + } + window.show(); + window.present(); + } + }); + }); +} + +/// The tray host left the session bus or refused the item: a window closed +/// to the tray (hidden, or without its page) comes back, so there is never +/// neither a window nor a tray icon. +pub(super) fn tray_gone() { + glib::MainContext::default().invoke(|| { + let hidden = WINDOW.with(|v| v.borrow().as_ref().is_some_and(|w| !w.is_visible())); + if hidden || WEBVIEW.with(|w| w.borrow().is_none()) { + show(); + } + }); +} + +/// Quits the window and its engine thread, from any thread. +pub(super) fn quit() { + glib::MainContext::default().invoke(|| { + PAGE_TX.with(|t| { + if let Some(tx) = t.borrow().as_ref() { + let _ = tx.send(Cmd::Quit); } }); + gtk::main_quit(); }); } @@ -222,6 +406,19 @@ pub(super) fn pick_compose_file(title: &str, filters: &[String; 2], done: impl F }); } +/// Settings → Storage → Change…: GTK's folder chooser (the desktop's portal +/// when there is one), on GTK's main thread. `done` gets the path, or None. +pub(super) fn pick_folder(title: &str, done: impl FnOnce(Option) + Send + 'static) { + let title = title.to_owned(); + glib::MainContext::default().invoke(move || { + let parent = WINDOW.with(|v| v.borrow().clone()); + let dialog = gtk::FileChooserNative::new(Some(&title), parent.as_ref(), gtk::FileChooserAction::SelectFolder, None, None); + let picked = if dialog.run() == gtk::ResponseType::Accept { dialog.filename() } else { None }; + dialog.destroy(); + done(picked); + }); +} + /// The installed font families, sorted; `mono` keeps the fixed-pitch ones. pub(super) fn font_families(mono: bool) -> Vec { let spacing = if mono { ":spacing=mono" } else { ":" }; @@ -235,3 +432,114 @@ pub(super) fn font_families(mono: bool) -> Vec { names.dedup(); names } + +#[cfg(test)] +mod tests { + use std::ffi::{c_char, c_int, c_void}; + use std::ptr; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::{FeatureApi, sym}; + + #[test] + fn sym_finds_loaded_symbols_and_rejects_missing_ones() { + assert!(sym(c"dlsym").is_some()); + assert!(sym(c"webkit_no_such_symbol_in_kiri").is_none()); + } + + #[test] + fn disable_damage_propagation_toggles_only_matching_feature_and_unrefs_list() { + static UNREFS: AtomicUsize = AtomicUsize::new(0); + static CALLS: AtomicUsize = AtomicUsize::new(0); + static LAST_SETTINGS: AtomicUsize = AtomicUsize::new(0); + static LAST_FEATURE: AtomicUsize = AtomicUsize::new(0); + static LAST_ENABLED: AtomicUsize = AtomicUsize::new(99); + + unsafe extern "C" fn all() -> *mut c_void { + 0x1000 as *mut c_void + } + unsafe extern "C" fn len(list: *mut c_void) -> usize { + assert_eq!(list, 0x1000 as *mut c_void); + 4 + } + unsafe extern "C" fn get(list: *mut c_void, idx: usize) -> *mut c_void { + assert_eq!(list, 0x1000 as *mut c_void); + match idx { + 0 => ptr::null_mut(), + 1 => 0x2001 as *mut c_void, + 2 => 0x2002 as *mut c_void, + 3 => 0x2003 as *mut c_void, + _ => unreachable!(), + } + } + unsafe extern "C" fn id(feature: *mut c_void) -> *const c_char { + match feature as usize { + 0x2001 => ptr::null(), + 0x2002 => c"AcceleratedCompositing".as_ptr(), + 0x2003 => c"PropagateDamagingInformation".as_ptr(), + _ => unreachable!(), + } + } + unsafe extern "C" fn set(settings: *mut c_void, feature: *mut c_void, enabled: c_int) { + CALLS.fetch_add(1, Ordering::SeqCst); + LAST_SETTINGS.store(settings as usize, Ordering::SeqCst); + LAST_FEATURE.store(feature as usize, Ordering::SeqCst); + LAST_ENABLED.store(enabled as usize, Ordering::SeqCst); + } + unsafe extern "C" fn unref(list: *mut c_void) { + assert_eq!(list, 0x1000 as *mut c_void); + UNREFS.fetch_add(1, Ordering::SeqCst); + } + + let api = FeatureApi { + all, + len, + get, + id, + set, + unref, + }; + // SAFETY: the test callbacks above expect these sentinel pointers. + unsafe { api.disable_damage_propagation(0x9000 as *mut c_void) }; + assert_eq!(CALLS.load(Ordering::SeqCst), 1); + assert_eq!(LAST_SETTINGS.load(Ordering::SeqCst), 0x9000); + assert_eq!(LAST_FEATURE.load(Ordering::SeqCst), 0x2003); + assert_eq!(LAST_ENABLED.load(Ordering::SeqCst), 0); + assert_eq!(UNREFS.load(Ordering::SeqCst), 1); + } + + #[test] + fn disable_damage_propagation_ignores_null_feature_list() { + static UNREFS: AtomicUsize = AtomicUsize::new(0); + unsafe extern "C" fn all() -> *mut c_void { + ptr::null_mut() + } + unsafe extern "C" fn len(_: *mut c_void) -> usize { + unreachable!() + } + unsafe extern "C" fn get(_: *mut c_void, _: usize) -> *mut c_void { + unreachable!() + } + unsafe extern "C" fn id(_: *mut c_void) -> *const c_char { + unreachable!() + } + unsafe extern "C" fn set(_: *mut c_void, _: *mut c_void, _: c_int) { + unreachable!() + } + unsafe extern "C" fn unref(_: *mut c_void) { + UNREFS.fetch_add(1, Ordering::SeqCst); + } + + let api = FeatureApi { + all, + len, + get, + id, + set, + unref, + }; + // SAFETY: `all` returns null so no pointer is dereferenced. + unsafe { api.disable_damage_propagation(ptr::null_mut()) }; + assert_eq!(UNREFS.load(Ordering::SeqCst), 0); + } +} diff --git a/crates/kiri/src/ui/index.html b/crates/kiri/src/ui/index.html index c689677fc..1e2bcb969 100644 --- a/crates/kiri/src/ui/index.html +++ b/crates/kiri/src/ui/index.html @@ -160,7 +160,7 @@ body.rail[data-vm=running] .vm .dot::after { content: ""; position: absolute; inset: 0; border-radius: 50%; background: var(--moss); --ring: 2.8; animation: var(--beat); pointer-events: none; } .mark .speed { fill: currentColor; opacity: .35; transition: opacity .3s; } [data-vm=running] .mark .speed { opacity: .9; } -[data-vm=booting] .mark .speed { animation: zoom .25s infinite alternate; } +[data-vm=booting] .mark .speed, [data-vm=restarting] .mark .speed { animation: zoom .25s infinite alternate; } [data-vm=stopped] .mark .eyes, [data-vm=asleep] .mark .eyes { transform: scaleY(.25); transform-origin: 46px 29px; } .navlabel { font-size: var(--fs); font-weight: 600; color: var(--faint); padding: 10px 8px 4px; text-transform: uppercase; letter-spacing: .06em; } @@ -180,7 +180,7 @@ .vm-head { display: flex; align-items: center; gap: 7px; font-weight: 600; } .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--faint); flex: none; } [data-vm=running] .dot { background: var(--moss); box-shadow: 0 0 0 3px color-mix(in srgb, var(--moss) 25%, transparent); } -[data-vm=booting] .dot, [data-vm=waking] .dot, [data-vm=stopping] .dot { background: var(--sun); animation: pulse .8s infinite alternate; } +[data-vm=booting] .dot, [data-vm=waking] .dot, [data-vm=stopping] .dot, [data-vm=restarting] .dot { background: var(--sun); animation: pulse .8s infinite alternate; } [data-vm=asleep] .dot { background: transparent; box-shadow: inset 0 0 0 2px var(--moss); } .vm-sub { color: var(--faint); font-size: var(--fs-small); margin-top: -6px; } #vm-state { margin-inline-start: auto; font-weight: 500; color: var(--muted); font-size: var(--fs); } @@ -868,7 +868,7 @@ .statusbar .k8s { width: 13px; height: 13px; fill: #326CE5; flex: none; } .statusbar .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--faint); } .statusbar .dot.running { background: var(--moss); } -.statusbar .dot.booting, .statusbar .dot.stopping { background: var(--sun); } +.statusbar .dot.booting, .statusbar .dot.stopping, .statusbar .dot.restarting { background: var(--sun); } .statusbar .dot.asleep { background: transparent; box-shadow: inset 0 0 0 1.5px var(--moss); } .statusbar .sep { color: var(--faint); } /* Kiri Dev, after the version: solid amber with near-black text, the same in either theme. */ @@ -1065,9 +1065,12 @@ font: 500 var(--fs) var(--ui-font); text-align: var(--start); cursor: pointer; } .menu button:hover, .menu button:focus-visible { background: var(--raised); outline: none; } .menu button.danger { color: var(--red); } -/* Settings */ -.settings { display: grid; grid-template-columns: 180px 1fr; gap: 28px; align-items: start; max-width: 860px; } -.settings .tabs { display: grid; gap: 2px; } +/* Settings: the left tab rail stays static while the pane body scrolls. */ +.content:has(> .settings) { display: flex; flex-direction: column; overflow: hidden; padding-block: 0; padding-inline-end: 0; } +.settings { flex: 1; min-height: 0; display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 28px; align-items: stretch; } +.settings .tabs { display: grid; gap: 2px; align-content: start; padding-block: 4px 20px; overflow-y: auto; } +.settings-body { min-width: 0; height: 100%; overflow-y: auto; overflow-x: hidden; padding-block: 4px calc(20px + var(--hold, 0px)); padding-inline-end: 24px; } +.settings-body > :is(.pane, .panes) { max-width: 652px; } .settings .tabs button { display: flex; align-items: center; gap: 9px; height: 31px; padding: 0 10px; border: 0; border-radius: 7px; background: transparent; color: var(--muted); font: 500 var(--fs) var(--ui-font); text-align: var(--start); cursor: pointer; } .settings .tabs button:hover { background: var(--row-hover); color: var(--text); } @@ -1091,7 +1094,7 @@ .linkbtn { background: none; border: 0; padding: 0; color: var(--blue-light); font: inherit; cursor: pointer; } .pref { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 4px 20px; align-items: center; padding-bottom: 18px; border-bottom: 1px solid var(--line); } .pref .t { font-weight: 600; } -.pref .d { color: var(--muted); font-size: var(--fs); grid-column: 1; } +.pref .d { color: var(--muted); font-size: var(--fs); grid-column: 1; min-width: 0; } .pref select { grid-row: 1 / span 2; grid-column: 2; height: 32px; width: 240px; padding: 0 10px; border-radius: 7px; border: 1px solid var(--line); background: var(--panel); color: var(--text); font: var(--fs) var(--ui-font); } /* Every other + + + + ${right}${reloadAttr ? btn(tr("Reload"), reloadAttr) : ""}${btn(tr("Clear"), clearAttr)}`; +} +function updateLogCount(el, countId, d) { + const cnt = $(countId); + if (!cnt || !d) return; + const all = el.childElementCount; + const showing = d.logFilter || d.logLevel ? (el._shown ?? all) : all; + cnt.textContent = d.logFilter || d.logLevel ? tr("{showing} of {all} lines", { showing: showing.toLocaleString(), all: all.toLocaleString() }) : tr("{all} lines", { all: all.toLocaleString() }); +} +function appendLogParts(el, countId, d, partial, nextN, parts) { + const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; + const filter = d.logFilter.toLowerCase(), level = d.logLevel; const frag = document.createDocumentFragment(); + let addedShown = 0; for (const p of parts) { - const lines = (ui.partial[p.e] + p.t.replace(ansi, "").replace(/\r\n/g, "\n")).split("\n"); - ui.partial[p.e] = lines.pop(); + const key = Boolean(p.e); + const lines = ((partial[key] || "") + p.t.replace(ansi, "").replace(/\r\n/g, "\n")).split("\n"); + partial[key] = lines.pop(); for (const line of lines) { const div = document.createElement("div"); const lvl = levelOf(line); @@ -3529,22 +3731,50 @@

Containers

LOG_MAX) logEl.firstElementChild.remove(); - if (ui.detail.follow && atEnd || ui.detail.follow && parts.length > 50) logEl.scrollTop = logEl.scrollHeight; - logCount(); -} - -function filterLogs() { - const d = ui.detail, f = d.logFilter.toLowerCase(); - for (const div of logEl.children) div.classList.toggle("hide", !shown(div, f, d.logLevel)); - logCount(); -} + el._shown = (el._shown ?? el.childElementCount) + addedShown; + el.append(frag); + while (el.childElementCount > LOG_MAX) { + if (!el.firstElementChild.classList.contains("hide")) el._shown--; + el.firstElementChild.remove(); + } + if (d.follow && atEnd || d.follow && parts.length > 50) el.scrollTop = el.scrollHeight; + updateLogCount(el, countId, d); +} +function applyLogFilter(el, countId, d) { + const f = d.logFilter.toLowerCase(); + let visCount = 0; + for (const div of el.children) { + const vis = shown(div, f, d.logLevel); + div.classList.toggle("hide", !vis); + if (vis) visCount++; + } + el._shown = visCount; + updateLogCount(el, countId, d); +} +function appendLogEnd(el, text) { + const div = document.createElement("div"); + div.className = "quiet"; + div.textContent = text; + el._shown = (el._shown ?? el.childElementCount) + 1; + el.append(div); +} +function clearLogConsole(el, countId, d, partial, resetN) { + el.textContent = ""; + el._shown = 0; + partial.false = ""; + partial.true = ""; + resetN(); + updateLogCount(el, countId, d); +} +function logCount() { updateLogCount(logEl, "log-count", ui.detail); } +function addLogs(parts) { appendLogParts(logEl, "log-count", ui.detail, ui.partial, () => ++ui.logN, parts); } +function filterLogs() { applyLogFilter(logEl, "log-count", ui.detail); } /* The prompt, as a shell shows it: user@host:dir# (or $ for other users). Until the container has answered, it comes from the inspect data. */ @@ -3694,12 +3924,7 @@

Containers

- - - - ${btn(tr("Clear"), "data-logclear")}`; + body.innerHTML = logToolbarHtml({ prefix: "log", filter: d.logFilter, level: d.logLevel, follow: d.follow, clearAttr: "data-logclear" }); body.append(logEl); logCount(); $("log-filter").addEventListener("input", (ev) => { d.logFilter = ev.target.value; filterLogs(); }); @@ -3775,9 +4000,10 @@

Containers

Containers