From 81f0d6c031376a25974ac1f6c7ac331f03485e9c Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Thu, 12 Nov 2026 11:03:57 +0100 Subject: [PATCH] Fix(server,client): keep web terminal alive across heartbeat reconnects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Go server answered TOKEN_HEARTBEAT with a 33-byte CMD_HEARTBEAT_ACK, while the Linux and Android clients gate the ACK on 1 + sizeof(HeartbeatACK) (1025 bytes) and silently drop anything shorter. Their application-level ACK watchdog therefore never got fed and disconnected the main connection every 60s. Each re-login replaced the whole hub.Device, wiping the screen/shell sub-conn bindings that ride their own TCP connections, so a web terminal kept receiving shell output while every keystroke was dropped — the "terminal goes unresponsive after a while" symptom — and the shell could no longer be torn down (orphan bash + leaked sockets). Clients now accept the 32-byte old ACK (Windows already did), and the server sends the full 1024-byte struct. Hub.Register carries the sub-conn session state across a re-login, and the disconnect cleanup is pinned to the connection it belongs to so a stale OnDisconnect cannot tear down a registration that has already replaced it. A shell sub-conn that can no longer be bound now tells the viewer instead of leaving the pane waiting. Verified on aa: RTT restored, zero "Heartbeat ACK timeout" lines, main-conn port stable; Go build/vet/test pass. Server deploy to the Go host is still pending, so un-upgraded clients will keep reconnecting until then. Co-Authored-By: deepseek-flash --- android/app/src/main/cpp/main.cpp | 12 +- linux/main.cpp | 18 ++- macos/main.mm | 18 ++- server/go/cmd/heartbeat_ack_test.go | 35 +++++ server/go/cmd/main.go | 64 ++++++--- server/go/hub/hub.go | 101 +++++++++++-- server/go/hub/register_session_test.go | 190 +++++++++++++++++++++++++ server/go/protocol/commands.go | 20 +++ 8 files changed, 412 insertions(+), 46 deletions(-) create mode 100644 server/go/cmd/heartbeat_ack_test.go create mode 100644 server/go/hub/register_session_test.go diff --git a/android/app/src/main/cpp/main.cpp b/android/app/src/main/cpp/main.cpp index e6df668..d88b084 100644 --- a/android/app/src/main/cpp/main.cpp +++ b/android/app/src/main/cpp/main.cpp @@ -1484,9 +1484,15 @@ int DataProcess(void* /*user*/, PBYTE szBuffer, ULONG ulLength) } case CMD_HEARTBEAT_ACK: - if (ulLength >= 1 + (ULONG)sizeof(HeartbeatACK)) { - HeartbeatACK ack; - memcpy(&ack, szBuffer + 1, sizeof(HeartbeatACK)); + // 完整结构 1024 字节;老服务端 / Go 服务端只回 HeartbeatACK_OldSize(32)。 + // 短包同样要喂 ACK 看门狗,否则每 60s 断开重连一次。Windows 端按 + // min(ulLength, 32) 兼容(KernelManager.cpp:2413)。 + if (ulLength >= 1 + (ULONG)HeartbeatACK_OldSize) { + HeartbeatACK ack = {}; + const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK)) + ? sizeof(HeartbeatACK) + : (size_t)(ulLength - 1); + memcpy(&ack, szBuffer + 1, copyLen); uint64_t now = GetUnixMs(); g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed); int64_t rtt = (int64_t)now - (int64_t)ack.Time; diff --git a/linux/main.cpp b/linux/main.cpp index 364dd4b..ed0974d 100644 --- a/linux/main.cpp +++ b/linux/main.cpp @@ -710,14 +710,22 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) Mprintf("** Screen preview thread failed: %s ***\n", e.what()); } } else if (szBuffer[0] == CMD_HEARTBEAT_ACK) { - if (ulLength >= 1 + sizeof(HeartbeatACK)) { - HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1); + // 必须同时认短包:完整结构是 1024 字节,但老服务端 / Go 服务端只回 + // HeartbeatACK_OldSize(32)。长度不足就当「没收到」会让下面的 ACK 看门狗 + // 每 60s 断开重连一次(表现为链路一直在抖、主连接端口不断变化)。 + // Windows 端同样按 min(ulLength, 32) 兼容,见 KernelManager.cpp:2413。 + if (ulLength >= 1 + HeartbeatACK_OldSize) { + HeartbeatACK ack = {}; // 短包时缺的字段保持 0(Authorization / ProcessingMs 等) + const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK)) + ? sizeof(HeartbeatACK) + : (size_t)(ulLength - 1); + memcpy(&ack, szBuffer + 1, copyLen); uint64_t now = GetUnixMs(); g_lastHeartbeatAckMs.store(now, std::memory_order_relaxed); // 喂应用层 ACK 看门狗 - int64_t total_rtt_ms = (int64_t)now - (int64_t)ack->Time; + int64_t total_rtt_ms = (int64_t)now - (int64_t)ack.Time; int64_t rtt_ms = total_rtt_ms; - if (ack->ProcessingMs > 0 && (int64_t)ack->ProcessingMs < total_rtt_ms) - rtt_ms = total_rtt_ms - (int64_t)ack->ProcessingMs; + if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < total_rtt_ms) + rtt_ms = total_rtt_ms - (int64_t)ack.ProcessingMs; g_rttEstimator.update_from_sample((double)rtt_ms); // 心跳节奏太密日志会刷屏;最多 60s 一行 static time_t lastAckLog = 0; diff --git a/macos/main.mm b/macos/main.mm index cfdae78..406eff8 100644 --- a/macos/main.mm +++ b/macos/main.mm @@ -813,13 +813,21 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) Mprintf("** [%p] V2 File recv error: %d ***\n", user, result); } } else if (szBuffer[0] == CMD_HEARTBEAT_ACK) { - if (ulLength >= 1 + sizeof(HeartbeatACK)) { - HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1); + // 必须同时认短包:完整结构是 1024 字节,但老服务端 / Go 服务端只回 + // HeartbeatACK_OldSize(32)。按 sizeof 卡长度的话 RTT 永远不更新(心跳里 + // Ping 恒为 0),Windows 端按 min(ulLength, 32) 兼容,见 KernelManager.cpp:2413。 + // macOS 没有 ACK 看门狗,不会因此断线重连,但 RTT 会被饿死。 + if (ulLength >= 1 + HeartbeatACK_OldSize) { + HeartbeatACK ack = {}; // 短包时缺的字段保持 0(Authorization / ProcessingMs 等) + const size_t copyLen = (ulLength - 1 >= sizeof(HeartbeatACK)) + ? sizeof(HeartbeatACK) + : (size_t)(ulLength - 1); + memcpy(&ack, szBuffer + 1, copyLen); uint64_t now = GetUnixMs(); - int64_t total_rtt_ms = (int64_t)now - (int64_t)ack->Time; + int64_t total_rtt_ms = (int64_t)now - (int64_t)ack.Time; int64_t rtt_ms = total_rtt_ms; - if (ack->ProcessingMs > 0 && (int64_t)ack->ProcessingMs < total_rtt_ms) - rtt_ms = total_rtt_ms - (int64_t)ack->ProcessingMs; + if (ack.ProcessingMs > 0 && (int64_t)ack.ProcessingMs < total_rtt_ms) + rtt_ms = total_rtt_ms - (int64_t)ack.ProcessingMs; g_rttEstimator.update_from_sample((double)rtt_ms); // Log at most once per minute static uint64_t lastLogTime = 0; diff --git a/server/go/cmd/heartbeat_ack_test.go b/server/go/cmd/heartbeat_ack_test.go new file mode 100644 index 0000000..8e7dde0 --- /dev/null +++ b/server/go/cmd/heartbeat_ack_test.go @@ -0,0 +1,35 @@ +package main + +import ( + "encoding/binary" + "testing" + + "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" +) + +// The Linux and Android clients only accept a heartbeat ACK when +// `ulLength >= 1 + sizeof(HeartbeatACK)` == 1025 bytes and silently ignore a +// shorter packet, so the 60s ACK watchdog never gets fed and the client +// reconnects forever. A 33-byte reply here did exactly that on the Go server +// (linux/main.cpp:2107 "Heartbeat ACK timeout: 60007 ms ... reconnecting", +// once a minute, with the terminal session dying on every reconnect). +func TestBuildHeartbeatACKIsFullSize(t *testing.T) { + const hbTime = uint64(0x1122334455667788) + resp := buildHeartbeatACK(hbTime, 2) + + if want := 1 + 1024; len(resp) != want { + t.Fatalf("ACK length = %d, want %d (shorter packets are ignored by the client)", len(resp), want) + } + if resp[0] != protocol.CommandHeartbeat { + t.Fatalf("cmd byte = %d, want %d", resp[0], protocol.CommandHeartbeat) + } + if got := binary.LittleEndian.Uint64(resp[1+protocol.HeartbeatACKOffTime:]); got != hbTime { + t.Fatalf("echoed Time = %#x, want %#x", got, hbTime) + } + if got := resp[1+protocol.HeartbeatACKOffAuthorized]; got != 2 { + t.Fatalf("Authorized = %d, want 2", got) + } + if got := binary.LittleEndian.Uint32(resp[1+protocol.HeartbeatACKOffProcessing:]); got != 0 { + t.Fatalf("ProcessingMs = %d, want 0 (unknown => plain now-Time RTT)", got) + } +} diff --git a/server/go/cmd/main.go b/server/go/cmd/main.go index 15c3805..aaec708 100644 --- a/server/go/cmd/main.go +++ b/server/go/cmd/main.go @@ -71,9 +71,15 @@ func (h *MyHandler) OnDisconnect(ctx *connection.Context) { // device-offline event, instead of frames/output continuing to // stream from orphaned sub-conn ctxs until they time out on // their own. Both calls no-op if there's no active session. - h.hub.CloseScreen(info.ClientID) - h.hub.CloseTerminalSession(info.ClientID) - h.hub.Unregister(info.ClientID) + // + // Use the *Pinned variants: this runs concurrently with a re-login + // on a fresh connection, and the plain versions would tear down the + // sessions Register just carried over (and Unregister by ID alone + // would delete the device that just re-registered, hiding a live + // client until its next reconnect). + h.hub.CloseScreenPinned(info.ClientID, ctx) + h.hub.CloseTerminalSessionPinned(info.ClientID, ctx) + h.hub.UnregisterPinned(info.ClientID, ctx) } } @@ -322,6 +328,16 @@ func (h *MyHandler) handleTerminalStart(ctx *connection.Context, isPTY bool) { } else { h.log.Warn("orphan terminal sub-conn: device=%s conn=%d isPTY=%v", devID, ctx.ID, isPTY) + // Genuine device, but no pending session: the term_open that + // spawned this shell was issued on a main conn that has since + // been replaced (Register deliberately does not carry + // terminalPending over, so the browser can retry). Tell the + // viewer instead of leaving the pane on "connecting" until it + // is closed by hand — the browser treats term_closed as the + // session being over and lets the user reopen it. + if mc != nil && mc.GetPeerIP() == ctx.GetPeerIP() { + h.hub.PublishTerminalClosed(devID, "reconnected") + } } ctx.Close() return @@ -696,10 +712,9 @@ func (h *MyHandler) handleAuth(ctx *connection.Context, data []byte) { // - offset 548: Passcode (44 bytes) // - offset 592: PwdHmac (8 bytes, uint64) // -// HeartbeatACK structure: -// - offset 0: Time (8 bytes, uint64) -// - offset 8: Authorized (1 byte, char) -// - offset 9: Reserved (23 bytes) +// The reply layout is HeartbeatACK (common/commands.h, 1024 bytes), rendered +// by buildHeartbeatACK from the offsets in protocol/commands.go — see the +// HeartbeatACKSize comment there for why the full size is mandatory. func (h *MyHandler) handleHeartbeat(ctx *connection.Context, data []byte) { // Parse Time from heartbeat request (offset 1, 8 bytes) @@ -768,27 +783,32 @@ func (h *MyHandler) handleHeartbeat(ctx *connection.Context, data []byte) { } } - // Build HeartbeatACK response: CMD_HEARTBEAT_ACK(1) + HeartbeatACK(32) - resp := make([]byte, 33) - resp[0] = protocol.CommandHeartbeat // CMD_HEARTBEAT_ACK = 216 - // Time at offset 1 (8 bytes, little-endian) - resp[1] = byte(hbTime) - resp[2] = byte(hbTime >> 8) - resp[3] = byte(hbTime >> 16) - resp[4] = byte(hbTime >> 24) - resp[5] = byte(hbTime >> 32) - resp[6] = byte(hbTime >> 40) - resp[7] = byte(hbTime >> 48) - resp[8] = byte(hbTime >> 56) - // Authorized at offset 9 (1 byte) - resp[9] = authorized - // Reserved[23] at offset 10 is already zero + resp := buildHeartbeatACK(hbTime, authorized) if err := h.srv.Send(ctx, resp); err != nil { h.log.Error("Failed to send heartbeat ACK to client %d: %v", ctx.ID, err) } } +// buildHeartbeatACK renders the CMD_HEARTBEAT_ACK reply: CMD_HEARTBEAT_ACK(1) +// + HeartbeatACK(1024). The packet MUST be the full struct size: clients +// deployed before 2026-11 only accept `ulLength >= 1 + sizeof(HeartbeatACK)` +// and silently ignore a shorter ACK, so a 33-byte reply left their 60s ACK +// watchdog unfed and made every such client reconnect forever. Current +// clients accept both sizes. The C++ server sends the same 1+1024 bytes +// (server/2015Remote/2015RemoteDlg.cpp). +// +// IsTrail / Authorization / ProcessingMs stay zero: clients sync the first two +// from CMD_MASTERSETTING, and ProcessingMs == 0 means "unknown", so the client +// computes RTT as plain now-Time (its behaviour before that field existed). +func buildHeartbeatACK(hbTime uint64, authorized byte) []byte { + resp := make([]byte, 1+protocol.HeartbeatACKSize) + resp[0] = protocol.CommandHeartbeat // CMD_HEARTBEAT_ACK = 216 + binary.LittleEndian.PutUint64(resp[1+protocol.HeartbeatACKOffTime:], hbTime) + resp[1+protocol.HeartbeatACKOffAuthorized] = authorized + return resp +} + // parsePorts parses a semicolon-separated port string and returns port numbers func parsePorts(portStr string) ([]int, error) { var ports []int diff --git a/server/go/hub/hub.go b/server/go/hub/hub.go index fafa2fe..fc097e8 100644 --- a/server/go/hub/hub.go +++ b/server/go/hub/hub.go @@ -471,6 +471,32 @@ func (h *Hub) Register(d *Device, conn *connection.Context) { } d.conn = conn h.mu.Lock() + // A reconnecting client logs in with a *fresh* Device struct, so every + // sub-conn-scoped field would come back zeroed even though the sub-conns + // themselves (screen / shell) ride their own TCP connections and normally + // survive a main-conn reconnect. Dropping them silently breaks live views: + // - terminal: SendToTerminal returns ErrDeviceOffline for every keystroke + // (handleTermInput ignores the error) while output keeps streaming the + // other way — the browser looks connected but typing does nothing, and + // CloseTerminalSession can no longer tear the shell down (orphan shells + // + leaked sockets); + // - screen: the cached resolution / last IDR are lost, so a viewer that + // joins before the next IDR has nothing to decode. + // The carried bindings may themselves be dead if the whole network path + // went away; the sub-conn read timeout then reaps them through + // UnbindScreenConn / UnbindTerminalConn, which clears the same fields. + // Carry the session state over. UnbindScreenConn / UnbindTerminalConn still + // clear it when a sub-conn really is gone, and a genuine offline closes + // both sessions via the *Pinned disconnect helpers, which no-op if a + // re-login has already taken ownership of this ID. + if prev, ok := h.devices[d.ID]; ok { + d.screenConn = prev.screenConn + d.screenWidth, d.screenHeight = prev.screenWidth, prev.screenHeight + d.lastKeyframe = prev.lastKeyframe + d.cursorSeen, d.lastCursorIndex = prev.cursorSeen, prev.lastCursorIndex + d.lastCursorX, d.lastCursorY, d.cursorPubAt = prev.lastCursorX, prev.lastCursorY, prev.cursorPubAt + d.terminalConn, d.terminalIsPTY = prev.terminalConn, prev.terminalIsPTY + } h.devices[d.ID] = d info := deviceToInfo(d) h.mu.Unlock() @@ -482,19 +508,34 @@ func (h *Hub) Register(d *Device, conn *connection.Context) { // Unregister removes a device by ID. No-op if not present. // Subscribers are notified after the device is removed (only if it existed). func (h *Hub) Unregister(id string) { + h.unregister(id, nil) +} + +// UnregisterPinned is Unregister restricted to a device still pinned to main. +// The disconnect path MUST use this: the old main conn's OnDisconnect runs +// concurrently with a re-login, and deleting by ID alone would remove the +// device that just re-registered, leaving a live client invisible in the +// online list until it reconnects again. +func (h *Hub) UnregisterPinned(id string, main *connection.Context) bool { + return h.unregister(id, main) +} + +func (h *Hub) unregister(id string, main *connection.Context) bool { if id == "" { - return + return false } h.mu.Lock() - _, existed := h.devices[id] + d, existed := h.devices[id] + if !existed || (main != nil && d.conn != main) { + h.mu.Unlock() + return false + } delete(h.devices, id) h.mu.Unlock() - if !existed { - return - } for _, s := range h.snapshotSubscribers() { s.OnDeviceOffline(id) } + return true } // ListDevices returns a fresh snapshot slice. The caller may mutate it freely; @@ -594,11 +635,25 @@ func (h *Hub) PublishCursor(deviceID string, index byte, x, y int) { // The actual sub-conn teardown is delegated to retireScreenConn, which is // shared with BindScreenConn's replacement path. func (h *Hub) CloseScreen(deviceID string) { + h.closeScreenPinned(deviceID, nil) +} + +// CloseScreenPinned is CloseScreen restricted to a device that is still +// pinned to main. The main-conn teardown path uses it so a client that has +// already logged in again on a fresh connection is not stripped of the +// screen session Register just carried over to it. The ownership check and +// the detach happen under one hub lock, so a concurrent Register cannot slip +// in between. +func (h *Hub) CloseScreenPinned(deviceID string, main *connection.Context) bool { + return h.closeScreenPinned(deviceID, main) +} + +func (h *Hub) closeScreenPinned(deviceID string, main *connection.Context) bool { h.mu.Lock() d, ok := h.devices[deviceID] - if !ok { + if !ok || (main != nil && d.conn != main) { h.mu.Unlock() - return + return false } sc := d.screenConn d.screenConn = nil @@ -607,6 +662,7 @@ func (h *Hub) CloseScreen(deviceID string) { d.lastKeyframe = nil h.mu.Unlock() h.retireScreenConn(sc) + return true } // PublishResolution announces a new (or first-ever) screen geometry for a @@ -853,11 +909,22 @@ func (h *Hub) TerminalIsPTY(id string) bool { // send COMMAND_BYE, then close after a short grace period so the client's // IOCPClient reconnect logic doesn't fire. func (h *Hub) CloseTerminalSession(deviceID string) { + h.closeTerminalPinned(deviceID, nil) +} + +// CloseTerminalSessionPinned is CloseTerminalSession restricted to a device +// still pinned to main; see CloseScreenPinned for why the disconnect path +// needs the ownership check. +func (h *Hub) CloseTerminalSessionPinned(deviceID string, main *connection.Context) bool { + return h.closeTerminalPinned(deviceID, main) +} + +func (h *Hub) closeTerminalPinned(deviceID string, main *connection.Context) bool { h.mu.Lock() d, ok := h.devices[deviceID] - if !ok { + if !ok || (main != nil && d.conn != main) { h.mu.Unlock() - return + return false } tc := d.terminalConn // hadSession guards against firing spurious OnTerminalClosed events @@ -872,7 +939,7 @@ func (h *Hub) CloseTerminalSession(deviceID string) { h.mu.Unlock() if !hadSession { - return + return true } for _, s := range h.snapshotSubscribers() { @@ -880,7 +947,7 @@ func (h *Hub) CloseTerminalSession(deviceID string) { } if tc == nil { - return + return true } h.terminalIndexMu.Lock() delete(h.terminalIndex, tc) @@ -896,6 +963,18 @@ func (h *Hub) CloseTerminalSession(deviceID string) { time.Sleep(500 * time.Millisecond) c.Close() }(tc) + return true +} + +// PublishTerminalClosed tells terminal viewers the session is over without +// touching hub session state. Used when the device opens a shell sub-conn that +// cannot be bound because the terminal request it answers no longer exists +// (the main conn reconnected in between); otherwise the browser pane would +// wait on term_ready forever. +func (h *Hub) PublishTerminalClosed(deviceID, reason string) { + for _, s := range h.snapshotSubscribers() { + s.OnTerminalClosed(deviceID, reason) + } } // PublishTerminalData fans out one chunk of shell output to subscribers. diff --git a/server/go/hub/register_session_test.go b/server/go/hub/register_session_test.go new file mode 100644 index 0000000..b612960 --- /dev/null +++ b/server/go/hub/register_session_test.go @@ -0,0 +1,190 @@ +package hub + +import ( + "bytes" + "testing" + + "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" +) + +// A reconnecting client logs in with a fresh Device struct. Its screen / shell +// sub-conns ride their own TCP connections and survive the main-conn reconnect, +// so Register must carry the session state over — otherwise a web terminal goes +// dead on every reconnect: SendToTerminal returns ErrDeviceOffline for every +// keystroke (handleTermInput drops the error silently) while shell output keeps +// streaming, so the browser looks connected but typing does nothing, and the +// shell can no longer be torn down (orphan shells + leaked sockets). +func TestRegisterKeepsTerminalSession(t *testing.T) { + h := New() + var sent []*connection.Context + h.SetSender(func(ctx *connection.Context, data []byte) error { + sent = append(sent, ctx) + return nil + }) + + mainConn := &connection.Context{RemoteAddr: "10.0.0.1:1000"} + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, mainConn) + if err := h.OpenTerminalSession("dev"); err != nil { + t.Fatalf("OpenTerminalSession: %v", err) + } + term := &connection.Context{RemoteAddr: "10.0.0.1:1001"} + if !h.BindTerminalConn("dev", term, true) { + t.Fatal("BindTerminalConn rejected the pending session") + } + + // Main conn drops and the client logs in again (fresh Device struct). + reconnected := &connection.Context{RemoteAddr: "10.0.0.1:1002"} + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, reconnected) + + if got := h.MainConn("dev"); got != reconnected { + t.Fatalf("MainConn = %p, want the reconnected ctx %p", got, reconnected) + } + sent = nil + if err := h.SendToTerminal("dev", []byte("ls\r")); err != nil { + t.Fatalf("SendToTerminal after re-register: %v (terminal binding was dropped)", err) + } + if len(sent) != 1 || sent[0] != term { + t.Fatalf("keystroke went to %v, want the bound shell sub-conn", sent) + } + if !h.TerminalIsPTY("dev") { + t.Fatal("terminalIsPTY lost across re-register (resize would be silently ignored)") + } + if got := h.TerminalDeviceID(term); got != "dev" { + t.Fatalf("TerminalDeviceID(shell) = %q, want dev (output would be parsed as commands)", got) + } +} + +// Same failure mode for the screen path: losing the cached geometry and last +// IDR leaves a viewer that joins right after the reconnect with nothing to +// decode until the device happens to emit the next IDR. +func TestRegisterKeepsScreenCache(t *testing.T) { + h := New() + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, + &connection.Context{RemoteAddr: "10.0.0.1:1000"}) + screen := &connection.Context{RemoteAddr: "10.0.0.1:1001"} + if !h.BindScreenConn("dev", screen) { + t.Fatal("BindScreenConn failed") + } + h.PublishResolution("dev", 1920, 1080) + keyframe := []byte{0xde, 0xad, 0xbe, 0xef} + h.PublishScreenFrame("dev", keyframe, true) + + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, + &connection.Context{RemoteAddr: "10.0.0.1:1002"}) + + st := h.ScreenState("dev") + if !st.Active { + t.Fatal("screen session marked inactive after re-register") + } + if st.Width != 1920 || st.Height != 1080 { + t.Fatalf("cached geometry = %dx%d, want 1920x1080", st.Width, st.Height) + } + if !bytes.Equal(st.Keyframe, keyframe) { + t.Fatalf("cached IDR = %x, want %x (late joiners would wait for the next IDR)", st.Keyframe, keyframe) + } +} + +// Once a sub-conn really goes away, its unbind must still clear the session so +// a later re-register cannot resurrect a stale binding. +func TestRegisterDoesNotReviveClosedSessions(t *testing.T) { + h := New() + h.SetSender(func(ctx *connection.Context, data []byte) error { return nil }) + + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, + &connection.Context{RemoteAddr: "10.0.0.1:1000"}) + if err := h.OpenTerminalSession("dev"); err != nil { + t.Fatalf("OpenTerminalSession: %v", err) + } + term := &connection.Context{RemoteAddr: "10.0.0.1:1001"} + if !h.BindTerminalConn("dev", term, true) { + t.Fatal("BindTerminalConn rejected the pending session") + } + h.UnbindTerminalConn(term) // shell sub-conn dropped + h.UnbindScreenConn(&connection.Context{RemoteAddr: "10.0.0.1:1003"}) // no-op, not bound + + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, + &connection.Context{RemoteAddr: "10.0.0.1:1002"}) + + if err := h.SendToTerminal("dev", []byte("ls\r")); err != ErrDeviceOffline { + t.Fatalf("SendToTerminal = %v, want ErrDeviceOffline (no session)", err) + } +} + +// The old main conn's OnDisconnect runs concurrently with a re-login. Its +// cleanup must be scoped to the connection it is about, otherwise the stale +// callback strips the sessions Register just carried over — and deleting by +// ID alone hides a live client until its next reconnect. +func TestStaleDisconnectCannotTearDownNewRegistration(t *testing.T) { + h := New() + h.SetSender(func(ctx *connection.Context, data []byte) error { return nil }) + + oldConn := &connection.Context{RemoteAddr: "10.0.0.1:1000"} + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, oldConn) + if err := h.OpenTerminalSession("dev"); err != nil { + t.Fatalf("OpenTerminalSession: %v", err) + } + term := &connection.Context{RemoteAddr: "10.0.0.1:1001"} + if !h.BindTerminalConn("dev", term, true) { + t.Fatal("BindTerminalConn failed") + } + if !h.BindScreenConn("dev", &connection.Context{RemoteAddr: "10.0.0.1:1003"}) { + t.Fatal("BindScreenConn failed") + } + + // Re-login lands first; the old conn's teardown runs afterwards. + newConn := &connection.Context{RemoteAddr: "10.0.0.1:1002"} + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, newConn) + + if h.CloseScreenPinned("dev", oldConn) { + t.Fatal("stale disconnect closed the screen session of the new registration") + } + if h.CloseTerminalSessionPinned("dev", oldConn) { + t.Fatal("stale disconnect closed the terminal session of the new registration") + } + if h.UnregisterPinned("dev", oldConn) { + t.Fatal("stale disconnect removed the re-registered device") + } + if got := h.MainConn("dev"); got != newConn { + t.Fatalf("MainConn = %p, want the new conn %p", got, newConn) + } + if !h.ScreenState("dev").Active { + t.Fatal("screen session lost to the stale disconnect") + } + if err := h.SendToTerminal("dev", []byte("ls\r")); err != nil { + t.Fatalf("SendToTerminal after stale disconnect: %v", err) + } + // The real owner can still clean up. + if !h.UnregisterPinned("dev", newConn) { + t.Fatal("UnregisterPinned rejected the owning main conn") + } + if h.MainConn("dev") != nil { + t.Fatal("device still registered after the owner's disconnect") + } +} + +// Only a *bound* session rides across a reconnect: a terminal request that +// never produced a shell sub-conn is re-issued by the browser instead of +// pinning the device "busy" forever. +func TestRegisterDoesNotCarryPendingTerminal(t *testing.T) { + h := New() + h.SetSender(func(ctx *connection.Context, data []byte) error { return nil }) + + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, + &connection.Context{RemoteAddr: "10.0.0.1:1000"}) + if err := h.OpenTerminalSession("dev"); err != nil { + t.Fatalf("OpenTerminalSession: %v", err) + } + if !h.IsTerminalPending("dev") { + t.Fatal("session should be pending after OpenTerminalSession") + } + + h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, + &connection.Context{RemoteAddr: "10.0.0.1:1002"}) + + if h.IsTerminalPending("dev") { + t.Fatal("pending request carried across re-register; device would stay 'busy' forever") + } + if err := h.OpenTerminalSession("dev"); err != nil { + t.Fatalf("retry after re-register: %v, want nil", err) + } +} diff --git a/server/go/protocol/commands.go b/server/go/protocol/commands.go index 0308969..a054ae2 100644 --- a/server/go/protocol/commands.go +++ b/server/go/protocol/commands.go @@ -134,6 +134,26 @@ const ( CmdSockDllLoader byte = 210 // SOCKET_DLLLOADER - shellcode/memory-DLL loader requests the full DLL payload ) +// HeartbeatACK (CMD_HEARTBEAT_ACK) response layout — mirrors the HeartbeatACK +// struct in common/commands.h, where sizeof(HeartbeatACK) == 1024. +// +// Size matters: clients deployed before 2026-11 gate the ACK on +// `ulLength >= 1 + sizeof(HeartbeatACK)` (1025 bytes) and silently drop +// anything shorter. That never feeds their application-level ACK watchdog, +// so they reconnect every 60s forever — a 33-byte reply here did exactly +// that on the Go server. Current clients accept both sizes (they clamp to +// min(ulLength-1, sizeof)), and the C++ server always sends 1+1024 +// (2015RemoteDlg.cpp), so the wire is 1+1024 for everyone. Windows was the +// only client tolerant of the short form from the start (KernelManager.cpp +// copies min(ulLength, 32)). +const ( + HeartbeatACKSize = 1024 + HeartbeatACKOffTime = 0 // uint64 LE — the request's Time, echoed back + HeartbeatACKOffAuthorized = 8 // byte — 0/1/2 (2 = authorized by admin) + HeartbeatACKOffIsTrail = 9 // byte — trial master + HeartbeatACKOffProcessing = 212 // uint32 LE — server-side processing time (ms) +) + // Sub-connection authentication (matches common/commands.h ConnAuth* structs). // Each newly-opened sub-conn first sends a 512-byte ConnAuthPacket, then waits // for a 256-byte ConnAuthAck before any further command is meaningful.