generically sanitize output

This commit is contained in:
Michael Eischer committed 2026-11-28 20:27:06 +01:00
1 parent 76925aeb63
commit 84a75fc09e
7 files changed
+121 -4

No files matched your search

+2 -1
View File
@@ -23,6 +23,7 @@ import (
"github.com/restic/restic/internal/feature"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/termstatus"
)
@@ -175,7 +176,7 @@ func printExitError(globalOptions global.Options, code int, message string) {
return
}
} else {
_, _ = fmt.Fprintf(os.Stderr, "%v\n", message)
_, _ = fmt.Fprintf(os.Stderr, "%s\n", ui.EscapeControls(message))
}
}
+54
View File
@@ -6,8 +6,10 @@ import (
"fmt"
"math/bits"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"golang.org/x/text/width"
@@ -156,6 +158,58 @@ func QuoteSlice(vals []string) []string {
return out
}
// EscapeControls replaces terminal control characters with Go escape sequences.
// Newlines and tabs are preserved so multi-line messages keep their layout.
// Printable text, including JSON, is returned unchanged.
func EscapeControls(s string) string {
if !hasTerminalControl(s) {
return s
}
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
if r == utf8.RuneError && size == 1 {
fmt.Fprintf(&b, `\x%02x`, s[i])
i++
continue
}
if !terminalControl(r) {
b.WriteRune(r)
} else {
q := strconv.QuoteRune(r)
b.WriteString(q[1 : len(q)-1])
}
i += size
}
return b.String()
}
func hasTerminalControl(s string) bool {
for i := 0; i < len(s); {
r, size := utf8.DecodeRuneInString(s[i:])
if (r == utf8.RuneError && size == 1) || terminalControl(r) {
return true
}
i += size
}
return false
}
// terminalControl reports whether r can change terminal state or modify
// rendering. Newlines and tabs are kept to allow multi-line messages.
//
// Matched runes are C0 and C1 controls (category Cc, including DEL) and
// format characters (category Cf: bidi controls, zero-width characters,
// tags).
func terminalControl(r rune) bool {
if r == '\n' || r == '\t' {
return false
}
return unicode.IsControl(r) || unicode.Is(unicode.Cf, r)
}
// Truncate s to fit in width (number of terminal cells) w.
// If w is negative, returns the empty string.
func Truncate(s string, w int) string {
+8
View File
@@ -136,6 +136,14 @@ func TestQuoteSlice(t *testing.T) {
rtest.Equals(t, []string{}, QuoteSlice(nil))
}
func TestEscapeControlsKeepsLayout(t *testing.T) {
in := "PID 1 on host\n\tstack"
rtest.Equals(t, in, EscapeControls(in))
rtest.Equals(t, "bell \\a\nnext", EscapeControls("bell \a\nnext"))
rtest.Equals(t, "esc \\x1b[2J", EscapeControls("esc \x1b[2J"))
rtest.Equals(t, "{\"hostname\":\"ok\"}\n", EscapeControls("{\"hostname\":\"ok\"}\n"))
}
func TestTruncate(t *testing.T) {
var tests = []struct {
input string
+2 -2
View File
@@ -130,7 +130,7 @@ func (t *Table) Write(w io.Writer) error {
return err
}
row = append(row, buf.String())
row = append(row, ui.EscapeControls(buf.String()))
buf.Reset()
}
lines = append(lines, row)
@@ -198,7 +198,7 @@ func (t *Table) Write(w io.Writer) error {
if len(t.footer) > 0 {
// write the footer
for _, line := range t.footer {
err := t.PrintFooter(w, line)
err := t.PrintFooter(w, ui.EscapeControls(line))
if err != nil {
return err
}
+20
View File
@@ -155,6 +155,26 @@ foo 2018-08-19 22:22:22 xxx other /home/user/other
foo 2018-08-19 22:22:22 xxx other /home/user/other
bar
------------------------------------------------------------
`,
},
{
func(t testing.TB) *Table {
table := New()
table.AddColumn("host", "{{.Host}}")
table.AddColumn("tags", `{{join .Tags "\n"}}`)
table.AddRow(struct {
Host string
Tags []string
}{"host\x1b[2J", []string{"ok", "a\nb"}})
return table
},
`
host tags
-----------------
host\x1b[2J ok
a
b
-----------------
`,
},
}
+1 -1
View File
@@ -377,7 +377,7 @@ func (t *terminal) print(line string, isErr bool) {
}
select {
case t.msg <- message{line: line, err: isErr}:
case t.msg <- message{line: ui.EscapeControls(line), err: isErr}:
case <-t.closed:
}
}
+34
View File
@@ -11,6 +11,7 @@ import (
tty "github.com/restic/restic/internal/terminal"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
)
func TestSetStatus(t *testing.T) {
@@ -116,6 +117,39 @@ func TestPrint(t *testing.T) {
rtest.Equals(t, exp, buf.String())
}
func TestPrintErrorEscapesControls(t *testing.T) {
buf, term, cancel := setupStatusTest()
const (
cl = tty.PosixControlClearLine
home = tty.PosixControlMoveCursorHome
)
hostile := "esc \x1b[2J del \x7f c1 \u009b tag \U000e0067 bad \xff"
term.Print("out " + hostile)
term.Error("err " + hostile)
// Newlines and tabs are part of the message layout and must survive.
term.Print("keep\n\ttabs")
term.Error("already\n")
exp := home + cl + ui.EscapeControls("out "+hostile+"\n")
exp += home + cl + ui.EscapeControls("err "+hostile+"\n")
exp += home + cl + "keep\n\ttabs\n"
exp += home + cl + "already\n"
cancel()
<-term.closed
got := buf.String()
rtest.Equals(t, exp, got)
// Clear-line uses ESC [2K, so a raw ESC byte is expected. The hostile sequence is not.
rtest.Assert(t, !strings.Contains(got, "\x1b[2J"), "raw CSI in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got)
rtest.Assert(t, !strings.Contains(got, "\xff"), "raw invalid UTF-8 in %q", got)
}
func TestSanitizeLines(t *testing.T) {
var tests = []struct {
input []string