Compare commits

...

22 Commits
2.5.0 ... 2.5.2

Author SHA1 Message Date
watermeko
d0ff328db8 fix(web): import react-simple-keyboard by its named export
`react-simple-keyboard` ships only a UMD/CJS bundle whose `module.exports`
is `{ KeyboardReact, default: KeyboardReact }` with `__esModule: true`.

Vite 8 applies Node-compatible CJS interop for ESM importers, so the
default import resolved to the whole `module.exports` object instead of
the component. Rendering it made React throw "Minified React error #130"
(`got: object`) as soon as the on-screen keyboard was opened.

Import the `KeyboardReact` named export, which is the same component,
and keep `KeyboardButtonTheme` as a type-only import.

Fixes #936
2026-09-29 10:15:53 +08:00
watermeko
ff45b46c49 feat(storage): mount images read-only and hand /data to one writer (#937)
Only one side may write the mounted image or the /data partition at a time,
and uploaded images are validated before they are stored.

Image mounts:

* Serve every mounted image read-only, in CD-ROM and mass storage mode alike:
  detach the LUN first and set the read-only flag before the image is
  attached, so the target machine can neither write to nor format it. The
  flags were previously only written for CD-ROM mounts, so a mass storage
  mount inherited ro=0 and the image stayed writable from the host.
* Report the virtual disk as on only while the LUN really carries the /data
  partition. With an image mounted the switch used to stay active but
  unchangeable, and enabling the disk is now a confirmed action instead of a
  rejected one: it cancels the mounted image, and the confirm also warns that
  the image download is interrupted because /data becomes read-only here.
* Ask before mounting: the image list warns that the virtual disk is released
  for the image, or offers to enable it first when it is off, instead of
  dropping the /data share silently. The new strings are translated for every
  locale.
* Name the mounted medium and the USB device after the image file, cut to the
  16 bytes of the SCSI inquiry product field and the 126 bytes of the USB
  product string, and restore the previous names on unmount.
* Reset the LUN flags on every gadget restart. They survived a restart, so
  the shared partition came back to the host read-only, or as an optical
  drive, after an image had been mounted.

The /data handover:

* Mount /data read-only at boot whenever the virtual disk serves the raw
  partition as a writable disk, so the handover holds from the first boot on.
* Add SetDataWritable(), which remounts /data and verifies the new state.
  Enabling the virtual disk makes /data read-only before the host can write
  it, and refuses to expose the disk when the remount fails instead of taking
  the risk. Unmounting an image, which hands the raw partition back to the
  host, does the same, while mounting an image switches /data back to
  writable because a served image is read-only for the host.
* Cancel a running image transfer before the handover and wait for it to
  stop, and report the state in the image list, where mounting still works
  while deleting and uploading do not. The delete action is disabled with a
  hint, and the downloader offers to turn the virtual disk off.

Image uploads:

* Validate the volume descriptors while streaming, so an unusable image is
  rejected in seconds instead of after the whole transfer: accept ISO 9660 and
  UDF volume descriptors (CD001, BEA01) as well as raw disk images (GPT, APFS,
  HFS+, MBR), and reject anything else. Require the image to fit in /data with
  a 128 MiB reserve before any of it is received, log the underlying errors on
  the rejection paths, and keep the temporary file, the progress ticker and the
  close handling in defers.

Add unit tests for the upload header check, the free space preflight and the
image name truncation.
2026-09-24 09:17:24 +08:00
Guoguo
bd070b2f5c docs: add 2.5.1 changelog entries (#929) 2026-09-09 16:38:14 +08:00
watermeko
5c0bef019f fix(terminal): start a root login shell
Launch Web terminal sessions in /root as login shells so they load the root profile and display the configured prompt.
2026-09-04 17:25:51 +08:00
watermeko
283c1390e5 feat(shell): add informative SSH prompt
Create a default root profile when one does not already exist. Show the user, hostname, and working directory while preserving custom profiles.
2026-09-04 17:25:51 +08:00
watermeko
7f95fe9bbd fix(stream): isolate H264 subscribers
Keep slow WebRTC consumers from blocking the shared H264 source by dropping buffered frames until the next keyframe. Restore the WebRTC NACK and RTCP report interceptors while retaining a safe RTP MTU, and enable linker --as-needed for libkvm to remove unused OpenCV dependencies.
2026-09-01 15:34:20 +08:00
watermeko
a9e1ef2459 perf(stream): share H264 capture frames
Route Direct and WebRTC consumers through one H264 capture source to avoid duplicate VENC reads. Overlap WebRTC capture with ordered RTP/SRTP writes and packetize each access unit once for all WebRTC clients.

Add libopencv_video.so.409 into dl_lib.
2026-09-01 15:34:20 +08:00
watermeko
2ba45a2147 feat(web): enhance configurable input regions
Make input-region calibration work across MJPEG and H.264 video modes, including robust four-sided black-border detection and initial-selection edge snapping. Persist multiple reusable manual regions, keep manual and original-resolution choices mutually exclusive, migrate legacy settings, and localize the new controls for every supported language.
2026-08-25 09:36:13 +08:00
watermeko
9e6d280826 feat(web): add configurable mouse input regions
Add device-level input-region APIs for reading, validating, and atomically persisting absolute mouse calibration settings, including automatic, manual, and disabled modes.

Introduce a shared screen viewport that keeps the rendered media geometry and configured input region aligned across MJPEG, direct H.264, and WebRTC streams. Add automatic black-border detection and a manual selection overlay with dragging, resizing, magnified preview, keyboard locking, and cancellation support.

Provide original-resolution presets so manual calibration can be recalculated for common aspect ratios, expose the controls from the desktop mouse menu, close menus before entering selection mode, and preserve active file transfers when the download menu closes.

Add localized control-region labels and messages for all supported locales, and update direct-frame rendering so media dimensions are reported after the canvas has been drawn.
2026-08-25 09:36:13 +08:00
watermeko
527caeff6a fix(web): correct mouse coordinates for direct h264 frames 2026-08-25 09:36:13 +08:00
肆月
71ab9127dd feat: add secure multi-user support (#876) 2026-08-20 14:29:56 +08:00
肆月
d382f0621d fix: report and retry WebRTC connection failures (#866) 2026-08-13 14:56:01 +08:00
watermeko
9415afb359 fix(mouse): improve touch interaction and screen fitting (#857)
- Add touch gestures for relative mouse mode, including tap, drag, long press, double-tap drag, and two-finger scrolling.

- Improve absolute mouse touch handling and prevent black letterbox areas from generating remote mouse events.

- Fit H.264 and MJPEG screens with contain scaling and disable browser touch handling on the screen elements.

- Move golang.org/x/sys to the direct dependency list.
2026-08-11 09:47:04 +08:00
肆月
e5f6dfabaa fix(ota): isolate updates in persistent workspaces (#863)
* fix(ota): isolate updates in persistent workspaces

Stage online and offline update archives under /root/.kvmcache/nanokvm-update-* and validate storage, manifests, and archive contents before changing the installed application.

* fix(ota): harden storage safety and release gates

Preserve the last rollback backup when update storage is insufficient, and verify the actual application mount point before installation.

Move the shared transfer sentinel from /tmp to /run, enforce device package limits in release verification, and run that verification in package CI.
2026-08-10 14:49:29 +08:00
watermeko
757e0f61c5 feature: provide HDMI status in /api/vm/hdmi (#859)
* feature: provide HDMI status in  /api/vm/hdmi

* fix: return false when HDMI idle in  /api/vm/hdmi
2026-08-07 09:43:22 +08:00
肆月
761b02ed7e feat(web): upgrade build tooling to Vite 8 (#853)
Upgrade Vite to 8.2.0 and @vitejs/plugin-react to 6.0.5.

Use Vite's native tsconfig path resolver and remove vite-tsconfig-paths.

Verified with pnpm build and pnpm lint (existing warnings only).
2026-08-06 14:25:55 +08:00
Guoguo
562ea8277c feat: add dev container for full-stack development (#861)
Layer the frontend toolchain on top of the existing release builder
image so a single container covers Go, C support-layer and web
development, with the builder image remaining the single source of
truth for the cross toolchain, Go and MaixCDK.

- Mount the workspace at /home/build/NanoKVM, where the Makefile and
  support/sg2002/build expect it, and resync MaixCDK components via
  update_lib on create so C builds never use stale sources
- Install Node from official dist tarballs (integrity-checked, pinned
  to the major used by CI), with NODE_DIST_MIRROR / NPM_REGISTRY /
  BASE_IMAGE build args for restrictive or mirrored corporate networks
- Export the MaixCDK virtualenv via remoteEnv so non-interactive
  processes (tasks, extensions, exec) get it too; make
  updateRemoteUserUID explicit since the published builder image bakes
  the CI runner's uid
- Run pnpm non-interactively during post-create (no TTY) and give the
  skeleton-less home a standard ~/.profile -> ~/.bashrc chain
- Make the web toolchain convention explicit via package.json engines
  (Node >= 22, pnpm >= 11, matching CI) and document it in web/README
- Document the dev container in the README, point server/README at the
  container flow that works on any host OS, and ignore .pnpm-store/
2026-08-06 11:00:40 +08:00
Guoguo
7abec3cbad docs: add 2.5.0 changelog entries (#860) 2026-08-06 10:18:29 +08:00
Guoguo
8fc31553f7 ci: prefix GitHub Release titles with nanokvm (#856) 2026-08-05 11:52:22 +08:00
watermeko
9e50040713 fix(ota): keep update lock through service restart 2026-08-05 11:50:39 +08:00
watermeko
0f8ef20fb5 feat(ota): verify offline update checksums 2026-08-05 11:50:39 +08:00
watermeko
7cda3b2920 feat(ota): add custom update server support
+ Add persistent custom update server configuration, authenticated URL support, manifest validation, and the settings UI.

+ Keep application updates rebootless by coordinating video shutdown, migration-time service startup, and online/offline service restarts.

+ Localize the custom update server workflow across all supported languages.
2026-08-05 11:50:39 +08:00
171 changed files with 11434 additions and 1661 deletions

52
.devcontainer/Dockerfile Normal file
View File

@@ -0,0 +1,52 @@
# Dev container image for VS Code / the devcontainer CLI.
#
# The release builder image (docker/Dockerfile) stays the single source of
# truth for the RISC-V cross toolchain, Go and MaixCDK. This layer only adds
# the frontend toolchain on top: the builder image deliberately ships without
# Node (`make web` runs on the host), but an IDE container should cover web
# development as well.
#
# BASE_IMAGE can be overridden to a locally built builder image, e.g. the
# output of `make builder-image` (nanokvm-builder-local-<uid>-<gid>).
ARG BASE_IMAGE=ghcr.io/sipeed/nanokvm-builder:latest
FROM ${BASE_IMAGE}
USER root
# Node major and pnpm major track .github/workflows/package.yml ("Set up
# Node" / "Set up pnpm") and web/package.json "engines" -- keep all of them
# in sync when CI bumps either.
ARG NODE_MAJOR=22
ARG PNPM_VERSION=11
# Both can be overridden behind restrictive or mirrored corporate networks
# via devcontainer.json, e.g.:
# "build": {"args": {
# "NODE_DIST_MIRROR": "https://registry.npmmirror.com/-/binary/node",
# "NPM_REGISTRY": "https://registry.npmmirror.com"
# }}
ARG NODE_DIST_MIRROR=https://nodejs.org/dist
ARG NPM_REGISTRY=https://registry.npmjs.org
# Install the latest Node of the pinned major from official dist tarballs;
# tracking the latest patch release is intentional (rebuild the container to
# pick up updates). The SHA-256 check guards download integrity -- it shares
# its origin with the tarball, so it is not an authenticity proof.
RUN set -eux; \
apt-get update; \
apt-get install -y ca-certificates curl xz-utils; \
rm -rf /var/lib/apt/lists/*; \
case "$(uname -m)" in \
x86_64) node_arch=x64 ;; \
aarch64) node_arch=arm64 ;; \
*) echo "unsupported architecture: $(uname -m)" >&2; exit 1 ;; \
esac; \
curl -fsSL "${NODE_DIST_MIRROR}/latest-v${NODE_MAJOR}.x/SHASUMS256.txt" \
-o /tmp/SHASUMS256.txt; \
tarball="$(grep -o "node-v[0-9.]*-linux-${node_arch}\.tar\.xz" /tmp/SHASUMS256.txt | head -n1)"; \
curl -fsSL "${NODE_DIST_MIRROR}/latest-v${NODE_MAJOR}.x/${tarball}" -o "/tmp/${tarball}"; \
cd /tmp && grep " ${tarball}\$" SHASUMS256.txt | sha256sum -c -; \
tar -xJf "/tmp/${tarball}" -C /usr/local --strip-components=1 --no-same-owner; \
rm -f "/tmp/${tarball}" /tmp/SHASUMS256.txt; \
node --version && npm --version
RUN npm install --global --registry "${NPM_REGISTRY}" "pnpm@${PNPM_VERSION}" \
&& pnpm --version

View File

@@ -0,0 +1,49 @@
// Dev container for NanoKVM: Go cross-compilation, MaixCDK C support layer
// and web frontend in a single container. See "Development" in README.md.
{
"name": "NanoKVM",
"build": {
"dockerfile": "Dockerfile"
},
// The Makefile and support/sg2002/build expect the repository at
// ~/NanoKVM of the baked-in "build" user -- mount it exactly there.
"workspaceMount": "source=${localWorkspaceFolder},target=/home/build/NanoKVM,type=bind,consistency=cached",
"workspaceFolder": "/home/build/NanoKVM",
"remoteUser": "build",
// The published builder image bakes in the CI runner's uid (currently
// 1001); on Linux hosts this remaps "build" to the local uid so the bind
// mount stays writable. The remap chowns /home/build once, which makes
// the first container creation noticeably slower.
"updateRemoteUserUID": true,
// Equivalent of `. ~/MaixCDK/bin/activate` for every process spawned in
// the container, interactive or not (tasks, extensions, exec).
"remoteEnv": {
"VIRTUAL_ENV": "/home/build/MaixCDK",
"PATH": "/home/build/MaixCDK/bin:${containerEnv:PATH}"
},
"forwardPorts": [3001],
"portsAttributes": {
"3001": {
"label": "web dev server (vite)"
}
},
"postCreateCommand": ".devcontainer/post-create.sh",
// This configuration itself mounts nothing from the host (VS Code may
// still forward your SSH agent and git credentials by default). To use
// git over SSH or reach a NanoKVM device from inside the container,
// uncomment the mount below.
// "mounts": [
// "source=${localEnv:HOME}/.ssh,target=/home/build/.ssh,type=bind,readonly"
// ],
"customizations": {
"vscode": {
"extensions": [
"golang.go",
"ms-vscode.cpptools",
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"bradlc.vscode-tailwindcss"
]
}
}
}

37
.devcontainer/post-create.sh Executable file
View File

@@ -0,0 +1,37 @@
#!/usr/bin/env bash
# Runs once inside the dev container after it is created (see
# .devcontainer/devcontainer.json). Keeps the container aligned with the
# CLI flow in the Makefile and scripts/build-in-container.sh.
set -euo pipefail
repo_root="$(cd "$(dirname "$0")/.." && pwd)"
# The MaixCDK components baked into the image can be older than this
# checkout; resync them so C builds never use stale sources (same reason
# scripts/build-in-container.sh runs update_lib first).
"$repo_root/support/sg2002/build" update_lib
# Frontend dependencies. postCreate has no TTY, and CI=true lets pnpm make
# its non-interactive choices -- e.g. purging a node_modules tree that was
# installed from the host OS through the bind mount.
(cd "$repo_root/web" && CI=true pnpm install --frozen-lockfile)
# Start every interactive shell with the MaixCDK virtualenv active,
# mirroring `make shell`.
activate_line='. "$HOME/MaixCDK/bin/activate"'
if ! grep -qxF "$activate_line" "$HOME/.bashrc" 2>/dev/null; then
printf '\n# MaixCDK virtualenv (added by .devcontainer/post-create.sh)\n%s\n' \
"$activate_line" >>"$HOME/.bashrc"
fi
# The build user's home has no shell skeleton files (useradd ran with
# --no-create-home), so login shells would skip ~/.bashrc; give them the
# standard Debian chain.
if [ ! -f "$HOME/.profile" ]; then
cat >"$HOME/.profile" <<'EOF'
# ~/.profile (added by .devcontainer/post-create.sh)
if [ -n "$BASH_VERSION" ] && [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
EOF
fi

View File

@@ -251,6 +251,11 @@ jobs:
echo "sha512_base64=${SHA512_BASE64}"
} > build/release/BUILD_INFO.txt
- name: Verify release assets
run: |
./scripts/verify-release-assets.sh \
build/release "${{ steps.version.outputs.version }}"
- name: Summary
env:
VERSION: ${{ steps.version.outputs.version }}

View File

@@ -147,7 +147,7 @@ jobs:
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
gh release create "$TAG" \
--verify-tag \
--title "$TAG" \
--title "nanokvm@${TAG}" \
--notes "$NOTES" \
"${STATE_ARGS[@]}" \
"$TARBALL" build/release/latest.json build/release/sha256.txt

4
.gitignore vendored
View File

@@ -5,6 +5,10 @@ web/node_modules
web/dist
web/web
# pnpm keeps its content-addressable store next to the project when the
# home directory is on a different filesystem (e.g. inside the dev container)
.pnpm-store/
.DS_Store
*.local
*.suo

View File

@@ -1,3 +1,81 @@
## 2.5.1 (2026-09-09)
### Features
* Added device-level multi-user support with `admin` and `user` roles and a user management page under Settings, separating administrative areas (terminal, scripts, storage, network, updates, MCP, PicoClaw and Tailscale) from the video, keyboard, mouse, paste, wake-on-LAN and power controls every account keeps
* Moved sessions to HttpOnly cookies with a per-user token version, so changing a password or disabling an account immediately ends that user's open web and WebSocket sessions
* Added support for a custom update server, so the application can be updated from your own mirror, with credentials in the URL, manifest validation and a settings page for configuring it
* Added SHA-256 verification of offline update packages before they are installed
* Added configurable mouse input regions for absolute mode, with automatic black-border detection, manual selection of the controllable area on screen, and original-resolution presets, so the pointer stays aligned when the target machine outputs a letterboxed or non-16:9 signal
* Added touch gestures to relative mouse mode, including tap, drag, long press, double-tap drag and two-finger scroll, so relative mode is now usable from a phone or tablet
* Added a `signal` field to `/api/vm/hdmi` reporting whether an HDMI source is actually present, not just whether capture is enabled
* Added a default root shell profile showing the user, host and working directory in the prompt over SSH and the Web terminal
### Bug Fixes
* Fixed mouse coordinates being offset in Direct H.264 mode when the target machine pads the picture with black bars
* Fixed touch input in absolute mode, and stopped taps on the black letterbox area from being sent to the target machine
* Fixed the video area not fitting the window, by scaling H.264 and MJPEG playback to contain and letting the page handle touch instead of the browser
* Fixed WebRTC H.264 failures leaving a silent black screen; signaling, negotiation, ICE and playback failures now report what went wrong and offer a retry
* Fixed a slow WebRTC viewer stalling the shared H.264 source for everyone else, by dropping its buffered frames until the next key frame
* Fixed application updates running from a temporary directory that could be too small or shared with another update; online and offline updates are now staged in isolated persistent workspaces with archive, manifest and free-space checks, and the last rollback backup is kept when space runs short
* Fixed the update lock being released before the server finished restarting, which allowed a second update to start and be killed mid-install
* Fixed Web terminal sessions not loading the root profile, by starting them as login shells in `/root`
### Performance
* Routed Direct and WebRTC viewers through a single shared H.264 capture source instead of each reading the encoder separately
### Localization
* Synchronized translations of other languages according to English
### Chores
* Upgraded the web build tooling to Vite 8 and switched to Vite's native tsconfig path resolution
* Added a dev container for full-stack development
* Prefixed GitHub Release titles with `nanokvm`
* Added release asset verification with per-device package size limits to the packaging workflow
## 2.5.0 (2026-08-04)
### Features
* Added an MCP service that lets trusted MCP clients capture screenshots and control the keyboard and mouse with an API key, including a settings page for enabling it and regenerating the key
* Added coordinated device control so MCP, PicoClaw and manual input hand ownership over to each other instead of writing HID input at the same time
* Added remote keyboard lock indicators that show the target machine's Num Lock, Caps Lock and Scroll Lock state
* Added an optional SHA-256 checksum and cancellation to remote image downloads
### Bug Fixes
* Fixed the USB network gadget getting a random host-side MAC on every bind, which made the attached PC register a new network adapter after each reboot; both the device and host MAC are now derived from the chip UID (thanks to [@BeaconCat](https://github.com/BeaconCat))
* Fixed OLED sleep durations above 255 seconds being truncated, so the 5 min, 10 min, 30 min and 1 hour options now behave as selected
* Fixed the mounted image API returning an error in HID-Only mode
* Fixed image downloads and application updates interfering with each other when running at the same time
* Fixed Direct H.264 playback falling behind when the decoder queue backed up, by resynchronizing at the next key frame and preferring hardware decoding
* Added a warning when Direct and WebRTC H.264 stream modes are used at the same time
* Made the video input state shared between processes and read it without shell pipelines, so HDMI status stays consistent between `NanoKVM-Server` and `kvm_system`
### Performance
* Reduced latency in 60 Hz mode with decode-driven flow control, GOP-aware bounded queues, and dedicated writer goroutines with write deadlines so a slow client no longer stalls the others
* Integrated zero-copy H.264 capture into the video pipeline instead of relying on a preload hook
* Stopped HDMI capture when no user is logged in or all viewers are idle, reducing power consumption
### UI Improvements
* Tidied the image download dialog layout and truncated long file names in the upload box
### Localization
* Synchronized translations of other languages according to English
### Chores
* Split release automation into separate package, tag and release workflows, and produced identifiable build artifacts with checksums for pull requests
* Allowed overriding the builder image, installed `patchelf` in the build environment, and fixed the exit codes of `support/sg2002/build`
* Fixed slow container builds caused by uid/gid mismatch and reused existing container users and groups
## 2.4.3 (2026-06-09)
### Features

View File

@@ -91,6 +91,18 @@ Start with the guide that matches the part of NanoKVM you want to work on:
> Backend compilation and runtime validation require the target toolchain or a NanoKVM device. See the module-specific guides above for the latest development workflow.
### Dev container (optional)
The repository ships a [Dev Container](https://containers.dev) setup (`.devcontainer/`) that layers the frontend toolchain (Node 22, pnpm 11) on top of the release builder image (RISC-V cross toolchain, Go, MaixCDK), so one container covers Go, C support-layer and web development. It is a convenience for IDE users; the `make` targets in the repository root remain the canonical CLI workflow.
- Requirements: Docker plus an editor or CLI with dev container support (e.g. the VS Code "Dev Containers" extension, or `devcontainer up`).
- On creation the container prepares itself automatically: `support/sg2002/build update_lib` (resyncs MaixCDK components with the checkout) and `pnpm install` for the frontend.
- Backend: run `server/build.sh` for a release-equivalent binary (BoringCrypto + `dl_lib` RPATH). `make app` builds a plain development binary without those, so prefer `server/build.sh` whenever the result should match a release.
- Support layer: `cd support/sg2002 && ./build kvm_system` (the MaixCDK virtualenv is part of the container environment).
- Frontend: `cd web && pnpm dev` (VS Code forwards port 3001 automatically; other clients may need to map it themselves); see [web/README.md](web/README.md) for pointing it at a device.
- The base image `ghcr.io/sipeed/nanokvm-builder:latest` is x86-64 only; on Apple Silicon it runs under emulation (works, but C builds are slow). You can also build the image locally first (`make builder-image`) and point the `BASE_IMAGE` build arg at it (e.g. via `build.args` in `devcontainer.json`). On Linux hosts the first container creation also takes a while: the container user is remapped to your uid, which re-chowns its home directory once.
- Hardware-dependent verification still requires a real NanoKVM device; the container covers compiling, linting and mock-mode web development only.
## 🔩 Hardware Platform (NanoKVM Cube/PCIe)
NanoKVM is based on Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html). You can find specifications, schematics, and dimensional drawings in the [download station](https://dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano).

View File

@@ -35,7 +35,14 @@ then
if [ -e /dev/mmcblk0p3 ]
then
mkdir -p /data
mount /dev/mmcblk0p3 /data
# The partition is the virtual disk. While it is shared as a writable
# disk the host is the only writer, so mount it read-only here.
if [ -e /boot/usb.disk0 ] && [ ! -e /boot/usb.disk0.ro ] && [ ! -s /boot/usb.disk0 ]
then
mount -o ro /dev/mmcblk0p3 /data
else
mount /dev/mmcblk0p3 /data
fi
fi
echo "OK"

View File

@@ -134,11 +134,15 @@ start_usb_dev(){
mkdir functions/mass_storage.disk0
ln -s functions/mass_storage.disk0 configs/c.1/
echo 1 > functions/mass_storage.disk0/lun.0/removable
# The LUN flags survive a restart of this script, so they are always set:
# a mounted image leaves them read-only and in CD-ROM mode.
if [ -e /boot/usb.disk0.ro ]
then
echo 1 > functions/mass_storage.disk0/lun.0/ro
echo 0 > functions/mass_storage.disk0/lun.0/cdrom
else
echo 0 > functions/mass_storage.disk0/lun.0/ro
fi
echo 0 > functions/mass_storage.disk0/lun.0/cdrom
echo "NanoKVM USB Mass Storage0520" > functions/mass_storage.disk0/lun.0/inquiry_string
disk=$(cat /boot/usb.disk0)
if [ -z "${disk}" ]

View File

@@ -1,9 +1,82 @@
#!/bin/sh
# nanokvm Rev3.1
wait_for_exit() {
process="$1"
timeout="$2"
elapsed=0
while pidof "$process" >/dev/null 2>&1; do
if [ "$elapsed" -ge "$timeout" ]; then
return 1
fi
sleep 1
elapsed=$((elapsed + 1))
done
return 0
}
stop_process() {
process="$1"
if ! pidof "$process" >/dev/null 2>&1; then
return
fi
killall -INT "$process" 2>/dev/null || true
if wait_for_exit "$process" 20; then
return
fi
killall -TERM "$process" 2>/dev/null || true
if wait_for_exit "$process" 5; then
return
fi
killall -KILL "$process" 2>/dev/null || true
wait_for_exit "$process" 2 || true
}
stop_services() {
# The server owns VI/VPSS. Let it release MMF before stopping kvm_system.
stop_process NanoKVM-Server
stop_process kvm_system
rm -rf /tmp/kvm_system /tmp/server
}
start_services() {
cp -r /kvmapp/kvm_system /tmp/
if [ -f /kvmapp/kvm_new_app ]; then
touch /tmp/.nanokvm_migrating
/tmp/kvm_system/kvm_system &
# The legacy migration invokes this init script recursively and starts
# the server itself. Wait for that single migration path to finish.
migration_wait=0
while [ "$migration_wait" -lt 30 ]; do
if [ ! -f /kvmapp/kvm_new_app ] && pidof NanoKVM-Server >/dev/null 2>&1; then
rm -f /tmp/.nanokvm_migrating
return
fi
sleep 1
migration_wait=$((migration_wait + 1))
done
rm -f /tmp/.nanokvm_migrating
else
/tmp/kvm_system/kvm_system &
fi
if ! pidof NanoKVM-Server >/dev/null 2>&1; then
rm -rf /tmp/server
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
fi
}
case "$1" in
start)
echo -n kvm > /boot/hostname.prefix
[ -e /root/.profile ] || printf '%s\n' 'export PS1="\u@\h:\w# "' > /root/.profile
# Copy sensor config if the file exists
[ -f /mnt/data/sensor_cfg.ini.LT ] && cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
@@ -45,30 +118,20 @@ case "$1" in
fi
# Start services
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
start_services
;;
stop)
killall kvm_system
killall NanoKVM-Server
rm -r /tmp/kvm_system /tmp/server
stop_services
echo "OK"
;;
restart)
killall kvm_system
killall NanoKVM-Server
rm -r /tmp/kvm_system /tmp/server
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &
cp -r /kvmapp/server /tmp/
/tmp/server/NanoKVM-Server &
if [ -f /tmp/.nanokvm_migrating ]; then
exit 0
fi
stop_services
start_services
sync
echo "OK"
@@ -78,4 +141,4 @@ case "$1" in
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac
esac

View File

@@ -16,9 +16,9 @@ over the air: `nanokvm_<version>.tar.gz` plus its `latest.json` manifest.
The format is not arbitrary — it is fixed by the on-device updater in
`server/service/application/`:
- **One root directory.** `install.go` untars the package and moves the single
top-level directory over `/kvmapp`, so the tarball must contain exactly
`nanokvm_<version>/`.
- **One safe root directory.** The updater scans before extracting and accepts
only directories and regular files under `nanokvm_<version>/`; links,
special files, duplicate paths, and path traversal are rejected.
- **`name` is the file name.** `version.go` builds the download URL as
`<base>/<name>`, where `<base>` is `https://cdn.sipeed.com/nanokvm` (or
`.../preview` when `/etc/kvm/preview_updates` exists).
@@ -27,9 +27,13 @@ The format is not arbitrary — it is fixed by the on-device updater in
- **`/kvmapp/version`** is what the device reports as its installed version, so
it must match the `version` field.
`size` is parsed into `Latest.Size` but never read anywhere, so nothing on the
device depends on its units. Published manifests have carried a kilobyte-ish
value; `package.sh` writes the exact byte count instead.
New releases use manifest v2. `size` remains the exact compressed byte count
for older clients, while v2 clients use `size_bytes` and
`unpacked_size_bytes` for storage preflight checks. Historical v1 `size`
values have inconsistent units, so v2 clients only require v1 `size` to be
non-zero and verify the downloaded SHA-512 instead. Publish v2 metadata before
releasing clients that consume it; clients retain v1 compatibility for custom
update servers.
## Building a release

View File

@@ -7,9 +7,9 @@
# download URL as "<base>/<name>", so "name" must be the tarball file name.
# - server/service/application/update.go verifies the download against
# "sha512", which is the *base64* encoding of the raw SHA-512 digest.
# - server/service/application/install.go untars the package and moves the
# single top-level directory over /kvmapp, so the tarball must contain
# exactly one root directory: nanokvm_<version>/.
# - server/service/application/archive.go validates and extracts the package
# before install.go moves its single top-level directory over /kvmapp, so
# the tarball must contain exactly one root directory: nanokvm_<version>/.
#
# Build artifacts are expected to be in place already (see
# scripts/build-in-container.sh and the "web" target in the Makefile):
@@ -157,7 +157,7 @@ printf '0\n' > "$STAGE/kvm/now_fps"
printf '60\n' > "$STAGE/kvm/qlty"
printf '1920\n' > "$STAGE/kvm/width"
printf '1080\n' > "$STAGE/kvm/height"
printf '1\n' > "$STAGE/kvm/state"
printf '0\n' > "$STAGE/kvm/state"
printf 'mjpeg\n' > "$STAGE/kvm/type"
printf '0' > "$STAGE/kvm/res"
@@ -199,14 +199,29 @@ fi
# --- manifest ----------------------------------------------------------------
# update.go compares base64(raw sha512), not the hex digest.
SHA512="$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)"
SIZE="$(wc -c < "$TARBALL" | tr -d ' ')"
SIZE_BYTES="$(wc -c < "$TARBALL" | tr -d ' ')"
UNPACKED_SIZE_BYTES="$(python3 - "$TARBALL" <<'PY'
import sys
import tarfile
total = 0
with tarfile.open(sys.argv[1], "r:gz") as archive:
for member in archive:
if member.isfile():
total += member.size
print(total)
PY
)"
cat > "$MANIFEST" <<EOF
{
"manifest_version": 2,
"version": "$VERSION",
"name": "nanokvm_$VERSION.tar.gz",
"sha512": "$SHA512",
"size": $SIZE
"size": $SIZE_BYTES,
"size_bytes": $SIZE_BYTES,
"unpacked_size_bytes": $UNPACKED_SIZE_BYTES
}
EOF

View File

@@ -28,6 +28,9 @@ for path in "$TARBALL" "$MANIFEST" "$CHECKSUM"; do
done
PACKAGE_ROOT="nanokvm_${VERSION}"
MAX_PACKAGE_SIZE=$((1 << 30))
MAX_UNPACKED_SIZE=$((2 << 30))
MAX_ARCHIVE_ENTRIES=100000
ENTRY_LIST=$(mktemp)
VERBOSE_LIST=$(mktemp)
trap 'rm -f "$ENTRY_LIST" "$VERBOSE_LIST"' EXIT
@@ -44,6 +47,10 @@ fi
ENTRY_COUNT=0
while IFS= read -r entry; do
ENTRY_COUNT=$((ENTRY_COUNT + 1))
if [ "$ENTRY_COUNT" -gt "$MAX_ARCHIVE_ENTRIES" ]; then
echo "[ERROR] archive contains more than $MAX_ARCHIVE_ENTRIES entries" >&2
exit 1
fi
case "$entry" in
"$PACKAGE_ROOT"|"$PACKAGE_ROOT"/*) ;;
*)
@@ -92,6 +99,9 @@ fi
MANIFEST_VERSION=$(jq -er '.version | select(type == "string" and length > 0)' "$MANIFEST")
MANIFEST_NAME=$(jq -er '.name | select(type == "string" and length > 0)' "$MANIFEST")
MANIFEST_SIZE=$(jq -er '.size | select(type == "number" and . >= 0 and floor == .)' "$MANIFEST")
MANIFEST_FORMAT=$(jq -er '.manifest_version | select(type == "number" and . == 2)' "$MANIFEST")
MANIFEST_SIZE_BYTES=$(jq -er '.size_bytes | select(type == "number" and . > 0 and floor == .)' "$MANIFEST")
MANIFEST_UNPACKED_SIZE_BYTES=$(jq -er '.unpacked_size_bytes | select(type == "number" and . > 0 and floor == .)' "$MANIFEST")
MANIFEST_SHA512=$(jq -er '.sha512 | select(type == "string" and length > 0)' "$MANIFEST")
if [ "$MANIFEST_VERSION" != "$VERSION" ]; then
@@ -104,10 +114,39 @@ if [ "$MANIFEST_NAME" != "$TARBALL_NAME" ]; then
fi
ACTUAL_SIZE=$(wc -c < "$TARBALL" | tr -d ' ')
if [ "$MANIFEST_SIZE" != "$ACTUAL_SIZE" ]; then
if [ "$MANIFEST_FORMAT" != "2" ]; then
echo "[ERROR] latest.json manifest_version must be 2" >&2
exit 1
fi
if [ "$MANIFEST_SIZE" != "$ACTUAL_SIZE" ] || [ "$MANIFEST_SIZE_BYTES" != "$ACTUAL_SIZE" ]; then
echo "[ERROR] latest.json size '$MANIFEST_SIZE' does not match '$ACTUAL_SIZE'" >&2
exit 1
fi
if [ "$ACTUAL_SIZE" -gt "$MAX_PACKAGE_SIZE" ]; then
echo "[ERROR] release tarball exceeds device limit of $MAX_PACKAGE_SIZE bytes" >&2
exit 1
fi
ACTUAL_UNPACKED_SIZE=$(python3 - "$TARBALL" <<'PY'
import sys
import tarfile
total = 0
with tarfile.open(sys.argv[1], "r:gz") as archive:
for member in archive:
if member.isfile():
total += member.size
print(total)
PY
)
if [ "$MANIFEST_UNPACKED_SIZE_BYTES" != "$ACTUAL_UNPACKED_SIZE" ]; then
echo "[ERROR] latest.json unpacked_size_bytes '$MANIFEST_UNPACKED_SIZE_BYTES' does not match '$ACTUAL_UNPACKED_SIZE'" >&2
exit 1
fi
if [ "$ACTUAL_UNPACKED_SIZE" -gt "$MAX_UNPACKED_SIZE" ]; then
echo "[ERROR] unpacked package exceeds device limit of $MAX_UNPACKED_SIZE bytes" >&2
exit 1
fi
ACTUAL_SHA512=$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)
if [ "$MANIFEST_SHA512" != "$ACTUAL_SHA512" ]; then

View File

@@ -48,7 +48,7 @@ authentication: enable # Whether to enable identity verification fo
jwt:
secretKey: "" # The secret key used to sign and verify JWT Tokens. If left empty, a random key will be generated automatically on startup
refreshTokenDuration: 2678400 # The token refresh duration threshold in seconds before forcing a re-login. Default is `2678400` (~31 days)
revokeTokensOnLogout: true # Whether to invalidate all existing tokens upon logout by rotating the SecretKey. Default is `true`
revokeTokensOnLogout: true # Whether logout invalidates all sessions belonging to that user. Other users are never logged out. Setting this to false only clears the browser cookie and is not recommended. Default is `true`
security:
loginLockoutDuration: 0, # The duration (in seconds) to ban an IP from attempting to log in again after reaching the failure limit. If set to `0` or left empty, brute-force protection is disabled. Default is `0`
loginMaxFailures: 5, # The maximum number of continuous failed login attempts allowed per IP before triggering protection. Default is `5`
@@ -62,9 +62,31 @@ turn:
turnCred: example_cred # The credential/password required for authorization to the TURN server
```
## Web Users
NanoKVM uses two device-wide roles:
- `admin`: KVM access plus user, system, network, update, storage, terminal, script, MCP, and PicoClaw administration.
- `user`: KVM video, keyboard, mouse, paste, power/reset, and Wake-on-LAN access.
Administrators manage accounts from **Settings > Account**. Account data remains in
`/etc/kvm/pwd`; the server migrates the legacy single-account JSON format in place and writes
the multi-user format atomically with mode `0600`. Keeping the same path preserves the physical
BOOT-button password reset behavior.
Users must confirm their current password when changing it themselves; administrators can reset
non-owner users from the account manager. Only the device owner can change the device owner's
password, because that password is also synchronized to the Linux root account.
All authenticated sessions are backed by the current account state. Disabling, deleting,
changing the role or password of a user invalidates that user's HTTP and real-time connections
without affecting other users. Multiple users may watch and control the KVM concurrently; input
uses the existing cooperative HID coordinator, so simultaneous input can interleave.
Video mode, quality, resolution, and MJPEG frame-detection controls remain shared KVM
operations; when several users adjust them concurrently, the latest change applies device-wide.
## Compile & Deploy
Note: Use Linux operating system (x86-64) with Go 1.25 or newer. This build process is not compatible with ARM, Windows or macOS.
Note: The manual steps below require a Linux x86-64 host with Go 1.25 or newer; they are not compatible with ARM, Windows or macOS. With Docker you can skip them entirely and use the containerized flow instead — the root [Makefile](../Makefile) (`make shell`) or the dev container (see "Development" in the root [README](../README.md)) — which works on any host OS; run `server/build.sh` inside the container for a release-equivalent build.
1. Install the Toolchain
1. Download the toolchain from the following link: [Download Link](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz).

View File

@@ -46,7 +46,7 @@ authentication: enable # 是否开启 HTTP 接口与网页的身份
jwt:
secretKey: "" # 用于签发和验证 JWT Token 的密钥。如果不填,服务启动时将自动随机生成
refreshTokenDuration: 2678400 # 登录超时的刷新周期(单位:秒)。默认为 `2678400`(约31天)
revokeTokensOnLogout: true # 退出登录时是否废除所有现存的 Token。启用此项可以在注销时轮换 SecretKey,强迫所有终端重新登录。默认为 `true`
revokeTokensOnLogout: true # 退出登录时是否废除该用户的全部会话;不会影响其他用户。设为 false 时仅清除浏览器 Cookie,不推荐使用。默认为 `true`
security:
loginLockoutDuration: 0, # 达到失败上限后,禁止该 IP 再次尝试登录的持续时间(单位:秒)。如果设为 `0` 或不填,则代表不开启防暴力破解功能。默认为 `0`
loginMaxFailures: 5, # 允许触发保护前,单个 IP 连续登录失败的最大次数。默认为 `5`
@@ -60,6 +60,22 @@ turn:
turnCred: example_cred # TURN 服务器授权连接时使用的凭据/密码
```
## Web 多用户
NanoKVM 使用两种设备级角色:
- `admin`:除 KVM 操作外,还可管理用户、系统、网络、更新、存储、终端、脚本、MCP 和 PicoClaw。
- `user`:可使用 KVM 视频、键盘、鼠标、粘贴、目标机电源/复位和网络唤醒。
管理员可在**设置 > 账户**中管理用户。账户数据继续保存在 `/etc/kvm/pwd`;服务会原地迁移旧版单账户
JSON,并以 `0600` 权限原子写入多用户格式。沿用同一路径可保持长按 BOOT 键重置密码的现有行为。
用户自助修改密码时必须验证当前密码;管理员可在账户管理中重置非设备所有者的密码。由于设备所有者
密码还会同步至 Linux root 账户,因此只有设备所有者本人可以修改自己的密码。
所有登录会话都会校验当前账户状态。禁用、删除、修改角色或密码会立即撤销该用户的 HTTP 与实时连接,
且不会影响其他用户。多个用户可同时观看和协作控制 KVM;输入沿用现有 HID 协调器,因此同时输入可能交错。
视频模式、画质、分辨率和 MJPEG 帧检测仍属于共享 KVM 操作;多人同时调整时,以最后一次设备级修改为准。
## 编译部署
**注意:请使用 Linux 操作系统(x86-64)和 Go 1.25 或更高版本。该工具链无法在 ARM、Windows 或 macOS 下使用。**

616
server/authn/store.go Normal file
View File

@@ -0,0 +1,616 @@
package authn
import (
"crypto/rand"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sync"
"NanoKVM-Server/utils"
"golang.org/x/crypto/bcrypt"
)
const (
AccountFile = "/etc/kvm/pwd"
currentFileVersion = 1
defaultUsername = "admin"
defaultPassword = "admin"
)
type Role string
const (
RoleAdmin Role = "admin"
RoleUser Role = "user"
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUserExists = errors.New("username already exists")
ErrLastAdmin = errors.New("at least one enabled admin is required")
ErrSelfModification = errors.New("administrators cannot disable or demote themselves")
ErrSelfDelete = errors.New("administrators cannot delete themselves")
ErrSystemAccount = errors.New("the device owner account must remain an enabled administrator")
usernamePattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,31}$`)
)
type User struct {
Username string `json:"username"`
PasswordHash string `json:"password"`
Role Role `json:"role"`
Enabled bool `json:"enabled"`
TokenVersion uint64 `json:"tokenVersion"`
MustChangePassword bool `json:"mustChangePassword,omitempty"`
SystemAccount bool `json:"systemAccount,omitempty"`
}
type UserInfo struct {
Username string `json:"username"`
Role Role `json:"role"`
Enabled bool `json:"enabled"`
SystemAccount bool `json:"systemAccount,omitempty"`
}
type UserPatch struct {
Role *Role
Enabled *bool
}
type database struct {
Version int `json:"version"`
Users []User `json:"users"`
LegacyUsername string `json:"username,omitempty"`
LegacyPassword string `json:"password,omitempty"`
}
type legacyAccount struct {
Username string `json:"username"`
Password string `json:"password"`
}
type Store struct {
path string
mutex sync.RWMutex
}
var DefaultStore = NewStore(AccountFile)
func NewStore(path string) *Store {
return &Store{path: path}
}
func IsValidRole(role Role) bool {
return role == RoleAdmin || role == RoleUser
}
func ValidateUsername(username string) error {
if !usernamePattern.MatchString(username) {
return errors.New("username must be 1-32 characters and contain only letters, numbers, '.', '_' or '-'")
}
return nil
}
func ValidatePassword(password string) error {
length := len([]byte(password))
if length < 8 || length > 72 {
return errors.New("password must be between 8 and 72 bytes")
}
return nil
}
func (s *Store) List() ([]UserInfo, error) {
s.mutex.RLock()
defer s.mutex.RUnlock()
db, err := s.loadLocked(false)
if err != nil {
return nil, err
}
users := make([]UserInfo, 0, len(db.Users))
for _, user := range db.Users {
users = append(users, UserInfo{
Username: user.Username,
Role: user.Role,
Enabled: user.Enabled,
SystemAccount: user.SystemAccount,
})
}
return users, nil
}
func (s *Store) Get(username string) (*User, error) {
s.mutex.RLock()
defer s.mutex.RUnlock()
db, err := s.loadLocked(false)
if err != nil {
return nil, err
}
return findUser(db.Users, username)
}
func (s *Store) Authenticate(username, password string) (*User, bool, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, false, err
}
user, err := findUser(db.Users, username)
if err != nil || !user.Enabled {
return nil, false, nil
}
if bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)) == nil {
return user, true, nil
}
// Older releases stored a reversibly encrypted password. Upgrade it after
// the first successful login so the compatibility path is not permanent.
legacyPassword, decodeErr := utils.DecodeDecrypt(user.PasswordHash)
if decodeErr != nil || legacyPassword != password {
return nil, false, nil
}
hash, hashErr := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if hashErr != nil {
return nil, false, hashErr
}
for index := range db.Users {
if db.Users[index].Username == username {
db.Users[index].PasswordHash = string(hash)
if db.Users[index].TokenVersion == 0 {
db.Users[index].TokenVersion = 1
}
user = cloneUser(&db.Users[index])
break
}
}
if err = s.saveLocked(db); err != nil {
return nil, false, err
}
return user, true, nil
}
func (s *Store) ValidateToken(username string, tokenVersion uint64) (*User, error) {
user, err := s.Get(username)
if err != nil {
return nil, err
}
if !user.Enabled || user.TokenVersion != tokenVersion {
return nil, errors.New("session revoked")
}
return user, nil
}
func (s *Store) Create(username, password string, role Role) error {
if err := ValidateUsername(username); err != nil {
return err
}
if err := ValidatePassword(password); err != nil {
return err
}
if !IsValidRole(role) {
return errors.New("invalid role")
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
tokenVersion, err := newTokenVersion()
if err != nil {
return err
}
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return err
}
if _, err = findUser(db.Users, username); err == nil {
return ErrUserExists
}
db.Users = append(db.Users, User{
Username: username,
PasswordHash: string(hash),
Role: role,
Enabled: true,
TokenVersion: tokenVersion,
})
return s.saveLocked(db)
}
func (s *Store) Update(actor, username string, patch UserPatch) (*User, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, err
}
index := userIndex(db.Users, username)
if index < 0 {
return nil, ErrUserNotFound
}
user := db.Users[index]
if patch.Role != nil && !IsValidRole(*patch.Role) {
return nil, errors.New("invalid role")
}
if actor == username && user.Role == RoleAdmin &&
((patch.Role != nil && *patch.Role != RoleAdmin) || (patch.Enabled != nil && !*patch.Enabled)) {
return nil, ErrSelfModification
}
if user.SystemAccount &&
((patch.Role != nil && *patch.Role != RoleAdmin) || (patch.Enabled != nil && !*patch.Enabled)) {
return nil, ErrSystemAccount
}
changed := false
if patch.Role != nil && user.Role != *patch.Role {
user.Role = *patch.Role
changed = true
}
if patch.Enabled != nil && user.Enabled != *patch.Enabled {
user.Enabled = *patch.Enabled
changed = true
}
if !changed {
return &user, nil
}
db.Users[index] = user
if enabledAdminCount(db.Users) == 0 {
return nil, ErrLastAdmin
}
db.Users[index].TokenVersion++
if err = s.saveLocked(db); err != nil {
return nil, err
}
return cloneUser(&db.Users[index]), nil
}
func (s *Store) Delete(actor, username string) error {
if actor == username {
return ErrSelfDelete
}
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return err
}
index := userIndex(db.Users, username)
if index < 0 {
return ErrUserNotFound
}
if db.Users[index].SystemAccount {
return ErrSystemAccount
}
users := append([]User(nil), db.Users[:index]...)
users = append(users, db.Users[index+1:]...)
if enabledAdminCount(users) == 0 {
return ErrLastAdmin
}
db.Users = users
return s.saveLocked(db)
}
func (s *Store) SetPassword(username, password string) (*User, error) {
return s.SetPasswordAndRun(username, password, nil)
}
// SetPasswordAndRun commits the web password before running the optional
// system-side update. If that update fails, the account record is rolled back
// while the store lock is still held.
func (s *Store) SetPasswordAndRun(username, password string, afterCommit func() error) (*User, error) {
if err := ValidatePassword(password); err != nil {
return nil, err
}
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, err
}
index := userIndex(db.Users, username)
if index < 0 {
return nil, ErrUserNotFound
}
previous := *db
previous.Users = append([]User(nil), db.Users...)
db.Users[index].PasswordHash = string(hash)
db.Users[index].MustChangePassword = false
db.Users[index].TokenVersion++
if err = s.saveLocked(db); err != nil {
return nil, err
}
if afterCommit != nil {
if err = afterCommit(); err != nil {
if rollbackErr := s.saveLocked(&previous); rollbackErr != nil {
return nil, fmt.Errorf("system password update failed: %v; account rollback failed: %w", err, rollbackErr)
}
return nil, err
}
}
return cloneUser(&db.Users[index]), nil
}
func (s *Store) Revoke(username string) (*User, error) {
s.mutex.Lock()
defer s.mutex.Unlock()
db, err := s.loadLocked(true)
if err != nil {
return nil, err
}
index := userIndex(db.Users, username)
if index < 0 {
return nil, ErrUserNotFound
}
db.Users[index].TokenVersion++
if err = s.saveLocked(db); err != nil {
return nil, err
}
return cloneUser(&db.Users[index]), nil
}
func (s *Store) loadLocked(migrate bool) (*database, error) {
data, err := os.ReadFile(s.path)
if errors.Is(err, os.ErrNotExist) {
db, defaultErr := defaultDatabase()
if defaultErr != nil {
return nil, defaultErr
}
if migrate {
if saveErr := s.saveLocked(db); saveErr != nil {
return nil, saveErr
}
}
return db, nil
}
if err != nil {
return nil, err
}
var db database
if err = json.Unmarshal(data, &db); err == nil && db.Version != 0 {
if err = validateDatabase(&db); err != nil {
return nil, err
}
return &db, nil
}
var legacy legacyAccount
if err = json.Unmarshal(data, &legacy); err != nil || legacy.Username == "" || legacy.Password == "" {
return nil, errors.New("invalid account file")
}
if err = ValidateUsername(legacy.Username); err != nil {
return nil, fmt.Errorf("invalid legacy username: %w", err)
}
tokenVersion, err := newTokenVersion()
if err != nil {
return nil, err
}
db = database{
Version: currentFileVersion,
Users: []User{{
Username: legacy.Username,
PasswordHash: legacy.Password,
Role: RoleAdmin,
Enabled: true,
TokenVersion: tokenVersion,
MustChangePassword: passwordMatches(legacy.Password, defaultPassword),
SystemAccount: true,
}},
}
if migrate {
if err = s.saveLocked(&db); err != nil {
return nil, err
}
}
return &db, nil
}
func (s *Store) saveLocked(db *database) error {
if err := validateDatabase(db); err != nil {
return err
}
syncLegacyAccount(db)
data, err := json.MarshalIndent(db, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
directory := filepath.Dir(s.path)
if err = os.MkdirAll(directory, 0o755); err != nil {
return err
}
temporary, err := os.CreateTemp(directory, ".pwd-*")
if err != nil {
return err
}
temporaryPath := temporary.Name()
defer func() { _ = os.Remove(temporaryPath) }()
if err = temporary.Chmod(0o600); err == nil {
_, err = temporary.Write(data)
}
if err == nil {
err = temporary.Sync()
}
closeErr := temporary.Close()
if err == nil {
err = closeErr
}
if err != nil {
return err
}
if err = os.Rename(temporaryPath, s.path); err != nil {
return err
}
dir, err := os.Open(directory)
if err != nil {
return err
}
defer func() { _ = dir.Close() }()
return dir.Sync()
}
func defaultDatabase() (*database, error) {
hash, err := bcrypt.GenerateFromPassword([]byte(defaultPassword), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
tokenVersion, err := newTokenVersion()
if err != nil {
return nil, err
}
return &database{
Version: currentFileVersion,
Users: []User{{
Username: defaultUsername,
PasswordHash: string(hash),
Role: RoleAdmin,
Enabled: true,
TokenVersion: tokenVersion,
MustChangePassword: true,
SystemAccount: true,
}},
}, nil
}
func newTokenVersion() (uint64, error) {
var data [8]byte
for {
if _, err := rand.Read(data[:]); err != nil {
return 0, err
}
version := binary.LittleEndian.Uint64(data[:])
if version != 0 && version != ^uint64(0) {
return version, nil
}
}
}
func validateDatabase(db *database) error {
if db.Version != currentFileVersion {
return fmt.Errorf("unsupported account file version: %d", db.Version)
}
if len(db.Users) == 0 {
return errors.New("account file contains no users")
}
seen := make(map[string]struct{}, len(db.Users))
systemAccounts := 0
for index := range db.Users {
user := &db.Users[index]
if err := ValidateUsername(user.Username); err != nil {
return err
}
if user.PasswordHash == "" || !IsValidRole(user.Role) {
return errors.New("account file contains an invalid user")
}
if _, exists := seen[user.Username]; exists {
return errors.New("account file contains duplicate usernames")
}
seen[user.Username] = struct{}{}
if user.TokenVersion == 0 {
user.TokenVersion = 1
}
if user.SystemAccount {
systemAccounts++
if user.Role != RoleAdmin || !user.Enabled || systemAccounts > 1 {
return ErrSystemAccount
}
}
}
if enabledAdminCount(db.Users) == 0 {
return ErrLastAdmin
}
return nil
}
func findUser(users []User, username string) (*User, error) {
index := userIndex(users, username)
if index < 0 {
return nil, ErrUserNotFound
}
return cloneUser(&users[index]), nil
}
func userIndex(users []User, username string) int {
for index := range users {
if users[index].Username == username {
return index
}
}
return -1
}
func enabledAdminCount(users []User) int {
count := 0
for _, user := range users {
if user.Role == RoleAdmin && user.Enabled {
count++
}
}
return count
}
func cloneUser(user *User) *User {
if user == nil {
return nil
}
copy := *user
return &copy
}
func passwordMatches(hash, password string) bool {
if bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) == nil {
return true
}
legacyPassword, err := utils.DecodeDecrypt(hash)
return err == nil && legacyPassword == password
}
// Keep a legacy top-level account mirror so downgrading to a single-user
// server still authenticates the original device owner instead of failing
// open or forcing an immediate physical reset.
func syncLegacyAccount(db *database) {
db.LegacyUsername = ""
db.LegacyPassword = ""
var fallback *User
for _, user := range db.Users {
if user.SystemAccount {
db.LegacyUsername = user.Username
db.LegacyPassword = user.PasswordHash
return
}
if fallback == nil && user.Role == RoleAdmin && user.Enabled {
copy := user
fallback = &copy
}
}
if fallback != nil {
db.LegacyUsername = fallback.Username
db.LegacyPassword = fallback.PasswordHash
}
}

212
server/authn/store_test.go Normal file
View File

@@ -0,0 +1,212 @@
package authn
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"testing"
"golang.org/x/crypto/bcrypt"
)
func TestLegacyAccountMigratesInPlace(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
hash, err := bcrypt.GenerateFromPassword([]byte("legacy-password"), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
legacy, _ := json.Marshal(legacyAccount{Username: "owner", Password: string(hash)})
if err = os.WriteFile(path, legacy, 0o644); err != nil {
t.Fatal(err)
}
store := NewStore(path)
user, ok, err := store.Authenticate("owner", "legacy-password")
if err != nil || !ok {
t.Fatalf("authenticate migrated account: ok=%v err=%v", ok, err)
}
if user.Role != RoleAdmin || !user.SystemAccount || user.TokenVersion == 0 {
t.Fatalf("unexpected migrated user: %+v", user)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var db database
if err = json.Unmarshal(data, &db); err != nil {
t.Fatalf("account file was not migrated: %v", err)
}
if db.Version != currentFileVersion || len(db.Users) != 1 {
t.Fatalf("unexpected database: %+v", db)
}
var downgrade legacyAccount
if err = json.Unmarshal(data, &downgrade); err != nil || downgrade.Username != "owner" || downgrade.Password == "" {
t.Fatalf("legacy downgrade mirror is invalid: %+v, %v", downgrade, err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("account mode = %o, want 600", info.Mode().Perm())
}
}
func TestCorruptAccountFileFailsClosed(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
if err := os.WriteFile(path, []byte("not json"), 0o600); err != nil {
t.Fatal(err)
}
_, ok, err := NewStore(path).Authenticate("admin", "admin")
if err == nil || ok {
t.Fatalf("corrupt file must fail closed: ok=%v err=%v", ok, err)
}
}
func TestUserLifecycleAndTokenRevocation(t *testing.T) {
store := NewStore(filepath.Join(t.TempDir(), "pwd"))
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err := store.Create("alice", "correct-horse", RoleUser); err != nil {
t.Fatal(err)
}
if _, ok, err := store.Authenticate("alice", "wrong-password"); err != nil || ok {
t.Fatalf("wrong password login: ok=%v err=%v", ok, err)
}
alice, err := store.Get("alice")
if err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("alice", alice.TokenVersion); err != nil {
t.Fatal(err)
}
if _, err = store.SetPassword("alice", "new-password"); err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("alice", alice.TokenVersion); err == nil {
t.Fatal("old token stayed valid after password change")
}
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || !ok {
t.Fatalf("new password login: ok=%v err=%v", ok, err)
}
disabled := false
if _, err = store.Update("admin", "alice", UserPatch{Enabled: &disabled}); err != nil {
t.Fatal(err)
}
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || ok {
t.Fatalf("disabled login: ok=%v err=%v", ok, err)
}
enabled := true
if _, err = store.Update("admin", "alice", UserPatch{Enabled: &enabled}); err != nil {
t.Fatal(err)
}
if err = store.Delete("admin", "alice"); err != nil {
t.Fatal(err)
}
if _, err = store.Get("alice"); !errors.Is(err, ErrUserNotFound) {
t.Fatalf("deleted user lookup error = %v", err)
}
}
func TestLastAdminAndSelfProtection(t *testing.T) {
store := NewStore(filepath.Join(t.TempDir(), "pwd"))
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
userRole := RoleUser
if _, err := store.Update("admin", "admin", UserPatch{Role: &userRole}); !errors.Is(err, ErrSelfModification) {
t.Fatalf("self demotion error = %v", err)
}
if err := store.Delete("admin", "admin"); !errors.Is(err, ErrSelfDelete) {
t.Fatalf("self delete error = %v", err)
}
if err := store.Create("second", "second-password", RoleAdmin); err != nil {
t.Fatal(err)
}
disabled := false
if _, err := store.Update("second", "admin", UserPatch{Enabled: &disabled}); !errors.Is(err, ErrSystemAccount) {
t.Fatalf("disable device owner error = %v", err)
}
if _, err := store.Update("second", "admin", UserPatch{Role: &userRole}); !errors.Is(err, ErrSystemAccount) {
t.Fatalf("demote device owner error = %v", err)
}
if err := store.Delete("second", "admin"); !errors.Is(err, ErrSystemAccount) {
t.Fatalf("delete device owner error = %v", err)
}
if err := store.Delete("admin", "second"); err != nil {
t.Fatal(err)
}
}
func TestRemovedAccountFileAndRecreatedUserInvalidateOldVersions(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
store := NewStore(path)
admin, ok, err := store.Authenticate("admin", "admin")
if err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("admin", admin.TokenVersion); err == nil {
t.Fatal("old admin token survived account-file reset")
}
if _, ok, err = store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("login after reset: ok=%v err=%v", ok, err)
}
if err = store.Create("alice", "alice-password", RoleUser); err != nil {
t.Fatal(err)
}
alice, err := store.Get("alice")
if err != nil {
t.Fatal(err)
}
if err = store.Delete("admin", "alice"); err != nil {
t.Fatal(err)
}
if err = store.Create("alice", "alice-password", RoleUser); err != nil {
t.Fatal(err)
}
if _, err = store.ValidateToken("alice", alice.TokenVersion); err == nil {
t.Fatal("old token survived deletion and username reuse")
}
}
func TestConcurrentCreatesDoNotLoseUsers(t *testing.T) {
store := NewStore(filepath.Join(t.TempDir(), "pwd"))
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
const count = 5
var workers sync.WaitGroup
errorsCh := make(chan error, count)
for index := 0; index < count; index++ {
workers.Add(1)
go func(index int) {
defer workers.Done()
errorsCh <- store.Create(fmt.Sprintf("user%d", index), "valid-password", RoleUser)
}(index)
}
workers.Wait()
close(errorsCh)
for err := range errorsCh {
if err != nil {
t.Fatal(err)
}
}
users, err := store.List()
if err != nil {
t.Fatal(err)
}
if len(users) != count+1 {
t.Fatalf("got %d users, want %d", len(users), count+1)
}
}

View File

@@ -18,7 +18,10 @@ var (
kvmVisionOnce sync.Once
)
type KvmVision struct{}
type KvmVision struct {
mutex sync.RWMutex
closed bool
}
func GetKvmVision() *KvmVision {
kvmVisionOnce.Do(func() {
@@ -33,6 +36,12 @@ func GetKvmVision() *KvmVision {
}
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data []byte, result int) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return nil, -1
}
var (
kvmData *C.uint8_t
dataSize C.uint32_t
@@ -57,6 +66,12 @@ func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data
}
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, result int) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return nil, -1
}
var (
kvmData *C.uint8_t
dataSize C.uint32_t
@@ -81,6 +96,12 @@ func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data
}
func (k *KvmVision) SetHDMI(enable bool) int {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return -1
}
hdmiEnable := C.uint8_t(0)
if enable {
hdmiEnable = C.uint8_t(1)
@@ -95,17 +116,46 @@ func (k *KvmVision) SetHDMI(enable bool) int {
return result
}
func (k *KvmVision) HasHDMISignal() bool {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return false
}
return C.kvmv_hdmi_signal_active() != 0
}
func (k *KvmVision) SetGop(gop uint8) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return
}
_gop := C.uint8_t(gop)
C.set_h264_gop(_gop)
}
func (k *KvmVision) SetFrameDetect(frame uint8) {
k.mutex.RLock()
defer k.mutex.RUnlock()
if k.closed {
return
}
_frame := C.uint8_t(frame)
C.set_frame_detact(_frame)
}
func (k *KvmVision) Close() {
k.mutex.Lock()
defer k.mutex.Unlock()
if k.closed {
return
}
k.closed = true
C.kvmv_deinit()
log.Debugf("stop kvm vision...")
}

View File

@@ -7,13 +7,6 @@ import (
"time"
)
// RegenerateSecretKey regenerate secret key when logout
func RegenerateSecretKey() {
if instance.JWT.RevokeTokensOnLogout {
instance.JWT.SecretKey = generateRandomSecretKey()
}
}
// Generate random string for secret key.
func generateRandomSecretKey() string {
b := make([]byte, 64)

Binary file not shown.

View File

@@ -14,6 +14,7 @@ require (
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0
github.com/modelcontextprotocol/go-sdk v1.6.1
github.com/pion/dtls/v3 v3.1.2
github.com/pion/interceptor v0.1.39
github.com/pion/rtp v1.8.18
github.com/pion/webrtc/v4 v4.0.1
github.com/rs/cors/wrapper/gin v0.0.0-20240830163046-1084d89a1692
@@ -21,6 +22,7 @@ require (
github.com/spf13/viper v1.19.0
github.com/unrolled/secure v1.15.0
golang.org/x/crypto v0.45.0
golang.org/x/sys v0.41.0
gopkg.in/yaml.v3 v3.0.1
)
@@ -47,7 +49,6 @@ require (
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
github.com/pion/datachannel v1.5.9 // indirect
github.com/pion/ice/v4 v4.0.2 // indirect
github.com/pion/interceptor v0.1.39 // indirect
github.com/pion/logging v0.2.4 // indirect
github.com/pion/mdns/v2 v2.0.7 // indirect
github.com/pion/randutil v0.1.0 // indirect
@@ -79,7 +80,6 @@ require (
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sys v0.41.0 // indirect
golang.org/x/text v0.31.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect

View File

@@ -66,6 +66,7 @@ void set_h264_gop(uint8_t _gop);
void set_frame_detact(uint8_t _frame_detact);
void kvmv_deinit();
uint8_t kvmv_hdmi_control(uint8_t _en);
uint8_t kvmv_hdmi_signal_active(void);
#ifdef __cplusplus
}

View File

@@ -1,68 +1,160 @@
package middleware
import (
"context"
"errors"
"net/http"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/config"
)
const (
principalContextKey = "principal"
tokenContextKey = "token"
CookieName = "nano-kvm-token"
sessionRecheckDelay = 5 * time.Second
)
type Principal struct {
Username string
Role authn.Role
}
type Token struct {
Username string `json:"username"`
Username string `json:"username"`
TokenVersion uint64 `json:"tokenVersion"`
jwt.RegisteredClaims
}
func CheckToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByToken(c) {
principal, token, ok := authenticate(c)
if !ok {
abortUnauthorized(c)
return
}
c.Set(principalContextKey, principal)
c.Set(tokenContextKey, token)
if token == nil || token.ExpiresAt == nil {
c.Next()
return
}
abortUnauthorized(c)
requestContext, cancel := context.WithCancel(c.Request.Context())
c.Request = c.Request.WithContext(requestContext)
unregister := activeSessions.register(principal.Username, cancel)
timer := time.AfterFunc(time.Until(token.ExpiresAt.Time), cancel)
go watchSessionState(requestContext, cancel, principal.Username, token.TokenVersion, sessionRecheckDelay)
defer func() {
timer.Stop()
unregister()
cancel()
}()
c.Next()
}
}
func watchSessionState(ctx context.Context, cancel context.CancelFunc, username string, tokenVersion uint64, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if _, err := authn.DefaultStore.ValidateToken(username, tokenVersion); err != nil {
cancel()
return
}
}
}
}
func RequireRole(roles ...authn.Role) gin.HandlerFunc {
allowed := make(map[authn.Role]struct{}, len(roles))
for _, role := range roles {
allowed[role] = struct{}{}
}
return func(c *gin.Context) {
principal, ok := CurrentPrincipal(c)
if !ok {
abortUnauthorized(c)
return
}
if _, ok = allowed[principal.Role]; !ok {
c.JSON(http.StatusForbidden, "forbidden")
c.Abort()
return
}
c.Next()
}
}
func CurrentPrincipal(c *gin.Context) (Principal, bool) {
value, exists := c.Get(principalContextKey)
if !exists {
return Principal{}, false
}
principal, ok := value.(Principal)
return principal, ok
}
func CheckLoopbackInternalToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByLoopbackInternalToken(c.Request) {
c.Next()
return
}
abortUnauthorized(c)
}
}
func CheckTokenOrLoopbackInternalToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByToken(c) || allowByLoopbackInternalToken(c.Request) {
if allowByLoopbackInternalToken(c.Request) {
c.Next()
return
}
abortUnauthorized(c)
principal, token, ok := authenticate(c)
if !ok {
abortUnauthorized(c)
return
}
c.Set(principalContextKey, principal)
c.Set(tokenContextKey, token)
c.Next()
}
}
func allowByToken(c *gin.Context) bool {
func authenticate(c *gin.Context) (Principal, *Token, bool) {
conf := config.GetInstance()
if conf.Authentication == "disable" {
return true
return Principal{Username: "admin", Role: authn.RoleAdmin}, nil, true
}
cookie, err := c.Cookie("nano-kvm-token")
cookie, err := c.Cookie(CookieName)
if err != nil {
return false
return Principal{}, nil, false
}
_, err = ParseJWT(cookie)
return err == nil
token, err := ParseJWT(cookie)
if err != nil {
return Principal{}, nil, false
}
user, err := authn.DefaultStore.ValidateToken(token.Username, token.TokenVersion)
if err != nil {
log.Debugf("validate session for %q: %s", token.Username, err)
return Principal{}, nil, false
}
return Principal{Username: user.Username, Role: user.Role}, token, true
}
func abortUnauthorized(c *gin.Context) {
@@ -70,37 +162,44 @@ func abortUnauthorized(c *gin.Context) {
c.Abort()
}
func GenerateJWT(username string) (string, error) {
func GenerateJWT(username string, tokenVersion uint64) (string, error) {
conf := config.GetInstance()
now := time.Now()
expireDuration := time.Duration(conf.JWT.RefreshTokenDuration) * time.Second
claims := Token{
Username: username,
Username: username,
TokenVersion: tokenVersion,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
Subject: username,
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(expireDuration)),
},
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return t.SignedString([]byte(conf.JWT.SecretKey))
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(conf.JWT.SecretKey))
}
func ParseJWT(jwtToken string) (*Token, error) {
conf := config.GetInstance()
t, err := jwt.ParseWithClaims(jwtToken, &Token{}, func(token *jwt.Token) (interface{}, error) {
return []byte(conf.JWT.SecretKey), nil
})
parsed, err := jwt.ParseWithClaims(
jwtToken,
&Token{},
func(token *jwt.Token) (interface{}, error) {
if token.Method != jwt.SigningMethodHS256 {
return nil, errors.New("unexpected signing method")
}
return []byte(conf.JWT.SecretKey), nil
},
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Alg()}),
jwt.WithExpirationRequired(),
)
if err != nil {
log.Debugf("parse jwt error: %s", err)
return nil, err
}
if claims, ok := t.Claims.(*Token); ok && t.Valid {
return claims, nil
} else {
return nil, err
claims, ok := parsed.Claims.(*Token)
if !ok || !parsed.Valid || claims.Username == "" || claims.Subject != claims.Username || claims.TokenVersion == 0 {
return nil, errors.New("invalid token claims")
}
return claims, nil
}

View File

@@ -0,0 +1,230 @@
package middleware
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/gorilla/websocket"
)
func TestCheckTokenUsesLiveRoleAndVersion(t *testing.T) {
gin.SetMode(gin.TestMode)
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
admin, ok, err := store.Authenticate("admin", "admin")
if err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err = store.Create("alice", "valid-password", authn.RoleUser); err != nil {
t.Fatal(err)
}
alice, err := store.Get("alice")
if err != nil {
t.Fatal(err)
}
restore := useTestAuthStore(t, store)
defer restore()
adminToken, err := GenerateJWT(admin.Username, admin.TokenVersion)
if err != nil {
t.Fatal(err)
}
userToken, err := GenerateJWT(alice.Username, alice.TokenVersion)
if err != nil {
t.Fatal(err)
}
router := gin.New()
router.GET("/admin", CheckToken(), RequireRole(authn.RoleAdmin), func(c *gin.Context) {
c.Status(http.StatusNoContent)
})
if status := requestWithToken(router, "/admin", ""); status != http.StatusUnauthorized {
t.Fatalf("missing token status = %d", status)
}
if status := requestWithToken(router, "/admin", adminToken); status != http.StatusNoContent {
t.Fatalf("admin status = %d", status)
}
if status := requestWithToken(router, "/admin", userToken); status != http.StatusForbidden {
t.Fatalf("user status = %d", status)
}
if _, err = store.Revoke("admin"); err != nil {
t.Fatal(err)
}
if status := requestWithToken(router, "/admin", adminToken); status != http.StatusUnauthorized {
t.Fatalf("revoked status = %d", status)
}
}
func TestParseJWTRejectsOtherHMACMethods(t *testing.T) {
conf := config.GetInstance()
originalSecret := conf.JWT.SecretKey
conf.JWT.SecretKey = "test-secret"
defer func() { conf.JWT.SecretKey = originalSecret }()
now := time.Now()
claims := Token{
Username: "admin",
TokenVersion: 1,
RegisteredClaims: jwt.RegisteredClaims{
Subject: "admin",
ExpiresAt: jwt.NewNumericDate(now.Add(time.Hour)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS384, claims).SignedString([]byte(conf.JWT.SecretKey))
if err != nil {
t.Fatal(err)
}
if _, err = ParseJWT(token); err == nil {
t.Fatal("HS384 token was accepted")
}
}
func TestParseJWTRejectsExpiredToken(t *testing.T) {
conf := config.GetInstance()
originalSecret := conf.JWT.SecretKey
conf.JWT.SecretKey = "test-secret"
defer func() { conf.JWT.SecretKey = originalSecret }()
claims := Token{
Username: "admin",
TokenVersion: 1,
RegisteredClaims: jwt.RegisteredClaims{
Subject: "admin",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(conf.JWT.SecretKey))
if err != nil {
t.Fatal(err)
}
if _, err = ParseJWT(token); err == nil {
t.Fatal("expired token was accepted")
}
}
func TestRevokeUserSessionsCancelsActiveRequests(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
unregister := activeSessions.register("alice", cancel)
defer unregister()
RevokeUserSessions("alice")
select {
case <-ctx.Done():
case <-time.After(time.Second):
t.Fatal("active session was not cancelled")
}
}
func TestAccountFileResetCancelsActiveSession(t *testing.T) {
path := filepath.Join(t.TempDir(), "pwd")
store := authn.NewStore(path)
user, ok, err := store.Authenticate("admin", "admin")
if err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
restore := useTestAuthStore(t, store)
defer restore()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go watchSessionState(ctx, cancel, user.Username, user.TokenVersion, 10*time.Millisecond)
if err = os.Remove(path); err != nil {
t.Fatal(err)
}
select {
case <-ctx.Done():
case <-time.After(2 * time.Second):
t.Fatal("active session survived account-file reset")
}
}
func TestWatchWebSocketClosesRevokedConnection(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
connection, err := upgrader.Upgrade(writer, request, nil)
if err != nil {
return
}
defer connection.Close()
stop := WatchWebSocket(ctx, connection)
defer stop()
_, _, _ = connection.ReadMessage()
}))
defer server.Close()
wsURL := "ws" + server.URL[len("http"):]
connection, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatal(err)
}
defer connection.Close()
cancel()
_ = connection.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _, err = connection.ReadMessage()
if !websocket.IsCloseError(err, SessionRevokedCloseCode) {
t.Fatalf("close error = %v, want code %d", err, SessionRevokedCloseCode)
}
}
func TestCheckWebSocketOrigin(t *testing.T) {
tests := []struct {
origin string
host string
want bool
}{
{"", "kvm.local", true},
{"http://kvm.local", "kvm.local", true},
{"http://KVM.local", "kvm.local", true},
{"http://kvm.local:8080", "kvm.local:8080", true},
{"http://kvm.local:8081", "kvm.local:8080", false},
{"http://evil.example", "kvm.local", false},
}
for _, test := range tests {
request := httptest.NewRequest(http.MethodGet, "http://"+test.host+"/api/ws", nil)
request.Host = test.host
if test.origin != "" {
request.Header.Set("Origin", test.origin)
}
if got := CheckWebSocketOrigin(request); got != test.want {
t.Fatalf("origin %q host %q = %v, want %v", test.origin, test.host, got, test.want)
}
}
}
func requestWithToken(handler http.Handler, path, token string) int {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, path, nil)
request.AddCookie(&http.Cookie{Name: CookieName, Value: token})
handler.ServeHTTP(recorder, request)
return recorder.Code
}
func useTestAuthStore(t *testing.T, store *authn.Store) func() {
t.Helper()
originalStore := authn.DefaultStore
conf := config.GetInstance()
originalAuthentication := conf.Authentication
originalSecret := conf.JWT.SecretKey
originalDuration := conf.JWT.RefreshTokenDuration
authn.DefaultStore = store
conf.Authentication = "enable"
conf.JWT.SecretKey = "test-secret"
conf.JWT.RefreshTokenDuration = 3600
return func() {
authn.DefaultStore = originalStore
conf.Authentication = originalAuthentication
conf.JWT.SecretKey = originalSecret
conf.JWT.RefreshTokenDuration = originalDuration
}
}

View File

@@ -0,0 +1,123 @@
package middleware
import (
"context"
"net"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/websocket"
)
const SessionRevokedCloseCode = 4401
type sessionRegistry struct {
mutex sync.Mutex
nextID atomic.Uint64
byUserID map[string]map[uint64]context.CancelFunc
}
var activeSessions = &sessionRegistry{byUserID: make(map[string]map[uint64]context.CancelFunc)}
func (r *sessionRegistry) register(username string, cancel context.CancelFunc) func() {
id := r.nextID.Add(1)
r.mutex.Lock()
if r.byUserID[username] == nil {
r.byUserID[username] = make(map[uint64]context.CancelFunc)
}
r.byUserID[username][id] = cancel
r.mutex.Unlock()
return func() {
r.mutex.Lock()
delete(r.byUserID[username], id)
if len(r.byUserID[username]) == 0 {
delete(r.byUserID, username)
}
r.mutex.Unlock()
}
}
func RevokeUserSessions(username string) {
activeSessions.mutex.Lock()
sessions := activeSessions.byUserID[username]
delete(activeSessions.byUserID, username)
activeSessions.mutex.Unlock()
for _, cancel := range sessions {
cancel()
}
}
func WatchWebSocket(ctx context.Context, connection *websocket.Conn) func() {
stopped := make(chan struct{})
var stopOnce sync.Once
go func() {
select {
case <-ctx.Done():
_ = connection.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(SessionRevokedCloseCode, "session expired or revoked"),
time.Now().Add(2*time.Second),
)
_ = connection.Close()
case <-stopped:
}
}()
return func() { stopOnce.Do(func() { close(stopped) }) }
}
func CheckWebSocketOrigin(request *http.Request) bool {
origin := strings.TrimSpace(request.Header.Get("Origin"))
if origin == "" {
return true
}
parsed, err := url.Parse(origin)
if err != nil || parsed.Host == "" {
return false
}
requestScheme := "http"
if request.TLS != nil {
requestScheme = "https"
}
if forwarded := strings.TrimSpace(strings.Split(request.Header.Get("X-Forwarded-Proto"), ",")[0]); forwarded != "" {
requestScheme = strings.ToLower(forwarded)
}
return equalOrigin(parsed, request.Host, requestScheme)
}
func equalOrigin(origin *url.URL, requestHost, requestScheme string) bool {
originHost, originPort := splitHostPort(origin.Host)
host, port := splitHostPort(requestHost)
if !strings.EqualFold(originHost, host) {
return false
}
if originPort == "" {
originPort = defaultPort(origin.Scheme)
}
if port == "" {
port = defaultPort(requestScheme)
}
return originPort == port
}
func splitHostPort(value string) (string, string) {
host, port, err := net.SplitHostPort(value)
if err == nil {
return host, port
}
return strings.Trim(value, "[]"), ""
}
func defaultPort(scheme string) string {
switch strings.ToLower(scheme) {
case "https", "wss":
return "443"
default:
return "80"
}
}

View File

@@ -12,3 +12,13 @@ type GetPreviewRsp struct {
type SetPreviewReq struct {
Enable bool `validate:"omitempty"`
}
type GetUpdateServerRsp struct {
Enabled bool `json:"enabled"`
URL string `json:"url"`
}
type SetUpdateServerReq struct {
Enabled *bool `json:"enabled" form:"enabled" validate:"required"`
URL string `json:"url" form:"url"`
}

View File

@@ -5,19 +5,38 @@ type LoginReq struct {
Password string `validate:"required"`
}
type LoginRsp struct {
Token string `json:"token"`
}
type GetAccountRsp struct {
Username string `json:"username"`
Role string `json:"role"`
}
type ChangePasswordReq struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
CurrentPassword string `json:"currentPassword"`
Password string `json:"password" validate:"required"`
}
type IsPasswordUpdatedRsp struct {
IsUpdated bool `json:"isUpdated"`
}
type UserInfo struct {
Username string `json:"username"`
Role string `json:"role"`
Enabled bool `json:"enabled"`
SystemAccount bool `json:"systemAccount,omitempty"`
}
type ListUsersRsp struct {
Users []UserInfo `json:"users"`
}
type CreateUserReq struct {
Username string `json:"username" validate:"required"`
Password string `json:"password" validate:"required"`
Role string `json:"role" validate:"required"`
}
type UpdateUserReq struct {
Role *string `json:"role"`
Enabled *bool `json:"enabled"`
}

View File

@@ -20,7 +20,7 @@ func ValidateRequest(req interface{}) error {
}
if env == "" || env == "debug" {
log.Debugf("request: %+v\n", req)
log.Debugf("request validated: %T", req)
}
return nil

View File

@@ -99,6 +99,7 @@ type GetOLEDRsp struct {
type GetGetHdmiStateRsp struct {
Enabled bool `json:"enabled"`
Signal bool `json:"signal"`
IdleTimeout int `json:"idleTimeout"`
}
@@ -151,3 +152,54 @@ type GetWebTitleRsp struct {
type SetTlsReq struct {
Enabled bool `validate:"omitempty"`
}
type InputRegion struct {
Mode string `json:"mode"`
FrameWidth int `json:"frameWidth"`
FrameHeight int `json:"frameHeight"`
Left int `json:"left"`
Top int `json:"top"`
Width int `json:"width"`
Height int `json:"height"`
Resolutions []OriginalResolution `json:"resolutions,omitempty"`
SelectedResolution string `json:"selectedResolution"`
Regions []ManualRegion `json:"regions,omitempty"`
SelectedRegion string `json:"selectedRegion"`
}
type ManualRegion struct {
FrameWidth int `json:"frameWidth"`
FrameHeight int `json:"frameHeight"`
Left int `json:"left"`
Top int `json:"top"`
Width int `json:"width"`
Height int `json:"height"`
}
type OriginalResolution struct {
Width int `json:"width"`
Height int `json:"height"`
}
type SetInputRegionReq struct {
Mode string `json:"mode"`
FrameWidth *int `json:"frameWidth,omitempty"`
FrameHeight *int `json:"frameHeight,omitempty"`
Left *int `json:"left,omitempty"`
Top *int `json:"top,omitempty"`
Width *int `json:"width,omitempty"`
Height *int `json:"height,omitempty"`
Resolutions *[]OriginalResolution `json:"resolutions,omitempty"`
SelectedResolution *string `json:"selectedResolution,omitempty"`
Regions *[]ManualRegion `json:"regions,omitempty"`
SelectedRegion *string `json:"selectedRegion,omitempty"`
}
type GetInputRegionRsp struct {
InputRegion
}
type GetInputResolutionRsp struct {
Width int `json:"width"`
Height int `json:"height"`
}

View File

@@ -1,6 +1,7 @@
package router
import (
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/application"
@@ -9,7 +10,7 @@ import (
func applicationRouter(r *gin.Engine) {
service := application.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api := r.Group("/api").Use(middleware.CheckToken(), middleware.RequireRole(authn.RoleAdmin))
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
@@ -17,4 +18,7 @@ func applicationRouter(r *gin.Engine) {
api.GET("/application/preview", service.GetPreview) // get preview updates state
api.POST("/application/preview", service.SetPreview) // set preview updates state
api.GET("/application/update-server", service.GetUpdateServer) // get custom update server
api.POST("/application/update-server", service.SetUpdateServer) // set custom update server
}

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/auth"
)
@@ -18,4 +19,14 @@ func authRouter(r *gin.Engine) {
api.GET("/auth/account", service.GetAccount) // get account
api.POST("/auth/password", service.ChangePassword) // change password
api.POST("/auth/logout", service.Logout) // logout
admin := r.Group("/api").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
admin.GET("/auth/users", service.ListUsers)
admin.POST("/auth/users", service.CreateUser)
admin.PUT("/auth/users/:username", service.UpdateUser)
admin.DELETE("/auth/users/:username", service.DeleteUser)
admin.POST("/auth/users/:username/password", service.ChangeUserPassword)
}

View File

@@ -4,6 +4,7 @@ import (
"net/http"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/hid"
@@ -19,7 +20,10 @@ type setAIControlModeRequest struct {
}
func controlRouter(r *gin.Engine, control *controlmode.Manager, picoclawService *picoclaw.Service) {
group := r.Group("/api/ai/control").Use(middleware.CheckToken())
group := r.Group("/api/ai/control").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
group.GET("/status", func(c *gin.Context) {
status, err := control.Status()
if err != nil {

View File

@@ -1,6 +1,7 @@
package router
import (
"NanoKVM-Server/authn"
"NanoKVM-Server/service/download"
"github.com/gin-gonic/gin"
@@ -9,7 +10,7 @@ import (
func downloadRouter(r *gin.Engine) {
service := download.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api := r.Group("/api").Use(middleware.CheckToken(), middleware.RequireRole(authn.RoleAdmin))
api.POST("/download/image", service.DownloadImage) // download image
api.POST("/download/image/cancel", service.CancelDownloadImage) // cancel image download

View File

@@ -1,6 +1,7 @@
package router
import (
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/extensions/tailscale"
@@ -8,7 +9,10 @@ import (
)
func extensionsRouter(r *gin.Engine) {
api := r.Group("/api/extensions").Use(middleware.CheckToken())
api := r.Group("/api/extensions").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
ts := tailscale.NewService()

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/hid"
)
@@ -20,17 +21,21 @@ func hidRouter(r *gin.Engine) {
api.POST("/hid/paste", service.Paste) // paste
api.GET("/hid/shortcuts", service.GetShortcuts) // get shortcuts
api.POST("/hid/shortcut", service.AddShortcut) // add shortcut
api.DELETE("/hid/shortcut", service.DeleteShortcut) // delete shortcut
api.GET("/hid/shortcuts", service.GetShortcuts) // get shortcuts
api.GET("/hid/shortcut/leader-key", service.GetLeaderKey) // get shortcut leader key
api.GET("/hid/shortcut/leader-key", service.GetLeaderKey) // set shortcut leader key
api.POST("/hid/shortcut/leader-key", service.SetLeaderKey) // set shortcut leader key
api.GET("/hid/mode", service.GetHidMode) // get hid mode
api.POST("/hid/mode", service.SetHidMode) // set hid mode
api.POST("/hid/reset", service.ResetHid) // reset hid
api.GET("/hid/mode", service.GetHidMode) // get hid mode
api.GET("/hid/leds", service.GetKeyboardLedStatus)
admin := r.Group("/api").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
admin.POST("/hid/mode", service.SetHidMode) // set hid mode
admin.POST("/hid/reset", service.ResetHid) // reset hid
admin.POST("/hid/shortcut", service.AddShortcut)
admin.DELETE("/hid/shortcut", service.DeleteShortcut)
admin.POST("/hid/shortcut/leader-key", service.SetLeaderKey)
localAPI.POST("/usb/recover", service.RecoverUSB)
}

View File

@@ -3,6 +3,7 @@ package router
import (
"net/http"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/hid"
@@ -23,7 +24,10 @@ func mcpRouter(r *gin.Engine, control *controlmode.Manager, picoclawService *pic
picoclawService.PublishControlModeChangedFrom(status, "mcp_config")
},
)
management := r.Group("/api/mcp").Use(middleware.CheckToken())
management := r.Group("/api/mcp").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
management.GET("/config", service.GetConfig)
management.POST("/config", service.SetConfig)
management.POST("/key/regenerate", service.RegenerateAPIKey)

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/network"
)
@@ -15,15 +16,19 @@ func networkRouter(r *gin.Engine) {
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
api.GET("/network/wol/mac", service.GetMac) // get mac list
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
api.POST("/network/wol/mac/name", service.SetMacName) // set mac name
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
api.GET("/network/wol/mac", service.GetMac) // get mac list
api.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
api.POST("/network/wifi/connect", service.ConnectWifi) // connect Wi-Fi
api.POST("/network/wifi/disconnect", service.DisconnectWifi) // disconnect Wi-Fi
admin := r.Group("/api").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
admin.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
admin.POST("/network/wol/mac/name", service.SetMacName) // set mac name
api.GET("/network/dns", service.GetDNS) // get DNS configuration
api.POST("/network/dns", service.SetDNS) // set DNS configuration
admin.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
admin.POST("/network/wifi/connect", service.ConnectWifi) // connect Wi-Fi
admin.POST("/network/wifi/disconnect", service.DisconnectWifi) // disconnect Wi-Fi
admin.GET("/network/dns", service.GetDNS) // get DNS configuration
admin.POST("/network/dns", service.SetDNS) // set DNS configuration
}

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/picoclaw"
)
@@ -39,7 +40,10 @@ func PicoclawLoopbackHTTPAllowedPaths() []string {
}
func picoclawRouter(r *gin.Engine, service *picoclaw.Service) {
frontendAPI := r.Group(picoclawBasePath).Use(middleware.CheckToken())
frontendAPI := r.Group(picoclawBasePath).Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
localAPI := r.Group(picoclawBasePath).Use(middleware.CheckLoopbackInternalToken())
localAPI.GET(picoclawScreenshotPath, service.Screenshot)

View File

@@ -3,13 +3,14 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/storage"
)
func storageRouter(r *gin.Engine) {
service := storage.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api := r.Group("/api").Use(middleware.CheckToken(), middleware.RequireRole(authn.RoleAdmin))
api.GET("/storage/image", service.GetImages) // get image list
api.GET("/storage/image/mounted", service.GetMountedImage) // get mounted image

View File

@@ -3,6 +3,7 @@ package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/vm"
)
@@ -11,6 +12,10 @@ func vmRouter(r *gin.Engine) {
service := vm.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
admin := r.Group("/api").Use(
middleware.CheckToken(),
middleware.RequireRole(authn.RoleAdmin),
)
api.GET("/vm/info", service.GetInfo) // get device information
api.GET("/vm/hardware", service.GetHardware) // get hardware version
@@ -19,55 +24,59 @@ func vmRouter(r *gin.Engine) {
api.GET("/vm/gpio", service.GetGpio) // get gpio
api.POST("/vm/screen", service.SetScreen) // update screen
api.GET("/vm/terminal", service.Terminal) // web terminal
api.GET("/vm/input-region", service.GetInputRegion)
api.POST("/vm/input-region", service.SetInputRegion)
api.GET("/vm/input-resolution", service.GetInputResolution)
api.GET("/vm/script", service.GetScripts) // get script
api.POST("/vm/script/upload", service.UploadScript) // upload script
api.POST("/vm/script/run", service.RunScript) // run script
api.DELETE("/vm/script", service.DeleteScript) // delete script
admin.GET("/vm/terminal", service.Terminal) // web terminal
api.GET("/vm/device/virtual", service.GetVirtualDevice) // get virtual device
api.POST("/vm/device/virtual", service.UpdateVirtualDevice) // update virtual device
admin.GET("/vm/script", service.GetScripts) // get script
admin.POST("/vm/script/upload", service.UploadScript) // upload script
admin.POST("/vm/script/run", service.RunScript) // run script
admin.DELETE("/vm/script", service.DeleteScript) // delete script
api.GET("/vm/memory/limit", service.GetMemoryLimit) // get memory limit
api.POST("/vm/memory/limit", service.SetMemoryLimit) // set memory limit
admin.GET("/vm/device/virtual", service.GetVirtualDevice) // get virtual device
admin.POST("/vm/device/virtual", service.UpdateVirtualDevice) // update virtual device
api.GET("/vm/oled", service.GetOLED) // get OLED configuration
api.POST("/vm/oled", service.SetOLED) // set OLED configuration
admin.GET("/vm/memory/limit", service.GetMemoryLimit) // get memory limit
admin.POST("/vm/memory/limit", service.SetMemoryLimit) // set memory limit
admin.GET("/vm/oled", service.GetOLED) // get OLED configuration
admin.POST("/vm/oled", service.SetOLED) // set OLED configuration
// Only supported by PCIe version
api.GET("/vm/hdmi", service.GetHdmiState) // get HDMI state
api.POST("/vm/hdmi/reset", service.ResetHdmi) // reset hdmi
api.POST("/vm/hdmi/enable", service.EnableHdmi) // enable hdmi
api.POST("/vm/hdmi/disable", service.DisableHdmi) // disable hdmi
api.POST("/vm/hdmi/timeout", service.SetHdmiIdleTimeout)
api.GET("/vm/hdmi", service.GetHdmiState) // get HDMI state
api.POST("/vm/hdmi/reset", service.ResetHdmi) // reset hdmi
admin.POST("/vm/hdmi/enable", service.EnableHdmi) // enable hdmi
admin.POST("/vm/hdmi/disable", service.DisableHdmi) // disable hdmi
admin.POST("/vm/hdmi/timeout", service.SetHdmiIdleTimeout)
api.GET("/vm/ssh", service.GetSSHState) // get SSH state
api.POST("/vm/ssh/enable", service.EnableSSH) // enable SSH
api.POST("/vm/ssh/disable", service.DisableSSH) // disable SSH
admin.GET("/vm/ssh", service.GetSSHState) // get SSH state
admin.POST("/vm/ssh/enable", service.EnableSSH) // enable SSH
admin.POST("/vm/ssh/disable", service.DisableSSH) // disable SSH
api.GET("/vm/swap", service.GetSwap) // get swap file size
api.POST("/vm/swap", service.SetSwap) // set swap file size
admin.GET("/vm/swap", service.GetSwap) // get swap file size
admin.POST("/vm/swap", service.SetSwap) // set swap file size
api.GET("/vm/mouse-jiggler", service.GetMouseJiggler) // get mouse jiggler
api.POST("/vm/mouse-jiggler/", service.SetMouseJiggler) // set mouse jiggler
admin.GET("/vm/mouse-jiggler", service.GetMouseJiggler) // get mouse jiggler
admin.POST("/vm/mouse-jiggler/", service.SetMouseJiggler) // set mouse jiggler
api.GET("/vm/hostname", service.GetHostname) // Get Hostname
api.POST("/vm/hostname", service.SetHostname) // Set Hostname
api.GET("/vm/hostname", service.GetHostname) // Get Hostname
admin.POST("/vm/hostname", service.SetHostname) // Set Hostname
api.GET("/vm/web-title", service.GetWebTitle) // Get web title
api.POST("/vm/web-title", service.SetWebTitle) // Set web title
api.GET("/vm/web-title", service.GetWebTitle) // Get web title
admin.POST("/vm/web-title", service.SetWebTitle) // Set web title
api.GET("/vm/mdns", service.GetMdnsState) // get mDNS state
api.POST("/vm/mdns/enable", service.EnableMdns) // enable mDNS
api.POST("/vm/mdns/disable", service.DisableMdns) // disable mDNS
admin.GET("/vm/mdns", service.GetMdnsState) // get mDNS state
admin.POST("/vm/mdns/enable", service.EnableMdns) // enable mDNS
admin.POST("/vm/mdns/disable", service.DisableMdns) // disable mDNS
api.POST("/vm/tls", service.SetTls) // enable/disable TLS
admin.POST("/vm/tls", service.SetTls) // enable/disable TLS
api.GET("/vm/autostart", service.GetAutostart) // get autostart list
api.GET("/vm/autostart/:name", service.GetAutostartContent) // get autostart content
api.DELETE("/vm/autostart/:name", service.DeleteAutostart) // delete autostart script
api.POST("/vm/autostart/:name", service.UploadAutostart) // upload autostart script
admin.GET("/vm/autostart", service.GetAutostart) // get autostart list
admin.GET("/vm/autostart/:name", service.GetAutostartContent) // get autostart content
admin.DELETE("/vm/autostart/:name", service.DeleteAutostart) // delete autostart script
admin.POST("/vm/autostart/:name", service.UploadAutostart) // upload autostart script
api.POST("/vm/system/reboot", service.Reboot) // reboot system
admin.POST("/vm/system/reboot", service.Reboot) // reboot system
}

View File

@@ -0,0 +1,203 @@
package application
import (
"archive/tar"
"compress/gzip"
"errors"
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"strings"
)
type updateArchiveInfo struct {
root string
expandedBytes uint64
entries int
}
func inspectUpdateArchive(archivePath, expectedRoot string) (updateArchiveInfo, error) {
file, err := os.Open(archivePath)
if err != nil {
return updateArchiveInfo{}, err
}
defer file.Close()
reader, err := gzip.NewReader(file)
if err != nil {
return updateArchiveInfo{}, fmt.Errorf("open gzip archive: %w", err)
}
defer reader.Close()
info := updateArchiveInfo{root: expectedRoot}
seen := make(map[string]struct{})
hasRoot, hasVersion := false, false
tarReader := tar.NewReader(reader)
for {
header, err := tarReader.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return updateArchiveInfo{}, fmt.Errorf("read tar archive: %w", err)
}
name, err := validateArchiveHeader(header, expectedRoot)
if err != nil {
return updateArchiveInfo{}, err
}
if _, ok := seen[name]; ok {
return updateArchiveInfo{}, fmt.Errorf("duplicate archive entry %q", name)
}
seen[name] = struct{}{}
info.entries++
if info.entries > maxArchiveEntries {
return updateArchiveInfo{}, fmt.Errorf("update archive has more than %d entries", maxArchiveEntries)
}
if name == expectedRoot && header.Typeflag == tar.TypeDir {
hasRoot = true
}
if name == expectedRoot+"/version" && isRegularType(header.Typeflag) {
hasVersion = true
}
if isRegularType(header.Typeflag) {
if header.Size < 0 {
return updateArchiveInfo{}, fmt.Errorf("negative archive file size")
}
size := uint64(header.Size)
if size > maxExpandedSize-info.expandedBytes {
return updateArchiveInfo{}, fmt.Errorf("update archive expanded size exceeds %d bytes", maxExpandedSize)
}
if info.expandedBytes > math.MaxUint64-size {
return updateArchiveInfo{}, fmt.Errorf("update archive expanded size overflow")
}
info.expandedBytes += size
}
}
if !hasRoot {
return updateArchiveInfo{}, fmt.Errorf("invalid update package layout: missing top-level directory")
}
if !hasVersion {
return updateArchiveInfo{}, fmt.Errorf("invalid update package layout: missing version file")
}
return info, nil
}
func extractUpdateArchive(archivePath, destDir, expectedRoot string) (string, error) {
file, err := os.Open(archivePath)
if err != nil {
return "", err
}
defer file.Close()
reader, err := gzip.NewReader(file)
if err != nil {
return "", fmt.Errorf("open gzip archive: %w", err)
}
defer reader.Close()
seen := make(map[string]struct{})
entries := 0
expanded := uint64(0)
tarReader := tar.NewReader(reader)
for {
header, err := tarReader.Next()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return "", fmt.Errorf("read tar archive: %w", err)
}
name, err := validateArchiveHeader(header, expectedRoot)
if err != nil {
return "", err
}
if _, ok := seen[name]; ok {
return "", fmt.Errorf("duplicate archive entry %q", name)
}
seen[name] = struct{}{}
entries++
if entries > maxArchiveEntries {
return "", fmt.Errorf("update archive has more than %d entries", maxArchiveEntries)
}
filename := filepath.Join(destDir, filepath.FromSlash(name))
switch header.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(filename, 0o755); err != nil {
return "", fmt.Errorf("create archive directory: %w", err)
}
case tar.TypeReg, tar.TypeRegA:
if header.Size < 0 {
return "", fmt.Errorf("negative archive file size")
}
size := uint64(header.Size)
if size > maxExpandedSize-expanded {
return "", fmt.Errorf("update archive expanded size exceeds %d bytes", maxExpandedSize)
}
expanded += size
if err := os.MkdirAll(filepath.Dir(filename), 0o755); err != nil {
return "", fmt.Errorf("create archive parent directory: %w", err)
}
out, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, os.FileMode(header.Mode)&0o777)
if err != nil {
return "", fmt.Errorf("create archive file: %w", err)
}
written, copyErr := io.CopyN(out, tarReader, header.Size)
closeErr := out.Close()
if copyErr != nil {
return "", fmt.Errorf("write archive file: %w", copyErr)
}
if written != header.Size {
return "", fmt.Errorf("truncated archive file %q", name)
}
if closeErr != nil {
return "", fmt.Errorf("close archive file: %w", closeErr)
}
}
}
return filepath.Join(destDir, expectedRoot), nil
}
func validateArchiveHeader(header *tar.Header, expectedRoot string) (string, error) {
if header.Name == "" || path.IsAbs(header.Name) {
return "", fmt.Errorf("invalid archive path %q", header.Name)
}
name := path.Clean(header.Name)
if name == "." || name == ".." || strings.HasPrefix(name, "../") {
return "", fmt.Errorf("invalid archive path %q", header.Name)
}
if name != expectedRoot && !strings.HasPrefix(name, expectedRoot+"/") {
return "", fmt.Errorf("invalid update package layout: entry %q is outside %s", header.Name, expectedRoot)
}
if !isRegularType(header.Typeflag) && header.Typeflag != tar.TypeDir {
return "", fmt.Errorf("unsupported archive entry type for %q", header.Name)
}
return name, nil
}
func isRegularType(typeFlag byte) bool {
return typeFlag == tar.TypeReg || typeFlag == tar.TypeRegA
}
func validateExtractedPackage(rootDir, expectedVersion string) error {
version, err := os.ReadFile(filepath.Join(rootDir, "version"))
if err != nil {
return fmt.Errorf("invalid update package layout: read version: %w", err)
}
if strings.TrimSpace(string(version)) != expectedVersion {
return fmt.Errorf("invalid update package layout: version mismatch")
}
for _, required := range []string{
"version",
"server/NanoKVM-Server",
"kvm_system/kvm_system",
"system/init.d/S95nanokvm",
} {
info, err := os.Stat(filepath.Join(rootDir, filepath.FromSlash(required)))
if err != nil || !info.Mode().IsRegular() {
return fmt.Errorf("invalid update package layout: missing required file %s", required)
}
}
return nil
}

View File

@@ -0,0 +1,90 @@
package application
import (
"archive/tar"
"compress/gzip"
"os"
"path/filepath"
"testing"
)
type archiveEntry struct {
name string
typeFlag byte
data string
}
func writeTestArchive(t *testing.T, entries []archiveEntry) string {
t.Helper()
file := filepath.Join(t.TempDir(), "update.tar.gz")
out, err := os.Create(file)
if err != nil {
t.Fatal(err)
}
gzipWriter := gzip.NewWriter(out)
tarWriter := tar.NewWriter(gzipWriter)
for _, entry := range entries {
header := &tar.Header{Name: entry.name, Typeflag: entry.typeFlag, Mode: 0o755}
if entry.typeFlag == tar.TypeReg || entry.typeFlag == tar.TypeRegA {
header.Size = int64(len(entry.data))
}
if err := tarWriter.WriteHeader(header); err != nil {
t.Fatal(err)
}
if entry.data != "" {
if _, err := tarWriter.Write([]byte(entry.data)); err != nil {
t.Fatal(err)
}
}
}
if err := tarWriter.Close(); err != nil {
t.Fatal(err)
}
if err := gzipWriter.Close(); err != nil {
t.Fatal(err)
}
if err := out.Close(); err != nil {
t.Fatal(err)
}
return file
}
func TestInspectArchiveRejectsUnsafeEntries(t *testing.T) {
root := "nanokvm_1.2.3"
for _, entry := range []archiveEntry{
{name: "../escape", typeFlag: tar.TypeReg, data: "x"},
{name: "/escape", typeFlag: tar.TypeReg, data: "x"},
{name: root + "/link", typeFlag: tar.TypeSymlink},
} {
archive := writeTestArchive(t, []archiveEntry{{name: root, typeFlag: tar.TypeDir}, entry})
if _, err := inspectUpdateArchive(archive, root); err == nil {
t.Fatalf("unsafe entry %+v was accepted", entry)
}
}
}
func TestInspectAndExtractArchive(t *testing.T) {
root := "nanokvm_1.2.3"
archive := writeTestArchive(t, []archiveEntry{
{name: root, typeFlag: tar.TypeDir},
{name: root + "/version", typeFlag: tar.TypeReg, data: "1.2.3\n"},
{name: root + "/server/NanoKVM-Server", typeFlag: tar.TypeReg, data: "server"},
{name: root + "/kvm_system/kvm_system", typeFlag: tar.TypeReg, data: "system"},
{name: root + "/system/init.d/S95nanokvm", typeFlag: tar.TypeReg, data: "init"},
})
info, err := inspectUpdateArchive(archive, root)
if err != nil {
t.Fatal(err)
}
if info.expandedBytes != 22 { // data totals: 6 + 6 + 6 + 4
t.Fatalf("unexpected expanded size %d", info.expandedBytes)
}
destination := t.TempDir()
extracted, err := extractUpdateArchive(archive, destination, root)
if err != nil {
t.Fatal(err)
}
if err := validateExtractedPackage(extracted, "1.2.3"); err != nil {
t.Fatal(err)
}
}

View File

@@ -31,17 +31,12 @@ func releaseUpdateLock() {
isUpdating = false
}
func installPackage(source string) error {
dir, err := utils.UnTarGz(source, CacheDir)
if err != nil {
return fmt.Errorf("failed to decompress app: %w", err)
}
func installPreparedPackage(sourceDir string) error {
if err := backupCurrentApp(); err != nil {
return err
}
if err := applyUpdate(dir); err != nil {
if err := applyUpdate(sourceDir); err != nil {
return err
}

View File

@@ -7,11 +7,13 @@ import (
"strings"
"time"
"NanoKVM-Server/utils"
log "github.com/sirupsen/logrus"
)
const (
sentinelPath = "/tmp/.download_in_progress"
sentinelPath = utils.TransferSentinelPath
tickerInterval = 2500 * time.Millisecond
sentinelPermission = 0644
)

View File

@@ -7,6 +7,14 @@ const (
AppDir = "/kvmapp"
BackupDir = "/root/old"
CacheDir = "/root/.kvmcache"
updateWorkspacePrefix = "nanokvm-update-"
cacheDirMode = 0o700
maxPackageSize = uint64(1 << 30)
maxExpandedSize = uint64(2 << 30)
maxArchiveEntries = 100_000
minFreeReserve = uint64(128 << 20)
freeReservePercent = uint64(5)
)
type Service struct{}

View File

@@ -0,0 +1,103 @@
package application
import (
"errors"
"fmt"
"math"
"os"
"path/filepath"
"golang.org/x/sys/unix"
)
var ErrInsufficientStorage = errors.New("insufficient storage")
type filesystemSpace struct {
total uint64
available uint64
}
func getFilesystemSpace(path string) (filesystemSpace, error) {
var stat unix.Statfs_t
if err := unix.Statfs(path, &stat); err != nil {
return filesystemSpace{}, fmt.Errorf("stat filesystem %s: %w", path, err)
}
return filesystemSpaceFromStats(uint64(stat.Blocks), uint64(stat.Bavail), uint64(stat.Bsize))
}
func filesystemSpaceFromStats(blocks, availableBlocks, blockSize uint64) (filesystemSpace, error) {
if blockSize != 0 && (blocks > math.MaxUint64/blockSize || availableBlocks > math.MaxUint64/blockSize) {
return filesystemSpace{}, fmt.Errorf("filesystem size overflow")
}
return filesystemSpace{total: blocks * blockSize, available: availableBlocks * blockSize}, nil
}
func reserveBytes(total uint64) uint64 {
percent := total / 100 * freeReservePercent
percent += total % 100 * freeReservePercent / 100
if percent > minFreeReserve {
return percent
}
return minFreeReserve
}
func hasFreeSpace(space filesystemSpace, payload uint64) (bool, uint64, error) {
reserve := reserveBytes(space.total)
if payload > math.MaxUint64-reserve {
return false, 0, fmt.Errorf("storage requirement overflow")
}
required := payload + reserve
return space.available >= required, required, nil
}
func ensureFreeSpace(path string, payloadBytes uint64) error {
space, err := getFilesystemSpace(path)
if err != nil {
return err
}
ok, required, err := hasFreeSpace(space, payloadBytes)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("%w: need %d MiB including reserve, %d MiB available on %s", ErrInsufficientStorage, required>>20, space.available>>20, path)
}
return nil
}
func ensureExpandedSpace(path string, expandedBytes uint64) error {
// Keep the last known-good backup until the new package is fully prepared.
// Reclaiming it here can leave the device without rollback material even
// when extraction later fails or the reclaimed space is still insufficient.
return ensureFreeSpace(path, expandedBytes)
}
func ensureInstallFilesystem(workspaceDir, appDir, backupDir string) error {
backupPath := backupDir
if _, err := os.Stat(backupPath); err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("stat backup path %s: %w", backupPath, err)
}
backupPath = filepath.Dir(backupPath)
}
// AppDir already exists (prepareCacheForUpdate verifies it), so stat the
// directory itself. Its parent can be on another filesystem when AppDir is
// a mount point.
paths := []string{workspaceDir, appDir, backupPath}
var device uint64
for i, path := range paths {
var stat unix.Stat_t
if err := unix.Stat(path, &stat); err != nil {
return fmt.Errorf("stat install filesystem %s: %w", path, err)
}
if i == 0 {
device = uint64(stat.Dev)
continue
}
if uint64(stat.Dev) != device {
return fmt.Errorf("update workspace, application and backup must be on the same filesystem")
}
}
return nil
}

View File

@@ -0,0 +1,46 @@
package application
import (
"math"
"path/filepath"
"testing"
)
func TestReserveBytesAndSpaceBoundary(t *testing.T) {
if got := reserveBytes(1 << 30); got != minFreeReserve {
t.Fatalf("reserve for 1 GiB = %d, want %d", got, minFreeReserve)
}
if got := reserveBytes(4 << 30); got != 214748364 {
t.Fatalf("reserve for 4 GiB = %d, want 214748364", got)
}
space := filesystemSpace{total: 1 << 30, available: (1 << 20) + minFreeReserve}
ok, required, err := hasFreeSpace(space, 1<<20)
if err != nil || !ok || required != space.available {
t.Fatalf("boundary should fit: ok=%v required=%d err=%v", ok, required, err)
}
space.available--
ok, _, err = hasFreeSpace(space, 1<<20)
if err != nil || ok {
t.Fatalf("one byte short should fail: ok=%v err=%v", ok, err)
}
}
func TestStorageOverflowIsRejected(t *testing.T) {
if _, err := filesystemSpaceFromStats(math.MaxUint64, 1, 2); err == nil {
t.Fatal("expected filesystem overflow")
}
if _, _, err := hasFreeSpace(filesystemSpace{total: 1}, math.MaxUint64); err == nil {
t.Fatal("expected requirement overflow")
}
}
func TestInstallFilesystemChecksAppMountPoint(t *testing.T) {
workspace := t.TempDir()
backup := filepath.Join(t.TempDir(), "backup")
// /proc is a mount point whose parent is /. Checking filepath.Dir(appDir)
// would therefore miss the cross-filesystem layout on a normal Linux host.
if err := ensureInstallFilesystem(workspace, "/proc", backup); err == nil {
t.Fatal("separate application mount point was accepted")
}
}

View File

@@ -8,6 +8,8 @@ import (
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/gin-gonic/gin"
@@ -28,9 +30,9 @@ func (s *Service) Update(c *gin.Context) {
rsp.ErrRsp(c, -1, "update already in progress")
return
}
defer releaseUpdateLock()
if err := update(); err != nil {
releaseUpdateLock()
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
return
}
@@ -38,40 +40,75 @@ func (s *Service) Update(c *gin.Context) {
rsp.OkRsp(c)
log.Debugf("update application success")
// Sleep for a second before restarting the device
go restartServices()
}
func restartServices() {
// Let the HTTP response reach the client before stopping the server.
time.Sleep(1 * time.Second)
_ = exec.Command("sh", "-c", "/etc/init.d/S95nanokvm restart").Run()
if err := exec.Command("/kvmapp/system/init.d/S95nanokvm", "restart").Run(); err != nil {
log.Errorf("failed to restart services after update: %v", err)
}
}
func update() error {
_ = os.RemoveAll(CacheDir)
_ = os.MkdirAll(CacheDir, 0o755)
defer func() {
_ = os.RemoveAll(CacheDir)
}()
// get latest information
latest, err := getLatest()
if err != nil {
return err
}
// download
target := fmt.Sprintf("%s/%s", CacheDir, latest.Name)
if err := download(latest.Url, target); err != nil {
log.Errorf("download app failed: %s", err)
if err := prepareCacheForUpdate(); err != nil {
return err
}
workspace, err := newUpdateWorkspace(CacheDir)
if err != nil {
return err
}
defer func() {
if err := workspace.Close(); err != nil {
log.Warnf("failed to clean update workspace %s: %v", workspace.dir, err)
}
}()
if err := ensureInstallFilesystem(workspace.dir, AppDir, BackupDir); err != nil {
return err
}
if err := preflightManifestSpace(workspace.dir, latest); err != nil {
return err
}
target := filepath.Join(workspace.dir, latest.Name)
downloadInfo, err := download(latest, target)
if err != nil {
log.Errorf("download app failed: %s", err)
return err
}
if err := validateDownloadedSize(latest, uint64(downloadInfo.Written)); err != nil {
return err
}
// check sha512
if err := checksum(target, latest.Sha512); err != nil {
log.Errorf("check sha512 failed: %s", err)
return err
}
// install
if err := installPackage(target); err != nil {
expectedRoot := strings.TrimSuffix(latest.Name, ".tar.gz")
info, err := inspectUpdateArchive(target, expectedRoot)
if err != nil {
return fmt.Errorf("inspect update package: %w", err)
}
if err := validateExpandedSize(latest, info.expandedBytes); err != nil {
return err
}
if err := ensureExpandedSpace(workspace.dir, info.expandedBytes); err != nil {
return err
}
sourceDir, err := extractUpdateArchive(target, workspace.dir, expectedRoot)
if err != nil {
return fmt.Errorf("extract update package: %w", err)
}
if err := validateExtractedPackage(sourceDir, latest.Version); err != nil {
return err
}
if err := installPreparedPackage(sourceDir); err != nil {
log.Errorf("failed to install package: %v", err)
return err
}
@@ -79,7 +116,7 @@ func update() error {
return nil
}
func download(url string, target string) (err error) {
func download(latest *Latest, target string) (info utils.DownloadInfo, err error) {
for i := range maxTries {
log.Debugf("attempt #%d/%d", i+1, maxTries)
if i > 0 {
@@ -87,21 +124,26 @@ func download(url string, target string) (err error) {
}
var req *http.Request
req, err = http.NewRequest("GET", url, nil)
req, err = utils.NewAuthenticatedRequest("GET", latest.Url, nil)
if err != nil {
log.Errorf("new request err: %s", err)
continue
}
log.Debugf("update will be saved to: %s", target)
err = utils.Download(req, target)
info, err = utils.Download(req, target, int64(maxPackageSize), func(contentLength int64) error {
if latest.ManifestVersion == 2 && uint64(contentLength) != latest.SizeBytes {
return fmt.Errorf("update package size mismatch: manifest has %d bytes, response has %d", latest.SizeBytes, contentLength)
}
return ensureFreeSpace(filepath.Dir(target), uint64(contentLength))
})
if err != nil {
log.Errorf("downloading latest application failed, try again...")
continue
}
return nil
return info, nil
}
return err
return utils.DownloadInfo{}, err
}
func checksum(filePath string, expectedHash string) error {

View File

@@ -1,15 +1,17 @@
package application
import (
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
@@ -25,9 +27,9 @@ func (s *Service) OfflineUpdate(c *gin.Context) {
rsp.ErrRsp(c, -1, "update already in progress")
return
}
defer releaseUpdateLock()
if err := offlineUpdate(c); err != nil {
releaseUpdateLock()
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
return
}
@@ -35,16 +37,42 @@ func (s *Service) OfflineUpdate(c *gin.Context) {
rsp.OkRsp(c)
log.Debugf("offline update application success")
time.Sleep(1 * time.Second)
_ = exec.Command("sh", "-c", "/etc/init.d/S95nanokvm restart").Run()
go restartServices()
}
func offlineUpdate(c *gin.Context) error {
_ = os.RemoveAll(CacheDir)
_ = os.MkdirAll(CacheDir, 0o755)
expectedSHA256, err := parseSHA256Checksum(c.GetHeader("X-SHA256-Checksum"))
if err != nil {
return err
}
if err := prepareCacheForUpdate(); err != nil {
return err
}
workspace, err := newUpdateWorkspace(CacheDir)
if err != nil {
return err
}
defer func() {
_ = os.RemoveAll(CacheDir)
if err := workspace.Close(); err != nil {
log.Warnf("failed to clean update workspace %s: %v", workspace.dir, err)
}
}()
if err := ensureInstallFilesystem(workspace.dir, AppDir, BackupDir); err != nil {
return err
}
maxRequestBytes := int64(maxPackageSize) + (1 << 20)
contentLength := c.Request.ContentLength
if contentLength > maxRequestBytes {
return fmt.Errorf("offline update request exceeds %d bytes", maxRequestBytes)
}
if contentLength > 0 {
if err := ensureFreeSpace(workspace.dir, uint64(contentLength)); err != nil {
return err
}
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxRequestBytes)
if err := createSentinelFile(); err != nil {
return err
@@ -57,13 +85,35 @@ func offlineUpdate(c *gin.Context) error {
return fmt.Errorf("invalid multipart data: %w", err)
}
target, err := processUpload(reader, c.Request.ContentLength)
target, err := processUpload(reader, contentLength, workspace.dir)
if err != nil {
log.Errorf("failed to upload install package: %v", err)
return err
}
if err := installPackage(target); err != nil {
if err := verifySHA256Checksum(target, expectedSHA256); err != nil {
log.Errorf("failed to verify install package: %v", err)
return err
}
archiveName := filepath.Base(target)
expectedRoot := strings.TrimSuffix(archiveName, ".tar.gz")
expectedVersion := strings.TrimPrefix(expectedRoot, "nanokvm_")
info, err := inspectUpdateArchive(target, expectedRoot)
if err != nil {
return fmt.Errorf("inspect update package: %w", err)
}
if err := ensureExpandedSpace(workspace.dir, info.expandedBytes); err != nil {
return err
}
sourceDir, err := extractUpdateArchive(target, workspace.dir, expectedRoot)
if err != nil {
return fmt.Errorf("extract update package: %w", err)
}
if err := validateExtractedPackage(sourceDir, expectedVersion); err != nil {
return err
}
if err := installPreparedPackage(sourceDir); err != nil {
log.Errorf("failed to install package: %v", err)
return err
}
@@ -71,6 +121,43 @@ func offlineUpdate(c *gin.Context) error {
return nil
}
func parseSHA256Checksum(value string) ([]byte, error) {
value = strings.TrimSpace(value)
if value == "" {
return nil, nil
}
checksum, err := hex.DecodeString(value)
if err != nil || len(checksum) != sha256.Size {
return nil, fmt.Errorf("invalid sha256 checksum")
}
return checksum, nil
}
func verifySHA256Checksum(filePath string, expected []byte) error {
if len(expected) == 0 {
return nil
}
file, err := os.Open(filePath)
if err != nil {
return fmt.Errorf("failed to open uploaded file: %w", err)
}
defer file.Close()
hasher := sha256.New()
if _, err := io.Copy(hasher, file); err != nil {
return fmt.Errorf("failed to calculate sha256 checksum: %w", err)
}
if subtle.ConstantTimeCompare(hasher.Sum(nil), expected) != 1 {
return fmt.Errorf("sha256 checksum mismatch")
}
return nil
}
func createSentinelFile() error {
file, err := os.OpenFile(
sentinelPath,
@@ -98,7 +185,7 @@ func createSentinelFile() error {
return nil
}
func processUpload(reader *multipart.Reader, contentLength int64) (string, error) {
func processUpload(reader *multipart.Reader, contentLength int64, workspaceDir string) (string, error) {
var outPath string
for {
@@ -113,8 +200,11 @@ func processUpload(reader *multipart.Reader, contentLength int64) (string, error
if part.FormName() != "file" {
continue
}
if outPath != "" {
return "", fmt.Errorf("multiple files uploaded")
}
outPath, err = saveUploadedFile(part, contentLength)
outPath, err = saveUploadedFile(part, contentLength, workspaceDir)
if err != nil {
return "", err
}
@@ -127,7 +217,7 @@ func processUpload(reader *multipart.Reader, contentLength int64) (string, error
return outPath, nil
}
func saveUploadedFile(part *multipart.Part, contentLength int64) (string, error) {
func saveUploadedFile(part *multipart.Part, contentLength int64, workspaceDir string) (string, error) {
filename := part.FileName()
if filename == "" {
return "", fmt.Errorf("no filename provided")
@@ -137,19 +227,36 @@ func saveUploadedFile(part *multipart.Part, contentLength int64) (string, error)
return "", err
}
outPath := filepath.Join(CacheDir, filename)
out, err := os.Create(outPath)
outPath := filepath.Join(workspaceDir, filename)
out, err := os.OpenFile(outPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return "", fmt.Errorf("failed to create output file: %w", err)
}
defer out.Close()
success := false
defer func() {
_ = out.Close()
if !success {
_ = os.Remove(outPath)
}
}()
if contentLength < 0 {
contentLength = 0
}
pw := newProgressWriter(out, contentLength)
defer pw.Stop()
if _, err := io.Copy(pw, part); err != nil {
written, err := io.Copy(pw, io.LimitReader(part, int64(maxPackageSize)+1))
if err != nil {
return "", fmt.Errorf("failed to write file: %w", err)
}
if written > int64(maxPackageSize) {
return "", fmt.Errorf("uploaded package exceeds %d bytes", maxPackageSize)
}
if err := out.Close(); err != nil {
return "", fmt.Errorf("failed to close output file: %w", err)
}
success = true
return outPath, nil
}
@@ -174,6 +281,9 @@ func validateFilename(filename string) error {
log.Warnf("Invalid filename characters: %s", filename)
return fmt.Errorf("invalid filename: contains invalid characters")
}
if !packageNamePattern.MatchString(filename) {
return fmt.Errorf("invalid update package name")
}
return nil
}

View File

@@ -0,0 +1,212 @@
package application
import (
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
UpdateServerConfigFile = "/etc/kvm/application-update.json"
maxUpdateServerURLSize = 2048
)
var (
updateServerConfigMu sync.Mutex
updateServerConfigPath = UpdateServerConfigFile
)
type UpdateServerConfig struct {
Enabled bool `json:"enabled"`
URL string `json:"url"`
}
func defaultUpdateServerConfig() UpdateServerConfig {
return UpdateServerConfig{URL: StableURL}
}
func (s *Service) GetUpdateServer(c *gin.Context) {
var rsp proto.Response
cfg, err := loadUpdateServerConfig()
if err != nil {
log.Errorf("failed to load update server config: %s", err)
rsp.ErrRsp(c, -1, "failed to load update server config")
return
}
rsp.OkRspWithData(c, &proto.GetUpdateServerRsp{
Enabled: cfg.Enabled,
URL: cfg.URL,
})
}
func (s *Service) SetUpdateServer(c *gin.Context) {
var req proto.SetUpdateServerReq
var rsp proto.Response
// Avoid the shared request logger because the URL may contain credentials.
if err := c.ShouldBind(&req); err != nil || req.Enabled == nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
normalizedURL, err := normalizeUpdateServerURL(req.URL)
if err != nil {
rsp.ErrRsp(c, -2, err.Error())
return
}
if *req.Enabled && normalizedURL == "" {
rsp.ErrRsp(c, -2, "update server URL is required")
return
}
if normalizedURL == "" {
normalizedURL = StableURL
}
cfg := UpdateServerConfig{Enabled: *req.Enabled, URL: normalizedURL}
if err := saveUpdateServerConfig(cfg); err != nil {
log.Errorf("failed to save update server config: %s", err)
rsp.ErrRsp(c, -3, "failed to save update server config")
return
}
rsp.OkRspWithData(c, &proto.GetUpdateServerRsp{
Enabled: cfg.Enabled,
URL: cfg.URL,
})
}
func resolveUpdateBaseURL() (string, error) {
cfg, err := loadUpdateServerConfig()
if err != nil {
return "", err
}
if cfg.Enabled {
return cfg.URL, nil
}
if isPreviewEnabled() {
return PreviewURL, nil
}
return StableURL, nil
}
func normalizeUpdateServerURL(raw string) (string, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return "", nil
}
if len(raw) > maxUpdateServerURLSize {
return "", errors.New("update server URL is too long")
}
parsed, err := url.Parse(raw)
if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
return "", errors.New("invalid update server URL")
}
if parsed.RawQuery != "" || parsed.Fragment != "" {
return "", errors.New("update server URL must not contain a query or fragment")
}
if strings.HasSuffix(strings.TrimRight(parsed.Path, "/"), "/latest.json") {
return "", errors.New("enter the update server directory, not latest.json")
}
parsed.Path = strings.TrimRight(parsed.Path, "/")
return parsed.String(), nil
}
func loadUpdateServerConfig() (UpdateServerConfig, error) {
updateServerConfigMu.Lock()
defer updateServerConfigMu.Unlock()
return loadUpdateServerConfigFromPath(updateServerConfigPath)
}
func loadUpdateServerConfigFromPath(path string) (UpdateServerConfig, error) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return defaultUpdateServerConfig(), nil
}
return UpdateServerConfig{}, err
}
var cfg UpdateServerConfig
if err := json.Unmarshal(data, &cfg); err != nil {
return UpdateServerConfig{}, fmt.Errorf("decode update server config: %w", err)
}
normalizedURL, err := normalizeUpdateServerURL(cfg.URL)
if err != nil {
return UpdateServerConfig{}, err
}
if normalizedURL == "" {
normalizedURL = StableURL
}
cfg.URL = normalizedURL
return cfg, nil
}
func saveUpdateServerConfig(cfg UpdateServerConfig) error {
updateServerConfigMu.Lock()
defer updateServerConfigMu.Unlock()
return saveUpdateServerConfigToPath(updateServerConfigPath, cfg)
}
func saveUpdateServerConfigToPath(path string, cfg UpdateServerConfig) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create update server config directory: %w", err)
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("encode update server config: %w", err)
}
data = append(data, '\n')
tmp, err := os.CreateTemp(dir, ".application-update.json.*")
if err != nil {
return fmt.Errorf("create temporary update server config: %w", err)
}
tmpPath := tmp.Name()
defer func() { _ = os.Remove(tmpPath) }()
if err := tmp.Chmod(0o600); err != nil {
_ = tmp.Close()
return fmt.Errorf("set update server config permissions: %w", err)
}
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write update server config: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync update server config: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close update server config: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
return fmt.Errorf("replace update server config: %w", err)
}
directory, err := os.Open(dir)
if err == nil {
_ = directory.Sync()
_ = directory.Close()
}
return nil
}

View File

@@ -1,28 +1,46 @@
package application
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"regexp"
"strings"
"time"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type Latest struct {
Version string `json:"version"`
Name string `json:"name"`
Sha512 string `json:"sha512"`
Size uint `json:"size"`
Url string `json:"url"`
ManifestVersion int `json:"manifest_version,omitempty"`
Version string `json:"version"`
Name string `json:"name"`
Sha512 string `json:"sha512"`
LegacySize uint64 `json:"size"`
SizeBytes uint64 `json:"size_bytes,omitempty"`
UnpackedSizeBytes uint64 `json:"unpacked_size_bytes,omitempty"`
Url string `json:"-"`
}
const (
maxLatestJSONSize = 64 * 1024
)
var (
latestClient = utils.NewUpdateHTTPClient(15 * time.Second)
packageNamePattern = regexp.MustCompile(`^nanokvm_[0-9]+\.[0-9]+\.[0-9]+\.tar\.gz$`)
versionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$`)
)
func (s *Service) GetVersion(c *gin.Context) {
var rsp proto.Response
@@ -39,9 +57,12 @@ func (s *Service) GetVersion(c *gin.Context) {
// latest version
latestVersion := ""
latest, err := getLatest()
if err == nil && latest != nil {
latestVersion = latest.Version
if err != nil {
log.Errorf("failed to get latest version: %s", err)
rsp.ErrRsp(c, -1, "failed to query latest version")
return
}
latestVersion = latest.Version
rsp.OkRspWithData(c, &proto.GetVersionRsp{
Current: currentVersion,
@@ -50,23 +71,37 @@ func (s *Service) GetVersion(c *gin.Context) {
}
func getLatest() (*Latest, error) {
baseURL := StableURL
if isPreviewEnabled() {
baseURL = PreviewURL
baseURL, err := resolveUpdateBaseURL()
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s/latest.json?now=%d", baseURL, time.Now().Unix())
resp, err := http.Get(url)
manifestURL, err := joinUpdateURL(baseURL, "latest.json")
if err != nil {
log.Debugf("failed to request version: %v", err)
return nil, err
}
parsedManifestURL, err := url.Parse(manifestURL)
if err != nil {
return nil, err
}
query := parsedManifestURL.Query()
query.Set("now", fmt.Sprintf("%d", time.Now().Unix()))
parsedManifestURL.RawQuery = query.Encode()
request, err := utils.NewAuthenticatedRequest("GET", parsedManifestURL.String(), nil)
if err != nil {
return nil, err
}
resp, err := latestClient.Do(request)
if err != nil {
log.Debugf("failed to request version from %s", parsedManifestURL.Redacted())
return nil, errors.New("update server is inaccessible")
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
body, err := io.ReadAll(io.LimitReader(resp.Body, maxLatestJSONSize+1))
if err != nil {
log.Errorf("failed to read response: %v", err)
return nil, err
@@ -76,15 +111,86 @@ func getLatest() (*Latest, error) {
log.Errorf("server responded with status code: %d", resp.StatusCode)
return nil, fmt.Errorf("status code %d", resp.StatusCode)
}
if len(body) > maxLatestJSONSize {
return nil, fmt.Errorf("latest manifest exceeds %d bytes", maxLatestJSONSize)
}
var latest Latest
if err := json.Unmarshal(body, &latest); err != nil {
log.Errorf("failed to unmarshal response: %s", err)
return nil, err
}
if err := validateLatest(&latest); err != nil {
return nil, err
}
latest.Url = fmt.Sprintf("%s/%s", baseURL, latest.Name)
latest.Url, err = joinUpdateURL(baseURL, latest.Name)
if err != nil {
return nil, err
}
log.Debugf("get application latest version: %s", latest.Version)
return &latest, nil
}
func joinUpdateURL(baseURL string, element string) (string, error) {
joined, err := url.JoinPath(baseURL, element)
if err != nil {
return "", fmt.Errorf("join update URL: %w", err)
}
return joined, nil
}
func validateLatest(latest *Latest) error {
if !versionPattern.MatchString(latest.Version) {
return errors.New("invalid latest version")
}
if !packageNamePattern.MatchString(latest.Name) {
return errors.New("invalid update package name")
}
digest, err := base64.StdEncoding.DecodeString(latest.Sha512)
if err != nil || len(digest) != 64 {
return errors.New("invalid update package sha512")
}
if latest.LegacySize == 0 {
return errors.New("invalid update package size")
}
switch latest.ManifestVersion {
case 0, 1:
return nil
case 2:
if latest.SizeBytes == 0 || latest.SizeBytes > maxPackageSize {
return errors.New("invalid update package size_bytes")
}
if latest.UnpackedSizeBytes == 0 || latest.UnpackedSizeBytes > maxExpandedSize {
return errors.New("invalid update package unpacked_size_bytes")
}
return nil
default:
return errors.New("unsupported update manifest version")
}
}
func preflightManifestSpace(path string, latest *Latest) error {
if latest.ManifestVersion != 2 {
return nil
}
return ensureFreeSpace(path, latest.SizeBytes)
}
func validateDownloadedSize(latest *Latest, written uint64) error {
if written > maxPackageSize {
return fmt.Errorf("update package exceeds %d bytes", maxPackageSize)
}
if latest.ManifestVersion == 2 && written != latest.SizeBytes {
return fmt.Errorf("update package size mismatch: expected %d bytes, got %d", latest.SizeBytes, written)
}
return nil
}
func validateExpandedSize(latest *Latest, expanded uint64) error {
if latest.ManifestVersion == 2 && expanded != latest.UnpackedSizeBytes {
return fmt.Errorf("update package expanded size mismatch: expected %d bytes, got %d", latest.UnpackedSizeBytes, expanded)
}
return nil
}

View File

@@ -0,0 +1,46 @@
package application
import (
"crypto/sha512"
"encoding/base64"
"testing"
)
func validLatest() Latest {
digest := sha512.Sum512([]byte("package"))
return Latest{
Version: "1.2.3", Name: "nanokvm_1.2.3.tar.gz",
Sha512: base64.StdEncoding.EncodeToString(digest[:]), LegacySize: 1,
}
}
func TestValidateLatestV1DoesNotInterpretLegacySizeAsBytes(t *testing.T) {
latest := validLatest()
latest.LegacySize = 15048 // historic stable manifests used a non-byte value
if err := validateLatest(&latest); err != nil {
t.Fatal(err)
}
if err := validateDownloadedSize(&latest, 15406125); err != nil {
t.Fatalf("v1 must not require equality with legacy size: %v", err)
}
}
func TestValidateLatestV2RequiresExactByteFields(t *testing.T) {
latest := validLatest()
latest.ManifestVersion = 2
latest.SizeBytes = 100
latest.UnpackedSizeBytes = 200
if err := validateLatest(&latest); err != nil {
t.Fatal(err)
}
if err := validateDownloadedSize(&latest, 99); err == nil {
t.Fatal("v2 size mismatch was accepted")
}
if err := validateExpandedSize(&latest, 199); err == nil {
t.Fatal("v2 expanded size mismatch was accepted")
}
latest.ManifestVersion = 3
if err := validateLatest(&latest); err == nil {
t.Fatal("unknown manifest version was accepted")
}
}

View File

@@ -0,0 +1,69 @@
package application
import (
"fmt"
"os"
"path/filepath"
"strings"
)
type updateWorkspace struct {
dir string
}
func newUpdateWorkspace(baseDir string) (*updateWorkspace, error) {
if err := os.MkdirAll(baseDir, cacheDirMode); err != nil {
return nil, fmt.Errorf("create update cache: %w", err)
}
if err := os.Chmod(baseDir, cacheDirMode); err != nil {
return nil, fmt.Errorf("chmod update cache: %w", err)
}
dir, err := os.MkdirTemp(baseDir, updateWorkspacePrefix)
if err != nil {
return nil, fmt.Errorf("create update workspace: %w", err)
}
return &updateWorkspace{dir: dir}, nil
}
func (w *updateWorkspace) Close() error {
return os.RemoveAll(w.dir)
}
func cleanupStaleWorkspaces(baseDir string) error {
entries, err := os.ReadDir(baseDir)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return err
}
for _, entry := range entries {
if !strings.HasPrefix(entry.Name(), updateWorkspacePrefix) {
continue
}
if err := os.RemoveAll(filepath.Join(baseDir, entry.Name())); err != nil {
return err
}
}
return nil
}
func prepareCacheForUpdate() error {
info, err := os.Stat(AppDir)
if err != nil {
return fmt.Errorf("stat current application: %w", err)
}
if !info.IsDir() {
return fmt.Errorf("current application is not a directory")
}
if err := os.MkdirAll(CacheDir, cacheDirMode); err != nil {
return fmt.Errorf("create update cache: %w", err)
}
if err := os.Chmod(CacheDir, cacheDirMode); err != nil {
return fmt.Errorf("chmod update cache: %w", err)
}
if err := cleanupStaleWorkspaces(CacheDir); err != nil {
return fmt.Errorf("clean stale update workspace: %w", err)
}
return nil
}

View File

@@ -0,0 +1,49 @@
package application
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestWorkspaceCleanupIsScopedToUpdaterDirectories(t *testing.T) {
base := t.TempDir()
for _, name := range []string{"nanokvm-update-old", "update-other", "firmware.tar.xz", "nanokvm-go_1.0.0"} {
if err := os.Mkdir(filepath.Join(base, name), 0o755); err != nil {
t.Fatal(err)
}
}
if err := cleanupStaleWorkspaces(base); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(base, "nanokvm-update-old")); !os.IsNotExist(err) {
t.Fatalf("stale workspace still exists: %v", err)
}
for _, name := range []string{"update-other", "firmware.tar.xz", "nanokvm-go_1.0.0"} {
if _, err := os.Stat(filepath.Join(base, name)); err != nil {
t.Fatalf("unrelated cache entry %s was removed: %v", name, err)
}
}
}
func TestNewWorkspaceIsPrivateAndCloseOnlyRemovesItself(t *testing.T) {
base := t.TempDir()
keep := filepath.Join(base, "keep")
if err := os.WriteFile(keep, []byte("keep"), 0o600); err != nil {
t.Fatal(err)
}
workspace, err := newUpdateWorkspace(base)
if err != nil {
t.Fatal(err)
}
if filepath.Dir(workspace.dir) != base || !strings.HasPrefix(filepath.Base(workspace.dir), updateWorkspacePrefix) {
t.Fatalf("unexpected workspace path %q", workspace.dir)
}
if err := workspace.Close(); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(keep); err != nil {
t.Fatalf("unrelated cache entry was removed: %v", err)
}
}

View File

@@ -1,113 +0,0 @@
package auth
import (
"NanoKVM-Server/utils"
"encoding/json"
"errors"
"os"
"path/filepath"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
const AccountFile = "/etc/kvm/pwd"
type Account struct {
Username string `json:"username"`
Password string `json:"password"` // should be named HashedPassword for clarity
}
func GetAccount() (*Account, error) {
if _, err := os.Stat(AccountFile); err != nil {
if errors.Is(err, os.ErrNotExist) {
return getDefaultAccount(), nil
}
return nil, err
}
content, err := os.ReadFile(AccountFile)
if err != nil {
return nil, err
}
var account Account
if err = json.Unmarshal(content, &account); err != nil {
log.Errorf("unmarshal account failed: %s", err)
return nil, err
}
return &account, nil
}
func SetAccount(username string, hashedPassword string) error {
account, err := json.Marshal(&Account{
Username: username,
Password: hashedPassword,
})
if err != nil {
log.Errorf("failed to marshal account information to json: %s", err)
return err
}
err = os.MkdirAll(filepath.Dir(AccountFile), 0o644)
if err != nil {
log.Errorf("create directory %s failed: %s", AccountFile, err)
return err
}
err = os.WriteFile(AccountFile, account, 0o644)
if err != nil {
log.Errorf("write password failed: %s", err)
return err
}
return nil
}
func CompareAccount(username string, plainPassword string) bool {
account, err := GetAccount()
if err != nil {
return false
}
if username != account.Username {
return false
}
hashedPassword, err := utils.DecodeDecrypt(plainPassword)
if err != nil || hashedPassword == "" {
return false
}
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(hashedPassword))
if err != nil {
// Compatible with old versions
accountHashedPassword, _ := utils.DecodeDecrypt(account.Password)
if accountHashedPassword == hashedPassword {
return true
}
return false
}
return true
}
func DelAccount() error {
if err := os.Remove(AccountFile); err != nil {
log.Errorf("failed to delete password: %s", err)
return err
}
return nil
}
func getDefaultAccount() *Account {
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("admin"), bcrypt.DefaultCost)
return &Account{
Username: "admin",
Password: string(hashedPassword),
}
}

View File

@@ -1,11 +1,15 @@
package auth
import (
"net/http"
"strings"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -15,12 +19,9 @@ func (s *Service) Login(c *gin.Context) {
var req proto.LoginReq
var rsp proto.Response
// authentication disabled
conf := config.GetInstance()
if conf.Authentication == "disable" {
rsp.OkRspWithData(c, &proto.LoginRsp{
Token: "disabled",
})
rsp.OkRsp(c)
return
}
@@ -30,63 +31,98 @@ func (s *Service) Login(c *gin.Context) {
rsp.ErrRsp(c, code, msg)
return
}
if err := proto.ParseFormRequest(c, &req); err != nil {
time.Sleep(3 * time.Second)
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
if ok := CompareAccount(req.Username, req.Password); !ok {
password, err := utils.DecodeDecrypt(req.Password)
if err != nil || password == "" {
s.loginFailed(c, clientIP, &rsp)
return
}
user, ok, err := authn.DefaultStore.Authenticate(req.Username, password)
if err != nil {
log.Errorf("load account during login: %s", err)
time.Sleep(2 * time.Second)
if locked, code, msg := RecordLoginFailure(clientIP); locked {
rsp.ErrRsp(c, code, msg)
return
}
rsp.ErrRsp(c, -2, "invalid username or password")
rsp.ErrRsp(c, -3, "authentication unavailable")
return
}
if !ok {
s.loginFailed(c, clientIP, &rsp)
return
}
ClearLoginAttempt(clientIP)
token, err := middleware.GenerateJWT(req.Username)
token, err := middleware.GenerateJWT(user.Username, user.TokenVersion)
if err != nil {
time.Sleep(1 * time.Second)
time.Sleep(time.Second)
rsp.ErrRsp(c, -3, "generate token failed")
return
}
setSessionCookie(c, token)
rsp.OkRsp(c)
log.Infof("user logged in: %s", user.Username)
}
rsp.OkRspWithData(c, &proto.LoginRsp{
Token: token,
})
log.Debugf("login success, username: %s", req.Username)
func (s *Service) loginFailed(c *gin.Context, clientIP string, rsp *proto.Response) {
time.Sleep(2 * time.Second)
if locked, code, msg := RecordLoginFailure(clientIP); locked {
rsp.ErrRsp(c, code, msg)
return
}
rsp.ErrRsp(c, -2, "invalid username or password")
}
func (s *Service) Logout(c *gin.Context) {
conf := config.GetInstance()
if conf.JWT.RevokeTokensOnLogout {
config.RegenerateSecretKey()
}
var rsp proto.Response
principal, ok := middleware.CurrentPrincipal(c)
conf := config.GetInstance()
if ok && conf.Authentication != "disable" && conf.JWT.RevokeTokensOnLogout {
if _, err := authn.DefaultStore.Revoke(principal.Username); err != nil {
rsp.ErrRsp(c, -1, "failed to revoke session")
return
}
middleware.RevokeUserSessions(principal.Username)
log.Infof("user logged out: %s", principal.Username)
}
clearSessionCookie(c)
rsp.OkRsp(c)
}
func (s *Service) GetAccount(c *gin.Context) {
var rsp proto.Response
account, err := GetAccount()
if err != nil {
principal, ok := middleware.CurrentPrincipal(c)
if !ok {
rsp.ErrRsp(c, -1, "get account failed")
return
}
rsp.OkRspWithData(c, &proto.GetAccountRsp{
Username: account.Username,
Username: principal.Username,
Role: string(principal.Role),
})
log.Debugf("get account successful")
}
func setSessionCookie(c *gin.Context, token string) {
conf := config.GetInstance()
secure := conf.Proto == "https" || c.Request.TLS != nil ||
strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")
c.SetSameSite(http.SameSiteStrictMode)
c.SetCookie(
middleware.CookieName,
token,
int(conf.JWT.RefreshTokenDuration),
"/",
"",
secure,
true,
)
}
func clearSessionCookie(c *gin.Context) {
conf := config.GetInstance()
secure := conf.Proto == "https" || c.Request.TLS != nil ||
strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https")
c.SetSameSite(http.SameSiteStrictMode)
c.SetCookie(middleware.CookieName, "", -1, "/", "", secure, true)
}

View File

@@ -1,124 +1,126 @@
package auth
import (
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"errors"
"io"
"os"
"os/exec"
"time"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/bcrypt"
)
var systemPasswordUpdater = changeRootPassword
func (s *Service) ChangePassword(c *gin.Context) {
var req proto.ChangePasswordReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
password, err := utils.DecodeDecrypt(req.Password)
if err != nil || password == "" {
rsp.ErrRsp(c, -2, "invalid password")
return
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
rsp.ErrRsp(c, -3, "failed to hash password")
return
}
if err = SetAccount(req.Username, string(hashedPassword)); err != nil {
rsp.ErrRsp(c, -4, "failed to save password")
return
}
// change root password
err = changeRootPassword(password)
if err != nil {
_ = DelAccount()
rsp.ErrRsp(c, -5, "failed to change password")
principal, ok := middleware.CurrentPrincipal(c)
if !ok {
rsp.ErrRsp(c, -2, "invalid session")
return
}
currentPassword, err := utils.DecodeDecrypt(req.CurrentPassword)
if err != nil || currentPassword == "" {
rsp.ErrRsp(c, -3, "current password is required")
return
}
if _, authenticated, authErr := authn.DefaultStore.Authenticate(principal.Username, currentPassword); authErr != nil {
rsp.ErrRsp(c, -4, "authentication unavailable")
return
} else if !authenticated {
rsp.ErrRsp(c, -3, "current password is incorrect")
return
}
if err := changeUserPassword(principal.Username, req.Password); err != nil {
rsp.ErrRsp(c, -5, err.Error())
return
}
middleware.RevokeUserSessions(principal.Username)
clearSessionCookie(c)
rsp.OkRsp(c)
log.Debugf("change password success, username: %s", req.Username)
log.Infof("password changed for user: %s", principal.Username)
}
func (s *Service) IsPasswordUpdated(c *gin.Context) {
var rsp proto.Response
if config.GetInstance().Authentication == "disable" {
rsp.OkRspWithData(c, &proto.IsPasswordUpdatedRsp{IsUpdated: true})
return
}
principal, ok := middleware.CurrentPrincipal(c)
if !ok {
rsp.ErrRsp(c, -1, "invalid session")
return
}
user, err := authn.DefaultStore.Get(principal.Username)
if err != nil {
rsp.ErrRsp(c, -2, "failed to get password state")
return
}
rsp.OkRspWithData(c, &proto.IsPasswordUpdatedRsp{IsUpdated: !user.MustChangePassword})
}
if _, err := os.Stat(AccountFile); err != nil {
rsp.OkRspWithData(c, &proto.IsPasswordUpdatedRsp{
IsUpdated: false,
func changeUserPassword(username, encryptedPassword string) error {
password, err := utils.DecodeDecrypt(encryptedPassword)
if err != nil || password == "" {
return errInvalidPassword
}
if err = authn.ValidatePassword(password); err != nil {
return err
}
user, err := authn.DefaultStore.Get(username)
if err != nil {
return err
}
if user.SystemAccount && user.Role == authn.RoleAdmin && user.Enabled {
_, err = authn.DefaultStore.SetPasswordAndRun(username, password, func() error {
return systemPasswordUpdater(password)
})
return
return err
}
account, err := GetAccount()
if err != nil || account == nil {
rsp.ErrRsp(c, -1, "failed to get password")
return
}
err = bcrypt.CompareHashAndPassword([]byte(account.Password), []byte("admin"))
rsp.OkRspWithData(c, &proto.IsPasswordUpdatedRsp{
// If the hash is not valid, still assume it's not updated
// The error we want to see is password and hash not matching
IsUpdated: errors.Is(err, bcrypt.ErrMismatchedHashAndPassword),
})
_, err = authn.DefaultStore.SetPassword(username, password)
return err
}
func changeRootPassword(password string) error {
err := passwd(password)
if err != nil {
if err := passwd(password); err != nil {
log.Errorf("failed to change root password: %s", err)
return err
}
log.Debugf("change root password successful.")
log.Debug("change root password successful")
return nil
}
func passwd(password string) error {
cmd := exec.Command("passwd", "root")
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
defer func() {
_ = stdin.Close()
}()
defer func() { _ = stdin.Close() }()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err = cmd.Start(); err != nil {
return err
}
if _, err = io.WriteString(stdin, password+"\n"); err != nil {
return err
}
time.Sleep(100 * time.Millisecond)
if _, err = io.WriteString(stdin, password+"\n"); err != nil {
return err
}
if err = cmd.Wait(); err != nil {
return err
}
return nil
return cmd.Wait()
}

View File

@@ -0,0 +1,307 @@
package auth
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"testing"
"NanoKVM-Server/authn"
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
"github.com/mervick/aes-everywhere/go/aes256"
)
func TestLoginCookieAndUserAuthorizationLifecycle(t *testing.T) {
gin.SetMode(gin.TestMode)
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
restore := useTestStore(store)
defer restore()
service := NewService()
router := gin.New()
router.POST("/login", service.Login)
authenticated := router.Group("/").Use(middleware.CheckToken())
authenticated.GET("/account", service.GetAccount)
authenticated.POST("/logout", service.Logout)
admin := router.Group("/").Use(middleware.CheckToken(), middleware.RequireRole(authn.RoleAdmin))
admin.GET("/users", service.ListUsers)
admin.POST("/users", service.CreateUser)
admin.PUT("/users/:username", service.UpdateUser)
adminCookie := loginCookie(t, router, "admin", "admin")
if !adminCookie.HttpOnly || adminCookie.SameSite != http.SameSiteStrictMode || adminCookie.Path != "/" {
t.Fatalf("unsafe session cookie: %+v", adminCookie)
}
createBody := map[string]any{
"username": "alice",
"password": encryptForRequest("valid-password"),
"role": "user",
}
if code := requestJSON(router, http.MethodPost, "/users", createBody, adminCookie); code != http.StatusOK {
t.Fatalf("create status = %d", code)
}
userCookie := loginCookie(t, router, "alice", "valid-password")
if code := requestJSON(router, http.MethodGet, "/users", nil, userCookie); code != http.StatusForbidden {
t.Fatalf("user management status = %d, want 403", code)
}
disabled := false
if code := requestJSON(router, http.MethodPut, "/users/alice", map[string]any{"enabled": disabled}, adminCookie); code != http.StatusOK {
t.Fatalf("disable status = %d", code)
}
if code := requestJSON(router, http.MethodGet, "/account", nil, userCookie); code != http.StatusUnauthorized {
t.Fatalf("disabled session status = %d, want 401", code)
}
}
func TestLogoutDoesNotInvalidateAnotherUser(t *testing.T) {
gin.SetMode(gin.TestMode)
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
restore := useTestStore(store)
defer restore()
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err := store.Create("alice", "alice-password", authn.RoleUser); err != nil {
t.Fatal(err)
}
if err := store.Create("bob", "bob-password", authn.RoleUser); err != nil {
t.Fatal(err)
}
service := NewService()
router := gin.New()
router.POST("/login", service.Login)
authenticated := router.Group("/").Use(middleware.CheckToken())
authenticated.GET("/account", service.GetAccount)
authenticated.POST("/logout", service.Logout)
aliceCookie := loginCookie(t, router, "alice", "alice-password")
bobCookie := loginCookie(t, router, "bob", "bob-password")
if code := requestJSON(router, http.MethodPost, "/logout", nil, aliceCookie); code != http.StatusOK {
t.Fatalf("logout status = %d", code)
}
if code := requestJSON(router, http.MethodGet, "/account", nil, aliceCookie); code != http.StatusUnauthorized {
t.Fatalf("logged out session status = %d", code)
}
if code := requestJSON(router, http.MethodGet, "/account", nil, bobCookie); code != http.StatusOK {
t.Fatalf("other user's session status = %d", code)
}
}
func TestNormalUserPasswordNeverChangesSystemPassword(t *testing.T) {
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
restore := useTestStore(store)
defer restore()
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err := store.Create("alice", "alice-password", authn.RoleUser); err != nil {
t.Fatal(err)
}
originalUpdater := systemPasswordUpdater
updates := 0
systemPasswordUpdater = func(string) error {
updates++
return nil
}
defer func() { systemPasswordUpdater = originalUpdater }()
if err := changeUserPassword("alice", encryptForRequest("new-password")); err != nil {
t.Fatal(err)
}
if updates != 0 {
t.Fatalf("system password updated %d times for a normal user", updates)
}
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || !ok {
t.Fatalf("new web password login: ok=%v err=%v", ok, err)
}
}
func TestSelfPasswordChangeRequiresCurrentPassword(t *testing.T) {
gin.SetMode(gin.TestMode)
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
restore := useTestStore(store)
defer restore()
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err := store.Create("alice", "alice-password", authn.RoleUser); err != nil {
t.Fatal(err)
}
service := NewService()
router := gin.New()
router.POST("/login", service.Login)
authenticated := router.Group("/").Use(middleware.CheckToken())
authenticated.POST("/password", service.ChangePassword)
cookie := loginCookie(t, router, "alice", "alice-password")
recorder := requestJSONRecorder(router, http.MethodPost, "/password", map[string]any{
"currentPassword": encryptForRequest("wrong-password"),
"password": encryptForRequest("new-password"),
}, cookie)
var response proto.Response
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatalf("decode wrong-current-password response: %v", err)
}
if response.Code != -3 || response.Msg != "current password is incorrect" {
t.Fatalf("wrong-current-password response = %+v", response)
}
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || ok {
t.Fatalf("password changed without current credential: ok=%v err=%v", ok, err)
}
requestJSON(router, http.MethodPost, "/password", map[string]any{
"currentPassword": encryptForRequest("alice-password"),
"password": encryptForRequest("new-password"),
}, cookie)
if _, ok, err := store.Authenticate("alice", "new-password"); err != nil || !ok {
t.Fatalf("valid password change failed: ok=%v err=%v", ok, err)
}
}
func TestAdministratorCannotResetDeviceOwnerPassword(t *testing.T) {
gin.SetMode(gin.TestMode)
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
restore := useTestStore(store)
defer restore()
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
if err := store.Create("second-admin", "second-password", authn.RoleAdmin); err != nil {
t.Fatal(err)
}
originalUpdater := systemPasswordUpdater
updates := 0
systemPasswordUpdater = func(string) error {
updates++
return nil
}
defer func() { systemPasswordUpdater = originalUpdater }()
service := NewService()
router := gin.New()
router.POST("/login", service.Login)
admin := router.Group("/").Use(middleware.CheckToken(), middleware.RequireRole(authn.RoleAdmin))
admin.POST("/users/:username/password", service.ChangeUserPassword)
cookie := loginCookie(t, router, "second-admin", "second-password")
requestJSON(router, http.MethodPost, "/users/admin/password", map[string]any{
"password": encryptForRequest("new-password"),
}, cookie)
if updates != 0 {
t.Fatalf("administrator changed the device owner's system password %d times", updates)
}
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("device owner password changed: ok=%v err=%v", ok, err)
}
if _, ok, err := store.Authenticate("admin", "new-password"); err != nil || ok {
t.Fatalf("unauthorized password became active: ok=%v err=%v", ok, err)
}
}
func TestSystemPasswordFailureRollsBackWebPassword(t *testing.T) {
store := authn.NewStore(filepath.Join(t.TempDir(), "pwd"))
restore := useTestStore(store)
defer restore()
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("default login: ok=%v err=%v", ok, err)
}
originalUpdater := systemPasswordUpdater
systemPasswordUpdater = func(string) error { return errors.New("passwd failed") }
defer func() { systemPasswordUpdater = originalUpdater }()
if err := changeUserPassword("admin", encryptForRequest("new-password")); err == nil {
t.Fatal("system password failure was ignored")
}
if _, ok, err := store.Authenticate("admin", "admin"); err != nil || !ok {
t.Fatalf("old web password was not restored: ok=%v err=%v", ok, err)
}
if _, ok, err := store.Authenticate("admin", "new-password"); err != nil || ok {
t.Fatalf("failed password stayed active: ok=%v err=%v", ok, err)
}
}
func loginCookie(t *testing.T, handler http.Handler, username, password string) *http.Cookie {
t.Helper()
body := map[string]any{"username": username, "password": encryptForRequest(password)}
recorder := httptest.NewRecorder()
request := jsonRequest(http.MethodPost, "/login", body)
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("login status = %d", recorder.Code)
}
if bytes.Contains(recorder.Body.Bytes(), []byte("token")) {
t.Fatalf("login exposed JWT in response: %s", recorder.Body.String())
}
for _, cookie := range recorder.Result().Cookies() {
if cookie.Name == middleware.CookieName {
return cookie
}
}
t.Fatal("login did not set session cookie")
return nil
}
func requestJSON(handler http.Handler, method, path string, body any, cookie *http.Cookie) int {
return requestJSONRecorder(handler, method, path, body, cookie).Code
}
func requestJSONRecorder(handler http.Handler, method, path string, body any, cookie *http.Cookie) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
request := jsonRequest(method, path, body)
if cookie != nil {
request.AddCookie(cookie)
}
handler.ServeHTTP(recorder, request)
return recorder
}
func jsonRequest(method, path string, body any) *http.Request {
var data []byte
if body != nil {
data, _ = json.Marshal(body)
}
request := httptest.NewRequest(method, path, bytes.NewReader(data))
request.Header.Set("Content-Type", "application/json")
return request
}
func encryptForRequest(password string) string {
return url.QueryEscape(aes256.Encrypt(password, utils.SecretKey))
}
func useTestStore(store *authn.Store) func() {
originalStore := authn.DefaultStore
conf := config.GetInstance()
originalAuthentication := conf.Authentication
originalSecret := conf.JWT.SecretKey
originalDuration := conf.JWT.RefreshTokenDuration
originalRevokeOnLogout := conf.JWT.RevokeTokensOnLogout
authn.DefaultStore = store
conf.Authentication = "enable"
conf.JWT.SecretKey = "test-secret"
conf.JWT.RefreshTokenDuration = 3600
conf.JWT.RevokeTokensOnLogout = true
return func() {
authn.DefaultStore = originalStore
conf.Authentication = originalAuthentication
conf.JWT.SecretKey = originalSecret
conf.JWT.RefreshTokenDuration = originalDuration
conf.JWT.RevokeTokensOnLogout = originalRevokeOnLogout
}
}

View File

@@ -0,0 +1,127 @@
package auth
import (
"errors"
"NanoKVM-Server/authn"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
var errInvalidPassword = errors.New("invalid password")
func (s *Service) ListUsers(c *gin.Context) {
var rsp proto.Response
users, err := authn.DefaultStore.List()
if err != nil {
rsp.ErrRsp(c, -1, "failed to load users")
return
}
result := make([]proto.UserInfo, 0, len(users))
for _, user := range users {
result = append(result, proto.UserInfo{
Username: user.Username,
Role: string(user.Role),
Enabled: user.Enabled,
SystemAccount: user.SystemAccount,
})
}
rsp.OkRspWithData(c, &proto.ListUsersRsp{Users: result})
}
func (s *Service) CreateUser(c *gin.Context) {
var req proto.CreateUserReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
password, err := decodePassword(req.Password)
if err != nil {
rsp.ErrRsp(c, -2, err.Error())
return
}
if err = authn.DefaultStore.Create(req.Username, password, authn.Role(req.Role)); err != nil {
rsp.ErrRsp(c, -3, err.Error())
return
}
rsp.OkRsp(c)
log.Infof("user created: %s (%s)", req.Username, req.Role)
}
func (s *Service) UpdateUser(c *gin.Context) {
var req proto.UpdateUserReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil || (req.Role == nil && req.Enabled == nil) {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
principal, _ := middleware.CurrentPrincipal(c)
patch := authn.UserPatch{Enabled: req.Enabled}
if req.Role != nil {
role := authn.Role(*req.Role)
patch.Role = &role
}
username := c.Param("username")
if _, err := authn.DefaultStore.Update(principal.Username, username, patch); err != nil {
rsp.ErrRsp(c, -2, err.Error())
return
}
middleware.RevokeUserSessions(username)
rsp.OkRsp(c)
log.Infof("user updated: %s", username)
}
func (s *Service) DeleteUser(c *gin.Context) {
var rsp proto.Response
principal, _ := middleware.CurrentPrincipal(c)
username := c.Param("username")
if err := authn.DefaultStore.Delete(principal.Username, username); err != nil {
rsp.ErrRsp(c, -1, err.Error())
return
}
middleware.RevokeUserSessions(username)
rsp.OkRsp(c)
log.Infof("user deleted: %s", username)
}
func (s *Service) ChangeUserPassword(c *gin.Context) {
var req proto.ChangePasswordReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid parameters")
return
}
username := c.Param("username")
user, err := authn.DefaultStore.Get(username)
if err != nil {
rsp.ErrRsp(c, -2, err.Error())
return
}
if user.SystemAccount {
rsp.ErrRsp(c, -3, "the device owner must change its own password")
return
}
if err := changeUserPassword(username, req.Password); err != nil {
rsp.ErrRsp(c, -4, err.Error())
return
}
middleware.RevokeUserSessions(username)
rsp.OkRsp(c)
log.Infof("password reset for user: %s", username)
}
func decodePassword(encrypted string) (string, error) {
password, err := utils.DecodeDecrypt(encrypted)
if err != nil || password == "" {
return "", errInvalidPassword
}
if err = authn.ValidatePassword(password); err != nil {
return "", err
}
return password, nil
}

View File

@@ -2,6 +2,7 @@ package download
import (
"NanoKVM-Server/proto"
"NanoKVM-Server/utils"
"bytes"
"context"
"crypto/sha256"
@@ -21,22 +22,36 @@ import (
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
type downloadStatus string
const (
transferSentinelPath = "/tmp/.download_in_progress"
transferSentinelPath = utils.TransferSentinelPath
downloadStatusIdle downloadStatus = "idle"
downloadStatusInProgress downloadStatus = "in_progress"
downloadStatusSuccess downloadStatus = "success"
downloadStatusFailed downloadStatus = "failed"
downloadStatusChecksumFailed downloadStatus = "checksum_failed"
imageDirectory = "/data"
// ISO 9660 and UDF volume descriptors live in sector 16 of the image.
volumeDescriptorOffset = 0x8001
volumeDescriptorSize = 5
// Only the descriptors are read before the image is stored, so an unusable
// image is rejected without transferring all of it.
imageHeaderSize = volumeDescriptorOffset + volumeDescriptorSize
// Keep /data from filling up completely: the exFAT metadata and the USB
// mass-storage export still need room while the image is written.
imageFreeReserve = 128 << 20
)
var (
errDownloadInProgress = errors.New("download in progress")
errSHA256Mismatch = errors.New("sha256 mismatch")
errUnsupportedImage = errors.New("unsupported image format: expected an ISO 9660/UDF image or a raw disk image")
validISOFilename = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
)
@@ -163,24 +178,73 @@ func (s *Service) ImageEnabled(c *gin.Context) {
rsp.OkRspWithData(c, &proto.ImageEnabledRsp{Enabled: true})
}
func isISO9660(path string) (bool, error) {
f, err := os.Open(path)
if err != nil {
return false, err
}
defer f.Close()
// ISO-9660 magic "CD001" at offset 32769.
if _, err = f.Seek(0x8001, io.SeekStart); err != nil {
return false, err
// isSupportedImage reports whether the uploaded image can be exposed through
// the USB mass-storage gadget. ISO 9660 images and UDF bridges, which is what
// bootable installer ISOs are normally built as, carry "CD001" in the volume
// descriptor sector, while UDF-only images carry "BEA01" there.
func isSupportedImage(head []byte) bool {
if len(head) >= volumeDescriptorOffset+volumeDescriptorSize {
switch string(head[volumeDescriptorOffset : volumeDescriptorOffset+volumeDescriptorSize]) {
case "CD001", "BEA01":
return true
}
}
buf := make([]byte, 5)
if _, err = io.ReadFull(f, buf); err != nil {
return false, err
return looksLikeDiskImage(head)
}
// looksLikeDiskImage reports whether the image starts with a partition table or
// a filesystem that a target machine can mount on its own, which covers raw
// disk images such as macOS installers converted from a DMG.
func looksLikeDiskImage(head []byte) bool {
if len(head) < 0x200 {
return false
}
return string(buf) == "CD001", nil
if len(head) >= 0x208 && string(head[0x200:0x208]) == "EFI PART" { // GPT header
return true
}
if len(head) >= 0x24 && string(head[0x20:0x24]) == "NXSB" { // APFS container superblock
return true
}
if len(head) >= 0x402 {
switch string(head[0x400:0x402]) { // HFS+/HFS volume header
case "H+", "BD":
return true
}
}
// MBR partition table. FAT, exFAT and NTFS volume images carry the same
// signature in their boot sector.
return head[0x1FE] == 0x55 && head[0x1FF] == 0xAA
}
// ensureImageSpace rejects an upload that cannot fit into dir, keeping a small
// reserve for filesystem metadata and for the USB mass-storage export.
func ensureImageSpace(dir string, contentLength int64) error {
if contentLength <= 0 {
return nil
}
var stat unix.Statfs_t
if err := unix.Statfs(dir, &stat); err != nil {
return fmt.Errorf("cannot read free space of %s: %w", dir, err)
}
available := uint64(stat.Bavail) * uint64(stat.Bsize)
payload := uint64(contentLength)
if payload > available || available-payload < imageFreeReserve {
return fmt.Errorf(
"not enough space in %s: need %d MiB including reserve, %d MiB available",
dir,
(payload+imageFreeReserve)>>20,
available>>20,
)
}
return nil
}
func (s *Service) StatusImage(c *gin.Context) {
@@ -209,6 +273,13 @@ func (s *Service) DownloadImageFile(c *gin.Context) {
return
}
// Reject an upload that cannot fit before any of it is received.
if err := ensureImageSpace(imageDirectory, c.Request.ContentLength); err != nil {
log.Warnf("reject image upload: %s", err)
rsp.ErrRsp(c, -1, err.Error())
return
}
done, err := s.beginDownload("", nil)
if err != nil {
rsp.ErrRsp(c, -1, err.Error())
@@ -243,16 +314,17 @@ func (s *Service) DownloadImageFile(c *gin.Context) {
filename := part.FileName()
if err := validateISOFilename(filename); err != nil {
_ = part.Close()
log.Warnf("reject uploaded image %q: %s", filename, err)
rsp.ErrRsp(c, -1, err.Error())
return
}
s.setDownloadFile(done, filename)
out, err := os.CreateTemp("/data", ".nanokvm-upload-*")
// The rejection paths below return without draining the request body: the
// client stops uploading as soon as the response arrives.
out, err := os.CreateTemp(imageDirectory, ".nanokvm-upload-*")
if err != nil {
_ = part.Close()
log.Error("cannot create temporary file")
log.Errorf("cannot create temporary file in %s: %s", imageDirectory, err)
rsp.ErrRsp(c, -1, "cannot create temporary file")
return
}
@@ -263,12 +335,30 @@ func (s *Service) DownloadImageFile(c *gin.Context) {
lw := newLoggingWriter(io.MultiWriter(out, hasher), c.Request.ContentLength, func(percentage string) {
s.setDownloadProgress(done, percentage)
})
_, copyErr := io.Copy(lw, part)
lw.stopTicker()
partCloseErr := part.Close()
outCloseErr := out.Close()
if copyErr != nil || partCloseErr != nil || outCloseErr != nil {
log.Error("write failed")
defer lw.stopTicker()
// Check the volume descriptors while streaming, so an unusable image is
// rejected in seconds instead of after the whole upload.
head := make([]byte, imageHeaderSize)
headSize, readErr := io.ReadFull(part, head)
if readErr != nil && readErr != io.ErrUnexpectedEOF && readErr != io.EOF {
log.Errorf("read uploaded image %q failed: %s", filename, readErr)
rsp.ErrRsp(c, -1, "write failed")
return
}
if !isSupportedImage(head[:headSize]) {
log.Warnf("reject uploaded image %q: %s", filename, errUnsupportedImage)
rsp.ErrRsp(c, -1, errUnsupportedImage.Error())
return
}
_, copyErr := lw.Write(head[:headSize])
if copyErr == nil {
_, copyErr = io.Copy(lw, part)
}
closeErr := out.Close()
if copyErr != nil || closeErr != nil {
log.Errorf("write uploaded image %q failed: %s", filename, errors.Join(copyErr, closeErr))
rsp.ErrRsp(c, -1, "write failed")
return
}
@@ -279,13 +369,7 @@ func (s *Service) DownloadImageFile(c *gin.Context) {
return
}
valid, err := isISO9660(tempPath)
if err != nil || !valid {
rsp.ErrRsp(c, -1, "file is not a valid ISO image")
return
}
outPath := filepath.Join("/data", filename)
outPath := filepath.Join(imageDirectory, filename)
if err := os.Rename(tempPath, outPath); err != nil {
rsp.ErrRsp(c, -1, "cannot install uploaded image")
return
@@ -421,7 +505,7 @@ func (s *Service) downloadRemoteImage(
return fmt.Errorf("download request returned status %d", resp.StatusCode)
}
tempFile, err := os.CreateTemp("/data", ".nanokvm-download-*")
tempFile, err := os.CreateTemp(imageDirectory, ".nanokvm-download-*")
if err != nil {
return fmt.Errorf("create temporary image failed: %w", err)
}
@@ -450,7 +534,7 @@ func (s *Service) downloadRemoteImage(
return ctx.Err()
}
destPath := filepath.Join("/data", filename)
destPath := filepath.Join(imageDirectory, filename)
if err := os.Rename(tempPath, destPath); err != nil {
return fmt.Errorf("install downloaded image failed: %w", err)
}

View File

@@ -0,0 +1,73 @@
package download
import (
"bytes"
"path/filepath"
"testing"
)
func headWithDescriptor(magic string) []byte {
head := make([]byte, imageHeaderSize)
copy(head[volumeDescriptorOffset:], magic)
return head
}
func TestIsSupportedImage(t *testing.T) {
mbr := make([]byte, imageHeaderSize)
mbr[0x1FE], mbr[0x1FF] = 0x55, 0xAA
gpt := make([]byte, imageHeaderSize)
copy(gpt[0x200:], "EFI PART")
apfs := make([]byte, imageHeaderSize)
copy(apfs[0x20:], "NXSB")
hfs := make([]byte, imageHeaderSize)
copy(hfs[0x400:], "H+")
tests := []struct {
name string
head []byte
want bool
}{
{"iso9660 image", headWithDescriptor("CD001"), true},
{"udf bridge image", headWithDescriptor("CD001"), true},
{"udf only image", headWithDescriptor("BEA01"), true},
{"gpt disk image", gpt, true},
{"apfs disk image", apfs, true},
{"hfs+ disk image", hfs, true},
{"mbr disk image", mbr, true},
{"compressed dmg", make([]byte, imageHeaderSize), false},
{"plain data", bytes.Repeat([]byte{0xA5}, imageHeaderSize), false},
{"truncated image", headWithDescriptor("CD001")[:16], false},
{"empty image", nil, false},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := isSupportedImage(test.head); got != test.want {
t.Fatalf("isSupportedImage(%s) = %v, want %v", test.name, got, test.want)
}
})
}
}
func TestEnsureImageSpace(t *testing.T) {
dir := t.TempDir()
if err := ensureImageSpace(dir, 0); err != nil {
t.Fatalf("an upload without a known size must not be rejected: %v", err)
}
if err := ensureImageSpace(dir, 1<<20); err != nil {
t.Fatalf("a small upload must fit: %v", err)
}
if err := ensureImageSpace(dir, 1<<62); err == nil {
t.Fatal("an upload larger than the filesystem must be rejected")
}
if err := ensureImageSpace(filepath.Join(dir, "missing"), 1<<20); err == nil {
t.Fatal("a missing directory must be rejected")
}
}

View File

@@ -7,6 +7,7 @@ import (
"sync"
"time"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/stream/mjpeg"
@@ -19,9 +20,7 @@ import (
var gatewayUpgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(r *http.Request) bool {
return true
},
CheckOrigin: middleware.CheckWebSocketOrigin,
}
type relayResult struct {
@@ -88,6 +87,8 @@ func (s *Service) ConnectGateway(c *gin.Context) {
GetSessionManager().Remove(sessionID)
return
}
stopSessionWatcher := middleware.WatchWebSocket(c.Request.Context(), downstream)
defer stopSessionWatcher()
GetSessionManager().AttachUpstream(sessionID, upstream)
GetSessionManager().AttachDownstream(sessionID, downstream)

View File

@@ -1,6 +1,7 @@
package storage
import (
"errors"
"fmt"
"os"
"os/exec"
@@ -8,9 +9,11 @@ import (
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
"NanoKVM-Server/proto"
"NanoKVM-Server/service/hid"
@@ -23,6 +26,12 @@ const (
mountDevice = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/file"
inquiryString = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/inquiry_string"
roFlag = "/sys/kernel/config/usb_gadget/g0/functions/mass_storage.disk0/lun.0/ro"
usbProduct = "/sys/kernel/config/usb_gadget/g0/strings/0x409/product"
usbProductName = "NanoKVM"
// the SCSI inquiry product field holds 16 bytes, the USB product string 126
inquiryProductSize = 16
usbProductSize = 126
)
func (s *Service) GetImages(c *gin.Context) {
@@ -63,35 +72,49 @@ func (s *Service) MountImage(c *gin.Context) {
return
}
// cdrom and ro flag
// The host owns the raw partition while the virtual disk serves it, so /data
// has to be read-only here before the host can write it.
if req.File == "" {
if err := SetDataWritable(false); err != nil {
log.Errorf("make %s read-only failed: %s", imageDirectory, err)
rsp.ErrRsp(c, -2, "make /data read-only failed")
return
}
}
// set the LUN flags, unmounting first so no image is ever served writable
if err := os.WriteFile(mountDevice, []byte("\n"), 0o666); err != nil {
log.Errorf("unmount file failed: %s", err)
rsp.ErrRsp(c, -2, "unmount image failed")
return
}
// ro flag
// set to 0 when unmount image
// set to 1 when mount image, the host can only read the image
roFlagValue := "0"
if req.File != "" {
roFlagValue = "1"
}
if err := os.WriteFile(roFlag, []byte(roFlagValue), 0o666); err != nil {
log.Errorf("set ro flag failed: %s", err)
rsp.ErrRsp(c, -2, "set ro flag failed")
return
}
// cdrom flag
// set to 0 when unmount image
// set to 1 when mount image and the CD-ROM is enabled
if req.File == "" || req.Cdrom {
flag := "0"
if req.File != "" && req.Cdrom {
flag = "1"
}
cdromFlagValue := "0"
if req.File != "" && req.Cdrom {
cdromFlagValue = "1"
}
// unmount
if err := os.WriteFile(mountDevice, []byte("\n"), 0o666); err != nil {
log.Errorf("unmount file failed: %s", err)
rsp.ErrRsp(c, -2, "unmount image failed")
return
}
// ro flag
if err := os.WriteFile(roFlag, []byte(flag), 0o666); err != nil {
log.Errorf("set ro flag failed: %s", err)
rsp.ErrRsp(c, -2, "set ro flag failed")
return
}
// cdrom flag
if err := os.WriteFile(cdromFlag, []byte(flag), 0o666); err != nil {
log.Errorf("set cdrom flag failed: %s", err)
rsp.ErrRsp(c, -2, "set cdrom flag failed")
return
}
if err := os.WriteFile(cdromFlag, []byte(cdromFlagValue), 0o666); err != nil {
log.Errorf("set cdrom flag failed: %s", err)
rsp.ErrRsp(c, -2, "set cdrom flag failed")
return
}
inquiryVen := "NanoKVM"
@@ -100,6 +123,17 @@ func (s *Service) MountImage(c *gin.Context) {
if req.Cdrom {
inquiryPrd = "USB CD/DVD-ROM"
}
// the image name is what the host shows for the device and for the medium,
// the SCSI inquiry is the medium and the USB product string the device itself
productName := usbProductName
if req.File != "" {
if name := imageName(req.File); name != "" {
inquiryPrd = cutName(name, inquiryProductSize)
productName = cutName(name, usbProductSize)
}
}
inquiryData := fmt.Sprintf("%-8s%-16s%04x", inquiryVen, inquiryPrd, inquiryVer)
if err := os.WriteFile(inquiryString, []byte(inquiryData), 0o666); err != nil {
@@ -108,6 +142,10 @@ func (s *Service) MountImage(c *gin.Context) {
return
}
if err := os.WriteFile(usbProduct, []byte(productName), 0o666); err != nil {
log.Errorf("set usb product %s failed: %s", productName, err)
}
// mount
image := req.File
if image == "" {
@@ -120,6 +158,14 @@ func (s *Service) MountImage(c *gin.Context) {
return
}
// An image is served read-only, so the KVM writes /data itself again. The
// host can not write the image either way.
if req.File != "" {
if err := SetDataWritable(true); err != nil {
log.Warnf("make %s writable failed: %s", imageDirectory, err)
}
}
h := hid.GetHid()
h.Lock()
h.CloseNoLock()
@@ -163,17 +209,12 @@ func (s *Service) GetMountedImage(c *gin.Context) {
return
}
content, err := os.ReadFile(mountDevice)
image, err := MountedImage()
if err != nil {
rsp.ErrRsp(c, -2, "read failed")
return
}
image := strings.ReplaceAll(string(content), "\n", "")
if image == imageNone {
image = ""
}
data := &proto.GetMountedImageRsp{
File: image,
}
@@ -181,6 +222,85 @@ func (s *Service) GetMountedImage(c *gin.Context) {
rsp.OkRspWithData(c, data)
}
// MountedImage returns the mounted image file, empty if no image is mounted
func MountedImage() (string, error) {
content, err := os.ReadFile(mountDevice)
if err != nil {
return "", err
}
image := strings.ReplaceAll(string(content), "\n", "")
if image == imageNone {
image = ""
}
return image, nil
}
// imageName returns the file name of an image without the extension
func imageName(file string) string {
return strings.TrimSuffix(filepath.Base(file), filepath.Ext(file))
}
// cutName cuts a name to size bytes without splitting a character
func cutName(name string, size int) string {
if len(name) <= size {
return name
}
name = name[:size]
for !utf8.ValidString(name) {
name = name[:len(name)-1]
}
return name
}
// SetDataWritable remounts /data read-write or read-only. Only one side may
// write the partition at a time: while the virtual disk shares it with the host
// as a writable disk, /data is read-only here, and it becomes writable again
// once the share is released or an image is served read-only instead.
func SetDataWritable(writable bool) error {
var stat unix.Statfs_t
if err := unix.Statfs(imageDirectory, &stat); err != nil {
return err
}
if (stat.Flags&unix.ST_RDONLY == 0) == writable {
return nil
}
option := "rw"
if !writable {
option = "ro"
}
if err := exec.Command("mount", "-o", "remount,"+option, imageDirectory).Run(); err != nil {
return err
}
// never hand a writable /data to the host
var check unix.Statfs_t
if err := unix.Statfs(imageDirectory, &check); err != nil {
return err
}
if (check.Flags&unix.ST_RDONLY == 0) != writable {
return errors.New(imageDirectory + " mount did not change")
}
return nil
}
// DataDiskAttached reports whether the mass storage device serves the whole /data partition to the host
func DataDiskAttached() bool {
content, err := os.ReadFile(mountDevice)
if err != nil {
return false
}
return strings.ReplaceAll(string(content), "\n", "") == imageNone
}
func (s *Service) GetCdRom(c *gin.Context) {
var rsp proto.Response

View File

@@ -0,0 +1,42 @@
package storage
import "testing"
func TestImageName(t *testing.T) {
tests := []struct {
file string
want string
}{
{"/data/ubuntu.iso", "ubuntu"},
{"/data/win11.img", "win11"},
{"/data/a.b.c.iso", "a.b.c"},
{"/data/no-extension", "no-extension"},
}
for _, tt := range tests {
if got := imageName(tt.file); got != tt.want {
t.Errorf("imageName(%q) = %q, want %q", tt.file, got, tt.want)
}
}
}
func TestCutName(t *testing.T) {
tests := []struct {
name string
size int
want string
}{
{"ubuntu", 16, "ubuntu"},
{"Install_macOS_27_Golden_Gate", 16, "Install_macOS_27"},
{"Install_macOS_27_Golden_Gate", 126, "Install_macOS_27_Golden_Gate"},
// 16 bytes is 5 three byte runes and 1 spare byte
{"中文安装镜像文件系统", 16, "中文安装镜"},
{"中文安装镜像文件系统", 126, "中文安装镜像文件系统"},
}
for _, tt := range tests {
if got := cutName(tt.name, tt.size); got != tt.want {
t.Errorf("cutName(%q, %d) = %q, want %q", tt.name, tt.size, got, tt.want)
}
}
}

View File

@@ -1,8 +1,8 @@
package direct
import (
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/stream"
"net/http"
"strconv"
"time"
@@ -17,9 +17,7 @@ var (
streamer = newStreamer()
upgrader = websocket.Upgrader{
WriteBufferSize: 256 * 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
CheckOrigin: middleware.CheckWebSocketOrigin,
}
)
@@ -29,6 +27,8 @@ func Connect(c *gin.Context) {
log.Errorf("failed to upgrade to websocket: %s", err)
return
}
stopSessionWatcher := middleware.WatchWebSocket(c.Request.Context(), ws)
defer stopSessionWatcher()
client := newClient(ws)
if flowWindow, err := strconv.Atoi(c.Query("flow")); err == nil && flowWindow > 0 {
client.queue.enableFlowControl(flowWindow)

View File

@@ -1,12 +1,10 @@
package direct
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"NanoKVM-Server/service/vm"
"sync"
"sync/atomic"
"time"
log "github.com/sirupsen/logrus"
)
@@ -87,17 +85,14 @@ func (s *Streamer) getClients() []*client {
}
func (s *Streamer) run() {
screen := common.GetScreen()
common.CheckScreen()
fps := screen.FPS
subscription := stream.SubscribeH264()
defer subscription.Close()
ticker := time.NewTicker(time.Second / time.Duration(fps))
defer ticker.Stop()
vision := common.GetKvmVision()
startTime := time.Now()
for range ticker.C {
for {
frame, ok := subscription.Next()
if !ok {
return
}
clients := s.getClients()
if len(clients) == 0 {
if s.stopIfIdle() {
@@ -107,28 +102,19 @@ func (s *Streamer) run() {
continue
}
if screen.FPS != fps && screen.FPS != 0 {
fps = screen.FPS
ticker.Reset(time.Second / time.Duration(fps))
}
if !hasCaptureDemand(clients) {
continue
}
data, result := vision.ReadH264(screen.Width, screen.Height, screen.BitRate)
stream.UpdateCaptureStatus(stream.CaptureModeDirect, result)
if result < 0 || len(data) == 0 {
stream.UpdateCaptureStatus(stream.CaptureModeDirect, frame.Result)
if frame.Result < 0 || len(frame.Data) == 0 {
continue
}
timestamp := time.Since(startTime).Microseconds()
frame := newOutboundFrame(result == 3, timestamp, data)
outbound := newOutboundFrame(frame.Result == 3, frame.Timestamp, frame.Data)
for _, client := range clients {
client.offer(frame)
client.offer(outbound)
}
stream.GetFrameRateCounter().Update()
}
}

View File

@@ -0,0 +1,185 @@
package stream
import (
"NanoKVM-Server/common"
"sync"
"sync/atomic"
"time"
)
type H264Frame struct {
Data []byte
Result int
Duration time.Duration
Timestamp int64
}
type H264Subscription struct {
frames chan H264Frame
done chan struct{}
closed atomic.Bool
once sync.Once
waitingForKeyframe bool
}
type H264Source struct {
mutex sync.Mutex
subscribers map[*H264Subscription]struct{}
running bool
}
var defaultH264Source = &H264Source{
subscribers: make(map[*H264Subscription]struct{}),
}
func SubscribeH264() *H264Subscription {
return defaultH264Source.subscribe()
}
func (s *H264Source) subscribe() *H264Subscription {
subscription := &H264Subscription{
frames: make(chan H264Frame, 4),
done: make(chan struct{}),
}
s.mutex.Lock()
s.subscribers[subscription] = struct{}{}
start := !s.running
if start {
s.running = true
}
s.mutex.Unlock()
if start {
go s.run()
}
return subscription
}
func (s *H264Subscription) Next() (H264Frame, bool) {
select {
case frame := <-s.frames:
return frame, true
case <-s.done:
return H264Frame{}, false
}
}
func (s *H264Subscription) Close() {
s.once.Do(func() {
s.closed.Store(true)
close(s.done)
defaultH264Source.remove(s)
})
}
func (s *H264Source) remove(subscription *H264Subscription) {
s.mutex.Lock()
delete(s.subscribers, subscription)
s.mutex.Unlock()
}
func (s *H264Source) run() {
screen := common.GetScreen()
common.CheckScreen()
fps := screen.FPS
ticker := time.NewTicker(time.Second / time.Duration(fps))
defer ticker.Stop()
vision := common.GetKvmVision()
startTime := time.Now()
for range ticker.C {
subscribers := s.snapshot()
if len(subscribers) == 0 {
s.mutex.Lock()
if len(s.subscribers) == 0 {
s.running = false
s.mutex.Unlock()
return
}
s.mutex.Unlock()
continue
}
if screen.FPS != fps && screen.FPS != 0 {
fps = screen.FPS
ticker.Reset(time.Second / time.Duration(fps))
}
data, result := vision.ReadH264(screen.Width, screen.Height, screen.BitRate)
if result < 0 {
frame := H264Frame{Result: result}
for _, subscription := range subscribers {
subscription.send(frame)
}
continue
}
if len(data) == 0 {
continue
}
frame := H264Frame{
Data: data,
Result: result,
Duration: time.Second / time.Duration(fps),
Timestamp: time.Since(startTime).Microseconds(),
}
for _, subscription := range subscribers {
subscription.send(frame)
}
GetFrameRateCounter().Update()
}
}
func (s *H264Source) snapshot() []*H264Subscription {
s.mutex.Lock()
defer s.mutex.Unlock()
subscribers := make([]*H264Subscription, 0, len(s.subscribers))
for subscription := range s.subscribers {
subscribers = append(subscribers, subscription)
}
return subscribers
}
func (s *H264Subscription) send(frame H264Frame) bool {
if s.closed.Load() {
return false
}
if s.waitingForKeyframe {
if frame.Result != 3 {
return false
}
s.waitingForKeyframe = false
}
select {
case s.frames <- frame:
return true
case <-s.done:
return false
default:
}
for {
select {
case <-s.frames:
case <-s.done:
return false
default:
s.waitingForKeyframe = true
if frame.Result != 3 {
return false
}
s.waitingForKeyframe = false
select {
case s.frames <- frame:
return true
case <-s.done:
return false
}
}
}
}

View File

@@ -2,17 +2,16 @@ package webrtc
import (
"encoding/json"
"errors"
"github.com/gorilla/websocket"
"github.com/pion/rtp"
"github.com/pion/rtp/codecs"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
"sync"
)
const h264SDPFmtpLine = "level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=4d001f"
func NewClient(ws *websocket.Conn, videoConn *webrtc.PeerConnection) *Client {
return &Client{
ws: ws,
@@ -72,7 +71,11 @@ func (c *Client) ReadMessage() (*Message, error) {
func (c *Client) AddTrack() error {
// video track
videoTrack, err := webrtc.NewTrackLocalStaticRTP(
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeH264},
webrtc.RTPCodecCapability{
MimeType: webrtc.MimeTypeH264,
ClockRate: 90000,
SDPFmtpLine: h264SDPFmtpLine,
},
"video",
"pion-video",
)
@@ -81,20 +84,6 @@ func (c *Client) AddTrack() error {
return err
}
videoPacketizer := rtp.NewPacketizer(
1200,
100,
0x1234ABCD,
&codecs.H264Payloader{},
rtp.NewRandomSequencer(),
90000,
)
if videoPacketizer == nil {
err := errors.New("failed to create rtp packetizer")
log.Error(err)
return err
}
videoSender, err := c.video.AddTrack(videoTrack)
if err != nil {
log.Errorf("failed to add video track: %s", err)
@@ -103,10 +92,8 @@ func (c *Client) AddTrack() error {
go startRTCPReader(videoSender)
track := &Track{
videoPacketizer: videoPacketizer,
video: videoTrack,
video: videoTrack,
}
track.updateExtension()
c.mutex.Lock()
c.track = track

View File

@@ -2,14 +2,15 @@ package webrtc
import (
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"encoding/json"
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/pion/dtls/v3"
"github.com/pion/interceptor"
"github.com/pion/webrtc/v4"
log "github.com/sirupsen/logrus"
)
@@ -17,9 +18,7 @@ import (
var (
upgrader = websocket.Upgrader{
WriteBufferSize: 256 * 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
CheckOrigin: middleware.CheckWebSocketOrigin,
}
globalManager *WebRTCManager
managerOnce sync.Once
@@ -39,6 +38,8 @@ func Connect(c *gin.Context) {
log.Errorf("failed to create h264 websocket: %s", err)
return
}
stopSessionWatcher := middleware.WatchWebSocket(c.Request.Context(), wsConn)
defer stopSessionWatcher()
defer func() {
_ = wsConn.Close()
log.Debugf("h264 websocket disconnected: %s", c.ClientIP())
@@ -151,14 +152,6 @@ func createMediaEngine() (*webrtc.MediaEngine, error) {
return nil, err
}
if err := mediaEngine.RegisterHeaderExtension(
webrtc.RTPHeaderExtensionCapability{URI: "http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"},
webrtc.RTPCodecTypeVideo,
); err != nil {
log.Errorf("failed to register header extension: %s", err)
return nil, err
}
return mediaEngine, nil
}
@@ -173,6 +166,14 @@ func createPeerConnection(iceServers []webrtc.ICEServer, mediaEngine *webrtc.Med
webrtc.WithSettingEngine(settingEngine),
}
if mediaEngine != nil {
registry := &interceptor.Registry{}
if err := webrtc.ConfigureNack(mediaEngine, registry); err != nil {
return nil, err
}
if err := webrtc.ConfigureRTCPReports(registry); err != nil {
return nil, err
}
apiOptions = append(apiOptions, webrtc.WithInterceptorRegistry(registry))
apiOptions = append(apiOptions, webrtc.WithMediaEngine(mediaEngine))
}

View File

@@ -1,19 +1,27 @@
package webrtc
import (
"NanoKVM-Server/common"
"NanoKVM-Server/service/stream"
"NanoKVM-Server/service/vm"
"time"
"github.com/gorilla/websocket"
"github.com/pion/rtp"
"github.com/pion/rtp/codecs"
"github.com/pion/webrtc/v4/pkg/media"
log "github.com/sirupsen/logrus"
)
func NewWebRTCManager() *WebRTCManager {
m := &WebRTCManager{
clients: make(map[*websocket.Conn]*Client),
clients: make(map[*websocket.Conn]*Client),
videoPacketizer: rtp.NewPacketizer(
1200,
100,
0x1234ABCD,
&codecs.H264Payloader{},
rtp.NewRandomSequencer(),
90000,
),
videoSending: false,
}
m.updateClientSnapshotLocked()
@@ -22,8 +30,6 @@ func NewWebRTCManager() *WebRTCManager {
}
func (m *WebRTCManager) AddClient(ws *websocket.Conn, client *Client) {
client.track.updateExtension()
m.mutex.Lock()
m.clients[ws] = client
count := m.updateClientSnapshotLocked()
@@ -96,52 +102,62 @@ func (m *WebRTCManager) stopVideoStreamIfIdle() bool {
}
func (m *WebRTCManager) sendVideoStream() {
screen := common.GetScreen()
common.CheckScreen()
fps := screen.FPS
duration := time.Second / time.Duration(fps)
subscription := stream.SubscribeH264()
defer subscription.Close()
samples, writerDone := m.startVideoWriter()
vision := common.GetKvmVision()
ticker := time.NewTicker(duration)
defer ticker.Stop()
for range ticker.C {
for {
frame, ok := subscription.Next()
if !ok {
close(samples)
<-writerDone
return
}
clients := m.getClients()
if len(clients) == 0 {
close(samples)
<-writerDone
if m.stopVideoStreamIfIdle() {
log.Debugf("stop sending h264 stream")
return
}
samples, writerDone = m.startVideoWriter()
continue
}
data, result := vision.ReadH264(screen.Width, screen.Height, screen.BitRate)
stream.UpdateCaptureStatus(stream.CaptureModeH264, result)
if result < 0 || len(data) == 0 {
stream.UpdateCaptureStatus(stream.CaptureModeH264, frame.Result)
if frame.Result < 0 || len(frame.Data) == 0 {
continue
}
sample := media.Sample{
Data: data,
Duration: duration,
Data: frame.Data,
Duration: frame.Duration,
}
for _, client := range clients {
if err := client.track.writeVideoSample(sample); err != nil {
log.Errorf("failed to write h264 video to client: %s", err)
m.RemoveClient(client.WsConn())
client.Close()
}
}
if screen.FPS != fps && screen.FPS != 0 {
fps = screen.FPS
duration = time.Second / time.Duration(fps)
ticker.Reset(duration)
}
stream.GetFrameRateCounter().Update()
samples <- sample
}
}
func (m *WebRTCManager) startVideoWriter() (chan media.Sample, <-chan struct{}) {
samples := make(chan media.Sample, 1)
done := make(chan struct{})
go func() {
defer close(done)
for sample := range samples {
packets := m.videoPacketizer.Packetize(sample.Data, uint32(sample.Duration.Seconds()*90000))
for _, client := range m.getClients() {
err := client.track.writeVideoPackets(packets)
if err != nil {
log.Errorf("failed to write h264 video to client: %s", err)
m.RemoveClient(client.WsConn())
client.Close()
}
}
}
}()
return samples, done
}

View File

@@ -157,11 +157,6 @@ func (s *SignalingHandler) handleVideoOffer(data string) error {
return err
}
if err := s.updateHeaderExtensionID(); err != nil {
log.Errorf("could not update header extension ID: %v", err)
return err
}
answerByte, err := json.Marshal(answer)
if err != nil {
log.Errorf("failed to marshal answer: %s", err)
@@ -171,30 +166,6 @@ func (s *SignalingHandler) handleVideoOffer(data string) error {
return s.client.WriteMessage("video-answer", string(answerByte))
}
// set extension ID
func (s *SignalingHandler) updateHeaderExtensionID() error {
receivers := s.client.video.GetReceivers()
if len(receivers) == 0 {
return errors.New("no RTP receiver found for video")
}
params := receivers[0].GetParameters()
if len(params.HeaderExtensions) == 0 {
return errors.New("no header extensions found in negotiated parameters")
}
for _, ext := range params.HeaderExtensions {
if ext.URI == "http://www.webrtc.org/experiments/rtp-hdrext/playout-delay" {
s.client.track.playoutDelayExtensionID = uint8(ext.ID)
log.Debugf("found and set playout delay extension ID to: %d", ext.ID)
return nil
}
}
log.Warnf("no track extension found in negotiated parameters, use default value 5")
return nil
}
// handle video candidate
func (s *SignalingHandler) handleVideoCandidate(data string) error {
candidate := webrtc.ICECandidateInit{}

View File

@@ -2,42 +2,11 @@ package webrtc
import (
"github.com/pion/rtp"
"github.com/pion/webrtc/v4/pkg/media"
log "github.com/sirupsen/logrus"
)
func (t *Track) updateExtension() {
if t.playoutDelayExtensionID == 0 {
t.playoutDelayExtensionID = 5
}
if len(t.playoutDelayExtensionData) == 0 {
playoutDelay := &rtp.PlayoutDelayExtension{
MinDelay: 0,
MaxDelay: 0,
}
playoutDelayExtensionData, err := playoutDelay.Marshal()
if err == nil {
t.playoutDelayExtensionData = playoutDelayExtensionData
}
}
}
func (t *Track) writeVideoSample(sample media.Sample) error {
samples := uint32(sample.Duration.Seconds() * 90000)
packets := t.videoPacketizer.Packetize(sample.Data, samples)
for _, p := range packets {
p.Header.Extension = true
p.Header.ExtensionProfile = 0xBEDE
if err := p.Header.SetExtension(t.playoutDelayExtensionID, t.playoutDelayExtensionData); err != nil {
log.Errorf("Failed to set extension: %v", err)
return err
}
if err := t.video.WriteRTP(p); err != nil {
log.Errorf("failed to write RTP: %v", err)
func (t *Track) writeVideoPackets(packets []*rtp.Packet) error {
for _, packet := range packets {
if err := t.video.WriteRTP(packet); err != nil {
return err
}
}

View File

@@ -10,11 +10,12 @@ import (
)
type WebRTCManager struct {
clients map[*websocket.Conn]*Client
clientSnapshot atomic.Pointer[[]*Client]
videoSending bool
mutex sync.Mutex
viewerVersion uint64
clients map[*websocket.Conn]*Client
clientSnapshot atomic.Pointer[[]*Client]
videoPacketizer rtp.Packetizer
videoSending bool
mutex sync.Mutex
viewerVersion uint64
}
type Client struct {
@@ -36,10 +37,7 @@ type SignalingHandler struct {
}
type Track struct {
playoutDelayExtensionID uint8
playoutDelayExtensionData []byte
videoPacketizer rtp.Packetizer
video *webrtc.TrackLocalStaticRTP
video *webrtc.TrackLocalStaticRTP
}
type Message struct {

View File

@@ -27,6 +27,7 @@ var (
setHDMI = func(enabled bool) { common.GetKvmVision().SetHDMI(enabled) }
isHdmiDisabled = utils.IsHdmiDisabled
getHdmiIdleTimeout = utils.GetHDMIIdleTimeout
getHdmiSignal = func() bool { return common.GetKvmVision().HasHDMISignal() }
)
func (s *Service) ResetHdmi(c *gin.Context) {
@@ -63,10 +64,12 @@ func (s *Service) DisableHdmi(c *gin.Context) {
func (s *Service) GetHdmiState(c *gin.Context) {
var rsp proto.Response
enabled := !isHdmiDisabled()
rsp.OkRspWithData(c, &proto.GetGetHdmiStateRsp{
Enabled: !utils.IsHdmiDisabled(),
IdleTimeout: utils.GetHDMIIdleTimeout(),
Enabled: enabled,
Signal: enabled && getHdmiSignal(),
IdleTimeout: getHdmiIdleTimeout(),
})
log.Debug("get hdmi state")

View File

@@ -0,0 +1,389 @@
package vm
import (
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
)
var (
inputRegionFile = "/etc/kvm/input-region.json"
inputRegionMu sync.RWMutex
)
func (s *Service) GetInputResolution(c *gin.Context) {
var rsp proto.Response
width, widthErr := readPositiveInt("/kvmapp/kvm/width")
height, heightErr := readPositiveInt("/kvmapp/kvm/height")
if widthErr != nil || heightErr != nil {
rsp.ErrRsp(c, -1, "failed to read input resolution")
return
}
rsp.OkRspWithData(c, &proto.GetInputResolutionRsp{Width: width, Height: height})
}
func readPositiveInt(path string) (int, error) {
data, err := os.ReadFile(path)
if err != nil {
return 0, err
}
value, err := strconv.Atoi(strings.TrimSpace(string(data)))
if err != nil || value <= 0 {
return 0, errors.New("invalid positive integer")
}
return value, nil
}
func (s *Service) GetInputRegion(c *gin.Context) {
var rsp proto.Response
inputRegionMu.RLock()
region, err := readInputRegion(inputRegionFile)
inputRegionMu.RUnlock()
if errors.Is(err, os.ErrNotExist) {
rsp.OkRspWithData(c, &proto.GetInputRegionRsp{InputRegion: proto.InputRegion{Mode: "off"}})
return
}
if err != nil {
rsp.ErrRsp(c, -1, "failed to read input region")
return
}
if region == nil {
rsp.OkRspWithData(c, &proto.GetInputRegionRsp{InputRegion: proto.InputRegion{Mode: "off"}})
return
}
rsp.OkRspWithData(c, &proto.GetInputRegionRsp{InputRegion: *region})
}
func (s *Service) SetInputRegion(c *gin.Context) {
var req proto.SetInputRegionReq
var rsp proto.Response
if err := c.ShouldBindJSON(&req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
inputRegionMu.Lock()
defer inputRegionMu.Unlock()
if req.Mode == "off" || req.Mode == "auto" ||
(req.Mode == "manual" && req.FrameWidth == nil && req.FrameHeight == nil &&
req.Left == nil && req.Top == nil && req.Width == nil && req.Height == nil) {
region, err := readInputRegion(inputRegionFile)
if err != nil && !errors.Is(err, os.ErrNotExist) {
rsp.ErrRsp(c, -2, "failed to read input region")
return
}
if region == nil {
region = &proto.InputRegion{}
}
region.Mode = req.Mode
if req.Resolutions != nil {
if err := validateOriginalResolutions(*req.Resolutions); err != nil {
rsp.ErrRsp(c, -1, "invalid original resolutions")
return
}
region.Resolutions = *req.Resolutions
}
if req.SelectedResolution != nil {
region.SelectedResolution = *req.SelectedResolution
}
if req.Regions != nil {
if err := validateManualRegions(*req.Regions); err != nil {
rsp.ErrRsp(c, -1, "invalid manual regions")
return
}
region.Regions = *req.Regions
if len(region.Regions) == 0 {
clearLegacyManualRegion(region)
}
}
if req.SelectedRegion != nil {
region.SelectedRegion = *req.SelectedRegion
}
if err := validateSelections(*region); err != nil {
rsp.ErrRsp(c, -1, "invalid selected resolution")
return
}
if err := writeInputRegion(inputRegionFile, *region); err != nil {
rsp.ErrRsp(c, -2, "failed to save input region mode")
return
}
rsp.OkRsp(c)
return
}
if req.Mode != "manual" {
rsp.ErrRsp(c, -1, "invalid input region mode")
return
}
region, err := inputRegionFromRequest(req)
if err != nil {
rsp.ErrRsp(c, -1, "invalid input region")
return
}
previous, readErr := readInputRegion(inputRegionFile)
if readErr != nil && !errors.Is(readErr, os.ErrNotExist) {
rsp.ErrRsp(c, -2, "failed to read input region")
return
}
if previous != nil {
region.Resolutions = previous.Resolutions
region.SelectedResolution = previous.SelectedResolution
region.Regions = previous.Regions
region.SelectedRegion = previous.SelectedRegion
}
if req.Resolutions != nil {
if err := validateOriginalResolutions(*req.Resolutions); err != nil {
rsp.ErrRsp(c, -1, "invalid original resolutions")
return
}
region.Resolutions = *req.Resolutions
}
if req.SelectedResolution != nil {
region.SelectedResolution = *req.SelectedResolution
}
if req.Regions != nil {
if err := validateManualRegions(*req.Regions); err != nil {
rsp.ErrRsp(c, -1, "invalid manual regions")
return
}
region.Regions = *req.Regions
if len(region.Regions) == 0 {
clearLegacyManualRegion(&region)
}
}
if req.SelectedRegion != nil {
region.SelectedRegion = *req.SelectedRegion
}
if err := validateSelections(region); err != nil {
rsp.ErrRsp(c, -1, "invalid selected resolution")
return
}
if err := writeInputRegion(inputRegionFile, region); err != nil {
rsp.ErrRsp(c, -2, "failed to save input region")
return
}
rsp.OkRsp(c)
}
func validateOriginalResolutions(resolutions []proto.OriginalResolution) error {
seen := make(map[proto.OriginalResolution]struct{}, len(resolutions))
for _, resolution := range resolutions {
if resolution.Width <= 0 || resolution.Height <= 0 {
return errors.New("resolution dimensions must be positive")
}
if _, ok := seen[resolution]; ok {
return errors.New("duplicate resolution")
}
seen[resolution] = struct{}{}
}
return nil
}
func validateSelectedResolution(selected string, resolutions []proto.OriginalResolution) error {
if selected == "" {
return nil
}
for _, resolution := range resolutions {
if selected == resolutionKey(resolution) {
return nil
}
}
return errors.New("selected resolution not found")
}
func validateManualRegions(regions []proto.ManualRegion) error {
seen := make(map[string]struct{}, len(regions))
for _, region := range regions {
if err := validateManualRegion(region); err != nil {
return err
}
key := manualRegionKey(region)
if _, ok := seen[key]; ok {
return errors.New("duplicate manual region")
}
seen[key] = struct{}{}
}
return nil
}
func validateManualRegion(region proto.ManualRegion) error {
return validateInputRegion(proto.InputRegion{
Mode: "manual",
FrameWidth: region.FrameWidth,
FrameHeight: region.FrameHeight,
Left: region.Left,
Top: region.Top,
Width: region.Width,
Height: region.Height,
})
}
func validateSelections(region proto.InputRegion) error {
if region.SelectedResolution != "" && region.SelectedRegion != "" {
return errors.New("only one input region source may be selected")
}
if err := validateSelectedResolution(region.SelectedResolution, region.Resolutions); err != nil {
return err
}
if region.SelectedRegion == "" {
return nil
}
for _, item := range region.Regions {
if region.SelectedRegion == manualRegionKey(item) {
return nil
}
}
return errors.New("selected manual region not found")
}
func resolutionKey(resolution proto.OriginalResolution) string {
return fmt.Sprintf("%dx%d", resolution.Width, resolution.Height)
}
func manualRegionKey(region proto.ManualRegion) string {
return fmt.Sprintf("%dx%d", region.Width, region.Height)
}
func clearLegacyManualRegion(region *proto.InputRegion) {
region.FrameWidth = 0
region.FrameHeight = 0
region.Left = 0
region.Top = 0
region.Width = 0
region.Height = 0
}
func inputRegionFromRequest(req proto.SetInputRegionReq) (proto.InputRegion, error) {
if req.FrameWidth == nil || req.FrameHeight == nil || req.Left == nil ||
req.Top == nil || req.Width == nil || req.Height == nil {
return proto.InputRegion{}, errors.New("input region must be complete")
}
region := proto.InputRegion{
Mode: "manual",
FrameWidth: *req.FrameWidth,
FrameHeight: *req.FrameHeight,
Left: *req.Left,
Top: *req.Top,
Width: *req.Width,
Height: *req.Height,
}
return region, validateInputRegion(region)
}
func validateInputRegion(region proto.InputRegion) error {
if region.Mode == "off" || region.Mode == "auto" {
return nil
}
if region.Mode == "manual" && region.FrameWidth == 0 && region.FrameHeight == 0 {
return nil
}
if region.Mode != "manual" {
return errors.New("invalid input region mode")
}
if region.FrameWidth <= 0 || region.FrameHeight <= 0 {
return errors.New("frame dimensions must be positive")
}
if region.Left < 0 || region.Top < 0 || region.Width <= 0 || region.Height <= 0 {
return errors.New("region dimensions must be positive and offsets non-negative")
}
if region.Left > region.FrameWidth-region.Width || region.Top > region.FrameHeight-region.Height {
return errors.New("region must be inside frame")
}
return nil
}
func readInputRegion(path string) (*proto.InputRegion, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var region *proto.InputRegion
if err := json.Unmarshal(data, &region); err != nil {
return nil, nil
}
if region == nil {
return nil, nil
}
if region.Mode == "" {
region.Mode = "manual"
}
if len(region.Regions) == 0 && region.FrameWidth > 0 && region.FrameHeight > 0 {
manual := proto.ManualRegion{
FrameWidth: region.FrameWidth,
FrameHeight: region.FrameHeight,
Left: region.Left,
Top: region.Top,
Width: region.Width,
Height: region.Height,
}
region.Regions = []proto.ManualRegion{manual}
if region.SelectedResolution == "" {
region.SelectedRegion = manualRegionKey(manual)
}
}
if err := validateInputRegion(*region); err != nil {
return nil, nil
}
if err := validateManualRegions(region.Regions); err != nil {
return nil, nil
}
if err := validateSelections(*region); err != nil {
return nil, nil
}
return region, nil
}
func writeInputRegion(path string, region proto.InputRegion) error {
data, err := json.Marshal(region)
if err != nil {
return err
}
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
tmp, err := os.CreateTemp(dir, ".input-region-*.tmp")
if err != nil {
return err
}
tmpPath := tmp.Name()
defer os.Remove(tmpPath)
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Chmod(0o644); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmpPath, path)
}
func removeInputRegion(path string) error {
err := os.Remove(path)
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}

View File

@@ -1,8 +1,8 @@
package vm
import (
"NanoKVM-Server/middleware"
"encoding/json"
"net/http"
"os"
"os/exec"
"time"
@@ -26,9 +26,7 @@ type WinSize struct {
var upgrader = websocket.Upgrader{
ReadBufferSize: maxMessageSize,
WriteBufferSize: maxMessageSize,
CheckOrigin: func(r *http.Request) bool {
return true
},
CheckOrigin: middleware.CheckWebSocketOrigin,
}
func (s *Service) Terminal(c *gin.Context) {
@@ -37,11 +35,14 @@ func (s *Service) Terminal(c *gin.Context) {
log.Errorf("failed to init websocket: %s", err)
return
}
stopSessionWatcher := middleware.WatchWebSocket(c.Request.Context(), ws)
defer stopSessionWatcher()
defer func() {
_ = ws.Close()
}()
cmd := exec.Command("/bin/sh")
cmd := exec.Command("/bin/sh", "-l")
cmd.Dir = "/root"
ptmx, err := pty.Start(cmd)
if err != nil {
log.Errorf("failed to start pty: %s", err)

View File

@@ -10,6 +10,7 @@ import (
"NanoKVM-Server/proto"
"NanoKVM-Server/service/hid"
"NanoKVM-Server/service/storage"
)
const (
@@ -49,11 +50,10 @@ func (s *Service) GetVirtualDevice(c *gin.Context) {
var rsp proto.Response
network, _ := isDeviceExist(virtualNetwork)
disk, _ := isDeviceExist(virtualDisk)
rsp.OkRspWithData(c, &proto.GetVirtualDeviceRsp{
Network: network,
Disk: disk,
Disk: diskAttached(),
})
log.Debugf("get virtual device success")
}
@@ -83,11 +83,18 @@ func (s *Service) UpdateVirtualDevice(c *gin.Context) {
case "disk":
device = virtualDisk
exist, _ := isDeviceExist(device)
if !exist {
commands = mountDiskCommands
} else {
if diskAttached() {
commands = unmountDiskCommands
} else {
// the host writes the partition from now on. A mounted image is released by
// the restarted gadget, which attaches the raw partition again.
if err := storage.SetDataWritable(false); err != nil {
log.Errorf("make /data read-only failed: %s", err)
rsp.ErrRsp(c, -3, "make /data read-only failed")
return
}
commands = mountDiskCommands
}
default:
rsp.ErrRsp(c, -2, "invalid arguments")
@@ -110,6 +117,13 @@ func (s *Service) UpdateVirtualDevice(c *gin.Context) {
}
}
// the disk is gone from the host, the KVM writes /data itself again
if device == virtualDisk && !diskAttached() {
if err := storage.SetDataWritable(true); err != nil {
log.Errorf("make /data writable failed: %s", err)
}
}
on, _ := isDeviceExist(device)
rsp.OkRspWithData(c, &proto.UpdateVirtualDeviceRsp{
On: on,
@@ -118,6 +132,14 @@ func (s *Service) UpdateVirtualDevice(c *gin.Context) {
log.Debugf("update virtual device %s success", req.Device)
}
// diskAttached reports whether the virtual disk is enabled and the /data
// partition is currently shared with the host. A virtual disk that serves an
// image, or nothing at all, counts as disabled.
func diskAttached() bool {
enabled, _ := isDeviceExist(virtualDisk)
return enabled && storage.DataDiskAttached()
}
func isDeviceExist(device string) (bool, error) {
_, err := os.Stat(device)

View File

@@ -1,7 +1,7 @@
package ws
import (
"net/http"
"NanoKVM-Server/middleware"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
@@ -13,9 +13,7 @@ type Service struct{}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
CheckOrigin: middleware.CheckWebSocketOrigin,
}
func NewService() *Service {
@@ -28,6 +26,8 @@ func (s *Service) Connect(c *gin.Context) {
log.Errorf("create websocket failed: %s", err)
return
}
stopSessionWatcher := middleware.WatchWebSocket(c.Request.Context(), ws)
defer stopSessionWatcher()
log.Debug("websocket connected")

View File

@@ -2,34 +2,80 @@ package utils
import (
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
func Download(req *http.Request, target string) error {
log.Debugf("downloading %s to %s", req.URL.String(), target)
err := os.MkdirAll(filepath.Dir(target), 0o755)
if err != nil {
log.Errorf("create dir %s err: %s", filepath.Dir(target), err)
return err
}
out, err := os.OpenFile(target, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)
if err != nil {
log.Errorf("cannot create file '%s', error: %s", target, err)
return err
}
defer func() {
_ = out.Close()
}()
var downloadClient = NewUpdateHTTPClient(15 * time.Minute)
resp, err := (&http.Client{}).Do(req)
type DownloadInfo struct {
ContentLength int64
Written int64
}
func NewAuthenticatedRequest(method string, rawURL string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, rawURL, body)
if err != nil {
log.Errorf("request error: %s", err)
return err
return nil, err
}
if req.URL.User != nil {
username := req.URL.User.Username()
password, _ := req.URL.User.Password()
req.SetBasicAuth(username, password)
// Keep credentials out of the request URL after copying them to the header.
req.URL.User = nil
}
return req, nil
}
func NewUpdateHTTPClient(timeout time.Duration) *http.Client {
return &http.Client{
Timeout: timeout,
CheckRedirect: preserveBasicAuthRedirect,
}
}
func preserveBasicAuthRedirect(req *http.Request, via []*http.Request) error {
if len(via) == 0 {
return nil
}
previous := via[len(via)-1]
authorization := previous.Header.Get("Authorization")
if authorization == "" {
return nil
}
if !sameUpdateHost(previous.URL, req.URL) ||
(previous.URL.Scheme == "https" && req.URL.Scheme != "https") {
return http.ErrUseLastResponse
}
req.Header.Set("Authorization", authorization)
return nil
}
func sameUpdateHost(left *url.URL, right *url.URL) bool {
return strings.EqualFold(left.Host, right.Host)
}
func Download(req *http.Request, target string, maxBytes int64, beforeWrite func(contentLength int64) error) (DownloadInfo, error) {
log.Debugf("downloading %s to %s", req.URL.Redacted(), target)
resp, err := downloadClient.Do(req)
if err != nil {
log.Errorf("request to %s failed", req.URL.Redacted())
return DownloadInfo{}, errors.New("update website is inaccessible right now")
}
defer func() {
_ = resp.Body.Close()
@@ -37,20 +83,57 @@ func Download(req *http.Request, target string) error {
if resp.StatusCode != http.StatusOK {
log.Errorf("request failed, status code: %d", resp.StatusCode)
return errors.New("update website is inaccessible right now")
return DownloadInfo{}, errors.New("update website is inaccessible right now")
}
contentType := resp.Header.Get("Content-Type")
if contentType != "application/octet-stream" && contentType != "application/zip" && contentType != "application/gzip" {
log.Debugf("unexpected content-type, it should be either octet-stream or (g)zip, but got: %s", contentType)
return errors.New("unsupported content type")
contentType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
if err != nil || !allowedDownloadContentType(contentType) {
log.Debugf("unexpected content-type: %s", resp.Header.Get("Content-Type"))
return DownloadInfo{}, errors.New("unsupported content type")
}
_, err = io.Copy(out, resp.Body)
if resp.ContentLength > maxBytes {
return DownloadInfo{}, fmt.Errorf("download exceeds %d bytes", maxBytes)
}
if resp.ContentLength > 0 && beforeWrite != nil {
if err := beforeWrite(resp.ContentLength); err != nil {
return DownloadInfo{}, err
}
}
if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
log.Errorf("create dir %s err: %s", filepath.Dir(target), err)
return DownloadInfo{}, err
}
out, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
log.Errorf("cannot create file '%s', error: %s", target, err)
return DownloadInfo{}, err
}
success := false
defer func() {
_ = out.Close()
if !success {
_ = os.Remove(target)
}
}()
written, err := io.Copy(out, io.LimitReader(resp.Body, maxBytes+1))
if err != nil {
log.Errorf("download file to %s err: %s", target, err)
return err
return DownloadInfo{}, err
}
if written > maxBytes {
return DownloadInfo{}, fmt.Errorf("download exceeds %d bytes", maxBytes)
}
if err := out.Close(); err != nil {
return DownloadInfo{}, err
}
success = true
return DownloadInfo{ContentLength: resp.ContentLength, Written: written}, nil
}
func allowedDownloadContentType(contentType string) bool {
switch contentType {
case "application/octet-stream", "application/gzip", "application/x-gzip", "application/x-compressed", "application/zip":
return true
default:
return false
}
return nil
}

76
server/utils/http_test.go Normal file
View File

@@ -0,0 +1,76 @@
package utils
import (
"errors"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (fn roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {
return fn(request)
}
func testDownloadClient(body, contentType string) *http.Client {
return &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{contentType}},
Body: io.NopCloser(strings.NewReader(body)),
ContentLength: int64(len(body)),
Request: request,
}, nil
})}
}
func TestDownloadPreflightRunsBeforeTargetCreation(t *testing.T) {
oldClient := downloadClient
downloadClient = testDownloadClient("package", "application/x-compressed; charset=binary")
defer func() { downloadClient = oldClient }()
target := filepath.Join(t.TempDir(), "package.tar.gz")
req, err := http.NewRequest(http.MethodGet, "https://updates.example/package", nil)
if err != nil {
t.Fatal(err)
}
_, err = Download(req, target, 1024, func(int64) error { return errors.New("no space") })
if err == nil {
t.Fatal("download succeeded despite failed preflight")
}
if _, statErr := os.Stat(target); !os.IsNotExist(statErr) {
t.Fatalf("target was created before preflight: %v", statErr)
}
}
func TestDownloadRemovesPartialFileAndReportsWrittenBytes(t *testing.T) {
oldClient := downloadClient
downloadClient = testDownloadClient("12345", "application/gzip")
defer func() { downloadClient = oldClient }()
request := func() *http.Request {
req, err := http.NewRequest(http.MethodGet, "https://updates.example/package", nil)
if err != nil {
t.Fatal(err)
}
return req
}
target := filepath.Join(t.TempDir(), "package.tar.gz")
if _, err := Download(request(), target, 4, nil); err == nil {
t.Fatal("oversized download was accepted")
}
if _, err := os.Stat(target); !os.IsNotExist(err) {
t.Fatalf("partial file remains: %v", err)
}
info, err := Download(request(), target, 5, nil)
if err != nil {
t.Fatal(err)
}
if info.Written != 5 {
t.Fatalf("written = %d, want 5", info.Written)
}
}

6
server/utils/transfer.go Normal file
View File

@@ -0,0 +1,6 @@
package utils
// TransferSentinelPath coordinates application uploads and virtual-media
// transfers. /run is already required by the device init scripts and preserves
// the previous reboot-clears-stale-state behaviour without using /tmp.
const TransferSentinelPath = "/run/nanokvm-transfer-in-progress"

View File

@@ -1,6 +1,7 @@
list(APPEND ADD_REQUIREMENTS vision basic peripheral)
list(APPEND ADD_INCLUDE "include")
list(APPEND ADD_LINK_DEFINITIONS_PRIVATE -Wl,--as-needed)
append_srcs_dir(ADD_SRCS "src")
register_component(DYNAMIC)
register_component(DYNAMIC)

View File

@@ -74,9 +74,10 @@ void set_h264_gop(uint8_t _gop);
void set_frame_detact(uint8_t _frame_detact);
void kvmv_deinit();
uint8_t kvmv_hdmi_control(uint8_t _en);
uint8_t kvmv_hdmi_signal_active(void);
#ifdef __cplusplus
}
#endif
#endif // KVM_VISION_H_
#endif // KVM_VISION_H_

View File

@@ -13,6 +13,9 @@
#include "vi_state_shared.hpp"
#include "internal/vi_state_writer.hpp"
#include <errno.h>
#include <sys/stat.h>
#define default_venc_chn 1
#define VENC_MJPEG 0
@@ -43,6 +46,7 @@
#define vi_height_path "/kvmapp/kvm/height"
#define hdmi_mode_path "/etc/kvm/hdmi_mode"
#define hdmi_state_path "/proc/lt_int"
#define hdmi_signal_file_path "/kvmapp/kvm/state"
#define watchdog_mode_path "/etc/kvm/watchdog"
#define watchdog_temp_path "/tmp/watchdog"
#define watchdog_file "/tmp/nanokvm_wd"
@@ -53,6 +57,7 @@
#define LT6911_WRITE 0x00
pthread_mutex_t vi_mutex;
pthread_mutex_t hdmi_signal_mutex = PTHREAD_MUTEX_INITIALIZER;
static char NanoKVM_edit[] = {
0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x41,0x0C,0x33,0xC2,0x66,0xBA,0x00,0x00,
@@ -77,7 +82,6 @@ typedef struct {
uint16_t vpss_height = default_vpss_height;
uint8_t venc_type;
uint16_t qlty;
uint8_t cam_state = 0;
uint8_t stream_stop;
uint8_t frame_detact = 0;
uint8_t display;
@@ -125,6 +129,83 @@ uint8_t kvmv_data_buffer_index = 0;
uint8_t debug_en = 0;
uint8_t last_vi_state_code = 0;
uint32_t last_vi_state_refresh_ms = 0;
uint8_t hdmi_capture_enabled = 0;
uint8_t hdmi_signal_active = 0;
void debug(const char *format, ...);
static bool write_hdmi_signal_file(uint8_t active)
{
char temp_path[] = "/kvmapp/kvm/.state.tmp.XXXXXX";
const char *state = active != 0 ? "1\n" : "0\n";
const size_t state_size = 2;
int fd = mkstemp(temp_path);
if(fd < 0){
debug("[hdmi] failed to create state file: %d\n", errno);
return false;
}
int failure = 0;
if(fchmod(fd, 0644) != 0){
failure = errno;
}
size_t written = 0;
while(failure == 0 && written < state_size){
ssize_t result = write(fd, state + written, state_size - written);
if(result > 0){
written += (size_t)result;
} else if(result < 0 && errno == EINTR){
continue;
} else {
failure = result < 0 ? errno : EIO;
}
}
if(failure == 0 && fsync(fd) != 0){
failure = errno;
}
if(close(fd) != 0 && failure == 0){
failure = errno;
}
if(failure == 0 && rename(temp_path, hdmi_signal_file_path) != 0){
failure = errno;
}
if(failure != 0){
unlink(temp_path);
debug("[hdmi] failed to publish state file: %d\n", failure);
return false;
}
return true;
}
static void set_hdmi_signal_state(uint8_t active)
{
pthread_mutex_lock(&hdmi_signal_mutex);
uint8_t enabled = __atomic_load_n(&hdmi_capture_enabled, __ATOMIC_ACQUIRE);
uint8_t next = enabled != 0 && active != 0 ? 1 : 0;
uint8_t previous = __atomic_exchange_n(&hdmi_signal_active, next, __ATOMIC_ACQ_REL);
if(previous != next){
write_hdmi_signal_file(next);
}
pthread_mutex_unlock(&hdmi_signal_mutex);
}
static void set_hdmi_capture_enabled(uint8_t enabled)
{
pthread_mutex_lock(&hdmi_signal_mutex);
__atomic_store_n(&hdmi_capture_enabled, enabled != 0 ? 1 : 0, __ATOMIC_RELEASE);
__atomic_store_n(&hdmi_signal_active, 0, __ATOMIC_RELEASE);
write_hdmi_signal_file(0);
pthread_mutex_unlock(&hdmi_signal_mutex);
}
static void set_hdmi_detection_state(uint8_t active)
{
__atomic_store_n(&kvmv_cfg.hdmi_cable_state, active != 0 ? 1 : 0, __ATOMIC_RELEASE);
set_hdmi_signal_state(active);
}
void debug(const char *format, ...)
{
if(debug_en){
@@ -136,8 +217,9 @@ uint8_t refresh_vi_state()
{
// The driver read blocks for about a second; mark the deadline before it so
// that the publication cadence measures wall-clock time, not read time plus it.
last_vi_state_refresh_ms = vi_state_shared::monotonic_ms();
last_vi_state_refresh_ms = vi_state_shared::monotonic_ms();
last_vi_state_code = vi_state_shared::refresh();
set_hdmi_detection_state(last_vi_state_code == 1 || last_vi_state_code >= 3);
return last_vi_state_code;
}
@@ -1176,7 +1258,7 @@ void* vi_subsystem_detection(void * arg)
if(lt6911_get_hdmi_res()){
// hdmi get res
debug("[hdmi] C HDMI cable insertion!\n");
kvmv_cfg.hdmi_cable_state = 1;
set_hdmi_detection_state(1);
kvmv_cfg.hdmi_res_type = lt6911_get_csi_res(&kvmv_cfg.vi_width, &kvmv_cfg.vi_height);
if (kvmv_cfg.hdmi_res_type == NEW_RES) kvmv_cfg.reopen_cam_flag = 1;
else if (kvmv_cfg.hdmi_res_type == UNKNOWN_RES){
@@ -1188,7 +1270,7 @@ void* vi_subsystem_detection(void * arg)
} else {
// HDMI res = 0*0/x*0
debug("[hdmi] C HDMI cable unplugged!\n");
kvmv_cfg.hdmi_cable_state = 0;
set_hdmi_detection_state(0);
}
lt6911_disable();
}
@@ -1201,7 +1283,7 @@ void* vi_subsystem_detection(void * arg)
if(lt6911_get_hdmi_res()){
// hdmi get res
debug("[hdmi] UXC HDMI cable insertion!\n");
kvmv_cfg.hdmi_cable_state = 1;
set_hdmi_detection_state(1);
kvmv_cfg.hdmi_res_type = lt6911_get_csi_res(&kvmv_cfg.vi_width, &kvmv_cfg.vi_height);
if (kvmv_cfg.hdmi_res_type == NEW_RES) kvmv_cfg.reopen_cam_flag = 1;
else if (kvmv_cfg.hdmi_res_type == UNKNOWN_RES){
@@ -1213,7 +1295,7 @@ void* vi_subsystem_detection(void * arg)
} else {
// HDMI res = 0*0/x*0
debug("[hdmi] UXC HDMI cable unplugged!\n");
kvmv_cfg.hdmi_cable_state = 0;
set_hdmi_detection_state(0);
}
lt6911_disable();
}
@@ -1226,7 +1308,7 @@ void* vi_subsystem_detection(void * arg)
if(lt6911_get_hdmi_res()){
// hdmi get res
debug("[hdmi] D HDMI cable insertion!\n");
kvmv_cfg.hdmi_cable_state = 1;
set_hdmi_detection_state(1);
kvmv_cfg.hdmi_res_type = lt6911_get_csi_res(&kvmv_cfg.vi_width, &kvmv_cfg.vi_height);
if (kvmv_cfg.hdmi_res_type == NEW_RES) kvmv_cfg.reopen_cam_flag = 1;
else if (kvmv_cfg.hdmi_res_type == UNKNOWN_RES){
@@ -1238,7 +1320,7 @@ void* vi_subsystem_detection(void * arg)
} else {
// HDMI res = 0*0/x*0
debug("[hdmi] D HDMI cable unplugged!\n");
kvmv_cfg.hdmi_cable_state = 0;
set_hdmi_detection_state(0);
}
lt6911_disable();
}
@@ -1639,7 +1721,7 @@ void kvmv_init(uint8_t _debug_info_en)
uint8_t check_kvmv(uint8_t _try_num)
{
if(kvmv_cfg.hdmi_cable_state == 0){
if(__atomic_load_n(&kvmv_cfg.hdmi_cable_state, __ATOMIC_ACQUIRE) == 0){
debug("[kvmv]HDMI Cable not exist!\n");
return 0;
}
@@ -1788,17 +1870,8 @@ int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _ql
}
}
}
if(kvmv_cfg.cam_state == 0) {
kvmv_cfg.cam_state = 1;
kvmv_cfg.hdmi_cable_state = 1;
system("echo 1 > /kvmapp/kvm/state");
}
} else {
if(kvmv_cfg.cam_state == 1) {
kvmv_cfg.cam_state = 0;
system("echo 0 > /kvmapp/kvm/state");
}
delete img;
delete img;
debug("[kvmv]can`t get img...\n");
continue;
// pthread_mutex_unlock(&vi_mutex);
@@ -1905,6 +1978,7 @@ void free_all_kvmv_data()
void kvmv_deinit()
{
set_hdmi_capture_enabled(0);
pthread_mutex_destroy(&vi_mutex);
kvmv_cfg.try_exit_thread = 1;
cam->close();
@@ -1914,6 +1988,10 @@ void kvmv_deinit()
uint8_t kvmv_hdmi_control(uint8_t _en)
{
if(_en == 0){
set_hdmi_capture_enabled(0);
}
if(kvmv_cfg.hw_version == 0){
FILE *fp;
@@ -1935,6 +2013,9 @@ uint8_t kvmv_hdmi_control(uint8_t _en)
}
if(kvmv_cfg.hw_version != 'p'){
debug("[kvmv]Hardware not support!\n");
if(_en != 0){
set_hdmi_capture_enabled(1);
}
return -1;
}
if(access("/sys/class/gpio/gpio451/value", F_OK) != 0){
@@ -1954,7 +2035,15 @@ uint8_t kvmv_hdmi_control(uint8_t _en)
// Reopening it here or from kvmv_read_img can exhaust the carveout
// heap while the HDMI detector is transitioning.
kvmv_cfg.fresh_frame_count = fresh_frame_discard_count;
set_hdmi_capture_enabled(1);
return 0;
}
return -1;
}
uint8_t kvmv_hdmi_signal_active()
{
uint8_t enabled = __atomic_load_n(&hdmi_capture_enabled, __ATOMIC_ACQUIRE);
uint8_t active = __atomic_load_n(&hdmi_signal_active, __ATOMIC_ACQUIRE);
return enabled != 0 && active != 0 ? 1 : 0;
}

View File

@@ -1,12 +1,47 @@
#include "config.h"
#include "system_init.h"
#include <errno.h>
#include <sys/stat.h>
using namespace maix;
using namespace maix::sys;
extern kvm_sys_state_t kvm_sys_state;
extern kvm_oled_state_t kvm_oled_state;
static void write_hdmi_state(uint8_t active)
{
char temp_path[] = "/kvmapp/kvm/.state.init.XXXXXX";
const char *state = active != 0 ? "1\n" : "0\n";
int fd = mkstemp(temp_path);
if(fd < 0){
printf("failed to create HDMI state file: %d\n", errno);
return;
}
int failure = 0;
if(fchmod(fd, 0644) != 0){
failure = errno;
}
if(failure == 0 && write(fd, state, 2) != 2){
failure = errno != 0 ? errno : EIO;
}
if(failure == 0 && fsync(fd) != 0){
failure = errno;
}
if(close(fd) != 0 && failure == 0){
failure = errno;
}
if(failure == 0 && rename(temp_path, "/kvmapp/kvm/state") != 0){
failure = errno;
}
if(failure != 0){
unlink(temp_path);
printf("failed to publish HDMI state file: %d\n", failure);
}
}
uint8_t get_hdmi_version()
{
FILE *fp;
@@ -101,7 +136,7 @@ void new_app_init(void)
system("echo 2000 > /kvmapp/kvm/qlty");
system("echo 720 > /kvmapp/kvm/res");
system("echo h264 > /kvmapp/kvm/type");
system("echo 0 > /kvmapp/kvm/state");
write_hdmi_state(0);
system("touch /etc/kvm/frame_detact");
// rm jpg_stream & kvm_stream

View File

@@ -22,6 +22,8 @@ src
## Local Development
Requirements: Node.js >= 22 and pnpm >= 11 (the versions CI uses; enforced via the `engines` field in `package.json`).
> Development requires SSH. You can enable it in the Web Settings: `Settings > SSH`.
Due to CORS restrictions, authentication needs to be disabled during local development.

View File

@@ -3,6 +3,10 @@
"private": true,
"version": "0.0.0",
"type": "module",
"engines": {
"node": ">=22",
"pnpm": ">=11"
},
"scripts": {
"dev": "vite",
"mocked": "vite --mode mocked",
@@ -23,7 +27,6 @@
"crypto-js": "^4.2.0",
"i18next": "^23.16.8",
"jotai": "^2.18.0",
"js-cookie": "^3.0.7",
"lucide-react": "^0.562.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
@@ -45,14 +48,13 @@
"@eslint/js": "^9.39.4",
"@ianvs/prettier-plugin-sort-imports": "^4.7.1",
"@types/crypto-js": "^4.2.2",
"@types/js-cookie": "^3.0.6",
"@types/react": "^18.3.28",
"@types/react-dom": "^18.3.7",
"@types/semver": "^7.7.1",
"@types/websocket": "^1.0.10",
"@typescript-eslint/eslint-plugin": "^8.59.0",
"@typescript-eslint/parser": "^8.59.0",
"@vitejs/plugin-react": "^4.7.0",
"@vitejs/plugin-react": "^6.0.5",
"autoprefixer": "^10.4.27",
"eslint": "^9.39.4",
"eslint-config-prettier": "^9.1.2",
@@ -67,8 +69,7 @@
"tailwindcss": "^3.4.19",
"typescript": "^5.9.3",
"typescript-eslint": "^8.59.0",
"vite": "7.3.2",
"vite-tsconfig-paths": "^4.3.2",
"vite": "8.2.0",
"yaml": "^2.8.3"
},
"msw": {

900
web/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,11 @@
import { http } from '@/lib/http.ts';
import { getBaseUrl } from '@/lib/service.ts';
export type UpdateServerConfig = {
enabled: boolean;
url: string;
};
// get application version
export function getVersion() {
return http.get('/api/application/version');
@@ -16,11 +21,12 @@ export function update() {
}
// offline update application
export function offlineUpdate(data: FormData) {
export function offlineUpdate(data: FormData, sha256Checksum = '') {
const baseUrl = getBaseUrl('http');
const url = `${baseUrl}/api/application/update/offline`;
return fetch(url, {
method: 'POST',
headers: sha256Checksum ? { 'X-SHA256-Checksum': sha256Checksum } : undefined,
body: data
});
}
@@ -37,3 +43,13 @@ export function setPreviewUpdates(enable: boolean) {
export function getPreviewUpdates() {
return http.get('/api/application/preview');
}
// get custom update server configuration
export function getUpdateServer() {
return http.get('/api/application/update-server');
}
// enable/disable custom update server
export function setUpdateServer(config: UpdateServerConfig) {
return http.post('/api/application/update-server', config);
}

View File

@@ -1,5 +1,17 @@
import { http } from '@/lib/http';
export type UserRole = 'admin' | 'user';
export type Account = {
username: string;
role: UserRole;
};
export type User = Account & {
enabled: boolean;
systemAccount?: boolean;
};
export function login(username: string, password: string) {
const data = {
username,
@@ -16,14 +28,34 @@ export function getAccount() {
return http.get('/api/auth/account');
}
export function changePassword(username: string, password: string) {
const data = {
username,
password
};
return http.post('/api/auth/password', data);
export function changePassword(currentPassword: string, password: string) {
return http.post('/api/auth/password', { currentPassword, password });
}
export function isPasswordUpdated() {
return http.get('/api/auth/password');
}
export function getUsers() {
return http.get('/api/auth/users');
}
export function createUser(username: string, password: string, role: UserRole) {
return http.post('/api/auth/users', { username, password, role });
}
export function updateUser(username: string, data: Partial<Pick<User, 'role' | 'enabled'>>) {
return http.request({
method: 'put',
url: `/api/auth/users/${encodeURIComponent(username)}`,
data
});
}
export function deleteUser(username: string) {
return http.delete(`/api/auth/users/${encodeURIComponent(username)}`);
}
export function resetUserPassword(username: string, password: string) {
return http.post(`/api/auth/users/${encodeURIComponent(username)}/password`, { password });
}

View File

@@ -1,3 +1,4 @@
import { ControlRegionMode, InputRegion, OriginalResolution } from '@/types';
import { http } from '@/lib/http.ts';
// get NanoKVM information
@@ -33,6 +34,76 @@ export function updateScreen(type: string, value: number) {
return http.post('/api/vm/screen', data);
}
// get the device-level absolute mouse input region
export function getInputRegion() {
return http.get('/api/vm/input-region');
}
export function getInputResolution() {
return http.get('/api/vm/input-resolution');
}
// save the device-level absolute mouse input region
export function setInputRegion(region: InputRegion) {
return http.post('/api/vm/input-region', { mode: 'manual', ...region });
}
export function setInputRegionConfig(
region: InputRegion,
regions: InputRegion[],
selectedRegion: string
) {
return http.post('/api/vm/input-region', {
mode: 'manual',
...region,
regions,
selectedRegion,
selectedResolution: ''
});
}
export function setControlRegionMode(mode: ControlRegionMode) {
return http.post('/api/vm/input-region', { mode });
}
export function setOriginalResolutions(mode: ControlRegionMode, resolutions: OriginalResolution[]) {
return http.post('/api/vm/input-region', { mode, resolutions });
}
export function setOriginalResolutionConfig(
resolutions: OriginalResolution[],
selectedResolution: string,
selectedRegion: string
) {
return http.post('/api/vm/input-region', {
mode: 'manual',
resolutions,
selectedResolution,
selectedRegion
});
}
export function setSelectedOriginalResolution(selectedResolution: string) {
return http.post('/api/vm/input-region', {
mode: 'manual',
selectedResolution,
selectedRegion: ''
});
}
export function setManualRegions(
regions: InputRegion[],
selectedRegion: string,
selectedResolution = ''
) {
return http.post('/api/vm/input-region', {
mode: 'manual',
regions,
selectedRegion,
selectedResolution
});
}
// get memory limit
export function getMemoryLimit() {
return http.get('/api/vm/memory/limit');

View File

@@ -1,14 +1,68 @@
import { ReactNode } from 'react';
import { ReactNode, useEffect, useState } from 'react';
import { AuthContext, useAuth } from '@/contexts/auth.ts';
import { Spin } from 'antd';
import { Navigate } from 'react-router-dom';
import { existToken } from '@/lib/cookie.ts';
import { Account, getAccount } from '@/api/auth.ts';
import { AUTH_EXPIRED_EVENT } from '@/lib/auth-events.ts';
export const ProtectedRoute = ({ children }: { children: ReactNode }) => {
const hasToken = existToken();
const [account, setAccount] = useState<Account | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(true);
if (!hasToken) {
useEffect(() => {
let active = true;
getAccount()
.then((rsp) => {
if (!active) return;
if (rsp.code !== 0 || !rsp.data?.username) {
setIsAuthenticated(false);
return;
}
setAccount({
username: rsp.data.username,
role: rsp.data.role === 'admin' ? 'admin' : 'user'
});
})
.catch(() => {
if (active) setIsAuthenticated(false);
})
.finally(() => {
if (active) setIsLoading(false);
});
const handleAuthExpired = () => {
setAccount(null);
setIsAuthenticated(false);
setIsLoading(false);
};
window.addEventListener(AUTH_EXPIRED_EVENT, handleAuthExpired);
return () => {
active = false;
window.removeEventListener(AUTH_EXPIRED_EVENT, handleAuthExpired);
};
}, []);
if (isLoading) {
return (
<div className="flex h-screen w-screen items-center justify-center">
<Spin size="large" />
</div>
);
}
if (!isAuthenticated || !account) {
return <Navigate to={'/auth/login'} replace />;
}
return children;
return <AuthContext.Provider value={{ account }}>{children}</AuthContext.Provider>;
};
export const AdminRoute = ({ children }: { children: ReactNode }) => {
const { account } = useAuth();
return account.role === 'admin' ? children : <Navigate to="/" replace />;
};

View File

@@ -1,9 +1,9 @@
import { useEffect } from 'react';
import { useOptionalAuth } from '@/contexts/auth.ts';
import { useAtom } from 'jotai';
import { Helmet, HelmetData } from 'react-helmet-async';
import { getWebTitle } from '@/api/vm.ts';
import { existToken } from '@/lib/cookie.ts';
import { webTitleAtom } from '@/jotai/settings.ts';
type HeadProps = {
@@ -15,16 +15,17 @@ const helmetData = new HelmetData({});
export const Head = ({ title = '', description = '' }: HeadProps = {}) => {
const [webTitle, setWebTitle] = useAtom(webTitleAtom);
const auth = useOptionalAuth();
useEffect(() => {
if (!existToken()) return;
if (!auth) return;
getWebTitle().then((rsp) => {
if (rsp.data?.title) {
setWebTitle(rsp.data.title);
}
});
}, []);
}, [auth, setWebTitle]);
return (
<Helmet

View File

@@ -1,9 +1,9 @@
import { ReactNode, useState } from 'react';
import { ReactNode, useEffect, useRef, useState } from 'react';
import { Popover, Tooltip } from 'antd';
import { useSetAtom } from 'jotai';
import { useAtomValue, useSetAtom } from 'jotai';
import { useMediaQuery } from 'react-responsive';
import { submenuOpenCountAtom } from '@/jotai/settings.ts';
import { menuCloseSignalAtom, submenuOpenCountAtom } from '@/jotai/settings.ts';
type MenuItemProps = {
title: string;
@@ -24,9 +24,27 @@ export const MenuItem = ({
}: MenuItemProps) => {
const isBigScreen = useMediaQuery({ minWidth: 640 });
const setSubmenuOpenCount = useSetAtom(submenuOpenCountAtom);
const menuCloseSignal = useAtomValue(menuCloseSignalAtom);
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
const handledCloseSignalRef = useRef(0);
useEffect(() => {
if (
menuCloseSignal === 0 ||
menuCloseSignal === handledCloseSignalRef.current ||
!isPopoverOpen
) {
return;
}
handledCloseSignalRef.current = menuCloseSignal;
setIsPopoverOpen(false);
setIsTooltipOpen(false);
setSubmenuOpenCount((count) => Math.max(0, count - 1));
onOpenChange?.(false);
}, [isPopoverOpen, menuCloseSignal, onOpenChange, setSubmenuOpenCount]);
function togglePopover(open: boolean) {
setIsTooltipOpen(false);

21
web/src/contexts/auth.ts Normal file
View File

@@ -0,0 +1,21 @@
import { createContext, useContext } from 'react';
import { Account } from '@/api/auth.ts';
export type AuthState = {
account: Account;
};
export const AuthContext = createContext<AuthState | null>(null);
export function useAuth() {
const auth = useContext(AuthContext);
if (!auth) {
throw new Error('useAuth must be used inside ProtectedRoute');
}
return auth;
}
export function useOptionalAuth() {
return useContext(AuthContext);
}

View File

@@ -64,6 +64,37 @@ const ca = {
video: 'Mode de vídeo',
videoDirectTips: "Activa HTTPS a 'Configuració > Dispositiu' per utilitzar aquest mode",
resolution: 'Resolució',
controlRegion: {
title: 'Calibratge del ratolí',
description:
'Utilitzeu aquesta opció quan el dispositiu controlat tingui una resolució que no sigui 16:9 i el cursor estigui desalineat horitzontalment o verticalment.',
off: 'Desactivat',
auto: 'Automàtic',
autoWarning:
"El calibratge pot fallar quan l'aplicació de l'usuari tingui un fons completament negre.",
manual: 'Manual',
selectedResolution: "Resolució de l'àrea seleccionada",
unused: 'No utilitzada',
originalResolution: 'Resolució original',
selectResolution: 'Selecciona la resolució original',
addResolution: 'Afegeix una resolució personalitzada',
add: 'Afegeix',
duplicateResolution: 'Aquesta resolució ja existeix.',
width: 'Amplada',
height: 'Alçada',
apply: 'Calcula i aplica',
invalidResolution: 'Introduïu una resolució original vàlida quan el vídeo estigui llest.',
select: "Selecciona l'àrea",
clear: 'Restaura la detecció automàtica',
saveFailed: "No s'ha pogut desar l'àrea d'entrada.",
tooSmall: "L'àrea seleccionada és massa petita.",
previewUnavailable: 'Vista prèvia no disponible',
clearConfirm: 'Voleu restaurar la detecció automàtica de vores negres?',
dragHint: "Arrossegueu per seleccionar l'àrea de l'escriptori remot",
finish: 'Fet',
confirm: 'Confirma',
cancel: 'Cancel·la'
},
auto: 'Automàtic',
autoTips:
"Poden aparèixer talls o desajustos del ratolí en certes resolucions. Prova a canviar la resolució de l'amfitrió remot o desactiva el mode automàtic.",
@@ -83,6 +114,10 @@ const ca = {
description:
"S'estan utilitzant H.264 Direct i H.264 WebRTC alhora. Això pot provocar esquinçament de pantalla o vídeo corrupte. Utilitzeu només un mode H.264."
},
webrtcConnectionFailed: {
title: 'Error de connexió WebRTC',
description: 'Comproveu la connexió de xarxa o canvieu el mode de vídeo.'
},
captureStatus: {
hdmiError: 'Error a la pantalla HDMI',
unsupportedResolution: 'La resolució actual no és compatible',
@@ -185,6 +220,12 @@ const ca = {
mountMode: 'Mode de muntatge',
mountFailed: 'Error en muntar',
mountDesc: 'En alguns sistemes cal expulsar el disc virtual abans de muntar la imatge.',
diskOnWarn:
"Muntar la imatge desactiva el disc virtual, de manera que l'ordinador ja no pot accedir a /data. Voleu continuar?",
diskOffWarn:
"El disc virtual està desactivat i cal activar-lo per muntar la imatge. Els dispositius USB de l'ordinador es tornaran a enumerar. Voleu continuar?",
diskShared:
'El disc virtual està activat, així que /data és només de lectura aquí. Desactiveu-lo per suprimir o pujar imatges.',
unmountFailed: "No s'ha pogut desmuntar",
unmountDesc:
"En alguns sistemes, cal expulsar manualment de l'amfitrió remot abans de desmuntar la imatge.",
@@ -253,6 +294,8 @@ const ca = {
input: 'Introdueix la URL de la imatge',
ok: "D'acord",
disabled: 'La partició /data és només lectura. No es pot descarregar la imatge.',
diskShared: "Apagueu primer el disc virtual i després useu la descàrrega d'imatges.",
diskOff: 'Apaga el disc virtual',
uploadbox: 'Deixeu anar el fitxer aquí o feu clic per seleccionar-lo',
inputfile: "Introduïu el fitxer d'imatge",
NoISO: 'Cap ISO',
@@ -392,7 +435,8 @@ const ca = {
hdmi: {
description: 'Activa la sortida HDMI',
idleTimeoutTitle: "Temps d'espera d'inactivitat de captura",
idleTimeoutDescription: "Atura la captura HDMI després de no detectar espectadors actius durant",
idleTimeoutDescription:
'Atura la captura HDMI després de no detectar espectadors actius durant',
minutes: 'min'
},
autostart: {
@@ -410,6 +454,11 @@ const ca = {
hidOnlyDesc: "Deixeu d'emular dispositius virtuals, conservant només el control bàsic HID",
disk: 'Disc virtual',
diskDesc: 'Munta un disc U virtual al dispositiu remot',
diskLocked: 'Desactivat mentre hi ha una imatge muntada (activar-lo cancel·la el muntatge)',
diskCancelMount:
"Activar el disc virtual cancel·la la imatge muntada i interromp una descàrrega o pujada d'imatge en curs. Voleu continuar?",
diskBreakDownload:
"Activar el disc virtual interromp la descàrrega d'imatges. Voleu continuar?",
network: 'Xarxa virtual',
networkDesc: 'Munta una targeta de xarxa virtual al dispositiu remot',
reboot: 'Reinicia',
@@ -517,10 +566,31 @@ const ca = {
preview: 'Versió de prova',
previewDesc: 'Prova noves funcions abans que ningú',
previewTip: 'Compte: aquestes versions poden tenir errors o funcions inacabades!',
customServer: {
title: 'Servidor d’actualitzacions personalitzat',
desc: 'Cerca i baixa actualitzacions en línia des d’un servidor especificat',
invalidUrl:
'Introduïu un directori de servidor HTTP o HTTPS vàlid, sense paràmetres de consulta, fragments ni latest.json.',
loadFailed: 'No s’ha pogut carregar la configuració del servidor d’actualitzacions.',
saveFailed: 'No s’ha pogut desar la configuració del servidor d’actualitzacions.',
saved: 'S’ha desat la configuració del servidor d’actualitzacions.',
save: 'Desa',
confirmTitle: 'Voleu utilitzar un servidor d’actualitzacions personalitzat?',
confirmDesc:
'SHA-512 només comprova que el paquet coincideixi amb el manifest proporcionat per aquest servidor. Això no demostra que el paquet sigui una versió oficial de NanoKVM. Un servidor defectuós o maliciós pot deixar el dispositiu inutilitzable, provocar la pèrdua de dades o comprometre el sistema.',
confirm: 'Utilitza’l igualment',
previewDisabled:
'Les actualitzacions de previsualització no estan disponibles mentre hi hagi activat un servidor d’actualitzacions personalitzat.'
},
offline: {
title: 'Actualitzacions fora de línia',
desc: "Actualització mitjançant el paquet d'instal·lació local",
upload: 'Puja',
checksumPlaceholder: 'Suma de verificació SHA-256 (opcional)',
invalidChecksum:
'La suma de verificació SHA-256 ha de contenir 64 caràcters hexadecimals.',
checksumMismatch:
'La verificació SHA-256 ha fallat. És possible que el paquet estigui malmès.',
invalidName: 'Format de nom de fitxer no vàlid. Baixeu-lo des de les versions de GitHub.',
updateFailed: 'Error en actualitzar. Torna-ho a intentar.'
}
@@ -570,8 +640,10 @@ const ca = {
ready: "Temps d'execució a punt",
stopped: "El temps d'execució s'ha aturat",
blockedByMCP: 'El control MCP extern està actiu',
readyBlockedByMCP: 'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl: 'The runtime is running. Grant PicoClaw device control before reconnecting.',
readyBlockedByMCP:
'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl:
'The runtime is running. Grant PicoClaw device control before reconnecting.',
unavailable: "Temps d'execució no disponible",
configError: 'Error de configuració'
},
@@ -602,7 +674,8 @@ const ca = {
mcp: 'Control del dispositiu: MCP extern',
mcpDescription: 'External MCP can write to the device. PicoClaw will not take over input.',
off: 'Control del dispositiu: desactivat',
offDescription: 'AI will not write keyboard or mouse input. Manual control remains available.',
offDescription:
'AI will not write keyboard or mouse input. Manual control remains available.',
transitioning: 'Device control: switching',
transitioningDescription: 'Device control is syncing. Please wait.',
grant: 'Concedeix control',
@@ -610,7 +683,8 @@ const ca = {
releasing: 'Releasing...',
switching: 'Switching...',
releasingLabel: 'Device control: releasing',
releasingDescription: 'Device control is being returned. PicoClaw has stopped current writes.',
releasingDescription:
'Device control is being returned. PicoClaw has stopped current writes.',
granted: 'Control de PicoClaw concedit',
released: 'Control de PicoClaw alliberat',
grantFailed: "No s'ha pogut concedir el control a PicoClaw",

View File

@@ -65,6 +65,36 @@ const cz = {
video: 'Režim videa',
videoDirectTips: 'Chcete-li používat tento režim, povolte HTTPS v "Nastavení > Zařízení"',
resolution: 'Rozlišení',
controlRegion: {
title: 'Kalibrace myši',
description:
'Toto nastavení použijte, pokud ovládané zařízení používá jiné rozlišení než 16:9 a kurzor je vodorovně nebo svisle posunutý.',
off: 'Vypnuto',
auto: 'Automaticky',
autoWarning: 'Kalibrace může selhat, pokud má uživatelská aplikace zcela černé pozadí.',
manual: 'Ručně',
selectedResolution: 'Rozlišení vybrané oblasti',
unused: 'Nepoužito',
originalResolution: 'Původní rozlišení',
selectResolution: 'Vyberte původní rozlišení',
addResolution: 'Přidat vlastní rozlišení',
add: 'Přidat',
duplicateResolution: 'Toto rozlišení již existuje.',
width: 'Šířka',
height: 'Výška',
apply: 'Vypočítat a použít',
invalidResolution: 'Po načtení videa zadejte platné původní rozlišení.',
select: 'Vybrat oblast',
clear: 'Obnovit automatickou detekci',
saveFailed: 'Vstupní oblast se nepodařilo uložit.',
tooSmall: 'Vybraná oblast je příliš malá.',
previewUnavailable: 'Náhled není k dispozici',
clearConfirm: 'Obnovit automatickou detekci černých okrajů?',
dragHint: 'Tažením vyberte oblast vzdálené plochy',
finish: 'Hotovo',
confirm: 'Potvrdit',
cancel: 'Zrušit'
},
auto: 'Automatické',
autoTips:
'Může docházet k trhání obrazu nebo posunu myši při určitých rozlišeních. Zvažte úpravu rozlišení vzdáleného hostitele nebo vypněte automatický režim.',
@@ -84,6 +114,10 @@ const cz = {
description:
'H.264 Direct a H.264 WebRTC se používají současně. To může způsobit trhání obrazu nebo poškozené video. Používejte pouze jeden režim H.264.'
},
webrtcConnectionFailed: {
title: 'Připojení WebRTC se nezdařilo',
description: 'Zkontrolujte síťové připojení nebo přepněte režim videa.'
},
captureStatus: {
hdmiError: 'Chyba obrazu HDMI',
unsupportedResolution: 'Aktuální rozlišení není podporováno',
@@ -188,6 +222,12 @@ const cz = {
mountFailed: 'Připojení se nezdařilo',
mountDesc:
'V některých systémech je nutné před připojením obrazu vysunout virtuální disk na vzdáleném hostiteli.',
diskOnWarn:
'Mounting the image turns the virtual disk off, so the computer can no longer access /data. Continue?',
diskOffWarn:
'The virtual disk is off and has to be enabled to mount the image. The USB devices on the computer are enumerated again. Continue?',
diskShared:
'Virtual disk is enabled, so /data is read-only here. Disable it to delete or upload images.',
unmountFailed: 'Odpojení se nezdařilo',
unmountDesc:
'Na některých systémech se musíte před odpojením obrazu ručně vysunout ze vzdáleného hostitele.',
@@ -256,6 +296,8 @@ const cz = {
input: 'Zadejte prosím vzdálený obrázek URL',
ok: 'OK',
disabled: 'Oddíl /data je RO, takže obrázek nelze stáhnout',
diskShared: 'Turn the virtual disk off first, then use the image download.',
diskOff: 'Turn off the virtual disk',
uploadbox: 'Přetáhněte soubor sem nebo kliknutím vyberte',
inputfile: 'Zadejte soubor obrázku',
NoISO: 'Žádné ISO',
@@ -413,6 +455,10 @@ const cz = {
hidOnlyDesc: 'Zastavit emulaci virtuálních zařízení a zachovat pouze základní ovládání HID',
disk: 'Virtuální disk',
diskDesc: 'Mount virtual U-disk on the remote host',
diskLocked: 'Off while an image is mounted (turning it on cancels the mount)',
diskCancelMount:
'Enabling the virtual disk cancels the mounted image and interrupts a running image download or upload. Continue?',
diskBreakDownload: 'Enabling the virtual disk interrupts the image download. Continue?',
network: 'Virtuální síť',
networkDesc: 'Připojit virtuální síťovou kartu na vzdáleném hostiteli',
reboot: 'Restartujte',
@@ -522,10 +568,29 @@ const cz = {
previewDesc: 'Získejte včasný přístup k novým funkcím a vylepšením',
previewTip:
'Uvědomte si prosím, že předběžné verze mohou obsahovat chyby nebo neúplné funkce!',
customServer: {
title: 'Vlastní aktualizační server',
desc: 'Vyhledávejte a stahujte online aktualizace ze zadaného serveru',
invalidUrl:
'Zadejte platnou adresu adresáře serveru HTTP nebo HTTPS bez parametrů, fragmentu nebo souboru latest.json.',
loadFailed: 'Konfiguraci aktualizačního serveru se nepodařilo načíst.',
saveFailed: 'Konfiguraci aktualizačního serveru se nepodařilo uložit.',
saved: 'Konfigurace aktualizačního serveru byla uložena.',
save: 'Uložit',
confirmTitle: 'Použít vlastní aktualizační server?',
confirmDesc:
'SHA-512 pouze ověřuje, že balíček odpovídá manifestu poskytnutému tímto serverem. Neprokazuje, že je balíček oficiálním vydáním NanoKVM. Vadný nebo škodlivý server může způsobit nefunkčnost zařízení, ztrátu dat nebo narušení zabezpečení systému.',
confirm: 'Přesto použít',
previewDisabled:
'Testovací aktualizace nejsou při použití vlastního aktualizačního serveru dostupné.'
},
offline: {
title: 'Offline aktualizace',
desc: 'Aktualizace prostřednictvím místního instalačního balíčku',
upload: 'Nahrát',
checksumPlaceholder: 'Kontrolní součet SHA-256 (volitelný)',
invalidChecksum: 'Kontrolní součet SHA-256 musí obsahovat 64 hexadecimálních znaků.',
checksumMismatch: 'Ověření SHA-256 se nezdařilo. Balíček může být poškozený.',
invalidName: 'Neplatný formát souboru. Stáhněte si prosím z vydání GitHubu.',
updateFailed: 'Aktualizace se nezdařila. Zkuste to prosím znovu.'
}
@@ -575,8 +640,10 @@ const cz = {
ready: 'Běhové prostředí připraveno',
stopped: 'Běhové prostředí zastaveno',
blockedByMCP: 'Externí ovládání MCP je aktivní',
readyBlockedByMCP: 'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl: 'The runtime is running. Grant PicoClaw device control before reconnecting.',
readyBlockedByMCP:
'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl:
'The runtime is running. Grant PicoClaw device control before reconnecting.',
unavailable: 'Běhové prostředí není k dispozici',
configError: 'Chyba konfigurace'
},
@@ -607,7 +674,8 @@ const cz = {
mcp: 'Ovládání zařízení: externí MCP',
mcpDescription: 'External MCP can write to the device. PicoClaw will not take over input.',
off: 'Ovládání zařízení: vypnuto',
offDescription: 'AI will not write keyboard or mouse input. Manual control remains available.',
offDescription:
'AI will not write keyboard or mouse input. Manual control remains available.',
transitioning: 'Device control: switching',
transitioningDescription: 'Device control is syncing. Please wait.',
grant: 'Předat ovládání',
@@ -615,7 +683,8 @@ const cz = {
releasing: 'Releasing...',
switching: 'Switching...',
releasingLabel: 'Device control: releasing',
releasingDescription: 'Device control is being returned. PicoClaw has stopped current writes.',
releasingDescription:
'Device control is being returned. PicoClaw has stopped current writes.',
granted: 'Ovládání PicoClaw povoleno',
released: 'Ovládání PicoClaw uvolněno',
grantFailed: 'Nepodařilo se předat ovládání PicoClaw',

View File

@@ -64,6 +64,37 @@ const da = {
video: 'Videotilstand',
videoDirectTips: 'Aktiver HTTPS i "Indstillinger > Enhed" for at bruge denne tilstand',
resolution: 'Opløsning',
controlRegion: {
title: 'Musekalibrering',
description:
'Brug denne indstilling, når den styrede enhed bruger en opløsning, der ikke er 16:9, og markøren er forskudt vandret eller lodret.',
off: 'Fra',
auto: 'Automatisk',
autoWarning:
'Kalibreringen kan mislykkes, hvis brugerprogrammet har en helt sort baggrund.',
manual: 'Manuel',
selectedResolution: 'Valgt områdeopløsning',
unused: 'Ikke i brug',
originalResolution: 'Oprindelig opløsning',
selectResolution: 'Vælg oprindelig opløsning',
addResolution: 'Tilføj brugerdefineret opløsning',
add: 'Tilføj',
duplicateResolution: 'Denne opløsning findes allerede.',
width: 'Bredde',
height: 'Højde',
apply: 'Beregn og anvend',
invalidResolution: 'Indtast en gyldig oprindelig opløsning, når videoen er klar.',
select: 'Vælg område',
clear: 'Gendan automatisk registrering',
saveFailed: 'Inputområdet kunne ikke gemmes.',
tooSmall: 'Det valgte område er for lille.',
previewUnavailable: 'Forhåndsvisning er ikke tilgængelig',
clearConfirm: 'Gendan automatisk registrering af sorte kanter?',
dragHint: 'Træk for at vælge fjernskrivebordets område',
finish: 'Færdig',
confirm: 'Bekræft',
cancel: 'Annuller'
},
auto: 'Automatisk',
autoTips:
'Screen-tearing eller mouse-offset kan opstå ved enkelte opløsninger. Hvis du oplever dette, kan du prøve at justere fjerncomputerens skærmopløsning eller deaktivere automatisk tilstand.',
@@ -83,6 +114,10 @@ const da = {
description:
'H.264 Direct og H.264 WebRTC bruges samtidigt. Dette kan forårsage skærmrivning eller beskadiget video. Brug kun én H.264-tilstand.'
},
webrtcConnectionFailed: {
title: 'WebRTC-forbindelse mislykkedes',
description: 'Kontrollér netværksforbindelsen, eller skift videotilstand.'
},
captureStatus: {
hdmiError: 'Fejl i HDMI-billedet',
unsupportedResolution: 'Den aktuelle opløsning understøttes ikke',
@@ -186,6 +221,12 @@ const da = {
mountFailed: 'Montering af diskbillede mislykkedes',
mountDesc:
'På nogle systemer kan det være nødvendigt at skubbe den virtuelle disk ud på fjerncomputeren før du kan montere diskbilledet.',
diskOnWarn:
'Mounting the image turns the virtual disk off, so the computer can no longer access /data. Continue?',
diskOffWarn:
'The virtual disk is off and has to be enabled to mount the image. The USB devices on the computer are enumerated again. Continue?',
diskShared:
'Virtual disk is enabled, so /data is read-only here. Disable it to delete or upload images.',
unmountFailed: 'Afmontering mislykkedes',
unmountDesc:
'På nogle systemer skal du manuelt skubbe ud fra fjernværten, før du afmonterer billedet.',
@@ -254,6 +295,8 @@ const da = {
input: 'Indtast venligst et fjernbillede URL',
ok: 'OK',
disabled: '/data partitionen er RO, så vi kan ikke downloade billedet',
diskShared: 'Turn the virtual disk off first, then use the image download.',
diskOff: 'Turn off the virtual disk',
uploadbox: 'Slip filen her, eller klik for at vælge',
inputfile: 'Indtast venligst billedfilen',
NoISO: 'Ingen ISO',
@@ -411,6 +454,10 @@ const da = {
'Stop med at emulere virtuelle enheder, og behold kun grundlæggende HID kontrol',
disk: 'Virtuel disk',
diskDesc: 'Mount virtual U-disk on the remote host',
diskLocked: 'Off while an image is mounted (turning it on cancels the mount)',
diskCancelMount:
'Enabling the virtual disk cancels the mounted image and interrupts a running image download or upload. Continue?',
diskBreakDownload: 'Enabling the virtual disk interrupts the image download. Continue?',
network: 'Virtuelt netværk',
networkDesc: 'Monter det virtuelle netværkskort på den eksterne vært',
reboot: 'Genstart',
@@ -520,10 +567,29 @@ const da = {
previewDesc: 'Få tidlig adgang til nye funktioner og forbedringer',
previewTip:
'Vær opmærksom på, at forhåndsvisningsudgivelser kan indeholde fejl eller ufuldstændig funktionalitet!',
customServer: {
title: 'Brugerdefineret opdateringsserver',
desc: 'Søg efter og download onlineopdateringer fra en angivet server',
invalidUrl:
'Indtast en gyldig HTTP- eller HTTPS-servermappe uden forespørgsel, fragment eller latest.json.',
loadFailed: 'Konfigurationen af opdateringsserveren kunne ikke indlæses.',
saveFailed: 'Konfigurationen af opdateringsserveren kunne ikke gemmes.',
saved: 'Konfigurationen af opdateringsserveren er gemt.',
save: 'Gem',
confirmTitle: 'Vil du bruge en brugerdefineret opdateringsserver?',
confirmDesc:
'SHA-512 kontrollerer kun, at pakken stemmer overens med manifestet fra denne server. Det beviser ikke, at pakken er en officiel NanoKVM-udgivelse. En fejlbehæftet eller ondsindet server kan gøre enheden ubrugelig, medføre tab af data eller kompromittere systemet.',
confirm: 'Brug alligevel',
previewDisabled:
'Forhåndsvisningsopdateringer er ikke tilgængelige, mens en brugerdefineret opdateringsserver er aktiveret.'
},
offline: {
title: 'Offline opdateringer',
desc: 'Opdatering via lokal installationspakke',
upload: 'Upload',
checksumPlaceholder: 'SHA-256-kontrolsum (valgfri)',
invalidChecksum: 'SHA-256-kontrolsummen skal indeholde 64 hexadecimale tegn.',
checksumMismatch: 'SHA-256-verificeringen mislykkedes. Pakken kan være beskadiget.',
invalidName: 'Ugyldigt filnavnsformat. Download venligst fra GitHub-udgivelser.',
updateFailed: 'Opdatering fejlede. Prøv igen.'
}
@@ -573,8 +639,10 @@ const da = {
ready: 'Runtime klar',
stopped: 'Runtime stoppet',
blockedByMCP: 'Ekstern MCP-styring er aktiv',
readyBlockedByMCP: 'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl: 'The runtime is running. Grant PicoClaw device control before reconnecting.',
readyBlockedByMCP:
'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl:
'The runtime is running. Grant PicoClaw device control before reconnecting.',
unavailable: 'Runtime utilgængelig',
configError: 'Konfigurationsfejl'
},
@@ -605,7 +673,8 @@ const da = {
mcp: 'Enhedsstyring: ekstern MCP',
mcpDescription: 'External MCP can write to the device. PicoClaw will not take over input.',
off: 'Enhedsstyring: fra',
offDescription: 'AI will not write keyboard or mouse input. Manual control remains available.',
offDescription:
'AI will not write keyboard or mouse input. Manual control remains available.',
transitioning: 'Device control: switching',
transitioningDescription: 'Device control is syncing. Please wait.',
grant: 'Giv styring',
@@ -613,7 +682,8 @@ const da = {
releasing: 'Releasing...',
switching: 'Switching...',
releasingLabel: 'Device control: releasing',
releasingDescription: 'Device control is being returned. PicoClaw has stopped current writes.',
releasingDescription:
'Device control is being returned. PicoClaw has stopped current writes.',
granted: 'PicoClaw-styring givet',
released: 'PicoClaw-styring frigivet',
grantFailed: 'Kunne ikke give PicoClaw styring',

View File

@@ -67,6 +67,38 @@ const de = {
videoDirectTips:
'Aktivieren Sie HTTPS unter „Einstellungen > Gerät“, um diesen Modus zu verwenden',
resolution: 'Auflösung',
controlRegion: {
title: 'Mauskalibrierung',
description:
'Verwenden Sie diese Einstellung, wenn das gesteuerte Gerät eine andere Auflösung als 16:9 verwendet und der Mauszeiger horizontal oder vertikal versetzt ist.',
off: 'Aus',
auto: 'Automatisch',
autoWarning:
'Die Kalibrierung kann fehlschlagen, wenn die Benutzeranwendung einen vollständig schwarzen Hintergrund hat.',
manual: 'Manuell',
selectedResolution: 'Auflösung des ausgewählten Bereichs',
unused: 'Nicht verwendet',
originalResolution: 'Originalauflösung',
selectResolution: 'Originalauflösung auswählen',
addResolution: 'Benutzerdefinierte Auflösung hinzufügen',
add: 'Hinzufügen',
duplicateResolution: 'Diese Auflösung ist bereits vorhanden.',
width: 'Breite',
height: 'Höhe',
apply: 'Berechnen und anwenden',
invalidResolution:
'Geben Sie eine gültige Originalauflösung ein, sobald das Video bereit ist.',
select: 'Bereich auswählen',
clear: 'Automatische Erkennung wiederherstellen',
saveFailed: 'Der Eingabebereich konnte nicht gespeichert werden.',
tooSmall: 'Der ausgewählte Bereich ist zu klein.',
previewUnavailable: 'Vorschau nicht verfügbar',
clearConfirm: 'Automatische Erkennung schwarzer Ränder wiederherstellen?',
dragHint: 'Ziehen Sie, um den Remote-Desktop-Bereich auszuwählen',
finish: 'Fertig',
confirm: 'Bestätigen',
cancel: 'Abbrechen'
},
auto: 'Automatisch',
autoTips:
'Bildverzerrungen oder ein versetzter Mauszeiger können bei bestimmten Auflösungen auftreten. Versuchen Sie, die Auflösung des entfernten Hosts anzupassen oder den automatischen Modus zu deaktivieren.',
@@ -86,6 +118,10 @@ const de = {
description:
'H.264 Direct und H.264 WebRTC werden gleichzeitig verwendet. Dies kann zu Bildschirm-Tearing oder beschädigtem Video führen. Bitte verwenden Sie nur einen H.264-Modus.'
},
webrtcConnectionFailed: {
title: 'WebRTC-Verbindung fehlgeschlagen',
description: 'Überprüfen Sie die Netzwerkverbindung oder wechseln Sie den Videomodus.'
},
captureStatus: {
hdmiError: 'HDMI-Bildschirmfehler',
unsupportedResolution: 'Die aktuelle Auflösung wird nicht unterstützt',
@@ -190,6 +226,12 @@ const de = {
mountFailed: 'Einbinden fehlgeschlagen',
mountDesc:
'In einigen Systemen ist es notwendig, die virtuelle Festplatte auf dem entfernten Host auszuwerfen, bevor das Image eingebunden werden kann.',
diskOnWarn:
'Beim Einbinden des Images wird das virtuelle Laufwerk ausgeschaltet, sodass der Computer nicht mehr auf /data zugreifen kann. Fortfahren?',
diskOffWarn:
'Das virtuelle Laufwerk ist ausgeschaltet und muss zum Einbinden des Images aktiviert werden. Die USB-Geräte am Computer werden neu erkannt. Fortfahren?',
diskShared:
'Das virtuelle Laufwerk ist aktiv, daher ist /data hier schreibgeschützt. Deaktivieren Sie es, um Images zu löschen oder hochzuladen.',
unmountFailed: 'Das Aufheben der Bereitstellung ist fehlgeschlagen',
unmountDesc:
'Auf einigen Systemen müssen Sie das Image manuell vom Remote-Host auswerfen, bevor Sie die Bereitstellung aufheben.',
@@ -259,6 +301,9 @@ const de = {
ok: 'Ok',
disabled:
'/data Partition ist nur-lesbar, daher kann das Systemabbild nicht heruntergeladen werden',
diskShared:
'Schalten Sie zuerst das virtuelle Laufwerk aus und verwenden Sie dann den Image-Download.',
diskOff: 'Virtuelles Laufwerk ausschalten',
uploadbox: 'Datei hier ablegen oder klicken zum Auswählen',
inputfile: 'Bitte geben Sie die Datei für das Systemabbild an',
NoISO: 'Keine ISO',
@@ -398,7 +443,8 @@ const de = {
hdmi: {
description: 'HDMI/Monitor-Ausgabe aktivieren',
idleTimeoutTitle: 'Zeitlimit für inaktive Aufnahme',
idleTimeoutDescription: 'HDMI-Aufnahme stoppen, wenn keine aktiven Zuschauer vorhanden sind für',
idleTimeoutDescription:
'HDMI-Aufnahme stoppen, wenn keine aktiven Zuschauer vorhanden sind für',
minutes: 'Min.'
},
autostart: {
@@ -417,6 +463,11 @@ const de = {
'Hören Sie auf, virtuelle Geräte zu emulieren, und behalten Sie nur die grundlegende HID-Steuerung bei',
disk: 'Virtuelle Festplatte',
diskDesc: 'Binde das virtuelle U-Laufwerk an den entfernten Host',
diskLocked: 'Aus, solange ein Image eingebunden ist (Einschalten bricht die Einbindung ab)',
diskCancelMount:
'Das Aktivieren des virtuellen Laufwerks bricht das eingebundene Image ab und unterbricht einen laufenden Image-Download oder -Upload. Fortfahren?',
diskBreakDownload:
'Das Aktivieren des virtuellen Laufwerks unterbricht den Image-Download. Fortfahren?',
network: 'Virtuelles Netzwerk',
networkDesc: 'Binde die virtuelle Netzwerkkarte an den entfernten Host',
reboot: 'Neustarten',
@@ -526,10 +577,30 @@ const de = {
previewDesc: 'Erhalten Sie vorab Zugriff auf neue Funktionen und Verbesserungen',
previewTip:
'Bitte beachten Sie, dass Vorab-Versionen womöglich noch Fehler oder unvollständige Funktionen enthalten!',
customServer: {
title: 'Benutzerdefinierter Update-Server',
desc: 'Online-Updates von einem angegebenen Server suchen und herunterladen',
invalidUrl:
'Geben Sie ein gültiges HTTP- oder HTTPS-Serververzeichnis ohne Abfrageparameter, Fragment oder latest.json ein.',
loadFailed: 'Die Konfiguration des Update-Servers konnte nicht geladen werden.',
saveFailed: 'Die Konfiguration des Update-Servers konnte nicht gespeichert werden.',
saved: 'Die Konfiguration des Update-Servers wurde gespeichert.',
save: 'Speichern',
confirmTitle: 'Benutzerdefinierten Update-Server verwenden?',
confirmDesc:
'SHA-512 bestätigt lediglich, dass das Paket mit dem von diesem Server bereitgestellten Manifest übereinstimmt. Es beweist nicht, dass das Paket eine offizielle NanoKVM-Version ist. Ein fehlerhafter oder bösartiger Server kann das Gerät unbrauchbar machen, Datenverlust verursachen oder das System kompromittieren.',
confirm: 'Trotzdem verwenden',
previewDisabled:
'Vorschau-Updates sind nicht verfügbar, solange ein benutzerdefinierter Update-Server aktiviert ist.'
},
offline: {
title: 'Offline Aktualisierung',
desc: 'Über lokales Installationspaket aktualisieren',
upload: 'Hochladen',
checksumPlaceholder: 'SHA-256-Prüfsumme (optional)',
invalidChecksum: 'Die SHA-256-Prüfsumme muss 64 hexadezimale Zeichen enthalten.',
checksumMismatch:
'Die SHA-256-Überprüfung ist fehlgeschlagen. Das Paket ist möglicherweise beschädigt.',
invalidName:
'Ungültiges Dateinamenformat. Bitte laden Sie von den GitHub-Releases herunter.',
updateFailed: 'Aktualisierung fehlgeschlagen. Bitte versuchen Sie es erneut.'
@@ -580,8 +651,10 @@ const de = {
ready: 'Runtime bereit',
stopped: 'Runtime gestoppt',
blockedByMCP: 'Externe MCP-Steuerung ist aktiv',
readyBlockedByMCP: 'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl: 'The runtime is running. Grant PicoClaw device control before reconnecting.',
readyBlockedByMCP:
'The runtime is running, but external MCP currently controls device input.',
readyWithoutControl:
'The runtime is running. Grant PicoClaw device control before reconnecting.',
unavailable: 'Runtime nicht verfügbar',
configError: 'Konfigurationsfehler'
},
@@ -612,7 +685,8 @@ const de = {
mcp: 'Gerätesteuerung: externes MCP',
mcpDescription: 'External MCP can write to the device. PicoClaw will not take over input.',
off: 'Gerätesteuerung: aus',
offDescription: 'AI will not write keyboard or mouse input. Manual control remains available.',
offDescription:
'AI will not write keyboard or mouse input. Manual control remains available.',
transitioning: 'Device control: switching',
transitioningDescription: 'Device control is syncing. Please wait.',
grant: 'Steuerung erteilen',
@@ -620,7 +694,8 @@ const de = {
releasing: 'Releasing...',
switching: 'Switching...',
releasingLabel: 'Device control: releasing',
releasingDescription: 'Device control is being returned. PicoClaw has stopped current writes.',
releasingDescription:
'Device control is being returned. PicoClaw has stopped current writes.',
granted: 'PicoClaw-Steuerung erteilt',
released: 'PicoClaw-Steuerung freigegeben',
grantFailed: 'PicoClaw-Steuerung konnte nicht erteilt werden',

Some files were not shown because too many files have changed in this diff Show More