mirror of https://github.com/jetkvm/kvm.git
Compare commits
21 Commits
challenge-
...
main
Author | SHA1 | Date |
---|---|---|
|
fe77acd5f0 | |
|
83caa8f82d | |
|
27750b9cc2 | |
|
5112bef19c | |
|
1ffdca4fd6 | |
|
c6dba4d59f | |
|
afb146d78c | |
|
72e3013337 | |
|
25b102ac34 | |
|
5c94c6c87f | |
|
cf679978be | |
|
80a8b9e9e3 | |
|
1717549578 | |
|
37b1a8bf34 | |
|
ca8b06f4cf | |
|
33e099f258 | |
|
ea068414dc | |
|
8d1a66806c | |
|
6202e3cafa | |
|
c866230711 | |
|
c8dd84c6b7 |
|
@ -301,13 +301,14 @@ export JETKVM_PROXY_URL="ws://<IP>"
|
||||||
|
|
||||||
### Performance Profiling
|
### Performance Profiling
|
||||||
|
|
||||||
```bash
|
1. Enable `Developer Mode` on your JetKVM device
|
||||||
# Enable profiling
|
2. Add a password on the `Access` tab
|
||||||
go build -o bin/jetkvm_app -ldflags="-X main.enableProfiling=true" cmd/main.go
|
|
||||||
|
|
||||||
|
```bash
|
||||||
# Access profiling
|
# Access profiling
|
||||||
curl http://<IP>:6060/debug/pprof/
|
curl http://api:$JETKVM_PASSWORD@YOUR_DEVICE_IP/developer/pprof/
|
||||||
```
|
```
|
||||||
|
|
||||||
### Advanced Environment Variables
|
### Advanced Environment Variables
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
31
Makefile
31
Makefile
|
@ -1,9 +1,9 @@
|
||||||
BRANCH ?= $(shell git rev-parse --abbrev-ref HEAD)
|
BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
|
||||||
BUILDDATE ?= $(shell date -u +%FT%T%z)
|
BUILDDATE := $(shell date -u +%FT%T%z)
|
||||||
BUILDTS ?= $(shell date -u +%s)
|
BUILDTS := $(shell date -u +%s)
|
||||||
REVISION ?= $(shell git rev-parse HEAD)
|
REVISION := $(shell git rev-parse HEAD)
|
||||||
VERSION_DEV ?= 0.4.7-dev$(shell date +%Y%m%d%H%M)
|
VERSION_DEV := 0.4.9-dev$(shell date +%Y%m%d%H%M)
|
||||||
VERSION ?= 0.4.6
|
VERSION := 0.4.8
|
||||||
|
|
||||||
PROMETHEUS_TAG := github.com/prometheus/common/version
|
PROMETHEUS_TAG := github.com/prometheus/common/version
|
||||||
KVM_PKG_NAME := github.com/jetkvm/kvm
|
KVM_PKG_NAME := github.com/jetkvm/kvm
|
||||||
|
@ -62,10 +62,25 @@ build_dev_test: build_test2json build_gotestsum
|
||||||
tar czfv device-tests.tar.gz -C $(BIN_DIR)/tests .
|
tar czfv device-tests.tar.gz -C $(BIN_DIR)/tests .
|
||||||
|
|
||||||
frontend:
|
frontend:
|
||||||
cd ui && npm ci && npm run build:device
|
cd ui && npm ci && npm run build:device && \
|
||||||
|
find ../static/ \
|
||||||
|
-type f \
|
||||||
|
\( -name '*.js' \
|
||||||
|
-o -name '*.css' \
|
||||||
|
-o -name '*.html' \
|
||||||
|
-o -name '*.ico' \
|
||||||
|
-o -name '*.png' \
|
||||||
|
-o -name '*.jpg' \
|
||||||
|
-o -name '*.jpeg' \
|
||||||
|
-o -name '*.gif' \
|
||||||
|
-o -name '*.svg' \
|
||||||
|
-o -name '*.webp' \
|
||||||
|
-o -name '*.woff2' \
|
||||||
|
\) \
|
||||||
|
-exec sh -c 'gzip -9 -kfv {}' \;
|
||||||
|
|
||||||
dev_release: frontend build_dev
|
dev_release: frontend build_dev
|
||||||
@echo "Uploading release..."
|
@echo "Uploading release... $(VERSION_DEV)"
|
||||||
@shasum -a 256 bin/jetkvm_app | cut -d ' ' -f 1 > bin/jetkvm_app.sha256
|
@shasum -a 256 bin/jetkvm_app | cut -d ' ' -f 1 > bin/jetkvm_app.sha256
|
||||||
rclone copyto bin/jetkvm_app r2://jetkvm-update/app/$(VERSION_DEV)/jetkvm_app
|
rclone copyto bin/jetkvm_app r2://jetkvm-update/app/$(VERSION_DEV)/jetkvm_app
|
||||||
rclone copyto bin/jetkvm_app.sha256 r2://jetkvm-update/app/$(VERSION_DEV)/jetkvm_app.sha256
|
rclone copyto bin/jetkvm_app.sha256 r2://jetkvm-update/app/$(VERSION_DEV)/jetkvm_app.sha256
|
||||||
|
|
4
cloud.go
4
cloud.go
|
@ -475,6 +475,10 @@ func handleSessionRequest(
|
||||||
|
|
||||||
cloudLogger.Info().Interface("session", session).Msg("new session accepted")
|
cloudLogger.Info().Interface("session", session).Msg("new session accepted")
|
||||||
cloudLogger.Trace().Interface("session", session).Msg("new session accepted")
|
cloudLogger.Trace().Interface("session", session).Msg("new session accepted")
|
||||||
|
|
||||||
|
// Cancel any ongoing keyboard macro when session changes
|
||||||
|
cancelKeyboardMacro()
|
||||||
|
|
||||||
currentSession = session
|
currentSession = session
|
||||||
_ = wsjson.Write(context.Background(), c, gin.H{"type": "answer", "data": sd})
|
_ = wsjson.Write(context.Background(), c, gin.H{"type": "answer", "data": sd})
|
||||||
return nil
|
return nil
|
||||||
|
|
20
config.go
20
config.go
|
@ -118,6 +118,7 @@ var defaultConfig = &Config{
|
||||||
DisplayMaxBrightness: 64,
|
DisplayMaxBrightness: 64,
|
||||||
DisplayDimAfterSec: 120, // 2 minutes
|
DisplayDimAfterSec: 120, // 2 minutes
|
||||||
DisplayOffAfterSec: 1800, // 30 minutes
|
DisplayOffAfterSec: 1800, // 30 minutes
|
||||||
|
JigglerEnabled: false,
|
||||||
// This is the "Standard" jiggler option in the UI
|
// This is the "Standard" jiggler option in the UI
|
||||||
JigglerConfig: &JigglerConfig{
|
JigglerConfig: &JigglerConfig{
|
||||||
InactivityLimitSeconds: 60,
|
InactivityLimitSeconds: 60,
|
||||||
|
@ -205,6 +206,15 @@ func LoadConfig() {
|
||||||
loadedConfig.NetworkConfig = defaultConfig.NetworkConfig
|
loadedConfig.NetworkConfig = defaultConfig.NetworkConfig
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if loadedConfig.JigglerConfig == nil {
|
||||||
|
loadedConfig.JigglerConfig = defaultConfig.JigglerConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// fixup old keyboard layout value
|
||||||
|
if loadedConfig.KeyboardLayout == "en_US" {
|
||||||
|
loadedConfig.KeyboardLayout = "en-US"
|
||||||
|
}
|
||||||
|
|
||||||
config = &loadedConfig
|
config = &loadedConfig
|
||||||
|
|
||||||
logging.GetRootLogger().UpdateLogLevel(config.DefaultLogLevel)
|
logging.GetRootLogger().UpdateLogLevel(config.DefaultLogLevel)
|
||||||
|
@ -221,6 +231,11 @@ func SaveConfig() error {
|
||||||
|
|
||||||
logger.Trace().Str("path", configPath).Msg("Saving config")
|
logger.Trace().Str("path", configPath).Msg("Saving config")
|
||||||
|
|
||||||
|
// fixup old keyboard layout value
|
||||||
|
if config.KeyboardLayout == "en_US" {
|
||||||
|
config.KeyboardLayout = "en-US"
|
||||||
|
}
|
||||||
|
|
||||||
file, err := os.Create(configPath)
|
file, err := os.Create(configPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create config file: %w", err)
|
return fmt.Errorf("failed to create config file: %w", err)
|
||||||
|
@ -233,6 +248,11 @@ func SaveConfig() error {
|
||||||
return fmt.Errorf("failed to encode config: %w", err)
|
return fmt.Errorf("failed to encode config: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := file.Sync(); err != nil {
|
||||||
|
return fmt.Errorf("failed to wite config: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Info().Str("path", configPath).Msg("config saved")
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
90
display.go
90
display.go
|
@ -1,6 +1,7 @@
|
||||||
package kvm
|
package kvm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
@ -63,11 +64,11 @@ func lvObjSetOpacity(objName string, opacity int) (*CtrlResponse, error) { // no
|
||||||
}
|
}
|
||||||
|
|
||||||
func lvObjFadeIn(objName string, duration uint32) (*CtrlResponse, error) {
|
func lvObjFadeIn(objName string, duration uint32) (*CtrlResponse, error) {
|
||||||
return CallCtrlAction("lv_obj_fade_in", map[string]any{"obj": objName, "time": duration})
|
return CallCtrlAction("lv_obj_fade_in", map[string]any{"obj": objName, "duration": duration})
|
||||||
}
|
}
|
||||||
|
|
||||||
func lvObjFadeOut(objName string, duration uint32) (*CtrlResponse, error) {
|
func lvObjFadeOut(objName string, duration uint32) (*CtrlResponse, error) {
|
||||||
return CallCtrlAction("lv_obj_fade_out", map[string]any{"obj": objName, "time": duration})
|
return CallCtrlAction("lv_obj_fade_out", map[string]any{"obj": objName, "duration": duration})
|
||||||
}
|
}
|
||||||
|
|
||||||
func lvLabelSetText(objName string, text string) (*CtrlResponse, error) {
|
func lvLabelSetText(objName string, text string) (*CtrlResponse, error) {
|
||||||
|
@ -110,12 +111,6 @@ func clearDisplayState() {
|
||||||
currentScreen = "ui_Boot_Screen"
|
currentScreen = "ui_Boot_Screen"
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
|
||||||
cloudBlinkLock sync.Mutex = sync.Mutex{}
|
|
||||||
cloudBlinkStopped bool
|
|
||||||
cloudBlinkTicker *time.Ticker
|
|
||||||
)
|
|
||||||
|
|
||||||
func updateDisplay() {
|
func updateDisplay() {
|
||||||
updateLabelIfChanged("ui_Home_Content_Ip", networkState.IPv4String())
|
updateLabelIfChanged("ui_Home_Content_Ip", networkState.IPv4String())
|
||||||
if usbState == "configured" {
|
if usbState == "configured" {
|
||||||
|
@ -152,48 +147,81 @@ func updateDisplay() {
|
||||||
stopCloudBlink()
|
stopCloudBlink()
|
||||||
case CloudConnectionStateConnecting:
|
case CloudConnectionStateConnecting:
|
||||||
_, _ = lvImgSetSrc("ui_Home_Header_Cloud_Status_Icon", "cloud.png")
|
_, _ = lvImgSetSrc("ui_Home_Header_Cloud_Status_Icon", "cloud.png")
|
||||||
startCloudBlink()
|
restartCloudBlink()
|
||||||
case CloudConnectionStateConnected:
|
case CloudConnectionStateConnected:
|
||||||
_, _ = lvImgSetSrc("ui_Home_Header_Cloud_Status_Icon", "cloud.png")
|
_, _ = lvImgSetSrc("ui_Home_Header_Cloud_Status_Icon", "cloud.png")
|
||||||
stopCloudBlink()
|
stopCloudBlink()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func startCloudBlink() {
|
const (
|
||||||
if cloudBlinkTicker == nil {
|
cloudBlinkInterval = 2 * time.Second
|
||||||
cloudBlinkTicker = time.NewTicker(2 * time.Second)
|
cloudBlinkDuration = 1 * time.Second
|
||||||
} else {
|
)
|
||||||
// do nothing if the blink isn't stopped
|
|
||||||
if cloudBlinkStopped {
|
|
||||||
cloudBlinkLock.Lock()
|
|
||||||
defer cloudBlinkLock.Unlock()
|
|
||||||
|
|
||||||
cloudBlinkStopped = false
|
var (
|
||||||
cloudBlinkTicker.Reset(2 * time.Second)
|
cloudBlinkTicker *time.Ticker
|
||||||
}
|
cloudBlinkCancel context.CancelFunc
|
||||||
}
|
cloudBlinkLock = sync.Mutex{}
|
||||||
|
)
|
||||||
|
|
||||||
go func() {
|
func doCloudBlink(ctx context.Context) {
|
||||||
for range cloudBlinkTicker.C {
|
for range cloudBlinkTicker.C {
|
||||||
if cloudConnectionState != CloudConnectionStateConnecting {
|
if cloudConnectionState != CloudConnectionStateConnecting {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
_, _ = lvObjFadeOut("ui_Home_Header_Cloud_Status_Icon", 1000)
|
|
||||||
time.Sleep(1000 * time.Millisecond)
|
_, _ = lvObjFadeOut("ui_Home_Header_Cloud_Status_Icon", uint32(cloudBlinkDuration.Milliseconds()))
|
||||||
_, _ = lvObjFadeIn("ui_Home_Header_Cloud_Status_Icon", 1000)
|
|
||||||
time.Sleep(1000 * time.Millisecond)
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-time.After(cloudBlinkDuration):
|
||||||
}
|
}
|
||||||
}()
|
|
||||||
|
_, _ = lvObjFadeIn("ui_Home_Header_Cloud_Status_Icon", uint32(cloudBlinkDuration.Milliseconds()))
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-time.After(cloudBlinkDuration):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func restartCloudBlink() {
|
||||||
|
stopCloudBlink()
|
||||||
|
startCloudBlink()
|
||||||
|
}
|
||||||
|
|
||||||
|
func startCloudBlink() {
|
||||||
|
cloudBlinkLock.Lock()
|
||||||
|
defer cloudBlinkLock.Unlock()
|
||||||
|
|
||||||
|
if cloudBlinkTicker == nil {
|
||||||
|
cloudBlinkTicker = time.NewTicker(cloudBlinkInterval)
|
||||||
|
} else {
|
||||||
|
cloudBlinkTicker.Reset(cloudBlinkInterval)
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
cloudBlinkCancel = cancel
|
||||||
|
|
||||||
|
go doCloudBlink(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
func stopCloudBlink() {
|
func stopCloudBlink() {
|
||||||
|
cloudBlinkLock.Lock()
|
||||||
|
defer cloudBlinkLock.Unlock()
|
||||||
|
|
||||||
|
if cloudBlinkCancel != nil {
|
||||||
|
cloudBlinkCancel()
|
||||||
|
cloudBlinkCancel = nil
|
||||||
|
}
|
||||||
|
|
||||||
if cloudBlinkTicker != nil {
|
if cloudBlinkTicker != nil {
|
||||||
cloudBlinkTicker.Stop()
|
cloudBlinkTicker.Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
cloudBlinkLock.Lock()
|
|
||||||
defer cloudBlinkLock.Unlock()
|
|
||||||
cloudBlinkStopped = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
|
3
go.mod
3
go.mod
|
@ -12,6 +12,7 @@ require (
|
||||||
github.com/gin-contrib/logger v1.2.6
|
github.com/gin-contrib/logger v1.2.6
|
||||||
github.com/gin-gonic/gin v1.10.1
|
github.com/gin-gonic/gin v1.10.1
|
||||||
github.com/go-co-op/gocron/v2 v2.16.5
|
github.com/go-co-op/gocron/v2 v2.16.5
|
||||||
|
github.com/google/flatbuffers v25.2.10+incompatible
|
||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/guregu/null/v6 v6.0.0
|
github.com/guregu/null/v6 v6.0.0
|
||||||
github.com/gwatts/rootcerts v0.0.0-20250901182336-dc5ae18bd79f
|
github.com/gwatts/rootcerts v0.0.0-20250901182336-dc5ae18bd79f
|
||||||
|
@ -23,6 +24,7 @@ require (
|
||||||
github.com/prometheus/common v0.66.0
|
github.com/prometheus/common v0.66.0
|
||||||
github.com/prometheus/procfs v0.17.0
|
github.com/prometheus/procfs v0.17.0
|
||||||
github.com/psanford/httpreadat v0.1.0
|
github.com/psanford/httpreadat v0.1.0
|
||||||
|
github.com/rs/xid v1.6.0
|
||||||
github.com/rs/zerolog v1.34.0
|
github.com/rs/zerolog v1.34.0
|
||||||
github.com/sourcegraph/tf-dag v0.2.2-0.20250131204052-3e8ff1477b4f
|
github.com/sourcegraph/tf-dag v0.2.2-0.20250131204052-3e8ff1477b4f
|
||||||
github.com/stretchr/testify v1.11.1
|
github.com/stretchr/testify v1.11.1
|
||||||
|
@ -81,6 +83,7 @@ require (
|
||||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||||
|
github.com/vearutop/statigz v1.5.0 // indirect
|
||||||
github.com/vishvananda/netns v0.0.5 // indirect
|
github.com/vishvananda/netns v0.0.5 // indirect
|
||||||
github.com/wlynxg/anet v0.0.5 // indirect
|
github.com/wlynxg/anet v0.0.5 // indirect
|
||||||
golang.org/x/arch v0.18.0 // indirect
|
golang.org/x/arch v0.18.0 // indirect
|
||||||
|
|
5
go.sum
5
go.sum
|
@ -53,6 +53,8 @@ github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAu
|
||||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||||
|
github.com/google/flatbuffers v25.2.10+incompatible h1:F3vclr7C3HpB1k9mxCGRMXq6FdUalZ6H/pNX4FP1v0Q=
|
||||||
|
github.com/google/flatbuffers v25.2.10+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8=
|
||||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
@ -152,6 +154,7 @@ github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
|
||||||
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
|
||||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
|
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||||
|
@ -171,6 +174,8 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||||
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||||
|
github.com/vearutop/statigz v1.5.0 h1:FuWwZiT82yBw4xbWdWIawiP2XFTyEPhIo8upRxiKLqk=
|
||||||
|
github.com/vearutop/statigz v1.5.0/go.mod h1:oHmjFf3izfCO804Di1ZjB666P3fAlVzJEx2k6jNt/Gk=
|
||||||
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
|
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
|
||||||
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
|
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
|
||||||
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||||
|
|
127
hidrpc.go
127
hidrpc.go
|
@ -1,11 +1,14 @@
|
||||||
package kvm
|
package kvm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/jetkvm/kvm/internal/hidrpc"
|
"github.com/jetkvm/kvm/internal/hidrpc"
|
||||||
"github.com/jetkvm/kvm/internal/usbgadget"
|
"github.com/jetkvm/kvm/internal/usbgadget"
|
||||||
|
"github.com/rs/zerolog"
|
||||||
)
|
)
|
||||||
|
|
||||||
func handleHidRPCMessage(message hidrpc.Message, session *Session) {
|
func handleHidRPCMessage(message hidrpc.Message, session *Session) {
|
||||||
|
@ -24,11 +27,19 @@ func handleHidRPCMessage(message hidrpc.Message, session *Session) {
|
||||||
}
|
}
|
||||||
session.hidRPCAvailable = true
|
session.hidRPCAvailable = true
|
||||||
case hidrpc.TypeKeypressReport, hidrpc.TypeKeyboardReport:
|
case hidrpc.TypeKeypressReport, hidrpc.TypeKeyboardReport:
|
||||||
keysDownState, err := handleHidRPCKeyboardInput(message)
|
rpcErr = handleHidRPCKeyboardInput(message)
|
||||||
if keysDownState != nil {
|
case hidrpc.TypeKeyboardMacroReport:
|
||||||
session.reportHidRPCKeysDownState(*keysDownState)
|
keyboardMacroReport, err := message.KeyboardMacroReport()
|
||||||
|
if err != nil {
|
||||||
|
logger.Warn().Err(err).Msg("failed to get keyboard macro report")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
rpcErr = err
|
rpcErr = rpcExecuteKeyboardMacro(keyboardMacroReport.Steps)
|
||||||
|
case hidrpc.TypeCancelKeyboardMacroReport:
|
||||||
|
rpcCancelKeyboardMacro()
|
||||||
|
return
|
||||||
|
case hidrpc.TypeKeypressKeepAliveReport:
|
||||||
|
rpcErr = handleHidRPCKeypressKeepAlive(session)
|
||||||
case hidrpc.TypePointerReport:
|
case hidrpc.TypePointerReport:
|
||||||
pointerReport, err := message.PointerReport()
|
pointerReport, err := message.PointerReport()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -52,8 +63,13 @@ func handleHidRPCMessage(message hidrpc.Message, session *Session) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func onHidMessage(data []byte, session *Session) {
|
func onHidMessage(msg hidQueueMessage, session *Session) {
|
||||||
scopedLogger := hidRPCLogger.With().Bytes("data", data).Logger()
|
data := msg.Data
|
||||||
|
|
||||||
|
scopedLogger := hidRPCLogger.With().
|
||||||
|
Str("channel", msg.channel).
|
||||||
|
Bytes("data", data).
|
||||||
|
Logger()
|
||||||
scopedLogger.Debug().Msg("HID RPC message received")
|
scopedLogger.Debug().Msg("HID RPC message received")
|
||||||
|
|
||||||
if len(data) < 1 {
|
if len(data) < 1 {
|
||||||
|
@ -68,7 +84,9 @@ func onHidMessage(data []byte, session *Session) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if scopedLogger.GetLevel() <= zerolog.DebugLevel {
|
||||||
scopedLogger = scopedLogger.With().Str("descr", message.String()).Logger()
|
scopedLogger = scopedLogger.With().Str("descr", message.String()).Logger()
|
||||||
|
}
|
||||||
|
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
|
@ -85,27 +103,88 @@ func onHidMessage(data []byte, session *Session) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleHidRPCKeyboardInput(message hidrpc.Message) (*usbgadget.KeysDownState, error) {
|
// Tunables
|
||||||
|
// Keep in mind
|
||||||
|
// macOS default: 15 * 15 = 225ms https://discussions.apple.com/thread/1316947?sortBy=rank
|
||||||
|
// Linux default: 250ms https://man.archlinux.org/man/kbdrate.8.en
|
||||||
|
// Windows default: 1s `HKEY_CURRENT_USER\Control Panel\Accessibility\Keyboard Response\AutoRepeatDelay`
|
||||||
|
|
||||||
|
const expectedRate = 50 * time.Millisecond // expected keepalive interval
|
||||||
|
const maxLateness = 50 * time.Millisecond // max jitter we'll tolerate OR jitter budget
|
||||||
|
const baseExtension = expectedRate + maxLateness // 100ms extension on perfect tick
|
||||||
|
|
||||||
|
const maxStaleness = 225 * time.Millisecond // discard ancient packets outright
|
||||||
|
|
||||||
|
func handleHidRPCKeypressKeepAlive(session *Session) error {
|
||||||
|
session.keepAliveJitterLock.Lock()
|
||||||
|
defer session.keepAliveJitterLock.Unlock()
|
||||||
|
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
// 1) Staleness guard: ensures packets that arrive far beyond the life of a valid key hold
|
||||||
|
// (e.g. after a network stall, retransmit burst, or machine sleep) are ignored outright.
|
||||||
|
// This prevents “zombie” keepalives from reviving a key that should already be released.
|
||||||
|
if !session.lastTimerResetTime.IsZero() && now.Sub(session.lastTimerResetTime) > maxStaleness {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
validTick := true
|
||||||
|
timerExtension := baseExtension
|
||||||
|
|
||||||
|
if !session.lastKeepAliveArrivalTime.IsZero() {
|
||||||
|
timeSinceLastTick := now.Sub(session.lastKeepAliveArrivalTime)
|
||||||
|
lateness := timeSinceLastTick - expectedRate
|
||||||
|
|
||||||
|
if lateness > 0 {
|
||||||
|
if lateness <= maxLateness {
|
||||||
|
// --- Small lateness (within jitterBudget) ---
|
||||||
|
// This is normal jitter (e.g., Wi-Fi contention).
|
||||||
|
// We still accept the tick, but *reduce the extension*
|
||||||
|
// so that the total hold time stays aligned with REAL client side intent.
|
||||||
|
timerExtension -= lateness
|
||||||
|
} else {
|
||||||
|
// --- Large lateness (beyond jitterBudget) ---
|
||||||
|
// This is likely a retransmit stall or ordering delay.
|
||||||
|
// We reject the tick entirely and DO NOT extend,
|
||||||
|
// so the auto-release still fires on time.
|
||||||
|
validTick = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !validTick {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
// Only valid ticks update our state and extend the timer.
|
||||||
|
session.lastKeepAliveArrivalTime = now
|
||||||
|
session.lastTimerResetTime = now
|
||||||
|
if gadget != nil {
|
||||||
|
gadget.DelayAutoReleaseWithDuration(timerExtension)
|
||||||
|
}
|
||||||
|
|
||||||
|
// On a miss: do not advance any state — keeps baseline stable.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleHidRPCKeyboardInput(message hidrpc.Message) error {
|
||||||
switch message.Type() {
|
switch message.Type() {
|
||||||
case hidrpc.TypeKeypressReport:
|
case hidrpc.TypeKeypressReport:
|
||||||
keypressReport, err := message.KeypressReport()
|
keypressReport, err := message.KeypressReport()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warn().Err(err).Msg("failed to get keypress report")
|
logger.Warn().Err(err).Msg("failed to get keypress report")
|
||||||
return nil, err
|
return err
|
||||||
}
|
}
|
||||||
keysDownState, rpcError := rpcKeypressReport(keypressReport.Key, keypressReport.Press)
|
return rpcKeypressReport(keypressReport.Key, keypressReport.Press)
|
||||||
return &keysDownState, rpcError
|
|
||||||
case hidrpc.TypeKeyboardReport:
|
case hidrpc.TypeKeyboardReport:
|
||||||
keyboardReport, err := message.KeyboardReport()
|
keyboardReport, err := message.KeyboardReport()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warn().Err(err).Msg("failed to get keyboard report")
|
logger.Warn().Err(err).Msg("failed to get keyboard report")
|
||||||
return nil, err
|
return err
|
||||||
}
|
}
|
||||||
keysDownState, rpcError := rpcKeyboardReport(keyboardReport.Modifier, keyboardReport.Keys)
|
return rpcKeyboardReport(keyboardReport.Modifier, keyboardReport.Keys)
|
||||||
return &keysDownState, rpcError
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, fmt.Errorf("unknown HID RPC message type: %d", message.Type())
|
return fmt.Errorf("unknown HID RPC message type: %d", message.Type())
|
||||||
}
|
}
|
||||||
|
|
||||||
func reportHidRPC(params any, session *Session) {
|
func reportHidRPC(params any, session *Session) {
|
||||||
|
@ -115,7 +194,10 @@ func reportHidRPC(params any, session *Session) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if !session.hidRPCAvailable || session.HidChannel == nil {
|
if !session.hidRPCAvailable || session.HidChannel == nil {
|
||||||
logger.Warn().Msg("HID RPC is not available, skipping reportHidRPC")
|
logger.Warn().
|
||||||
|
Bool("hidRPCAvailable", session.hidRPCAvailable).
|
||||||
|
Bool("HidChannel", session.HidChannel != nil).
|
||||||
|
Msg("HID RPC is not available, skipping reportHidRPC")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -128,6 +210,8 @@ func reportHidRPC(params any, session *Session) {
|
||||||
message, err = hidrpc.NewKeyboardLedMessage(params).Marshal()
|
message, err = hidrpc.NewKeyboardLedMessage(params).Marshal()
|
||||||
case usbgadget.KeysDownState:
|
case usbgadget.KeysDownState:
|
||||||
message, err = hidrpc.NewKeydownStateMessage(params).Marshal()
|
message, err = hidrpc.NewKeydownStateMessage(params).Marshal()
|
||||||
|
case hidrpc.KeyboardMacroState:
|
||||||
|
message, err = hidrpc.NewKeyboardMacroStateMessage(params.State, params.IsPaste).Marshal()
|
||||||
default:
|
default:
|
||||||
err = fmt.Errorf("unknown HID RPC message type: %T", params)
|
err = fmt.Errorf("unknown HID RPC message type: %T", params)
|
||||||
}
|
}
|
||||||
|
@ -143,6 +227,10 @@ func reportHidRPC(params any, session *Session) {
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := session.HidChannel.Send(message); err != nil {
|
if err := session.HidChannel.Send(message); err != nil {
|
||||||
|
if errors.Is(err, io.ErrClosedPipe) {
|
||||||
|
logger.Debug().Err(err).Msg("HID RPC channel closed, skipping reportHidRPC")
|
||||||
|
return
|
||||||
|
}
|
||||||
logger.Warn().Err(err).Msg("failed to send HID RPC message")
|
logger.Warn().Err(err).Msg("failed to send HID RPC message")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -156,7 +244,16 @@ func (s *Session) reportHidRPCKeyboardLedState(state usbgadget.KeyboardState) {
|
||||||
|
|
||||||
func (s *Session) reportHidRPCKeysDownState(state usbgadget.KeysDownState) {
|
func (s *Session) reportHidRPCKeysDownState(state usbgadget.KeysDownState) {
|
||||||
if !s.hidRPCAvailable {
|
if !s.hidRPCAvailable {
|
||||||
|
usbLogger.Debug().Interface("state", state).Msg("reporting keys down state")
|
||||||
writeJSONRPCEvent("keysDownState", state, s)
|
writeJSONRPCEvent("keysDownState", state, s)
|
||||||
}
|
}
|
||||||
|
usbLogger.Debug().Interface("state", state).Msg("reporting keys down state, calling reportHidRPC")
|
||||||
|
reportHidRPC(state, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Session) reportHidRPCKeyboardMacroState(state hidrpc.KeyboardMacroState) {
|
||||||
|
if !s.hidRPCAvailable {
|
||||||
|
writeJSONRPCEvent("keyboardMacroState", state, s)
|
||||||
|
}
|
||||||
reportHidRPC(state, s)
|
reportHidRPC(state, s)
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,9 +15,13 @@ const (
|
||||||
TypePointerReport MessageType = 0x03
|
TypePointerReport MessageType = 0x03
|
||||||
TypeWheelReport MessageType = 0x04
|
TypeWheelReport MessageType = 0x04
|
||||||
TypeKeypressReport MessageType = 0x05
|
TypeKeypressReport MessageType = 0x05
|
||||||
|
TypeKeypressKeepAliveReport MessageType = 0x09
|
||||||
TypeMouseReport MessageType = 0x06
|
TypeMouseReport MessageType = 0x06
|
||||||
|
TypeKeyboardMacroReport MessageType = 0x07
|
||||||
|
TypeCancelKeyboardMacroReport MessageType = 0x08
|
||||||
TypeKeyboardLedState MessageType = 0x32
|
TypeKeyboardLedState MessageType = 0x32
|
||||||
TypeKeydownState MessageType = 0x33
|
TypeKeydownState MessageType = 0x33
|
||||||
|
TypeKeyboardMacroState MessageType = 0x34
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -29,10 +33,13 @@ func GetQueueIndex(messageType MessageType) int {
|
||||||
switch messageType {
|
switch messageType {
|
||||||
case TypeHandshake:
|
case TypeHandshake:
|
||||||
return 0
|
return 0
|
||||||
case TypeKeyboardReport, TypeKeypressReport, TypeKeyboardLedState, TypeKeydownState:
|
case TypeKeyboardReport, TypeKeypressReport, TypeKeyboardMacroReport, TypeKeyboardLedState, TypeKeydownState, TypeKeyboardMacroState:
|
||||||
return 1
|
return 1
|
||||||
case TypePointerReport, TypeMouseReport, TypeWheelReport:
|
case TypePointerReport, TypeMouseReport, TypeWheelReport:
|
||||||
return 2
|
return 2
|
||||||
|
// we don't want to block the queue for this message
|
||||||
|
case TypeCancelKeyboardMacroReport:
|
||||||
|
return 3
|
||||||
default:
|
default:
|
||||||
return 3
|
return 3
|
||||||
}
|
}
|
||||||
|
@ -98,3 +105,19 @@ func NewKeydownStateMessage(state usbgadget.KeysDownState) *Message {
|
||||||
d: data,
|
d: data,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewKeyboardMacroStateMessage creates a new keyboard macro state message.
|
||||||
|
func NewKeyboardMacroStateMessage(state bool, isPaste bool) *Message {
|
||||||
|
data := make([]byte, 2)
|
||||||
|
if state {
|
||||||
|
data[0] = 1
|
||||||
|
}
|
||||||
|
if isPaste {
|
||||||
|
data[1] = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Message{
|
||||||
|
t: TypeKeyboardMacroState,
|
||||||
|
d: data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,6 +1,7 @@
|
||||||
package hidrpc
|
package hidrpc
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -43,6 +44,13 @@ func (m *Message) String() string {
|
||||||
return fmt.Sprintf("MouseReport{Malformed: %v}", m.d)
|
return fmt.Sprintf("MouseReport{Malformed: %v}", m.d)
|
||||||
}
|
}
|
||||||
return fmt.Sprintf("MouseReport{DX: %d, DY: %d, Button: %d}", m.d[0], m.d[1], m.d[2])
|
return fmt.Sprintf("MouseReport{DX: %d, DY: %d, Button: %d}", m.d[0], m.d[1], m.d[2])
|
||||||
|
case TypeKeypressKeepAliveReport:
|
||||||
|
return "KeypressKeepAliveReport"
|
||||||
|
case TypeKeyboardMacroReport:
|
||||||
|
if len(m.d) < 5 {
|
||||||
|
return fmt.Sprintf("KeyboardMacroReport{Malformed: %v}", m.d)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("KeyboardMacroReport{IsPaste: %v, Length: %d}", m.d[0] == uint8(1), binary.BigEndian.Uint32(m.d[1:5]))
|
||||||
default:
|
default:
|
||||||
return fmt.Sprintf("Unknown{Type: %d, Data: %v}", m.t, m.d)
|
return fmt.Sprintf("Unknown{Type: %d, Data: %v}", m.t, m.d)
|
||||||
}
|
}
|
||||||
|
@ -84,6 +92,55 @@ func (m *Message) KeyboardReport() (KeyboardReport, error) {
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Macro ..
|
||||||
|
type KeyboardMacroStep struct {
|
||||||
|
Modifier byte // 1 byte
|
||||||
|
Keys []byte // 6 bytes: hidKeyBufferSize
|
||||||
|
Delay uint16 // 2 bytes
|
||||||
|
}
|
||||||
|
type KeyboardMacroReport struct {
|
||||||
|
IsPaste bool
|
||||||
|
StepCount uint32
|
||||||
|
Steps []KeyboardMacroStep
|
||||||
|
}
|
||||||
|
|
||||||
|
// HidKeyBufferSize is the size of the keys buffer in the keyboard report.
|
||||||
|
const HidKeyBufferSize = 6
|
||||||
|
|
||||||
|
// KeyboardMacroReport returns the keyboard macro report from the message.
|
||||||
|
func (m *Message) KeyboardMacroReport() (KeyboardMacroReport, error) {
|
||||||
|
if m.t != TypeKeyboardMacroReport {
|
||||||
|
return KeyboardMacroReport{}, fmt.Errorf("invalid message type: %d", m.t)
|
||||||
|
}
|
||||||
|
|
||||||
|
isPaste := m.d[0] == uint8(1)
|
||||||
|
stepCount := binary.BigEndian.Uint32(m.d[1:5])
|
||||||
|
|
||||||
|
// check total length
|
||||||
|
expectedLength := int(stepCount)*9 + 5
|
||||||
|
if len(m.d) != expectedLength {
|
||||||
|
return KeyboardMacroReport{}, fmt.Errorf("invalid length: %d, expected: %d", len(m.d), expectedLength)
|
||||||
|
}
|
||||||
|
|
||||||
|
steps := make([]KeyboardMacroStep, 0, int(stepCount))
|
||||||
|
offset := 5
|
||||||
|
for i := 0; i < int(stepCount); i++ {
|
||||||
|
steps = append(steps, KeyboardMacroStep{
|
||||||
|
Modifier: m.d[offset],
|
||||||
|
Keys: m.d[offset+1 : offset+7],
|
||||||
|
Delay: binary.BigEndian.Uint16(m.d[offset+7 : offset+9]),
|
||||||
|
})
|
||||||
|
|
||||||
|
offset += 1 + HidKeyBufferSize + 2
|
||||||
|
}
|
||||||
|
|
||||||
|
return KeyboardMacroReport{
|
||||||
|
IsPaste: isPaste,
|
||||||
|
Steps: steps,
|
||||||
|
StepCount: stepCount,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
// PointerReport ..
|
// PointerReport ..
|
||||||
type PointerReport struct {
|
type PointerReport struct {
|
||||||
X int
|
X int
|
||||||
|
@ -131,3 +188,20 @@ func (m *Message) MouseReport() (MouseReport, error) {
|
||||||
Button: uint8(m.d[2]),
|
Button: uint8(m.d[2]),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type KeyboardMacroState struct {
|
||||||
|
State bool
|
||||||
|
IsPaste bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyboardMacroState returns the keyboard macro state report from the message.
|
||||||
|
func (m *Message) KeyboardMacroState() (KeyboardMacroState, error) {
|
||||||
|
if m.t != TypeKeyboardMacroState {
|
||||||
|
return KeyboardMacroState{}, fmt.Errorf("invalid message type: %d", m.t)
|
||||||
|
}
|
||||||
|
|
||||||
|
return KeyboardMacroState{
|
||||||
|
State: m.d[0] == uint8(1),
|
||||||
|
IsPaste: m.d[1] == uint8(1),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
|
@ -56,13 +56,12 @@ type NetworkConfig struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *NetworkConfig) GetMDNSMode() *mdns.MDNSListenOptions {
|
func (c *NetworkConfig) GetMDNSMode() *mdns.MDNSListenOptions {
|
||||||
mode := c.MDNSMode.String
|
|
||||||
listenOptions := &mdns.MDNSListenOptions{
|
listenOptions := &mdns.MDNSListenOptions{
|
||||||
IPv4: true,
|
IPv4: c.IPv4Mode.String != "disabled",
|
||||||
IPv6: true,
|
IPv6: c.IPv6Mode.String != "disabled",
|
||||||
}
|
}
|
||||||
|
|
||||||
switch mode {
|
switch c.MDNSMode.String {
|
||||||
case "ipv4_only":
|
case "ipv4_only":
|
||||||
listenOptions.IPv6 = false
|
listenOptions.IPv6 = false
|
||||||
case "ipv6_only":
|
case "ipv6_only":
|
||||||
|
|
|
@ -48,7 +48,7 @@ type NetworkInterfaceOptions struct {
|
||||||
DefaultHostname string
|
DefaultHostname string
|
||||||
OnStateChange func(state *NetworkInterfaceState)
|
OnStateChange func(state *NetworkInterfaceState)
|
||||||
OnInitialCheck func(state *NetworkInterfaceState)
|
OnInitialCheck func(state *NetworkInterfaceState)
|
||||||
OnDhcpLeaseChange func(lease *udhcpc.Lease)
|
OnDhcpLeaseChange func(lease *udhcpc.Lease, state *NetworkInterfaceState)
|
||||||
OnConfigChange func(config *NetworkConfig)
|
OnConfigChange func(config *NetworkConfig)
|
||||||
NetworkConfig *NetworkConfig
|
NetworkConfig *NetworkConfig
|
||||||
}
|
}
|
||||||
|
@ -94,7 +94,7 @@ func NewNetworkInterfaceState(opts *NetworkInterfaceOptions) (*NetworkInterfaceS
|
||||||
_ = s.updateNtpServersFromLease(lease)
|
_ = s.updateNtpServersFromLease(lease)
|
||||||
_ = s.setHostnameIfNotSame()
|
_ = s.setHostnameIfNotSame()
|
||||||
|
|
||||||
opts.OnDhcpLeaseChange(lease)
|
opts.OnDhcpLeaseChange(lease, s)
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -239,6 +239,10 @@ func (s *NetworkInterfaceState) update() (DhcpTargetState, error) {
|
||||||
ipv4Addresses = append(ipv4Addresses, addr.IP)
|
ipv4Addresses = append(ipv4Addresses, addr.IP)
|
||||||
ipv4AddressesString = append(ipv4AddressesString, addr.IPNet.String())
|
ipv4AddressesString = append(ipv4AddressesString, addr.IPNet.String())
|
||||||
} else if addr.IP.To16() != nil {
|
} else if addr.IP.To16() != nil {
|
||||||
|
if s.config.IPv6Mode.String == "disabled" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
scopedLogger := s.l.With().Str("ipv6", addr.IP.String()).Logger()
|
scopedLogger := s.l.With().Str("ipv6", addr.IP.String()).Logger()
|
||||||
// check if it's a link local address
|
// check if it's a link local address
|
||||||
if addr.IP.IsLinkLocalUnicast() {
|
if addr.IP.IsLinkLocalUnicast() {
|
||||||
|
@ -287,6 +291,7 @@ func (s *NetworkInterfaceState) update() (DhcpTargetState, error) {
|
||||||
}
|
}
|
||||||
s.ipv4Addresses = ipv4AddressesString
|
s.ipv4Addresses = ipv4AddressesString
|
||||||
|
|
||||||
|
if s.config.IPv6Mode.String != "disabled" {
|
||||||
if ipv6LinkLocal != nil {
|
if ipv6LinkLocal != nil {
|
||||||
if s.ipv6LinkLocal == nil || s.ipv6LinkLocal.String() != ipv6LinkLocal.String() {
|
if s.ipv6LinkLocal == nil || s.ipv6LinkLocal.String() != ipv6LinkLocal.String() {
|
||||||
scopedLogger := s.l.With().Str("ipv6", ipv6LinkLocal.String()).Logger()
|
scopedLogger := s.l.With().Str("ipv6", ipv6LinkLocal.String()).Logger()
|
||||||
|
@ -318,6 +323,7 @@ func (s *NetworkInterfaceState) update() (DhcpTargetState, error) {
|
||||||
changed = true
|
changed = true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// if it's the initial check, we'll set changed to false
|
// if it's the initial check, we'll set changed to false
|
||||||
initialCheck := !s.checked
|
initialCheck := !s.checked
|
||||||
|
|
|
@ -65,7 +65,7 @@ func (s *NetworkInterfaceState) IPv6LinkLocalAddress() string {
|
||||||
func (s *NetworkInterfaceState) RpcGetNetworkState() RpcNetworkState {
|
func (s *NetworkInterfaceState) RpcGetNetworkState() RpcNetworkState {
|
||||||
ipv6Addresses := make([]RpcIPv6Address, 0)
|
ipv6Addresses := make([]RpcIPv6Address, 0)
|
||||||
|
|
||||||
if s.ipv6Addresses != nil {
|
if s.ipv6Addresses != nil && s.config.IPv6Mode.String != "disabled" {
|
||||||
for _, addr := range s.ipv6Addresses {
|
for _, addr := range s.ipv6Addresses {
|
||||||
ipv6Addresses = append(ipv6Addresses, RpcIPv6Address{
|
ipv6Addresses = append(ipv6Addresses, RpcIPv6Address{
|
||||||
Address: addr.Prefix.String(),
|
Address: addr.Prefix.String(),
|
||||||
|
|
|
@ -9,17 +9,32 @@ import (
|
||||||
"github.com/beevik/ntp"
|
"github.com/beevik/ntp"
|
||||||
)
|
)
|
||||||
|
|
||||||
var defaultNTPServers = []string{
|
var defaultNTPServerIPs = []string{
|
||||||
|
// These servers are known by static IP and as such don't need DNS lookups
|
||||||
|
// These are from Google and Cloudflare since if they're down, the internet
|
||||||
|
// is broken anyway
|
||||||
|
"162.159.200.1", // time.cloudflare.com IPv4
|
||||||
|
"162.159.200.123", // time.cloudflare.com IPv4
|
||||||
|
"2606:4700:f1::1", // time.cloudflare.com IPv6
|
||||||
|
"2606:4700:f1::123", // time.cloudflare.com IPv6
|
||||||
|
"216.239.35.0", // time.google.com IPv4
|
||||||
|
"216.239.35.4", // time.google.com IPv4
|
||||||
|
"216.239.35.8", // time.google.com IPv4
|
||||||
|
"216.239.35.12", // time.google.com IPv4
|
||||||
|
"2001:4860:4806::", // time.google.com IPv6
|
||||||
|
"2001:4860:4806:4::", // time.google.com IPv6
|
||||||
|
"2001:4860:4806:8::", // time.google.com IPv6
|
||||||
|
"2001:4860:4806:c::", // time.google.com IPv6
|
||||||
|
}
|
||||||
|
|
||||||
|
var defaultNTPServerHostnames = []string{
|
||||||
|
// should use something from https://github.com/jauderho/public-ntp-servers
|
||||||
"time.apple.com",
|
"time.apple.com",
|
||||||
"time.aws.com",
|
"time.aws.com",
|
||||||
"time.windows.com",
|
"time.windows.com",
|
||||||
"time.google.com",
|
"time.google.com",
|
||||||
"162.159.200.123", // time.cloudflare.com IPv4
|
"time.cloudflare.com",
|
||||||
"2606:4700:f1::123", // time.cloudflare.com IPv6
|
"pool.ntp.org",
|
||||||
"0.pool.ntp.org",
|
|
||||||
"1.pool.ntp.org",
|
|
||||||
"2.pool.ntp.org",
|
|
||||||
"3.pool.ntp.org",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *TimeSync) queryNetworkTime(ntpServers []string) (now *time.Time, offset *time.Duration) {
|
func (t *TimeSync) queryNetworkTime(ntpServers []string) (now *time.Time, offset *time.Duration) {
|
||||||
|
|
|
@ -158,6 +158,7 @@ func (t *TimeSync) Sync() error {
|
||||||
var (
|
var (
|
||||||
now *time.Time
|
now *time.Time
|
||||||
offset *time.Duration
|
offset *time.Duration
|
||||||
|
log zerolog.Logger
|
||||||
)
|
)
|
||||||
|
|
||||||
metricTimeSyncCount.Inc()
|
metricTimeSyncCount.Inc()
|
||||||
|
@ -166,54 +167,54 @@ func (t *TimeSync) Sync() error {
|
||||||
|
|
||||||
Orders:
|
Orders:
|
||||||
for _, mode := range syncMode.Ordering {
|
for _, mode := range syncMode.Ordering {
|
||||||
|
log = t.l.With().Str("mode", mode).Logger()
|
||||||
switch mode {
|
switch mode {
|
||||||
case "ntp_user_provided":
|
case "ntp_user_provided":
|
||||||
if syncMode.Ntp {
|
if syncMode.Ntp {
|
||||||
t.l.Info().Msg("using NTP custom servers")
|
log.Info().Msg("using NTP custom servers")
|
||||||
now, offset = t.queryNetworkTime(t.networkConfig.TimeSyncNTPServers)
|
now, offset = t.queryNetworkTime(t.networkConfig.TimeSyncNTPServers)
|
||||||
if now != nil {
|
if now != nil {
|
||||||
t.l.Info().Str("source", "NTP").Time("now", *now).Msg("time obtained")
|
|
||||||
break Orders
|
break Orders
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "ntp_dhcp":
|
case "ntp_dhcp":
|
||||||
if syncMode.Ntp {
|
if syncMode.Ntp {
|
||||||
t.l.Info().Msg("using NTP servers from DHCP")
|
log.Info().Msg("using NTP servers from DHCP")
|
||||||
now, offset = t.queryNetworkTime(t.dhcpNtpAddresses)
|
now, offset = t.queryNetworkTime(t.dhcpNtpAddresses)
|
||||||
if now != nil {
|
if now != nil {
|
||||||
t.l.Info().Str("source", "NTP DHCP").Time("now", *now).Msg("time obtained")
|
|
||||||
break Orders
|
break Orders
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "ntp":
|
case "ntp":
|
||||||
if syncMode.Ntp && syncMode.NtpUseFallback {
|
if syncMode.Ntp && syncMode.NtpUseFallback {
|
||||||
t.l.Info().Msg("using NTP fallback")
|
log.Info().Msg("using NTP fallback IPs")
|
||||||
now, offset = t.queryNetworkTime(defaultNTPServers)
|
now, offset = t.queryNetworkTime(defaultNTPServerIPs)
|
||||||
|
if now == nil {
|
||||||
|
log.Info().Msg("using NTP fallback hostnames")
|
||||||
|
now, offset = t.queryNetworkTime(defaultNTPServerHostnames)
|
||||||
|
}
|
||||||
if now != nil {
|
if now != nil {
|
||||||
t.l.Info().Str("source", "NTP fallback").Time("now", *now).Msg("time obtained")
|
|
||||||
break Orders
|
break Orders
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "http_user_provided":
|
case "http_user_provided":
|
||||||
if syncMode.Http {
|
if syncMode.Http {
|
||||||
t.l.Info().Msg("using HTTP custom URLs")
|
log.Info().Msg("using HTTP custom URLs")
|
||||||
now = t.queryAllHttpTime(t.networkConfig.TimeSyncHTTPUrls)
|
now = t.queryAllHttpTime(t.networkConfig.TimeSyncHTTPUrls)
|
||||||
if now != nil {
|
if now != nil {
|
||||||
t.l.Info().Str("source", "HTTP").Time("now", *now).Msg("time obtained")
|
|
||||||
break Orders
|
break Orders
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case "http":
|
case "http":
|
||||||
if syncMode.Http && syncMode.HttpUseFallback {
|
if syncMode.Http && syncMode.HttpUseFallback {
|
||||||
t.l.Info().Msg("using HTTP fallback")
|
log.Info().Msg("using HTTP fallback")
|
||||||
now = t.queryAllHttpTime(defaultHTTPUrls)
|
now = t.queryAllHttpTime(defaultHTTPUrls)
|
||||||
if now != nil {
|
if now != nil {
|
||||||
t.l.Info().Str("source", "HTTP fallback").Time("now", *now).Msg("time obtained")
|
|
||||||
break Orders
|
break Orders
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
t.l.Warn().Str("mode", mode).Msg("unknown time sync mode, skipping")
|
log.Warn().Msg("unknown time sync mode, skipping")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -226,6 +227,8 @@ Orders:
|
||||||
now = &newNow
|
now = &newNow
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.Info().Time("now", *now).Msg("time obtained")
|
||||||
|
|
||||||
err := t.setSystemTime(*now)
|
err := t.setSystemTime(*now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to set system time: %w", err)
|
return fmt.Errorf("failed to set system time: %w", err)
|
||||||
|
|
|
@ -5,7 +5,11 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/rs/xid"
|
||||||
|
"github.com/rs/zerolog"
|
||||||
)
|
)
|
||||||
|
|
||||||
var keyboardConfig = gadgetConfigItem{
|
var keyboardConfig = gadgetConfigItem{
|
||||||
|
@ -145,32 +149,95 @@ func (u *UsbGadget) GetKeysDownState() KeysDownState {
|
||||||
return u.keysDownState
|
return u.keysDownState
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UsbGadget) updateKeyDownState(state KeysDownState) {
|
func (u *UsbGadget) SetOnKeysDownChange(f func(state KeysDownState)) {
|
||||||
u.log.Trace().Interface("old", u.keysDownState).Interface("new", state).Msg("acquiring keyboardStateLock for updateKeyDownState")
|
u.onKeysDownChange = &f
|
||||||
|
}
|
||||||
|
|
||||||
// this is intentional to unlock keyboard state lock before onKeysDownChange callback
|
func (u *UsbGadget) SetOnKeepAliveReset(f func()) {
|
||||||
{
|
u.onKeepAliveReset = &f
|
||||||
u.keyboardStateLock.Lock()
|
}
|
||||||
defer u.keyboardStateLock.Unlock()
|
|
||||||
|
|
||||||
if u.keysDownState.Modifier == state.Modifier &&
|
// DefaultAutoReleaseDuration is the default duration for auto-release of a key.
|
||||||
bytes.Equal(u.keysDownState.Keys, state.Keys) {
|
const DefaultAutoReleaseDuration = 100 * time.Millisecond
|
||||||
return // No change in key down state
|
|
||||||
|
func (u *UsbGadget) scheduleAutoRelease(key byte) {
|
||||||
|
u.kbdAutoReleaseLock.Lock()
|
||||||
|
defer unlockWithLog(&u.kbdAutoReleaseLock, u.log, "autoRelease scheduled")
|
||||||
|
|
||||||
|
if u.kbdAutoReleaseTimers[key] != nil {
|
||||||
|
u.kbdAutoReleaseTimers[key].Stop()
|
||||||
}
|
}
|
||||||
|
|
||||||
u.log.Trace().Interface("old", u.keysDownState).Interface("new", state).Msg("keysDownState updated")
|
// TODO: make this configurable
|
||||||
u.keysDownState = state
|
// We currently hardcode the duration to 100ms
|
||||||
}
|
// However, it should be the same as the duration of the keep-alive reset called baseExtension.
|
||||||
|
u.kbdAutoReleaseTimers[key] = time.AfterFunc(100*time.Millisecond, func() {
|
||||||
|
u.performAutoRelease(key)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
if u.onKeysDownChange != nil {
|
func (u *UsbGadget) cancelAutoRelease(key byte) {
|
||||||
u.log.Trace().Interface("state", state).Msg("calling onKeysDownChange")
|
u.kbdAutoReleaseLock.Lock()
|
||||||
(*u.onKeysDownChange)(state)
|
defer unlockWithLog(&u.kbdAutoReleaseLock, u.log, "autoRelease cancelled")
|
||||||
u.log.Trace().Interface("state", state).Msg("onKeysDownChange called")
|
|
||||||
|
if timer := u.kbdAutoReleaseTimers[key]; timer != nil {
|
||||||
|
timer.Stop()
|
||||||
|
u.kbdAutoReleaseTimers[key] = nil
|
||||||
|
delete(u.kbdAutoReleaseTimers, key)
|
||||||
|
|
||||||
|
// Reset keep-alive timing when key is released
|
||||||
|
if u.onKeepAliveReset != nil {
|
||||||
|
(*u.onKeepAliveReset)()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UsbGadget) SetOnKeysDownChange(f func(state KeysDownState)) {
|
func (u *UsbGadget) DelayAutoReleaseWithDuration(resetDuration time.Duration) {
|
||||||
u.onKeysDownChange = &f
|
u.kbdAutoReleaseLock.Lock()
|
||||||
|
defer unlockWithLog(&u.kbdAutoReleaseLock, u.log, "autoRelease delayed")
|
||||||
|
|
||||||
|
u.log.Debug().Dur("reset_duration", resetDuration).Msg("delaying auto-release with dynamic duration")
|
||||||
|
|
||||||
|
for _, timer := range u.kbdAutoReleaseTimers {
|
||||||
|
if timer != nil {
|
||||||
|
timer.Reset(resetDuration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *UsbGadget) performAutoRelease(key byte) {
|
||||||
|
u.kbdAutoReleaseLock.Lock()
|
||||||
|
|
||||||
|
if u.kbdAutoReleaseTimers[key] == nil {
|
||||||
|
u.log.Warn().Uint8("key", key).Msg("autoRelease timer not found")
|
||||||
|
u.kbdAutoReleaseLock.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
u.kbdAutoReleaseTimers[key].Stop()
|
||||||
|
u.kbdAutoReleaseTimers[key] = nil
|
||||||
|
delete(u.kbdAutoReleaseTimers, key)
|
||||||
|
u.kbdAutoReleaseLock.Unlock()
|
||||||
|
|
||||||
|
// Skip if already released
|
||||||
|
state := u.GetKeysDownState()
|
||||||
|
alreadyReleased := true
|
||||||
|
|
||||||
|
for i := range state.Keys {
|
||||||
|
if state.Keys[i] == key {
|
||||||
|
alreadyReleased = false
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if alreadyReleased {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := u.keypressReport(key, false)
|
||||||
|
if err != nil {
|
||||||
|
u.log.Warn().Uint8("key", key).Msg("failed to release key")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UsbGadget) listenKeyboardEvents() {
|
func (u *UsbGadget) listenKeyboardEvents() {
|
||||||
|
@ -242,7 +309,11 @@ func (u *UsbGadget) OpenKeyboardHidFile() error {
|
||||||
return u.openKeyboardHidFile()
|
return u.openKeyboardHidFile()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var keyboardWriteHidFileLock sync.Mutex
|
||||||
|
|
||||||
func (u *UsbGadget) keyboardWriteHidFile(modifier byte, keys []byte) error {
|
func (u *UsbGadget) keyboardWriteHidFile(modifier byte, keys []byte) error {
|
||||||
|
keyboardWriteHidFileLock.Lock()
|
||||||
|
defer keyboardWriteHidFileLock.Unlock()
|
||||||
if err := u.openKeyboardHidFile(); err != nil {
|
if err := u.openKeyboardHidFile(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -266,17 +337,29 @@ func (u *UsbGadget) UpdateKeysDown(modifier byte, keys []byte) KeysDownState {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
downState := KeysDownState{
|
state := KeysDownState{
|
||||||
Modifier: modifier,
|
Modifier: modifier,
|
||||||
Keys: []byte(keys[:]),
|
Keys: []byte(keys[:]),
|
||||||
}
|
}
|
||||||
u.updateKeyDownState(downState)
|
|
||||||
return downState
|
u.keyboardStateLock.Lock()
|
||||||
|
|
||||||
|
if u.keysDownState.Modifier == state.Modifier &&
|
||||||
|
bytes.Equal(u.keysDownState.Keys, state.Keys) {
|
||||||
|
u.keyboardStateLock.Unlock()
|
||||||
|
return state // No change in key down state
|
||||||
|
}
|
||||||
|
|
||||||
|
u.keysDownState = state
|
||||||
|
u.keyboardStateLock.Unlock()
|
||||||
|
|
||||||
|
if u.onKeysDownChange != nil {
|
||||||
|
(*u.onKeysDownChange)(state) // this enques to the outgoing hidrpc queue via usb.go → currentSession.enqueueKeysDownState(...)
|
||||||
|
}
|
||||||
|
return state
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UsbGadget) KeyboardReport(modifier byte, keys []byte) (KeysDownState, error) {
|
func (u *UsbGadget) KeyboardReport(modifier byte, keys []byte) error {
|
||||||
u.keyboardLock.Lock()
|
|
||||||
defer u.keyboardLock.Unlock()
|
|
||||||
defer u.resetUserInputTime()
|
defer u.resetUserInputTime()
|
||||||
|
|
||||||
if len(keys) > hidKeyBufferSize {
|
if len(keys) > hidKeyBufferSize {
|
||||||
|
@ -291,7 +374,8 @@ func (u *UsbGadget) KeyboardReport(modifier byte, keys []byte) (KeysDownState, e
|
||||||
u.log.Warn().Uint8("modifier", modifier).Uints8("keys", keys).Msg("Could not write keyboard report to hidg0")
|
u.log.Warn().Uint8("modifier", modifier).Uints8("keys", keys).Msg("Could not write keyboard report to hidg0")
|
||||||
}
|
}
|
||||||
|
|
||||||
return u.UpdateKeysDown(modifier, keys), err
|
u.UpdateKeysDown(modifier, keys)
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
@ -331,17 +415,23 @@ var KeyCodeToMaskMap = map[byte]byte{
|
||||||
RightSuper: ModifierMaskRightSuper,
|
RightSuper: ModifierMaskRightSuper,
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *UsbGadget) KeypressReport(key byte, press bool) (KeysDownState, error) {
|
func (u *UsbGadget) keypressReport(key byte, press bool) (KeysDownState, error) {
|
||||||
u.keyboardLock.Lock()
|
|
||||||
defer u.keyboardLock.Unlock()
|
|
||||||
defer u.resetUserInputTime()
|
defer u.resetUserInputTime()
|
||||||
|
|
||||||
|
l := u.log.With().Uint8("key", key).Bool("press", press).Logger()
|
||||||
|
if l.GetLevel() <= zerolog.DebugLevel {
|
||||||
|
requestID := xid.New()
|
||||||
|
l = l.With().Str("requestID", requestID.String()).Logger()
|
||||||
|
}
|
||||||
|
|
||||||
// IMPORTANT: This code parallels the logic in the kernel's hid-gadget driver
|
// IMPORTANT: This code parallels the logic in the kernel's hid-gadget driver
|
||||||
// for handling key presses and releases. It ensures that the USB gadget
|
// for handling key presses and releases. It ensures that the USB gadget
|
||||||
// behaves similarly to a real USB HID keyboard. This logic is paralleled
|
// behaves similarly to a real USB HID keyboard. This logic is paralleled
|
||||||
// in the client/browser-side code in useKeyboard.ts so make sure to keep
|
// in the client/browser-side code in useKeyboard.ts so make sure to keep
|
||||||
// them in sync.
|
// them in sync.
|
||||||
var state = u.keysDownState
|
var state = u.GetKeysDownState()
|
||||||
|
l.Trace().Interface("state", state).Msg("got keys down state")
|
||||||
|
|
||||||
modifier := state.Modifier
|
modifier := state.Modifier
|
||||||
keys := append([]byte(nil), state.Keys...)
|
keys := append([]byte(nil), state.Keys...)
|
||||||
|
|
||||||
|
@ -381,22 +471,36 @@ func (u *UsbGadget) KeypressReport(key byte, press bool) (KeysDownState, error)
|
||||||
// If we reach here it means we didn't find an empty slot or the key in the buffer
|
// If we reach here it means we didn't find an empty slot or the key in the buffer
|
||||||
if overrun {
|
if overrun {
|
||||||
if press {
|
if press {
|
||||||
u.log.Error().Uint8("key", key).Msg("keyboard buffer overflow, key not added")
|
l.Error().Msg("keyboard buffer overflow, key not added")
|
||||||
// Fill all key slots with ErrorRollOver (0x01) to indicate overflow
|
// Fill all key slots with ErrorRollOver (0x01) to indicate overflow
|
||||||
for i := range keys {
|
for i := range keys {
|
||||||
keys[i] = hidErrorRollOver
|
keys[i] = hidErrorRollOver
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// If we are releasing a key, and we didn't find it in a slot, who cares?
|
// If we are releasing a key, and we didn't find it in a slot, who cares?
|
||||||
u.log.Warn().Uint8("key", key).Msg("key not found in buffer, nothing to release")
|
l.Warn().Msg("key not found in buffer, nothing to release")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := u.keyboardWriteHidFile(modifier, keys)
|
err := u.keyboardWriteHidFile(modifier, keys)
|
||||||
if err != nil {
|
|
||||||
u.log.Warn().Uint8("modifier", modifier).Uints8("keys", keys).Msg("Could not write keypress report to hidg0")
|
|
||||||
}
|
|
||||||
|
|
||||||
return u.UpdateKeysDown(modifier, keys), err
|
return u.UpdateKeysDown(modifier, keys), err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *UsbGadget) KeypressReport(key byte, press bool) error {
|
||||||
|
state, err := u.keypressReport(key, press)
|
||||||
|
if err != nil {
|
||||||
|
u.log.Warn().Uint8("key", key).Bool("press", press).Msg("failed to report key")
|
||||||
|
}
|
||||||
|
isRolledOver := state.Keys[0] == hidErrorRollOver
|
||||||
|
|
||||||
|
if isRolledOver {
|
||||||
|
u.cancelAutoRelease(key)
|
||||||
|
} else if press {
|
||||||
|
u.scheduleAutoRelease(key)
|
||||||
|
} else {
|
||||||
|
u.cancelAutoRelease(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
|
@ -68,6 +68,9 @@ type UsbGadget struct {
|
||||||
keyboardState byte // keyboard latched state (NumLock, CapsLock, ScrollLock, Compose, Kana)
|
keyboardState byte // keyboard latched state (NumLock, CapsLock, ScrollLock, Compose, Kana)
|
||||||
keysDownState KeysDownState // keyboard dynamic state (modifier keys and pressed keys)
|
keysDownState KeysDownState // keyboard dynamic state (modifier keys and pressed keys)
|
||||||
|
|
||||||
|
kbdAutoReleaseLock sync.Mutex
|
||||||
|
kbdAutoReleaseTimers map[byte]*time.Timer
|
||||||
|
|
||||||
keyboardStateLock sync.Mutex
|
keyboardStateLock sync.Mutex
|
||||||
keyboardStateCtx context.Context
|
keyboardStateCtx context.Context
|
||||||
keyboardStateCancel context.CancelFunc
|
keyboardStateCancel context.CancelFunc
|
||||||
|
@ -85,6 +88,7 @@ type UsbGadget struct {
|
||||||
|
|
||||||
onKeyboardStateChange *func(state KeyboardState)
|
onKeyboardStateChange *func(state KeyboardState)
|
||||||
onKeysDownChange *func(state KeysDownState)
|
onKeysDownChange *func(state KeysDownState)
|
||||||
|
onKeepAliveReset *func()
|
||||||
|
|
||||||
log *zerolog.Logger
|
log *zerolog.Logger
|
||||||
|
|
||||||
|
@ -132,6 +136,7 @@ func newUsbGadget(name string, configMap map[string]gadgetConfigItem, enabledDev
|
||||||
keyboardStateCancel: keyboardCancel,
|
keyboardStateCancel: keyboardCancel,
|
||||||
keyboardState: 0,
|
keyboardState: 0,
|
||||||
keysDownState: KeysDownState{Modifier: 0, Keys: []byte{0, 0, 0, 0, 0, 0}}, // must be initialized to hidKeyBufferSize (6) zero bytes
|
keysDownState: KeysDownState{Modifier: 0, Keys: []byte{0, 0, 0, 0, 0, 0}}, // must be initialized to hidKeyBufferSize (6) zero bytes
|
||||||
|
kbdAutoReleaseTimers: make(map[byte]*time.Timer),
|
||||||
enabledDevices: *enabledDevices,
|
enabledDevices: *enabledDevices,
|
||||||
lastUserInput: time.Now(),
|
lastUserInput: time.Now(),
|
||||||
log: logger,
|
log: logger,
|
||||||
|
@ -149,3 +154,37 @@ func newUsbGadget(name string, configMap map[string]gadgetConfigItem, enabledDev
|
||||||
|
|
||||||
return g
|
return g
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close cleans up resources used by the USB gadget
|
||||||
|
func (u *UsbGadget) Close() error {
|
||||||
|
// Cancel keyboard state context
|
||||||
|
if u.keyboardStateCancel != nil {
|
||||||
|
u.keyboardStateCancel()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop auto-release timer
|
||||||
|
u.kbdAutoReleaseLock.Lock()
|
||||||
|
for _, timer := range u.kbdAutoReleaseTimers {
|
||||||
|
if timer != nil {
|
||||||
|
timer.Stop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
u.kbdAutoReleaseTimers = make(map[byte]*time.Timer)
|
||||||
|
u.kbdAutoReleaseLock.Unlock()
|
||||||
|
|
||||||
|
// Close HID files
|
||||||
|
if u.keyboardHidFile != nil {
|
||||||
|
u.keyboardHidFile.Close()
|
||||||
|
u.keyboardHidFile = nil
|
||||||
|
}
|
||||||
|
if u.absMouseHidFile != nil {
|
||||||
|
u.absMouseHidFile.Close()
|
||||||
|
u.absMouseHidFile = nil
|
||||||
|
}
|
||||||
|
if u.relMouseHidFile != nil {
|
||||||
|
u.relMouseHidFile.Close()
|
||||||
|
u.relMouseHidFile = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
|
@ -120,6 +121,12 @@ func (u *UsbGadget) writeWithTimeout(file *os.File, data []byte) (n int, err err
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
u.log.Trace().
|
||||||
|
Str("file", file.Name()).
|
||||||
|
Bytes("data", data).
|
||||||
|
Err(err).
|
||||||
|
Msg("write failed")
|
||||||
|
|
||||||
if errors.Is(err, os.ErrDeadlineExceeded) {
|
if errors.Is(err, os.ErrDeadlineExceeded) {
|
||||||
u.logWithSuppression(
|
u.logWithSuppression(
|
||||||
fmt.Sprintf("writeWithTimeout_%s", file.Name()),
|
fmt.Sprintf("writeWithTimeout_%s", file.Name()),
|
||||||
|
@ -164,3 +171,8 @@ func (u *UsbGadget) resetLogSuppressionCounter(counterName string) {
|
||||||
u.logSuppressionCounter[counterName] = 0
|
u.logSuppressionCounter[counterName] = 0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func unlockWithLog(lock *sync.Mutex, logger *zerolog.Logger, msg string, args ...any) {
|
||||||
|
logger.Trace().Msgf(msg, args...)
|
||||||
|
lock.Unlock()
|
||||||
|
}
|
||||||
|
|
|
@ -0,0 +1,73 @@
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ValidSSHKeyTypes is a list of valid SSH key types
|
||||||
|
//
|
||||||
|
// Please make sure that all the types in this list are supported by dropbear
|
||||||
|
// https://github.com/mkj/dropbear/blob/003c5fcaabc114430d5d14142e95ffdbbd2d19b6/src/signkey.c#L37
|
||||||
|
//
|
||||||
|
// ssh-dss is not allowed here as it's insecure
|
||||||
|
var ValidSSHKeyTypes = []string{
|
||||||
|
ssh.KeyAlgoRSA,
|
||||||
|
ssh.KeyAlgoED25519,
|
||||||
|
ssh.KeyAlgoECDSA256,
|
||||||
|
ssh.KeyAlgoECDSA384,
|
||||||
|
ssh.KeyAlgoECDSA521,
|
||||||
|
ssh.KeyAlgoSKED25519,
|
||||||
|
ssh.KeyAlgoSKECDSA256,
|
||||||
|
}
|
||||||
|
|
||||||
|
// ValidateSSHKey validates authorized_keys file content
|
||||||
|
func ValidateSSHKey(sshKey string) error {
|
||||||
|
// validate SSH key
|
||||||
|
var (
|
||||||
|
hasValidPublicKey = false
|
||||||
|
lastError = fmt.Errorf("no valid SSH key found")
|
||||||
|
)
|
||||||
|
for _, key := range strings.Split(sshKey, "\n") {
|
||||||
|
key = strings.TrimSpace(key)
|
||||||
|
|
||||||
|
// skip empty lines and comments
|
||||||
|
if key == "" || strings.HasPrefix(key, "#") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedPublicKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(key))
|
||||||
|
if err != nil {
|
||||||
|
lastError = err
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if parsedPublicKey == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
parsedType := parsedPublicKey.Type()
|
||||||
|
textType := strings.Fields(key)[0]
|
||||||
|
|
||||||
|
if parsedType != textType {
|
||||||
|
lastError = fmt.Errorf("parsed SSH key type %s does not match type in text %s", parsedType, textType)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !slices.Contains(ValidSSHKeyTypes, parsedType) {
|
||||||
|
lastError = fmt.Errorf("invalid SSH key type: %s", parsedType)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
hasValidPublicKey = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hasValidPublicKey {
|
||||||
|
return lastError
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
|
@ -0,0 +1,220 @@
|
||||||
|
package utils
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidateSSHKey(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
sshKey string
|
||||||
|
expectError bool
|
||||||
|
errorMsg string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "valid RSA key",
|
||||||
|
sshKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid ED25519 key",
|
||||||
|
sshKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBSbM8wuD5ab0nHsXaYOqaD3GLLUwmDzSk79Xi/N+H2j test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid ECDSA key",
|
||||||
|
sshKey: "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBAlTkxIo4mXBR+gEX0Q74BpYX4bFFHoX+8Uz7tsob8HvsnMvsEE+BW9h9XrbWX4/4ppL/o6sHbvsqNr9HcyKfdc= test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid SK-backed ED25519 key",
|
||||||
|
sshKey: "sk-ssh-ed25519@openssh.com AAAAGnNrLXNzaC1lZDI1NTE5QG9wZW5zc2guY29tAAAAIHHSRVC3qISk/mOorf24au6esimA9Uu1/BkEnVKJ+4bFAAAABHNzaDo= test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid SK-backed ECDSA key",
|
||||||
|
sshKey: "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBL/CFBZksvs+gJODMB9StxnkY6xRKH73npOzJBVb0UEGCPTAhDrvzW1PE5X5GDYXmZw1s7c/nS+GH0LF0OFCpwAAAAAEc3NoOg== test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "multiple valid keys",
|
||||||
|
sshKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp test@example.com\nssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBSbM8wuD5ab0nHsXaYOqaD3GLLUwmDzSk79Xi/N+H2j test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid key with comment",
|
||||||
|
sshKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp user@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid key with options and comment (we don't support options yet)",
|
||||||
|
sshKey: "command=\"echo hello\" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp user@example.com",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "empty string",
|
||||||
|
sshKey: "",
|
||||||
|
expectError: true,
|
||||||
|
errorMsg: "no valid SSH key found",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "whitespace only",
|
||||||
|
sshKey: " \n\t \n ",
|
||||||
|
expectError: true,
|
||||||
|
errorMsg: "no valid SSH key found",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "comment only",
|
||||||
|
sshKey: "# This is a comment\n# Another comment",
|
||||||
|
expectError: true,
|
||||||
|
errorMsg: "no valid SSH key found",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid key format",
|
||||||
|
sshKey: "not-a-valid-ssh-key",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "invalid key type",
|
||||||
|
sshKey: "ssh-dss AAAAB3NzaC1kc3MAAACBAOeB...",
|
||||||
|
expectError: true,
|
||||||
|
errorMsg: "invalid SSH key type: ssh-dss",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unsupported key type",
|
||||||
|
sshKey: "ssh-rsa-cert-v01@openssh.com AAAAB3NzaC1yc2EAAAADAQABAAABgQC7vbqajDhA...",
|
||||||
|
expectError: true,
|
||||||
|
errorMsg: "invalid SSH key type: ssh-rsa-cert-v01@openssh.com",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "malformed key data",
|
||||||
|
sshKey: "ssh-rsa invalid-base64-data",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "type mismatch",
|
||||||
|
sshKey: "ssh-rsa AAAAC3NzaC1lZDI1NTE5AAAAIGomKoH...",
|
||||||
|
expectError: true,
|
||||||
|
errorMsg: "parsed SSH key type ssh-ed25519 does not match type in text ssh-rsa",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "mixed valid and invalid keys",
|
||||||
|
sshKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp test@example.com\ninvalid-key\nssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBSbM8wuD5ab0nHsXaYOqaD3GLLUwmDzSk79Xi/N+H2j test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "valid key with empty lines and comments",
|
||||||
|
sshKey: "# Comment line\n\nssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp test@example.com\n# Another comment\n\t\n",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "all invalid keys",
|
||||||
|
sshKey: "invalid-key-1\ninvalid-key-2\nssh-dss AAAAB3NzaC1kc3MAAACBAOeB...",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
err := ValidateSSHKey(tt.sshKey)
|
||||||
|
|
||||||
|
if tt.expectError {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("ValidateSSHKey() expected error but got none")
|
||||||
|
} else if tt.errorMsg != "" && !strings.ContainsAny(err.Error(), tt.errorMsg) {
|
||||||
|
t.Errorf("ValidateSSHKey() error = %v, expected to contain %v", err, tt.errorMsg)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("ValidateSSHKey() unexpected error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestValidSSHKeyTypes(t *testing.T) {
|
||||||
|
expectedTypes := []string{
|
||||||
|
"ssh-rsa",
|
||||||
|
"ssh-ed25519",
|
||||||
|
"ecdsa-sha2-nistp256",
|
||||||
|
"ecdsa-sha2-nistp384",
|
||||||
|
"ecdsa-sha2-nistp521",
|
||||||
|
"sk-ecdsa-sha2-nistp256@openssh.com",
|
||||||
|
"sk-ssh-ed25519@openssh.com",
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(ValidSSHKeyTypes) != len(expectedTypes) {
|
||||||
|
t.Errorf("ValidSSHKeyTypes length = %d, expected %d", len(ValidSSHKeyTypes), len(expectedTypes))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, expectedType := range expectedTypes {
|
||||||
|
found := false
|
||||||
|
for _, actualType := range ValidSSHKeyTypes {
|
||||||
|
if actualType == expectedType {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
t.Errorf("ValidSSHKeyTypes missing expected type: %s", expectedType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestValidateSSHKeyEdgeCases tests edge cases and boundary conditions
|
||||||
|
func TestValidateSSHKeyEdgeCases(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
sshKey string
|
||||||
|
expectError bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "key with only type",
|
||||||
|
sshKey: "ssh-rsa",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "key with type and empty data",
|
||||||
|
sshKey: "ssh-rsa ",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "key with type and whitespace data",
|
||||||
|
sshKey: "ssh-rsa \t ",
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "key with multiple spaces between type and data",
|
||||||
|
sshKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "key with tabs",
|
||||||
|
sshKey: "\tssh-rsa\tAAAAB3NzaC1yc2EAAAADAQABAAABAQDiYUb9Fy2vlPfO+HwubnshimpVrWPoePyvyN+jPC5gWqZSycjMy6Is2vFVn7oQc72bkY0wZalspT5wUOwKtltSoLpL7vcqGL9zHVw4yjYXtPGIRd3zLpU9wdngevnepPQWTX3LvZTZfmOsrGoMDKIG+Lbmiq/STMuWYecIqMp7tUKRGS8vfAmpu6MsrN9/4UTcdWWXYWJQQn+2nCyMz28jYlWRsKtqFK6owrdZWt8WQnPN+9Upcf2ByQje+0NLnpNrnh+yd2ocuVW9wQYKAZXy7IaTfEJwd5m34sLwkqlZTaBBcmWJU+3RfpYXE763cf3rUoPIGQ8eUEBJ8IdM4vhp test@example.com",
|
||||||
|
expectError: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "very long line",
|
||||||
|
sshKey: "ssh-rsa " + string(make([]byte, 10000)),
|
||||||
|
expectError: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
err := ValidateSSHKey(tt.sshKey)
|
||||||
|
|
||||||
|
if tt.expectError {
|
||||||
|
if err == nil {
|
||||||
|
t.Errorf("ValidateSSHKey() expected error but got none")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("ValidateSSHKey() unexpected error = %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
14
jiggler.go
14
jiggler.go
|
@ -17,16 +17,20 @@ type JigglerConfig struct {
|
||||||
Timezone string `json:"timezone,omitempty"`
|
Timezone string `json:"timezone,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var jigglerEnabled = false
|
|
||||||
var jobDelta time.Duration = 0
|
var jobDelta time.Duration = 0
|
||||||
var scheduler gocron.Scheduler = nil
|
var scheduler gocron.Scheduler = nil
|
||||||
|
|
||||||
func rpcSetJigglerState(enabled bool) {
|
func rpcSetJigglerState(enabled bool) error {
|
||||||
jigglerEnabled = enabled
|
config.JigglerEnabled = enabled
|
||||||
|
err := SaveConfig()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to save config: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func rpcGetJigglerState() bool {
|
func rpcGetJigglerState() bool {
|
||||||
return jigglerEnabled
|
return config.JigglerEnabled
|
||||||
}
|
}
|
||||||
|
|
||||||
func rpcGetTimezones() []string {
|
func rpcGetTimezones() []string {
|
||||||
|
@ -118,7 +122,7 @@ func runJigglerCronTab() error {
|
||||||
}
|
}
|
||||||
|
|
||||||
func runJiggler() {
|
func runJiggler() {
|
||||||
if jigglerEnabled {
|
if config.JigglerEnabled {
|
||||||
if config.JigglerConfig.JitterPercentage != 0 {
|
if config.JigglerConfig.JitterPercentage != 0 {
|
||||||
jitter := calculateJitterDuration(jobDelta)
|
jitter := calculateJitterDuration(jobDelta)
|
||||||
time.Sleep(jitter)
|
time.Sleep(jitter)
|
||||||
|
|
137
jsonrpc.go
137
jsonrpc.go
|
@ -1,6 +1,7 @@
|
||||||
package kvm
|
package kvm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
|
@ -10,13 +11,16 @@ import (
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/pion/webrtc/v4"
|
"github.com/pion/webrtc/v4"
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
"go.bug.st/serial"
|
"go.bug.st/serial"
|
||||||
|
|
||||||
|
"github.com/jetkvm/kvm/internal/hidrpc"
|
||||||
"github.com/jetkvm/kvm/internal/usbgadget"
|
"github.com/jetkvm/kvm/internal/usbgadget"
|
||||||
|
"github.com/jetkvm/kvm/internal/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
type JSONRPCRequest struct {
|
type JSONRPCRequest struct {
|
||||||
|
@ -278,6 +282,17 @@ func rpcGetUpdateStatus() (*UpdateStatus, error) {
|
||||||
return updateStatus, nil
|
return updateStatus, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func rpcGetLocalVersion() (*LocalMetadata, error) {
|
||||||
|
systemVersion, appVersion, err := GetLocalVersion()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("error getting local version: %w", err)
|
||||||
|
}
|
||||||
|
return &LocalMetadata{
|
||||||
|
AppVersion: appVersion.String(),
|
||||||
|
SystemVersion: systemVersion.String(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func rpcTryUpdate() error {
|
func rpcTryUpdate() error {
|
||||||
includePreRelease := config.IncludePreRelease
|
includePreRelease := config.IncludePreRelease
|
||||||
go func() {
|
go func() {
|
||||||
|
@ -429,7 +444,19 @@ func rpcGetSSHKeyState() (string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func rpcSetSSHKeyState(sshKey string) error {
|
func rpcSetSSHKeyState(sshKey string) error {
|
||||||
if sshKey != "" {
|
if sshKey == "" {
|
||||||
|
// Remove SSH key file if empty string is provided
|
||||||
|
if err := os.Remove(sshKeyFile); err != nil && !os.IsNotExist(err) {
|
||||||
|
return fmt.Errorf("failed to remove SSH key file: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate SSH key
|
||||||
|
if err := utils.ValidateSSHKey(sshKey); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// Create directory if it doesn't exist
|
// Create directory if it doesn't exist
|
||||||
if err := os.MkdirAll(sshKeyDir, 0700); err != nil {
|
if err := os.MkdirAll(sshKeyDir, 0700); err != nil {
|
||||||
return fmt.Errorf("failed to create SSH key directory: %w", err)
|
return fmt.Errorf("failed to create SSH key directory: %w", err)
|
||||||
|
@ -439,12 +466,6 @@ func rpcSetSSHKeyState(sshKey string) error {
|
||||||
if err := os.WriteFile(sshKeyFile, []byte(sshKey), 0600); err != nil {
|
if err := os.WriteFile(sshKeyFile, []byte(sshKey), 0600); err != nil {
|
||||||
return fmt.Errorf("failed to write SSH key: %w", err)
|
return fmt.Errorf("failed to write SSH key: %w", err)
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
// Remove SSH key file if empty string is provided
|
|
||||||
if err := os.Remove(sshKeyFile); err != nil && !os.IsNotExist(err) {
|
|
||||||
return fmt.Errorf("failed to remove SSH key file: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
@ -1049,6 +1070,103 @@ func rpcSetLocalLoopbackOnly(enabled bool) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
keyboardMacroCancel context.CancelFunc
|
||||||
|
keyboardMacroLock sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
// cancelKeyboardMacro cancels any ongoing keyboard macro execution
|
||||||
|
func cancelKeyboardMacro() {
|
||||||
|
keyboardMacroLock.Lock()
|
||||||
|
defer keyboardMacroLock.Unlock()
|
||||||
|
|
||||||
|
if keyboardMacroCancel != nil {
|
||||||
|
keyboardMacroCancel()
|
||||||
|
logger.Info().Msg("canceled keyboard macro")
|
||||||
|
keyboardMacroCancel = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func setKeyboardMacroCancel(cancel context.CancelFunc) {
|
||||||
|
keyboardMacroLock.Lock()
|
||||||
|
defer keyboardMacroLock.Unlock()
|
||||||
|
|
||||||
|
keyboardMacroCancel = cancel
|
||||||
|
}
|
||||||
|
|
||||||
|
func rpcExecuteKeyboardMacro(macro []hidrpc.KeyboardMacroStep) error {
|
||||||
|
cancelKeyboardMacro()
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
setKeyboardMacroCancel(cancel)
|
||||||
|
|
||||||
|
s := hidrpc.KeyboardMacroState{
|
||||||
|
State: true,
|
||||||
|
IsPaste: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
if currentSession != nil {
|
||||||
|
currentSession.reportHidRPCKeyboardMacroState(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
err := rpcDoExecuteKeyboardMacro(ctx, macro)
|
||||||
|
|
||||||
|
setKeyboardMacroCancel(nil)
|
||||||
|
|
||||||
|
s.State = false
|
||||||
|
if currentSession != nil {
|
||||||
|
currentSession.reportHidRPCKeyboardMacroState(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func rpcCancelKeyboardMacro() {
|
||||||
|
cancelKeyboardMacro()
|
||||||
|
}
|
||||||
|
|
||||||
|
var keyboardClearStateKeys = make([]byte, hidrpc.HidKeyBufferSize)
|
||||||
|
|
||||||
|
func isClearKeyStep(step hidrpc.KeyboardMacroStep) bool {
|
||||||
|
return step.Modifier == 0 && bytes.Equal(step.Keys, keyboardClearStateKeys)
|
||||||
|
}
|
||||||
|
|
||||||
|
func rpcDoExecuteKeyboardMacro(ctx context.Context, macro []hidrpc.KeyboardMacroStep) error {
|
||||||
|
logger.Debug().Interface("macro", macro).Msg("Executing keyboard macro")
|
||||||
|
|
||||||
|
for i, step := range macro {
|
||||||
|
delay := time.Duration(step.Delay) * time.Millisecond
|
||||||
|
|
||||||
|
err := rpcKeyboardReport(step.Modifier, step.Keys)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warn().Err(err).Msg("failed to execute keyboard macro")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// notify the device that the keyboard state is being cleared
|
||||||
|
if isClearKeyStep(step) {
|
||||||
|
gadget.UpdateKeysDown(0, keyboardClearStateKeys)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use context-aware sleep that can be cancelled
|
||||||
|
select {
|
||||||
|
case <-time.After(delay):
|
||||||
|
// Sleep completed normally
|
||||||
|
case <-ctx.Done():
|
||||||
|
// make sure keyboard state is reset
|
||||||
|
err := rpcKeyboardReport(0, keyboardClearStateKeys)
|
||||||
|
if err != nil {
|
||||||
|
logger.Warn().Err(err).Msg("failed to reset keyboard state")
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.Debug().Int("step", i).Msg("Keyboard macro cancelled during sleep")
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
var rpcHandlers = map[string]RPCHandler{
|
var rpcHandlers = map[string]RPCHandler{
|
||||||
"ping": {Func: rpcPing},
|
"ping": {Func: rpcPing},
|
||||||
"reboot": {Func: rpcReboot, Params: []string{"force"}},
|
"reboot": {Func: rpcReboot, Params: []string{"force"}},
|
||||||
|
@ -1059,10 +1177,10 @@ var rpcHandlers = map[string]RPCHandler{
|
||||||
"getNetworkSettings": {Func: rpcGetNetworkSettings},
|
"getNetworkSettings": {Func: rpcGetNetworkSettings},
|
||||||
"setNetworkSettings": {Func: rpcSetNetworkSettings, Params: []string{"settings"}},
|
"setNetworkSettings": {Func: rpcSetNetworkSettings, Params: []string{"settings"}},
|
||||||
"renewDHCPLease": {Func: rpcRenewDHCPLease},
|
"renewDHCPLease": {Func: rpcRenewDHCPLease},
|
||||||
"keyboardReport": {Func: rpcKeyboardReport, Params: []string{"modifier", "keys"}},
|
|
||||||
"getKeyboardLedState": {Func: rpcGetKeyboardLedState},
|
"getKeyboardLedState": {Func: rpcGetKeyboardLedState},
|
||||||
"keypressReport": {Func: rpcKeypressReport, Params: []string{"key", "press"}},
|
|
||||||
"getKeyDownState": {Func: rpcGetKeysDownState},
|
"getKeyDownState": {Func: rpcGetKeysDownState},
|
||||||
|
"keyboardReport": {Func: rpcKeyboardReport, Params: []string{"modifier", "keys"}},
|
||||||
|
"keypressReport": {Func: rpcKeypressReport, Params: []string{"key", "press"}},
|
||||||
"absMouseReport": {Func: rpcAbsMouseReport, Params: []string{"x", "y", "buttons"}},
|
"absMouseReport": {Func: rpcAbsMouseReport, Params: []string{"x", "y", "buttons"}},
|
||||||
"relMouseReport": {Func: rpcRelMouseReport, Params: []string{"dx", "dy", "buttons"}},
|
"relMouseReport": {Func: rpcRelMouseReport, Params: []string{"dx", "dy", "buttons"}},
|
||||||
"wheelReport": {Func: rpcWheelReport, Params: []string{"wheelY"}},
|
"wheelReport": {Func: rpcWheelReport, Params: []string{"wheelY"}},
|
||||||
|
@ -1084,6 +1202,7 @@ var rpcHandlers = map[string]RPCHandler{
|
||||||
"setEDID": {Func: rpcSetEDID, Params: []string{"edid"}},
|
"setEDID": {Func: rpcSetEDID, Params: []string{"edid"}},
|
||||||
"getDevChannelState": {Func: rpcGetDevChannelState},
|
"getDevChannelState": {Func: rpcGetDevChannelState},
|
||||||
"setDevChannelState": {Func: rpcSetDevChannelState, Params: []string{"enabled"}},
|
"setDevChannelState": {Func: rpcSetDevChannelState, Params: []string{"enabled"}},
|
||||||
|
"getLocalVersion": {Func: rpcGetLocalVersion},
|
||||||
"getUpdateStatus": {Func: rpcGetUpdateStatus},
|
"getUpdateStatus": {Func: rpcGetUpdateStatus},
|
||||||
"tryUpdate": {Func: rpcTryUpdate},
|
"tryUpdate": {Func: rpcTryUpdate},
|
||||||
"getDevModeState": {Func: rpcGetDevModeState},
|
"getDevModeState": {Func: rpcGetDevModeState},
|
||||||
|
|
9
main.go
9
main.go
|
@ -96,16 +96,25 @@ func Main() {
|
||||||
if !config.AutoUpdateEnabled {
|
if !config.AutoUpdateEnabled {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if isTimeSyncNeeded() || !timeSync.IsSyncSuccess() {
|
||||||
|
logger.Debug().Msg("system time is not synced, will retry in 30 seconds")
|
||||||
|
time.Sleep(30 * time.Second)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
if currentSession != nil {
|
if currentSession != nil {
|
||||||
logger.Debug().Msg("skipping update since a session is active")
|
logger.Debug().Msg("skipping update since a session is active")
|
||||||
time.Sleep(1 * time.Minute)
|
time.Sleep(1 * time.Minute)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
includePreRelease := config.IncludePreRelease
|
includePreRelease := config.IncludePreRelease
|
||||||
err = TryUpdate(context.Background(), GetDeviceID(), includePreRelease)
|
err = TryUpdate(context.Background(), GetDeviceID(), includePreRelease)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warn().Err(err).Msg("failed to auto update")
|
logger.Warn().Err(err).Msg("failed to auto update")
|
||||||
}
|
}
|
||||||
|
|
||||||
time.Sleep(1 * time.Hour)
|
time.Sleep(1 * time.Hour)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
5
mdns.go
5
mdns.go
|
@ -13,10 +13,7 @@ func initMdns() error {
|
||||||
networkState.GetHostname(),
|
networkState.GetHostname(),
|
||||||
networkState.GetFQDN(),
|
networkState.GetFQDN(),
|
||||||
},
|
},
|
||||||
ListenOptions: &mdns.MDNSListenOptions{
|
ListenOptions: config.NetworkConfig.GetMDNSMode(),
|
||||||
IPv4: true,
|
|
||||||
IPv6: true,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
27
network.go
27
network.go
|
@ -15,7 +15,7 @@ var (
|
||||||
networkState *network.NetworkInterfaceState
|
networkState *network.NetworkInterfaceState
|
||||||
)
|
)
|
||||||
|
|
||||||
func networkStateChanged() {
|
func networkStateChanged(isOnline bool) {
|
||||||
// do not block the main thread
|
// do not block the main thread
|
||||||
go waitCtrlAndRequestDisplayUpdate(true)
|
go waitCtrlAndRequestDisplayUpdate(true)
|
||||||
|
|
||||||
|
@ -37,6 +37,13 @@ func networkStateChanged() {
|
||||||
networkState.GetFQDN(),
|
networkState.GetFQDN(),
|
||||||
}, true)
|
}, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// if the network is now online, trigger an NTP sync if still needed
|
||||||
|
if isOnline && timeSync != nil && (isTimeSyncNeeded() || !timeSync.IsSyncSuccess()) {
|
||||||
|
if err := timeSync.Sync(); err != nil {
|
||||||
|
logger.Warn().Str("error", err.Error()).Msg("unable to sync time on network state change")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func initNetwork() error {
|
func initNetwork() error {
|
||||||
|
@ -48,13 +55,13 @@ func initNetwork() error {
|
||||||
NetworkConfig: config.NetworkConfig,
|
NetworkConfig: config.NetworkConfig,
|
||||||
Logger: networkLogger,
|
Logger: networkLogger,
|
||||||
OnStateChange: func(state *network.NetworkInterfaceState) {
|
OnStateChange: func(state *network.NetworkInterfaceState) {
|
||||||
networkStateChanged()
|
networkStateChanged(state.IsOnline())
|
||||||
},
|
},
|
||||||
OnInitialCheck: func(state *network.NetworkInterfaceState) {
|
OnInitialCheck: func(state *network.NetworkInterfaceState) {
|
||||||
networkStateChanged()
|
networkStateChanged(state.IsOnline())
|
||||||
},
|
},
|
||||||
OnDhcpLeaseChange: func(lease *udhcpc.Lease) {
|
OnDhcpLeaseChange: func(lease *udhcpc.Lease, state *network.NetworkInterfaceState) {
|
||||||
networkStateChanged()
|
networkStateChanged(state.IsOnline())
|
||||||
|
|
||||||
if currentSession == nil {
|
if currentSession == nil {
|
||||||
return
|
return
|
||||||
|
@ -64,7 +71,15 @@ func initNetwork() error {
|
||||||
},
|
},
|
||||||
OnConfigChange: func(networkConfig *network.NetworkConfig) {
|
OnConfigChange: func(networkConfig *network.NetworkConfig) {
|
||||||
config.NetworkConfig = networkConfig
|
config.NetworkConfig = networkConfig
|
||||||
networkStateChanged()
|
networkStateChanged(false)
|
||||||
|
|
||||||
|
if mDNS != nil {
|
||||||
|
_ = mDNS.SetListenOptions(networkConfig.GetMDNSMode())
|
||||||
|
_ = mDNS.SetLocalNames([]string{
|
||||||
|
networkState.GetHostname(),
|
||||||
|
networkState.GetFQDN(),
|
||||||
|
}, true)
|
||||||
|
}
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
Binary file not shown.
|
@ -1 +1 @@
|
||||||
6dabd0e657dd099280d9173069687786a4a8c9c25cf7f9e7ce2f940cab67c521
|
a4fca98710932aaa2765b57404e080105190cfa3af69171f4b4d95d4b78f9af0
|
||||||
|
|
Binary file not shown.
|
@ -0,0 +1,77 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
#
|
||||||
|
# Exit immediately if a command exits with a non-zero status
|
||||||
|
set -e
|
||||||
|
|
||||||
|
C_RST="$(tput sgr0)"
|
||||||
|
C_ERR="$(tput setaf 1)"
|
||||||
|
C_OK="$(tput setaf 2)"
|
||||||
|
C_WARN="$(tput setaf 3)"
|
||||||
|
C_INFO="$(tput setaf 5)"
|
||||||
|
|
||||||
|
msg() { printf '%s%s%s\n' $2 "$1" $C_RST; }
|
||||||
|
|
||||||
|
msg_info() { msg "$1" $C_INFO; }
|
||||||
|
msg_ok() { msg "$1" $C_OK; }
|
||||||
|
msg_err() { msg "$1" $C_ERR; }
|
||||||
|
msg_warn() { msg "$1" $C_WARN; }
|
||||||
|
|
||||||
|
# Get the latest release information
|
||||||
|
msg_info "Getting latest release information ..."
|
||||||
|
LATEST_RELEASE=$(curl -s \
|
||||||
|
-H "Accept: application/vnd.github+json" \
|
||||||
|
-H "X-GitHub-Api-Version: 2022-11-28" \
|
||||||
|
https://api.github.com/repos/netbootxyz/netboot.xyz/releases | jq '
|
||||||
|
[.[] | select(.prerelease == false and .draft == false and .assets != null and (.assets | length > 0))] |
|
||||||
|
sort_by(.created_at) |
|
||||||
|
.[-1]')
|
||||||
|
|
||||||
|
# Extract version, download URL, and digest
|
||||||
|
VERSION=$(echo "$LATEST_RELEASE" | jq -r '.tag_name')
|
||||||
|
ISO_URL=$(echo "$LATEST_RELEASE" | jq -r '.assets[] | select(.name == "netboot.xyz-multiarch.iso") | .browser_download_url')
|
||||||
|
EXPECTED_CHECKSUM=$(echo "$LATEST_RELEASE" | jq -r '.assets[] | select(.name == "netboot.xyz-multiarch.iso") | .digest' | sed 's/sha256://')
|
||||||
|
|
||||||
|
msg_ok "Latest version: $VERSION"
|
||||||
|
msg_ok "ISO URL: $ISO_URL"
|
||||||
|
msg_ok "Expected SHA256: $EXPECTED_CHECKSUM"
|
||||||
|
|
||||||
|
|
||||||
|
# Check if we already have the same version
|
||||||
|
if [ -f "resource/netboot.xyz-multiarch.iso" ]; then
|
||||||
|
msg_info "Checking current resource file ..."
|
||||||
|
|
||||||
|
# First check by checksum (fastest)
|
||||||
|
CURRENT_CHECKSUM=$(shasum -a 256 resource/netboot.xyz-multiarch.iso | awk '{print $1}')
|
||||||
|
|
||||||
|
if [ "$CURRENT_CHECKSUM" = "$EXPECTED_CHECKSUM" ]; then
|
||||||
|
msg_ok "Resource file is already up to date (version $VERSION). No update needed."
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
msg_info "Checksums differ, proceeding with download ..."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Download ISO file
|
||||||
|
TMP_ISO=$(mktemp -t netbootxyziso)
|
||||||
|
msg_info "Downloading ISO file ..."
|
||||||
|
curl -L -o "$TMP_ISO" "$ISO_URL"
|
||||||
|
|
||||||
|
# Verify SHA256 checksum
|
||||||
|
msg_info "Verifying SHA256 checksum ..."
|
||||||
|
ACTUAL_CHECKSUM=$(shasum -a 256 "$TMP_ISO" | awk '{print $1}')
|
||||||
|
|
||||||
|
if [ "$EXPECTED_CHECKSUM" = "$ACTUAL_CHECKSUM" ]; then
|
||||||
|
msg_ok "Verified SHA256 checksum."
|
||||||
|
mv -f "$TMP_ISO" "resource/netboot.xyz-multiarch.iso"
|
||||||
|
msg_ok "Updated ISO file."
|
||||||
|
git add "resource/netboot.xyz-multiarch.iso"
|
||||||
|
git commit -m "chore: update netboot.xyz-multiarch.iso to $VERSION"
|
||||||
|
msg_ok "Committed changes."
|
||||||
|
msg_ok "You can now push the changes to the remote repository."
|
||||||
|
exit 0
|
||||||
|
else
|
||||||
|
msg_err "Inconsistent SHA256 checksum."
|
||||||
|
msg_err "Expected: $EXPECTED_CHECKSUM"
|
||||||
|
msg_err "Actual: $ACTUAL_CHECKSUM"
|
||||||
|
exit 1
|
||||||
|
fi
|
|
@ -6,27 +6,34 @@
|
||||||
<!-- These are the fonts used in the app -->
|
<!-- These are the fonts used in the app -->
|
||||||
<link
|
<link
|
||||||
rel="preload"
|
rel="preload"
|
||||||
href="/fonts/CircularXXWeb-Medium.woff2"
|
href="./public/fonts/CircularXXWeb-Medium.woff2"
|
||||||
as="font"
|
as="font"
|
||||||
type="font/woff2"
|
type="font/woff2"
|
||||||
crossorigin
|
crossorigin
|
||||||
/>
|
/>
|
||||||
<link
|
<link
|
||||||
rel="preload"
|
rel="preload"
|
||||||
href="/fonts/CircularXXWeb-Book.woff2"
|
href="./public/fonts/CircularXXWeb-Book.woff2"
|
||||||
as="font"
|
as="font"
|
||||||
type="font/woff2"
|
type="font/woff2"
|
||||||
crossorigin
|
crossorigin
|
||||||
/>
|
/>
|
||||||
<link
|
<link
|
||||||
rel="preload"
|
rel="preload"
|
||||||
href="/fonts/CircularXXWeb-Regular.woff2"
|
href="./public/fonts/CircularXXWeb-Regular.woff2"
|
||||||
|
as="font"
|
||||||
|
type="font/woff2"
|
||||||
|
crossorigin
|
||||||
|
/>
|
||||||
|
<link
|
||||||
|
rel="preload"
|
||||||
|
href="./public/fonts/CircularXXWeb-Black.woff2"
|
||||||
as="font"
|
as="font"
|
||||||
type="font/woff2"
|
type="font/woff2"
|
||||||
crossorigin
|
crossorigin
|
||||||
/>
|
/>
|
||||||
<title>JetKVM</title>
|
<title>JetKVM</title>
|
||||||
<link rel="stylesheet" href="/fonts/fonts.css" />
|
<link rel="stylesheet" href="./public/fonts/fonts.css" />
|
||||||
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
|
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<link rel="shortcut icon" href="/favicon.ico" />
|
<link rel="shortcut icon" href="/favicon.ico" />
|
||||||
|
@ -36,23 +43,21 @@
|
||||||
<meta name="theme-color" content="#051946" />
|
<meta name="theme-color" content="#051946" />
|
||||||
<meta name="description" content="A web-based KVM console for managing remote servers." />
|
<meta name="description" content="A web-based KVM console for managing remote servers." />
|
||||||
<script>
|
<script>
|
||||||
// Initial theme setup
|
function applyThemeFromPreference() {
|
||||||
document.documentElement.classList.toggle(
|
// dark theme setup
|
||||||
"dark",
|
var darkDesired = localStorage.theme === "dark" ||
|
||||||
localStorage.theme === "dark" ||
|
|
||||||
(!("theme" in localStorage) &&
|
(!("theme" in localStorage) &&
|
||||||
window.matchMedia("(prefers-color-scheme: dark)").matches),
|
window.matchMedia("(prefers-color-scheme: dark)").matches)
|
||||||
);
|
|
||||||
|
document.documentElement.classList.toggle("dark", darkDesired)
|
||||||
|
}
|
||||||
|
|
||||||
|
// initial theme application
|
||||||
|
applyThemeFromPreference();
|
||||||
|
|
||||||
// Listen for system theme changes
|
// Listen for system theme changes
|
||||||
window
|
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", applyThemeFromPreference);
|
||||||
.matchMedia("(prefers-color-scheme: dark)")
|
window.matchMedia("(prefers-color-scheme: light)").addEventListener("change", applyThemeFromPreference);
|
||||||
.addEventListener("change", ({ matches }) => {
|
|
||||||
if (!("theme" in localStorage)) {
|
|
||||||
// Only auto-switch if user hasn't manually set a theme
|
|
||||||
document.documentElement.classList.toggle("dark", matches);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
</script>
|
||||||
</head>
|
</head>
|
||||||
<body
|
<body
|
||||||
|
|
|
@ -68,7 +68,7 @@
|
||||||
"prettier-plugin-tailwindcss": "^0.6.14",
|
"prettier-plugin-tailwindcss": "^0.6.14",
|
||||||
"tailwindcss": "^4.1.12",
|
"tailwindcss": "^4.1.12",
|
||||||
"typescript": "^5.9.2",
|
"typescript": "^5.9.2",
|
||||||
"vite": "^7.1.4",
|
"vite": "^7.1.5",
|
||||||
"vite-tsconfig-paths": "^5.1.4"
|
"vite-tsconfig-paths": "^5.1.4"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
|
@ -1793,6 +1793,66 @@
|
||||||
"node": ">=14.0.0"
|
"node": ">=14.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
|
||||||
|
"version": "1.4.5",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/wasi-threads": "1.0.4",
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
|
||||||
|
"version": "1.4.5",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
|
||||||
|
"version": "1.0.4",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
|
||||||
|
"version": "0.2.12",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"@emnapi/core": "^1.4.3",
|
||||||
|
"@emnapi/runtime": "^1.4.3",
|
||||||
|
"@tybys/wasm-util": "^0.10.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
|
||||||
|
"version": "0.10.0",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true,
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "^2.4.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
|
||||||
|
"version": "2.8.0",
|
||||||
|
"dev": true,
|
||||||
|
"inBundle": true,
|
||||||
|
"license": "0BSD",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
|
||||||
"version": "4.1.12",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.12.tgz",
|
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.12.tgz",
|
||||||
|
@ -6563,13 +6623,13 @@
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/tinyglobby": {
|
"node_modules/tinyglobby": {
|
||||||
"version": "0.2.14",
|
"version": "0.2.15",
|
||||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.14.tgz",
|
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
|
||||||
"integrity": "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ==",
|
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fdir": "^6.4.4",
|
"fdir": "^6.5.0",
|
||||||
"picomatch": "^4.0.2"
|
"picomatch": "^4.0.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=12.0.0"
|
"node": ">=12.0.0"
|
||||||
|
@ -6893,9 +6953,9 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "7.1.4",
|
"version": "7.1.5",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.4.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-7.1.5.tgz",
|
||||||
"integrity": "sha512-X5QFK4SGynAeeIt+A7ZWnApdUyHYm+pzv/8/A57LqSGcI88U6R6ipOs3uCesdc6yl7nl+zNO0t8LmqAdXcQihw==",
|
"integrity": "sha512-4cKBO9wR75r0BeIWWWId9XK9Lj6La5X846Zw9dFfzMRw38IlTk2iCcUt6hsyiDRcPidc55ZParFYDXi0nXOeLQ==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "^0.25.0",
|
"esbuild": "^0.25.0",
|
||||||
|
@ -6903,7 +6963,7 @@
|
||||||
"picomatch": "^4.0.3",
|
"picomatch": "^4.0.3",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"rollup": "^4.43.0",
|
"rollup": "^4.43.0",
|
||||||
"tinyglobby": "^0.2.14"
|
"tinyglobby": "^0.2.15"
|
||||||
},
|
},
|
||||||
"bin": {
|
"bin": {
|
||||||
"vite": "bin/vite.js"
|
"vite": "bin/vite.js"
|
||||||
|
|
|
@ -79,7 +79,7 @@
|
||||||
"prettier-plugin-tailwindcss": "^0.6.14",
|
"prettier-plugin-tailwindcss": "^0.6.14",
|
||||||
"tailwindcss": "^4.1.12",
|
"tailwindcss": "^4.1.12",
|
||||||
"typescript": "^5.9.2",
|
"typescript": "^5.9.2",
|
||||||
"vite": "^7.1.4",
|
"vite": "^7.1.5",
|
||||||
"vite-tsconfig-paths": "^5.1.4"
|
"vite-tsconfig-paths": "^5.1.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,2 +0,0 @@
|
||||||
User-agent: *
|
|
||||||
Disallow: /
|
|
|
@ -27,6 +27,7 @@ export default function InfoBar() {
|
||||||
|
|
||||||
const { rpcDataChannel } = useRTCStore();
|
const { rpcDataChannel } = useRTCStore();
|
||||||
const { debugMode, mouseMode, showPressedKeys } = useSettingsStore();
|
const { debugMode, mouseMode, showPressedKeys } = useSettingsStore();
|
||||||
|
const { isPasteInProgress } = useHidStore();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!rpcDataChannel) return;
|
if (!rpcDataChannel) return;
|
||||||
|
@ -108,7 +109,12 @@ export default function InfoBar() {
|
||||||
<span className="text-xs">{rpcHidStatus}</span>
|
<span className="text-xs">{rpcHidStatus}</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{isPasteInProgress && (
|
||||||
|
<div className="flex w-[156px] items-center gap-x-1">
|
||||||
|
<span className="text-xs font-semibold">Paste Mode:</span>
|
||||||
|
<span className="text-xs">Enabled</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{showPressedKeys && (
|
{showPressedKeys && (
|
||||||
<div className="flex items-center gap-x-1">
|
<div className="flex items-center gap-x-1">
|
||||||
<span className="text-xs font-semibold">Keys:</span>
|
<span className="text-xs font-semibold">Keys:</span>
|
||||||
|
|
|
@ -17,7 +17,7 @@ export default function Ipv6NetworkCard({
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-x-6 gap-y-2">
|
<div className="grid grid-cols-2 gap-x-6 gap-y-2">
|
||||||
{networkState?.dhcp_lease?.ip && (
|
{networkState?.ipv6_link_local && (
|
||||||
<div className="flex flex-col justify-between">
|
<div className="flex flex-col justify-between">
|
||||||
<span className="text-sm text-slate-600 dark:text-slate-400">
|
<span className="text-sm text-slate-600 dark:text-slate-400">
|
||||||
Link-local
|
Link-local
|
||||||
|
|
|
@ -22,15 +22,7 @@ const USBStateMap: Record<USBStates, string> = {
|
||||||
"not attached": "Disconnected",
|
"not attached": "Disconnected",
|
||||||
suspended: "Low power mode",
|
suspended: "Low power mode",
|
||||||
};
|
};
|
||||||
|
const StatusCardProps: StatusProps = {
|
||||||
export default function USBStateStatus({
|
|
||||||
state,
|
|
||||||
peerConnectionState,
|
|
||||||
}: {
|
|
||||||
state: USBStates;
|
|
||||||
peerConnectionState?: RTCPeerConnectionState | null;
|
|
||||||
}) {
|
|
||||||
const StatusCardProps: StatusProps = {
|
|
||||||
configured: {
|
configured: {
|
||||||
icon: ({ className }) => (
|
icon: ({ className }) => (
|
||||||
<img className={cx(className)} src={KeyboardAndMouseConnectedIcon} alt="" />
|
<img className={cx(className)} src={KeyboardAndMouseConnectedIcon} alt="" />
|
||||||
|
@ -62,7 +54,16 @@ export default function USBStateStatus({
|
||||||
iconClassName: "h-5 w-5 opacity-50 grayscale filter",
|
iconClassName: "h-5 w-5 opacity-50 grayscale filter",
|
||||||
statusIndicatorClassName: "bg-green-500 border-green-600",
|
statusIndicatorClassName: "bg-green-500 border-green-600",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export default function USBStateStatus({
|
||||||
|
state,
|
||||||
|
peerConnectionState,
|
||||||
|
}: {
|
||||||
|
state: USBStates;
|
||||||
|
peerConnectionState?: RTCPeerConnectionState | null;
|
||||||
|
}) {
|
||||||
|
|
||||||
const props = StatusCardProps[state];
|
const props = StatusCardProps[state];
|
||||||
if (!props) {
|
if (!props) {
|
||||||
console.warn("Unsupported USB state: ", state);
|
console.warn("Unsupported USB state: ", state);
|
||||||
|
|
|
@ -237,6 +237,7 @@ export default function WebRTCVideo() {
|
||||||
const keyDownHandler = useCallback(
|
const keyDownHandler = useCallback(
|
||||||
(e: KeyboardEvent) => {
|
(e: KeyboardEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (e.repeat) return;
|
||||||
const code = getAdjustedKeyCode(e);
|
const code = getAdjustedKeyCode(e);
|
||||||
const hidKey = keys[code];
|
const hidKey = keys[code];
|
||||||
|
|
||||||
|
|
|
@ -1,40 +1,44 @@
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
|
||||||
import { LuCornerDownLeft } from "react-icons/lu";
|
|
||||||
import { ExclamationCircleIcon } from "@heroicons/react/16/solid";
|
|
||||||
import { useClose } from "@headlessui/react";
|
import { useClose } from "@headlessui/react";
|
||||||
|
import { ExclamationCircleIcon } from "@heroicons/react/16/solid";
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
import { LuCornerDownLeft } from "react-icons/lu";
|
||||||
|
|
||||||
import { Button } from "@components/Button";
|
import { cx } from "@/cva.config";
|
||||||
import { GridCard } from "@components/Card";
|
import { useHidStore, useSettingsStore, useUiStore } from "@/hooks/stores";
|
||||||
import { TextAreaWithLabel } from "@components/TextArea";
|
|
||||||
import { SettingsPageHeader } from "@components/SettingsPageheader";
|
|
||||||
import { JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
import { JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
||||||
import { useHidStore, useRTCStore, useUiStore, useSettingsStore } from "@/hooks/stores";
|
import useKeyboard, { type MacroStep } from "@/hooks/useKeyboard";
|
||||||
import { keys, modifiers } from "@/keyboardMappings";
|
|
||||||
import { KeyStroke } from "@/keyboardLayouts";
|
|
||||||
import useKeyboardLayout from "@/hooks/useKeyboardLayout";
|
import useKeyboardLayout from "@/hooks/useKeyboardLayout";
|
||||||
import notifications from "@/notifications";
|
import notifications from "@/notifications";
|
||||||
|
import { Button } from "@components/Button";
|
||||||
|
import { GridCard } from "@components/Card";
|
||||||
|
import { InputFieldWithLabel } from "@components/InputField";
|
||||||
|
import { SettingsPageHeader } from "@components/SettingsPageheader";
|
||||||
|
import { TextAreaWithLabel } from "@components/TextArea";
|
||||||
|
|
||||||
const hidKeyboardPayload = (modifier: number, keys: number[]) => {
|
// uint32 max value / 4
|
||||||
return { modifier, keys };
|
const pasteMaxLength = 1073741824;
|
||||||
};
|
|
||||||
|
|
||||||
const modifierCode = (shift?: boolean, altRight?: boolean) => {
|
|
||||||
return (shift ? modifiers.ShiftLeft : 0)
|
|
||||||
| (altRight ? modifiers.AltRight : 0)
|
|
||||||
}
|
|
||||||
const noModifier = 0
|
|
||||||
|
|
||||||
export default function PasteModal() {
|
export default function PasteModal() {
|
||||||
const TextAreaRef = useRef<HTMLTextAreaElement>(null);
|
const TextAreaRef = useRef<HTMLTextAreaElement>(null);
|
||||||
const { setPasteModeEnabled } = useHidStore();
|
const { isPasteInProgress } = useHidStore();
|
||||||
const { setDisableVideoFocusTrap } = useUiStore();
|
const { setDisableVideoFocusTrap } = useUiStore();
|
||||||
|
|
||||||
const { send } = useJsonRpc();
|
const { send } = useJsonRpc();
|
||||||
const { rpcDataChannel } = useRTCStore();
|
const { executeMacro, cancelExecuteMacro } = useKeyboard();
|
||||||
|
|
||||||
const [invalidChars, setInvalidChars] = useState<string[]>([]);
|
const [invalidChars, setInvalidChars] = useState<string[]>([]);
|
||||||
|
const [delayValue, setDelayValue] = useState(100);
|
||||||
|
const delay = useMemo(() => {
|
||||||
|
if (delayValue < 50 || delayValue > 65534) {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
return delayValue;
|
||||||
|
}, [delayValue]);
|
||||||
const close = useClose();
|
const close = useClose();
|
||||||
|
|
||||||
|
const debugMode = useSettingsStore(state => state.debugMode);
|
||||||
|
const delayClassName = useMemo(() => debugMode ? "" : "hidden", [debugMode]);
|
||||||
|
|
||||||
const { setKeyboardLayout } = useSettingsStore();
|
const { setKeyboardLayout } = useSettingsStore();
|
||||||
const { selectedKeyboard } = useKeyboardLayout();
|
const { selectedKeyboard } = useKeyboardLayout();
|
||||||
|
|
||||||
|
@ -46,21 +50,19 @@ export default function PasteModal() {
|
||||||
}, [send, setKeyboardLayout]);
|
}, [send, setKeyboardLayout]);
|
||||||
|
|
||||||
const onCancelPasteMode = useCallback(() => {
|
const onCancelPasteMode = useCallback(() => {
|
||||||
setPasteModeEnabled(false);
|
cancelExecuteMacro();
|
||||||
setDisableVideoFocusTrap(false);
|
setDisableVideoFocusTrap(false);
|
||||||
setInvalidChars([]);
|
setInvalidChars([]);
|
||||||
}, [setDisableVideoFocusTrap, setPasteModeEnabled]);
|
}, [setDisableVideoFocusTrap, cancelExecuteMacro]);
|
||||||
|
|
||||||
const onConfirmPaste = useCallback(async () => {
|
const onConfirmPaste = useCallback(async () => {
|
||||||
setPasteModeEnabled(false);
|
if (!TextAreaRef.current || !selectedKeyboard) return;
|
||||||
setDisableVideoFocusTrap(false);
|
|
||||||
|
|
||||||
if (rpcDataChannel?.readyState !== "open" || !TextAreaRef.current) return;
|
|
||||||
if (!selectedKeyboard) return;
|
|
||||||
|
|
||||||
const text = TextAreaRef.current.value;
|
const text = TextAreaRef.current.value;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const macroSteps: MacroStep[] = [];
|
||||||
|
|
||||||
for (const char of text) {
|
for (const char of text) {
|
||||||
const keyprops = selectedKeyboard.chars[char];
|
const keyprops = selectedKeyboard.chars[char];
|
||||||
if (!keyprops) continue;
|
if (!keyprops) continue;
|
||||||
|
@ -70,39 +72,41 @@ export default function PasteModal() {
|
||||||
|
|
||||||
// if this is an accented character, we need to send that accent FIRST
|
// if this is an accented character, we need to send that accent FIRST
|
||||||
if (accentKey) {
|
if (accentKey) {
|
||||||
await sendKeystroke({modifier: modifierCode(accentKey.shift, accentKey.altRight), keys: [ keys[accentKey.key] ] })
|
const accentModifiers: string[] = [];
|
||||||
|
if (accentKey.shift) accentModifiers.push("ShiftLeft");
|
||||||
|
if (accentKey.altRight) accentModifiers.push("AltRight");
|
||||||
|
|
||||||
|
macroSteps.push({
|
||||||
|
keys: [String(accentKey.key)],
|
||||||
|
modifiers: accentModifiers.length > 0 ? accentModifiers : null,
|
||||||
|
delay,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// now send the actual key
|
// now send the actual key
|
||||||
await sendKeystroke({ modifier: modifierCode(shift, altRight), keys: [ keys[key] ]});
|
const modifiers: string[] = [];
|
||||||
|
if (shift) modifiers.push("ShiftLeft");
|
||||||
|
if (altRight) modifiers.push("AltRight");
|
||||||
|
|
||||||
|
macroSteps.push({
|
||||||
|
keys: [String(key)],
|
||||||
|
modifiers: modifiers.length > 0 ? modifiers : null,
|
||||||
|
delay
|
||||||
|
});
|
||||||
|
|
||||||
// if what was requested was a dead key, we need to send an unmodified space to emit
|
// if what was requested was a dead key, we need to send an unmodified space to emit
|
||||||
// just the accent character
|
// just the accent character
|
||||||
if (deadKey) {
|
if (deadKey) macroSteps.push({ keys: ["Space"], modifiers: null, delay });
|
||||||
await sendKeystroke({ modifier: noModifier, keys: [ keys["Space"] ] });
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// now send a message with no keys down to "release" the keys
|
if (macroSteps.length > 0) {
|
||||||
await sendKeystroke({ modifier: 0, keys: [] });
|
await executeMacro(macroSteps);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Failed to paste text:", error);
|
console.error("Failed to paste text:", error);
|
||||||
notifications.error("Failed to paste text");
|
notifications.error("Failed to paste text");
|
||||||
}
|
}
|
||||||
|
}, [selectedKeyboard, executeMacro, delay]);
|
||||||
async function sendKeystroke(stroke: KeyStroke) {
|
|
||||||
await new Promise<void>((resolve, reject) => {
|
|
||||||
send(
|
|
||||||
"keyboardReport",
|
|
||||||
hidKeyboardPayload(stroke.modifier, stroke.keys),
|
|
||||||
params => {
|
|
||||||
if ("error" in params) return reject(params.error);
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}, [selectedKeyboard, rpcDataChannel?.readyState, send, setDisableVideoFocusTrap, setPasteModeEnabled]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (TextAreaRef.current) {
|
if (TextAreaRef.current) {
|
||||||
|
@ -122,19 +126,25 @@ export default function PasteModal() {
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
className="animate-fadeIn opacity-0 space-y-2"
|
className="animate-fadeIn space-y-2 opacity-0"
|
||||||
style={{
|
style={{
|
||||||
animationDuration: "0.7s",
|
animationDuration: "0.7s",
|
||||||
animationDelay: "0.1s",
|
animationDelay: "0.1s",
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div>
|
<div>
|
||||||
<div className="w-full" onKeyUp={e => e.stopPropagation()} onKeyDown={e => e.stopPropagation()}>
|
<div
|
||||||
|
className="w-full"
|
||||||
|
onKeyUp={e => e.stopPropagation()}
|
||||||
|
onKeyDown={e => e.stopPropagation()} onKeyDownCapture={e => e.stopPropagation()}
|
||||||
|
onKeyUpCapture={e => e.stopPropagation()}
|
||||||
|
>
|
||||||
<TextAreaWithLabel
|
<TextAreaWithLabel
|
||||||
ref={TextAreaRef}
|
ref={TextAreaRef}
|
||||||
label="Paste from host"
|
label="Paste from host"
|
||||||
rows={4}
|
rows={4}
|
||||||
onKeyUp={e => e.stopPropagation()}
|
onKeyUp={e => e.stopPropagation()}
|
||||||
|
maxLength={pasteMaxLength}
|
||||||
onKeyDown={e => {
|
onKeyDown={e => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
||||||
|
@ -171,9 +181,31 @@ export default function PasteModal() {
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div className={cx("text-xs text-slate-600 dark:text-slate-400", delayClassName)}>
|
||||||
|
<InputFieldWithLabel
|
||||||
|
type="number"
|
||||||
|
label="Delay between keys"
|
||||||
|
placeholder="Delay between keys"
|
||||||
|
min={50}
|
||||||
|
max={65534}
|
||||||
|
value={delayValue}
|
||||||
|
onChange={e => {
|
||||||
|
setDelayValue(parseInt(e.target.value, 10));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{delayValue < 50 || delayValue > 65534 && (
|
||||||
|
<div className="mt-2 flex items-center gap-x-2">
|
||||||
|
<ExclamationCircleIcon className="h-4 w-4 text-red-500 dark:text-red-400" />
|
||||||
|
<span className="text-xs text-red-500 dark:text-red-400">
|
||||||
|
Delay must be between 50 and 65534
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
<p className="text-xs text-slate-600 dark:text-slate-400">
|
<p className="text-xs text-slate-600 dark:text-slate-400">
|
||||||
Sending text using keyboard layout: {selectedKeyboard.isoCode}-{selectedKeyboard.name}
|
Sending text using keyboard layout: {selectedKeyboard.isoCode}-
|
||||||
|
{selectedKeyboard.name}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -181,7 +213,7 @@ export default function PasteModal() {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div
|
<div
|
||||||
className="flex animate-fadeIn opacity-0 items-center justify-end gap-x-2"
|
className="flex animate-fadeIn items-center justify-end gap-x-2 opacity-0"
|
||||||
style={{
|
style={{
|
||||||
animationDuration: "0.7s",
|
animationDuration: "0.7s",
|
||||||
animationDelay: "0.2s",
|
animationDelay: "0.2s",
|
||||||
|
@ -200,6 +232,7 @@ export default function PasteModal() {
|
||||||
size="SM"
|
size="SM"
|
||||||
theme="primary"
|
theme="primary"
|
||||||
text="Confirm Paste"
|
text="Confirm Paste"
|
||||||
|
disabled={isPasteInProgress}
|
||||||
onClick={onConfirmPaste}
|
onClick={onConfirmPaste}
|
||||||
LeadingIcon={LuCornerDownLeft}
|
LeadingIcon={LuCornerDownLeft}
|
||||||
/>
|
/>
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { KeyboardLedState, KeysDownState } from "./stores";
|
import { hidKeyBufferSize, KeyboardLedState, KeysDownState } from "./stores";
|
||||||
|
|
||||||
export const HID_RPC_MESSAGE_TYPES = {
|
export const HID_RPC_MESSAGE_TYPES = {
|
||||||
Handshake: 0x01,
|
Handshake: 0x01,
|
||||||
|
@ -6,9 +6,13 @@ export const HID_RPC_MESSAGE_TYPES = {
|
||||||
PointerReport: 0x03,
|
PointerReport: 0x03,
|
||||||
WheelReport: 0x04,
|
WheelReport: 0x04,
|
||||||
KeypressReport: 0x05,
|
KeypressReport: 0x05,
|
||||||
|
KeypressKeepAliveReport: 0x09,
|
||||||
MouseReport: 0x06,
|
MouseReport: 0x06,
|
||||||
|
KeyboardMacroReport: 0x07,
|
||||||
|
CancelKeyboardMacroReport: 0x08,
|
||||||
KeyboardLedState: 0x32,
|
KeyboardLedState: 0x32,
|
||||||
KeysDownState: 0x33,
|
KeysDownState: 0x33,
|
||||||
|
KeyboardMacroState: 0x34,
|
||||||
}
|
}
|
||||||
|
|
||||||
export type HidRpcMessageType = typeof HID_RPC_MESSAGE_TYPES[keyof typeof HID_RPC_MESSAGE_TYPES];
|
export type HidRpcMessageType = typeof HID_RPC_MESSAGE_TYPES[keyof typeof HID_RPC_MESSAGE_TYPES];
|
||||||
|
@ -28,7 +32,31 @@ const fromInt32toUint8 = (n: number) => {
|
||||||
(n >> 24) & 0xFF,
|
(n >> 24) & 0xFF,
|
||||||
(n >> 16) & 0xFF,
|
(n >> 16) & 0xFF,
|
||||||
(n >> 8) & 0xFF,
|
(n >> 8) & 0xFF,
|
||||||
(n >> 0) & 0xFF,
|
n & 0xFF,
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fromUint16toUint8 = (n: number) => {
|
||||||
|
if (n > 65535 || n < 0) {
|
||||||
|
throw new Error(`Number ${n} is not within the uint16 range`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Uint8Array([
|
||||||
|
(n >> 8) & 0xFF,
|
||||||
|
n & 0xFF,
|
||||||
|
]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const fromUint32toUint8 = (n: number) => {
|
||||||
|
if (n > 4294967295 || n < 0) {
|
||||||
|
throw new Error(`Number ${n} is not within the uint32 range`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Uint8Array([
|
||||||
|
(n >> 24) & 0xFF,
|
||||||
|
(n >> 16) & 0xFF,
|
||||||
|
(n >> 8) & 0xFF,
|
||||||
|
n & 0xFF,
|
||||||
]);
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -37,7 +65,7 @@ const fromInt8ToUint8 = (n: number) => {
|
||||||
throw new Error(`Number ${n} is not within the int8 range`);
|
throw new Error(`Number ${n} is not within the int8 range`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (n >> 0) & 0xFF;
|
return n & 0xFF;
|
||||||
};
|
};
|
||||||
|
|
||||||
const keyboardLedStateMasks = {
|
const keyboardLedStateMasks = {
|
||||||
|
@ -186,6 +214,99 @@ export class KeyboardReportMessage extends RpcMessage {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface KeyboardMacroStep extends KeysDownState {
|
||||||
|
delay: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class KeyboardMacroReportMessage extends RpcMessage {
|
||||||
|
isPaste: boolean;
|
||||||
|
stepCount: number;
|
||||||
|
steps: KeyboardMacroStep[];
|
||||||
|
|
||||||
|
KEYS_LENGTH = hidKeyBufferSize;
|
||||||
|
|
||||||
|
constructor(isPaste: boolean, stepCount: number, steps: KeyboardMacroStep[]) {
|
||||||
|
super(HID_RPC_MESSAGE_TYPES.KeyboardMacroReport);
|
||||||
|
this.isPaste = isPaste;
|
||||||
|
this.stepCount = stepCount;
|
||||||
|
this.steps = steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
marshal(): Uint8Array {
|
||||||
|
// validate if length is correct
|
||||||
|
if (this.stepCount !== this.steps.length) {
|
||||||
|
throw new Error(`Length ${this.stepCount} is not equal to the number of steps ${this.steps.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = new Uint8Array(this.stepCount * 9 + 6);
|
||||||
|
data.set(new Uint8Array([
|
||||||
|
this.messageType,
|
||||||
|
this.isPaste ? 1 : 0,
|
||||||
|
...fromUint32toUint8(this.stepCount),
|
||||||
|
]), 0);
|
||||||
|
|
||||||
|
for (let i = 0; i < this.stepCount; i++) {
|
||||||
|
const step = this.steps[i];
|
||||||
|
if (!withinUint8Range(step.modifier)) {
|
||||||
|
throw new Error(`Modifier ${step.modifier} is not within the uint8 range`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure the keys are within the KEYS_LENGTH range
|
||||||
|
const keys = step.keys;
|
||||||
|
if (keys.length > this.KEYS_LENGTH) {
|
||||||
|
throw new Error(`Keys ${keys} is not within the hidKeyBufferSize range`);
|
||||||
|
} else if (keys.length < this.KEYS_LENGTH) {
|
||||||
|
keys.push(...Array(this.KEYS_LENGTH - keys.length).fill(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of keys) {
|
||||||
|
if (!withinUint8Range(key)) {
|
||||||
|
throw new Error(`Key ${key} is not within the uint8 range`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const macroBinary = new Uint8Array([
|
||||||
|
step.modifier,
|
||||||
|
...keys,
|
||||||
|
...fromUint16toUint8(step.delay),
|
||||||
|
]);
|
||||||
|
const offset = 6 + i * 9;
|
||||||
|
|
||||||
|
|
||||||
|
data.set(macroBinary, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class KeyboardMacroStateMessage extends RpcMessage {
|
||||||
|
state: boolean;
|
||||||
|
isPaste: boolean;
|
||||||
|
|
||||||
|
constructor(state: boolean, isPaste: boolean) {
|
||||||
|
super(HID_RPC_MESSAGE_TYPES.KeyboardMacroState);
|
||||||
|
this.state = state;
|
||||||
|
this.isPaste = isPaste;
|
||||||
|
}
|
||||||
|
|
||||||
|
marshal(): Uint8Array {
|
||||||
|
return new Uint8Array([
|
||||||
|
this.messageType,
|
||||||
|
this.state ? 1 : 0,
|
||||||
|
this.isPaste ? 1 : 0,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static unmarshal(data: Uint8Array): KeyboardMacroStateMessage | undefined {
|
||||||
|
if (data.length < 1) {
|
||||||
|
throw new Error(`Invalid keyboard macro state report message length: ${data.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new KeyboardMacroStateMessage(data[0] === 1, data[1] === 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class KeyboardLedStateMessage extends RpcMessage {
|
export class KeyboardLedStateMessage extends RpcMessage {
|
||||||
keyboardLedState: KeyboardLedState;
|
keyboardLedState: KeyboardLedState;
|
||||||
|
|
||||||
|
@ -256,6 +377,17 @@ export class PointerReportMessage extends RpcMessage {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class CancelKeyboardMacroReportMessage extends RpcMessage {
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super(HID_RPC_MESSAGE_TYPES.CancelKeyboardMacroReport);
|
||||||
|
}
|
||||||
|
|
||||||
|
marshal(): Uint8Array {
|
||||||
|
return new Uint8Array([this.messageType]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class MouseReportMessage extends RpcMessage {
|
export class MouseReportMessage extends RpcMessage {
|
||||||
dx: number;
|
dx: number;
|
||||||
dy: number;
|
dy: number;
|
||||||
|
@ -278,12 +410,26 @@ export class MouseReportMessage extends RpcMessage {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class KeypressKeepAliveMessage extends RpcMessage {
|
||||||
|
constructor() {
|
||||||
|
super(HID_RPC_MESSAGE_TYPES.KeypressKeepAliveReport);
|
||||||
|
}
|
||||||
|
|
||||||
|
marshal(): Uint8Array {
|
||||||
|
return new Uint8Array([this.messageType]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export const messageRegistry = {
|
export const messageRegistry = {
|
||||||
[HID_RPC_MESSAGE_TYPES.Handshake]: HandshakeMessage,
|
[HID_RPC_MESSAGE_TYPES.Handshake]: HandshakeMessage,
|
||||||
[HID_RPC_MESSAGE_TYPES.KeysDownState]: KeysDownStateMessage,
|
[HID_RPC_MESSAGE_TYPES.KeysDownState]: KeysDownStateMessage,
|
||||||
[HID_RPC_MESSAGE_TYPES.KeyboardLedState]: KeyboardLedStateMessage,
|
[HID_RPC_MESSAGE_TYPES.KeyboardLedState]: KeyboardLedStateMessage,
|
||||||
[HID_RPC_MESSAGE_TYPES.KeyboardReport]: KeyboardReportMessage,
|
[HID_RPC_MESSAGE_TYPES.KeyboardReport]: KeyboardReportMessage,
|
||||||
[HID_RPC_MESSAGE_TYPES.KeypressReport]: KeypressReportMessage,
|
[HID_RPC_MESSAGE_TYPES.KeypressReport]: KeypressReportMessage,
|
||||||
|
[HID_RPC_MESSAGE_TYPES.KeyboardMacroReport]: KeyboardMacroReportMessage,
|
||||||
|
[HID_RPC_MESSAGE_TYPES.CancelKeyboardMacroReport]: CancelKeyboardMacroReportMessage,
|
||||||
|
[HID_RPC_MESSAGE_TYPES.KeyboardMacroState]: KeyboardMacroStateMessage,
|
||||||
|
[HID_RPC_MESSAGE_TYPES.KeypressKeepAliveReport]: KeypressKeepAliveMessage,
|
||||||
}
|
}
|
||||||
|
|
||||||
export const unmarshalHidRpcMessage = (data: Uint8Array): RpcMessage | undefined => {
|
export const unmarshalHidRpcMessage = (data: Uint8Array): RpcMessage | undefined => {
|
||||||
|
|
|
@ -105,12 +105,21 @@ export interface RTCState {
|
||||||
setRpcDataChannel: (channel: RTCDataChannel) => void;
|
setRpcDataChannel: (channel: RTCDataChannel) => void;
|
||||||
rpcDataChannel: RTCDataChannel | null;
|
rpcDataChannel: RTCDataChannel | null;
|
||||||
|
|
||||||
|
hidRpcDisabled: boolean;
|
||||||
|
setHidRpcDisabled: (disabled: boolean) => void;
|
||||||
|
|
||||||
rpcHidProtocolVersion: number | null;
|
rpcHidProtocolVersion: number | null;
|
||||||
setRpcHidProtocolVersion: (version: number) => void;
|
setRpcHidProtocolVersion: (version: number | null) => void;
|
||||||
|
|
||||||
rpcHidChannel: RTCDataChannel | null;
|
rpcHidChannel: RTCDataChannel | null;
|
||||||
setRpcHidChannel: (channel: RTCDataChannel) => void;
|
setRpcHidChannel: (channel: RTCDataChannel) => void;
|
||||||
|
|
||||||
|
rpcHidUnreliableChannel: RTCDataChannel | null;
|
||||||
|
setRpcHidUnreliableChannel: (channel: RTCDataChannel) => void;
|
||||||
|
|
||||||
|
rpcHidUnreliableNonOrderedChannel: RTCDataChannel | null;
|
||||||
|
setRpcHidUnreliableNonOrderedChannel: (channel: RTCDataChannel) => void;
|
||||||
|
|
||||||
peerConnectionState: RTCPeerConnectionState | null;
|
peerConnectionState: RTCPeerConnectionState | null;
|
||||||
setPeerConnectionState: (state: RTCPeerConnectionState) => void;
|
setPeerConnectionState: (state: RTCPeerConnectionState) => void;
|
||||||
|
|
||||||
|
@ -157,12 +166,21 @@ export const useRTCStore = create<RTCState>(set => ({
|
||||||
rpcDataChannel: null,
|
rpcDataChannel: null,
|
||||||
setRpcDataChannel: (channel: RTCDataChannel) => set({ rpcDataChannel: channel }),
|
setRpcDataChannel: (channel: RTCDataChannel) => set({ rpcDataChannel: channel }),
|
||||||
|
|
||||||
|
hidRpcDisabled: false,
|
||||||
|
setHidRpcDisabled: (disabled: boolean) => set({ hidRpcDisabled: disabled }),
|
||||||
|
|
||||||
rpcHidProtocolVersion: null,
|
rpcHidProtocolVersion: null,
|
||||||
setRpcHidProtocolVersion: (version: number) => set({ rpcHidProtocolVersion: version }),
|
setRpcHidProtocolVersion: (version: number | null) => set({ rpcHidProtocolVersion: version }),
|
||||||
|
|
||||||
rpcHidChannel: null,
|
rpcHidChannel: null,
|
||||||
setRpcHidChannel: (channel: RTCDataChannel) => set({ rpcHidChannel: channel }),
|
setRpcHidChannel: (channel: RTCDataChannel) => set({ rpcHidChannel: channel }),
|
||||||
|
|
||||||
|
rpcHidUnreliableChannel: null,
|
||||||
|
setRpcHidUnreliableChannel: (channel: RTCDataChannel) => set({ rpcHidUnreliableChannel: channel }),
|
||||||
|
|
||||||
|
rpcHidUnreliableNonOrderedChannel: null,
|
||||||
|
setRpcHidUnreliableNonOrderedChannel: (channel: RTCDataChannel) => set({ rpcHidUnreliableNonOrderedChannel: channel }),
|
||||||
|
|
||||||
transceiver: null,
|
transceiver: null,
|
||||||
setTransceiver: (transceiver: RTCRtpTransceiver) => set({ transceiver }),
|
setTransceiver: (transceiver: RTCRtpTransceiver) => set({ transceiver }),
|
||||||
|
|
||||||
|
@ -464,7 +482,7 @@ export interface HidState {
|
||||||
isVirtualKeyboardEnabled: boolean;
|
isVirtualKeyboardEnabled: boolean;
|
||||||
setVirtualKeyboardEnabled: (enabled: boolean) => void;
|
setVirtualKeyboardEnabled: (enabled: boolean) => void;
|
||||||
|
|
||||||
isPasteModeEnabled: boolean;
|
isPasteInProgress: boolean;
|
||||||
setPasteModeEnabled: (enabled: boolean) => void;
|
setPasteModeEnabled: (enabled: boolean) => void;
|
||||||
|
|
||||||
usbState: USBStates;
|
usbState: USBStates;
|
||||||
|
@ -481,8 +499,8 @@ export const useHidStore = create<HidState>(set => ({
|
||||||
isVirtualKeyboardEnabled: false,
|
isVirtualKeyboardEnabled: false,
|
||||||
setVirtualKeyboardEnabled: (enabled: boolean): void => set({ isVirtualKeyboardEnabled: enabled }),
|
setVirtualKeyboardEnabled: (enabled: boolean): void => set({ isVirtualKeyboardEnabled: enabled }),
|
||||||
|
|
||||||
isPasteModeEnabled: false,
|
isPasteInProgress: false,
|
||||||
setPasteModeEnabled: (enabled: boolean): void => set({ isPasteModeEnabled: enabled }),
|
setPasteModeEnabled: (enabled: boolean): void => set({ isPasteInProgress: enabled }),
|
||||||
|
|
||||||
// Add these new properties for USB state
|
// Add these new properties for USB state
|
||||||
usbState: "not attached",
|
usbState: "not attached",
|
||||||
|
|
|
@ -3,9 +3,13 @@ import { useCallback, useEffect, useMemo } from "react";
|
||||||
import { useRTCStore } from "@/hooks/stores";
|
import { useRTCStore } from "@/hooks/stores";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
CancelKeyboardMacroReportMessage,
|
||||||
HID_RPC_VERSION,
|
HID_RPC_VERSION,
|
||||||
HandshakeMessage,
|
HandshakeMessage,
|
||||||
|
KeyboardMacroStep,
|
||||||
|
KeyboardMacroReportMessage,
|
||||||
KeyboardReportMessage,
|
KeyboardReportMessage,
|
||||||
|
KeypressKeepAliveMessage,
|
||||||
KeypressReportMessage,
|
KeypressReportMessage,
|
||||||
MouseReportMessage,
|
MouseReportMessage,
|
||||||
PointerReportMessage,
|
PointerReportMessage,
|
||||||
|
@ -13,20 +17,60 @@ import {
|
||||||
unmarshalHidRpcMessage,
|
unmarshalHidRpcMessage,
|
||||||
} from "./hidRpc";
|
} from "./hidRpc";
|
||||||
|
|
||||||
|
const KEEPALIVE_MESSAGE = new KeypressKeepAliveMessage();
|
||||||
|
|
||||||
|
interface sendMessageParams {
|
||||||
|
ignoreHandshakeState?: boolean;
|
||||||
|
useUnreliableChannel?: boolean;
|
||||||
|
requireOrdered?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
||||||
const { rpcHidChannel, setRpcHidProtocolVersion, rpcHidProtocolVersion } = useRTCStore();
|
const {
|
||||||
|
rpcHidChannel,
|
||||||
|
rpcHidUnreliableChannel,
|
||||||
|
rpcHidUnreliableNonOrderedChannel,
|
||||||
|
setRpcHidProtocolVersion,
|
||||||
|
rpcHidProtocolVersion, hidRpcDisabled,
|
||||||
|
} = useRTCStore();
|
||||||
|
|
||||||
const rpcHidReady = useMemo(() => {
|
const rpcHidReady = useMemo(() => {
|
||||||
|
if (hidRpcDisabled) return false;
|
||||||
return rpcHidChannel?.readyState === "open" && rpcHidProtocolVersion !== null;
|
return rpcHidChannel?.readyState === "open" && rpcHidProtocolVersion !== null;
|
||||||
}, [rpcHidChannel, rpcHidProtocolVersion]);
|
}, [rpcHidChannel, rpcHidProtocolVersion, hidRpcDisabled]);
|
||||||
|
|
||||||
|
const rpcHidUnreliableReady = useMemo(() => {
|
||||||
|
return (
|
||||||
|
rpcHidUnreliableChannel?.readyState === "open" && rpcHidProtocolVersion !== null
|
||||||
|
);
|
||||||
|
}, [rpcHidProtocolVersion, rpcHidUnreliableChannel?.readyState]);
|
||||||
|
|
||||||
|
const rpcHidUnreliableNonOrderedReady = useMemo(() => {
|
||||||
|
return (
|
||||||
|
rpcHidUnreliableNonOrderedChannel?.readyState === "open" &&
|
||||||
|
rpcHidProtocolVersion !== null
|
||||||
|
);
|
||||||
|
}, [rpcHidProtocolVersion, rpcHidUnreliableNonOrderedChannel?.readyState]);
|
||||||
|
|
||||||
const rpcHidStatus = useMemo(() => {
|
const rpcHidStatus = useMemo(() => {
|
||||||
|
if (hidRpcDisabled) return "disabled";
|
||||||
|
|
||||||
if (!rpcHidChannel) return "N/A";
|
if (!rpcHidChannel) return "N/A";
|
||||||
if (rpcHidChannel.readyState !== "open") return rpcHidChannel.readyState;
|
if (rpcHidChannel.readyState !== "open") return rpcHidChannel.readyState;
|
||||||
if (!rpcHidProtocolVersion) return "handshaking";
|
if (!rpcHidProtocolVersion) return "handshaking";
|
||||||
return `ready (v${rpcHidProtocolVersion})`;
|
return `ready (v${rpcHidProtocolVersion}${rpcHidUnreliableReady ? "+u" : ""})`;
|
||||||
}, [rpcHidChannel, rpcHidProtocolVersion]);
|
}, [rpcHidChannel, rpcHidProtocolVersion, rpcHidUnreliableReady, hidRpcDisabled]);
|
||||||
|
|
||||||
const sendMessage = useCallback((message: RpcMessage, ignoreHandshakeState = false) => {
|
const sendMessage = useCallback(
|
||||||
|
(
|
||||||
|
message: RpcMessage,
|
||||||
|
{
|
||||||
|
ignoreHandshakeState,
|
||||||
|
useUnreliableChannel,
|
||||||
|
requireOrdered = true,
|
||||||
|
}: sendMessageParams = {},
|
||||||
|
) => {
|
||||||
|
if (hidRpcDisabled) return;
|
||||||
if (rpcHidChannel?.readyState !== "open") return;
|
if (rpcHidChannel?.readyState !== "open") return;
|
||||||
if (!rpcHidReady && !ignoreHandshakeState) return;
|
if (!rpcHidReady && !ignoreHandshakeState) return;
|
||||||
|
|
||||||
|
@ -38,13 +82,32 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
||||||
}
|
}
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
|
|
||||||
|
if (useUnreliableChannel) {
|
||||||
|
if (requireOrdered && rpcHidUnreliableReady) {
|
||||||
|
rpcHidUnreliableChannel?.send(data as unknown as ArrayBuffer);
|
||||||
|
} else if (!requireOrdered && rpcHidUnreliableNonOrderedReady) {
|
||||||
|
rpcHidUnreliableNonOrderedChannel?.send(data as unknown as ArrayBuffer);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
rpcHidChannel?.send(data as unknown as ArrayBuffer);
|
rpcHidChannel?.send(data as unknown as ArrayBuffer);
|
||||||
}, [rpcHidChannel, rpcHidReady]);
|
},
|
||||||
|
[
|
||||||
|
rpcHidChannel,
|
||||||
|
rpcHidUnreliableChannel,
|
||||||
|
hidRpcDisabled, rpcHidUnreliableNonOrderedChannel,
|
||||||
|
rpcHidReady,
|
||||||
|
rpcHidUnreliableReady,
|
||||||
|
rpcHidUnreliableNonOrderedReady,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
const reportKeyboardEvent = useCallback(
|
const reportKeyboardEvent = useCallback(
|
||||||
(keys: number[], modifier: number) => {
|
(keys: number[], modifier: number) => {
|
||||||
sendMessage(new KeyboardReportMessage(keys, modifier));
|
sendMessage(new KeyboardReportMessage(keys, modifier));
|
||||||
}, [sendMessage],
|
},
|
||||||
|
[sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const reportKeypressEvent = useCallback(
|
const reportKeypressEvent = useCallback(
|
||||||
|
@ -56,7 +119,9 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
||||||
|
|
||||||
const reportAbsMouseEvent = useCallback(
|
const reportAbsMouseEvent = useCallback(
|
||||||
(x: number, y: number, buttons: number) => {
|
(x: number, y: number, buttons: number) => {
|
||||||
sendMessage(new PointerReportMessage(x, y, buttons));
|
sendMessage(new PointerReportMessage(x, y, buttons), {
|
||||||
|
useUnreliableChannel: true,
|
||||||
|
});
|
||||||
},
|
},
|
||||||
[sendMessage],
|
[sendMessage],
|
||||||
);
|
);
|
||||||
|
@ -68,14 +133,36 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
||||||
[sendMessage],
|
[sendMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const reportKeyboardMacroEvent = useCallback(
|
||||||
|
(steps: KeyboardMacroStep[]) => {
|
||||||
|
sendMessage(new KeyboardMacroReportMessage(false, steps.length, steps));
|
||||||
|
},
|
||||||
|
[sendMessage],
|
||||||
|
);
|
||||||
|
|
||||||
|
const cancelOngoingKeyboardMacro = useCallback(
|
||||||
|
() => {
|
||||||
|
sendMessage(new CancelKeyboardMacroReportMessage());
|
||||||
|
},
|
||||||
|
[sendMessage],
|
||||||
|
);
|
||||||
|
|
||||||
|
const reportKeypressKeepAlive = useCallback(() => {
|
||||||
|
sendMessage(KEEPALIVE_MESSAGE);
|
||||||
|
}, [sendMessage]);
|
||||||
|
|
||||||
const sendHandshake = useCallback(() => {
|
const sendHandshake = useCallback(() => {
|
||||||
|
if (hidRpcDisabled) return;
|
||||||
if (rpcHidProtocolVersion) return;
|
if (rpcHidProtocolVersion) return;
|
||||||
if (!rpcHidChannel) return;
|
if (!rpcHidChannel) return;
|
||||||
|
|
||||||
sendMessage(new HandshakeMessage(HID_RPC_VERSION), true);
|
sendMessage(new HandshakeMessage(HID_RPC_VERSION), { ignoreHandshakeState: true });
|
||||||
}, [rpcHidChannel, rpcHidProtocolVersion, sendMessage]);
|
}, [rpcHidChannel, rpcHidProtocolVersion, sendMessage, hidRpcDisabled]);
|
||||||
|
|
||||||
|
const handleHandshake = useCallback(
|
||||||
|
(message: HandshakeMessage) => {
|
||||||
|
if (hidRpcDisabled) return;
|
||||||
|
|
||||||
const handleHandshake = useCallback((message: HandshakeMessage) => {
|
|
||||||
if (!message.version) {
|
if (!message.version) {
|
||||||
console.error("Received handshake message without version", message);
|
console.error("Received handshake message without version", message);
|
||||||
return;
|
return;
|
||||||
|
@ -90,10 +177,13 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
||||||
}
|
}
|
||||||
|
|
||||||
setRpcHidProtocolVersion(message.version);
|
setRpcHidProtocolVersion(message.version);
|
||||||
}, [setRpcHidProtocolVersion]);
|
},
|
||||||
|
[setRpcHidProtocolVersion, hidRpcDisabled],
|
||||||
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!rpcHidChannel) return;
|
if (!rpcHidChannel) return;
|
||||||
|
if (hidRpcDisabled) return;
|
||||||
|
|
||||||
// send handshake message
|
// send handshake message
|
||||||
sendHandshake();
|
sendHandshake();
|
||||||
|
@ -123,26 +213,42 @@ export function useHidRpc(onHidRpcMessage?: (payload: RpcMessage) => void) {
|
||||||
onHidRpcMessage?.(message);
|
onHidRpcMessage?.(message);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const openHandler = () => {
|
||||||
|
console.info("HID RPC channel opened");
|
||||||
|
sendHandshake();
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeHandler = () => {
|
||||||
|
console.info("HID RPC channel closed");
|
||||||
|
setRpcHidProtocolVersion(null);
|
||||||
|
};
|
||||||
|
|
||||||
rpcHidChannel.addEventListener("message", messageHandler);
|
rpcHidChannel.addEventListener("message", messageHandler);
|
||||||
|
rpcHidChannel.addEventListener("close", closeHandler);
|
||||||
|
rpcHidChannel.addEventListener("open", openHandler);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
rpcHidChannel.removeEventListener("message", messageHandler);
|
rpcHidChannel.removeEventListener("message", messageHandler);
|
||||||
|
rpcHidChannel.removeEventListener("close", closeHandler);
|
||||||
|
rpcHidChannel.removeEventListener("open", openHandler);
|
||||||
};
|
};
|
||||||
},
|
}, [
|
||||||
[
|
|
||||||
rpcHidChannel,
|
rpcHidChannel,
|
||||||
onHidRpcMessage,
|
onHidRpcMessage,
|
||||||
setRpcHidProtocolVersion,
|
setRpcHidProtocolVersion,
|
||||||
sendHandshake,
|
sendHandshake,
|
||||||
handleHandshake,
|
handleHandshake,
|
||||||
],
|
hidRpcDisabled,
|
||||||
);
|
]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
reportKeyboardEvent,
|
reportKeyboardEvent,
|
||||||
reportKeypressEvent,
|
reportKeypressEvent,
|
||||||
reportAbsMouseEvent,
|
reportAbsMouseEvent,
|
||||||
reportRelMouseEvent,
|
reportRelMouseEvent,
|
||||||
|
reportKeyboardMacroEvent,
|
||||||
|
cancelOngoingKeyboardMacro,
|
||||||
|
reportKeypressKeepAlive,
|
||||||
rpcHidProtocolVersion,
|
rpcHidProtocolVersion,
|
||||||
rpcHidReady,
|
rpcHidReady,
|
||||||
rpcHidStatus,
|
rpcHidStatus,
|
||||||
|
|
|
@ -29,6 +29,8 @@ export interface JsonRpcErrorResponse {
|
||||||
|
|
||||||
export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
|
export type JsonRpcResponse = JsonRpcSuccessResponse | JsonRpcErrorResponse;
|
||||||
|
|
||||||
|
export const RpcMethodNotFound = -32601;
|
||||||
|
|
||||||
const callbackStore = new Map<number | string, (resp: JsonRpcResponse) => void>();
|
const callbackStore = new Map<number | string, (resp: JsonRpcResponse) => void>();
|
||||||
let requestCounter = 0;
|
let requestCounter = 0;
|
||||||
|
|
||||||
|
|
|
@ -1,15 +1,51 @@
|
||||||
import { useCallback } from "react";
|
import { useCallback, useRef } from "react";
|
||||||
|
|
||||||
import { hidErrorRollOver, hidKeyBufferSize, KeysDownState, useHidStore, useRTCStore } from "@/hooks/stores";
|
import {
|
||||||
import { JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
KeyboardLedStateMessage,
|
||||||
|
KeyboardMacroStateMessage,
|
||||||
|
KeyboardMacroStep,
|
||||||
|
KeysDownStateMessage,
|
||||||
|
} from "@/hooks/hidRpc";
|
||||||
|
import {
|
||||||
|
hidErrorRollOver,
|
||||||
|
hidKeyBufferSize,
|
||||||
|
KeysDownState,
|
||||||
|
useHidStore,
|
||||||
|
useRTCStore,
|
||||||
|
} from "@/hooks/stores";
|
||||||
import { useHidRpc } from "@/hooks/useHidRpc";
|
import { useHidRpc } from "@/hooks/useHidRpc";
|
||||||
import { KeyboardLedStateMessage, KeysDownStateMessage } from "@/hooks/hidRpc";
|
import { JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
||||||
import { hidKeyToModifierMask, keys, modifiers } from "@/keyboardMappings";
|
import { hidKeyToModifierMask, keys, modifiers } from "@/keyboardMappings";
|
||||||
|
|
||||||
|
const MACRO_RESET_KEYBOARD_STATE = {
|
||||||
|
keys: new Array(hidKeyBufferSize).fill(0),
|
||||||
|
modifier: 0,
|
||||||
|
delay: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface MacroStep {
|
||||||
|
keys: string[] | null;
|
||||||
|
modifiers: string[] | null;
|
||||||
|
delay: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MacroSteps = MacroStep[];
|
||||||
|
|
||||||
|
const sleep = (ms: number): Promise<void> => new Promise(resolve => setTimeout(resolve, ms));
|
||||||
|
|
||||||
export default function useKeyboard() {
|
export default function useKeyboard() {
|
||||||
const { send } = useJsonRpc();
|
const { send } = useJsonRpc();
|
||||||
const { rpcDataChannel } = useRTCStore();
|
const { rpcDataChannel } = useRTCStore();
|
||||||
const { keysDownState, setKeysDownState, setKeyboardLedState } = useHidStore();
|
const { keysDownState, setKeysDownState, setKeyboardLedState, setPasteModeEnabled } =
|
||||||
|
useHidStore();
|
||||||
|
|
||||||
|
const abortController = useRef<AbortController | null>(null);
|
||||||
|
const setAbortController = useCallback((ac: AbortController | null) => {
|
||||||
|
abortController.current = ac;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Keepalive timer management
|
||||||
|
const keepAliveTimerRef = useRef<number | null>(null);
|
||||||
|
|
||||||
// INTRODUCTION: The earlier version of the JetKVM device shipped with all keyboard state
|
// INTRODUCTION: The earlier version of the JetKVM device shipped with all keyboard state
|
||||||
// being tracked on the browser/client-side. When adding the keyPressReport API to the
|
// being tracked on the browser/client-side. When adding the keyPressReport API to the
|
||||||
|
@ -18,16 +54,18 @@ export default function useKeyboard() {
|
||||||
// support the keyPressReport API. In that case, we need to handle the key presses locally
|
// support the keyPressReport API. In that case, we need to handle the key presses locally
|
||||||
// and send the full state to the device, so it can behave like a real USB HID keyboard.
|
// and send the full state to the device, so it can behave like a real USB HID keyboard.
|
||||||
// This flag indicates whether the keyPressReport API is available on the device which is
|
// This flag indicates whether the keyPressReport API is available on the device which is
|
||||||
// dynamically set when the device responds to the first key press event or reports its
|
// dynamically set when the device responds to the first key press event or reports its // keysDownState when queried since the keyPressReport was introduced together with the
|
||||||
// keysDownState when queried since the keyPressReport was introduced together with the
|
|
||||||
// getKeysDownState API.
|
// getKeysDownState API.
|
||||||
|
|
||||||
// HidRPC is a binary format for exchanging keyboard and mouse events
|
// HidRPC is a binary format for exchanging keyboard and mouse events
|
||||||
const {
|
const {
|
||||||
reportKeyboardEvent: sendKeyboardEventHidRpc,
|
reportKeyboardEvent: sendKeyboardEventHidRpc,
|
||||||
reportKeypressEvent: sendKeypressEventHidRpc,
|
reportKeypressEvent: sendKeypressEventHidRpc,
|
||||||
|
reportKeyboardMacroEvent: sendKeyboardMacroEventHidRpc,
|
||||||
|
cancelOngoingKeyboardMacro: cancelOngoingKeyboardMacroHidRpc,
|
||||||
|
reportKeypressKeepAlive: sendKeypressKeepAliveHidRpc,
|
||||||
rpcHidReady,
|
rpcHidReady,
|
||||||
} = useHidRpc((message) => {
|
} = useHidRpc(message => {
|
||||||
switch (message.constructor) {
|
switch (message.constructor) {
|
||||||
case KeysDownStateMessage:
|
case KeysDownStateMessage:
|
||||||
setKeysDownState((message as KeysDownStateMessage).keysDownState);
|
setKeysDownState((message as KeysDownStateMessage).keysDownState);
|
||||||
|
@ -35,88 +73,101 @@ export default function useKeyboard() {
|
||||||
case KeyboardLedStateMessage:
|
case KeyboardLedStateMessage:
|
||||||
setKeyboardLedState((message as KeyboardLedStateMessage).keyboardLedState);
|
setKeyboardLedState((message as KeyboardLedStateMessage).keyboardLedState);
|
||||||
break;
|
break;
|
||||||
|
case KeyboardMacroStateMessage:
|
||||||
|
if (!(message as KeyboardMacroStateMessage).isPaste) break;
|
||||||
|
setPasteModeEnabled((message as KeyboardMacroStateMessage).state);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// sendKeyboardEvent is used to send the full keyboard state to the device for macro handling
|
const handleLegacyKeyboardReport = useCallback(
|
||||||
// and resetting keyboard state. It sends the keys currently pressed and the modifier state.
|
async (keys: number[], modifier: number) => {
|
||||||
// The device will respond with the keysDownState if it supports the keyPressReport API
|
send("keyboardReport", { keys, modifier }, (resp: JsonRpcResponse) => {
|
||||||
// or just accept the state if it does not support (returning no result)
|
|
||||||
const sendKeyboardEvent = useCallback(
|
|
||||||
async (state: KeysDownState) => {
|
|
||||||
if (rpcDataChannel?.readyState !== "open" && !rpcHidReady) return;
|
|
||||||
|
|
||||||
console.debug(`Send keyboardReport keys: ${state.keys}, modifier: ${state.modifier}`);
|
|
||||||
|
|
||||||
if (rpcHidReady) {
|
|
||||||
console.debug("Sending keyboard report via HidRPC");
|
|
||||||
sendKeyboardEventHidRpc(state.keys, state.modifier);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
send("keyboardReport", { keys: state.keys, modifier: state.modifier }, (resp: JsonRpcResponse) => {
|
|
||||||
if ("error" in resp) {
|
if ("error" in resp) {
|
||||||
console.error(`Failed to send keyboard report ${state}`, resp.error);
|
console.error(`Failed to send keyboard report ${keys} ${modifier}`, resp.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// On older backends, we need to set the keysDownState manually since without the hidRpc API, the state doesn't trickle down from the backend
|
||||||
|
setKeysDownState({ modifier, keys });
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
[
|
[send, setKeysDownState],
|
||||||
rpcDataChannel?.readyState,
|
|
||||||
rpcHidReady,
|
|
||||||
send,
|
|
||||||
sendKeyboardEventHidRpc,
|
|
||||||
],
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// resetKeyboardState is used to reset the keyboard state to no keys pressed and no modifiers.
|
const sendKeystrokeLegacy = useCallback(async (keys: number[], modifier: number, ac?: AbortController) => {
|
||||||
// This is useful for macros and when the browser loses focus to ensure that the keyboard state
|
return await new Promise<void>((resolve, reject) => {
|
||||||
// is clean.
|
const abortListener = () => {
|
||||||
const resetKeyboardState = useCallback(
|
reject(new Error("Keyboard report aborted"));
|
||||||
async () => {
|
|
||||||
// Reset the keys buffer to zeros and the modifier state to zero
|
|
||||||
keysDownState.keys.length = hidKeyBufferSize;
|
|
||||||
keysDownState.keys.fill(0);
|
|
||||||
keysDownState.modifier = 0;
|
|
||||||
sendKeyboardEvent(keysDownState);
|
|
||||||
}, [keysDownState, sendKeyboardEvent]);
|
|
||||||
|
|
||||||
// executeMacro is used to execute a macro consisting of multiple steps.
|
|
||||||
// Each step can have multiple keys, multiple modifiers and a delay.
|
|
||||||
// The keys and modifiers are pressed together and held for the delay duration.
|
|
||||||
// After the delay, the keys and modifiers are released and the next step is executed.
|
|
||||||
// If a step has no keys or modifiers, it is treated as a delay-only step.
|
|
||||||
// A small pause is added between steps to ensure that the device can process the events.
|
|
||||||
const executeMacro = async (steps: { keys: string[] | null; modifiers: string[] | null; delay: number }[]) => {
|
|
||||||
for (const [index, step] of steps.entries()) {
|
|
||||||
const keyValues = (step.keys || []).map(key => keys[key]).filter(Boolean);
|
|
||||||
const modifierMask: number = (step.modifiers || []).map(mod => modifiers[mod]).reduce((acc, val) => acc + val, 0);
|
|
||||||
|
|
||||||
// If the step has keys and/or modifiers, press them and hold for the delay
|
|
||||||
if (keyValues.length > 0 || modifierMask > 0) {
|
|
||||||
sendKeyboardEvent({ keys: keyValues, modifier: modifierMask });
|
|
||||||
await new Promise(resolve => setTimeout(resolve, step.delay || 50));
|
|
||||||
|
|
||||||
resetKeyboardState();
|
|
||||||
} else {
|
|
||||||
// This is a delay-only step, just wait for the delay amount
|
|
||||||
await new Promise(resolve => setTimeout(resolve, step.delay || 50));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add a small pause between steps if not the last step
|
|
||||||
if (index < steps.length - 1) {
|
|
||||||
await new Promise(resolve => setTimeout(resolve, 10));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
ac?.signal?.addEventListener("abort", abortListener);
|
||||||
|
|
||||||
|
send(
|
||||||
|
"keyboardReport",
|
||||||
|
{ keys, modifier },
|
||||||
|
params => {
|
||||||
|
if ("error" in params) return reject(params.error);
|
||||||
|
resolve();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}, [send]);
|
||||||
|
|
||||||
|
const KEEPALIVE_INTERVAL = 50;
|
||||||
|
|
||||||
|
const cancelKeepAlive = useCallback(() => {
|
||||||
|
if (keepAliveTimerRef.current) {
|
||||||
|
clearInterval(keepAliveTimerRef.current);
|
||||||
|
keepAliveTimerRef.current = null;
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const scheduleKeepAlive = useCallback(() => {
|
||||||
|
// Clears existing keepalive timer
|
||||||
|
cancelKeepAlive();
|
||||||
|
|
||||||
|
keepAliveTimerRef.current = setInterval(() => {
|
||||||
|
sendKeypressKeepAliveHidRpc();
|
||||||
|
}, KEEPALIVE_INTERVAL);
|
||||||
|
}, [cancelKeepAlive, sendKeypressKeepAliveHidRpc]);
|
||||||
|
|
||||||
|
// resetKeyboardState is used to reset the keyboard state to no keys pressed and no modifiers.
|
||||||
|
// This is useful for macros, in case of client-side rollover, and when the browser loses focus
|
||||||
|
const resetKeyboardState = useCallback(async () => {
|
||||||
|
// Cancel keepalive since we're resetting the keyboard state
|
||||||
|
cancelKeepAlive();
|
||||||
|
// Reset the keys buffer to zeros and the modifier state to zero
|
||||||
|
const { keys, modifier } = MACRO_RESET_KEYBOARD_STATE;
|
||||||
|
if (rpcHidReady) {
|
||||||
|
sendKeyboardEventHidRpc(keys, modifier);
|
||||||
|
} else {
|
||||||
|
// Older backends don't support the hidRpc API, so we send the full reset state
|
||||||
|
handleLegacyKeyboardReport(keys, modifier);
|
||||||
|
}
|
||||||
|
}, [rpcHidReady, sendKeyboardEventHidRpc, handleLegacyKeyboardReport, cancelKeepAlive]);
|
||||||
|
|
||||||
// handleKeyPress is used to handle a key press or release event.
|
// handleKeyPress is used to handle a key press or release event.
|
||||||
// This function handle both key press and key release events.
|
// This function handle both key press and key release events.
|
||||||
// It checks if the keyPressReport API is available and sends the key press event.
|
// It checks if the keyPressReport API is available and sends the key press event.
|
||||||
// If the keyPressReport API is not available, it simulates the device-side key
|
// If the keyPressReport API is not available, it simulates the device-side key
|
||||||
// handling for legacy devices and updates the keysDownState accordingly.
|
// handling for legacy devices and updates the keysDownState accordingly.
|
||||||
// It then sends the full keyboard state to the device.
|
// It then sends the full keyboard state to the device.
|
||||||
|
|
||||||
|
const sendKeypress = useCallback(
|
||||||
|
(key: number, press: boolean) => {
|
||||||
|
cancelKeepAlive();
|
||||||
|
|
||||||
|
sendKeypressEventHidRpc(key, press);
|
||||||
|
|
||||||
|
if (press) {
|
||||||
|
scheduleKeepAlive();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[sendKeypressEventHidRpc, scheduleKeepAlive, cancelKeepAlive],
|
||||||
|
);
|
||||||
|
|
||||||
const handleKeyPress = useCallback(
|
const handleKeyPress = useCallback(
|
||||||
async (key: number, press: boolean) => {
|
async (key: number, press: boolean) => {
|
||||||
if (rpcDataChannel?.readyState !== "open" && !rpcHidReady) return;
|
if (rpcDataChannel?.readyState !== "open" && !rpcHidReady) return;
|
||||||
|
@ -129,11 +180,18 @@ export default function useKeyboard() {
|
||||||
// Older device version doesn't support this API, so we will switch to local key handling
|
// Older device version doesn't support this API, so we will switch to local key handling
|
||||||
// In that case we will switch to local key handling and update the keysDownState
|
// In that case we will switch to local key handling and update the keysDownState
|
||||||
// in client/browser-side code using simulateDeviceSideKeyHandlingForLegacyDevices.
|
// in client/browser-side code using simulateDeviceSideKeyHandlingForLegacyDevices.
|
||||||
sendKeypressEventHidRpc(key, press);
|
sendKeypress(key, press);
|
||||||
} else {
|
} else {
|
||||||
// if the keyPress api is not available, we need to handle the key locally
|
// Older backends don't support the hidRpc API, so we need:
|
||||||
const downState = simulateDeviceSideKeyHandlingForLegacyDevices(keysDownState, key, press);
|
// 1. Calculate the state
|
||||||
sendKeyboardEvent(downState); // then we send the full state
|
// 2. Send the newly calculated state to the device
|
||||||
|
const downState = simulateDeviceSideKeyHandlingForLegacyDevices(
|
||||||
|
keysDownState,
|
||||||
|
key,
|
||||||
|
press,
|
||||||
|
);
|
||||||
|
|
||||||
|
handleLegacyKeyboardReport(downState.keys, downState.modifier);
|
||||||
|
|
||||||
// if we just sent ErrorRollOver, reset to empty state
|
// if we just sent ErrorRollOver, reset to empty state
|
||||||
if (downState.keys[0] === hidErrorRollOver) {
|
if (downState.keys[0] === hidErrorRollOver) {
|
||||||
|
@ -142,17 +200,21 @@ export default function useKeyboard() {
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[
|
[
|
||||||
|
rpcDataChannel?.readyState,
|
||||||
rpcHidReady,
|
rpcHidReady,
|
||||||
keysDownState,
|
keysDownState,
|
||||||
|
handleLegacyKeyboardReport,
|
||||||
resetKeyboardState,
|
resetKeyboardState,
|
||||||
rpcDataChannel?.readyState,
|
sendKeypress,
|
||||||
sendKeyboardEvent,
|
|
||||||
sendKeypressEventHidRpc,
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
// IMPORTANT: See the keyPressReportApiAvailable comment above for the reason this exists
|
// IMPORTANT: See the keyPressReportApiAvailable comment above for the reason this exists
|
||||||
function simulateDeviceSideKeyHandlingForLegacyDevices(state: KeysDownState, key: number, press: boolean): KeysDownState {
|
function simulateDeviceSideKeyHandlingForLegacyDevices(
|
||||||
|
state: KeysDownState,
|
||||||
|
key: number,
|
||||||
|
press: boolean,
|
||||||
|
): KeysDownState {
|
||||||
// IMPORTANT: This code parallels the logic in the kernel's hid-gadget driver
|
// IMPORTANT: This code parallels the logic in the kernel's hid-gadget driver
|
||||||
// for handling key presses and releases. It ensures that the USB gadget
|
// for handling key presses and releases. It ensures that the USB gadget
|
||||||
// behaves similarly to a real USB HID keyboard. This logic is paralleled
|
// behaves similarly to a real USB HID keyboard. This logic is paralleled
|
||||||
|
@ -181,7 +243,7 @@ export default function useKeyboard() {
|
||||||
// and if we find a zero byte, we can place the key there (if press is true)
|
// and if we find a zero byte, we can place the key there (if press is true)
|
||||||
if (keys[i] === key || keys[i] === 0) {
|
if (keys[i] === key || keys[i] === 0) {
|
||||||
if (press) {
|
if (press) {
|
||||||
keys[i] = key // overwrites the zero byte or the same key if already pressed
|
keys[i] = key; // overwrites the zero byte or the same key if already pressed
|
||||||
} else {
|
} else {
|
||||||
// we are releasing the key, remove it from the buffer
|
// we are releasing the key, remove it from the buffer
|
||||||
if (keys[i] !== 0) {
|
if (keys[i] !== 0) {
|
||||||
|
@ -203,12 +265,113 @@ export default function useKeyboard() {
|
||||||
keys.fill(hidErrorRollOver);
|
keys.fill(hidErrorRollOver);
|
||||||
} else {
|
} else {
|
||||||
// If we are releasing a key, and we didn't find it in a slot, who cares?
|
// If we are releasing a key, and we didn't find it in a slot, who cares?
|
||||||
console.debug(`key ${key} not found in buffer, nothing to release`)
|
console.debug(`key ${key} not found in buffer, nothing to release`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return { modifier: modifiers, keys };
|
return { modifier: modifiers, keys };
|
||||||
}
|
}
|
||||||
|
|
||||||
return { handleKeyPress, resetKeyboardState, executeMacro };
|
// Cleanup function to cancel keepalive timer
|
||||||
|
const cleanup = useCallback(() => {
|
||||||
|
cancelKeepAlive();
|
||||||
|
}, [cancelKeepAlive]);
|
||||||
|
|
||||||
|
|
||||||
|
// executeMacro is used to execute a macro consisting of multiple steps.
|
||||||
|
// Each step can have multiple keys, multiple modifiers and a delay.
|
||||||
|
// The keys and modifiers are pressed together and held for the delay duration.
|
||||||
|
// After the delay, the keys and modifiers are released and the next step is executed.
|
||||||
|
// If a step has no keys or modifiers, it is treated as a delay-only step.
|
||||||
|
// A small pause is added between steps to ensure that the device can process the events.
|
||||||
|
const executeMacroRemote = useCallback(async (
|
||||||
|
steps: MacroSteps,
|
||||||
|
) => {
|
||||||
|
const macro: KeyboardMacroStep[] = [];
|
||||||
|
|
||||||
|
for (const [_, step] of steps.entries()) {
|
||||||
|
const keyValues = (step.keys || []).map(key => keys[key]).filter(Boolean);
|
||||||
|
const modifierMask: number = (step.modifiers || [])
|
||||||
|
|
||||||
|
.map(mod => modifiers[mod])
|
||||||
|
|
||||||
|
.reduce((acc, val) => acc + val, 0);
|
||||||
|
|
||||||
|
// If the step has keys and/or modifiers, press them and hold for the delay
|
||||||
|
if (keyValues.length > 0 || modifierMask > 0) {
|
||||||
|
macro.push({ keys: keyValues, modifier: modifierMask, delay: 20 });
|
||||||
|
macro.push({ ...MACRO_RESET_KEYBOARD_STATE, delay: step.delay || 100 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendKeyboardMacroEventHidRpc(macro);
|
||||||
|
}, [sendKeyboardMacroEventHidRpc]);
|
||||||
|
const executeMacroClientSide = useCallback(async (steps: MacroSteps) => {
|
||||||
|
const promises: (() => Promise<void>)[] = [];
|
||||||
|
|
||||||
|
const ac = new AbortController();
|
||||||
|
setAbortController(ac);
|
||||||
|
|
||||||
|
for (const [_, step] of steps.entries()) {
|
||||||
|
const keyValues = (step.keys || []).map(key => keys[key]).filter(Boolean);
|
||||||
|
const modifierMask: number = (step.modifiers || [])
|
||||||
|
.map(mod => modifiers[mod])
|
||||||
|
.reduce((acc, val) => acc + val, 0);
|
||||||
|
|
||||||
|
// If the step has keys and/or modifiers, press them and hold for the delay
|
||||||
|
if (keyValues.length > 0 || modifierMask > 0) {
|
||||||
|
promises.push(() => sendKeystrokeLegacy(keyValues, modifierMask, ac));
|
||||||
|
promises.push(() => resetKeyboardState());
|
||||||
|
promises.push(() => sleep(step.delay || 100));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const runAll = async () => {
|
||||||
|
for (const promise of promises) {
|
||||||
|
// Check if we've been aborted before executing each promise
|
||||||
|
if (ac.signal.aborted) {
|
||||||
|
throw new Error("Macro execution aborted");
|
||||||
|
}
|
||||||
|
await promise();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return await new Promise<void>((resolve, reject) => {
|
||||||
|
// Set up abort listener
|
||||||
|
const abortListener = () => {
|
||||||
|
reject(new Error("Macro execution aborted"));
|
||||||
|
};
|
||||||
|
|
||||||
|
ac.signal.addEventListener("abort", abortListener);
|
||||||
|
|
||||||
|
runAll()
|
||||||
|
.then(() => {
|
||||||
|
ac.signal.removeEventListener("abort", abortListener);
|
||||||
|
resolve();
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
ac.signal.removeEventListener("abort", abortListener);
|
||||||
|
reject(error);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [sendKeystrokeLegacy, resetKeyboardState, setAbortController]);
|
||||||
|
const executeMacro = useCallback(async (steps: MacroSteps) => {
|
||||||
|
if (rpcHidReady) {
|
||||||
|
return executeMacroRemote(steps);
|
||||||
|
}
|
||||||
|
return executeMacroClientSide(steps);
|
||||||
|
}, [rpcHidReady, executeMacroRemote, executeMacroClientSide]);
|
||||||
|
|
||||||
|
const cancelExecuteMacro = useCallback(async () => {
|
||||||
|
if (abortController.current) {
|
||||||
|
abortController.current.abort();
|
||||||
|
}
|
||||||
|
if (!rpcHidReady) return;
|
||||||
|
// older versions don't support this API,
|
||||||
|
// and all paste actions are pure-frontend,
|
||||||
|
// we don't need to cancel it actually
|
||||||
|
cancelOngoingKeyboardMacroHidRpc();
|
||||||
|
}, [rpcHidReady, cancelOngoingKeyboardMacroHidRpc, abortController]);
|
||||||
|
|
||||||
|
return { handleKeyPress, resetKeyboardState, executeMacro, cleanup, cancelExecuteMacro };
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,79 @@
|
||||||
|
import { useCallback } from "react";
|
||||||
|
|
||||||
|
import { useDeviceStore } from "@/hooks/stores";
|
||||||
|
import { type JsonRpcResponse, RpcMethodNotFound, useJsonRpc } from "@/hooks/useJsonRpc";
|
||||||
|
import notifications from "@/notifications";
|
||||||
|
|
||||||
|
export interface VersionInfo {
|
||||||
|
appVersion: string;
|
||||||
|
systemVersion: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SystemVersionInfo {
|
||||||
|
local: VersionInfo;
|
||||||
|
remote?: VersionInfo;
|
||||||
|
systemUpdateAvailable: boolean;
|
||||||
|
appUpdateAvailable: boolean;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useVersion() {
|
||||||
|
const {
|
||||||
|
appVersion,
|
||||||
|
systemVersion,
|
||||||
|
setAppVersion,
|
||||||
|
setSystemVersion,
|
||||||
|
} = useDeviceStore();
|
||||||
|
const { send } = useJsonRpc();
|
||||||
|
const getVersionInfo = useCallback(() => {
|
||||||
|
return new Promise<SystemVersionInfo>((resolve, reject) => {
|
||||||
|
send("getUpdateStatus", {}, (resp: JsonRpcResponse) => {
|
||||||
|
if ("error" in resp) {
|
||||||
|
notifications.error(`Failed to check for updates: ${resp.error}`);
|
||||||
|
reject(new Error("Failed to check for updates"));
|
||||||
|
} else {
|
||||||
|
const result = resp.result as SystemVersionInfo;
|
||||||
|
setAppVersion(result.local.appVersion);
|
||||||
|
setSystemVersion(result.local.systemVersion);
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
notifications.error(`Failed to check for updates: ${result.error}`);
|
||||||
|
reject(new Error("Failed to check for updates"));
|
||||||
|
} else {
|
||||||
|
resolve(result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [send, setAppVersion, setSystemVersion]);
|
||||||
|
|
||||||
|
const getLocalVersion = useCallback(() => {
|
||||||
|
return new Promise<VersionInfo>((resolve, reject) => {
|
||||||
|
send("getLocalVersion", {}, (resp: JsonRpcResponse) => {
|
||||||
|
if ("error" in resp) {
|
||||||
|
console.log(resp.error)
|
||||||
|
if (resp.error.code === RpcMethodNotFound) {
|
||||||
|
console.warn("Failed to get device version, using legacy version");
|
||||||
|
return getVersionInfo().then(result => resolve(result.local)).catch(reject);
|
||||||
|
}
|
||||||
|
console.error("Failed to get device version N", resp.error);
|
||||||
|
notifications.error(`Failed to get device version: ${resp.error}`);
|
||||||
|
reject(new Error("Failed to get device version"));
|
||||||
|
} else {
|
||||||
|
const result = resp.result as VersionInfo;
|
||||||
|
|
||||||
|
setAppVersion(result.appVersion);
|
||||||
|
setSystemVersion(result.systemVersion);
|
||||||
|
resolve(result);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}, [send, setAppVersion, setSystemVersion, getVersionInfo]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
getVersionInfo,
|
||||||
|
getLocalVersion,
|
||||||
|
appVersion,
|
||||||
|
systemVersion,
|
||||||
|
};
|
||||||
|
}
|
|
@ -239,7 +239,7 @@ video::-webkit-media-controls {
|
||||||
}
|
}
|
||||||
|
|
||||||
.simple-keyboard-arrows .hg-button {
|
.simple-keyboard-arrows .hg-button {
|
||||||
@apply flex w-[50px] grow-0 items-center justify-center;
|
@apply flex w-[50px] items-center justify-center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.controlArrows {
|
.controlArrows {
|
||||||
|
@ -264,7 +264,7 @@ video::-webkit-media-controls {
|
||||||
}
|
}
|
||||||
|
|
||||||
.simple-keyboard-control .hg-button {
|
.simple-keyboard-control .hg-button {
|
||||||
@apply flex w-[50px] grow-0 items-center justify-center;
|
@apply flex w-[50px] items-center justify-center;
|
||||||
}
|
}
|
||||||
|
|
||||||
.numPad {
|
.numPad {
|
||||||
|
|
|
@ -3,12 +3,12 @@ import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
import { CheckCircleIcon } from "@heroicons/react/20/solid";
|
import { CheckCircleIcon } from "@heroicons/react/20/solid";
|
||||||
|
|
||||||
import Card from "@/components/Card";
|
import Card from "@/components/Card";
|
||||||
import { JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
import { useJsonRpc } from "@/hooks/useJsonRpc";
|
||||||
import { Button } from "@components/Button";
|
import { Button } from "@components/Button";
|
||||||
import { UpdateState, useDeviceStore, useUpdateStore } from "@/hooks/stores";
|
import { UpdateState, useUpdateStore } from "@/hooks/stores";
|
||||||
import notifications from "@/notifications";
|
|
||||||
import LoadingSpinner from "@/components/LoadingSpinner";
|
import LoadingSpinner from "@/components/LoadingSpinner";
|
||||||
import { useDeviceUiNavigation } from "@/hooks/useAppNavigation";
|
import { useDeviceUiNavigation } from "@/hooks/useAppNavigation";
|
||||||
|
import { SystemVersionInfo, useVersion } from "@/hooks/useVersion";
|
||||||
|
|
||||||
export default function SettingsGeneralUpdateRoute() {
|
export default function SettingsGeneralUpdateRoute() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
@ -41,13 +41,7 @@ export default function SettingsGeneralUpdateRoute() {
|
||||||
return <Dialog onClose={() => navigate("..")} onConfirmUpdate={onConfirmUpdate} />;
|
return <Dialog onClose={() => navigate("..")} onConfirmUpdate={onConfirmUpdate} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SystemVersionInfo {
|
|
||||||
local: { appVersion: string; systemVersion: string };
|
|
||||||
remote?: { appVersion: string; systemVersion: string };
|
|
||||||
systemUpdateAvailable: boolean;
|
|
||||||
appUpdateAvailable: boolean;
|
|
||||||
error?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function Dialog({
|
export function Dialog({
|
||||||
onClose,
|
onClose,
|
||||||
|
@ -134,30 +128,8 @@ function LoadingState({
|
||||||
}) {
|
}) {
|
||||||
const [progressWidth, setProgressWidth] = useState("0%");
|
const [progressWidth, setProgressWidth] = useState("0%");
|
||||||
const abortControllerRef = useRef<AbortController | null>(null);
|
const abortControllerRef = useRef<AbortController | null>(null);
|
||||||
const { setAppVersion, setSystemVersion } = useDeviceStore();
|
|
||||||
const { send } = useJsonRpc();
|
|
||||||
|
|
||||||
const getVersionInfo = useCallback(() => {
|
const { getVersionInfo } = useVersion();
|
||||||
return new Promise<SystemVersionInfo>((resolve, reject) => {
|
|
||||||
send("getUpdateStatus", {}, (resp: JsonRpcResponse) => {
|
|
||||||
if ("error" in resp) {
|
|
||||||
notifications.error(`Failed to check for updates: ${resp.error}`);
|
|
||||||
reject(new Error("Failed to check for updates"));
|
|
||||||
} else {
|
|
||||||
const result = resp.result as SystemVersionInfo;
|
|
||||||
setAppVersion(result.local.appVersion);
|
|
||||||
setSystemVersion(result.local.systemVersion);
|
|
||||||
|
|
||||||
if (result.error) {
|
|
||||||
notifications.error(`Failed to check for updates: ${result.error}`);
|
|
||||||
reject(new Error("Failed to check for updates"));
|
|
||||||
} else {
|
|
||||||
resolve(result);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}, [send, setAppVersion, setSystemVersion]);
|
|
||||||
|
|
||||||
const progressBarRef = useRef<HTMLDivElement>(null);
|
const progressBarRef = useRef<HTMLDivElement>(null);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
|
|
@ -90,6 +90,7 @@ export default function SettingsMouseRoute() {
|
||||||
send("getJigglerState", {}, (resp: JsonRpcResponse) => {
|
send("getJigglerState", {}, (resp: JsonRpcResponse) => {
|
||||||
if ("error" in resp) return;
|
if ("error" in resp) return;
|
||||||
const isEnabled = resp.result as boolean;
|
const isEnabled = resp.result as boolean;
|
||||||
|
console.log("Jiggler is enabled:", isEnabled);
|
||||||
|
|
||||||
// If the jiggler is disabled, set the selected option to "disabled" and nothing else
|
// If the jiggler is disabled, set the selected option to "disabled" and nothing else
|
||||||
if (!isEnabled) return setSelectedJigglerOption("disabled");
|
if (!isEnabled) return setSelectedJigglerOption("disabled");
|
||||||
|
|
|
@ -166,11 +166,11 @@ export default function SettingsNetworkRoute() {
|
||||||
}, [getNetworkState, getNetworkSettings]);
|
}, [getNetworkState, getNetworkSettings]);
|
||||||
|
|
||||||
const handleIpv4ModeChange = (value: IPv4Mode | string) => {
|
const handleIpv4ModeChange = (value: IPv4Mode | string) => {
|
||||||
setNetworkSettings({ ...networkSettings, ipv4_mode: value as IPv4Mode });
|
setNetworkSettingsRemote({ ...networkSettings, ipv4_mode: value as IPv4Mode });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleIpv6ModeChange = (value: IPv6Mode | string) => {
|
const handleIpv6ModeChange = (value: IPv6Mode | string) => {
|
||||||
setNetworkSettings({ ...networkSettings, ipv6_mode: value as IPv6Mode });
|
setNetworkSettingsRemote({ ...networkSettings, ipv6_mode: value as IPv6Mode });
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleLldpModeChange = (value: LLDPMode | string) => {
|
const handleLldpModeChange = (value: LLDPMode | string) => {
|
||||||
|
@ -419,7 +419,7 @@ export default function SettingsNetworkRoute() {
|
||||||
value={networkSettings.ipv6_mode}
|
value={networkSettings.ipv6_mode}
|
||||||
onChange={e => handleIpv6ModeChange(e.target.value)}
|
onChange={e => handleIpv6ModeChange(e.target.value)}
|
||||||
options={filterUnknown([
|
options={filterUnknown([
|
||||||
// { value: "disabled", label: "Disabled" },
|
{ value: "disabled", label: "Disabled" },
|
||||||
{ value: "slaac", label: "SLAAC" },
|
{ value: "slaac", label: "SLAAC" },
|
||||||
// { value: "dhcpv6", label: "DHCPv6" },
|
// { value: "dhcpv6", label: "DHCPv6" },
|
||||||
// { value: "slaac_and_dhcpv6", label: "SLAAC and DHCPv6" },
|
// { value: "slaac_and_dhcpv6", label: "SLAAC and DHCPv6" },
|
||||||
|
|
|
@ -19,14 +19,12 @@ import { CLOUD_API, DEVICE_API } from "@/ui.config";
|
||||||
import api from "@/api";
|
import api from "@/api";
|
||||||
import { checkAuth, isInCloud, isOnDevice } from "@/main";
|
import { checkAuth, isInCloud, isOnDevice } from "@/main";
|
||||||
import { cx } from "@/cva.config";
|
import { cx } from "@/cva.config";
|
||||||
import notifications from "@/notifications";
|
|
||||||
import {
|
import {
|
||||||
KeyboardLedState,
|
KeyboardLedState,
|
||||||
KeysDownState,
|
KeysDownState,
|
||||||
NetworkState,
|
NetworkState,
|
||||||
OtaState,
|
OtaState,
|
||||||
USBStates,
|
USBStates,
|
||||||
useDeviceStore,
|
|
||||||
useHidStore,
|
useHidStore,
|
||||||
useNetworkStateStore,
|
useNetworkStateStore,
|
||||||
User,
|
User,
|
||||||
|
@ -42,7 +40,7 @@ const ConnectionStatsSidebar = lazy(() => import('@/components/sidebar/connectio
|
||||||
const Terminal = lazy(() => import('@components/Terminal'));
|
const Terminal = lazy(() => import('@components/Terminal'));
|
||||||
const UpdateInProgressStatusCard = lazy(() => import("@/components/UpdateInProgressStatusCard"));
|
const UpdateInProgressStatusCard = lazy(() => import("@/components/UpdateInProgressStatusCard"));
|
||||||
import Modal from "@/components/Modal";
|
import Modal from "@/components/Modal";
|
||||||
import { JsonRpcRequest, JsonRpcResponse, useJsonRpc } from "@/hooks/useJsonRpc";
|
import { JsonRpcRequest, JsonRpcResponse, RpcMethodNotFound, useJsonRpc } from "@/hooks/useJsonRpc";
|
||||||
import {
|
import {
|
||||||
ConnectionFailedOverlay,
|
ConnectionFailedOverlay,
|
||||||
LoadingConnectionOverlay,
|
LoadingConnectionOverlay,
|
||||||
|
@ -51,7 +49,7 @@ import {
|
||||||
import { useDeviceUiNavigation } from "@/hooks/useAppNavigation";
|
import { useDeviceUiNavigation } from "@/hooks/useAppNavigation";
|
||||||
import { FeatureFlagProvider } from "@/providers/FeatureFlagProvider";
|
import { FeatureFlagProvider } from "@/providers/FeatureFlagProvider";
|
||||||
import { DeviceStatus } from "@routes/welcome-local";
|
import { DeviceStatus } from "@routes/welcome-local";
|
||||||
import { SystemVersionInfo } from "@routes/devices.$id.settings.general.update";
|
import { useVersion } from "@/hooks/useVersion";
|
||||||
|
|
||||||
interface LocalLoaderResp {
|
interface LocalLoaderResp {
|
||||||
authMode: "password" | "noPassword" | null;
|
authMode: "password" | "noPassword" | null;
|
||||||
|
@ -136,6 +134,8 @@ export default function KvmIdRoute() {
|
||||||
rpcDataChannel,
|
rpcDataChannel,
|
||||||
setTransceiver,
|
setTransceiver,
|
||||||
setRpcHidChannel,
|
setRpcHidChannel,
|
||||||
|
setRpcHidUnreliableNonOrderedChannel,
|
||||||
|
setRpcHidUnreliableChannel,
|
||||||
} = useRTCStore();
|
} = useRTCStore();
|
||||||
|
|
||||||
const location = useLocation();
|
const location = useLocation();
|
||||||
|
@ -488,6 +488,24 @@ export default function KvmIdRoute() {
|
||||||
setRpcHidChannel(rpcHidChannel);
|
setRpcHidChannel(rpcHidChannel);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const rpcHidUnreliableChannel = pc.createDataChannel("hidrpc-unreliable-ordered", {
|
||||||
|
ordered: true,
|
||||||
|
maxRetransmits: 0,
|
||||||
|
});
|
||||||
|
rpcHidUnreliableChannel.binaryType = "arraybuffer";
|
||||||
|
rpcHidUnreliableChannel.onopen = () => {
|
||||||
|
setRpcHidUnreliableChannel(rpcHidUnreliableChannel);
|
||||||
|
};
|
||||||
|
|
||||||
|
const rpcHidUnreliableNonOrderedChannel = pc.createDataChannel("hidrpc-unreliable-nonordered", {
|
||||||
|
ordered: false,
|
||||||
|
maxRetransmits: 0,
|
||||||
|
});
|
||||||
|
rpcHidUnreliableNonOrderedChannel.binaryType = "arraybuffer";
|
||||||
|
rpcHidUnreliableNonOrderedChannel.onopen = () => {
|
||||||
|
setRpcHidUnreliableNonOrderedChannel(rpcHidUnreliableNonOrderedChannel);
|
||||||
|
};
|
||||||
|
|
||||||
setPeerConnection(pc);
|
setPeerConnection(pc);
|
||||||
}, [
|
}, [
|
||||||
cleanupAndStopReconnecting,
|
cleanupAndStopReconnecting,
|
||||||
|
@ -499,6 +517,8 @@ export default function KvmIdRoute() {
|
||||||
setPeerConnectionState,
|
setPeerConnectionState,
|
||||||
setRpcDataChannel,
|
setRpcDataChannel,
|
||||||
setRpcHidChannel,
|
setRpcHidChannel,
|
||||||
|
setRpcHidUnreliableNonOrderedChannel,
|
||||||
|
setRpcHidUnreliableChannel,
|
||||||
setTransceiver,
|
setTransceiver,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
@ -583,6 +603,7 @@ export default function KvmIdRoute() {
|
||||||
keyboardLedState, setKeyboardLedState,
|
keyboardLedState, setKeyboardLedState,
|
||||||
keysDownState, setKeysDownState, setUsbState,
|
keysDownState, setKeysDownState, setUsbState,
|
||||||
} = useHidStore();
|
} = useHidStore();
|
||||||
|
const setHidRpcDisabled = useRTCStore(state => state.setHidRpcDisabled);
|
||||||
|
|
||||||
const [hasUpdated, setHasUpdated] = useState(false);
|
const [hasUpdated, setHasUpdated] = useState(false);
|
||||||
const { navigateTo } = useDeviceUiNavigation();
|
const { navigateTo } = useDeviceUiNavigation();
|
||||||
|
@ -692,9 +713,10 @@ export default function KvmIdRoute() {
|
||||||
send("getKeyDownState", {}, (resp: JsonRpcResponse) => {
|
send("getKeyDownState", {}, (resp: JsonRpcResponse) => {
|
||||||
if ("error" in resp) {
|
if ("error" in resp) {
|
||||||
// -32601 means the method is not supported
|
// -32601 means the method is not supported
|
||||||
if (resp.error.code === -32601) {
|
if (resp.error.code === RpcMethodNotFound) {
|
||||||
// if we don't support key down state, we know key press is also not available
|
// if we don't support key down state, we know key press is also not available
|
||||||
console.warn("Failed to get key down state, switching to old-school", resp.error);
|
console.warn("Failed to get key down state, switching to old-school", resp.error);
|
||||||
|
setHidRpcDisabled(true);
|
||||||
} else {
|
} else {
|
||||||
console.error("Failed to get key down state", resp.error);
|
console.error("Failed to get key down state", resp.error);
|
||||||
}
|
}
|
||||||
|
@ -705,7 +727,7 @@ export default function KvmIdRoute() {
|
||||||
}
|
}
|
||||||
setNeedKeyDownState(false);
|
setNeedKeyDownState(false);
|
||||||
});
|
});
|
||||||
}, [keysDownState, needKeyDownState, rpcDataChannel?.readyState, send, setKeysDownState]);
|
}, [keysDownState, needKeyDownState, rpcDataChannel?.readyState, send, setKeysDownState, setHidRpcDisabled]);
|
||||||
|
|
||||||
// When the update is successful, we need to refresh the client javascript and show a success modal
|
// When the update is successful, we need to refresh the client javascript and show a success modal
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
@ -734,26 +756,13 @@ export default function KvmIdRoute() {
|
||||||
if (location.pathname !== "/other-session") navigateTo("/");
|
if (location.pathname !== "/other-session") navigateTo("/");
|
||||||
}, [navigateTo, location.pathname]);
|
}, [navigateTo, location.pathname]);
|
||||||
|
|
||||||
const { appVersion, setAppVersion, setSystemVersion} = useDeviceStore();
|
const { appVersion, getLocalVersion} = useVersion();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (appVersion) return;
|
if (appVersion) return;
|
||||||
|
|
||||||
send("getUpdateStatus", {}, (resp: JsonRpcResponse) => {
|
getLocalVersion();
|
||||||
if ("error" in resp) {
|
}, [appVersion, getLocalVersion]);
|
||||||
notifications.error(`Failed to get device version: ${resp.error}`);
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = resp.result as SystemVersionInfo;
|
|
||||||
if (result.error) {
|
|
||||||
notifications.error(`Failed to get device version: ${result.error}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
setAppVersion(result.local.appVersion);
|
|
||||||
setSystemVersion(result.local.systemVersion);
|
|
||||||
});
|
|
||||||
}, [appVersion, send, setAppVersion, setSystemVersion]);
|
|
||||||
|
|
||||||
const ConnectionStatusElement = useMemo(() => {
|
const ConnectionStatusElement = useMemo(() => {
|
||||||
const hasConnectionFailed =
|
const hasConnectionFailed =
|
||||||
|
|
|
@ -31,7 +31,23 @@ export default defineConfig(({ mode, command }) => {
|
||||||
esbuild: {
|
esbuild: {
|
||||||
pure: ["console.debug"],
|
pure: ["console.debug"],
|
||||||
},
|
},
|
||||||
build: { outDir: isCloud ? "dist" : "../static" },
|
assetsInclude: ["**/*.woff2"],
|
||||||
|
build: {
|
||||||
|
outDir: isCloud ? "dist" : "../static",
|
||||||
|
rollupOptions: {
|
||||||
|
output: {
|
||||||
|
manualChunks: (id) => {
|
||||||
|
if (id.includes("node_modules")) {
|
||||||
|
return "vendor";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
assetFileNames: "assets/immutable/[name]-[hash][extname]",
|
||||||
|
chunkFileNames: "assets/immutable/[name]-[hash].js",
|
||||||
|
entryFileNames: "assets/immutable/[name]-[hash].js",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
server: {
|
server: {
|
||||||
host: "0.0.0.0",
|
host: "0.0.0.0",
|
||||||
https: useSSL,
|
https: useSSL,
|
||||||
|
|
12
usb.go
12
usb.go
|
@ -33,7 +33,13 @@ func initUsbGadget() {
|
||||||
|
|
||||||
gadget.SetOnKeysDownChange(func(state usbgadget.KeysDownState) {
|
gadget.SetOnKeysDownChange(func(state usbgadget.KeysDownState) {
|
||||||
if currentSession != nil {
|
if currentSession != nil {
|
||||||
currentSession.reportHidRPCKeysDownState(state)
|
currentSession.enqueueKeysDownState(state)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
gadget.SetOnKeepAliveReset(func() {
|
||||||
|
if currentSession != nil {
|
||||||
|
currentSession.resetKeepAliveTime()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -43,11 +49,11 @@ func initUsbGadget() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func rpcKeyboardReport(modifier byte, keys []byte) (usbgadget.KeysDownState, error) {
|
func rpcKeyboardReport(modifier byte, keys []byte) error {
|
||||||
return gadget.KeyboardReport(modifier, keys)
|
return gadget.KeyboardReport(modifier, keys)
|
||||||
}
|
}
|
||||||
|
|
||||||
func rpcKeypressReport(key byte, press bool) (usbgadget.KeysDownState, error) {
|
func rpcKeypressReport(key byte, press bool) error {
|
||||||
return gadget.KeypressReport(key, press)
|
return gadget.KeypressReport(key, press)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
65
web.go
65
web.go
|
@ -11,6 +11,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/pprof"
|
"net/http/pprof"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
@ -24,6 +25,7 @@ import (
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
|
"github.com/vearutop/statigz"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -66,6 +68,10 @@ type SetupRequest struct {
|
||||||
Password string `json:"password,omitempty"`
|
Password string `json:"password,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var cachableFileExtensions = []string{
|
||||||
|
".jpg", ".jpeg", ".png", ".svg", ".gif", ".webp", ".ico", ".woff2",
|
||||||
|
}
|
||||||
|
|
||||||
func setupRouter() *gin.Engine {
|
func setupRouter() *gin.Engine {
|
||||||
gin.SetMode(gin.ReleaseMode)
|
gin.SetMode(gin.ReleaseMode)
|
||||||
gin.DisableConsoleColor()
|
gin.DisableConsoleColor()
|
||||||
|
@ -75,23 +81,47 @@ func setupRouter() *gin.Engine {
|
||||||
return *ginLogger
|
return *ginLogger
|
||||||
}),
|
}),
|
||||||
))
|
))
|
||||||
staticFS, _ := fs.Sub(staticFiles, "static")
|
|
||||||
|
staticFS, err := fs.Sub(staticFiles, "static")
|
||||||
|
if err != nil {
|
||||||
|
logger.Fatal().Err(err).Msg("failed to get rooted static files subdirectory")
|
||||||
|
}
|
||||||
|
staticFileServer := http.StripPrefix("/static", statigz.FileServer(
|
||||||
|
staticFS.(fs.ReadDirFS),
|
||||||
|
))
|
||||||
|
|
||||||
// Add a custom middleware to set cache headers for images
|
// Add a custom middleware to set cache headers for images
|
||||||
// This is crucial for optimizing the initial welcome screen load time
|
// This is crucial for optimizing the initial welcome screen load time
|
||||||
// By enabling caching, we ensure that pre-loaded images are stored in the browser cache
|
// By enabling caching, we ensure that pre-loaded images are stored in the browser cache
|
||||||
// This allows for a smoother enter animation and improved user experience on the welcome screen
|
// This allows for a smoother enter animation and improved user experience on the welcome screen
|
||||||
r.Use(func(c *gin.Context) {
|
r.Use(func(c *gin.Context) {
|
||||||
|
if strings.HasPrefix(c.Request.URL.Path, "/static/assets/immutable/") {
|
||||||
|
c.Header("Cache-Control", "public, max-age=31536000, immutable") // Cache for 1 year
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if strings.HasPrefix(c.Request.URL.Path, "/static/") {
|
if strings.HasPrefix(c.Request.URL.Path, "/static/") {
|
||||||
ext := filepath.Ext(c.Request.URL.Path)
|
ext := filepath.Ext(c.Request.URL.Path)
|
||||||
if ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".webp" {
|
if slices.Contains(cachableFileExtensions, ext) {
|
||||||
c.Header("Cache-Control", "public, max-age=300") // Cache for 5 minutes
|
c.Header("Cache-Control", "public, max-age=300") // Cache for 5 minutes
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
c.Next()
|
c.Next()
|
||||||
})
|
})
|
||||||
|
|
||||||
r.StaticFS("/static", http.FS(staticFS))
|
r.GET("/robots.txt", func(c *gin.Context) {
|
||||||
|
c.Header("Content-Type", "text/plain")
|
||||||
|
c.Header("Cache-Control", "public, max-age=31536000, immutable") // Cache for 1 year
|
||||||
|
c.String(http.StatusOK, "User-agent: *\nDisallow: /")
|
||||||
|
})
|
||||||
|
|
||||||
|
r.Any("/static/*w", func(c *gin.Context) {
|
||||||
|
staticFileServer.ServeHTTP(c.Writer, c.Request)
|
||||||
|
})
|
||||||
|
|
||||||
|
// Public routes (no authentication required)
|
||||||
r.POST("/auth/login-local", handleLogin)
|
r.POST("/auth/login-local", handleLogin)
|
||||||
|
|
||||||
// We use this to determine if the device is setup
|
// We use this to determine if the device is setup
|
||||||
|
@ -198,6 +228,10 @@ func handleWebRTCSession(c *gin.Context) {
|
||||||
_ = peerConn.Close()
|
_ = peerConn.Close()
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Cancel any ongoing keyboard macro when session changes
|
||||||
|
cancelKeyboardMacro()
|
||||||
|
|
||||||
currentSession = session
|
currentSession = session
|
||||||
c.JSON(http.StatusOK, gin.H{"sd": sd})
|
c.JSON(http.StatusOK, gin.H{"sd": sd})
|
||||||
}
|
}
|
||||||
|
@ -532,14 +566,31 @@ func RunWebServer() {
|
||||||
r := setupRouter()
|
r := setupRouter()
|
||||||
|
|
||||||
// Determine the binding address based on the config
|
// Determine the binding address based on the config
|
||||||
bindAddress := ":80" // Default to all interfaces
|
var bindAddress string
|
||||||
|
listenPort := 80 // default port
|
||||||
|
useIPv4 := config.NetworkConfig.IPv4Mode.String != "disabled"
|
||||||
|
useIPv6 := config.NetworkConfig.IPv6Mode.String != "disabled"
|
||||||
|
|
||||||
if config.LocalLoopbackOnly {
|
if config.LocalLoopbackOnly {
|
||||||
bindAddress = "localhost:80" // Loopback only (both IPv4 and IPv6)
|
if useIPv4 && useIPv6 {
|
||||||
|
bindAddress = fmt.Sprintf("localhost:%d", listenPort)
|
||||||
|
} else if useIPv4 {
|
||||||
|
bindAddress = fmt.Sprintf("127.0.0.1:%d", listenPort)
|
||||||
|
} else if useIPv6 {
|
||||||
|
bindAddress = fmt.Sprintf("[::1]:%d", listenPort)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if useIPv4 && useIPv6 {
|
||||||
|
bindAddress = fmt.Sprintf(":%d", listenPort)
|
||||||
|
} else if useIPv4 {
|
||||||
|
bindAddress = fmt.Sprintf("0.0.0.0:%d", listenPort)
|
||||||
|
} else if useIPv6 {
|
||||||
|
bindAddress = fmt.Sprintf("[::]:%d", listenPort)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Info().Str("bindAddress", bindAddress).Bool("loopbackOnly", config.LocalLoopbackOnly).Msg("Starting web server")
|
logger.Info().Str("bindAddress", bindAddress).Bool("loopbackOnly", config.LocalLoopbackOnly).Msg("Starting web server")
|
||||||
err := r.Run(bindAddress)
|
if err := r.Run(bindAddress); err != nil {
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
142
webrtc.go
142
webrtc.go
|
@ -7,12 +7,14 @@ import (
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/coder/websocket"
|
"github.com/coder/websocket"
|
||||||
"github.com/coder/websocket/wsjson"
|
"github.com/coder/websocket/wsjson"
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/jetkvm/kvm/internal/hidrpc"
|
"github.com/jetkvm/kvm/internal/hidrpc"
|
||||||
"github.com/jetkvm/kvm/internal/logging"
|
"github.com/jetkvm/kvm/internal/logging"
|
||||||
|
"github.com/jetkvm/kvm/internal/usbgadget"
|
||||||
"github.com/pion/webrtc/v4"
|
"github.com/pion/webrtc/v4"
|
||||||
"github.com/rs/zerolog"
|
"github.com/rs/zerolog"
|
||||||
)
|
)
|
||||||
|
@ -28,8 +30,25 @@ type Session struct {
|
||||||
rpcQueue chan webrtc.DataChannelMessage
|
rpcQueue chan webrtc.DataChannelMessage
|
||||||
|
|
||||||
hidRPCAvailable bool
|
hidRPCAvailable bool
|
||||||
|
lastKeepAliveArrivalTime time.Time // Track when last keep-alive packet arrived
|
||||||
|
lastTimerResetTime time.Time // Track when auto-release timer was last reset
|
||||||
|
keepAliveJitterLock sync.Mutex // Protect jitter compensation timing state
|
||||||
hidQueueLock sync.Mutex
|
hidQueueLock sync.Mutex
|
||||||
hidQueue []chan webrtc.DataChannelMessage
|
hidQueue []chan hidQueueMessage
|
||||||
|
|
||||||
|
keysDownStateQueue chan usbgadget.KeysDownState
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Session) resetKeepAliveTime() {
|
||||||
|
s.keepAliveJitterLock.Lock()
|
||||||
|
defer s.keepAliveJitterLock.Unlock()
|
||||||
|
s.lastKeepAliveArrivalTime = time.Time{} // Reset keep-alive timing tracking
|
||||||
|
s.lastTimerResetTime = time.Time{} // Reset auto-release timer tracking
|
||||||
|
}
|
||||||
|
|
||||||
|
type hidQueueMessage struct {
|
||||||
|
webrtc.DataChannelMessage
|
||||||
|
channel string
|
||||||
}
|
}
|
||||||
|
|
||||||
type SessionConfig struct {
|
type SessionConfig struct {
|
||||||
|
@ -78,16 +97,85 @@ func (s *Session) initQueues() {
|
||||||
s.hidQueueLock.Lock()
|
s.hidQueueLock.Lock()
|
||||||
defer s.hidQueueLock.Unlock()
|
defer s.hidQueueLock.Unlock()
|
||||||
|
|
||||||
s.hidQueue = make([]chan webrtc.DataChannelMessage, 0)
|
s.hidQueue = make([]chan hidQueueMessage, 0)
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
q := make(chan webrtc.DataChannelMessage, 256)
|
q := make(chan hidQueueMessage, 256)
|
||||||
s.hidQueue = append(s.hidQueue, q)
|
s.hidQueue = append(s.hidQueue, q)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Session) handleQueues(index int) {
|
func (s *Session) handleQueues(index int) {
|
||||||
for msg := range s.hidQueue[index] {
|
for msg := range s.hidQueue[index] {
|
||||||
onHidMessage(msg.Data, s)
|
onHidMessage(msg, s)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const keysDownStateQueueSize = 64
|
||||||
|
|
||||||
|
func (s *Session) initKeysDownStateQueue() {
|
||||||
|
// serialise outbound key state reports so unreliable links can't stall input handling
|
||||||
|
s.keysDownStateQueue = make(chan usbgadget.KeysDownState, keysDownStateQueueSize)
|
||||||
|
go s.handleKeysDownStateQueue()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Session) handleKeysDownStateQueue() {
|
||||||
|
for state := range s.keysDownStateQueue {
|
||||||
|
s.reportHidRPCKeysDownState(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Session) enqueueKeysDownState(state usbgadget.KeysDownState) {
|
||||||
|
if s == nil || s.keysDownStateQueue == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case s.keysDownStateQueue <- state:
|
||||||
|
default:
|
||||||
|
hidRPCLogger.Warn().Msg("dropping keys down state update; queue full")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getOnHidMessageHandler(session *Session, scopedLogger *zerolog.Logger, channel string) func(msg webrtc.DataChannelMessage) {
|
||||||
|
return func(msg webrtc.DataChannelMessage) {
|
||||||
|
l := scopedLogger.With().
|
||||||
|
Str("channel", channel).
|
||||||
|
Int("length", len(msg.Data)).
|
||||||
|
Logger()
|
||||||
|
// only log data if the log level is debug or lower
|
||||||
|
if scopedLogger.GetLevel() > zerolog.DebugLevel {
|
||||||
|
l = l.With().Str("data", string(msg.Data)).Logger()
|
||||||
|
}
|
||||||
|
|
||||||
|
if msg.IsString {
|
||||||
|
l.Warn().Msg("received string data in HID RPC message handler")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(msg.Data) < 1 {
|
||||||
|
l.Warn().Msg("received empty data in HID RPC message handler")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
l.Trace().Msg("received data in HID RPC message handler")
|
||||||
|
|
||||||
|
// Enqueue to ensure ordered processing
|
||||||
|
queueIndex := hidrpc.GetQueueIndex(hidrpc.MessageType(msg.Data[0]))
|
||||||
|
if queueIndex >= len(session.hidQueue) || queueIndex < 0 {
|
||||||
|
l.Warn().Int("queueIndex", queueIndex).Msg("received data in HID RPC message handler, but queue index not found")
|
||||||
|
queueIndex = 3
|
||||||
|
}
|
||||||
|
|
||||||
|
queue := session.hidQueue[queueIndex]
|
||||||
|
if queue != nil {
|
||||||
|
queue <- hidQueueMessage{
|
||||||
|
DataChannelMessage: msg,
|
||||||
|
channel: channel,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
l.Warn().Int("queueIndex", queueIndex).Msg("received data in HID RPC message handler, but queue is nil")
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -133,6 +221,7 @@ func newSession(config SessionConfig) (*Session, error) {
|
||||||
session := &Session{peerConnection: peerConnection}
|
session := &Session{peerConnection: peerConnection}
|
||||||
session.rpcQueue = make(chan webrtc.DataChannelMessage, 256)
|
session.rpcQueue = make(chan webrtc.DataChannelMessage, 256)
|
||||||
session.initQueues()
|
session.initQueues()
|
||||||
|
session.initKeysDownStateQueue()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
for msg := range session.rpcQueue {
|
for msg := range session.rpcQueue {
|
||||||
|
@ -157,40 +246,12 @@ func newSession(config SessionConfig) (*Session, error) {
|
||||||
switch d.Label() {
|
switch d.Label() {
|
||||||
case "hidrpc":
|
case "hidrpc":
|
||||||
session.HidChannel = d
|
session.HidChannel = d
|
||||||
d.OnMessage(func(msg webrtc.DataChannelMessage) {
|
d.OnMessage(getOnHidMessageHandler(session, scopedLogger, "hidrpc"))
|
||||||
l := scopedLogger.With().Int("length", len(msg.Data)).Logger()
|
// we won't send anything over the unreliable channels
|
||||||
// only log data if the log level is debug or lower
|
case "hidrpc-unreliable-ordered":
|
||||||
if scopedLogger.GetLevel() > zerolog.DebugLevel {
|
d.OnMessage(getOnHidMessageHandler(session, scopedLogger, "hidrpc-unreliable-ordered"))
|
||||||
l = l.With().Str("data", string(msg.Data)).Logger()
|
case "hidrpc-unreliable-nonordered":
|
||||||
}
|
d.OnMessage(getOnHidMessageHandler(session, scopedLogger, "hidrpc-unreliable-nonordered"))
|
||||||
|
|
||||||
if msg.IsString {
|
|
||||||
l.Warn().Msg("received string data in HID RPC message handler")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(msg.Data) < 1 {
|
|
||||||
l.Warn().Msg("received empty data in HID RPC message handler")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
l.Trace().Msg("received data in HID RPC message handler")
|
|
||||||
|
|
||||||
// Enqueue to ensure ordered processing
|
|
||||||
queueIndex := hidrpc.GetQueueIndex(hidrpc.MessageType(msg.Data[0]))
|
|
||||||
if queueIndex >= len(session.hidQueue) || queueIndex < 0 {
|
|
||||||
l.Warn().Int("queueIndex", queueIndex).Msg("received data in HID RPC message handler, but queue index not found")
|
|
||||||
queueIndex = 3
|
|
||||||
}
|
|
||||||
|
|
||||||
queue := session.hidQueue[queueIndex]
|
|
||||||
if queue != nil {
|
|
||||||
queue <- msg
|
|
||||||
} else {
|
|
||||||
l.Warn().Int("queueIndex", queueIndex).Msg("received data in HID RPC message handler, but queue is nil")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
})
|
|
||||||
case "rpc":
|
case "rpc":
|
||||||
session.RPCChannel = d
|
session.RPCChannel = d
|
||||||
d.OnMessage(func(msg webrtc.DataChannelMessage) {
|
d.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||||
|
@ -266,6 +327,8 @@ func newSession(config SessionConfig) (*Session, error) {
|
||||||
if connectionState == webrtc.ICEConnectionStateClosed {
|
if connectionState == webrtc.ICEConnectionStateClosed {
|
||||||
scopedLogger.Debug().Msg("ICE Connection State is closed, unmounting virtual media")
|
scopedLogger.Debug().Msg("ICE Connection State is closed, unmounting virtual media")
|
||||||
if session == currentSession {
|
if session == currentSession {
|
||||||
|
// Cancel any ongoing keyboard report multi when session closes
|
||||||
|
cancelKeyboardMacro()
|
||||||
currentSession = nil
|
currentSession = nil
|
||||||
}
|
}
|
||||||
// Stop RPC processor
|
// Stop RPC processor
|
||||||
|
@ -280,6 +343,9 @@ func newSession(config SessionConfig) (*Session, error) {
|
||||||
session.hidQueue[i] = nil
|
session.hidQueue[i] = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
close(session.keysDownStateQueue)
|
||||||
|
session.keysDownStateQueue = nil
|
||||||
|
|
||||||
if session.shouldUmountVirtualMedia {
|
if session.shouldUmountVirtualMedia {
|
||||||
if err := rpcUnmountImage(); err != nil {
|
if err := rpcUnmountImage(); err != nil {
|
||||||
scopedLogger.Warn().Err(err).Msg("unmount image failed on connection close")
|
scopedLogger.Warn().Err(err).Msg("unmount image failed on connection close")
|
||||||
|
|
Loading…
Reference in New Issue