-
Notifications
You must be signed in to change notification settings - Fork 314
Expand file tree
/
Copy pathusb.go
More file actions
259 lines (210 loc) · 6.56 KB
/
usb.go
File metadata and controls
259 lines (210 loc) · 6.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package kvm
import (
"sync"
"time"
"github.com/jetkvm/kvm/internal/usbgadget"
)
var gadget *usbgadget.UsbGadget
// initUsbGadget initializes the USB gadget.
// call it only after the config is loaded.
func initUsbGadget() {
gadget = usbgadget.NewUsbGadget(
"jetkvm",
config.UsbDevices,
config.UsbConfig,
usbLogger,
)
setUSBRecoveryTimer(time.Now())
go func() {
for {
checkUSBState()
time.Sleep(500 * time.Millisecond)
}
}()
gadget.SetOnKeyboardStateChange(func(state usbgadget.KeyboardState) {
if currentSession != nil {
currentSession.reportHidRPCKeyboardLedState(state)
}
})
gadget.SetOnKeysDownChange(func(state usbgadget.KeysDownState) {
if currentSession != nil {
currentSession.enqueueKeysDownState(state)
}
})
gadget.SetOnKeepAliveReset(func() {
if currentSession != nil {
currentSession.resetKeepAliveTime()
}
})
// open the keyboard hid file to listen for keyboard events
if err := gadget.OpenKeyboardHidFile(); err != nil {
usbLogger.Error().Err(err).Msg("failed to open keyboard hid file")
}
}
// rpcHidReport wraps a HID gadget call with the common guard (skip if USB not
// ready) and error suppression (swallow transient HID errors during rebind).
func rpcHidReport(fn func() error) error {
if !usbReadyForHidReports() {
return nil
}
if err := fn(); err != nil && !usbgadget.IsHIDTemporarilyUnavailableError(err) {
return err
}
return nil
}
func rpcKeyboardReport(modifier byte, keys []byte) error {
return rpcHidReport(func() error { return gadget.KeyboardReport(modifier, keys) })
}
func rpcKeypressReport(key byte, press bool) error {
return rpcHidReport(func() error { return gadget.KeypressReport(key, press) })
}
func rpcAbsMouseReport(x int, y int, buttons uint8) error {
return rpcHidReport(func() error { return gadget.AbsMouseReport(x, y, buttons) })
}
func rpcRelMouseReport(dx int8, dy int8, buttons uint8) error {
return rpcHidReport(func() error { return gadget.RelMouseReport(dx, dy, buttons) })
}
func rpcWheelReport(wheelY int8, wheelX int8) error {
return rpcHidReport(func() error {
if err := gadget.AbsMouseWheelReport(wheelY, wheelX); err != nil {
return err
}
return gadget.RelMouseWheelReport(wheelY, wheelX)
})
}
func rpcGetKeyboardLedState() (state usbgadget.KeyboardState) {
return gadget.GetKeyboardState()
}
func rpcGetKeysDownState() (state usbgadget.KeysDownState) {
return gadget.GetKeysDownState()
}
var (
usbState = usbgadget.USBStateUnknown
usbStateLock sync.Mutex
usbEmulationDesired = true
lastUSBRecoveryTry time.Time
)
func usbReadyForHidReports() bool {
usbStateLock.Lock()
state := usbState
usbStateLock.Unlock()
return state != usbgadget.USBStateNotAttached && state != usbgadget.USBStateUnknown
}
func rpcGetUSBState() (state string) {
return gadget.GetUsbState()
}
func setUSBEmulationDesired(enabled bool) {
usbStateLock.Lock()
defer usbStateLock.Unlock()
usbEmulationDesired = enabled
}
func setUSBRecoveryTimer(lastAttempt time.Time) {
usbStateLock.Lock()
defer usbStateLock.Unlock()
lastUSBRecoveryTry = lastAttempt
}
func attemptUSBRecovery(state string) string {
now := time.Now()
usbStateLock.Lock()
desired := usbEmulationDesired
lastAttempt := lastUSBRecoveryTry
shouldRecover := usbgadget.ShouldAttemptUSBRecovery(state, desired, lastAttempt, now)
if shouldRecover {
lastUSBRecoveryTry = now
}
usbStateLock.Unlock()
if !shouldRecover {
return state
}
usbLogger.Warn().Msg("USB gadget is detached while USB emulation should be enabled; rebinding USB gadget")
if err := gadget.RebindUsb(true); err != nil {
usbLogger.Warn().Err(err).Msg("failed to recover USB gadget by rebinding USB device controller")
return state
}
// Clear stale /dev/hidg* handles from the pre-rebind gadget instance.
// The next write/open must use the newly recreated device nodes.
gadget.ResetHIDFiles()
// After rebind, the kernel recreates /dev/hidg* but the character
// devices take several seconds to become usable (ENXIO until the
// function driver attaches). Retry the keyboard HID file open with
// increasing delays up to ~20 seconds total.
delays := []time.Duration{
1 * time.Second,
1 * time.Second,
2 * time.Second,
2 * time.Second,
3 * time.Second,
3 * time.Second,
4 * time.Second,
4 * time.Second,
}
tryReopenKeyboard := func(openDelays []time.Duration, reason string) bool {
for _, delay := range openDelays {
time.Sleep(delay)
if err := gadget.ReopenKeyboardHidFile(); err == nil {
usbLogger.Info().Str("reason", reason).Msg("keyboard HID file reopened successfully after USB recovery")
return true
}
}
return false
}
if tryReopenKeyboard(delays, "udc_rebind") {
return gadget.GetUsbState()
}
usbLogger.Warn().Msg("keyboard HID file not ready after UDC rebind; attempting full USB gadget reconfigure")
if err := gadget.UpdateGadgetConfig(); err != nil {
usbLogger.Warn().Err(err).Msg("failed to recover USB gadget with full gadget reconfigure")
return gadget.GetUsbState()
}
gadget.ResetHIDFiles()
if !tryReopenKeyboard(delays, "gadget_reconfigure") {
usbLogger.Warn().Msg("keyboard HID file not ready after full USB recovery retry window")
}
return gadget.GetUsbState()
}
func triggerUSBStateUpdate() {
go func() {
if currentSession == nil {
usbLogger.Info().Msg("No active RPC session, skipping USB state update")
return
}
writeJSONRPCEvent("usbState", usbState, currentSession)
}()
}
func checkUSBState() {
newState := gadget.GetUsbState()
if newState == usbgadget.USBStateNotAttached {
newState = attemptUSBRecovery(newState)
}
usbStateLock.Lock()
defer usbStateLock.Unlock()
if newState != usbgadget.USBStateNotAttached {
// Once USB is attached again, clear recovery rate limiting so any future
// detach can be recovered immediately.
lastUSBRecoveryTry = time.Time{}
}
if newState == usbState {
return
}
oldState := usbState
usbState = newState
usbLogger.Info().Str("from", oldState).Str("to", newState).Msg("USB state changed")
if newState != usbgadget.USBStateNotAttached {
openErr := gadget.OpenKeyboardHidFile()
if openErr != nil {
usbLogger.Warn().Err(openErr).Str("state", newState).Msg("HID chardev broken after state change, attempting corrective rebind")
lastUSBRecoveryTry = time.Now()
usbStateLock.Unlock()
gadget.ResetHIDFiles()
if rebindErr := gadget.RebindUsb(true); rebindErr == nil {
time.Sleep(1 * time.Second)
_ = gadget.OpenKeyboardHidFile()
}
usbStateLock.Lock()
usbState = gadget.GetUsbState()
lastUSBRecoveryTry = time.Now()
}
}
requestDisplayUpdate(false, "usb_state_changed")
triggerUSBStateUpdate()
}