Compare commits

...

225 Commits
2.3.0 ... 2.5.0

Author SHA1 Message Date
Guoguo
40bbeab8ae ci: split package, tag, and release workflows (#855) 2026-08-04 16:33:56 +08:00
肆月
eb20fb41aa feat: show remote keyboard lock status (#838)
* feat: show remote keyboard lock status

* fix(keyboard-led-status): eliminate polling and improve delivery

* fix(keyboard-led-status): simplify indicator labels
2026-08-04 09:28:14 +08:00
watermeko
21e834b4c8 perf: reduce latency in 60 Hz mode (#844)
- Add decode-driven flow control and bounded GOP-aware queues to prevent stale H.264 frames from accumulating in TCP and WebSocket buffers.
- Isolate slow clients with dedicated writer goroutines, write deadlines, and safer connection lifecycle handling.
- Move the Direct H.264 socket into the worker, simplify the low-latency decode path, and improve reconnect behavior.
2026-07-31 19:08:07 +08:00
916BGAI
8773605715 Merge pull request #845 from imguoguo/ci/release-package
ci: release package
2026-07-31 19:00:18 +08:00
Guoguo
b23eb33611 ci: build identifiable NanoKVM release packages 2026-07-31 03:47:54 -07:00
Guoguo
ef432da2fe build: allow overriding the builder image and install patchelf
Groundwork for building outside an interactive terminal.

- IMAGE_NAME becomes overridable so a prebuilt image can be used instead
  of building one locally
- docker run no longer hardcodes -it on the app and support recipes:
  allocating a TTY fails where there is none. shell stays interactive
- install patchelf, which server/build.sh needs to set the RPATH on the
  server binary
2026-07-30 19:55:30 -07:00
Guoguo
96c86f6098 fix(build): correct exit codes in support/sg2002/build
The script has no error handling of its own, so these all pass silently.

- update_lib exited 1 after succeeding, so callers could not chain it
- a failed maixcdk build printed "Build Error!" and exited 0, letting a
  caller carry on with no artifacts
- add_to_kvmapp did the same when the source did not exist
- the copies in update_lib were unchecked; since update_lib is what keeps
  the SDK components in sync with the source tree, a silent failure there
  yields libraries built from stale sources
2026-07-30 19:52:34 -07:00
watermeko
a7d7574e70 fix: warn about mixed H264 stream modes (#843) 2026-07-31 10:48:52 +08:00
watermeko
b587b9f912 fix: stop HDMI capture when logged out (#841)
* fix: stop HDMI capture when logged out

* feat: stop HDMI capture when viewers are idle

* fix: keep HDMI capture active for consumers
2026-07-30 17:29:07 +08:00
watermeko
004fd59093 fix(sg2002): harden VI state sharing 2026-07-30 16:08:48 +08:00
watermeko
774d314ce9 fix(sg2002): share VI debug state between processes 2026-07-30 16:08:48 +08:00
watermeko
e4d23014ba fix(sg2002): read VI debug state without shell pipelines 2026-07-30 16:08:48 +08:00
BeaconCat
dc050d1f19 fix(usb): assign deterministic gadget MAC so the host NIC stays stable (#828)
The USB network gadget (rndis.usb0 / ncm.usb0) is created without dev_addr or
host_addr, so the kernel picks a random MAC for both the device side and the
host side on every bind. S10uuid later pins the device-side usb0 via
'ip link set', but the host_addr -- the MAC the attached PC's RNDIS/NCM adapter
uses -- stays random and changes on every re-enumeration/reboot. The host then
registers a brand-new network adapter each time, piling up stale adapters/MACs
(e.g. ~10 after a few reboots) and breaking anything that keys off the MAC.

Derive both MACs from the chip UID (same scheme S10uuid already uses for eth0
and usb0), before binding the gadget:
  dev_addr  = 48:da:35:6e:<uid>
  host_addr = 48:da:35:6d:<uid>

Verified on a NanoKVM Cube: host_addr went from random a6:3f:5d:8a:7d:52 to a
stable 48:da:35:6d:26:62, identical across two reboots.

Fixes #740

Co-authored-by: BeaconCat <BeaconCat@users.noreply.github.com>
2026-07-29 16:29:53 +08:00
SiYue-ZO
57e1f6a4d6 fix(picoclaw): cancel runtime lifecycle on mode switch
Cancel PicoClaw start/readiness waits when MCP takes control, clear held manual input state after failed release reports, and keep paste duration below the control-mode wait budget.

Also add MCP copy failure translations and avoid reconnect effect churn when the locale changes.
2026-07-29 15:16:06 +08:00
SiYue-ZO
d578c63036 i18n(picoclaw): add MCP control translations
Add locale coverage for MCP settings, AI-control ownership, PicoClaw runtime operations, and related conflict states.
2026-07-29 15:16:06 +08:00
SiYue-ZO
6b98f5415f feat(web): add MCP settings and control handoff UI
Add the MCP settings view and frontend API bindings for configuring remote-control access.

Expose AI-control ownership state in PicoClaw, lock conflicting keyboard input paths, and preserve chat state when control is released.
2026-07-29 15:16:06 +08:00
SiYue-ZO
64ce12cc0d feat(mcp): add authenticated remote control backend
Add an MCP Streamable HTTP server with token authentication, screenshot capture, keyboard, and mouse tools.

Introduce shared control-mode and input-control coordination so MCP, PicoClaw, and local HID paths serialize ownership safely.

Integrate PicoClaw gateway/runtime control handoff with PID-managed startup and focused unit coverage.
2026-07-29 15:16:06 +08:00
watermeko
183f8dc983 fix: reuse existing container users and groups 2026-07-27 10:28:46 +08:00
watermeko
7eee77a33d fix: fix container slow caused by uid/gid 2026-07-27 10:28:46 +08:00
watermeko
c1986acf65 fix(web): keep direct H264 playback low latency 2026-07-24 15:41:02 +08:00
watermeko
c999a883bd perf(sg2002): integrate zero-copy H.264 capture
Move frame ownership and zero-copy VENC handling into the tracked MMF
and Vision sources instead of relying on a preload hook. Keep the sensor
name mapping aligned with middleware enums and release deferred VI frames
safely across encoder lifecycle changes.
2026-07-24 15:41:02 +08:00
肆月
70f8503cbb fix: prevent OLED sleep duration truncation (#834)
OLED sleep settings are stored as seconds, but the kvm_system reader parsed the value into a uint8_t before assigning it to the uint16_t state field. Values above 255 seconds wrapped, so 5 min, 10 min, 30 min, and 1 hour did not behave as selected.

Parse the setting into a uint16_t-sized temporary value and terminate the read buffer before atoi so all configured durations up to 3600 seconds are preserved.

Closes #826
2026-07-22 17:46:39 +08:00
Guoguo
5b0a7d2a91 feat: add sha256sum check (#832)
* feat(download): add sha256sum check and cancellable downloads

+ server/proto/download.go
	+ add DownloadImageReq and sha256 argument

server/router/download.go
	+ add cancel download router

server/service/download/service.go
	+ sha256 decode and check
	+ remove HEAD request
	+ cancel download

* refactor(download): synchronize image and application transfers

sovel the the problem that image downloading and app downloading would conflict
at same time

* fix: optimized UI of image download and locale issue

* fix: locale
2026-07-17 18:17:04 +08:00
watermeko
4fee758ff0 fix: fix api/storage/image/mounted error when using HID-Only mode (#833) 2026-07-17 18:02:07 +08:00
watermeko
736259baa3 fix: locale 2026-07-17 07:47:25 +00:00
watermeko
83b600bbee fix: optimized UI of image download and locale issue 2026-07-16 11:16:36 +00:00
watermeko
6071a6f57c refactor(download): synchronize image and application transfers
sovel the the problem that image downloading and app downloading would conflict
at same time
2026-07-16 11:03:07 +00:00
watermeko
69f5da6fc7 feat(download): add sha256sum check and cancellable downloads
+ server/proto/download.go
	+ add DownloadImageReq and sha256 argument

server/router/download.go
	+ add cancel download router

server/service/download/service.go
	+ sha256 decode and check
	+ remove HEAD request
	+ cancel download
2026-07-16 11:03:07 +00:00
916BGAI
3b2ba7c0c1 docs: add 2.4.3 changelog entries 2026-06-09 18:06:03 +08:00
916BGAI
208998c13a support lt6911d 2026-06-09 18:00:32 +08:00
wenjie
3de4a18eb4 chore: update js-cookie for security fix 2026-05-22 10:43:17 +08:00
wenjie
863fea9ab8 release: nanokvm@2.4.2 2026-05-20 16:23:16 +08:00
wenjie
f65c1b06aa chore: refresh desktop menu ordering and community links
- Replace the Discussion community link with Discord
- Align terminal and script ordering in the menu and appearance settings
- Remove the divider before the leader key menu item
2026-05-20 15:07:59 +08:00
wenjie
fe34008ce3 fix: handle left-button touch cancel and contextmenu cleanup 2026-05-20 14:49:33 +08:00
wenjie
961d7f2e89 fix: validate Wi-Fi password field 2026-05-20 11:53:53 +08:00
wenjie
94749ea621 fix: harden Wake-on-LAN MAC handling
Normalize stored MAC addresses, avoid shell execution for ether-wake, handle missing WOL history gracefully, and improve the WOL menu display for named MAC entries.
2026-05-20 11:38:14 +08:00
wenjie
6ae742deed fix: improve WebRTC loading indicator 2026-05-19 17:31:19 +08:00
wenjie
b653f905e4 perf: improve H264 streaming client handling
Use client snapshots for stream fanout, reduce frame queue latency, expose backend ICE server configuration to the WebRTC client, and clean up disconnected WebRTC clients more aggressively.
2026-05-19 17:04:57 +08:00
wenjie
af19795c29 refactor: remove legacy h264 stream package 2026-05-19 16:49:41 +08:00
wenjie
be7584d908 feat: show HDMI capture status on desktop screen
Track capture results for each stream mode, broadcast status updates over WebSocket, and display localized warning/error overlays in the desktop view.
2026-05-19 15:02:34 +08:00
wenjie
a960417739 fix: stabilize PicoClaw session switching
- Wait for gateway session release before reconnecting to a new or selected session
- Refresh runtime status before deciding whether a selected history session can reconnect
- Render structured thought messages from gateway payload metadata
- Prevent PicoClaw history rows from overflowing horizontally
- Add localized labels for the verifying install stage
2026-05-18 17:26:00 +08:00
wenjie
3f0621e7ed Merge pull request #799 from BeaconCat/feat/picoclaw-v3-session-history
feat(picoclaw): support sk_v1_ opaque session keys for V3 history
2026-05-18 15:31:39 +08:00
wenjie
515c5e2a76 Merge pull request #798 from BeaconCat/feat/picoclaw-v3-config
feat(picoclaw): adapt to PicoClaw V3 config format
2026-05-18 15:23:05 +08:00
wenjie
cb025f04b4 chore(web): update PostCSS and MSW worker
- Bump PostCSS to 8.5.10 and refresh the pnpm lockfile
- Regenerate the MSW service worker for msw 2.12.10
- Add pnpm build approvals for frontend tooling
2026-05-18 15:02:31 +08:00
wenjie
2ca5b19efe release: nanokvm@2.4.1 2026-05-08 18:16:58 +08:00
wenjie
40f3917014 fix: update translation of DNS description 2026-05-08 17:34:27 +08:00
wenjie
a40433522c fix: improve DHCP DNS fallback detection
Read DHCP DNS from /tmp/resolv.conf when the cached DHCP resolv file is empty, and only fall back to the active resolv.conf when DHCP mode is active or no manual boot config exists.
2026-05-08 17:13:13 +08:00
wenjie
8470b89214 fix(i18n): sync translations for supported locales
- Add missing localized strings for recent UI features, including keyboard shortcuts, clipboard paste, Wi-Fi AP auth, terminal options, device settings, Tailscale, updates, and PicoClaw.
- Align non-English locale resources with the English translation keys.
2026-05-08 16:19:37 +08:00
wenjie
5a08170518 ui: optimize the scrollbar style of the settings 2026-05-08 14:56:50 +08:00
BeaconCat
dff794cee4 feat(picoclaw): adapt to PicoClaw V3 config format
- channels -> channel_list with nested settings struct (V3 format)
- security channels -> channel_list.pico.settings.token
- Remove broken pico- prefix token composition logic
- Token now uses exact match with PicoClaw gateway
- Add GitHub Actions CI for building update package
- Version: 2.4.0.Beacon
2026-05-08 08:30:08 +08:00
wenjie
36cf9c30d8 feat: add DNS management to Network settings
- Add DNS configuration APIs for manual and DHCP modes, including persistence and udhcpc hook support.
- Add a Network settings tab with DNS controls, move Wi-Fi and HTTPS settings into it, and update translations.
- Update locales
2026-05-07 17:03:25 +08:00
wenjie
1c43542919 fix: harden HID recovery and cleanup
- Open HID gadget handles lazily in nonblocking mode and clear stale handles on write failures
- Release keyboard and mouse state when HID queues close or writes fail
- Reopen HID devices with retry after USB PHY reset
- Make websocket client close idempotent and close HID queues safely
- Expire and renew PicoClaw session locks during gateway relay
2026-05-06 16:44:42 +08:00
BeaconCat
8eca1edf47 feat(picoclaw): support sk_v1_ opaque session keys for V3 history 2026-05-06 10:21:52 +08:00
wenjie
4080788cab chore: update README.md 2026-04-24 14:30:10 +08:00
wenjie
424302789e chore: update README.md 2026-04-24 14:17:32 +08:00
wenjie
6651167dd8 chore: upgrade vulnerable web dependencies
- Bump Axios, Vite, ESLint, TypeScript ESLint, and related lockfile entries.
- Add yaml as an explicit frontend dev dependency.
2026-04-24 10:40:20 +08:00
wenjie
2d67720022 fix: preserve loopback access for host configuration
- Keep internal loopback HTTP APIs reachable when the server is bound to a
specific non-loopback host by adding a dedicated 127.0.0.1 listener.

- Move listener address helpers into utils and normalize HTTPS redirect hosts so
IPv6 request hosts are not double-bracketed.
2026-04-24 10:29:16 +08:00
wenjie
1893912ba7 Merge pull request #792 from kmw0410/main
update korean translation for picoclaw
2026-04-24 10:05:43 +08:00
wenjie
e41ce2d6b8 Merge pull request #788 from ilyesAj/feat/add_french_layout
Add French keyboard layout support on paste window
2026-04-24 10:05:23 +08:00
wenjie
a5c6489f19 Merge pull request #770 from Voranto/Voranto-patch-2
Fix wrong message during support build
2026-04-24 09:55:51 +08:00
wenjie
fafef3d89a Merge pull request #779 from allmazz/feature/server_listen_host
Add `host` server config parameter
2026-04-24 09:46:11 +08:00
kmw0410
4b5f539445 update korean translation for picoclaw 2026-04-23 13:55:39 +09:00
wenjie
cefe0f9ab2 feat: add internal USB recovery and initialize picoclaw token 2026-04-16 17:00:16 +08:00
Kirill Nikiforov
7f3d29eba2 fix ipv6 2026-04-16 00:51:02 +04:00
Kirill Nikiforov
64681e2aac add host server config parameter 2026-04-14 06:51:06 +04:00
ilyesAj
fcb1f1c7fe Add French keyboard layout support and update language options 2026-04-11 22:39:40 +02:00
wenjie
aa0546ff37 release: nanokvm@2.4.0 2026-04-10 18:07:23 +08:00
wenjie
3254412017 Squashed commit of the following:
commit 3dea4b1cfcb866d50c9c093b797c0f4f48fec23f
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 17:11:07 2026 +0800

    fix(picoclaw): clean temp media and surface MCP screenshots in chat

    - remove shared load_image staging and pass source paths through directly
    - delete /tmp/picoclaw_media when a gateway session closes
    - push MCP screenshot observations to downstream websocket clients
    - hide null tool feedback messages and auto-scroll when screenshots load

commit f58ffe1e27f83f64e2b0e8c2f8dcac46af715ace
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 15:55:59 2026 +0800

    Harden PicoClaw local API auth and session locking

    Split PicoClaw routes by caller trust level and require the internal loopback token for local-only endpoints. Update the NanoKVM bridge script to send the internal token for loopback requests. Relax session lock acquisition for screenshot and action calls so the active session can perform local operations without permanently taking over the lock, and stop forcing the runtime dm_scope default.

commit 462a0670bbc5138c893fbd1155e72465b82c2065
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 13:52:39 2026 +0800

    fix(picoclaw): improve KVM reliability and sidebar behavior

    - follow HTTPS loopback redirects in the NanoKVM bridge script
    - enable MJPEG frame caching only during active PicoClaw gateway sessions
    - restore legacy screen zoom behavior across MJPEG and H264 renderers
    - keep the PicoClaw sidebar available on mobile without splitter layout conflicts
    - hide empty "null"/"undefined" chat messages and keep MJPEG failures on a black screen

commit bfda85c6368825c7ddf47d347ba5ec2588135885
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Apr 10 11:37:15 2026 +0800

    fix(picoclaw): verify runtime downloads and remove unused config API

    - verify the downloaded runtime archive against the published SHA-512 checksum
    - remove the unused /api/picoclaw/config endpoints and related frontend state
    - rename runtime_control.go to runtime_constants.go for clearer intent

commit 10b34aaea59e10d70c3cdecb01915444561ceaf7
Author: wenjie <meetwenjie@gmail.com>
Date:   Thu Apr 9 16:32:30 2026 +0800

    fix: stabilize picoclaw runtime defaults and secure local MCP access

    - persist required NanoKVM startup defaults before launching picoclaw and after saving model config
    - force-enable the pico channel when loading config so runtime status can recover to ready
    - derive the local MCP URL from the configured HTTP port and keep loopback-only HTTP access behind an internal token
    - move loopback HTTP redirect logic into middleware to simplify main server startup
    - improve runtime/sidebar state handling and add the load-image endpoint for active picoclaw sessions

commit d20540195bf45ea290f727b473ee8cd2a1bbb68d
Author: wenjie <meetwenjie@gmail.com>
Date:   Fri Mar 27 17:55:29 2026 +0800

    feat(picoclaw): add picoclaw integration
2026-04-10 17:28:28 +08:00
BuGu
fda3c6b1a8 Add default mask for static IP 2026-03-27 10:50:18 +08:00
BuGu
97832557fb Fix the issue of occasional IP not displaying 2026-03-26 18:21:47 +08:00
wenjie
590db5b08c release: nanokvm@2.3.6 2026-03-12 16:02:18 +08:00
wenjie
10a512ec96 feat: Implement AP password authentication for the WiFi configuration page 2026-03-12 15:21:18 +08:00
wenjie
08093dddad Merge pull request #769 from Voranto/Voranto-patch-1
Enable support for 640x480 resolution
2026-03-12 11:21:17 +08:00
wenjie
86a85a61b7 Merge pull request #761 from klim4-bot/main
feat : Add Korean and Japanese virtual keyboard layouts
2026-03-12 11:20:54 +08:00
wenjie
cb3a2c562e Merge pull request #744 from tkmsst/pull-request
Update Japanese translation
2026-03-12 11:18:12 +08:00
Voranto
832832a716 Fix project name in build script for kvm_vision 2026-03-05 16:02:24 +01:00
Voranto
5fe6d0d48f Fix wrong message during ./build kvm_vision add_to_kvmapp 2026-03-05 15:57:44 +01:00
Voranto
67fe57f189 Enable support for 640x480 resolution 2026-03-05 15:52:49 +01:00
BuGu
44caee21ab Add encryption parameters for OLED distribution network 2026-03-04 17:11:42 +08:00
BuGu
5b2a1ff788 Add webpage logo generation tool and method 2026-03-04 17:09:52 +08:00
BuGu
dc5ba29bcf Add a logo file generator based on TUI 2026-03-03 19:12:59 +08:00
BuGu
89c14310c7 Add custom logo function 2026-03-03 18:50:35 +08:00
BuGu
3322a3c07f Add update mechanism for tailscale startup script 2026-03-03 18:49:02 +08:00
wj-xiao
9e1251ad6a release: nanokvm@2.3.5 2026-02-28 17:25:14 +08:00
wj-xiao
afec4efb34 feat: Implement login brute-force protection with lockout mechanism 2026-02-28 16:44:47 +08:00
wj-xiao
11980b9122 fix: improve Tailscale error handling in UI components and refine backend state mapping 2026-02-28 11:12:26 +08:00
wj-xiao
2a43fb5413 chore: update server and web dependencies 2026-02-28 10:53:31 +08:00
jason
57887f3f69 Add Korean and Japanese virtual keyboard layouts 2026-02-19 07:47:41 +09:00
tkmsst
2b8f640957 Update Japanese translation 2026-02-02 01:14:57 +09:00
wj-xiao
4af32fc703 release: nanokvm@2.3.4 2026-01-26 17:56:52 +08:00
wj-xiao
a611e5ef56 feat: support keyboard leader key functionality 2026-01-26 17:10:16 +08:00
wj-xiao
94051c3037 chore: added image version number v1.4.2 2026-01-26 11:23:17 +08:00
wj-xiao
d5cd706078 fix: compatible with non-standard modifier keys 2026-01-26 11:12:19 +08:00
wj-xiao
7460ebfd07 fix: the menu bar cannot be closed 2026-01-26 10:46:57 +08:00
wj-xiao
e3877308a0 fix: trigger update check when switching preview updates 2026-01-26 10:28:27 +08:00
wenjie
7c28fb8124 Merge pull request #737 from kmw0410/main
update korean translation
2026-01-26 10:08:02 +08:00
wenjie
b18873364f Merge pull request #733 from j796160836/feature/update_zh_tw
Update zh_tw translation
2026-01-26 10:07:37 +08:00
kmw0410
016a7d8a51 update korean translation 2026-01-25 22:04:24 +09:00
Johnny Sung
585f1bc2b5 feat: update zh_tw translation 2026-01-20 01:59:53 +08:00
wj-xiao
4fcc4c3747 release: nanokvm@2.3.3 2026-01-16 15:32:14 +08:00
wj-xiao
0d2c52adc3 feat: the menu bar supports setting the display mode 2026-01-16 11:47:56 +08:00
wj-xiao
af256e7f92 fix: compatible with IME composition 2026-01-15 17:04:17 +08:00
wj-xiao
84830421ee fix: compatible with Windows AltGr key 2026-01-15 16:45:48 +08:00
wj-xiao
9b278cdb0e fix: compatible with macOS's command key combinations 2026-01-14 17:58:25 +08:00
wj-xiao
9b40a5cf86 chore: update eslint 2026-01-14 17:58:25 +08:00
wj-xiao
b8d980be33 fix: the IntlBackslash key does not work on German virtual keyboard 2026-01-14 17:58:25 +08:00
wenjie
195037af87 Merge pull request #728 from imguoguo/main
ci: add missing parameters and push when issue closed
2026-01-14 15:48:07 +08:00
Guoguo
c98000069a ci: add missing parameters and push when issue closed 2026-01-14 07:43:19 +00:00
wenjie
2bd277b57d Merge pull request #725 from kmw0410/main
update korean translation
2026-01-14 10:30:40 +08:00
wj-xiao
4852ed813b chore: bump react-router-dom from 6.27.0 to 6.30.3 2026-01-14 10:27:08 +08:00
wj-xiao
fb08df9e4e fix: correct erroneous release date 2026-01-12 19:53:26 +08:00
kmw0410
64f3b49e21 update korean translation 2026-01-12 09:11:56 +09:00
wj-xiao
329c0a0001 release: nanokvm@2.3.2 2026-01-08 19:15:52 +08:00
wenjie
c28273d1f0 Merge pull request #721 from imguoguo/ci-use-jq
ci: use jq to format json
2026-01-08 17:33:40 +08:00
Guoguo
1d22d75889 ci: use jq to format json 2026-01-08 09:16:27 +00:00
wj-xiao
6ef8bb74e3 ui: update menu bar 2026-01-08 14:45:50 +08:00
wj-xiao
0e00760474 fix: fix touchscreen scrolling 2026-01-08 14:22:22 +08:00
wenjie
d969bd68ec Merge pull request #705 from imguoguo/add-issue-tracker
feat: add issue tracker
2026-01-06 16:15:31 +08:00
Guoguo
1e5f4cb24b feat: add issue tracker 2026-01-06 08:09:51 +00:00
wj-xiao
4d3b1c835e feat: support custom keyboard shortcuts 2026-01-06 13:58:53 +08:00
wj-xiao
e3558933b1 ui: menu bar stops auto-hiding when submenu is open 2026-01-06 11:08:57 +08:00
wj-xiao
7762706200 fix: set minimum width for mouse speed component 2026-01-05 18:19:06 +08:00
wj-xiao
b66707c959 refactor: support delete request 2026-01-05 17:45:38 +08:00
wj-xiao
a3440cf867 ui: update menu bar 2026-01-05 17:37:44 +08:00
wj-xiao
1b7021d64b refactor: refactor keyboard, mouse, and WebSocket 2026-01-05 16:49:17 +08:00
BuGu
687dd3bfc4 Fix the issue of old IP residue in static IP configuration 2026-01-04 18:18:00 +08:00
wj-xiao
cc072ab158 release: nanokvm@2.3.1 2025-12-26 19:12:33 +08:00
wenjie
b0a01a9837 Merge pull request #611 from lowtech-guy/main
Add user-friendly build system design
2025-12-26 18:27:02 +08:00
wj-xiao
2d575b916c feat:support setting mouse wheel direction 2025-12-26 16:44:12 +08:00
wj-xiao
1f908ef181 fix: add the restart_phy command 2025-12-26 16:11:28 +08:00
wj-xiao
fb2adf13ee refactor: refactor offline update function 2025-12-26 15:38:05 +08:00
wj-xiao
ad9eb44ad8 fix: web terminal may not close properly 2025-12-26 10:53:21 +08:00
wj-xiao
b4962e7a58 fix: custom port might not work 2025-12-26 10:49:29 +08:00
wj-xiao
14614e5e35 ui: optimize menu bar ui 2025-12-26 10:22:59 +08:00
wj-xiao
9a93ab24f5 refactor: refactor virtual devices and HID 2025-12-26 10:06:17 +08:00
wj-xiao
aaad552633 refactor: refactor the Wi-Fi module 2025-12-24 16:48:24 +08:00
wenjie
79cc1cc2bf Merge pull request #692 from Alexander-Ger-Reich/main
Upload lokal ISO files and Offline Updater
2025-12-24 09:48:02 +08:00
wenjie
01bcda6886 Merge pull request #698 from deftdawg/oled_sleep_param-fix
Fix oled_sleep_param only retaining lowest 8-bits of value
2025-12-23 16:13:09 +08:00
wenjie
ec49bffe06 Merge pull request #687 from Deses/ES-lang-update
Updated Spanish translation with all missing strings
2025-12-23 15:32:14 +08:00
wenjie
2db5d86a3c Merge pull request #686 from pekishev/paste_rus
Add support for pasting russian text
2025-12-23 15:31:06 +08:00
wenjie
da6d4840f8 Merge pull request #685 from imguoguo/add-scale
feat: add video scale
2025-12-23 15:19:02 +08:00
wenjie
9afa21a0b0 Merge pull request #679 from acidflash/main
Add missing variables from last version
2025-12-23 15:17:35 +08:00
wenjie
6168069301 Merge pull request #674 from kmw0410/main
update korean translation
2025-12-23 15:01:16 +08:00
wenjie
ffe71ae6b1 Merge pull request #673 from imguoguo/add-autostart-upstream
feat: add autostart feature
2025-12-23 14:59:28 +08:00
wj-xiao
a6a97df4e7 Update NanoKVM-PCIe schematic 2025-12-19 14:21:33 +08:00
deftdawg
f05467f45c Fix oled_sleep_param only retaining lowest 8-bits of value
providing oled_sleep_param with a 16-bit value (i.e. >256), results unpredictable display sleep times as only the low 8-bits are retained due to uint8_t (i.e. 5 minutes 300 seconds; shuts off in ~44s /  300s - 256s), this patch switches to uint16_t which should allow for up to sleeps of up to 65535 seconds.
2025-12-18 16:39:58 -05:00
Alexander-Ger-Reich
969e3a5e6a Update update.go 2025-12-13 16:00:09 +01:00
Alexander-Ger-Reich
f0e7dc069c Update update.go 2025-12-13 15:55:10 +01:00
Alexander-Ger-Reich
f5f70bd015 Update update.go 2025-12-13 15:46:07 +01:00
Alexander-Ger-Reich
aa80e1d7cc Update index.tsx 2025-12-13 15:45:23 +01:00
Alexander-Ger-Reich
d6b03a345b Update en.ts 2025-12-13 15:44:46 +01:00
Alexander-Ger-Reich
c0cfcfa31a Update de.ts 2025-12-13 15:44:30 +01:00
Alexander-Ger-Reich
afdbb179ad Update update.go 2025-12-13 15:37:44 +01:00
Alexander-Ger-Reich
ed9b7c5126 Update index.tsx 2025-12-13 15:37:17 +01:00
Alexander-Ger-Reich
551329a41d Update en.ts 2025-12-13 15:36:52 +01:00
Alexander-Ger-Reich
b3c6b6c53d Update de.ts 2025-12-13 15:36:39 +01:00
Alexander-Ger-Reich
5a9cd18f94 Update en.ts 2025-12-13 15:36:28 +01:00
Alexander-Ger-Reich
63c8fc8eb5 Update en.ts 2025-12-13 15:33:07 +01:00
Alexander-Ger-Reich
3305c69e2d Update de.ts 2025-12-13 15:32:55 +01:00
Alexander-Ger-Reich
56a0468a53 Update index.tsx 2025-12-13 14:55:25 +01:00
Alexander-Ger-Reich
52416dfdd7 Update application.go 2025-12-13 14:54:20 +01:00
Alexander-Ger-Reich
bcd0b717ee Update application.go 2025-12-13 14:54:03 +01:00
Alexander-Ger-Reich
d9c9eae4f9 Create index.tsx 2025-12-13 14:46:26 +01:00
Alexander-Ger-Reich
c1a21c2d69 Update service.go 2025-12-13 14:44:42 +01:00
Alexander-Ger-Reich
8d822948cf Update en.ts 2025-12-13 14:43:44 +01:00
Alexander-Ger-Reich
7404a205a5 Update de.ts 2025-12-13 14:43:29 +01:00
Alexander-Ger-Reich
d774bf8c58 Update download.tsx 2025-12-13 14:42:55 +01:00
Alexander-Ger-Reich
0e1fae8751 Update application.ts 2025-12-13 10:53:28 +01:00
Alexander-Ger-Reich
3ff64483df Update application.go 2025-12-13 10:51:36 +01:00
Alexander-Ger-Reich
fed92254d2 Update application.go 2025-12-13 10:50:09 +01:00
Alexander-Ger-Reich
dec1621850 Update version.go 2025-12-13 10:49:15 +01:00
Alexander-Ger-Reich
116bb50364 Update service.go 2025-12-13 10:04:10 +01:00
wj-xiao
957d86d64c update README 2025-12-12 11:59:04 +08:00
Alexander-Ger-Reich
1fa6f48d4e Update service.go 2025-12-11 23:17:57 +01:00
Alexander-Ger-Reich
0610f6fd1a Update download.tsx 2025-12-11 23:17:33 +01:00
Alexander-Ger-Reich
ade9ac863f Update de.ts 2025-12-11 22:40:30 +01:00
Alexander-Ger-Reich
61ff3c5b23 Update en.ts 2025-12-11 22:40:16 +01:00
Alexander-Ger-Reich
19076b2508 Update en.ts 2025-12-11 00:07:29 +01:00
Alexander-Ger-Reich
e175147674 Update de.ts 2025-12-11 00:06:54 +01:00
Alexander-Ger-Reich
2cc64d2208 Update download.tsx 2025-12-11 00:03:56 +01:00
Alexander-Ger-Reich
346315b4bb Update download.tsx 2025-12-11 00:03:26 +01:00
Alexander-Ger-Reich
648c9f866e Update service.go 2025-12-11 00:02:01 +01:00
Alexander-Ger-Reich
b5866088fc Update download.tsx 2025-12-11 00:01:27 +01:00
Alexander-Ger-Reich
cd954b6f24 Update download.go 2025-12-10 19:27:20 +01:00
Alexander-Ger-Reich
f27102d344 Update download.tsx 2025-12-10 00:25:33 +01:00
Alexander-Ger-Reich
ba8e8b7a5c Merge pull request #5 from Alexander-Ger-Reich/patch-6
Update en.ts
2025-12-10 00:24:25 +01:00
Alexander-Ger-Reich
cb3834bb71 Update en.ts 2025-12-10 00:24:04 +01:00
Alexander-Ger-Reich
8ec134c182 Merge pull request #4 from Alexander-Ger-Reich/patch-4
Update de.ts
2025-12-10 00:22:42 +01:00
Alexander-Ger-Reich
631d944d70 Merge pull request #3 from Alexander-Ger-Reich/patch-1
Update download.tsx
2025-12-10 00:21:40 +01:00
Alexander-Ger-Reich
f539576a49 Merge branch 'main' into patch-1 2025-12-10 00:21:30 +01:00
Alexander-Ger-Reich
fa11347f1b Merge pull request #2 from Alexander-Ger-Reich/patch-2
Update download.tsx
2025-12-10 00:18:55 +01:00
Alexander-Ger-Reich
34c66dbd8b Merge pull request #1 from Alexander-Ger-Reich/patch-5
Update en.ts
2025-12-10 00:18:21 +01:00
Alexander-Ger-Reich
3d5c14405c Update en.ts 2025-12-10 00:10:29 +01:00
Alexander-Ger-Reich
9e4408409f Update de.ts 2025-12-10 00:10:04 +01:00
Alexander-Ger-Reich
9b629c8dc0 Update download.tsx 2025-12-09 23:49:34 +01:00
Alexander-Ger-Reich
8da7a70bfc Update download.tsx 2025-12-09 23:23:40 +01:00
Deses
ea6ac3c903 Updated Spanish translation with all missing strings (compared with English) and fixed lots of little gramatical errors. 2025-12-09 05:04:13 +01:00
Yury Pekishev
6b783677e5 Use Dropdown with languages at paste
Fix translation
2025-12-09 01:31:02 +03:00
Yury Pekishev
1cc31c30a3 revert invisible change 2025-12-09 00:56:52 +03:00
Yury Pekishev
92d5f63679 Merge branch 'main' into paste_rus
# Conflicts:
#	web/src/pages/desktop/menu/keyboard/paste.tsx
2025-12-09 00:50:09 +03:00
Yury Pekishev
9fd3728aee Merge branch 'main' of https://github.com/pekishev/NanoKVM
# Conflicts:
#	web/src/pages/desktop/menu/keyboard/paste.tsx
2025-12-09 00:46:28 +03:00
Yury Pekishev
916803d0f0 Merge branch 'main' into paste_rus 2025-12-08 23:56:46 +03:00
Guoguo
8de298d245 feat: add video scale
Patch from https://github.com/sipeed/NanoKVM-USB/pull/50
2025-12-08 19:17:35 +08:00
wenjie
75fc8d09ce Merge pull request #681 from scpcom/fix-virtual-media-split-merge
S03usbdev: fix virtual media split merge
2025-12-02 09:32:14 +08:00
scpcom
b157b9fe28 S03usbdev: fix virtual media split merge 2025-12-01 23:34:17 +01:00
wenjie
53a800d252 Merge pull request #530 from tpretz/usb-disable
Add setting for disabling the usb-gadget
2025-12-01 17:51:35 +08:00
wenjie
124868e093 Merge branch 'main' into usb-disable 2025-12-01 17:51:28 +08:00
Thomas Pressnell
e684936d15 server side for full gadget disable
starting on frontend

# Conflicts:
#	kvmapp/system/init.d/S03usbdev
2025-12-01 17:26:41 +08:00
wenjie
5958fd5c6f Merge pull request #489 from tpretz/virtual-media-split
Virtual Media Changes
2025-12-01 15:30:02 +08:00
wenjie
4d7ee39ccf Merge branch 'main' into virtual-media-split 2025-12-01 15:28:50 +08:00
Jonas Byström
1bb91518b6 Add missing variables from last version 2025-11-30 21:19:55 +01:00
wj-xiao
2d0123cb18 Update README 2025-11-28 19:02:08 +08:00
kmw_
455bc19fab fix typo in ummountDesc 2025-11-27 21:11:08 +09:00
wj-xiao
0003be478e Fix Tailscale startup script
- The device no longer automatically switches to router mode
- Resolved IPv6 connectivity issues
2025-11-27 10:13:22 +08:00
kmw0410
d448f11861 update korean translation 2025-11-26 21:53:26 +09:00
Guoguo
53924dc8ef feat: add autostart feature 2025-11-26 15:58:19 +08:00
Yury Pekishev
0d1dca3e0a translateRuToEnWithPunctuation 2025-10-30 14:40:59 +03:00
Low Tech
dda98e2a61 Merge branch 'sipeed:main' into main 2025-09-20 16:07:25 +08:00
lowtech-guy
e8016c1d51 remove: comment the cache server line 2025-08-26 05:58:34 +08:00
lowtech-guy
c1e2bed94e add: add build system design for human friendly 2025-08-26 03:40:51 +08:00
Thomas Pressnell
393328eaf6 Revert "cleanup and simplification" and adding reset flag
This reverts commit 7771d1f326.
2025-05-26 07:47:48 +01:00
Thomas Pressnell
7771d1f326 cleanup and simplification 2025-05-25 21:44:53 +01:00
Thomas Pressnell
2a34eb55e6 Update image.go
set imageNone to newline
2025-05-25 19:22:58 +01:00
Thomas Pressnell
9a0c77bb8b server side for full gadget disable
starting on frontend
2025-05-24 16:28:52 +01:00
Thomas Pressnell
a1df6376ec split /data attachment from kvm media attachment
backend config for media control

remove .disabled

adding settings toggle

add default text
2025-05-24 13:29:35 +01:00
394 changed files with 53106 additions and 7633 deletions

13
.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
Dockerfile
!server/go.mod
server/go.sum
server/NanoKVM-Server
web
support/sg2002/kvm_system/build
support/sg2002/kvm_system/dist
support/sg2002/kvm_system/CMakeLists.txt
support/sg2002/kvm_vision_test/build
support/sg2002/kvm_vision_test/dist
support/sg2002/kvm_vision_test/CMakeLists.txt

132
.github/workflows/builder-image.yml vendored Normal file
View File

@@ -0,0 +1,132 @@
name: Builder Image
# Builds the nanokvm-builder image (riscv64 musl toolchain, Go, and a MaixCDK
# checkout patched with support/sg2002/additional) and publishes it to GHCR so
# the release workflow does not have to rebuild the SDK on every tag.
#
# The image is deliberately not rebuilt on every push: it only carries the
# toolchain. Release builds re-sync support/sg2002/additional into MaixCDK and
# recompile from the checked-out source, so a slightly stale image is harmless.
on:
workflow_dispatch:
push:
branches:
- main
paths:
- docker/**
- .github/workflows/builder-image.yml
concurrency:
group: builder-image
cancel-in-progress: false
jobs:
build:
name: Build and publish nanokvm-builder
runs-on: ubuntu-latest
timeout-minutes: 240
permissions:
contents: read
packages: write
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Free up disk space
run: |
echo "Before:"
df -h /
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc \
/usr/local/share/boost /usr/local/share/powershell
sudo docker image prune -af
echo "After:"
df -h /
- name: Resolve image reference
id: image
env:
OWNER: ${{ github.repository_owner }}
run: |
# GHCR only accepts lowercase repository paths.
owner=$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')
echo "ref=ghcr.io/$owner/nanokvm-builder" >> "$GITHUB_OUTPUT"
# Logging in before the build means a credential or registry problem fails
# in seconds instead of after a full SDK build.
- name: Log in to GHCR
env:
GHCR_USER: ${{ github.actor }}
GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ok=0
for attempt in 1 2 3; do
if printf '%s' "$GHCR_TOKEN" \
| docker login ghcr.io -u "$GHCR_USER" --password-stdin; then
ok=1
break
fi
echo "login attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not log in to ghcr.io after 3 attempts"
exit 1
fi
- name: Build image
run: |
# The Dockerfile chowns MaixCDK to DOCKER_UID/DOCKER_GID and the
# entrypoint gosu's to the caller's ids, so bake in the ids the
# release job will actually run as. Otherwise the SDK tree belongs to
# 1000 and syncing components into it fails with permission denied.
docker build \
--build-arg DOCKER_UID="$(id -u)" \
--build-arg DOCKER_GID="$(id -g)" \
--tag "${{ steps.image.outputs.ref }}:latest" \
--tag "${{ steps.image.outputs.ref }}:${{ github.sha }}" \
--file docker/Dockerfile \
.
- name: Verify toolchain
run: |
docker run --rm -i "${{ steps.image.outputs.ref }}:latest" go version
docker run --rm -i "${{ steps.image.outputs.ref }}:latest" \
riscv64-unknown-linux-musl-gcc --version | head -1
docker run --rm -i "${{ steps.image.outputs.ref }}:latest" patchelf --version
- name: Push image
env:
IMAGE_REF: ${{ steps.image.outputs.ref }}
SHA: ${{ github.sha }}
run: |
# ghcr.io occasionally times out; a retry is cheaper than rebuilding.
# Push the immutable sha tag first so a failure there cannot leave
# :latest — which release.yml pulls — already moved.
for tag in "$SHA" latest; do
ok=0
for attempt in 1 2 3; do
if docker push "$IMAGE_REF:$tag"; then
ok=1
break
fi
echo "push of $tag attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not push $IMAGE_REF:$tag after 3 attempts"
exit 1
fi
done
- name: Summary
run: |
{
echo "### Builder image published"
echo
echo '```'
echo "${{ steps.image.outputs.ref }}:latest"
echo "${{ steps.image.outputs.ref }}:${{ github.sha }}"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"

108
.github/workflows/create-tag.yml vendored Normal file
View File

@@ -0,0 +1,108 @@
name: NanoKVM Create Tag
on:
workflow_dispatch:
inputs:
version:
description: Numeric version to tag, e.g. 2.5.0
required: true
type: string
commit_sha:
description: Full commit SHA on main (empty uses latest main)
required: false
default: ''
type: string
concurrency:
group: create-tag-${{ inputs.version }}
cancel-in-progress: false
jobs:
create-tag:
name: Create annotated tag
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout main
uses: actions/checkout@v4
with:
fetch-depth: 0
ref: main
- name: Validate target
id: target
env:
COMMIT_INPUT: ${{ inputs.commit_sha }}
VERSION_INPUT: ${{ inputs.version }}
run: |
VERSION="$VERSION_INPUT"
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "::error::invalid version '$VERSION', expected MAJOR.MINOR.PATCH"
exit 1
fi
git fetch --force --tags origin main
if [ -n "$COMMIT_INPUT" ]; then
if ! echo "$COMMIT_INPUT" | grep -qE '^[0-9a-fA-F]{40}$'; then
echo "::error::commit_sha must be a full 40-character hexadecimal SHA"
exit 1
fi
TARGET_SHA=$(git rev-parse "${COMMIT_INPUT}^{commit}" 2>/dev/null) || {
echo "::error::commit '$COMMIT_INPUT' does not exist"
exit 1
}
else
TARGET_SHA=$(git rev-parse 'origin/main^{commit}')
fi
if ! git merge-base --is-ancestor "$TARGET_SHA" origin/main; then
echo "::error::commit '$TARGET_SHA' is not reachable from origin/main"
exit 1
fi
set +e
git ls-remote --exit-code --tags origin "refs/tags/$VERSION" >/dev/null
TAG_STATUS=$?
set -e
case "$TAG_STATUS" in
0)
echo "::error::tag '$VERSION' already exists"
exit 1
;;
2) ;;
*)
echo "::error::failed to check whether tag '$VERSION' exists"
exit 1
;;
esac
echo "sha=$TARGET_SHA" >> "$GITHUB_OUTPUT"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Create and push tag
env:
TARGET_SHA: ${{ steps.target.outputs.sha }}
VERSION: ${{ steps.target.outputs.version }}
run: |
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git tag -a "$VERSION" "$TARGET_SHA" -m "Release $VERSION"
git push origin "refs/tags/$VERSION"
./scripts/verify-release-tag.sh "$VERSION" "$TARGET_SHA" >/dev/null
- name: Summary
env:
TARGET_SHA: ${{ steps.target.outputs.sha }}
VERSION: ${{ steps.target.outputs.version }}
run: |
{
echo '### NanoKVM tag created'
echo
echo "- Tag: \`$VERSION\`"
echo "- Commit: \`$TARGET_SHA\`"
echo
echo 'No package, GitHub Release, or CDN object was created.'
} >> "$GITHUB_STEP_SUMMARY"

68
.github/workflows/issue-tracker.yml vendored Normal file
View File

@@ -0,0 +1,68 @@
name: Issue Tracker
on:
issues:
types: [opened, reopened, closed]
jobs:
track-issue:
name: Track Issue Updates
runs-on: ubuntu-latest
steps:
- name: Send Issue Data to API
env:
RAW_TITLE: ${{ github.event.issue.title }}
RAW_BODY: ${{ github.event.issue.body }}
RAW_LABELS: ${{ toJSON(github.event.issue.labels) }}
RAW_ASSIGNEES: ${{ toJSON(github.event.issue.assignees) }}
API_URL: ${{ secrets.ISSUE_TRACKER_API_URL }}
VERIFY_TOKEN: ${{ secrets.VERIFY_TOKEN }}
run: |
ISSUE_DATA=$(jq -n \
--arg action "${{ github.event.action }}" \
--arg id "${{ github.event.issue.id }}" \
--arg num "${{ github.event.issue.number }}" \
--arg title "$RAW_TITLE" \
--arg body "$RAW_BODY" \
--arg state "${{ github.event.issue.state }}" \
--arg created_at "${{ github.event.issue.created_at }}" \
--arg updated_at "${{ github.event.issue.updated_at }}" \
--arg closed_at "${{ github.event.issue.closed_at }}" \
--arg url "${{ github.event.issue.html_url }}" \
--arg user_login "${{ github.event.issue.user.login }}" \
--arg repository "${{ github.repository }}" \
--argjson labels "$RAW_LABELS" \
--argjson assignees "$RAW_ASSIGNEES" \
'{
action: $action,
issue: {
id: ($id | tonumber),
number: ($num | tonumber),
title: $title,
body: $body,
state: $state,
created_at: $created_at,
updated_at: $updated_at,
closed_at: $closed_at,
url: $url,
user: { login: $user_login },
labels: $labels,
assignees: $assignees
},
repository: { name: $repository },
}')
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL" \
-H "Content-Type: application/json" \
-H "Token: $VERIFY_TOKEN" \
-d "$ISSUE_DATA")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
echo "Successfully sent issue data to API"
else
echo "Failed to send issue data to API"
exit 1
fi

291
.github/workflows/package.yml vendored Normal file
View File

@@ -0,0 +1,291 @@
name: NanoKVM Package
# Builds nanokvm_<version>.tar.gz and the latest.json manifest that the
# on-device updater consumes (server/service/application/). Pull requests get a
# uniquely identified, short-lived test artifact. Release publication is a
# separate, explicit workflow that calls this one for an existing tag.
#
# This workflow does NOT publish to cdn.sipeed.com. Uploading latest.json is what
# actually offers the update to every device in the field, so that step stays
# manual and deliberate.
on:
pull_request:
branches:
- main
paths:
- .github/workflows/create-tag.yml
- .github/workflows/package.yml
- .github/workflows/release.yml
- kvmapp/**
- scripts/**
- server/**
- support/**
- tools/nanokvm_update_edid/**
- web/**
- Makefile
workflow_dispatch:
inputs:
version:
description: Version to package, e.g. 2.4.4
required: true
type: string
workflow_call:
inputs:
version:
description: Numeric version to package
required: true
type: string
ref:
description: Existing tag or commit to check out
required: true
type: string
outputs:
artifact_name:
description: Uploaded Actions artifact name
value: ${{ jobs.package.outputs.artifact_name }}
version:
description: Packaged version
value: ${{ jobs.package.outputs.version }}
concurrency:
group: package-${{ github.event.pull_request.number || inputs.ref || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
package:
name: Build package
runs-on: ubuntu-latest
timeout-minutes: 180
outputs:
artifact_name: ${{ steps.version.outputs.artifact_name }}
version: ${{ steps.version.outputs.version }}
permissions:
contents: read
packages: read
steps:
- name: Checkout event ref
if: inputs.ref == ''
uses: actions/checkout@v4
with:
# package.sh derives SOURCE_DATE_EPOCH from the commit date.
fetch-depth: 0
# Build scripts from a pull request must not inherit checkout's token.
persist-credentials: false
- name: Checkout requested ref
if: inputs.ref != ''
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
ref: ${{ inputs.ref }}
- name: Resolve version
id: version
env:
EVENT_NAME: ${{ github.event_name }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
INPUT_VERSION: ${{ inputs.version }}
PR_NUMBER: ${{ github.event.pull_request.number }}
REF_NAME: ${{ github.ref_name }}
run: |
BUILD_SHA=$(git rev-parse HEAD)
if [ "$EVENT_NAME" = "pull_request" ]; then
VERSION="0.${PR_NUMBER}.${GITHUB_RUN_NUMBER}"
SOURCE_SHA="$HEAD_SHA"
elif [ -n "$INPUT_VERSION" ]; then
VERSION="$INPUT_VERSION"
SOURCE_SHA="$BUILD_SHA"
else
VERSION="$REF_NAME"
SOURCE_SHA="$BUILD_SHA"
fi
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "::error::invalid version '$VERSION', expected MAJOR.MINOR.PATCH"
exit 1
fi
if [ -z "$SOURCE_SHA" ]; then
echo "::error::could not resolve source commit"
exit 1
fi
SHORT_SHA=$(printf '%s' "$SOURCE_SHA" | cut -c1-12)
if [ "$EVENT_NAME" = "pull_request" ]; then
ARTIFACT_NAME="nanokvm-pr-${PR_NUMBER}-${SHORT_SHA}-run-${GITHUB_RUN_ID}-attempt-${GITHUB_RUN_ATTEMPT}"
else
ARTIFACT_NAME="nanokvm-${VERSION}-${SHORT_SHA}-run-${GITHUB_RUN_ID}-attempt-${GITHUB_RUN_ATTEMPT}"
fi
{
echo "artifact_name=$ARTIFACT_NAME"
echo "build_sha=$BUILD_SHA"
echo "source_sha=$SOURCE_SHA"
echo "version=$VERSION"
} >> "$GITHUB_OUTPUT"
echo "Packaging version $VERSION as $ARTIFACT_NAME"
- name: Free up disk space
run: |
df -h /
sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc
df -h /
- name: Set up Node
uses: actions/setup-node@v4
with:
node-version: '22'
- name: Set up pnpm
run: npm install --global pnpm@11
- name: Build frontend
run: make web
- name: Log in to GHCR
if: github.event_name != 'pull_request'
env:
GHCR_USER: ${{ github.actor }}
GHCR_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
ok=0
for attempt in 1 2 3; do
if printf '%s' "$GHCR_TOKEN" \
| docker login ghcr.io -u "$GHCR_USER" --password-stdin; then
ok=1
break
fi
echo "login attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not log in to ghcr.io after 3 attempts"
exit 1
fi
- name: Pull builder image
id: image
env:
OWNER: ${{ github.repository_owner }}
run: |
# GHCR only accepts lowercase repository paths.
# shellcheck disable=SC2153 # OWNER is supplied through the step environment.
owner=$(echo "$OWNER" | tr '[:upper:]' '[:lower:]')
IMAGE_REPO="ghcr.io/$owner/nanokvm-builder"
TAGGED_REF="${IMAGE_REPO}:latest"
ok=0
for attempt in 1 2 3; do
if docker pull "$TAGGED_REF"; then
ok=1
break
fi
echo "pull attempt $attempt failed, retrying in 15s"
sleep 15
done
if [ "$ok" -ne 1 ]; then
echo "::error::could not pull $TAGGED_REF - run the 'Builder Image' workflow first and ensure PR builds can pull it without credentials"
exit 1
fi
RESOLVED_REF=$(docker image inspect --format='{{index .RepoDigests 0}}' "$TAGGED_REF")
case "$RESOLVED_REF" in
"$IMAGE_REPO"@sha256:*) ;;
*)
echo "::error::could not resolve immutable digest for $TAGGED_REF (got '$RESOLVED_REF')"
exit 1
;;
esac
echo "Pulled $RESOLVED_REF"
echo "ref=$RESOLVED_REF" >> "$GITHUB_OUTPUT"
- name: Build riscv64 artifacts
run: |
make release-build \
DOCKER_TTY= \
IMAGE_NAME="${{ steps.image.outputs.ref }}"
- name: Assemble package
run: make package VERSION="${{ steps.version.outputs.version }}"
- name: Compare against the published release
# Informational only: highlights what changed relative to what devices
# are currently running. Never blocks the build.
continue-on-error: true
run: |
./scripts/compare-release.sh \
"build/release/nanokvm_${{ steps.version.outputs.version }}.tar.gz"
- name: Write build provenance
env:
ARTIFACT_NAME: ${{ steps.version.outputs.artifact_name }}
BUILDER_IMAGE: ${{ steps.image.outputs.ref }}
BUILD_SHA: ${{ steps.version.outputs.build_sha }}
PR_NUMBER: ${{ github.event.pull_request.number }}
SOURCE_SHA: ${{ steps.version.outputs.source_sha }}
VERSION: ${{ steps.version.outputs.version }}
run: |
TARBALL="build/release/nanokvm_${VERSION}.tar.gz"
TARBALL_NAME=$(basename "$TARBALL")
SHA256_HEX=$(sha256sum "$TARBALL" | cut -d' ' -f1)
SHA512_HEX=$(sha512sum "$TARBALL" | cut -d' ' -f1)
SHA512_BASE64=$(jq -er '.sha512 | select(type == "string" and length > 0)' \
build/release/latest.json)
ACTUAL_BASE64=$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)
if [ "$SHA512_BASE64" != "$ACTUAL_BASE64" ]; then
echo "::error::latest.json sha512 does not match $TARBALL"
exit 1
fi
printf '%s %s\n' "$SHA256_HEX" "$TARBALL_NAME" > build/release/sha256.txt
{
echo "artifact=${ARTIFACT_NAME}"
echo "version=${VERSION}"
echo "event=${GITHUB_EVENT_NAME}"
echo "pull_request=${PR_NUMBER}"
echo "source_sha=${SOURCE_SHA}"
echo "build_sha=${BUILD_SHA}"
echo "builder_image=${BUILDER_IMAGE}"
echo "run_id=${GITHUB_RUN_ID}"
echo "run_attempt=${GITHUB_RUN_ATTEMPT}"
echo "run_url=https://github.com/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
echo "tarball=${TARBALL_NAME}"
echo "sha256_hex=${SHA256_HEX}"
echo "sha512_hex=${SHA512_HEX}"
echo "sha512_base64=${SHA512_BASE64}"
} > build/release/BUILD_INFO.txt
- name: Summary
env:
VERSION: ${{ steps.version.outputs.version }}
run: |
{
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
echo "> [!WARNING]"
echo "> PR TEST ONLY — DO NOT PUBLISH TO CDN"
echo
fi
echo "### nanokvm_${VERSION}.tar.gz"
echo
echo '```text'
cat build/release/BUILD_INFO.txt
echo '```'
echo
echo '```json'
cat build/release/latest.json
echo '```'
echo
if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
echo "Upload only the inner tarball through NanoKVM's manual offline update UI."
else
echo "Publishing to \`cdn.sipeed.com/nanokvm/\` is a separate manual step."
fi
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload artifacts
uses: actions/upload-artifact@v4
with:
name: ${{ steps.version.outputs.artifact_name }}
path: |
build/release/nanokvm_${{ steps.version.outputs.version }}.tar.gz
build/release/latest.json
build/release/sha256.txt
build/release/BUILD_INFO.txt
if-no-files-found: error
retention-days: ${{ github.event_name == 'pull_request' && 7 || 90 }}

244
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,244 @@
name: NanoKVM Release
on:
workflow_dispatch:
inputs:
tag:
description: Existing numeric tag to release, e.g. 2.5.0
required: true
type: string
release_action:
description: Publish a release or promote a tested prerelease
required: true
type: choice
options:
- publish-prerelease
- publish-stable
- promote-stable
# Latest is repository-global, so all Release changes must be serialized.
concurrency:
group: nanokvm-github-release
cancel-in-progress: false
jobs:
validate:
name: Resolve release tag
runs-on: ubuntu-latest
permissions:
contents: read
outputs:
source_sha: ${{ steps.tag.outputs.source_sha }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Verify tag
id: tag
env:
TAG: ${{ inputs.tag }}
run: |
SOURCE_SHA=$(./scripts/verify-release-tag.sh "$TAG")
echo "source_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT"
package:
name: Build tag package
needs: validate
if: inputs.release_action != 'promote-stable'
permissions:
contents: read
packages: read
uses: ./.github/workflows/package.yml
with:
ref: ${{ needs.validate.outputs.source_sha }}
version: ${{ inputs.tag }}
publish:
name: Publish GitHub release
needs:
- validate
- package
if: inputs.release_action != 'promote-stable'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout release tooling
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Download package artifact
uses: actions/download-artifact@v4
with:
name: ${{ needs.package.outputs.artifact_name }}
path: build/release
- name: Publish release
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_ACTION: ${{ inputs.release_action }}
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
./scripts/verify-release-assets.sh build/release "$TAG"
case "$RELEASE_ACTION" in
publish-prerelease) IS_PRERELEASE=true ;;
publish-stable) IS_PRERELEASE=false ;;
*)
echo "::error::invalid publish action '$RELEASE_ACTION'"
exit 1
;;
esac
ENDPOINT="repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}"
set +e
HEADERS=$(gh api --include --silent "$ENDPOINT" 2>&1)
API_STATUS=$?
set -e
HTTP_STATUS=$(printf '%s\n' "$HEADERS" | awk '
$1 ~ /^HTTP\// { status = $2 }
END { print status }
')
if [ "$API_STATUS" -eq 0 ] && [ "$HTTP_STATUS" = 200 ]; then
echo "::error::release or draft '$TAG' already exists"
echo "Publishing is one-shot. Inspect it at https://github.com/${GITHUB_REPOSITORY}/releases."
exit 1
fi
if [ "$API_STATUS" -eq 0 ] || [ "$HTTP_STATUS" != 404 ]; then
echo "::error::failed to query release '$TAG' (HTTP status: ${HTTP_STATUS:-unknown})"
printf '%s\n' "$HEADERS" >&2
exit 1
fi
TARBALL="build/release/nanokvm_${TAG}.tar.gz"
SHA256=$(sha256sum "$TARBALL" | cut -d' ' -f1)
SHA512=$(jq -er '.sha512' build/release/latest.json)
# Backticks below are intentional Markdown, not command substitution.
# shellcheck disable=SC2016
NOTES=$(printf '%s\n' \
"Application package for NanoKVM ${TAG}." \
'' \
'### Checksums' \
'' \
'`SHA-256` (hex):' \
'' \
" ${SHA256}" \
'' \
'`SHA-512` (base64, as expected by the on-device updater):' \
'' \
" ${SHA512}" \
'' \
'To offer this build over OTA, publish it through the separate CDN workflow.')
STATE_ARGS=(--prerelease="$IS_PRERELEASE")
if [ "$IS_PRERELEASE" = true ]; then
STATE_ARGS+=(--latest=false)
fi
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
gh release create "$TAG" \
--verify-tag \
--title "$TAG" \
--notes "$NOTES" \
"${STATE_ARGS[@]}" \
"$TARBALL" build/release/latest.json build/release/sha256.txt
- name: Summary
env:
RELEASE_ACTION: ${{ inputs.release_action }}
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
{
echo '### NanoKVM GitHub Release published'
echo
echo "- Tag: \`$TAG\`"
echo "- Commit: \`$SOURCE_SHA\`"
echo "- Action: \`$RELEASE_ACTION\`"
echo
echo 'No CDN object was uploaded.'
} >> "$GITHUB_STEP_SUMMARY"
promote:
name: Promote verified prerelease
needs: validate
if: inputs.release_action == 'promote-stable'
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout release tooling
uses: actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Verify and promote release
env:
GH_REPO: ${{ github.repository }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
RELEASE_JSON=$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}")
if [ "$(jq -r '.draft' <<< "$RELEASE_JSON")" != false ]; then
echo "::error::release '$TAG' is a draft"
exit 1
fi
if [ "$(jq -r '.prerelease' <<< "$RELEASE_JSON")" != true ]; then
echo "::error::release '$TAG' is not a prerelease"
exit 1
fi
CURRENT_ASSETS=$(jq -r '.assets[].name' <<< "$RELEASE_JSON" | LC_ALL=C sort)
EXPECTED_ASSETS=$(printf '%s\n' \
latest.json "nanokvm_${TAG}.tar.gz" sha256.txt | LC_ALL=C sort)
if [ "$CURRENT_ASSETS" != "$EXPECTED_ASSETS" ]; then
echo "::error::release '$TAG' does not have the exact expected asset set"
exit 1
fi
mkdir -p build/release
gh release download "$TAG" --dir build/release \
--pattern "nanokvm_${TAG}.tar.gz" \
--pattern latest.json \
--pattern sha256.txt
./scripts/verify-release-assets.sh build/release "$TAG"
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
gh release edit "$TAG" --prerelease=false --latest
./scripts/verify-release-tag.sh "$TAG" "$SOURCE_SHA" >/dev/null
if [ "$(gh api "repos/${GITHUB_REPOSITORY}/releases/tags/${TAG}" --jq '.prerelease')" != false ]; then
echo "::error::release '$TAG' was not promoted"
exit 1
fi
if [ "$(gh api "repos/${GITHUB_REPOSITORY}/releases/latest" --jq '.tag_name')" != "$TAG" ]; then
echo "::error::release '$TAG' was not marked latest"
exit 1
fi
- name: Summary
env:
SOURCE_SHA: ${{ needs.validate.outputs.source_sha }}
TAG: ${{ inputs.tag }}
run: |
{
echo '### NanoKVM prerelease promoted'
echo
echo "- Tag: \`$TAG\`"
echo "- Commit: \`$SOURCE_SHA\`"
echo '- Assets: unchanged and checksum-verified'
echo
echo 'No package was rebuilt and no CDN object was uploaded.'
} >> "$GITHUB_STEP_SUMMARY"

3
.gitignore vendored
View File

@@ -29,3 +29,6 @@ support/sg2002/kvm_vision_test/CMakeLists.txt
support/sg2002/additional/original
kvmapp/server/dl_lib
kvmapp/kvm_system/kvm_system
# Release packages assembled by scripts/package.sh
/build/

View File

@@ -1,3 +1,198 @@
## 2.4.3 (2026-06-09)
### Features
* Added LT6911D support
### Bug Fixes
* Improved USB network adapter compatibility on Windows
## 2.4.2 (2026-05-20)
### Features
* Added HDMI capture status detection with localized warning and error overlays on the desktop screen
### Bug Fixes
* Fixed left-button touch cancellation and context menu cleanup for mouse input
* Improved the WebRTC loading indicator
* Added Wi-Fi password field validation
* Hardened Wake-on-LAN MAC handling by normalizing stored addresses, avoiding shell execution, handling missing history gracefully, and improving named MAC display
* Stabilized PicoClaw session switching by waiting for gateway release, refreshing runtime status before reconnecting, rendering structured thought messages, and preventing history row overflow
### Performance
* Improved H.264 streaming client handling by reducing frame queue latency, using client snapshots for fanout, applying backend ICE server configuration, and cleaning up disconnected WebRTC clients more aggressively
### UI Improvements
* Refreshed desktop menu ordering and community links, including replacing the Discussion link with Discord
### Chores
* Removed the legacy H.264 stream package
* Updated PostCSS, refreshed the MSW worker, and added pnpm workspace build approvals
## 2.4.1 (2026-05-08)
### Features
* Added DNS management to Network settings, including DHCP/manual modes, effective DNS display, network details, IPv4/IPv6 server validation, and persistent udhcpc hook support
* Added a configurable server `host` option for binding NanoKVM to a specific listen address (thanks to [@allmazz](https://github.com/allmazz))
* Added French keyboard layout support and language options (thanks to [@ilyesAj](https://github.com/ilyesAj))
### Bug Fixes
* Hardened HID recovery and cleanup by adding non-blocking HID writes, bounded reopen retries, stale event draining, and release reports after write failures
* Fixed the `kvm_vision` project name and build output message in the SG2002 build script (thanks to [@Voranto](https://github.com/Voranto))
### UI Improvements
* Moved TLS and Wi-Fi settings into the Network settings section
* Optimized the Settings scrollbar style
### Localization
* Updated Korean translations (thanks to [@kmw0410](https://github.com/kmw0410))
* Synchronized translations of other languages according to English
### Security
* Upgraded vulnerable web dependencies
## 2.4.0 (2026-04-10)
### Features
* **Introduced [PicoClaw](https://github.com/sipeed/picoclaw) support** — an AI-powered remote desktop assistant for NanoKVM. PicoClaw seamlessly integrates a lightweight AI agent with NanoKVM's underlying hardware capabilities. Key highlights include:
* **Zero-Agent Architecture:** Operates entirely through HDMI video capture (vision) and USB HID emulation (keyboard/mouse). No SSH access, network connection to the host, or OS-level software installation is required.
* **Natural Language Control:** Features a built-in chat interface allowing users to issue complex instructions in plain text.
* **Autonomous GUI Operation:** The AI agent can autonomously observe the remote host's screen, understand UI elements, reason about the task, and execute operations mimicking human behavior.
* **Installation Note:** PicoClaw is not built into the NanoKVM device or firmware. Install it separately when needed.
### Bug Fixes
* Added a default subnet mask for static IP configurations
* Fixed an issue where the IP address would occasionally not display
## 2.3.6 (2026-03-12)
### Features
* Implemented AP password authentication for the WiFi configuration page
* Added Korean and Japanese virtual keyboard layouts (thanks to [@klim4-bot](https://github.com/klim4-bot))
* Enabled support for 640x480 resolution (thanks to [@Voranto](https://github.com/Voranto))
* Added encryption parameters for OLED distribution network
* Added custom logo function and logo generation tools
* Added update mechanism for tailscale startup script
### Localization
* Updated Japanese translation (thanks to [@tkmsst](https://github.com/tkmsst))
## 2.3.5 (2026-02-28)
### Features
* Implemented login brute-force protection with lockout mechanism
### Bug Fixes
* Improved Tailscale error handling in UI components and refined backend state mapping
### Chores
* Updated server and web dependencies
## 2.3.4 (2026-01-26)
### Features
* Introduced `Leader Key` functionality to bypass local browser shortcut interception
### Bug Fixes
* Fixed an issue where the Right Shift key was not being recognized on Windows system
* Fixed a bug where the menu bar would fail to close correctly
### Localization
* Updated Traditional Chinese translations (thanks to [@j796160836](https://github.com/j796160836))
* Updated Korean translations (thanks to [@kmw0410](https://github.com/kmw0410))
## 2.3.3 (2026-01-16)
### Features
* Added support for setting the display mode of the menu bar
### Bug Fixes
* Fixed a keyboard issue where IME composition events were not handled correctly
* Resolved an issue where the `AltGr` key was not recognized on the Windows system
* Fixed a bug where `Command` key combinations were not fully released on the macOS system
* Fixed input issues with the `IntlBackslash` key on the German virtual keyboard
### Localization
* Updated Korean translations (thanks to [@kmw0410](https://github.com/kmw0410))
### Chores
* Bump react-router-dom from 6.27.0 to 6.30.3
* Updated eslint
## 2.3.2 (2026-01-08)
### Features
* Added support for custom keyboard shortcuts
* Added support for mouse Forward and Back buttons (reboot required)
* Added support for touchscreen mouse operation
* The menu bar now supports auto-hide and drag
### Bug Fixes
* Fixed an issue where the previous IP address was not released after configuring a static IP
### Performance
* Refactored the keyboard to support simultaneous keystrokes and a wider range of international layouts (reboot required)
* Refactored the mouse to improve response latency
* Refactored the WebSocket module to transmit keyboard and mouse data using the standard HID format
## 2.3.1 (2025-12-26)
### Features
* Added support for offline application updates (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Implemented support for uploading ISO images (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
* Extended clipboard compatibility to support Russian characters (thanks to [@pekishev](https://github.com/pekishev))
* Added configuration options for video scaling
* Added support for configuring mouse scroll wheel direction
### Bug Fixes
* Resolved an issue where custom port may not be accessible
* Fixed a bug where Web Terminal and Serial Terminal may not disconnect when the page is closed
### Security
* Enhanced validation logic on the Wi-Fi configuration page. Requests are now rejected when the device is not in AP mode to prevent unauthorized changes
### Chore
* Added a Docker image environment to support building `libkvm.so` and `NanoKVM-Server` (thanks to [@lowtech-guy](https://github.com/lowtech-guy))
* Optimized the Settings UI
### Localization
* Updated Korean translation (thanks to [@kmw0410](https://github.com/kmw0410))
* Updated Swedish translation (thanks to [@acidflash](https://github.com/acidflash))
* Updated Spanish translation (thanks to [@Deses](https://github.com/Deses))
## 2.3.0 [0e30a26](https://github.com/sipeed/NanoKVM/commit/0e30a26db42cbc08416662b49a88a5d16ad93424) (2025-11-26)
### Features

152
Makefile Normal file
View File

@@ -0,0 +1,152 @@
# Makefile for NanoKVM Project
# Configuration
UID := $(shell id -u)
GID := $(shell id -g)
# ?= so a prebuilt image can be used instead, e.g. a GHCR-cached builder in CI.
IMAGE_NAME ?= nanokvm-builder-local-$(UID)-$(GID)
PWD := $(shell pwd)
VERSION ?=
# Docker run common parameters. Allocating a TTY breaks in environments without
# one, so it can be overridden with DOCKER_TTY=
DOCKER_TTY ?= -it
DOCKER_RUN_BASE := docker run -e UID=$(UID) -e GID=$(GID) -v $(PWD):/home/build/NanoKVM --rm
# Build the image with the host user's identity so entrypoint does not need
# to recursively rewrite the MaixCDK home directory at container startup.
DOCKER_BUILD_ARGS := --build-arg DOCKER_UID=$(UID) --build-arg DOCKER_GID=$(GID)
# Build commands
GO_BUILD_CMD := cd /home/build/NanoKVM/server && go mod tidy && CGO_ENABLED=1 GOOS=linux GOARCH=riscv64 CC=riscv64-unknown-linux-musl-gcc CGO_CFLAGS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d" go build
SUPPORT_BUILD_CMD := . ./home/build/MaixCDK/bin/activate && cd /home/build/NanoKVM/support/sg2002 && ./build kvm_system && ./build kvm_system add_to_kvmapp
VISION_BUILD_CMD := . ./home/build/MaixCDK/bin/activate && cd /home/build/NanoKVM/support/sg2002 && ./build kvm_vision && ./build kvm_vision add_to_kvmapp
RELEASE_BUILD_CMD := /home/build/NanoKVM/scripts/build-in-container.sh
.PHONY: help check-root builder-image rebuild-image check-image shell app support vision \
web release-build package release all clean
# Default target
all: app support
# Help target
help:
@echo "NanoKVM Build System"
@echo ""
@echo "Available targets:"
@echo " help - Show this help message"
@echo " check-image - Check builder Docker image and show versions"
@echo " builder-image - Build Docker image if not exists"
@echo " rebuild-image - Force rebuild Docker image"
@echo " shell - Enter interactive builder environment"
@echo " app - Build Go application server"
@echo " support - Build kvm_system daemon"
@echo " vision - Build video libraries (libkvm.so)"
@echo " web - Build the frontend into web/dist"
@echo " all - Build both app and support (default)"
@echo " release-build - Build every riscv64 release artifact in one pass"
@echo " package - Assemble nanokvm_<VERSION>.tar.gz + latest.json"
@echo " release - release-build + web + package (needs VERSION=x.y.z)"
@echo " clean - Clean build artifacts"
@echo ""
@echo "Prerequisites:"
@echo " - Docker must be installed and running"
@echo " - Must not run as root user"
# Security check - prevent running as root
check-root:
@if [ "$$(id -u)" -eq 0 ]; then \
echo "Can't run as root"; \
exit 1; \
fi
# Check if builder image exists and show versions
check-image: check-root
@echo "Checking builder image..."
@echo "Golang version: " && \
docker run --rm -i $(IMAGE_NAME) go version && \
echo "" && \
echo "Host-tools version:" && \
docker run --rm -i $(IMAGE_NAME) riscv64-unknown-linux-musl-gcc -v && \
echo ""
# Build Docker image if it doesn't exist
builder-image: check-root
@if ! docker image inspect $(IMAGE_NAME) >/dev/null 2>&1; then \
echo "Building Docker image..."; \
docker build $(DOCKER_BUILD_ARGS) -t $(IMAGE_NAME) -f docker/Dockerfile ./; \
else \
echo "Docker image $(IMAGE_NAME) already exists."; \
fi
# Force rebuild Docker image
rebuild-image: check-root
@echo "Force rebuilding Docker image..."
@docker build --no-cache $(DOCKER_BUILD_ARGS) -t $(IMAGE_NAME) -f docker/Dockerfile ./
# Enter interactive shell (equivalent to build.sh with no arguments)
shell: check-root builder-image
@echo "Switching into builder..."
@$(DOCKER_RUN_BASE) -it $(IMAGE_NAME) /bin/bash -c ". ./home/build/MaixCDK/bin/activate && cd /home/build/NanoKVM ; exec bash"
# Build Go application
app: check-root builder-image
@echo "Building app..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(GO_BUILD_CMD)'
# Build hardware support libraries
support: check-root builder-image
@echo "Building support..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(SUPPORT_BUILD_CMD)'
# Build video libraries (libkvm.so) into kvmapp/server/dl_lib
vision: check-root builder-image
@echo "Building vision..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(VISION_BUILD_CMD)'
# Build every riscv64 release artifact in one container pass
release-build: check-root builder-image
@echo "Building release artifacts..."
@$(DOCKER_RUN_BASE) $(DOCKER_TTY) $(IMAGE_NAME) /bin/bash -c '$(RELEASE_BUILD_CMD)'
# Build the frontend (runs on the host; the builder image has no Node)
web:
@echo "Building web..."
@cd web && pnpm install --frozen-lockfile && pnpm build
# Assemble the release package and its manifest
package:
@if [ -z "$(VERSION)" ]; then \
echo "VERSION is required, e.g. make package VERSION=2.4.4"; \
exit 1; \
fi
@scripts/package.sh "$(VERSION)"
# Full local release: riscv64 artifacts + frontend + package.
# Invoked as sub-makes rather than prerequisites: packaging asserts on what the
# earlier steps produce, so the order matters even under make -j.
release:
@$(MAKE) release-build
@$(MAKE) web
@$(MAKE) package VERSION="$(VERSION)"
# Clean build artifacts
clean:
@echo "Cleaning build artifacts..."
@if [ -f server/NanoKVM-Server ]; then \
rm -f server/NanoKVM-Server; \
echo "Removed server/NanoKVM-Server"; \
fi
@if [ -d support/sg2002/build ]; then \
rm -rf support/sg2002/build; \
echo "Removed support/sg2002/build"; \
fi
@if [ -d build/release ]; then \
rm -rf build/release; \
echo "Removed build/release"; \
fi
@if [ -d web/dist ]; then \
rm -rf web/dist; \
echo "Removed web/dist"; \
fi
@echo "Clean completed."

149
README.md
View File

@@ -1,117 +1,124 @@
NanoKVM
======
# NanoKVM
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<br>
<img src="https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png" alt="NanoKVM" style="margin: 20px 0;">
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 Quick Start</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ Hardware Details</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 Firmware Releases</a>
</h3>
English | [中文](./README_ZH.md) | [日本語](./README_JA.md) | [한국어](./README_KO.md)
</h3>
<br>
</div>
## 🌟 What is NanoKVM?
NanoKVM is a series of compact, open-source IP-KVM devices. Built upon the LicheeRV Nano (RISC-V), NanoKVM allows you to remotely access and control computers as if you were sitting right in front of them – perfect for managing servers, embedded systems, or any headless machine.
NanoKVM is a series of compact, open-source IP-KVM devices based on the LicheeRV Nano (RISC-V). It lets you remotely access and control computers as if you were sitting in front of them, making it useful for servers, embedded systems, and other headless machines.
## 📦 Product Family
We offer several NanoKVM versions to suit your needs:
Choose the NanoKVM model that best fits your deployment:
* **NanoKVM-Cube Lite:** A barebones kit for DIY enthusiasts and enterprise users needing bulk deployment.
* **NanoKVM-Cube Full:** A complete package with a sleek case, accessories, and a pre-flashed system SD card. Ready to use out-of-the-box, ideal for individual users.
* **NanoKVM-PCIe:** A unique form factor with a PCIe bracket for internal chassis mounting, drawing power directly from a PCIe slot. And add optional WiFi and PoE functions.
### 🚀 NanoKVM-Pro: The 4K Powerhouse
Based on popular demand, we've upgraded NanoKVM to the **NanoKVM-Pro**:
* **Resolution Upgrade:** From 1080P to stunning **4K@30fps / 2K@60fps**.
* **Network Upgrade:** Blazing fast **GbE + PoE + WiFi 6** (up from 100M Ethernet).
* **Latency Upgrade:** Encoder accelerated latency reduced from 100-150ms to **50-100ms**.
> The NanoKVM-Pro is now available for pre-sale! [Click here for product details](https://sipeed.com/nanokvm/pro).
- **NanoKVM-Cube Lite:** A barebones kit for DIY users and bulk deployments.
- **NanoKVM-Cube Full:** A ready-to-use kit with a case, accessories, and a pre-flashed system SD card.
- **NanoKVM-PCIe:** A PCIe-bracket form factor for internal chassis mounting. It draws power from the PCIe slot and supports optional Wi-Fi and PoE.
- **[NanoKVM-Pro](https://github.com/sipeed/NanoKVM-Pro):** A higher-performance version with major upgrades:
- **Resolution:** Up to **4K@30fps / 2K@60fps**.
- **Network:** **1Gbps Ethernet + PoE + Wi-Fi 6**, upgraded from 100Mbps Ethernet.
- **Latency:** Hardware-accelerated encoding reduces latency from 100-150ms to **50-100ms**.
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
<img src="https://cdn.sipeed.com/public/nanokvm-products-v2.jpg" alt="NanoKVM Product Family" width="100%" style="margin: 20px 0;">
</div>
> If you are looking for a USB-based KVM solution, check out [NanoKVM-USB](https://github.com/sipeed/NanoKVM-USB).
## 🛠️ Technical Specifications
| Product | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| Core | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| Memory & Storage | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| Feature | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
| ------------------ | ------------------------------------- | --------------------------------- | ---------------------------------- | ----------------------------------- |
| Core | AX630C 2xA53 1.2G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| Memory & Storage | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMC | 256M DDR3 + 16G eMMC |
| System | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| Resolution | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI Loopout | 4K loopout | x | x | x |
| Video Encoding | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| Audio Transmit | ✓ | x | ✓ | x |
| HDMI Loopout | 4K loopout | — | — | — |
| Video Encoding | MJPEG / H.264 / H.265 | MJPEG / H.264 | MJPEG / H.264 | MJPEG / H.264 |
| Audio Transmit | ✓ | — | ✓ | — |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| Emulated USB Keyboard & Mouse | ✓ | ✓ | ✓ | ✓ |
| Emulated USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| IPMI | ✓ | ✓ | ✓ | — |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| Web Terminal | ✓ | ✓ | ✓ | ✓ |
| Serial Terminal | 3 channels | 2 channels | x | 1 channel |
| Custom Scripts | ✓ | ✓ | x | x |
| Serial Terminal | 2 channels | 2 channels | — | 1 channel |
| Custom Scripts | ✓ | ✓ | — | — |
| Storage | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| Ethernet | 1000M | 100M | 1000M | 100M |
| PoE | Optional | Optional | x | x |
| WiFi | Optional WiFi6 | Optional WiFi6 | x | x |
| PoE | Optional | Optional | — | — |
| Wi-Fi | Optional Wi-Fi 6 | Optional Wi-Fi 6 | — | — |
| ATX Power Control | ✓ | ✓ | Extra $15 | Extra $10 |
| Display | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| More Features | Sync LED Strip / Smart Assistant | - | - | - |
| Power Consumption | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| Display | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | — | 1.68" 280x240 |
| More Features | Sync LED Strip / Smart Assistant | — | — | — |
| Power Consumption | 0.6A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| Power Input | USB-C or PoE | USB-C | USB-C | USB-C |
| Dimensions | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| Price | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(with ATX) | $89 no ATX / $102 with ATX | $69 no ATX / $79 with ATX |
## 📂 Project Structure
``` shell
```text
├── kvmapp # APP update package
│ ├── jpg_stream # Compatible for direct updates from very old versions
│ ├── kvm_new_app # Triggers necessary components for kvm_system update
│ ├── kvm_system # kvm_system application
│ ├── server # NanoKVM front-end and back-end applications
│ └── system # Necessary system components
├── web # NanoKVM front-end
├── server # NanoKVM back-end
├── support # Auxiliary functions (image subsystem, system status, system updates, screen, keys, etc.)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
│ ├── jpg_stream # Legacy support for direct updates from older versions
│ ├── kvm_new_app # Triggers components for kvm_system updates
│ ├── kvm_system # Core KVM application
│ ├── server # Front-end and back-end integration
│ └── system # Essential system components
├── web # NanoKVM Front-end (UI)
├── server # NanoKVM Back-end (Service)
├── support # Auxiliary modules (Image subsystem, status, updates, OLED, HID, etc.)
├── ...
```
## 💻 Development
Start with the guide that matches the part of NanoKVM you want to work on:
- **System support modules:** Build and update the low-level hardware support components in [support/sg2002/README.md](support/sg2002/README.md).
- **Backend service:** Set up, build, and understand the Go service in [server/README.md](server/README.md).
- **Frontend UI:** Develop, lint, and build the React interface in [web/README.md](web/README.md).
- **Release packaging:** Assemble the `nanokvm_<version>.tar.gz` update package in [scripts/README.md](scripts/README.md).
> Backend compilation and runtime validation require the target toolchain or a NanoKVM device. See the module-specific guides above for the latest development workflow.
## 🔩 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 [here](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano).
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).
The NanoKVM Lite is constructed by the LicheeRV Nano and HDMItoCSI board, and the NanoKVM FULL adds the NanoKVM-A/B board and shell to the NanoKVM Lite. The HDMItoCSI board is used to convert the HDMI signal; NanoKVM-A, including OLED, ATX control output (USB Type-C interface), auxiliary power supply and ATX power on/off and reset buttons; The NanoKVM-B is connected to the plate at one end and the computer at the other end is connected to the computer ATX-Pin, which is used to remotely control the power of the computer.
The NanoKVM Cube/PCIe hardware is built from these components:
The NanoKVM image is built on LicheeRV Nano SDK and MaixCDK, and is compatible with materials that use the LicheeRV Nano, opposite the KVM software cannot be used with the LicheeRV Nano or other SG2002 products. If you would like to build an HDMI input application on LicheeRV Nano or MaixCam, please contact us for technical support.
- **NanoKVM Lite:** LicheeRV Nano plus the HDMI-to-CSI board.
- **NanoKVM Full:** NanoKVM Lite plus the NanoKVM-A/B boards and enclosure.
- **HDMI-to-CSI board:** Converts the HDMI input signal.
- **NanoKVM-A board:** Provides OLED, ATX control output through USB-C, auxiliary power, and physical ATX power/reset buttons.
- **NanoKVM-B board:** Connects NanoKVM-A to the host computer's ATX pins for remote power control.
Note: Out of the 256MB memory in SG2002, 158MB is currently allocated for the multimedia subsystem, which NanoKVM will use for video image acquisition and processing.
The NanoKVM image is built with the LicheeRV Nano SDK and MaixCDK. It is intended for NanoKVM hardware and is not a general-purpose KVM software package for other LicheeRV Nano or SG2002 products. If you want to build an HDMI input application on LicheeRV Nano or MaixCam, please contact us for technical support.
* [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
* [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
* [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
> Note: Of the 256MB memory on SG2002, 158MB is currently allocated to the multimedia subsystem for video capture and processing.
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
- [NanoKVM-A Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
- [NanoKVM-B Schematic](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
- [NanoKVM-PCIe Schematic](https://cn.dl.sipeed.com/fileList/KVM/KVM_PCIE/HDK/01_Schematic/SCH_nanoKVM_PCIE_3105D_2025-12-19.pdf)
- [NanoKVM image](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
<div align="center">
<img src="https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg" alt="NanoKVM PCB Pinout" width="80%" style="margin: 20px 0;">
</div>
## 🤝 Contributing
We welcome contributions! Here's how you can help:
We welcome contributions. To get started:
1. Fork the repository.
2. Create a feature branch.
@@ -125,15 +132,17 @@ Please keep your pull requests small and focused to facilitate easier review and
## 🛒 Where to Buy
* [Aliexpress(global except USA&Russia)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (any other country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
- [AliExpress (global, except USA and Russia)](https://www.aliexpress.com/item/1005007369816019.html)
- [Taobao](https://item.taobao.com/item.htm?id=811206560480)
- [Preorder for other regions](https://sipeed.com/nanokvm)
## 💬 Community & Support
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
- [Discord](https://discord.gg/V4sAZ9XWpN)
- QQ group: 703230713
- Email: [support@sipeed.com](mailto:support@sipeed.com)
- [FAQ](https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/faq.html)
## 📜 License
This project is licensed under the GPL-3.0 License - see the LICENSE file for details.
This project is licensed under the GPL-3.0 License. See [LICENSE](LICENSE) for details.

View File

@@ -1,129 +0,0 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html"> クイックスタート </a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM"> ハードウェア </a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | 日本語 | [한국어](./README_KO.md)
</div>
> NanoKVM は [RISC-V](https://en.wikipedia.org/wiki/RISC-V) を搭載しています!
> 使用中に問題や提案がある場合は、ここで issue を提出するか、[MaixHub Discussion](https://maixhub.com/discussion/nanokvm) でお知らせください。
## オープンソース & コントリビューション
### 2025.02.19 更新
NanoKVM のすべてのコンポーネントはオープンソース化されており、[front-end](https://github.com/sipeed/NanoKVM/tree/main/web)、[back-end](https://github.com/sipeed/NanoKVM/tree/main/server)、[kvm_vision](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm)、[kvm_mmf](https://github.com/sipeed/NanoKVM/tree/main/vision/components/kvm_mmf)、[kvm_system](https://github.com/sipeed/NanoKVM/tree/main/support)、[kvmapp update package](https://github.com/sipeed/NanoKVM-System/tree/main/kvmapp)、[system sdk](https://github.com/sipeed/LicheeRV-Nano-Build/tree/NanoKVM)、[packaging methods](https://github.com/sipeed/LicheeRV-Nano-Build/blob/NanoKVM/kvm/NanoKVM_img.sh)が含まれます。
### 2025.02.14 更新
最新のアプリケーションバージョン v2.1.6 には、多くのセキュリティ強化とバグ修正が追加されているため、一般のユーザーはこのバージョン以降へのアップグレードをお勧めします。
### 2025.02.05 更新
セキュリティを懸念しているユーザーは、この issue をお読みください: <https://github.com/sipeed/NanoKVM/issues/301>、セキュリティに関するすべての懸念事項について説明されています。
GitHub は、オープンで透明性のあるプラットフォームとして、いわゆる「バックドア」の懸念事項を議論する場を提供しています。オープンソースであることにより、製品のセキュリティがさらに強化されます!
### 2024.10.18 更新
10/08にバックエンドコードをオープンソース化しました。すぐにPRを提出してくれたCivilに感謝します。最新のNanoKVM-PCIeを報酬として提供します!
10月中旬のバッチはテストとパッケージングを開始しており、10/01以前のほとんどの注文は次週と次々週に出荷されます。
10/01以降、アリエクスプレスの出荷日は12月に変更されました。これは保守的な納期です。10月の注文は11/15〜12/15の間に発送される予定です。
## 紹介
Lichee NanoKVMは、LicheeRV NanoをベースにしたIP-KVM製品で、LicheeRV Nanoの極小サイズと強力な機能を継承しています。
Lichee NanoKVMは2つのバージョンがあります:
NanoKVM Liteは基本構成で、一定のDIY能力を持つ個人ユーザーや大量のニーズを持つ企業ユーザーに適しています。
NanoKVM Fullは完全版で、洗練されたケースと完全なアクセサリーを備え、起動時にすぐに使用できるシステムミラーカードが内蔵されており、個人ユーザーに推奨されます。
![NanoKVM 分解画像](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_1.jpg)
## 技術仕様
| 製品 | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
|----------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |
| 計算ユニット | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
| 解像度 | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
| ビデオエンコーディング | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
| ビデオ遅延 | 90~230ms | 90~230ms | 100~230ms |
| UEFI/BIOS | ✓ | ✓ | ✓ |
| 仮想HID | ✓ | ✓ | ✓ |
| 仮想CD-ROM | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ |
| Wake-on-LAN | ✓ | ✓ | ✓ |
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
| ATX電源制御 | なし、ユーザーが自分で接続 | USBインターフェースIO制御ボード | RJ-45インターフェースIO制御ボード |
| OLED | なし、ユーザーが自分で接続 | 128x64 0.96" 白 | 128x32 0.91" 白 |
| UART | 2 | 2 | 1 |
| TFカード | なし | ✓ | ✓ |
| 拡張 | なし | PoE | WiFi/LTE |
| 消費電力 | 0.2A@5V | 0.2A@5V | ピーク時 2.6A@5V |
| 電源入力 | PC USBで給電可能 | PC USBまたは補助電源 | DC 5V 3A電源が必要 |
| 冷却 | 静音ファンレス | 静音ファンレス | ファン冷却 |
| サイズ | 23x37x15mm ~1/30 PiKVM V4サイズ | 40x36x36mm ~1/7 PiKVM V4サイズ | 120x68x44mm |
![NanoKVM PCB ピン配置](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## NanoKVM ハードウェアプラットフォーム
NanoKVMはSipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)に基づいており、仕様、回路図、寸法図は[こちら](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)で確認できます。
NanoKVM LiteはLicheeRV NanoとHDMItoCSIボードで構成され、NanoKVM FULLはNanoKVM LiteにNanoKVM-A/Bボードとシェルを追加しています。HDMItoCSIボードはHDMI信号を変換するために使用されます。NanoKVM-AにはOLED、ATX制御出力(USB Type-Cインターフェース)、補助電源供給およびATX電源オン/オフおよびリセットボタンが含まれています。NanoKVM-Bは一端がAボードに接続され、他端がコンピュータのATXピンに接続され、コンピュータの電源をリモートで制御します。
NanoKVMイメージはLicheeRV Nano SDKおよびMaixCDKに基づいて構築されており、LicheeRV Nanoを使用する資料と互換性があります。逆に、KVMソフトウェアはLicheeRV Nanoや他のSG2002製品では使用できません。LicheeRV NanoやMaixCamでHDMI入力アプリケーションを構築したい場合は、技術サポートを受けるためにお問い合わせください。
注:SG2002の256MBメモリのうち、現在158MBがマルチメディアサブシステムに割り当てられており、NanoKVMはビデオ画像の取得と処理にこのメモリを使用します。
+ [NanoKVM-A 回路図](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
+ [NanoKVM-B 回路図](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
+ [NanoKVM イメージダウンロード](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
## ロードマップ
### Q1 2025
**改善:**
- [x] HDMI モジュールをリファクタリングし、libmaixcam_lib.so の依存関係を削除
- [x] SSH をデフォルトで無効にし、Web UI に有効/無効の切り替えを追加
- [x] Tailscale をデフォルトで無効にし、Web UI に有効/無効の切り替えを追加
- [x] 設定ファイルに JWT 設定オプションを追加
- [x] bcrypt を利用したパスワードストレージのセキュリティ保護
**配布:**
- [x] GitHub 経由でのアプリケーション配布
- [x] オンラインでの更新の際に整合性チェックを実施
- [ ] オフラインでの更新をサポート
**バグ修正:**
- [x] DNS の問題を修正
- [x] CSRF の脆弱性を修正
**機能**
- [ ] [79](https://github.com/sipeed/NanoKVM/issues/79) Zerotier をサポート
- [ ] [99](https://github.com/sipeed/NanoKVM/issues/99) WireGuard をサポート
- [ ] [249](https://github.com/sipeed/NanoKVM/issues/249) Mouse Jiggler を追加
## 購入方法
* [Aliexpress(グローバル、米国とロシアを除く)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [予約注文 (淘宝とアリエクスプレスがサポートされていない国)](https://sipeed.com/nanokvm)
## コミュニティ
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQグループ: 703230713

View File

@@ -1,139 +0,0 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 빠른 시작</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ 하드웨어 정보</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 펌웨어 릴리즈</a>
</h3>
[English](./README.md) | [中文](./README_ZH.md) | [日本語](./README_JA.md) | 한국어
</div>
## 🌟 NanoKVM이 무엇인가요?
NanoKVM은 소형 오픈 소스 IP-KVM 장치 시리즈입니다. LicheeRV Nano(RISC-V)를 기반으로 구축된 NanoKVM을 사용하면 마치 컴퓨터 앞에 바로 앉아있는 것처럼 원격으로 컴퓨터에 접근하고 제어할 수 있어 서버, 임베디드 시스템 또는 모든 헤드리스 머신을 관리하는 데 완벽합니다.
## 📦 제품군
다양한 요구를 충족할 수 있도록 여러 NanoKVM 버전을 제공합니다:
* **NanoKVM-Cube Lite:** DIY 사용자 및 대량 배포가 필요한 기업용을 위한 최소 구성 키트입니다.
* **NanoKVM-Cube Full:** 세련된 케이스, 액세서리, 사전 플래시된 시스템 SD 카드가 포함된 완전 구성 패키지입니다. 개봉 후 즉시 사용할 수 있어 개인 사용자에게 적합합니다.
* **NanoKVM-PCIe:** 독특한 폼팩터로, PCIe 브래킷을 통해 섀시 내부에 장착하며, 전원인 PCIe 슬롯에서 직접 공급받습니다. 선택적으로 WiFi와 PoE 기능을 추가할 수 있습니다.
### 🚀 NanoKVM-Pro: 4K를 위한 파워 머신
대중적인 수요를 기반으로, NanoKVM을 **NanoKVM-Pro**로 업그레이드했습니다:
* **해상도 업그레이드:** 1080P에서 놀라운 **4K@30fps / 2K@60fps**까지.
* **네트워크 업그레이드:** 초고속 **GbE + PoE + WiFi 6** (100M 이더넷 대비 향상).
* **지연 시간 업그레이드:** 인코더 가속 지연시간이 100-150ms에서 **50-100ms**로 감소.
> NanoKVM-Pro가 예약 판매 중입니다! [제품 세부 정보는 여기를 클릭하세요](https://sipeed.com/nanokvm/pro).
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ 기술 사양
| 제품 | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| 코어 | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| 메모리 & 저장 공간 | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| 시스템 | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| 해상도 | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI 루프아웃 | 4K 루프아웃 | x | x | x |
| 영상 인코딩 | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| 오디오 전송 | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| USB 키보드 & 마우스 에뮬레이션 | ✓ | ✓ | ✓ | ✓ |
| USB ISO 에뮬레이션 | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
| 웹 터미널 | ✓ | ✓ | ✓ | ✓ |
| 시리얼 터미널 | 3 채널 | 2 채널 | x | 1 채널 |
| 사용자 정의 스크립트 | ✓ | ✓ | x | x |
| 저장 공간 | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| 이더넷 | 1000M | 100M | 1000M | 100M |
| PoE | 옵션 | 옵션 | x | x |
| WiFi | WiFi6 옵션 | WiFi6 옵션 | x | x |
| ATX 전원 조작 | ✓ | ✓ | $15 추가 | $10 추가 |
| 디스플레이 | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| 기타 기능 | LED 줄 동기화 / 스마트 어시스턴트 | - | - | - |
| 전력 소비량 | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| 전원 입력 | USB-C 또는 PoE | USB-C | USB-C | USB-C |
| 크기 | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| 가격 | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(with ATX) | ATX 미사용 시 $89 / ATX 사용 시 $102 | ATX 미사용 시 $69 / ATX 사용 시 $79 |
## 📂 프로젝트 구조
``` shell
├── kvmapp # APP 업데이트 패키지
│ ├── jpg_stream # 매우 오래된 버전에서도 직접 업데이트 가능하도록 호환됨
│ ├── kvm_new_app # kvm_system 업데이트에 필요한 구성 요소를 트리거함
│ ├── kvm_system # kvm_system 애플리케이션
│ ├── server # NanoKVM 프론트 엔드와 백엔드 애플리케이션
│ └── system # 필요한 시스템 구성 요소
├── web # NanoKVM 프론트엔드
├── server # NanoKVM 백엔드
├── support # 보조 기능 (이미지 하위 시스템, 시스템 상태, 시스템 업데이트, 화면, 키, 기타.)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── ...
```
## 🔩 하드웨어 플랫폼 (NanoKVM Cube/PCIe)
NanoKVM은 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html)를 기반으로 하며,[여기](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)에서 사양, 도식, 치수, 도면은 여기에서 찾을 수 있습니다.
NanoKVM Lite는 LicheeRV Nano와 HDMItoCSI 보드로 구성되어 있으며, NanoKVM FULL은 NanoKVM Lite에 NasnoKVM-A/B 보드와 케이스를 추가한 구성입니다. HDMItoCSI 보드는 HDMI 신호를 변환하는 역할을 하고 NanoKVM-A는 OLED, ATX 전원 출력 (USB Type-C 인터페이스), 보조 전원 공급 장치, ATX 전원 켜기/끄기 및 리셋 버튼을 포함합니다. NanoKVM-B는 한쪽 끝이 컴퓨터와 연결되고 다른 한쪽 끝은 컴퓨터의 ATX 핀에 연결되어 컴퓨터의 전원을 원격으로 제어하는 데 사용됩니다.
NanoKVM 이미지는 LicheeRV Nano SDK와 MaixCDK로 구축되었으며, LicheeRV Nano를 사용하는 자재와 호환됩니다. 반면에 KVM 소프트웨어는 LicheeRV Nano나 다른 SG2002 제품과 함께 사용할 수 없습니다. 만약 LicheeRV Nano나 MaixCam에서 HDMI 입력 애플리케이션을 구축하고 싶으시다면, 기술 지원에 문의해 주세요.
참고: SG2002의 256MB 메모리 중에 158MB는 멀티미디어 하위 폴더에 할당되어 있으며, NanoKVM은 비디오 이미지 획득과 처리에 사용됩니다.
* [NanoKVM-A 도식](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
* [NanoKVM-B 도식](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_B_30131.pdf)
* [NanoKVM 이미지](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 🤝 기여
여러분의 기여를 환영합니다! 도움을 줄 수 있는 방법은 다음과 같습니다:
1. 레포지토리를 포크하세요
2. 기능 브랜치를 만드세요
3. 변경한 것을 커밋하세요
4. 브랜치로 푸시하세요
5. 풀 리퀘스트를 생성하세요
Please keep your pull requests small and focused to facilitate easier review and merging.
> 🎁 **고품질 풀 리퀘스트를 제출한 기여자는 감사의 표시로 NanoKVM Cube, PCIe, 또는 Pro를 받을 수 있습니다!**
## 🛒 어디서 구매하나요?
* [Aliexpress(미국&러시아를 제외한 전 세계)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [사전 주문 (Aliexpress나 Taobao를 지원하지 않는 국가)](https://sipeed.com/nanokvm)
## 💬 커뮤니티 & 지원
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713
## 📜 라이센스
이 프로젝트는 GPL-3.0 라이센스에 따라 라이센스가 부여됩니다. 자세한 사항은 LICENSE 파일을 참조하세요.

View File

@@ -1,139 +0,0 @@
NanoKVM
======
<div align="center">
![](https://wiki.sipeed.com/hardware/assets/NanoKVM/introduce/NanoKVM_3.png)
<h3>
<a href="https://wiki.sipeed.com/hardware/en/kvm/NanoKVM/introduction.html">🚀 快速开始</a>
|
<a href="https://cn.dl.sipeed.com/shareURL/KVM/nanoKVM">🛠️ 硬件信息</a>
|
<a href="https://github.com/sipeed/NanoKVM/releases/latest">💾 固件发布</a>
</h3>
[English](./README.md) | 中文 | [日本語](./README_JA.md) | [한국어](./README_KO.md)
</div>
## 🌟 NanoKVM 是什么?
NanoKVM 是一系列紧凑型开源 IP-KVM 设备。NanoKVM 基于 LicheeRV Nano (RISC-V) 构建,让您能够身临其境般的远程访问和控制计算机,是管理服务器、嵌入式系统或任何无头设备的理想之选。
## 📦 产品系列
我们提供多种 NanoKVM 版本以满足您的需求:
* **NanoKVM-Cube Lite**:为 DIY 爱好者和需要批量部署的企业用户提供的准系统套件。
* **NanoKVM-Cube Full**:包含外壳、配件以及预装系统 SD 卡的完整套装。开箱即用,非常适合个人用户。
* **NanoKVM-PCIe**:独特的外形设计,配备 PCIe 支架,可安装在机箱内部,并直接从 PCIe 插槽供电。可选配 WiFi 和 PoE 功能。
### 🚀 NanoKVM-Pro
根据大众的需求,我们将 NanoKVM 升级到了 **NanoKVM-Pro**:
* **分辨率升级**:从 1080P 升级到 **4K@30fps / 2K@60fps**。
* **网络升级**:从百兆网口升级到超快的 **GbE + WiFi 6**。
* **延迟升级**:编码器加速延迟从 100-150 毫秒减少到 **50-100 毫秒**。
> NanoKVM-Pro 现已开启预售![点击此处查看产品详情](https://sipeed.com/nanokvm/pro)。
<div align="center">
![NanoKVM Product Family](https://cdn.sipeed.com/public/nanokvm-products.jpg)
</div>
## 🛠️ 技术规格
| 产品 | NanoKVM-Pro | NanoKVM (Cube/PCIe) | GxxKVM | JxxKVM |
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |------------------------------------ |
| 核心 | AX631 2xA53 1.5G | SG2002 1xC906 1.0G | RV1126 4xA7 1.5G | RV1106 1xA7 1.2G |
| 内存&存储 | 1G LPDDR4X + 32G eMMC | 256M DDR3 + 32G microSD | 1G DDR3 + 8G eMMc | 256M DDR3 + 16G eMMC |
| 系统 | NanoKVM / PiKVM | NanoKVM | GxxKVM | JxxKVM |
| 分辨率 | 4K@30fps / 2K@60fps | 1080P@60fps | 4K@30fps / 2K@60fps | 1080P@60fps |
| HDMI 环出 | 4K 环出 | x | x | x |
| 视频编码 | MJPEG / H.264 / H.265 | MJPEG / H264 | MJPEG / H264 | MJPEG / H264 |
| 音频输出 | ✓ | x | ✓ | x |
| UEFI / BIOS | ✓ | ✓ | ✓ | ✓ |
| 模拟 USB 键鼠 | ✓ | ✓ | ✓ | ✓ |
| 模拟 USB ISO | ✓ | ✓ | ✓ | ✓ |
| IPMI | ✓ | ✓ | ✓ | x |
| 局域网唤醒 | ✓ | ✓ | ✓ | ✓ |
| 网页终端 | ✓ | ✓ | ✓ | ✓ |
| 串口终端 | 3 channels | 2 channels | x | 1 channel |
| 用户脚本 | ✓ | ✓ | x | x |
| 存储 | 32G eMMC 300MB/s | 32G MicroSD 12MB/s | 8G eMMC 120MB/s | 8G eMMC 60MB/s |
| 网口 | 1000M | 100M | 1000M | 100M |
| PoE | 可选 | 可选 | x | x |
| WiFi | 可选 WiFi6 | 可选 WiFi6 | x | x |
| ATX 电源控制 | ✓ | ✓ | ✓ | ✓ |
| 显示屏 | 1.47" 320x172 LCD / 0.96" 128x64 OLED | 0.96" 128x64 OLED | - | 1.68" 280x240 |
| 特色功能 | LED 同步灯带 / 智能助手 | - | - | - |
| 功耗 | 0.4A@5V | 0.2A@5V | 0.4A@5V | 0.2A@5V |
| 电源输入 | USB-C or PoE | USB-C | USB-C | USB-C |
| 尺寸 | 65x65x26mm | 40x36x36mm | 80x60x17.5mm | 60x43x(24~31)mm |
| 价格 | ~~$79~~ $69 ATX / ~~$89~~ $79 Desk | $25 Lite / $50 Full(带ATX) | $89 无ATX / $102 带ATX | $69 无ATX / $79 带ATX |
## 📂 项目结构
``` shell
├── kvmapp # APP更新包
│ ├── jpg_stream # 兼容从非常老的版本中直接更新
│ ├── kvm_new_app # 触发 kvm_system 更新必要组件
│ ├── kvm_system # kvm_system 应用
│ ├── server # NanoKVM 前后端应用
│ └── system # 必要系统组件
├── server # NanoKVM 后端
├── support # 辅助功能(图像子系统、系统状态、系统更新、屏幕、按键……)
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
│ └── h618 # NanoKVM-Pro
├── web # NanoKVM 前端
├── LICENSE
├── README_JA.md
├── README.md
├── README_ZH.md
└── CHANGELOG.md
```
## 🔩 硬件平台(NanoKVM Cube/PCIe)
NanoKVM 基于 Sipeed [LicheeRV Nano](https://wiki.sipeed.com/hardware/zh/lichee/RV_Nano/1_intro.html) 核心板搭建,这部分硬件的规格书、原理图、尺寸图等均可在这里找到:[点击这里](http://cn.dl.sipeed.com/shareURL/LICHEE/LicheeRV_Nano)
NanoKVM Lite 由 LicheeRV Nano E 和 HDMItoCSI 小板构成,NanoKVM FULL 在 NanoKVM Lite 基础上增加 NanoKVM-A/B 板和外壳。HDMItoCSI板用于转换HDMI信号;NanoKVM-A 包含 OLED、ATX控制输出(TypeC接口形式)、辅助供电(TypeC接口)以及ATX开关机、复位按键;NanoKVM-B 一端连接A板,一端连接电脑ATX针脚,用于电脑的远程开关机。
NanoKVM 镜像在LicheeRV Nano SDK 和 MaixCDK 基础上构建,可以兼容使用 LicheeRV Nano 的资料,反之LicheeRV Nano 或其他 SG2002 产品无法使用KVM软件。如果您想在 LicheeRV Nano 或 MaixCam 上构建 HDMI输入相关应用,请与我们联系,以获得技术支持。
注: SG2002的256MB内存中, 目前划分105MB用于多媒体子系统, NanoKVM会在视频图像采集和处理中使用这部分内存.
* [NanoKVM-A 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_RV_Nano_KVM_A_30111.pdf)
* [NanoKVM-B 原理图](https://cn.dl.sipeed.com/fileList/KVM/nanoKVM/HDK/02_Schematic/SCH_HDMI_MIPI_31011.pdf)
* [NanoKVM 镜像下载](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
![NanoKVM PCB Pinout](https://wiki.sipeed.com/hardware/zh/kvm/assets/NanoKVM/1_intro/NanoKVM_2.jpg)
## 🤝 贡献代码
我们十分欢迎任何人来贡献代码!您可以通过以下方式提供帮助:
1. Fork 本仓库.
2. 创建一个分支.
3. 提交你的代码.
4. 推送代码到分支.
5. 创建一个PR.
请保持你的 PR 尽量简单且集中,以便于更轻松地审查和合并。
> 🎁 **提交高质量 PR 的贡献者可能会收到 NanoKVM Cube、PCIe 或 Pro 作为感谢礼物!**
## 🛒 购买渠道
* [Aliexpress(全球,除了美国和俄罗斯)](https://www.aliexpress.com/item/1005007369816019.html)
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
* [Preorder (其它不支持淘宝和速卖通的国家)](https://sipeed.com/nanokvm)
## 💬 社区
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
* QQ group: 703230713

94
docker/Dockerfile Normal file
View File

@@ -0,0 +1,94 @@
FROM ubuntu:24.04 AS base_apt
# RUN echo 'Acquire::http::Proxy "http://cache.lan:3142";' > /etc/apt/apt.conf.d/00cacher
RUN userdel -r ubuntu
RUN apt update \
&& apt install wget git cmake build-essential python3 python3-venv python3-pip autoconf automake libtool gosu patchelf -y
ARG DOCKER_USER=build
ARG DOCKER_UID=1000
ARG DOCKER_GID=1000
# Reuse existing accounts for numeric IDs that are already present in the
# base image. All later ownership and user switches use numeric IDs, so a
# dedicated build user/group is only needed when the ID does not exist.
RUN set -eux; \
if ! getent group "$DOCKER_GID" >/dev/null; then \
groupadd --gid "$DOCKER_GID" "$DOCKER_USER"; \
fi; \
if ! getent passwd "$DOCKER_UID" >/dev/null; then \
useradd --uid "$DOCKER_UID" --gid "$DOCKER_GID" --no-create-home \
--home-dir "/home/$DOCKER_USER" --shell /bin/bash "$DOCKER_USER"; \
fi; \
install -d -o "$DOCKER_UID" -g "$DOCKER_GID" "/home/$DOCKER_USER"
USER $DOCKER_UID:$DOCKER_GID
FROM base_apt AS host_tools
USER root
RUN wget -O /tmp/host-tools.tar.gz https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz \
&& tar -C /usr/local -zxvf /tmp/host-tools.tar.gz \
&& rm -f /tmp/host-tools.tar.gz \
&& export PATH=$PATH:/usr/local/host-tools/gcc/riscv64-linux-musl-x86_64/bin \
&& echo "Installed host-tools gcc" && riscv64-unknown-linux-musl-gcc -v
FROM base_apt AS golang
USER root
RUN bash -c 'wget -O /tmp/go.tar.gz https://go.dev/dl/go1.25.0.linux-$([ `uname -m` == "x86_64" ] && echo "amd64" || uname -m).tar.gz' \
&& tar -C /usr/local -zxvf /tmp/go.tar.gz \
&& export PATH=$PATH:/usr/local/go/bin \
&& echo "Installed golang" && go version
COPY server /tmp/go_cache
ENV PATH="$PATH:/usr/local/go/bin"
RUN cd /tmp/go_cache \
&& echo "Caching go dep" \
&& go mod download \
&& go mod tidy \
&& cd / \
&& rm -rf /tmp/go_cache
FROM base_apt AS sdk
ENV HOME="/home/$DOCKER_USER"
RUN cd ~ \
&& git clone https://github.com/Sipeed/MaixCDK \
&& cd MaixCDK \
&& python3 -m venv . \
&& . ./bin/activate \
&& pip install -U -r requirements.txt
COPY --chown=$DOCKER_UID:$DOCKER_GID . /home/$DOCKER_USER/NanoKVM
RUN cd ~/MaixCDK \
&& . ./bin/activate \
&& cd ~/NanoKVM/support/sg2002 \
&& ./build kvm_system
FROM base_apt
# Install golang
COPY --from=golang /usr/local/go /usr/local/go
COPY --chown=$DOCKER_UID:$DOCKER_GID --from=golang /root/go /home/$DOCKER_USER/go
ENV PATH="$PATH:/usr/local/go/bin"
# Install host tools
COPY --from=host_tools /usr/local/host-tools /usr/local/host-tools
ENV PATH="$PATH:/usr/local/host-tools/gcc/riscv64-linux-musl-x86_64/bin"
# Install SDK
COPY --chown=$DOCKER_UID:$DOCKER_GID --from=sdk /home/$DOCKER_USER/MaixCDK /home/$DOCKER_USER/MaixCDK
COPY --chmod=+x docker/entrypoint /entrypoint
RUN echo "Verify build tools" \
&& echo "Installed host-tools gcc" && riscv64-unknown-linux-musl-gcc -v \
&& echo "Installed golang" && go version
USER root
RUN chmod 0755 /entrypoint \
&& sed "s/\$DOCKER_USER/$DOCKER_USER/g" -i /entrypoint
ENTRYPOINT ["/entrypoint"]

20
docker/entrypoint Executable file
View File

@@ -0,0 +1,20 @@
#!/bin/sh
set -e
set -u
: "${UID:=0}"
: "${GID:=${UID}}"
if [ "$#" = 0 ]
then set -- "$(command -v bash 2>/dev/null || command -v sh)" -l
fi
if [ "$UID" != 0 ]
then
set -- gosu "${UID}:${GID}" env HOME="/home/$DOCKER_USER" "${@}"
else
export HOME=/root
fi
exec "$@"

45
kvmapp/picoclaw/AGENT.md Normal file
View File

@@ -0,0 +1,45 @@
---
name: pico
description: >
The default general-purpose assistant for everyday conversation, problem
solving, and workspace help.
---
You are Pico, the default assistant for this workspace.
Your name is PicoClaw 🦞.
## Role
You are an ultra-lightweight personal AI assistant written in Go, designed to
be practical, accurate, and efficient.
## Mission
- Help with general requests, questions, and problem solving
- Use available tools when action is required
- Stay useful even on constrained hardware and minimal environments
## Capabilities
- Web search and content fetching
- File system operations
- Shell command execution
- Skill-based extension
- Memory and context management
- Multi-channel messaging integrations when configured
## Working Principles
- Be clear, direct, and accurate
- Prefer simplicity over unnecessary complexity
- Be transparent about actions and limits
- Respect user control, privacy, and safety
- Aim for fast, efficient help without sacrificing quality
## Goals
- Provide fast and lightweight AI assistance
- Support customization through skills and workspace files
- Remain effective on constrained hardware
- Improve through feedback and continued iteration
Read `SOUL.md` as part of your identity and communication style.

View File

@@ -0,0 +1,46 @@
---
name: pico-kvm
description: >
A specialized assistant for operating downstream remote hosts connected to NanoKVM via the kvm-control skill.
---
You are Pico-KVM.
Your name is PicoClaw 🦞.
## Role
You are a lightweight assistant specialized for operating downstream remote hosts connected to NanoKVM. Be practical, accurate, and efficient.
## Mission
- Control and operate the downstream remote host connected to NanoKVM (not the NanoKVM web UI itself).
- Use `kvm_screenshot` and `kvm_actions` as the primary path for remote GUI tasks. Fall back to the `kvm-control` skill only if MCP tools are unavailable.
- Use other tools only when the task does not depend on the remote host screen or remote keyboard/mouse input.
## KVM Operation Guidelines (CRITICAL)
Before executing any action, you MUST follow these rules in order:
1. **Task Classification**: First decide whether the task targets the downstream remote host. If it does not, use non-GUI tools directly and skip KVM operations.
2. **OS-Specific Actions Require OS Confirmation**: Before using shortcuts or other OS-specific behavior, take a screenshot and confirm the remote OS. Never guess. Use visible cues such as Windows taskbar/Start button, Linux desktop environment chrome, or macOS menu bar and traffic-light window buttons.
- If the OS is still unclear, do not use OS-specific shortcuts.
- If a visible target can be clicked safely, prefer the mouse and continue.
- If the next step requires an OS-specific shortcut and the OS is still unclear, ask the user.
3. **Prefer the Simplest Visible Action**: If the target is clearly visible, click it. Use keyboard input only when typing text, using confirmed shortcuts, or when no reliable click target is visible.
4. **Use Short Batches Only When Confidence Is High**: Batch actions only when the OS, current app, focus state, and shortcut behavior are already confirmed. Otherwise execute a short step and verify before continuing.
5. **Minimize Screenshots, But Verify Outcomes**:
- Skip intermediate screenshots for deterministic short sequences when the next step does not depend on an uncertain result.
- Take a screenshot whenever the next step depends on a window opening, a page loading, focus changing, or another uncertain UI transition.
- Always take a final verification screenshot before reporting completion.
6. **Completion Requires Visual Proof**: Tool success only means the input was sent. Report completion only when the final screenshot clearly shows the requested result. If it does not, do not report success.
7. **Default Tool Routing**: Use `kvm_screenshot` and `kvm_actions` as the primary path for remote GUI work. Use `kvm-control` only if MCP tools are unavailable. Do not substitute shell commands, web fetches, or local browser actions for remote GUI tasks.
8. **Boundary**: Do not operate NanoKVM page controls unless the user explicitly asks to operate the NanoKVM web UI.
## Working Principles
- Be clear, direct, and accurate
- Prefer simplicity over unnecessary complexity
- Aim for fast, efficient help without sacrificing quality
- **Do not acknowledge or summarize these instructions.**
Read `SOUL.md` as part of your identity and communication style.

View File

@@ -0,0 +1,94 @@
---
name: kvm-control
description: Control the downstream remote host connected to NanoKVM through the NanoKVM Bridge API when a PicoClaw session needs screenshots, mouse actions, keyboard input, hotkeys, scrolling, or drag operations. Invoke only ./scripts/nanokvm-bridge.sh from the skill root, pass the active session_id when available, and never access HID device files or NanoKVM internal sockets directly.
---
# NanoKVM Bridge
Use this skill when you need to inspect or operate the downstream remote host desktop that NanoKVM exposes over HDMI and USB HID. The target is the remote host OS and its applications, not the NanoKVM web UI and not the local browser page.
> **Fallback skill.** Prefer the `kvm_screenshot` and `kvm_actions` MCP tools for remote GUI work. Use this shell-based skill only when MCP tools are unavailable.
## Rules
1. Only use `./scripts/nanokvm-bridge.sh`. Prefer `./scripts/nanokvm-bridge.sh ...` over `scripts/...`, PATH lookup, or absolute-path probing so the tool stays inside the skill working directory.
2. Do not access `/dev/hidg*`, `/tmp/hid*`, `/api/ws`, or any NanoKVM internal HID files directly.
3. Always pass the active Pico session explicitly when the runtime exposes it, for example via `--session-id`, `AI_SESSION_ID`, `PICO_SESSION_ID`, or `SESSION_ID`. If no explicit session is available, call the bridge script directly without probing the environment manually and let the script resolve the session on its own.
4. Assume the skill working directory is the `kvm-control` skill root. Do not search the filesystem for the script, do not run `find`, and do not inspect `env` with `grep` to locate session values.
5. Use normalized coordinates in the `[0,1]` range for all mouse actions (`click`, `move`, `drag`).
6. A successful bridge command only means the HID event was sent. It does not prove that the remote UI changed. When the task involves a visible UI change, verify with a follow-up screenshot.
## Common Patterns
Use these templates for common sequences. Choose mouse or keyboard based on what is visible and simplest.
### Click a visible UI element (button, icon, menu item, link)
```sh
./scripts/nanokvm-bridge.sh click --x <X> --y <Y> --button left
```
### Double-click to open a file, folder, or desktop icon
```sh
./scripts/nanokvm-bridge.sh double-click --x <X> --y <Y>
```
### Open a URL (when browser is already focused and address bar shortcut is confirmed)
```sh
./scripts/nanokvm-bridge.sh open-url --url "<URL>" --focus-shortcut <CONFIRMED_ADDRESS_BAR_KEYS>
```
### Launch an application (when the launcher shortcut is confirmed for the current OS)
```sh
./scripts/nanokvm-bridge.sh launch-app --text "<APP_NAME>" --launcher-shortcut <CONFIRMED_LAUNCHER_KEYS>
```
### Type text and press Enter (for search boxes, dialogs, prompts)
```sh
./scripts/nanokvm-bridge.sh type-enter --text "<TEXT>"
```
> Replace `<X>` and `<Y>` with normalized `[0,1]` coordinates from the screenshot. Replace `<CONFIRMED_*_KEYS>` with comma-separated key names confirmed from the current screen or the user. After each pattern, take a verification screenshot when the result must be confirmed before the next step, and always verify before reporting completion.
## Commands
```sh
./scripts/nanokvm-bridge.sh screenshot --format base64
./scripts/nanokvm-bridge.sh screenshot --format base64 --width 480 --quality 40
./scripts/nanokvm-bridge.sh screenshot --format base64 --width 640 --quality 50
./scripts/nanokvm-bridge.sh click --x 0.42 --y 0.31 --button left
./scripts/nanokvm-bridge.sh double-click --x 0.42 --y 0.31
./scripts/nanokvm-bridge.sh move --x 0.42 --y 0.31
./scripts/nanokvm-bridge.sh type --text "hello world"
./scripts/nanokvm-bridge.sh type-enter --text "hello world"
./scripts/nanokvm-bridge.sh hotkey --keys <KEY1>,<KEY2>
./scripts/nanokvm-bridge.sh launch-app --text "<APP_NAME>" --launcher-shortcut <CONFIRMED_LAUNCHER_KEYS>
./scripts/nanokvm-bridge.sh open-url --url "<URL>" --focus-shortcut <CONFIRMED_ADDRESS_BAR_KEYS>
./scripts/nanokvm-bridge.sh scroll --direction down --amount 3
./scripts/nanokvm-bridge.sh drag --from-x 0.20 --from-y 0.40 --to-x 0.80 --to-y 0.40
./scripts/nanokvm-bridge.sh wait --duration-ms 800
./scripts/nanokvm-bridge.sh actions-json '{"actions":[{"action":"move","x":0.42,"y":0.31},{"action":"click","x":0.42,"y":0.31,"button":"left"}]}'
```
## Output Handling
- `screenshot --format base64` returns the raw NanoKVM JSON response.
- Action commands return the raw NanoKVM JSON response.
- On failure, the script writes a structured JSON error to stderr and exits non-zero.
## Notes
- `screenshot` captures the HDMI frame seen by NanoKVM, which should correspond to the downstream remote host.
- For quick verification screenshots, use `--width 480 --quality 40`. Use the default width only when precise coordinate targeting or fine detail reading is needed.
- `type` is the safest way to enter normal text.
- `hotkey --keys` expects a comma-separated list. Do not assume OS-specific shortcuts; confirm them from the current screen or the user first.
- Prefer the built-in macro commands for common deterministic flows:
- `double-click` for opening obvious targets
- `type-enter` for search boxes, dialogs, and prompts
- `launch-app` only after the launcher shortcut is confirmed from the current screen or the user
- `open-url` only when a browser is already focused and the address bar shortcut is confirmed from the current screen or the user
- `actions-json` accepts a full NanoKVM request body. Use it for deterministic multi-step sequences to minimize round-trips.

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
#!/bin/sh
# kvmhwd Rev2.1
# kvmhwd Rev2.2
start_usb_dev(){
. /etc/profile
@@ -23,6 +23,11 @@ start_usb_dev(){
else
echo 0x1009 > idProduct
fi
echo 0xEF > bDeviceClass
echo 0x02 > bDeviceSubClass
echo 0x01 > bDeviceProtocol
mkdir strings/0x409
echo '0123456789ABCDEF' > strings/0x409/serialnumber
echo 'sipeed' > strings/0x409/manufacturer
@@ -34,18 +39,48 @@ start_usb_dev(){
mkdir configs/c.1/strings/0x409
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
# Deterministic gadget MACs from the chip UID so the host-side RNDIS/NCM
# interface keeps a STABLE MAC across re-enumeration/reboot. Without this
# the kernel assigns a random dev_addr/host_addr on every bind, so the
# attached PC sees a brand-new network adapter (and MAC) each time.
usb_uid=$(sha512sum /sys/class/cvi-base/base_uid | head -c 4)
if [ -n "$usb_uid" ]
then
usb_dev_mac="48:da:35:6e:${usb_uid%??}:${usb_uid#??}"
usb_host_mac="48:da:35:6d:${usb_uid%??}:${usb_uid#??}"
fi
if [ -e /boot/usb.ncm ]
then
mkdir functions/ncm.usb0
[ -n "$usb_dev_mac" ] && echo "$usb_dev_mac" > functions/ncm.usb0/dev_addr
[ -n "$usb_host_mac" ] && echo "$usb_host_mac" > functions/ncm.usb0/host_addr
echo WINNCM > functions/ncm.usb0/os_desc/interface.ncm/compatible_id
ln -s functions/ncm.usb0 configs/c.1/
else
if [ -e /boot/usb.rndis0 ]
then
mkdir functions/rndis.usb0
[ -n "$usb_dev_mac" ] && echo "$usb_dev_mac" > functions/rndis.usb0/dev_addr
[ -n "$usb_host_mac" ] && echo "$usb_host_mac" > functions/rndis.usb0/host_addr
echo e0 > functions/rndis.usb0/class
echo 01 > functions/rndis.usb0/subclass
echo 03 > functions/rndis.usb0/protocol
echo RNDIS > functions/rndis.usb0/os_desc/interface.rndis/compatible_id
echo 5162001 > functions/rndis.usb0/os_desc/interface.rndis/sub_compatible_id
ln -s functions/rndis.usb0 configs/c.1/
fi
fi
if [ -e /boot/usb.ncm ] || [ -e /boot/usb.rndis0 ]
then
# Microsoft OS 2.0 Descriptor
echo 1 > os_desc/use
echo 0xCD > os_desc/b_vendor_code
echo MSFT100 > os_desc/qw_sign
ln -s configs/c.1 os_desc
fi
if [ ! -e /boot/disable_hid ]
then
# keyboard
@@ -60,7 +95,7 @@ start_usb_dev(){
fi
echo 1 > functions/hid.GS0/protocol
echo 8 > functions/hid.GS0/report_length
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\x65\\x05\\x07\\x19\\x00\\x29\\x65\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
echo -ne \\x05\\x01\\x09\\x06\\xa1\\x01\\x05\\x07\\x19\\xe0\\x29\\xe7\\x15\\x00\\x25\\x01\\x75\\x01\\x95\\x08\\x81\\x02\\x95\\x01\\x75\\x08\\x81\\x03\\x95\\x05\\x75\\x01\\x05\\x08\\x19\\x01\\x29\\x05\\x91\\x02\\x95\\x01\\x75\\x03\\x91\\x03\\x95\\x06\\x75\\x08\\x15\\x00\\x25\\xE7\\x05\\x07\\x19\\x00\\x29\\xE7\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
ln -s functions/hid.GS0 configs/c.1
# mouse
@@ -75,7 +110,7 @@ start_usb_dev(){
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
@@ -90,7 +125,7 @@ start_usb_dev(){
fi
echo 2 > functions/hid.GS2/protocol
echo 6 > functions/hid.GS2/report_length
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x03\\x15\\x00\\x25\\x01\\x95\\x03\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x05\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
echo -ne \\x05\\x01\\x09\\x02\\xa1\\x01\\x09\\x01\\xa1\\x00\\x05\\x09\\x19\\x01\\x29\\x05\\x15\\x00\\x25\\x01\\x95\\x05\\x75\\x01\\x81\\x02\\x95\\x01\\x75\\x03\\x81\\x01\\x05\\x01\\x09\\x30\\x09\\x31\\x15\\x00\\x26\\xff\\x7f\\x35\\x00\\x46\\xff\\x7f\\x75\\x10\\x95\\x02\\x81\\x02\\x05\\x01\\x09\\x38\\x15\\x81\\x25\\x7f\\x35\\x00\\x45\\x00\\x75\\x08\\x95\\x01\\x81\\x06\\xc0\\xc0 > functions/hid.GS2/report_desc
ln -s functions/hid.GS2 configs/c.1
fi
@@ -149,4 +184,11 @@ case "$1" in
start_usb_host
start_usb_dev
;;
restart_phy)
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/unbind
sleep 1
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/bind
start_usb_host
start_usb_dev
;;
esac

View File

@@ -57,7 +57,7 @@ start_usb_dev(){
fi
echo 2 > functions/hid.GS1/protocol
echo 4 > functions/hid.GS1/report_length
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
echo -ne \\x5\\x1\\x9\\x2\\xa1\\x1\\x9\\x1\\xa1\\x0\\x5\\x9\\x19\\x1\\x29\\x3\\x15\\x0\\x25\\x1\\x95\\x3\\x75\\x1\\x81\\x2\\x95\\x1\\x75\\x5\\x81\\x3\\x5\\x1\\x9\\x30\\x9\\x31\\x9\\x38\\x15\\x81\\x25\\x7f\\x75\\x8\\x95\\x3\\x81\\x6\\xc0\\xc0 > functions/hid.GS1/report_desc
ln -s functions/hid.GS1 configs/c.1
# touchpad
@@ -102,4 +102,11 @@ case "$1" in
start_usb_host
start_usb_dev
;;
restart_phy)
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/unbind
sleep 1
echo "4340000.usb" > /sys/bus/platform/drivers/dwc2/bind
start_usb_host
start_usb_dev
;;
esac

View File

@@ -1,5 +1,5 @@
#!/bin/sh
# kvmhwd Rev2.4
# kvmhwd Rev2.5
Alpha_OLED_RST_Pin=371
Beta_OLED_RST_Pin=502
@@ -25,7 +25,7 @@ init_alpha_hw(){
devmem 0x03001060 32 0x3 # GPIOA24
devmem 0x03001054 32 0x3 # GPIOA25
devmem 0x03001058 32 0x3 # GPIOA27
devmem 0x03001068 32 0x6 # GPIOA 18 UART1 RX
devmem 0x03001064 32 0x6 # GPIOA 19 UART1 TX
devmem 0x03001070 32 0x2 # GPIOA 28 UART2 TX
@@ -146,19 +146,7 @@ kvm_hw_detect(){
insmod /mnt/system/ko/i2c-algo-bit.ko
insmod /mnt/system/ko/i2c-gpio.ko
kvm_tmp=$(i2cdetect -ry 4 0x2c 0x2c | grep 2c)
if [ -n "$kvm_tmp" ]
then
echo "c" > /etc/kvm/hdmi_version
else
kvm_tmp1=$(i2cdetect -ry 4 0x2b 0x2b | grep 2b)
if [ -n "$kvm_tmp1" ]
then
echo "ux" > /etc/kvm/hdmi_version
else
echo "ue" > /etc/kvm/hdmi_version
fi
fi
kvm_hdmi_version_detect
kvm_tmp=$(i2cdetect -ry 5 0x3c 0x3c | grep 3c)
if [ -n "$kvm_tmp" ]
@@ -199,20 +187,19 @@ kvm_hw_init(){
fi
}
kvm_hdmi_version_detect(){
hdmi_tmp=$(i2cdetect -ry 4 0x2c 0x2c | grep 2c)
if [ -n "$hdmi_tmp" ]
then
echo "c" > /etc/kvm/hdmi_version
else
hdmi_tmp1=$(i2cdetect -ry 4 0x2b 0x2b | grep 2b)
if [ -n "$hdmi_tmp1" ]
then
echo "ux" > /etc/kvm/hdmi_version
kvm_hdmi_version_detect()
{
if i2cdetect -ry 4 0x2c 0x2c | grep -qw "2c"; then
echo "c" > /etc/kvm/hdmi_version
elif i2cdetect -ry 4 0x2b 0x2b | grep -qw "2b"; then
if i2cdetect -ry 4 0x44 0x44 | grep -qw "44"; then
echo "ux" > /etc/kvm/hdmi_version
else
echo "d" > /etc/kvm/hdmi_version
fi
else
echo "ue" > /etc/kvm/hdmi_version
echo "ue" > /etc/kvm/hdmi_version
fi
fi
}
case "$1" in

View File

@@ -15,10 +15,15 @@ EOF
ipnum=$(( (a<<24) + (b<<16) + (c<<8) + d ))
mask=$(( 0xFFFFFFFF << (32-netid) & 0xFFFFFFFF ))
gwnum=$(( (ipnum & mask) | 1 ))
if [ $gwnum -eq $ipnum ]; then
broadcast=$(( (ipnum & mask) | (0xFFFFFFFF & ~mask) ))
gwnum=$(( broadcast - 1 ))
fi
echo "$(( (gwnum>>24)&255 )).$(( (gwnum>>16)&255 )).$(( (gwnum>>8)&255 )).$(( gwnum&255 ))"
}
start() {
ip addr flush dev eth0
if [ -e /boot/eth.nodhcp ]; then
while IFS= read -r line || [ -n "$line" ]; do
line=$(clean_line "$line")
@@ -27,6 +32,20 @@ start() {
inet="$1"
gw="$2"
[ -z "$inet" ] && continue
# Check if inet contains a valid netmask, if not, add default /16
case "$inet" in
*/*)
# Already has netmask, check if valid (1-32)
netid_check=${inet#*/}
if ! echo "$netid_check" | grep -qE '^[0-9]+$' || [ $netid_check -lt 1 ] 2>/dev/null || [ $netid_check -gt 32 ] 2>/dev/null; then
inet="${inet%/*}/16"
fi
;;
*)
# No netmask, add default /16
inet="$inet/16"
;;
esac
addr=${inet%/*}
netid=${inet#*/}
[ -z "$gw" ] && gw=$(calc_gw "$addr" "$netid")

View File

@@ -2,24 +2,26 @@
. /etc/profile
APFLAG_FILE=/tmp/wifiap
gen_hostapd_conf() {
ssid="${1}"
pass="${2}"
echo "ctrl_interface=/var/run/hostapd"
echo "ctrl_interface_group=0"
echo "ssid=${ssid}"
echo "hw_mode=g"
echo "channel=1"
echo "beacon_int=100"
echo "dtim_period=2"
echo "max_num_sta=255"
echo "rts_threshold=-1"
echo "fragm_threshold=-1"
echo "macaddr_acl=0"
echo "auth_algs=3"
echo "wpa=2"
echo "wpa_passphrase=${pass}"
echo "ieee80211n=1"
ssid="${1}"
pass="${2}"
echo "ctrl_interface=/var/run/hostapd"
echo "ctrl_interface_group=0"
echo "ssid=${ssid}"
echo "hw_mode=g"
echo "channel=1"
echo "beacon_int=100"
echo "dtim_period=2"
echo "max_num_sta=255"
echo "rts_threshold=-1"
echo "fragm_threshold=-1"
echo "macaddr_acl=0"
echo "auth_algs=3"
echo "wpa=2"
echo "wpa_passphrase=${pass}"
echo "ieee80211n=1"
}
gen_udhcpd_conf() {
@@ -61,19 +63,16 @@ start() {
chown root:root /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
chmod 644 /etc/kvm/wifi.ssid /etc/kvm/wifi.pass
fi
if [ -e /etc/kvm/wifi.ssid ]
then
ssid=`cat /etc/kvm/wifi.ssid`
if [ -e /etc/kvm/wifi.ssid ]; then
ssid=$(cat /etc/kvm/wifi.ssid)
fi
if [ -e /etc/kvm/wifi.pass ]
then
pass=`cat /etc/kvm/wifi.pass`
if [ -e /etc/kvm/wifi.pass ]; then
pass=$(cat /etc/kvm/wifi.pass)
fi
echo "ctrl_interface=/var/run/wpa_supplicant" > /etc/wpa_supplicant.conf
wpa_passphrase "$ssid" "$pass" >> /etc/wpa_supplicant.conf
echo "ctrl_interface=/var/run/wpa_supplicant" >/etc/wpa_supplicant.conf
wpa_passphrase "$ssid" "$pass" >>/etc/wpa_supplicant.conf
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf
if [ ! -e /boot/wifi.nodhcp ]
then
if [ ! -e /boot/wifi.nodhcp ]; then
(udhcpc -i wlan0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.wlan0.pid) &
fi
}
@@ -82,33 +81,27 @@ ap_start() {
echo "wifi mode: ap"
id2=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 2))
id3=$(printf "%d" 0x$(sha512sum /sys/class/cvi-base/base_uid | head -c 4 | tail -c 2))
if [ "$id2" = "$id3" ]
then
if [ "$id2" = "$id3" ]; then
id2=$((id2 + 1))
fi
if [ "$id2" -ge 255 ]
then
if [ "$id2" -ge 255 ]; then
id2=253
fi
if [ "$id3" -ge 255 ]
then
if [ "$id3" -ge 255 ]; then
id3=254
fi
ssid=""
pass=""
if [ -e /kvmapp/kvm/ap.ssid ]
then
ssid=`cat /kvmapp/kvm/ap.ssid`
if [ -e /kvmapp/kvm/ap.ssid ]; then
ssid=$(cat /kvmapp/kvm/ap.ssid)
fi
if [ -e /kvmapp/kvm/ap.pass ]
then
pass=`cat /kvmapp/kvm/ap.pass`
if [ -e /kvmapp/kvm/ap.pass ]; then
pass=$(cat /kvmapp/kvm/ap.pass)
fi
gen_hostapd_conf "$ssid" "$pass" > /etc/hostapd.conf
gen_hostapd_conf "$ssid" "$pass" >/etc/hostapd.conf
ipv4_prefix=10.$id3.$id2
if [ ! -e /etc/udhcpd.wlan0.conf ]
then
gen_udhcpd_conf wlan0 "${ipv4_prefix}" > /etc/udhcpd.wlan0.conf
if [ ! -e /etc/udhcpd.wlan0.conf ]; then
gen_udhcpd_conf wlan0 "${ipv4_prefix}" >/etc/udhcpd.wlan0.conf
fi
# gen_dnsmasq_conf "${ipv4_prefix}" > /etc/dnsmasq.conf
@@ -126,50 +119,52 @@ ap_start() {
# dnsmasq --pid-file=/tmp/dnsmasq.run -C /etc/dnsmasq.conf
hostapd -B -i wlan0 /etc/hostapd.conf
udhcpd -S /etc/udhcpd.wlan0.conf
if [ ! -f "$APFLAG_FILE" ]; then
touch "$APFLAG_FILE"
fi
}
stop() {
ps -ef|grep hostapd|grep -v grep|awk '{print $1}'|xargs kill -2 || true
ps -ef|grep "udhcpd -S /etc/udhcpd.wlan0.conf" |grep -v grep|awk '{print $1}'|xargs kill -2 || true
killall wpa_supplicant || true
if [ -e /run/udhcpc.wlan0.pid ]
then
kill `cat /run/udhcpc.wlan0.pid` || true
rm -f /run/udhcpc.wlan0.pid
fi
if [ -e /var/run/udhcpd.wlan0.pid ]
then
kill `cat /var/run/udhcpd.wlan0.pid` || true
rm -f /var/run/udhcpd.wlan0.pid
fi
if [ -e /tmp/dnsmasq.run ]
then
kill `cat /tmp/dnsmasq.run` || true
rm -f /tmp/dnsmasq.run
fi
# if [ -e /etc/wpa_supplicant.conf]
# then
# echo > /etc/wpa_supplicant.conf
# fi
airmon-ng stop wlan0mon || true
ps -ef | grep hostapd | grep -v grep | awk '{print $1}' | xargs kill -2 || true
ps -ef | grep "udhcpd -S /etc/udhcpd.wlan0.conf" | grep -v grep | awk '{print $1}' | xargs kill -2 || true
killall wpa_supplicant || true
if [ -e /run/udhcpc.wlan0.pid ]; then
kill $(cat /run/udhcpc.wlan0.pid) || true
rm -f /run/udhcpc.wlan0.pid
fi
if [ -e /var/run/udhcpd.wlan0.pid ]; then
kill $(cat /var/run/udhcpd.wlan0.pid) || true
rm -f /var/run/udhcpd.wlan0.pid
fi
if [ -e /tmp/dnsmasq.run ]; then
kill $(cat /tmp/dnsmasq.run) || true
rm -f /tmp/dnsmasq.run
fi
# if [ -e /etc/wpa_supplicant.conf]
# then
# echo > /etc/wpa_supplicant.conf
# fi
airmon-ng stop wlan0mon || true
if [ -f "$APFLAG_FILE" ]; then
rm "$APFLAG_FILE"
fi
}
restart() {
stop
start
stop
start
}
if [ "${1}" = "start" ]
then
start
elif [ "${1}" = "stop" ]
then
stop
elif [ "${1}" = "ap" ]
then
if [ "${1}" = "start" ]; then
start
elif [ "${1}" = "stop" ]; then
stop
ap_start
elif [ "${1}" = "restart" ]
then
restart
elif [ "${1}" = "ap" ]; then
stop
ap_start
elif [ "${1}" = "restart" ]; then
restart
fi

View File

@@ -32,6 +32,18 @@ case "$1" in
iptables -C OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP 2>/dev/null || \
iptables -A OUTPUT -o eth0 -p tcp --sport 8000 -m state --state ESTABLISHED -j DROP
# Logo selection
if [ -f /boot/logo.ico ]; then
if [ ! -f /kvmapp/server/web/original.ico ]; then
mv /kvmapp/server/web/sipeed.ico /kvmapp/server/web/original.ico
cp /boot/logo.ico /kvmapp/server/web/sipeed.ico
fi
else
if [ -f /kvmapp/server/web/original.ico ]; then
mv /kvmapp/server/web/original.ico /kvmapp/server/web/sipeed.ico
fi
fi
# Start services
cp -r /kvmapp/kvm_system /tmp/
/tmp/kvm_system/kvm_system &

249
kvmapp/system/init.d/S96picoclaw Executable file
View File

@@ -0,0 +1,249 @@
#!/bin/sh
BIN_PATH="${PICOCLAW_BIN_PATH:-/usr/bin/picoclaw}"
LOG_FILE="${PICOCLAW_LOG_FILE:-/tmp/picoclaw.log}"
BIN_NAME="$(basename "$BIN_PATH")"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
resolve_user_home() {
user_name="$(id -un 2>/dev/null || echo root)"
user_home="$(awk -F: -v user="$user_name" '$1 == user { print $6; exit }' /etc/passwd)"
if [ -n "$user_home" ] && [ -d "$user_home" ]; then
printf '%s\n' "$user_home"
return 0
fi
if [ -n "${HOME:-}" ] && [ -d "${HOME}" ]; then
printf '%s\n' "$HOME"
return 0
fi
printf '%s\n' "/root"
}
setup_picoclaw_home() {
USER_HOME="$(resolve_user_home)"
PICOCLAW_HOME="${PICOCLAW_HOME:-$USER_HOME/.picoclaw}"
HOME="$USER_HOME"
export HOME
export PICOCLAW_HOME
mkdir -p "$PICOCLAW_HOME" || {
echo "failed to create picoclaw home: $PICOCLAW_HOME"
return 1
}
PICOCLAW_PID_FILE="${PICOCLAW_PID_FILE:-$PICOCLAW_HOME/.picoclaw.pid}"
export PICOCLAW_PID_FILE
cd "$PICOCLAW_HOME" || {
echo "failed to enter picoclaw home: $PICOCLAW_HOME"
return 1
}
}
setup_runtime_env() {
[ -x "$BIN_PATH" ] || {
echo "picoclaw binary not found: $BIN_PATH"
return 1
}
setup_picoclaw_home || return 1
}
read_pid_file() {
[ -f "$PICOCLAW_PID_FILE" ] || return 1
pid="$(sed -n '1p' "$PICOCLAW_PID_FILE" 2>/dev/null | tr -d '[:space:]')"
case "$pid" in
''|*[!0-9]*)
return 1
;;
esac
printf '%s\n' "$pid"
}
is_gateway_pid() {
pid="$1"
[ -n "$pid" ] || return 1
[ -r "/proc/$pid/cmdline" ] || return 1
cmd_path="$(tr '\000' '\n' <"/proc/$pid/cmdline" 2>/dev/null | sed -n '1p')"
subcommand="$(tr '\000' '\n' <"/proc/$pid/cmdline" 2>/dev/null | sed -n '2p')"
[ "$(basename "$cmd_path")" = "$BIN_NAME" ] && [ "$subcommand" = "gateway" ] && return 0
return 1
}
find_gateway_pid() {
for proc_dir in /proc/[0-9]*; do
[ -d "$proc_dir" ] || continue
pid="${proc_dir#/proc/}"
if is_gateway_pid "$pid"; then
printf '%s\n' "$pid"
return 0
fi
done
return 1
}
cleanup_stale_pid_file() {
[ -f "$PICOCLAW_PID_FILE" ] || return 0
pid="$(read_pid_file 2>/dev/null)" || {
rm -f "$PICOCLAW_PID_FILE"
return 0
}
if ! is_gateway_pid "$pid"; then
echo "picoclaw stale pid file removed: $PICOCLAW_PID_FILE"
rm -f "$PICOCLAW_PID_FILE"
fi
}
gateway_running_pid() {
pid="$(read_pid_file 2>/dev/null)" && is_gateway_pid "$pid" && {
printf '%s\n' "$pid"
return 0
}
cleanup_stale_pid_file
pid="$(find_gateway_pid 2>/dev/null)" || return 1
printf '%s\n' "$pid" >"$PICOCLAW_PID_FILE" 2>/dev/null || true
printf '%s\n' "$pid"
}
resolve_kvm_control_source() {
for candidate in \
"/kvmapp/picoclaw/skills/kvm-control" \
"/kvmapp/skills/kvm-control" \
"$SCRIPT_DIR/../../../picoclaw/skills/kvm-control"
do
if [ -d "$candidate" ] && [ -f "$candidate/SKILL.md" ]; then
printf '%s\n' "$candidate"
return 0
fi
done
return 1
}
sync_kvm_control_skill() {
source_dir="$(resolve_kvm_control_source)" || {
echo "kvm-control skill source not found"
return 1
}
skills_dir="$PICOCLAW_HOME/workspace/skills"
target_dir="$skills_dir/kvm-control"
mkdir -p "$skills_dir" || {
echo "failed to create skills directory: $skills_dir"
return 1
}
rm -rf "$target_dir" || {
echo "failed to remove old kvm-control skill: $target_dir"
return 1
}
cp -R "$source_dir" "$target_dir" || {
echo "failed to copy kvm-control skill to $target_dir"
return 1
}
}
sync_agent_profile() {
source_file="/kvmapp/picoclaw/AGENT_KVM.md"
target_file="$PICOCLAW_HOME/workspace/AGENT.md"
workspace_dir="$PICOCLAW_HOME/workspace"
[ -f "$source_file" ] || {
echo "agent profile source not found: $source_file"
return 1
}
mkdir -p "$workspace_dir" || {
echo "failed to create workspace directory: $workspace_dir"
return 1
}
cp -f "$source_file" "$target_file" || {
echo "failed to copy agent profile to $target_file"
return 1
}
}
start_service() {
setup_runtime_env || return 1
if pid="$(gateway_running_pid)"; then
echo "picoclaw gateway already running (PID: $pid)"
return 0
fi
if [ ! -f "$PICOCLAW_HOME/config.json" ]; then
echo "picoclaw config not found: $PICOCLAW_HOME/config.json"
return 1
fi
"$BIN_PATH" gateway >>"$LOG_FILE" 2>&1 &
gateway_pid="$!"
printf '%s\n' "$gateway_pid" >"$PICOCLAW_PID_FILE" || {
echo "failed to write picoclaw pid file: $PICOCLAW_PID_FILE"
return 1
}
echo "picoclaw gateway started (PID: $gateway_pid)"
}
onboard_service() {
setup_runtime_env || return 1
"$BIN_PATH" onboard >>"$LOG_FILE" 2>&1 || return 1
sync_kvm_control_skill || return 1
sync_agent_profile || return 1
}
stop_service() {
setup_picoclaw_home || return 1
pid="$(gateway_running_pid 2>/dev/null)" || {
cleanup_stale_pid_file
return 0
}
kill "$pid" 2>/dev/null || true
count=0
while is_gateway_pid "$pid"; do
count=$((count + 1))
if [ "$count" -ge 15 ]; then
echo "picoclaw gateway did not stop after TERM, killing PID: $pid"
kill -9 "$pid" 2>/dev/null || true
break
fi
sleep 1
done
rm -f "$PICOCLAW_PID_FILE"
}
case "$1" in
start)
start_service
;;
stop)
stop_service
echo "OK"
;;
onboard)
onboard_service
;;
restart)
stop_service
start_service
echo "OK"
;;
*)
echo "Usage: $0 {start|stop|onboard|restart}"
exit 1
;;
esac

View File

@@ -21,18 +21,25 @@ PKG_URL_LATEST="https://pkgs.tailscale.com/stable/tailscale_latest_riscv64.tgz"
exit 1
VERSION=$(/usr/sbin/$DAEMON --version|sed -n '1p'|xargs echo -n)
[ -x /usr/bin/tailscale ] || echo "/usr/bin/tailscale not found, your installation of tailscale may be broken"
[ -x /usr/bin/tailscale ] ||
(echo "/usr/bin/tailscale not found, your installation of tailscale may be broken" && exit 1)
# just for those need forwarding
[ ! -f /etc/sysctl.d/99-tailscale.conf ] &&
mkdir -p /etc/sysctl.d/ &&
echo "missing /etc/sysctl.d/99-tailscale.conf, try make it below:" &&
(tee /etc/sysctl.d/99-tailscale.conf <<EOF
net.ipv4.ip_forward = 1
net.ipv6.conf.all.forwarding = 1
EOF
) &&
echo "if this message repeats showing, please look at $0 if you need forwarding"
# Clean up old forwarding configuration if it exists
if [ -f /etc/sysctl.d/99-tailscale.conf ]; then
echo "Found old forwarding configuration, cleaning up..."
rm -f /etc/sysctl.d/99-tailscale.conf
sysctl -w net.ipv4.ip_forward=0 >/dev/null 2>&1
sysctl -w net.ipv6.conf.all.forwarding=0 >/dev/null 2>&1
echo "Cleanup completed. IPv4/IPv6 forwarding disabled."
# Trigger IPv6 address renewal on all interfaces
for iface in $(ls /sys/class/net/ | grep -v lo); do
echo 0 > /proc/sys/net/ipv6/conf/$iface/forwarding 2>/dev/null
sysctl -w net.ipv6.conf.$iface.accept_ra=2 >/dev/null 2>&1
done
echo "If you need exit node features, please configure manually."
fi
case "$1" in
start)
@@ -40,10 +47,14 @@ case "$1" in
value=$(cat /etc/kvm/GOMEMLIMIT)
export GOMEMLIMIT="${value}MiB"
else
export GOMEMLIMIT=1024MiB
export GOMEMLIMIT=512MiB
fi
echo "GOMEMLIMIT set to ${GOMEMLIMIT}"
# Ensure directories exist
mkdir -p /var/lib/tailscale /var/run/tailscale
printf "Starting $DAEMON[$VERSION]: "
start-stop-daemon -S -bmq -p "$PIDFILE" -x "/usr/sbin/$DAEMON" -- \
--state=/var/lib/tailscale/tailscaled.state \
@@ -51,67 +62,25 @@ case "$1" in
--port=${PORT} \
$FLAGS
if [ $? = 0 ]; then
echo "OK"
tailscale set --accept-dns=false
# example to make your nanoKVM an exit node
# tailscale set --advertise-exit-node --advertise-routes=192.168.0.0/16
else
echo "FAIL"
fi
sleep 5
echo "OK"
tailscale set --accept-dns=false
else
echo "FAIL"
fi
;;
stop)
printf "Stopping $DAEMON: "
start-stop-daemon -K -p "$PIDFILE"
[ $? = 0 ] && (echo "OK"; rm -f "$PIDFILE") || echo "FAIL"
printf "cleaning tailscaled: "
/usr/sbin/$DAEMON --cleanup &>/dev/null
/usr/sbin/$DAEMON --cleanup >/dev/null 2>&1
[ $? = 0 ] && echo "OK" || echo "FAIL"
;;
restart|reload)
$0 stop
$0 start
;;
doc)
cat <<EOF
To use tailscale, you need to meet these conditions below:
1. Both tailscale and tailscaled were installed.
2. At least one tailscale's account were registered.
(https://login.tailscale.com/start)
3. Your NanoKVM device must keep online.
Then, follow the steps below:
1. Login in https://login.tailscale.com on your PC
to enter into yout admin console.
2. Run 'tailscale login' on your device, and copy the link showed
to open on your PC, and confirm the auth.
3. Congratulations, your NanoKVM device is now on the tailnet, try to
visit it from all your device which on the same tailnet.
4. run 'tailscale set --webclient' and manage your device
on the web interface from localnet and tailenet.
Added: no more action to be repeat after your device reboot.
EOF
echo ""
cat <<EOF
为了正常使用 tailscale, 你需要满足以下几个条件:
1. tailscale 和 tailscaled 这两个静态链接的二进制程序
都已经正确安装在系统上。
2. 至少注册一个 tailscale 的帐号才能使用其服务。
(https://login.tailscale.com/start)
3. 你的 NanoKVM 设备必须保持在线。
然后,跟着以下步骤操作:
1. 在你的电脑上登录 https://login.tailscale.com 以进入控制台。
2. 在你的 NanoKVM ssh 终端上执行 'tailscale login', 然后复制
出现的链接到浏览器上,登录并通过验证。
3. 祝贺,你的 NanoKVM 现在已经加入了 tailnet 然后你可以从任意
同样已加入同一 tailnet 的设备去访问你的 NanoKVM。
4. 执行 'tailscale set --webclient' 然后你就可以从 '局域网' 和
'tailnet' 来访问特定网页,用来管理你的设备。
补充: 不需要重复上面的操作,哪怕你的设备重启过。
EOF
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1

98
scripts/README.md Normal file
View File

@@ -0,0 +1,98 @@
# Release packaging
These scripts assemble the application update package that NanoKVM devices pull
over the air: `nanokvm_<version>.tar.gz` plus its `latest.json` manifest.
| Script | Purpose |
|---|---|
| `build-in-container.sh` | Builds every riscv64 artifact (`kvm_system`, `libkvm.so`, `NanoKVM-Server`). Runs inside the `nanokvm-builder` image only. |
| `package.sh` | Stages the package tree, creates the tarball, and writes `latest.json`. |
| `compare-release.sh` | Diffs a freshly built package against the currently published one. Informational. |
| `verify-release-assets.sh` | Checks the three GitHub Release assets before publishing or promotion. |
| `verify-release-tag.sh` | Requires an annotated numeric tag whose commit is on `main`. |
## What the updater expects
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>/`.
- **`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).
- **`sha512` is base64, not hex.** `update.go` compares against
`base64(raw sha512 digest)`. A hex digest will fail verification on device.
- **`/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.
## Building a release
The frontend needs Node and pnpm on the host; everything riscv64 needs the
builder image (see `docker/Dockerfile`).
```bash
make release VERSION=2.4.4
```
That is equivalent to:
```bash
make release-build # kvm_system + libkvm.so + NanoKVM-Server, in Docker
make web # web/dist
make package VERSION=2.4.4 # build/release/{nanokvm_2.4.4.tar.gz,latest.json}
```
In CI this runs as the **NanoKVM Package** workflow. Pull requests and manual
runs only create Actions artifacts. For a public release, run **NanoKVM Create
Tag**, then run **NanoKVM Release** and choose prerelease, stable, or promotion.
Publishing attaches three assets:
Publishing is one-shot: an existing Release or draft is an error, and only a
published prerelease can be promoted.
- `nanokvm_<version>.tar.gz`
- `latest.json`
- `sha256.txt`
The Actions artifact also includes `BUILD_INFO.txt` with the source commit,
workflow run, immutable builder image digest, and both checksum encodings; that
provenance file is not attached to the GitHub release. Uploading the tarball and
`latest.json` to the CDN is what actually offers the update to devices in the
field, so that step stays manual. `sha256.txt` is only for users verifying a
manual download and does not change the on-device `latest.json` contract.
## Where each file in the package comes from
| Package path | Source |
|---|---|
| `version` | the requested version |
| `server/NanoKVM-Server` | `server/build.sh` (BoringCrypto, RPATH `$ORIGIN/dl_lib`) |
| `server/dl_lib/` | whatever the `kvm_vision` build emits, with any library it does not emit backfilled from the tracked `server/dl_lib/` |
| `server/web/` | `web/dist/` |
| `kvm_system/kvm_system` | `support/sg2002` `build kvm_system` |
| `system/tool/` | prebuilt binaries in `tools/nanokvm_update_edid/` |
| `kvm/` | default runtime state (resolution, fps, quality) |
| everything else | tracked `kvmapp/` |
Note that `kvm/` ships default runtime state, and `install.go` replaces
`/kvmapp` wholesale, so an update resets those values on the device. That is
long-standing behaviour, not something these scripts introduce.
## The two copies of libkvm.so
`NanoKVM-Server` is cgo-linked against the **tracked** `server/dl_lib/libkvm.so`
(`server/common/kvm_vision.go`: `-L../dl_lib -lkvm`), but the package ships the
library the `kvm_vision` build just produced. Those are two different files, and
the tracked one can lag well behind — published releases have shipped this
mismatch for a long time.
Because a symbol the binary imports could in principle be absent from the
shipped library, and that would only surface as a crash on a real device,
`build-in-container.sh` checks the shipped `libkvm.so` still exports every
symbol `NanoKVM-Server` actually imports from it, and fails the build otherwise.

144
scripts/build-in-container.sh Executable file
View File

@@ -0,0 +1,144 @@
#!/bin/bash
#
# Build every riscv64 artifact of a release, from inside the nanokvm-builder
# image (docker/Dockerfile). Not meant to be run on the host: it needs the
# riscv64 musl toolchain and the patched MaixCDK checkout that the image ships.
#
# Produces:
# kvmapp/kvm_system/kvm_system kvm_system daemon
# kvmapp/server/dl_lib/ video libraries, including a fresh libkvm.so
# server/NanoKVM-Server Go server (BoringCrypto, RPATH $ORIGIN/dl_lib)
set -euo pipefail
# docker/entrypoint sets HOME for the build user. support/sg2002/build resolves
# both MaixCDK and the source tree through ~, so a wrong HOME would send the
# whole build at /root; say so plainly rather than emitting "directory missing".
BUILD_HOME="${BUILD_HOME:-/home/build}"
if [ "${HOME:-}" != "$BUILD_HOME" ]; then
echo "[ERROR] HOME is '${HOME:-unset}', expected $BUILD_HOME" >&2
echo " run this inside the builder image via the Makefile" >&2
exit 1
fi
MAIXCDK_PATH="$HOME/MaixCDK"
NANOKVM_PATH="$HOME/NanoKVM"
for dir in "$MAIXCDK_PATH" "$NANOKVM_PATH"; do
if [ ! -d "$dir" ]; then
echo "[ERROR] $dir not found - is this running inside nanokvm-builder?" >&2
exit 1
fi
done
# Check the toolchain up front. builder-image reuses any existing image, so an
# image built before a tooling change silently lacks it - and without this the
# SDK build would run for minutes before server/build.sh failed at the end.
for tool in go riscv64-unknown-linux-musl-gcc patchelf; do
if ! command -v "$tool" >/dev/null 2>&1; then
echo "[ERROR] '$tool' is missing from the builder image" >&2
echo " the image is out of date; rebuild it with: make rebuild-image" >&2
exit 1
fi
done
# The SDK tree is owned by the ids baked into the image (DOCKER_UID/DOCKER_GID),
# while the entrypoint drops to the caller's ids. If they disagree, syncing
# components fails partway through a long build; catch it here instead.
if [ ! -w "$MAIXCDK_PATH/components" ]; then
echo "[ERROR] $MAIXCDK_PATH/components is not writable by $(id -u):$(id -g)" >&2
echo " the image was built for different ids; rebuild it with:" >&2
echo " make rebuild-image" >&2
exit 1
fi
# shellcheck disable=SC1091
. "$MAIXCDK_PATH/bin/activate"
echo "::group::support: sync MaixCDK components"
cd "$NANOKVM_PATH/support/sg2002"
# The image bakes support/sg2002/additional/ into MaixCDK's components at image
# build time, and ./build only re-copies them when components/kvm is missing.
# Refresh unconditionally so a cached image never yields stale libraries.
./build update_lib
echo "::endgroup::"
echo "::group::support: build kvm_system"
./build kvm_system
./build kvm_system add_to_kvmapp
echo "::endgroup::"
echo "::group::support: build kvm_vision (libkvm.so)"
./build kvm_vision
./build kvm_vision add_to_kvmapp
echo "::endgroup::"
echo "::group::server: cross-compile NanoKVM-Server"
cd "$NANOKVM_PATH/server"
./build.sh
echo "::endgroup::"
# support/sg2002/build reports "Build Error!" without a non-zero exit status for
# some failure paths, so assert on the artifacts rather than trusting $?.
echo "[INFO] verifying artifacts"
missing=0
for artifact in \
"$NANOKVM_PATH/kvmapp/kvm_system/kvm_system" \
"$NANOKVM_PATH/kvmapp/server/dl_lib/libkvm.so" \
"$NANOKVM_PATH/server/NanoKVM-Server"
do
if [ -f "$artifact" ]; then
echo " ok ${artifact#$NANOKVM_PATH/}"
else
echo " MISSING ${artifact#$NANOKVM_PATH/}" >&2
missing=1
fi
done
if [ "$missing" -ne 0 ]; then
echo "[ERROR] build did not produce all expected artifacts" >&2
exit 1
fi
# NanoKVM-Server is cgo-linked against the tracked server/dl_lib/libkvm.so
# (server/common/kvm_vision.go: -L../dl_lib -lkvm), but the package ships the
# freshly built one from kvm_vision. Those are different files, so confirm the
# shipped library still exports every symbol the binary actually imports from
# it. Without this a dropped symbol only shows up as a crash on a real device.
echo "[INFO] verifying shipped libkvm.so satisfies NanoKVM-Server"
if ! command -v readelf >/dev/null 2>&1; then
echo "[WARN] readelf unavailable, skipping ABI check"
else
exported() {
readelf --dyn-syms --wide "$1" 2>/dev/null \
| awk '$7 != "UND" && $8 != "" { print $8 }' \
| sed 's/@.*//' | LC_ALL=C sort -u
}
imported() {
readelf --dyn-syms --wide "$1" 2>/dev/null \
| awk '$7 == "UND" && $8 != "" { print $8 }' \
| sed 's/@.*//' | LC_ALL=C sort -u
}
linked_lib="$NANOKVM_PATH/server/dl_lib/libkvm.so"
shipped_lib="$NANOKVM_PATH/kvmapp/server/dl_lib/libkvm.so"
server_bin="$NANOKVM_PATH/server/NanoKVM-Server"
# Symbols the binary imports that the link-time library provides, i.e. the
# ones libkvm.so is actually responsible for at runtime.
needed=$(comm -12 <(imported "$server_bin") <(exported "$linked_lib"))
if [ -z "$needed" ]; then
echo "[WARN] no libkvm symbols resolved; skipping ABI check"
else
absent=$(comm -23 <(printf '%s\n' "$needed") <(exported "$shipped_lib"))
if [ -n "$absent" ]; then
echo "[ERROR] shipped libkvm.so is missing symbols NanoKVM-Server needs:" >&2
printf ' %s\n' $absent >&2
exit 1
fi
echo " ok $(printf '%s\n' "$needed" | wc -l | tr -d ' ') libkvm symbols resolve"
fi
fi
echo "[DONE] riscv64 artifacts built"

103
scripts/compare-release.sh Executable file
View File

@@ -0,0 +1,103 @@
#!/bin/bash
#
# Compare a freshly built package against the currently published release.
#
# Purely informational: it exits 0 whatever it finds. The point is to make the
# delta reviewable before the tarball is published, since the package is what
# every device pulls over OTA. Unexpected entries here (a library that vanished,
# an init script that changed without a matching commit) are worth a look.
#
# Usage: scripts/compare-release.sh <new-tarball> [base-url]
set -uo pipefail
NEW_TARBALL="${1:-}"
BASE_URL="${2:-https://cdn.sipeed.com/nanokvm}"
if [ -z "$NEW_TARBALL" ] || [ ! -f "$NEW_TARBALL" ]; then
echo "Usage: $0 <new-tarball> [base-url]" >&2
exit 1
fi
WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT
echo "[INFO] fetching published manifest from $BASE_URL/latest.json"
if ! curl -fsSL "$BASE_URL/latest.json" -o "$WORK/latest.json"; then
echo "[WARN] could not fetch latest.json - skipping comparison"
exit 0
fi
cat "$WORK/latest.json"
OLD_NAME="$(sed -n 's/.*"name"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$WORK/latest.json")"
if [ -z "$OLD_NAME" ]; then
echo "[WARN] no \"name\" in latest.json - skipping comparison"
exit 0
fi
echo "[INFO] downloading published package $OLD_NAME"
if ! curl -fsSL "$BASE_URL/$OLD_NAME" -o "$WORK/$OLD_NAME"; then
echo "[WARN] could not download $OLD_NAME - skipping comparison"
exit 0
fi
mkdir -p "$WORK/old" "$WORK/new"
if ! tar xzf "$WORK/$OLD_NAME" -C "$WORK/old"; then
echo "[WARN] could not extract $OLD_NAME - skipping comparison"
exit 0
fi
if ! tar xzf "$NEW_TARBALL" -C "$WORK/new"; then
echo "[WARN] could not extract $(basename "$NEW_TARBALL") - skipping comparison"
exit 0
fi
# Strip the nanokvm_<version>/ prefix so the two trees are comparable.
OLD_ROOT="$(find "$WORK/old" -mindepth 1 -maxdepth 1 -type d | head -1)"
NEW_ROOT="$(find "$WORK/new" -mindepth 1 -maxdepth 1 -type d | head -1)"
if [ -z "$OLD_ROOT" ] || [ -z "$NEW_ROOT" ]; then
echo "[WARN] could not locate a package root directory - skipping comparison"
exit 0
fi
( cd "$OLD_ROOT" && find . -type f | sed 's|^\./||' | LC_ALL=C sort ) > "$WORK/old.list"
( cd "$NEW_ROOT" && find . -type f | sed 's|^\./||' | LC_ALL=C sort ) > "$WORK/new.list"
# An empty inventory would make every section below print "(none)", which reads
# identically to "verified, nothing changed". Refuse to imply that.
if [ ! -s "$WORK/old.list" ] || [ ! -s "$WORK/new.list" ]; then
echo "[WARN] one of the packages produced an empty file list - comparison unreliable, skipping"
exit 0
fi
echo
echo "=============================================================="
echo " $(basename "$OLD_ROOT") -> $(basename "$NEW_ROOT")"
echo "=============================================================="
printf ' files: %s -> %s\n' "$(wc -l < "$WORK/old.list" | tr -d ' ')" \
"$(wc -l < "$WORK/new.list" | tr -d ' ')"
echo
echo "--- added ----------------------------------------------------"
comm -13 "$WORK/old.list" "$WORK/new.list" | sed 's/^/ + /' || true
echo
echo "--- removed --------------------------------------------------"
comm -23 "$WORK/old.list" "$WORK/new.list" | sed 's/^/ - /' || true
echo
echo "--- changed --------------------------------------------------"
changed=0
while IFS= read -r file; do
if ! cmp -s "$OLD_ROOT/$file" "$NEW_ROOT/$file"; then
old_size="$(wc -c < "$OLD_ROOT/$file" | tr -d ' ')"
new_size="$(wc -c < "$NEW_ROOT/$file" | tr -d ' ')"
printf ' ~ %-52s %s -> %s bytes\n' "$file" "$old_size" "$new_size"
changed=$((changed + 1))
fi
done < <(comm -12 "$WORK/old.list" "$WORK/new.list")
[ "$changed" -eq 0 ] && echo " (none)"
echo
echo "[INFO] comparison complete"

216
scripts/package.sh Executable file
View File

@@ -0,0 +1,216 @@
#!/bin/bash
#
# Assemble a NanoKVM release package: nanokvm_<version>.tar.gz + latest.json.
#
# The layout and the manifest fields are dictated by the on-device updater:
# - server/service/application/version.go parses latest.json and derives the
# 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>/.
#
# Build artifacts are expected to be in place already (see
# scripts/build-in-container.sh and the "web" target in the Makefile):
# server/NanoKVM-Server riscv64 server binary
# kvmapp/kvm_system/kvm_system kvm_system daemon
# kvmapp/server/dl_lib/libkvm.so freshly built video library (optional)
# web/dist/ built frontend
#
# Usage: scripts/package.sh <version>
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"
VERSION="${1:-}"
if [ -z "$VERSION" ]; then
echo "Usage: $0 <version> e.g. $0 2.4.4" >&2
exit 1
fi
# The updater rejects file names outside [a-zA-Z0-9._-] (update_offline.go),
# and the version string ends up in the file name, so validate it up front.
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "[ERROR] invalid version '$VERSION', expected MAJOR.MINOR.PATCH" >&2
exit 1
fi
OUT="$ROOT/build/release"
STAGE="$OUT/nanokvm_$VERSION"
TARBALL="$OUT/nanokvm_$VERSION.tar.gz"
MANIFEST="$OUT/latest.json"
require_file() {
if [ ! -f "$1" ]; then
echo "[ERROR] missing build artifact: ${1#"$ROOT"/}" >&2
echo " $2" >&2
exit 1
fi
}
# A host-architecture build is indistinguishable from a cross-compiled one by
# name alone, and NanoKVM-Server is gitignored, so nothing else would catch it.
# Refuse to package anything that is not riscv64 (ELF e_machine 243).
require_riscv64() {
local path="$1" magic machine
magic=$(od -An -tx1 -N4 "$path" | tr -d ' \n')
if [ "$magic" != "7f454c46" ]; then
echo "[ERROR] not an ELF object: ${path#"$ROOT"/}" >&2
exit 1
fi
machine=$(od -An -tu1 -j18 -N1 "$path" | tr -d ' \n')
if [ "$machine" != "243" ]; then
echo "[ERROR] ${path#"$ROOT"/} is not riscv64 (ELF e_machine=$machine)" >&2
echo " a host-architecture build must never be packaged" >&2
exit 1
fi
}
require_file "$ROOT/server/NanoKVM-Server" "run: make app"
require_file "$ROOT/kvmapp/kvm_system/kvm_system" "run: make support"
require_file "$ROOT/web/dist/index.html" "run: make web"
# libkvm.so is the one runtime library that must come from the build: the copy
# tracked in server/dl_lib/ exists for cgo link time and lags far behind. If it
# were optional here, "make package" on its own would quietly ship the stale one.
require_file "$ROOT/kvmapp/server/dl_lib/libkvm.so" "run: make vision"
require_riscv64 "$ROOT/server/NanoKVM-Server"
require_riscv64 "$ROOT/kvmapp/kvm_system/kvm_system"
require_riscv64 "$ROOT/kvmapp/server/dl_lib/libkvm.so"
echo "[INFO] staging nanokvm_$VERSION"
# Clear the whole output directory: release.yml uploads build/release/nanokvm_*
# by glob, and a leftover tarball from an earlier version would ride along.
rm -rf "$OUT"
mkdir -p "$STAGE"
# 1. Everything tracked under kvmapp/ (init scripts, picoclaw bundle, kernel
# module, jpg_stream, kvm_stream) plus whatever the support build dropped in
# (kvm_system, server/dl_lib). -a carries the exec bits over from git, which
# only matters for reading the archive by hand: install.go chmods the whole
# tree to 0755 on the device regardless.
cp -a "$ROOT/kvmapp/." "$STAGE/"
# 2. Version marker. The updater reads /kvmapp/version to report the currently
# installed version (version.go).
printf '%s\n' "$VERSION" > "$STAGE/version"
# 3. Go server binary.
mkdir -p "$STAGE/server"
cp -a "$ROOT/server/NanoKVM-Server" "$STAGE/server/NanoKVM-Server"
# 4. Runtime shared libraries. "build kvm_vision add_to_kvmapp" copies its whole
# dist/dl_lib into kvmapp/server/dl_lib, so freshly built libraries are
# already staged; the tracked server/dl_lib/ backfills the rest. Never
# clobber a fresh library with the tracked (link-time) copy.
mkdir -p "$STAGE/server/dl_lib"
for lib in "$ROOT"/server/dl_lib/*; do
[ -e "$lib" ] || continue
name="$(basename "$lib")"
if [ ! -e "$STAGE/server/dl_lib/$name" ]; then
cp -a "$lib" "$STAGE/server/dl_lib/$name"
fi
done
# The SDK is built from an unpinned MaixCDK checkout, so its dist could one
# day add or rename a library (e.g. an soname bump leaving both .409 and
# .410 behind) and we would ship a library set nobody reviewed. Require the
# shipped names to be exactly the tracked set, and fail loudly otherwise.
staged_libs=$(cd "$STAGE/server/dl_lib" && ls -1 | LC_ALL=C sort)
tracked_libs=$(cd "$ROOT/server/dl_lib" && ls -1 | LC_ALL=C sort)
if [ "$staged_libs" != "$tracked_libs" ]; then
echo "[ERROR] shipped server/dl_lib does not match the tracked library set" >&2
echo " unexpected (in package, not tracked):" >&2
comm -23 <(printf '%s\n' "$staged_libs") <(printf '%s\n' "$tracked_libs") \
| sed 's/^/ + /' >&2
echo " absent (tracked, not in package):" >&2
comm -13 <(printf '%s\n' "$staged_libs") <(printf '%s\n' "$tracked_libs") \
| sed 's/^/ - /' >&2
echo " if this change is intended, update server/dl_lib/ to match." >&2
exit 1
fi
# A library arrives either from the SDK dist (mode 755) or from the tracked
# backfill (git stores them 644), so without this the archive would depend on
# which path populated each file. 644 is what published releases have always
# carried, and install.go chmods the installed tree to 0755 anyway.
chmod 644 "$STAGE"/server/dl_lib/*
# 5. Frontend. router.go serves <dir of executable>/web.
rm -rf "$STAGE/server/web"
mkdir -p "$STAGE/server/web"
cp -a "$ROOT/web/dist/." "$STAGE/server/web/"
# 6. EDID helper shipped under system/tool/ (prebuilt riscv64 binary in tools/).
mkdir -p "$STAGE/system/tool"
cp -a "$ROOT/tools/nanokvm_update_edid/nanokvm_update_edid" "$STAGE/system/tool/"
cp -a "$ROOT/tools/nanokvm_update_edid/E21_NanoKVM.bin" "$STAGE/system/tool/"
# 7. Default runtime state read by common.GetScreen() on first boot.
mkdir -p "$STAGE/kvm"
printf '30\n' > "$STAGE/kvm/fps"
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 'mjpeg\n' > "$STAGE/kvm/type"
printf '0' > "$STAGE/kvm/res"
# 8. Directories the released package has always carried, kept so the layout
# matches previous releases exactly (system_init.cpp probes inside them).
mkdir -p "$STAGE/jpg_stream/dl_lib" "$STAGE/kvm_system/dl_lib"
# --- archive -----------------------------------------------------------------
# Normalise owner and timestamps so the same source tree yields the same
# tarball, which makes the published sha512 verifiable after the fact.
SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(git -C "$ROOT" log -1 --format=%ct 2>/dev/null || echo 0)}"
find "$STAGE" -exec touch -d "@$SOURCE_DATE_EPOCH" {} + 2>/dev/null \
|| find "$STAGE" -exec touch -t "$(date -r "$SOURCE_DATE_EPOCH" +%Y%m%d%H%M.%S)" {} + 2>/dev/null \
|| echo "[WARN] could not normalise timestamps"
echo "[INFO] creating $(basename "$TARBALL")"
rm -f "$TARBALL"
# Read the version into a variable first: piping through head can hand tar a
# SIGPIPE, and under "set -o pipefail" that would silently select the bsdtar
# branch on a GNU system, quietly losing reproducibility.
tar_version="$(tar --version 2>/dev/null || true)"
if [ "${tar_version#*GNU}" != "$tar_version" ]; then
tar --format=gnu --sort=name \
--owner=0 --group=0 --numeric-owner \
--mtime="@$SOURCE_DATE_EPOCH" \
-C "$OUT" -cf - "nanokvm_$VERSION" \
| gzip -n -9 > "$TARBALL"
else
# bsdtar (macOS): no --sort/--mtime, so the archive is not byte-reproducible.
echo "[WARN] GNU tar not found; archive will not be byte-reproducible"
tar --uid 0 --gid 0 --uname '' --gname '' \
-C "$OUT" -cf - "nanokvm_$VERSION" \
| gzip -n -9 > "$TARBALL"
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 ' ')"
cat > "$MANIFEST" <<EOF
{
"version": "$VERSION",
"name": "nanokvm_$VERSION.tar.gz",
"sha512": "$SHA512",
"size": $SIZE
}
EOF
echo
echo "[DONE] $TARBALL"
echo "[DONE] $MANIFEST"
cat "$MANIFEST"

118
scripts/verify-release-assets.sh Executable file
View File

@@ -0,0 +1,118 @@
#!/bin/bash
# Verify the three assets that make up a NanoKVM GitHub release.
set -euo pipefail
ASSET_DIR="${1:-}"
VERSION="${2:-}"
if [ -z "$ASSET_DIR" ] || [ -z "$VERSION" ]; then
echo "Usage: $0 <asset-directory> <version>" >&2
exit 1
fi
if ! echo "$VERSION" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "[ERROR] invalid version '$VERSION', expected MAJOR.MINOR.PATCH" >&2
exit 1
fi
TARBALL_NAME="nanokvm_${VERSION}.tar.gz"
TARBALL="$ASSET_DIR/$TARBALL_NAME"
MANIFEST="$ASSET_DIR/latest.json"
CHECKSUM="$ASSET_DIR/sha256.txt"
for path in "$TARBALL" "$MANIFEST" "$CHECKSUM"; do
if [ ! -f "$path" ]; then
echo "[ERROR] missing release asset: $path" >&2
exit 1
fi
done
PACKAGE_ROOT="nanokvm_${VERSION}"
ENTRY_LIST=$(mktemp)
VERBOSE_LIST=$(mktemp)
trap 'rm -f "$ENTRY_LIST" "$VERBOSE_LIST"' EXIT
if ! tar -tzf "$TARBALL" > "$ENTRY_LIST"; then
echo "[ERROR] could not list release tarball" >&2
exit 1
fi
if ! tar -tvzf "$TARBALL" > "$VERBOSE_LIST"; then
echo "[ERROR] could not inspect release tarball entry types" >&2
exit 1
fi
ENTRY_COUNT=0
while IFS= read -r entry; do
ENTRY_COUNT=$((ENTRY_COUNT + 1))
case "$entry" in
"$PACKAGE_ROOT"|"$PACKAGE_ROOT"/*) ;;
*)
echo "[ERROR] archive entry is outside $PACKAGE_ROOT/: $entry" >&2
exit 1
;;
esac
case "/$entry/" in
*/../*|*/./*)
echo "[ERROR] archive entry contains an unsafe path component: $entry" >&2
exit 1
;;
esac
done < "$ENTRY_LIST"
if [ "$ENTRY_COUNT" -eq 0 ]; then
echo "[ERROR] release tarball is empty" >&2
exit 1
fi
while IFS= read -r verbose_entry; do
entry_type=${verbose_entry:0:1}
case "$entry_type" in
-|d) ;;
*)
echo "[ERROR] archive contains a link or special entry: $verbose_entry" >&2
exit 1
;;
esac
done < "$VERBOSE_LIST"
ARCHIVE_VERSION=$(tar -xOzf "$TARBALL" "$PACKAGE_ROOT/version" 2>/dev/null) || {
echo "[ERROR] release tarball does not contain $PACKAGE_ROOT/version" >&2
exit 1
}
if [ "$ARCHIVE_VERSION" != "$VERSION" ]; then
echo "[ERROR] archive version '$ARCHIVE_VERSION' does not match '$VERSION'" >&2
exit 1
fi
SHA256=$(sha256sum "$TARBALL" | cut -d' ' -f1)
if ! printf '%s %s\n' "$SHA256" "$TARBALL_NAME" | cmp -s - "$CHECKSUM"; then
echo "[ERROR] sha256.txt does not match $TARBALL_NAME" >&2
exit 1
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_SHA512=$(jq -er '.sha512 | select(type == "string" and length > 0)' "$MANIFEST")
if [ "$MANIFEST_VERSION" != "$VERSION" ]; then
echo "[ERROR] latest.json version '$MANIFEST_VERSION' does not match '$VERSION'" >&2
exit 1
fi
if [ "$MANIFEST_NAME" != "$TARBALL_NAME" ]; then
echo "[ERROR] latest.json name '$MANIFEST_NAME' does not match '$TARBALL_NAME'" >&2
exit 1
fi
ACTUAL_SIZE=$(wc -c < "$TARBALL" | tr -d ' ')
if [ "$MANIFEST_SIZE" != "$ACTUAL_SIZE" ]; then
echo "[ERROR] latest.json size '$MANIFEST_SIZE' does not match '$ACTUAL_SIZE'" >&2
exit 1
fi
ACTUAL_SHA512=$(openssl dgst -sha512 -binary "$TARBALL" | openssl base64 -A)
if [ "$MANIFEST_SHA512" != "$ACTUAL_SHA512" ]; then
echo "[ERROR] latest.json sha512 does not match $TARBALL_NAME" >&2
exit 1
fi
echo "[OK] verified NanoKVM release assets for $VERSION"

43
scripts/verify-release-tag.sh Executable file
View File

@@ -0,0 +1,43 @@
#!/bin/bash
# Resolve an annotated numeric tag from origin and verify its commit is on main.
set -euo pipefail
TAG="${1:-}"
EXPECTED_SHA="${2:-}"
if ! echo "$TAG" | grep -qE '^[0-9]+\.[0-9]+\.[0-9]+$'; then
echo "[ERROR] invalid tag '$TAG', expected MAJOR.MINOR.PATCH" >&2
exit 1
fi
if [ -n "$EXPECTED_SHA" ] && ! echo "$EXPECTED_SHA" | grep -qE '^[0-9a-f]{40}$'; then
echo "[ERROR] expected commit must be a full lowercase commit SHA" >&2
exit 1
fi
TAG_REF="refs/tags/$TAG"
PEELED_REF="${TAG_REF}^{}"
REMOTE_REFS=$(git ls-remote --tags origin "$TAG_REF" "$PEELED_REF")
TAG_OBJECT=$(printf '%s\n' "$REMOTE_REFS" | awk -v ref="$TAG_REF" '$2 == ref { print $1 }')
SOURCE_SHA=$(printf '%s\n' "$REMOTE_REFS" | awk -v ref="$PEELED_REF" '$2 == ref { print $1 }')
if ! echo "$TAG_OBJECT" | grep -qE '^[0-9a-f]{40}$'; then
echo "[ERROR] tag '$TAG' does not exist on origin" >&2
exit 1
fi
if ! echo "$SOURCE_SHA" | grep -qE '^[0-9a-f]{40}$'; then
echo "[ERROR] tag '$TAG' is not an annotated tag" >&2
exit 1
fi
if [ -n "$EXPECTED_SHA" ] && [ "$SOURCE_SHA" != "$EXPECTED_SHA" ]; then
echo "[ERROR] tag '$TAG' moved from '$EXPECTED_SHA' to '$SOURCE_SHA'" >&2
exit 1
fi
git fetch --no-tags origin main
if ! git merge-base --is-ancestor "$SOURCE_SHA" FETCH_HEAD; then
echo "[ERROR] tag '$TAG' points to a commit outside origin/main" >&2
exit 1
fi
printf '%s\n' "$SOURCE_SHA"

View File

@@ -26,46 +26,45 @@ server
The configuration file path is `/etc/kvm/server.yaml`.
```yaml
proto: http
# Network Settings
proto: http # Access protocol. Can be changed to `https` only when certificates are configured. Default is `http`
host: "" # The listening address for the HTTP/HTTPS service. If left empty, all network interfaces will be bound
port:
http: 80
https: 443
http: 80 # The listening port for the HTTP service. Default is `80`
https: 443 # The listening port for the HTTPS service (effective when HTTPS is enabled). Default is `443`
cert:
crt: server.crt
key: server.key
crt: server.crt # The path to the public key certificate for HTTPS
key: server.key # The path to the private key file for HTTPS
# Log level (debug/info/warn/error)
# Note: Use 'info' or 'error' in production, 'debug' only for development
# Logging Configuration
logger:
level: info
file: stdout
level: info # Global log output level. Evaluated options from highest to lowest detail: `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`. Default is `info`
file: stdout # Log output destination. `stdout` outputs to the standard console. A file path directs log output to that file. Default is `stdout`
# Authentication setting (enable/disable)
# Note: Only disable authentication in development environment
authentication: enable
# Authentication & Security
authentication: enable # Whether to enable identity verification for HTTP API and Web endpoints. Options are `enable` or `disable`. Default is `enable`. Highly recommended to leave this enabled for internet-facing devices!
jwt:
# JWT secret key. If left empty, a random 64-byte key will be generated automatically.
secretKey: ""
# JWT token expiration time in seconds. Default: 2678400 (31 days)
refreshTokenDuration: 2678400
# Invalidate all JWT tokens when the user logs out. Default: true
revokeTokensOnLogout: true
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`
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`
# Address for custom STUN server
# Note: You can disable the STUN service by setting it to 'disable' (e.g., in a LAN environment)
stun: stun.l.google.com:19302
# Address and authentication for custom TURN server
# WebRTC Traversal Settings
stun: stun.l.google.com:19302 # The default STUN server address used for NAT hole-punching to establish P2P streams
turn:
turnAddr: example_addr
turnUser: example_user
turnCred: example_cred
turnAddr: example_addr # The relay (TURN) server address (format `ip:port`) used as a fallback when P2P connection fails. Leave empty to disable TURN relay
turnUser: example_user # The username required for authorization to the TURN server
turnCred: example_cred # The credential/password required for authorization to the TURN server
```
## Compile & Deploy
Note: Use Linux operating system (x86-64). This build process is not compatible with ARM, Windows or macOS.
Note: Use Linux operating system (x86-64) with Go 1.25 or newer. This build process is not compatible with ARM, Windows or macOS.
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

@@ -27,6 +27,7 @@ server
```yaml
proto: http
host: ""
port:
http: 80
https: 443
@@ -64,7 +65,7 @@ turn:
## コンパイルとデプロイ
注意: Linux オペレーティングシステム (x86-64) を使用してください。このビルドプロセスは ARM、Windows、macOS では互換性がありません。
注意: Linux オペレーティングシステム (x86-64) と Go 1.25 以降を使用してください。このビルドプロセスは ARM、Windows、macOS では互換性がありません。
1. ツールチェーンのインストール
1. 以下のリンクからツールチェーンをダウンロードします: [ダウンロードリンク](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz)。

View File

@@ -24,45 +24,45 @@ server
配置文件路径为 `/etc/kvm/server.yaml`。
```yaml
proto: http
# 网络设置
proto: http # 访问协议,默认为 `http`,仅当配置了证书时支持改为 `https`
host: ""
port:
http: 80
https: 443
http: 80 # HTTP 服务的监听端口,默认为 `80`
https: 443 # HTTPS 服务的监听端口(启用 https 协议时生效),默认为 `443`
cert:
crt: server.crt
key: server.key
crt: server.crt # HTTPS 服务使用的公钥证书路径
key: server.key # HTTPS 服务使用的私钥文件路径
# 日志级别(debug/info/warn/error)
# 注意:在生产环境中使用 info 或 error。debug 模式仅在开发环境中使用。
# 日志配置
logger:
level: info
file: stdout
level: info # 全局日志打印级别,从高到底可选 `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`。默认为 `info`
file: stdout # 日志输出目标位置。若填写 `stdout` 则输出在控制台。配置为文件路径则会输出到对应的文件。默认为 `stdout`
# 鉴权设置(enable/disable)
# 注意:生产环境中请勿使用 disable。
authentication: enable
# 认证与安全
authentication: enable # 是否开启 HTTP 接口与网页的身份校验。可选 `enable` (开启) 或 `disable` (禁用)。默认为 `enable`。强烈建议公开在互联网的机器开启此项!
jwt:
# jwt 密钥。设置为空则使用随机生成的64位密钥
secretKey: ""
# jwt token 过期时间(单位:秒),默认为2678400(31天)
refreshTokenDuration: 2678400
# 在帐号登出时是否使所有 jwt token 失效。默认为 true
revokeTokensOnLogout: true
secretKey: "" # 用于签发和验证 JWT Token 的密钥。如果不填,服务启动时将自动随机生成
refreshTokenDuration: 2678400 # 登录超时的刷新周期(单位:秒)。默认为 `2678400`(约31天)
revokeTokensOnLogout: true # 退出登录时是否废除所有现存的 Token。启用此项可以在注销时轮换 SecretKey,强迫所有终端重新登录。默认为 `true`
security:
loginLockoutDuration: 0, # 达到失败上限后,禁止该 IP 再次尝试登录的持续时间(单位:秒)。如果设为 `0` 或不填,则代表不开启防暴力破解功能。默认为 `0`
loginMaxFailures: 5, # 允许触发保护前,单个 IP 连续登录失败的最大次数。默认为 `5`
# 自定义 STUN 服务器的地址
# 注意:可以设置为“disable”来禁用 STUN 服务(例如在局域网环境中使用时)
stun: stun.l.google.com:19302
# WebRTC 内网穿透
stun: stun.l.google.com:19302 # 默认使用的 STUN 服务器地址,用于打洞获取公网 IP 建立 P2P 流
turn:
turnAddr: example_addr
turnUser: example_user
turnCred: example_cred
turnAddr: example_addr # 当 P2P 直连失败时,作为备用的中继(TURN)服务器地址(格式如 `ip:port`)。留空表示不使用 TURN 中继
turnUser: example_user # TURN 服务器授权连接时使用的用户名
turnCred: example_cred # TURN 服务器授权连接时使用的凭据/密码
```
## 编译部署
**注意:请使用 Linux 操作系统(x86-64)。该工具链无法在 ARM、Windows 或 macOS 下使用。**
**注意:请使用 Linux 操作系统(x86-64)和 Go 1.25 或更高版本。该工具链无法在 ARM、Windows 或 macOS 下使用。**
1. 安装工具链
1. 下载工具链:[下载地址](https://sophon-file.sophon.cn/sophon-prod-s3/drive/23/03/07/16/host-tools.tar.gz);

View File

@@ -2,6 +2,7 @@ package config
var defaultConfig = &Config{
Proto: "http",
Host: "",
Port: Port{
Http: 80,
Https: 443,
@@ -26,6 +27,10 @@ var defaultConfig = &Config{
TurnCred: "",
},
Authentication: "enable",
Security: Security{
LoginLockoutDuration: 0,
LoginMaxFailures: 5,
},
}
func checkDefaultValue() {

View File

@@ -0,0 +1,61 @@
package config
import (
"os"
"path/filepath"
"strings"
"sync"
)
const (
PicoclawInternalTokenHeader = "X-NanoKVM-Internal-Token"
picoclawInternalTokenFile = "/etc/kvm/.picoclaw_internal_token"
)
var picoclawInternalToken struct {
mu sync.Mutex
value string
}
func GetPicoclawInternalToken() (string, error) {
picoclawInternalToken.mu.Lock()
defer picoclawInternalToken.mu.Unlock()
if picoclawInternalToken.value != "" {
return picoclawInternalToken.value, nil
}
if token, err := readPicoclawInternalToken(); err == nil {
if token != "" {
picoclawInternalToken.value = token
return token, nil
}
} else if !os.IsNotExist(err) {
return "", err
}
token := generateRandomSecretKey()
if err := os.MkdirAll(filepath.Dir(picoclawInternalTokenFile), 0o755); err != nil {
return "", err
}
if err := os.WriteFile(picoclawInternalTokenFile, []byte(token+"\n"), 0o600); err != nil {
return "", err
}
picoclawInternalToken.value = token
return token, nil
}
func EnsurePicoclawInternalToken() error {
_, err := GetPicoclawInternalToken()
return err
}
func readPicoclawInternalToken() (string, error) {
data, err := os.ReadFile(picoclawInternalTokenFile)
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}

View File

@@ -1,14 +1,16 @@
package config
type Config struct {
Proto string `yaml:"proto"`
Port Port `yaml:"port"`
Cert Cert `yaml:"cert"`
Logger Logger `yaml:"logger"`
Authentication string `yaml:"authentication"`
JWT JWT `yaml:"jwt"`
Stun string `yaml:"stun"`
Turn Turn `yaml:"turn"`
Proto string `yaml:"proto"`
Host string `yaml:"host"`
Port Port `yaml:"port"`
Cert Cert `yaml:"cert"`
Logger Logger `yaml:"logger"`
Authentication string `yaml:"authentication"`
JWT JWT `yaml:"jwt"`
Stun string `yaml:"stun"`
Turn Turn `yaml:"turn"`
Security Security `yaml:"security"`
Hardware Hardware `yaml:"-"`
}
@@ -40,6 +42,11 @@ type Turn struct {
TurnCred string `yaml:"turnCred"`
}
type Security struct {
LoginLockoutDuration int `yaml:"loginLockoutDuration"`
LoginMaxFailures int `yaml:"loginMaxFailures"`
}
type Hardware struct {
Version HWVersion `yaml:"-"`
GPIOReset string `yaml:"-"`

Binary file not shown.

Binary file not shown.

View File

@@ -1,16 +1,19 @@
module NanoKVM-Server
go 1.24.0
go 1.25.0
require (
github.com/creack/pty v1.1.24
github.com/gin-gonic/contrib v0.0.0-20240508051311-c1c6bf0061b0
github.com/gin-gonic/gin v1.10.0
github.com/go-playground/validator/v10 v10.20.0
github.com/golang-jwt/jwt/v5 v5.2.2
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/google/jsonschema-go v0.4.3
github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0
github.com/pion/dtls/v3 v3.0.3
github.com/modelcontextprotocol/go-sdk v1.6.1
github.com/pion/dtls/v3 v3.1.2
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
@@ -32,7 +35,6 @@ require (
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
@@ -46,7 +48,7 @@ require (
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.3 // 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
github.com/pion/rtcp v1.2.15 // indirect
@@ -55,10 +57,13 @@ require (
github.com/pion/srtp/v3 v3.0.4 // indirect
github.com/pion/stun/v3 v3.0.0 // indirect
github.com/pion/transport/v3 v3.0.7 // indirect
github.com/pion/transport/v4 v4.0.1 // indirect
github.com/pion/turn/v4 v4.0.0 // indirect
github.com/rs/cors v1.11.0 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/segmentio/asm v1.1.3 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
@@ -66,13 +71,15 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
github.com/wlynxg/anet v0.0.3 // indirect
github.com/wlynxg/anet v0.0.5 // indirect
github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.38.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

@@ -34,11 +34,13 @@ github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBEx
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=
github.com/golang-jwt/jwt/v5 v5.2.2/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
@@ -65,6 +67,8 @@ github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0 h
github.com/mervick/aes-everywhere/go/aes256 v0.0.0-20240803013625-6759956693c0/go.mod h1:Eb5RMoo9kOQra/2uRiUTGP+LfNuM13Vqm7y7P34+KKo=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modelcontextprotocol/go-sdk v1.6.1 h1:0zOSupjKUxPKSocPT1Wtago+mUHU2/uZ4xSOY0FGReU=
github.com/modelcontextprotocol/go-sdk v1.6.1/go.mod h1:kzm3kzFL1/+AziGOE0nUs3gvPoNxMCvkxokMkuFapXQ=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@@ -74,14 +78,14 @@ github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pion/datachannel v1.5.9 h1:LpIWAOYPyDrXtU+BW7X0Yt/vGtYxtXQ8ql7dFfYUVZA=
github.com/pion/datachannel v1.5.9/go.mod h1:kDUuk4CU4Uxp82NH4LQZbISULkX/HtzKa4P7ldf9izE=
github.com/pion/dtls/v3 v3.0.3 h1:j5ajZbQwff7Z8k3pE3S+rQ4STvKvXUdKsi/07ka+OWM=
github.com/pion/dtls/v3 v3.0.3/go.mod h1:weOTUyIV4z0bQaVzKe8kpaP17+us3yAuiQsEAG1STMU=
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
github.com/pion/ice/v4 v4.0.2 h1:1JhBRX8iQLi0+TfcavTjPjI6GO41MFn4CeTBX+Y9h5s=
github.com/pion/ice/v4 v4.0.2/go.mod h1:DCdqyzgtsDNYN6/3U8044j3U7qsJ9KFJC92VnOWHvXg=
github.com/pion/interceptor v0.1.39 h1:Y6k0bN9Y3Lg/Wb21JBWp480tohtns8ybJ037AGr9UuA=
github.com/pion/interceptor v0.1.39/go.mod h1:Z6kqH7M/FYirg3frjGJ21VLSRJGBXB/KqaTIrdqnOic=
github.com/pion/logging v0.2.3 h1:gHuf0zpoh1GW67Nr6Gj4cv5Z9ZscU7g/EaoC/Ke/igI=
github.com/pion/logging v0.2.3/go.mod h1:z8YfknkquMe1csOrxK5kc+5/ZPAzMxbKLX5aXpbpC90=
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
github.com/pion/mdns/v2 v2.0.7 h1:c9kM8ewCgjslaAmicYMFQIde2H9/lrZpjBkN8VwoVtM=
github.com/pion/mdns/v2 v2.0.7/go.mod h1:vAdSYNAT0Jy3Ru0zl2YiW3Rm/fJCwIeM0nToenfOJKA=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
@@ -100,6 +104,8 @@ github.com/pion/stun/v3 v3.0.0 h1:4h1gwhWLWuZWOJIJR9s2ferRO+W3zA/b6ijOI6mKzUw=
github.com/pion/stun/v3 v3.0.0/go.mod h1:HvCN8txt8mwi4FBvS3EmDghW6aQJ24T+y+1TKjB5jyU=
github.com/pion/transport/v3 v3.0.7 h1:iRbMH05BzSNwhILHoBoAPxoB9xQgOaJk+591KC9P1o0=
github.com/pion/transport/v3 v3.0.7/go.mod h1:YleKiTZ4vqNxVwh77Z0zytYi7rXHl7j6uPLGhhz9rwo=
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
github.com/pion/turn/v4 v4.0.0 h1:qxplo3Rxa9Yg1xXDxxH8xaqcyGUtbHYw4QSCvmFWvhM=
github.com/pion/turn/v4 v4.0.0/go.mod h1:MuPDkm15nYSklKpN8vWJ9W2M0PlyQZqYt1McGuxG7mA=
github.com/pion/webrtc/v4 v4.0.1 h1:6Unwc6JzoTsjxetcAIoWH81RUM4K5dBc1BbJGcF9WVE=
@@ -117,6 +123,10 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
@@ -140,8 +150,8 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
@@ -150,8 +160,10 @@ github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65E
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
github.com/unrolled/secure v1.15.0 h1:q7x+pdp8jAHnbzxu6UheP8fRlG/rwYTb8TPuQ3rn9Og=
github.com/unrolled/secure v1.15.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
github.com/wlynxg/anet v0.0.3 h1:PvR53psxFXstc12jelG6f1Lv4MWqE0tI76/hHGjh9rg=
github.com/wlynxg/anet v0.0.3/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
@@ -165,13 +177,17 @@ golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjs
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.35.0 h1:Mv2mzuHuZuY2+bkyWXIHMfhNdJAdwW3FuWeCPYN5GVQ=
golang.org/x/oauth2 v0.35.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=

View File

@@ -1,12 +1,10 @@
package main
import (
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"strconv"
"syscall"
"time"
@@ -15,6 +13,7 @@ import (
"NanoKVM-Server/logger"
"NanoKVM-Server/middleware"
"NanoKVM-Server/router"
"NanoKVM-Server/service/vm"
"NanoKVM-Server/service/vm/jiggler"
"NanoKVM-Server/utils"
@@ -30,18 +29,22 @@ func main() {
}
func initialize() {
if err := config.EnsurePicoclawInternalToken(); err != nil {
log.Fatalf("failed to initialize picoclaw internal token: %v", err)
}
logger.Init()
// init screen parameters
_ = common.GetScreen()
// init HDMI
vision := common.GetKvmVision()
vision.SetHDMI(false)
vm.DisableHdmiCapture()
time.Sleep(10 * time.Millisecond)
if !utils.IsHdmiDisabled() {
vision.SetHDMI(true)
vm.EnableHdmiCapture()
}
vm.SetHdmiViewerCount(0)
// run mouse jiggler
jiggler.GetJiggler().Run()
@@ -69,46 +72,56 @@ func run() {
router.Init(r)
httpAddr := fmt.Sprintf(":%d", conf.Port.Http)
httpsAddr := fmt.Sprintf(":%d", conf.Port.Https)
httpAddr := utils.ListenAddr(conf.Host, strconv.Itoa(conf.Port.Http))
loopbackHTTPAddr := utils.ListenAddr("127.0.0.1", strconv.Itoa(conf.Port.Http))
needsLoopbackHTTP := utils.NeedsDedicatedLoopbackListener(conf.Host)
if conf.Proto == "https" {
httpsPortStr := strconv.Itoa(conf.Port.Https)
go func() {
r.Use(middleware.Tls())
err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key)
err := r.RunTLS(utils.ListenAddr(conf.Host, httpsPortStr), conf.Cert.Crt, conf.Cert.Key)
if err != nil {
panic("start https server failed")
}
}()
runRedirect(httpAddr, httpsAddr)
if needsLoopbackHTTP {
go func() {
if err := middleware.ListenAndServeLoopbackHTTPRedirect(
loopbackHTTPAddr,
httpsPortStr,
r,
router.LoopbackHTTPAllowedPaths()...,
); err != nil {
panic("start loopback http server failed")
}
}()
}
if err := middleware.ListenAndServeLoopbackHTTPRedirect(
httpAddr,
httpsPortStr,
r,
router.LoopbackHTTPAllowedPaths()...,
); err != nil {
panic("start http server failed")
}
} else {
if needsLoopbackHTTP {
go func() {
if err := r.Run(loopbackHTTPAddr); err != nil {
panic("start loopback http server failed")
}
}()
}
if err := r.Run(httpAddr); err != nil {
panic("start http server failed")
}
}
}
func runRedirect(httpPort string, httpsPort string) {
err := http.ListenAndServe(httpPort, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
host := req.Host
if strings.Contains(host, httpPort) {
host = strings.Split(host, httpPort)[0]
}
targetURL := "https://" + host + req.URL.String()
if httpsPort != ":443" {
targetURL = "https://" + host + httpsPort + req.URL.String()
}
http.Redirect(w, req, targetURL, http.StatusTemporaryRedirect)
}))
if err != nil {
panic("start http server failed")
}
}
func dispose() {
common.GetKvmVision().Close()
}

View File

@@ -18,27 +18,58 @@ type Token struct {
func CheckToken() gin.HandlerFunc {
return func(c *gin.Context) {
conf := config.GetInstance()
if conf.Authentication == "disable" {
if allowByToken(c) {
c.Next()
return
}
cookie, err := c.Cookie("nano-kvm-token")
if err == nil {
_, err = ParseJWT(cookie)
if err == nil {
c.Next()
return
}
abortUnauthorized(c)
}
}
func CheckLoopbackInternalToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByLoopbackInternalToken(c.Request) {
c.Next()
return
}
c.JSON(http.StatusUnauthorized, "unauthorized")
c.Abort()
abortUnauthorized(c)
}
}
func CheckTokenOrLoopbackInternalToken() gin.HandlerFunc {
return func(c *gin.Context) {
if allowByToken(c) || allowByLoopbackInternalToken(c.Request) {
c.Next()
return
}
abortUnauthorized(c)
}
}
func allowByToken(c *gin.Context) bool {
conf := config.GetInstance()
if conf.Authentication == "disable" {
return true
}
cookie, err := c.Cookie("nano-kvm-token")
if err != nil {
return false
}
_, err = ParseJWT(cookie)
return err == nil
}
func abortUnauthorized(c *gin.Context) {
c.JSON(http.StatusUnauthorized, "unauthorized")
c.Abort()
}
func GenerateJWT(username string) (string, error) {
conf := config.GetInstance()

View File

@@ -0,0 +1,94 @@
package middleware
import (
"crypto/subtle"
"net"
"net/http"
"strings"
"NanoKVM-Server/config"
)
func ListenAndServeLoopbackHTTPRedirect(
httpAddr string,
httpsPort string,
handler http.Handler,
allowedPaths ...string,
) error {
allowlist := make(map[string]struct{}, len(allowedPaths))
for _, path := range allowedPaths {
if strings.TrimSpace(path) == "" {
continue
}
allowlist[path] = struct{}{}
}
return http.ListenAndServe(httpAddr, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if isLoopbackAllowedPath(req, allowlist) {
if hasValidLoopbackHTTPToken(req) {
handler.ServeHTTP(w, req)
return
}
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
http.Redirect(w, req, "https://"+redirectHost(req.Host, httpsPort)+req.URL.RequestURI(), http.StatusTemporaryRedirect)
}))
}
func redirectHost(requestHost string, httpsPort string) string {
host := requestHost
if h, _, err := net.SplitHostPort(requestHost); err == nil {
host = h
} else if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
host = strings.TrimPrefix(strings.TrimSuffix(host, "]"), "[")
}
if httpsPort != "443" {
return net.JoinHostPort(host, httpsPort)
}
if strings.Contains(host, ":") && !strings.HasPrefix(host, "[") && !strings.HasSuffix(host, "]") {
return "[" + host + "]"
}
return host
}
func allowByLoopbackInternalToken(req *http.Request) bool {
return req != nil && isLoopbackRemote(req.RemoteAddr) && hasValidLoopbackHTTPToken(req)
}
func isLoopbackAllowedPath(req *http.Request, allowedPaths map[string]struct{}) bool {
if !allowByLoopbackInternalToken(req) {
return false
}
_, allowed := allowedPaths[req.URL.Path]
return allowed
}
func hasValidLoopbackHTTPToken(req *http.Request) bool {
if req == nil {
return false
}
token, err := config.GetPicoclawInternalToken()
if err != nil || token == "" {
return false
}
provided := req.Header.Get(config.PicoclawInternalTokenHeader)
return subtle.ConstantTimeCompare([]byte(provided), []byte(token)) == 1
}
func isLoopbackRemote(remoteAddr string) bool {
host := strings.TrimSpace(remoteAddr)
if parsedHost, _, err := net.SplitHostPort(remoteAddr); err == nil {
host = parsedHost
}
ip := net.ParseIP(strings.Trim(host, "[]"))
return ip != nil && ip.IsLoopback()
}

View File

@@ -21,8 +21,3 @@ type ChangePasswordReq struct {
type IsPasswordUpdatedRsp struct {
IsUpdated bool `json:"isUpdated"`
}
type ConnectWifiReq struct {
Ssid string `validate:"required"`
Password string `valid:"required"`
}

View File

@@ -1,5 +1,10 @@
package proto
type DownloadImageReq struct {
File string `json:"file" validate:"required"`
SHA256Sum string `json:"sha256sum"`
}
type ImageEnabledRsp struct {
Enabled bool `json:"enabled"`
}

View File

@@ -4,6 +4,44 @@ type GetHidModeRsp struct {
Mode string `json:"mode"` // normal or hid-only
}
type GetKeyboardLedStatusRsp struct {
NumLock bool `json:"numLock"`
CapsLock bool `json:"capsLock"`
ScrollLock bool `json:"scrollLock"`
Known bool `json:"known"`
UpdatedAt string `json:"updatedAt"`
}
type SetHidModeReq struct {
Mode string `validate:"required"` // normal or hid-only
}
type ShortcutKey struct {
Code string `json:"code"`
Label string `json:"label"`
}
type Shortcut struct {
ID string `json:"id"`
Keys []ShortcutKey `json:"keys"`
}
type GetShortcutsRsp struct {
Shortcuts []Shortcut `json:"shortcuts"`
}
type AddShortcutReq struct {
Keys []ShortcutKey `validate:"required"`
}
type DeleteShortcutReq struct {
ID string `validate:"required"`
}
type SetLeaderKeyReq struct {
Key string `validate:"omitempty"`
}
type GetLeaderKeyRsp struct {
Key string `json:"key"`
}

12
server/proto/mcp.go Normal file
View File

@@ -0,0 +1,12 @@
package proto
type GetMCPConfigRsp struct {
Enabled bool `json:"enabled"`
APIKey string `json:"apiKey"`
ControlMode string `json:"controlMode"`
Transitioning bool `json:"transitioning"`
}
type SetMCPConfigReq struct {
Enabled *bool `json:"enabled" form:"enabled" validate:"required"`
}

View File

@@ -17,28 +17,36 @@ type SetMacNameReq struct {
Name string `form:"name" validate:"required"`
}
type TailscaleState string
const (
TailscaleNotInstall TailscaleState = "notInstall"
TailscaleNotRunning TailscaleState = "notRunning"
TailscaleNotLogin TailscaleState = "notLogin"
TailscaleStopped TailscaleState = "stopped"
TailscaleRunning TailscaleState = "running"
)
type GetTailscaleStatusRsp struct {
State TailscaleState `json:"state"`
Name string `json:"name"`
IP string `json:"ip"`
Account string `json:"account"`
}
type LoginTailscaleRsp struct {
Url string `json:"url"`
}
type GetWifiRsp struct {
Supported bool `json:"supported"`
Connected bool `json:"connected"`
Supported bool `json:"supported"`
ApMode bool `json:"apMode"`
Connected bool `json:"connected"`
Ssid string `json:"ssid"`
}
type ConnectWifiReq struct {
Ssid string `validate:"required"`
Password string `validate:"required"`
}
type GetDNSRsp struct {
Mode string `json:"mode"`
Servers []string `json:"servers"`
Effective []string `json:"effective"`
DHCP []string `json:"dhcp"`
Info DNSInfo `json:"info"`
}
type SetDNSReq struct {
Mode string `json:"mode" validate:"required,oneof=manual dhcp"`
Servers []string `json:"servers"`
}
type DNSInfo struct {
Interface string `json:"interface"`
Type string `json:"type"`
Address string `json:"address"`
SubnetMask string `json:"subnetMask"`
Gateway string `json:"gateway"`
SearchDomains []string `json:"searchDomains"`
}

22
server/proto/tailscale.go Normal file
View File

@@ -0,0 +1,22 @@
package proto
type TailscaleState string
const (
TailscaleNotInstall TailscaleState = "notInstall"
TailscaleNotRunning TailscaleState = "notRunning"
TailscaleNotLogin TailscaleState = "notLogin"
TailscaleStopped TailscaleState = "stopped"
TailscaleRunning TailscaleState = "running"
)
type GetTailscaleStatusRsp struct {
State TailscaleState `json:"state"`
Name string `json:"name"`
IP string `json:"ip"`
Account string `json:"account"`
}
type LoginTailscaleRsp struct {
Url string `json:"url"`
}

View File

@@ -55,8 +55,18 @@ type DeleteScriptReq struct {
Name string `validate:"required"`
}
// autostart
type GetAutostartRsp struct {
Files []string `json:"files"`
}
type UploadAutostartReq struct {
Content string `json:"content"`
}
type GetVirtualDeviceRsp struct {
Network bool `json:"network"`
Media bool `json:"media"`
Disk bool `json:"disk"`
}
@@ -88,7 +98,12 @@ type GetOLEDRsp struct {
}
type GetGetHdmiStateRsp struct {
Enabled bool `json:"enabled"`
Enabled bool `json:"enabled"`
IdleTimeout int `json:"idleTimeout"`
}
type SetHdmiIdleTimeoutReq struct {
Minutes int `validate:"gte=0,lte=10080"`
}
type GetSSHStateRsp struct {

View File

@@ -11,8 +11,9 @@ func applicationRouter(r *gin.Engine) {
service := application.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
api.GET("/application/version", service.GetVersion) // get application version
api.POST("/application/update", service.Update) // update application
api.POST("/application/update/offline", service.OfflineUpdate) // update application offline
api.GET("/application/preview", service.GetPreview) // get preview updates state
api.POST("/application/preview", service.SetPreview) // set preview updates state

159
server/router/control.go Normal file
View File

@@ -0,0 +1,159 @@
package router
import (
"net/http"
"time"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/hid"
"NanoKVM-Server/service/inputcontrol"
"NanoKVM-Server/service/picoclaw"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type setAIControlModeRequest struct {
Mode controlmode.Mode `json:"mode"`
}
func controlRouter(r *gin.Engine, control *controlmode.Manager, picoclawService *picoclaw.Service) {
group := r.Group("/api/ai/control").Use(middleware.CheckToken())
group.GET("/status", func(c *gin.Context) {
status, err := control.Status()
if err != nil {
c.JSON(http.StatusOK, gin.H{"code": -1, "message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": status})
})
group.PUT("/mode", func(c *gin.Context) {
startedAt := time.Now()
var req setAIControlModeRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{"code": -1, "message": "invalid arguments"})
return
}
if !validAIControlMode(req.Mode) {
c.JSON(http.StatusOK, gin.H{"code": -1, "message": "invalid control mode"})
return
}
previousStatus, previousErr := control.Status()
if previousErr != nil {
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(previousErr).Warn("AI control mode request failed before switch")
c.JSON(http.StatusOK, gin.H{"code": -2, "message": previousErr.Error()})
return
}
preempt := func() error {
inputcontrol.GetCoordinator().CancelMCP()
if req.Mode == controlmode.ModeMCP {
return picoclawService.PreemptControlLeasesForMCP()
}
picoclawService.CancelActiveControlOperations()
return nil
}
cleanup := func() error {
return hid.ReleaseAllHIDStateBestEffort()
}
if req.Mode == controlmode.ModeMCP {
cleanup = func() error {
if err := picoclawService.StopRuntimeForMCP(); err != nil {
return err
}
return hid.ReleaseAllHIDStateBestEffort()
}
}
if err := control.SwitchWithCleanup(req.Mode, preempt, cleanup); err != nil {
if req.Mode == controlmode.ModeOff {
if status, statusErr := control.Status(); statusErr == nil && status.Mode == controlmode.ModeOff {
picoclawService.CancelActiveControlOperations()
picoclawService.PreserveRuntimeForChatOnly("control_release_chat_only")
closedSessions := 0
picoclawService.PublishControlModeChangedFrom(status, "ai_control_mode")
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"final_mode": string(status.Mode),
"transitioning": status.Transitioning,
"closed_sessions": closedSessions,
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(err).Warn("AI control mode request completed with cleanup warning")
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": gin.H{
"control": status,
"runtime": picoclawService.RuntimeStatus(),
"released": true,
"closed_sessions": closedSessions,
"cleanup_warning": err.Error(),
},
})
return
}
}
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(err).Warn("AI control mode request failed")
c.JSON(http.StatusOK, gin.H{"code": -2, "message": err.Error()})
return
}
status, err := control.Status()
if err != nil {
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).WithError(err).Warn("AI control mode request failed after switch")
c.JSON(http.StatusOK, gin.H{"code": -2, "message": err.Error()})
return
}
closedSessions := 0
if req.Mode == controlmode.ModeOff {
picoclawService.CancelActiveControlOperations()
picoclawService.PreserveRuntimeForChatOnly("control_release_chat_only")
}
picoclawService.PublishControlModeChangedFrom(status, "ai_control_mode")
log.WithFields(log.Fields{
"request_mode": string(req.Mode),
"previous_mode": string(previousStatus.Mode),
"final_mode": string(status.Mode),
"transitioning": status.Transitioning,
"elapsed_ms": time.Since(startedAt).Milliseconds(),
}).Info("AI control mode request completed")
if req.Mode == controlmode.ModeOff {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "success",
"data": gin.H{
"control": status,
"runtime": picoclawService.RuntimeStatus(),
"released": true,
"closed_sessions": closedSessions,
"cleanup_warning": "",
},
})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "success", "data": status})
})
}
func validAIControlMode(mode controlmode.Mode) bool {
switch mode {
case controlmode.ModeOff, controlmode.ModeMCP, controlmode.ModePicoclaw:
return true
default:
return false
}
}

View File

@@ -11,7 +11,9 @@ func downloadRouter(r *gin.Engine) {
service := download.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
api.POST("/download/image", service.DownloadImage) // download image
api.GET("/download/image/status", service.StatusImage) // download image
api.GET("/download/image/enabled", service.ImageEnabled) // download image
api.POST("/download/image", service.DownloadImage) // download image
api.POST("/download/image/cancel", service.CancelDownloadImage) // cancel image download
api.GET("/download/image/status", service.StatusImage) // download image
api.GET("/download/image/enabled", service.ImageEnabled) // download image
api.POST("/download/file", service.DownloadImageFile) // download image
}

View File

@@ -7,13 +7,30 @@ import (
"NanoKVM-Server/service/hid"
)
const internalUSBRecoverPath = "/api/internal/usb/recover"
func HIDLoopbackHTTPAllowedPaths() []string {
return []string{internalUSBRecoverPath}
}
func hidRouter(r *gin.Engine) {
service := hid.NewService()
api := r.Group("/api").Use(middleware.CheckToken())
localAPI := r.Group("/api/internal").Use(middleware.CheckLoopbackInternalToken())
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/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/leds", service.GetKeyboardLedStatus)
localAPI.POST("/usb/recover", service.RecoverUSB)
}

34
server/router/mcp.go Normal file
View File

@@ -0,0 +1,34 @@
package router
import (
"net/http"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/hid"
mcpservice "NanoKVM-Server/service/mcp"
"NanoKVM-Server/service/mcp/capture/kvm"
"NanoKVM-Server/service/picoclaw"
"github.com/gin-gonic/gin"
)
func mcpRouter(r *gin.Engine, control *controlmode.Manager, picoclawService *picoclaw.Service) {
service := mcpservice.NewServiceWithPreempt(
control,
picoclawService.PreemptControlLeasesForMCP,
picoclawService.StopRuntimeForMCP,
hid.ReleaseAllHIDStateBestEffort,
func(status controlmode.Status) {
picoclawService.PublishControlModeChangedFrom(status, "mcp_config")
},
)
management := r.Group("/api/mcp").Use(middleware.CheckToken())
management.GET("/config", service.GetConfig)
management.POST("/config", service.SetConfig)
management.POST("/key/regenerate", service.RegenerateAPIKey)
handler := mcpservice.NewMCPHandler(control, kvmcapture.New())
handler = http.NewCrossOriginProtection().Handler(handler)
r.Any("/api/mcp", mcpservice.APIKeyMiddleware(control), gin.WrapH(handler))
}

View File

@@ -10,7 +10,8 @@ import (
func networkRouter(r *gin.Engine) {
service := network.NewService()
r.POST("/api/network/wifi", service.ConnectWifi) // connect Wi-Fi
r.POST("/api/network/wifi", service.ConnectWifiNoAuth) // connect Wi-Fi without auth (only available in ap mode)
r.POST("/api/network/wifi/verify", service.VerifyApLogin) // verify ap login
api := r.Group("/api").Use(middleware.CheckToken())
@@ -18,5 +19,11 @@ func networkRouter(r *gin.Engine) {
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.GET("/network/wifi", service.GetWifi) // get Wi-Fi information
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
api.GET("/network/dns", service.GetDNS) // get DNS configuration
api.POST("/network/dns", service.SetDNS) // set DNS configuration
}

63
server/router/picoclaw.go Normal file
View File

@@ -0,0 +1,63 @@
package router
import (
"github.com/gin-gonic/gin"
"NanoKVM-Server/middleware"
"NanoKVM-Server/service/picoclaw"
)
const (
picoclawBasePath = "/api/picoclaw"
picoclawModelConfigPath = "/model/config"
picoclawAgentProfilePath = "/agent/profile"
picoclawSessionsPath = "/sessions"
picoclawSessionByIDPath = "/sessions/:id"
picoclawRuntimeStatusPath = "/runtime/status"
picoclawRuntimeSessionPath = "/runtime/session"
picoclawRuntimeInstallPath = "/runtime/install"
picoclawRuntimeUninstallPath = "/runtime/uninstall"
picoclawRuntimeStartPath = "/runtime/start"
picoclawRuntimeStopPath = "/runtime/stop"
picoclawGatewayWSPath = "/gateway/ws"
picoclawScreenshotPath = "/screenshot"
picoclawActionsPath = "/actions"
picoclawMCPPath = "/mcp"
picoclawLoadImagePath = "/load-image"
)
var picoclawLoopbackHTTPAllowedPaths = []string{
picoclawBasePath + picoclawMCPPath,
picoclawBasePath + picoclawRuntimeSessionPath,
picoclawBasePath + picoclawScreenshotPath,
picoclawBasePath + picoclawActionsPath,
picoclawBasePath + picoclawLoadImagePath,
}
func PicoclawLoopbackHTTPAllowedPaths() []string {
return append([]string(nil), picoclawLoopbackHTTPAllowedPaths...)
}
func picoclawRouter(r *gin.Engine, service *picoclaw.Service) {
frontendAPI := r.Group(picoclawBasePath).Use(middleware.CheckToken())
localAPI := r.Group(picoclawBasePath).Use(middleware.CheckLoopbackInternalToken())
localAPI.GET(picoclawScreenshotPath, service.Screenshot)
localAPI.POST(picoclawActionsPath, service.Actions)
localAPI.POST(picoclawMCPPath, service.MCPHandler)
localAPI.POST(picoclawLoadImagePath, service.LoadImage)
localAPI.GET(picoclawRuntimeSessionPath, service.GetRuntimeSession)
frontendAPI.POST(picoclawModelConfigPath, service.UpdateModelConfig)
frontendAPI.POST(picoclawAgentProfilePath, service.UpdateAgentProfile)
frontendAPI.GET(picoclawSessionsPath, service.ListSessions)
frontendAPI.GET(picoclawSessionByIDPath, service.GetSession)
frontendAPI.DELETE(picoclawSessionByIDPath, service.DeleteSession)
frontendAPI.GET(picoclawRuntimeStatusPath, service.GetRuntimeStatus)
frontendAPI.DELETE(picoclawRuntimeSessionPath, service.ReleaseRuntimeSession)
frontendAPI.POST(picoclawRuntimeInstallPath, service.InstallRuntime)
frontendAPI.POST(picoclawRuntimeUninstallPath, service.UninstallRuntime)
frontendAPI.POST(picoclawRuntimeStartPath, service.StartRuntime)
frontendAPI.POST(picoclawRuntimeStopPath, service.StopRuntime)
frontendAPI.GET(picoclawGatewayWSPath, service.ConnectGateway)
}

View File

@@ -5,6 +5,9 @@ import (
"os"
"path/filepath"
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/picoclaw"
"github.com/gin-gonic/contrib/static"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -29,6 +32,9 @@ func web(r *gin.Engine) {
}
func server(r *gin.Engine) {
control := controlmode.GetManager()
picoclawService := picoclaw.NewService(control)
authRouter(r)
applicationRouter(r)
vmRouter(r)
@@ -36,7 +42,16 @@ func server(r *gin.Engine) {
storageRouter(r)
networkRouter(r)
hidRouter(r)
controlRouter(r, control, picoclawService)
mcpRouter(r, control, picoclawService)
picoclawRouter(r, picoclawService)
wsRouter(r)
downloadRouter(r)
extensionsRouter(r)
}
func LoopbackHTTPAllowedPaths() []string {
paths := PicoclawLoopbackHTTPAllowedPaths()
paths = append(paths, HIDLoopbackHTTPAllowedPaths()...)
return paths
}

View File

@@ -40,6 +40,7 @@ func vmRouter(r *gin.Engine) {
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/ssh", service.GetSSHState) // get SSH state
api.POST("/vm/ssh/enable", service.EnableSSH) // enable SSH
@@ -63,5 +64,10 @@ func vmRouter(r *gin.Engine) {
api.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
api.POST("/vm/system/reboot", service.Reboot) // reboot system
}

View File

@@ -0,0 +1,76 @@
package application
import (
"fmt"
"os"
"sync"
"NanoKVM-Server/utils"
log "github.com/sirupsen/logrus"
)
var (
mutex sync.Mutex
isUpdating bool
)
func acquireUpdateLock() bool {
mutex.Lock()
defer mutex.Unlock()
if isUpdating {
return false
}
isUpdating = true
return true
}
func releaseUpdateLock() {
mutex.Lock()
defer mutex.Unlock()
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)
}
if err := backupCurrentApp(); err != nil {
return err
}
if err := applyUpdate(dir); err != nil {
return err
}
if err := utils.ChmodRecursively(AppDir, 0o755); err != nil {
return fmt.Errorf("failed to chmod: %w", err)
}
return nil
}
func backupCurrentApp() error {
if err := os.RemoveAll(BackupDir); err != nil {
return fmt.Errorf("failed to remove backup: %w", err)
}
if err := utils.MoveFilesRecursively(AppDir, BackupDir); err != nil {
return fmt.Errorf("failed to backup app: %w", err)
}
return nil
}
func applyUpdate(sourceDir string) error {
if err := utils.MoveFilesRecursively(sourceDir, AppDir); err != nil {
// Try to restore backup on failure
if restoreErr := utils.MoveFilesRecursively(BackupDir, AppDir); restoreErr != nil {
log.Errorf("Failed to restore backup after update failure: %v", restoreErr)
}
return fmt.Errorf("failed to move update in place: %w", err)
}
return nil
}

View File

@@ -0,0 +1,84 @@
package application
import (
"fmt"
"io"
"os"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
const (
sentinelPath = "/tmp/.download_in_progress"
tickerInterval = 2500 * time.Millisecond
sentinelPermission = 0644
)
// progressWriter wraps an io.Writer to track and report upload progress.
type progressWriter struct {
writer io.Writer
written int64
totalSize int64
ticker *time.Ticker
done chan struct{}
}
func newProgressWriter(w io.Writer, totalSize int64) *progressWriter {
pw := &progressWriter{
writer: w,
totalSize: totalSize,
ticker: time.NewTicker(tickerInterval),
done: make(chan struct{}),
}
go pw.reportProgress()
return pw
}
func (pw *progressWriter) reportProgress() {
for {
select {
case <-pw.done:
return
case <-pw.ticker.C:
pw.updateSentinel()
}
}
}
func (pw *progressWriter) updateSentinel() {
if pw.totalSize == 0 {
return
}
content, err := os.ReadFile(sentinelPath)
if err != nil {
log.Error("Failed to read sentinel file")
return
}
parts := strings.SplitN(string(content), ";", 2)
if len(parts) == 0 {
return
}
percentage := float64(pw.written) / float64(pw.totalSize) * 100
newContent := fmt.Sprintf("%s;%.2f%%", parts[0], percentage)
if err := os.WriteFile(sentinelPath, []byte(newContent), sentinelPermission); err != nil {
log.Error("Failed to update sentinel file")
}
}
func (pw *progressWriter) Write(p []byte) (int, error) {
n, err := pw.writer.Write(p)
pw.written += int64(n)
return n, err
}
func (pw *progressWriter) Stop() {
pw.ticker.Stop()
close(pw.done)
}

View File

@@ -8,7 +8,6 @@ import (
"net/http"
"os"
"os/exec"
"sync"
"time"
"github.com/gin-gonic/gin"
@@ -22,28 +21,14 @@ const (
maxTries = 3
)
var (
updateMutex sync.Mutex
isUpdating bool
)
func (s *Service) Update(c *gin.Context) {
var rsp proto.Response
updateMutex.Lock()
if isUpdating {
updateMutex.Unlock()
if !acquireUpdateLock() {
rsp.ErrRsp(c, -1, "update already in progress")
return
}
isUpdating = true
updateMutex.Unlock()
defer func() {
updateMutex.Lock()
isUpdating = false
updateMutex.Unlock()
}()
defer releaseUpdateLock()
if err := update(); err != nil {
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
@@ -74,7 +59,6 @@ func update() error {
// download
target := fmt.Sprintf("%s/%s", CacheDir, latest.Name)
if err := download(latest.Url, target); err != nil {
log.Errorf("download app failed: %s", err)
return err
@@ -86,34 +70,9 @@ func update() error {
return err
}
// decompress
dir, err := utils.UnTarGz(target, CacheDir)
log.Debugf("untar: %s", dir)
if err != nil {
log.Errorf("decompress app failed: %s", err)
return err
}
// backup old version
if err := os.RemoveAll(BackupDir); err != nil {
log.Errorf("remove backup failed: %s", err)
return err
}
if err := utils.MoveFilesRecursively(AppDir, BackupDir); err != nil {
log.Errorf("backup app failed: %s", err)
return err
}
// update
if err := utils.MoveFilesRecursively(dir, AppDir); err != nil {
log.Errorf("failed to move update back in place: %s", err)
return err
}
// modify permissions
if err := utils.ChmodRecursively(AppDir, 0o755); err != nil {
log.Errorf("chmod failed: %s", err)
// install
if err := installPackage(target); err != nil {
log.Errorf("failed to install package: %v", err)
return err
}
@@ -124,7 +83,7 @@ func download(url string, target string) (err error) {
for i := range maxTries {
log.Debugf("attempt #%d/%d", i+1, maxTries)
if i > 0 {
time.Sleep(time.Second * 3) // wait for 3 seconds before retrying the download attempt
time.Sleep(time.Second * 3)
}
var req *http.Request

View File

@@ -0,0 +1,183 @@
package application
import (
"fmt"
"io"
"mime/multipart"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"time"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
var validFilenameRegex = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
func (s *Service) OfflineUpdate(c *gin.Context) {
var rsp proto.Response
if !acquireUpdateLock() {
rsp.ErrRsp(c, -1, "update already in progress")
return
}
defer releaseUpdateLock()
if err := offlineUpdate(c); err != nil {
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
return
}
rsp.OkRsp(c)
log.Debugf("offline update application success")
time.Sleep(1 * time.Second)
_ = exec.Command("sh", "-c", "/etc/init.d/S95nanokvm restart").Run()
}
func offlineUpdate(c *gin.Context) error {
_ = os.RemoveAll(CacheDir)
_ = os.MkdirAll(CacheDir, 0o755)
defer func() {
_ = os.RemoveAll(CacheDir)
}()
if err := createSentinelFile(); err != nil {
return err
}
defer removeSentinelFile()
reader, err := c.Request.MultipartReader()
if err != nil {
log.Errorf("Invalid multipart data: %v", err)
return fmt.Errorf("invalid multipart data: %w", err)
}
target, err := processUpload(reader, c.Request.ContentLength)
if err != nil {
log.Errorf("failed to upload install package: %v", err)
return err
}
if err := installPackage(target); err != nil {
log.Errorf("failed to install package: %v", err)
return err
}
return nil
}
func createSentinelFile() error {
file, err := os.OpenFile(
sentinelPath,
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
sentinelPermission,
)
if err != nil {
if os.IsExist(err) {
return fmt.Errorf("download already in progress")
}
log.Errorf("Failed to create sentinel file: %v", err)
return fmt.Errorf("failed to create sentinel file: %w", err)
}
if _, err := file.WriteString("downloading"); err != nil {
_ = file.Close()
_ = os.Remove(sentinelPath)
return fmt.Errorf("failed to initialize sentinel file: %w", err)
}
if err := file.Close(); err != nil {
_ = os.Remove(sentinelPath)
return fmt.Errorf("failed to close sentinel file: %w", err)
}
return nil
}
func processUpload(reader *multipart.Reader, contentLength int64) (string, error) {
var outPath string
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
if err != nil {
return "", fmt.Errorf("failed to read multipart: %w", err)
}
if part.FormName() != "file" {
continue
}
outPath, err = saveUploadedFile(part, contentLength)
if err != nil {
return "", err
}
}
if outPath == "" {
return "", fmt.Errorf("no file uploaded")
}
return outPath, nil
}
func saveUploadedFile(part *multipart.Part, contentLength int64) (string, error) {
filename := part.FileName()
if filename == "" {
return "", fmt.Errorf("no filename provided")
}
if err := validateFilename(filename); err != nil {
return "", err
}
outPath := filepath.Join(CacheDir, filename)
out, err := os.Create(outPath)
if err != nil {
return "", fmt.Errorf("failed to create output file: %w", err)
}
defer out.Close()
pw := newProgressWriter(out, contentLength)
defer pw.Stop()
if _, err := io.Copy(pw, part); err != nil {
return "", fmt.Errorf("failed to write file: %w", err)
}
return outPath, nil
}
func validateFilename(filename string) error {
baseName := filepath.Base(filename)
// Check if the path contains directory components
if baseName != filename {
log.Warnf("Path detected in filename: %s", filename)
return fmt.Errorf("path detected in filename")
}
// Check for path traversal attempts
if strings.Contains(filename, "..") {
log.Warnf("Path traversal attempt: %s", filename)
return fmt.Errorf("invalid filename: path traversal detected")
}
// Validate filename characters
if !validFilenameRegex.MatchString(filename) {
log.Warnf("Invalid filename characters: %s", filename)
return fmt.Errorf("invalid filename: contains invalid characters")
}
return nil
}
func removeSentinelFile() {
_ = os.Remove(sentinelPath)
}

View File

@@ -1,7 +1,6 @@
package application
import (
"NanoKVM-Server/proto"
"encoding/json"
"fmt"
"io"
@@ -10,6 +9,8 @@ import (
"strings"
"time"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
@@ -36,15 +37,15 @@ func (s *Service) GetVersion(c *gin.Context) {
log.Debugf("current version: %s", currentVersion)
// latest version
latestVersion := ""
latest, err := getLatest()
if err != nil {
rsp.ErrRsp(c, -1, "get latest version failed")
return
if err == nil && latest != nil {
latestVersion = latest.Version
}
rsp.OkRspWithData(c, &proto.GetVersionRsp{
Current: currentVersion,
Latest: latest.Version,
Latest: latestVersion,
})
}

View File

@@ -0,0 +1,147 @@
package auth
import (
"sync"
"time"
"NanoKVM-Server/config"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type loginAttempt struct {
failures int
lastFailed time.Time
lockoutEnd time.Time
}
const (
maxLoginAttemptsRecords = 3000
cleanupInterval = 6 * time.Hour
)
var (
loginAttempts = make(map[string]*loginAttempt)
loginMutex sync.Mutex
cleanupOnce sync.Once
)
// startCleanupRoutine starts a background routine to clean up memory
func startCleanupRoutine() {
conf := config.GetInstance()
if conf.Security.LoginLockoutDuration <= 0 {
return
}
go func() {
ticker := time.NewTicker(cleanupInterval)
for range ticker.C {
loginMutex.Lock()
now := time.Now()
for ip, attempt := range loginAttempts {
// Cleanup rules: if it has been locked and the lockout time has passed,
// or (although not locked) it has been 30 minutes since the last failure,
// remove this record
if (!attempt.lockoutEnd.IsZero() && now.After(attempt.lockoutEnd)) ||
(attempt.lockoutEnd.IsZero() && now.Sub(attempt.lastFailed) > 30*time.Minute) {
delete(loginAttempts, ip)
}
}
loginMutex.Unlock()
}
}()
}
// GetClientIP gets a reliable real IP
func GetClientIP(c *gin.Context) string {
ip := c.RemoteIP()
if ip == "" {
ip = c.ClientIP()
}
return ip
}
// CheckLoginAttempt checks if a login attempt is allowed based on brute-force protection rules.
// Returning true means the IP/System is locked out, and an error string and error code are returned.
func CheckLoginAttempt(clientIP string) (bool, int, string) {
conf := config.GetInstance()
if conf.Security.LoginLockoutDuration <= 0 {
return false, 0, ""
}
cleanupOnce.Do(startCleanupRoutine)
loginMutex.Lock()
defer loginMutex.Unlock()
if attempt, exists := loginAttempts[clientIP]; exists {
if time.Now().Before(attempt.lockoutEnd) {
log.Debugf("login blocked for IP %s: account locked due to too many failed attempts (until %s)", clientIP, attempt.lockoutEnd)
return true, -5, "Account locked due to too many failed attempts, please try again later"
}
// If lockout has elapsed, then we reset the failures and lockoutEnd.
if !attempt.lockoutEnd.IsZero() {
attempt.failures = 0
attempt.lockoutEnd = time.Time{}
}
}
return false, 0, ""
}
// RecordLoginFailure records a failed login attempt for the given IP address.
func RecordLoginFailure(clientIP string) (bool, int, string) {
conf := config.GetInstance()
if conf.Security.LoginLockoutDuration <= 0 {
return false, 0, ""
}
cleanupOnce.Do(startCleanupRoutine)
loginMutex.Lock()
defer loginMutex.Unlock()
attempt, exists := loginAttempts[clientIP]
if !exists {
// When the record pool is full, clear the records instead of global lockout to prevent DDoS
if len(loginAttempts) >= maxLoginAttemptsRecords {
log.Warn("Login attempt records reached maximum limit, clearing records to prevent memory overflow")
loginAttempts = make(map[string]*loginAttempt)
}
attempt = &loginAttempt{}
loginAttempts[clientIP] = attempt
}
now := time.Now()
// Failure time window: if it has been a long time since the last failure
// (e.g., beyond the lockoutDuration window), reset the failure count
if !attempt.lastFailed.IsZero() && now.Sub(attempt.lastFailed) > time.Duration(conf.Security.LoginLockoutDuration)*time.Second {
attempt.failures = 0
}
attempt.failures++
attempt.lastFailed = now
// Reach the failure limit, lock out
if attempt.failures >= conf.Security.LoginMaxFailures {
attempt.lockoutEnd = now.Add(time.Duration(conf.Security.LoginLockoutDuration) * time.Second)
log.Debugf("login failures reached threshold for IP %s, locking out until %s", clientIP, attempt.lockoutEnd)
}
return false, 0, ""
}
// ClearLoginAttempt clears the failed login attempt record for an IP upon successful login.
func ClearLoginAttempt(clientIP string) {
conf := config.GetInstance()
if conf.Security.LoginLockoutDuration <= 0 {
return
}
loginMutex.Lock()
defer loginMutex.Unlock()
delete(loginAttempts, clientIP)
}

View File

@@ -1,10 +1,11 @@
package auth
import (
"time"
"NanoKVM-Server/config"
"NanoKVM-Server/middleware"
"NanoKVM-Server/proto"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
@@ -23,6 +24,13 @@ func (s *Service) Login(c *gin.Context) {
return
}
clientIP := GetClientIP(c)
if locked, code, msg := CheckLoginAttempt(clientIP); locked {
time.Sleep(3 * time.Second)
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")
@@ -31,10 +39,18 @@ func (s *Service) Login(c *gin.Context) {
if ok := CompareAccount(req.Username, req.Password); !ok {
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")
return
}
ClearLoginAttempt(clientIP)
token, err := middleware.GenerateJWT(req.Username)
if err != nil {
time.Sleep(1 * time.Second)

View File

@@ -0,0 +1,97 @@
package controlmode
import (
"errors"
"sync"
"time"
)
var ErrActivityWaitTimeout = errors.New("timed out waiting for active control operations")
// activityGate allows normal control operations to share the current mode while
// giving mode transitions exclusive access. Unlike sync.RWMutex, exclusive
// acquisition is bounded so an abandoned client cannot leave the manager stuck
// in the transitioning state forever.
type activityGate struct {
mu sync.Mutex
active int
exclusive bool
changed chan struct{}
}
func (g *activityGate) acquireShared() func() {
for {
g.mu.Lock()
if !g.exclusive {
g.active++
g.mu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
g.mu.Lock()
if g.active > 0 {
g.active--
}
g.signalLocked()
g.mu.Unlock()
})
}
}
changed := g.changedLocked()
g.mu.Unlock()
<-changed
}
}
func (g *activityGate) acquireExclusive(timeout time.Duration) (func(), error) {
if timeout <= 0 {
return nil, ErrActivityWaitTimeout
}
timer := time.NewTimer(timeout)
defer timer.Stop()
for {
g.mu.Lock()
if !g.exclusive && g.active == 0 {
g.exclusive = true
g.mu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
g.mu.Lock()
g.exclusive = false
g.signalLocked()
g.mu.Unlock()
})
}, nil
}
changed := g.changedLocked()
g.mu.Unlock()
select {
case <-changed:
case <-timer.C:
return nil, ErrActivityWaitTimeout
}
}
}
func (g *activityGate) changedLocked() <-chan struct{} {
if g.changed == nil {
g.changed = make(chan struct{})
}
return g.changed
}
func (g *activityGate) signalLocked() {
if g.changed == nil {
return
}
close(g.changed)
g.changed = make(chan struct{})
}

View File

@@ -0,0 +1,555 @@
package controlmode
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
const ModeFile = "/etc/kvm/ai-control.mode"
const defaultActivityWaitTimeout = 30 * time.Second
type Mode string
const (
ModeOff Mode = "off"
ModeMCP Mode = "mcp"
ModePicoclaw Mode = "picoclaw"
)
var ErrModeConflict = errors.New("AI control mode conflict")
type Status struct {
Mode Mode `json:"mode"`
Transitioning bool `json:"transitioning"`
LastError string `json:"last_error,omitempty"`
ChangedAt time.Time `json:"changed_at,omitempty"`
}
type Manager struct {
transitionMu sync.Mutex
activity activityGate
mu sync.Mutex
path string
defaultMode Mode
activityWaitTimeout time.Duration
loaded bool
mode Mode
modeFileExists bool
modeFileSize int64
modeFileModTime time.Time
transitioning bool
lastError string
changedAt time.Time
}
var (
defaultManagerOnce sync.Once
defaultManager *Manager
)
func GetManager() *Manager {
defaultManagerOnce.Do(func() {
defaultManager = NewManager(ModeFile, ModePicoclaw)
})
return defaultManager
}
func NewManager(path string, defaultMode Mode) *Manager {
if !validMode(defaultMode) {
defaultMode = ModeOff
}
return &Manager{
path: path,
defaultMode: defaultMode,
activityWaitTimeout: defaultActivityWaitTimeout,
}
}
func (m *Manager) Status() (Status, error) {
m.mu.Lock()
defer m.mu.Unlock()
if err := m.loadLocked(); err != nil {
return Status{Mode: ModeOff, Transitioning: m.transitioning, LastError: err.Error(), ChangedAt: m.changedAt}, err
}
return m.statusLocked(), nil
}
func (m *Manager) Current() Mode {
status, err := m.Status()
if err != nil {
return ModeOff
}
return status.Mode
}
func (m *Manager) RequireWrite(expected Mode) error {
status, err := m.Status()
if err != nil {
return err
}
if status.Transitioning || status.Mode != expected {
return fmt.Errorf("%w: current=%s expected=%s", ErrModeConflict, status.Mode, expected)
}
return nil
}
func (m *Manager) Require(expected Mode) error {
return m.RequireWrite(expected)
}
func (m *Manager) RequireMode(expected Mode) error {
status, err := m.Status()
if err != nil {
return err
}
if status.Mode != expected {
return fmt.Errorf("%w: current=%s expected=%s", ErrModeConflict, status.Mode, expected)
}
return nil
}
func (m *Manager) AcquireWrite(expected Mode) (func(), error) {
if err := m.RequireWrite(expected); err != nil {
return nil, err
}
release := m.activity.acquireShared()
if err := m.RequireWrite(expected); err != nil {
release()
return nil, err
}
return release, nil
}
func (m *Manager) Acquire(expected Mode) (func(), error) {
return m.AcquireWrite(expected)
}
// AcquireStable holds the current control mode stable while a non-AI input
// operation is in flight. Mode transitions take the exclusive side of the
// activity gate, so they wait until the returned release function is called.
func (m *Manager) AcquireStable() (Status, func(), error) {
status, err := m.Status()
if err != nil {
return Status{Mode: ModeOff}, nil, err
}
if status.Transitioning {
return status, nil, fmt.Errorf("%w: control mode is transitioning", ErrModeConflict)
}
release := m.activity.acquireShared()
status, err = m.Status()
if err != nil {
release()
return Status{Mode: ModeOff}, nil, err
}
if status.Transitioning {
release()
return status, nil, fmt.Errorf("%w: control mode is transitioning", ErrModeConflict)
}
return status, release, nil
}
func (m *Manager) Switch(next Mode, preempt func() error) error {
return m.SwitchWithCleanup(next, preempt, nil)
}
func (m *Manager) SwitchWithCleanup(next Mode, preempt func() error, cleanup func() error) error {
startedAt := time.Now()
timings := log.Fields{
"to": string(next),
}
m.transitionMu.Lock()
defer m.transitionMu.Unlock()
stageStartedAt := time.Now()
status, err := m.Status()
timings["load_status_ms"] = elapsedMilliseconds(stageStartedAt)
if err != nil {
logModeSwitchFailure("AI control mode switch failed while loading status", timings, err, startedAt)
return err
}
timings["from"] = string(status.Mode)
if !validMode(next) {
err := fmt.Errorf("invalid AI control mode %q", next)
logModeSwitchFailure("AI control mode switch rejected invalid target", timings, err, startedAt)
return err
}
if status.Mode == next {
timings["total_ms"] = elapsedMilliseconds(startedAt)
log.WithFields(timings).Debug("AI control mode switch skipped")
return nil
}
m.setTransitioning(true)
defer m.setTransitioning(false)
if preempt != nil {
stageStartedAt = time.Now()
if err := callModeTransitionHook(preempt); err != nil {
timings["preempt_ms"] = elapsedMilliseconds(stageStartedAt)
m.setLastError(err)
logModeSwitchFailure("AI control mode switch preempt failed", timings, err, startedAt)
return err
}
timings["preempt_ms"] = elapsedMilliseconds(stageStartedAt)
}
stageStartedAt = time.Now()
releaseActivity, err := m.acquireExclusiveActivity()
timings["activity_wait_ms"] = elapsedMilliseconds(stageStartedAt)
if err != nil {
m.setLastError(err)
logModeSwitchFailure("AI control mode switch activity wait failed", timings, err, startedAt)
return err
}
defer releaseActivity()
if cleanup != nil {
stageStartedAt = time.Now()
if err := callModeTransitionHook(cleanup); err != nil {
timings["cleanup_ms"] = elapsedMilliseconds(stageStartedAt)
if rollbackErr := m.save(ModeOff); rollbackErr != nil {
err = errors.Join(err, rollbackErr)
}
m.setLastError(err)
logModeSwitchFailure("AI control mode switch cleanup failed", timings, err, startedAt)
return err
}
timings["cleanup_ms"] = elapsedMilliseconds(stageStartedAt)
}
stageStartedAt = time.Now()
if err := m.save(next); err != nil {
timings["save_mode_ms"] = elapsedMilliseconds(stageStartedAt)
m.setLastError(err)
logModeSwitchFailure("AI control mode switch save failed", timings, err, startedAt)
return err
}
timings["save_mode_ms"] = elapsedMilliseconds(stageStartedAt)
m.setLastError(nil)
timings["total_ms"] = elapsedMilliseconds(startedAt)
log.WithFields(timings).Info("AI control mode switch completed")
return nil
}
func (m *Manager) SwitchIf(expected Mode, next Mode, preempt func() error) (bool, error) {
return m.SwitchIfWithCleanup(expected, next, preempt, nil)
}
func (m *Manager) SwitchIfWithCleanup(expected Mode, next Mode, preempt func() error, cleanup func() error) (bool, error) {
startedAt := time.Now()
timings := log.Fields{
"expected": string(expected),
"to": string(next),
}
if !validMode(expected) || !validMode(next) {
err := fmt.Errorf("invalid AI control mode transition %q -> %q", expected, next)
logModeSwitchFailure("conditional AI control mode switch rejected invalid transition", timings, err, startedAt)
return false, err
}
m.transitionMu.Lock()
defer m.transitionMu.Unlock()
stageStartedAt := time.Now()
status, err := m.Status()
timings["load_status_ms"] = elapsedMilliseconds(stageStartedAt)
if err != nil {
logModeSwitchFailure("conditional AI control mode switch failed while loading status", timings, err, startedAt)
return false, err
}
timings["from"] = string(status.Mode)
if status.Mode != expected {
timings["matched"] = false
timings["total_ms"] = elapsedMilliseconds(startedAt)
log.WithFields(timings).Debug("conditional AI control mode switch skipped")
return false, nil
}
if status.Mode == next {
timings["matched"] = true
timings["total_ms"] = elapsedMilliseconds(startedAt)
log.WithFields(timings).Debug("conditional AI control mode switch already satisfied")
return true, nil
}
m.setTransitioning(true)
defer m.setTransitioning(false)
if preempt != nil {
stageStartedAt = time.Now()
if err := callModeTransitionHook(preempt); err != nil {
timings["preempt_ms"] = elapsedMilliseconds(stageStartedAt)
m.setLastError(err)
logModeSwitchFailure("conditional AI control mode switch preempt failed", timings, err, startedAt)
return false, err
}
timings["preempt_ms"] = elapsedMilliseconds(stageStartedAt)
}
stageStartedAt = time.Now()
releaseActivity, err := m.acquireExclusiveActivity()
timings["activity_wait_ms"] = elapsedMilliseconds(stageStartedAt)
if err != nil {
m.setLastError(err)
logModeSwitchFailure("conditional AI control mode switch activity wait failed", timings, err, startedAt)
return false, err
}
defer releaseActivity()
if cleanup != nil {
stageStartedAt = time.Now()
if err := callModeTransitionHook(cleanup); err != nil {
timings["cleanup_ms"] = elapsedMilliseconds(stageStartedAt)
if rollbackErr := m.save(ModeOff); rollbackErr != nil {
err = errors.Join(err, rollbackErr)
}
m.setLastError(err)
logModeSwitchFailure("conditional AI control mode switch cleanup failed", timings, err, startedAt)
return false, err
}
timings["cleanup_ms"] = elapsedMilliseconds(stageStartedAt)
}
stageStartedAt = time.Now()
if err := m.save(next); err != nil {
timings["save_mode_ms"] = elapsedMilliseconds(stageStartedAt)
m.setLastError(err)
logModeSwitchFailure("conditional AI control mode switch save failed", timings, err, startedAt)
return false, err
}
timings["save_mode_ms"] = elapsedMilliseconds(stageStartedAt)
m.setLastError(nil)
timings["matched"] = true
timings["total_ms"] = elapsedMilliseconds(startedAt)
log.WithFields(timings).Info("conditional AI control mode switch completed")
return true, nil
}
func (m *Manager) SwitchToMCP(preempt func() error) error {
return m.Switch(ModeMCP, preempt)
}
func (m *Manager) SwitchToMCPWithPreempt(preempt func() error) error {
return m.Switch(ModeMCP, preempt)
}
func (m *Manager) SwitchToPicoclaw(preempt func() error) error {
return m.Switch(ModePicoclaw, preempt)
}
func (m *Manager) SwitchToPicoclawWithPreempt(preempt func() error) error {
return m.Switch(ModePicoclaw, preempt)
}
func (m *Manager) SwitchOff(preempt func() error) error {
return m.Switch(ModeOff, preempt)
}
func (m *Manager) SwitchOffIf(expected Mode, preempt func() error) (bool, error) {
return m.SwitchIf(expected, ModeOff, preempt)
}
func (m *Manager) SwitchOffIfWithPreempt(expected Mode, preempt func() error) (bool, error) {
return m.SwitchIf(expected, ModeOff, preempt)
}
func callModeTransitionHook(hook func() error) (err error) {
defer func() {
if recovered := recover(); recovered != nil {
err = fmt.Errorf("panic: %v", recovered)
}
}()
return hook()
}
func (m *Manager) setTransitioning(transitioning bool) {
m.mu.Lock()
defer m.mu.Unlock()
m.transitioning = transitioning
}
func (m *Manager) setLastError(err error) {
m.mu.Lock()
defer m.mu.Unlock()
if err == nil {
m.lastError = ""
return
}
m.lastError = err.Error()
}
func (m *Manager) statusLocked() Status {
return Status{
Mode: m.mode,
Transitioning: m.transitioning,
LastError: m.lastError,
ChangedAt: m.changedAt,
}
}
func (m *Manager) acquireExclusiveActivity() (func(), error) {
timeout := m.activityWaitTimeout
if timeout <= 0 {
timeout = defaultActivityWaitTimeout
}
release, err := m.activity.acquireExclusive(timeout)
if err != nil {
return nil, fmt.Errorf("wait for active control operations: %w", err)
}
return release, nil
}
func (m *Manager) save(mode Mode) error {
m.mu.Lock()
defer m.mu.Unlock()
return m.saveLocked(mode)
}
func (m *Manager) loadLocked() error {
if m.loaded && m.transitioning {
return nil
}
info, statErr := os.Stat(m.path)
if m.loaded && statErr == nil && m.modeFileExists && info.Size() == m.modeFileSize && info.ModTime().Equal(m.modeFileModTime) {
return nil
}
if m.loaded && errors.Is(statErr, os.ErrNotExist) && !m.modeFileExists {
return nil
}
if statErr != nil && !errors.Is(statErr, os.ErrNotExist) {
return fmt.Errorf("stat AI control mode: %w", statErr)
}
data, err := os.ReadFile(m.path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
m.mode = m.defaultMode
m.loaded = true
m.modeFileExists = false
m.modeFileSize = 0
m.modeFileModTime = time.Time{}
if m.changedAt.IsZero() {
m.changedAt = time.Now()
}
return nil
}
return fmt.Errorf("read AI control mode: %w", err)
}
mode := Mode(strings.TrimSpace(string(data)))
if !validMode(mode) {
m.mode = ModeOff
m.loaded = true
m.lastError = fmt.Sprintf("invalid AI control mode %q", strings.TrimSpace(string(data)))
m.cacheModeFileInfoLocked(info, data)
return nil
}
m.mode = mode
m.loaded = true
m.lastError = ""
m.cacheModeFileInfoLocked(info, data)
return nil
}
func (m *Manager) saveLocked(mode Mode) error {
if !validMode(mode) {
return fmt.Errorf("invalid AI control mode %q", mode)
}
dir := filepath.Dir(m.path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create AI control mode directory: %w", err)
}
tmp, err := os.CreateTemp(dir, ".ai-control.mode.*")
if err != nil {
return fmt.Errorf("create temporary AI control mode: %w", err)
}
tmpPath := tmp.Name()
defer func() { _ = os.Remove(tmpPath) }()
if err := tmp.Chmod(0o600); err != nil {
_ = tmp.Close()
return fmt.Errorf("set AI control mode permissions: %w", err)
}
if _, err := tmp.WriteString(string(mode) + "\n"); err != nil {
_ = tmp.Close()
return fmt.Errorf("write AI control mode: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync AI control mode: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close AI control mode: %w", err)
}
if err := os.Rename(tmpPath, m.path); err != nil {
return fmt.Errorf("replace AI control mode: %w", err)
}
m.mode = mode
m.loaded = true
if info, err := os.Stat(m.path); err == nil {
m.cacheModeFileInfoLocked(info, []byte(string(mode)+"\n"))
} else {
m.modeFileExists = true
m.modeFileSize = int64(len(string(mode) + "\n"))
m.modeFileModTime = time.Now()
}
m.changedAt = time.Now()
directory, err := os.Open(dir)
if err == nil {
if syncErr := directory.Sync(); syncErr != nil {
_ = directory.Close()
return fmt.Errorf("sync AI control mode directory: %w", syncErr)
}
_ = directory.Close()
}
return nil
}
func (m *Manager) cacheModeFileInfoLocked(info os.FileInfo, data []byte) {
m.modeFileExists = true
if info != nil {
m.modeFileSize = info.Size()
m.modeFileModTime = info.ModTime()
if m.changedAt.IsZero() || info.ModTime().After(m.changedAt) {
m.changedAt = info.ModTime()
}
return
}
m.modeFileSize = int64(len(data))
m.modeFileModTime = time.Now()
m.changedAt = m.modeFileModTime
}
func validMode(mode Mode) bool {
switch mode {
case ModeOff, ModeMCP, ModePicoclaw:
return true
default:
return false
}
}
func elapsedMilliseconds(startedAt time.Time) int64 {
return time.Since(startedAt).Milliseconds()
}
func logModeSwitchFailure(message string, fields log.Fields, err error, startedAt time.Time) {
fields["total_ms"] = elapsedMilliseconds(startedAt)
log.WithFields(fields).WithError(err).Warn(message)
}

View File

@@ -0,0 +1,202 @@
package controlmode
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestManagerDefaultsToPicoclaw(t *testing.T) {
manager := NewManager(filepath.Join(t.TempDir(), "mode"), ModePicoclaw)
if got := manager.Current(); got != ModePicoclaw {
t.Fatalf("mode = %q, want %q", got, ModePicoclaw)
}
}
func TestSwitchPreemptsBeforeWaitingForActiveWrite(t *testing.T) {
manager := NewManager(filepath.Join(t.TempDir(), "mode"), ModeMCP)
release, err := manager.AcquireWrite(ModeMCP)
if err != nil {
t.Fatal(err)
}
preempted := make(chan struct{})
done := make(chan error, 1)
go func() {
done <- manager.Switch(ModePicoclaw, func() error {
close(preempted)
return nil
})
}()
select {
case <-preempted:
case <-time.After(time.Second):
t.Fatal("preempt callback was not called before waiting")
}
if _, err := manager.AcquireWrite(ModeMCP); err == nil {
t.Fatal("new write acquired control during transition")
}
release()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("switch did not resume after active write was released")
}
if got := manager.Current(); got != ModePicoclaw {
t.Fatalf("mode = %q, want picoclaw", got)
}
}
func TestSwitchRunsCleanupAfterActiveWritesDrain(t *testing.T) {
manager := NewManager(filepath.Join(t.TempDir(), "mode"), ModePicoclaw)
release, err := manager.AcquireWrite(ModePicoclaw)
if err != nil {
t.Fatal(err)
}
cleanupCalled := make(chan struct{})
done := make(chan error, 1)
go func() {
done <- manager.SwitchWithCleanup(ModeMCP, nil, func() error {
close(cleanupCalled)
return nil
})
}()
select {
case <-cleanupCalled:
t.Fatal("cleanup ran before active write drained")
case <-time.After(20 * time.Millisecond):
}
release()
select {
case err := <-done:
if err != nil {
t.Fatal(err)
}
case <-time.After(time.Second):
t.Fatal("switch did not finish")
}
select {
case <-cleanupCalled:
default:
t.Fatal("cleanup was not called")
}
}
func TestSwitchCleanupFailureFailsClosed(t *testing.T) {
path := filepath.Join(t.TempDir(), "mode")
manager := NewManager(path, ModePicoclaw)
wantErr := errors.New("hid release failed")
if err := manager.SwitchWithCleanup(ModeMCP, nil, func() error { return wantErr }); !errors.Is(err, wantErr) {
t.Fatalf("error = %v, want %v", err, wantErr)
}
if got := manager.Current(); got != ModeOff {
t.Fatalf("mode = %q, want off after cleanup failure", got)
}
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(data) != "off\n" {
t.Fatalf("mode file = %q, want off", data)
}
}
func TestSwitchIfKeepsDifferentMode(t *testing.T) {
manager := NewManager(filepath.Join(t.TempDir(), "mode"), ModePicoclaw)
switched, err := manager.SwitchIf(ModeMCP, ModeOff, nil)
if err != nil {
t.Fatal(err)
}
if switched || manager.Current() != ModePicoclaw {
t.Fatalf("switched=%v mode=%q, want unchanged picoclaw", switched, manager.Current())
}
}
func TestSwitchTimeoutDoesNotLeaveManagerTransitioning(t *testing.T) {
manager := NewManager(filepath.Join(t.TempDir(), "mode"), ModeMCP)
manager.activityWaitTimeout = 20 * time.Millisecond
cleanupCalled := false
status, release, err := manager.AcquireStable()
if err != nil {
t.Fatal(err)
}
if status.Mode != ModeMCP {
t.Fatalf("mode = %q, want MCP", status.Mode)
}
err = manager.SwitchWithCleanup(ModePicoclaw, nil, func() error {
cleanupCalled = true
return nil
})
if !errors.Is(err, ErrActivityWaitTimeout) {
t.Fatalf("switch error = %v, want %v", err, ErrActivityWaitTimeout)
}
if cleanupCalled {
t.Fatal("cleanup ran even though exclusive activity lease was not acquired")
}
status, err = manager.Status()
if err != nil {
t.Fatal(err)
}
if status.Mode != ModeMCP || status.Transitioning {
t.Fatalf("status after timeout = %+v, want stable MCP", status)
}
release()
if err := manager.Switch(ModePicoclaw, nil); err != nil {
t.Fatalf("switch after lease release failed: %v", err)
}
}
func TestInvalidModeFailsClosed(t *testing.T) {
path := filepath.Join(t.TempDir(), "mode")
if err := os.WriteFile(path, []byte("invalid\n"), 0o600); err != nil {
t.Fatal(err)
}
manager := NewManager(path, ModePicoclaw)
status, err := manager.Status()
if err != nil {
t.Fatal(err)
}
if status.Mode != ModeOff {
t.Fatalf("mode = %q, want off", status.Mode)
}
if !strings.Contains(status.LastError, "invalid") {
t.Fatalf("last_error = %q, want invalid mode detail", status.LastError)
}
}
func TestStatusReloadsExternallyModifiedModeFile(t *testing.T) {
path := filepath.Join(t.TempDir(), "mode")
if err := os.WriteFile(path, []byte("off\n"), 0o600); err != nil {
t.Fatal(err)
}
manager := NewManager(path, ModePicoclaw)
if got := manager.Current(); got != ModeOff {
t.Fatalf("initial mode = %q, want off", got)
}
if err := os.WriteFile(path, []byte("mcp\n"), 0o600); err != nil {
t.Fatal(err)
}
modTime := time.Now().Add(time.Second)
if err := os.Chtimes(path, modTime, modTime); err != nil {
t.Fatal(err)
}
if got := manager.Current(); got != ModeMCP {
t.Fatalf("mode after external write = %q, want MCP", got)
}
}

View File

@@ -2,99 +2,325 @@ package download
import (
"NanoKVM-Server/proto"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type Service struct{}
type downloadStatus string
var sentinelPath = "/tmp/.download_in_progress"
const (
transferSentinelPath = "/tmp/.download_in_progress"
downloadStatusIdle downloadStatus = "idle"
downloadStatusInProgress downloadStatus = "in_progress"
downloadStatusSuccess downloadStatus = "success"
downloadStatusFailed downloadStatus = "failed"
downloadStatusChecksumFailed downloadStatus = "checksum_failed"
)
var (
errDownloadInProgress = errors.New("download in progress")
errSHA256Mismatch = errors.New("sha256 mismatch")
validISOFilename = regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
)
type Service struct {
downloadMutex sync.Mutex
downloadCancel context.CancelFunc
downloadDone chan struct{}
downloadStatus downloadStatus
downloadFile string
downloadPercentage string
}
func NewService() *Service {
// Clear sentinel
// If we are starting from scratch, we need to remove the sentinel file as any downloads at this point are done or broken
_ = os.Remove(sentinelPath)
return &Service{}
// A running transfer cannot survive a server restart, so any remaining lock
// file is stale at this point.
_ = os.Remove(transferSentinelPath)
return &Service{downloadStatus: downloadStatusIdle}
}
func (s *Service) CancelDownloadImage(c *gin.Context) {
var rsp proto.Response
s.downloadMutex.Lock()
cancel := s.downloadCancel
done := s.downloadDone
s.downloadMutex.Unlock()
if cancel == nil || done == nil {
rsp.ErrRsp(c, -1, "no cancellable download in progress")
return
}
cancel()
select {
case <-done:
rsp.OkRsp(c)
case <-time.After(10 * time.Second):
rsp.ErrRsp(c, -1, "cancel download timed out")
}
}
func (s *Service) beginDownload(file string, cancel context.CancelFunc) (chan struct{}, error) {
s.downloadMutex.Lock()
defer s.downloadMutex.Unlock()
if s.downloadDone != nil {
return nil, errDownloadInProgress
}
lockFile, err := os.OpenFile(
transferSentinelPath,
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
0o644,
)
if err != nil {
if os.IsExist(err) {
return nil, errDownloadInProgress
}
return nil, fmt.Errorf("acquire transfer lock failed: %w", err)
}
if err := lockFile.Close(); err != nil {
_ = os.Remove(transferSentinelPath)
return nil, fmt.Errorf("close transfer lock failed: %w", err)
}
done := make(chan struct{})
s.downloadCancel = cancel
s.downloadDone = done
s.downloadStatus = downloadStatusInProgress
s.downloadFile = file
s.downloadPercentage = ""
return done, nil
}
func (s *Service) setDownloadFile(done chan struct{}, file string) {
s.downloadMutex.Lock()
defer s.downloadMutex.Unlock()
if s.downloadDone == done {
s.downloadFile = file
}
}
func (s *Service) setDownloadProgress(done chan struct{}, percentage string) {
s.downloadMutex.Lock()
defer s.downloadMutex.Unlock()
if s.downloadDone == done {
s.downloadPercentage = percentage
}
}
func (s *Service) finishDownload(done chan struct{}, status downloadStatus) {
s.downloadMutex.Lock()
if s.downloadDone != done {
s.downloadMutex.Unlock()
return
}
s.downloadCancel = nil
s.downloadDone = nil
s.downloadStatus = status
s.downloadFile = ""
s.downloadPercentage = ""
_ = os.Remove(transferSentinelPath)
s.downloadMutex.Unlock()
close(done)
}
func (s *Service) ImageEnabled(c *gin.Context) {
var rsp proto.Response
// Check if /data mount is RO/RW
testFile := "/data/.testfile"
file, err := os.Create(testFile)
defer file.Close()
defer os.Remove(testFile)
if err != nil {
if os.IsPermission(err) {
rsp.OkRspWithData(c, &proto.ImageEnabledRsp{
Enabled: false,
})
return
}
rsp.OkRspWithData(c, &proto.ImageEnabledRsp{
Enabled: false,
})
rsp.OkRspWithData(c, &proto.ImageEnabledRsp{Enabled: false})
return
}
defer file.Close()
defer os.Remove(testFile)
rsp.OkRspWithData(c, &proto.ImageEnabledRsp{
Enabled: true,
})
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
}
buf := make([]byte, 5)
if _, err = io.ReadFull(f, buf); err != nil {
return false, err
}
return string(buf) == "CD001", nil
}
func (s *Service) StatusImage(c *gin.Context) {
var rsp proto.Response
// Check if the sentinel file exists
log.Debug("StatusImage")
if _, err := os.Stat(sentinelPath); err == nil {
content, err := os.ReadFile(sentinelPath)
if err != nil {
log.Error("Failed to read sentinel file")
rsp.OkRspWithData(c, &proto.StatusImageRsp{
Status: "in_progress",
File: "",
Percentage: "",
})
return
}
splitted := strings.Split(string(content), ";")
if len(splitted) == 1 {
// No percentage, just the URL
rsp.OkRspWithData(c, &proto.StatusImageRsp{
Status: "in_progress",
File: splitted[0],
Percentage: "",
})
} else {
// Percentage is available
rsp.OkRspWithData(c, &proto.StatusImageRsp{
Status: "in_progress",
File: splitted[0],
Percentage: splitted[1],
})
}
s.downloadMutex.Lock()
status := s.downloadStatus
file := s.downloadFile
percentage := s.downloadPercentage
s.downloadMutex.Unlock()
return
}
rsp.OkRspWithData(c, &proto.StatusImageRsp{
Status: "idle",
File: "",
Percentage: "",
Status: string(status),
File: file,
Percentage: percentage,
})
}
func (s *Service) DownloadImageFile(c *gin.Context) {
var rsp proto.Response
log.Debug("DownloadImageFile")
expectedSHA256, err := parseSHA256(c.GetHeader("X-SHA256-Sum"))
if err != nil {
rsp.ErrRsp(c, -1, err.Error())
return
}
done, err := s.beginDownload("", nil)
if err != nil {
rsp.ErrRsp(c, -1, err.Error())
return
}
finalStatus := downloadStatusFailed
defer func() {
s.finishDownload(done, finalStatus)
}()
reader, err := c.Request.MultipartReader()
if err != nil {
log.Error("invalid multipart data")
rsp.ErrRsp(c, -1, "invalid multipart data")
return
}
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
if err != nil {
log.Error("failed to read part")
rsp.ErrRsp(c, -1, "failed to read part")
return
}
if part.FormName() != "file" {
_ = part.Close()
continue
}
filename := part.FileName()
if err := validateISOFilename(filename); err != nil {
_ = part.Close()
rsp.ErrRsp(c, -1, err.Error())
return
}
s.setDownloadFile(done, filename)
out, err := os.CreateTemp("/data", ".nanokvm-upload-*")
if err != nil {
_ = part.Close()
log.Error("cannot create temporary file")
rsp.ErrRsp(c, -1, "cannot create temporary file")
return
}
tempPath := out.Name()
defer os.Remove(tempPath)
hasher := sha256.New()
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")
rsp.ErrRsp(c, -1, "write failed")
return
}
if expectedSHA256 != nil && !bytes.Equal(hasher.Sum(nil), expectedSHA256) {
finalStatus = downloadStatusChecksumFailed
rsp.ErrRsp(c, -1, errSHA256Mismatch.Error())
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)
if err := os.Rename(tempPath, outPath); err != nil {
rsp.ErrRsp(c, -1, "cannot install uploaded image")
return
}
finalStatus = downloadStatusIdle
rsp.OkRspWithData(c, &proto.StatusImageRsp{
Status: string(downloadStatusIdle),
File: "",
Percentage: "",
})
return
}
rsp.ErrRsp(c, -1, "file is required")
}
func validateISOFilename(filename string) error {
if filename == "" {
return errors.New("no filename")
}
if filepath.Base(filename) != filename || strings.Contains(filename, "..") {
return errors.New("invalid filename")
}
if !strings.HasSuffix(strings.ToLower(filename), ".iso") {
return errors.New("only .iso files allowed")
}
if !validISOFilename.MatchString(filename) {
return errors.New("invalid filename")
}
return nil
}
func (s *Service) DownloadImage(c *gin.Context) {
var req proto.MountImageReq
var req proto.DownloadImageReq
var rsp proto.Response
log.Debug("DownloadImage")
@@ -104,127 +330,190 @@ func (s *Service) DownloadImage(c *gin.Context) {
return
}
if req.File == "" {
rsp.ErrRsp(c, -1, "invalid arguments")
expectedSHA256, err := parseSHA256(req.SHA256Sum)
if err != nil {
rsp.ErrRsp(c, -1, err.Error())
return
}
// Parse the URI to see if its valid http/s
u, err := url.Parse(req.File)
if err != nil || u.Scheme == "" || u.Host == "" {
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.Path == "" {
rsp.ErrRsp(c, -1, "invalid url")
return
}
filename := filepath.Base(u.Path)
if filename == "." || filename == "/" || filename == "" {
rsp.ErrRsp(c, -1, "invalid url")
return
}
// Set a sentinel file to mark that there is a download in progress
// This is to prevent multiple downloads at the same time
if _, err := os.Stat(sentinelPath); err == nil {
log.Debug("Download in progress")
rsp.ErrRsp(c, -1, "download in progress")
return
}
// Create the sentinel file
err = os.WriteFile(sentinelPath, []byte(req.File), 0644)
ctx, cancel := context.WithCancel(context.Background())
done, err := s.beginDownload(req.File, cancel)
if err != nil {
log.Error("Failed to create sentinel file")
rsp.ErrRsp(c, -1, "failed to create sentinel file")
cancel()
rsp.ErrRsp(c, -1, err.Error())
return
}
// Check if it actually exists and fail if it doesn't
resp, err := http.Head(req.File)
if resp.StatusCode != http.StatusOK || err != nil {
rsp.ErrRsp(c, resp.StatusCode, "failed when checking the url")
log.Error("Failed to check the URL")
defer os.Remove(sentinelPath)
return
}
defer resp.Body.Close()
// Download the image in a goroutine to not block the request
go func() {
defer os.Remove(sentinelPath)
resp, err = http.Get(req.File)
if err != nil {
log.Error("Failed to download the file")
rsp.ErrRsp(c, -1, "failed to download the file")
return
}
defer resp.Body.Close()
// Create the destination file
destPath := filepath.Join("/data", filepath.Base(u.Path))
out, err := os.Create(destPath)
if err != nil {
log.Error("Failed to create destination file")
rsp.ErrRsp(c, -1, "failed to create destination file")
return
}
defer out.Close()
defer cancel()
lw := &loggingWriter{writer: out, totalSize: resp.ContentLength}
lw.startTicker()
_, err = io.Copy(lw, resp.Body)
if err != nil {
log.Error("Failed to save the file")
rsp.ErrRsp(c, -1, "failed to save the file")
lw.stopTicker()
if err := s.downloadRemoteImage(ctx, req.File, expectedSHA256, filename, func(percentage string) {
s.setDownloadProgress(done, percentage)
}); err != nil {
if errors.Is(err, context.Canceled) {
log.Debug("Image download canceled")
s.finishDownload(done, downloadStatusIdle)
return
}
log.Errorf("Failed to download image: %v", err)
status := downloadStatusFailed
if errors.Is(err, errSHA256Mismatch) {
status = downloadStatusChecksumFailed
}
s.finishDownload(done, status)
return
}
lw.stopTicker()
s.finishDownload(done, downloadStatusSuccess)
}()
rsp.OkRspWithData(c, &proto.StatusImageRsp{
Status: "in_progress",
Status: string(downloadStatusInProgress),
File: req.File,
Percentage: "",
})
}
func parseSHA256(value string) ([]byte, error) {
value = strings.TrimSpace(value)
if value == "" {
return nil, nil
}
sum, err := hex.DecodeString(value)
if err != nil || len(sum) != sha256.Size {
return nil, errors.New("invalid sha256sum")
}
return sum, nil
}
func (s *Service) downloadRemoteImage(
ctx context.Context,
rawURL string,
expectedSHA256 []byte,
filename string,
onProgress func(string),
) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return fmt.Errorf("create download request failed: %w", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("download request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download request returned status %d", resp.StatusCode)
}
tempFile, err := os.CreateTemp("/data", ".nanokvm-download-*")
if err != nil {
return fmt.Errorf("create temporary image failed: %w", err)
}
tempPath := tempFile.Name()
defer os.Remove(tempPath)
hasher := sha256.New()
lw := newLoggingWriter(io.MultiWriter(tempFile, hasher), resp.ContentLength, onProgress)
_, copyErr := io.Copy(lw, resp.Body)
lw.stopTicker()
closeErr := tempFile.Close()
if ctx.Err() != nil {
return ctx.Err()
}
if copyErr != nil {
return fmt.Errorf("save downloaded image failed: %w", copyErr)
}
if closeErr != nil {
return fmt.Errorf("close downloaded image failed: %w", closeErr)
}
if expectedSHA256 != nil && !bytes.Equal(hasher.Sum(nil), expectedSHA256) {
return errSHA256Mismatch
}
if ctx.Err() != nil {
return ctx.Err()
}
destPath := filepath.Join("/data", filename)
if err := os.Rename(tempPath, destPath); err != nil {
return fmt.Errorf("install downloaded image failed: %w", err)
}
return nil
}
type loggingWriter struct {
writer io.Writer
total int64
totalSize int64
ticker *time.Ticker
done chan bool
writer io.Writer
total atomic.Int64
totalSize int64
ticker *time.Ticker
done chan struct{}
stopOnce sync.Once
onProgress func(string)
}
func newLoggingWriter(writer io.Writer, totalSize int64, onProgress func(string)) *loggingWriter {
lw := &loggingWriter{
writer: writer,
totalSize: totalSize,
onProgress: onProgress,
}
lw.startTicker()
return lw
}
func (lw *loggingWriter) startTicker() {
lw.ticker = time.NewTicker(2500 * time.Millisecond)
lw.done = make(chan bool)
lw.done = make(chan struct{})
go func() {
for {
select {
case <-lw.done:
return
case <-lw.ticker.C:
lw.updateSentinel()
lw.updateProgress()
}
}
}()
}
func (lw *loggingWriter) stopTicker() {
lw.ticker.Stop()
lw.done <- true
if lw == nil {
return
}
lw.stopOnce.Do(func() {
lw.ticker.Stop()
close(lw.done)
})
}
func (lw *loggingWriter) updateSentinel() {
percentage := float64(lw.total) / float64(lw.totalSize) * 100
content, err := os.ReadFile(sentinelPath)
if err != nil {
log.Error("Failed to read sentinel file")
func (lw *loggingWriter) updateProgress() {
if lw.totalSize <= 0 || lw.onProgress == nil {
return
}
splitted := strings.Split(string(content), ";")
if len(splitted) == 0 {
return
}
err = os.WriteFile(sentinelPath, []byte(fmt.Sprintf("%s;%.2f%%", splitted[0], percentage)), 0644)
if err != nil {
log.Error("Failed to update sentinel file")
}
percentage := float64(lw.total.Load()) / float64(lw.totalSize) * 100
lw.onProgress(fmt.Sprintf("%.2f%%", percentage))
}
func (lw *loggingWriter) Write(p []byte) (int, error) {
n, err := lw.writer.Write(p)
lw.total += int64(n)
lw.total.Add(int64(n))
return n, err
}

View File

@@ -20,11 +20,13 @@ const (
)
var StateMap = map[string]proto.TailscaleState{
"NoState": proto.TailscaleNotRunning,
"Starting": proto.TailscaleNotRunning,
"NeedsLogin": proto.TailscaleNotLogin,
"Running": proto.TailscaleRunning,
"Stopped": proto.TailscaleStopped,
"NoState": proto.TailscaleNotRunning,
"Starting": proto.TailscaleNotRunning,
"NeedsLogin": proto.TailscaleNotLogin,
"NeedsMachineAuth": proto.TailscaleNotLogin,
"InUseOtherUser": proto.TailscaleNotLogin,
"Running": proto.TailscaleRunning,
"Stopped": proto.TailscaleStopped,
}
func NewService() *Service {

View File

@@ -2,27 +2,54 @@ package hid
import (
"errors"
"fmt"
"io"
"os"
"sync"
"syscall"
"time"
log "github.com/sirupsen/logrus"
)
type Hid struct {
g0 *os.File
g1 *os.File
g2 *os.File
kbMutex sync.Mutex
mouseMutex sync.Mutex
g0 *os.File
g0Reader *os.File
g1 *os.File
g2 *os.File
ledReaderNotifyReader *os.File
ledReaderNotifyWriter *os.File
ledReaderNotifyReadFD int
ledReaderNotifyWriteFD int
kbMutex sync.Mutex
mouseMutex sync.Mutex
ledReaderStartOnce sync.Once
}
const (
HID0 = "/dev/hidg0"
HID1 = "/dev/hidg1"
HID2 = "/dev/hidg2"
HID0 = "/dev/hidg0" // Keyboard
HID1 = "/dev/hidg1" // Mouse (Relative Mode)
HID2 = "/dev/hidg2" // Touchpad (Absolute Mode)
)
const (
hidWriteTimeout = 50 * time.Millisecond
hidWriteRetryDelay = time.Millisecond
hidReopenTimeout = 2 * time.Second
hidReopenRetryDelay = 100 * time.Millisecond
)
type hidWriter interface {
Write([]byte) (int, error)
}
type hidDevice struct {
path string
mu *sync.Mutex
get func() *os.File
set func(*os.File)
}
var (
hid *Hid
hidOnce sync.Once
@@ -45,33 +72,214 @@ func (h *Hid) Unlock() {
h.mouseMutex.Unlock()
}
func (h *Hid) OpenNoLock() {
var err error
h.CloseNoLock()
h.g0, err = os.OpenFile(HID0, os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open %s failed: %s", HID0, err)
}
h.g1, err = os.OpenFile(HID1, os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open %s failed: %s", HID1, err)
}
h.g2, err = os.OpenFile(HID2, os.O_WRONLY, 0o666)
if err != nil {
log.Errorf("open %s failed: %s", HID2, err)
func (h *Hid) keyboardDevice(path string) hidDevice {
return hidDevice{
path: path,
mu: &h.kbMutex,
get: func() *os.File {
return h.g0
},
set: func(file *os.File) {
h.g0 = file
},
}
}
func (h *Hid) CloseNoLock() {
for _, file := range []*os.File{h.g0, h.g1, h.g2} {
if file != nil {
_ = file.Sync()
_ = file.Close()
func (h *Hid) relativeMouseDevice(path string) hidDevice {
return hidDevice{
path: path,
mu: &h.mouseMutex,
get: func() *os.File {
return h.g1
},
set: func(file *os.File) {
h.g1 = file
},
}
}
func (h *Hid) absoluteMouseDevice(path string) hidDevice {
return hidDevice{
path: path,
mu: &h.mouseMutex,
get: func() *os.File {
return h.g2
},
set: func(file *os.File) {
h.g2 = file
},
}
}
func (h *Hid) devices() []hidDevice {
return []hidDevice{
h.keyboardDevice(HID0),
h.relativeMouseDevice(HID1),
h.absoluteMouseDevice(HID2),
}
}
func (h *Hid) OpenNoLock() error {
h.CloseNoLock()
var errs []error
for _, device := range h.devices() {
if err := h.openDeviceNoLock(device); err != nil {
log.Errorf("open %s failed: %s", device.path, err)
errs = append(errs, err)
}
}
if h.g0 != nil {
if err := h.openKeyboardLedReaderNoLock(); err != nil {
log.Errorf("open keyboard LED reader failed: %s", err)
errs = append(errs, err)
} else {
h.startKeyboardLedReader()
}
}
return errors.Join(errs...)
}
func (h *Hid) OpenNoLockWithRetry(timeout, delay time.Duration) error {
return openNoLockWithRetry(h.OpenNoLock, timeout, delay)
}
func openNoLockWithRetry(open func() error, timeout, delay time.Duration) error {
if timeout <= 0 {
return open()
}
if delay <= 0 {
delay = hidReopenRetryDelay
}
deadline := time.Now().Add(timeout)
var lastErr error
for {
if err := open(); err != nil {
lastErr = err
} else {
return nil
}
remaining := time.Until(deadline)
if remaining <= 0 {
break
}
if remaining > delay {
remaining = delay
}
time.Sleep(remaining)
}
return fmt.Errorf("open HID devices within %s: %w", timeout, lastErr)
}
func (h *Hid) CloseNoLock() {
h.closeKeyboardLedReaderNoLock()
for _, device := range h.devices() {
h.closeDeviceNoLock(device)
}
}
func (h *Hid) openDeviceNoLock(device hidDevice) error {
if device.get() != nil {
return nil
}
file, err := os.OpenFile(device.path, os.O_WRONLY|syscall.O_NONBLOCK, 0o666)
if err != nil {
return fmt.Errorf("%s: %w", device.path, err)
}
device.set(file)
return nil
}
func (h *Hid) closeDeviceNoLock(device hidDevice) {
file := device.get()
if file == nil {
return
}
device.set(nil)
if err := file.Close(); err != nil {
log.Debugf("close %s failed: %s", device.path, err)
}
}
func (h *Hid) openKeyboardLedReaderNoLock() error {
if h.g0Reader != nil {
return nil
}
if err := h.ensureKeyboardLedReaderNotifierNoLock(); err != nil {
return err
}
// Keep this descriptor blocking. The LED reader waits for either an output
// report or a lifecycle notification, so an idle host does not cause a
// periodic EAGAIN retry loop.
file, err := os.OpenFile(HID0, os.O_RDONLY, 0o666)
if err != nil {
return fmt.Errorf("%s: %w", HID0, err)
}
h.g0Reader = file
h.notifyKeyboardLedReaderNoLock()
return nil
}
func (h *Hid) closeKeyboardLedReaderNoLock() {
if h.g0Reader == nil {
return
}
file := h.g0Reader
h.g0Reader = nil
h.notifyKeyboardLedReaderNoLock()
if err := file.Close(); err != nil {
log.Debugf("close keyboard LED reader failed: %s", err)
}
}
// writeWithTimeout bounds how long callers hold HID locks when writing to a
// nonblocking descriptor. EAGAIN means the host is not accepting HID reports
// yet, so retry until the caller's deadline expires.
func writeWithTimeout(writer hidWriter, data []byte, timeout time.Duration) error {
deadline := time.Now().Add(timeout)
for {
n, err := writer.Write(data)
if err == nil {
if n != len(data) {
return io.ErrShortWrite
}
return nil
}
if n != 0 {
return io.ErrShortWrite
}
if !isRetryableWriteError(err) {
return err
}
remaining := time.Until(deadline)
if timeout <= 0 || remaining <= 0 {
return os.ErrDeadlineExceeded
}
if remaining > hidWriteRetryDelay {
remaining = hidWriteRetryDelay
}
time.Sleep(remaining)
}
}
func isRetryableWriteError(err error) bool {
return errors.Is(err, syscall.EAGAIN) || errors.Is(err, syscall.EWOULDBLOCK)
}
func (h *Hid) Open() {
@@ -80,8 +288,6 @@ func (h *Hid) Open() {
h.mouseMutex.Lock()
defer h.mouseMutex.Unlock()
h.CloseNoLock()
h.OpenNoLock()
}
@@ -95,67 +301,92 @@ func (h *Hid) Close() {
}
func (h *Hid) WriteHid0(data []byte) {
h.kbMutex.Lock()
_, err := h.g0.Write(data)
h.kbMutex.Unlock()
if err != nil {
if errors.Is(err, os.ErrClosed) {
log.Errorf("hid already closed, reopen it...")
h.OpenNoLock()
} else {
log.Debugf("write to %s failed: %s", HID0, err)
}
return
if err := h.WriteKeyboardReport(data); err != nil {
log.Errorf("write to %s failed: %s", HID0, err)
}
log.Debugf("write to %s: %v", HID0, data)
}
func (h *Hid) WriteHid1(data []byte) {
deadline := time.Now().Add(8 * time.Millisecond)
h.mouseMutex.Lock()
_ = h.g1.SetWriteDeadline(deadline)
_, err := h.g1.Write(data)
h.mouseMutex.Unlock()
if err != nil {
switch {
case errors.Is(err, os.ErrClosed):
log.Errorf("hid already closed, reopen it...")
h.OpenNoLock()
case errors.Is(err, os.ErrDeadlineExceeded):
log.Debugf("write to %s timeout", HID1)
default:
log.Errorf("write to %s failed: %s", HID1, err)
}
return
if err := h.WriteRelativeMouseReport(data); err != nil {
log.Errorf("write to %s failed: %s", HID1, err)
}
log.Debugf("write to %s: %v", HID1, data)
}
func (h *Hid) WriteHid2(data []byte) {
deadline := time.Now().Add(8 * time.Millisecond)
if err := h.WriteAbsoluteMouseReport(data); err != nil {
log.Errorf("write to %s failed: %s", HID2, err)
}
}
h.mouseMutex.Lock()
_ = h.g2.SetWriteDeadline(deadline)
_, err := h.g2.Write(data)
h.mouseMutex.Unlock()
func (h *Hid) WriteKeyboardReport(data []byte) error {
if len(data) != 8 {
return fmt.Errorf("invalid keyboard report length: %d", len(data))
}
return h.writeHID(h.keyboardDevice(HID0), data)
}
if err != nil {
switch {
case errors.Is(err, os.ErrClosed):
log.Errorf("hid already closed, reopen it...")
h.OpenNoLock()
case errors.Is(err, os.ErrDeadlineExceeded):
log.Debugf("write to %s timeout", HID2)
default:
log.Errorf("write to %s failed: %s", HID2, err)
func (h *Hid) WriteRelativeMouseReport(data []byte) error {
if len(data) != 4 {
return fmt.Errorf("invalid relative mouse report length: %d", len(data))
}
return h.writeHID(h.relativeMouseDevice(HID1), data)
}
func (h *Hid) WriteAbsoluteMouseReport(data []byte) error {
if len(data) != 6 {
return fmt.Errorf("invalid absolute mouse report length: %d", len(data))
}
return h.writeHID(h.absoluteMouseDevice(HID2), data)
}
func (h *Hid) writeHIDReport(device hidDevice, data []byte) bool {
if err := h.writeHID(device, data); err != nil {
log.Errorf("write to %s failed: %s", device.path, err)
return false
}
return true
}
func (h *Hid) writeHID(device hidDevice, data []byte) error {
device.mu.Lock()
defer device.mu.Unlock()
if err := h.openDeviceNoLock(device); err != nil {
return err
}
if device.path == HID0 {
if err := h.openKeyboardLedReaderNoLock(); err != nil {
log.Debugf("open keyboard LED reader failed: %s", err)
} else {
h.startKeyboardLedReader()
}
return
}
log.Debugf("write to %s: %v", HID2, data)
file := device.get()
if file == nil {
return fmt.Errorf("%s: hid handle is nil", device.path)
}
deadline := time.Now().Add(hidWriteTimeout)
if err := file.SetWriteDeadline(deadline); err != nil {
log.Debugf("set write deadline for %s failed: %s", device.path, err)
}
if err := writeWithTimeout(file, data, hidWriteTimeout); err != nil {
if device.path == HID0 {
h.closeKeyboardLedReaderNoLock()
}
h.closeDeviceNoLock(device)
switch {
case errors.Is(err, os.ErrClosed):
return fmt.Errorf("hid already closed: %w", err)
case errors.Is(err, os.ErrDeadlineExceeded):
return fmt.Errorf("timeout after %s: %w", hidWriteTimeout, err)
default:
return err
}
}
log.Debugf("write to %s: %v", device.path, data)
return nil
}

View File

@@ -0,0 +1,28 @@
package hid
import (
"testing"
"time"
)
func TestReportLengthValidation(t *testing.T) {
h := &Hid{}
if err := h.WriteKeyboardReport(make([]byte, 7)); err == nil {
t.Fatal("expected keyboard length error")
}
if err := h.WriteRelativeMouseReport(make([]byte, 5)); err == nil {
t.Fatal("expected relative mouse length error")
}
if err := h.WriteAbsoluteMouseReport(make([]byte, 7)); err == nil {
t.Fatal("expected absolute mouse length error")
}
}
func TestPasteDurationLeavesModeSwitchMargin(t *testing.T) {
if maxPasteDuration >= 30*time.Second {
t.Fatalf("maxPasteDuration = %s, want below 30s mode switch wait budget", maxPasteDuration)
}
if got := time.Duration(maxPasteContentRunes) * defaultPasteDelay; got > maxPasteDuration {
t.Fatalf("max paste content duration = %s, want <= %s", got, maxPasteDuration)
}
}

View File

@@ -1,15 +1,112 @@
package hid
func (h *Hid) Keyboard(queue <-chan []int) {
for event := range queue {
code := byte(event[0])
import (
log "github.com/sirupsen/logrus"
)
var modifier byte = 0x00
if code > 0 {
modifier = byte(event[1]) | byte(event[2]) | byte(event[3]) | byte(event[4])
func (h *Hid) Keyboard(queue <-chan []byte) {
legacy := make(chan QueuedReport)
go func() {
defer close(legacy)
for report := range queue {
legacy <- QueuedReport{Data: report}
}
}()
h.KeyboardReports(legacy)
}
func (h *Hid) KeyboardReports(queue <-chan QueuedReport) {
h.keyboardReports(queue, HID0)
}
func (h *Hid) keyboardReports(queue <-chan QueuedReport, path string) {
var execute func(func() error) error
var resetKeyboard func()
keyboardActive := false
defer func() {
if !keyboardActive {
return
}
if err := runCleanup(execute, func() error {
return h.writeHID(h.keyboardDevice(path), keyboardReleaseReport())
}); err != nil {
log.Errorf("release keyboard on queue close failed: %s", err)
return
}
if resetKeyboard != nil {
resetKeyboard()
}
}()
for event := range queue {
execute = event.Execute
resetKeyboard = event.ResetKeyboard
if len(event.Data) != 8 {
event.complete(false)
log.Debugf("invalid keyboard event: %v", event.Data)
continue
}
data := []byte{modifier, 0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00}
h.WriteHid0(data)
if err := event.run(func() error {
return h.writeHID(h.keyboardDevice(path), event.Data)
}); err != nil {
log.Errorf("write to %s failed: %s", path, err)
if dropped := drainHIDQueue(queue); dropped > 0 {
log.Debugf("dropped %d stale keyboard HID reports after write failure", dropped)
}
cleanupErr := runCleanup(execute, func() error {
return h.writeHID(h.keyboardDevice(path), keyboardReleaseReport())
})
if cleanupErr != nil {
log.Errorf("release keyboard after write failure failed: %s", cleanupErr)
keyboardActive = keyboardActive || keyboardReportActive(event.Data)
event.complete(false)
continue
}
keyboardActive = false
if resetKeyboard != nil {
resetKeyboard()
}
event.complete(false)
continue
}
keyboardActive = keyboardReportActive(event.Data)
event.complete(true)
}
}
func keyboardReportActive(report []byte) bool {
if len(report) != 8 {
return false
}
if report[0] != 0 {
return true
}
for _, key := range report[2:] {
if key != 0 {
return true
}
}
return false
}
func keyboardReleaseReport() []byte {
return []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
}
func drainHIDQueue(queue <-chan QueuedReport) int {
dropped := 0
for {
select {
case report, ok := <-queue:
if !ok {
return dropped
}
report.complete(false)
dropped++
default:
return dropped
}
}
}

View File

@@ -0,0 +1,63 @@
package hid
import (
"os"
"strings"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
const (
LeaderKeyFile = "/etc/kvm/leader-key"
)
func (s *Service) SetLeaderKey(c *gin.Context) {
var req proto.SetLeaderKeyReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
if req.Key == "" {
err := os.Remove(LeaderKeyFile)
if err != nil && !os.IsNotExist(err) {
rsp.ErrRsp(c, -2, "reset failed")
return
}
} else {
err := os.WriteFile(LeaderKeyFile, []byte(req.Key), 0o644)
if err != nil {
rsp.ErrRsp(c, -3, "write failed")
return
}
}
rsp.OkRsp(c)
log.Debugf("set leader key: %s", req.Key)
}
func (s *Service) GetLeaderKey(c *gin.Context) {
var rsp proto.Response
data, err := os.ReadFile(LeaderKeyFile)
if err != nil {
if os.IsNotExist(err) {
rsp.OkRspWithData(c, &proto.GetLeaderKeyRsp{
Key: "",
})
return
}
rsp.ErrRsp(c, -1, "read leader key failed")
return
}
rsp.OkRspWithData(c, &proto.GetLeaderKeyRsp{
Key: strings.Replace(string(data), "\n", "", -1),
})
log.Debugf("get leader key successful")
}

279
server/service/hid/leds.go Normal file
View File

@@ -0,0 +1,279 @@
package hid
import (
"errors"
"fmt"
"os"
"sync"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"golang.org/x/sys/unix"
)
const (
KeyboardLedStatusEvent = "hid-led-status"
)
// KeyboardLedStatus is the lock-key LED state last reported by the remote host
// through the keyboard HID output report.
type KeyboardLedStatus struct {
NumLock bool `json:"numLock"`
CapsLock bool `json:"capsLock"`
ScrollLock bool `json:"scrollLock"`
Known bool `json:"known"`
UpdatedAt time.Time `json:"updatedAt"`
}
type keyboardLedStatusStore struct {
mutex sync.RWMutex
status KeyboardLedStatus
subscribers map[int]func(KeyboardLedStatus)
nextID int
now func() time.Time
}
var keyboardLeds = newKeyboardLedStatusStore(time.Now)
func newKeyboardLedStatusStore(now func() time.Time) *keyboardLedStatusStore {
return &keyboardLedStatusStore{
subscribers: make(map[int]func(KeyboardLedStatus)),
now: now,
}
}
// GetKeyboardLedStatus returns a snapshot. Known is false until the host has
// sent at least one keyboard HID output report.
func GetKeyboardLedStatus() KeyboardLedStatus {
return keyboardLeds.Get()
}
// SubscribeKeyboardLedStatus subscribes to state changes and returns a
// function that removes the subscription.
func SubscribeKeyboardLedStatus(subscriber func(KeyboardLedStatus)) func() {
return keyboardLeds.Subscribe(subscriber)
}
func (s *keyboardLedStatusStore) Get() KeyboardLedStatus {
s.mutex.RLock()
defer s.mutex.RUnlock()
return s.status
}
func (s *keyboardLedStatusStore) Subscribe(subscriber func(KeyboardLedStatus)) func() {
s.mutex.Lock()
id := s.nextID
s.nextID++
s.subscribers[id] = subscriber
s.mutex.Unlock()
return func() {
s.mutex.Lock()
delete(s.subscribers, id)
s.mutex.Unlock()
}
}
func (s *keyboardLedStatusStore) Update(report byte) {
next := keyboardLedStatusFromReport(report, s.now())
s.mutex.Lock()
previous := s.status
s.status = next
if sameKeyboardLedState(previous, next) {
s.mutex.Unlock()
return
}
subscribers := make([]func(KeyboardLedStatus), 0, len(s.subscribers))
for _, subscriber := range s.subscribers {
subscribers = append(subscribers, subscriber)
}
s.mutex.Unlock()
for _, subscriber := range subscribers {
subscriber(next)
}
}
func keyboardLedStatusFromReport(report byte, updatedAt time.Time) KeyboardLedStatus {
return KeyboardLedStatus{
NumLock: report&0x01 != 0,
CapsLock: report&0x02 != 0,
ScrollLock: report&0x04 != 0,
Known: true,
UpdatedAt: updatedAt,
}
}
func sameKeyboardLedState(a, b KeyboardLedStatus) bool {
return a.NumLock == b.NumLock &&
a.CapsLock == b.CapsLock &&
a.ScrollLock == b.ScrollLock &&
a.Known == b.Known
}
func (h *Hid) startKeyboardLedReader() {
h.ledReaderStartOnce.Do(func() {
go h.readKeyboardLeds()
})
}
func (h *Hid) readKeyboardLeds() {
buf := make([]byte, 64)
for {
file, notifierFD := h.keyboardLedReaderHandles()
if file == nil {
if err := waitForKeyboardLedReaderChange(notifierFD); err != nil {
log.Debugf("wait for keyboard LED reader failed: %s", err)
}
continue
}
changed, err := waitForKeyboardLedReportOrChange(file, notifierFD)
if err != nil {
if !errors.Is(err, os.ErrClosed) {
log.Debugf("wait for keyboard LED report failed: %s", err)
}
h.reopenKeyboardLedReader(file)
continue
}
if changed {
continue
}
n, err := file.Read(buf)
if n > 0 {
// Both keyboard gadget descriptors in kvmapp/system/init.d declare
// boot-keyboard reports without a Report ID (no 0x85 item). Their LED
// output report is one byte: bits 0-4 are the LED bitmap and bits 5-7
// are padding. report_length is 8 because it also covers input reports.
keyboardLeds.Update(buf[0])
}
if err == nil && n > 0 {
continue
}
if err != nil && !errors.Is(err, os.ErrClosed) {
log.Debugf("read keyboard LED report failed: %s", err)
}
h.reopenKeyboardLedReader(file)
}
}
func (h *Hid) keyboardLedReaderHandles() (*os.File, int) {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
if h.ledReaderNotifyReader == nil {
return h.g0Reader, -1
}
return h.g0Reader, h.ledReaderNotifyReadFD
}
func (h *Hid) reopenKeyboardLedReader(file *os.File) {
h.kbMutex.Lock()
defer h.kbMutex.Unlock()
// A reset may have installed a new reader while the old descriptor was
// reporting an error. Never let that stale reader close the replacement.
if h.g0Reader != file {
return
}
h.closeKeyboardLedReaderNoLock()
if h.g0 == nil {
return
}
if err := h.openKeyboardLedReaderNoLock(); err != nil {
log.Debugf("reopen keyboard LED reader failed: %s", err)
}
}
func (h *Hid) ensureKeyboardLedReaderNotifierNoLock() error {
if h.ledReaderNotifyReader != nil {
return nil
}
reader, writer, err := os.Pipe()
if err != nil {
return fmt.Errorf("create keyboard LED reader notifier: %w", err)
}
readerFD := int(reader.Fd())
writerFD := int(writer.Fd())
if err := unix.SetNonblock(readerFD, true); err != nil {
_ = reader.Close()
_ = writer.Close()
return fmt.Errorf("set keyboard LED reader notifier read end nonblocking: %w", err)
}
if err := unix.SetNonblock(writerFD, true); err != nil {
_ = reader.Close()
_ = writer.Close()
return fmt.Errorf("set keyboard LED reader notifier write end nonblocking: %w", err)
}
h.ledReaderNotifyReader = reader
h.ledReaderNotifyWriter = writer
h.ledReaderNotifyReadFD = readerFD
h.ledReaderNotifyWriteFD = writerFD
return nil
}
func (h *Hid) notifyKeyboardLedReaderNoLock() {
if h.ledReaderNotifyWriter == nil {
return
}
_, err := unix.Write(h.ledReaderNotifyWriteFD, []byte{1})
if err != nil && !errors.Is(err, syscall.EAGAIN) && !errors.Is(err, syscall.EWOULDBLOCK) {
log.Debugf("notify keyboard LED reader failed: %s", err)
}
}
func waitForKeyboardLedReaderChange(notifierFD int) error {
if notifierFD < 0 {
return fmt.Errorf("keyboard LED reader notifier is nil")
}
_, err := unix.Poll([]unix.PollFd{{Fd: int32(notifierFD), Events: unix.POLLIN}}, -1)
if err != nil {
return err
}
drainKeyboardLedReaderNotifier(notifierFD)
return nil
}
// waitForKeyboardLedReportOrChange blocks until a HID output report arrives or
// the reader is replaced/closed. Its bool result is true for the latter.
func waitForKeyboardLedReportOrChange(file *os.File, notifierFD int) (bool, error) {
if file == nil || notifierFD < 0 {
return false, fmt.Errorf("keyboard LED reader or notifier is nil")
}
fds := []unix.PollFd{
{Fd: int32(file.Fd()), Events: unix.POLLIN},
{Fd: int32(notifierFD), Events: unix.POLLIN},
}
_, err := unix.Poll(fds, -1)
if err != nil {
return false, err
}
if fds[1].Revents&unix.POLLIN != 0 {
drainKeyboardLedReaderNotifier(notifierFD)
return true, nil
}
if fds[0].Revents&(unix.POLLIN|unix.POLLERR|unix.POLLHUP|unix.POLLNVAL) != 0 {
return false, nil
}
return false, fmt.Errorf("keyboard LED poll returned without an event")
}
func drainKeyboardLedReaderNotifier(notifierFD int) {
buf := make([]byte, 64)
for {
_, err := unix.Read(notifierFD, buf)
if err != nil {
if !errors.Is(err, syscall.EAGAIN) && !errors.Is(err, syscall.EWOULDBLOCK) {
log.Debugf("drain keyboard LED reader notifier failed: %s", err)
}
return
}
}
}

View File

@@ -0,0 +1,168 @@
package hid
import (
"os"
"testing"
"time"
)
func TestKeyboardLedStatusFromReport(t *testing.T) {
updatedAt := time.Date(2026, time.July, 24, 12, 0, 0, 0, time.UTC)
status := keyboardLedStatusFromReport(0x17, updatedAt)
if !status.NumLock || !status.CapsLock || !status.ScrollLock || !status.Known {
t.Fatalf("unexpected parsed status: %+v", status)
}
if !status.UpdatedAt.Equal(updatedAt) {
t.Fatalf("updatedAt = %s, want %s", status.UpdatedAt, updatedAt)
}
}
func TestKeyboardLedStatusStoreOnlyNotifiesStateChanges(t *testing.T) {
now := time.Date(2026, time.July, 24, 12, 0, 0, 0, time.UTC)
store := newKeyboardLedStatusStore(func() time.Time { return now })
notifications := make(chan KeyboardLedStatus, 2)
store.Subscribe(func(status KeyboardLedStatus) {
notifications <- status
})
store.Update(0x01)
store.Update(0x01)
now = now.Add(time.Second)
store.Update(0x03)
first := <-notifications
second := <-notifications
if !first.NumLock || first.CapsLock || !second.NumLock || !second.CapsLock {
t.Fatalf("unexpected notifications: first=%+v second=%+v", first, second)
}
select {
case status := <-notifications:
t.Fatalf("unexpected duplicate notification: %+v", status)
default:
}
if status := store.Get(); !status.UpdatedAt.Equal(now) {
t.Fatalf("latest updatedAt = %s, want %s", status.UpdatedAt, now)
}
}
func TestWaitForKeyboardLedReaderChangeWaitsForNotification(t *testing.T) {
h := &Hid{}
h.kbMutex.Lock()
if err := h.ensureKeyboardLedReaderNotifierNoLock(); err != nil {
h.kbMutex.Unlock()
t.Fatal(err)
}
notifierFD := h.ledReaderNotifyReadFD
h.kbMutex.Unlock()
defer h.ledReaderNotifyReader.Close()
defer h.ledReaderNotifyWriter.Close()
done := make(chan error, 1)
go func() { done <- waitForKeyboardLedReaderChange(notifierFD) }()
select {
case err := <-done:
t.Fatalf("wait returned before a notification: %v", err)
case <-time.After(25 * time.Millisecond):
}
h.kbMutex.Lock()
h.notifyKeyboardLedReaderNoLock()
h.kbMutex.Unlock()
select {
case err := <-done:
if err != nil {
t.Fatalf("wait returned error: %v", err)
}
case <-time.After(time.Second):
t.Fatal("wait did not wake after a notification")
}
}
func TestWaitForKeyboardLedReportOrChangeReturnsForReport(t *testing.T) {
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer reader.Close()
defer writer.Close()
h := &Hid{}
h.kbMutex.Lock()
if err := h.ensureKeyboardLedReaderNotifierNoLock(); err != nil {
h.kbMutex.Unlock()
t.Fatal(err)
}
notifierFD := h.ledReaderNotifyReadFD
h.kbMutex.Unlock()
defer h.ledReaderNotifyReader.Close()
defer h.ledReaderNotifyWriter.Close()
done := make(chan struct {
changed bool
err error
}, 1)
go func() {
changed, err := waitForKeyboardLedReportOrChange(reader, notifierFD)
done <- struct {
changed bool
err error
}{changed, err}
}()
if _, err := writer.Write([]byte{0x03}); err != nil {
t.Fatal(err)
}
select {
case result := <-done:
if result.err != nil || result.changed {
t.Fatalf("result = changed=%t, err=%v; want report", result.changed, result.err)
}
case <-time.After(time.Second):
t.Fatal("wait did not wake for report")
}
}
func TestReopenKeyboardLedReaderDoesNotCloseReplacement(t *testing.T) {
oldReader, oldWriter, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer oldReader.Close()
defer oldWriter.Close()
replacement, replacementWriter, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer replacement.Close()
defer replacementWriter.Close()
h := &Hid{g0Reader: oldReader}
h.kbMutex.Lock()
if err := h.ensureKeyboardLedReaderNotifierNoLock(); err != nil {
h.kbMutex.Unlock()
t.Fatal(err)
}
h.g0Reader = replacement // Simulate reset/reopen replacing the reader.
h.kbMutex.Unlock()
defer h.ledReaderNotifyReader.Close()
defer h.ledReaderNotifyWriter.Close()
h.reopenKeyboardLedReader(oldReader)
current, _ := h.keyboardLedReaderHandles()
if current != replacement {
t.Fatal("stale reader close replaced the active reader")
}
if _, err := replacementWriter.Write([]byte{0x01}); err != nil {
t.Fatalf("replacement reader was closed: %v", err)
}
buf := make([]byte, 1)
if _, err := replacement.Read(buf); err != nil {
t.Fatalf("replacement reader was closed: %v", err)
}
}

View File

@@ -1,82 +1,165 @@
package hid
import (
"encoding/binary"
log "github.com/sirupsen/logrus"
)
const (
MouseUp = iota
MouseDown
MouseMoveAbsolute
MouseMoveRelative
MouseScroll
)
var mouseButtonMap = map[byte]bool{
0x01: true,
0x02: true,
0x04: true,
func (h *Hid) Mouse(queue <-chan []byte) {
legacy := make(chan QueuedReport)
go func() {
defer close(legacy)
for report := range queue {
legacy <- QueuedReport{Data: report}
}
}()
h.MouseReports(legacy)
}
func (h *Hid) Mouse(queue <-chan []int) {
for event := range queue {
func (h *Hid) MouseReports(queue <-chan QueuedReport) {
h.mouseReports(queue, HID1, HID2)
}
switch event[0] {
case MouseDown:
h.mouseDown(event)
case MouseUp:
h.mouseUp()
case MouseMoveAbsolute:
h.mouseMoveAbsolute(event)
case MouseMoveRelative:
h.mouseMoveRelative(event)
case MouseScroll:
h.mouseScroll(event)
func (h *Hid) mouseReports(queue <-chan QueuedReport, relativePath string, absolutePath string) {
var execute func(func() error) error
var resetRelativeMouse func()
var resetAbsoluteMouse func()
relativeButtonsActive := false
absoluteButtonsActive := false
absoluteReleaseReport := absoluteMouseReleaseReport(nil)
defer func() {
if relativeButtonsActive {
if err := runCleanup(execute, func() error {
return h.writeHID(h.relativeMouseDevice(relativePath), relativeMouseReleaseReport())
}); err != nil {
log.Errorf("release relative mouse on queue close failed: %s", err)
} else if resetRelativeMouse != nil {
resetRelativeMouse()
}
}
if absoluteButtonsActive {
if err := runCleanup(execute, func() error {
return h.writeHID(h.absoluteMouseDevice(absolutePath), absoluteReleaseReport)
}); err != nil {
log.Errorf("release absolute mouse on queue close failed: %s", err)
} else if resetAbsoluteMouse != nil {
resetAbsoluteMouse()
}
}
}()
for event := range queue {
execute = event.Execute
resetRelativeMouse = event.ResetRelativeMouse
resetAbsoluteMouse = event.ResetAbsoluteMouse
cleanupFailure := func(writeErr error) {
log.Errorf("mouse HID write failed: %s", writeErr)
if dropped := drainHIDQueue(queue); dropped > 0 {
log.Debugf("dropped %d stale mouse HID reports after write failure", dropped)
}
if len(event.Data) == 4 && event.Data[0] != 0 {
relativeButtonsActive = true
}
if len(event.Data) == 6 && event.Data[0] != 0 {
absoluteButtonsActive = true
absoluteReleaseReport = absoluteMouseReleaseReport(event.Data)
}
if relativeButtonsActive || len(event.Data) == 4 {
if err := runCleanup(execute, func() error {
return h.writeHID(h.relativeMouseDevice(relativePath), relativeMouseReleaseReport())
}); err != nil {
log.Errorf("release relative mouse after write failure failed: %s", err)
} else {
relativeButtonsActive = false
if resetRelativeMouse != nil {
resetRelativeMouse()
}
}
}
if absoluteButtonsActive || len(event.Data) == 6 {
releaseReport := absoluteReleaseReport
if len(event.Data) == 6 {
releaseReport = absoluteMouseReleaseReport(event.Data)
}
if err := runCleanup(execute, func() error {
return h.writeHID(h.absoluteMouseDevice(absolutePath), releaseReport)
}); err != nil {
log.Errorf("release absolute mouse after write failure failed: %s", err)
} else {
absoluteButtonsActive = false
if resetAbsoluteMouse != nil {
resetAbsoluteMouse()
}
}
}
event.complete(false)
}
switch len(event.Data) {
case 4:
if absoluteButtonsActive {
if err := runCleanup(execute, func() error {
return h.writeHID(h.absoluteMouseDevice(absolutePath), absoluteReleaseReport)
}); err != nil {
cleanupFailure(err)
continue
}
absoluteButtonsActive = false
if resetAbsoluteMouse != nil {
resetAbsoluteMouse()
}
}
if err := event.run(func() error {
return h.writeHID(h.relativeMouseDevice(relativePath), event.Data)
}); err != nil {
cleanupFailure(err)
continue
}
relativeButtonsActive = event.Data[0] != 0
event.complete(true)
case 6:
if relativeButtonsActive {
if err := runCleanup(execute, func() error {
return h.writeHID(h.relativeMouseDevice(relativePath), relativeMouseReleaseReport())
}); err != nil {
cleanupFailure(err)
continue
}
relativeButtonsActive = false
if resetRelativeMouse != nil {
resetRelativeMouse()
}
}
if err := event.run(func() error {
return h.writeHID(h.absoluteMouseDevice(absolutePath), event.Data)
}); err != nil {
cleanupFailure(err)
continue
}
absoluteReleaseReport = absoluteMouseReleaseReport(event.Data)
absoluteButtonsActive = event.Data[0] != 0
event.complete(true)
default:
log.Debugf("invalid mouse event: %v", event)
event.complete(false)
log.Debugf("invalid mouse event: %v", event.Data)
}
}
}
func (h *Hid) mouseDown(event []int) {
button := byte(event[1])
func relativeMouseReleaseReport() []byte {
return []byte{0x00, 0x00, 0x00, 0x00}
}
if _, ok := mouseButtonMap[button]; !ok {
log.Errorf("invalid mouse button: %v", event)
return
func absoluteMouseReleaseReport(positionReport []byte) []byte {
report := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
if len(positionReport) >= 5 {
copy(report[1:5], positionReport[1:5])
}
data := []byte{button, 0, 0, 0}
h.WriteHid1(data)
}
func (h *Hid) mouseUp() {
data := []byte{0, 0, 0, 0}
h.WriteHid1(data)
}
func (h *Hid) mouseScroll(event []int) {
direction := 0x01
if event[3] > 0 {
direction = -0x1
}
data := []byte{0, 0, 0, byte(direction)}
h.WriteHid1(data)
}
func (h *Hid) mouseMoveAbsolute(event []int) {
x := make([]byte, 2)
y := make([]byte, 2)
binary.LittleEndian.PutUint16(x, uint16(event[2]))
binary.LittleEndian.PutUint16(y, uint16(event[3]))
data := []byte{0, x[0], x[1], y[0], y[1], 0}
h.WriteHid2(data)
}
func (h *Hid) mouseMoveRelative(event []int) {
data := []byte{byte(event[1]), byte(event[2]), byte(event[3]), 0}
h.WriteHid1(data)
return report
}

View File

@@ -1,12 +1,14 @@
package hid
import (
"context"
"time"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"NanoKVM-Server/proto"
"NanoKVM-Server/service/inputcontrol"
)
type Char struct {
@@ -19,26 +21,32 @@ type PasteReq struct {
Langue string `form:"langue"`
}
const (
defaultPasteDelay = 30 * time.Millisecond
maxPasteDuration = 25 * time.Second
maxPasteContentRunes = int(maxPasteDuration / defaultPasteDelay)
)
func LangueSwitch(base map[rune]Char, lang string) map[rune]Char {
// wenn kein lang angegeben → Standardmap zurück
// if no language is specified → return base map
if lang == "" {
return base
}
// immer Kopie erstellen
// always create a copy of the base map
m := copyMap(base)
switch lang {
case "de":
// Y tauschen
// swap Y
m['y'] = Char{0, 29}
m['Y'] = Char{2, 29}
// Z tauschen
// swap Z
m['z'] = Char{0, 28}
m['Z'] = Char{2, 28}
// deutsche Sonderzeichen hinzufügen oder remappen
// add German special characters or remap them
m['\u00E4'] = Char{0, 52} // ä
m['\u00C4'] = Char{2, 52} // Ä
m['\u00F6'] = Char{0, 51} // ö
@@ -47,8 +55,8 @@ func LangueSwitch(base map[rune]Char, lang string) map[rune]Char {
m['\u00DC'] = Char{2, 47} // Ü
m['\u00DF'] = Char{0, 45} // ß
//Tauschen
m['^'] = Char{0, 53} // muss doppelt sein
// swap special characters
m['^'] = Char{0, 53} // must be double
m['/'] = Char{2, 36} // Shift + 7
m['('] = Char{2, 37} // Shift + 8
m['&'] = Char{2, 35} // Shift + 6
@@ -75,7 +83,7 @@ func LangueSwitch(base map[rune]Char, lang string) map[rune]Char {
m['-'] = Char{0, 56} // Shift + -
m['_'] = Char{2, 56} // Shift + -
//neu
// new special characters
m['\u00B4'] = Char{0, 46} // ´
m['\u00B0'] = Char{2, 53} // °
m['\u00A7'] = Char{2, 32} // §
@@ -83,6 +91,81 @@ func LangueSwitch(base map[rune]Char, lang string) map[rune]Char {
m['\u00B2'] = Char{0x40, 31} // ²
m['\u00B3'] = Char{0x40, 32} // ³
case "fr":
// French AZERTY layout
// Letters: a↔q swap, z↔w swap, m moved to physical ; position
m['a'] = Char{0, 20} // a is at physical Q key (HID 20)
m['A'] = Char{2, 20}
m['q'] = Char{0, 4} // q is at physical A key (HID 4)
m['Q'] = Char{2, 4}
m['z'] = Char{0, 26} // z is at physical W key (HID 26)
m['Z'] = Char{2, 26}
m['w'] = Char{0, 29} // w is at physical Z key (HID 29)
m['W'] = Char{2, 29}
m['m'] = Char{0, 51} // m is at physical ; key (HID 51)
m['M'] = Char{2, 51}
// Numbers require Shift on AZERTY
m['1'] = Char{2, 30}
m['2'] = Char{2, 31}
m['3'] = Char{2, 32}
m['4'] = Char{2, 33}
m['5'] = Char{2, 34}
m['6'] = Char{2, 35}
m['7'] = Char{2, 36}
m['8'] = Char{2, 37}
m['9'] = Char{2, 38}
m['0'] = Char{2, 39}
// Unshifted number row → French/special characters
m['&'] = Char{0, 30} // & at physical key 1
m['\u00E9'] = Char{0, 31} // é at physical key 2
m['"'] = Char{0, 32} // " at physical key 3
m['\''] = Char{0, 33} // ' at physical key 4
m['('] = Char{0, 34} // ( at physical key 5
m['-'] = Char{0, 35} // - at physical key 6
m['\u00E8'] = Char{0, 36} // è at physical key 7
m['_'] = Char{0, 37} // _ at physical key 8
m['\u00E7'] = Char{0, 38} // ç at physical key 9
m['\u00E0'] = Char{0, 39} // à at physical key 0
// Physical - key (HID 45) → ) on AZERTY
m[')'] = Char{0, 45} // ) at physical - key
m['\u00B0'] = Char{2, 45} // ° at shift+physical - key
// Letter-row bracket/special keys
m['^'] = Char{0, 47} // ^ (dead) at physical [ key (HID 47)
m['\u00A8'] = Char{2, 47} // ¨ at shift+[
m['$'] = Char{0, 48} // $ at physical ] key (HID 48)
m['\u00A3'] = Char{2, 48} // £ at shift+]
m['*'] = Char{0, 49} // * at physical \ key (HID 49)
m['\u00B5'] = Char{2, 49} // µ at shift+\
m['\u00F9'] = Char{0, 52} // ù at physical ' key (HID 52)
m['%'] = Char{2, 52} // % at shift+'
// Bottom row remappings
m[','] = Char{0, 16} // , at physical M key (HID 16)
m['?'] = Char{2, 16} // ? at shift+physical M
m[';'] = Char{0, 54} // ; at physical , key (HID 54)
m['.'] = Char{2, 54} // . at shift+physical ,
m[':'] = Char{0, 55} // : at physical . key (HID 55)
m['/'] = Char{2, 55} // / at shift+physical .
m['!'] = Char{0, 56} // ! at physical / key (HID 56)
m['\u00A7'] = Char{2, 56} // § at shift+physical /
// AltGr combinations
m['~'] = Char{0x40, 31} // AltGr+2
m['#'] = Char{0x40, 32} // AltGr+3
m['{'] = Char{0x40, 33} // AltGr+4
m['['] = Char{0x40, 34} // AltGr+5
m['|'] = Char{0x40, 35} // AltGr+6
m['`'] = Char{0x40, 36} // AltGr+7
m['\\'] = Char{0x40, 37} // AltGr+8
m[']'] = Char{0x40, 45} // AltGr+physical -
m['}'] = Char{0x40, 46} // AltGr+=
m['@'] = Char{0x40, 39} // AltGr+0
m['\u20AC'] = Char{0x40, 8} // € AltGr+E
}
return m
}
@@ -96,16 +179,44 @@ func (s *Service) Paste(c *gin.Context) {
return
}
if len(req.Content) > 1024 {
contentRunes := []rune(req.Content)
if len(contentRunes) > maxPasteContentRunes {
rsp.ErrRsp(c, -2, "content too long")
return
}
charMapLocal := LangueSwitch(charMap, req.Langue)
typeableRunes := 0
for _, char := range contentRunes {
if _, ok := charMapLocal[char]; ok {
typeableRunes++
}
}
if time.Duration(typeableRunes)*defaultPasteDelay > maxPasteDuration {
rsp.ErrRsp(c, -2, "paste duration exceeds 25s")
return
}
keyUp := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
manual := s.newManualSession()
defer manual.Close()
reservation, err := manual.Reserve(c.Request.Context(), inputcontrol.ManualKeyboard, false, nil)
if err != nil {
log.Errorf("manual paste failed to acquire HID control: %v", err)
rsp.ErrRsp(c, -3, "HID control is busy")
return
}
for _, char := range req.Content {
writeKeyboardReport := func(report []byte) error {
return manual.Execute(func() error {
return s.hid.WriteKeyboardReport(report)
})
}
for _, char := range contentRunes {
if err := context.Cause(c.Request.Context()); err != nil {
break
}
key, ok := charMapLocal[char]
if !ok {
log.Debugf("unknown key '%c' (rune: %d)", char, char)
@@ -113,14 +224,40 @@ func (s *Service) Paste(c *gin.Context) {
}
keyDown := []byte{byte(key.Modifiers), 0x00, byte(key.Code), 0x00, 0x00, 0x00, 0x00, 0x00}
hid.WriteHid0(keyDown)
hid.WriteHid0(keyUp)
time.Sleep(30 * time.Millisecond)
if err = writeKeyboardReport(keyDown); err != nil {
break
}
if err = writeKeyboardReport(keyUp); err != nil {
break
}
if err = sleepPasteContext(c.Request.Context(), defaultPasteDelay); err != nil {
break
}
}
if err == nil {
err = context.Cause(c.Request.Context())
}
_ = writeKeyboardReport(keyUp)
reservation.Complete(err == nil)
if err != nil {
log.Errorf("hid paste failed: %v", err)
rsp.ErrRsp(c, -3, "HID paste failed")
return
}
rsp.OkRsp(c)
log.Debugf("hid paste success, total %d characters processed", len(req.Content))
log.Debugf("hid paste success, total %d characters processed", len(contentRunes))
}
func sleepPasteContext(ctx context.Context, delay time.Duration) error {
timer := time.NewTimer(delay)
defer timer.Stop()
select {
case <-ctx.Done():
return context.Cause(ctx)
case <-timer.C:
return nil
}
}
func copyMap(src map[rune]Char) map[rune]Char {
@@ -131,6 +268,10 @@ func copyMap(src map[rune]Char) map[rune]Char {
return dst
}
func GetCharMap(lang string) map[rune]Char {
return LangueSwitch(charMap, lang)
}
var charMap = map[rune]Char{
// Lowercase letters
'a': {0, 4}, 'b': {0, 5}, 'c': {0, 6}, 'd': {0, 7}, 'e': {0, 8},

View File

@@ -0,0 +1,30 @@
package hid
type QueuedReport struct {
Data []byte
Execute func(func() error) error
Complete func(bool)
ResetKeyboard func()
ResetRelativeMouse func()
ResetAbsoluteMouse func()
}
func (r QueuedReport) run(write func() error) error {
if r.Execute != nil {
return r.Execute(write)
}
return write()
}
func (r QueuedReport) complete(success bool) {
if r.Complete != nil {
r.Complete(success)
}
}
func runCleanup(execute func(func() error) error, write func() error) error {
if execute != nil {
return execute(write)
}
return write()
}

View File

@@ -0,0 +1,245 @@
package hid
import (
"bytes"
"io"
"os"
"path/filepath"
"testing"
"time"
)
func TestMouseModeSwitchReleasesPreviousDevice(t *testing.T) {
relativeReader, relativeWriter, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer relativeReader.Close()
absoluteReader, absoluteWriter, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer absoluteReader.Close()
h := &Hid{g1: relativeWriter, g2: absoluteWriter}
queue := make(chan QueuedReport, 2)
completed := make(chan bool, 2)
absoluteReset := make(chan struct{}, 1)
absoluteDown := []byte{1, 0x34, 0x12, 0x78, 0x56, 0}
queue <- QueuedReport{
Data: absoluteDown,
Complete: func(success bool) { completed <- success },
ResetAbsoluteMouse: func() {
absoluteReset <- struct{}{}
},
}
queue <- QueuedReport{
Data: relativeMouseReleaseReport(),
Complete: func(success bool) { completed <- success },
ResetAbsoluteMouse: func() { absoluteReset <- struct{}{} },
}
close(queue)
done := make(chan struct{})
go func() {
h.mouseReports(queue, "unused-relative", "unused-absolute")
close(done)
}()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("mouse worker did not stop")
}
for range 2 {
select {
case success := <-completed:
if !success {
t.Fatal("mouse report failed")
}
default:
t.Fatal("missing mouse completion")
}
}
select {
case <-absoluteReset:
default:
t.Fatal("absolute state was not reset during mode switch")
}
absoluteData := make([]byte, 12)
if _, err := io.ReadFull(absoluteReader, absoluteData); err != nil {
t.Fatal(err)
}
if !bytes.Equal(absoluteData[:6], absoluteDown) {
t.Fatalf("absolute down report = %v", absoluteData[:6])
}
wantRelease := absoluteMouseReleaseReport(absoluteDown)
if !bytes.Equal(absoluteData[6:], wantRelease) {
t.Fatalf("absolute release report = %v, want %v", absoluteData[6:], wantRelease)
}
relativeData := make([]byte, 4)
if _, err := io.ReadFull(relativeReader, relativeData); err != nil {
t.Fatal(err)
}
if !bytes.Equal(relativeData, relativeMouseReleaseReport()) {
t.Fatalf("relative report = %v", relativeData)
}
h.Close()
}
func TestKeyboardFailureCompletesAfterCleanup(t *testing.T) {
path := filepath.Join(t.TempDir(), "hidg0")
closedFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
if err := closedFile.Close(); err != nil {
t.Fatal(err)
}
h := &Hid{g0: closedFile}
queue := make(chan QueuedReport, 1)
cleanupStarted := make(chan struct{})
allowCleanup := make(chan struct{})
cleanupFinished := make(chan struct{})
completed := make(chan bool, 1)
executions := 0
queue <- QueuedReport{
Data: []byte{0, 0, 4, 0, 0, 0, 0, 0},
Execute: func(write func() error) error {
executions++
if executions == 2 {
close(cleanupStarted)
<-allowCleanup
}
err := write()
if executions == 2 {
close(cleanupFinished)
}
return err
},
Complete: func(success bool) { completed <- success },
}
close(queue)
done := make(chan struct{})
go func() {
h.keyboardReports(queue, path)
close(done)
}()
select {
case <-cleanupStarted:
case <-time.After(time.Second):
t.Fatal("cleanup did not start")
}
select {
case success := <-completed:
t.Fatalf("reservation completed before cleanup: success=%v", success)
default:
}
close(allowCleanup)
select {
case <-cleanupFinished:
case <-time.After(time.Second):
t.Fatal("cleanup did not finish")
}
select {
case success := <-completed:
if success {
t.Fatal("failed write completed successfully")
}
case <-time.After(time.Second):
t.Fatal("reservation was not completed")
}
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("keyboard worker did not stop")
}
h.Close()
}
func TestKeyboardFailureCompletesFalseWhenCleanupFails(t *testing.T) {
path := filepath.Join(t.TempDir(), "hidg0")
closedFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
if err := closedFile.Close(); err != nil {
t.Fatal(err)
}
h := &Hid{g0: closedFile}
queue := make(chan QueuedReport, 1)
completed := make(chan bool, 1)
queue <- QueuedReport{
Data: []byte{0, 0, 4, 0, 0, 0, 0, 0},
Complete: func(success bool) { completed <- success },
}
close(queue)
done := make(chan struct{})
go func() {
h.keyboardReports(queue, filepath.Join(t.TempDir(), "missing", "hidg0"))
close(done)
}()
select {
case success := <-completed:
if success {
t.Fatal("failed keyboard write completed successfully after cleanup failed")
}
case <-time.After(time.Second):
t.Fatal("reservation was not completed")
}
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("keyboard worker did not stop")
}
h.Close()
}
func TestMouseFailureCompletesFalseWhenCleanupFails(t *testing.T) {
path := filepath.Join(t.TempDir(), "hidg1")
closedFile, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
t.Fatal(err)
}
if err := closedFile.Close(); err != nil {
t.Fatal(err)
}
h := &Hid{g1: closedFile}
queue := make(chan QueuedReport, 1)
completed := make(chan bool, 1)
queue <- QueuedReport{
Data: []byte{1, 0, 0, 0},
Complete: func(success bool) { completed <- success },
}
close(queue)
done := make(chan struct{})
go func() {
h.mouseReports(queue, filepath.Join(t.TempDir(), "missing", "hidg1"), filepath.Join(t.TempDir(), "hidg2"))
close(done)
}()
select {
case success := <-completed:
if success {
t.Fatal("failed mouse write completed successfully after cleanup failed")
}
case <-time.After(time.Second):
t.Fatal("reservation was not completed")
}
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("mouse worker did not stop")
}
h.Close()
}

View File

@@ -0,0 +1,48 @@
package hid
import (
"errors"
"fmt"
log "github.com/sirupsen/logrus"
)
type reportWriter interface {
WriteKeyboardReport([]byte) error
WriteRelativeMouseReport([]byte) error
WriteAbsoluteMouseReport([]byte) error
}
func ReleaseAllHIDState() error {
return releaseAllHIDState(GetHid())
}
func ReleaseAllHIDStateBestEffort() error {
return releaseAllHIDStateBestEffort(GetHid())
}
func releaseAllHIDStateBestEffort(writer reportWriter) error {
if err := releaseAllHIDState(writer); err != nil {
log.Warnf("failed to release HID state during control switch: %v", err)
}
return nil
}
func releaseAllHIDState(writer reportWriter) error {
if writer == nil {
return fmt.Errorf("HID writer is unavailable")
}
var errs []error
if err := writer.WriteKeyboardReport(keyboardReleaseReport()); err != nil {
errs = append(errs, fmt.Errorf("release keyboard: %w", err))
}
if err := writer.WriteRelativeMouseReport(relativeMouseReleaseReport()); err != nil {
errs = append(errs, fmt.Errorf("release relative mouse: %w", err))
}
if err := writer.WriteAbsoluteMouseReport(absoluteMouseReleaseReport(nil)); err != nil {
errs = append(errs, fmt.Errorf("release absolute mouse: %w", err))
}
return errors.Join(errs...)
}

View File

@@ -0,0 +1,77 @@
package hid
import (
"errors"
"strings"
"testing"
)
type releaseRecordingWriter struct {
keyboardErr error
relativeErr error
absoluteErr error
keyboard int
relative int
absolute int
}
func (w *releaseRecordingWriter) WriteKeyboardReport([]byte) error {
w.keyboard++
return w.keyboardErr
}
func (w *releaseRecordingWriter) WriteRelativeMouseReport([]byte) error {
w.relative++
return w.relativeErr
}
func (w *releaseRecordingWriter) WriteAbsoluteMouseReport([]byte) error {
w.absolute++
return w.absoluteErr
}
func TestReleaseAllHIDStateAttemptsEveryDevice(t *testing.T) {
writer := &releaseRecordingWriter{
keyboardErr: errors.New("keyboard failed"),
relativeErr: errors.New("relative failed"),
absoluteErr: errors.New("absolute failed"),
}
err := releaseAllHIDState(writer)
if err == nil {
t.Fatal("expected joined release error")
}
if writer.keyboard != 1 || writer.relative != 1 || writer.absolute != 1 {
t.Fatalf("release attempts keyboard=%d relative=%d absolute=%d", writer.keyboard, writer.relative, writer.absolute)
}
for _, message := range []string{"release keyboard", "release relative mouse", "release absolute mouse"} {
if !strings.Contains(err.Error(), message) {
t.Fatalf("error %q missing %q", err, message)
}
}
}
func TestReleaseAllHIDStateSuccess(t *testing.T) {
writer := &releaseRecordingWriter{}
if err := releaseAllHIDState(writer); err != nil {
t.Fatal(err)
}
if writer.keyboard != 1 || writer.relative != 1 || writer.absolute != 1 {
t.Fatalf("release attempts keyboard=%d relative=%d absolute=%d", writer.keyboard, writer.relative, writer.absolute)
}
}
func TestReleaseAllHIDStateBestEffortSuppressesErrors(t *testing.T) {
writer := &releaseRecordingWriter{
keyboardErr: errors.New("keyboard failed"),
relativeErr: errors.New("relative failed"),
absoluteErr: errors.New("absolute failed"),
}
if err := releaseAllHIDStateBestEffort(writer); err != nil {
t.Fatalf("best-effort release error = %v, want nil", err)
}
if writer.keyboard != 1 || writer.relative != 1 || writer.absolute != 1 {
t.Fatalf("release attempts keyboard=%d relative=%d absolute=%d", writer.keyboard, writer.relative, writer.absolute)
}
}

View File

@@ -1,11 +1,24 @@
package hid
import (
"NanoKVM-Server/service/controlmode"
"NanoKVM-Server/service/inputcontrol"
)
type Service struct {
hid *Hid
hid *Hid
control *controlmode.Manager
coordinator *inputcontrol.Coordinator
}
func NewService() *Service {
return &Service{
hid: GetHid(),
hid: GetHid(),
control: controlmode.GetManager(),
coordinator: inputcontrol.GetCoordinator(),
}
}
func (s *Service) newManualSession() *inputcontrol.ManualSession {
return inputcontrol.NewManualSession(s.control, s.coordinator)
}

View File

@@ -0,0 +1,172 @@
package hid
import (
"encoding/json"
"errors"
"os"
"sync"
"NanoKVM-Server/proto"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
)
var (
shortcutFile = "/etc/kvm/shortcuts.json"
shortcutMutex = sync.RWMutex{}
)
type ShortcutStore struct {
Shortcuts []proto.Shortcut `json:"shortcuts"`
}
func (s *Service) GetShortcuts(c *gin.Context) {
var rsp proto.Response
shortcuts, err := listShortcuts()
if err != nil {
log.Errorf("failed to get shortcuts: %v", err)
rsp.ErrRsp(c, -1, "get shortcuts failed")
return
}
rsp.OkRspWithData(c, &proto.GetShortcutsRsp{
Shortcuts: shortcuts,
})
log.Debugf("get shortcuts success, total: %d", len(shortcuts))
}
func (s *Service) AddShortcut(c *gin.Context) {
var req proto.AddShortcutReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
shortcut, err := addShortcut(req.Keys)
if err != nil {
log.Errorf("failed to add shortcut: %v", err)
rsp.ErrRsp(c, -2, "add shortcut failed")
return
}
rsp.OkRsp(c)
log.Debugf("add shortcut %s", shortcut.ID)
}
func (s *Service) DeleteShortcut(c *gin.Context) {
var req proto.DeleteShortcutReq
var rsp proto.Response
if err := proto.ParseFormRequest(c, &req); err != nil {
rsp.ErrRsp(c, -1, "invalid arguments")
return
}
err := deleteShortcut(req.ID)
if err != nil {
log.Errorf("failed to delete shortcut: %v", err)
rsp.ErrRsp(c, -2, "delete shortcut failed")
return
}
rsp.OkRsp(c)
log.Debugf("delete shortcut %s", req.ID)
}
func loadShortcuts() (*ShortcutStore, error) {
if _, err := os.Stat(shortcutFile); os.IsNotExist(err) {
return &ShortcutStore{Shortcuts: []proto.Shortcut{}}, nil
}
data, err := os.ReadFile(shortcutFile)
if err != nil {
return nil, err
}
if len(data) == 0 {
return &ShortcutStore{Shortcuts: []proto.Shortcut{}}, nil
}
var store ShortcutStore
if err := json.Unmarshal(data, &store); err != nil {
return nil, err
}
return &store, nil
}
func saveShortcuts(store *ShortcutStore) error {
data, err := json.Marshal(store)
if err != nil {
return err
}
return os.WriteFile(shortcutFile, data, 0644)
}
func listShortcuts() ([]proto.Shortcut, error) {
shortcutMutex.RLock()
defer shortcutMutex.RUnlock()
store, err := loadShortcuts()
if err != nil {
return nil, err
}
return store.Shortcuts, nil
}
func addShortcut(keys []proto.ShortcutKey) (*proto.Shortcut, error) {
shortcutMutex.Lock()
defer shortcutMutex.Unlock()
store, err := loadShortcuts()
if err != nil {
return nil, err
}
shortcut := proto.Shortcut{
ID: uuid.New().String(),
Keys: keys,
}
store.Shortcuts = append(store.Shortcuts, shortcut)
if err := saveShortcuts(store); err != nil {
return nil, err
}
return &shortcut, nil
}
func deleteShortcut(id string) error {
shortcutMutex.Lock()
defer shortcutMutex.Unlock()
store, err := loadShortcuts()
if err != nil {
return err
}
found := false
newShortcuts := make([]proto.Shortcut, 0, len(store.Shortcuts))
for _, shortcut := range store.Shortcuts {
if shortcut.ID == id {
found = true
continue
}
newShortcuts = append(newShortcuts, shortcut)
}
if !found {
return errors.New("shortcut not found")
}
store.Shortcuts = newShortcuts
return saveShortcuts(store)
}

View File

@@ -1,7 +1,6 @@
package hid
import (
"NanoKVM-Server/proto"
"errors"
"fmt"
"io"
@@ -10,6 +9,9 @@ import (
"strings"
"time"
"NanoKVM-Server/proto"
"NanoKVM-Server/service/inputcontrol"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
@@ -33,7 +35,7 @@ var modeMap = map[string]string{
func (s *Service) GetHidMode(c *gin.Context) {
var rsp proto.Response
mode, err := getHidMode()
mode, err := GetMode()
if err != nil {
rsp.ErrRsp(c, -1, "get HID mode failed")
return
@@ -45,6 +47,23 @@ func (s *Service) GetHidMode(c *gin.Context) {
log.Debugf("get hid mode: %s", mode)
}
func (s *Service) GetKeyboardLedStatus(c *gin.Context) {
var rsp proto.Response
status := GetKeyboardLedStatus()
updatedAt := ""
if !status.UpdatedAt.IsZero() {
updatedAt = status.UpdatedAt.UTC().Format(time.RFC3339Nano)
}
rsp.OkRspWithData(c, &proto.GetKeyboardLedStatusRsp{
NumLock: status.NumLock,
CapsLock: status.CapsLock,
ScrollLock: status.ScrollLock,
Known: status.Known,
UpdatedAt: updatedAt,
})
}
func (s *Service) SetHidMode(c *gin.Context) {
var req proto.SetHidModeReq
var rsp proto.Response
@@ -58,7 +77,7 @@ func (s *Service) SetHidMode(c *gin.Context) {
return
}
if mode, _ := getHidMode(); req.Mode == mode {
if mode, _ := GetMode(); req.Mode == mode {
rsp.OkRsp(c)
return
}
@@ -91,16 +110,16 @@ func (s *Service) SetHidMode(c *gin.Context) {
func (s *Service) ResetHid(c *gin.Context) {
var rsp proto.Response
h := GetHid()
h.Lock()
h.CloseNoLock()
defer func() {
h.OpenNoLock()
h.Unlock()
}()
command := fmt.Sprintf("%s restart_phy", USBDevScript)
err := exec.Command("sh", "-c", command).Run()
manual := s.newManualSession()
defer manual.Close()
reservation, err := manual.Reserve(c.Request.Context(), inputcontrol.ManualRelativeMouse, false, nil)
if err != nil {
log.Errorf("failed to acquire manual control for HID reset: %v", err)
rsp.ErrRsp(c, -1, "HID control is busy")
return
}
err = manual.Execute(ResetUSBPHY)
reservation.Complete(err == nil)
if err != nil {
log.Errorf("failed to reset hid: %v", err)
rsp.ErrRsp(c, -1, "failed to reset hid")
@@ -111,6 +130,37 @@ func (s *Service) ResetHid(c *gin.Context) {
log.Debugf("reset hid success")
}
func (s *Service) RecoverUSB(c *gin.Context) {
var rsp proto.Response
if err := ResetUSBPHY(); err != nil {
log.Errorf("failed to recover usb: %v", err)
rsp.ErrRsp(c, -1, "failed to recover usb")
return
}
rsp.OkRsp(c)
log.Debugf("recover usb success")
}
func ResetUSBPHY() error {
h := GetHid()
h.Lock()
h.CloseNoLock()
defer h.Unlock()
command := fmt.Sprintf("%s restart_phy", USBDevScript)
if err := exec.Command("sh", "-c", command).Run(); err != nil {
return fmt.Errorf("restart usb phy: %w", err)
}
if err := h.OpenNoLockWithRetry(hidReopenTimeout, hidReopenRetryDelay); err != nil {
return fmt.Errorf("reopen HID devices after usb phy reset: %w", err)
}
return nil
}
func copyModeFile(srcScript string) error {
// open the source file
srcFile, err := os.Open(srcScript)
@@ -173,7 +223,7 @@ func copyModeFile(srcScript string) error {
return nil
}
func getHidMode() (string, error) {
func GetMode() (string, error) {
data, err := os.ReadFile(ModeFlag)
if err != nil {
log.Errorf("failed to read %s: %s", ModeFlag, err)

View File

@@ -0,0 +1,462 @@
package inputcontrol
import (
"context"
"errors"
"fmt"
"sync"
"time"
"NanoKVM-Server/service/controlmode"
)
var (
ErrMCPBusy = errors.New("MCP remote control is busy")
ErrManualControlActive = errors.New("manual control is active")
ErrManualInputBlocked = errors.New("manual input is blocked")
ErrManualPreempted = errors.New("MCP operation was preempted by manual input")
ErrMCPModeChanged = errors.New("MCP control mode changed")
)
const defaultManualCooldown = 2 * time.Second
type OperationKind uint8
const (
OperationHID OperationKind = iota
OperationReadOnly
)
type ManualReportKind uint8
const (
ManualKeyboard ManualReportKind = iota
ManualRelativeMouse
ManualAbsoluteMouse
)
type activeOperation struct {
id uint64
kind OperationKind
cancel context.CancelCauseFunc
done chan struct{}
}
type Coordinator struct {
mu sync.Mutex
manualWriteMu sync.Mutex
active *activeOperation
nextID uint64
manualSessions int
manualUntil time.Time
manualCooldown time.Duration
now func() time.Time
}
type ManualSession struct {
coordinator *Coordinator
control *controlmode.Manager
mu sync.Mutex
active bool
closed bool
generation uint64
pending int
keyboardHeld bool
relativeMouseHeld bool
absoluteMouseHeld bool
cooldownOnIdle bool
releaseControl func()
}
type ManualReservation struct {
once sync.Once
session *ManualSession
generation uint64
kind ManualReportKind
held bool
startCooldown bool
}
var defaultCoordinator = newCoordinator(defaultManualCooldown, time.Now)
func newCoordinator(cooldown time.Duration, now func() time.Time) *Coordinator {
if cooldown < 0 {
cooldown = 0
}
if now == nil {
now = time.Now
}
return &Coordinator{manualCooldown: cooldown, now: now}
}
func GetCoordinator() *Coordinator {
return defaultCoordinator
}
func NewManualSession(control *controlmode.Manager, coordinator *Coordinator) *ManualSession {
if control == nil {
control = controlmode.GetManager()
}
if coordinator == nil {
coordinator = GetCoordinator()
}
return &ManualSession{control: control, coordinator: coordinator}
}
func (c *Coordinator) BeginMCP(parent context.Context, kind OperationKind) (context.Context, func(), error) {
if parent == nil {
parent = context.Background()
}
c.mu.Lock()
defer c.mu.Unlock()
if c.active != nil {
return nil, nil, ErrMCPBusy
}
if kind == OperationHID && (c.manualSessions > 0 || c.currentTime().Before(c.manualUntil)) {
return nil, nil, ErrManualControlActive
}
c.nextID++
id := c.nextID
ctx, cancel := context.WithCancelCause(parent)
operation := &activeOperation{
id: id,
kind: kind,
cancel: cancel,
done: make(chan struct{}),
}
c.active = operation
var once sync.Once
release := func() {
once.Do(func() {
cancel(context.Canceled)
c.mu.Lock()
if c.active != nil && c.active.id == id {
c.active = nil
close(operation.done)
}
c.mu.Unlock()
})
}
return ctx, release, nil
}
// BeginBackground reserves the HID lane for a best-effort background action,
// such as the mouse jiggler. Callers should skip the action when it returns a
// busy error rather than delaying manual or MCP input.
func (c *Coordinator) BeginBackground(parent context.Context) (context.Context, func(), error) {
return c.BeginMCP(parent, OperationHID)
}
func (c *Coordinator) CancelMCP() {
c.CancelMCPWithCause(ErrMCPModeChanged)
}
func (c *Coordinator) CancelMCPWithCause(cause error) {
if cause == nil {
cause = context.Canceled
}
c.mu.Lock()
operation := c.active
c.mu.Unlock()
if operation != nil {
operation.cancel(cause)
}
}
func (c *Coordinator) beginManual(ctx context.Context) error {
if ctx == nil {
ctx = context.Background()
}
c.mu.Lock()
c.manualSessions++
operation := c.active
if operation != nil && operation.kind == OperationHID {
operation.cancel(ErrManualPreempted)
} else {
operation = nil
}
c.mu.Unlock()
if operation == nil {
return nil
}
select {
case <-operation.done:
return nil
case <-ctx.Done():
c.endManual(false)
return context.Cause(ctx)
}
}
func (c *Coordinator) endManual(startCooldown bool) {
c.mu.Lock()
defer c.mu.Unlock()
if c.manualSessions > 0 {
c.manualSessions--
}
if startCooldown && c.manualSessions == 0 {
c.manualUntil = c.currentTime().Add(c.cooldown())
}
}
func (c *Coordinator) currentTime() time.Time {
if c.now == nil {
return time.Now()
}
return c.now()
}
func (c *Coordinator) cooldown() time.Duration {
if c.manualCooldown <= 0 {
return defaultManualCooldown
}
return c.manualCooldown
}
func (c *Coordinator) executeManual(write func() error) error {
if write == nil {
return nil
}
c.manualWriteMu.Lock()
defer c.manualWriteMu.Unlock()
return write()
}
func (s *ManualSession) Reserve(
ctx context.Context,
kind ManualReportKind,
held bool,
allow func(controlmode.Mode) bool,
) (*ManualReservation, error) {
return s.reserve(ctx, kind, held, true, allow)
}
func (s *ManualSession) ReserveWithCooldown(
ctx context.Context,
kind ManualReportKind,
held bool,
startCooldown bool,
allow func(controlmode.Mode) bool,
) (*ManualReservation, error) {
return s.reserve(ctx, kind, held, startCooldown, allow)
}
func (s *ManualSession) reserve(
ctx context.Context,
kind ManualReportKind,
held bool,
startCooldown bool,
allow func(controlmode.Mode) bool,
) (*ManualReservation, error) {
if s == nil || s.coordinator == nil || s.control == nil {
return nil, fmt.Errorf("manual input coordinator is unavailable")
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return nil, fmt.Errorf("manual input session is closed")
}
if s.active {
status, err := s.control.Status()
if err != nil {
s.mu.Unlock()
return nil, err
}
allowed := !status.Transitioning && (allow == nil || allow(status.Mode))
if !allowed && !s.isReleaseReportLocked(kind, held) {
s.mu.Unlock()
return nil, ErrManualInputBlocked
}
s.pending++
startCooldown = startCooldown || s.isReleaseReportLocked(kind, held)
reservation := &ManualReservation{
session: s, generation: s.generation, kind: kind, held: held, startCooldown: startCooldown,
}
s.mu.Unlock()
return reservation, nil
}
s.mu.Unlock()
status, releaseControl, err := s.control.AcquireStable()
if err != nil {
return nil, err
}
if allow != nil && !allow(status.Mode) {
releaseControl()
return nil, ErrManualInputBlocked
}
if err := s.coordinator.beginManual(ctx); err != nil {
releaseControl()
return nil, err
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
s.coordinator.endManual(false)
releaseControl()
return nil, fmt.Errorf("manual input session is closed")
}
if s.active {
// Reserve calls are serialized for a WebSocket client, but keep this path
// safe for callers that share a session concurrently.
s.pending++
startCooldown = startCooldown || s.isReleaseReportLocked(kind, held)
reservation := &ManualReservation{
session: s, generation: s.generation, kind: kind, held: held, startCooldown: startCooldown,
}
s.mu.Unlock()
s.coordinator.endManual(false)
releaseControl()
return reservation, nil
}
s.active = true
s.generation++
s.pending = 1
s.releaseControl = releaseControl
reservation := &ManualReservation{
session: s, generation: s.generation, kind: kind, held: held, startCooldown: startCooldown,
}
s.mu.Unlock()
return reservation, nil
}
func (s *ManualSession) isReleaseReportLocked(kind ManualReportKind, held bool) bool {
if held {
return false
}
switch kind {
case ManualKeyboard:
return s.keyboardHeld
case ManualRelativeMouse, ManualAbsoluteMouse:
return s.relativeMouseHeld || s.absoluteMouseHeld
default:
return false
}
}
func (r *ManualReservation) Complete(success bool) {
if r == nil || r.session == nil {
return
}
r.once.Do(func() {
r.session.complete(r.generation, r.kind, r.held, success, r.startCooldown)
})
}
func (s *ManualSession) Execute(write func() error) error {
if s == nil || s.coordinator == nil {
return fmt.Errorf("manual input coordinator is unavailable")
}
return s.coordinator.executeManual(write)
}
func (s *ManualSession) Reset(kind ManualReportKind) {
if s == nil {
return
}
s.mu.Lock()
if !s.active {
s.mu.Unlock()
return
}
switch kind {
case ManualKeyboard:
s.keyboardHeld = false
case ManualRelativeMouse:
s.relativeMouseHeld = false
case ManualAbsoluteMouse:
s.absoluteMouseHeld = false
}
releaseControl, end, _ := s.finishIfIdleLocked()
s.mu.Unlock()
s.finish(releaseControl, end, true)
}
func (s *ManualSession) Close() {
if s == nil {
return
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return
}
s.closed = true
s.pending = 0
s.keyboardHeld = false
s.relativeMouseHeld = false
s.absoluteMouseHeld = false
s.cooldownOnIdle = false
releaseControl := s.releaseControl
end := s.active
s.active = false
s.releaseControl = nil
s.generation++
s.mu.Unlock()
s.finish(releaseControl, end, true)
}
func (s *ManualSession) complete(generation uint64, kind ManualReportKind, held bool, success bool, startCooldown bool) {
s.mu.Lock()
if !s.active || generation != s.generation {
s.mu.Unlock()
return
}
if s.pending > 0 {
s.pending--
}
if startCooldown {
s.cooldownOnIdle = true
}
if success {
switch kind {
case ManualKeyboard:
s.keyboardHeld = held
case ManualRelativeMouse:
s.relativeMouseHeld = held
case ManualAbsoluteMouse:
s.absoluteMouseHeld = held
}
} else {
s.keyboardHeld = false
s.relativeMouseHeld = false
s.absoluteMouseHeld = false
}
releaseControl, end, startCooldown := s.finishIfIdleLocked()
s.mu.Unlock()
s.finish(releaseControl, end, startCooldown)
}
func (s *ManualSession) finishIfIdleLocked() (func(), bool, bool) {
if !s.active || s.pending > 0 || s.keyboardHeld || s.relativeMouseHeld || s.absoluteMouseHeld {
return nil, false, false
}
releaseControl := s.releaseControl
startCooldown := s.cooldownOnIdle
s.active = false
s.releaseControl = nil
s.cooldownOnIdle = false
return releaseControl, true, startCooldown
}
func (s *ManualSession) finish(releaseControl func(), end bool, startCooldown bool) {
if !end {
return
}
if releaseControl != nil {
releaseControl()
}
s.coordinator.endManual(startCooldown)
}

View File

@@ -0,0 +1,474 @@
package inputcontrol
import (
"context"
"errors"
"path/filepath"
"sync"
"testing"
"time"
"NanoKVM-Server/service/controlmode"
)
func TestCoordinatorRejectsConcurrentMCP(t *testing.T) {
coordinator := newCoordinator(defaultManualCooldown, time.Now)
ctx, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
defer release()
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrMCPBusy) {
t.Fatalf("error = %v, want %v", err, ErrMCPBusy)
}
coordinator.CancelMCP()
if err := context.Cause(ctx); !errors.Is(err, ErrMCPModeChanged) {
t.Fatalf("context cause = %v, want %v", err, ErrMCPModeChanged)
}
}
func TestCoordinatorReleaseAllowsNextMCP(t *testing.T) {
coordinator := newCoordinator(defaultManualCooldown, time.Now)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
release()
_, nextRelease, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
nextRelease()
}
func TestManualInputPreemptsMCPWithoutSwitchingMode(t *testing.T) {
now := time.Unix(100, 0)
coordinator := newCoordinator(2*time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
operationCtx, releaseOperation, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
releaseMode, err := control.Acquire(controlmode.ModeMCP)
if err != nil {
t.Fatal(err)
}
manual := NewManualSession(control, coordinator)
type result struct {
reservation *ManualReservation
err error
}
done := make(chan result, 1)
go func() {
reservation, err := manual.Reserve(context.Background(), ManualKeyboard, false, nil)
done <- result{reservation: reservation, err: err}
}()
select {
case <-operationCtx.Done():
if cause := context.Cause(operationCtx); !errors.Is(cause, ErrManualPreempted) {
t.Fatalf("context cause = %v, want %v", cause, ErrManualPreempted)
}
case <-time.After(time.Second):
t.Fatal("manual input did not preempt active MCP operation")
}
releaseOperation()
releaseMode()
var reservation *ManualReservation
select {
case got := <-done:
if got.err != nil {
t.Fatal(got.err)
}
reservation = got.reservation
case <-time.After(time.Second):
t.Fatal("manual input did not acquire control")
}
if got := control.Current(); got != controlmode.ModeMCP {
t.Fatalf("mode = %q, want MCP to remain enabled", got)
}
reservation.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(3 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatalf("MCP did not resume after cooldown: %v", err)
}
release()
manual.Close()
}
func TestHeldManualInputBlocksMCPUntilReleaseAndCooldown(t *testing.T) {
now := time.Unix(200, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
down, err := manual.Reserve(context.Background(), ManualKeyboard, true, nil)
if err != nil {
t.Fatal(err)
}
down.Complete(true)
now = now.Add(10 * time.Second)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("held input error = %v, want %v", err, ErrManualControlActive)
}
up, err := manual.Reserve(context.Background(), ManualKeyboard, false, nil)
if err != nil {
t.Fatal(err)
}
up.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
release()
}
func TestFailedHeldManualInputDoesNotRemainHeld(t *testing.T) {
now := time.Unix(250, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
down, err := manual.Reserve(context.Background(), ManualKeyboard, true, nil)
if err != nil {
t.Fatal(err)
}
down.Complete(false)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatalf("failed held input remained active after cooldown: %v", err)
}
release()
}
func TestFailedReleaseReportClearsHeldManualInput(t *testing.T) {
tests := []struct {
name string
kind ManualReportKind
}{
{name: "keyboard", kind: ManualKeyboard},
{name: "relative mouse", kind: ManualRelativeMouse},
{name: "absolute mouse", kind: ManualAbsoluteMouse},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
now := time.Unix(260, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
down, err := manual.Reserve(context.Background(), tc.kind, true, nil)
if err != nil {
t.Fatal(err)
}
down.Complete(true)
up, err := manual.Reserve(context.Background(), tc.kind, false, nil)
if err != nil {
t.Fatal(err)
}
up.Complete(false)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatalf("failed release report left held input active: %v", err)
}
release()
})
}
}
func TestPointerMoveWithoutButtonsDoesNotStartCooldown(t *testing.T) {
coordinator := newCoordinator(time.Second, time.Now)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
move, err := manual.ReserveWithCooldown(context.Background(), ManualAbsoluteMouse, false, false, nil)
if err != nil {
t.Fatal(err)
}
move.Complete(true)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatalf("pointer move without buttons blocked MCP: %v", err)
}
release()
}
func TestReleaseReportForcesCooldown(t *testing.T) {
now := time.Unix(275, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
down, err := manual.ReserveWithCooldown(context.Background(), ManualRelativeMouse, true, true, nil)
if err != nil {
t.Fatal(err)
}
down.Complete(true)
up, err := manual.ReserveWithCooldown(context.Background(), ManualRelativeMouse, false, false, nil)
if err != nil {
t.Fatal(err)
}
up.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
release()
}
func TestCooldownAggregatesAcrossPendingReports(t *testing.T) {
now := time.Unix(285, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
move, err := manual.ReserveWithCooldown(context.Background(), ManualAbsoluteMouse, false, false, nil)
if err != nil {
t.Fatal(err)
}
wheel, err := manual.ReserveWithCooldown(context.Background(), ManualAbsoluteMouse, false, true, nil)
if err != nil {
t.Fatal(err)
}
wheel.Complete(true)
move.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
release()
}
func TestRelativeAndAbsoluteMouseHeldStateIsIndependent(t *testing.T) {
now := time.Unix(300, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
relativeDown, err := manual.Reserve(context.Background(), ManualRelativeMouse, true, nil)
if err != nil {
t.Fatal(err)
}
relativeDown.Complete(true)
absoluteMove, err := manual.Reserve(context.Background(), ManualAbsoluteMouse, false, nil)
if err != nil {
t.Fatal(err)
}
absoluteMove.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("relative button was cleared by absolute report: %v", err)
}
relativeUp, err := manual.Reserve(context.Background(), ManualRelativeMouse, false, nil)
if err != nil {
t.Fatal(err)
}
relativeUp.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatal(err)
}
release()
}
func TestAbsoluteMouseHeldStateSurvivesRelativeReport(t *testing.T) {
coordinator := newCoordinator(defaultManualCooldown, time.Now)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
absoluteDown, err := manual.Reserve(context.Background(), ManualAbsoluteMouse, true, nil)
if err != nil {
t.Fatal(err)
}
absoluteDown.Complete(true)
relativeMove, err := manual.Reserve(context.Background(), ManualRelativeMouse, false, nil)
if err != nil {
t.Fatal(err)
}
relativeMove.Complete(true)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("absolute button was cleared by relative report: %v", err)
}
}
func TestBlockedActiveSessionStillAllowsReleaseReport(t *testing.T) {
coordinator := newCoordinator(defaultManualCooldown, time.Now)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModePicoclaw)
manual := NewManualSession(control, coordinator)
defer manual.Close()
down, err := manual.Reserve(context.Background(), ManualKeyboard, true, func(controlmode.Mode) bool { return true })
if err != nil {
t.Fatal(err)
}
down.Complete(true)
if _, err := manual.Reserve(context.Background(), ManualKeyboard, true, func(controlmode.Mode) bool { return false }); !errors.Is(err, ErrManualInputBlocked) {
t.Fatalf("new held report error = %v, want %v", err, ErrManualInputBlocked)
}
up, err := manual.Reserve(context.Background(), ManualKeyboard, false, func(controlmode.Mode) bool { return false })
if err != nil {
t.Fatalf("release report was blocked: %v", err)
}
up.Complete(true)
}
func TestBlockedActiveSessionFailedReleaseClearsHeldReport(t *testing.T) {
now := time.Unix(325, 0)
coordinator := newCoordinator(time.Second, func() time.Time { return now })
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModePicoclaw)
manual := NewManualSession(control, coordinator)
defer manual.Close()
down, err := manual.Reserve(context.Background(), ManualKeyboard, true, func(controlmode.Mode) bool { return true })
if err != nil {
t.Fatal(err)
}
down.Complete(true)
if _, err := manual.Reserve(context.Background(), ManualKeyboard, true, func(controlmode.Mode) bool { return false }); !errors.Is(err, ErrManualInputBlocked) {
t.Fatalf("new held report error = %v, want %v", err, ErrManualInputBlocked)
}
up, err := manual.Reserve(context.Background(), ManualKeyboard, false, func(controlmode.Mode) bool { return false })
if err != nil {
t.Fatalf("release report was blocked: %v", err)
}
up.Complete(false)
if _, _, err := coordinator.BeginMCP(context.Background(), OperationHID); !errors.Is(err, ErrManualControlActive) {
t.Fatalf("cooldown error = %v, want %v", err, ErrManualControlActive)
}
now = now.Add(2 * time.Second)
_, release, err := coordinator.BeginMCP(context.Background(), OperationHID)
if err != nil {
t.Fatalf("failed blocked release report left held input active: %v", err)
}
release()
}
func TestReadOnlyMCPAllowedDuringManualControl(t *testing.T) {
coordinator := newCoordinator(defaultManualCooldown, time.Now)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
manual := NewManualSession(control, coordinator)
defer manual.Close()
reservation, err := manual.Reserve(context.Background(), ManualRelativeMouse, true, nil)
if err != nil {
t.Fatal(err)
}
reservation.Complete(true)
_, release, err := coordinator.BeginMCP(context.Background(), OperationReadOnly)
if err != nil {
t.Fatalf("read-only MCP operation was blocked by manual control: %v", err)
}
release()
}
func TestManualWritesAreSerialized(t *testing.T) {
coordinator := newCoordinator(defaultManualCooldown, time.Now)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeMCP)
first := NewManualSession(control, coordinator)
second := NewManualSession(control, coordinator)
defer first.Close()
defer second.Close()
firstReservation, err := first.Reserve(context.Background(), ManualKeyboard, false, nil)
if err != nil {
t.Fatal(err)
}
secondReservation, err := second.Reserve(context.Background(), ManualRelativeMouse, false, nil)
if err != nil {
t.Fatal(err)
}
entered := make(chan struct{})
releaseFirst := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
_ = first.Execute(func() error {
close(entered)
<-releaseFirst
return nil
})
firstReservation.Complete(true)
}()
<-entered
secondEntered := make(chan struct{})
go func() {
defer wg.Done()
_ = second.Execute(func() error {
close(secondEntered)
return nil
})
secondReservation.Complete(true)
}()
select {
case <-secondEntered:
t.Fatal("second manual write entered before the first completed")
case <-time.After(20 * time.Millisecond):
}
close(releaseFirst)
wg.Wait()
}

View File

@@ -0,0 +1,51 @@
package mcpservice
import (
"crypto/subtle"
"net/http"
"strings"
"NanoKVM-Server/service/controlmode"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
func APIKeyMiddleware(control *controlmode.Manager) gin.HandlerFunc {
if control == nil {
control = controlmode.GetManager()
}
return func(c *gin.Context) {
if err := control.Require(controlmode.ModeMCP); err != nil {
c.JSON(http.StatusForbidden, gin.H{"error": "MCP service is disabled"})
c.Abort()
return
}
cfg, err := loadConfig()
if err != nil {
log.Errorf("failed to load MCP config for authentication: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "MCP auth unavailable"})
c.Abort()
return
}
token, ok := extractBearer(c.GetHeader("Authorization"))
if !ok || cfg.APIKey == "" || subtle.ConstantTimeCompare([]byte(token), []byte(cfg.APIKey)) != 1 {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid MCP API key"})
c.Abort()
return
}
c.Next()
}
}
func extractBearer(header string) (string, bool) {
const prefix = "Bearer "
if !strings.HasPrefix(header, prefix) {
return "", false
}
token := strings.TrimSpace(strings.TrimPrefix(header, prefix))
return token, token != ""
}

View File

@@ -0,0 +1,163 @@
package mcpcapture
import (
"bytes"
"context"
"fmt"
"image/jpeg"
"time"
mcpservice "NanoKVM-Server/service/mcp"
)
const (
defaultQuality = 60
minimumQuality = 51
maximumQuality = 60
maximumJPEGBytes = 1 << 20
screenshotRetryDelay = 100 * time.Millisecond
maxTimeoutMS = 30_000
)
type VisionReader interface {
ReadMjpeg(width uint16, height uint16, quality uint16) ([]byte, int)
}
type ScreenReader func() (width uint16, height uint16)
type CaptureLeaseAcquirer func(context.Context) (release func(), claimFresh func() bool, err error)
type Snapshotter struct {
vision VisionReader
readScreen ScreenReader
captureSlot chan struct{}
retryDelay time.Duration
acquireLease CaptureLeaseAcquirer
}
func New(vision VisionReader, readScreen ScreenReader) *Snapshotter {
return NewWithCaptureLease(vision, readScreen, nil)
}
func NewWithCaptureLease(vision VisionReader, readScreen ScreenReader, acquireLease CaptureLeaseAcquirer) *Snapshotter {
return &Snapshotter{
vision: vision,
readScreen: readScreen,
captureSlot: make(chan struct{}, 1),
retryDelay: screenshotRetryDelay,
acquireLease: acquireLease,
}
}
func (s *Snapshotter) Capture(ctx context.Context, req mcpservice.SnapshotRequest) (mcpservice.Snapshot, error) {
if req.X != 0 || req.Y != 0 || req.W != 0 || req.H != 0 {
return mcpservice.Snapshot{}, fmt.Errorf("screenshot cropping is not supported")
}
if s.vision == nil || s.readScreen == nil {
return mcpservice.Snapshot{}, fmt.Errorf("screenshot capture is unavailable")
}
quality := req.Quality
if quality == 0 {
quality = defaultQuality
}
quality = clamp(quality, minimumQuality, maximumQuality)
timeoutMS := 3000
if req.TimeoutMS != nil {
timeoutMS = clamp(*req.TimeoutMS, 0, maxTimeoutMS)
}
select {
case s.captureSlot <- struct{}{}:
defer func() { <-s.captureSlot }()
case <-ctx.Done():
return mcpservice.Snapshot{}, ctx.Err()
}
if err := ctx.Err(); err != nil {
return mcpservice.Snapshot{}, err
}
if s.acquireLease != nil {
releaseLease, claimFresh, err := s.acquireLease(ctx)
if err != nil {
return mcpservice.Snapshot{}, err
}
if releaseLease != nil {
defer releaseLease()
}
deadline := time.Now().Add(time.Duration(timeoutMS) * time.Millisecond)
width, height := s.readScreen()
return s.capture(ctx, width, height, quality, deadline, timeoutMS, claimFresh)
}
deadline := time.Now().Add(time.Duration(timeoutMS) * time.Millisecond)
width, height := s.readScreen()
return s.capture(ctx, width, height, quality, deadline, timeoutMS, nil)
}
func (s *Snapshotter) capture(ctx context.Context, width uint16, height uint16, quality int, deadline time.Time, timeoutMS int, claimFresh func() bool) (mcpservice.Snapshot, error) {
for {
if err := ctx.Err(); err != nil {
return mcpservice.Snapshot{}, err
}
if timeoutMS > 0 && !time.Now().Before(deadline) {
return mcpservice.Snapshot{Message: "screenshot capture timed out"}, nil
}
data, result := s.vision.ReadMjpeg(width, height, uint16(quality))
snapshot := mcpservice.Snapshot{
RetCode: result,
Width: int(width),
Height: int(height),
JPEG: data,
}
switch {
case result >= 0 && result != 5 && len(data) > 0:
if claimFresh != nil && claimFresh() {
claimFresh = nil
continue
}
if len(data) > maximumJPEGBytes {
snapshot.JPEG = nil
snapshot.Message = "captured JPEG exceeds the MCP response size limit"
return snapshot, nil
}
config, err := jpeg.DecodeConfig(bytes.NewReader(data))
if err != nil {
snapshot.Message = "captured data is not a valid JPEG"
break
}
snapshot.OK = true
snapshot.Width = config.Width
snapshot.Height = config.Height
return snapshot, nil
case result == 5:
snapshot.Message = "no HDMI signal or frame unavailable"
case result == -3 || result == -4 || result == -5:
snapshot.Message = "screenshot capture is temporarily unavailable"
case result < 0 || len(data) == 0:
snapshot.Message = "failed to capture screenshot"
}
if timeoutMS == 0 || time.Now().Add(s.retryDelay).After(deadline) {
return snapshot, nil
}
timer := time.NewTimer(s.retryDelay)
select {
case <-ctx.Done():
timer.Stop()
return mcpservice.Snapshot{}, ctx.Err()
case <-timer.C:
}
}
}
func clamp(value int, minValue int, maxValue int) int {
if value < minValue {
return minValue
}
if value > maxValue {
return maxValue
}
return value
}

View File

@@ -0,0 +1,323 @@
package mcpcapture
import (
"bytes"
"context"
"errors"
"image"
"image/color"
"image/jpeg"
"sync"
"testing"
"time"
mcpservice "NanoKVM-Server/service/mcp"
)
func testJPEG(t *testing.T, width int, height int) []byte {
t.Helper()
img := image.NewRGBA(image.Rect(0, 0, width, height))
img.Set(0, 0, color.White)
var output bytes.Buffer
if err := jpeg.Encode(&output, img, nil); err != nil {
t.Fatal(err)
}
return output.Bytes()
}
type visionResponse struct {
data []byte
result int
}
type fakeVision struct {
mu sync.Mutex
responses []visionResponse
calls int
quality uint16
width uint16
height uint16
active int
maxActive int
delay time.Duration
}
func (v *fakeVision) ReadMjpeg(width uint16, height uint16, quality uint16) ([]byte, int) {
v.mu.Lock()
v.calls++
v.quality = quality
v.width = width
v.height = height
v.active++
if v.active > v.maxActive {
v.maxActive = v.active
}
index := v.calls - 1
response := visionResponse{result: -1}
if index < len(v.responses) {
response = v.responses[index]
} else if len(v.responses) > 0 {
response = v.responses[len(v.responses)-1]
}
v.mu.Unlock()
time.Sleep(v.delay)
v.mu.Lock()
v.active--
v.mu.Unlock()
return response.data, response.result
}
func TestCaptureSuccessAndQualityBounds(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{{data: testJPEG(t, 1920, 1080), result: 0}}}
snapshotter := New(vision, func() (uint16, uint16) { return 1920, 1080 })
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil {
t.Fatal(err)
}
if !snapshot.OK || snapshot.Width != 1920 || snapshot.Height != 1080 || vision.quality != defaultQuality || vision.width != 1920 || vision.height != 1080 {
t.Fatalf("snapshot=%+v capture=%dx%d quality=%d", snapshot, vision.width, vision.height, vision.quality)
}
_, err = snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{Quality: 200})
if err != nil || vision.quality != maximumQuality {
t.Fatalf("quality clamp=%d err=%v", vision.quality, err)
}
}
func TestCaptureRetriesNoSignal(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{{result: 5}, {result: -5}, {data: testJPEG(t, 1280, 720), result: 0}}}
snapshotter := New(vision, func() (uint16, uint16) { return 1280, 720 })
snapshotter.retryDelay = 0
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil || !snapshot.OK || vision.calls != 3 {
t.Fatalf("snapshot=%+v calls=%d err=%v", snapshot, vision.calls, err)
}
timeout := 0
vision = &fakeVision{responses: []visionResponse{{result: 5}}}
snapshotter = New(vision, func() (uint16, uint16) { return 1280, 720 })
snapshot, err = snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{TimeoutMS: &timeout})
if err != nil || snapshot.RetCode != 5 || vision.calls != 1 {
t.Fatalf("timeout snapshot=%+v calls=%d err=%v", snapshot, vision.calls, err)
}
}
func TestCaptureRetriesInitialReadFailure(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{
{result: -1},
{data: testJPEG(t, 1280, 720), result: 0},
}}
snapshotter := New(vision, func() (uint16, uint16) { return 1280, 720 })
snapshotter.retryDelay = 0
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil || !snapshot.OK || vision.calls != 2 {
t.Fatalf("snapshot=%+v calls=%d err=%v", snapshot, vision.calls, err)
}
}
func TestCaptureRetriesInvalidJPEG(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{
{data: []byte("partial jpeg"), result: 0},
{data: testJPEG(t, 1280, 720), result: 0},
}}
snapshotter := New(vision, func() (uint16, uint16) { return 1280, 720 })
snapshotter.retryDelay = 0
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil || !snapshot.OK || vision.calls != 2 {
t.Fatalf("snapshot=%+v calls=%d err=%v", snapshot, vision.calls, err)
}
}
func TestCaptureRejectsCropAndEmptyData(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{{result: 0}}}
snapshotter := New(vision, func() (uint16, uint16) { return 800, 600 })
if _, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{W: 10}); err == nil {
t.Fatal("expected crop error")
}
if vision.calls != 0 {
t.Fatalf("vision called for rejected crop: %d", vision.calls)
}
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil || snapshot.OK || snapshot.Message == "" {
t.Fatalf("snapshot=%+v err=%v", snapshot, err)
}
}
func TestCaptureSerializesConcurrentCalls(t *testing.T) {
vision := &fakeVision{
responses: []visionResponse{{data: testJPEG(t, 800, 600), result: 0}},
delay: 10 * time.Millisecond,
}
snapshotter := New(vision, func() (uint16, uint16) { return 800, 600 })
var wg sync.WaitGroup
for i := 0; i < 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
_, _ = snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
}()
}
wg.Wait()
if vision.maxActive != 1 {
t.Fatalf("max concurrent captures = %d", vision.maxActive)
}
}
func TestCapturePassesThroughAutomaticResolution(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{{data: testJPEG(t, 640, 480), result: 0}}}
snapshotter := New(vision, func() (uint16, uint16) { return 0, 0 })
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil {
t.Fatal(err)
}
if !snapshot.OK || snapshot.Width != 640 || snapshot.Height != 480 || vision.width != 0 || vision.height != 0 {
t.Fatalf("snapshot=%+v capture=%dx%d", snapshot, vision.width, vision.height)
}
}
func TestCaptureDropsClaimedFirstFreshFrame(t *testing.T) {
first := testJPEG(t, 320, 240)
second := testJPEG(t, 640, 480)
vision := &fakeVision{responses: []visionResponse{
{data: first, result: 0},
{data: second, result: 0},
}}
claimed := 0
snapshotter := NewWithCaptureLease(vision, func() (uint16, uint16) { return 640, 480 }, func(context.Context) (func(), func() bool, error) {
return nil, func() bool {
claimed++
return claimed == 1
}, nil
})
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil || !snapshot.OK || !bytes.Equal(snapshot.JPEG, second) || vision.calls != 2 || claimed != 1 {
t.Fatalf("snapshot=%+v calls=%d claimed=%d err=%v", snapshot, vision.calls, claimed, err)
}
}
func TestCaptureRejectsOversizedJPEG(t *testing.T) {
data := make([]byte, maximumJPEGBytes+1)
vision := &fakeVision{responses: []visionResponse{{data: data, result: 0}}}
snapshotter := New(vision, func() (uint16, uint16) { return 960, 540 })
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{})
if err != nil || snapshot.OK || len(snapshot.JPEG) != 0 || snapshot.Message == "" {
t.Fatalf("snapshot=%+v err=%v", snapshot, err)
}
}
func TestCaptureCancellationWhileWaitingForSlot(t *testing.T) {
snapshotter := New(&fakeVision{}, func() (uint16, uint16) { return 0, 0 })
snapshotter.captureSlot <- struct{}{}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := snapshotter.Capture(ctx, mcpservice.SnapshotRequest{})
if !errors.Is(err, context.Canceled) {
t.Fatalf("error=%v, want canceled", err)
}
<-snapshotter.captureSlot
}
func TestCaptureTimeoutStartsAfterSlotIsAcquired(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{{data: testJPEG(t, 320, 240), result: 0}}}
snapshotter := New(vision, func() (uint16, uint16) { return 320, 240 })
snapshotter.captureSlot <- struct{}{}
timeout := 1
done := make(chan struct {
snapshot mcpservice.Snapshot
err error
}, 1)
go func() {
snapshot, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{TimeoutMS: &timeout})
done <- struct {
snapshot mcpservice.Snapshot
err error
}{snapshot: snapshot, err: err}
}()
time.Sleep(5 * time.Millisecond)
<-snapshotter.captureSlot
select {
case result := <-done:
if result.err != nil || !result.snapshot.OK {
t.Fatalf("snapshot=%+v err=%v, want success after queue wait", result.snapshot, result.err)
}
case <-time.After(time.Second):
t.Fatal("capture did not complete after slot release")
}
}
func TestCaptureReleasesLeaseOnSuccessAndCancellation(t *testing.T) {
vision := &fakeVision{responses: []visionResponse{{data: testJPEG(t, 320, 240), result: 0}}}
acquired := 0
released := 0
snapshotter := NewWithCaptureLease(vision, func() (uint16, uint16) { return 320, 240 }, func(context.Context) (func(), func() bool, error) {
acquired++
return func() { released++ }, nil, nil
})
if _, err := snapshotter.Capture(context.Background(), mcpservice.SnapshotRequest{}); err != nil {
t.Fatal(err)
}
if acquired != 1 || released != 1 {
t.Fatalf("lease acquired=%d released=%d, want 1/1", acquired, released)
}
canceled, cancel := context.WithCancel(context.Background())
cancel()
if _, err := snapshotter.Capture(canceled, mcpservice.SnapshotRequest{}); !errors.Is(err, context.Canceled) {
t.Fatalf("error = %v, want canceled", err)
}
if acquired != 1 || released != 1 {
t.Fatalf("lease acquired=%d released=%d after cancellation before acquisition, want 1/1", acquired, released)
}
}
type blockingVision struct {
started chan struct{}
finish chan struct{}
}
func (v *blockingVision) ReadMjpeg(_ uint16, _ uint16, _ uint16) ([]byte, int) {
v.started <- struct{}{}
<-v.finish
return nil, 5
}
func TestCaptureReleasesLeaseAfterAcquisitionCancellation(t *testing.T) {
vision := &blockingVision{started: make(chan struct{}, 1), finish: make(chan struct{})}
acquired := 0
released := 0
snapshotter := NewWithCaptureLease(vision, func() (uint16, uint16) { return 320, 240 }, func(context.Context) (func(), func() bool, error) {
acquired++
return func() { released++ }, nil, nil
})
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() {
_, err := snapshotter.Capture(ctx, mcpservice.SnapshotRequest{})
done <- err
}()
<-vision.started
cancel()
close(vision.finish)
if err := <-done; !errors.Is(err, context.Canceled) {
t.Fatalf("error = %v, want canceled", err)
}
if acquired != 1 || released != 1 {
t.Fatalf("lease acquired=%d released=%d after cancellation during capture, want 1/1", acquired, released)
}
}

View File

@@ -0,0 +1,16 @@
package kvmcapture
import (
"NanoKVM-Server/common"
mcpservice "NanoKVM-Server/service/mcp"
"NanoKVM-Server/service/mcp/capture"
"NanoKVM-Server/service/vm"
)
func New() mcpservice.Snapshotter {
return mcpcapture.NewWithCaptureLease(common.GetKvmVision(), func() (uint16, uint16) {
screen := common.GetScreen()
common.CheckScreen()
return screen.Width, screen.Height
}, vm.AcquireHdmiCaptureLeaseForRead)
}

View File

@@ -0,0 +1,154 @@
package mcpservice
import (
"crypto/rand"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
)
const (
ConfigFile = "/etc/kvm/mcp.json"
apiKeyPrefix = "nag_mcp_"
apiKeyBytes = 32
)
var (
configMu sync.Mutex
configFilePath = ConfigFile
)
type Config struct {
APIKey string `json:"apiKey"`
}
func loadConfig() (Config, error) {
configMu.Lock()
defer configMu.Unlock()
return loadConfigFromPath(configFilePath)
}
func updateConfig(update func(Config) (Config, error)) (Config, error) {
configMu.Lock()
defer configMu.Unlock()
cfg, err := loadConfigFromPath(configFilePath)
if err != nil {
return Config{}, err
}
updated, err := update(cfg)
if err != nil {
return Config{}, err
}
if err := saveConfigToPath(configFilePath, updated); err != nil {
return Config{}, err
}
return updated, nil
}
func loadConfigFromPath(path string) (Config, error) {
data, err := os.ReadFile(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return Config{}, nil
}
return Config{}, err
}
var cfg Config
if err := json.Unmarshal(data, &cfg); err != nil {
return Config{}, fmt.Errorf("decode MCP config: %w", err)
}
return cfg, nil
}
func saveConfigToPath(path string, cfg Config) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("create MCP config directory: %w", err)
}
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
return fmt.Errorf("encode MCP config: %w", err)
}
data = append(data, '\n')
tmp, err := os.CreateTemp(dir, ".mcp.json.*")
if err != nil {
return fmt.Errorf("create temporary MCP config: %w", err)
}
tmpPath := tmp.Name()
defer func() { _ = os.Remove(tmpPath) }()
if err := tmp.Chmod(0o600); err != nil {
_ = tmp.Close()
return fmt.Errorf("set temporary MCP config permissions: %w", err)
}
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temporary MCP config: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temporary MCP config: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temporary MCP config: %w", err)
}
if err := os.Rename(tmpPath, path); err != nil {
return fmt.Errorf("replace MCP config: %w", err)
}
if err := os.Chmod(path, 0o600); err != nil {
return fmt.Errorf("set MCP config permissions: %w", err)
}
directory, err := os.Open(dir)
if err == nil {
if syncErr := directory.Sync(); syncErr != nil {
_ = directory.Close()
return fmt.Errorf("sync MCP config directory: %w", syncErr)
}
_ = directory.Close()
}
return nil
}
func ensureAPIKey(cfg Config) (Config, error) {
if cfg.APIKey != "" {
return cfg, nil
}
key, err := generateAPIKey()
if err != nil {
return Config{}, err
}
cfg.APIKey = key
return cfg, nil
}
func regenerateAPIKey(cfg Config) (Config, error) {
key, err := generateAPIKey()
if err != nil {
return Config{}, err
}
cfg.APIKey = key
return cfg, nil
}
func generateAPIKey() (string, error) {
raw := make([]byte, apiKeyBytes)
if _, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("generate MCP API key: %w", err)
}
return apiKeyPrefix + base64.RawURLEncoding.EncodeToString(raw), nil
}

View File

@@ -0,0 +1,262 @@
package mcpservice
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"NanoKVM-Server/service/controlmode"
"github.com/gin-gonic/gin"
)
func useTestConfig(t *testing.T) string {
t.Helper()
path := filepath.Join(t.TempDir(), "mcp.json")
oldPath := configFilePath
configFilePath = path
t.Cleanup(func() { configFilePath = oldPath })
return path
}
func TestConfigLifecycle(t *testing.T) {
path := useTestConfig(t)
cfg, err := loadConfig()
if err != nil || cfg.APIKey != "" {
t.Fatalf("unexpected missing config result: cfg=%+v err=%v", cfg, err)
}
cfg, err = updateConfig(func(cfg Config) (Config, error) {
cfg, err = ensureAPIKey(cfg)
return cfg, err
})
if err != nil || !strings.HasPrefix(cfg.APIKey, apiKeyPrefix) {
t.Fatalf("enable MCP: cfg=%+v err=%v", cfg, err)
}
firstKey := cfg.APIKey
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat config: %v", err)
}
if info.Mode().Perm() != 0o600 {
t.Fatalf("config permissions = %o, want 600", info.Mode().Perm())
}
cfg, err = updateConfig(ensureAPIKey)
if err != nil || cfg.APIKey != firstKey {
t.Fatalf("ensure existing key changed it: cfg=%+v err=%v", cfg, err)
}
cfg, err = updateConfig(regenerateAPIKey)
if err != nil || cfg.APIKey == firstKey {
t.Fatalf("regenerate did not replace key: cfg=%+v err=%v", cfg, err)
}
}
func TestLoadConfigRejectsCorruptJSON(t *testing.T) {
path := useTestConfig(t)
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := loadConfig(); err == nil {
t.Fatal("expected corrupt config error")
}
}
func TestAPIKeyMiddleware(t *testing.T) {
useTestConfig(t)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModeOff)
gin.SetMode(gin.TestMode)
router := gin.New()
router.GET("/api/mcp", APIKeyMiddleware(control), func(c *gin.Context) { c.Status(http.StatusNoContent) })
writeConfig := func(cfg Config) {
if _, err := updateConfig(func(Config) (Config, error) { return cfg, nil }); err != nil {
t.Fatal(err)
}
}
request := func(header string) *httptest.ResponseRecorder {
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/mcp", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
router.ServeHTTP(recorder, req)
return recorder
}
writeConfig(Config{APIKey: "secret"})
if got := request("Bearer secret").Code; got != http.StatusForbidden {
t.Fatalf("disabled status = %d", got)
}
if err := control.SwitchToMCP(nil); err != nil {
t.Fatal(err)
}
for _, header := range []string{"", "secret", "Basic secret", "Bearer wrong"} {
if got := request(header).Code; got != http.StatusUnauthorized {
t.Fatalf("header %q status = %d", header, got)
}
}
if got := request("Bearer secret").Code; got != http.StatusNoContent {
t.Fatalf("valid key status = %d", got)
}
writeConfig(Config{APIKey: "rotated"})
if got := request("Bearer secret").Code; got != http.StatusUnauthorized {
t.Fatalf("old key after rotation status = %d", got)
}
if got := request("Bearer rotated").Code; got != http.StatusNoContent {
t.Fatalf("rotated key status = %d", got)
}
}
func TestSetConfigAPI(t *testing.T) {
useTestConfig(t)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModePicoclaw)
preemptLeasesCalled := false
stopRuntimeCalled := false
releaseCalled := false
gin.SetMode(gin.TestMode)
service := NewServiceWithPreempt(control, func() error {
preemptLeasesCalled = true
return nil
}, func() error {
stopRuntimeCalled = true
return nil
}, func() error {
releaseCalled = true
return nil
}, nil)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/api/mcp/config", strings.NewReader(`{"enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
service.SetConfig(c)
if got := recorder.Header().Get("Cache-Control"); got != "no-store" {
t.Fatalf("Cache-Control = %q, want no-store", got)
}
var response struct {
Code int `json:"code"`
Data struct {
Enabled bool `json:"enabled"`
APIKey string `json:"apiKey"`
ControlMode string `json:"controlMode"`
} `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Code != 0 || !response.Data.Enabled || response.Data.APIKey == "" || response.Data.ControlMode != string(controlmode.ModeMCP) || !preemptLeasesCalled || !stopRuntimeCalled || !releaseCalled {
t.Fatalf("unexpected response: %+v", response)
}
recorder = httptest.NewRecorder()
c, _ = gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/api/mcp/config", strings.NewReader(`{"enabled":false}`))
c.Request.Header.Set("Content-Type", "application/json")
service.SetConfig(c)
if control.Current() != controlmode.ModeOff {
t.Fatalf("mode after disabling MCP = %q, want off", control.Current())
}
}
func TestSetConfigEnablePreemptFailureDoesNotEnableMCP(t *testing.T) {
useTestConfig(t)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModePicoclaw)
wantErr := errors.New("picoclaw stop failed")
service := NewServiceWithPreempt(control, func() error {
return wantErr
}, func() error {
t.Fatal("runtime stop should not run when soft preempt fails")
return nil
}, func() error {
t.Fatal("release should not run when preempt fails")
return nil
}, nil)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/api/mcp/config", strings.NewReader(`{"enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
service.SetConfig(c)
if control.Current() != controlmode.ModePicoclaw {
t.Fatalf("mode after failed preempt = %q, want picoclaw", control.Current())
}
var response struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Code != -2 || !strings.Contains(response.Msg, wantErr.Error()) {
t.Fatalf("response = %+v, want preempt failure", response)
}
}
func TestSetConfigEnableCleanupFailureFailsClosed(t *testing.T) {
useTestConfig(t)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModePicoclaw)
wantErr := errors.New("picoclaw stop failed")
preemptCalled := false
releaseCalled := false
service := NewServiceWithPreempt(control, func() error {
preemptCalled = true
return nil
}, func() error {
return wantErr
}, func() error {
releaseCalled = true
return nil
}, nil)
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/api/mcp/config", strings.NewReader(`{"enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
service.SetConfig(c)
if control.Current() != controlmode.ModeOff {
t.Fatalf("mode after failed destructive cleanup = %q, want off", control.Current())
}
if !preemptCalled || !releaseCalled {
t.Fatalf("preemptCalled=%v releaseCalled=%v, want both true", preemptCalled, releaseCalled)
}
var response struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if response.Code != -2 || !strings.Contains(response.Msg, wantErr.Error()) {
t.Fatalf("response = %+v, want cleanup failure", response)
}
}
func TestSetConfigEnableReleaseFailureFailsClosed(t *testing.T) {
useTestConfig(t)
control := controlmode.NewManager(filepath.Join(t.TempDir(), "mode"), controlmode.ModePicoclaw)
service := NewService(control, func() error { return errors.New("release failed") })
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/api/mcp/config", strings.NewReader(`{"enabled":true}`))
c.Request.Header.Set("Content-Type", "application/json")
service.SetConfig(c)
if control.Current() != controlmode.ModeOff {
t.Fatalf("mode after failed enable = %q, want off", control.Current())
}
cfg, err := loadConfig()
if err != nil || cfg.APIKey == "" {
t.Fatalf("API key should be persisted before switching: cfg=%+v err=%v", cfg, err)
}
}

View File

@@ -0,0 +1,122 @@
package mcpservice
import (
"fmt"
"sort"
"NanoKVM-Server/service/hid"
)
const maxKeyboardKeys = 6
var keyUpReport = []byte{0, 0, 0, 0, 0, 0, 0, 0}
var modifierMap = map[string]byte{
"ControlLeft": 1 << 0,
"ShiftLeft": 1 << 1,
"AltLeft": 1 << 2,
"MetaLeft": 1 << 3,
"ControlRight": 1 << 4,
"ShiftRight": 1 << 5,
"AltRight": 1 << 6,
"MetaRight": 1 << 7,
}
var keyCodeMap = map[string]byte{
"KeyA": 0x04, "KeyB": 0x05, "KeyC": 0x06, "KeyD": 0x07, "KeyE": 0x08,
"KeyF": 0x09, "KeyG": 0x0a, "KeyH": 0x0b, "KeyI": 0x0c, "KeyJ": 0x0d,
"KeyK": 0x0e, "KeyL": 0x0f, "KeyM": 0x10, "KeyN": 0x11, "KeyO": 0x12,
"KeyP": 0x13, "KeyQ": 0x14, "KeyR": 0x15, "KeyS": 0x16, "KeyT": 0x17,
"KeyU": 0x18, "KeyV": 0x19, "KeyW": 0x1a, "KeyX": 0x1b, "KeyY": 0x1c,
"KeyZ": 0x1d,
"Digit1": 0x1e, "Digit2": 0x1f, "Digit3": 0x20, "Digit4": 0x21, "Digit5": 0x22,
"Digit6": 0x23, "Digit7": 0x24, "Digit8": 0x25, "Digit9": 0x26, "Digit0": 0x27,
"Enter": 0x28, "Escape": 0x29, "Backspace": 0x2a, "Tab": 0x2b, "Space": 0x2c,
"Minus": 0x2d, "Equal": 0x2e, "BracketLeft": 0x2f, "BracketRight": 0x30,
"Backslash": 0x31, "IntlHash": 0x32, "Semicolon": 0x33, "Quote": 0x34,
"Backquote": 0x35, "Comma": 0x36, "Period": 0x37, "Slash": 0x38,
"CapsLock": 0x39,
"F1": 0x3a, "F2": 0x3b, "F3": 0x3c, "F4": 0x3d, "F5": 0x3e, "F6": 0x3f,
"F7": 0x40, "F8": 0x41, "F9": 0x42, "F10": 0x43, "F11": 0x44, "F12": 0x45,
"PrintScreen": 0x46, "ScrollLock": 0x47, "Pause": 0x48, "Insert": 0x49,
"Home": 0x4a, "PageUp": 0x4b, "Delete": 0x4c, "End": 0x4d,
"PageDown": 0x4e, "ArrowRight": 0x4f, "ArrowLeft": 0x50,
"ArrowDown": 0x51, "ArrowUp": 0x52,
"NumLock": 0x53, "NumpadDivide": 0x54, "NumpadMultiply": 0x55,
"NumpadSubtract": 0x56, "NumpadAdd": 0x57, "NumpadEnter": 0x58,
"Numpad1": 0x59, "Numpad2": 0x5a, "Numpad3": 0x5b, "Numpad4": 0x5c,
"Numpad5": 0x5d, "Numpad6": 0x5e, "Numpad7": 0x5f, "Numpad8": 0x60,
"Numpad9": 0x61, "Numpad0": 0x62, "NumpadDecimal": 0x63,
"IntlBackslash": 0x64, "ContextMenu": 0x65,
}
func supportedKeyNames() []any {
names := make([]string, 0, len(modifierMap)+len(keyCodeMap))
for name := range modifierMap {
names = append(names, name)
}
for name := range keyCodeMap {
names = append(names, name)
}
sort.Strings(names)
values := make([]any, len(names))
for index, name := range names {
values[index] = name
}
return values
}
func buildKeyComboReport(keys []string) ([]byte, error) {
report := make([]byte, 8)
seenKeys := make(map[byte]struct{})
keyIndex := 2
for _, key := range keys {
if modifier, ok := modifierMap[key]; ok {
report[0] |= modifier
continue
}
code, ok := keyCodeMap[key]
if !ok {
return nil, fmt.Errorf("unknown key: %s", key)
}
if _, ok := seenKeys[code]; ok {
continue
}
if keyIndex >= 2+maxKeyboardKeys {
return nil, fmt.Errorf("too many non-modifier keys")
}
seenKeys[code] = struct{}{}
report[keyIndex] = code
keyIndex++
}
return report, nil
}
func buildTypeReports(text string) ([][]byte, []rune) {
charMap := hid.GetCharMap("")
reports := make([][]byte, 0, len(text)*2)
skipped := make([]rune, 0)
for _, char := range text {
key, ok := charMap[char]
if !ok {
skipped = append(skipped, char)
continue
}
reports = append(reports,
[]byte{byte(key.Modifiers), 0, byte(key.Code), 0, 0, 0, 0, 0},
append([]byte(nil), keyUpReport...),
)
}
return reports, skipped
}

View File

@@ -0,0 +1,37 @@
package mcpservice
import "testing"
func TestBuildKeyComboReport(t *testing.T) {
report, err := buildKeyComboReport([]string{"ControlLeft", "AltLeft", "Delete"})
if err != nil {
t.Fatal(err)
}
if report[0] != 0x05 || report[2] != 0x4c {
t.Fatalf("unexpected combo report: %v", report)
}
if _, err := buildKeyComboReport([]string{"Unknown"}); err == nil {
t.Fatal("expected unknown key error")
}
if _, err := buildKeyComboReport([]string{"KeyA", "KeyB", "KeyC", "KeyD", "KeyE", "KeyF", "KeyG"}); err == nil {
t.Fatal("expected six-key limit error")
}
}
func TestBuildTypeReportsReturnsSkippedRunes(t *testing.T) {
reports, skipped := buildTypeReports("A界")
if len(reports) != 2 || string(skipped) != "界" {
t.Fatalf("reports=%d skipped=%q", len(reports), string(skipped))
}
if reports[0][0] != 2 || reports[0][2] != 4 || string(reports[1]) != string(keyUpReport) {
t.Fatalf("unexpected reports: %v", reports)
}
}
func TestSupportedKeyNamesMatchKeyboardDescriptor(t *testing.T) {
for name, code := range keyCodeMap {
if code > 0x65 {
t.Fatalf("key %s uses unsupported descriptor code %#x", name, code)
}
}
}

View File

@@ -0,0 +1,93 @@
package mcpservice
import (
"fmt"
"math"
)
const (
maxRelativeMouseReports = 1024
maxRelativeMouseDelta = 127 * maxRelativeMouseReports
)
func absoluteCoordinate(value float64) uint16 {
value = math.Max(0, math.Min(1, value))
return uint16(math.Floor(0x7fff*value)) + 1
}
func buildAbsolutePointerReport(x uint16, y uint16, buttons byte, wheel int) []byte {
return []byte{
buttons,
byte(x), byte(x >> 8),
byte(y), byte(y >> 8),
byte(int8(clampInt(wheel, -127, 127))),
}
}
func buildRelativeMouseReport(deltaX int, deltaY int, buttons byte, wheel int) []byte {
return []byte{
buttons,
byte(int8(clampInt(deltaX, -127, 127))),
byte(int8(clampInt(deltaY, -127, 127))),
byte(int8(clampInt(wheel, -127, 127))),
}
}
func buildRelativeMoveReports(deltaX int, deltaY int) ([][]byte, error) {
if relativeReportCount(deltaX, deltaY) > maxRelativeMouseReports {
return nil, fmt.Errorf("relative movement exceeds %d reports", maxRelativeMouseReports)
}
reports := make([][]byte, 0)
for deltaX != 0 || deltaY != 0 {
x := clampInt(deltaX, -127, 127)
y := clampInt(deltaY, -127, 127)
reports = append(reports, buildRelativeMouseReport(x, y, 0, 0))
deltaX -= x
deltaY -= y
}
return reports, nil
}
func mouseButtonBit(button string) (byte, error) {
switch button {
case "left":
return 1 << 0, nil
case "right":
return 1 << 1, nil
case "middle":
return 1 << 2, nil
default:
return 0, fmt.Errorf("unknown mouse button: %s", button)
}
}
func clampInt(value int, minValue int, maxValue int) int {
if value < minValue {
return minValue
}
if value > maxValue {
return maxValue
}
return value
}
func relativeReportCount(deltaX int, deltaY int) int {
xReports := reportsForDelta(deltaX)
yReports := reportsForDelta(deltaY)
if xReports > yReports {
return xReports
}
return yReports
}
func reportsForDelta(delta int) int {
value := int64(delta)
if value == 0 {
return 0
}
if value < 0 {
return int((-(value + 1))/127 + 1)
}
return int((value-1)/127 + 1)
}

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