package mcp import "strings" // Terminal output cleaning, ported byte-for-byte from the Win32 server // (server/2015Remote/McpServer.cpp:3875-4060). The stage order is load-bearing // — ConPTY is a screen-rendering stream, not a byte stream, so echoed input, // ANSI repaints and sentinel remnants all interact. clean_test.go locks the // behaviour against samples captured from the MFC implementation; do not // "simplify" the matchers. // // MFC's CleanTerminalOutput runs: StripAnsi → CRLF normalize → StripEchoedInput // (which itself ends with StripSentinelText) → TrimRight. We keep that order. // stripAnsi drops CSI/OSC and other single-byte ESC sequences so terminal // colour codes never reach the model. func stripAnsi(s string) string { var b strings.Builder b.Grow(len(s)) for i := 0; i < len(s); i++ { if s[i] != 0x1b { b.WriteByte(s[i]) continue } i++ // swallow ESC if i < len(s) && s[i] == '[' { // CSI ... ends at @..~ i++ for i < len(s) && !(s[i] >= '@' && s[i] <= '~') { i++ } } else if i < len(s) && s[i] == ']' { // OSC ... ends at BEL or ST i++ for i < len(s) && s[i] != 0x07 && s[i] != 0x1b { i++ } // ST is the two-byte sequence ESC '\'; consume both. if i+1 < len(s) && s[i] == 0x1b && s[i+1] == '\\' { i++ } } // Any other one-byte ESC sequence: the byte after ESC is swallowed by // the loop increment. } return b.String() } // stripEchoedLine removes the first occurrence of line, ignoring CR/LF inside // the match because ConPTY wraps a long echo at 80 columns. The echoed line's // trailing newlines are removed with it. func stripEchoedLine(s, line string) string { if line == "" || s == "" { return s } for i := 0; i < len(s); i++ { j, k := 0, i for j < len(line) && k < len(s) { c := s[k] if c == '\r' || c == '\n' { k++ continue } if c != line[j] { break } j++ k++ } if j != len(line) { continue } for k < len(s) && (s[k] == '\r' || s[k] == '\n') { k++ } return s[:i] + s[k:] } return s } // cutThroughEchoedLine deletes everything up to and including the echoed input // line. ConPTY replays the boot screen and prompt just before our input echo, // so the echo marks where real output starts. ok=false means the client did // not echo; the caller then falls back to stripEchoedLine. func cutThroughEchoedLine(s, line string) (string, bool) { if line == "" || s == "" { return s, false } for i := 0; i < len(s); i++ { j, k := 0, i for j < len(line) && k < len(s) { c := s[k] if c == '\r' || c == '\n' { k++ continue } if c != line[j] { break } j++ k++ } if j != len(line) { continue } for k < len(s) && (s[k] == '\r' || s[k] == '\n') { k++ } return s[k:], true } return s, false } // trimLeadingNewlines drops the blank lines left by the boot screen or the // previous command's trailing newline. func trimLeadingNewlines(s string) string { i := 0 for i < len(s) && (s[i] == '\r' || s[i] == '\n') { i++ } return s[i:] } // stripSentinelText erases sentinel remnants that a ConPTY repaint duplicated // into the output (e.g. `cmd /c echo abc` renders as "abc__MCP_DONE_x__0"). // The nonce is random per command, so real output cannot contain the marker; // matching skips CR/LF (wrapped echoes) and also eats a trailing // "%errorlevel%" echo template. A preceding "echo " is removed with it. func stripSentinelText(s, nonce string) string { if nonce == "" || s == "" { return s } marker := "__MCP_DONE_" + nonce + "__" i := 0 for i < len(s) { j, k := 0, i for j < len(marker) && k < len(s) { c := s[k] if c == '\r' || c == '\n' { k++ continue } if c != marker[j] { break } j++ k++ } if j != len(marker) { i++ continue } end := k if end < len(s) && s[end] == '-' { end++ } for end < len(s) && s[end] >= '0' && s[end] <= '9' { end++ } if end < len(s) && s[end] == '%' { // echoed template ...__%errorlevel% for end < len(s) && s[end] != '\r' && s[end] != '\n' { end++ } } begin := i // also remove a stray "echo " left in front of it if begin >= 5 && strings.EqualFold(s[begin-5:begin], "echo ") { begin -= 5 } s = s[:begin] + s[end:] i = begin } return s } // stripEchoedInput removes the PTY's echo of the command line and sentinel // line. Non-PTY sessions only remove the sentinel line: the legacy shell // manager skips the echo by written length, so deleting the command echo could // eat real output (e.g. `echo echo hello`). func stripEchoedInput(s string, isPTY bool, cmdLine, sentLine, nonce string) string { out := s cut := false if isPTY { out, cut = cutThroughEchoedLine(out, cmdLine) } if isPTY && !cut { out = stripEchoedLine(out, cmdLine) } out = stripEchoedLine(out, sentLine) out = stripSentinelText(out, nonce) return trimLeadingNewlines(out) } // buildSentinelLines builds the command line and sentinel line for one // platform. PTY platforms send them as two lines so line-swallowing commands // (rem / cmd / exit / if / for) cannot eat the sentinel; the legacy non-PTY // path keeps the single-line &&/|| form. func buildSentinelLines(isPTY, posix bool, command, nonce string) (cmdLine, sentLine string) { if posix { return command, "echo __MCP_DONE_" + nonce + "__$?" } if !isPTY { return command + " 2>&1 && echo __MCP_DONE_" + nonce + "__0 || echo __MCP_DONE_" + nonce + "__1", "" } return "@echo off & " + command, "echo __MCP_DONE_" + nonce + "__%errorlevel%" } // buildTerminalWire assembles what goes to the shell. POSIX shells print PS1 // on every read, which would pollute stdout, so it is cleared first; that // line's echo is cut together with the boot noise. func buildTerminalWire(posix bool, cmdLine, sentLine string) []byte { var b strings.Builder if posix { b.WriteString("PS1=\r\n") } b.WriteString(cmdLine) b.WriteString("\r\n") if sentLine != "" { b.WriteString(sentLine) b.WriteString("\r\n") } return []byte(b.String()) } // containsControlChar reports a byte < 0x20, including CR/LF. A newline would // split the command into extra lines, only the last of which carries the // sentinel, so the exit code would be wrong. func containsControlChar(s string) bool { for i := 0; i < len(s); i++ { if s[i] < 0x20 { return true } } return false } // hasPosixBackgroundAmpersand reports an unquoted, unescaped '&' that is not // part of &&, &> or >&. A background command's output and exit code cannot be // attributed to the sentinel, so it is refused. func hasPosixBackgroundAmpersand(s string) bool { var inSingle, inDouble, esc bool for i := 0; i < len(s); i++ { c := s[i] if esc { esc = false continue } if c == '\\' && !inSingle { esc = true continue } if inSingle { if c == '\'' { inSingle = false } continue } if inDouble { if c == '"' { inDouble = false } continue } if c == '\'' { inSingle = true continue } if c == '"' { inDouble = true continue } if c != '&' { continue } if i+1 < len(s) && (s[i+1] == '&' || s[i+1] == '>') { i++ continue } if i > 0 && s[i-1] == '>' { // 2>&1 / >&2 continue } return true } return false } // normalizeCRLF drops the '\r' of every CRLF pair, as MFC does. func normalizeCRLF(s string) string { if !strings.Contains(s, "\r\n") { return s } var b strings.Builder b.Grow(len(s)) for i := 0; i < len(s); i++ { if s[i] == '\r' && i+1 < len(s) && s[i+1] == '\n' { continue } b.WriteByte(s[i]) } return b.String() } // cleanTerminalOutput is one delivery window's worth of cleaning. first is // true only for the command-issuing call's first window (echo exists only // there); trimTrailing stays false for a partial window so the next window's // first line does not get glued onto this one. func cleanTerminalOutput(raw []byte, isPTY, first bool, cmdLine, sentLine, nonce string, trimTrailing bool) string { if len(raw) == 0 { return "" } s := stripAnsi(string(raw)) s = normalizeCRLF(s) if first { s = stripEchoedInput(s, isPTY, cmdLine, sentLine, nonce) } else { s = stripSentinelText(s, nonce) s = trimLeadingNewlines(s) } if trimTrailing { s = strings.TrimRight(s, " \t\r\n") } return s }