diff --git a/internal/app/keymap_flow.go b/internal/app/keymap_flow.go index ab7023a..104083f 100644 --- a/internal/app/keymap_flow.go +++ b/internal/app/keymap_flow.go @@ -1,8 +1,6 @@ package app import ( - "time" - "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" @@ -10,7 +8,6 @@ import ( ) const KeymapRequiredAgentVersion = guesttools.KeymapAgentVersion -const keymapStatusMaxAge = 30 * time.Second type VMKeymapUpdate struct { Preset string `json:"preset"` @@ -84,10 +81,10 @@ func (a *App) keymapStatus(name string, running bool, cfg vmstart.VMKeymapConfig srv := a.guestTools a.mu.Unlock() if srv != nil && running { - guest := srv.Status(name, keymapStatusMaxAge) + guest := srv.Status(name, guesttools.KeymapStatusMaxAge) status.GuestConnected = guest.Connected status.GuestAgentVersion = guest.AgentVersion - status.GuestKeymapActive = guest.KeymapActive && guest.AgentVersion >= KeymapRequiredAgentVersion + status.GuestKeymapActive = guest.KeymapActive } svc := a.getInputService() status.InputServiceAvailable = svc != nil @@ -143,8 +140,7 @@ func (a *App) syncKeymapRulesLocked() { srv.SetKeymapCarrier(vm.Name, false) } srv.SetKeymapCarrier(vm.Name, svc != nil && vmstart.NeedsGuestCarrier(effective)) - status := srv.Status(vm.Name, keymapStatusMaxAge) - rule.CarrierReady = status.Connected && status.KeymapActive && status.AgentVersion >= KeymapRequiredAgentVersion + rule.CarrierReady = srv.Status(vm.Name, guesttools.KeymapStatusMaxAge).KeymapActive } if len(effective) != 0 { rules = append(rules, rule) diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 9bb5fd6..0601183 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -1451,7 +1451,6 @@ a%23note.txt' clipboard_worker) text_input_loop() { :; } drop_events_loop() { :; } - file_sync_loop() { :; } load_conf() { :; } sync_clipboard() { printf 'clip\n' >> calls; exit; } apply_host_config() { :; } diff --git a/internal/guesttools/drop.go b/internal/guesttools/drop.go index 07a5af6..a1a7cc2 100644 --- a/internal/guesttools/drop.go +++ b/internal/guesttools/drop.go @@ -256,7 +256,7 @@ func (s *Server) handleDropEvents(w http.ResponseWriter, r *http.Request) { cur.dropQueue[0] = nil cur.dropQueue = cur.dropQueue[1:] cur.dropActive[item.DropID] = item - cur.lastSeen = time.Now() + cur.markSeen(time.Now()) cur.lastDropPoll = time.Now() s.mu.Unlock() diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 76c065c..0bb5fb7 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -130,7 +130,6 @@ FOLDER_MODE_DIR="$APP_DIR/folder_modes" FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" TMP_DIR="$PWD/tmp" REIMS_HOST_URL=http://stub:19847 -keymap_active=false sync_keymap_carrier() { :; } REIMS_TOKEN=token REIMS_VM=mac diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index c9b4c74..3b0e8e0 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -24,9 +24,8 @@ const BidirectionalClipboardFilesAgentVersion = 16 const WindowReportAgentVersion = 17 const PasteReadyAgentVersion = 18 const FileClipboardReadinessAgentVersion = 19 -const KeymapStatusStabilityAgentVersion = 20 -const CurrentAgentVersion = KeymapStatusStabilityAgentVersion +const CurrentAgentVersion = FileClipboardReadinessAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 04b9aab..426f94e 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -161,14 +161,13 @@ INJECT_LOCK="$TMP_DIR/injecting" DROP_INJECT_LOCK="$TMP_DIR/drop-injecting" CLIP_LOCK="$TMP_DIR/clip.lock" mkdir -p "$APP_DIR" "$SHARE_SYNC" "$SHARE_MOUNT" "$DRIVE_MOUNT_ROOT" "$TMP_DIR" "$DROP_MOUNT" -rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" "$TMP_DIR/clip_file_config" "$TMP_DIR/mount_mode" 2>/dev/null || true +rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" "$TMP_DIR/clip_file_config" 2>/dev/null || true rm -rf "$CLIP_LOCK" "$CLIP_LOCK".reaping.* 2>/dev/null || true CAFFEINATE_PID="" TEXT_INPUT_PID="" DROP_EVENTS_PID="" CLIPBOARD_PID="" -FILE_SYNC_PID="" WINDOW_REPORTER_PID="" window_report_generation="" keymap_active="false" @@ -201,9 +200,6 @@ cleanup() { if [ -n "$CLIPBOARD_PID" ]; then kill "$CLIPBOARD_PID" 2>/dev/null || true fi - if [ -n "$FILE_SYNC_PID" ]; then - kill "$FILE_SYNC_PID" 2>/dev/null || true - fi stop_window_reporter rm -f "$INJECT_LOCK" "$INJECT_LOCK.completed" "${DROP_INJECT_LOCK:-}" 2>/dev/null || true } @@ -556,14 +552,10 @@ apply_host_config() { fi printf '%s %s\n' "$upload_files" "$archive_bytes" > "$TMP_DIR/clip_file_config.tmp" && mv -f "$TMP_DIR/clip_file_config.tmp" "$TMP_DIR/clip_file_config" - previous_keymap_active="$keymap_active" - sync_keymap_carrier "$cfg_json" - if [ "$keymap_active" != "$previous_keymap_active" ]; then - report_status - fi sync_drive_mounts "$cfg_json" folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') sync_folder_mounts "${folders_count:-0}" + sync_keymap_carrier "$cfg_json" sync_timezone "$cfg_json" if printf '%s' "$cfg_json" | grep -q '"prevent_sleep"[[:space:]]*:[[:space:]]*true'; then if [ -z "$CAFFEINATE_PID" ] || ! kill -0 "$CAFFEINATE_PID" 2>/dev/null; then @@ -1417,37 +1409,24 @@ text_input_loop() { done } -file_sync_loop() { - trap 'exit 0' INT TERM - while :; do - if IFS= read -r file_sync_mode 2>/dev/null < "$TMP_DIR/mount_mode" && - [ "$file_sync_mode" != "webdav" ]; then - load_conf - sync_files - fi - sleep 4 - done -} - text_input_loop & TEXT_INPUT_PID=$! drop_events_loop & DROP_EVENTS_PID=$! clipboard_loop & CLIPBOARD_PID=$! -file_sync_loop & -FILE_SYNC_PID=$! while :; do if [ $((tick % 5)) -eq 0 ]; then load_conf apply_host_config ensure_webdav_mount - printf '%s\n' "$mount_mode" > "$TMP_DIR/mount_mode.tmp" && - mv -f "$TMP_DIR/mount_mode.tmp" "$TMP_DIR/mount_mode" ensure_drop_webdav_mount report_status fi + if [ "$mount_mode" != "webdav" ] && [ $((tick % 2)) -eq 0 ]; then + sync_files + fi tick=$((tick + 1)) sleep 2 done diff --git a/internal/guesttools/keymap_agent_test.go b/internal/guesttools/keymap_agent_test.go index 8d1edab..34c3933 100644 --- a/internal/guesttools/keymap_agent_test.go +++ b/internal/guesttools/keymap_agent_test.go @@ -26,67 +26,6 @@ func TestGuestAgentKeymapScript(t *testing.T) { if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":`+strconv.Itoa(CurrentAgentVersion)+`,\"keymap_active\":$keymap_active`) { t.Fatal("missing guest keymap script or current agent version in status") } - t.Run("config_reports_keymap_before_mounts", func(t *testing.T) { - lockShellFixture(t) - fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") + - scriptSection(t, agent, "apply_host_config() {", "\nreport_status() {") + ` -REIMS_HOST_URL=http://stub -REIMS_TOKEN=token -TMP_DIR=. -curl() { printf '{"keymap_carrier_enabled":%s}' "$enabled"; } -sync_window_reporter() { :; } -sync_timezone() { :; } -report_status() { printf 'status %s\n' "$keymap_active"; } -sync_drive_mounts() { printf 'drives\n'; } -sync_folder_mounts() { printf 'folders\n'; } -enabled=true -apply_host_config -apply_host_config -enabled=false -apply_host_config -` - cmd := exec.Command(sh, "-s") - cmd.Dir = t.TempDir() - cmd.Stdin = strings.NewReader(fixture) - const want = "status true\ndrives\nfolders\ndrives\nfolders\nstatus false\ndrives\nfolders\n" - if out, err := cmd.CombinedOutput(); err != nil || string(out) != want { - t.Fatalf("config order = %q, %v; want %q", out, err, want) - } - }) - t.Run("file_sync_worker", func(t *testing.T) { - lockShellFixture(t) - cleanup := scriptSection(t, agent, "\ncleanup() {", "\ntrap cleanup EXIT") - startup := scriptSection(t, agent, "\ntext_input_loop &", "\nwhile :; do") - _, main, _ := strings.Cut(agent, startup) - if !strings.Contains(startup, "file_sync_loop &\nFILE_SYNC_PID=$!") || - !strings.Contains(cleanup, `kill "$FILE_SYNC_PID"`) || strings.Contains(main, "sync_files") || - !strings.Contains(main, `mv -f "$TMP_DIR/mount_mode.tmp" "$TMP_DIR/mount_mode"`) { - t.Fatal("file sync must run in a background worker with mount mode updates and cleanup") - } - fixture := "set -eu\n" + scriptSection(t, agent, "file_sync_loop() {", "\ntext_input_loop &") + ` -TMP_DIR=. -polls=0 -load_conf() { printf 'config\n'; } -sync_files() { printf 'sync\n'; } -sleep() { - [ "$1" = 4 ] - polls=$((polls + 1)) - case "$polls" in - 1) printf 'webdav\n' > mount_mode ;; - 2) printf 'sync\n' > mount_mode ;; - 3) printf 'webdav\n' > mount_mode ;; - 4) exit ;; - esac -} -file_sync_loop -` - cmd := exec.Command(sh, "-s") - cmd.Dir = t.TempDir() - cmd.Stdin = strings.NewReader(fixture) - if out, err := cmd.CombinedOutput(); err != nil || string(out) != "config\nsync\n" { - t.Fatalf("worker should sync only in fallback mode: %q, %v", out, err) - } - }) for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} { t.Run(input, func(t *testing.T) { t.Parallel() @@ -183,7 +122,6 @@ PATH="/usr/bin:/bin:$PATH" CAFFEINATE_PID= TEXT_INPUT_PID= CLIPBOARD_PID= -FILE_SYNC_PID= INJECT_LOCK=./injecting keymap_active=false keymap_applied=false @@ -227,8 +165,12 @@ func TestKeymapCarrierStatusHandshake(t *testing.T) { if !strings.Contains(w.Body.String(), `"keymap_carrier_enabled":true`) { t.Fatalf("guest config = %s", w.Body) } - postStatus := func(body string) { - t.Helper() + for _, body := range []string{ + `{"agent_version":9,"keymap_active":true}`, + `{"agent_version":10,"keymap_active":true}`, + `{"agent_version":10,"keymap_active":true}`, + `{"agent_version":10,"keymap_active":false}`, + } { req := httptest.NewRequest("POST", "/v1/status", strings.NewReader(body)) req.Header.Set("Authorization", "Bearer token") w := httptest.NewRecorder() @@ -237,48 +179,7 @@ func TestKeymapCarrierStatusHandshake(t *testing.T) { t.Fatalf("status = %d: %s", w.Code, w.Body) } } - for _, body := range []string{ - `{"agent_version":9,"keymap_active":true}`, - `{"agent_version":10,"keymap_active":true}`, - `{"agent_version":10,"keymap_active":true}`, - `{"agent_version":10,"keymap_active":false}`, - } { - postStatus(body) - } if len(statuses) != 3 || statuses[0] || !statuses[1] || statuses[2] { t.Fatalf("callbacks = %v", statuses) } - - const active = `{"agent_version":10,"keymap_active":true}` - const inactive = `{"agent_version":10,"keymap_active":false}` - const maxAge = 30 * time.Second - check := func(connected, keymapActive bool) { - t.Helper() - got := srv.Status("mac", maxAge) - if got.Connected != connected || got.KeymapActive != keymapActive { - t.Fatalf("connected/keymap active = %t/%t, want %t/%t", got.Connected, got.KeymapActive, connected, keymapActive) - } - } - postStatus(active) - vm := srv.vms[normalizeVMRegistryKey("mac")] - vm.lastStatus = time.Now().Add(-2 * time.Minute) - srv.touchLastSeen("mac") - check(true, true) - - vm.lastSeen = vm.lastStatus - check(false, false) - statuses = nil - postStatus(active) - check(true, true) - postStatus(inactive) - check(true, false) - if len(statuses) != 2 || !statuses[0] || statuses[1] { - t.Fatalf("callbacks after reconnect and disable = %v", statuses) - } - - postStatus(active) - srv.SetKeymapCarrier("mac", false) - check(true, false) - srv.SetKeymapCarrier("mac", true) - check(true, false) } diff --git a/internal/guesttools/keymap_status_test.go b/internal/guesttools/keymap_status_test.go new file mode 100644 index 0000000..13e0ae7 --- /dev/null +++ b/internal/guesttools/keymap_status_test.go @@ -0,0 +1,80 @@ +package guesttools + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestKeymapConfirmationFollowsGuestConnection(t *testing.T) { + for _, agentVersion := range []int{14, CurrentAgentVersion} { + t.Run(fmt.Sprintf("agent_%d", agentVersion), func(t *testing.T) { + srv := NewTransportServer(nil) + cfg := VMConfig{VMName: "mac", Token: "token", SharedDir: t.TempDir()} + srv.RegisterVM(cfg) + srv.SetKeymapCarrier(cfg.VMName, true) + + request := func(handler http.HandlerFunc, method, path, body string) { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Authorization", "Bearer "+cfg.Token) + w := httptest.NewRecorder() + handler(w, req) + if w.Code != http.StatusOK { + t.Fatalf("%s %s: status %d: %s", method, path, w.Code, w.Body) + } + } + report := func(active bool) { + t.Helper() + body := fmt.Sprintf(`{"mount_mode":"sync","agent_version":%d,"keymap_active":%t}`, agentVersion, active) + request(srv.handleStatus, http.MethodPost, "/v1/status", body) + } + check := func(connected, active bool) { + t.Helper() + got := srv.Status(cfg.VMName, KeymapStatusMaxAge) + if got.Connected != connected || got.KeymapActive != active { + t.Fatalf("guest connected/keymap active = %t/%t, want %t/%t", got.Connected, got.KeymapActive, connected, active) + } + } + + report(true) + check(true, true) + + // The guest can still be handling files after its last status report expires. + srv.mu.Lock() + vm := srv.vms[normalizeVMRegistryKey(cfg.VMName)] + vm.lastStatus = time.Now().Add(-2 * KeymapStatusMaxAge) + vm.lastSeen = time.Now().Add(-KeymapStatusMaxAge / 2) + srv.mu.Unlock() + request(srv.handleListFiles, http.MethodGet, "/v1/files", "") + check(true, true) + + // A resumed connection without a fresh report cannot restore the mapping. + srv.mu.Lock() + vm.lastSeen = time.Now().Add(-2 * KeymapStatusMaxAge) + srv.mu.Unlock() + check(false, false) + request(srv.handleConfig, http.MethodGet, "/v1/config", "") + check(true, false) + report(true) + check(true, true) + report(false) + check(true, false) + + report(true) + srv.SetKeymapCarrier(cfg.VMName, false) + srv.SetKeymapCarrier(cfg.VMName, true) + check(true, false) + report(true) + cfg.Token = "replacement" + srv.RegisterVM(cfg) + request(srv.handleConfig, http.MethodGet, "/v1/config", "") + check(true, false) + report(true) + check(true, true) + }) + } +} diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 8772f39..a56974c 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -45,6 +45,9 @@ const ( const bridgeProtocolVersion = 4 +// KeymapStatusMaxAge is the maximum idle time of a confirmed keymap session. +const KeymapStatusMaxAge = 30 * time.Second + // ErrGuestToolsNotConnected is returned when a guest-assisted operation // requires a live Guest Tools agent inside macOS. var ErrGuestToolsNotConnected = errors.New("guest tools not connected") @@ -268,7 +271,7 @@ type registeredVM struct { resolvedFolders map[string]ResolvedSharedFolder verifyFolderRoot func(*os.Root, ResolvedSharedFolder) error keymapCarrierEnabled bool - keymapActive bool + keymapActive bool // Carrier confirmed by a status report since the last disconnect. lastStatus time.Time mountMode string sleepActive bool @@ -591,6 +594,7 @@ func (s *Server) RegisterVM(cfg VMConfig) { } else if cur.token != cfg.Token { cur.dropShares.revokeClipboard() s.clearVMClipFilesLocked(key) + cur.keymapActive = false cur.windowReportGen = 0 cur.windowReport = windowReport{} cur.clipboardDelivery = guestClipboardDelivery{} @@ -889,7 +893,7 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { HostDNSActive: dnsReported && vm.hostDNSActive, HostDNSReported: dnsReported, HostDNSConfigStale: dnsReported && vm.hostDNSConfigStale, - KeymapActive: connected && !vm.lastStatus.IsZero() && vm.keymapCarrierEnabled && vm.keymapActive, + KeymapActive: connected && vm.keymapActive, Connected: connected, MountMode: vm.mountMode, PreventSleep: vm.preventSleep, @@ -918,11 +922,19 @@ func (s *Server) SetStatusChangeHandler(fn func(vmName string)) { s.onStatusChange = fn } +func (vm *registeredVM) markSeen(now time.Time) { + // After a disconnected session, require the agent to confirm the mapping again. + if now.Sub(vm.lastSeen) > KeymapStatusMaxAge { + vm.keymapActive = false + } + vm.lastSeen = now +} + func (s *Server) touchLastSeen(vmName string) { vmName = normalizeVMRegistryKey(vmName) s.mu.Lock() if vm := s.vms[vmName]; vm != nil { - vm.lastSeen = time.Now() + vm.markSeen(time.Now()) } s.mu.Unlock() } @@ -953,7 +965,7 @@ func (s *Server) authenticateToken(tok string) *registeredVM { defer s.mu.Unlock() for _, vm := range s.vms { if len(vm.token) == len(tok) && subtle.ConstantTimeCompare([]byte(vm.token), []byte(tok)) == 1 { - vm.lastSeen = time.Now() + vm.markSeen(time.Now()) // A snapshot of the plain fields only: copying *vm would copy // injectMu and alias the text queues. Handlers that need the // queues look the live VM up again by name under s.mu. @@ -1098,10 +1110,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { var notify func(string) if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token { now := time.Now() + cur.markSeen(now) active := cur.keymapCarrierEnabled && req.KeymapActive && req.AgentVersion >= KeymapAgentVersion - // Authentication already refreshed lastSeen. A gap in status reports - // also covers reconnects where the reported mapping did not change. - if cur.keymapActive != active || now.Sub(cur.lastStatus) > 30*time.Second { + if cur.keymapActive != active || now.Sub(cur.lastStatus) > KeymapStatusMaxAge { notify = s.onStatusChange } cur.keymapActive = active @@ -1119,7 +1130,6 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { if req.AgentVersion > 0 { cur.agentVersion = req.AgentVersion } - cur.lastSeen = time.Now() } s.mu.Unlock() w.WriteHeader(http.StatusOK) @@ -1571,7 +1581,7 @@ func (s *Server) handleTextInput(w http.ResponseWriter, r *http.Request) { item := cur.textQueue[0] cur.textQueue = cur.textQueue[1:] cur.textActive[item.id] = item - cur.lastSeen = time.Now() + cur.markSeen(time.Now()) cur.lastTextPoll = time.Now() s.mu.Unlock()