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 { OpenTerminalSession(deviceID string) error CloseTerminalSession(deviceID string) 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() if err := t.hub.OpenTerminalSession(deviceID); 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.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.CloseTerminalSession(deviceID) 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 { t.mu.Lock() sess, ok := t.byDevice[deviceID] if !ok || (want != nil && sess != want) { t.mu.Unlock() return false } delete(t.byDevice, deviceID) t.mu.Unlock() sess.mu.Lock() wasClosed := sess.closed sess.closed = true sess.closeReason = "closed" sess.cond.Broadcast() sess.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. if t.hub != nil && !wasClosed { // Fires OnTerminalClosed, which is a no-op now that the entry is gone. t.hub.CloseTerminalSession(deviceID) } return true } // sweepIdle closes sessions whose last use is older than idle. Intended for // the periodic reaper: a model that forgets terminal_close must not lock a // human out of the device's shell. // // The M4c reaper must skip sessions with an in-flight command (pending != // nil): a quiet command (sleep, a slow download) still owns the lease and // must not be reaped just because it printed nothing for a while. func (t *sessionTable) sweepIdle(now time.Time, idle time.Duration) int { type staleEntry struct { id string sess *termSession } var stale []staleEntry t.mu.Lock() for id, sess := range t.byDevice { sess.mu.Lock() last := sess.lastUsed sess.mu.Unlock() if now.Sub(last) >= idle { stale = append(stale, staleEntry{id, sess}) } } t.mu.Unlock() n := 0 for _, e := range stale { if t.closeSessionIf(e.id, e.sess) { n++ } } return n } // 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() }