diff --git a/changelog/unreleased/pull-22216 b/changelog/unreleased/pull-22216 index 336d74fe7..fcaa42881 100644 --- a/changelog/unreleased/pull-22216 +++ b/changelog/unreleased/pull-22216 @@ -6,6 +6,8 @@ printed many of those strings verbatim, which could mangle the status output or change the terminal state. Text output now quotes strings that contain non-printable or invalid UTF-8 -characters. JSON output is unchanged. +characters. JSON output escapes control and format characters using standard +JSON escape sequences so it remains valid and decodes identically. The `cat` +command and `dump` commands still output data verbatim. https://github.com/restic/restic/pull/22216 diff --git a/cmd/restic/cmd_find.go b/cmd/restic/cmd_find.go index 7dee887a6..c8cf72f4b 100644 --- a/cmd/restic/cmd_find.go +++ b/cmd/restic/cmd_find.go @@ -159,7 +159,7 @@ func (s *statefulOutput) PrintPatternJSON(path string, node *data.Node) { if s.hits > 0 { _, _ = s.stdout.Write([]byte(",")) } - _, _ = s.stdout.Write(b) + _, _ = io.WriteString(s.stdout, ui.EscapeControls(string(b))) s.hits++ } @@ -210,7 +210,7 @@ func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn * if s.hits > 0 { _, _ = s.stdout.Write([]byte(",")) } - _, _ = s.stdout.Write(b) + _, _ = io.WriteString(s.stdout, ui.EscapeControls(string(b))) s.hits++ } diff --git a/cmd/restic/cmd_find_test.go b/cmd/restic/cmd_find_test.go index 5ab6de6b7..69055e895 100644 --- a/cmd/restic/cmd_find_test.go +++ b/cmd/restic/cmd_find_test.go @@ -1,11 +1,15 @@ package main import ( + "bytes" + "context" + "encoding/json" "strconv" "strings" "testing" "github.com/restic/restic/internal/data" + "github.com/restic/restic/internal/restic" rtest "github.com/restic/restic/internal/test" "github.com/restic/restic/internal/ui" "github.com/restic/restic/internal/ui/progress" @@ -28,3 +32,66 @@ func TestPrintObjectQuotesPath(t *testing.T) { out.PrintObjectNormal("blob", "abcd", "/ordinary/file", "tree", &data.Snapshot{}) rtest.Equals(t, " ... in file /ordinary/file", term.Output[1]) } + +type fakeSnapshotLoader struct{} + +func (fakeSnapshotLoader) Connections() uint { return 1 } +func (fakeSnapshotLoader) LoadUnpacked(_ context.Context, _ restic.FileType, _ restic.ID) ([]byte, error) { + return []byte("{}"), nil +} + +func TestFindJSONEscapesControls(t *testing.T) { + hostilePath := "/dir/c1\u009b2J_del\x7f_tag\U000e0067" + sn, err := data.LoadSnapshot(t.Context(), fakeSnapshotLoader{}, restic.NewRandomID()) + rtest.OK(t, err) + + t.Run("pattern", func(t *testing.T) { + var buf bytes.Buffer + out := &statefulOutput{ + JSON: true, + newsn: sn, + printer: progress.NewTerminalPrinter(true, 1, &ui.MockTerminal{}), + stdout: &buf, + } + out.PrintPatternJSON(hostilePath, &data.Node{Name: "file"}) + out.Finish() + + got := buf.String() + rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got) + rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got) + rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got) + + var parsed []struct { + Matches []struct { + Path string `json:"path"` + } `json:"matches"` + } + rtest.OK(t, json.Unmarshal(buf.Bytes(), &parsed)) + rtest.Equals(t, 1, len(parsed)) + rtest.Equals(t, 1, len(parsed[0].Matches)) + rtest.Equals(t, hostilePath, parsed[0].Matches[0].Path) + }) + + t.Run("object", func(t *testing.T) { + var buf bytes.Buffer + out := &statefulOutput{ + JSON: true, + printer: progress.NewTerminalPrinter(true, 1, &ui.MockTerminal{}), + stdout: &buf, + } + out.PrintObjectJSON("file", "abcd", hostilePath, "tree", sn) + out.Finish() + + got := buf.String() + rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got) + rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got) + rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got) + + var parsed []struct { + Path string `json:"path"` + } + rtest.OK(t, json.Unmarshal(buf.Bytes(), &parsed)) + rtest.Equals(t, 1, len(parsed)) + rtest.Equals(t, hostilePath, parsed[0].Path) + }) +} diff --git a/cmd/restic/main.go b/cmd/restic/main.go index 65ac1f6c9..b4f1ce5ff 100644 --- a/cmd/restic/main.go +++ b/cmd/restic/main.go @@ -168,13 +168,14 @@ func printExitError(globalOptions global.Options, code int, message string) { Message: message, } - err := json.NewEncoder(os.Stderr).Encode(jsonS) + b, err := json.Marshal(jsonS) if err != nil { // ignore error as there's no good way to handle it _, _ = fmt.Fprintf(os.Stderr, "JSON encode failed: %v\n", err) debug.Log("JSON encode failed: %v\n", err) return } + _, _ = fmt.Fprintf(os.Stderr, "%s\n", ui.EscapeControls(string(b))) } else { _, _ = fmt.Fprintf(os.Stderr, "%s\n", ui.EscapeControls(message)) } diff --git a/internal/ui/format.go b/internal/ui/format.go index 6ae787993..7f086918c 100644 --- a/internal/ui/format.go +++ b/internal/ui/format.go @@ -9,6 +9,7 @@ import ( "strings" "time" "unicode" + "unicode/utf16" "unicode/utf8" "golang.org/x/text/width" @@ -158,9 +159,10 @@ func QuoteSlice(vals []string) []string { return out } -// EscapeControls replaces terminal control characters with Go escape sequences. +// EscapeControls replaces terminal control characters with escape sequences. // Newlines and tabs are preserved so multi-line messages keep their layout. -// Printable text, including JSON, is returned unchanged. +// Runes use JSON-compatible \uXXXX (and UTF-16 surrogate pair) escapes +// so JSON output remains valid and decodes identically. func EscapeControls(s string) string { if !hasTerminalControl(s) { return s @@ -177,9 +179,11 @@ func EscapeControls(s string) string { } if !terminalControl(r) { b.WriteRune(r) + } else if r <= 0xffff { + fmt.Fprintf(&b, `\u%04x`, r) } else { - q := strconv.QuoteRune(r) - b.WriteString(q[1 : len(q)-1]) + r1, r2 := utf16.EncodeRune(r) + fmt.Fprintf(&b, `\u%04x\u%04x`, r1, r2) } i += size } diff --git a/internal/ui/format_test.go b/internal/ui/format_test.go index 36555bfa6..b4fda9c4d 100644 --- a/internal/ui/format_test.go +++ b/internal/ui/format_test.go @@ -1,7 +1,9 @@ package ui import ( + "encoding/json" "strconv" + "strings" "testing" rtest "github.com/restic/restic/internal/test" @@ -139,11 +141,41 @@ func TestQuoteSlice(t *testing.T) { 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, "bell \\u0007\nnext", EscapeControls("bell \a\nnext")) + rtest.Equals(t, "esc \\u001b[2J", EscapeControls("esc \x1b[2J")) + rtest.Equals(t, "del \\u007f", EscapeControls("del \x7f")) + rtest.Equals(t, "c1 \\u009b2J", EscapeControls("c1 \u009b2J")) + rtest.Equals(t, "tag \\udb40\\udc67", EscapeControls("tag \U000e0067")) + rtest.Equals(t, "bad \\xff", EscapeControls("bad \xff")) + rtest.Equals(t, "repl \uFFFD", EscapeControls("repl \uFFFD")) + rtest.Equals(t, "nbsp \u00a0", EscapeControls("nbsp \u00a0")) + rtest.Equals(t, "pua \ue000", EscapeControls("pua \ue000")) + rtest.Equals(t, "zwj \\u200d", EscapeControls("zwj \u200d")) + rtest.Equals(t, "sep \u2028\u2029", EscapeControls("sep \u2028\u2029")) rtest.Equals(t, "{\"hostname\":\"ok\"}\n", EscapeControls("{\"hostname\":\"ok\"}\n")) } +func TestEscapeControlsJSONRoundTrip(t *testing.T) { + type payload struct { + Value string `json:"value"` + } + in := payload{ + Value: "plain \x1b[2J del:\x7f c1:\u009b2J bidi:\u202e zwj:\u200d flag:\U0001f3f4\U000e0067\U000e007f repl:\uFFFD", + } + raw, err := json.Marshal(in) + rtest.OK(t, err) + + escaped := EscapeControls(string(raw)) + rtest.Assert(t, !strings.ContainsRune(escaped, '\x7f'), "raw DEL in %q", escaped) + rtest.Assert(t, !strings.ContainsRune(escaped, '\u009b'), "raw C1 CSI in %q", escaped) + rtest.Assert(t, !strings.ContainsRune(escaped, '\u202e'), "raw Bidi RLO in %q", escaped) + rtest.Assert(t, !strings.ContainsRune(escaped, '\U000e0067'), "raw non-BMP tag in %q", escaped) + + var decoded payload + rtest.OK(t, json.Unmarshal([]byte(escaped), &decoded)) + rtest.Equals(t, in, decoded) +} + func TestTruncate(t *testing.T) { var tests = []struct { input string diff --git a/internal/ui/table/table_test.go b/internal/ui/table/table_test.go index 54b22276c..917168fb6 100644 --- a/internal/ui/table/table_test.go +++ b/internal/ui/table/table_test.go @@ -169,12 +169,12 @@ foo 2018-08-19 22:22:22 xxx other /home/user/other return table }, ` -host tags ------------------ -host\x1b[2J ok - a - b ------------------ +host tags +------------------- +host\u001b[2J ok + a + b +------------------- `, }, }