Repository navigation
Expand file tree
/
Copy pathos_services.go
More file actions
688 lines (623 loc) · 20.8 KB
/
Copy pathos_services.go
File metadata and controls
688 lines (623 loc) · 20.8 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
package kvm
import (
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"os"
"path/filepath"
"sync"
"time"
"github.com/jetkvm/kvm/internal/logging"
"github.com/jetkvm/kvm/internal/osservices"
"github.com/jetkvm/kvm/internal/osservices/ffs"
"github.com/jetkvm/kvm/internal/usbgadget"
"github.com/pion/webrtc/v4"
)
// IP-KVM OS Services: a service on the target computer talks to the KVM
// over the KVM's USB cable (jetkvm/os-services PROTOCOL.md). The protocol
// runs in internal/osservices; this file connects it to the USB gadget, the
// settings, the browser and the video pipeline.
var osServicesLogger = logging.GetSubsystemLogger("os_services")
const (
osServicesUSBKey = "os_services"
osServicesFFSInstance = "os_services"
osServicesFFSMount = "/dev/ffs-os-services"
osServicesKeyPath = "/userdata/jetkvm/os_services.key"
osServicesTick = 50 * time.Millisecond
// The RPC waits this long for a clipboard answer: the session's own
// timeout, a write and some slack.
osServicesClipboardWait = osservices.ClipboardTimeoutMS*time.Millisecond + 2500*time.Millisecond
)
var osServices *osServicesService
type clipboardResult struct {
status osservices.ClipboardStatus
answered bool
text string
truncated bool
}
type osServicesService struct {
link *ffs.Link
session *osservices.Session // guarded by link.Mu
key ed25519.PrivateKey
fingerprint string
start time.Time
fnMu sync.Mutex
fn *ffs.Function
settingsMu sync.Mutex
settingsSequence uint32
stateSignal chan struct{}
// The source last logged; guarded by link.Mu.
lastSource osservices.VideoSource
// Guarded by link.Mu.
clipboardWaits map[uint32]chan clipboardResult
terminals map[uint32]*guestTerminal
drops map[uint32]*guestDrop
video guestVideo
}
// initOSServices sets up OS Services before the USB gadget, which links the
// OS Services function once its descriptors are written.
func initOSServices() {
if failsafeModeActive {
return
}
key, err := loadOSServicesKey(osServicesKeyPath)
if err != nil {
osServicesLogger.Error().Err(err).Msg("OS Services disabled: no KVM key")
return
}
digest := sha256.Sum256(key.Public().(ed25519.PublicKey))
s := &osServicesService{
key: key,
fingerprint: osservices.FormatFingerprint(digest[:]),
start: time.Now(),
stateSignal: make(chan struct{}, 1),
clipboardWaits: map[uint32]chan clipboardResult{},
terminals: map[uint32]*guestTerminal{},
drops: map[uint32]*guestDrop{},
}
s.video.init(s)
udc := ""
if udcs, _ := filepath.Glob("/sys/class/udc/*"); len(udcs) > 0 {
udc = filepath.Base(udcs[0])
}
s.link = ffs.NewLink(osServicesLogger, udc)
s.session = osservices.New(s, s.config().sessionSettings(osservices.CodecH264))
s.session.SetFingerprint(s.fingerprint)
s.link.SetSession(s.session)
osServices = s
usbgadget.RegisterExternalFunction(usbgadget.ExternalFunction{
Key: osServicesUSBKey,
Instance: osServicesFFSInstance,
Order: 5000,
Prepare: s.prepareFunction,
Release: s.releaseFunction,
MSOSDescriptors: true,
Enabled: func() bool { return s.config().Enabled },
})
go s.ticker()
go s.stateNotifier()
osServicesLogger.Info().Str("fingerprint", s.fingerprint).Msg("OS Services ready")
}
// loadOSServicesKey reads the KVM's Ed25519 seed, or makes one. The key stays
// until a factory reset.
func loadOSServicesKey(path string) (ed25519.PrivateKey, error) {
seed, err := os.ReadFile(path)
if err == nil && len(seed) == ed25519.SeedSize {
return ed25519.NewKeyFromSeed(seed), nil
}
if err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
seed = make([]byte, ed25519.SeedSize)
if _, err := rand.Read(seed); err != nil {
return nil, err
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, seed, 0o600); err != nil {
return nil, err
}
if err := os.Rename(tmp, path); err != nil {
return nil, err
}
return ed25519.NewKeyFromSeed(seed), nil
}
// prepareFunction mounts the FunctionFS instance and writes its descriptors,
// unless the function is open; usbgadget calls it before each configuration.
func (s *osServicesService) prepareFunction(spareIN bool) error {
s.fnMu.Lock()
defer s.fnMu.Unlock()
if s.fn != nil {
return nil
}
if err := ffs.Mount(osServicesFFSMount, osServicesFFSInstance); err != nil {
return err
}
fn, err := ffs.Open(osServicesFFSMount, spareIN)
if err != nil {
return err
}
s.fn = fn
s.link.Start(fn)
osServicesLogger.Info().Bool("spare_in", spareIN).Msg("OS Services USB function ready")
return nil
}
// releaseFunction stops the link and closes the FunctionFS instance, so that
// the next prepareFunction writes the descriptors again. usbgadget calls it
// with the gadget detached from the USB controller. After an error the
// function stays open and the link stays stopped.
func (s *osServicesService) releaseFunction() error {
s.fnMu.Lock()
defer s.fnMu.Unlock()
if s.fn == nil {
return nil
}
if err := s.link.Stop(); err != nil {
return err
}
s.fn.Close()
s.fn = nil
osServicesLogger.Info().Msg("OS Services USB function released")
return nil
}
// osServicesNoteKVMRestart: the KVM restarts its own USB device; a session
// that ends for it does not count against the video retry budget.
func osServicesNoteKVMRestart() {
if osServices != nil {
osServices.link.NoteKVMRestart()
}
}
func (s *osServicesService) config() OSServicesConfig {
configLock.Lock()
defer configLock.Unlock()
if config == nil || config.OSServices == nil {
return *defaultOSServicesConfig()
}
return *config.OSServices
}
// do runs fn with the session lock held.
func (s *osServicesService) do(fn func(*osservices.Session)) {
s.link.Mu.Lock()
defer s.link.Mu.Unlock()
fn(s.session)
}
func (s *osServicesService) ticker() {
t := time.NewTicker(osServicesTick)
defer t.Stop()
for range t.C {
s.link.Mu.Lock()
s.session.Tick()
s.video.tick(s.session)
if source := s.session.Source(); source != s.lastSource {
s.lastSource = source
osServicesLogger.Info().Str("session", s.session.String()).Bool("owned", s.video.owned.Load()).
Bool("presented", s.video.presented.Load()).Msg("video source changed")
}
s.flushTerminalCredits()
s.link.Mu.Unlock()
s.link.Wake()
}
}
// applySettings hands the settings and the browser's codec to the session.
func (s *osServicesService) applySettings() {
s.applySettingsFor(currentSession)
}
func (s *osServicesService) applySettingsFor(browser *Session) {
settings := s.config().sessionSettings(browserCodec(browser))
s.do(func(session *osservices.Session) { session.ApplySettings(settings) })
}
// browserCodec is the codec a browser session negotiated.
func browserCodec(session *Session) osservices.Codec {
if session != nil && session.codecMimeType == webrtc.MimeTypeH265 {
return osservices.CodecH265
}
return osservices.CodecH264
}
// --- Platform -----------------------------------------------------------------
func (s *osServicesService) NowMS() int64 { return time.Since(s.start).Milliseconds() }
func (s *osServicesService) NowUS() int64 { return time.Since(s.start).Microseconds() }
func (s *osServicesService) FillRandom(b []byte) {
if _, err := rand.Read(b); err != nil {
panic(err)
}
}
func (s *osServicesService) PublicKey() ([]byte, bool) {
return s.key.Public().(ed25519.PublicKey), true
}
func (s *osServicesService) Sign(message []byte) ([]byte, bool) {
return ed25519.Sign(s.key, message), true
}
func (s *osServicesService) Write(envelope, head, body []byte) bool {
return s.link.Write(envelope, head, body)
}
func (s *osServicesService) SessionEnded(reason string) {
osServicesLogger.Info().Str("reason", reason).Msg("OS Services session ended")
s.link.SessionEnded()
}
func (s *osServicesService) ResetTransport() { s.link.ResetTransport() }
// StateChanged may come without the session lock (the update relay).
func (s *osServicesService) StateChanged() {
select {
case s.stateSignal <- struct{}{}:
default:
}
}
func (s *osServicesService) ClipboardDone(id uint32, status osservices.ClipboardStatus, answered bool, text []byte, truncated bool) {
wait, ok := s.clipboardWaits[id]
if !ok {
return
}
delete(s.clipboardWaits, id)
wait <- clipboardResult{status: status, answered: answered, text: string(text), truncated: truncated}
}
// stateNotifier sends the browser the changed state, at most every 100 ms.
func (s *osServicesService) stateNotifier() {
var last string
for range s.stateSignal {
state := currentVideoState()
if status := state.OSServices; status != nil && status.Connected && !status.ApprovalPending && status.Sender != nil {
s.noteSender(status.Sender.Version)
}
if text := fmt.Sprintf("%+v", state); text != last {
last = text
writeJSONRPCEvent("videoInputState", state, currentSession)
}
time.Sleep(100 * time.Millisecond)
}
}
// --- State for the browser ------------------------------------------------------
type osServicesSenderJSON struct {
Version string `json:"version"`
Displays []string `json:"displays"`
}
type osServicesStatusJSON struct {
Enabled bool `json:"enabled"`
Sender *osServicesSenderJSON `json:"sender,omitempty"`
Connected bool `json:"connected"`
Video bool `json:"video"`
VideoRegistered bool `json:"videoRegistered"`
VideoError string `json:"videoError,omitempty"`
Clipboard bool `json:"clipboard"`
ApprovalPending bool `json:"approvalPending"`
Fingerprint string `json:"fingerprint"`
// BrowserCodecNotOffered: this browser session negotiated H.265 and
// the sender shows video without it. A new session takes H.264
// (resolveCodec), so the browser connects again.
BrowserCodecNotOffered bool `json:"browserCodecNotOffered,omitempty"`
}
type guestClipboardJSON struct {
Read bool `json:"read"`
Write bool `json:"write"`
OS string `json:"os"`
}
type guestFileJSON struct {
Receive bool `json:"receive"`
}
// rpcVideoState is videoInputState and the getVideoState answer: the video
// state, and on a KVM with OS Services the source and the sender.
type rpcVideoState struct {
Ready bool `json:"ready"`
Streaming int `json:"streaming"`
Error string `json:"error,omitempty"`
Width int `json:"width"`
Height int `json:"height"`
FramePerSecond float64 `json:"fps"`
Source string `json:"source,omitempty"`
OSServices *osServicesStatusJSON `json:"osServices,omitempty"`
GuestClipboard *guestClipboardJSON `json:"guestClipboard,omitempty"`
GuestTerminal bool `json:"guestTerminal,omitempty"`
GuestFile *guestFileJSON `json:"guestFile,omitempty"`
GuestUpdate any `json:"guestUpdate,omitempty"`
}
func currentVideoState() rpcVideoState {
v := lastVideoState
state := rpcVideoState{
Ready: v.Ready,
Streaming: int(v.Streaming),
Error: v.Error,
Width: v.Width,
Height: v.Height,
FramePerSecond: v.FramePerSecond,
}
if osServices == nil {
return state
}
var st osservices.State
osServices.do(func(session *osservices.Session) { st = session.State() })
state.Source = st.Source.String()
switch st.Source {
case osservices.SourceGuest:
state.Ready = true
state.Error = ""
if st.StreamStarted {
state.Width = int(st.StreamWidth)
state.Height = int(st.StreamHeight)
state.FramePerSecond = float64(st.StreamFPS)
}
case osservices.SourceSwitchingToGuest, osservices.SourceSwitchingToPhysical:
// The hardware capture's state during a switch is no signal, which
// the browser does not show then.
state.Ready = false
state.Error = ""
}
status := &osServicesStatusJSON{
Enabled: osServices.config().Enabled,
Connected: st.Connected,
Video: st.Source == osservices.SourceGuest,
VideoRegistered: st.VideoRegistered,
VideoError: st.VideoError,
Clipboard: st.Clipboard,
ApprovalPending: st.ApprovalPending,
Fingerprint: st.Fingerprint,
}
if session := currentSession; session != nil && session.codecMimeType == webrtc.MimeTypeH265 {
status.BrowserCodecNotOffered = st.VideoRegistered &&
st.VideoCodecFlags&osservices.VideoCodecFlagH265 == 0 && osServices.config().VideoEnabled
}
if st.SenderInfo {
displays := st.Displays
if displays == nil {
displays = []string{}
}
status.Sender = &osServicesSenderJSON{Version: st.SenderVersion, Displays: displays}
}
state.OSServices = status
if st.Clipboard {
state.GuestClipboard = &guestClipboardJSON{
Read: st.ClipboardFlags&osservices.ClipboardFlagRead != 0,
Write: st.ClipboardFlags&osservices.ClipboardFlagWrite != 0,
OS: st.ClipboardOS.String(),
}
}
state.GuestTerminal = st.Terminal
if st.FileReceive {
state.GuestFile = &guestFileJSON{Receive: true}
}
if update := osServicesUpdateState(st); update != nil {
state.GuestUpdate = update
}
return state
}
// --- RPC ------------------------------------------------------------------------
func requireOSServices() (*osServicesService, error) {
if osServices == nil {
return nil, errors.New("OS Services unavailable")
}
return osServices, nil
}
func rpcGetOsServicesSettings() (OSServicesConfig, error) {
s, err := requireOSServices()
if err != nil {
return OSServicesConfig{}, err
}
return s.config(), nil
}
type osServicesSettingsEvent struct {
Sequence uint32 `json:"sequence"`
Settings OSServicesConfig `json:"settings"`
}
func rpcSetOsServicesSettings(settings map[string]any) (OSServicesConfig, error) {
s, err := requireOSServices()
if err != nil {
return OSServicesConfig{}, err
}
s.settingsMu.Lock()
defer s.settingsMu.Unlock()
current := s.config()
merged, err := mergeOSServicesConfig(current, settings)
if err != nil {
return current, err
}
if merged == current {
return current, nil
}
store := func(settings OSServicesConfig) {
configLock.Lock()
config.OSServices = &settings
configLock.Unlock()
}
// While the gadget changes, the config holds the new switch, and a save
// from another call can write it. So a change that is taken back is
// saved too.
takeBack := func() {
store(current)
if err := SaveConfig(); err != nil {
osServicesLogger.Warn().Err(err).Msg("cannot save the OS Services settings that were taken back")
}
}
// The gadget reads the switch from the config. As for the USB devices,
// the gadget changes first and the settings are saved after it, so a
// gadget that refuses the change leaves the settings as they were.
updateGadget := func() error {
osServicesNoteKVMRestart()
setUSBRecoveryTimer(time.Now())
err := gadget.UpdateGadgetConfig()
setUSBRecoveryTimer(time.Now())
return err
}
store(merged)
if merged.Enabled != current.Enabled {
if err := updateGadget(); err != nil {
takeBack()
if again := updateGadget(); again != nil {
osServicesLogger.Warn().Err(again).Msg("cannot put the gadget back after a refused OS Services switch")
}
return current, fmt.Errorf("failed to write gadget config: %w", err)
}
}
if err := SaveConfig(); err != nil {
takeBack()
if merged.Enabled != current.Enabled {
if again := updateGadget(); again != nil {
osServicesLogger.Warn().Err(again).Msg("cannot put the gadget back after a failed save")
}
}
return current, fmt.Errorf("failed to save config: %w", err)
}
s.applySettings()
s.announceSettings(merged)
return merged, nil
}
// announceSettings tells the browser the settings; the caller holds
// settingsMu.
func (s *osServicesService) announceSettings(settings OSServicesConfig) {
s.settingsSequence++
event := osServicesSettingsEvent{Sequence: s.settingsSequence, Settings: settings}
go writeJSONRPCEvent("osServicesSettings", event, currentSession)
s.StateChanged()
}
// osServicesLastSenderAge is how old the stored time of the last sender can
// be before a session of the same version writes it again.
const osServicesLastSenderAge = time.Hour
// noteSender stores the sender of an approved session, so that the KVM
// knows later that a sender was installed.
func (s *osServicesService) noteSender(version string) {
s.settingsMu.Lock()
defer s.settingsMu.Unlock()
current := s.config()
if current.LastSenderVersion == version {
if at, err := time.Parse(time.RFC3339, current.LastSenderAt); err == nil && time.Since(at) < osServicesLastSenderAge {
return
}
}
current.LastSenderVersion = version
current.LastSenderAt = time.Now().UTC().Format(time.RFC3339)
configLock.Lock()
stored := current
config.OSServices = &stored
configLock.Unlock()
if err := SaveConfig(); err != nil {
osServicesLogger.Warn().Err(err).Msg("cannot store the last OS Services sender")
return
}
s.announceSettings(current)
}
const (
clipboardUnavailable = "no OS Services clipboard is connected"
clipboardDisabled = "clipboard sharing is turned off in the OS Services settings"
clipboardNoAnswer = "the target computer's clipboard did not answer in time"
)
func (s *osServicesService) clipboardCall(text []byte, set bool) (clipboardResult, error) {
wait := make(chan clipboardResult, 1)
var startErr error
s.do(func(session *osservices.Session) {
id, status := session.ClipboardRequest(text, set)
switch {
case id != 0:
s.clipboardWaits[id] = wait
case !session.Settings().ClipboardEnabled:
startErr = errors.New(clipboardDisabled)
case status == osservices.ClipboardUnsupported:
startErr = errors.New(clipboardUnavailable)
default:
startErr = errors.New("the clipboard request could not be sent")
}
})
if startErr != nil {
return clipboardResult{}, startErr
}
select {
case result := <-wait:
if !result.answered {
open := false
s.do(func(session *osservices.Session) { open = session.Open() })
if open {
return result, errors.New(clipboardNoAnswer)
}
return result, errors.New(clipboardUnavailable)
}
return result, nil
case <-time.After(osServicesClipboardWait):
return clipboardResult{}, errors.New(clipboardNoAnswer)
}
}
type guestClipboardGetResult struct {
Status string `json:"status"`
Text string `json:"text"`
Truncated bool `json:"truncated"`
}
func rpcGuestClipboardGet() (guestClipboardGetResult, error) {
s, err := requireOSServices()
if err != nil {
return guestClipboardGetResult{}, errors.New(clipboardUnavailable)
}
result, err := s.clipboardCall(nil, false)
if err != nil {
return guestClipboardGetResult{}, err
}
answer := guestClipboardGetResult{Status: result.status.String(), Truncated: result.truncated}
if result.status == osservices.ClipboardOK {
answer.Text = result.text
}
return answer, nil
}
type guestClipboardSetResult struct {
Status string `json:"status"`
}
func rpcGuestClipboardSet(text string) (guestClipboardSetResult, error) {
s, err := requireOSServices()
if err != nil {
return guestClipboardSetResult{}, errors.New(clipboardUnavailable)
}
if len(text) > osservices.ClipboardMaxText {
return guestClipboardSetResult{}, fmt.Errorf("clipboard text exceeds %d bytes", osservices.ClipboardMaxText)
}
if !osservices.UTF8Valid([]byte(text)) {
return guestClipboardSetResult{}, errors.New("clipboard text is not valid UTF-8")
}
result, err := s.clipboardCall([]byte(text), true)
if err != nil {
return guestClipboardSetResult{}, err
}
return guestClipboardSetResult{Status: result.status.String()}, nil
}
// --- Helpers for the rest of the firmware ----------------------------------------
// osServicesOwnsVideo reports whether service video owns the display: the
// hardware capture stays off and its frames go nowhere.
func osServicesOwnsVideo() bool {
return osServices != nil && osServices.video.owned.Load()
}
// osServicesDisplayEDID is the EDID of the KVM display while service video
// owns it, else "".
func osServicesDisplayEDID() string {
if osServices == nil {
return ""
}
if edid, ok := osServices.video.edid.Load().(string); ok {
return edid
}
return ""
}
// osServicesPrefersH264: a sender shows video without H.265, so a new
// browser session takes H.264.
func osServicesPrefersH264() bool {
if osServices == nil {
return false
}
prefer := false
osServices.do(func(session *osservices.Session) {
st := session.State()
prefer = st.VideoRegistered && st.VideoCodecFlags&osservices.VideoCodecFlagH265 == 0 &&
session.Settings().VideoEnabled
})
return prefer
}
// osServicesBrowserChanged: a browser session connected; it needs the codec
// it negotiated and a keyframe. currentSession may not point at it yet.
func osServicesBrowserChanged(session *Session) {
if osServices == nil {
return
}
osServices.applySettingsFor(session)
osServices.video.wantKeyframe()
}
// osServicesKeyframeRequest: the browser lost video (PLI or FIR).
func osServicesKeyframeRequest() {
if osServicesOwnsVideo() {
osServices.video.wantKeyframe()
}
}