Add the terminal_close tool so a caller can release a shell session explicitly instead of waiting for it to age out. The tool is idempotent for the session it names, rejects a session_id that does not match the live session with -32002, and runs without the per-device lock so it can interrupt a terminal_exec call that is still polling on the same device. Give hub leases a generation counter: the generation is bumped when a pending lease is created and carried across a device re-login. MCP-side closes pass the generation, so a stale session can no longer tear down a shell a human operator opened after the device reconnected. The reaper runs on a 30 s ticker (shortened when TermIdle is smaller), skips sessions that are still opening, and reclaims idle sessions as well as commands overdue past the one-hour busy cap. The pre-bind terminal-close path in cmd no longer closes unconditionally; it touches only a pending lease, because an unbound sub-connection carries no lease identity and may be a stale orphan. Covered by unit tests for close semantics, lock exemption, reaper lifecycle and lease-generation ownership, plus a live run against a Debug ghost: close before and during a command, reopen, idle reap and mismatched-id rejection all behave as specified. Co-Authored-By: deepseek-flash
375 lines
12 KiB
Go
375 lines
12 KiB
Go
package mcp
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
|
|
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
|
|
)
|
|
|
|
// errNoDeviceHub means the endpoint was built without a device registry, so
|
|
// no shell can be opened. Mirrors the local tools' nil-Hub behaviour (-32000).
|
|
var errNoDeviceHub = errors.New("no device hub configured")
|
|
|
|
// terminalHub is the slice of *hub.Hub the session table needs. An interface
|
|
// keeps the table testable and documents that MCP never touches a terminal
|
|
// sub-connection directly — it goes through the hub's single-viewer lease.
|
|
type terminalHub interface {
|
|
OpenTerminalSessionLease(deviceID string) (uint64, error)
|
|
CloseTerminalSessionLease(deviceID string, lease uint64) bool
|
|
HasTerminalSession(deviceID string) bool
|
|
SendToTerminal(deviceID string, data []byte) error
|
|
}
|
|
|
|
// sessionTable owns the MCP-created terminal sessions, keyed by device. A
|
|
// session is created before hub.OpenTerminalSession so OnTerminalReady (which
|
|
// can fire on another goroutine as soon as the client answers) always finds
|
|
// the object; a failed open rolls the entry back.
|
|
type sessionTable struct {
|
|
hub terminalHub
|
|
|
|
mu sync.Mutex
|
|
byDevice map[string]*termSession
|
|
}
|
|
|
|
func newSessionTable(h terminalHub) *sessionTable {
|
|
return &sessionTable{hub: h, byDevice: make(map[string]*termSession)}
|
|
}
|
|
|
|
func (t *sessionTable) get(deviceID string) *termSession {
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
return t.byDevice[deviceID]
|
|
}
|
|
|
|
// errSessionClosed means the session disappeared while its open was in
|
|
// flight (shutdown or an explicit close raced it).
|
|
var errSessionClosed = errors.New("terminal session closed during open")
|
|
|
|
// open claims a shell for the device. ErrTerminalBusy comes back when a web
|
|
// console (or another MCP call) already holds it; the hub enforces the
|
|
// single-viewer lease, so v1 never pre-empts a human.
|
|
func (t *sessionTable) open(deviceID string) (*termSession, error) {
|
|
if t.hub == nil {
|
|
return nil, errNoDeviceHub
|
|
}
|
|
t.mu.Lock()
|
|
if _, ok := t.byDevice[deviceID]; ok {
|
|
t.mu.Unlock()
|
|
return nil, hub.ErrTerminalBusy
|
|
}
|
|
sess := newTermSession(deviceID)
|
|
// Until the hub call returns, any OnTerminalClosed for this device belongs
|
|
// to the viewer that just released the lease, not to this session.
|
|
sess.opening = true
|
|
t.byDevice[deviceID] = sess
|
|
t.mu.Unlock()
|
|
|
|
lease, err := t.hub.OpenTerminalSessionLease(deviceID)
|
|
if err != nil {
|
|
t.mu.Lock()
|
|
delete(t.byDevice, deviceID)
|
|
t.mu.Unlock()
|
|
sess.mu.Lock()
|
|
sess.opening = false
|
|
sess.closed = true
|
|
sess.closeReason = "open failed"
|
|
sess.cond.Broadcast()
|
|
sess.mu.Unlock()
|
|
return nil, err
|
|
}
|
|
|
|
sess.mu.Lock()
|
|
sess.opening = false
|
|
sess.lease = lease
|
|
sess.mu.Unlock()
|
|
|
|
// An explicit close (or shutdown) may have removed the entry while the hub
|
|
// call was in flight. The hub lease is ours by now, so release it instead
|
|
// of returning a session nobody can reach.
|
|
t.mu.Lock()
|
|
cur, ok := t.byDevice[deviceID]
|
|
t.mu.Unlock()
|
|
if !ok || cur != sess {
|
|
t.hub.CloseTerminalSessionLease(deviceID, lease)
|
|
return nil, errSessionClosed
|
|
}
|
|
return sess, nil
|
|
}
|
|
|
|
// ready records that the shell sub-conn is bound. Called from the hub's TCP
|
|
// read loop, so it must stay short (a mutex and a broadcast).
|
|
func (t *sessionTable) ready(deviceID string, isPTY bool) {
|
|
sess := t.get(deviceID)
|
|
if sess == nil {
|
|
return
|
|
}
|
|
sess.mu.Lock()
|
|
sess.isPTY = isPTY
|
|
sess.ready = true
|
|
sess.lastUsed = time.Now()
|
|
sess.cond.Broadcast()
|
|
sess.mu.Unlock()
|
|
}
|
|
|
|
// closed runs when the shell ends for any reason — device-side exit, sub-conn
|
|
// drop, or an explicit teardown. Waiters wake up and deliver whatever output
|
|
// is already buffered.
|
|
//
|
|
// A session with a command still in flight stays in the table even after the
|
|
// shell is gone: the bytes it produced but nobody has polled yet must remain
|
|
// reachable (MFC's closed branch keeps it for the same reason). The entry is
|
|
// dropped by forget once the tail is delivered, or by the M4c idle reaper if
|
|
// the model never comes back.
|
|
func (t *sessionTable) closed(deviceID, reason string) {
|
|
// A web console's teardown can race a fresh open: by the time this event is
|
|
// delivered, the hub lease may already belong to a new MCP session. The hub
|
|
// is the authority on whether a session still exists; if it does, the event
|
|
// described the previous viewer and must not touch ours.
|
|
if t.hub != nil && t.hub.HasTerminalSession(deviceID) {
|
|
return
|
|
}
|
|
t.mu.Lock()
|
|
defer t.mu.Unlock()
|
|
sess, ok := t.byDevice[deviceID]
|
|
if !ok {
|
|
return
|
|
}
|
|
sess.mu.Lock()
|
|
defer sess.mu.Unlock()
|
|
if sess.opening {
|
|
// Our own hub call has not returned yet, so any close for this device
|
|
// still refers to whoever held the lease before us.
|
|
return
|
|
}
|
|
if !sess.hasUndrainedLocked() {
|
|
delete(t.byDevice, deviceID)
|
|
}
|
|
sess.closed = true
|
|
sess.closeReason = reason
|
|
sess.cond.Broadcast()
|
|
}
|
|
|
|
// hasUndrainedLocked reports whether the in-flight command still has output the
|
|
// client has not received. An ended shell delivers everything up to total, so a
|
|
// running command's undelivered bytes all count.
|
|
func (s *termSession) hasUndrainedLocked() bool {
|
|
p := s.pending
|
|
if p == nil {
|
|
return false
|
|
}
|
|
end := s.total
|
|
if p.done {
|
|
end = min(p.outputEnd, s.total)
|
|
}
|
|
return s.delivered < end
|
|
}
|
|
|
|
// forget removes a session whose shell is already gone. It must not call the
|
|
// hub: the device may have reconnected and a new viewer may hold a fresh shell
|
|
// by now.
|
|
func (t *sessionTable) forget(deviceID string, want *termSession) {
|
|
t.mu.Lock()
|
|
if t.byDevice[deviceID] == want {
|
|
delete(t.byDevice, deviceID)
|
|
}
|
|
t.mu.Unlock()
|
|
}
|
|
|
|
// closeSession tears down the MCP-owned session for deviceID, if any. It is
|
|
// idempotent: a call for a device MCP does not own returns false and leaves
|
|
// the web console's session alone.
|
|
func (t *sessionTable) closeSession(deviceID string) bool {
|
|
return t.closeSessionIf(deviceID, nil)
|
|
}
|
|
|
|
// closeSessionIf closes the device's session only if the table still holds
|
|
// exactly want. The identity check matters for sweepIdle: between its scan
|
|
// and the close, the stale session can be replaced by a fresh one.
|
|
func (t *sessionTable) closeSessionIf(deviceID string, want *termSession) bool {
|
|
return t.closeIf(deviceID, want, func(*termSession) string { return "closed" })
|
|
}
|
|
|
|
// closeIf closes a session if decide says so. decide runs with both locks held
|
|
// (table then session), so it must read only session fields and lock nothing:
|
|
// the staleness reaper uses it to re-check under the same lock that deletes,
|
|
// closing the scan-then-close window where a poll could refresh the session.
|
|
// A returned "" cancels the close and nothing is touched.
|
|
func (t *sessionTable) closeIf(deviceID string, want *termSession, decide func(*termSession) string) bool {
|
|
t.mu.Lock()
|
|
sess, ok := t.byDevice[deviceID]
|
|
if !ok || (want != nil && sess != want) {
|
|
t.mu.Unlock()
|
|
return false
|
|
}
|
|
sess.mu.Lock()
|
|
reason := decide(sess)
|
|
if reason == "" {
|
|
sess.mu.Unlock()
|
|
t.mu.Unlock()
|
|
return false
|
|
}
|
|
delete(t.byDevice, deviceID)
|
|
wasClosed := sess.closed
|
|
lease := sess.lease
|
|
sess.closed = true
|
|
sess.closeReason = reason
|
|
sess.cond.Broadcast()
|
|
sess.mu.Unlock()
|
|
t.mu.Unlock()
|
|
// A session that was already closed lost its hub lease when the close event
|
|
// arrived; the hub may since have handed a fresh shell to another viewer (a
|
|
// reconnected device). Only an explicit close of a live session may touch
|
|
// it, and even then only the lease MCP itself opened (the generation check
|
|
// in the hub), never whatever lease the device holds now.
|
|
if t.hub != nil && !wasClosed && lease != 0 {
|
|
t.hub.CloseTerminalSessionLease(deviceID, lease)
|
|
}
|
|
return true
|
|
}
|
|
|
|
// termBusyMax bounds how long one command may hold a session with nobody
|
|
// polling it. Without it a hung command — or a model that never comes back —
|
|
// would lock the device's single terminal slot forever. MFC reclaims at the
|
|
// same one-hour limit (McpServer.cpp:4674).
|
|
const termBusyMax = time.Hour
|
|
|
|
// sweepIdle closes sessions whose last use is older than idle, plus live
|
|
// commands that outlived termBusyMax. Intended for the periodic reaper: a
|
|
// model that forgets terminal_close must not lock a human out of the device's
|
|
// shell.
|
|
//
|
|
// A session with a live command (pending, not done) is skipped no matter how
|
|
// quiet it is: a sleep or a slow download still owns the lease and must not be
|
|
// reaped just because it printed nothing for a while. A session whose shell is
|
|
// already gone is reaped on idle alone — its only remaining value is the
|
|
// undelivered tail, and a model that never polls it must not pin the slot.
|
|
// A session that never became ready is left alone: its open is still waiting
|
|
// on a caller, which releases it (with a lease-checked close) on its own.
|
|
func (t *sessionTable) sweepIdle(now time.Time, idle time.Duration) int {
|
|
type entry struct {
|
|
id string
|
|
sess *termSession
|
|
}
|
|
var candidates []entry
|
|
t.mu.Lock()
|
|
for id, sess := range t.byDevice {
|
|
candidates = append(candidates, entry{id, sess})
|
|
}
|
|
t.mu.Unlock()
|
|
|
|
n := 0
|
|
for _, e := range candidates {
|
|
if t.closeIf(e.id, e.sess, func(s *termSession) string {
|
|
return s.reclaimReasonLocked(now, idle)
|
|
}) {
|
|
n++
|
|
}
|
|
}
|
|
return n
|
|
}
|
|
|
|
// reclaimReasonLocked returns why the session should be dropped, or "" to keep
|
|
// it. Callers hold s.mu.
|
|
func (s *termSession) reclaimReasonLocked(now time.Time, idle time.Duration) string {
|
|
inactive := func() string {
|
|
return fmt.Sprintf(
|
|
"Terminal session was reclaimed after %s of inactivity; call terminal_exec again to open a new one", idle)
|
|
}
|
|
if !s.ready {
|
|
// Still waiting for the shell to bind; a caller holds this session and
|
|
// releases it when its own wait ends. Reaping here would kill a live
|
|
// open (and, if the lease changed hands meanwhile, someone else's).
|
|
return ""
|
|
}
|
|
if s.closed {
|
|
if now.Sub(s.lastUsed) >= idle {
|
|
return inactive()
|
|
}
|
|
return ""
|
|
}
|
|
if p := s.pending; p != nil && !p.done {
|
|
if now.Sub(p.busySince) >= termBusyMax {
|
|
return fmt.Sprintf(
|
|
"Terminal session was reclaimed after the command ran longer than %s; call terminal_exec again to open a new one", termBusyMax)
|
|
}
|
|
return ""
|
|
}
|
|
if now.Sub(s.lastUsed) >= idle {
|
|
return inactive()
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// closeAll drops every session; used at shutdown. The hub teardown is still
|
|
// best-effort because the TCP servers may already be stopping.
|
|
func (t *sessionTable) closeAll() {
|
|
t.mu.Lock()
|
|
ids := make([]string, 0, len(t.byDevice))
|
|
for id := range t.byDevice {
|
|
ids = append(ids, id)
|
|
}
|
|
t.mu.Unlock()
|
|
for _, id := range ids {
|
|
t.closeSession(id)
|
|
}
|
|
}
|
|
|
|
// sessionIDFallback numbers ids when crypto/rand is unavailable. It is only a
|
|
// last resort: ids are opaque to clients, and uniqueness matters, not secrecy.
|
|
var sessionIDFallback atomic.Uint32
|
|
|
|
func newSessionID() string {
|
|
var b [3]byte
|
|
if _, err := rand.Read(b[:]); err == nil {
|
|
return "s-" + hex.EncodeToString(b[:])
|
|
}
|
|
return fmt.Sprintf("s-%06x", sessionIDFallback.Add(1)&0xffffff)
|
|
}
|
|
|
|
// Server implements hub.EventHandler so the endpoint can observe shell
|
|
// traffic. Only the terminal events do work; the screen and lifecycle events
|
|
// are ignored (the web console owns those views).
|
|
var _ hub.EventHandler = (*Server)(nil)
|
|
|
|
func (s *Server) OnDeviceOnline(hub.DeviceInfo) {}
|
|
func (s *Server) OnDeviceOffline(string) {}
|
|
func (s *Server) OnDeviceUpdate(string, int, string) {}
|
|
func (s *Server) OnScreenFrame(string, []byte, bool) {}
|
|
func (s *Server) OnResolutionChange(string, int, int) {}
|
|
func (s *Server) OnCursorChange(string, byte, int, int) {}
|
|
func (s *Server) OnClipboardText(string, string) {}
|
|
func (s *Server) OnTerminalReady(deviceID string, isPTY bool) { s.sessions.ready(deviceID, isPTY) }
|
|
func (s *Server) OnTerminalClosed(deviceID, reason string) { s.sessions.closed(deviceID, reason) }
|
|
|
|
// OnTerminalData runs on the device's TCP read loop. It must never block:
|
|
// look up the session, strip the browser demux prefix, append to the ring,
|
|
// check the in-flight sentinel and wake any waiter. Sessions MCP did not
|
|
// create (the web console's) are dropped at the map lookup with no work.
|
|
func (s *Server) OnTerminalData(deviceID string, packet []byte) {
|
|
sess := s.sessions.get(deviceID)
|
|
if sess == nil {
|
|
return
|
|
}
|
|
if len(packet) >= len(protocol.TerminalBinaryMagic) &&
|
|
bytes.Equal(packet[:len(protocol.TerminalBinaryMagic)], protocol.TerminalBinaryMagic[:]) {
|
|
packet = packet[len(protocol.TerminalBinaryMagic):]
|
|
}
|
|
sess.mu.Lock()
|
|
if sess.closed {
|
|
sess.mu.Unlock()
|
|
return
|
|
}
|
|
sess.appendLocked(packet)
|
|
sess.scanPendingLocked()
|
|
sess.cond.Broadcast()
|
|
sess.mu.Unlock()
|
|
}
|