mirror of
https://github.com/sipeed/NanoKVM.git
synced 2026-11-10 01:49:00 -06:00
Compare commits
388 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2ca5b19efe | ||
|
|
40f3917014 | ||
|
|
a40433522c | ||
|
|
8470b89214 | ||
|
|
5a08170518 | ||
|
|
36cf9c30d8 | ||
|
|
1c43542919 | ||
|
|
4080788cab | ||
|
|
424302789e | ||
|
|
6651167dd8 | ||
|
|
2d67720022 | ||
|
|
1893912ba7 | ||
|
|
e41ce2d6b8 | ||
|
|
a5c6489f19 | ||
|
|
fafef3d89a | ||
|
|
4b5f539445 | ||
|
|
cefe0f9ab2 | ||
|
|
7f3d29eba2 | ||
|
|
64681e2aac | ||
|
|
fcb1f1c7fe | ||
|
|
aa0546ff37 | ||
|
|
3254412017 | ||
|
|
fda3c6b1a8 | ||
|
|
97832557fb | ||
|
|
590db5b08c | ||
|
|
10a512ec96 | ||
|
|
08093dddad | ||
|
|
86a85a61b7 | ||
|
|
cb3a2c562e | ||
|
|
832832a716 | ||
|
|
5fe6d0d48f | ||
|
|
67fe57f189 | ||
|
|
44caee21ab | ||
|
|
5b2a1ff788 | ||
|
|
dc5ba29bcf | ||
|
|
89c14310c7 | ||
|
|
3322a3c07f | ||
|
|
9e1251ad6a | ||
|
|
afec4efb34 | ||
|
|
11980b9122 | ||
|
|
2a43fb5413 | ||
|
|
57887f3f69 | ||
|
|
2b8f640957 | ||
|
|
4af32fc703 | ||
|
|
a611e5ef56 | ||
|
|
94051c3037 | ||
|
|
d5cd706078 | ||
|
|
7460ebfd07 | ||
|
|
e3877308a0 | ||
|
|
7c28fb8124 | ||
|
|
b18873364f | ||
|
|
016a7d8a51 | ||
|
|
585f1bc2b5 | ||
|
|
4fcc4c3747 | ||
|
|
0d2c52adc3 | ||
|
|
af256e7f92 | ||
|
|
84830421ee | ||
|
|
9b278cdb0e | ||
|
|
9b40a5cf86 | ||
|
|
b8d980be33 | ||
|
|
195037af87 | ||
|
|
c98000069a | ||
|
|
2bd277b57d | ||
|
|
4852ed813b | ||
|
|
fb08df9e4e | ||
|
|
64f3b49e21 | ||
|
|
329c0a0001 | ||
|
|
c28273d1f0 | ||
|
|
1d22d75889 | ||
|
|
6ef8bb74e3 | ||
|
|
0e00760474 | ||
|
|
d969bd68ec | ||
|
|
1e5f4cb24b | ||
|
|
4d3b1c835e | ||
|
|
e3558933b1 | ||
|
|
7762706200 | ||
|
|
b66707c959 | ||
|
|
a3440cf867 | ||
|
|
1b7021d64b | ||
|
|
687dd3bfc4 | ||
|
|
cc072ab158 | ||
|
|
b0a01a9837 | ||
|
|
2d575b916c | ||
|
|
1f908ef181 | ||
|
|
fb2adf13ee | ||
|
|
ad9eb44ad8 | ||
|
|
b4962e7a58 | ||
|
|
14614e5e35 | ||
|
|
9a93ab24f5 | ||
|
|
aaad552633 | ||
|
|
79cc1cc2bf | ||
|
|
01bcda6886 | ||
|
|
ec49bffe06 | ||
|
|
2db5d86a3c | ||
|
|
da6d4840f8 | ||
|
|
9afa21a0b0 | ||
|
|
6168069301 | ||
|
|
ffe71ae6b1 | ||
|
|
a6a97df4e7 | ||
|
|
f05467f45c | ||
|
|
969e3a5e6a | ||
|
|
f0e7dc069c | ||
|
|
f5f70bd015 | ||
|
|
aa80e1d7cc | ||
|
|
d6b03a345b | ||
|
|
c0cfcfa31a | ||
|
|
afdbb179ad | ||
|
|
ed9b7c5126 | ||
|
|
551329a41d | ||
|
|
b3c6b6c53d | ||
|
|
5a9cd18f94 | ||
|
|
63c8fc8eb5 | ||
|
|
3305c69e2d | ||
|
|
56a0468a53 | ||
|
|
52416dfdd7 | ||
|
|
bcd0b717ee | ||
|
|
d9c9eae4f9 | ||
|
|
c1a21c2d69 | ||
|
|
8d822948cf | ||
|
|
7404a205a5 | ||
|
|
d774bf8c58 | ||
|
|
0e1fae8751 | ||
|
|
3ff64483df | ||
|
|
fed92254d2 | ||
|
|
dec1621850 | ||
|
|
116bb50364 | ||
|
|
957d86d64c | ||
|
|
1fa6f48d4e | ||
|
|
0610f6fd1a | ||
|
|
ade9ac863f | ||
|
|
61ff3c5b23 | ||
|
|
19076b2508 | ||
|
|
e175147674 | ||
|
|
2cc64d2208 | ||
|
|
346315b4bb | ||
|
|
648c9f866e | ||
|
|
b5866088fc | ||
|
|
cd954b6f24 | ||
|
|
f27102d344 | ||
|
|
ba8e8b7a5c | ||
|
|
cb3834bb71 | ||
|
|
8ec134c182 | ||
|
|
631d944d70 | ||
|
|
f539576a49 | ||
|
|
fa11347f1b | ||
|
|
34c66dbd8b | ||
|
|
3d5c14405c | ||
|
|
9e4408409f | ||
|
|
9b629c8dc0 | ||
|
|
8da7a70bfc | ||
|
|
ea6ac3c903 | ||
|
|
6b783677e5 | ||
|
|
1cc31c30a3 | ||
|
|
92d5f63679 | ||
|
|
9fd3728aee | ||
|
|
916803d0f0 | ||
|
|
8de298d245 | ||
|
|
75fc8d09ce | ||
|
|
b157b9fe28 | ||
|
|
53a800d252 | ||
|
|
124868e093 | ||
|
|
e684936d15 | ||
|
|
5958fd5c6f | ||
|
|
4d7ee39ccf | ||
|
|
1bb91518b6 | ||
|
|
2d0123cb18 | ||
|
|
455bc19fab | ||
|
|
0003be478e | ||
|
|
d448f11861 | ||
|
|
53924dc8ef | ||
|
|
9311b898f2 | ||
|
|
0e30a26db4 | ||
|
|
24a460e64a | ||
|
|
f62320f3e1 | ||
|
|
0d73e8b52a | ||
|
|
11d66da064 | ||
|
|
f24fecf01c | ||
|
|
1c16444614 | ||
|
|
8b7b1236ba | ||
|
|
c44bf06cc9 | ||
|
|
8230d59354 | ||
|
|
0f270c8823 | ||
|
|
95970f87fa | ||
|
|
469c1693bd | ||
|
|
2a45a8a8fa | ||
|
|
2180fa70f7 | ||
|
|
b093e11aeb | ||
|
|
140812606f | ||
|
|
14239b8a6f | ||
|
|
0d1dca3e0a | ||
|
|
dfee0934f0 | ||
|
|
42c332a406 | ||
|
|
4c1ebc84e9 | ||
|
|
81a6e5d152 | ||
|
|
145a43d688 | ||
|
|
386c5fa86c | ||
|
|
1499edd83c | ||
|
|
db719c32ad | ||
|
|
340477a31f | ||
|
|
fd57047e86 | ||
|
|
496b9f981e | ||
|
|
76dc2312b4 | ||
|
|
ade6d80f10 | ||
|
|
574b41a0a1 | ||
|
|
f907a340b6 | ||
|
|
0498b39f0e | ||
|
|
5d196ff8d8 | ||
|
|
84d65fb167 | ||
|
|
0f22d53e7c | ||
|
|
f44bc72201 | ||
|
|
310d550ff6 | ||
|
|
044292ccb4 | ||
|
|
0dc0f9ea73 | ||
|
|
5fcdf888b3 | ||
|
|
dda98e2a61 | ||
|
|
f209cb1e0e | ||
|
|
7d3df10915 | ||
|
|
fb9f127289 | ||
|
|
bc64084516 | ||
|
|
e86d385521 | ||
|
|
6ca0fa7626 | ||
|
|
f8d8b04de3 | ||
|
|
305a75d1a7 | ||
|
|
c3a9e9d402 | ||
|
|
48c941fb86 | ||
|
|
1016853d25 | ||
|
|
90068a3c2d | ||
|
|
8fc71a2e36 | ||
|
|
8310e43b31 | ||
|
|
0e30b62894 | ||
|
|
3de21f295b | ||
|
|
d8c4de9a01 | ||
|
|
acf366d61e | ||
|
|
b9c85fad7b | ||
|
|
196b9555ab | ||
|
|
e9cccd58ea | ||
|
|
00d30efa45 | ||
|
|
309b9665cb | ||
|
|
759abc92c9 | ||
|
|
ae8f0e2236 | ||
|
|
815770fabf | ||
|
|
e82069dea2 | ||
|
|
396aee7d0a | ||
|
|
3299c202b0 | ||
|
|
755cbe113d | ||
|
|
bab729ed18 | ||
|
|
350dbdfe4b | ||
|
|
1b5ca8eef6 | ||
|
|
e8016c1d51 | ||
|
|
c1e2bed94e | ||
|
|
ba242be427 | ||
|
|
fce974c146 | ||
|
|
a82aa792d8 | ||
|
|
105f77d9ec | ||
|
|
b6d87b9799 | ||
|
|
6279086b5a | ||
|
|
61ea4bd385 | ||
|
|
7f3e039d1b | ||
|
|
f2c91c09c7 | ||
|
|
32c81f220d | ||
|
|
c77981cc0c | ||
|
|
cd767d16df | ||
|
|
8591aecb9c | ||
|
|
34746afea3 | ||
|
|
393328eaf6 | ||
|
|
7771d1f326 | ||
|
|
2a34eb55e6 | ||
|
|
9d6cf49c3f | ||
|
|
dcb87d0d89 | ||
|
|
9a0c77bb8b | ||
|
|
6e45e6b135 | ||
|
|
a1df6376ec | ||
|
|
7f7e31bae9 | ||
|
|
4499f9ed44 | ||
|
|
9a5ad1dff2 | ||
|
|
2f8f77cb89 | ||
|
|
a4978d93d6 | ||
|
|
01e28f10ae | ||
|
|
ea9068fd0d | ||
|
|
d85823abcf | ||
|
|
4c0027ffd3 | ||
|
|
afb868af30 | ||
|
|
66b1d5dc30 | ||
|
|
7d8cdc74c6 | ||
|
|
809581df49 | ||
|
|
5d47a8d48d | ||
|
|
6242f1931e | ||
|
|
b768219c18 | ||
|
|
6935923bd1 | ||
|
|
559e6e2556 | ||
|
|
f354fdfbf4 | ||
|
|
f242b5a378 | ||
|
|
e18ec2219d | ||
|
|
d075ae58d9 | ||
|
|
e8ccac8e61 | ||
|
|
7c8f9f3cd8 | ||
|
|
66e434db24 | ||
|
|
0be553c4c8 | ||
|
|
1dda0f29be | ||
|
|
fbdedc7d8a | ||
|
|
e325352309 | ||
|
|
bf51b50346 | ||
|
|
96b52f3ac0 | ||
|
|
ad44db254b | ||
|
|
736b89d7d1 | ||
|
|
3122531cae | ||
|
|
cbb47ab735 | ||
|
|
fa8d4fd5ca | ||
|
|
423d05a087 | ||
|
|
7036e94dab | ||
|
|
3a19180a51 | ||
|
|
f8f8920fc5 | ||
|
|
507b53c10e | ||
|
|
6aafb78680 | ||
|
|
c83dc5565c | ||
|
|
59a03cacef | ||
|
|
c6af287b11 | ||
|
|
bc636bd9fd | ||
|
|
1f2b6c5d44 | ||
|
|
b42ffe8e0b | ||
|
|
f9244b36df | ||
|
|
87f697622c | ||
|
|
52dbc0fe40 | ||
|
|
4a69bdcd12 | ||
|
|
e9e47d797c | ||
|
|
66cdb5e376 | ||
|
|
c7575393c9 | ||
|
|
3b9005e9a8 | ||
|
|
e3fd5876d2 | ||
|
|
f71c2d3f8d | ||
|
|
7163854185 | ||
|
|
8037081e0c | ||
|
|
642a00051e | ||
|
|
7f9bd1c457 | ||
|
|
477f7dfa03 | ||
|
|
d45aaf6cb2 | ||
|
|
4650da8373 | ||
|
|
13128a8a90 | ||
|
|
23b19015f4 | ||
|
|
843a1f97ce | ||
|
|
43d6002542 | ||
|
|
f9d9677bc0 | ||
|
|
49220d8024 | ||
|
|
013d76b006 | ||
|
|
c7d3755149 | ||
|
|
8d67ecd6a0 | ||
|
|
6005bb1b8d | ||
|
|
c4e8d19649 | ||
|
|
82be18c469 | ||
|
|
e6565fbe4b | ||
|
|
087dbaded9 | ||
|
|
6c42c57e59 | ||
|
|
3286cc2f85 | ||
|
|
d098a5ef09 | ||
|
|
040335ace0 | ||
|
|
dbc74834cd | ||
|
|
f1b411e3b6 | ||
|
|
7a9f5f9e6e | ||
|
|
cffa9a97f3 | ||
|
|
1bf986d41b | ||
|
|
eb343b0d31 | ||
|
|
628cb3b8c9 | ||
|
|
ebd391ec26 | ||
|
|
a3b577e563 | ||
|
|
f60adcc797 | ||
|
|
ee77f7bed1 | ||
|
|
6ef83cb22f | ||
|
|
1a3fd15fdf | ||
|
|
3e5a46570c | ||
|
|
2c4fbf7179 | ||
|
|
5409fb783c | ||
|
|
4cec610aba | ||
|
|
57d88d7889 | ||
|
|
7f305ae3cf | ||
|
|
eb4ac33fcd | ||
|
|
7a3c6c1690 | ||
|
|
ca63609545 | ||
|
|
bcaa8896ee | ||
|
|
13b19e3889 | ||
|
|
99d1fc0a64 | ||
|
|
86b7d676dd | ||
|
|
1adf6edffc | ||
|
|
a16af99648 | ||
|
|
9fdcb428c0 | ||
|
|
cee9bbb079 | ||
|
|
fcc09e2ef0 | ||
|
|
5d96a8060f | ||
|
|
023fb4b68b |
13
.dockerignore
Normal file
13
.dockerignore
Normal 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
|
||||
68
.github/workflows/issue-tracker.yml
vendored
Normal file
68
.github/workflows/issue-tracker.yml
vendored
Normal 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
|
||||
302
CHANGELOG.md
302
CHANGELOG.md
@@ -1,3 +1,299 @@
|
||||
## 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
|
||||
|
||||
* Added an EDID editor in the terminal with a built-in 1080P EDID template
|
||||
* Added German virtual keyboard and German clipboard support (thanks to [@Alexander-Ger-Reich](https://github.com/Alexander-Ger-Reich))
|
||||
* Resetting the HID also resets the USB hardware
|
||||
* Added support for deleting ISO images
|
||||
|
||||
### Refactoring & Improvements
|
||||
|
||||
* Video (H.264 WebRTC): Refactored the module to significantly reduce video latency
|
||||
* Video (H.264 Direct): Refactored to optimize data transmission and support data parsing even when the page is in the background
|
||||
* Video (MJPEG): Refactored and ensure correct data length transmission
|
||||
* Added locking before resetting USB to prevent HID deadlock (thanks to [@scpcom](https://github.com/scpcom))
|
||||
* Optimized HID writing logic
|
||||
* Made HDMI toggle state persist across reboots (thanks to [@tpretz](https://github.com/tpretz))
|
||||
* Enhanced the paste feature with browser clipboard API integration (thanks to [@patrickpilon](https://github.com/patrickpilon))
|
||||
* Set the inquiry string for the virtual storage device (thanks to [@scpcom](https://github.com/scpcom))
|
||||
* Hostname now updates `/etc/hosts` simultaneously and takes effect immediately (thanks to [@scpcom](https://github.com/scpcom))
|
||||
* Improved compatibility for static IP configuration on Windows
|
||||
* Optimized the web page title update logic
|
||||
* Added a confirmation dialog when uninstalling Tailscale
|
||||
* Improved UI for Clipboard, Image Mounting, and settings pages
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* Tailscale: Fixed an issue where Tailscale would turn the device into a router
|
||||
* Tailscale: Fixed an issue where Tailscale would disable IPv6
|
||||
* Tailscale: Added a swap memory option to prevent Tailscale Out-Of-Memory errors
|
||||
* Tailscale: Fixed Tailscale accept-dns configuration (thanks to [@lazydba247](https://github.com/lazydba247))
|
||||
* Fixed an issue where certain modifier keys were not recognized
|
||||
* Fixed vertical mouse drift when the page is zoomed in or out
|
||||
|
||||
### Localization
|
||||
|
||||
* Update Korean translation (thanks to [@xenix4845](https://github.com/xenix4845))
|
||||
* Update Traditional Chinese translation (thanks to [@protonchang](https://github.com/protonchang))
|
||||
* Add Brazilian Portuguese translation (thanks to [@chiconws](https://github.com/chiconws) and [@Luccas-LF](https://github.com/Luccas-LF))
|
||||
* Add Swedish translation (thanks to [@acidflash](https://github.com/acidflash))
|
||||
* Add Catalan translation (thanks to [@Zagur](https://github.com/Zagur))
|
||||
* Add Turkish translation (thanks to [@Keylem](https://github.com/Keylem))
|
||||
|
||||
### Security
|
||||
|
||||
* Implemented a delay after failed login attempts to mitigate brute-force attacks
|
||||
* Upgraded dependencies to fix known security vulnerabilities
|
||||
|
||||
## 2.2.9 [c77981c](https://github.com/sipeed/NanoKVM/commit/c77981cc0ceebd8f6705b6c5d8c3cf4edf4f6717) (2025-06-13)
|
||||
|
||||
* fix(security): resolve parameter injection in serial port terminal
|
||||
|
||||
## 2.2.8 [01e28f1](https://github.com/sipeed/NanoKVM/commit/01e28f10ae8b581d484bb6077ddfe7bbe4e57919) (2025-05-22)
|
||||
|
||||
* feat: add AZERTY virtual keyboard Layout (thanks to [@felix068](https://github.com/felix068))
|
||||
* feat: add support for enabling/disabling HDMI output (PCIe version only) (thanks to [@tpretz](https://github.com/tpretz))
|
||||
* feat: add support for custom mouse wheel speed
|
||||
* fix: prevent direct H.264 stream buffer overflow and replay issues
|
||||
* perf: improve keyboard paste performance (thanks to [@ethanperrine](https://github.com/ethanperrine))
|
||||
* Localization
|
||||
* update Korean translation (thanks to [@kmw0410](https://github.com/kmw0410))
|
||||
* update Ukrainian translation (thanks to [@arbdevml](https://github.com/arbdevml))
|
||||
* update Russian translation (thanks to [@arbdevml](https://github.com/arbdevml))
|
||||
|
||||
## 2.2.7 [e18ec22](https://github.com/sipeed/NanoKVM/commit/e18ec2219d22886529575d1fdaad5c320e05f5b2) (2025-05-08)
|
||||
|
||||
* feat: add HTTPS support
|
||||
* feat: support direct H.264 streaming over HTTP
|
||||
* Localization
|
||||
* update Russian translation (thanks to [polyzium](https://github.com/polyzium))
|
||||
* update Dutch translation (thanks to [LeonStraathof](https://github.com/LeonStraathof))
|
||||
* update Ukrainian translation (thanks to [click0](https://github.com/click0))
|
||||
* update German translation (thanks to [3limin4tor](https://github.com/3limin4tor))
|
||||
|
||||
## 2.2.6 [c83dc55](https://github.com/sipeed/NanoKVM/commit/c83dc5565c9dbed22336661a8832edbd93a06d11) (2025-04-17)
|
||||
|
||||
* feat: add mouse jiggler to prevent system sleep
|
||||
* feat: add support for swap memory
|
||||
* feat: add support for customizing the device hostname
|
||||
* feat: add support for customizing the web page title
|
||||
* feat: add support for assigning custom names to Wake-on-LAN MAC addresses
|
||||
* feat: add confirmation prompts for power operations
|
||||
* feat: add logo to the login page (thanks to [S33G](https://github.com/S33G))
|
||||
* fix: fix possible privacy issues with MIC drivers. [Repair Record](https://github.com/sipeed/NanoKVM/commit/f9244b36df090a05cd59ba11ea4fd01e9b638995)
|
||||
* fix: fix iptables rule that could interfere with SSH connections (thanks to [scpcom](https://github.com/scpcom))
|
||||
* fix: fix the static IP gateway configuration might not apply correctly (thanks to [xitation](https://github.com/xitation))
|
||||
* perf: optimized OLED display handling and sleep logic
|
||||
* perf: improve H.264 streaming reliability by adding a heartbeat mechanism
|
||||
* perf: set the minimum screen size to 640x480
|
||||
* perf: add display of both wired and wireless IPv4 addresses in the settings page
|
||||
* perf: update the Thai language translations (thanks to [ChokunPlayZ](https://github.com/ChokunPlayZ))
|
||||
* chore: bump axios to 1.8.4
|
||||
* chore: bump golang.org/x/net to v0.39.0
|
||||
* chore: bump github.com/golang-jwt/jwt/v5 to to v5.2.2
|
||||
|
||||
## 2.2.5 [3286cc2](https://github.com/sipeed/NanoKVM/commit/3286cc2f85a14133d65935cb476c833dcf151459) (2025-03-26)
|
||||
|
||||
* fix: server crash caused by MJPEG frame detection error
|
||||
* feat: add HID-Only mode
|
||||
* feat: support preview updates
|
||||
* perf: improve image reading performance by optimizing screen parameters
|
||||
|
||||
## 2.2.4 [1bf986d](https://github.com/sipeed/NanoKVM/commit/1bf986d41b34d568c1ffee5df90ce61b6b08456b) (2025-03-21)
|
||||
|
||||
* fix: resolve USB initialization issue
|
||||
* fix: correct abnormal updates in certain models
|
||||
* perf: add version restrictions for production testing
|
||||
|
||||
## 2.2.3 [6ef83cb](https://github.com/sipeed/NanoKVM/commit/6ef83cb22fcd77f721d32c97c85d12f2bfc3035a) (2025-03-21)
|
||||
|
||||
* feat: add support for setting H.264 GOP
|
||||
* fix: resolve deadlock caused by HDMI resolution errors
|
||||
* perf: merge H.264 SPS and PPS into I-frame
|
||||
* perf: refactor MJPEG frame detection
|
||||
* perf: added more configuration options to the serial port terminal (thanks to [@mekaris](https://github.com/mekaris))
|
||||
* perf: improve the `update-nanokvm.py` script (thanks to [@reishoku](https://github.com/reishoku))
|
||||
* perf: disable mDNS by default in new products
|
||||
* perf: update log timestamp to millisecond precision
|
||||
* chore: bump Go to 1.23
|
||||
* chore: bump `golang.org/x/net` to v0.37.0
|
||||
|
||||
## 2.2.2 [58d5ab2](https://github.com/sipeed/NanoKVM/commit/58d5ab2d37244b1e1a68b925a5c23c324c489ad3) (2025-03-11)
|
||||
|
||||
* feat: add watchdog for NanoKVM-Server
|
||||
* feat: add support for UE chip
|
||||
* feat: support system reboot
|
||||
* feat: support enable/disable mDNS
|
||||
* fix: resolve UE chip cannot start server
|
||||
* perf: refactor automatic resolution detection
|
||||
* perf: add output prompt for unsupported resolutions
|
||||
* perf: add lock to kvmv_read_img
|
||||
* perf: configurable VENC automatic recycling feature
|
||||
* perf: add maximum limit for vi
|
||||
* perf: add tooltips to menu bar (thanks to [@S33G](https://github.com/S33G))
|
||||
* perf: menu bar is now draggable (thanks to [@forumi0721](https://github.com/forumi0721))
|
||||
* perf: image list support auto-refresh (thanks to [@forumi0721](https://github.com/forumi0721))
|
||||
* perf: update translations
|
||||
|
||||
## 2.2.1 [b5e48a0](https://github.com/sipeed/NanoKVM/commit/b5e48a07e82df3aedd60442342ae50b95684a697) (2025-02-21)
|
||||
|
||||
* fix: mounted image were not being detected correctly
|
||||
@@ -30,9 +326,9 @@ NanoKVM [Image v1.4.0](https://github.com/sipeed/NanoKVM/releases/tag/v1.4.0) ha
|
||||
* perf: download Tailscale installation package from the official source
|
||||
* perf: automatic enable/disable GOMEMLIMIT on tailscale start/stop
|
||||
* perf: add JWT configuration
|
||||
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
|
||||
* refreshTokenDuration: customize token expiration time
|
||||
* revokeTokensOnLogout: invalidate all JWT tokens on logout
|
||||
* secretKey: customize secret key. If empty, generated a random 64-byte secret key by default
|
||||
* refreshTokenDuration: customize token expiration time
|
||||
* revokeTokensOnLogout: invalidate all JWT tokens on logout
|
||||
* perf: implement secure password storage using bcrypt hashing
|
||||
* perf: implement integrity checks for online updates
|
||||
* refactor: refactor HDMI module and remove the dependency `libmaixcam_lib.so`
|
||||
|
||||
97
Makefile
Normal file
97
Makefile
Normal file
@@ -0,0 +1,97 @@
|
||||
# Makefile for NanoKVM Project
|
||||
|
||||
# Configuration
|
||||
IMAGE_NAME := nanokvm-builder
|
||||
UID := $(shell id -u)
|
||||
GID := $(shell id -g)
|
||||
PWD := $(shell pwd)
|
||||
|
||||
# Docker run common parameters
|
||||
DOCKER_RUN_BASE := docker run -e UID=$(UID) -e GID=$(GID) -v $(PWD):/home/build/NanoKVM --rm
|
||||
|
||||
# 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
|
||||
|
||||
.PHONY: help check-root builder-image rebuild-image check-image shell app support 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 hardware support libraries"
|
||||
@echo " all - Build both app and support (default)"
|
||||
@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 -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 -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) -it $(IMAGE_NAME) /bin/bash -c '$(GO_BUILD_CMD)'
|
||||
|
||||
# Build hardware support libraries
|
||||
support: check-root builder-image
|
||||
@echo "Building support..."
|
||||
@$(DOCKER_RUN_BASE) -it $(IMAGE_NAME) /bin/bash -c '$(SUPPORT_BUILD_CMD)'
|
||||
|
||||
# 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
|
||||
@echo "Clean completed."
|
||||
234
README.md
234
README.md
@@ -1,151 +1,147 @@
|
||||
NanoKVM
|
||||
======
|
||||
# NanoKVM
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
|
||||
<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 </a>
|
||||
</h3>
|
||||
|
||||
English | [中文](./README_ZH.md) | [日本語](./README_JA.md)
|
||||
|
||||
<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>
|
||||
<br>
|
||||
</div>
|
||||
|
||||
> Your NanoKVM is powered by [RISC-V](https://en.wikipedia.org/wiki/RISC-V)!
|
||||
> If you have any issues or suggestions, creating issue here, or tell us with [MaixHub Discussion](https://maixhub.com/discussion/nanokvm).
|
||||
## 🌟 What is NanoKVM?
|
||||
|
||||
## Opensource & Contribution
|
||||
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.
|
||||
|
||||
### 2025.03.04 Update Content
|
||||
+ Updated directory structure
|
||||
## 📦 Product Family
|
||||
|
||||
``` shell
|
||||
Choose the NanoKVM model that best fits your deployment:
|
||||
|
||||
- **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">
|
||||
<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
|
||||
|
||||
| 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 | — | — | — |
|
||||
| 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 | ✓ | ✓ | ✓ | — |
|
||||
| Wake-on-LAN | ✓ | ✓ | ✓ | ✓ |
|
||||
| Web Terminal | ✓ | ✓ | ✓ | ✓ |
|
||||
| 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 | — | — |
|
||||
| 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.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 |
|
||||
|
||||
## 📂 Project Structure
|
||||
|
||||
```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
|
||||
├── server # NanoKVM back-end
|
||||
├── support # Auxiliary functions (image subsystem, system status, system updates, screen, keys, etc.)
|
||||
│ ├── sg2002 # NanoKVM-Lite/Full/PCIe
|
||||
│ └── h618 # NanoKVM-Pro
|
||||
├── web # NanoKVM front-end
|
||||
├── LICENSE
|
||||
├── README_JA.md
|
||||
├── README.md
|
||||
├── README_ZH.md
|
||||
└── CHANGELOG.md
|
||||
│ ├── 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.)
|
||||
├── ...
|
||||
```
|
||||
|
||||
+ Add NanoKVM app installation package `kvmapp`
|
||||
+ Add compilation scripts and compilation instructions
|
||||
## 💻 Development
|
||||
|
||||
### Update 2025.02.19
|
||||
All components of NanoKVM were open-sourced, including the [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), the [kvmapp update package](https://github.com/sipeed/NanoKVM-System/tree/main/kvmapp), [system sdk](https://github.com/sipeed/LicheeRV-Nano-Build/tree/NanoKVM), and [packaging methods](https://github.com/sipeed/LicheeRV-Nano-Build/blob/NanoKVM/kvm/NanoKVM_img.sh).
|
||||
Start with the guide that matches the part of NanoKVM you want to work on:
|
||||
|
||||
### Update 2025.02.14
|
||||
Newest APP v2.1.6 add most security enhancements&bug fix, recommend regular users upgrade to this version or newer.
|
||||
- **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).
|
||||
|
||||
### Update 2025.02.05
|
||||
For users concerned about security, you can read this issue: https://github.com/sipeed/NanoKVM/issues/301 , you will find explanations addressing all security concerns.
|
||||
GitHub, as an open and transparent platform, provides a space for discussing so-called "backdoor" concerns. Open-source makes products more secure!
|
||||
> Backend compilation and runtime validation require the target toolchain or a NanoKVM device. See the module-specific guides above for the latest development workflow.
|
||||
|
||||
### Update 2024.10.18
|
||||
## 🔩 Hardware Platform (NanoKVM Cube/PCIe)
|
||||
|
||||
We have open-sourced the backend code in 10.8, and thank you for civil PR it immediately, we will give you newest NanoKVM-PCIe as a reward!
|
||||
The mid-Oct batch is starting testing and packaging, most orders before 10.1 will ship out next and next next week.
|
||||
The aliexpress shipping date is change to Dec since 10.1, it is a conservative delivery time. the order in Oct. should send out during 11.15~12.15.
|
||||
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).
|
||||
|
||||
## Introduction
|
||||
The NanoKVM Cube/PCIe hardware is built from these components:
|
||||
|
||||
Lichee NanoKVM is an IP-KVM product based on LicheeRV Nano, inheriting the extreme size and powerful features of LicheeRV Nano.
|
||||
The Lichee NanoKVM is available in two versions:
|
||||
NanoKVM Lite is a basic configuration that is suitable for individual users with certain DIY capabilities and enterprise users with bulk requirements.
|
||||
The NanoKVM Full is a full version with a sophisticated case and complete accessories, as well as a built-in system mirror card that is ready to use at boot, and is recommended for individual users.
|
||||
- **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.
|
||||
|
||||

|
||||
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.
|
||||
|
||||
## Tech Specs
|
||||
> Note: Of the 256MB memory on SG2002, 158MB is currently allocated to the multimedia subsystem for video capture and processing.
|
||||
|
||||
| Products | NanoKVM (Lite) | NanoKVM (Full) | PiKVM V4 |
|
||||
|------------------- |-------------------------------------- |---------------------------------- |----------------------------------- |
|
||||
| Compute Units | LicheeRV Nano(RISCV) | LicheeRV Nano(RISCV) | CM4 (ARM) |
|
||||
| Resolution | 1080P @ 60fps | 1080P @ 60fps | 1080P @ 60fps |
|
||||
| Video encoding | MJPEG, H264 | MJPEG, H264 | MJPEG, H264 |
|
||||
| Video delay | 90~230ms | 90~230ms | 100~230ms |
|
||||
| UEFI/BIOS | ✓ | ✓ | ✓ |
|
||||
| Virtual HID | ✓ | ✓ | ✓ |
|
||||
| Virtual CD-ROM | ✓ | ✓ | ✓ |
|
||||
| IPMI | ✓ | ✓ | ✓ |
|
||||
| Wake-on-LAN | ✓ | ✓ | ✓ |
|
||||
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
|
||||
| ATX power control | None,Users can connect by their own | USB interface IO control board | RJ-45 interface IO control board |
|
||||
| OLED | None,Users can connect by their own | 128x64 0.96" white | 128x32 0.91" white |
|
||||
| UART | 2 | 2 | 1 |
|
||||
| TF Card | None | ✓ | ✓ |
|
||||
| Expansion | None | PoE | WiFi/LTE |
|
||||
| Power consumption | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
|
||||
| Power input | PC USB can be powered | PC USB or auxiliary power supply | DC 5V 3A power supply is required |
|
||||
| Cooling | Silent fanless | Silent fanless | Fan cooling |
|
||||
| Size | 23x37x15mm ~1/30 PiKVM V4 size | 40x36x36mm ~1/7 PiKVM V4 size | 120x68x44mm |
|
||||
- [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>
|
||||
|
||||
## Hardware platform NanoKVM
|
||||
## 🤝 Contributing
|
||||
|
||||
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).
|
||||
We welcome contributions. To get started:
|
||||
|
||||
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.
|
||||
1. Fork the repository.
|
||||
2. Create a feature branch.
|
||||
3. Commit your changes.
|
||||
4. Push to the branch.
|
||||
5. Open a Pull Request.
|
||||
|
||||
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.
|
||||
Please keep your pull requests small and focused to facilitate easier review and merging.
|
||||
|
||||
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.
|
||||
> 🎁 **Contributors who submit high-quality Pull Requests may receive a NanoKVM Cube, PCIe, or Pro as a token of our appreciation!**
|
||||
|
||||
+ [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_HDMI_MIPI_31011.pdf)
|
||||
+ [NanoKVM img](https://github.com/sipeed/NanoKVM/releases/tag/NanoKVM)
|
||||
## 🛒 Where to Buy
|
||||
|
||||
## Roadmap
|
||||
- [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)
|
||||
|
||||
### Q1 2025
|
||||
## 💬 Community & Support
|
||||
|
||||
**Enhancements:**
|
||||
- [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)
|
||||
|
||||
- [x] Refactor the HDMI module and remove the libmaixcam_lib.so dependency
|
||||
- [x] Disable SSH by default and add an enable/disable toggle in the web UI
|
||||
- [x] Disable Tailscale by default and add an enable/disable toggle in the web UI
|
||||
- [x] Add JWT configuration options to the configuration file
|
||||
- [x] Secure password storage with bcrypt
|
||||
## 📜 License
|
||||
|
||||
**Distribution:**
|
||||
|
||||
- [x] Distribute applications via GitHub
|
||||
- [x] Implement integrity checks for online updates
|
||||
- [ ] Support offline updates
|
||||
|
||||
**Bug Fixes:**
|
||||
|
||||
- [x] Fix the DNS issue
|
||||
- [x] Fix the CSRF vulnerability
|
||||
|
||||
**Features**
|
||||
|
||||
- [ ] [79](https://github.com/sipeed/NanoKVM/issues/79) Support Zerotier
|
||||
- [ ] [99](https://github.com/sipeed/NanoKVM/issues/99) Support WireGuard
|
||||
- [ ] [249](https://github.com/sipeed/NanoKVM/issues/249) Add Mouse Jiggler
|
||||
|
||||
## Where to buy
|
||||
|
||||
* [Aliexpress(global except USA&Russia)](https://www.aliexpress.com/item/1005007369816019.html)
|
||||
* [淘宝](https://item.taobao.com/item.htm?id=811206560480)
|
||||
* [Preorder (anyother country that not support in Aliexpress or Taobao)](https://sipeed.com/nanokvm)
|
||||
|
||||
## Community
|
||||
|
||||
* [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)
|
||||
* QQ group: 703230713
|
||||
This project is licensed under the GPL-3.0 License. See [LICENSE](LICENSE) for details.
|
||||
|
||||
129
README_JA.md
129
README_JA.md
@@ -1,129 +0,0 @@
|
||||
NanoKVM
|
||||
======
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
|
||||
<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) | 日本語
|
||||
|
||||
</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 (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 ハードウェアプラットフォーム
|
||||
|
||||
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
|
||||
122
README_ZH.md
122
README_ZH.md
@@ -1,122 +0,0 @@
|
||||
NanoKVM
|
||||
======
|
||||
|
||||
<div align="center">
|
||||
|
||||

|
||||
|
||||
<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 </a>
|
||||
</h3>
|
||||
|
||||
[English](./README.md) | 中文 | [日本語](./README_JA.md)
|
||||
|
||||
</div>
|
||||
|
||||
> Your NanoKVM Power by RISC-V !
|
||||
> 如果您在使用过程中有任何问题或建议,请在这里提交 issue, 或在 [MaixHub Discussion](https://maixhub.com/discussion/nanokvm)告诉我们.
|
||||
|
||||
## 开源与贡献
|
||||
|
||||
### 2025.03.04 更新内容
|
||||
+ 更新目录结构
|
||||
|
||||
``` 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 app安装包`kvmapp`
|
||||
+ 添加编译脚本和编译说明
|
||||
|
||||
### 2025.02.19 更新内容
|
||||
所有 NanoKVM 组件已开源,包括
|
||||
[前端](https://github.com/sipeed/NanoKVM/tree/main/web)、[后端](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 更新包](https://github.com/sipeed/NanoKVM-System/tree/main/kvmapp)、[系统 SDK](https://github.com/sipeed/LicheeRV-Nano-Build/tree/NanoKVM) 和 [固件打包方法](https://github.com/sipeed/LicheeRV-Nano-Build/blob/NanoKVM/kvm/NanoKVM_img.sh)。
|
||||
|
||||
### 2025.02.14 更新内容
|
||||
最新的 APP v2.1.6 添加了大多数安全增强和 bug 修复,建议普通用户升级到此版本或更新版本。
|
||||
|
||||
### 2025.02.05 更新内容
|
||||
对于关注安全的用户,可以阅读此问题:https://github.com/sipeed/NanoKVM/issues/301,您会找到有关所有安全问题的解释。GitHub 作为一个开放和透明的平台,为讨论所谓的“后门”担忧提供了空间。开源使产品更加安全!
|
||||
|
||||
### 2024.10.18 更新内容
|
||||
我们在 10.8 中开源了后端代码,感谢您立即提交的文明 PR,我们将赠送您最新的 NanoKVM-PCIe 作为奖励!
|
||||
十月中旬的批次正在开始测试和打包,大多数在 10.1 之前的订单将在下周和下下周发货。
|
||||
自 10.1 起,AliExpress 的发货日期已更改为 12 月,这是一个保守的交货时间。十月的订单应在 11.15~12.15 期间发出。
|
||||
|
||||
## 简介
|
||||
|
||||
Lichee NanoKVM 是基于 LicheeRV Nano 的 IP-KVM 产品,继承了 LicheeRV Nano的极致体积 和 强大功能。
|
||||
Lichee NanoKVM分为两个版本:
|
||||
NanoKVM Lite 为基础版配置,适合 具有一定DIY能力的个人用户 和 有批量需求的企业用户。
|
||||
NanoKVM Full 为完整版配置,带精致外壳和完整配件,内置开机即用的系统镜像卡,推荐个人用户购买。
|
||||
|
||||

|
||||
|
||||
## 参数
|
||||
|
||||
| 产品 | 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 | ✓ | ✓ | ✓ |
|
||||
| 模拟USB键鼠 | ✓ | ✓ | ✓ |
|
||||
| 模拟USB存储 | ✓ | ✓ | ✓ |
|
||||
| IPMI | ✓ | ✓ | ✓ |
|
||||
| Wake-on-LAN | ✓ | ✓ | ✓ |
|
||||
| ETH | 100M/10M | 100M/10M | 1000M/100M/10M |
|
||||
| ATX电源控制 | 无,用户可自行连接 | USB接口IO控制板 | RJ45接口IO控制板 |
|
||||
| OLED显示 | 无,用户可自行扩展 | 128x64 0.96" white | 128x32 0.91" white |
|
||||
| 外接串口 | 2路 | 2路 | 1路 |
|
||||
| TF卡 | 无,用户自备 | 有,开机即用 | 有 |
|
||||
| 扩展配件 | 无 | PoE | WiFi/LTE |
|
||||
| 功耗 | 0.2A@5V | 0.2A@5V | Peak 2.6A@5V |
|
||||
| 电源输入 | PC USB即可供电 | PC USB即可供电 <br> 也支持额外辅助供电 | 需要DC 5V 3A供电 |
|
||||
| 散热 | 静音无风扇 | 静音无风扇 | 需要风扇主动散热 |
|
||||
| 尺寸 | 23x37x15mm <br> ~1/30 PiKVM V4 体积 | 40x36x36mm <br/> ~1/7 PiKVM V4 体积 | 120x68x44mm |
|
||||
|
||||

|
||||
|
||||
## 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 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)
|
||||
|
||||
|
||||
## 购买渠道
|
||||
|
||||
* [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
|
||||
79
docker/Dockerfile
Normal file
79
docker/Dockerfile
Normal file
@@ -0,0 +1,79 @@
|
||||
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 -y
|
||||
|
||||
ARG DOCKER_USER=build
|
||||
RUN useradd -m "$DOCKER_USER"
|
||||
USER $DOCKER_USER
|
||||
|
||||
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
|
||||
|
||||
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_USER . /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_USER --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 --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"]
|
||||
22
docker/entrypoint
Normal file
22
docker/entrypoint
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/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
|
||||
usermod -u "$UID" "$DOCKER_USER" 2>/dev/null && {
|
||||
groupmod -g "$GID" "$DOCKER_USER" 2>/dev/null ||
|
||||
usermod -a -G "$GID" "$DOCKER_USER"
|
||||
}
|
||||
set -- gosu "${UID}:${GID}" "${@}"
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
45
kvmapp/picoclaw/AGENT.md
Normal file
45
kvmapp/picoclaw/AGENT.md
Normal 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.
|
||||
46
kvmapp/picoclaw/AGENT_KVM.md
Normal file
46
kvmapp/picoclaw/AGENT_KVM.md
Normal 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.
|
||||
94
kvmapp/picoclaw/skills/kvm-control/SKILL.md
Normal file
94
kvmapp/picoclaw/skills/kvm-control/SKILL.md
Normal 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.
|
||||
1123
kvmapp/picoclaw/skills/kvm-control/scripts/nanokvm-bridge.sh
Executable file
1123
kvmapp/picoclaw/skills/kvm-control/scripts/nanokvm-bridge.sh
Executable file
File diff suppressed because it is too large
Load Diff
32
kvmapp/system/init.d/S00kmod
Executable file
32
kvmapp/system/init.d/S00kmod
Executable file
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
|
||||
if [ "$1" = "start" ]
|
||||
then
|
||||
. /etc/profile
|
||||
printf "load kernel module: "
|
||||
cd /mnt/system/ko/
|
||||
insmod soph_sys.ko
|
||||
insmod soph_base.ko
|
||||
insmod soph_rtos_cmdqu.ko
|
||||
insmod soph_fast_image.ko
|
||||
insmod soph_mipi_rx.ko
|
||||
insmod soph_snsr_i2c.ko
|
||||
insmod soph_vi.ko
|
||||
insmod soph_vpss.ko
|
||||
insmod soph_dwa.ko
|
||||
insmod soph_vo.ko
|
||||
insmod soph_rgn.ko
|
||||
insmod soph_wdt.ko
|
||||
insmod soph_clock_cooling.ko
|
||||
insmod soph_tpu.ko
|
||||
insmod soph_vcodec.ko
|
||||
insmod soph_jpeg.ko
|
||||
insmod soph_vc_driver.ko MaxVencChnNum=9 MaxVdecChnNum=9
|
||||
insmod soph_rtc.ko
|
||||
insmod soph_ive.ko
|
||||
insmod soph_mon.ko
|
||||
insmod soph_pwm.ko
|
||||
insmod soph_wiegand.ko
|
||||
echo "OK"
|
||||
exit 0
|
||||
fi
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# kvmhwd Rev2.0
|
||||
# kvmhwd Rev2.1
|
||||
|
||||
start_usb_dev(){
|
||||
. /etc/profile
|
||||
@@ -9,8 +9,20 @@ start_usb_dev(){
|
||||
mkdir g0
|
||||
cd g0
|
||||
|
||||
echo 0x3346 > idVendor
|
||||
echo 0x1009 > idProduct
|
||||
# echo 0x3346 > idVendor
|
||||
# echo 0x1009 > idProduct
|
||||
if [ -e /boot/usb.vid ]
|
||||
then
|
||||
cat /boot/usb.vid > idVendor
|
||||
else
|
||||
echo 0x3346 > idVendor
|
||||
fi
|
||||
if [ -e /boot/usb.pid ]
|
||||
then
|
||||
cat /boot/usb.pid > idProduct
|
||||
else
|
||||
echo 0x1009 > idProduct
|
||||
fi
|
||||
mkdir strings/0x409
|
||||
echo '0123456789ABCDEF' > strings/0x409/serialnumber
|
||||
echo 'sipeed' > strings/0x409/manufacturer
|
||||
@@ -47,8 +59,8 @@ start_usb_dev(){
|
||||
echo 1 > functions/hid.GS0/wakeup_on_write
|
||||
fi
|
||||
echo 1 > functions/hid.GS0/protocol
|
||||
echo 6 > 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 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\\xE7\\x05\\x07\\x19\\x00\\x29\\xE7\\x81\\x00\\xc0 > functions/hid.GS0/report_desc
|
||||
ln -s functions/hid.GS0 configs/c.1
|
||||
|
||||
# mouse
|
||||
@@ -62,8 +74,8 @@ start_usb_dev(){
|
||||
echo 1 > functions/hid.GS1/wakeup_on_write
|
||||
fi
|
||||
echo 2 > functions/hid.GS1/protocol
|
||||
echo -ne \\x34 > 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 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
|
||||
ln -s functions/hid.GS1 configs/c.1
|
||||
|
||||
# touchpad
|
||||
@@ -78,7 +90,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
|
||||
|
||||
@@ -92,6 +104,7 @@ start_usb_dev(){
|
||||
echo 1 > functions/mass_storage.disk0/lun.0/ro
|
||||
echo 0 > functions/mass_storage.disk0/lun.0/cdrom
|
||||
fi
|
||||
echo "NanoKVM USB Mass Storage0520" > functions/mass_storage.disk0/lun.0/inquiry_string
|
||||
disk=$(cat /boot/usb.disk0)
|
||||
if [ -z "${disk}" ]
|
||||
then
|
||||
@@ -136,4 +149,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
|
||||
|
||||
112
kvmapp/system/init.d/S03usbhid
Executable file
112
kvmapp/system/init.d/S03usbhid
Executable file
@@ -0,0 +1,112 @@
|
||||
#!/bin/sh
|
||||
# kvmhwd hid only
|
||||
|
||||
start_usb_dev(){
|
||||
. /etc/profile
|
||||
echo "usb mode: device"
|
||||
cd /sys/kernel/config/usb_gadget
|
||||
|
||||
mkdir g0
|
||||
cd g0
|
||||
|
||||
echo 0x0101 > bcdUSB
|
||||
echo 0x0623 > bcdDevice
|
||||
# echo 0x3346 > idVendor
|
||||
# echo 0x1009 > idProduct
|
||||
if [ -e /boot/usb.vid ]
|
||||
then
|
||||
cat /boot/usb.vid > idVendor
|
||||
else
|
||||
echo 0x3346 > idVendor
|
||||
fi
|
||||
if [ -e /boot/usb.pid ]
|
||||
then
|
||||
cat /boot/usb.pid > idProduct
|
||||
else
|
||||
echo 0x1009 > idProduct
|
||||
fi
|
||||
mkdir strings/0x409
|
||||
# echo '0' > strings/0x409/serialnumber
|
||||
echo 'sipeed' > strings/0x409/manufacturer
|
||||
echo 'NanoKVM' > strings/0x409/product
|
||||
|
||||
mkdir configs/c.1
|
||||
echo 0xA0 > configs/c.1/bmAttributes
|
||||
echo 200 > configs/c.1/MaxPower
|
||||
mkdir configs/c.1/strings/0x409
|
||||
echo "NanoKVM" > configs/c.1/strings/0x409/configuration
|
||||
|
||||
# keyboard
|
||||
mkdir functions/hid.GS0
|
||||
echo 1 > functions/hid.GS0/subclass
|
||||
if [ ! -e /boot/usb.notwakeup ]
|
||||
then
|
||||
echo 1 > functions/hid.GS0/wakeup_on_write
|
||||
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
|
||||
ln -s functions/hid.GS0 configs/c.1
|
||||
|
||||
# mouse
|
||||
mkdir functions/hid.GS1
|
||||
echo 1 > functions/hid.GS1/subclass
|
||||
if [ ! -e /boot/usb.notwakeup ]
|
||||
then
|
||||
echo 1 > functions/hid.GS1/wakeup_on_write
|
||||
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
|
||||
ln -s functions/hid.GS1 configs/c.1
|
||||
|
||||
# touchpad
|
||||
mkdir functions/hid.GS2
|
||||
echo 1 > functions/hid.GS2/subclass
|
||||
if [ ! -e /boot/usb.notwakeup ]
|
||||
then
|
||||
echo 1 > functions/hid.GS2/wakeup_on_write
|
||||
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
|
||||
ln -s functions/hid.GS2 configs/c.1
|
||||
|
||||
ls /sys/class/udc/ | cat > UDC
|
||||
echo device > /proc/cviusb/otg_role
|
||||
}
|
||||
|
||||
start_usb_host(){
|
||||
echo '' > /sys/kernel/config/usb_gadget/g0/UDC
|
||||
echo host > /proc/cviusb/otg_role
|
||||
}
|
||||
|
||||
restart_usb_dev(){
|
||||
echo > /sys/kernel/config/usb_gadget/g0/UDC
|
||||
sleep 1
|
||||
ls /sys/class/udc/ | cat > /sys/kernel/config/usb_gadget/g0/UDC
|
||||
echo "USB Restart OK!"
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
start_usb_dev
|
||||
;;
|
||||
restart)
|
||||
restart_usb_dev
|
||||
;;
|
||||
stop)
|
||||
start_usb_host
|
||||
;;
|
||||
stop_start)
|
||||
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
|
||||
@@ -1,115 +1,86 @@
|
||||
#!/bin/sh
|
||||
|
||||
. /etc/profile
|
||||
RESERVE_INET="192.168.90.1/22"
|
||||
|
||||
# /boot/eth.nodhcp for example
|
||||
# ipaddr/net gw[optional]
|
||||
# 192.168.0.101/24 192.168.0.1
|
||||
# 192.168.3.116/22
|
||||
clean_line() {
|
||||
echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//;s/\r//g'
|
||||
}
|
||||
|
||||
RESERVE_INET="192.168.0.1/24"
|
||||
calc_gw() {
|
||||
addr="$1"
|
||||
netid="$2"
|
||||
IFS=. read a b c d <<EOF
|
||||
$addr
|
||||
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() {
|
||||
printf "start ethernet: "
|
||||
if [ -e /boot/eth.nodhcp ]
|
||||
then
|
||||
[ -e /boot/eth.nodhcp ] &&
|
||||
cat /boot/eth.nodhcp | while read inet gw
|
||||
do
|
||||
addr=${inet%/*}
|
||||
netid=${inet#*/}
|
||||
[ -z $gw ] &&
|
||||
gw=$( echo $addr| ( IFS='.' read a b c d; echo $((
|
||||
(((((($a<<8)+$b)<<8)+$c)<<8)+$d)
|
||||
& (((1<<$netid)-1)<<(32-$netid))
|
||||
))
|
||||
)) &&
|
||||
gw=$(($gw>>24&0xff)).$(($gw>>16&0xff)).$(($gw>>8&0xff)).$((1+( $gw>>0&0xff )))
|
||||
ip addr flush dev eth0
|
||||
if [ -e /boot/eth.nodhcp ]; then
|
||||
while IFS= read -r line || [ -n "$line" ]; do
|
||||
line=$(clean_line "$line")
|
||||
[ -z "$line" ] && continue
|
||||
set -- $line
|
||||
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")
|
||||
arping -Dqc2 -Ieth0 "$addr" || continue
|
||||
ip a add "$inet" brd + dev eth0
|
||||
ip r add default via "$gw" dev eth0
|
||||
echo -e "nameserver $gw" >> /etc/resolv.conf
|
||||
break
|
||||
done < /boot/eth.nodhcp
|
||||
|
||||
arping -Dqc2 -Ieth0 $addr || continue
|
||||
ip a add $inet brd + dev eth0
|
||||
ip r add default via $gw dev eth0
|
||||
cat > /etc/resolve.conf << EOF
|
||||
nameserver $gw
|
||||
nameserver 8.8.8.8
|
||||
nameserver 114.114.114.114
|
||||
EOF
|
||||
break
|
||||
done &&
|
||||
ip a show dev eth0|grep inet || (
|
||||
udhcpc -i eth0 -t 3 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &>/dev/null
|
||||
ip a show dev eth0|grep inet
|
||||
) || (
|
||||
# failed to apply dynamic addr, need a available static addr to visit the LAN
|
||||
inet=$RESERVE_INET
|
||||
addr=${inet%/*}
|
||||
ip a add $inet brd + dev eth0
|
||||
) || exit 1
|
||||
ip a show dev eth0 | grep inet > /dev/null || {
|
||||
udhcpc -i eth0 -t 3 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &>/dev/null
|
||||
ip a show dev eth0 | grep inet > /dev/null
|
||||
} || {
|
||||
inet=$RESERVE_INET
|
||||
addr=${inet%/*}
|
||||
ip a add "$inet" brd + dev eth0
|
||||
} || exit 1
|
||||
else
|
||||
(udhcpc -i eth0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid) &
|
||||
udhcpc -i eth0 -t 10 -T 1 -A 5 -b -p /run/udhcpc.eth0.pid &
|
||||
fi
|
||||
|
||||
echo "OK"
|
||||
}
|
||||
|
||||
stop() {
|
||||
[[ ! -e "/run/udhcpc.eth0.pid" ]] && echo "udhcpc is not running..." && exit 1
|
||||
kill `cat /run/udhcpc.eth0.pid`
|
||||
[ ! -e "/run/udhcpc.eth0.pid" ] && exit 1
|
||||
kill "$(cat /run/udhcpc.eth0.pid)"
|
||||
rm /run/udhcpc.eth0.pid
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
start
|
||||
;;
|
||||
stop)
|
||||
stop
|
||||
;;
|
||||
restart|reload)
|
||||
$0 stop
|
||||
$0 start
|
||||
;;
|
||||
doc)
|
||||
cat <<EOF
|
||||
If you want to set your own static ip address
|
||||
rather then fetch it by dhcp.
|
||||
Then you need to create a file \`/boot/eth.nodhcp\`,
|
||||
and edit it following the format below:
|
||||
\`addr/netid gw[optional]\` in one line
|
||||
for example (support muti definations, checks with arp):
|
||||
1. 192.168.0.101/24 192.168.0.1
|
||||
2. 192.168.3.116/22
|
||||
Delete this file if you change to use dhcp default.
|
||||
ATTENTION: If all the STATIC address you set in the file is
|
||||
already in use on this LAN checked with arp, then none
|
||||
of them will be yours. And it will trigger dhcp, try to
|
||||
fetch DYNAMIC one. If it's also failed, your address will
|
||||
be the REVERSE one, 192.168.0.1/24. Just to be sure that
|
||||
you can visit your NanoKVM device through eth to fix some
|
||||
problems by ssh, unless you must disassemble it and modify
|
||||
or rewrite the TFCard once again.
|
||||
EOF
|
||||
echo ""
|
||||
cat <<EOF
|
||||
如果您想自行设置静态 ip 地址而不是使用 dhcp 来获取它。
|
||||
|
||||
那么您需要新建一个文件 \`/boot/eth.nodhcp\`,然后按照以下格式编辑它:
|
||||
\`addr/netid gw[optional]\` 在一行内
|
||||
示例(支持多个预设,会通过 arp 检查是否占用):
|
||||
1. 192.168.0.101/24 192.168.0.1
|
||||
2. 192.168.3.116/22
|
||||
|
||||
如果您想改回默认 dhcp 获取 ip 地址的方式,删除该文件后即可恢复。
|
||||
|
||||
注意:如果您预设的所有静态 ip 地址都被 arp 检测到已占用,则不会成功设置。
|
||||
此时会触发 dhcp 尝试获取 ip 地址,如果仍失败,那么最终会强制设置成
|
||||
192.168.90.1/24。这是为了保证您的 NanoKVM 设备总是能有一个可用的
|
||||
ip 地址,方便您通过局域网 ssh 连接设备进行一些修复,否则您可能需要
|
||||
拆开外壳以手动修改 TF 卡或重新烧卡。
|
||||
|
||||
|
||||
EOF
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|restart}"
|
||||
exit 1
|
||||
start) start ;;
|
||||
stop) stop ;;
|
||||
restart|reload)
|
||||
$0 stop
|
||||
$0 start
|
||||
;;
|
||||
*) exit 1 ;;
|
||||
esac
|
||||
@@ -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
|
||||
|
||||
@@ -3,67 +3,71 @@
|
||||
# sshd Starts sshd.
|
||||
#
|
||||
|
||||
# Make sure the ssh-keygen progam exists
|
||||
[ -f /usr/bin/ssh-keygen ] || exit 0
|
||||
# Ensure required binaries exist
|
||||
[ -x /usr/bin/ssh-keygen ] || exit 0
|
||||
[ -x /usr/sbin/sshd ] || exit 1
|
||||
|
||||
PIDFILE="/var/run/sshd.pid"
|
||||
|
||||
umask 077
|
||||
|
||||
startssh() {
|
||||
/usr/bin/ssh-keygen -A
|
||||
# Generate SSH keys if they do not exist
|
||||
[ ! -f /etc/ssh/ssh_host_rsa_key ] && /usr/bin/ssh-keygen -A
|
||||
|
||||
printf "Starting sshd: "
|
||||
/usr/sbin/sshd
|
||||
touch /var/lock/sshd
|
||||
echo "OK"
|
||||
printf "Starting sshd: "
|
||||
/usr/sbin/sshd
|
||||
touch /var/lock/sshd
|
||||
echo "OK"
|
||||
}
|
||||
|
||||
start() {
|
||||
# Create any missing keys
|
||||
if [ -e /etc/kvm/ssh_stop ]
|
||||
then
|
||||
if [ -e /boot/start_ssh_once ]
|
||||
then
|
||||
rm /boot/start_ssh_once
|
||||
startssh
|
||||
else
|
||||
echo "SSH does not start"
|
||||
fi
|
||||
else
|
||||
startssh
|
||||
fi
|
||||
if [ -e /etc/kvm/ssh_stop ]; then
|
||||
if [ -e /boot/start_ssh_once ]; then
|
||||
rm -f /boot/start_ssh_once
|
||||
startssh
|
||||
else
|
||||
echo "SSH does not start"
|
||||
exit 0
|
||||
fi
|
||||
else
|
||||
startssh
|
||||
fi
|
||||
}
|
||||
|
||||
stop() {
|
||||
printf "Stopping sshd: "
|
||||
killall sshd
|
||||
rm -f /var/lock/sshd
|
||||
echo "OK"
|
||||
printf "Stopping sshd: "
|
||||
killall sshd 2>/dev/null
|
||||
rm -f /var/lock/sshd
|
||||
echo "OK"
|
||||
}
|
||||
|
||||
restart() {
|
||||
stop
|
||||
start
|
||||
stop
|
||||
start
|
||||
}
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
start
|
||||
;;
|
||||
stop)
|
||||
stop
|
||||
;;
|
||||
restart|reload)
|
||||
restart
|
||||
;;
|
||||
permanent_on)
|
||||
rm /etc/kvm/ssh_stop
|
||||
start
|
||||
;;
|
||||
permanent_off)
|
||||
touch /etc/kvm/ssh_stop
|
||||
stop
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
|
||||
exit 1
|
||||
start)
|
||||
start
|
||||
;;
|
||||
stop)
|
||||
stop
|
||||
;;
|
||||
restart|reload)
|
||||
restart
|
||||
;;
|
||||
permanent_on)
|
||||
rm -f /etc/kvm/ssh_stop
|
||||
start
|
||||
;;
|
||||
permanent_off)
|
||||
touch /etc/kvm/ssh_stop
|
||||
stop
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|restart|permanent_on|permanent_off}"
|
||||
exit 1
|
||||
esac
|
||||
|
||||
exit $?
|
||||
|
||||
exit 0
|
||||
@@ -1,42 +1,69 @@
|
||||
#!/bin/sh
|
||||
# nanokvm Rev3.0
|
||||
# nanokvm Rev3.1
|
||||
|
||||
case "$1" in
|
||||
start)
|
||||
echo -n kvm > /boot/hostname.prefix
|
||||
cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
|
||||
|
||||
str_value=$(cat /sys/class/cvi-base/base_uid | awk '{print $2}')
|
||||
first_uint=$(echo $str_value | cut -d'_' -f1)
|
||||
second_uint=$(echo $str_value | cut -d'_' -f2)
|
||||
result="$first_uint$second_uint"
|
||||
echo $result > /device_key
|
||||
# Copy sensor config if the file exists
|
||||
[ -f /mnt/data/sensor_cfg.ini.LT ] && cp /mnt/data/sensor_cfg.ini.LT /mnt/data/sensor_cfg.ini
|
||||
|
||||
# Generate unique device key
|
||||
if [ -f /sys/class/cvi-base/base_uid ]; then
|
||||
str_value=$(awk '{print $2}' /sys/class/cvi-base/base_uid)
|
||||
first_uint=$(echo "$str_value" | cut -d'_' -f1)
|
||||
second_uint=$(echo "$str_value" | cut -d'_' -f2)
|
||||
echo "$first_uint$second_uint" > /device_key
|
||||
fi
|
||||
|
||||
# Set iptables rules (skip if already present)
|
||||
iptables -C INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
|
||||
iptables -A INPUT -i eth0 -p tcp --dport 80 -m state --state NEW,ESTABLISHED -j ACCEPT
|
||||
|
||||
iptables -C OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
|
||||
iptables -A OUTPUT -o eth0 -p tcp --sport 80 -m state --state ESTABLISHED -j ACCEPT
|
||||
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
|
||||
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
|
||||
|
||||
iptables -C INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT 2>/dev/null || \
|
||||
iptables -A INPUT -i eth0 -p tcp --sport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
|
||||
|
||||
iptables -C OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT 2>/dev/null || \
|
||||
iptables -A OUTPUT -o eth0 -p tcp --dport 22 -m state --state ESTABLISHED -j ACCEPT
|
||||
|
||||
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 &
|
||||
|
||||
|
||||
cp -r /kvmapp/server /tmp/
|
||||
/tmp/server/NanoKVM-Server &
|
||||
;;
|
||||
;;
|
||||
|
||||
stop)
|
||||
killall kvm_system
|
||||
killall NanoKVM-Server
|
||||
rm -r /tmp/kvm_system
|
||||
rm -r /tmp/server
|
||||
rm -r /tmp/kvm_system /tmp/server
|
||||
echo "OK"
|
||||
;;
|
||||
;;
|
||||
|
||||
restart)
|
||||
killall kvm_system
|
||||
killall NanoKVM-Server
|
||||
rm -r /tmp/kvm_system
|
||||
rm -r /tmp/server
|
||||
|
||||
rm -r /tmp/kvm_system /tmp/server
|
||||
|
||||
cp -r /kvmapp/kvm_system /tmp/
|
||||
/tmp/kvm_system/kvm_system &
|
||||
|
||||
@@ -44,7 +71,11 @@ case "$1" in
|
||||
/tmp/server/NanoKVM-Server &
|
||||
|
||||
sync
|
||||
|
||||
echo "OK"
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Usage: $0 {start|stop|restart}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
158
kvmapp/system/init.d/S96picoclaw
Executable file
158
kvmapp/system/init.d/S96picoclaw
Executable file
@@ -0,0 +1,158 @@
|
||||
#!/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_runtime_env() {
|
||||
[ -x "$BIN_PATH" ] || {
|
||||
echo "picoclaw binary not found: $BIN_PATH"
|
||||
return 1
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
cd "$PICOCLAW_HOME" || {
|
||||
echo "failed to enter picoclaw home: $PICOCLAW_HOME"
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
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 pidof "$BIN_NAME" >/dev/null 2>&1; then
|
||||
echo "picoclaw already running"
|
||||
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 &
|
||||
}
|
||||
|
||||
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() {
|
||||
killall "$BIN_NAME" 2>/dev/null || true
|
||||
}
|
||||
|
||||
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
|
||||
@@ -21,94 +21,69 @@ 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)
|
||||
tailscale set --accept-dns=false
|
||||
if [ -f /etc/kvm/GOMEMLIMIT ]; then
|
||||
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 \
|
||||
--socket=/var/run/tailscale/tailscaled.sock \
|
||||
--port=${PORT} \
|
||||
$FLAGS
|
||||
[ $? = 0 ] && echo "OK" || echo "FAIL"
|
||||
if [ $? = 0 ]; then
|
||||
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
|
||||
esac
|
||||
|
||||
exit 0
|
||||
exit 0
|
||||
|
||||
@@ -2,41 +2,38 @@ import os
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
|
||||
import pathlib
|
||||
import requests
|
||||
|
||||
temporary = "/root/.kvm-cache/"
|
||||
temporary: str = "/root/.kvm-cache/"
|
||||
|
||||
|
||||
def mkdir():
|
||||
is_exists = os.path.exists(temporary)
|
||||
if is_exists:
|
||||
def mkdir() -> None:
|
||||
if pathlib.Path(temporary).exists():
|
||||
shutil.rmtree(temporary)
|
||||
os.mkdir(temporary)
|
||||
print(f"create temporary directory {temporary}")
|
||||
pathlib.Path(temporary).mkdir()
|
||||
print(f"Created temporary directory {temporary}")
|
||||
|
||||
|
||||
def read(file):
|
||||
with open(file, "r") as f:
|
||||
content = f.read()
|
||||
return content.replace("\n", "")
|
||||
def read(file: str) -> str:
|
||||
return pathlib.Path(file).read_text().replace("\n", "")
|
||||
|
||||
|
||||
def download_firmware():
|
||||
print("download firmware...")
|
||||
def download_firmware() -> None:
|
||||
print("Downloading firmware...")
|
||||
|
||||
now = int(time.time())
|
||||
url = f"https://cdn.sipeed.com/nanokvm/latest.zip?n={now}"
|
||||
print(f"download from {url}")
|
||||
print(f"Downloading firmware from {url}")
|
||||
|
||||
response = requests.get(url)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"download firmware failed, status: {response.status_code}")
|
||||
raise Exception(f"Failed to download firmware, status: {response.status_code}")
|
||||
|
||||
content_type = response.headers.get("content-type")
|
||||
if content_type != "application/zip":
|
||||
raise Exception(f"download firmware failed, content_type: {content_type}")
|
||||
raise Exception(f"Failed to download firmware, content_type: {content_type}")
|
||||
|
||||
zip_file = f"{temporary}/latest.zip"
|
||||
with open(zip_file, "wb") as f:
|
||||
@@ -46,49 +43,23 @@ def download_firmware():
|
||||
with zipfile.ZipFile(zip_file, "r") as f:
|
||||
f.extractall(temporary)
|
||||
|
||||
print("download firmware done")
|
||||
print("Completed downloading firmware.")
|
||||
|
||||
|
||||
def download_lib():
|
||||
print("download lib...")
|
||||
def update() -> None:
|
||||
backup_dir = pathlib.Path("/root/old")
|
||||
firmware_dir = pathlib.Path("/kvmapp")
|
||||
|
||||
device_key = read("/device_key")
|
||||
if backup_dir.exists():
|
||||
shutil.rmtree(backup_dir)
|
||||
|
||||
url = f"https://maixvision.sipeed.com/api/v1/nanokvm/encryption?uid={device_key}"
|
||||
headers = {"token": "MaixVision2024"}
|
||||
response = requests.get(url, headers=headers, stream=True)
|
||||
if firmware_dir.exists():
|
||||
firmware_dir.rename(backup_dir)
|
||||
|
||||
if response.status_code != 200:
|
||||
raise Exception(f"download lib failed, status: {response.status_code}")
|
||||
|
||||
content_type = response.headers.get("content-type")
|
||||
if content_type != "application/octet-stream":
|
||||
raise Exception(f"download lib failed, content_type: {content_type}")
|
||||
|
||||
lib_file = f"{temporary}/libmaixcam_lib.so"
|
||||
with open(lib_file, "wb") as f:
|
||||
f.write(response.content)
|
||||
|
||||
lib_dir = f"{temporary}/latest/kvm_system/dl_lib/"
|
||||
shutil.copy(lib_file, lib_dir)
|
||||
|
||||
print("download lib done")
|
||||
pathlib.Path(f"{temporary}/latest").rename(firmware_dir)
|
||||
|
||||
|
||||
def update():
|
||||
backup_dir = "/root/old"
|
||||
firmware_dir = "/kvmapp"
|
||||
|
||||
if os.path.exists(backup_dir):
|
||||
shutil.rmtree(backup_dir)
|
||||
|
||||
if os.path.exists(firmware_dir):
|
||||
shutil.move(firmware_dir, backup_dir)
|
||||
|
||||
shutil.move(f"{temporary}/latest", firmware_dir)
|
||||
|
||||
|
||||
def change_permissions():
|
||||
def change_permissions() -> None:
|
||||
for root, dirs, files in os.walk("/kvmapp"):
|
||||
os.chmod(root, 0o755)
|
||||
|
||||
@@ -97,23 +68,22 @@ def change_permissions():
|
||||
os.chmod(file_path, 0o755)
|
||||
|
||||
print("change permissions done")
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
def main() -> None:
|
||||
try:
|
||||
print("stop service...")
|
||||
print("Stopping nanokvm service...")
|
||||
os.system("/etc/init.d/S95nanokvm stop")
|
||||
|
||||
print("start update......")
|
||||
print("Staring update...")
|
||||
|
||||
mkdir()
|
||||
download_firmware()
|
||||
# download_lib()
|
||||
update()
|
||||
change_permissions()
|
||||
|
||||
version = read("/kvmapp/version")
|
||||
print(f"update to {version} success.")
|
||||
print(f"Successfully updated to version: {version}")
|
||||
print("restart service\nthe nanokvm will reboot")
|
||||
except Exception as e:
|
||||
print(f"update failed\n{e}")
|
||||
@@ -123,4 +93,4 @@ def main():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
|
||||
@@ -13,7 +13,7 @@ server
|
||||
├── dl_lib // Shared object libraries
|
||||
├── include // Header files for shared objects
|
||||
├── logger // Logging system
|
||||
├── middleware // Server middleware components
|
||||
├── middleware // Server middleware components
|
||||
├── proto // API request/response definitions
|
||||
├── router // API route handlers
|
||||
├── service // Core service implementations
|
||||
@@ -26,41 +26,40 @@ 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
|
||||
|
||||
# Authentication setting (enable/disable)
|
||||
# Note: Only disable authentication in development environment
|
||||
authentication: enable
|
||||
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 & 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
|
||||
@@ -75,8 +74,9 @@ Note: Use Linux operating system (x86-64). This build process is not compatible
|
||||
2. Compile the Project
|
||||
1. Run `cd server` from the project root directory.
|
||||
2. Run `go mod tidy` to install Go dependencies.
|
||||
3. Run `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` to compile the project.
|
||||
4. After compilation, an executable file named `NanoKVM-Server` will be generated.
|
||||
3. (Optional) If you compiled `libkvm.so` yourself, you need to modify its RPATH by `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so`.
|
||||
4. Run `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` to compile the project.
|
||||
5. After compilation, an executable file named `NanoKVM-Server` will be generated.
|
||||
|
||||
3. Modify RPATH
|
||||
1. Run `sudo apt install patchelf` or `pip install patchelf` to install patchelf.
|
||||
|
||||
@@ -27,6 +27,7 @@ server
|
||||
|
||||
```yaml
|
||||
proto: http
|
||||
host: ""
|
||||
port:
|
||||
http: 80
|
||||
https: 443
|
||||
|
||||
@@ -24,40 +24,40 @@ 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
|
||||
|
||||
# 日志级别(debug/info/warn/error)
|
||||
# 注意:在生产环境中使用 info 或 error。debug 模式仅在开发环境中使用。
|
||||
crt: server.crt # HTTPS 服务使用的公钥证书路径
|
||||
key: server.key # HTTPS 服务使用的私钥文件路径
|
||||
|
||||
|
||||
# 日志配置
|
||||
logger:
|
||||
level: info
|
||||
file: stdout
|
||||
|
||||
# 鉴权设置(enable/disable)
|
||||
# 注意:生产环境中请勿使用 disable。
|
||||
authentication: enable
|
||||
level: info # 全局日志打印级别,从高到底可选 `trace`, `debug`, `info`, `warn`, `error`, `fatal`, `panic`。默认为 `info`
|
||||
file: stdout # 日志输出目标位置。若填写 `stdout` 则输出在控制台。配置为文件路径则会输出到对应的文件。默认为 `stdout`
|
||||
|
||||
|
||||
# 认证与安全
|
||||
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 服务器授权连接时使用的凭据/密码
|
||||
```
|
||||
|
||||
## 编译部署
|
||||
@@ -72,8 +72,9 @@ turn:
|
||||
2. 编译
|
||||
1. 在项目根目录下执行 `cd server` 进入 server 目录;
|
||||
2. 执行 `go mod tidy` 安装 Go 依赖包;
|
||||
3. 执行 `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` 进行编译;
|
||||
4. 编译完成后,会生成可执行文件 `NanoKVM-Server`。
|
||||
3. (可选)如果您手动编译了 `libkvm.so`,则需要通过 `patchelf --add-rpath \$ORIGIN ./dl_lib/libkvm.so` 修改其 RPATH 属性。
|
||||
4. 执行 `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` 进行编译;
|
||||
5. 编译完成后,会生成可执行文件 `NanoKVM-Server`。
|
||||
|
||||
3. 修改 RPATH
|
||||
1. 执行 `sudo apt install patchelf` 或 `pip install patchelf` 安装 patchelf;
|
||||
@@ -81,8 +82,8 @@ turn:
|
||||
3. 执行 `patchelf --add-rpath \$ORIGIN/dl_lib NanoKVM-Server` 修改可执行文件的 RPATH 属性。
|
||||
|
||||
4. 部署
|
||||
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
|
||||
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
|
||||
1. 上传文件需要启用 SSH 功能。请在 Web `设置 - SSH` 中检查 SSH 是否已经启用;
|
||||
2. 使用编译生成的 `NanoKVM-Server` 文件,替换 NanoKVM 中 `/kvmapp/server/` 目录下的原始文件;
|
||||
3. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
|
||||
|
||||
## 手动更新
|
||||
@@ -92,4 +93,4 @@ turn:
|
||||
1. 从 [GitHub](https://github.com/sipeed/NanoKVM/releases) 下载最新的应用安装包;
|
||||
2. 解压缩下载的安装包,并将解压后的文件夹重命名为 `kvmapp`;
|
||||
3. 备份 NanoKVM 系统中的 `/kvmapp` 目录,然后用解压后的 `kvmapp` 文件夹替换现有目录。
|
||||
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
|
||||
4. 在 NanoKVM 中执行 `/etc/init.d/S95nanokvm restart` 重启服务。
|
||||
|
||||
64
server/build.sh
Executable file
64
server/build.sh
Executable file
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -e
|
||||
|
||||
# Configuration Variables
|
||||
BINARY_NAME="NanoKVM-Server"
|
||||
CC_COMPILER="riscv64-unknown-linux-musl-gcc"
|
||||
CGO_CFLAGS_OPTS="-mcpu=c906fdv -march=rv64imafdcv0p7xthead -mcmodel=medany -mabi=lp64d"
|
||||
|
||||
# Define colors for output
|
||||
GREEN='\033[0;32m'
|
||||
RED='\033[0;31m'
|
||||
YELLOW='\033[1;33m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Helper function to check if a command exists
|
||||
check_dependency() {
|
||||
if ! command -v "$1" &> /dev/null; then
|
||||
echo -e "${RED}[ERROR] Required command '$1' not found.${NC}"
|
||||
echo "Please install it or ensure it is in your PATH."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Step 1: Check Prerequisites
|
||||
# ------------------------------------------------------------------------------
|
||||
echo -e "${YELLOW}[INFO] Checking build environment...${NC}"
|
||||
|
||||
check_dependency "go"
|
||||
check_dependency "patchelf"
|
||||
check_dependency "$CC_COMPILER"
|
||||
|
||||
echo -e "${GREEN}[OK] All dependencies found.${NC}"
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Step 2: Build the Binary
|
||||
# ------------------------------------------------------------------------------
|
||||
echo -e "${YELLOW}[INFO] Starting cross-compilation for RISC-V 64-bit (BoringCrypto enabled)...${NC}"
|
||||
|
||||
export CGO_ENABLED=1
|
||||
export GOOS=linux
|
||||
export GOARCH=riscv64
|
||||
export GOEXPERIMENT=boringcrypto
|
||||
export CC="$CC_COMPILER"
|
||||
export CGO_CFLAGS="$CGO_CFLAGS_OPTS"
|
||||
|
||||
go build -o "$BINARY_NAME" -v
|
||||
|
||||
if [ -f "$BINARY_NAME" ]; then
|
||||
echo -e "${GREEN}[SUCCESS] Binary '$BINARY_NAME' created successfully.${NC}"
|
||||
else
|
||||
echo -e "${RED}[ERROR] Build failed. Binary not found.${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ------------------------------------------------------------------------------
|
||||
# Step 3: Patch RPATH
|
||||
# ------------------------------------------------------------------------------
|
||||
echo -e "${YELLOW}[INFO] Patching RPATH with patchelf...${NC}"
|
||||
|
||||
patchelf --add-rpath '$ORIGIN/dl_lib' "$BINARY_NAME"
|
||||
|
||||
echo -e "${GREEN}[DONE] Build script completed successfully!${NC}"
|
||||
@@ -7,8 +7,6 @@ package common
|
||||
*/
|
||||
import "C"
|
||||
import (
|
||||
"NanoKVM-Server/config"
|
||||
"strings"
|
||||
"sync"
|
||||
"unsafe"
|
||||
|
||||
@@ -20,23 +18,14 @@ var (
|
||||
kvmVisionOnce sync.Once
|
||||
)
|
||||
|
||||
type KvmVision struct {
|
||||
mutex sync.Mutex
|
||||
}
|
||||
type KvmVision struct{}
|
||||
|
||||
func GetKvmVision() *KvmVision {
|
||||
kvmVisionOnce.Do(func() {
|
||||
kvmVision = &KvmVision{}
|
||||
|
||||
conf := config.GetInstance()
|
||||
logLevel := strings.ToLower(conf.Logger.Level)
|
||||
|
||||
logEnable := C.uint8_t(0)
|
||||
if logLevel == "debug" {
|
||||
logEnable = C.uint8_t(1)
|
||||
}
|
||||
|
||||
C.kvmv_init(logEnable)
|
||||
logLevel := C.uint8_t(0)
|
||||
C.kvmv_init(logLevel)
|
||||
log.Debugf("kvm vision initialized")
|
||||
})
|
||||
|
||||
@@ -44,9 +33,6 @@ func GetKvmVision() *KvmVision {
|
||||
}
|
||||
|
||||
func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data []byte, result int) {
|
||||
k.mutex.Lock()
|
||||
defer k.mutex.Unlock()
|
||||
|
||||
var (
|
||||
kvmData *C.uint8_t
|
||||
dataSize C.uint32_t
|
||||
@@ -67,15 +53,10 @@ func (k *KvmVision) ReadMjpeg(width uint16, height uint16, quality uint16) (data
|
||||
defer C.free_kvmv_data(&kvmData)
|
||||
|
||||
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
|
||||
|
||||
log.Debugf("read kvm image: %v", result)
|
||||
return
|
||||
}
|
||||
|
||||
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, sps []byte, pps []byte, result int) {
|
||||
k.mutex.Lock()
|
||||
defer k.mutex.Unlock()
|
||||
|
||||
func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data []byte, result int) {
|
||||
var (
|
||||
kvmData *C.uint8_t
|
||||
dataSize C.uint32_t
|
||||
@@ -96,49 +77,9 @@ func (k *KvmVision) ReadH264(width uint16, height uint16, bitRate uint16) (data
|
||||
defer C.free_kvmv_data(&kvmData)
|
||||
|
||||
data = C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
|
||||
|
||||
if result == 3 {
|
||||
sps, _ = k.ReadH264SPS()
|
||||
pps, _ = k.ReadH264PPS()
|
||||
}
|
||||
|
||||
log.Debugf("read kvm image: %v", result)
|
||||
return
|
||||
}
|
||||
|
||||
func (k *KvmVision) ReadH264SPS() ([]byte, int) {
|
||||
var (
|
||||
kvmData *C.uint8_t
|
||||
dataSize C.uint32_t
|
||||
)
|
||||
|
||||
result := int(C.kvmv_get_sps_frame(&kvmData, &dataSize))
|
||||
if result < 0 {
|
||||
log.Errorf("failed to read sps: %v", result)
|
||||
return nil, result
|
||||
}
|
||||
|
||||
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
|
||||
|
||||
return data, result
|
||||
}
|
||||
|
||||
func (k *KvmVision) ReadH264PPS() ([]byte, int) {
|
||||
var (
|
||||
kvmData *C.uint8_t
|
||||
dataSize C.uint32_t
|
||||
)
|
||||
|
||||
result := int(C.kvmv_get_pps_frame(&kvmData, &dataSize))
|
||||
if result < 0 {
|
||||
log.Errorf("failed to read pps: %v", result)
|
||||
return nil, result
|
||||
}
|
||||
|
||||
data := C.GoBytes(unsafe.Pointer(kvmData), C.int(dataSize))
|
||||
return data, result
|
||||
}
|
||||
|
||||
func (k *KvmVision) SetHDMI(enable bool) int {
|
||||
hdmiEnable := C.uint8_t(0)
|
||||
if enable {
|
||||
@@ -154,10 +95,17 @@ func (k *KvmVision) SetHDMI(enable bool) int {
|
||||
return result
|
||||
}
|
||||
|
||||
func (k *KvmVision) Close() {
|
||||
k.mutex.Lock()
|
||||
defer k.mutex.Unlock()
|
||||
func (k *KvmVision) SetGop(gop uint8) {
|
||||
_gop := C.uint8_t(gop)
|
||||
C.set_h264_gop(_gop)
|
||||
}
|
||||
|
||||
func (k *KvmVision) SetFrameDetect(frame uint8) {
|
||||
_frame := C.uint8_t(frame)
|
||||
C.set_frame_detact(_frame)
|
||||
}
|
||||
|
||||
func (k *KvmVision) Close() {
|
||||
C.kvmv_deinit()
|
||||
log.Debugf("stop kvm vision...")
|
||||
}
|
||||
@@ -8,6 +8,7 @@ type Screen struct {
|
||||
FPS int
|
||||
Quality uint16
|
||||
BitRate uint16
|
||||
GOP uint8
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -46,6 +47,7 @@ func GetScreen() *Screen {
|
||||
Quality: 80,
|
||||
FPS: 30,
|
||||
BitRate: 3000,
|
||||
GOP: 30,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -70,6 +72,24 @@ func SetScreen(key string, value int) {
|
||||
|
||||
case "fps":
|
||||
screen.FPS = validateFPS(value)
|
||||
|
||||
case "gop":
|
||||
screen.GOP = uint8(value)
|
||||
}
|
||||
}
|
||||
|
||||
func CheckScreen() {
|
||||
if _, ok := ResolutionMap[screen.Height]; !ok {
|
||||
screen.Width = 1920
|
||||
screen.Height = 1080
|
||||
}
|
||||
|
||||
if _, ok := QualityMap[screen.Quality]; !ok {
|
||||
screen.Quality = 80
|
||||
}
|
||||
|
||||
if _, ok := BitRateMap[screen.BitRate]; !ok {
|
||||
screen.BitRate = 3000
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
45
server/config/file.go
Normal file
45
server/config/file.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const ConfigurationFile = "/etc/kvm/server.yaml"
|
||||
|
||||
func Read() (*Config, error) {
|
||||
data, err := os.ReadFile(ConfigurationFile)
|
||||
if err != nil {
|
||||
log.Errorf("failed to read config: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var conf Config
|
||||
|
||||
if err := yaml.Unmarshal(data, &conf); err != nil {
|
||||
log.Fatalf("failed to unmarshal config: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Debugf("read %s successfully", ConfigurationFile)
|
||||
return &conf, nil
|
||||
}
|
||||
|
||||
func Write(conf *Config) error {
|
||||
data, err := yaml.Marshal(&conf)
|
||||
if err != nil {
|
||||
log.Errorf("failed to marshal config: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.WriteFile(ConfigurationFile, data, 0644)
|
||||
if err != nil {
|
||||
log.Errorf("failed to write config: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
log.Debugf("write to %s successfully", ConfigurationFile)
|
||||
return nil
|
||||
}
|
||||
@@ -54,24 +54,27 @@ func (h HWVersion) String() string {
|
||||
}
|
||||
}
|
||||
|
||||
func getHwVersion() HWVersion {
|
||||
func GetHwVersion() HWVersion {
|
||||
content, err := os.ReadFile(HWVersionFile)
|
||||
if err != nil {
|
||||
return HWVersionAlpha
|
||||
}
|
||||
|
||||
version := strings.ReplaceAll(string(content), "\n", "")
|
||||
if version == "beta" {
|
||||
switch version {
|
||||
case "alpha":
|
||||
return HWVersionAlpha
|
||||
case "beta":
|
||||
return HWVersionBeta
|
||||
} else if version == "pcie" {
|
||||
case "pcie":
|
||||
return HWVersionPcie
|
||||
default:
|
||||
return HWVersionAlpha
|
||||
}
|
||||
|
||||
return HWVersionAlpha
|
||||
}
|
||||
|
||||
func getHardware() (h Hardware) {
|
||||
version := getHwVersion()
|
||||
version := GetHwVersion()
|
||||
|
||||
switch version {
|
||||
case HWVersionAlpha:
|
||||
|
||||
61
server/config/picoclaw_internal.go
Normal file
61
server/config/picoclaw_internal.go
Normal 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
|
||||
}
|
||||
@@ -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.
@@ -1,21 +1,24 @@
|
||||
module NanoKVM-Server
|
||||
|
||||
go 1.22.1
|
||||
go 1.24.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.1
|
||||
github.com/golang-jwt/jwt/v5 v5.2.2
|
||||
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.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
|
||||
github.com/sirupsen/logrus v1.9.3
|
||||
github.com/spf13/viper v1.19.0
|
||||
github.com/unrolled/secure v1.15.0
|
||||
golang.org/x/crypto v0.31.0
|
||||
golang.org/x/crypto v0.45.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
@@ -30,7 +33,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
|
||||
@@ -42,19 +44,18 @@ require (
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/pion/datachannel v1.5.9 // indirect
|
||||
github.com/pion/dtls/v3 v3.0.3 // indirect
|
||||
github.com/pion/ice/v4 v4.0.2 // indirect
|
||||
github.com/pion/interceptor v0.1.37 // indirect
|
||||
github.com/pion/logging v0.2.2 // indirect
|
||||
github.com/pion/interceptor v0.1.39 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
github.com/pion/mdns/v2 v2.0.7 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/rtcp v1.2.14 // indirect
|
||||
github.com/pion/rtp v1.8.9 // indirect
|
||||
github.com/pion/rtcp v1.2.15 // indirect
|
||||
github.com/pion/sctp v1.8.33 // indirect
|
||||
github.com/pion/sdp/v3 v3.0.9 // indirect
|
||||
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
|
||||
@@ -66,14 +67,14 @@ 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
|
||||
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.33.0 // indirect
|
||||
golang.org/x/sys v0.28.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
golang.org/x/net v0.47.0 // indirect
|
||||
golang.org/x/sys v0.38.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
|
||||
)
|
||||
|
||||
@@ -34,8 +34,8 @@ 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.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
|
||||
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
|
||||
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/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
@@ -74,22 +74,22 @@ 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.37 h1:aRA8Zpab/wE7/c0O3fh1PqY0AJI3fCSEM5lRWJVorwI=
|
||||
github.com/pion/interceptor v0.1.37/go.mod h1:JzxbJ4umVTlZAf+/utHzNesY8tmRkM2lVmkS82TTj8Y=
|
||||
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
|
||||
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
|
||||
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.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=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtcp v1.2.14 h1:KCkGV3vJ+4DAJmvP0vaQShsb0xkRfWkO540Gy102KyE=
|
||||
github.com/pion/rtcp v1.2.14/go.mod h1:sn6qjxvnwyAkkPzPULIbVqSKI5Dv54Rv7VG0kNxh9L4=
|
||||
github.com/pion/rtp v1.8.9 h1:E2HX740TZKaqdcPmf4pw6ZZuG8u5RlMMt+l3dxeu6Wk=
|
||||
github.com/pion/rtp v1.8.9/go.mod h1:pBGHaFt/yW7bf1jjWAoUjpSNoDnw98KTMg+jWWvziqU=
|
||||
github.com/pion/rtcp v1.2.15 h1:LZQi2JbdipLOj4eBjK4wlVoQWfrZbh3Q6eHtWtJBZBo=
|
||||
github.com/pion/rtcp v1.2.15/go.mod h1:jlGuAjHMEXwMUHK78RgX0UmEJFV4zUKOFHR7OP+D3D0=
|
||||
github.com/pion/rtp v1.8.18 h1:yEAb4+4a8nkPCecWzQB6V/uEU18X1lQCGAQCjP+pyvU=
|
||||
github.com/pion/rtp v1.8.18/go.mod h1:bAu2UFKScgzyFqvUKmbvzSdPr+NGbZtv6UB2hesqXBk=
|
||||
github.com/pion/sctp v1.8.33 h1:dSE4wX6uTJBcNm8+YlMg7lw1wqyKHggsP5uKbdj+NZw=
|
||||
github.com/pion/sctp v1.8.33/go.mod h1:beTnqSzewI53KWoG3nqB282oDMGrhNxBdb+JZnkCwRM=
|
||||
github.com/pion/sdp/v3 v3.0.9 h1:pX++dCHoHUwq43kuwf3PyJfHlwIj4hXA7Vrifiq0IJY=
|
||||
@@ -100,6 +100,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=
|
||||
@@ -139,8 +141,9 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
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 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.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=
|
||||
@@ -149,8 +152,8 @@ 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=
|
||||
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=
|
||||
@@ -158,19 +161,19 @@ go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTV
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
|
||||
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
|
||||
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
|
||||
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
|
||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
|
||||
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
|
||||
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.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
|
||||
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
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/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
||||
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=
|
||||
|
||||
@@ -50,20 +50,20 @@ void set_venc_auto_recyc(uint8_t _enable);
|
||||
-5: Retrieving image, please wait
|
||||
-4: Modifying image resolution, please wait
|
||||
-3: img buffer full
|
||||
-2: VENC Errorl
|
||||
-2: VENC Error
|
||||
-1: No images were acquired
|
||||
0: Acquire MJPEG encoded images
|
||||
1: Acquire H264 encoded images(SPS)
|
||||
2: Acquire H264 encoded images(PPS)
|
||||
1: Acquire H264 encoded images(SPS)[Deprecated]
|
||||
2: Acquire H264 encoded images(PPS)[Deprecated]
|
||||
3: Acquire H264 encoded images(I)
|
||||
4: Acquire H264 encoded images(P)
|
||||
5: IMG not changed
|
||||
**********************************************************************************/
|
||||
int kvmv_read_img(uint16_t _width, uint16_t _height, uint8_t _type, uint16_t _qlty, uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
|
||||
int kvmv_get_sps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
|
||||
int kvmv_get_pps_frame(uint8_t** _pp_kvm_data, uint32_t* _p_kvmv_data_size);
|
||||
int free_kvmv_data(uint8_t ** _pp_kvm_data);
|
||||
void free_all_kvmv_data();
|
||||
void set_h264_gop(uint8_t _gop);
|
||||
void set_frame_detact(uint8_t _frame_detact);
|
||||
void kvmv_deinit();
|
||||
uint8_t kvmv_hdmi_control(uint8_t _en);
|
||||
|
||||
@@ -71,4 +71,4 @@ uint8_t kvmv_hdmi_control(uint8_t _en);
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif // KVM_VISION_H_
|
||||
#endif // KVM_VISION_H_
|
||||
|
||||
@@ -22,7 +22,7 @@ func (f *formatter) Format(entry *logrus.Entry) ([]byte, error) {
|
||||
buffer = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
now := entry.Time.Format("2006-01-02 15:04:05")
|
||||
now := entry.Time.Format("2006-01-02 15:04:05.000")
|
||||
|
||||
if entry.HasCaller() {
|
||||
fileName := filepath.Base(entry.Caller.File)
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"NanoKVM-Server/common"
|
||||
"NanoKVM-Server/config"
|
||||
"NanoKVM-Server/logger"
|
||||
"NanoKVM-Server/middleware"
|
||||
"NanoKVM-Server/router"
|
||||
"NanoKVM-Server/service/vm/jiggler"
|
||||
"NanoKVM-Server/utils"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
cors "github.com/rs/cors/wrapper/gin"
|
||||
@@ -26,6 +28,10 @@ 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
|
||||
@@ -35,9 +41,12 @@ func initialize() {
|
||||
vision := common.GetKvmVision()
|
||||
vision.SetHDMI(false)
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
vision.SetHDMI(true)
|
||||
if !utils.IsHdmiDisabled() {
|
||||
vision.SetHDMI(true)
|
||||
}
|
||||
|
||||
utils.InitGoMemLimit()
|
||||
// run mouse jiggler
|
||||
jiggler.GetJiggler().Run()
|
||||
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
|
||||
@@ -56,30 +65,56 @@ func run() {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
r := gin.New()
|
||||
r.Use(gin.Recovery())
|
||||
|
||||
if conf.Authentication == "disable" {
|
||||
r.Use(cors.AllowAll())
|
||||
}
|
||||
|
||||
router.Init(r)
|
||||
|
||||
httpAddr := fmt.Sprintf(":%d", conf.Port.Http)
|
||||
httpsAddr := fmt.Sprintf(":%d", conf.Port.Https)
|
||||
log.Printf("proto: %s, port: %d %d\n", conf.Proto, conf.Port.Http, 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" {
|
||||
r.Use(middleware.Tls())
|
||||
httpsPortStr := strconv.Itoa(conf.Port.Https)
|
||||
|
||||
go func() {
|
||||
if err := r.Run(httpAddr); err != nil {
|
||||
panic("start http server failed")
|
||||
err := r.RunTLS(utils.ListenAddr(conf.Host, httpsPortStr), conf.Cert.Crt, conf.Cert.Key)
|
||||
if err != nil {
|
||||
panic("start https server failed")
|
||||
}
|
||||
}()
|
||||
|
||||
if err := r.RunTLS(httpsAddr, conf.Cert.Crt, conf.Cert.Key); err != nil {
|
||||
panic("start https server failed")
|
||||
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")
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
94
server/middleware/loopback_http.go
Normal file
94
server/middleware/loopback_http.go
Normal 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()
|
||||
}
|
||||
@@ -4,3 +4,11 @@ type GetVersionRsp struct {
|
||||
Current string `json:"current"`
|
||||
Latest string `json:"latest"`
|
||||
}
|
||||
|
||||
type GetPreviewRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type SetPreviewReq struct {
|
||||
Enable bool `validate:"omitempty"`
|
||||
}
|
||||
|
||||
@@ -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"`
|
||||
}
|
||||
|
||||
39
server/proto/hid.go
Normal file
39
server/proto/hid.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package proto
|
||||
|
||||
type GetHidModeRsp struct {
|
||||
Mode string `json:"mode"` // normal or hid-only
|
||||
}
|
||||
|
||||
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,28 +12,41 @@ type DeleteMacReq struct {
|
||||
Mac string `form:"mac" 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 SetMacNameReq struct {
|
||||
Mac string `form:"mac" validate:"required"`
|
||||
Name string `form:"name" validate:"required"`
|
||||
}
|
||||
|
||||
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 `valid:"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"`
|
||||
}
|
||||
|
||||
@@ -16,3 +16,7 @@ type GetMountedImageRsp struct {
|
||||
type GetCdRomRsp struct {
|
||||
Cdrom int64 `json:"cdrom"`
|
||||
}
|
||||
|
||||
type DeleteImageReq struct {
|
||||
File string `json:"file" validate:"required"`
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package proto
|
||||
|
||||
type GetFrameDetectRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
type UpdateFrameDetectReq struct {
|
||||
Enabled bool `validate:"omitempty"`
|
||||
}
|
||||
|
||||
type UpdateFrameDetectRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
type StopFrameDetectReq struct {
|
||||
Duration int `validate:"omitempty"`
|
||||
}
|
||||
|
||||
22
server/proto/tailscale.go
Normal file
22
server/proto/tailscale.go
Normal 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"`
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
package proto
|
||||
|
||||
type IP struct {
|
||||
Name string `json:"name"`
|
||||
Addr string `json:"addr"`
|
||||
Version string `json:"version"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type GetInfoRsp struct {
|
||||
Ip string `json:"ip"`
|
||||
IPs []IP `json:"ips"`
|
||||
Mdns string `json:"mdns"`
|
||||
Image string `json:"image"`
|
||||
Application string `json:"application"`
|
||||
@@ -48,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"`
|
||||
}
|
||||
|
||||
@@ -62,8 +79,8 @@ type UpdateVirtualDeviceRsp struct {
|
||||
}
|
||||
|
||||
type SetMemoryLimitReq struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Limit int64 `json:"limit"`
|
||||
Enabled bool `validate:"omitempty"`
|
||||
Limit int64 `validate:"omitempty"`
|
||||
}
|
||||
|
||||
type GetMemoryLimitRsp struct {
|
||||
@@ -72,7 +89,7 @@ type GetMemoryLimitRsp struct {
|
||||
}
|
||||
|
||||
type SetOledReq struct {
|
||||
Sleep int `json:"sleep"`
|
||||
Sleep int `validate:"omitempty"`
|
||||
}
|
||||
|
||||
type GetOLEDRsp struct {
|
||||
@@ -80,10 +97,52 @@ type GetOLEDRsp struct {
|
||||
Sleep int `json:"sleep"`
|
||||
}
|
||||
|
||||
type GetGetHdmiStateRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type GetSSHStateRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type GetSwapRsp struct {
|
||||
Size int64 `json:"size"` // unit: MB
|
||||
}
|
||||
|
||||
type SetSwapReq struct {
|
||||
Size int64 `validate:"omitempty"` // unit: MB
|
||||
}
|
||||
|
||||
type GetMouseJigglerRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
|
||||
type SetMouseJigglerReq struct {
|
||||
Enabled bool `validate:"omitempty"`
|
||||
Mode string `validate:"omitempty"`
|
||||
}
|
||||
|
||||
type GetMdnsStateRsp struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type SetHostnameReq struct {
|
||||
Hostname string `validate:"required"`
|
||||
}
|
||||
|
||||
type GetHostnameRsp struct {
|
||||
Hostname string `json:"hostname"`
|
||||
}
|
||||
|
||||
type SetWebTitleReq struct {
|
||||
Title string `validate:"omitempty"`
|
||||
}
|
||||
|
||||
type GetWebTitleRsp struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
type SetTlsReq struct {
|
||||
Enabled bool `validate:"omitempty"`
|
||||
}
|
||||
|
||||
@@ -11,6 +11,10 @@ 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
|
||||
}
|
||||
|
||||
@@ -14,4 +14,5 @@ func downloadRouter(r *gin.Engine) {
|
||||
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/file", service.DownloadImageFile) // download image
|
||||
}
|
||||
|
||||
@@ -7,10 +7,29 @@ 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/reset", service.Reset) // reset hid
|
||||
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
|
||||
|
||||
localAPI.POST("/usb/recover", service.RecoverUSB)
|
||||
}
|
||||
|
||||
@@ -10,13 +10,20 @@ 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())
|
||||
|
||||
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
|
||||
api.GET("/network/wol/mac", service.GetMac) // get mac list
|
||||
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
|
||||
api.POST("/network/wol", service.WakeOnLAN) // wake on lan
|
||||
api.GET("/network/wol/mac", service.GetMac) // get mac list
|
||||
api.DELETE("/network/wol/mac", service.DeleteMac) // delete mac
|
||||
api.POST("/network/wol/mac/name", service.SetMacName) // set mac name
|
||||
|
||||
api.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
|
||||
}
|
||||
|
||||
64
server/router/picoclaw.go
Normal file
64
server/router/picoclaw.go
Normal file
@@ -0,0 +1,64 @@
|
||||
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.NewService()
|
||||
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)
|
||||
}
|
||||
@@ -36,7 +36,14 @@ func server(r *gin.Engine) {
|
||||
storageRouter(r)
|
||||
networkRouter(r)
|
||||
hidRouter(r)
|
||||
picoclawRouter(r)
|
||||
wsRouter(r)
|
||||
downloadRouter(r)
|
||||
extensionsRouter(r)
|
||||
}
|
||||
|
||||
func LoopbackHTTPAllowedPaths() []string {
|
||||
paths := PicoclawLoopbackHTTPAllowedPaths()
|
||||
paths = append(paths, HIDLoopbackHTTPAllowedPaths()...)
|
||||
return paths
|
||||
}
|
||||
|
||||
@@ -15,4 +15,5 @@ func storageRouter(r *gin.Engine) {
|
||||
api.GET("/storage/image/mounted", service.GetMountedImage) // get mounted image
|
||||
api.POST("/storage/image/mount", service.MountImage) // mount image
|
||||
api.GET("/storage/cdrom", service.GetCdRom) // get CD-ROM flag
|
||||
api.POST("/storage/image/delete", service.DeleteImage) // delete image
|
||||
}
|
||||
|
||||
@@ -2,8 +2,9 @@ package router
|
||||
|
||||
import (
|
||||
"NanoKVM-Server/middleware"
|
||||
"NanoKVM-Server/service/stream/h264"
|
||||
"NanoKVM-Server/service/stream/direct"
|
||||
"NanoKVM-Server/service/stream/mjpeg"
|
||||
"NanoKVM-Server/service/stream/webrtc"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -12,9 +13,9 @@ func streamRouter(r *gin.Engine) {
|
||||
api := r.Group("/api").Use(middleware.CheckToken())
|
||||
|
||||
api.GET("/stream/mjpeg", mjpeg.Connect) // mjpeg stream
|
||||
api.GET("/stream/mjpeg/detect", mjpeg.GetFrameDetect) // get frame detect state
|
||||
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect state
|
||||
api.POST("/stream/mjpeg/detect", mjpeg.UpdateFrameDetect) // update frame detect
|
||||
api.POST("/stream/mjpeg/detect/stop", mjpeg.StopFrameDetect) // temporary stop frame detect
|
||||
|
||||
api.GET("/stream/h264", h264.Connect) // h264 stream
|
||||
api.GET("/stream/h264", webrtc.Connect) // h264 stream (webrtc)
|
||||
api.GET("/stream/h264/direct", direct.Connect) // h264 stream (http)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
func vmRouter(r *gin.Engine) {
|
||||
service := vm.NewService()
|
||||
|
||||
api := r.Group("/api").Use(middleware.CheckToken())
|
||||
|
||||
api.GET("/vm/info", service.GetInfo) // get device information
|
||||
@@ -34,15 +35,38 @@ func vmRouter(r *gin.Engine) {
|
||||
api.GET("/vm/oled", service.GetOLED) // get OLED configuration
|
||||
api.POST("/vm/oled", service.SetOLED) // set OLED configuration
|
||||
|
||||
api.POST("/vm/hdmi/reset", service.ResetHdmi) // reset hdmi (pcie only)
|
||||
// Only supported by PCIe version
|
||||
api.GET("/vm/hdmi", service.GetHdmiState) // get HDMI state
|
||||
api.POST("/vm/hdmi/reset", service.ResetHdmi) // reset hdmi
|
||||
api.POST("/vm/hdmi/enable", service.EnableHdmi) // enable hdmi
|
||||
api.POST("/vm/hdmi/disable", service.DisableHdmi) // disable hdmi
|
||||
|
||||
api.GET("/vm/ssh", service.GetSSHState) // get SSH state
|
||||
api.POST("/vm/ssh/enable", service.EnableSSH) // enable SSH
|
||||
api.POST("/vm/ssh/disable", service.DisableSSH) // disable SSH
|
||||
|
||||
api.GET("/vm/swap", service.GetSwap) // get swap file size
|
||||
api.POST("/vm/swap", service.SetSwap) // set swap file size
|
||||
|
||||
api.GET("/vm/mouse-jiggler", service.GetMouseJiggler) // get mouse jiggler
|
||||
api.POST("/vm/mouse-jiggler/", service.SetMouseJiggler) // set mouse jiggler
|
||||
|
||||
api.GET("/vm/hostname", service.GetHostname) // Get Hostname
|
||||
api.POST("/vm/hostname", service.SetHostname) // Set Hostname
|
||||
|
||||
api.GET("/vm/web-title", service.GetWebTitle) // Get web title
|
||||
api.POST("/vm/web-title", service.SetWebTitle) // Set web title
|
||||
|
||||
api.GET("/vm/mdns", service.GetMdnsState) // get mDNS state
|
||||
api.POST("/vm/mdns/enable", service.EnableMdns) // enable mDNS
|
||||
api.POST("/vm/mdns/disable", service.DisableMdns) // disable mDNS
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
76
server/service/application/install.go
Normal file
76
server/service/application/install.go
Normal 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
|
||||
}
|
||||
60
server/service/application/preview.go
Normal file
60
server/service/application/preview.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"NanoKVM-Server/proto"
|
||||
"os"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
PreviewUpdatesFlag = "/etc/kvm/preview_updates"
|
||||
)
|
||||
|
||||
func (s *Service) GetPreview(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
isEnabled := isPreviewEnabled()
|
||||
|
||||
rsp.OkRspWithData(c, &proto.GetPreviewRsp{
|
||||
Enabled: isEnabled,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) SetPreview(c *gin.Context) {
|
||||
var req proto.SetPreviewReq
|
||||
var rsp proto.Response
|
||||
|
||||
if err := proto.ParseFormRequest(c, &req); err != nil {
|
||||
rsp.ErrRsp(c, -1, "invalid arguments")
|
||||
return
|
||||
}
|
||||
|
||||
if req.Enable == isPreviewEnabled() {
|
||||
rsp.OkRsp(c)
|
||||
return
|
||||
}
|
||||
|
||||
if req.Enable {
|
||||
if err := os.WriteFile(PreviewUpdatesFlag, []byte("1"), 0o644); err != nil {
|
||||
log.Errorf("failed to write %s: %s", PreviewUpdatesFlag, err)
|
||||
rsp.ErrRsp(c, -2, "enable failed")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
if err := os.Remove(PreviewUpdatesFlag); err != nil {
|
||||
log.Errorf("failed to remove %s: %s", PreviewUpdatesFlag, err)
|
||||
rsp.ErrRsp(c, -3, "disable failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("set preview updates state: %t", req.Enable)
|
||||
}
|
||||
|
||||
func isPreviewEnabled() bool {
|
||||
_, err := os.Stat(PreviewUpdatesFlag)
|
||||
return err == nil
|
||||
}
|
||||
84
server/service/application/progress_writer.go
Normal file
84
server/service/application/progress_writer.go
Normal 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)
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
package application
|
||||
|
||||
const (
|
||||
BaseURL = "https://cdn.sipeed.com/nanokvm"
|
||||
StableURL = "https://cdn.sipeed.com/nanokvm"
|
||||
PreviewURL = "https://cdn.sipeed.com/nanokvm/preview"
|
||||
|
||||
AppDir = "/kvmapp"
|
||||
BackupDir = "/root/old"
|
||||
|
||||
@@ -3,13 +3,11 @@ package application
|
||||
import (
|
||||
"crypto/sha512"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -23,42 +21,15 @@ const (
|
||||
maxTries = 3
|
||||
)
|
||||
|
||||
type Latest struct {
|
||||
Version string `json:"version"`
|
||||
Name string `json:"name"`
|
||||
Sha512 string `json:"sha512"`
|
||||
Size uint `json:"size"`
|
||||
}
|
||||
|
||||
func (s *Service) GetVersion(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
// current version
|
||||
currentVersion := "1.0.0"
|
||||
|
||||
versionFile := fmt.Sprintf("%s/version", AppDir)
|
||||
if version, err := os.ReadFile(versionFile); err == nil {
|
||||
currentVersion = strings.ReplaceAll(string(version), "\n", "")
|
||||
}
|
||||
|
||||
log.Debugf("current version: %s", currentVersion)
|
||||
|
||||
// latest version
|
||||
latest, err := getLatest()
|
||||
if err != nil {
|
||||
rsp.ErrRsp(c, -1, "get latest version failed")
|
||||
return
|
||||
}
|
||||
|
||||
rsp.OkRspWithData(c, &proto.GetVersionRsp{
|
||||
Current: currentVersion,
|
||||
Latest: latest.Version,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) Update(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
if !acquireUpdateLock() {
|
||||
rsp.ErrRsp(c, -1, "update already in progress")
|
||||
return
|
||||
}
|
||||
defer releaseUpdateLock()
|
||||
|
||||
if err := update(); err != nil {
|
||||
rsp.ErrRsp(c, -1, fmt.Sprintf("update failed: %s", err))
|
||||
return
|
||||
@@ -87,10 +58,8 @@ func update() error {
|
||||
}
|
||||
|
||||
// download
|
||||
url := fmt.Sprintf("%s/%s", BaseURL, latest.Name)
|
||||
target := fmt.Sprintf("%s/%s", CacheDir, latest.Name)
|
||||
|
||||
if err := download(url, target); err != nil {
|
||||
if err := download(latest.Url, target); err != nil {
|
||||
log.Errorf("download app failed: %s", err)
|
||||
return err
|
||||
}
|
||||
@@ -101,78 +70,20 @@ 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
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func getLatest() (*Latest, error) {
|
||||
url := fmt.Sprintf("%s/latest.json?now=%d", BaseURL, time.Now().Unix())
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Debugf("failed to request version: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorf("failed to read response: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Errorf("server responded with status code: %d", resp.StatusCode)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var latest Latest
|
||||
if err := json.Unmarshal(body, &latest); err != nil {
|
||||
log.Errorf("failed to unmarshal response: %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
log.Debugf("get application latest version: %s", latest.Version)
|
||||
return &latest, nil
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
176
server/service/application/update_offline.go
Normal file
176
server/service/application/update_offline.go
Normal file
@@ -0,0 +1,176 @@
|
||||
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 := checkDownloadInProgress(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
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 checkDownloadInProgress() error {
|
||||
if _, err := os.Stat(sentinelPath); err == nil {
|
||||
log.Debug("Download in progress")
|
||||
return fmt.Errorf("download already in progress")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createSentinelFile() error {
|
||||
if err := os.WriteFile(sentinelPath, []byte("downloading"), sentinelPermission); err != nil {
|
||||
log.Errorf("Failed to create sentinel file: %v", err)
|
||||
return fmt.Errorf("failed to create 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)
|
||||
}
|
||||
90
server/service/application/version.go
Normal file
90
server/service/application/version.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"NanoKVM-Server/proto"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Latest struct {
|
||||
Version string `json:"version"`
|
||||
Name string `json:"name"`
|
||||
Sha512 string `json:"sha512"`
|
||||
Size uint `json:"size"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
func (s *Service) GetVersion(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
// current version
|
||||
currentVersion := "1.0.0"
|
||||
|
||||
versionFile := fmt.Sprintf("%s/version", AppDir)
|
||||
if version, err := os.ReadFile(versionFile); err == nil {
|
||||
currentVersion = strings.ReplaceAll(string(version), "\n", "")
|
||||
}
|
||||
|
||||
log.Debugf("current version: %s", currentVersion)
|
||||
|
||||
// latest version
|
||||
latestVersion := ""
|
||||
latest, err := getLatest()
|
||||
if err == nil && latest != nil {
|
||||
latestVersion = latest.Version
|
||||
}
|
||||
|
||||
rsp.OkRspWithData(c, &proto.GetVersionRsp{
|
||||
Current: currentVersion,
|
||||
Latest: latestVersion,
|
||||
})
|
||||
}
|
||||
|
||||
func getLatest() (*Latest, error) {
|
||||
baseURL := StableURL
|
||||
if isPreviewEnabled() {
|
||||
baseURL = PreviewURL
|
||||
}
|
||||
|
||||
url := fmt.Sprintf("%s/latest.json?now=%d", baseURL, time.Now().Unix())
|
||||
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Debugf("failed to request version: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
_ = resp.Body.Close()
|
||||
}()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Errorf("failed to read response: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Errorf("server responded with status code: %d", resp.StatusCode)
|
||||
return nil, fmt.Errorf("status code %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var latest Latest
|
||||
if err := json.Unmarshal(body, &latest); err != nil {
|
||||
log.Errorf("failed to unmarshal response: %s", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
latest.Url = fmt.Sprintf("%s/%s", baseURL, latest.Name)
|
||||
|
||||
log.Debugf("get application latest version: %s", latest.Version)
|
||||
return &latest, nil
|
||||
}
|
||||
147
server/service/auth/brute_force.go
Normal file
147
server/service/auth/brute_force.go
Normal 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)
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"NanoKVM-Server/config"
|
||||
"NanoKVM-Server/middleware"
|
||||
"NanoKVM-Server/proto"
|
||||
@@ -22,18 +24,36 @@ 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")
|
||||
return
|
||||
}
|
||||
|
||||
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)
|
||||
rsp.ErrRsp(c, -3, "generate token failed")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
type Service struct{}
|
||||
@@ -51,6 +52,28 @@ func (s *Service) ImageEnabled(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func isISO9660(path string) (bool, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// ISO-9660 Magic "CD001" bei Offset 32769
|
||||
_, err = f.Seek(0x8001, io.SeekStart)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
buf := make([]byte, 5)
|
||||
_, err = io.ReadFull(f, buf)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return string(buf) == "CD001", nil
|
||||
}
|
||||
|
||||
func (s *Service) StatusImage(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
@@ -93,6 +116,170 @@ func (s *Service) StatusImage(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) DownloadImageFile(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
log.Debug("DownloadImage")
|
||||
|
||||
// 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("start"), 0644)
|
||||
if err != nil {
|
||||
log.Error("Failed to create sentinel file")
|
||||
rsp.ErrRsp(c, -1, "failed to create sentinel file")
|
||||
return
|
||||
}
|
||||
|
||||
// Multipart Reader direkt nutzen (keine FormFile!)
|
||||
reader, err := c.Request.MultipartReader()
|
||||
if err != nil {
|
||||
log.Error("invalid multipart data")
|
||||
rsp.ErrRsp(c, -1, "invalid multipart data")
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
var lw *loggingWriter
|
||||
|
||||
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")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
if part.FormName() != "file" {
|
||||
continue
|
||||
}
|
||||
|
||||
filename := part.FileName()
|
||||
if filename == "" {
|
||||
log.Error("no filename")
|
||||
rsp.ErrRsp(c, -1, "no filename")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
filename = filepath.Base(filename)
|
||||
|
||||
if filename != part.FileName() {
|
||||
log.Warn("path detected in filename")
|
||||
rsp.ErrRsp(c, -1, "invalid filename")
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
if strings.Contains(filename, "..") {
|
||||
log.Warn("path traversal attempt")
|
||||
rsp.ErrRsp(c, -1, "invalid filename")
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
if !strings.HasSuffix(strings.ToLower(filename), ".iso") {
|
||||
rsp.ErrRsp(c, -1, "only .iso files allowed")
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
valid := regexp.MustCompile(`^[a-zA-Z0-9._-]+$`)
|
||||
if !valid.MatchString(filename) {
|
||||
rsp.ErrRsp(c, -1, "invalid filename")
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(sentinelPath)
|
||||
if err != nil {
|
||||
log.Error("Read failed")
|
||||
rsp.ErrRsp(c, -1, "Read failed")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
outPath := "/data/" + filename
|
||||
out, err := os.Create(outPath)
|
||||
if err != nil {
|
||||
log.Error("cannot create file")
|
||||
rsp.ErrRsp(c, -1, "cannot create file")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if strings.Contains(string(data), "start") {
|
||||
err = os.WriteFile(sentinelPath, []byte(filename), 0644)
|
||||
if err != nil {
|
||||
log.Error("Failed to create sentinel file")
|
||||
rsp.ErrRsp(c, -1, "failed to create sentinel file")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(outPath)
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
lw = &loggingWriter{writer: out, totalSize: c.Request.ContentLength}
|
||||
lw.startTicker()
|
||||
} else {
|
||||
if !strings.Contains(string(data), filename) {
|
||||
log.Error("failed")
|
||||
rsp.ErrRsp(c, -1, "failed")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(outPath)
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Direkt streamen → kein RAM-Bedarf außer kleinem Buffer
|
||||
_, err = io.Copy(lw, part)
|
||||
if err != nil {
|
||||
log.Error("write failed")
|
||||
rsp.ErrRsp(c, -1, "write failed")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(outPath)
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
ok, err := isISO9660(outPath)
|
||||
if err != nil || !ok {
|
||||
rsp.ErrRsp(c, -1, "file is not a valid ISO image")
|
||||
lw.stopTicker()
|
||||
defer os.Remove(outPath)
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
lw.stopTicker()
|
||||
|
||||
rsp.OkRspWithData(c, &proto.StatusImageRsp{
|
||||
Status: "idle",
|
||||
File: "",
|
||||
Percentage: "",
|
||||
})
|
||||
|
||||
defer os.Remove(sentinelPath)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Service) DownloadImage(c *gin.Context) {
|
||||
var req proto.MountImageReq
|
||||
var rsp proto.Response
|
||||
|
||||
@@ -69,8 +69,6 @@ func (c *Cli) Stop() error {
|
||||
return err
|
||||
}
|
||||
|
||||
_ = os.Remove(ConfigPath)
|
||||
|
||||
return os.Remove(ScriptPath)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,17 +15,18 @@ type Service struct{}
|
||||
const (
|
||||
TailscalePath = "/usr/bin/tailscale"
|
||||
TailscaledPath = "/usr/sbin/tailscaled"
|
||||
ConfigPath = "etc/sysctl.d/99-tailscale.conf"
|
||||
|
||||
GoMemLimit int64 = 75
|
||||
)
|
||||
|
||||
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 {
|
||||
@@ -40,6 +41,8 @@ func (s *Service) Install(c *gin.Context) {
|
||||
rsp.ErrRsp(c, -1, "install failed")
|
||||
return
|
||||
}
|
||||
|
||||
_ = NewCli().Start()
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
@@ -54,7 +57,6 @@ func (s *Service) Uninstall(c *gin.Context) {
|
||||
|
||||
_ = os.Remove(TailscalePath)
|
||||
_ = os.Remove(TailscaledPath)
|
||||
_ = os.Remove(ConfigPath)
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("uninstall tailscale successfully")
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
)
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
var (
|
||||
hid *Hid
|
||||
hidOnce sync.Once
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type Hid struct {
|
||||
@@ -18,6 +20,42 @@ type Hid struct {
|
||||
mouseMutex sync.Mutex
|
||||
}
|
||||
|
||||
const (
|
||||
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
|
||||
)
|
||||
|
||||
func GetHid() *Hid {
|
||||
hidOnce.Do(func() {
|
||||
hid = &Hid{}
|
||||
})
|
||||
return hid
|
||||
}
|
||||
|
||||
func (h *Hid) Lock() {
|
||||
h.kbMutex.Lock()
|
||||
h.mouseMutex.Lock()
|
||||
@@ -28,9 +66,238 @@ func (h *Hid) Unlock() {
|
||||
h.mouseMutex.Unlock()
|
||||
}
|
||||
|
||||
func GetHid() *Hid {
|
||||
hidOnce.Do(func() {
|
||||
hid = &Hid{}
|
||||
})
|
||||
return hid
|
||||
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) 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)
|
||||
}
|
||||
}
|
||||
|
||||
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() {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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() {
|
||||
h.kbMutex.Lock()
|
||||
defer h.kbMutex.Unlock()
|
||||
h.mouseMutex.Lock()
|
||||
defer h.mouseMutex.Unlock()
|
||||
|
||||
h.OpenNoLock()
|
||||
}
|
||||
|
||||
func (h *Hid) Close() {
|
||||
h.kbMutex.Lock()
|
||||
defer h.kbMutex.Unlock()
|
||||
h.mouseMutex.Lock()
|
||||
defer h.mouseMutex.Unlock()
|
||||
|
||||
h.CloseNoLock()
|
||||
}
|
||||
|
||||
func (h *Hid) WriteHid0(data []byte) {
|
||||
h.writeHIDReport(h.keyboardDevice(HID0), data)
|
||||
}
|
||||
|
||||
func (h *Hid) WriteHid1(data []byte) {
|
||||
h.writeHIDReport(h.relativeMouseDevice(HID1), data)
|
||||
}
|
||||
|
||||
func (h *Hid) WriteHid2(data []byte) {
|
||||
h.writeHIDReport(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
|
||||
}
|
||||
|
||||
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 {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,21 +1,50 @@
|
||||
package hid
|
||||
|
||||
func (h *Hid) Keyboard(queue <-chan []int) {
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (h *Hid) Keyboard(queue <-chan []byte) {
|
||||
h.keyboard(queue, HID0)
|
||||
}
|
||||
|
||||
func (h *Hid) keyboard(queue <-chan []byte, path string) {
|
||||
defer h.releaseKeyboard(path)
|
||||
|
||||
for event := range queue {
|
||||
h.kbMutex.Lock()
|
||||
h.writeKeyboard(event)
|
||||
h.kbMutex.Unlock()
|
||||
if len(event) != 8 {
|
||||
log.Debugf("invalid keyboard event: %v", event)
|
||||
continue
|
||||
}
|
||||
|
||||
if !h.writeHIDReport(h.keyboardDevice(path), event) {
|
||||
if dropped := drainHIDQueue(queue); dropped > 0 {
|
||||
log.Debugf("dropped %d stale keyboard HID reports after write failure", dropped)
|
||||
}
|
||||
h.releaseKeyboard(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) writeKeyboard(event []int) {
|
||||
code := byte(event[0])
|
||||
|
||||
var modifier byte = 0x00
|
||||
if code > 0 {
|
||||
modifier = byte(event[1]) | byte(event[2]) | byte(event[3]) | byte(event[4])
|
||||
}
|
||||
|
||||
data := []byte{modifier, 0x00, code, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
h.Write(h.g0, data)
|
||||
func (h *Hid) releaseKeyboard(path string) {
|
||||
h.writeHIDReport(h.keyboardDevice(path), keyboardReleaseReport())
|
||||
}
|
||||
|
||||
func keyboardReleaseReport() []byte {
|
||||
return []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
}
|
||||
|
||||
func drainHIDQueue(queue <-chan []byte) int {
|
||||
dropped := 0
|
||||
for {
|
||||
select {
|
||||
case _, ok := <-queue:
|
||||
if !ok {
|
||||
return dropped
|
||||
}
|
||||
dropped++
|
||||
default:
|
||||
return dropped
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
63
server/service/hid/leader_key.go
Normal file
63
server/service/hid/leader_key.go
Normal 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")
|
||||
}
|
||||
@@ -1,111 +1,71 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
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) {
|
||||
h.mouse(queue, HID1, HID2)
|
||||
}
|
||||
|
||||
func (h *Hid) Mouse(queue <-chan []int) {
|
||||
func (h *Hid) mouse(queue <-chan []byte, relativePath string, absolutePath string) {
|
||||
defer h.releaseRelativeMouse(relativePath)
|
||||
|
||||
absoluteButtonsActive := false
|
||||
var absoluteReleaseReport []byte
|
||||
defer func() {
|
||||
if absoluteButtonsActive {
|
||||
h.releaseAbsoluteMouse(absolutePath, absoluteReleaseReport)
|
||||
}
|
||||
}()
|
||||
|
||||
for event := range queue {
|
||||
h.mouseMutex.Lock()
|
||||
|
||||
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)
|
||||
switch len(event) {
|
||||
case 4:
|
||||
if !h.writeHIDReport(h.relativeMouseDevice(relativePath), event) {
|
||||
if dropped := drainHIDQueue(queue); dropped > 0 {
|
||||
log.Debugf("dropped %d stale mouse HID reports after relative write failure", dropped)
|
||||
}
|
||||
h.releaseRelativeMouse(relativePath)
|
||||
}
|
||||
case 6:
|
||||
if !h.writeHIDReport(h.absoluteMouseDevice(absolutePath), event) {
|
||||
if dropped := drainHIDQueue(queue); dropped > 0 {
|
||||
log.Debugf("dropped %d stale mouse HID reports after absolute write failure", dropped)
|
||||
}
|
||||
if absoluteButtonsActive {
|
||||
if h.releaseAbsoluteMouse(absolutePath, absoluteReleaseReport) {
|
||||
absoluteButtonsActive = false
|
||||
}
|
||||
} else if event[0] != 0 {
|
||||
h.releaseAbsoluteMouse(absolutePath, absoluteMouseReleaseReport(event))
|
||||
}
|
||||
continue
|
||||
}
|
||||
absoluteReleaseReport = absoluteMouseReleaseReport(event)
|
||||
absoluteButtonsActive = event[0] != 0
|
||||
default:
|
||||
log.Debugf("invalid mouse event: %+v", event)
|
||||
log.Debugf("invalid mouse event: %v", event)
|
||||
}
|
||||
|
||||
h.mouseMutex.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) mouseDown(event []int) {
|
||||
button := byte(event[1])
|
||||
func (h *Hid) releaseRelativeMouse(path string) {
|
||||
h.writeHIDReport(h.relativeMouseDevice(path), relativeMouseReleaseReport())
|
||||
}
|
||||
|
||||
if _, ok := mouseButtonMap[button]; !ok {
|
||||
log.Debugf("invalid mouse button: %+v", event)
|
||||
return
|
||||
func (h *Hid) releaseAbsoluteMouse(path string, report []byte) bool {
|
||||
return h.writeHIDReport(h.absoluteMouseDevice(path), report)
|
||||
}
|
||||
|
||||
func relativeMouseReleaseReport() []byte {
|
||||
return []byte{0x00, 0x00, 0x00, 0x00}
|
||||
}
|
||||
|
||||
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.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) mouseUp() {
|
||||
data := []byte{0, 0, 0, 0}
|
||||
h.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) mouseScroll(event []int) {
|
||||
direction := 0x01
|
||||
if event[3] > 0 {
|
||||
direction = -0x1
|
||||
}
|
||||
|
||||
data := []byte{0, 0, 0, byte(direction)}
|
||||
h.writeWithTimeout(h.g1, 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.writeWithTimeout(h.g2, data)
|
||||
}
|
||||
|
||||
func (h *Hid) mouseMoveRelative(event []int) {
|
||||
data := []byte{byte(event[1]), byte(event[2]), byte(event[3]), 0}
|
||||
h.writeWithTimeout(h.g1, data)
|
||||
}
|
||||
|
||||
func (h *Hid) writeWithTimeout(file *os.File, data []byte) {
|
||||
deadline := time.Now().Add(8 * time.Millisecond)
|
||||
_ = file.SetWriteDeadline(deadline)
|
||||
|
||||
_, err := file.Write(data)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, os.ErrClosed):
|
||||
log.Debugf("hid already closed, reopen it...")
|
||||
h.OpenNoLock()
|
||||
case errors.Is(err, os.ErrDeadlineExceeded):
|
||||
log.Debugf("write to hid timeout")
|
||||
default:
|
||||
log.Errorf("write to hid failed: %s", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Debugf("write to hid: %+v", data)
|
||||
return report
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (h *Hid) OpenNoLock() {
|
||||
var err error
|
||||
h.CloseNoLock()
|
||||
|
||||
h.g0, err = os.OpenFile("/dev/hidg0", os.O_WRONLY, 0o666)
|
||||
if err != nil {
|
||||
log.Errorf("open /dev/hidg0 failed: %s", err)
|
||||
}
|
||||
|
||||
h.g1, err = os.OpenFile("/dev/hidg1", os.O_WRONLY, 0o666)
|
||||
if err != nil {
|
||||
log.Errorf("open /dev/hidg1 failed: %s", err)
|
||||
}
|
||||
|
||||
h.g2, err = os.OpenFile("/dev/hidg2", os.O_WRONLY, 0o666)
|
||||
if err != nil {
|
||||
log.Errorf("open /dev/hidg2 failed: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hid) Open() {
|
||||
h.kbMutex.Lock()
|
||||
defer h.kbMutex.Unlock()
|
||||
h.mouseMutex.Lock()
|
||||
defer h.mouseMutex.Unlock()
|
||||
|
||||
h.CloseNoLock()
|
||||
|
||||
h.OpenNoLock()
|
||||
}
|
||||
|
||||
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) Close() {
|
||||
h.kbMutex.Lock()
|
||||
defer h.kbMutex.Unlock()
|
||||
h.mouseMutex.Lock()
|
||||
defer h.mouseMutex.Unlock()
|
||||
|
||||
h.CloseNoLock()
|
||||
}
|
||||
|
||||
func (h *Hid) Write(file *os.File, data []byte) {
|
||||
_, err := file.Write(data)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrClosed) {
|
||||
log.Debugf("hid already closed, reopen it...")
|
||||
h.OpenNoLock()
|
||||
} else {
|
||||
log.Errorf("write to hid failed: %s", err)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
log.Debugf("write to hid: %+v", data)
|
||||
}
|
||||
@@ -16,6 +16,150 @@ type Char struct {
|
||||
|
||||
type PasteReq struct {
|
||||
Content string `form:"content" validate:"required"`
|
||||
Langue string `form:"langue"`
|
||||
}
|
||||
|
||||
func LangueSwitch(base map[rune]Char, lang string) map[rune]Char {
|
||||
// if no language is specified → return base map
|
||||
if lang == "" {
|
||||
return base
|
||||
}
|
||||
|
||||
// always create a copy of the base map
|
||||
m := copyMap(base)
|
||||
|
||||
switch lang {
|
||||
case "de":
|
||||
// swap Y
|
||||
m['y'] = Char{0, 29}
|
||||
m['Y'] = Char{2, 29}
|
||||
|
||||
// swap Z
|
||||
m['z'] = Char{0, 28}
|
||||
m['Z'] = Char{2, 28}
|
||||
|
||||
// add German special characters or remap them
|
||||
m['\u00E4'] = Char{0, 52} // ä
|
||||
m['\u00C4'] = Char{2, 52} // Ä
|
||||
m['\u00F6'] = Char{0, 51} // ö
|
||||
m['\u00D6'] = Char{2, 51} // Ö
|
||||
m['\u00FC'] = Char{0, 47} // ü
|
||||
m['\u00DC'] = Char{2, 47} // Ü
|
||||
m['\u00DF'] = Char{0, 45} // ß
|
||||
|
||||
// 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
|
||||
m[')'] = Char{2, 38} // Shift + 9
|
||||
m['`'] = Char{2, 46} // Grave Accent / Backtick
|
||||
m['"'] = Char{2, 31} // Shift + 2
|
||||
m['?'] = Char{2, 45} // Shift + ß
|
||||
m['{'] = Char{0x40, 36} // ALt Gr + 7
|
||||
m['['] = Char{0x40, 37} // ALt Gr + 8
|
||||
m[']'] = Char{0x40, 38} // ALt Gr + 6
|
||||
m['}'] = Char{0x40, 39} // ALt Gr + 0
|
||||
m['\\'] = Char{0x40, 45} // ALt Gr + ß
|
||||
m['@'] = Char{0x40, 20} // ALt Gr + q
|
||||
m['+'] = Char{0, 48} // Shift + +
|
||||
m['*'] = Char{2, 48} // Shift + +
|
||||
m['~'] = Char{0x40, 48} // Shift + +
|
||||
m['#'] = Char{0, 49} // Shift + #
|
||||
m['\''] = Char{2, 49} // Shift + #
|
||||
m['<'] = Char{0, 100} // Shift + <
|
||||
m['>'] = Char{2, 100} // Shift + <
|
||||
m['|'] = Char{0x40, 100} // ALt Gr + <
|
||||
m[';'] = Char{2, 54} // Shift + ,
|
||||
m[':'] = Char{2, 55} // Shift + .
|
||||
m['-'] = Char{0, 56} // Shift + -
|
||||
m['_'] = Char{2, 56} // Shift + -
|
||||
|
||||
// new special characters
|
||||
m['\u00B4'] = Char{0, 46} // ´
|
||||
m['\u00B0'] = Char{2, 53} // °
|
||||
m['\u00A7'] = Char{2, 32} // §
|
||||
m['\u20AC'] = Char{0x40, 8} // €
|
||||
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
|
||||
}
|
||||
|
||||
func (s *Service) Paste(c *gin.Context) {
|
||||
@@ -28,145 +172,105 @@ func (s *Service) Paste(c *gin.Context) {
|
||||
}
|
||||
|
||||
if len(req.Content) > 1024 {
|
||||
rsp.ErrRsp(c, -2, "")
|
||||
rsp.ErrRsp(c, -2, "content too long")
|
||||
return
|
||||
}
|
||||
|
||||
s.hid.kbMutex.Lock()
|
||||
charMapLocal := LangueSwitch(charMap, req.Langue)
|
||||
|
||||
keyUp := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
|
||||
for _, char := range req.Content {
|
||||
key, ok := charMap[char]
|
||||
key, ok := charMapLocal[char]
|
||||
if !ok {
|
||||
log.Debugf("unknown key %c", char)
|
||||
log.Debugf("unknown key '%c' (rune: %d)", char, char)
|
||||
continue
|
||||
}
|
||||
|
||||
keyDown := []byte{byte(key.Modifiers), 0x00, byte(key.Code), 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
keyUp := []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
|
||||
// only handle shift. Need to handle all modifiers?
|
||||
if key.Modifiers > 0 {
|
||||
keyShift := []byte{0x00, 0x00, byte(225), 0x00, 0x00, 0x00, 0x00, 0x00}
|
||||
s.hid.Write(s.hid.g0, keyShift)
|
||||
}
|
||||
|
||||
s.hid.Write(s.hid.g0, keyDown)
|
||||
s.hid.Write(s.hid.g0, keyUp)
|
||||
|
||||
if key.Modifiers > 0 {
|
||||
s.hid.Write(s.hid.g0, keyUp)
|
||||
}
|
||||
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
hid.WriteHid0(keyDown)
|
||||
hid.WriteHid0(keyUp)
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
}
|
||||
s.hid.kbMutex.Unlock()
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("hid paste success, total %d", len(req.Content))
|
||||
log.Debugf("hid paste success, total %d characters processed", len(req.Content))
|
||||
}
|
||||
|
||||
func copyMap(src map[rune]Char) map[rune]Char {
|
||||
dst := make(map[rune]Char, len(src))
|
||||
for k, v := range src {
|
||||
dst[k] = v
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
func GetCharMap(lang string) map[rune]Char {
|
||||
return LangueSwitch(charMap, lang)
|
||||
}
|
||||
|
||||
var charMap = map[rune]Char{
|
||||
97: {0, 4}, // a
|
||||
98: {0, 5}, // b
|
||||
99: {0, 6}, // c
|
||||
100: {0, 7}, // d
|
||||
101: {0, 8}, // e
|
||||
102: {0, 9}, // f
|
||||
103: {0, 10}, // g
|
||||
104: {0, 11}, // h
|
||||
105: {0, 12}, // i
|
||||
106: {0, 13}, // j
|
||||
107: {0, 14}, // k
|
||||
108: {0, 15}, // l
|
||||
109: {0, 16}, // m
|
||||
110: {0, 17}, // n
|
||||
111: {0, 18}, // o
|
||||
112: {0, 19}, // p
|
||||
113: {0, 20}, // q
|
||||
114: {0, 21}, // r
|
||||
115: {0, 22}, // s
|
||||
116: {0, 23}, // t
|
||||
117: {0, 24}, // u
|
||||
118: {0, 25}, // v
|
||||
119: {0, 26}, // w
|
||||
120: {0, 27}, // x
|
||||
121: {0, 28}, // y
|
||||
122: {0, 29}, // z
|
||||
// Lowercase letters
|
||||
'a': {0, 4}, 'b': {0, 5}, 'c': {0, 6}, 'd': {0, 7}, 'e': {0, 8},
|
||||
'f': {0, 9}, 'g': {0, 10}, 'h': {0, 11}, 'i': {0, 12}, 'j': {0, 13},
|
||||
'k': {0, 14}, 'l': {0, 15}, 'm': {0, 16}, 'n': {0, 17}, 'o': {0, 18},
|
||||
'p': {0, 19}, 'q': {0, 20}, 'r': {0, 21}, 's': {0, 22}, 't': {0, 23},
|
||||
'u': {0, 24}, 'v': {0, 25}, 'w': {0, 26}, 'x': {0, 27}, 'y': {0, 28},
|
||||
'z': {0, 29},
|
||||
|
||||
49: {0, 30}, // 1
|
||||
50: {0, 31}, // 2
|
||||
51: {0, 32}, // 3
|
||||
52: {0, 33}, // 4
|
||||
53: {0, 34}, // 5
|
||||
54: {0, 35}, // 6
|
||||
55: {0, 36}, // 7
|
||||
56: {0, 37}, // 8
|
||||
57: {0, 38}, // 9
|
||||
48: {0, 39}, // 0
|
||||
// Uppercase letters (Modifier 2 typically means Left Shift)
|
||||
'A': {2, 4}, 'B': {2, 5}, 'C': {2, 6}, 'D': {2, 7}, 'E': {2, 8},
|
||||
'F': {2, 9}, 'G': {2, 10}, 'H': {2, 11}, 'I': {2, 12}, 'J': {2, 13},
|
||||
'K': {2, 14}, 'L': {2, 15}, 'M': {2, 16}, 'N': {2, 17}, 'O': {2, 18},
|
||||
'P': {2, 19}, 'Q': {2, 20}, 'R': {2, 21}, 'S': {2, 22}, 'T': {2, 23},
|
||||
'U': {2, 24}, 'V': {2, 25}, 'W': {2, 26}, 'X': {2, 27}, 'Y': {2, 28},
|
||||
'Z': {2, 29},
|
||||
|
||||
10: {0, 40}, // Enter
|
||||
9: {0, 43}, // Tab
|
||||
32: {0, 44}, // Space
|
||||
45: {0, 45}, // -
|
||||
61: {0, 46}, // =
|
||||
91: {0, 47}, // [
|
||||
93: {0, 48}, // ]
|
||||
92: {0, 49}, // \
|
||||
// Numbers
|
||||
'1': {0, 30}, '2': {0, 31}, '3': {0, 32}, '4': {0, 33}, '5': {0, 34},
|
||||
'6': {0, 35}, '7': {0, 36}, '8': {0, 37}, '9': {0, 38}, '0': {0, 39},
|
||||
|
||||
59: {0, 51}, // ;
|
||||
39: {0, 52}, // '
|
||||
96: {0, 53}, // `
|
||||
44: {0, 54}, // ,
|
||||
46: {0, 55}, // .
|
||||
47: {0, 56}, // /
|
||||
// Shifted numbers / Symbols
|
||||
'!': {2, 30}, // Shift + 1
|
||||
'@': {2, 31}, // Shift + 2
|
||||
'#': {2, 32}, // Shift + 3
|
||||
'$': {2, 33}, // Shift + 4
|
||||
'%': {2, 34}, // Shift + 5
|
||||
'^': {2, 35}, // Shift + 6
|
||||
'&': {2, 36}, // Shift + 7
|
||||
'*': {2, 37}, // Shift + 8
|
||||
'(': {2, 38}, // Shift + 9
|
||||
')': {2, 39}, // Shift + 0
|
||||
|
||||
65: {2, 4}, // A
|
||||
66: {2, 5}, // B
|
||||
67: {2, 6}, // C
|
||||
68: {2, 7}, // D
|
||||
69: {2, 8}, // E
|
||||
70: {2, 9}, // F
|
||||
71: {2, 10}, // G
|
||||
72: {2, 11}, // H
|
||||
73: {2, 12}, // I
|
||||
74: {2, 13}, // J
|
||||
75: {2, 14}, // K
|
||||
76: {2, 15}, // L
|
||||
77: {2, 16}, // M
|
||||
78: {2, 17}, // N
|
||||
79: {2, 18}, // O
|
||||
80: {2, 19}, // P
|
||||
81: {2, 20}, // Q
|
||||
82: {2, 21}, // R
|
||||
83: {2, 22}, // S
|
||||
84: {2, 23}, // T
|
||||
85: {2, 24}, // U
|
||||
86: {2, 25}, // V
|
||||
87: {2, 26}, // W
|
||||
88: {2, 27}, // X
|
||||
89: {2, 28}, // Y
|
||||
90: {2, 29}, // Z
|
||||
// Other common characters
|
||||
'\n': {0, 40}, // Enter (Return)
|
||||
'\t': {0, 43}, // Tab
|
||||
' ': {0, 44}, // Space
|
||||
'-': {0, 45}, // Hyphen / Minus
|
||||
'=': {0, 46}, // Equals
|
||||
'[': {0, 47}, // Left Square Bracket
|
||||
']': {0, 48}, // Right Square Bracket
|
||||
'\\': {0, 49}, // Backslash
|
||||
|
||||
33: {2, 30}, // !
|
||||
64: {2, 31}, // @
|
||||
35: {2, 32}, // #
|
||||
36: {2, 33}, // $
|
||||
37: {2, 34}, // %
|
||||
94: {2, 35}, // ^
|
||||
38: {2, 36}, // &
|
||||
42: {2, 37}, // *
|
||||
40: {2, 38}, // (
|
||||
41: {2, 39}, // )
|
||||
';': {0, 51}, // Semicolon
|
||||
'\'': {0, 52}, // Apostrophe / Single Quote
|
||||
'`': {0, 53}, // Grave Accent / Backtick
|
||||
',': {0, 54}, // Comma
|
||||
'.': {0, 55}, // Period / Dot
|
||||
'/': {0, 56}, // Slash
|
||||
|
||||
95: {2, 45}, // _
|
||||
43: {2, 46}, // +
|
||||
123: {2, 47}, // {
|
||||
125: {2, 48}, // }
|
||||
124: {2, 49}, // |
|
||||
// Shifted symbols
|
||||
'_': {2, 45}, // Underscore (Shift + Hyphen)
|
||||
'+': {2, 46}, // Plus (Shift + Equals)
|
||||
'{': {2, 47}, // Left Curly Brace (Shift + Left Square Bracket)
|
||||
'}': {2, 48}, // Right Curly Brace (Shift + Right Square Bracket)
|
||||
'|': {2, 49}, // Pipe (Shift + Backslash)
|
||||
|
||||
58: {2, 51}, // :
|
||||
34: {2, 52}, // "
|
||||
126: {2, 53}, // ~
|
||||
60: {2, 54}, // <
|
||||
62: {2, 55}, // >
|
||||
63: {2, 56}, // ?
|
||||
':': {2, 51}, // Colon (Shift + Semicolon)
|
||||
'"': {2, 52}, // Double Quote (Shift + Apostrophe)
|
||||
'~': {2, 53}, // Tilde (Shift + Grave Accent)
|
||||
'<': {2, 54}, // Less Than (Shift + Comma)
|
||||
'>': {2, 55}, // Greater Than (Shift + Period)
|
||||
'?': {2, 56}, // Question Mark (Shift + Slash)
|
||||
}
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"NanoKVM-Server/proto"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (s *Service) Reset(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
// reset USB
|
||||
f, err := os.OpenFile("/sys/kernel/config/usb_gadget/g0/UDC", os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
log.Errorf("open /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "open usb gadget file failed")
|
||||
return
|
||||
}
|
||||
err = f.Truncate(0)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
log.Errorf("truncate /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "truncate usb gadget file failed")
|
||||
return
|
||||
}
|
||||
_, err = f.Seek(0, 0)
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
log.Errorf("seek to 0 failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "seek to 0 in usb gadget file failed")
|
||||
return
|
||||
}
|
||||
_, err = f.WriteString("\n")
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
log.Errorf("write to /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "write to usb gadget file failed")
|
||||
return
|
||||
}
|
||||
_ = f.Close()
|
||||
|
||||
time.Sleep(1 * time.Second)
|
||||
|
||||
devices, err := os.ReadDir("/sys/class/udc/")
|
||||
if err != nil {
|
||||
log.Errorf("read udc directory failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "read udc directory failed")
|
||||
return
|
||||
}
|
||||
|
||||
f, err = os.OpenFile("/sys/kernel/config/usb_gadget/g0/UDC", os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
log.Errorf("open /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "open usb gadget file failed")
|
||||
return
|
||||
}
|
||||
for _, device := range devices {
|
||||
_, err = f.WriteString(device.Name() + "\n")
|
||||
if err != nil {
|
||||
_ = f.Close()
|
||||
log.Errorf("write to /sys/kernel/config/usb_gadget/g0/UDC failed: %s", err)
|
||||
rsp.ErrRsp(c, -1, "write to usb gadget file failed")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
_ = f.Close()
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("reset hid success")
|
||||
}
|
||||
172
server/service/hid/shortcut.go
Normal file
172
server/service/hid/shortcut.go
Normal 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)
|
||||
}
|
||||
212
server/service/hid/status.go
Normal file
212
server/service/hid/status.go
Normal file
@@ -0,0 +1,212 @@
|
||||
package hid
|
||||
|
||||
import (
|
||||
"NanoKVM-Server/proto"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
ModeNormal = "normal"
|
||||
ModeHidOnly = "hid-only"
|
||||
ModeFlag = "/sys/kernel/config/usb_gadget/g0/bcdDevice"
|
||||
|
||||
ModeNormalScript = "/kvmapp/system/init.d/S03usbdev"
|
||||
ModeHidOnlyScript = "/kvmapp/system/init.d/S03usbhid"
|
||||
|
||||
USBDevScript = "/etc/init.d/S03usbdev"
|
||||
)
|
||||
|
||||
var modeMap = map[string]string{
|
||||
"0x0510": ModeNormal,
|
||||
"0x0623": ModeHidOnly,
|
||||
}
|
||||
|
||||
func (s *Service) GetHidMode(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
mode, err := getHidMode()
|
||||
if err != nil {
|
||||
rsp.ErrRsp(c, -1, "get HID mode failed")
|
||||
return
|
||||
}
|
||||
|
||||
rsp.OkRspWithData(c, &proto.GetHidModeRsp{
|
||||
Mode: mode,
|
||||
})
|
||||
log.Debugf("get hid mode: %s", mode)
|
||||
}
|
||||
|
||||
func (s *Service) SetHidMode(c *gin.Context) {
|
||||
var req proto.SetHidModeReq
|
||||
var rsp proto.Response
|
||||
|
||||
if err := proto.ParseFormRequest(c, &req); err != nil {
|
||||
rsp.ErrRsp(c, -1, "invalid arguments")
|
||||
return
|
||||
}
|
||||
if req.Mode != ModeNormal && req.Mode != ModeHidOnly {
|
||||
rsp.ErrRsp(c, -2, "invalid arguments")
|
||||
return
|
||||
}
|
||||
|
||||
if mode, _ := getHidMode(); req.Mode == mode {
|
||||
rsp.OkRsp(c)
|
||||
return
|
||||
}
|
||||
|
||||
h := GetHid()
|
||||
h.Lock()
|
||||
h.CloseNoLock()
|
||||
defer func() {
|
||||
h.OpenNoLock()
|
||||
h.Unlock()
|
||||
}()
|
||||
|
||||
srcScript := ModeNormalScript
|
||||
if req.Mode == ModeHidOnly {
|
||||
srcScript = ModeHidOnlyScript
|
||||
}
|
||||
|
||||
if err := copyModeFile(srcScript); err != nil {
|
||||
rsp.ErrRsp(c, -3, "operation failed")
|
||||
return
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
|
||||
log.Println("reboot system...")
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
_ = exec.Command("reboot").Run()
|
||||
}
|
||||
|
||||
func (s *Service) ResetHid(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
if err := ResetUSBPHY(); err != nil {
|
||||
log.Errorf("failed to reset hid: %v", err)
|
||||
rsp.ErrRsp(c, -1, "failed to reset hid")
|
||||
return
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
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)
|
||||
if err != nil {
|
||||
log.Errorf("failed to open %s: %s", srcScript, err)
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = srcFile.Close()
|
||||
}()
|
||||
|
||||
srcInfo, err := srcFile.Stat()
|
||||
if err != nil {
|
||||
log.Errorf("failed to get %s info: %s", srcScript, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// create and copy to temporary file
|
||||
tmpFile, err := os.CreateTemp("/etc/init.d/", ".S03usbdev-")
|
||||
if err != nil {
|
||||
log.Errorf("failed to create temp %s: %s", USBDevScript, err)
|
||||
return err
|
||||
}
|
||||
tmpPath := tmpFile.Name()
|
||||
defer func() {
|
||||
_ = os.Remove(tmpPath)
|
||||
}()
|
||||
log.Debugf("create temporary file: %s", tmpPath)
|
||||
|
||||
if err := tmpFile.Chmod(srcInfo.Mode()); err != nil {
|
||||
_ = tmpFile.Close()
|
||||
log.Errorf("failed to set %s mode: %s", tmpPath, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := io.Copy(tmpFile, srcFile); err != nil {
|
||||
_ = tmpFile.Close()
|
||||
log.Errorf("failed to copy %s: %s", srcScript, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tmpFile.Sync(); err != nil {
|
||||
_ = tmpFile.Close()
|
||||
log.Errorf("failed to sync %s: %s", tmpPath, err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tmpFile.Close(); err != nil {
|
||||
log.Errorf("failed to close %s: %s", tmpPath, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// replace the target file with the temporary file
|
||||
if err := os.Rename(tmpPath, USBDevScript); err != nil {
|
||||
log.Errorf("failed to rename %s: %s", tmpPath, err)
|
||||
return err
|
||||
}
|
||||
|
||||
log.Debugf("copy %s to %s successful", srcScript, USBDevScript)
|
||||
return nil
|
||||
}
|
||||
|
||||
func getHidMode() (string, error) {
|
||||
data, err := os.ReadFile(ModeFlag)
|
||||
if err != nil {
|
||||
log.Errorf("failed to read %s: %s", ModeFlag, err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
key := strings.TrimSpace(string(data))
|
||||
mode, ok := modeMap[key]
|
||||
if !ok {
|
||||
log.Errorf("invalid mode flag: %s", key)
|
||||
return "", errors.New("invalid mode flag")
|
||||
}
|
||||
|
||||
return mode, nil
|
||||
}
|
||||
642
server/service/network/dns.go
Normal file
642
server/service/network/dns.go
Normal file
@@ -0,0 +1,642 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"NanoKVM-Server/proto"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
dnsModeManual = "manual"
|
||||
dnsModeDHCP = "dhcp"
|
||||
|
||||
dnsConfigDir = "/etc/kvm/network"
|
||||
dnsModeFile = "/etc/kvm/network/dns.mode"
|
||||
dnsServersFile = "/etc/kvm/network/dns.servers"
|
||||
bootResolvFile = "/boot/resolv.conf"
|
||||
bootResolvBackup = "/boot/resolv.conf.manual.bak"
|
||||
etcResolvFile = "/etc/resolv.conf"
|
||||
dhcpResolvFile = "/etc/resolv.conf.dhcp"
|
||||
tmpResolvFile = "/tmp/resolv.conf"
|
||||
udhcpcHookFile = "/usr/share/udhcpc/default.script.d/99-nanokvm-dns"
|
||||
|
||||
maxDNSServers = 6
|
||||
)
|
||||
|
||||
//go:embed scripts/99-nanokvm-dns
|
||||
var udhcpcDNSHook string
|
||||
|
||||
type resolvConfig struct {
|
||||
Servers []string
|
||||
SearchDomains []string
|
||||
}
|
||||
|
||||
func (s *Service) GetDNS(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
mode := currentDNSMode()
|
||||
|
||||
servers := readManualDNSServers()
|
||||
if len(servers) == 0 {
|
||||
servers, _ = parseResolvConf(bootResolvFile)
|
||||
}
|
||||
if len(servers) == 0 {
|
||||
servers, _ = parseResolvConf(bootResolvBackup)
|
||||
}
|
||||
|
||||
effective, _ := parseResolvConf(etcResolvFile)
|
||||
dhcpConfig, _ := readDHCPResolvConfig(canFallbackEffectiveForDHCP())
|
||||
dhcp := dhcpConfig.Servers
|
||||
info := getDNSInfo()
|
||||
|
||||
rsp.OkRspWithData(c, &proto.GetDNSRsp{
|
||||
Mode: mode,
|
||||
Servers: servers,
|
||||
Effective: effective,
|
||||
DHCP: dhcp,
|
||||
Info: info,
|
||||
})
|
||||
log.Debugf("get dns config: mode=%s servers=%v effective=%v dhcp=%v info=%+v", mode, servers, effective, dhcp, info)
|
||||
}
|
||||
|
||||
func (s *Service) SetDNS(c *gin.Context) {
|
||||
var req proto.SetDNSReq
|
||||
var rsp proto.Response
|
||||
|
||||
if err := proto.ParseFormRequest(c, &req); err != nil {
|
||||
rsp.ErrRsp(c, -1, "invalid arguments")
|
||||
return
|
||||
}
|
||||
|
||||
switch req.Mode {
|
||||
case dnsModeManual:
|
||||
if err := setManualDNS(req.Servers); err != nil {
|
||||
log.Errorf("failed to set manual dns: %s", err)
|
||||
rsp.ErrRsp(c, -2, err.Error())
|
||||
return
|
||||
}
|
||||
case dnsModeDHCP:
|
||||
if err := setDHCPDNS(); err != nil {
|
||||
log.Errorf("failed to set dhcp dns: %s", err)
|
||||
rsp.ErrRsp(c, -3, err.Error())
|
||||
return
|
||||
}
|
||||
default:
|
||||
rsp.ErrRsp(c, -1, "invalid dns mode")
|
||||
return
|
||||
}
|
||||
|
||||
_ = exec.Command("sync").Run()
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("set dns config: mode=%s servers=%v", req.Mode, req.Servers)
|
||||
}
|
||||
|
||||
func setManualDNS(servers []string) error {
|
||||
normalized, err := validateDNSServers(servers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
return fmt.Errorf("dns servers are required")
|
||||
}
|
||||
|
||||
if currentDNSMode() == dnsModeDHCP {
|
||||
if err := refreshDHCPResolvCacheFromEffective(); err != nil {
|
||||
log.Warnf("failed to refresh dhcp dns cache before switching to manual: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(dnsConfigDir, 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create dns config directory: %w", err)
|
||||
}
|
||||
|
||||
if err := writeDNSMode(dnsModeManual); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(dnsServersFile, []byte(strings.Join(normalized, "\n")+"\n"), 0o644); err != nil {
|
||||
return fmt.Errorf("failed to write dns servers: %w", err)
|
||||
}
|
||||
|
||||
if err := renderResolvConf(bootResolvFile, normalized); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := renderResolvConf(etcResolvFile, normalized); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return installUDHCPCDNSHook()
|
||||
}
|
||||
|
||||
func setDHCPDNS() error {
|
||||
dhcpConfig, err := readDHCPResolvConfig(canFallbackEffectiveForDHCP())
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read dhcp dns: %w", err)
|
||||
}
|
||||
if len(dhcpConfig.Servers) == 0 {
|
||||
return fmt.Errorf("no dhcp dns is currently available")
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(dnsConfigDir, 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create dns config directory: %w", err)
|
||||
}
|
||||
|
||||
if err := renderResolvConfig(dhcpResolvFile, dhcpConfig); err != nil {
|
||||
return fmt.Errorf("failed to write dhcp dns cache: %w", err)
|
||||
}
|
||||
|
||||
if err := writeDNSMode(dnsModeDHCP); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := preserveManualDNSServers(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := backupAndRemoveBootResolv(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := renderResolvConfig(etcResolvFile, dhcpConfig); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return installUDHCPCDNSHook()
|
||||
}
|
||||
|
||||
func currentDNSMode() string {
|
||||
mode := readRawDNSMode()
|
||||
if mode == "" {
|
||||
mode = defaultDNSMode()
|
||||
}
|
||||
|
||||
return mode
|
||||
}
|
||||
|
||||
func readDNSMode() string {
|
||||
return readRawDNSMode()
|
||||
}
|
||||
|
||||
func readRawDNSMode() string {
|
||||
data, err := os.ReadFile(dnsModeFile)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
mode := strings.TrimSpace(string(data))
|
||||
if mode != dnsModeManual && mode != dnsModeDHCP {
|
||||
return ""
|
||||
}
|
||||
|
||||
return mode
|
||||
}
|
||||
|
||||
func canFallbackEffectiveForDHCP() bool {
|
||||
mode := readRawDNSMode()
|
||||
if mode == dnsModeDHCP {
|
||||
return true
|
||||
}
|
||||
if mode == dnsModeManual {
|
||||
return false
|
||||
}
|
||||
if _, err := os.Stat(bootResolvFile); os.IsNotExist(err) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func defaultDNSMode() string {
|
||||
if _, err := os.Stat(bootResolvFile); err == nil {
|
||||
return dnsModeManual
|
||||
}
|
||||
|
||||
return dnsModeDHCP
|
||||
}
|
||||
|
||||
func writeDNSMode(mode string) error {
|
||||
if err := os.WriteFile(dnsModeFile, []byte(mode+"\n"), 0o644); err != nil {
|
||||
return fmt.Errorf("failed to write dns mode: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readManualDNSServers() []string {
|
||||
servers, err := parsePlainDNSServers(dnsServersFile)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return servers
|
||||
}
|
||||
|
||||
func preserveManualDNSServers() error {
|
||||
if len(readManualDNSServers()) > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
servers, _ := parseResolvConf(bootResolvFile)
|
||||
if len(servers) == 0 {
|
||||
servers, _ = parseResolvConf(bootResolvBackup)
|
||||
}
|
||||
if len(servers) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := os.WriteFile(dnsServersFile, []byte(strings.Join(servers, "\n")+"\n"), 0o644); err != nil {
|
||||
return fmt.Errorf("failed to preserve manual dns servers: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func parsePlainDNSServers(path string) ([]string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
lines := strings.Split(string(data), "\n")
|
||||
return normalizeDNSServers(lines)
|
||||
}
|
||||
|
||||
func readDHCPResolvConfig(allowEffectiveFallback bool) (resolvConfig, error) {
|
||||
config, err := parseResolvConfig(dhcpResolvFile)
|
||||
if err == nil && len(config.Servers) > 0 {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
tmpConfig, tmpErr := parseResolvConfig(tmpResolvFile)
|
||||
if tmpErr == nil && len(tmpConfig.Servers) > 0 {
|
||||
return tmpConfig, nil
|
||||
}
|
||||
|
||||
if allowEffectiveFallback {
|
||||
effective, effectiveErr := parseResolvConfig(etcResolvFile)
|
||||
if effectiveErr == nil && len(effective.Servers) > 0 {
|
||||
return effective, nil
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return resolvConfig{}, err
|
||||
}
|
||||
if tmpErr != nil && !os.IsNotExist(tmpErr) {
|
||||
return resolvConfig{}, tmpErr
|
||||
}
|
||||
|
||||
return resolvConfig{}, nil
|
||||
}
|
||||
|
||||
func refreshDHCPResolvCacheFromEffective() error {
|
||||
config, err := parseResolvConfig(etcResolvFile)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if len(config.Servers) == 0 {
|
||||
return nil
|
||||
}
|
||||
if len(config.SearchDomains) == 0 {
|
||||
cached, _ := parseResolvConfig(dhcpResolvFile)
|
||||
config.SearchDomains = cached.SearchDomains
|
||||
}
|
||||
|
||||
return renderResolvConfig(dhcpResolvFile, config)
|
||||
}
|
||||
|
||||
func parseResolvConf(path string) ([]string, error) {
|
||||
config, err := parseResolvConfig(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return config.Servers, nil
|
||||
}
|
||||
|
||||
func parseResolvConfig(path string) (resolvConfig, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return resolvConfig{}, err
|
||||
}
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
|
||||
var servers []string
|
||||
var searchDomains []string
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
line := stripInlineComment(scanner.Text())
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
continue
|
||||
}
|
||||
|
||||
switch fields[0] {
|
||||
case "nameserver":
|
||||
servers = append(servers, fields[1])
|
||||
case "search":
|
||||
searchDomains = append(searchDomains, fields[1:]...)
|
||||
case "domain":
|
||||
searchDomains = append(searchDomains, fields[1])
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return resolvConfig{}, err
|
||||
}
|
||||
|
||||
normalizedServers, err := normalizeDNSServers(servers)
|
||||
if err != nil {
|
||||
return resolvConfig{}, err
|
||||
}
|
||||
|
||||
return resolvConfig{
|
||||
Servers: normalizedServers,
|
||||
SearchDomains: normalizeSearchDomains(searchDomains),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func getDNSInfo() proto.DNSInfo {
|
||||
ifaceName, gateway := getDefaultIPv4Route()
|
||||
if ifaceName == "" {
|
||||
ifaceName = getFallbackIPv4Interface()
|
||||
}
|
||||
|
||||
info := proto.DNSInfo{
|
||||
Interface: ifaceName,
|
||||
Gateway: gateway,
|
||||
}
|
||||
|
||||
dhcpConfig, _ := readDHCPResolvConfig(canFallbackEffectiveForDHCP())
|
||||
info.SearchDomains = dhcpConfig.SearchDomains
|
||||
|
||||
if ifaceName == "" {
|
||||
return info
|
||||
}
|
||||
|
||||
iface, err := net.InterfaceByName(ifaceName)
|
||||
if err != nil {
|
||||
return info
|
||||
}
|
||||
|
||||
info.Type = getDNSInterfaceType(iface.Name)
|
||||
info.Address, info.SubnetMask = getIPv4AddressInfo(*iface)
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
func getDefaultIPv4Route() (string, string) {
|
||||
file, err := os.Open("/proc/net/route")
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) < 8 || fields[1] != "00000000" {
|
||||
continue
|
||||
}
|
||||
|
||||
return fields[0], parseRouteGateway(fields[2])
|
||||
}
|
||||
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func parseRouteGateway(value string) string {
|
||||
gateway, err := strconv.ParseUint(value, 16, 32)
|
||||
if err != nil || gateway == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return net.IPv4(byte(gateway), byte(gateway>>8), byte(gateway>>16), byte(gateway>>24)).String()
|
||||
}
|
||||
|
||||
func getFallbackIPv4Interface() string {
|
||||
interfaces, err := net.Interfaces()
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, iface := range interfaces {
|
||||
if iface.Flags&net.FlagUp == 0 {
|
||||
continue
|
||||
}
|
||||
if getDNSInterfaceType(iface.Name) == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
address, _ := getIPv4AddressInfo(iface)
|
||||
if address != "" {
|
||||
return iface.Name
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func getDNSInterfaceType(name string) string {
|
||||
if strings.HasPrefix(name, "eth") || strings.HasPrefix(name, "en") {
|
||||
return "Wired"
|
||||
}
|
||||
|
||||
if strings.HasPrefix(name, "wlan") || strings.HasPrefix(name, "wl") {
|
||||
return "Wireless"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func getIPv4AddressInfo(iface net.Interface) (string, string) {
|
||||
addrs, err := iface.Addrs()
|
||||
if err != nil {
|
||||
return "", ""
|
||||
}
|
||||
|
||||
for _, addr := range addrs {
|
||||
ipNet, ok := addr.(*net.IPNet)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
ip := ipNet.IP.To4()
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
ones, _ := ipNet.Mask.Size()
|
||||
return fmt.Sprintf("%s/%d", ip.String(), ones), net.IP(ipNet.Mask).String()
|
||||
}
|
||||
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func renderResolvConf(path string, servers []string) error {
|
||||
return renderResolvConfig(path, resolvConfig{Servers: servers})
|
||||
}
|
||||
|
||||
func renderResolvConfig(path string, config resolvConfig) error {
|
||||
normalized, err := normalizeDNSServers(config.Servers)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(normalized) == 0 {
|
||||
return fmt.Errorf("dns servers are required")
|
||||
}
|
||||
|
||||
var builder strings.Builder
|
||||
searchDomains := normalizeSearchDomains(config.SearchDomains)
|
||||
if len(searchDomains) > 0 {
|
||||
builder.WriteString("search ")
|
||||
builder.WriteString(strings.Join(searchDomains, " "))
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
for _, server := range normalized {
|
||||
builder.WriteString("nameserver ")
|
||||
builder.WriteString(server)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create dns file directory: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(path, []byte(builder.String()), 0o644); err != nil {
|
||||
return fmt.Errorf("failed to write %s: %w", path, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDNSServers(servers []string) ([]string, error) {
|
||||
normalized, err := normalizeDNSServers(servers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(normalized) > maxDNSServers {
|
||||
return nil, fmt.Errorf("too many dns servers")
|
||||
}
|
||||
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func normalizeDNSServers(servers []string) ([]string, error) {
|
||||
seen := make(map[string]struct{})
|
||||
var normalized []string
|
||||
|
||||
for _, server := range servers {
|
||||
server = normalizeDNSServer(server)
|
||||
if server == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
ip := net.ParseIP(server)
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("invalid dns server: %s", server)
|
||||
}
|
||||
|
||||
server = ip.String()
|
||||
if _, exists := seen[server]; exists {
|
||||
continue
|
||||
}
|
||||
|
||||
seen[server] = struct{}{}
|
||||
normalized = append(normalized, server)
|
||||
}
|
||||
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func normalizeSearchDomains(domains []string) []string {
|
||||
seen := make(map[string]struct{})
|
||||
var normalized []string
|
||||
|
||||
for _, domain := range domains {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[domain]; exists {
|
||||
continue
|
||||
}
|
||||
|
||||
seen[domain] = struct{}{}
|
||||
normalized = append(normalized, domain)
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
func normalizeDNSServer(server string) string {
|
||||
server = stripInlineComment(server)
|
||||
server = strings.TrimSpace(server)
|
||||
fields := strings.Fields(server)
|
||||
if len(fields) == 0 {
|
||||
return ""
|
||||
}
|
||||
|
||||
return fields[0]
|
||||
}
|
||||
|
||||
func stripInlineComment(value string) string {
|
||||
if index := strings.Index(value, "#"); index >= 0 {
|
||||
return value[:index]
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
func backupAndRemoveBootResolv() error {
|
||||
data, err := os.ReadFile(bootResolvFile)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to read boot resolv: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(bootResolvBackup, data, 0o644); err != nil {
|
||||
return fmt.Errorf("failed to backup boot resolv: %w", err)
|
||||
}
|
||||
|
||||
if err := os.Remove(bootResolvFile); err != nil && !os.IsNotExist(err) {
|
||||
return fmt.Errorf("failed to remove boot resolv: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func installUDHCPCDNSHook() error {
|
||||
if err := os.MkdirAll(filepath.Dir(udhcpcHookFile), 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create udhcpc hook directory: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(udhcpcHookFile, []byte(udhcpcDNSHook), 0o755); err != nil {
|
||||
return fmt.Errorf("failed to install udhcpc dns hook: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
56
server/service/network/scripts/99-nanokvm-dns
Normal file
56
server/service/network/scripts/99-nanokvm-dns
Normal file
@@ -0,0 +1,56 @@
|
||||
#!/bin/sh
|
||||
|
||||
ACTION="$1"
|
||||
CACHE="/etc/resolv.conf.dhcp"
|
||||
ACTIVE="/etc/resolv.conf"
|
||||
MODE="/etc/kvm/network/dns.mode"
|
||||
BOOT="/boot/resolv.conf"
|
||||
|
||||
[ "$ACTION" = "bound" ] || [ "$ACTION" = "renew" ] || exit 0
|
||||
[ -n "$dns" ] || exit 0
|
||||
|
||||
TMPFILE="$(mktemp)" || exit 1
|
||||
|
||||
write_search_domain() {
|
||||
if [ -n "$search" ]; then
|
||||
printf "search"
|
||||
for domain_name in $search; do
|
||||
printf " %s" "$domain_name"
|
||||
done
|
||||
printf "\n"
|
||||
return
|
||||
fi
|
||||
|
||||
if [ -n "$domain" ]; then
|
||||
printf "domain %s\n" "$domain"
|
||||
return
|
||||
fi
|
||||
|
||||
for source in "$CACHE" "$ACTIVE"; do
|
||||
[ -f "$source" ] || continue
|
||||
while IFS= read -r line; do
|
||||
line="${line%%#*}"
|
||||
set -- $line
|
||||
[ "$1" = "search" ] || [ "$1" = "domain" ] || continue
|
||||
[ -n "$2" ] || continue
|
||||
printf "%s\n" "$line"
|
||||
return
|
||||
done < "$source"
|
||||
done
|
||||
}
|
||||
|
||||
{
|
||||
write_search_domain
|
||||
for server in $dns; do
|
||||
printf "nameserver %s\n" "$server"
|
||||
done
|
||||
} > "$TMPFILE"
|
||||
|
||||
cat "$TMPFILE" > "$CACHE"
|
||||
MODE_VALUE="$(cat "$MODE" 2>/dev/null)"
|
||||
if [ "$MODE_VALUE" = "dhcp" ] || { [ -z "$MODE_VALUE" ] && [ ! -f "$BOOT" ]; }; then
|
||||
cat "$TMPFILE" > "$ACTIVE"
|
||||
fi
|
||||
rm -f "$TMPFILE"
|
||||
|
||||
exit 0
|
||||
@@ -1,20 +1,28 @@
|
||||
package network
|
||||
|
||||
import (
|
||||
"NanoKVM-Server/proto"
|
||||
"crypto/subtle"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"NanoKVM-Server/proto"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const (
|
||||
WiFiExistFile = "/etc/kvm/wifi_exist"
|
||||
WiFiSSID = "/etc/kvm/wifi.ssid"
|
||||
WiFiPasswd = "/etc/kvm/wifi.pass"
|
||||
WiFiConnect = "/kvmapp/kvm/wifi_try_connect"
|
||||
WiFiStateFile = "/kvmapp/kvm/wifi_state"
|
||||
WiFiExistFile = "/etc/kvm/wifi_exist"
|
||||
WiFiApModeFile = "/tmp/wifiap"
|
||||
WiFiSSID = "/etc/kvm/wifi.ssid"
|
||||
WiFiPasswd = "/etc/kvm/wifi.pass"
|
||||
WiFiConnect = "/kvmapp/kvm/wifi_try_connect"
|
||||
WiFiStateFile = "/kvmapp/kvm/wifi_state"
|
||||
WiFiScript = "/etc/init.d/S30wifi"
|
||||
WiFiApPassFile = "/kvmapp/kvm/ap.pass"
|
||||
)
|
||||
|
||||
func (s *Service) GetWifi(c *gin.Context) {
|
||||
@@ -22,25 +30,84 @@ func (s *Service) GetWifi(c *gin.Context) {
|
||||
|
||||
data := &proto.GetWifiRsp{}
|
||||
|
||||
_, err := os.Stat(WiFiExistFile)
|
||||
if err != nil {
|
||||
data.Supported = isSupported()
|
||||
if !data.Supported {
|
||||
rsp.OkRspWithData(c, data)
|
||||
return
|
||||
}
|
||||
|
||||
data.Supported = true
|
||||
data.ApMode = isAPMode()
|
||||
|
||||
content, err := os.ReadFile(WiFiStateFile)
|
||||
if err != nil {
|
||||
data.Connected = isConnected()
|
||||
if !data.Connected {
|
||||
rsp.OkRspWithData(c, data)
|
||||
return
|
||||
}
|
||||
|
||||
state := strings.ReplaceAll(string(content), "\n", "")
|
||||
data.Connected = state == "1"
|
||||
data.Ssid = getWiFiSsid()
|
||||
if data.Ssid == "" {
|
||||
data.Ssid = "Wi-Fi"
|
||||
}
|
||||
|
||||
rsp.OkRspWithData(c, data)
|
||||
log.Debugf("get wifi state: %s", state)
|
||||
log.Debugf("get wifi state: %+v", data)
|
||||
}
|
||||
|
||||
func (s *Service) ConnectWifiNoAuth(c *gin.Context) {
|
||||
var req proto.ConnectWifiReq
|
||||
var rsp proto.Response
|
||||
|
||||
// Check Wi-Fi configuration mode
|
||||
if !isSupported() || !isAPMode() {
|
||||
time.Sleep(2 * time.Second)
|
||||
rsp.ErrRsp(c, -1, "invalid mode")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify AP Password
|
||||
apKey := c.GetHeader("X-AP-Key")
|
||||
expectedPass := getApPassword()
|
||||
if apKey == "" || expectedPass == "" || subtle.ConstantTimeCompare([]byte(apKey), []byte(expectedPass)) != 1 {
|
||||
time.Sleep(2 * time.Second)
|
||||
rsp.ErrRsp(c, -4, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
if err := proto.ParseFormRequest(c, &req); err != nil {
|
||||
time.Sleep(1 * time.Second)
|
||||
rsp.ErrRsp(c, -2, "invalid parameters")
|
||||
return
|
||||
}
|
||||
|
||||
if err := connect(req.Ssid, req.Password); err != nil {
|
||||
rsp.ErrRsp(c, -3, "failed to connect wifi")
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("set wifi ap mode successfully")
|
||||
}
|
||||
|
||||
func (s *Service) VerifyApLogin(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
if !isSupported() || !isAPMode() {
|
||||
time.Sleep(2 * time.Second)
|
||||
rsp.ErrRsp(c, -1, "invalid mode")
|
||||
return
|
||||
}
|
||||
|
||||
apKey := c.GetHeader("X-AP-Key")
|
||||
expectedPass := getApPassword()
|
||||
if apKey == "" || expectedPass == "" || subtle.ConstantTimeCompare([]byte(apKey), []byte(expectedPass)) != 1 {
|
||||
time.Sleep(2 * time.Second)
|
||||
rsp.ErrRsp(c, -4, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
}
|
||||
|
||||
func (s *Service) ConnectWifi(c *gin.Context) {
|
||||
@@ -52,24 +119,105 @@ func (s *Service) ConnectWifi(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.WriteFile(WiFiSSID, []byte(req.Ssid), 0o644); err != nil {
|
||||
log.Errorf("failed to save wifi ssid: %s", err)
|
||||
rsp.ErrRsp(c, -2, "failed to save wifi")
|
||||
if err := connect(req.Ssid, req.Password); err != nil {
|
||||
rsp.ErrRsp(c, -2, "failed to connect wifi")
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.WriteFile(WiFiPasswd, []byte(req.Password), 0o644); err != nil {
|
||||
log.Errorf("failed to save wifi password: %s", err)
|
||||
rsp.ErrRsp(c, -3, "failed to save wifi")
|
||||
// Waiting for Wi-Fi connection
|
||||
maxTries := 7
|
||||
if isConnected() {
|
||||
maxTries = 3
|
||||
time.Sleep(12 * time.Second)
|
||||
}
|
||||
|
||||
for range maxTries {
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
if isConnected() && getWiFiSsid() != "" {
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("set wifi successfully: %s", req.Ssid)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
rsp.ErrRsp(c, -3, "failed to get wifi status")
|
||||
}
|
||||
|
||||
func (s *Service) DisconnectWifi(c *gin.Context) {
|
||||
var rsp proto.Response
|
||||
|
||||
command := fmt.Sprintf("%s stop", WiFiScript)
|
||||
cmd := exec.Command("sh", "-c", command)
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
log.Errorf("failed to disconnect wifi: %s", output)
|
||||
rsp.ErrRsp(c, -1, "failed to stop wifi")
|
||||
return
|
||||
}
|
||||
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
_ = os.Remove(WiFiSSID)
|
||||
_ = os.Remove(WiFiPasswd)
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("stop wifi successfully")
|
||||
}
|
||||
|
||||
func connect(ssid string, password string) error {
|
||||
if err := os.WriteFile(WiFiSSID, []byte(ssid), 0o644); err != nil {
|
||||
log.Errorf("failed to save wifi ssid: %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(WiFiPasswd, []byte(password), 0o644); err != nil {
|
||||
log.Errorf("failed to save wifi password: %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.WriteFile(WiFiConnect, nil, 0o644); err != nil {
|
||||
log.Errorf("failed to connect wifi: %s", err)
|
||||
rsp.ErrRsp(c, -4, "failed to connect wifi")
|
||||
return
|
||||
return err
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("set wifi successfully: %s", req.Ssid)
|
||||
return nil
|
||||
}
|
||||
|
||||
func isSupported() bool {
|
||||
_, err := os.Stat(WiFiExistFile)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func isAPMode() bool {
|
||||
_, err := os.Stat(WiFiApModeFile)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func isConnected() bool {
|
||||
content, err := os.ReadFile(WiFiStateFile)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
state := strings.ReplaceAll(string(content), "\n", "")
|
||||
return state == "1"
|
||||
}
|
||||
|
||||
func getWiFiSsid() string {
|
||||
ssidByte, err := os.ReadFile(WiFiSSID)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.ReplaceAll(string(ssidByte), "\n", "")
|
||||
}
|
||||
|
||||
func getApPassword() string {
|
||||
passByte, err := os.ReadFile(WiFiApPassFile)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return strings.ReplaceAll(string(passByte), "\n", "")
|
||||
}
|
||||
|
||||
@@ -65,6 +65,54 @@ func (s *Service) GetMac(c *gin.Context) {
|
||||
rsp.OkRspWithData(c, data)
|
||||
}
|
||||
|
||||
func (s *Service) SetMacName(c *gin.Context) {
|
||||
var req proto.SetMacNameReq // Mac:string Name:string
|
||||
var rsp proto.Response
|
||||
|
||||
if err := proto.ParseFormRequest(c, &req); err != nil {
|
||||
rsp.ErrRsp(c, -1, "invalid arguments")
|
||||
return
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(WolMacFile)
|
||||
if err != nil {
|
||||
log.Errorf("failed to open %s: %s", WolMacFile, err)
|
||||
rsp.ErrRsp(c, -2, "read failed")
|
||||
return
|
||||
}
|
||||
|
||||
macs := strings.Split(string(content), "\n")
|
||||
var newLines []string
|
||||
macFound := false
|
||||
|
||||
for _, line := range macs {
|
||||
parts := strings.Split(line, " ")
|
||||
if req.Mac != parts[0] {
|
||||
newLines = append(newLines, line)
|
||||
continue
|
||||
}
|
||||
newLines = append(newLines, parts[0]+" "+req.Name)
|
||||
macFound = true
|
||||
}
|
||||
|
||||
if !macFound {
|
||||
log.Errorf("failed to found mac %s: %s", req.Mac, err)
|
||||
rsp.ErrRsp(c, -3, "write failed")
|
||||
return
|
||||
}
|
||||
|
||||
data := strings.Join(newLines, "\n")
|
||||
err = os.WriteFile(WolMacFile, []byte(data), 0o644)
|
||||
if err != nil {
|
||||
log.Errorf("failed to write %s: %s", WolMacFile, err)
|
||||
rsp.ErrRsp(c, -3, "write failed")
|
||||
return
|
||||
}
|
||||
|
||||
rsp.OkRsp(c)
|
||||
log.Debugf("set wol mac name: %s %s", req.Mac, req.Name)
|
||||
}
|
||||
|
||||
func (s *Service) DeleteMac(c *gin.Context) {
|
||||
var req proto.DeleteMacReq
|
||||
var rsp proto.Response
|
||||
@@ -85,7 +133,8 @@ func (s *Service) DeleteMac(c *gin.Context) {
|
||||
var newMacs []string
|
||||
|
||||
for _, mac := range macs {
|
||||
if req.Mac != mac {
|
||||
parts := strings.Split(mac, " ")
|
||||
if req.Mac != parts[0] {
|
||||
newMacs = append(newMacs, mac)
|
||||
}
|
||||
}
|
||||
@@ -164,7 +213,8 @@ func isMacExist(mac string) bool {
|
||||
|
||||
macs := strings.Split(string(content), "\n")
|
||||
for _, item := range macs {
|
||||
if mac == item {
|
||||
parts := strings.Split(item, " ")
|
||||
if mac == parts[0] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
316
server/service/picoclaw/actions.go
Normal file
316
server/service/picoclaw/actions.go
Normal file
@@ -0,0 +1,316 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"math"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"NanoKVM-Server/service/hid"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultClickHold = 40 * time.Millisecond
|
||||
defaultKeyDelay = 30 * time.Millisecond
|
||||
defaultDragSteps = 10
|
||||
defaultScrollStep = 20 * time.Millisecond
|
||||
)
|
||||
|
||||
func (s *Service) Actions(c *gin.Context) {
|
||||
sessionID, sessionErr := s.requireSessionID(c)
|
||||
if sessionErr != nil {
|
||||
writePicoclawError(c, sessionErr)
|
||||
return
|
||||
}
|
||||
|
||||
releaseAfter, lockErr := s.lock.AcquireTemporary(sessionID)
|
||||
if lockErr != nil {
|
||||
writePicoclawError(c, lockErr)
|
||||
return
|
||||
}
|
||||
if releaseAfter {
|
||||
defer s.lock.Release(sessionID)
|
||||
}
|
||||
|
||||
actions, actionErr := normalizeActions(c)
|
||||
if actionErr != nil {
|
||||
writePicoclawError(c, actionErr)
|
||||
return
|
||||
}
|
||||
|
||||
result, execErr := s.executeActions(sessionID, actions)
|
||||
if execErr != nil {
|
||||
writePicoclawError(c, execErr)
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccess(c, result)
|
||||
}
|
||||
|
||||
func normalizeActions(c *gin.Context) ([]Action, *PicoclawError) {
|
||||
body := bytes.NewBuffer(nil)
|
||||
if _, err := body.ReadFrom(c.Request.Body); err != nil {
|
||||
return nil, newPicoclawError(CodeInvalidAction, "failed to read action payload")
|
||||
}
|
||||
|
||||
raw := body.Bytes()
|
||||
if len(raw) == 0 {
|
||||
return nil, newPicoclawError(CodeInvalidAction, "empty action payload")
|
||||
}
|
||||
|
||||
var batch ActionBatch
|
||||
if err := json.Unmarshal(raw, &batch); err == nil && len(batch.Actions) > 0 {
|
||||
return batch.Actions, nil
|
||||
}
|
||||
|
||||
var action Action
|
||||
if err := json.Unmarshal(raw, &action); err != nil || action.Action == "" {
|
||||
return nil, newPicoclawError(CodeInvalidAction, "invalid action payload")
|
||||
}
|
||||
|
||||
return []Action{action}, nil
|
||||
}
|
||||
|
||||
func (s *Service) executeActions(sessionID string, actions []Action) (result ActionResult, err *PicoclawError) {
|
||||
startedAt := time.Now()
|
||||
if len(actions) == 0 {
|
||||
return ActionResult{}, newPicoclawError(CodeInvalidAction, "empty actions")
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
s.releaseAllHIDState()
|
||||
}
|
||||
}()
|
||||
|
||||
totalWrites := 0
|
||||
for idx, action := range actions {
|
||||
if lockErr := s.lock.Ensure(sessionID); lockErr != nil {
|
||||
lockErr.Index = &idx
|
||||
return ActionResult{}, lockErr
|
||||
}
|
||||
|
||||
writes, execErr := s.executeAction(action)
|
||||
if execErr != nil {
|
||||
execErr.Index = &idx
|
||||
return ActionResult{}, execErr
|
||||
}
|
||||
totalWrites += writes
|
||||
}
|
||||
|
||||
result = ActionResult{
|
||||
Action: actions[0].Action,
|
||||
DurationMs: time.Since(startedAt).Milliseconds(),
|
||||
HIDWrites: totalWrites,
|
||||
ExecutedActions: len(actions),
|
||||
}
|
||||
if len(actions) > 1 {
|
||||
result.Action = "batch"
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) executeAction(action Action) (int, *PicoclawError) {
|
||||
switch strings.ToLower(strings.TrimSpace(action.Action)) {
|
||||
case "click":
|
||||
x, y, err := normalizedPoint(action.X, action.Y)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
button, err := mouseButton(action.Button)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
writes := 0
|
||||
writes += s.sendMouseMoveWithButton(x, y, 0x00, 0)
|
||||
writes += s.sendMousePress(x, y, button)
|
||||
time.Sleep(defaultClickHold)
|
||||
writes += s.sendMouseRelease(x, y)
|
||||
return writes, nil
|
||||
|
||||
case "move":
|
||||
x, y, err := normalizedPoint(action.X, action.Y)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return s.sendMouseMoveWithButton(x, y, 0x00, 0), nil
|
||||
|
||||
case "wait":
|
||||
if action.DurationMs < 0 {
|
||||
return 0, newPicoclawError(CodeInvalidAction, "wait duration must be >= 0")
|
||||
}
|
||||
time.Sleep(time.Duration(action.DurationMs) * time.Millisecond)
|
||||
return 0, nil
|
||||
|
||||
case "drag":
|
||||
fromX, fromY, err := normalizedNestedPoint(action.From)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
toX, toY, err := normalizedNestedPoint(action.To)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
button, err := mouseButton(action.Button)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
writes := 0
|
||||
writes += s.sendMouseMoveWithButton(fromX, fromY, 0x00, 0)
|
||||
writes += s.sendMousePress(fromX, fromY, button)
|
||||
for step := 1; step <= defaultDragSteps; step++ {
|
||||
ratio := float64(step) / float64(defaultDragSteps)
|
||||
x := fromX + (toX-fromX)*ratio
|
||||
y := fromY + (toY-fromY)*ratio
|
||||
writes += s.sendMouseMoveWithButton(x, y, button, 0)
|
||||
}
|
||||
writes += s.sendMouseRelease(toX, toY)
|
||||
return writes, nil
|
||||
|
||||
case "scroll":
|
||||
x, y := 0.5, 0.5
|
||||
if action.X != nil || action.Y != nil {
|
||||
var err *PicoclawError
|
||||
x, y, err = normalizedPoint(action.X, action.Y)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
|
||||
amount := action.Amount
|
||||
if amount == 0 {
|
||||
amount = 1
|
||||
}
|
||||
if amount < 0 {
|
||||
return 0, newPicoclawError(CodeInvalidAction, "scroll amount must be > 0")
|
||||
}
|
||||
|
||||
wheel := 1
|
||||
switch strings.ToLower(strings.TrimSpace(action.Direction)) {
|
||||
case "", "up":
|
||||
wheel = 1
|
||||
case "down":
|
||||
wheel = -1
|
||||
default:
|
||||
return 0, newPicoclawError(CodeInvalidAction, "invalid scroll direction")
|
||||
}
|
||||
|
||||
writes := 0
|
||||
for range amount {
|
||||
writes += s.sendMouseMoveWithButton(x, y, 0x00, wheel)
|
||||
writes += s.sendMouseMoveWithButton(x, y, 0x00, 0)
|
||||
time.Sleep(defaultScrollStep)
|
||||
}
|
||||
return writes, nil
|
||||
|
||||
case "type":
|
||||
if action.Text == "" {
|
||||
return 0, newPicoclawError(CodeInvalidAction, "type requires text")
|
||||
}
|
||||
charMap := hid.GetCharMap("")
|
||||
writes := 0
|
||||
for _, char := range action.Text {
|
||||
key, ok := charMap[char]
|
||||
if !ok {
|
||||
return 0, newPicoclawError(CodeInvalidAction, "unsupported character in type action")
|
||||
}
|
||||
|
||||
writes += s.sendKeyboardReport([]byte{byte(key.Modifiers), 0x00, byte(key.Code), 0x00, 0x00, 0x00, 0x00, 0x00})
|
||||
writes += s.sendKeyboardReport([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
|
||||
time.Sleep(defaultKeyDelay)
|
||||
}
|
||||
return writes, nil
|
||||
|
||||
case "hotkey":
|
||||
report, err := buildHotkeyReport([]string(action.Keys))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
writes := 0
|
||||
writes += s.sendKeyboardReport(report)
|
||||
time.Sleep(defaultClickHold)
|
||||
writes += s.sendKeyboardReport([]byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})
|
||||
return writes, nil
|
||||
}
|
||||
|
||||
return 0, newPicoclawError(CodeInvalidAction, "unknown or invalid action")
|
||||
}
|
||||
|
||||
func toAbsoluteHidCoord(normalized float64) uint16 {
|
||||
if normalized < 0 {
|
||||
normalized = 0
|
||||
}
|
||||
if normalized > 1 {
|
||||
normalized = 1
|
||||
}
|
||||
return uint16(math.Floor(0x7FFF*normalized)) + 1
|
||||
}
|
||||
|
||||
func (s *Service) sendMousePress(x float64, y float64, button byte) int {
|
||||
return s.sendMouseMoveWithButton(x, y, button, 0)
|
||||
}
|
||||
|
||||
func (s *Service) sendMouseRelease(x float64, y float64) int {
|
||||
return s.sendMouseMoveWithButton(x, y, 0x00, 0)
|
||||
}
|
||||
|
||||
func (s *Service) sendMouseMoveWithButton(x float64, y float64, buttons byte, wheel int) int {
|
||||
absoluteX := toAbsoluteHidCoord(x)
|
||||
absoluteY := toAbsoluteHidCoord(y)
|
||||
|
||||
report := []byte{
|
||||
buttons,
|
||||
byte(absoluteX & 0xff),
|
||||
byte(absoluteX >> 8),
|
||||
byte(absoluteY & 0xff),
|
||||
byte(absoluteY >> 8),
|
||||
byte(int8(wheel)),
|
||||
}
|
||||
s.hid.WriteHid2(report)
|
||||
return 1
|
||||
}
|
||||
|
||||
func (s *Service) sendKeyboardReport(report []byte) int {
|
||||
s.hid.WriteHid0(report)
|
||||
return 1
|
||||
}
|
||||
|
||||
func normalizedPoint(x *float64, y *float64) (float64, float64, *PicoclawError) {
|
||||
if x == nil || y == nil {
|
||||
return 0, 0, newPicoclawError(CodeInvalidAction, "action requires x and y")
|
||||
}
|
||||
if *x < 0 || *x > 1 || *y < 0 || *y > 1 {
|
||||
return 0, 0, newPicoclawError(CodeInvalidAction, "coordinates must be within [0,1]")
|
||||
}
|
||||
return *x, *y, nil
|
||||
}
|
||||
|
||||
func normalizedNestedPoint(point *Point) (float64, float64, *PicoclawError) {
|
||||
if point == nil {
|
||||
return 0, 0, newPicoclawError(CodeInvalidAction, "action requires point coordinates")
|
||||
}
|
||||
return normalizedPoint(point.X, point.Y)
|
||||
}
|
||||
|
||||
func mouseButton(button string) (byte, *PicoclawError) {
|
||||
switch strings.ToLower(strings.TrimSpace(button)) {
|
||||
case "", "left":
|
||||
return 1 << 0, nil
|
||||
case "right":
|
||||
return 1 << 1, nil
|
||||
case "middle":
|
||||
return 1 << 2, nil
|
||||
case "back":
|
||||
return 1 << 3, nil
|
||||
case "forward":
|
||||
return 1 << 4, nil
|
||||
default:
|
||||
return 0, newPicoclawError(CodeInvalidAction, "invalid mouse button")
|
||||
}
|
||||
}
|
||||
147
server/service/picoclaw/agent_profile.go
Normal file
147
server/service/picoclaw/agent_profile.go
Normal file
@@ -0,0 +1,147 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
agentProfileDefault = "default"
|
||||
agentProfileKVM = "kvm"
|
||||
agentProfileFile = "AGENT.md"
|
||||
)
|
||||
|
||||
type AgentProfileUpdateRequest struct {
|
||||
Profile string `json:"profile"`
|
||||
}
|
||||
|
||||
func resolveAgentProfileSourcePath(profile string) (string, error) {
|
||||
fileName := agentProfileFile
|
||||
switch profile {
|
||||
case agentProfileDefault:
|
||||
fileName = "AGENT.md"
|
||||
case agentProfileKVM:
|
||||
fileName = "AGENT_KVM.md"
|
||||
default:
|
||||
return "", fmt.Errorf("unsupported agent profile: %s", profile)
|
||||
}
|
||||
|
||||
candidates := make([]string, 0, 4)
|
||||
if wd, err := os.Getwd(); err == nil {
|
||||
candidates = append(candidates,
|
||||
filepath.Join(wd, "picoclaw", fileName),
|
||||
filepath.Join(wd, "docs", fileName),
|
||||
)
|
||||
}
|
||||
candidates = append(candidates,
|
||||
filepath.Join("/kvmapp", "picoclaw", fileName),
|
||||
filepath.Join(filepath.Dir(os.Args[0]), "..", "picoclaw", fileName),
|
||||
)
|
||||
|
||||
for _, candidate := range candidates {
|
||||
if _, err := os.Stat(candidate); err == nil {
|
||||
return candidate, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("agent profile source not found: %s", fileName)
|
||||
}
|
||||
|
||||
func detectPicoclawAgentProfile() string {
|
||||
workspacePath, err := resolvePicoclawWorkspacePath()
|
||||
if err != nil {
|
||||
return agentProfileKVM
|
||||
}
|
||||
|
||||
targetPath := filepath.Join(workspacePath, agentProfileFile)
|
||||
targetContent, err := os.ReadFile(targetPath)
|
||||
if err != nil {
|
||||
return agentProfileKVM
|
||||
}
|
||||
|
||||
switch parseAgentProfileName(string(targetContent)) {
|
||||
case "pico":
|
||||
return agentProfileDefault
|
||||
case "pico-kvm":
|
||||
return agentProfileKVM
|
||||
default:
|
||||
return agentProfileKVM
|
||||
}
|
||||
}
|
||||
|
||||
func parseAgentProfileName(content string) string {
|
||||
scanner := bufio.NewScanner(strings.NewReader(content))
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if !strings.HasPrefix(line, "name:") {
|
||||
continue
|
||||
}
|
||||
return strings.TrimSpace(strings.TrimPrefix(line, "name:"))
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func applyPicoclawAgentProfile(profile string) error {
|
||||
sourcePath, err := resolveAgentProfileSourcePath(profile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
workspacePath, err := resolvePicoclawWorkspacePath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(workspacePath, 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create picoclaw workspace: %w", err)
|
||||
}
|
||||
|
||||
sourceContent, err := os.ReadFile(sourcePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read agent profile source: %w", err)
|
||||
}
|
||||
|
||||
targetPath := filepath.Join(workspacePath, agentProfileFile)
|
||||
if err := os.WriteFile(targetPath, sourceContent, 0o644); err != nil {
|
||||
return fmt.Errorf("failed to write picoclaw AGENT.md: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func withAgentProfile(status RuntimeStatus) RuntimeStatus {
|
||||
status.AgentProfile = detectPicoclawAgentProfile()
|
||||
return status
|
||||
}
|
||||
|
||||
func (s *Service) UpdateAgentProfile(c *gin.Context) {
|
||||
var req AgentProfileUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeInvalidAction, "invalid agent profile payload"))
|
||||
return
|
||||
}
|
||||
|
||||
profile := strings.TrimSpace(req.Profile)
|
||||
if profile != agentProfileDefault && profile != agentProfileKVM {
|
||||
writePicoclawError(c, newPicoclawError(CodeInvalidAction, "invalid agent profile"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := applyPicoclawAgentProfile(profile); err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
_ = s.syncConfigFromPicoclaw()
|
||||
_ = s.ensureRuntimeReady()
|
||||
|
||||
writeSuccess(c, gin.H{
|
||||
"profile": profile,
|
||||
"status": withAgentProfile(s.runtime.Get()),
|
||||
})
|
||||
}
|
||||
179
server/service/picoclaw/config.go
Normal file
179
server/service/picoclaw/config.go
Normal file
@@ -0,0 +1,179 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPicoclawGatewayHost = "127.0.0.1"
|
||||
defaultPicoclawGatewayPort = 18790
|
||||
picoclawGatewayPath = "/pico/ws"
|
||||
)
|
||||
|
||||
func defaultConfig() Config {
|
||||
cfg := Config{
|
||||
GatewayURL: "ws://127.0.0.1:18790/pico/ws",
|
||||
ConnectTimeoutMs: 10000,
|
||||
ReadTimeoutMs: 60000,
|
||||
WriteTimeoutMs: 10000,
|
||||
PingIntervalMs: 30000,
|
||||
MaxMessageBytes: 1024 * 1024,
|
||||
AllowTokenQuery: false,
|
||||
}
|
||||
|
||||
settings, err := loadPicoclawGatewaySettings()
|
||||
if err != nil {
|
||||
return cfg
|
||||
}
|
||||
|
||||
cfg.GatewayURL = settings.GatewayURL
|
||||
cfg.Token = settings.Token
|
||||
cfg.AllowTokenQuery = settings.AllowTokenQuery
|
||||
if settings.PingIntervalMs > 0 {
|
||||
cfg.PingIntervalMs = settings.PingIntervalMs
|
||||
}
|
||||
if settings.ReadTimeoutMs > 0 {
|
||||
cfg.ReadTimeoutMs = settings.ReadTimeoutMs
|
||||
}
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func (s *Service) syncConfigFromPicoclaw() *PicoclawError {
|
||||
installed, installedKnown := picoclawInstalledState()
|
||||
|
||||
if patchErr := preparePicoclawConfigForRead(); patchErr != nil {
|
||||
s.runtime.Update(func(status *RuntimeStatus) {
|
||||
status.Ready = false
|
||||
status.Status = "config_error"
|
||||
status.ConfigError = patchErr.Error()
|
||||
status.LastError = patchErr.Error()
|
||||
if installedKnown {
|
||||
status.Installed = installed
|
||||
}
|
||||
status.CheckedAt = time.Now()
|
||||
})
|
||||
return newPicoclawError(CodeRuntimeUnavailable, patchErr.Error())
|
||||
}
|
||||
|
||||
settings, err := loadPicoclawGatewaySettings()
|
||||
if err != nil {
|
||||
s.runtime.Update(func(status *RuntimeStatus) {
|
||||
status.Ready = false
|
||||
status.Status = "config_error"
|
||||
status.ConfigError = err.Error()
|
||||
status.LastError = err.Error()
|
||||
if installedKnown {
|
||||
status.Installed = installed
|
||||
}
|
||||
status.CheckedAt = time.Now()
|
||||
})
|
||||
return newPicoclawError(CodeRuntimeUnavailable, err.Error())
|
||||
}
|
||||
|
||||
cfg := s.config.Get()
|
||||
cfg.GatewayURL = settings.GatewayURL
|
||||
cfg.Token = settings.Token
|
||||
cfg.AllowTokenQuery = settings.AllowTokenQuery
|
||||
if settings.PingIntervalMs > 0 {
|
||||
cfg.PingIntervalMs = settings.PingIntervalMs
|
||||
}
|
||||
if settings.ReadTimeoutMs > 0 {
|
||||
cfg.ReadTimeoutMs = settings.ReadTimeoutMs
|
||||
}
|
||||
s.config.Set(cfg)
|
||||
|
||||
s.runtime.Update(func(status *RuntimeStatus) {
|
||||
status.Installed = true
|
||||
status.ModelConfigured = settings.ModelConfigured
|
||||
if settings.ModelConfigured {
|
||||
status.ModelName = settings.ModelName
|
||||
} else {
|
||||
status.ModelName = settings.TargetModelName
|
||||
}
|
||||
status.ConfigError = ""
|
||||
if status.Status == "config_error" && status.Ready {
|
||||
status.Status = "ready"
|
||||
}
|
||||
status.CheckedAt = time.Now()
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type picoclawGatewaySettings struct {
|
||||
GatewayURL string
|
||||
Token string
|
||||
AllowTokenQuery bool
|
||||
PingIntervalMs int
|
||||
ReadTimeoutMs int
|
||||
ModelConfigured bool
|
||||
ModelName string
|
||||
TargetModelName string
|
||||
}
|
||||
|
||||
func loadPicoclawGatewaySettings() (picoclawGatewaySettings, error) {
|
||||
doc, err := loadPicoclawConfigDocument()
|
||||
if err != nil {
|
||||
return picoclawGatewaySettings{}, err
|
||||
}
|
||||
if err := ensurePicoclawPicoChannelEnabled(doc); err != nil {
|
||||
return picoclawGatewaySettings{}, err
|
||||
}
|
||||
|
||||
cfg := doc.config
|
||||
|
||||
host := cfg.Gateway.Host
|
||||
if host == "" || host == "0.0.0.0" {
|
||||
host = defaultPicoclawGatewayHost
|
||||
}
|
||||
|
||||
port := cfg.Gateway.Port
|
||||
if port <= 0 {
|
||||
port = defaultPicoclawGatewayPort
|
||||
}
|
||||
|
||||
settings := picoclawGatewaySettings{
|
||||
GatewayURL: fmt.Sprintf("ws://%s:%d%s", host, port, picoclawGatewayPath),
|
||||
Token: doc.resolvedGatewayToken(),
|
||||
AllowTokenQuery: cfg.Channels.Pico.AllowTokenQuery,
|
||||
}
|
||||
settings.TargetModelName = resolvePicoclawTargetModelName(cfg)
|
||||
|
||||
if isPicoclawModelConfigured(cfg, doc.security, settings.TargetModelName) {
|
||||
settings.ModelConfigured = true
|
||||
settings.ModelName = settings.TargetModelName
|
||||
}
|
||||
|
||||
if cfg.Channels.Pico.PingInterval > 0 {
|
||||
settings.PingIntervalMs = cfg.Channels.Pico.PingInterval * 1000
|
||||
}
|
||||
if cfg.Channels.Pico.ReadTimeout > 0 {
|
||||
settings.ReadTimeoutMs = cfg.Channels.Pico.ReadTimeout * 1000
|
||||
}
|
||||
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func resolvePicoclawTargetModelName(cfg picoclawConfigFile) string {
|
||||
return strings.TrimSpace(cfg.Agents.Defaults.ModelName)
|
||||
}
|
||||
|
||||
func preparePicoclawConfigForRead() error {
|
||||
configPath, err := resolvePicoclawConfigPath()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err := os.Stat(configPath); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to stat picoclaw config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
256
server/service/picoclaw/config_files.go
Normal file
256
server/service/picoclaw/config_files.go
Normal file
@@ -0,0 +1,256 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/user"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
const (
|
||||
picoclawPIDFileName = ".picoclaw.pid"
|
||||
picoclawGatewayTokenPrefix = "pico-"
|
||||
)
|
||||
|
||||
type picoclawConfigFile struct {
|
||||
Agents struct {
|
||||
Defaults struct {
|
||||
ModelName string `json:"model_name"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Workspace string `json:"workspace,omitempty"`
|
||||
} `json:"defaults"`
|
||||
} `json:"agents"`
|
||||
Gateway struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
} `json:"gateway"`
|
||||
ModelList []struct {
|
||||
ModelName string `json:"model_name"`
|
||||
Model string `json:"model"`
|
||||
APIBase string `json:"api_base"`
|
||||
APIKey string `json:"api_key"`
|
||||
APIKeys []string `json:"api_keys,omitempty"`
|
||||
} `json:"model_list"`
|
||||
Channels struct {
|
||||
Pico struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Token string `json:"token"`
|
||||
AllowTokenQuery bool `json:"allow_token_query"`
|
||||
PingInterval int `json:"ping_interval"`
|
||||
ReadTimeout int `json:"read_timeout"`
|
||||
} `json:"pico"`
|
||||
} `json:"channels"`
|
||||
}
|
||||
|
||||
type picoclawConfigDocument struct {
|
||||
configPath string
|
||||
securityPath string
|
||||
config picoclawConfigFile
|
||||
raw map[string]any
|
||||
security picoclawSecurityConfig
|
||||
}
|
||||
|
||||
func loadPicoclawConfigDocument() (*picoclawConfigDocument, error) {
|
||||
configPath, err := resolvePicoclawConfigPath()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
data, err := os.ReadFile(configPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read picoclaw config: %w", err)
|
||||
}
|
||||
|
||||
var cfg picoclawConfigFile
|
||||
if err := json.Unmarshal(data, &cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse picoclaw config: %w", err)
|
||||
}
|
||||
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal(data, &raw); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse picoclaw config for update: %w", err)
|
||||
}
|
||||
|
||||
securityPath := resolvePicoclawSecurityPath(configPath)
|
||||
security, err := loadPicoclawSecurityConfig(securityPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &picoclawConfigDocument{
|
||||
configPath: configPath,
|
||||
securityPath: securityPath,
|
||||
config: cfg,
|
||||
raw: raw,
|
||||
security: security,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func resolvePicoclawConfigPath() (string, error) {
|
||||
home := os.Getenv("PICOCLAW_HOME")
|
||||
if home == "" {
|
||||
currentUser, err := user.Current()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve PICOCLAW_HOME: %w", err)
|
||||
}
|
||||
home = filepath.Join(currentUser.HomeDir, ".picoclaw")
|
||||
}
|
||||
|
||||
return filepath.Join(home, "config.json"), nil
|
||||
}
|
||||
|
||||
func expandPicoclawPath(path string) string {
|
||||
path = strings.TrimSpace(path)
|
||||
if path == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if strings.HasPrefix(path, "~/") || path == "~" {
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
if path == "~" {
|
||||
return home
|
||||
}
|
||||
return filepath.Join(home, strings.TrimPrefix(path, "~/"))
|
||||
}
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
func resolvePicoclawSecurityPath(configPath string) string {
|
||||
return filepath.Join(filepath.Dir(configPath), ".security.yml")
|
||||
}
|
||||
|
||||
func (d *picoclawConfigDocument) saveConfig() error {
|
||||
updated, err := json.MarshalIndent(d.raw, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to encode updated picoclaw config: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(d.configPath, updated, 0o600); err != nil {
|
||||
return fmt.Errorf("failed to write picoclaw config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *picoclawConfigDocument) saveSecurity() error {
|
||||
var buf bytes.Buffer
|
||||
encoder := yaml.NewEncoder(&buf)
|
||||
encoder.SetIndent(2)
|
||||
if err := encoder.Encode(d.security); err != nil {
|
||||
return fmt.Errorf("failed to encode picoclaw security config: %w", err)
|
||||
}
|
||||
if err := encoder.Close(); err != nil {
|
||||
return fmt.Errorf("failed to finalize picoclaw security config: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(d.securityPath, buf.Bytes(), 0o600); err != nil {
|
||||
return fmt.Errorf("failed to write picoclaw security config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type picoclawSecurityConfig struct {
|
||||
ModelList map[string]picoclawModelSecurityEntry `yaml:"model_list,omitempty"`
|
||||
Channels picoclawSecurityChannels `yaml:"channels,omitempty"`
|
||||
}
|
||||
|
||||
type picoclawModelSecurityEntry struct {
|
||||
APIKeys []string `yaml:"api_keys,omitempty"`
|
||||
}
|
||||
|
||||
type picoclawSecurityChannels struct {
|
||||
Pico *picoclawPicoSecurity `yaml:"pico,omitempty"`
|
||||
}
|
||||
|
||||
type picoclawPicoSecurity struct {
|
||||
Token string `yaml:"token,omitempty"`
|
||||
}
|
||||
|
||||
type picoclawPIDFile struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
func (d *picoclawConfigDocument) resolvedPicoToken() string {
|
||||
if d == nil {
|
||||
return ""
|
||||
}
|
||||
if d.security.Channels.Pico != nil {
|
||||
if token := d.security.Channels.Pico.Token; token != "" {
|
||||
return token
|
||||
}
|
||||
}
|
||||
return d.config.Channels.Pico.Token
|
||||
}
|
||||
|
||||
func (d *picoclawConfigDocument) resolvedGatewayToken() string {
|
||||
baseToken := strings.TrimSpace(d.resolvedPicoToken())
|
||||
if baseToken == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
runtimeToken, err := d.resolvedPIDToken()
|
||||
if err != nil {
|
||||
return baseToken
|
||||
}
|
||||
|
||||
return composePicoclawGatewayToken(baseToken, runtimeToken)
|
||||
}
|
||||
|
||||
func (d *picoclawConfigDocument) resolvedPIDToken() (string, error) {
|
||||
if d == nil || d.configPath == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
pidPath := filepath.Join(filepath.Dir(d.configPath), picoclawPIDFileName)
|
||||
data, err := os.ReadFile(pidPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", nil
|
||||
}
|
||||
return "", fmt.Errorf("failed to read picoclaw pid file: %w", err)
|
||||
}
|
||||
|
||||
var pidFile picoclawPIDFile
|
||||
if err := json.Unmarshal(data, &pidFile); err != nil {
|
||||
return "", fmt.Errorf("failed to parse picoclaw pid file: %w", err)
|
||||
}
|
||||
|
||||
return strings.TrimSpace(pidFile.Token), nil
|
||||
}
|
||||
|
||||
func composePicoclawGatewayToken(baseToken, runtimeToken string) string {
|
||||
baseToken = strings.TrimSpace(baseToken)
|
||||
runtimeToken = strings.TrimSpace(runtimeToken)
|
||||
|
||||
switch {
|
||||
case baseToken == "":
|
||||
return ""
|
||||
case strings.HasPrefix(baseToken, picoclawGatewayTokenPrefix):
|
||||
return baseToken
|
||||
case runtimeToken == "":
|
||||
return baseToken
|
||||
default:
|
||||
return picoclawGatewayTokenPrefix + runtimeToken + baseToken
|
||||
}
|
||||
}
|
||||
|
||||
func loadPicoclawSecurityConfig(securityPath string) (picoclawSecurityConfig, error) {
|
||||
data, err := os.ReadFile(securityPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return picoclawSecurityConfig{}, nil
|
||||
}
|
||||
return picoclawSecurityConfig{}, fmt.Errorf("failed to read picoclaw security config: %w", err)
|
||||
}
|
||||
|
||||
var sec picoclawSecurityConfig
|
||||
if err := yaml.Unmarshal(data, &sec); err != nil {
|
||||
return picoclawSecurityConfig{}, fmt.Errorf("failed to parse picoclaw security config: %w", err)
|
||||
}
|
||||
|
||||
return sec, nil
|
||||
}
|
||||
71
server/service/picoclaw/errors.go
Normal file
71
server/service/picoclaw/errors.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
CodePicoclawLockHeld = "AI_LOCK_HELD"
|
||||
CodeScreenshotFailed = "SCREENSHOT_FAILED"
|
||||
CodeScreenshotNoSignal = "SCREENSHOT_NO_SIGNAL"
|
||||
CodeHIDWriteFailed = "HID_WRITE_FAILED"
|
||||
CodeInvalidAction = "INVALID_ACTION"
|
||||
CodeRuntimeUnavailable = "RUNTIME_UNAVAILABLE"
|
||||
CodeRuntimeStartFailed = "RUNTIME_START_FAILED"
|
||||
CodeSessionIDMissing = "SESSION_ID_MISSING"
|
||||
CodeSessionIDInvalid = "SESSION_ID_INVALID"
|
||||
)
|
||||
|
||||
type PicoclawError struct {
|
||||
StatusCode int
|
||||
Code string
|
||||
Message string
|
||||
SessionID string
|
||||
Index *int
|
||||
}
|
||||
|
||||
func (e *PicoclawError) Error() string {
|
||||
return e.Code + ": " + e.Message
|
||||
}
|
||||
|
||||
func newPicoclawError(code string, message string) *PicoclawError {
|
||||
return &PicoclawError{
|
||||
StatusCode: http.StatusOK,
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
|
||||
func writeSuccess(c *gin.Context, data interface{}) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": data,
|
||||
})
|
||||
}
|
||||
|
||||
func writePicoclawError(c *gin.Context, err *PicoclawError) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
payload := gin.H{
|
||||
"code": err.Code,
|
||||
"message": err.Message,
|
||||
}
|
||||
if err.SessionID != "" {
|
||||
payload["session_id"] = err.SessionID
|
||||
}
|
||||
if err.Index != nil {
|
||||
payload["index"] = *err.Index
|
||||
}
|
||||
|
||||
statusCode := err.StatusCode
|
||||
if statusCode == 0 {
|
||||
statusCode = http.StatusOK
|
||||
}
|
||||
|
||||
c.JSON(statusCode, payload)
|
||||
}
|
||||
107
server/service/picoclaw/gateway_client.go
Normal file
107
server/service/picoclaw/gateway_client.go
Normal file
@@ -0,0 +1,107 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
func (s *Service) connectGateway(sessionID string) (*websocket.Conn, *PicoclawError) {
|
||||
cfg := s.config.Get()
|
||||
|
||||
gatewayURL, err := buildGatewayURL(cfg, sessionID)
|
||||
if err != nil {
|
||||
s.runtime.Update(func(status *RuntimeStatus) {
|
||||
status.Ready = false
|
||||
status.Status = "config_error"
|
||||
status.ConfigError = err.Error()
|
||||
status.LastError = err.Error()
|
||||
status.CheckedAt = time.Now()
|
||||
status.CurrentSession = s.lock.Owner()
|
||||
})
|
||||
return nil, newPicoclawError(CodeRuntimeUnavailable, err.Error())
|
||||
}
|
||||
header := http.Header{}
|
||||
if cfg.Token != "" {
|
||||
header.Set("Authorization", fmt.Sprintf("Bearer %s", cfg.Token))
|
||||
}
|
||||
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: time.Duration(cfg.ConnectTimeoutMs) * time.Millisecond,
|
||||
NetDialContext: (&net.Dialer{
|
||||
Timeout: time.Duration(cfg.ConnectTimeoutMs) * time.Millisecond,
|
||||
}).DialContext,
|
||||
}
|
||||
|
||||
upstream, response, err := dialer.Dial(gatewayURL, header)
|
||||
if err != nil {
|
||||
s.runtime.Update(func(status *RuntimeStatus) {
|
||||
status.Ready = false
|
||||
status.Status = "unavailable"
|
||||
status.ConfigError = ""
|
||||
status.LastError = err.Error()
|
||||
status.CheckedAt = time.Now()
|
||||
status.CurrentSession = s.lock.Owner()
|
||||
if response != nil && response.StatusCode == http.StatusUnauthorized {
|
||||
status.Status = "config_error"
|
||||
status.ConfigError = "gateway authentication failed"
|
||||
}
|
||||
})
|
||||
return nil, newPicoclawError(CodeRuntimeUnavailable, "gateway is unavailable")
|
||||
}
|
||||
|
||||
s.runtime.Update(func(status *RuntimeStatus) {
|
||||
status.Ready = true
|
||||
status.Status = "ready"
|
||||
status.ConfigError = ""
|
||||
status.LastError = ""
|
||||
status.CheckedAt = time.Now()
|
||||
status.CurrentSession = s.lock.Owner()
|
||||
})
|
||||
|
||||
return upstream, nil
|
||||
}
|
||||
|
||||
func buildGatewayURL(cfg Config, sessionID string) (string, error) {
|
||||
parsed, err := url.Parse(cfg.GatewayURL)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid gateway url: %w", err)
|
||||
}
|
||||
if parsed.Scheme != "ws" && parsed.Scheme != "wss" {
|
||||
return "", fmt.Errorf("invalid gateway url scheme: %s", parsed.Scheme)
|
||||
}
|
||||
if parsed.Host == "" {
|
||||
return "", fmt.Errorf("invalid gateway url host")
|
||||
}
|
||||
|
||||
query := parsed.Query()
|
||||
query.Set("session_id", sessionID)
|
||||
if cfg.Token != "" && cfg.AllowTokenQuery {
|
||||
query.Set("token", cfg.Token)
|
||||
}
|
||||
parsed.RawQuery = query.Encode()
|
||||
|
||||
return parsed.String(), nil
|
||||
}
|
||||
|
||||
func gatewayHostPort(parsed *url.URL) (string, error) {
|
||||
if parsed == nil || parsed.Host == "" {
|
||||
return "", fmt.Errorf("invalid gateway url host")
|
||||
}
|
||||
if _, _, err := net.SplitHostPort(parsed.Host); err == nil {
|
||||
return parsed.Host, nil
|
||||
}
|
||||
|
||||
switch parsed.Scheme {
|
||||
case "ws":
|
||||
return net.JoinHostPort(parsed.Host, "80"), nil
|
||||
case "wss":
|
||||
return net.JoinHostPort(parsed.Host, "443"), nil
|
||||
default:
|
||||
return "", fmt.Errorf("invalid gateway url scheme: %s", parsed.Scheme)
|
||||
}
|
||||
}
|
||||
277
server/service/picoclaw/gateway_proxy.go
Normal file
277
server/service/picoclaw/gateway_proxy.go
Normal file
@@ -0,0 +1,277 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"NanoKVM-Server/service/stream/mjpeg"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/websocket"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var gatewayUpgrader = websocket.Upgrader{
|
||||
ReadBufferSize: 4096,
|
||||
WriteBufferSize: 4096,
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
type relayResult struct {
|
||||
Source string
|
||||
CloseCode int
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (s *Service) ConnectGateway(c *gin.Context) {
|
||||
sessionID := strings.TrimSpace(c.Query("session_id"))
|
||||
if sessionID == "" {
|
||||
sessionID = uuid.NewString()
|
||||
}
|
||||
|
||||
if lockErr := s.lock.Ensure(sessionID); lockErr != nil {
|
||||
c.AbortWithStatusJSON(http.StatusConflict, gin.H{
|
||||
"code": CodePicoclawLockHeld,
|
||||
"message": lockErr.Message,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
session, sessionErr := GetSessionManager().Register(sessionID, nil)
|
||||
if sessionErr != nil {
|
||||
s.lock.Release(sessionID)
|
||||
c.AbortWithStatusJSON(http.StatusConflict, gin.H{
|
||||
"code": CodePicoclawLockHeld,
|
||||
"message": sessionErr.Message,
|
||||
})
|
||||
return
|
||||
}
|
||||
GetSessionManager().SetState(sessionID, SessionStateConnecting)
|
||||
|
||||
if runtimeErr := s.syncConfigFromPicoclaw(); runtimeErr != nil {
|
||||
s.closeGatewaySession(session, CloseCodeRuntimeUnavailable, runtimeErr.Message)
|
||||
return
|
||||
}
|
||||
|
||||
upstream, gatewayErr := s.connectGateway(sessionID)
|
||||
if gatewayErr != nil {
|
||||
s.closeGatewaySession(session, CloseCodeRuntimeUnavailable, gatewayErr.Message)
|
||||
return
|
||||
}
|
||||
|
||||
downstream, err := gatewayUpgrader.Upgrade(c.Writer, c.Request, nil)
|
||||
if err != nil {
|
||||
log.Errorf("failed to upgrade gateway websocket: %s", err)
|
||||
_ = upstream.Close()
|
||||
ReleaseSession(sessionID)
|
||||
GetSessionManager().SetState(sessionID, SessionStateClosed)
|
||||
GetSessionManager().Remove(sessionID)
|
||||
return
|
||||
}
|
||||
|
||||
GetSessionManager().AttachUpstream(sessionID, upstream)
|
||||
GetSessionManager().AttachDownstream(sessionID, downstream)
|
||||
GetSessionManager().SetState(sessionID, SessionStateActive)
|
||||
mjpeg.EnableLatestFrameCache()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan relayResult, 2)
|
||||
cfg := s.config.Get()
|
||||
|
||||
s.configureRelayConn(downstream, cfg)
|
||||
s.configureRelayConn(upstream, cfg)
|
||||
|
||||
wg.Add(4)
|
||||
go s.runPingLoop("downstream", session.SessionID, downstream, cfg, &wg)
|
||||
go s.runPingLoop("upstream", session.SessionID, upstream, cfg, &wg)
|
||||
go s.proxyMessages("downstream", session, downstream, cfg, &wg, results)
|
||||
go s.proxyMessages("upstream", session, upstream, cfg, &wg, results)
|
||||
|
||||
result := <-results
|
||||
closeCode := result.CloseCode
|
||||
if closeCode == 0 {
|
||||
closeCode = websocket.CloseNormalClosure
|
||||
}
|
||||
|
||||
if result.Source == "upstream" {
|
||||
if closeCode == websocket.CloseNormalClosure {
|
||||
closeCode = CloseCodeUpstreamClosed
|
||||
}
|
||||
s.closeGatewaySession(session, closeCode, result.Reason)
|
||||
} else {
|
||||
s.closeGatewaySession(session, closeCode, result.Reason)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func (s *Service) proxyMessages(source string, session *GatewaySession, src *websocket.Conn, cfg Config, wg *sync.WaitGroup, results chan<- relayResult) {
|
||||
defer wg.Done()
|
||||
|
||||
for {
|
||||
messageType, data, err := src.ReadMessage()
|
||||
if err != nil {
|
||||
results <- relayResult{
|
||||
Source: source,
|
||||
CloseCode: closeCodeFromError(source, err),
|
||||
Reason: closeReasonFromError(err),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if source == "upstream" && messageType == websocket.BinaryMessage {
|
||||
results <- relayResult{
|
||||
Source: source,
|
||||
CloseCode: CloseCodeUpstreamClosed,
|
||||
Reason: "upstream sent unsupported binary message",
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if !s.lock.Renew(session.SessionID) {
|
||||
results <- relayResult{
|
||||
Source: source,
|
||||
CloseCode: CloseCodePicoclawTakenOver,
|
||||
Reason: "session lock lost",
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var writeErr error
|
||||
switch source {
|
||||
case "downstream":
|
||||
writeErr = session.writeUpstreamMessage(cfg, messageType, data)
|
||||
default:
|
||||
writeErr = session.writeDownstreamMessage(cfg, messageType, data)
|
||||
}
|
||||
if writeErr != nil {
|
||||
results <- relayResult{
|
||||
Source: source,
|
||||
CloseCode: closeCodeFromError(source, writeErr),
|
||||
Reason: closeReasonFromError(writeErr),
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) runPingLoop(name string, sessionID string, conn *websocket.Conn, cfg Config, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
ticker := time.NewTicker(time.Duration(cfg.PingIntervalMs) * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
if !s.lock.Renew(sessionID) {
|
||||
writeGatewayClose(conn, CloseCodePicoclawTakenOver, "session lock lost")
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
|
||||
if err := conn.WriteControl(
|
||||
websocket.PingMessage,
|
||||
[]byte(name),
|
||||
time.Now().Add(time.Duration(cfg.WriteTimeoutMs)*time.Millisecond),
|
||||
); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) configureRelayConn(conn *websocket.Conn, cfg Config) {
|
||||
readTimeout := time.Duration(cfg.ReadTimeoutMs) * time.Millisecond
|
||||
conn.SetReadLimit(int64(cfg.MaxMessageBytes))
|
||||
_ = conn.SetReadDeadline(time.Now().Add(readTimeout))
|
||||
conn.SetPongHandler(func(string) error {
|
||||
return conn.SetReadDeadline(time.Now().Add(readTimeout))
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) closeGatewaySession(session *GatewaySession, closeCode int, reason string) {
|
||||
if session == nil {
|
||||
return
|
||||
}
|
||||
|
||||
session.closeOnce.Do(func() {
|
||||
hadDownstream := session.Downstream != nil
|
||||
|
||||
mjpeg.DisableLatestFrameCache()
|
||||
GetSessionManager().SetState(session.SessionID, SessionStateClosing)
|
||||
|
||||
if session.Upstream != nil {
|
||||
writeGatewayClose(session.Upstream, websocket.CloseNormalClosure, "relay closing")
|
||||
_ = session.Upstream.Close()
|
||||
}
|
||||
if session.Downstream != nil {
|
||||
writeGatewayClose(session.Downstream, closeCode, reason)
|
||||
_ = session.Downstream.Close()
|
||||
}
|
||||
|
||||
if hadDownstream {
|
||||
cleanupPicoclawMediaTempDir()
|
||||
}
|
||||
|
||||
ReleaseSession(session.SessionID)
|
||||
GetSessionManager().SetState(session.SessionID, SessionStateClosed)
|
||||
GetSessionManager().Remove(session.SessionID)
|
||||
|
||||
status := s.runtime.Get()
|
||||
status.CurrentSession = s.lock.Owner()
|
||||
if closeCode == CloseCodeUpstreamClosed || closeCode == CloseCodeRuntimeUnavailable {
|
||||
status.Ready = false
|
||||
if closeCode == CloseCodeUpstreamClosed {
|
||||
status.Status = "unavailable"
|
||||
}
|
||||
status.LastError = reason
|
||||
status.CheckedAt = time.Now()
|
||||
s.runtime.Set(status)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeGatewayClose(conn *websocket.Conn, code int, reason string) {
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
|
||||
message := websocket.FormatCloseMessage(code, reason)
|
||||
_ = conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(2*time.Second))
|
||||
}
|
||||
|
||||
func closeCodeFromError(source string, err error) int {
|
||||
if closeErr, ok := err.(*websocket.CloseError); ok {
|
||||
if closeErr.Code == websocket.CloseNormalClosure || closeErr.Code == websocket.CloseGoingAway {
|
||||
return websocket.CloseNormalClosure
|
||||
}
|
||||
if closeErr.Code == websocket.CloseAbnormalClosure || closeErr.Code == websocket.CloseNoStatusReceived {
|
||||
if source == "upstream" {
|
||||
return CloseCodeUpstreamClosed
|
||||
}
|
||||
return websocket.CloseNormalClosure
|
||||
}
|
||||
return closeErr.Code
|
||||
}
|
||||
|
||||
if source == "upstream" {
|
||||
return CloseCodeUpstreamClosed
|
||||
}
|
||||
return websocket.CloseNormalClosure
|
||||
}
|
||||
|
||||
func closeReasonFromError(err error) string {
|
||||
if err == nil {
|
||||
return "closed"
|
||||
}
|
||||
if closeErr, ok := err.(*websocket.CloseError); ok {
|
||||
if closeErr.Text != "" {
|
||||
return closeErr.Text
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("relay closed: %v", err)
|
||||
}
|
||||
86
server/service/picoclaw/gateway_write.go
Normal file
86
server/service/picoclaw/gateway_write.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type picoGatewayMessage struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
Timestamp int64 `json:"timestamp,omitempty"`
|
||||
Payload map[string]any `json:"payload,omitempty"`
|
||||
}
|
||||
|
||||
func newPicoGatewayMessage(sessionID string, payload map[string]any) picoGatewayMessage {
|
||||
return picoGatewayMessage{
|
||||
Type: "message.send",
|
||||
ID: uuid.NewString(),
|
||||
SessionID: sessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
Payload: payload,
|
||||
}
|
||||
}
|
||||
|
||||
func newPicoGatewayObservationMessage(sessionID string, payload map[string]any) picoGatewayMessage {
|
||||
return picoGatewayMessage{
|
||||
Type: "observation",
|
||||
ID: uuid.NewString(),
|
||||
SessionID: sessionID,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
Payload: payload,
|
||||
}
|
||||
}
|
||||
|
||||
func (session *GatewaySession) writeUpstreamJSON(cfg Config, value any) error {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return session.writeUpstreamMessage(cfg, websocket.TextMessage, raw)
|
||||
}
|
||||
|
||||
func (session *GatewaySession) writeDownstreamJSON(cfg Config, value any) error {
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return session.writeDownstreamMessage(cfg, websocket.TextMessage, raw)
|
||||
}
|
||||
|
||||
func (session *GatewaySession) writeUpstreamMessage(cfg Config, messageType int, data []byte) error {
|
||||
if session == nil || session.Upstream == nil {
|
||||
return fmt.Errorf("upstream connection is unavailable")
|
||||
}
|
||||
|
||||
session.upstreamWriteMu.Lock()
|
||||
defer session.upstreamWriteMu.Unlock()
|
||||
|
||||
_ = session.Upstream.SetWriteDeadline(gatewayWriteDeadline(cfg))
|
||||
return session.Upstream.WriteMessage(messageType, data)
|
||||
}
|
||||
|
||||
func (session *GatewaySession) writeDownstreamMessage(cfg Config, messageType int, data []byte) error {
|
||||
if session == nil || session.Downstream == nil {
|
||||
return fmt.Errorf("downstream connection is unavailable")
|
||||
}
|
||||
|
||||
session.downstreamWriteMu.Lock()
|
||||
defer session.downstreamWriteMu.Unlock()
|
||||
|
||||
_ = session.Downstream.SetWriteDeadline(gatewayWriteDeadline(cfg))
|
||||
return session.Downstream.WriteMessage(messageType, data)
|
||||
}
|
||||
|
||||
func gatewayWriteDeadline(cfg Config) time.Time {
|
||||
timeout := time.Duration(cfg.WriteTimeoutMs) * time.Millisecond
|
||||
if timeout <= 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
return time.Now().Add(timeout)
|
||||
}
|
||||
271
server/service/picoclaw/keyboard_map.go
Normal file
271
server/service/picoclaw/keyboard_map.go
Normal file
@@ -0,0 +1,271 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
modifierLeftCtrl = 1 << 0
|
||||
modifierLeftShift = 1 << 1
|
||||
modifierLeftAlt = 1 << 2
|
||||
modifierLeftMeta = 1 << 3
|
||||
modifierRightCtrl = 1 << 4
|
||||
modifierRightShift = 1 << 5
|
||||
modifierRightAlt = 1 << 6
|
||||
modifierRightMeta = 1 << 7
|
||||
)
|
||||
|
||||
var modifierMap = map[string]byte{
|
||||
"ControlLeft": modifierLeftCtrl,
|
||||
"ShiftLeft": modifierLeftShift,
|
||||
"AltLeft": modifierLeftAlt,
|
||||
"MetaLeft": modifierLeftMeta,
|
||||
"ControlRight": modifierRightCtrl,
|
||||
"ShiftRight": modifierRightShift,
|
||||
"AltRight": modifierRightAlt,
|
||||
"MetaRight": modifierRightMeta,
|
||||
}
|
||||
|
||||
var keyAliases = map[string]string{
|
||||
"CTRL": "ControlLeft",
|
||||
"CONTROL": "ControlLeft",
|
||||
"SHIFT": "ShiftLeft",
|
||||
"ALT": "AltLeft",
|
||||
"OPTION": "AltLeft",
|
||||
"META": "MetaLeft",
|
||||
"WIN": "MetaLeft",
|
||||
"WINDOWS": "MetaLeft",
|
||||
"COMMAND": "MetaLeft",
|
||||
"CMD": "MetaLeft",
|
||||
"SUPER": "MetaLeft",
|
||||
"ESC": "Escape",
|
||||
"RETURN": "Enter",
|
||||
"DEL": "Delete",
|
||||
"INS": "Insert",
|
||||
"UP": "ArrowUp",
|
||||
"DOWN": "ArrowDown",
|
||||
"LEFT": "ArrowLeft",
|
||||
"RIGHT": "ArrowRight",
|
||||
"SPACEBAR": "Space",
|
||||
"SPACE": "Space",
|
||||
"TAB": "Tab",
|
||||
"ENTER": "Enter",
|
||||
"BACKSPACE": "Backspace",
|
||||
"PGUP": "PageUp",
|
||||
"PGDN": "PageDown",
|
||||
}
|
||||
|
||||
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,
|
||||
"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,
|
||||
"Power": 0x66,
|
||||
"NumpadEqual": 0x67,
|
||||
"F13": 0x68, "F14": 0x69, "F15": 0x6a, "F16": 0x6b, "F17": 0x6c, "F18": 0x6d,
|
||||
"F19": 0x6e, "F20": 0x6f, "F21": 0x70, "F22": 0x71, "F23": 0x72, "F24": 0x73,
|
||||
|
||||
"Execute": 0x74,
|
||||
"Help": 0x75,
|
||||
"Props": 0x76,
|
||||
"Select": 0x77,
|
||||
"Stop": 0x78,
|
||||
"Again": 0x79,
|
||||
"Undo": 0x7a,
|
||||
"Cut": 0x7b,
|
||||
"Copy": 0x7c,
|
||||
"Paste": 0x7d,
|
||||
"Find": 0x7e,
|
||||
|
||||
"AudioVolumeMute": 0x7f,
|
||||
"AudioVolumeUp": 0x80,
|
||||
"AudioVolumeDown": 0x81,
|
||||
"VolumeMute": 0x7f,
|
||||
"VolumeUp": 0x80,
|
||||
"VolumeDown": 0x81,
|
||||
|
||||
"LockingCapsLock": 0x82,
|
||||
"LockingNumLock": 0x83,
|
||||
"LockingScrollLock": 0x84,
|
||||
"NumpadComma": 0x85,
|
||||
"NumpadEqual2": 0x86,
|
||||
"IntlRo": 0x87,
|
||||
"KanaMode": 0x88,
|
||||
"IntlYen": 0x89,
|
||||
"Convert": 0x8a,
|
||||
"NonConvert": 0x8b,
|
||||
"International6": 0x8c,
|
||||
"International7": 0x8d,
|
||||
"International8": 0x8e,
|
||||
"International9": 0x8f,
|
||||
"Lang1": 0x90, "Lang2": 0x91, "Lang3": 0x92, "Lang4": 0x93, "Lang5": 0x94,
|
||||
"Lang6": 0x95, "Lang7": 0x96, "Lang8": 0x97, "Lang9": 0x98,
|
||||
"IntlHash": 0x32,
|
||||
|
||||
"NumpadParenLeft": 0xb6,
|
||||
"NumpadParenRight": 0xb7,
|
||||
"NumpadBackspace": 0xbb,
|
||||
"NumpadMemoryStore": 0xd0,
|
||||
"NumpadMemoryRecall": 0xd1,
|
||||
"NumpadMemoryClear": 0xd2,
|
||||
"NumpadMemoryAdd": 0xd3,
|
||||
"NumpadMemorySubtract": 0xd4,
|
||||
"NumpadClear": 0xd8,
|
||||
"NumpadClearEntry": 0xd9,
|
||||
|
||||
"BrowserSearch": 0xf0,
|
||||
"BrowserHome": 0xf1,
|
||||
"BrowserBack": 0xf2,
|
||||
"BrowserForward": 0xf3,
|
||||
"BrowserStop": 0xf4,
|
||||
"BrowserRefresh": 0xf5,
|
||||
"BrowserFavorites": 0xf6,
|
||||
|
||||
"MediaPlayPause": 0xe8,
|
||||
"MediaStop": 0xe9,
|
||||
"MediaTrackPrevious": 0xea,
|
||||
"MediaTrackNext": 0xeb,
|
||||
"Eject": 0xec,
|
||||
"MediaSelect": 0xed,
|
||||
"LaunchMail": 0xee,
|
||||
"LaunchApp1": 0xef,
|
||||
"LaunchApp2": 0xf0,
|
||||
"Sleep": 0xf8,
|
||||
"Wake": 0xf9,
|
||||
"MediaRewind": 0xfa,
|
||||
"MediaFastForward": 0xfb,
|
||||
}
|
||||
|
||||
func resolveKey(key string) (string, byte, bool, error) {
|
||||
trimmed := strings.TrimSpace(key)
|
||||
if trimmed == "" {
|
||||
return "", 0, false, fmt.Errorf("empty key")
|
||||
}
|
||||
|
||||
if modifier, ok := modifierMap[trimmed]; ok {
|
||||
return trimmed, modifier, true, nil
|
||||
}
|
||||
if _, ok := keycodeMap[trimmed]; ok {
|
||||
return trimmed, keycodeMap[trimmed], false, nil
|
||||
}
|
||||
|
||||
upper := strings.ToUpper(trimmed)
|
||||
if alias, ok := keyAliases[upper]; ok {
|
||||
if modifier, ok := modifierMap[alias]; ok {
|
||||
return alias, modifier, true, nil
|
||||
}
|
||||
return alias, keycodeMap[alias], false, nil
|
||||
}
|
||||
|
||||
if len(upper) == 1 && upper[0] >= 'A' && upper[0] <= 'Z' {
|
||||
code := "Key" + upper
|
||||
return code, keycodeMap[code], false, nil
|
||||
}
|
||||
if len(upper) == 1 && upper[0] >= '0' && upper[0] <= '9' {
|
||||
code := "Digit" + upper
|
||||
return code, keycodeMap[code], false, nil
|
||||
}
|
||||
|
||||
if modifier, ok := modifierMap[upper]; ok {
|
||||
return upper, modifier, true, nil
|
||||
}
|
||||
if code, ok := keycodeMap[trimmed]; ok {
|
||||
return trimmed, code, false, nil
|
||||
}
|
||||
if code, ok := keycodeMap[upper]; ok {
|
||||
return upper, code, false, nil
|
||||
}
|
||||
|
||||
return "", 0, false, fmt.Errorf("unsupported key: %s", key)
|
||||
}
|
||||
|
||||
func buildHotkeyReport(keys []string) ([]byte, *PicoclawError) {
|
||||
if len(keys) == 0 {
|
||||
return nil, newPicoclawError(CodeInvalidAction, "hotkey requires at least one key")
|
||||
}
|
||||
|
||||
report := make([]byte, 8)
|
||||
nextIndex := 2
|
||||
|
||||
for _, key := range keys {
|
||||
_, code, isModifier, err := resolveKey(key)
|
||||
if err != nil {
|
||||
return nil, newPicoclawError(CodeInvalidAction, err.Error())
|
||||
}
|
||||
|
||||
if isModifier {
|
||||
report[0] |= code
|
||||
continue
|
||||
}
|
||||
|
||||
if nextIndex >= len(report) {
|
||||
return nil, newPicoclawError(CodeInvalidAction, "hotkey supports at most 6 non-modifier keys")
|
||||
}
|
||||
report[nextIndex] = code
|
||||
nextIndex++
|
||||
}
|
||||
|
||||
return report, nil
|
||||
}
|
||||
102
server/service/picoclaw/load_image_instruction.go
Normal file
102
server/service/picoclaw/load_image_instruction.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultImagePrompt = "Describe the image briefly."
|
||||
)
|
||||
|
||||
func (s *Service) LoadImage(c *gin.Context) {
|
||||
var req LoadImageRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeInvalidAction, "invalid load image payload"))
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, session, sessionErr := s.requireActiveGatewaySession(c)
|
||||
if sessionErr != nil {
|
||||
writePicoclawError(c, sessionErr)
|
||||
return
|
||||
}
|
||||
|
||||
sourcePath, pathErr := normalizeLoadImagePath(req.Path)
|
||||
if pathErr != nil {
|
||||
writePicoclawError(c, pathErr)
|
||||
return
|
||||
}
|
||||
|
||||
instruction := buildLoadImageInstruction(sourcePath, req.Prompt)
|
||||
message := newPicoGatewayMessage(sessionID, map[string]any{
|
||||
"content": instruction,
|
||||
})
|
||||
if err := session.writeUpstreamJSON(s.config.Get(), message); err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, "failed to deliver image instruction to picoclaw"))
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccess(c, gin.H{
|
||||
"accepted": true,
|
||||
"session_id": sessionID,
|
||||
"message_id": message.ID,
|
||||
"path": sourcePath,
|
||||
"user_prompt": normalizeImagePrompt(req.Prompt),
|
||||
"instructed_at": time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) requireActiveGatewaySession(c *gin.Context) (string, *GatewaySession, *PicoclawError) {
|
||||
sessionID := strings.TrimSpace(c.GetHeader(sessionIDHeader))
|
||||
if sessionID == "" {
|
||||
sessionID = strings.TrimSpace(s.lock.Owner())
|
||||
}
|
||||
if sessionID == "" {
|
||||
return "", nil, newPicoclawError(CodeSessionIDMissing, "missing X-PicoClaw-Session-ID")
|
||||
}
|
||||
|
||||
session, ok := GetSessionManager().Get(sessionID)
|
||||
if !ok || session == nil {
|
||||
err := newPicoclawError(CodeRuntimeUnavailable, "picoclaw session is not connected")
|
||||
err.SessionID = sessionID
|
||||
return "", nil, err
|
||||
}
|
||||
if session.State != SessionStateActive || session.Upstream == nil {
|
||||
err := newPicoclawError(CodeRuntimeUnavailable, "picoclaw session is not active")
|
||||
err.SessionID = sessionID
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
return sessionID, session, nil
|
||||
}
|
||||
|
||||
func normalizeLoadImagePath(sourcePath string) (string, *PicoclawError) {
|
||||
sourcePath = strings.TrimSpace(sourcePath)
|
||||
if sourcePath == "" {
|
||||
return "", newPicoclawError(CodeInvalidAction, "image path is required")
|
||||
}
|
||||
|
||||
return sourcePath, nil
|
||||
}
|
||||
|
||||
func buildLoadImageInstruction(sourcePath string, prompt string) string {
|
||||
argsJSON, _ := json.Marshal(map[string]string{"path": sourcePath})
|
||||
return fmt.Sprintf(
|
||||
"Call `load_image` first with this exact argument object:\n```json\n%s\n```\n\nDo not ask the user to re-upload the image. Do not modify the path. Do not use `read_file` or any other tool to inspect this image directly.\n\nAfter `load_image` succeeds, treat the loaded image as the current task input and continue with this request:\n%s",
|
||||
string(argsJSON),
|
||||
normalizeImagePrompt(prompt),
|
||||
)
|
||||
}
|
||||
|
||||
func normalizeImagePrompt(prompt string) string {
|
||||
prompt = strings.TrimSpace(prompt)
|
||||
if prompt == "" {
|
||||
return defaultImagePrompt
|
||||
}
|
||||
return prompt
|
||||
}
|
||||
299
server/service/picoclaw/mcp_handler.go
Normal file
299
server/service/picoclaw/mcp_handler.go
Normal file
@@ -0,0 +1,299 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// JSON-RPC 2.0 types for MCP HTTP transport
|
||||
|
||||
type jsonRPCRequest struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type jsonRPCResponse struct {
|
||||
JSONRPC string `json:"jsonrpc"`
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result interface{} `json:"result,omitempty"`
|
||||
Error *jsonRPCError `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type jsonRPCError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// MCP tool definitions
|
||||
|
||||
var mcpToolDefinitions = []map[string]interface{}{
|
||||
{
|
||||
"name": "kvm_screenshot",
|
||||
"description": "Capture the current HDMI frame from the downstream remote host as a base64-encoded JPEG image.",
|
||||
"inputSchema": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"width": map[string]interface{}{"type": "integer", "description": "Target width in pixels (optional, default: 960)"},
|
||||
"height": map[string]interface{}{"type": "integer", "description": "Target height in pixels (optional)"},
|
||||
"quality": map[string]interface{}{"type": "integer", "description": "JPEG quality 1-100 (optional, default: 60)"},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "kvm_actions",
|
||||
"description": "Send one or more HID actions (click, type, hotkey, scroll, drag, move, wait) to the downstream remote host. Use normalized [0,1] coordinates for mouse actions.",
|
||||
"inputSchema": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"actions": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "Array of action objects. Each requires an 'action' field (click, move, type, hotkey, scroll, drag, wait).",
|
||||
"items": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"action": map[string]interface{}{"type": "string"},
|
||||
"x": map[string]interface{}{"type": "number"},
|
||||
"y": map[string]interface{}{"type": "number"},
|
||||
"button": map[string]interface{}{"type": "string"},
|
||||
"text": map[string]interface{}{"type": "string"},
|
||||
"keys": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}},
|
||||
"direction": map[string]interface{}{"type": "string"},
|
||||
"amount": map[string]interface{}{"type": "integer"},
|
||||
"duration_ms": map[string]interface{}{"type": "integer"},
|
||||
"from": map[string]interface{}{"type": "object", "properties": map[string]interface{}{"x": map[string]interface{}{"type": "number"}, "y": map[string]interface{}{"type": "number"}}},
|
||||
"to": map[string]interface{}{"type": "object", "properties": map[string]interface{}{"x": map[string]interface{}{"type": "number"}, "y": map[string]interface{}{"type": "number"}}},
|
||||
},
|
||||
"required": []string{"action"},
|
||||
},
|
||||
},
|
||||
},
|
||||
"required": []string{"actions"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// MCPHandler handles MCP HTTP transport (JSON-RPC 2.0 over POST).
|
||||
func (s *Service) MCPHandler(c *gin.Context) {
|
||||
var req jsonRPCRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Error: &jsonRPCError{Code: -32700, Message: "parse error"},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if req.JSONRPC != "2.0" {
|
||||
c.JSON(http.StatusOK, jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Error: &jsonRPCError{Code: -32600, Message: "invalid request: jsonrpc must be 2.0"},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var resp jsonRPCResponse
|
||||
switch req.Method {
|
||||
case "initialize":
|
||||
resp = s.mcpInitialize(req)
|
||||
case "tools/list":
|
||||
resp = s.mcpToolsList(req)
|
||||
case "tools/call":
|
||||
resp = s.mcpToolsCall(req, c)
|
||||
case "ping":
|
||||
resp = jsonRPCResponse{JSONRPC: "2.0", ID: req.ID, Result: map[string]interface{}{}}
|
||||
default:
|
||||
resp = jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Error: &jsonRPCError{Code: -32601, Message: fmt.Sprintf("method not found: %s", req.Method)},
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (s *Service) mcpInitialize(req jsonRPCRequest) jsonRPCResponse {
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Result: map[string]interface{}{
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": map[string]interface{}{
|
||||
"tools": map[string]interface{}{},
|
||||
},
|
||||
"serverInfo": map[string]interface{}{
|
||||
"name": "nanokvm",
|
||||
"version": "1.0.0",
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) mcpToolsList(req jsonRPCRequest) jsonRPCResponse {
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Result: map[string]interface{}{
|
||||
"tools": mcpToolDefinitions,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) mcpToolsCall(req jsonRPCRequest, c *gin.Context) jsonRPCResponse {
|
||||
var params struct {
|
||||
Name string `json:"name"`
|
||||
Arguments json.RawMessage `json:"arguments"`
|
||||
}
|
||||
if err := json.Unmarshal(req.Params, ¶ms); err != nil {
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Error: &jsonRPCError{Code: -32602, Message: "invalid params"},
|
||||
}
|
||||
}
|
||||
|
||||
switch params.Name {
|
||||
case "kvm_screenshot":
|
||||
return s.mcpScreenshot(req, params.Arguments, c)
|
||||
case "kvm_actions":
|
||||
return s.mcpActions(req, params.Arguments, c)
|
||||
default:
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Error: &jsonRPCError{Code: -32602, Message: fmt.Sprintf("unknown tool: %s", params.Name)},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) mcpScreenshot(req jsonRPCRequest, args json.RawMessage, c *gin.Context) jsonRPCResponse {
|
||||
var params struct {
|
||||
Width uint16 `json:"width"`
|
||||
Height uint16 `json:"height"`
|
||||
Quality uint16 `json:"quality"`
|
||||
}
|
||||
if args != nil {
|
||||
_ = json.Unmarshal(args, ¶ms)
|
||||
}
|
||||
|
||||
query := ScreenshotQuery{
|
||||
Format: "base64",
|
||||
Width: params.Width,
|
||||
Height: params.Height,
|
||||
Quality: params.Quality,
|
||||
}
|
||||
|
||||
data, meta, err := s.captureScreenshot(query)
|
||||
if err != nil {
|
||||
return mcpToolError(req, err.Message)
|
||||
}
|
||||
|
||||
b64 := base64.StdEncoding.EncodeToString(data)
|
||||
s.publishMCPObservation(c, "screenshot captured", b64)
|
||||
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Result: map[string]interface{}{
|
||||
"content": []map[string]interface{}{
|
||||
{
|
||||
"type": "text",
|
||||
"text": "screenshot captured",
|
||||
},
|
||||
{
|
||||
"type": "image",
|
||||
"data": b64,
|
||||
"mimeType": "image/jpeg",
|
||||
},
|
||||
},
|
||||
"meta": map[string]interface{}{
|
||||
"source_width": meta.SourceWidth,
|
||||
"source_height": meta.SourceHeight,
|
||||
"capture_width": meta.CaptureWidth,
|
||||
"capture_height": meta.CaptureHeight,
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) publishMCPObservation(c *gin.Context, text string, imageBase64 string) {
|
||||
if strings.TrimSpace(imageBase64) == "" {
|
||||
return
|
||||
}
|
||||
|
||||
sessionID, session, err := s.requireActiveGatewaySession(c)
|
||||
if err != nil || session == nil || session.Downstream == nil {
|
||||
return
|
||||
}
|
||||
|
||||
message := newPicoGatewayObservationMessage(sessionID, map[string]any{
|
||||
"content": text,
|
||||
"image_base64": imageBase64,
|
||||
"mime_type": "image/jpeg",
|
||||
})
|
||||
if writeErr := session.writeDownstreamJSON(s.config.Get(), message); writeErr != nil {
|
||||
log.Warnf("failed to deliver picoclaw observation message: %v", writeErr)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) mcpActions(req jsonRPCRequest, args json.RawMessage, c *gin.Context) jsonRPCResponse {
|
||||
var params struct {
|
||||
Actions []Action `json:"actions"`
|
||||
}
|
||||
if err := json.Unmarshal(args, ¶ms); err != nil {
|
||||
return mcpToolError(req, "invalid actions payload")
|
||||
}
|
||||
if len(params.Actions) == 0 {
|
||||
return mcpToolError(req, "empty actions array")
|
||||
}
|
||||
|
||||
sessionID := c.GetHeader(sessionIDHeader)
|
||||
if sessionID == "" {
|
||||
sessionID = s.lock.Owner()
|
||||
}
|
||||
|
||||
result, err := s.executeActions(sessionID, params.Actions)
|
||||
if err != nil {
|
||||
return mcpToolError(req, err.Message)
|
||||
}
|
||||
|
||||
resultJSON, _ := json.Marshal(result)
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Result: map[string]interface{}{
|
||||
"content": []map[string]interface{}{
|
||||
{
|
||||
"type": "text",
|
||||
"text": string(resultJSON),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func mcpToolError(req jsonRPCRequest, message string) jsonRPCResponse {
|
||||
return jsonRPCResponse{
|
||||
JSONRPC: "2.0",
|
||||
ID: req.ID,
|
||||
Result: map[string]interface{}{
|
||||
"isError": true,
|
||||
"content": []map[string]interface{}{
|
||||
{
|
||||
"type": "text",
|
||||
"text": message,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
225
server/service/picoclaw/model_config.go
Normal file
225
server/service/picoclaw/model_config.go
Normal file
@@ -0,0 +1,225 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func extractPicoclawModelName(model string) string {
|
||||
model = strings.TrimSpace(model)
|
||||
if model == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if index := strings.LastIndex(model, "/"); index >= 0 && index < len(model)-1 {
|
||||
return strings.TrimSpace(model[index+1:])
|
||||
}
|
||||
|
||||
return model
|
||||
}
|
||||
|
||||
func isPicoclawModelConfigured(cfg picoclawConfigFile, security picoclawSecurityConfig, modelName string) bool {
|
||||
if modelName == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, model := range cfg.ModelList {
|
||||
if strings.TrimSpace(model.ModelName) != modelName {
|
||||
continue
|
||||
}
|
||||
if model.APIBase == "" {
|
||||
continue
|
||||
}
|
||||
if securityHasModelAPIKeys(security, modelName) {
|
||||
return true
|
||||
}
|
||||
return configHasModelAPIKeys(model.APIKey, model.APIKeys)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func configHasModelAPIKeys(apiKey string, apiKeys []string) bool {
|
||||
return strings.TrimSpace(apiKey) != "" || len(apiKeys) > 0
|
||||
}
|
||||
|
||||
func securityHasModelAPIKeys(security picoclawSecurityConfig, modelName string) bool {
|
||||
if modelName == "" || len(security.ModelList) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
if entry, ok := security.ModelList[modelName]; ok && len(entry.APIKeys) > 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
prefix := modelName + ":"
|
||||
for key, entry := range security.ModelList {
|
||||
if strings.HasPrefix(key, prefix) && len(entry.APIKeys) > 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
type ModelConfigUpdateRequest struct {
|
||||
Model string `json:"model"`
|
||||
APIBase string `json:"api_base"`
|
||||
APIKey string `json:"api_key"`
|
||||
}
|
||||
|
||||
func (s *Service) UpdateModelConfig(c *gin.Context) {
|
||||
var req ModelConfigUpdateRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeInvalidAction, "invalid model config payload"))
|
||||
return
|
||||
}
|
||||
|
||||
currentStatus := s.runtime.Get()
|
||||
shouldRestart := currentStatus.Ready || currentStatus.Status == "ready"
|
||||
|
||||
modelName, err := updatePicoclawModelConfig(
|
||||
strings.TrimSpace(req.APIBase),
|
||||
strings.TrimSpace(req.APIKey),
|
||||
strings.TrimSpace(req.Model),
|
||||
)
|
||||
if err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, err.Error()))
|
||||
return
|
||||
}
|
||||
if err := ensurePicoclawStartupDefaults(); err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, "model config saved, but failed to persist picoclaw defaults: "+err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
if shouldRestart {
|
||||
if _, _, stopErr := s.stopRuntime(); stopErr != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, "model config saved, but failed to restart picoclaw runtime: "+stopErr.Message))
|
||||
return
|
||||
}
|
||||
if _, _, startErr := s.startRuntime(); startErr != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, "model config saved, but failed to restart picoclaw runtime: "+startErr.Message))
|
||||
return
|
||||
}
|
||||
} else {
|
||||
_ = s.syncConfigFromPicoclaw()
|
||||
_ = s.ensureRuntimeReady()
|
||||
}
|
||||
|
||||
writeSuccess(c, gin.H{
|
||||
"model_name": modelName,
|
||||
"status": s.runtime.Get(),
|
||||
})
|
||||
}
|
||||
|
||||
func updatePicoclawModelConfig(apiBase string, apiKey string, model string) (string, error) {
|
||||
if apiBase == "" {
|
||||
return "", fmt.Errorf("model api_base is required")
|
||||
}
|
||||
if apiKey == "" {
|
||||
return "", fmt.Errorf("model api_key is required")
|
||||
}
|
||||
if model == "" {
|
||||
return "", fmt.Errorf("model identifier is required")
|
||||
}
|
||||
|
||||
modelName := extractPicoclawModelName(model)
|
||||
if modelName == "" {
|
||||
return "", fmt.Errorf("model identifier is required")
|
||||
}
|
||||
|
||||
doc, err := loadPicoclawConfigDocument()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
modelListValue, ok := doc.raw["model_list"].([]any)
|
||||
if !ok {
|
||||
modelListValue = []any{}
|
||||
}
|
||||
|
||||
modelUpdated := false
|
||||
updatedModelIndex := -1
|
||||
for index, item := range modelListValue {
|
||||
modelMap, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
currentModelName := strings.TrimSpace(fmt.Sprintf("%v", modelMap["model_name"]))
|
||||
if currentModelName != modelName {
|
||||
continue
|
||||
}
|
||||
modelMap["model_name"] = modelName
|
||||
modelMap["model"] = model
|
||||
modelMap["api_base"] = apiBase
|
||||
delete(modelMap, "api_key")
|
||||
delete(modelMap, "api_keys")
|
||||
modelUpdated = true
|
||||
updatedModelIndex = index
|
||||
break
|
||||
}
|
||||
if !modelUpdated {
|
||||
modelListValue = append(modelListValue, map[string]any{
|
||||
"model_name": modelName,
|
||||
"model": model,
|
||||
"api_base": apiBase,
|
||||
})
|
||||
doc.raw["model_list"] = modelListValue
|
||||
updatedModelIndex = len(modelListValue) - 1
|
||||
}
|
||||
|
||||
agents, ok := doc.raw["agents"].(map[string]any)
|
||||
if !ok {
|
||||
agents = map[string]any{}
|
||||
doc.raw["agents"] = agents
|
||||
}
|
||||
defaults, ok := agents["defaults"].(map[string]any)
|
||||
if !ok {
|
||||
defaults = map[string]any{}
|
||||
agents["defaults"] = defaults
|
||||
}
|
||||
defaults["model_name"] = modelName
|
||||
delete(defaults, "model")
|
||||
|
||||
if err := doc.saveConfig(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if doc.security.ModelList == nil {
|
||||
doc.security.ModelList = map[string]picoclawModelSecurityEntry{}
|
||||
}
|
||||
securityModelName := indexedModelName(modelListValue, updatedModelIndex, modelName)
|
||||
doc.security.ModelList[securityModelName] = picoclawModelSecurityEntry{
|
||||
APIKeys: []string{apiKey},
|
||||
}
|
||||
if err := doc.saveSecurity(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return modelName, nil
|
||||
}
|
||||
|
||||
func indexedModelName(modelList []any, targetIndex int, modelName string) string {
|
||||
if targetIndex < 0 {
|
||||
return modelName
|
||||
}
|
||||
|
||||
currentIndex := 0
|
||||
for index, item := range modelList {
|
||||
modelMap, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
currentModelName := strings.TrimSpace(fmt.Sprintf("%v", modelMap["model_name"]))
|
||||
if currentModelName != modelName {
|
||||
continue
|
||||
}
|
||||
if index == targetIndex {
|
||||
return fmt.Sprintf("%s:%d", modelName, currentIndex)
|
||||
}
|
||||
currentIndex++
|
||||
}
|
||||
|
||||
return modelName
|
||||
}
|
||||
22
server/service/picoclaw/runtime_constants.go
Normal file
22
server/service/picoclaw/runtime_constants.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
picoclawBinaryPath = "/usr/bin/picoclaw"
|
||||
picoclawCacheDir = "/root/.picoclaw-cache"
|
||||
picoclawDownloadURL = "https://cdn.sipeed.com/nanokvm/resources/picoclaw/v0.2.6/picoclaw_Linux_riscv64.tar.gz"
|
||||
picoclawChecksumURL = "https://cdn.sipeed.com/nanokvm/resources/picoclaw/v0.2.6/sha512.txt"
|
||||
etcInitPicoclawScript = "/etc/init.d/S96picoclaw"
|
||||
kvmappPicoclawScript = "/kvmapp/system/init.d/S96picoclaw"
|
||||
picoclawStartTimeout = 15 * time.Second
|
||||
picoclawStopTimeout = 15 * time.Second
|
||||
picoclawOnboardTimeout = 60 * time.Second
|
||||
picoclawInstallTimeout = 12 * time.Minute
|
||||
picoclawDownloadTimeout = 10 * time.Minute
|
||||
picoclawStartWaitPeriod = 1500 * time.Millisecond
|
||||
picoclawStopWaitPeriod = 500 * time.Millisecond
|
||||
picoclawReadyPollPeriod = 500 * time.Millisecond
|
||||
)
|
||||
227
server/service/picoclaw/runtime_defaults.go
Normal file
227
server/service/picoclaw/runtime_defaults.go
Normal file
@@ -0,0 +1,227 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
serverConfig "NanoKVM-Server/config"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultPicoclawPingSec = 30
|
||||
defaultPicoclawReadSec = 60
|
||||
defaultPicoclawWriteSec = 10
|
||||
defaultPicoclawMaxConns = 100
|
||||
)
|
||||
|
||||
type picoclawConfigDefault struct {
|
||||
path []string
|
||||
value any
|
||||
}
|
||||
|
||||
var picoclawNanoKVMDefaults = []picoclawConfigDefault{
|
||||
{path: []string{"agents", "defaults", "restrict_to_workspace"}, value: false},
|
||||
{path: []string{"agents", "defaults", "allow_read_outside_workspace"}, value: true},
|
||||
{path: []string{"agents", "defaults", "tool_feedback", "enabled"}, value: true},
|
||||
{path: []string{"gateway", "host"}, value: defaultPicoclawGatewayHost},
|
||||
{path: []string{"gateway", "port"}, value: defaultPicoclawGatewayPort},
|
||||
{path: []string{"gateway", "hot_reload"}, value: false},
|
||||
{path: []string{"tools", "cron", "allow_command"}, value: true},
|
||||
{path: []string{"tools", "exec", "allow_remote"}, value: true},
|
||||
{path: []string{"tools", "exec", "enable_deny_patterns"}, value: false},
|
||||
{path: []string{"channels", "pico", "allow_token_query"}, value: false},
|
||||
{path: []string{"channels", "pico", "ping_interval"}, value: defaultPicoclawPingSec},
|
||||
{path: []string{"channels", "pico", "read_timeout"}, value: defaultPicoclawReadSec},
|
||||
{path: []string{"channels", "pico", "write_timeout"}, value: defaultPicoclawWriteSec},
|
||||
{path: []string{"channels", "pico", "max_connections"}, value: defaultPicoclawMaxConns},
|
||||
{path: []string{"tools", "mcp", "enabled"}, value: true},
|
||||
}
|
||||
|
||||
func ensurePicoclawStartupDefaults() error {
|
||||
doc, err := loadPicoclawConfigDocument()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
editor := &picoclawConfigEditor{raw: doc.raw}
|
||||
forceEnablePicoclawPicoChannel(doc, editor)
|
||||
if err := applyPicoclawStartupDefaults(editor); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tokenChanged, err := ensurePicoclawPicoToken(doc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if tokenChanged {
|
||||
if err := doc.saveSecurity(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if editor.changed {
|
||||
if err := doc.saveConfig(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensurePicoclawPicoChannelEnabled(doc *picoclawConfigDocument) error {
|
||||
if doc == nil || doc.config.Channels.Pico.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
editor := &picoclawConfigEditor{raw: doc.raw}
|
||||
forceEnablePicoclawPicoChannel(doc, editor)
|
||||
if !editor.changed {
|
||||
return nil
|
||||
}
|
||||
|
||||
return doc.saveConfig()
|
||||
}
|
||||
|
||||
func applyPicoclawStartupDefaults(editor *picoclawConfigEditor) error {
|
||||
for _, entry := range picoclawNanoKVMDefaults {
|
||||
editor.setValue(entry.value, entry.path...)
|
||||
}
|
||||
server, err := defaultPicoclawMCPServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
editor.setMCPServer("nanokvm", server)
|
||||
return nil
|
||||
}
|
||||
|
||||
func forceEnablePicoclawPicoChannel(doc *picoclawConfigDocument, editor *picoclawConfigEditor) {
|
||||
if doc == nil || editor == nil || doc.config.Channels.Pico.Enabled {
|
||||
return
|
||||
}
|
||||
|
||||
editor.setValue(true, "channels", "pico", "enabled")
|
||||
doc.config.Channels.Pico.Enabled = true
|
||||
}
|
||||
|
||||
func defaultPicoclawMCPServer() (map[string]any, error) {
|
||||
internalToken, err := serverConfig.GetPicoclawInternalToken()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return map[string]any{
|
||||
"enabled": true,
|
||||
"type": "http",
|
||||
"url": nanoKVMMCPURL(),
|
||||
"headers": map[string]any{
|
||||
serverConfig.PicoclawInternalTokenHeader: internalToken,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func nanoKVMMCPURL() string {
|
||||
port := serverConfig.GetInstance().Port.Http
|
||||
if port <= 0 {
|
||||
port = 80
|
||||
}
|
||||
|
||||
return fmt.Sprintf("http://%s:%d/api/picoclaw/mcp", defaultPicoclawGatewayHost, port)
|
||||
}
|
||||
|
||||
type picoclawConfigEditor struct {
|
||||
raw map[string]any
|
||||
changed bool
|
||||
}
|
||||
|
||||
func (e *picoclawConfigEditor) setValue(value any, path ...string) {
|
||||
if len(path) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
target := e.ensureObject(path[:len(path)-1]...)
|
||||
key := path[len(path)-1]
|
||||
if current, exists := target[key]; exists && reflect.DeepEqual(current, value) {
|
||||
return
|
||||
}
|
||||
|
||||
target[key] = value
|
||||
e.changed = true
|
||||
}
|
||||
|
||||
func (e *picoclawConfigEditor) ensureObject(path ...string) map[string]any {
|
||||
current := e.raw
|
||||
for _, key := range path {
|
||||
next, ok := current[key].(map[string]any)
|
||||
if !ok {
|
||||
next = map[string]any{}
|
||||
current[key] = next
|
||||
e.changed = true
|
||||
}
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
func (e *picoclawConfigEditor) setMCPServer(name string, fields map[string]any) {
|
||||
servers := e.ensureObject("tools", "mcp", "servers")
|
||||
entry, ok := servers[name].(map[string]any)
|
||||
if !ok {
|
||||
entry = map[string]any{}
|
||||
servers[name] = entry
|
||||
e.changed = true
|
||||
}
|
||||
|
||||
for key, value := range fields {
|
||||
if current, exists := entry[key]; exists && reflect.DeepEqual(current, value) {
|
||||
continue
|
||||
}
|
||||
entry[key] = value
|
||||
e.changed = true
|
||||
}
|
||||
}
|
||||
|
||||
func generatePicoclawToken() (string, error) {
|
||||
buf := make([]byte, 24)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
return "", fmt.Errorf("failed to generate picoclaw pico token: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(buf), nil
|
||||
}
|
||||
|
||||
func ensurePicoclawPicoToken(doc *picoclawConfigDocument) (bool, error) {
|
||||
token, err := picoSecurityToken(doc)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
if doc.security.Channels.Pico == nil {
|
||||
doc.security.Channels.Pico = &picoclawPicoSecurity{}
|
||||
}
|
||||
if strings.TrimSpace(doc.security.Channels.Pico.Token) == token {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
doc.security.Channels.Pico.Token = token
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func picoSecurityToken(doc *picoclawConfigDocument) (string, error) {
|
||||
if doc == nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if doc.security.Channels.Pico != nil {
|
||||
if token := strings.TrimSpace(doc.security.Channels.Pico.Token); token != "" {
|
||||
return token, nil
|
||||
}
|
||||
}
|
||||
|
||||
if token := strings.TrimSpace(doc.config.Channels.Pico.Token); token != "" {
|
||||
return token, nil
|
||||
}
|
||||
|
||||
return generatePicoclawToken()
|
||||
}
|
||||
110
server/service/picoclaw/runtime_handlers.go
Normal file
110
server/service/picoclaw/runtime_handlers.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func (s *Service) StartRuntime(c *gin.Context) {
|
||||
command, output, err := s.startRuntime()
|
||||
if err != nil {
|
||||
writePicoclawError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccess(c, RuntimeStartResult{
|
||||
Started: true,
|
||||
Command: command,
|
||||
Output: output,
|
||||
Status: s.runtime.Get(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) StopRuntime(c *gin.Context) {
|
||||
command, output, err := s.stopRuntime()
|
||||
if err != nil {
|
||||
writePicoclawError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccess(c, RuntimeStartResult{
|
||||
Started: false,
|
||||
Command: command,
|
||||
Output: output,
|
||||
Status: s.runtime.Get(),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) InstallRuntime(c *gin.Context) {
|
||||
output, err := s.installRuntime()
|
||||
if err != nil {
|
||||
writePicoclawError(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
currentStatus := s.runtime.Get()
|
||||
writeSuccess(c, RuntimeInstallResult{
|
||||
Installed: currentStatus.Installed && !currentStatus.Installing,
|
||||
Binary: picoclawBinaryPath,
|
||||
Download: picoclawDownloadURL,
|
||||
Output: output,
|
||||
Status: currentStatus,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) UninstallRuntime(c *gin.Context) {
|
||||
currentStatus := s.runtime.Get()
|
||||
uninstallOutput := "picoclaw uninstalled successfully"
|
||||
if currentStatus.Installing {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeStartFailed, "cannot uninstall while installation is in progress"))
|
||||
return
|
||||
}
|
||||
|
||||
running, err := isRuntimeRunning()
|
||||
if err != nil {
|
||||
writePicoclawError(c, newPicoclawError(CodeRuntimeUnavailable, "failed to check picoclaw runtime status"))
|
||||
return
|
||||
}
|
||||
|
||||
if running || currentStatus.Ready || currentStatus.Status == "ready" {
|
||||
if _, _, stopErr := s.stopRuntime(); stopErr != nil {
|
||||
uninstallOutput = "picoclaw uninstalled successfully (stop failed before uninstall: " + stopErr.Message + ")"
|
||||
}
|
||||
}
|
||||
|
||||
if configPath, err := resolvePicoclawConfigPath(); err == nil {
|
||||
_ = os.RemoveAll(filepath.Dir(configPath))
|
||||
} else {
|
||||
home, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
_ = os.RemoveAll(filepath.Join(home, ".picoclaw"))
|
||||
} else {
|
||||
_ = os.RemoveAll("/root/.picoclaw")
|
||||
}
|
||||
}
|
||||
_ = os.Remove(picoclawBinaryPath)
|
||||
_ = os.RemoveAll(picoclawCacheDir)
|
||||
|
||||
s.runtime.Set(RuntimeStatus{
|
||||
Ready: false,
|
||||
Installed: false,
|
||||
Installing: false,
|
||||
InstallProgress: 0,
|
||||
InstallStage: "",
|
||||
InstallPath: picoclawBinaryPath,
|
||||
Status: "not_installed",
|
||||
CheckedAt: time.Now(),
|
||||
CurrentSession: "",
|
||||
})
|
||||
|
||||
writeSuccess(c, RuntimeInstallResult{
|
||||
Installed: false,
|
||||
Binary: picoclawBinaryPath,
|
||||
Download: picoclawDownloadURL,
|
||||
Output: uninstallOutput,
|
||||
Status: s.runtime.Get(),
|
||||
})
|
||||
}
|
||||
441
server/service/picoclaw/runtime_install.go
Normal file
441
server/service/picoclaw/runtime_install.go
Normal file
@@ -0,0 +1,441 @@
|
||||
package picoclaw
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"crypto/sha512"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (s *Service) installRuntime() (string, *PicoclawError) {
|
||||
log.Debugf("picoclaw install: start, binary=%s, cache=%s", picoclawBinaryPath, picoclawCacheDir)
|
||||
|
||||
currentStatus := s.runtime.Get()
|
||||
if currentStatus.Installing {
|
||||
log.Debugf("picoclaw install: install already in progress")
|
||||
return "picoclaw installation is already in progress", nil
|
||||
}
|
||||
|
||||
if installed, err := isPicoclawInstalled(); err == nil && installed {
|
||||
settings, _ := loadPicoclawGatewaySettings()
|
||||
log.Debugf("picoclaw install: binary already exists at %s", picoclawBinaryPath)
|
||||
s.runtime.Set(RuntimeStatus{
|
||||
Ready: false,
|
||||
Installed: true,
|
||||
Installing: false,
|
||||
InstallProgress: 100,
|
||||
InstallStage: "installed",
|
||||
InstallPath: picoclawBinaryPath,
|
||||
ModelConfigured: settings.ModelConfigured,
|
||||
ModelName: settings.ModelName,
|
||||
Status: "installed",
|
||||
CheckedAt: time.Now(),
|
||||
})
|
||||
return "picoclaw is already installed", nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), picoclawInstallTimeout)
|
||||
s.runtime.Set(RuntimeStatus{
|
||||
Ready: false,
|
||||
Installed: false,
|
||||
Installing: true,
|
||||
InstallProgress: 0,
|
||||
InstallStage: "preparing",
|
||||
InstallPath: picoclawBinaryPath,
|
||||
Status: "installing",
|
||||
CheckedAt: time.Now(),
|
||||
})
|
||||
|
||||
go s.runInstallRuntime(ctx, cancel)
|
||||
return "picoclaw installation started", nil
|
||||
}
|
||||
|
||||
func (s *Service) runInstallRuntime(ctx context.Context, cancel context.CancelFunc) {
|
||||
defer cancel()
|
||||
|
||||
_ = os.RemoveAll(picoclawCacheDir)
|
||||
if err := os.MkdirAll(picoclawCacheDir, 0o755); err != nil {
|
||||
log.Errorf("picoclaw install: failed to create cache directory %s: %v", picoclawCacheDir, err)
|
||||
s.finishInstallFailure("install_failed", fmt.Sprintf("failed to create cache directory: %v", err))
|
||||
return
|
||||
}
|
||||
log.Debugf("picoclaw install: cache directory ready at %s", picoclawCacheDir)
|
||||
defer func() {
|
||||
if err := os.RemoveAll(picoclawCacheDir); err != nil {
|
||||
log.Errorf("picoclaw install: failed to clean cache directory %s: %v", picoclawCacheDir, err)
|
||||
return
|
||||
}
|
||||
log.Debugf("picoclaw install: cleaned cache directory %s", picoclawCacheDir)
|
||||
}()
|
||||
|
||||
s.setInstallProgress("downloading", 5, "")
|
||||
log.Debugf("picoclaw install: downloading checksum from %s", picoclawChecksumURL)
|
||||
expectedDigest, err := downloadPicoclawChecksum(ctx)
|
||||
if err != nil {
|
||||
log.Errorf("picoclaw install: checksum download failed: %v", err)
|
||||
s.finishInstallFailure(installFailureStatus(err), err.Error())
|
||||
return
|
||||
}
|
||||
log.Debug("picoclaw install: checksum file downloaded")
|
||||
|
||||
archivePath := filepath.Join(picoclawCacheDir, "picoclaw.tar.gz")
|
||||
log.Debugf("picoclaw install: downloading archive from %s to %s", picoclawDownloadURL, archivePath)
|
||||
if err := downloadPicoclawArchive(ctx, archivePath, func(downloaded int64, total int64) {
|
||||
progress := 10
|
||||
if total > 0 {
|
||||
progress = 10 + int(float64(downloaded)*70/float64(total))
|
||||
if progress > 80 {
|
||||
progress = 80
|
||||
}
|
||||
}
|
||||
s.setInstallProgress("downloading", progress, "")
|
||||
}); err != nil {
|
||||
log.Errorf("picoclaw install: download failed: %v", err)
|
||||
s.finishInstallFailure(installFailureStatus(err), err.Error())
|
||||
return
|
||||
}
|
||||
log.Debugf("picoclaw install: archive download completed")
|
||||
|
||||
s.setInstallProgress("verifying", 82, "")
|
||||
|
||||
if err := verifyFileSHA512(archivePath, expectedDigest); err != nil {
|
||||
log.Errorf("picoclaw install: checksum verification failed: %v", err)
|
||||
s.finishInstallFailure(installFailureStatus(err), err.Error())
|
||||
return
|
||||
}
|
||||
log.Debugf("picoclaw install: archive checksum verified for %s", archivePath)
|
||||
|
||||
s.setInstallProgress("extracting", 85, "")
|
||||
log.Debugf("picoclaw install: extracting binary from %s", archivePath)
|
||||
extractedPath, err := extractPicoclawBinary(archivePath, picoclawCacheDir)
|
||||
if err != nil {
|
||||
log.Errorf("picoclaw install: extract failed: %v", err)
|
||||
s.finishInstallFailure(installFailureStatus(err), err.Error())
|
||||
return
|
||||
}
|
||||
log.Debugf("picoclaw install: extracted binary to %s", extractedPath)
|
||||
|
||||
s.setInstallProgress("installing", 95, "")
|
||||
log.Debugf("picoclaw install: installing binary to %s", picoclawBinaryPath)
|
||||
if err := installPicoclawBinary(extractedPath, picoclawBinaryPath); err != nil {
|
||||
log.Errorf("picoclaw install: install failed: %v", err)
|
||||
s.finishInstallFailure(installFailureStatus(err), err.Error())
|
||||
return
|
||||
}
|
||||
log.Debugf("picoclaw install: install completed successfully")
|
||||
|
||||
s.runtime.Set(RuntimeStatus{
|
||||
Ready: false,
|
||||
Installed: true,
|
||||
Installing: false,
|
||||
InstallProgress: 100,
|
||||
InstallStage: "installed",
|
||||
InstallPath: picoclawBinaryPath,
|
||||
Status: "installed",
|
||||
CheckedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func downloadPicoclawArchive(ctx context.Context, destination string, onProgress func(downloaded int64, total int64)) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, picoclawDownloadURL, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create download request: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: picoclawDownloadTimeout,
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to download picoclaw: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to download picoclaw: unexpected status %s", resp.Status)
|
||||
}
|
||||
|
||||
file, err := os.Create(destination)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create archive file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if err := copyWithProgress(ctx, file, resp.Body, resp.ContentLength, onProgress); err != nil {
|
||||
return fmt.Errorf("failed to save archive: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func downloadPicoclawChecksum(ctx context.Context) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, picoclawChecksumURL, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create checksum request: %w", err)
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: picoclawDownloadTimeout,
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to download picoclaw checksum: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("failed to download picoclaw checksum: unexpected status %s", resp.Status)
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(resp.Body, 16*1024))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read checksum file: %w", err)
|
||||
}
|
||||
|
||||
digest, err := parseSHA512Digest(string(data), filepath.Base(picoclawDownloadURL))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return digest, nil
|
||||
}
|
||||
|
||||
func copyWithProgress(ctx context.Context, dst io.Writer, src io.Reader, total int64, onProgress func(downloaded int64, total int64)) error {
|
||||
buffer := make([]byte, 32*1024)
|
||||
var downloaded int64
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
default:
|
||||
}
|
||||
|
||||
n, readErr := src.Read(buffer)
|
||||
if n > 0 {
|
||||
if _, writeErr := dst.Write(buffer[:n]); writeErr != nil {
|
||||
return writeErr
|
||||
}
|
||||
downloaded += int64(n)
|
||||
if onProgress != nil {
|
||||
onProgress(downloaded, total)
|
||||
}
|
||||
}
|
||||
if readErr == io.EOF {
|
||||
if onProgress != nil {
|
||||
onProgress(downloaded, total)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) setInstallProgress(stage string, progress int, lastError string) {
|
||||
if progress < 0 {
|
||||
progress = 0
|
||||
}
|
||||
if progress > 100 {
|
||||
progress = 100
|
||||
}
|
||||
|
||||
s.runtime.UpdateInstallStatus(func(status *RuntimeStatus) {
|
||||
status.Ready = false
|
||||
status.Installed = false
|
||||
status.Installing = true
|
||||
status.InstallProgress = progress
|
||||
status.InstallStage = stage
|
||||
status.Status = "installing"
|
||||
status.LastError = lastError
|
||||
status.CheckedAt = time.Now()
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) finishInstallFailure(status string, message string) {
|
||||
s.runtime.Set(RuntimeStatus{
|
||||
Ready: false,
|
||||
Installed: false,
|
||||
Installing: false,
|
||||
InstallProgress: 0,
|
||||
InstallStage: status,
|
||||
InstallPath: picoclawBinaryPath,
|
||||
Status: status,
|
||||
LastError: message,
|
||||
CheckedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
func installFailureStatus(err error) string {
|
||||
if err == nil {
|
||||
return "install_failed"
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return "install_timeout"
|
||||
}
|
||||
return "install_failed"
|
||||
}
|
||||
|
||||
func parseSHA512Digest(raw string, expectedName string) (string, error) {
|
||||
lines := strings.Split(raw, "\n")
|
||||
var fallback string
|
||||
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if trimmed == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
fields := strings.Fields(trimmed)
|
||||
if len(fields) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
digest := fields[0]
|
||||
if !isValidSHA512Digest(digest) {
|
||||
continue
|
||||
}
|
||||
|
||||
if len(fields) == 1 {
|
||||
if fallback == "" {
|
||||
fallback = strings.ToLower(digest)
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
name := strings.TrimPrefix(fields[len(fields)-1], "*")
|
||||
if expectedName == "" || name == expectedName {
|
||||
return strings.ToLower(digest), nil
|
||||
}
|
||||
}
|
||||
|
||||
if fallback != "" {
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("failed to parse sha512 digest from checksum file")
|
||||
}
|
||||
|
||||
func isValidSHA512Digest(value string) bool {
|
||||
if len(value) != sha512.Size*2 {
|
||||
return false
|
||||
}
|
||||
|
||||
_, err := hex.DecodeString(value)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func verifyFileSHA512(filePath string, expectedDigest string) error {
|
||||
expectedDigest = strings.ToLower(strings.TrimSpace(expectedDigest))
|
||||
if !isValidSHA512Digest(expectedDigest) {
|
||||
return fmt.Errorf("invalid expected sha512 digest")
|
||||
}
|
||||
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open file for sha512 verification: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
hasher := sha512.New()
|
||||
if _, err := io.Copy(hasher, file); err != nil {
|
||||
return fmt.Errorf("failed to hash file for sha512 verification: %w", err)
|
||||
}
|
||||
|
||||
actualDigest := hex.EncodeToString(hasher.Sum(nil))
|
||||
if actualDigest != expectedDigest {
|
||||
return fmt.Errorf("sha512 mismatch: got %s", actualDigest)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func extractPicoclawBinary(archivePath string, destinationDir string) (string, error) {
|
||||
file, err := os.Open(archivePath)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to open archive: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
gzipReader, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read archive: %w", err)
|
||||
}
|
||||
defer gzipReader.Close()
|
||||
|
||||
tarReader := tar.NewReader(gzipReader)
|
||||
for {
|
||||
header, err := tarReader.Next()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to extract archive: %w", err)
|
||||
}
|
||||
if header.Typeflag != tar.TypeReg {
|
||||
continue
|
||||
}
|
||||
if filepath.Base(header.Name) != "picoclaw" {
|
||||
continue
|
||||
}
|
||||
|
||||
extractedPath := filepath.Join(destinationDir, "picoclaw")
|
||||
outFile, err := os.OpenFile(extractedPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create extracted binary: %w", err)
|
||||
}
|
||||
if _, err := io.Copy(outFile, tarReader); err != nil {
|
||||
_ = outFile.Close()
|
||||
return "", fmt.Errorf("failed to extract picoclaw binary: %w", err)
|
||||
}
|
||||
if err := outFile.Close(); err != nil {
|
||||
return "", fmt.Errorf("failed to finalize extracted binary: %w", err)
|
||||
}
|
||||
return extractedPath, nil
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("picoclaw binary not found in archive")
|
||||
}
|
||||
|
||||
func installPicoclawBinary(source string, destination string) error {
|
||||
inFile, err := os.Open(source)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to open extracted picoclaw binary: %w", err)
|
||||
}
|
||||
defer inFile.Close()
|
||||
|
||||
tempDestination := destination + ".tmp"
|
||||
outFile, err := os.OpenFile(tempDestination, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create destination binary: %w", err)
|
||||
}
|
||||
|
||||
if _, err := io.Copy(outFile, inFile); err != nil {
|
||||
_ = outFile.Close()
|
||||
_ = os.Remove(tempDestination)
|
||||
return fmt.Errorf("failed to write destination binary: %w", err)
|
||||
}
|
||||
if err := outFile.Close(); err != nil {
|
||||
_ = os.Remove(tempDestination)
|
||||
return fmt.Errorf("failed to finalize destination binary: %w", err)
|
||||
}
|
||||
if err := os.Chmod(tempDestination, 0o755); err != nil {
|
||||
_ = os.Remove(tempDestination)
|
||||
return fmt.Errorf("failed to set destination mode: %w", err)
|
||||
}
|
||||
if err := os.Rename(tempDestination, destination); err != nil {
|
||||
_ = os.Remove(tempDestination)
|
||||
return fmt.Errorf("failed to install picoclaw binary: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user