Windows: official port -- UCRT static build, UTF-8 throughout, Low IL sandbox, ncurses TUI, installer; v0.6.0

Build
  * cross build switches to pkgsCross.ucrt64 (shell-win.nix); curl (Schannel),
    winpthreads and ncurses 6.6 are linked statically, so the release is
    cst-agent.exe + busybox.exe (busybox-w32 Unicode) with no extra DLLs
  * windres embeds a manifest with activeCodePage=UTF-8 and a version resource
  * ncurses 6.6 Windows console driver patches (mouse button state, A_DIM,
    wide-char declarations): scripts/patches/
  * scripts/bootstrap_msys2.sh builds the same release natively in MSYS2
    UCRT64; PR #1's MINGW64 notes now point there
  * vendor/tre-regex (musl's TRE) provides <regex.h> on MinGW

UTF-8
  * paths cross the system call boundary as UTF-16 (*W APIs); console code
    pages set to 65001 and restored on exit; files are read and written in
    binary mode
  * child output that is not valid UTF-8 is decoded from the console, OEM or
    ANSI system code page
  * read_file hides CR; edit_file, apply_patch and write_file keep CRLF line
    endings and a UTF-8 BOM

OS layer and processes
  * os_dir_* and cst_fnmatch replace the POSIX-only directory walks in
    subagent, plugins, skills, undo and fs_tools; realpath / path_under and
    symlink rejection work on Windows
  * every child goes through CreateProcessW with its own environment block
    inside a Job Object, so timeouts and Esc end the whole process tree

Sandbox (auto mode, "auto · lowil")
  * run_shell runs with a restricted Low integrity token; the workspace gets
    an inheritable Low label once, the sandbox TEMP is labeled Low, and the
    credentials file gets a no-read-up label
  * drive roots, the profile and system folders are never labeled
  * network commands still ask, since Low IL does not block the network;
    Access denied and MSYS2's 0xc0000142 offer a rerun outside the sandbox
  * /sandbox lists labeled folders, /sandbox reset-labels restores them

TUI
  * raster console fonts are switched to Consolas / NSimSun while running
  * the home logo falls back to text when the console font lacks U+2580
  * mouse drag copy goes to the Windows clipboard

Distribution
  * scripts/install_windows.ps1 installs a Gitea release into
    %LOCALAPPDATA%\Programs\cst-agent and adds it to the user PATH;
    cst-agent-update.cmd reruns it; scripts/release_windows.sh uploads the
    zip with the token taken from the environment
  * scripts/run_windows.bat is gone; docs/README-windows.md is rewritten

Tests
  * new test_lowil, test_win_utf8 and test_os_dir; tests made portable
    (cst_test_util.h)
  * scripts/win_test.sh and scripts/winvm/ run the suite on English and
    Chinese Windows Server VMs as Administrator, a standard user and a
    Chinese user name: 29/29 on all six
This commit is contained in:
WHC
2026-10-06 23:08:14 +08:00
parent 9862c29f58
commit 2a43ae6622
84 changed files with 9784 additions and 1083 deletions
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# Native Windows build from an MSYS2 UCRT64 shell (https://www.msys2.org/).
# scripts/bootstrap_msys2.sh [repo-dir]
# Installs the UCRT64 toolchain with pacman, builds the same pinned static
# deps as the Linux cross build (curl with Schannel, ncurses with the Windows
# console patches, busybox-w32 Unicode), then a static cst-agent.exe with the
# UTF-8 manifest, runs the tests and packages dist/windows-x86_64/.
# CST_SKIP_TESTS=1 skips ctest.
set -euo pipefail
if [[ "${MSYSTEM:-}" != UCRT64 ]]; then
echo "run this from the MSYS2 UCRT64 shell: the UTF-8 manifest needs the" \
"UCRT runtime (MINGW64 links msvcrt)" >&2
exit 1
fi
REPO_URL="${CST_AGENT_REPO:-https://git.whcself.xyz/WHC/CST-agent.git}"
DIR="${1:-}"
if [[ -z "$DIR" ]]; then
if [[ -f CMakeLists.txt && -d src ]]; then
DIR="$(pwd)"
else
DIR="CST-agent"
fi
fi
pacman -S --needed --noconfirm \
mingw-w64-ucrt-x86_64-gcc mingw-w64-ucrt-x86_64-cmake \
mingw-w64-ucrt-x86_64-ninja make git patch tar perl zip diffutils
if [[ ! -f "$DIR/CMakeLists.txt" ]]; then
echo "==> git clone $REPO_URL -> $DIR"
git clone "$REPO_URL" "$DIR"
fi
cd "$DIR"
# third-party script: unprefixed native tools
export MINGW_HOST= BUILD_CC=gcc
[[ -f third_party/prefix-mingw/lib/libcurl.a ]] || scripts/build_third_party_mingw.sh curl
[[ -f third_party/prefix-mingw/lib/libncursesw.a ]] || scripts/build_third_party_mingw.sh ncurses
if [[ ! -f third_party/busybox/busybox.exe ]]; then
scripts/build_third_party_mingw.sh busybox-w32 || scripts/fetch_busybox_w32.sh
fi
echo "==> cmake (MSYS2 UCRT64, static, TUI)"
cmake -S . -B build-msys2 -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DCMAKE_PREFIX_PATH="$PWD/third_party/prefix-mingw" \
-DCST_WIN_STATIC=ON -DCST_BUILD_TUI=ON
cmake --build build-msys2
if [[ -z "${CST_SKIP_TESTS:-}" ]]; then
echo "==> ctest"
cp -f third_party/busybox/busybox.exe build-msys2/
ctest --test-dir build-msys2 --output-on-failure
fi
echo "==> package"
CST_WIN_BUILD=build-msys2 scripts/package_windows.sh
+24 -25
View File
@@ -1,11 +1,13 @@
#!/usr/bin/env bash
# One-shot on a Linux host: cross-build Windows x86_64 release (MinGW).
# Output: dist/windows-x86_64/ — copy that folder to a Windows machine.
# Linux host: cross-build the Windows x86_64 release (mingw-w64, UCRT, static).
# scripts/bootstrap_windows.sh [repo-dir]
# With Nix the toolchain comes from shell-win.nix; otherwise x86_64-w64-mingw32-gcc
# (UCRT flavour, with winpthreads), cmake, ninja, git and perl must be installed.
# Output: dist/windows-x86_64/ and dist/cst-agent-VERSION-windows-x86_64.zip
set -euo pipefail
REPO_URL="${CST_AGENT_REPO:-https://git.whcself.xyz/WHC/CST-agent.git}"
DIR="${1:-}"
if [[ -z "$DIR" ]]; then
if [[ -f CMakeLists.txt && -d src ]]; then
DIR="$(pwd)"
@@ -13,36 +15,33 @@ if [[ -z "$DIR" ]]; then
DIR="CST-agent"
fi
fi
if [[ ! -f "$DIR/CMakeLists.txt" ]]; then
echo "==> git clone $REPO_URL -> $DIR"
git clone "$REPO_URL" "$DIR"
fi
cd "$DIR"
need() { command -v "$1" >/dev/null || { echo "missing $1 (install mingw-w64 gcc cmake git)" >&2; exit 1; }; }
need git; need cmake; need x86_64-w64-mingw32-gcc
if ! command -v x86_64-w64-mingw32-gcc >/dev/null && [[ -z "${IN_NIX_SHELL:-}" ]] &&
command -v nix-shell >/dev/null; then
exec nix-shell shell-win.nix --run "$(printf '%q ' "$0" "$PWD")"
fi
echo "==> third-party (curl Schannel + PDCurses + busybox-w32)"
chmod +x scripts/*.sh 2>/dev/null || true
./scripts/build_third_party_mingw.sh all
need() { command -v "$1" >/dev/null || { echo "missing $1 (mingw-w64 UCRT gcc, cmake, ninja, git, perl)" >&2; exit 1; }; }
need git; need cmake; need ninja; need perl; need x86_64-w64-mingw32-gcc
if ! printf '#include <stdio.h>\n' | x86_64-w64-mingw32-gcc -dM -E - | grep -qw _UCRT; then
echo "x86_64-w64-mingw32-gcc targets msvcrt; the UTF-8 manifest needs a UCRT toolchain" >&2
exit 1
fi
echo "==> cmake Windows TUI"
cmake -B build-win-tui \
[[ -f third_party/prefix-mingw/lib/libcurl.a ]] || scripts/build_third_party_mingw.sh curl
[[ -f third_party/prefix-mingw/lib/libncursesw.a ]] || scripts/build_third_party_mingw.sh ncurses
[[ -f third_party/busybox/busybox.exe ]] || scripts/build_third_party_mingw.sh busybox-w32
echo "==> cmake (Windows, TUI)"
cmake -S . -B build-win-tui -G Ninja \
-DCMAKE_TOOLCHAIN_FILE=cmake/mingw-w64-x86_64.cmake \
-DCST_BUILD_TUI=ON \
-DCMAKE_PREFIX_PATH="$PWD/third_party/prefix-mingw" \
-DPDCurses_ROOT="$PWD/third_party/prefix-mingw"
cmake --build build-win-tui -j"$(nproc 2>/dev/null || echo 4)"
-DCMAKE_BUILD_TYPE=Release -DCST_BUILD_TUI=ON
cmake --build build-win-tui
echo "==> package"
./scripts/package_windows.sh
echo
echo "OK: dist/windows-x86_64/"
echo "Copy that folder to Windows, then:"
echo " set OPENAI_API_KEY=sk-..."
echo " set OPENAI_BASE_URL=https://api.openai.com/v1"
echo " set OPENAI_MODEL=gpt-4.1-mini"
echo " cst-agent.exe --workspace ."
echo "See docs/env_openai.md and docs/README-windows.md"
scripts/package_windows.sh
+100 -112
View File
@@ -1,139 +1,127 @@
#!/usr/bin/env bash
# Build third-party deps for Windows MinGW cross + optional Unix busybox.
# Sources:
# busybox-w32: https://github.com/rmyorston/busybox-w32.git
# busybox: https://github.com/mirror/busybox.git
# curl: https://github.com/curl/curl.git (Windows via Schannel)
# PDCurses: https://github.com/wmcbrine/PDCurses.git
# Build pinned third-party deps for Windows x86_64 (mingw-w64, UCRT) into
# third_party/prefix-mingw, plus busybox-w32 into third_party/busybox.
# nix-shell shell-win.nix --run 'scripts/build_third_party_mingw.sh [all|curl|pdcurses|ncurses|busybox-w32]'
# Works the same from an MSYS2 UCRT64 shell (MINGW_HOST= uses unprefixed tools).
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
TP="$ROOT/third_party"
HOST="${MINGW_HOST:-x86_64-w64-mingw32}"
PREFIX="$TP/prefix-mingw"
HOST="${MINGW_HOST-x86_64-w64-mingw32}"
T="${HOST:+$HOST-}"
JOBS="${JOBS:-$(nproc 2>/dev/null || echo 4)}"
mkdir -p "$TP"
CURL_TAG=curl-8_22_0
PDCURSES_TAG=3.9
NCURSES_VER=6.6
BUSYBOX_W32_REV=9b50a1e
mkdir -p "$TP" "$PREFIX"
need_cmd() { command -v "$1" >/dev/null || { echo "missing: $1" >&2; exit 1; }; }
need_cmd git
need_cmd make
need_cmd "${HOST}-gcc"
need_cmd "${T}gcc"
clone_or_update() {
local url="$1" dir="$2"
if [[ -d "$dir/.git" ]]; then
git -C "$dir" fetch --depth 1 origin 2>/dev/null || true
git -C "$dir" pull --ff-only 2>/dev/null || true
else
git clone --depth 1 "$url" "$dir"
checkout() { # url dir rev
local url="$1" dir="$2" rev="$3"
[[ -d "$dir/.git" ]] || git clone -q --filter=blob:none "$url" "$dir"
if ! git -C "$dir" rev-parse -q --verify "$rev^{commit}" >/dev/null; then
git -C "$dir" fetch -q --tags origin
fi
git -C "$dir" checkout -q --detach "$rev"
}
# --- curl (static, Schannel) ---
build_curl_mingw() {
clone_or_update https://github.com/curl/curl.git "$TP/curl"
cd "$TP/curl"
if [[ ! -f configure ]]; then
autoreconf -fi 2>/dev/null || true
fi
# Prefer cmake for curl modern tree
rm -rf build-mingw
cmake -B build-mingw -G "Unix Makefiles" \
-DCMAKE_SYSTEM_NAME=Windows \
-DCMAKE_C_COMPILER="${HOST}-gcc" \
-DCMAKE_RC_COMPILER="${HOST}-windres" \
-DCMAKE_INSTALL_PREFIX="$TP/prefix-mingw" \
-DBUILD_SHARED_LIBS=OFF \
-DCURL_USE_SCHANNEL=ON \
-DCURL_USE_OPENSSL=OFF \
-DCURL_DISABLE_LDAP=ON \
-DCURL_USE_LIBPSL=OFF \
-DCURL_ZLIB=OFF \
-DCURL_BROTLI=OFF \
-DCURL_ZSTD=OFF \
-DUSE_NGHTTP2=OFF \
-DBUILD_CURL_EXE=OFF \
-DBUILD_TESTING=OFF \
-DHTTP_ONLY=OFF
cmake --build build-mingw -j"$JOBS"
cmake --install build-mingw
echo "curl installed -> $TP/prefix-mingw"
build_curl() {
checkout https://github.com/curl/curl.git "$TP/curl" "$CURL_TAG"
rm -rf "$TP/curl/build-mingw"
local tc=()
[[ -n "$HOST" ]] && tc=(-DCMAKE_SYSTEM_NAME=Windows -DCMAKE_C_COMPILER="${T}gcc" -DCMAKE_RC_COMPILER="${T}windres")
cmake -S "$TP/curl" -B "$TP/curl/build-mingw" -G Ninja "${tc[@]}" \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX="$PREFIX" \
-DBUILD_SHARED_LIBS=OFF -DBUILD_STATIC_LIBS=ON \
-DCURL_USE_SCHANNEL=ON -DCURL_USE_OPENSSL=OFF \
-DCURL_WINDOWS_SSPI=ON -DENABLE_UNICODE=ON \
-DCURL_DISABLE_LDAP=ON -DCURL_USE_LIBPSL=OFF -DCURL_USE_LIBSSH2=OFF \
-DUSE_LIBIDN2=OFF -DUSE_NGHTTP2=OFF \
-DCURL_ZLIB=OFF -DCURL_BROTLI=OFF -DCURL_ZSTD=OFF \
-DBUILD_CURL_EXE=OFF -DBUILD_TESTING=OFF -DBUILD_EXAMPLES=OFF \
-DBUILD_LIBCURL_DOCS=OFF -DBUILD_MISC_DOCS=OFF -DENABLE_CURL_MANUAL=OFF
cmake --build "$TP/curl/build-mingw" -j"$JOBS"
cmake --install "$TP/curl/build-mingw"
echo "curl $CURL_TAG -> $PREFIX"
}
# --- PDCurses ---
build_pdcurses_mingw() {
clone_or_update https://github.com/wmcbrine/PDCurses.git "$TP/PDCurses"
build_pdcurses() {
checkout https://github.com/wmcbrine/PDCurses.git "$TP/PDCurses" "$PDCURSES_TAG"
cd "$TP/PDCurses/wincon"
make -f Makefile clean 2>/dev/null || true
make -f Makefile \
CC="${HOST}-gcc" \
LINK="${HOST}-gcc" \
CFLAGS="-O2 -I.. -DPDC_WIDE -DPDC_FORCE_UTF8" \
LIBEXE="${HOST}-ar" \
LIBFLAGS=rcv \
pdcurses.a
mkdir -p "$TP/prefix-mingw/include" "$TP/prefix-mingw/lib"
cp -f ../curses.h "$TP/prefix-mingw/include/"
[[ -f ../panel.h ]] && cp -f ../panel.h "$TP/prefix-mingw/include/" || true
cp -f pdcurses.a "$TP/prefix-mingw/lib/libpdcurses.a"
# Also install as curses for find_library
cp -f pdcurses.a "$TP/prefix-mingw/lib/libcurses.a"
echo "PDCurses -> $TP/prefix-mingw"
make clean >/dev/null 2>&1 || true
make -j"$JOBS" CC="${T}gcc" AR="${T}ar" STRIP="${T}strip" WIDE=Y UTF8=Y pdcurses.a
mkdir -p "$PREFIX/include/pdcurses" "$PREFIX/lib"
cp -f ../curses.h ../panel.h "$PREFIX/include/pdcurses/"
cp -f pdcurses.a "$PREFIX/lib/libpdcurses.a"
echo "PDCurses $PDCURSES_TAG -> $PREFIX"
}
build_ncurses() {
local src="$TP/ncurses-$NCURSES_VER" tgz="$TP/ncurses-$NCURSES_VER.tar.gz"
[[ -f "$tgz" ]] || curl -fL -o "$tgz" \
"https://invisible-island.net/archives/ncurses/ncurses-$NCURSES_VER.tar.gz"
[[ -d "$src" ]] || tar -C "$TP" -xzf "$tgz"
local pf
for pf in "$ROOT"/scripts/patches/ncurses-"$NCURSES_VER"-*.patch; do
[[ -e "$pf" ]] || continue
patch -d "$src" -p1 -R --dry-run -s -f <"$pf" >/dev/null 2>&1 && continue
if ! patch -d "$src" -p1 --dry-run -s -f <"$pf" >/dev/null 2>&1; then
echo "ncurses: $src has another version of $(basename "$pf"); re-extracting"
rm -rf "$src"
tar -C "$TP" -xzf "$tgz"
fi
patch -d "$src" -p1 -s <"$pf"
done
rm -rf "$src/build-mingw"
mkdir -p "$src/build-mingw"
cd "$src/build-mingw"
../configure --host="${HOST:-x86_64-w64-mingw32}" --prefix="$PREFIX" \
--without-ada --without-cxx --without-cxx-binding --without-manpages \
--without-progs --without-tests --without-debug --without-shared \
--enable-widec --enable-sp-funcs --enable-term-driver \
--enable-interop --disable-home-terminfo --disable-db-install \
--with-fallbacks=ms-terminal,xterm-256color --without-pkg-config \
--disable-pc-files --with-build-cc="${BUILD_CC:-cc}" >/dev/null
make -j"$JOBS" libs >/dev/null
make install.libs >/dev/null
echo "ncurses $NCURSES_VER -> $PREFIX"
}
# --- busybox-w32 ---
build_busybox_w32() {
clone_or_update https://github.com/rmyorston/busybox-w32.git "$TP/busybox-w32"
checkout https://github.com/rmyorston/busybox-w32.git "$TP/busybox-w32" "$BUSYBOX_W32_REV"
cd "$TP/busybox-w32"
# configs: try mingw64 defconfig
if [[ -f configs/mingw64_defconfig ]]; then
make mingw64_defconfig
elif [[ -f configs/mingw_defconfig ]]; then
make mingw_defconfig
else
make defconfig
fi
# Cross compile
make -j"$JOBS" CROSS_COMPILE="${HOST}-" \
CONFIG_EXTRA_CFLAGS="-O2" \
busybox.exe 2>&1 || make -j"$JOBS" CROSS_COMPILE="${HOST}-"
make -s mingw64u_defconfig >/dev/null
make -s -j"$JOBS" CROSS_COMPILE="$T" </dev/null
mkdir -p "$TP/busybox"
if [[ -f busybox.exe ]]; then
cp -f busybox.exe "$TP/busybox/busybox.exe"
else
find . -name 'busybox.exe' | head -1 | xargs -I{} cp -f {} "$TP/busybox/busybox.exe"
fi
cat > "$TP/busybox/LICENSE.busybox" << 'EOF'
BusyBox is GPLv2. Source: https://github.com/rmyorston/busybox-w32
Upstream BusyBox: https://github.com/mirror/busybox
cp -f busybox.exe "$TP/busybox/busybox.exe"
cat >"$TP/busybox/LICENSE.busybox" <<EOF
BusyBox is GPLv2. This busybox.exe is busybox-w32 ($BUSYBOX_W32_REV, Unicode build):
https://github.com/rmyorston/busybox-w32
Upstream BusyBox: https://busybox.net/
EOF
ls -la "$TP/busybox/busybox.exe"
}
# --- Unix busybox (optional, for Linux/Termux side-by-side bundle) ---
build_busybox_unix() {
clone_or_update https://github.com/mirror/busybox.git "$TP/busybox-src"
cd "$TP/busybox-src"
make defconfig
# Keep applets reasonable; enable ash + diff
make -j"$JOBS" busybox
mkdir -p "$TP/busybox"
cp -f busybox "$TP/busybox/busybox"
echo "unix busybox -> $TP/busybox/busybox"
}
TARGETS="${1:-all}"
case "$TARGETS" in
curl) build_curl_mingw ;;
pdcurses) build_pdcurses_mingw ;;
busybox-w32) build_busybox_w32 ;;
busybox-unix) build_busybox_unix ;;
all)
build_curl_mingw
build_pdcurses_mingw
build_busybox_w32
;;
*)
echo "usage: $0 [all|curl|pdcurses|busybox-w32|busybox-unix]"
exit 1
;;
case "${1:-all}" in
curl) build_curl ;;
pdcurses) build_pdcurses ;;
ncurses) build_ncurses ;;
busybox-w32) build_busybox_w32 ;;
all)
build_curl
build_ncurses
build_busybox_w32
;;
*)
echo "usage: $0 [all|curl|pdcurses|ncurses|busybox-w32]"
exit 1
;;
esac
echo "DONE"
+106
View File
@@ -0,0 +1,106 @@
# Install or update CST-Agent on Windows from a Gitea release.
#
# irm https://git.whcself.xyz/WHC/CST-agent/raw/branch/main/scripts/install_windows.ps1 | iex
# powershell -ExecutionPolicy Bypass -File install_windows.ps1 [-Version 0.6.0] [-Prefix DIR] [-Zip FILE] [-NoPath]
#
# Installs into %LOCALAPPDATA%\Programs\cst-agent (no admin rights needed),
# adds it to the user PATH and leaves cst-agent-update.cmd beside the exe,
# which reruns this script for that folder. Environment overrides:
# CST_VERSION, CST_PREFIX, CST_GITEA (server URL), CST_REPO (owner/name).
# Needs Windows 10 1903+ / Server 2022+ (UTF-8 process code page).
# Keep this file ASCII: Windows PowerShell 5.1 reads BOM-less scripts in the
# ANSI code page.
param(
[string]$Version = $env:CST_VERSION,
[string]$Prefix = $env:CST_PREFIX,
[string]$Zip = "",
[switch]$NoPath
)
$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Server = if ($env:CST_GITEA) { $env:CST_GITEA.TrimEnd("/") } else { "https://git.whcself.xyz" }
$Repo = if ($env:CST_REPO) { $env:CST_REPO } else { "WHC/CST-agent" }
if (-not $Prefix) { $Prefix = Join-Path $env:LOCALAPPDATA "Programs\cst-agent" }
$Prefix = [IO.Path]::GetFullPath($Prefix)
$build = [Environment]::OSVersion.Version.Build
if ($build -lt 18362) {
throw "CST-Agent needs Windows 10 1903 (build 18362) or newer; this is build $build."
}
$work = Join-Path ([IO.Path]::GetTempPath()) ("cst-agent-install-" + [Guid]::NewGuid().ToString("N"))
New-Item -ItemType Directory -Force $work | Out-Null
try {
if (-not $Zip) {
$api = "$Server/api/v1/repos/$Repo/releases"
$url = if (-not $Version -or $Version -eq "latest") { "$api/latest" } else { "$api/tags/v$($Version.TrimStart('v'))" }
Write-Host "==> $url"
try {
$rel = Invoke-RestMethod -Uri $url -UseBasicParsing
} catch {
throw "no release found at $url ($($_.Exception.Message))"
}
$asset = $rel.assets | Where-Object { $_.name -like "*-windows-x86_64.zip" } | Select-Object -First 1
if (-not $asset) { throw "release $($rel.tag_name) has no *-windows-x86_64.zip" }
$Zip = Join-Path $work $asset.name
Write-Host "==> download $($asset.name) ($($rel.tag_name))"
Invoke-WebRequest -Uri $asset.browser_download_url -OutFile $Zip -UseBasicParsing
$sum = $rel.assets | Where-Object { $_.name -eq "$($asset.name).sha256" } | Select-Object -First 1
if ($sum) {
$sumFile = Join-Path $work $sum.name
Invoke-WebRequest -Uri $sum.browser_download_url -OutFile $sumFile -UseBasicParsing
$want = ((Get-Content $sumFile -Raw).Trim() -split "\s+")[0].ToLower()
$got = (Get-FileHash -Algorithm SHA256 $Zip).Hash.ToLower()
if ($want -ne $got) { throw "sha256 mismatch for $($asset.name): expected $want, got $got" }
Write-Host "==> sha256 ok"
}
}
Expand-Archive -Path $Zip -DestinationPath $work -Force
$src = Join-Path $work "windows-x86_64"
if (-not (Test-Path (Join-Path $src "cst-agent.exe"))) { throw "$Zip has no windows-x86_64\cst-agent.exe" }
New-Item -ItemType Directory -Force $Prefix | Out-Null
# A running exe cannot be overwritten but can be renamed out of the way.
foreach ($name in @("cst-agent.exe", "busybox.exe")) {
$dst = Join-Path $Prefix $name
$old = "$dst.old"
if (Test-Path $old) { Remove-Item -Force $old -ErrorAction SilentlyContinue }
if (Test-Path $dst) {
try { Remove-Item -Force $dst } catch { Rename-Item -Force $dst "$name.old" }
}
}
Copy-Item -Force -Recurse (Join-Path $src "*") $Prefix
$update = Join-Path $Prefix "cst-agent-update.cmd"
if (-not (Test-Path $update)) {
Set-Content -Encoding Ascii -Path $update -Value @(
"@echo off",
"rem Update CST-Agent in this folder from the latest release.",
"powershell -NoProfile -ExecutionPolicy Bypass -File `"%~dp0install_windows.ps1`" -Prefix `"%~dp0.`" %*"
)
}
if (-not (Test-Path (Join-Path $Prefix "install_windows.ps1")) -and $PSCommandPath) {
Copy-Item -Force $PSCommandPath (Join-Path $Prefix "install_windows.ps1")
}
if (-not $NoPath) {
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
$parts = @($userPath -split ";" | Where-Object { $_ })
if (-not ($parts | Where-Object { $_.TrimEnd("\") -ieq $Prefix.TrimEnd("\") })) {
[Environment]::SetEnvironmentVariable("Path", (($parts + $Prefix) -join ";"), "User")
Write-Host "==> added $Prefix to the user PATH (open a new terminal to use it)"
}
if (-not (($env:Path -split ";") | Where-Object { $_.TrimEnd("\") -ieq $Prefix.TrimEnd("\") })) {
$env:Path = "$env:Path;$Prefix"
}
}
$ver = (& (Join-Path $Prefix "cst-agent.exe") --version) 2>&1 | Select-Object -First 1
Write-Host "==> installed $ver in $Prefix"
Write-Host "Run 'cst-agent' inside a project folder; update later with 'cst-agent-update'."
} finally {
Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue
}
+27 -7
View File
@@ -1,18 +1,38 @@
#!/usr/bin/env bash
# Assemble dist/windows-x86_64 from MinGW TUI build + busybox.
# Assemble dist/windows-x86_64/ and dist/cst-agent-VERSION-windows-x86_64.zip
# from the cross build (build-win-tui, else build-win; CST_WIN_BUILD=DIR
# picks another, e.g. build-msys2) and busybox-w32.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
REL="$ROOT/dist/windows-x86_64"
EXE="$ROOT/build-win-tui/cst-agent.exe"
[[ -f "$EXE" ]] || EXE="$ROOT/build-win/cst-agent.exe"
if [[ -n "${CST_WIN_BUILD:-}" ]]; then
EXE="$ROOT/$CST_WIN_BUILD/cst-agent.exe"
else
EXE="$ROOT/build-win-tui/cst-agent.exe"
[[ -f "$EXE" ]] || EXE="$ROOT/build-win/cst-agent.exe"
fi
BB="$ROOT/third_party/busybox/busybox.exe"
DLL="/usr/x86_64-w64-mingw32/bin/libwinpthread-1.dll"
[[ -f "$EXE" ]] || { echo "no cst-agent.exe; build first" >&2; exit 1; }
[[ -f "$BB" ]] || { echo "no busybox.exe; scripts/build_third_party_mingw.sh busybox-w32" >&2; exit 1; }
ver="$(sed -n 's/^#define CST_VERSION_\(MAJOR\|MINOR\|PATCH\) \([0-9]*\)$/\2/p' "$ROOT/include/cst_version.h" | paste -sd.)"
strip="${MINGW_HOST-x86_64-w64-mingw32}"
strip="${strip:+$strip-}strip"
command -v "$strip" >/dev/null || strip=strip # MSYS2: unprefixed
rm -rf "$REL"
mkdir -p "$REL"
cp -f "$EXE" "$REL/cst-agent.exe"
"$strip" "$REL/cst-agent.exe"
cp -f "$BB" "$REL/busybox.exe"
cp -f "$ROOT/third_party/busybox/LICENSE.busybox" "$REL/"
cp -f "$ROOT/docs/README-windows.md" "$REL/"
[[ -f "$DLL" ]] && cp -f "$DLL" "$REL/"
cp -f "$ROOT/docs/README-windows.md" "$REL/README.md"
cp -f "$ROOT/scripts/windows/cst-agent-update.cmd" "$ROOT/scripts/install_windows.ps1" "$REL/"
echo "$ver" >"$REL/VERSION"
zip="$ROOT/dist/cst-agent-$ver-windows-x86_64.zip"
rm -f "$zip"
(cd "$ROOT/dist" && zip -qr "$zip" windows-x86_64)
(cd "$ROOT/dist" && sha256sum "$(basename "$zip")" >"$(basename "$zip").sha256")
ls -la "$REL"
file "$REL/cst-agent.exe"
echo "$zip"
@@ -0,0 +1,350 @@
--- a/ncurses/curses.priv.h
+++ b/ncurses/curses.priv.h
@@ -2294,7 +2294,10 @@
#if defined(_NC_WINDOWS_NATIVE) && !defined(_NC_MSC) && !USE_NAMED_PIPES
/*
* MinGW has wide-character functions, but they do not work correctly.
+ * Declare the originals first so a later <wchar.h> is not macro-expanded.
*/
+#include <stdlib.h>
+#include <wchar.h>
extern int __MINGW_NOTHROW _nc_wctomb(char *, wchar_t);
#define wctomb(s,wc) _nc_wctomb(s,wc)
#define wcrtomb(s,wc,n) _nc_wctomb(s,wc)
--- a/ncurses/tinfo/lib_win32con.c
+++ b/ncurses/tinfo/lib_win32con.c
@@ -653,6 +653,21 @@
return result;
}
+/* Whether handle_mouse() turns this record into an event: wheel, a button
+ * change (press or release), or a drag. */
+static bool
+mouse_wanted(const SCREEN *sp, const MOUSE_EVENT_RECORD *mer)
+{
+ int held = (int) (mer->dwButtonState & BUTTON_MASK);
+
+ if (mer->dwEventFlags & MOUSE_WHEELED)
+ return TRUE;
+ if (held != sp->_drv_mouse_new_buttons)
+ return TRUE;
+ return (mer->dwEventFlags & MOUSE_MOVED) && held
+ && (sp->_mouse_mask & REPORT_MOUSE_POSITION);
+}
+
#define AdjustY() (WINCONSOLE.buffered \
? 0 \
: (int) WINCONSOLE.SBI.srWindow.Top)
@@ -661,36 +676,47 @@
handle_mouse(SCREEN *sp, MOUSE_EVENT_RECORD mer)
{
MEVENT work;
- bool result = FALSE;
+ int old_buttons;
+ int new_buttons;
assert(sp);
- sp->_drv_mouse_old_buttons = sp->_drv_mouse_new_buttons;
- sp->_drv_mouse_new_buttons = mer.dwButtonState & BUTTON_MASK;
+ if (sp->_drv_mouse_tail >= FIFO_SIZE)
+ return FALSE;
- /*
- * We're only interested if the button is pressed or released.
- * FIXME: implement continuous event-tracking.
- */
- if (sp->_drv_mouse_new_buttons != sp->_drv_mouse_old_buttons) {
- memset(&work, 0, sizeof(work));
+ memset(&work, 0, sizeof(work));
+ work.x = mer.dwMousePosition.X;
+ work.y = mer.dwMousePosition.Y - AdjustY();
+
+ /* the wheel reports like xterm: button 4 up, button 5 down */
+ if (mer.dwEventFlags & MOUSE_WHEELED) {
+ work.bstate = ((SHORT) HIWORD(mer.dwButtonState) > 0)
+ ? BUTTON4_PRESSED
+ : BUTTON5_PRESSED;
+ sp->_drv_mouse_fifo[sp->_drv_mouse_tail++] = work;
+ return TRUE;
+ }
- if (sp->_drv_mouse_new_buttons) {
- work.bstate |= decode_mouse(sp, sp->_drv_mouse_new_buttons);
+ old_buttons = sp->_drv_mouse_new_buttons;
+ new_buttons = (int) (mer.dwButtonState & BUTTON_MASK);
+ sp->_drv_mouse_old_buttons = old_buttons;
+ sp->_drv_mouse_new_buttons = new_buttons;
+
+ if (new_buttons != old_buttons) {
+ if (new_buttons & ~old_buttons) {
+ work.bstate = decode_mouse(sp, new_buttons & ~old_buttons);
} else {
/* cf: BUTTON_PRESSED, BUTTON_RELEASED */
- work.bstate |= (decode_mouse(sp, sp->_drv_mouse_old_buttons)
- >> 1);
- result = TRUE;
+ work.bstate = decode_mouse(sp, old_buttons & ~new_buttons) >> 1;
}
-
- work.x = mer.dwMousePosition.X;
- work.y = mer.dwMousePosition.Y - AdjustY();
-
- sp->_drv_mouse_fifo[sp->_drv_mouse_tail] = work;
- sp->_drv_mouse_tail += 1;
+ } else if ((mer.dwEventFlags & MOUSE_MOVED) && new_buttons
+ && (sp->_mouse_mask & REPORT_MOUSE_POSITION)) {
+ work.bstate = REPORT_MOUSE_POSITION; /* drag */
+ } else {
+ return FALSE;
}
- return result;
+ sp->_drv_mouse_fifo[sp->_drv_mouse_tail++] = work;
+ return TRUE;
}
static int
@@ -813,6 +839,13 @@
returnCode(found);
}
+#if USE_WIDEC_SUPPORT
+/* UTF-8 bytes of the last non-ASCII key event not yet read */
+static int utf8_pend[4];
+static int utf8_len, utf8_pos;
+static unsigned utf8_high;
+#endif
+
NCURSES_EXPORT(int)
_nc_console_twait(
const SCREEN *sp,
@@ -845,6 +878,14 @@
TR(TRACE_IEVENT, ("start twait: hdl=%p, %d milliseconds, mode: %d",
hdl, milliseconds, mode));
+#if USE_WIDEC_SUPPORT
+ if ((mode & TW_INPUT) && utf8_pos < utf8_len) {
+ if (timeleft)
+ *timeleft = milliseconds;
+ return TW_INPUT;
+ }
+#endif
+
if (milliseconds < 0)
milliseconds = NC_INFINITY;
@@ -940,9 +981,7 @@
continue;
case MOUSE_EVENT:
T(("twait:event MOUSE_EVENT"));
- if (decode_mouse(sp,
- (inp_rec.Event.MouseEvent.dwButtonState
- & BUTTON_MASK)) == 0) {
+ if (!mouse_wanted(sp, &inp_rec.Event.MouseEvent)) {
CONSUME();
} else if (mode & TW_MOUSE) {
code = TW_MOUSE;
@@ -1024,6 +1063,16 @@
T((T_CALLED("lib_win32con::_nc_console_read(%p)"), sp));
+#if USE_WIDEC_SUPPORT
+ /* wget_wch() decodes the input as a byte stream in the locale's
+ * multibyte encoding (UTF-8), so non-ASCII UTF-16 key events are
+ * handed over one UTF-8 byte per call. */
+ if (utf8_pos < utf8_len) {
+ *buf = utf8_pend[utf8_pos++];
+ returnCode(1);
+ }
+#endif
+
while ((b = read_keycode(hdl, &inp_rec, 1, &nRead))) {
if (b && nRead > 0) {
if (rc < 0)
@@ -1034,6 +1083,36 @@
continue;
*buf = (int) inp_rec.Event.KeyEventChar;
vk = inp_rec.Event.KeyEvent.wVirtualKeyCode;
+#if USE_WIDEC_SUPPORT
+ if (*buf >= 0x80) {
+ unsigned cp = (unsigned) *buf;
+ if (cp >= 0xD800 && cp < 0xDC00) {
+ utf8_high = cp;
+ continue;
+ }
+ if (cp >= 0xDC00 && cp < 0xE000) {
+ if (!utf8_high)
+ continue;
+ cp = 0x10000 + ((utf8_high - 0xD800) << 10) + (cp - 0xDC00);
+ }
+ utf8_high = 0;
+ utf8_len = 0;
+ if (cp < 0x800) {
+ utf8_pend[utf8_len++] = (int) (0xC0 | (cp >> 6));
+ } else if (cp < 0x10000) {
+ utf8_pend[utf8_len++] = (int) (0xE0 | (cp >> 12));
+ utf8_pend[utf8_len++] = (int) (0x80 | ((cp >> 6) & 0x3F));
+ } else {
+ utf8_pend[utf8_len++] = (int) (0xF0 | (cp >> 18));
+ utf8_pend[utf8_len++] = (int) (0x80 | ((cp >> 12) & 0x3F));
+ utf8_pend[utf8_len++] = (int) (0x80 | ((cp >> 6) & 0x3F));
+ }
+ utf8_pend[utf8_len++] = (int) (0x80 | (cp & 0x3F));
+ *buf = utf8_pend[0];
+ utf8_pos = 1;
+ break;
+ }
+#endif
/*
* There are 24 virtual function-keys, and typically
* 12 function-keys on a keyboard. Use the shift-modifier
--- a/ncurses/widechar/widechars.c
+++ b/ncurses/widechar/widechars.c
@@ -97,20 +97,10 @@
wchar_t temp;
if (s != NULL && n != 0) {
+ /* _nc_mbtowc() returns the bytes used, not a character count */
count = _nc_mbtowc(&temp, s, n);
- if (count == 1) {
- int check = WideCharToMultiByte(CP_UTF8,
- 0,
- &temp,
- 1,
- NULL,
- 0, /* compute length only */
- NULL,
- NULL);
- TR(TRACE_BITS, ("\tcheck ->%d\n", check));
- if (check > 0 && (size_t) check <= n) {
- result = check;
- }
+ if (count > 0 && (size_t) count <= n) {
+ result = count;
}
} else {
result = 0;
--- a/ncurses/win32con/win32_driver.c
+++ b/ncurses/win32con/win32_driver.c
@@ -87,8 +87,13 @@
if (ch & A_BOLD)
res |= FOREGROUND_INTENSITY;
- if (ch & A_DIM)
- res |= BACKGROUND_INTENSITY;
+ /* dim lowers the foreground: bright -> normal, light gray -> dark gray */
+ if ((ch & A_DIM) && !(ch & A_BOLD)) {
+ if (res & FOREGROUND_INTENSITY)
+ res &= ~FOREGROUND_INTENSITY;
+ else if ((res & 7) == 7)
+ res = (res & ~7) | FOREGROUND_INTENSITY;
+ }
return res;
}
@@ -159,7 +164,6 @@
int y, int x, cchar_t *str, int limit)
{
int actual = 0;
- MakeArray(ci, CHAR_INFO, limit);
COORD loc, siz;
SMALL_RECT rec;
int i;
@@ -169,39 +173,71 @@
AssertTCB();
SetSP();
- for (i = actual = 0; i < limit; i++) {
- ch = str[i];
- if (isWidecExt(ch))
- continue;
- ci[actual].CharInfoChar = CharOf(ch);
- ci[actual].Attributes = MapAttr(WINCONSOLE.SBI.wAttributes,
- AttrOf(ch));
- if (AttrOf(ch) & A_ALTCHARSET) {
- if (_nc_wacs) {
- int which = CharOf(ch);
- if (which > 0
- && which < ACS_LEN
- && CharOf(_nc_wacs[which]) != 0) {
- ci[actual].CharInfoChar = CharOf(_nc_wacs[which]);
+ /*
+ * The console stores a double-width character as two cells flagged
+ * leading/trailing byte. Never start or end a write inside one, and
+ * emit both halves so the columns after it stay put.
+ */
+ if (limit > 0 && x > 0 && isWidecExt(str[0])) {
+ --str;
+ --x;
+ ++limit;
+ }
+ if (limit > 0 && x + limit < screen_columns(sp) && isWidecExt(str[limit]))
+ ++limit;
+
+ {
+ MakeArray(ci, CHAR_INFO, limit);
+
+ for (i = actual = 0; i < limit; i++) {
+ ch = str[i];
+ if (isWidecExt(ch)) {
+ if (actual > 0
+ && (ci[actual - 1].Attributes & COMMON_LVB_LEADING_BYTE)) {
+ ci[actual] = ci[actual - 1];
+ ci[actual].Attributes = (WORD)
+ ((ci[actual].Attributes & ~COMMON_LVB_LEADING_BYTE)
+ | COMMON_LVB_TRAILING_BYTE);
} else {
ci[actual].CharInfoChar = ' ';
+ ci[actual].Attributes = MapAttr(WINCONSOLE.SBI.wAttributes,
+ AttrOf(ch));
}
+ ++actual;
+ continue;
}
+ ci[actual].CharInfoChar = CharOf(ch);
+ ci[actual].Attributes = MapAttr(WINCONSOLE.SBI.wAttributes,
+ AttrOf(ch));
+ if (AttrOf(ch) & A_ALTCHARSET) {
+ if (_nc_wacs) {
+ int which = CharOf(ch);
+ if (which > 0
+ && which < ACS_LEN
+ && CharOf(_nc_wacs[which]) != 0) {
+ ci[actual].CharInfoChar = CharOf(_nc_wacs[which]);
+ } else {
+ ci[actual].CharInfoChar = ' ';
+ }
+ }
+ }
+ if (i + 1 < limit && isWidecExt(str[i + 1]))
+ ci[actual].Attributes |= COMMON_LVB_LEADING_BYTE;
+ ++actual;
}
- ++actual;
- }
- loc.X = (SHORT) 0;
- loc.Y = (SHORT) 0;
- siz.X = (SHORT) actual;
- siz.Y = 1;
-
- rec.Left = (SHORT) x;
- rec.Top = (SHORT) (y + AdjustY());
- rec.Right = (SHORT) (x + limit - 1);
- rec.Bottom = rec.Top;
+ loc.X = (SHORT) 0;
+ loc.Y = (SHORT) 0;
+ siz.X = (SHORT) actual;
+ siz.Y = 1;
+
+ rec.Left = (SHORT) x;
+ rec.Top = (SHORT) (y + AdjustY());
+ rec.Right = (SHORT) (x + actual - 1);
+ rec.Bottom = rec.Top;
- return write_screen(WINCONSOLE.hdl, ci, siz, loc, &rec);
+ return write_screen(WINCONSOLE.hdl, ci, siz, loc, &rec);
+ }
}
#define con_write(tcb, y, x, str, n) con_write16(tcb, y, x, str, n)
#else
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
# Publish dist/cst-agent-VERSION-windows-x86_64.zip (+ .sha256) to the Gitea
# release vVERSION, creating the release (and its tag at HEAD) when missing.
# GITEA_TOKEN=... scripts/release_windows.sh [--build]
# --build runs scripts/bootstrap_windows.sh first. The token is only read from
# the environment and handed to curl on stdin: it never appears in argv, on
# disk or in the output. Assets of the same name are replaced.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
SERVER="${CST_GITEA:-https://git.whcself.xyz}"
REPO="${CST_REPO:-WHC/CST-agent}"
API="$SERVER/api/v1/repos/$REPO"
[[ -n "${GITEA_TOKEN:-}" ]] || {
echo "set GITEA_TOKEN (a Gitea token with write:repository)" >&2
exit 1
}
command -v python3 >/dev/null || { echo "missing python3" >&2; exit 1; }
cd "$ROOT"
[[ "${1:-}" == --build ]] && scripts/bootstrap_windows.sh "$ROOT"
ver="$(sed -n 's/^#define CST_VERSION_\(MAJOR\|MINOR\|PATCH\) \([0-9]*\)$/\2/p' include/cst_version.h | paste -sd.)"
tag="v$ver"
zip="dist/cst-agent-$ver-windows-x86_64.zip"
for f in "$zip" "$zip.sha256"; do
[[ -f "$f" ]] || { echo "missing $f (scripts/package_windows.sh, or --build)" >&2; exit 1; }
done
api() { # METHOD PATH [curl args...]
local m="$1" p="$2"
shift 2
printf 'Authorization: token %s\n' "$GITEA_TOKEN" |
curl -fsS -X "$m" -H @- "$API$p" "$@"
}
json() { # CODE [ARGS...]: d = the JSON on stdin, ARGS in sys.argv[1:]
local code="$1"
shift
python3 -c "import json,sys; d=json.load(sys.stdin); $code" "$@"
}
if rel="$(api GET "/releases/tags/$tag" 2>/dev/null)"; then
echo "==> release $tag exists"
else
head="$(git rev-parse HEAD)"
if ! git branch -r --contains "$head" 2>/dev/null | grep -q .; then
echo "HEAD $head is not on any remote branch; push it first" >&2
exit 1
fi
echo "==> creating release $tag at $head"
body="$(python3 -c 'import json,sys; print(json.dumps({"tag_name": sys.argv[1], "target_commitish": sys.argv[2], "name": "CST-Agent " + sys.argv[1], "body": "Windows x86_64: unzip, or install with scripts/install_windows.ps1"}))' "$tag" "$head")"
rel="$(api POST /releases -H 'Content-Type: application/json' -d "$body")"
fi
id="$(json 'print(d["id"])' <<<"$rel")"
for f in "$zip" "$zip.sha256"; do
name="$(basename "$f")"
old="$(json "print(' '.join(str(a['id']) for a in d.get('assets') or [] if a['name'] == sys.argv[1]))" "$name" <<<"$rel")"
for aid in $old; do
echo "==> replacing $name"
api DELETE "/releases/$id/assets/$aid" >/dev/null
done
echo "==> upload $name"
api POST "/releases/$id/assets?name=$name" -F "attachment=@$f" >/dev/null
done
echo "$SERVER/$REPO/releases/tag/$tag"
-27
View File
@@ -1,27 +0,0 @@
@echo off
REM Run ON Windows after copying dist/windows-x86_64 (or a full git checkout + MSYS2 build).
REM This script only documents env + launch; prefer bootstrap_windows.sh on Linux for cross-build.
setlocal
if "%OPENAI_API_KEY%"=="" if "%CST_API_KEY%"=="" (
echo Set OPENAI_API_KEY or CST_API_KEY first. See docs\env_openai.md
echo Example:
echo set OPENAI_API_KEY=sk-...
echo set OPENAI_BASE_URL=https://api.openai.com/v1
echo set OPENAI_MODEL=gpt-4.1-mini
exit /b 1
)
if not exist cst-agent.exe (
echo cst-agent.exe not found in %CD%
echo Copy dist\windows-x86_64\* here, or build with MSYS2/MinGW.
exit /b 1
)
if not exist busybox.exe (
echo WARNING: busybox.exe missing — run_shell may fail. Place busybox.exe beside cst-agent.exe
)
echo Launching CST-Agent...
cst-agent.exe --workspace .
endlocal
+65
View File
@@ -0,0 +1,65 @@
#!/usr/bin/env bash
# Run the cross-built Windows tests inside the test VMs (scripts/winvm/vm.sh).
#
# scripts/win_test.sh [-b BUILD_DIR] [-v "en zh"] [-u "Administrator tester 测试"] [-f FILTER]
#
# BUILD_DIR (default build-win) must contain test_*.exe from the MinGW build;
# busybox.exe is taken from third_party/busybox/. VMs that are not running are
# started and stopped again afterwards. Exit status is the number of failed
# variant/user runs.
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VM="$ROOT/scripts/winvm/vm.sh"
BUILD="$ROOT/build-win"
VARIANTS="en zh"
USERS_LIST="Administrator tester 测试"
FILTER="*"
while getopts "b:v:u:f:" o; do
case "$o" in
b) BUILD="$(cd "$OPTARG" && pwd)" ;;
v) VARIANTS="$OPTARG" ;;
u) USERS_LIST="$OPTARG" ;;
f) FILTER="$OPTARG" ;;
*) sed -n '2,8p' "$0"; exit 2 ;;
esac
done
shopt -s nullglob
exes=("$BUILD"/test_*.exe)
[[ ${#exes[@]} -gt 0 ]] || { echo "no test_*.exe in $BUILD" >&2; exit 1; }
stage="$(mktemp -d)"
trap 'rm -rf "$stage"' EXIT
mkdir -p "$stage/bundle/bin" "$stage/bundle/data/tests"
cp "${exes[@]}" "$stage/bundle/bin/"
for f in "$BUILD"/*.dll "$ROOT/third_party/busybox/busybox.exe"; do
[[ -f "$f" ]] && cp "$f" "$stage/bundle/bin/"
done
cp -r "$ROOT/tests/fixtures" "$stage/bundle/data/tests/"
cp "$ROOT/scripts/winvm/run_tests.ps1" "$stage/bundle/"
tar -C "$stage" -cf "$stage/bundle.tar" bundle
total_fail=0
summary=()
for v in $VARIANTS; do
started=0
if [[ "$("$VM" status "$v")" != running ]]; then
"$VM" start "$v"
started=1
fi
"$VM" ssh "$v" 'Remove-Item -Recurse -Force C:\cst-test\bundle -ErrorAction SilentlyContinue; New-Item -ItemType Directory -Force C:\cst-test | Out-Null' >/dev/null
"$VM" put "$v" "$stage/bundle.tar" "C:/cst-test/bundle.tar"
"$VM" ssh "$v" 'tar -xf C:\cst-test\bundle.tar -C C:\cst-test; Remove-Item C:\cst-test\bundle.tar' >/dev/null
for u in $USERS_LIST; do
echo "===== $v / $u"
rc=0
"$VM" ps "$v" "$u" "$stage/bundle/run_tests.ps1" -Bundle 'C:\cst-test\bundle' -Filter "'$FILTER'" || rc=$?
summary+=("$v/$u: $([[ $rc == 0 ]] && echo ok || echo FAIL)")
[[ $rc == 0 ]] || total_fail=$((total_fail + 1))
done
[[ $started == 1 ]] && "$VM" stop "$v"
done
echo
printf '%s\n' "${summary[@]}"
exit "$total_fail"
+4
View File
@@ -0,0 +1,4 @@
@echo off
rem Update CST-Agent in this folder from the latest release.
rem cst-agent-update [-Version 0.6.0]
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0install_windows.ps1" -Prefix "%~dp0." %*
+98
View File
@@ -0,0 +1,98 @@
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
<settings pass="windowsPE">
<component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<SetupUILanguage>
<UILanguage>en-US</UILanguage>
</SetupUILanguage>
<InputLocale>en-US</InputLocale>
<SystemLocale>en-US</SystemLocale>
<UILanguage>en-US</UILanguage>
<UserLocale>en-US</UserLocale>
</component>
<component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<DiskConfiguration>
<Disk wcm:action="add">
<DiskID>0</DiskID>
<WillWipeDisk>true</WillWipeDisk>
<CreatePartitions>
<CreatePartition wcm:action="add">
<Order>1</Order>
<Type>Primary</Type>
<Extend>true</Extend>
</CreatePartition>
</CreatePartitions>
<ModifyPartitions>
<ModifyPartition wcm:action="add">
<Order>1</Order>
<PartitionID>1</PartitionID>
<Active>true</Active>
<Format>NTFS</Format>
<Label>Windows</Label>
<Letter>C</Letter>
</ModifyPartition>
</ModifyPartitions>
</Disk>
</DiskConfiguration>
<ImageInstall>
<OSImage>
<InstallFrom>
<MetaData wcm:action="add">
<Key>/IMAGE/NAME</Key>
<Value>@IMAGE_NAME@</Value>
</MetaData>
</InstallFrom>
<InstallTo>
<DiskID>0</DiskID>
<PartitionID>1</PartitionID>
</InstallTo>
</OSImage>
</ImageInstall>
<UserData>
<AcceptEula>true</AcceptEula>
<FullName>CST</FullName>
<Organization>CST</Organization>
</UserData>
</component>
</settings>
<settings pass="specialize">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<ComputerName>cst-win</ComputerName>
<TimeZone>China Standard Time</TimeZone>
</component>
</settings>
<settings pass="oobeSystem">
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
<OOBE>
<HideEULAPage>true</HideEULAPage>
<HideOnlineAccountScreens>true</HideOnlineAccountScreens>
<HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
<ProtectYourPC>3</ProtectYourPC>
<NetworkLocation>Work</NetworkLocation>
</OOBE>
<UserAccounts>
<AdministratorPassword>
<Value>@ADMIN_PASSWORD@</Value>
<PlainText>true</PlainText>
</AdministratorPassword>
</UserAccounts>
<AutoLogon>
<Enabled>true</Enabled>
<Username>Administrator</Username>
<Password>
<Value>@ADMIN_PASSWORD@</Value>
<PlainText>true</PlainText>
</Password>
<LogonCount>1</LogonCount>
</AutoLogon>
<FirstLogonCommands>
<SynchronousCommand wcm:action="add">
<Order>1</Order>
<CommandLine>powershell -NoProfile -ExecutionPolicy Bypass -Command "foreach ($d in Get-PSDrive -PSProvider FileSystem) { $p = Join-Path $d.Root 'setup.ps1'; if (Test-Path $p) { &amp; $p; break } }"</CommandLine>
<Description>Enable OpenSSH</Description>
<RequiresUserInput>false</RequiresUserInput>
</SynchronousCommand>
</FirstLogonCommands>
</component>
</settings>
</unattend>
+28
View File
@@ -0,0 +1,28 @@
# Idempotent VM setup after install: test users, sshd access, console defaults.
# Users come from C:\Windows\Temp\cst-users.txt ("name<TAB>password", UTF-8), deleted afterwards.
$ErrorActionPreference = 'Stop'
$list = 'C:\Windows\Temp\cst-users.txt'
if (Test-Path $list) {
foreach ($line in Get-Content -Path $list -Encoding UTF8) {
$name, $pw = $line -split "`t", 2
if (-not $name) { continue }
$sec = ConvertTo-SecureString $pw -AsPlainText -Force
if (Get-LocalUser -Name $name -ErrorAction SilentlyContinue) {
Set-LocalUser -Name $name -Password $sec
} else {
New-LocalUser -Name $name -Password $sec -PasswordNeverExpires -AccountNeverExpires | Out-Null
}
foreach ($g in 'Users', 'OpenSSH Users') {
Add-LocalGroupMember -Group $g -Member $name -ErrorAction SilentlyContinue
}
"user ok: $name"
}
Remove-Item -Force $list
}
# the built-in rule only covers the Private profile; QEMU user networking is Public
Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -Profile Any -Enabled True
Set-SConfig -AutoLaunch $false
New-Item -ItemType Directory -Force C:\cst-test | Out-Null
"provision ok"
+51
View File
@@ -0,0 +1,51 @@
# Run cross-built test_*.exe inside the VM as the current user.
# run_tests.ps1 BUNDLE [FILTER]
# BUNDLE holds bin\ (exes, busybox.exe) and data\ (repo-relative fixtures).
# Each run copies data\ into a per-user work dir and uses it as the cwd.
param([Parameter(Mandatory = $true)][string]$Bundle, [string]$Filter = '*')
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$OutputEncoding = [Console]::OutputEncoding
$work = Join-Path $env:TEMP ('cst-test-' + [guid]::NewGuid().ToString('N').Substring(0, 8))
New-Item -ItemType Directory -Force $work | Out-Null
Copy-Item -Recurse -Force (Join-Path $Bundle 'data\*') $work
$env:PATH = (Join-Path $Bundle 'bin') + ';' + $env:PATH
$acp = [Text.Encoding]::Default.CodePage
"== user=$env:USERNAME acp=$acp work=$work"
$fail = 0
$pass = 0
foreach ($exe in Get-ChildItem (Join-Path $Bundle 'bin') -Filter "test_$Filter.exe" | Sort-Object Name) {
$name = $exe.BaseName
$out = Join-Path $work "$name.out"
$err = Join-Path $work "$name.err"
$sw = [Diagnostics.Stopwatch]::StartNew()
$p = Start-Process -FilePath $exe.FullName -WorkingDirectory $work -NoNewWindow -PassThru `
-RedirectStandardOutput $out -RedirectStandardError $err
$null = $p.Handle
if (-not $p.WaitForExit(300000)) {
& taskkill.exe /T /F /PID $p.Id | Out-Null
$code = 'timeout'
} else {
$p.WaitForExit()
$code = $p.ExitCode
}
$secs = [math]::Round($sw.Elapsed.TotalSeconds, 1)
if ($code -eq 0) {
$pass++
"PASS $name (${secs}s)"
} else {
$fail++
"FAIL $name (exit $code, ${secs}s)"
foreach ($f in $out, $err) {
if (Test-Path $f) {
Get-Content -Path $f -Encoding UTF8 -Tail 25 | ForEach-Object { " $_" }
}
}
}
}
"== $pass passed, $fail failed"
Set-Location $env:TEMP
Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue
exit $fail
+28
View File
@@ -0,0 +1,28 @@
Start-Transcript -Path C:\setup.log -Append
$ErrorActionPreference = 'Continue'
if (-not (Get-Service sshd -ErrorAction SilentlyContinue)) {
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
}
Set-Service -Name sshd -StartupType Automatic
Start-Service sshd
$keys = 'C:\ProgramData\ssh\administrators_authorized_keys'
Get-Content (Join-Path $PSScriptRoot 'vm_key.pub') | Set-Content -Path $keys -Encoding ascii
icacls $keys /inheritance:r /grant 'Administrators:F' /grant 'SYSTEM:F'
New-ItemProperty -Path HKLM:\SOFTWARE\OpenSSH -Name DefaultShell -PropertyType String -Force `
-Value 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
if (Get-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -ErrorAction SilentlyContinue) {
# the built-in rule only covers the Private profile; QEMU user networking is Public
Set-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -Profile Any -Enabled True
} else {
New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' `
-Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 -Profile Any
}
powercfg /change monitor-timeout-ac 0
powercfg /change standby-timeout-ac 0
New-Item -Path C:\setup.done -ItemType File -Force
Stop-Transcript
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env python3
"""Type text into the VM console via QMP.
type.py QMP_SOCKET TEXT (\\n = Enter)
type.py QMP_SOCKET @FILE the file's first line, then Enter (secrets stay
off the command line)
type.py QMP_SOCKET --cad Ctrl+Alt+Del
"""
import json
import os
import socket
import sys
import time
SHIFTED = {
'!': '1', '@': '2', '#': '3', '$': '4', '%': '5', '^': '6', '&': '7',
'*': '8', '(': '9', ')': '0', '_': 'minus', '+': 'equal', '{': 'bracket_left',
'}': 'bracket_right', '|': 'backslash', ':': 'semicolon', '"': 'apostrophe',
'<': 'comma', '>': 'dot', '?': 'slash', '~': 'grave_accent',
}
PLAIN = {
' ': 'spc', '\n': 'ret', '\t': 'tab', '-': 'minus', '=': 'equal',
'[': 'bracket_left', ']': 'bracket_right', '\\': 'backslash', ';': 'semicolon',
"'": 'apostrophe', ',': 'comma', '.': 'dot', '/': 'slash', '`': 'grave_accent',
}
def keys_for(ch):
if ch.isascii() and ch.isalpha():
return (['shift'] if ch.isupper() else []) + [ch.lower()]
if ch.isdigit():
return [ch]
if ch in PLAIN:
return [PLAIN[ch]]
if ch in SHIFTED:
return ['shift', SHIFTED[ch]]
raise SystemExit(f'unsupported char {ch!r}')
def main():
arg = sys.argv[2]
if arg == '--cad':
combos = [['ctrl', 'alt', 'delete']]
else:
if arg.startswith('@'):
with open(arg[1:], encoding='utf-8') as fp:
text = fp.readline().rstrip('\r\n') + '\n'
else:
text = arg.encode().decode('unicode_escape')
combos = [keys_for(ch) for ch in text]
s = socket.socket(socket.AF_UNIX)
s.connect(sys.argv[1])
f = s.makefile('rw')
f.readline()
f.write(json.dumps({'execute': 'qmp_capabilities'}) + '\n')
f.flush()
f.readline()
for combo in combos:
keys = [{'type': 'qcode', 'data': k} for k in combo]
f.write(json.dumps({'execute': 'send-key', 'arguments': {'keys': keys}}) + '\n')
f.flush()
f.readline()
time.sleep(0.03)
main()
+288
View File
@@ -0,0 +1,288 @@
#!/usr/bin/env bash
# Headless Windows Server 2025 Core test VMs (QEMU/KVM).
#
# vm.sh create download the evaluation ISO, install base.qcow2
# vm.sh variants en.qcow2 / zh.qcow2 overlays on top of base.qcow2
# (zh: zh-CN system locale, ANSI code page 936)
# vm.sh start|stop|status|wait VARIANT
# vm.sh ssh VARIANT [USER] [command...] USER: Administrator (default), tester, 测试
# vm.sh put VARIANT SRC... DEST scp as Administrator
# vm.sh ps VARIANT [USER] FILE.ps1 [args...] run a script (uploaded with a UTF-8 BOM)
# vm.sh shot VARIANT [out.png] console screenshot
# vm.sh type VARIANT TEXT type into the console (\n = Enter)
# vm.sh login VARIANT unlock the console as Administrator
#
# State (ISO, disks, keys, passwords) lives in $CST_WINVM_DIR, default ~/winvm.
# Keys and passwords are created there with mode 0600 and never printed.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
D="${CST_WINVM_DIR:-$HOME/winvm}"
ISO_URL="https://aka.ms/WinServ2025iso-enus"
IMAGE_NAME="Windows Server 2025 SERVERSTANDARDCORE"
USERS=(tester 测试)
if ! command -v qemu-system-x86_64 >/dev/null || ! command -v sshpass >/dev/null ||
! command -v socat >/dev/null || ! command -v xorriso >/dev/null; then
if command -v nix-shell >/dev/null && [[ -z "${CST_WINVM_NIX:-}" ]]; then
export CST_WINVM_NIX=1
exec nix-shell -p qemu sshpass socat xorriso imagemagick python3 \
--run "$(printf '%q ' "$0" "$@")"
fi
echo "need qemu-system-x86_64, sshpass, socat, xorriso" >&2
exit 1
fi
die() { echo "vm.sh: $*" >&2; exit 1; }
port_of() {
case "$1" in
base) echo 2221 ;;
en) echo 2222 ;;
zh) echo 2223 ;;
*) die "unknown variant '$1' (base, en, zh)" ;;
esac
}
pw_file() {
case "$1" in
Administrator) echo "$D/admin-password" ;;
tester) echo "$D/tester-password" ;;
测试) echo "$D/ceshi-password" ;;
*) die "unknown user '$1'" ;;
esac
}
new_password() { # prefix -> file, mixed classes for Windows complexity rules
local f="$2"
[[ -s "$f" ]] && return 0
(umask 077; printf '%s%s9a' "$1" "$(head -c 256 /dev/urandom | tr -dc 'A-Za-z0-9' | head -c 16)" >"$f")
}
running() {
local pid
pid="$(cat "$D/$1.pid" 2>/dev/null)" || return 1
[[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null
}
ssh_opts() {
echo -p "$(port_of "$1")" -o UserKnownHostsFile="$D/known_hosts" \
-o StrictHostKeyChecking=accept-new -o LogLevel=ERROR -o ConnectTimeout=10
}
vm_ssh() { # variant user command...
local v="$1" u="$2"
shift 2
# shellcheck disable=SC2046
if [[ "$u" == Administrator ]]; then
ssh -i "$D/vm_key" -o BatchMode=yes $(ssh_opts "$v") "Administrator@127.0.0.1" "$@"
else
SSHPASS="$(cat "$(pw_file "$u")")" sshpass -e ssh -o PubkeyAuthentication=no \
-o PreferredAuthentications=password $(ssh_opts "$v") "$u@127.0.0.1" "$@"
fi
}
vm_put() { # variant src... dest
local v="$1"
shift
local dest="${!#}"
local srcs=("${@:1:$#-1}")
# shellcheck disable=SC2046
scp -q -r -i "$D/vm_key" -o BatchMode=yes $(ssh_opts "$v" | sed 's/^-p/-P/') \
"${srcs[@]}" "Administrator@127.0.0.1:$dest"
}
qemu_start() { # variant disk [extra args...]
local v="$1" disk="$2"
shift 2
running "$v" && return 0
[[ -f "$disk" ]] || die "missing $disk"
qemu-system-x86_64 \
-name "cst-win-$v" -machine q35,accel=kvm \
-cpu host,hv_relaxed,hv_spinlocks=0x1fff,hv_vapic,hv_time \
-smp 4 -m 6G -rtc base=localtime \
-device ahci,id=ahci \
-drive file="$disk",if=none,id=d0,cache=writeback,discard=unmap \
-device ide-hd,drive=d0,bus=ahci.0 \
-netdev user,id=n0,hostfwd=tcp:127.0.0.1:"$(port_of "$v")"-:22 \
-device e1000e,netdev=n0 \
-device qemu-xhci,id=xhci -device usb-tablet,bus=xhci.0 \
-display none -qmp unix:"$D/$v.qmp",server,nowait \
-pidfile "$D/$v.pid" -daemonize "$@"
}
disk_of() {
case "$1" in
base) echo "$D/base.qcow2" ;;
*) echo "$D/$1.qcow2" ;;
esac
}
vm_wait() { # variant [timeout_s]
local v="$1" t="${2:-900}" i
for ((i = 0; i < t; i += 5)); do
if vm_ssh "$v" Administrator 'Test-Path C:\setup.done' 2>/dev/null | grep -q True; then
return 0
fi
running "$v" || die "$v is not running"
sleep 5
done
die "$v: no SSH after ${t}s"
}
vm_stop() {
local v="$1" i
running "$v" || return 0
vm_ssh "$v" Administrator 'Stop-Computer -Force' >/dev/null 2>&1 || true
for ((i = 0; i < 120; i++)); do
running "$v" || { rm -f "$D/$v.pid" "$D/$v.qmp"; return 0; }
sleep 1
done
printf '%s\n' '{"execute":"qmp_capabilities"}' '{"execute":"quit"}' |
socat - UNIX-CONNECT:"$D/$v.qmp" >/dev/null || true
rm -f "$D/$v.pid" "$D/$v.qmp"
}
with_bom() { # file -> temp copy with a UTF-8 BOM (Windows PowerShell 5.1 reads ANSI otherwise)
local out
out="$(mktemp --suffix=.ps1)"
printf '\xef\xbb\xbf' >"$out"
sed '1s/^\xef\xbb\xbf//' "$1" >>"$out"
echo "$out"
}
vm_ps() { # variant user file args...
local v="$1" u="$2" f="$3"
shift 3
local tmp name
tmp="$(with_bom "$f")"
name="cst-$(basename "$f" .ps1)-$$.ps1"
vm_put "$v" "$tmp" "C:/Windows/Temp/$name"
rm -f "$tmp"
vm_ssh "$v" Administrator "icacls C:\\Windows\\Temp\\$name /grant 'Users:RX' | Out-Null" >/dev/null
local rc=0
vm_ssh "$v" "$u" "powershell -NoProfile -ExecutionPolicy Bypass -File C:\\Windows\\Temp\\$name $*" || rc=$?
vm_ssh "$v" Administrator "Remove-Item -Force C:\\Windows\\Temp\\$name" >/dev/null 2>&1 || true
return $rc
}
provision() { # variant: users, sshd, console; idempotent
local v="$1" u tmp
tmp="$(mktemp)"
chmod 600 "$tmp"
for u in "${USERS[@]}"; do
new_password "Tst!" "$(pw_file "$u")"
printf '%s\t%s\n' "$u" "$(cat "$(pw_file "$u")")" >>"$tmp"
done
vm_put "$v" "$tmp" "C:/Windows/Temp/cst-users.txt"
rm -f "$tmp"
vm_ps "$v" Administrator "$HERE/provision.ps1"
}
cmd_create() {
mkdir -p "$D"
chmod 700 "$D"
[[ -f "$D/base.qcow2" ]] && die "$D/base.qcow2 exists"
if [[ ! -s "$D/server2025.iso" ]]; then
echo "==> downloading the Windows Server 2025 evaluation ISO (~8 GB)"
curl -fL -C - -o "$D/server2025.iso" "$ISO_URL"
fi
[[ -f "$D/vm_key" ]] || ssh-keygen -q -t ed25519 -N "" -C cst-winvm -f "$D/vm_key"
new_password "Cst!" "$D/admin-password"
local u
u="$(mktemp -d)"
chmod 700 "$u"
cp "$HERE/setup.ps1" "$D/vm_key.pub" "$u/"
(umask 077
sed -e "s|@IMAGE_NAME@|$IMAGE_NAME|" -e "s|@ADMIN_PASSWORD@|$(cat "$D/admin-password")|g" \
"$HERE/autounattend.xml.in" >"$u/autounattend.xml"
xorriso -as mkisofs -quiet -J -r -V UNATTEND -o "$D/unattend.iso" "$u/" 2>/dev/null)
rm -rf "$u"
qemu-img create -q -f qcow2 "$D/base.qcow2" 60G
echo "==> unattended install (20-30 minutes)"
qemu_start base "$D/base.qcow2" \
-drive file="$D/server2025.iso",media=cdrom,if=none,id=cd0,readonly=on \
-device ide-cd,drive=cd0,bus=ahci.1 \
-drive file="$D/unattend.iso",media=cdrom,if=none,id=cd1,readonly=on \
-device ide-cd,drive=cd1,bus=ahci.2 \
-boot order=c,once=d
vm_wait base 3600
provision base
vm_stop base
echo "OK: $D/base.qcow2; next: vm.sh variants"
}
cmd_variants() {
[[ -f "$D/base.qcow2" ]] || die "no base.qcow2; run vm.sh create"
running base && die "stop the base VM first"
local v
for v in en zh; do
running "$v" && vm_stop "$v"
rm -f "$D/$v.qcow2"
qemu-img create -q -f qcow2 -b "$D/base.qcow2" -F qcow2 "$D/$v.qcow2"
done
qemu_start zh "$D/zh.qcow2"
vm_wait zh
vm_ssh zh Administrator 'Set-WinSystemLocale -SystemLocale zh-CN; Set-Culture zh-CN; Set-WinHomeLocation -GeoId 45; Restart-Computer -Force' || true
sleep 20
vm_wait zh
echo "zh ANSI code page: $(vm_ssh zh Administrator '[Text.Encoding]::Default.CodePage')"
vm_stop zh
echo "OK: en.qcow2 zh.qcow2"
}
cmd="${1:-}"
shift || true
case "$cmd" in
create) cmd_create ;;
variants) cmd_variants ;;
provision) provision "${1:?variant}" ;;
start)
qemu_start "${1:?variant}" "$(disk_of "$1")"
vm_wait "$1"
;;
stop) vm_stop "${1:?variant}" ;;
status) running "${1:?variant}" && echo running || echo stopped ;;
wait) vm_wait "${1:?variant}" "${2:-900}" ;;
ssh)
v="${1:?variant}"
shift
u=Administrator
if [[ $# -gt 0 ]] && [[ "$1" == Administrator || "$1" == tester || "$1" == 测试 ]]; then
u="$1"
shift
fi
vm_ssh "$v" "$u" "$@"
;;
put) vm_put "$@" ;;
ps)
v="${1:?variant}"
shift
u=Administrator
if [[ "$1" == Administrator || "$1" == tester || "$1" == 测试 ]]; then
u="$1"
shift
fi
vm_ps "$v" "$u" "$@"
;;
shot)
v="${1:?variant}"
out="${2:-$D/$v.png}"
printf '%s\n' '{"execute":"qmp_capabilities"}' \
'{"execute":"screendump","arguments":{"filename":"'"$D/$v.ppm"'"}}' |
socat - UNIX-CONNECT:"$D/$v.qmp" >/dev/null
sleep 1
magick "$D/$v.ppm" -resize '1024x1024>' "$out"
rm -f "$D/$v.ppm"
echo "$out"
;;
type) python3 "$HERE/type.py" "$D/${1:?variant}.qmp" "${2:?text}" ;;
login)
python3 "$HERE/type.py" "$D/${1:?variant}.qmp" --cad
sleep 3
python3 "$HERE/type.py" "$D/$1.qmp" "@$D/admin-password"
;;
*) sed -n '2,15p' "$0" | sed 's/^# \{0,1\}//'; exit 2 ;;
esac