From 0e50a959d504c64d77d96cd8b405c33d736b7a69 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 13:45:58 +0100 Subject: [PATCH 01/14] ui: add helper to quote slices --- internal/ui/format.go | 10 ++++++++++ internal/ui/format_test.go | 7 +++++++ 2 files changed, 17 insertions(+) diff --git a/internal/ui/format.go b/internal/ui/format.go index a9300008e..1a41b61a0 100644 --- a/internal/ui/format.go +++ b/internal/ui/format.go @@ -146,6 +146,16 @@ func Quote(line string) string { return line } +// QuoteSlice quotes elements that contain terminal control characters. +// Elements that are already safe to print are left unchanged. +func QuoteSlice(vals []string) []string { + out := make([]string, len(vals)) + for i, v := range vals { + out[i] = Quote(v) + } + return out +} + // 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 { diff --git a/internal/ui/format_test.go b/internal/ui/format_test.go index 563a38870..8dcee674a 100644 --- a/internal/ui/format_test.go +++ b/internal/ui/format_test.go @@ -129,6 +129,13 @@ func TestQuote(t *testing.T) { } } +func TestQuoteSlice(t *testing.T) { + in := []string{"ok", "a\nb", "plain"} + rtest.Equals(t, []string{"ok", strconv.Quote("a\nb"), "plain"}, QuoteSlice(in)) + rtest.Equals(t, "a\nb", in[1]) + rtest.Equals(t, []string{}, QuoteSlice(nil)) +} + func TestTruncate(t *testing.T) { var tests = []struct { input string From 584ec2316044e4704591f4da3f2dad36ab46d5b6 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 14:04:21 +0100 Subject: [PATCH 02/14] quote paths in direct command output --- cmd/restic/cmd_backup.go | 8 ++++---- cmd/restic/cmd_diff.go | 6 +++++- cmd/restic/cmd_diff_test.go | 21 +++++++++++++++++++++ cmd/restic/cmd_dump.go | 2 +- cmd/restic/cmd_find.go | 4 ++-- cmd/restic/cmd_find_test.go | 30 ++++++++++++++++++++++++++++++ cmd/restic/cmd_key_list.go | 5 +++++ cmd/restic/cmd_ls.go | 2 +- cmd/restic/cmd_mount.go | 2 +- cmd/restic/cmd_restore.go | 6 +++--- cmd/restic/cmd_rewrite.go | 4 ++-- cmd/restic/cmd_snapshots.go | 12 ++++++------ internal/data/node.go | 3 ++- internal/fs/node_unix.go | 5 +++-- internal/ui/backup/text.go | 2 +- internal/ui/backup/text_test.go | 6 ++++++ internal/ui/restore/text.go | 6 +++--- internal/ui/restore/text_test.go | 21 ++++++++++++++------- 18 files changed, 110 insertions(+), 35 deletions(-) create mode 100644 cmd/restic/cmd_diff_test.go create mode 100644 cmd/restic/cmd_find_test.go diff --git a/cmd/restic/cmd_backup.go b/cmd/restic/cmd_backup.go index 2231ea995..35e2ec5be 100644 --- a/cmd/restic/cmd_backup.go +++ b/cmd/restic/cmd_backup.go @@ -187,9 +187,9 @@ func filterExisting(items []string, warnf func(msg string, args ...any)) (result _, err := fs.Lstat(item) if err != nil { if errors.Is(err, os.ErrNotExist) { - warnf("%v does not exist, skipping\n", item) + warnf("%v does not exist, skipping\n", ui.Quote(item)) } else { - warnf("%v cannot be accessed, skipping\n", item) + warnf("%v cannot be accessed, skipping\n", ui.Quote(item)) } continue } @@ -646,7 +646,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te sc.Result = progressReporter.ReportTotal if !gopts.JSON { - printer.V("start scan on %v", targets) + printer.V("start scan on %v", ui.QuoteSlice(targets)) } wg.Go(func() error { return sc.Scan(cancelCtx, targets) }) } @@ -692,7 +692,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts global.Options, te } if !gopts.JSON { - printer.V("start backup on %v", targets) + printer.V("start backup on %v", ui.QuoteSlice(targets)) } _, id, summary, err := arch.Snapshot(ctx, targets, snapshotOpts) diff --git a/cmd/restic/cmd_diff.go b/cmd/restic/cmd_diff.go index 1519b37c7..a46d22ea8 100644 --- a/cmd/restic/cmd_diff.go +++ b/cmd/restic/cmd_diff.go @@ -97,6 +97,10 @@ func NewChange(path string, mode string) *Change { return &Change{MessageType: "change", Path: path, Modifier: mode} } +func printTextDiffChange(S func(string, ...any), change *Change) { + S("%-5s%v", change.Modifier, ui.Quote(change.Path)) +} + // DiffStat collects stats for all types of items. type DiffStat struct { Files int `json:"files"` @@ -412,7 +416,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts global.Options, args [ opts: opts, printError: printer.E, printChange: func(change *Change) { - printer.S("%-5s%v", change.Modifier, change.Path) + printTextDiffChange(printer.S, change) }, } diff --git a/cmd/restic/cmd_diff_test.go b/cmd/restic/cmd_diff_test.go new file mode 100644 index 000000000..1684350ca --- /dev/null +++ b/cmd/restic/cmd_diff_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "strconv" + "testing" + + rtest "github.com/restic/restic/internal/test" + "github.com/restic/restic/internal/ui" + "github.com/restic/restic/internal/ui/progress" +) + +func TestPrintTextDiffChangeQuotesPath(t *testing.T) { + term := &ui.MockTerminal{} + printer := progress.NewTerminalPrinter(false, 1, term) + printTextDiffChange(printer.S, NewChange("dir\nfile", "+")) + rtest.Equals(t, []string{"+ " + strconv.Quote("dir\nfile")}, term.Output) + + term.Output = nil + printTextDiffChange(printer.S, NewChange("/ordinary/file", "+")) + rtest.Equals(t, []string{"+ /ordinary/file"}, term.Output) +} diff --git a/cmd/restic/cmd_dump.go b/cmd/restic/cmd_dump.go index a7abf83e7..d6982ec7f 100644 --- a/cmd/restic/cmd_dump.go +++ b/cmd/restic/cmd_dump.go @@ -209,7 +209,7 @@ func runDump(ctx context.Context, opts DumpOptions, gopts global.Options, args [ totalErrors := 0 d.Error = func(nodePath string, err error) { totalErrors++ - printer.E("ignoring error for %s: %s\n", nodePath, err) + printer.E("ignoring error for %s: %s\n", ui.Quote(nodePath), err) } err = printFromTree(ctx, tree, repo, "/", splittedPath, d, canWriteArchiveFunc) if err != nil { diff --git a/cmd/restic/cmd_find.go b/cmd/restic/cmd_find.go index c43342180..7ae1b3fef 100644 --- a/cmd/restic/cmd_find.go +++ b/cmd/restic/cmd_find.go @@ -217,10 +217,10 @@ func (s *statefulOutput) PrintObjectJSON(kind, id, nodepath, treeID string, sn * func (s *statefulOutput) PrintObjectNormal(kind, id, nodepath, treeID string, sn *data.Snapshot) { s.printer.S("Found %s %s", kind, id) if kind == "blob" { - s.printer.S(" ... in file %s", nodepath) + s.printer.S(" ... in file %s", ui.Quote(nodepath)) s.printer.S(" (tree %s)", treeID) } else { - s.printer.S(" ... path %s", nodepath) + s.printer.S(" ... path %s", ui.Quote(nodepath)) } s.printer.S(" ... in snapshot %s (%s)", sn.ID().Str(), sn.Time.Local().Format(global.TimeFormat)) } diff --git a/cmd/restic/cmd_find_test.go b/cmd/restic/cmd_find_test.go new file mode 100644 index 000000000..5ab6de6b7 --- /dev/null +++ b/cmd/restic/cmd_find_test.go @@ -0,0 +1,30 @@ +package main + +import ( + "strconv" + "strings" + "testing" + + "github.com/restic/restic/internal/data" + rtest "github.com/restic/restic/internal/test" + "github.com/restic/restic/internal/ui" + "github.com/restic/restic/internal/ui/progress" +) + +func TestPrintObjectQuotesPath(t *testing.T) { + term := &ui.MockTerminal{} + out := &statefulOutput{ + printer: progress.NewTerminalPrinter(false, 1, term), + } + out.PrintObjectNormal("file", "abcd", "dir\nfile", "", &data.Snapshot{}) + + rtest.Equals(t, " ... path "+strconv.Quote("dir\nfile"), term.Output[1]) + for _, line := range term.Output { + rtest.Assert(t, !strings.Contains(line, "\n"), "raw newline in %q", line) + } + + term = &ui.MockTerminal{} + out.printer = progress.NewTerminalPrinter(false, 1, term) + out.PrintObjectNormal("blob", "abcd", "/ordinary/file", "tree", &data.Snapshot{}) + rtest.Equals(t, " ... in file /ordinary/file", term.Output[1]) +} diff --git a/cmd/restic/cmd_key_list.go b/cmd/restic/cmd_key_list.go index 1d86e3e79..e744b50c2 100644 --- a/cmd/restic/cmd_key_list.go +++ b/cmd/restic/cmd_key_list.go @@ -99,6 +99,11 @@ func listKeys(ctx context.Context, s *repository.Repository, gopts global.Option return json.NewEncoder(gopts.Term.OutputWriter()).Encode(keys) } + for i := range keys { + keys[i].UserName = ui.Quote(keys[i].UserName) + keys[i].HostName = ui.Quote(keys[i].HostName) + } + tab := table.New() tab.AddColumn(" ID", "{{if .Current}}*{{else}} {{end}}{{ .ShortID }}") tab.AddColumn("User", "{{ .UserName }}") diff --git a/cmd/restic/cmd_ls.go b/cmd/restic/cmd_ls.go index 2052a4271..35fe03687 100644 --- a/cmd/restic/cmd_ls.go +++ b/cmd/restic/cmd_ls.go @@ -296,7 +296,7 @@ type textLsPrinter struct { } func (p *textLsPrinter) Snapshot(sn *data.Snapshot) error { - p.termPrinter.P("%v filtered by %v:", sn, p.dirs) + p.termPrinter.P("%v filtered by %v:", sn, ui.QuoteSlice(p.dirs)) return nil } func (p *textLsPrinter) NodeOutput(node lsNodeOutput, isPrefixDirectory bool) error { diff --git a/cmd/restic/cmd_mount.go b/cmd/restic/cmd_mount.go index 969e4898f..e761f2254 100644 --- a/cmd/restic/cmd_mount.go +++ b/cmd/restic/cmd_mount.go @@ -201,7 +201,7 @@ func runMount(ctx context.Context, opts MountOptions, gopts global.Options, args err = fusefs.Serve(c, root) }() - printer.S("Now serving the repository at %s", mountpoint) + printer.S("Now serving the repository at %s", ui.Quote(mountpoint)) printer.S("Use another terminal or tool to browse the contents of this folder.") printer.S("When finished, quit with Ctrl-c here or umount the mountpoint.") debug.Log("serving mount at %v", mountpoint) diff --git a/cmd/restic/cmd_restore.go b/cmd/restic/cmd_restore.go index 31081f011..58ca3e070 100644 --- a/cmd/restic/cmd_restore.go +++ b/cmd/restic/cmd_restore.go @@ -243,7 +243,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options, } if !gopts.JSON { - printer.P("restoring %s to %s\n", res.Snapshot(), opts.Target) + printer.P("restoring %s to %s\n", res.Snapshot(), ui.Quote(opts.Target)) } countRestoredFiles, err := res.RestoreTo(ctx, opts.Target) @@ -259,7 +259,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options, if opts.Verify { if !gopts.JSON { - printer.P("verifying files in %s\n", opts.Target) + printer.P("verifying files in %s\n", ui.Quote(opts.Target)) } var count int t0 := time.Now() @@ -273,7 +273,7 @@ func runRestore(ctx context.Context, opts RestoreOptions, gopts global.Options, } if !gopts.JSON { - printer.P("finished verifying %d files in %s (took %s)\n", count, opts.Target, + printer.P("finished verifying %d files in %s (took %s)\n", count, ui.Quote(opts.Target), time.Since(t0).Round(time.Millisecond)) } } diff --git a/cmd/restic/cmd_rewrite.go b/cmd/restic/cmd_rewrite.go index 064f4a05d..fb2b0c017 100644 --- a/cmd/restic/cmd_rewrite.go +++ b/cmd/restic/cmd_rewrite.go @@ -245,7 +245,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d } if newMetadata != nil && newMetadata.Hostname != "" { - printer.P("would set hostname to %s", newMetadata.Hostname) + printer.P("would set hostname to %s", ui.Quote(newMetadata.Hostname)) } return true, nil @@ -268,7 +268,7 @@ func filterAndReplaceSnapshot(ctx context.Context, repo restic.Repository, sn *d } if newMetadata != nil && newMetadata.Hostname != "" { - printer.P("setting host to %s", newMetadata.Hostname) + printer.P("setting host to %s", ui.Quote(newMetadata.Hostname)) sn.Hostname = newMetadata.Hostname } diff --git a/cmd/restic/cmd_snapshots.go b/cmd/restic/cmd_snapshots.go index 79b67272e..a927267a3 100644 --- a/cmd/restic/cmd_snapshots.go +++ b/cmd/restic/cmd_snapshots.go @@ -275,9 +275,9 @@ func printSnapshotsTable(stdout io.Writer, list data.Snapshots, reasons []data.K data := snapshot{ ID: sn.ID().Str(), Timestamp: sn.Time.Local().Format(global.TimeFormat), - Hostname: sn.Hostname, - Tags: sn.Tags, - Paths: sn.Paths, + Hostname: ui.Quote(sn.Hostname), + Tags: ui.QuoteSlice(sn.Tags), + Paths: ui.QuoteSlice(sn.Paths), } if len(reasons) > 0 { @@ -344,13 +344,13 @@ func PrintSnapshotGroupHeader(stdout io.Writer, groupKeyJSON string) error { header := "snapshots" var infoStrings []string if key.Hostname != "" { - infoStrings = append(infoStrings, "host ["+key.Hostname+"]") + infoStrings = append(infoStrings, "host ["+ui.Quote(key.Hostname)+"]") } if key.Tags != nil { - infoStrings = append(infoStrings, "tags ["+strings.Join(key.Tags, ", ")+"]") + infoStrings = append(infoStrings, "tags ["+strings.Join(ui.QuoteSlice(key.Tags), ", ")+"]") } if key.Paths != nil { - infoStrings = append(infoStrings, "paths ["+strings.Join(key.Paths, ", ")+"]") + infoStrings = append(infoStrings, "paths ["+strings.Join(ui.QuoteSlice(key.Paths), ", ")+"]") } if infoStrings != nil { header += " for (" + strings.Join(infoStrings, ", ") + ")" diff --git a/internal/data/node.go b/internal/data/node.go index e700e9e66..7f2154ebb 100644 --- a/internal/data/node.go +++ b/internal/data/node.go @@ -14,6 +14,7 @@ import ( "github.com/restic/restic/internal/errors" "github.com/restic/restic/internal/restic" + "github.com/restic/restic/internal/ui" "github.com/restic/restic/internal/debug" ) @@ -400,7 +401,7 @@ func handleUnknownGenericAttributeFound(genericAttributeType GenericAttributeTyp debug.Log("Ignoring a generic attribute found in the repository: %s which may not be compatible with your OS. Compatible OS: %s", genericAttributeType, os) } else { // If genericAttributesForOS in node.go does not know about this attribute, then the repository may have been created by a newer version which has a newer GenericAttributeType. - warn(fmt.Sprintf("Found an unrecognized generic attribute in the repository: %s. You may need to upgrade to latest version of restic.", genericAttributeType)) + warn(fmt.Sprintf("Found an unrecognized generic attribute in the repository: %s. You may need to upgrade to latest version of restic.", ui.Quote(string(genericAttributeType)))) } } } diff --git a/internal/fs/node_unix.go b/internal/fs/node_unix.go index d41d1a691..724f77004 100644 --- a/internal/fs/node_unix.go +++ b/internal/fs/node_unix.go @@ -7,6 +7,7 @@ import ( "os" "github.com/restic/restic/internal/data" + "github.com/restic/restic/internal/ui" ) func lchown(name string, node *data.Node, lookupByName bool, warn func(msg string)) error { @@ -19,14 +20,14 @@ func lchown(name string, node *data.Node, lookupByName bool, warn func(msg strin if id, ok := lookupUid(node.User); ok { uid = id } else if warn != nil { - warn(fmt.Sprintf("cannot resolve user %q for %v, using uid %d", node.User, name, uid)) + warn(fmt.Sprintf("cannot resolve user %q for %s, using uid %d", node.User, ui.Quote(name), uid)) } } if node.Group != "" { if id, ok := lookupGid(node.Group); ok { gid = id } else if warn != nil { - warn(fmt.Sprintf("cannot resolve group %q for %v, using gid %d", node.Group, name, gid)) + warn(fmt.Sprintf("cannot resolve group %q for %s, using gid %d", node.Group, ui.Quote(name), gid)) } } } diff --git a/internal/ui/backup/text.go b/internal/ui/backup/text.go index 32ff0effd..a10a3c726 100644 --- a/internal/ui/backup/text.go +++ b/internal/ui/backup/text.go @@ -160,5 +160,5 @@ func (b *textProgress) Finish(id restic.ID, summary *archiver.Summary, dryRun bo } func (b *textProgress) ExcludedItem(path string) { - b.VV("excluded %s", path) + b.VV("excluded %s", ui.Quote(path)) } diff --git a/internal/ui/backup/text_test.go b/internal/ui/backup/text_test.go index 39338a50c..e813d0f08 100644 --- a/internal/ui/backup/text_test.go +++ b/internal/ui/backup/text_test.go @@ -25,3 +25,9 @@ func TestScannerError(t *testing.T) { test.Equals(t, printer.ScannerError("/path", errors.New("error \"message\"")), nil) test.Equals(t, []string{"scan: error \"message\"\n"}, term.Errors) } + +func TestExcludedItem(t *testing.T) { + term, printer := createTextProgress() + printer.ExcludedItem("/p\nath") + test.Equals(t, []string{"excluded \"/p\\nath\""}, term.Output) +} diff --git a/internal/ui/restore/text.go b/internal/ui/restore/text.go index da0fd0319..9ceacabdb 100644 --- a/internal/ui/restore/text.go +++ b/internal/ui/restore/text.go @@ -41,7 +41,7 @@ func (t *textPrinter) Update(p State, duration time.Duration) { } func (t *textPrinter) Error(item string, err error) error { - t.E("ignoring error for %s: %s\n", item, err) + t.E("ignoring error for %s: %s\n", ui.Quote(item), err) return nil } @@ -65,9 +65,9 @@ func (t *textPrinter) CompleteItem(messageType restorer.ItemAction, item string, } if messageType == restorer.ActionDirRestored || messageType == restorer.ActionOtherRestored || messageType == restorer.ActionDeleted { - t.VV("%-9v %v", action, item) + t.VV("%-9v %v", action, ui.Quote(item)) } else { - t.VV("%-9v %v with size %v", action, item, ui.FormatBytes(size)) + t.VV("%-9v %v with size %v", action, ui.Quote(item), ui.FormatBytes(size)) } } diff --git a/internal/ui/restore/text_test.go b/internal/ui/restore/text_test.go index 9f1790152..787f19612 100644 --- a/internal/ui/restore/text_test.go +++ b/internal/ui/restore/text_test.go @@ -1,6 +1,7 @@ package restore import ( + "strconv" "testing" "time" @@ -49,18 +50,20 @@ func TestPrintSummaryOnSuccessWithSkipped(t *testing.T) { func TestPrintCompleteItem(t *testing.T) { for _, data := range []struct { action restorer.ItemAction + item string size uint64 expected string }{ - {restorer.ActionDirRestored, 0, "restored test"}, - {restorer.ActionFileRestored, 123, "restored test with size 123 B"}, - {restorer.ActionOtherRestored, 0, "restored test"}, - {restorer.ActionFileUpdated, 123, "updated test with size 123 B"}, - {restorer.ActionFileUnchanged, 123, "unchanged test with size 123 B"}, - {restorer.ActionDeleted, 0, "deleted test"}, + {restorer.ActionDirRestored, "test", 0, "restored test"}, + {restorer.ActionFileRestored, "test", 123, "restored test with size 123 B"}, + {restorer.ActionOtherRestored, "test", 0, "restored test"}, + {restorer.ActionFileUpdated, "test", 123, "updated test with size 123 B"}, + {restorer.ActionFileUnchanged, "test", 123, "unchanged test with size 123 B"}, + {restorer.ActionDeleted, "test", 0, "deleted test"}, + {restorer.ActionFileRestored, "a\nb", 123, "restored " + strconv.Quote("a\nb") + " with size 123 B"}, } { term, printer := createTextProgress() - printer.CompleteItem(data.action, "test", data.size) + printer.CompleteItem(data.action, data.item, data.size) test.Equals(t, []string{data.expected}, term.Output) } } @@ -69,4 +72,8 @@ func TestError(t *testing.T) { term, printer := createTextProgress() test.Equals(t, printer.Error("/path", errors.New("error \"message\"")), nil) test.Equals(t, []string{"ignoring error for /path: error \"message\"\n"}, term.Errors) + + term, printer = createTextProgress() + test.Equals(t, printer.Error("a\nb", errors.New("failed")), nil) + test.Equals(t, []string{"ignoring error for " + strconv.Quote("a\nb") + ": failed\n"}, term.Errors) } From 2518cd4a75d9c5456e850ca46c3d90b8aebf3bd3 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 14:13:28 +0100 Subject: [PATCH 03/14] data / repository: quote fields in String() methods --- cmd/restic/cmd_forget.go | 2 +- cmd/restic/cmd_forget_integration_test.go | 2 +- cmd/restic/format.go | 6 +++--- cmd/restic/format_test.go | 22 ++++++++++++++++++++++ internal/data/node.go | 2 +- internal/data/node_test.go | 10 ++++++++++ internal/data/snapshot.go | 3 ++- internal/data/snapshot_group.go | 8 +++++--- internal/data/snapshot_group_test.go | 13 +++++++++++++ internal/data/snapshot_test.go | 12 ++++++++++++ internal/data/tag_list.go | 4 +++- internal/data/tag_list_test.go | 6 ++++++ internal/repository/key.go | 3 ++- internal/repository/lock_file.go | 3 ++- internal/repository/lock_file_test.go | 23 +++++++++++++++++++++++ 15 files changed, 106 insertions(+), 13 deletions(-) diff --git a/cmd/restic/cmd_forget.go b/cmd/restic/cmd_forget.go index 01568f22a..8368c1b96 100644 --- a/cmd/restic/cmd_forget.go +++ b/cmd/restic/cmd_forget.go @@ -280,7 +280,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption keep, remove, reasons := data.ApplyPolicy(snapshotGroup, policy) if !policy.Empty() && len(keep) == 0 { - return fmt.Errorf("refusing to delete last snapshot of snapshot group \"%v\"", key.String()) + return fmt.Errorf("refusing to delete last snapshot of snapshot group [%s]", key.String()) } if len(keep) != 0 && !gopts.Quiet && !gopts.JSON { printer.P("keep %d snapshots:\n", len(keep)) diff --git a/cmd/restic/cmd_forget_integration_test.go b/cmd/restic/cmd_forget_integration_test.go index 93a178481..38d107b29 100644 --- a/cmd/restic/cmd_forget_integration_test.go +++ b/cmd/restic/cmd_forget_integration_test.go @@ -42,7 +42,7 @@ func TestRunForgetSafetyNet(t *testing.T) { KeepTags: data.TagLists{data.TagList{"invalid"}}, GroupBy: data.SnapshotGroupByOptions{Host: true, Path: true}, }) - rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group "host example, path`), "wrong error message got %v", err) + rtest.Assert(t, strings.Contains(err.Error(), `refusing to delete last snapshot of snapshot group [host example, path`), "wrong error message got %v", err) // disallow `forget --unsafe-allow-remove-all` err = testRunForgetMayFail(t, env.gopts, ForgetOptions{ diff --git a/cmd/restic/format.go b/cmd/restic/format.go index 79e55570a..4614a4629 100644 --- a/cmd/restic/format.go +++ b/cmd/restic/format.go @@ -11,7 +11,7 @@ import ( func formatNodeOutput(n lsNodeOutput, long bool, human bool) string { if !long { - return n.Path + return ui.Quote(n.Path) } var mode os.FileMode @@ -31,7 +31,7 @@ func formatNodeOutput(n lsNodeOutput, long bool, human bool) string { mode = os.ModeDir case data.NodeTypeSymlink: mode = os.ModeSymlink - target = fmt.Sprintf(" -> %v", n.LinkTarget) + target = fmt.Sprintf(" -> %s", ui.Quote(n.LinkTarget)) case data.NodeTypeDev: mode = os.ModeDevice case data.NodeTypeCharDev: @@ -44,7 +44,7 @@ func formatNodeOutput(n lsNodeOutput, long bool, human bool) string { return fmt.Sprintf("%s %5d %5d %s %s %s%s", mode|n.Mode, n.UID, n.GID, size, - n.ModTime.Local().Format(global.TimeFormat), n.Path, + n.ModTime.Local().Format(global.TimeFormat), ui.Quote(n.Path), target) } diff --git a/cmd/restic/format_test.go b/cmd/restic/format_test.go index 9d19a70f4..f584ba3d9 100644 --- a/cmd/restic/format_test.go +++ b/cmd/restic/format_test.go @@ -1,6 +1,8 @@ package main import ( + "os" + "strconv" "testing" "time" @@ -54,6 +56,26 @@ func TestFormatNode(t *testing.T) { human: true, expect: "---------- 1000 2000 14.000 MiB 2020-01-02 03:04:05 " + testPath, }, + { + path: "dir\nfile", + Node: node, + long: false, + expect: strconv.Quote("dir\nfile"), + }, + { + path: "dir\nfile", + Node: data.Node{ + Name: "link", + Type: data.NodeTypeSymlink, + Mode: os.ModeSymlink | 0777, + LinkTarget: "target\x1b", + UID: 1000, + GID: 2000, + ModTime: time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC), + }, + long: true, + expect: "Lrwxrwxrwx 1000 2000 0 2020-01-02 03:04:05 " + strconv.Quote("dir\nfile") + " -> " + strconv.Quote("target\x1b"), + }, } { r := formatNode(c.path, &c.Node, c.long, c.human) rtest.Equals(t, c.expect, r) diff --git a/internal/data/node.go b/internal/data/node.go index 7f2154ebb..b9a27f388 100644 --- a/internal/data/node.go +++ b/internal/data/node.go @@ -135,7 +135,7 @@ func (node Node) String() string { } return fmt.Sprintf("%s %5d %5d %6d %s %s", - mode|node.Mode, node.UID, node.GID, node.Size, node.ModTime, node.Name) + mode|node.Mode, node.UID, node.GID, node.Size, node.ModTime, ui.Quote(node.Name)) } // GetExtendedAttribute gets the extended attribute. diff --git a/internal/data/node_test.go b/internal/data/node_test.go index 06a527cfd..675a1cf95 100644 --- a/internal/data/node_test.go +++ b/internal/data/node_test.go @@ -2,6 +2,8 @@ package data import ( "encoding/json" + "strconv" + "strings" "testing" "time" @@ -93,3 +95,11 @@ func TestSymlinkSerializationFormat(t *testing.T) { test.Assert(t, n2.LinkTargetRaw == nil, "quoted link target is just a helper field and must be unset after decoding") } } + +func TestNodeStringQuotesName(t *testing.T) { + ordinary := Node{Name: "file", UID: 1, GID: 2}.String() + test.Assert(t, strings.HasSuffix(ordinary, " file"), "ordinary name was quoted: %s", ordinary) + + quoted := Node{Name: "a\nb", UID: 1, GID: 2}.String() + test.Assert(t, strings.HasSuffix(quoted, " "+strconv.Quote("a\nb")), "hostile name was not quoted: %s", quoted) +} diff --git a/internal/data/snapshot.go b/internal/data/snapshot.go index 18972ff79..f27543737 100644 --- a/internal/data/snapshot.go +++ b/internal/data/snapshot.go @@ -11,6 +11,7 @@ import ( "github.com/restic/restic/internal/debug" "github.com/restic/restic/internal/restic" + "github.com/restic/restic/internal/ui" ) // Snapshot is the state of a resource at one point in time. @@ -119,7 +120,7 @@ func ForAllSnapshots(ctx context.Context, be restic.Lister, loader restic.Loader func (sn Snapshot) String() string { return fmt.Sprintf("snapshot %s of %v at %s by %s@%s", - sn.id.Str(), sn.Paths, sn.Time, sn.Username, sn.Hostname) + sn.id.Str(), ui.QuoteSlice(sn.Paths), sn.Time, ui.Quote(sn.Username), ui.Quote(sn.Hostname)) } // ID returns the snapshot's ID. diff --git a/internal/data/snapshot_group.go b/internal/data/snapshot_group.go index 620e153f5..9033781d1 100644 --- a/internal/data/snapshot_group.go +++ b/internal/data/snapshot_group.go @@ -5,6 +5,8 @@ import ( "fmt" "sort" "strings" + + "github.com/restic/restic/internal/ui" ) type SnapshotGroupByOptions struct { @@ -69,13 +71,13 @@ type SnapshotGroupKey struct { func (s *SnapshotGroupKey) String() string { var parts []string if s.Hostname != "" { - parts = append(parts, fmt.Sprintf("host %v", s.Hostname)) + parts = append(parts, fmt.Sprintf("host %v", ui.Quote(s.Hostname))) } if len(s.Paths) != 0 { - parts = append(parts, fmt.Sprintf("path %v", s.Paths)) + parts = append(parts, fmt.Sprintf("path %v", ui.QuoteSlice(s.Paths))) } if len(s.Tags) != 0 { - parts = append(parts, fmt.Sprintf("tags %v", s.Tags)) + parts = append(parts, fmt.Sprintf("tags %v", ui.QuoteSlice(s.Tags))) } return strings.Join(parts, ", ") } diff --git a/internal/data/snapshot_group_test.go b/internal/data/snapshot_group_test.go index 3cbbc7862..e009d02ae 100644 --- a/internal/data/snapshot_group_test.go +++ b/internal/data/snapshot_group_test.go @@ -1,6 +1,7 @@ package data_test import ( + "strconv" "testing" "github.com/google/go-cmp/cmp" @@ -48,3 +49,15 @@ func TestGroupByOptions(t *testing.T) { test.Assert(t, err != nil, "missing error on invalid tags") test.Assert(t, !opts.Host && !opts.Path && !opts.Tag, "unexpected opts %s %s %s", opts.Host, opts.Path, opts.Tag) } + +func TestSnapshotGroupKeyStringQuotes(t *testing.T) { + ordinary := (&data.SnapshotGroupKey{Hostname: "host", Paths: []string{"/ok"}, Tags: []string{"tag"}}).String() + test.Equals(t, "host host, path [/ok], tags [tag]", ordinary) + + hostile := (&data.SnapshotGroupKey{ + Hostname: "a\nb", + Paths: []string{"/ok", "p\nq"}, + Tags: []string{"t\tu"}, + }).String() + test.Equals(t, "host "+strconv.Quote("a\nb")+", path [/ok "+strconv.Quote("p\nq")+"], tags ["+strconv.Quote("t\tu")+"]", hostile) +} diff --git a/internal/data/snapshot_test.go b/internal/data/snapshot_test.go index 84c93228e..2aeae6cb4 100644 --- a/internal/data/snapshot_test.go +++ b/internal/data/snapshot_test.go @@ -66,3 +66,15 @@ func testLoadJSONUnpacked(t *testing.T, version uint) { rtest.Equals(t, sn.Hostname, sn2.Hostname) rtest.Equals(t, sn.Username, sn2.Username) } + +func TestSnapshotStringQuotesFields(t *testing.T) { + ordinary := data.Snapshot{Paths: []string{"/home"}, Username: "alice", Hostname: "box"}.String() + rtest.Equals(t, "snapshot [nil] of [/home] at 0001-01-01 00:00:00 +0000 UTC by alice@box", ordinary) + + hostile := data.Snapshot{ + Paths: []string{"/ok", "a\nb"}, + Username: "u\nv", + Hostname: "host", + }.String() + rtest.Equals(t, `snapshot [nil] of [/ok "a\nb"] at 0001-01-01 00:00:00 +0000 UTC by "u\nv"@host`, hostile) +} diff --git a/internal/data/tag_list.go b/internal/data/tag_list.go index 4139e5624..7d5a26c88 100644 --- a/internal/data/tag_list.go +++ b/internal/data/tag_list.go @@ -4,6 +4,8 @@ import ( "fmt" "slices" "strings" + + "github.com/restic/restic/internal/ui" ) // TagList is a list of tags. @@ -25,7 +27,7 @@ func splitTagList(s string) (TagList, error) { } func (l TagList) String() string { - return "[" + strings.Join(l, ", ") + "]" + return "[" + strings.Join(ui.QuoteSlice(l), ", ") + "]" } // Set updates the TagList's value. diff --git a/internal/data/tag_list_test.go b/internal/data/tag_list_test.go index 17f9df669..c463021f7 100644 --- a/internal/data/tag_list_test.go +++ b/internal/data/tag_list_test.go @@ -1,6 +1,7 @@ package data import ( + "strconv" "testing" rtest "github.com/restic/restic/internal/test" @@ -78,3 +79,8 @@ func TestTagListSetInvalid(t *testing.T) { rtest.Equals(t, TagLists(nil), ls) } } + +func TestTagListStringQuotes(t *testing.T) { + rtest.Equals(t, "[ok, plain]", TagList{"ok", "plain"}.String()) + rtest.Equals(t, "[ok, "+strconv.Quote("a\nb")+"]", TagList{"ok", "a\nb"}.String()) +} diff --git a/internal/repository/key.go b/internal/repository/key.go index 279fbf2b6..ee1d1630f 100644 --- a/internal/repository/key.go +++ b/internal/repository/key.go @@ -11,6 +11,7 @@ import ( "github.com/restic/restic/internal/errors" "github.com/restic/restic/internal/restic" + "github.com/restic/restic/internal/ui" "github.com/restic/restic/internal/backend" "github.com/restic/restic/internal/debug" @@ -299,7 +300,7 @@ func (k *Key) String() string { if k == nil { return "" } - return fmt.Sprintf("", k.Username, k.Hostname, k.Created) + return fmt.Sprintf("", ui.Quote(k.Username), ui.Quote(k.Hostname), k.Created) } // ID returns an identifier for the key. diff --git a/internal/repository/lock_file.go b/internal/repository/lock_file.go index b05bf286a..654d57149 100644 --- a/internal/repository/lock_file.go +++ b/internal/repository/lock_file.go @@ -12,6 +12,7 @@ import ( "github.com/restic/restic/internal/debug" "github.com/restic/restic/internal/errors" "github.com/restic/restic/internal/restic" + "github.com/restic/restic/internal/ui" ) // unlockCancelDelay bounds the duration how long lock cleanup operations will wait @@ -376,7 +377,7 @@ func (l *lockHandle) checkExistence(ctx context.Context) (bool, error) { func (l *lockHandle) String() string { text := fmt.Sprintf("PID %d on %s by %s (UID %d, GID %d)\nlock was created at %s (%s ago)\nstorage ID %v", - l.PID, l.Hostname, l.Username, l.UID, l.GID, + l.PID, ui.Quote(l.Hostname), ui.Quote(l.Username), l.UID, l.GID, l.Time.Format("2006-01-02 15:04:05"), time.Since(l.Time), l.lockID.Str()) diff --git a/internal/repository/lock_file_test.go b/internal/repository/lock_file_test.go index c8b2984f2..54bcd7bee 100644 --- a/internal/repository/lock_file_test.go +++ b/internal/repository/lock_file_test.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "os" + "regexp" "testing" "time" @@ -246,3 +247,25 @@ func TestLockRefreshStaleMissing(t *testing.T) { err = lock.refreshStaleLock(context.TODO()) rtest.Assert(t, err == errRemovedLock, "unexpected error, expected %v, got %v", errRemovedLock, err) } + +func TestLockStringQuotesHost(t *testing.T) { + created := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC) + age := regexp.MustCompile(`\([^)]* ago\)`) + lockText := func(host string) string { + return age.ReplaceAllString((&lockHandle{Lock: Lock{PID: 7, Hostname: host, Username: "user", UID: 1, GID: 2, Time: created}}).String(), "(AGE ago)") + } + + rtest.Equals(t, "PID 7 on host by user (UID 1, GID 2)\nlock was created at 2020-01-02 03:04:05 (AGE ago)\nstorage ID [nil]", lockText("host")) + rtest.Equals(t, "PID 7 on \"h\\x1b\" by user (UID 1, GID 2)\nlock was created at 2020-01-02 03:04:05 (AGE ago)\nstorage ID [nil]", lockText("h\x1b")) +} + +func TestKeyStringQuotesIdentity(t *testing.T) { + rtest.Equals(t, "", (*Key)(nil).String()) + + created := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC) + ordinary := (&Key{Username: "alice", Hostname: "box", Created: created}).String() + rtest.Equals(t, "", ordinary) + + hostile := (&Key{Username: "a\nb", Hostname: "box", Created: created}).String() + rtest.Equals(t, ``, hostile) +} From 76925aeb636fde9f385abc7ffa8069ad0c08d823 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 13:45:14 +0100 Subject: [PATCH 04/14] always quote paths in error messages --- cmd/restic/cmd_backup.go | 2 +- cmd/restic/cmd_mount.go | 14 +++++------ internal/archiver/archiver.go | 10 ++++---- internal/archiver/exclude.go | 4 +-- internal/archiver/file_saver.go | 2 +- internal/archiver/tree.go | 2 +- internal/data/tree.go | 10 ++++---- internal/data/tree_test.go | 10 +++++--- internal/dump/tar_test.go | 2 +- internal/dump/zip_test.go | 2 +- internal/fs/file.go | 2 +- internal/fs/fs_local_vss.go | 6 ++--- internal/fs/fs_local_vss_test.go | 21 ++++++---------- internal/fs/node_test.go | 4 +-- internal/fs/node_windows.go | 34 +++++++++++++------------- internal/fs/node_windows_test.go | 28 ++++++++++----------- internal/fs/node_xattr.go | 2 +- internal/fs/priv_windows_test.go | 8 +++--- internal/fs/sd_windows_test.go | 6 ++--- internal/fs/sd_windows_test_helpers.go | 28 ++++++++++----------- internal/fs/stat_darwin.go | 2 +- internal/fs/stat_darwin_test.go | 2 +- internal/fs/stat_windows.go | 2 +- internal/fs/vss_windows.go | 6 ++--- internal/global/global.go | 18 +++++++------- internal/global/global_test.go | 3 ++- internal/repository/upgrade_repo.go | 2 +- internal/restorer/restorer.go | 10 ++++---- internal/restorer/restorer_test.go | 10 ++++---- internal/walker/walker.go | 2 +- 30 files changed, 126 insertions(+), 128 deletions(-) diff --git a/cmd/restic/cmd_backup.go b/cmd/restic/cmd_backup.go index 35e2ec5be..1101f9c70 100644 --- a/cmd/restic/cmd_backup.go +++ b/cmd/restic/cmd_backup.go @@ -424,7 +424,7 @@ func collectTargets(opts BackupOptions, args []string, warnf func(msg string, ar var expanded []string expanded, err := filepath.Glob(line) if err != nil { - return nil, fmt.Errorf("pattern: %s: %w", line, err) + return nil, fmt.Errorf("pattern: %q: %w", line, err) } if len(expanded) == 0 { warnf("pattern %q does not match any files, skipping\n", line) diff --git a/cmd/restic/cmd_mount.go b/cmd/restic/cmd_mount.go index e761f2254..eed2a7b1a 100644 --- a/cmd/restic/cmd_mount.go +++ b/cmd/restic/cmd_mount.go @@ -227,16 +227,16 @@ func validateMountpoint(mountpoint string, gopts global.Options) error { // prevent unnecessary computations while opening the repository. stat, err := os.Stat(mountpoint) if errors.Is(err, os.ErrNotExist) { - return errors.Fatal(fmt.Sprintf("mountpoint %s does not exist", mountpoint)) + return errors.Fatal(fmt.Sprintf("mountpoint %q does not exist", mountpoint)) } else if err != nil { - return errors.Fatal(fmt.Sprintf("mountpoint %s is inaccessible: %v", mountpoint, err)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is inaccessible: %v", mountpoint, err)) } else if !stat.IsDir() { - return errors.Fatal(fmt.Sprintf("mountpoint %s is not a directory", mountpoint)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is not a directory", mountpoint)) } err = unix.Access(mountpoint, unix.W_OK|unix.X_OK) if err != nil { - return errors.Fatal(fmt.Sprintf("mountpoint %s is not writeable or not executable", mountpoint)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is not writeable or not executable", mountpoint)) } // Refuse to mount onto (or under, or over) the local repository directory. @@ -271,11 +271,11 @@ func checkMountpointOverlap(repoPath, mountpoint string) error { const tail = "; refusing to mount to avoid deadlocking the FUSE server" switch { case rp == mp: - return errors.Fatal(fmt.Sprintf("mountpoint %s is the local repository directory%s", mp, tail)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is the local repository directory%s", mp, tail)) case fs.HasPathPrefix(rp, mp): - return errors.Fatal(fmt.Sprintf("mountpoint %s is inside the local repository directory %s%s", mp, rp, tail)) + return errors.Fatal(fmt.Sprintf("mountpoint %q is inside the local repository directory %q%s", mp, rp, tail)) case fs.HasPathPrefix(mp, rp): - return errors.Fatal(fmt.Sprintf("local repository directory %s is inside the mountpoint %s%s", rp, mp, tail)) + return errors.Fatal(fmt.Sprintf("local repository directory %q is inside the mountpoint %q%s", rp, mp, tail)) } return nil } diff --git a/internal/archiver/archiver.go b/internal/archiver/archiver.go index 1aec70785..4d2292ed4 100644 --- a/internal/archiver/archiver.go +++ b/internal/archiver/archiver.go @@ -272,7 +272,7 @@ func (arch *Archiver) nodeFromFileInfo(snPath, filename string, meta toNoder, ig node.Name = path.Base(snPath) // do not filter error for nodes of irregular or invalid type if node.Type != data.NodeTypeIrregular && node.Type != data.NodeTypeInvalid && err != nil { - err = fmt.Errorf("incomplete metadata for %v: %w", filename, err) + err = fmt.Errorf("incomplete metadata for %q: %w", filename, err) return node, arch.error(filename, err) } return node, err @@ -383,7 +383,7 @@ func (arch *Archiver) dirToNodeAndEntries(snPath, dir string, meta fs.File) (nod names, err = meta.Readdirnames(-1) if err != nil { - return nil, nil, fmt.Errorf("readdirnames %v failed: %w", dir, err) + return nil, nil, fmt.Errorf("readdirnames %q failed: %w", dir, err) } sort.Strings(names) @@ -547,7 +547,7 @@ func (arch *Archiver) save(ctx context.Context, snPath, target string, previous debug.Log("%v hasn't changed, but contents are missing!", target) // There are contents missing - inform user! - err := errors.Errorf("parts of %v not found in the repository index; storing the file again", target) + err := errors.Errorf("parts of %q not found in the repository index; storing the file again", target) err = arch.error(abstarget, err) if err != nil { return futureNode{}, false, err @@ -670,7 +670,7 @@ func (arch *Archiver) saveTree(ctx context.Context, snPath string, atree *tree, var node *data.Node if snPath != "/" { if atree.FileInfoPath == "" { - return futureNode{}, 0, errors.Errorf("FileInfoPath for %v is empty", snPath) + return futureNode{}, 0, errors.Errorf("FileInfoPath for %q is empty", snPath) } var err error @@ -780,7 +780,7 @@ func (arch *Archiver) dirPathToNode(snPath, target string) (node *data.Node, err return nil, err } if node.Type != data.NodeTypeDir { - return nil, errors.Errorf("path is not a directory: %v", target) + return nil, errors.Errorf("path is not a directory: %q", target) } return node, err } diff --git a/internal/archiver/exclude.go b/internal/archiver/exclude.go index 571680929..c6ec039af 100644 --- a/internal/archiver/exclude.go +++ b/internal/archiver/exclude.go @@ -242,7 +242,7 @@ func (m deviceMap) IsAllowed(item string, deviceID uint64, fs fs.FS) (bool, erro return true, nil } - return false, fmt.Errorf("item %v (device ID %v) not found, deviceMap: %v", item, deviceID, m) + return false, fmt.Errorf("item %q (device ID %v) not found, deviceMap: %v", item, deviceID, m) } // RejectByDevice returns a RejectFunc that rejects files which are on a @@ -322,7 +322,7 @@ func RejectCloudFiles(warnf func(msg string, args ...any)) (RejectFunc, error) { return func(item string, fi *fs.ExtendedFileInfo, _ fs.FS) bool { recall, err := fi.RecallOnDataAccess() if err != nil { - warnf("item %v: error checking online-only status: %v", item, err) + warnf("item %q: error checking online-only status: %v", item, err) return false } diff --git a/internal/archiver/file_saver.go b/internal/archiver/file_saver.go index ab6a9b32f..a5526534b 100644 --- a/internal/archiver/file_saver.go +++ b/internal/archiver/file_saver.go @@ -193,7 +193,7 @@ func (s *fileSaver) saveFile(ctx context.Context, chnker restic.Chunker, chunkSt panic("completed twice") } isCompleted = true - fnr.err = fmt.Errorf("failed to save %v: %w", target, err) + fnr.err = fmt.Errorf("failed to save %q: %w", target, err) fnr.node = nil fnr.stats = ItemStats{} finish(fnr) diff --git a/internal/archiver/tree.go b/internal/archiver/tree.go index 9e760752b..2303e9c53 100644 --- a/internal/archiver/tree.go +++ b/internal/archiver/tree.go @@ -175,7 +175,7 @@ func (t *tree) add(fs fs.FS, target, root string, pc []string, explicit bool) er } if node.Path != "" { - return errors.Errorf("path is already set for target %v", target) + return errors.Errorf("path is already set for target %q", target) } node.Path = target node.Explicit = explicit diff --git a/internal/data/tree.go b/internal/data/tree.go index 1c9e76a19..45c3400e9 100644 --- a/internal/data/tree.go +++ b/internal/data/tree.go @@ -341,22 +341,22 @@ func FindTreeDirectory(ctx context.Context, repo restic.BlobLoader, id *restic.I subfolder = path.Join(subfolder, name) tree, err := LoadTree(ctx, repo, *id) if err != nil { - return nil, fmt.Errorf("path %s: %w", subfolder, err) + return nil, fmt.Errorf("path %q: %w", subfolder, err) } finder := NewTreeFinder(tree) node, err := finder.Find(name) finder.Close() if err != nil { - return nil, fmt.Errorf("path %s: %w", subfolder, err) + return nil, fmt.Errorf("path %q: %w", subfolder, err) } if node == nil { if runtime.GOOS == "windows" && strings.Contains(dir, "\\") { - return nil, fmt.Errorf("path %s: not found; subfolder syntax currently requires forward slashes; check the output of `restic ls` for valid paths", subfolder) + return nil, fmt.Errorf("path %q: not found; subfolder syntax currently requires forward slashes; check the output of `restic ls` for valid paths", subfolder) } - return nil, fmt.Errorf("path %s: not found", subfolder) + return nil, fmt.Errorf("path %q: not found", subfolder) } if node.Type != NodeTypeDir || node.Subtree == nil { - return nil, fmt.Errorf("path %s: not a directory", subfolder) + return nil, fmt.Errorf("path %q: not a directory", subfolder) } id = node.Subtree } diff --git a/internal/data/tree_test.go b/internal/data/tree_test.go index e0e1be9aa..337f4eedc 100644 --- a/internal/data/tree_test.go +++ b/internal/data/tree_test.go @@ -471,8 +471,8 @@ func TestFindTreeDirectory(t *testing.T) { {"", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil}, {"/", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil}, {".", restic.TestParseID("8804a5505fc3012e7d08b2843e9bda1bf3dc7644f64b542470340e1b4059f09f"), nil}, - {"..", restic.ID{}, errors.New("path ..: not found")}, - {"file-1", restic.ID{}, errors.New("path file-1: not a directory")}, + {"..", restic.ID{}, errors.New(`path "..": not found`)}, + {"file-1", restic.ID{}, errors.New(`path "file-1": not a directory`)}, {"dir-7", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil}, {"/dir-7", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil}, {"dir-7/", restic.TestParseID("1af51eb70cd4457d51db40d649bb75446a3eaa29b265916d411bb7ae971d4849"), nil}, @@ -491,6 +491,10 @@ func TestFindTreeDirectory(t *testing.T) { _, err := data.FindTreeDirectory(context.TODO(), repo, nil, "") rtest.Assert(t, err != nil, "missing error on null tree id") + + _, err = data.FindTreeDirectory(context.TODO(), repo, sn.Tree, "a\nb") + rtest.Assert(t, err != nil && strings.Contains(err.Error(), strconv.Quote("a\nb")), + "hostile path was not quoted: %v", err) } func TestFindTreeDirectoryWindowsBackslashHint(t *testing.T) { @@ -504,7 +508,7 @@ func TestFindTreeDirectoryWindowsBackslashHint(t *testing.T) { rtest.Assert(t, strings.Contains(err.Error(), "forward slashes"), "expected backslash hint on Windows, got %v", err) } else { - rtest.Assert(t, err.Error() == `path missing\path: not found`, + rtest.Assert(t, err.Error() == `path "missing\\path": not found`, "unexpected err: %v", err) } } diff --git a/internal/dump/tar_test.go b/internal/dump/tar_test.go index 06e49c828..dd164028d 100644 --- a/internal/dump/tar_test.go +++ b/internal/dump/tar_test.go @@ -87,7 +87,7 @@ func checkTar(t *testing.T, testDir string, srcTar *bytes.Buffer) error { return err } if target != hdr.Linkname { - return fmt.Errorf("symlink target does not match, got %s want %s", target, hdr.Linkname) + return fmt.Errorf("symlink target does not match, got %q want %q", target, hdr.Linkname) } default: if match.Size() != hdr.Size { diff --git a/internal/dump/zip_test.go b/internal/dump/zip_test.go index c6eb04206..64c85568f 100644 --- a/internal/dump/zip_test.go +++ b/internal/dump/zip_test.go @@ -98,7 +98,7 @@ func checkZip(t *testing.T, testDir string, srcZip *bytes.Buffer) error { t.Fatal(err) } if target != string(linkName) { - return fmt.Errorf("symlink target does not match, got %s want %s", string(linkName), target) + return fmt.Errorf("symlink target does not match, got %q want %q", string(linkName), target) } default: if f.Method != zip.Deflate { diff --git a/internal/fs/file.go b/internal/fs/file.go index 21ba4244a..509664a78 100644 --- a/internal/fs/file.go +++ b/internal/fs/file.go @@ -75,7 +75,7 @@ func Readdirnames(filesystem FS, dir string, flags int) ([]string, error) { entries, err := f.Readdirnames(-1) if err != nil { _ = f.Close() - return nil, fmt.Errorf("readdirnames %v failed: %w", dir, err) + return nil, fmt.Errorf("readdirnames %q failed: %w", dir, err) } err = f.Close() diff --git a/internal/fs/fs_local_vss.go b/internal/fs/fs_local_vss.go index e0b04ac8f..c4462ea4f 100644 --- a/internal/fs/fs_local_vss.go +++ b/internal/fs/fs_local_vss.go @@ -74,7 +74,7 @@ func parseMountPoints(list string, msgError ErrorHandler) (volumes map[string]st } for s := range strings.SplitSeq(list, ";") { if v, err := getVolumeNameForVolumeMountPoint(s); err != nil { - msgError(s, errors.Errorf("failed to parse vss.exclude-volumes [%s]: %s", s, err)) + msgError(s, errors.Errorf("failed to parse vss.exclude-volumes %q: %s", s, err)) } else { if volumes == nil { volumes = make(map[string]struct{}) @@ -137,7 +137,7 @@ func (fs *LocalVss) isMountPointIncluded(mountPoint string) bool { volume, err := getVolumeNameForVolumeMountPoint(mountPoint) if err != nil { - fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point [%s]: %s", mountPoint, err)) + fs.msgError(mountPoint, errors.Errorf("failed to get volume from mount point %q: %s", mountPoint, err)) return true } @@ -193,7 +193,7 @@ func (fs *LocalVss) snapshotPath(path string) string { } if snapshot, err := newVssSnapshot(fs.provider, vssVolume, fs.timeout, includeVolume, fs.msgError); err != nil { - fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for [%s]: %s", + fs.msgError(vssVolume, errors.Errorf("failed to create snapshot for %q: %s", vssVolume, err)) fs.failedSnapshots[volumeNameLower] = struct{}{} } else { diff --git a/internal/fs/fs_local_vss_test.go b/internal/fs/fs_local_vss_test.go index 15536804e..7e7e3d936 100644 --- a/internal/fs/fs_local_vss_test.go +++ b/internal/fs/fs_local_vss_test.go @@ -24,14 +24,7 @@ func matchStrings(ptrs []string, strs []string) bool { } for i, p := range ptrs { - if p == "" { - return false - } - matched, err := regexp.MatchString(p, strs[i]) - if err != nil { - panic(err) - } - if !matched { + if p == "" || !strings.HasPrefix(strs[i], p) { return false } } @@ -180,12 +173,12 @@ func TestParseMountPoints(t *testing.T) { {``, true}, }, []string{ - `failed to parse vss\.exclude-volumes \[z:\\nonexistent\]:.*`, - `failed to parse vss\.exclude-volumes \[c:\\windows\\\]:.*`, - `failed to parse vss\.exclude-volumes \[\\\\\?\\Volume\{39b9cac2-bcdb-4d51-97c8-0d0677d607fb\}\\\]:.*`, - `failed to get volume from mount point \[c:\\windows\\\]:.*`, - `failed to get volume from mount point \[\\\\\?\\Volume\{39b9cac2-bcdb-4d51-97c8-0d0677d607fb\}\\\]:.*`, - `failed to get volume from mount point \[\]:.*`, + `failed to parse vss.exclude-volumes "z:\\nonexistent":`, + `failed to parse vss.exclude-volumes "c:\\windows\\":`, + `failed to parse vss.exclude-volumes "\\\\?\\Volume{39b9cac2-bcdb-4d51-97c8-0d0677d607fb}\\":`, + `failed to get volume from mount point "c:\\windows\\":`, + `failed to get volume from mount point "\\\\?\\Volume{39b9cac2-bcdb-4d51-97c8-0d0677d607fb}\\":`, + `failed to get volume from mount point "":`, }, }, } diff --git a/internal/fs/node_test.go b/internal/fs/node_test.go index 4f087635e..3792d3ed2 100644 --- a/internal/fs/node_test.go +++ b/internal/fs/node_test.go @@ -219,7 +219,7 @@ func TestNodeRestoreAt(t *testing.T) { } rtest.OK(t, NodeCreateAt(&test, nodePath)) // Restore metadata, restoring all xattrs - rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) }, + rtest.OK(t, NodeRestoreMetadata(&test, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", nodePath, msg)) }, func(_ string) bool { return true }, ownershipByName)) fs := NewLocal() @@ -296,7 +296,7 @@ func TestNodeRestoreMetadataError(t *testing.T) { nodePath := filepath.Join(tempdir, node.Name) // This will fail because the target file does not exist - err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", nodePath, msg)) }, + err := NodeRestoreMetadata(node, nodePath, func(msg string) { rtest.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", nodePath, msg)) }, func(_ string) bool { return true }, false) rtest.Assert(t, errors.Is(err, os.ErrNotExist), "failed for an unexpected reason") } diff --git a/internal/fs/node_windows.go b/internal/fs/node_windows.go index 1d4c3f801..4f6d74442 100644 --- a/internal/fs/node_windows.go +++ b/internal/fs/node_windows.go @@ -115,7 +115,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(for return nil } if err != nil { - return errors.Errorf("get EA failed while opening file handle for path %v, with: %v", path, err) + return errors.Errorf("get EA failed while opening file handle for path %q, with: %v", path, err) } defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call //Get the windows Extended Attributes using the file handle @@ -123,7 +123,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, _ bool, _ func(for extAtts, err = fgetEA(fileHandle) debug.Log("fillExtendedAttributes(%v) %v", path, extAtts) if err != nil { - return errors.Errorf("get EA failed for path %v, with: %v", path, err) + return errors.Errorf("get EA failed for path %q, with: %v", path, err) } if len(extAtts) == 0 { return nil @@ -157,7 +157,7 @@ func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extend return nil } if err != nil { - return errors.Errorf("set EA failed while opening file handle for path %v, with: %v", path, err) + return errors.Errorf("set EA failed while opening file handle for path %q, with: %v", path, err) } defer closeFileHandle(fileHandle, path) // Replaced inline defer with named function call @@ -182,7 +182,7 @@ func restoreExtendedAttributes(nodeType data.NodeType, path string, eas []extend } if err = fsetEA(fileHandle, eas); err != nil { - return errors.Errorf("set EA failed for path %v, with: %v", path, err) + return errors.Errorf("set EA failed for path %q, with: %v", path, err) } return nil } @@ -195,21 +195,21 @@ func nodeRestoreGenericAttributes(node *data.Node, path string, warn func(msg st var errs []error windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes) if err != nil { - return fmt.Errorf("error parsing generic attribute for: %s : %v", path, err) + return fmt.Errorf("error parsing generic attribute for: %q : %v", path, err) } if windowsAttributes.CreationTime != nil { if err := restoreCreationTime(path, windowsAttributes.CreationTime); err != nil { - errs = append(errs, fmt.Errorf("error restoring creation time for: %s : %v", path, err)) + errs = append(errs, fmt.Errorf("error restoring creation time for: %q : %v", path, err)) } } if windowsAttributes.FileAttributes != nil { if err := restoreFileAttributes(path, windowsAttributes.FileAttributes); err != nil { - errs = append(errs, fmt.Errorf("error restoring file attributes for: %s : %v", path, err)) + errs = append(errs, fmt.Errorf("error restoring file attributes for: %q : %v", path, err)) } } if windowsAttributes.SecurityDescriptor != nil { if err := setSecurityDescriptor(path, windowsAttributes.SecurityDescriptor); err != nil { - errs = append(errs, fmt.Errorf("error restoring security descriptor for: %s : %v", path, err)) + errs = append(errs, fmt.Errorf("error restoring security descriptor for: %q : %v", path, err)) } } @@ -272,24 +272,24 @@ func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (er // The readonly and system flags will be set again at the end of this func if they are needed. err = ResetPermissions(path) if err != nil { - return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: failed to reset permissions: %q : %v", path, err) } err = clearSystem(path) if err != nil { - return fmt.Errorf("failed to encrypt file: failed to clear system flag: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: failed to clear system flag: %q : %v", path, err) } err = encryptFile(pathPointer) if err != nil { - return fmt.Errorf("failed retry to encrypt file: %s : %v", path, err) + return fmt.Errorf("failed retry to encrypt file: %q : %v", path, err) } } else { - return fmt.Errorf("failed to encrypt file: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: %q : %v", path, err) } } } else { existingAttrs, err := windows.GetFileAttributes(pathPointer) if err != nil { - return fmt.Errorf("failed to get file attributes for existing file: %s : %v", path, err) + return fmt.Errorf("failed to get file attributes for existing file: %q : %v", path, err) } if existingAttrs&windows.FILE_ATTRIBUTE_ENCRYPTED != 0 { // File should not be encrypted, but it's already encrypted. Decrypt it. @@ -300,18 +300,18 @@ func fixEncryptionAttribute(path string, attrs *uint32, pathPointer *uint16) (er // The readonly and system flags will be set again after this func if they are needed. err = ResetPermissions(path) if err != nil { - return fmt.Errorf("failed to encrypt file: failed to reset permissions: %s : %v", path, err) + return fmt.Errorf("failed to encrypt file: failed to reset permissions: %q : %v", path, err) } err = clearSystem(path) if err != nil { - return fmt.Errorf("failed to decrypt file: failed to clear system flag: %s : %v", path, err) + return fmt.Errorf("failed to decrypt file: failed to clear system flag: %q : %v", path, err) } err = decryptFile(pathPointer) if err != nil { - return fmt.Errorf("failed retry to decrypt file: %s : %v", path, err) + return fmt.Errorf("failed retry to decrypt file: %q : %v", path, err) } } else { - return fmt.Errorf("failed to decrypt file: %s : %v", path, err) + return fmt.Errorf("failed to decrypt file: %q : %v", path, err) } } } diff --git a/internal/fs/node_windows_test.go b/internal/fs/node_windows_test.go index 174c637bd..a7c5feaa7 100644 --- a/internal/fs/node_windows_test.go +++ b/internal/fs/node_windows_test.go @@ -33,10 +33,10 @@ func TestRestoreSecurityDescriptors(t *testing.T) { func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, fileType data.NodeType, fileName string) { // Decode the encoded string SD to get the security descriptor input in bytes. sdInputBytes, err := base64.StdEncoding.DecodeString(sd) - test.OK(t, errors.Wrapf(err, "Error decoding SD for: %s", fileName)) + test.OK(t, errors.Wrapf(err, "Error decoding SD for: %q", fileName)) // Wrap the security descriptor bytes in windows attributes and convert to generic attributes. genericAttributes, err := data.WindowsAttrsToGenericAttributes(data.WindowsAttributes{CreationTime: nil, FileAttributes: nil, SecurityDescriptor: &sdInputBytes}) - test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %s", fileName)) + test.OK(t, errors.Wrapf(err, "Error constructing windows attributes for: %q", fileName)) // Construct a Node with the generic attributes. expectedNode := getNode(fileName, fileType, genericAttributes) @@ -47,7 +47,7 @@ func testRestoreSecurityDescriptor(t *testing.T, sd string, tempDir string, file // Get the security descriptor for the test path after the restore. sdBytesFromRestoredPath, err := getSecurityDescriptor(testPath) - test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error while getting the security descriptor for: %q", testPath)) // Compare the input SD and the SD got from the restored file. compareSecurityDescriptors(t, testPath, sdInputBytes, *sdBytesFromRestoredPath) @@ -239,7 +239,7 @@ func getNode(name string, fileType data.NodeType, genericAttributes map[data.Gen func getWindowsAttr(t *testing.T, testPath string, node *data.Node) data.WindowsAttributes { windowsAttributes, unknownAttribs, err := genericAttributesToWindowsAttrs(node.GenericAttributes) - test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting windows attr from generic attr: %q", testPath)) test.Assert(t, len(unknownAttribs) == 0, "Unknown attribs found: %s for: %s", unknownAttribs, testPath) return windowsAttributes } @@ -248,7 +248,7 @@ func TestRestoreCreationTime(t *testing.T) { t.Parallel() path := t.TempDir() fi, err := os.Lstat(path) - test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %s", path)) + test.OK(t, errors.Wrapf(err, "Could not Lstat for path: %q", path)) attr := fi.Sys().(*syscall.Win32FileAttributeData) creationTimeAttribute := attr.CreationTime //Using the temp dir creation time as the test creation time for the test file and folder @@ -367,17 +367,17 @@ func runGenericAttributesTestForNodes(t *testing.T, expectedNodes []data.Node, t func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warningExpected bool) (string, *data.Node) { testPath := filepath.Join(tempDir, "001", testNode.Name) err := os.MkdirAll(filepath.Dir(testPath), testNode.Mode) - test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to create parent directories for: %q", testPath)) if testNode.Type == data.NodeTypeFile { testFile, err := os.Create(testPath) - test.OK(t, errors.Wrapf(err, "Failed to create test file: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to create test file: %q", testPath)) testFile.Close() } else if testNode.Type == data.NodeTypeDir { err := os.Mkdir(testPath, testNode.Mode) - test.OK(t, errors.Wrapf(err, "Failed to create test directory: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to create test directory: %q", testPath)) } err = NodeRestoreMetadata(testNode, testPath, func(msg string) { @@ -385,16 +385,16 @@ func restoreAndGetNode(t *testing.T, tempDir string, testNode *data.Node, warnin test.Assert(t, warningExpected, "Warning triggered as expected: %s", msg) } else { // If warning is not expected, this code should not get triggered. - test.OK(t, fmt.Errorf("Warning triggered for path: %s: %s", testPath, msg)) + test.OK(t, fmt.Errorf("Warning triggered for path: %q: %s", testPath, msg)) } }, func(_ string) bool { return true }, false) - test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Failed to restore metadata for: %q", testPath)) fs := NewLocal() meta, err := fs.OpenFile(testPath, O_NOFOLLOW, true) test.OK(t, err) nodeFromFileInfo, err := meta.ToNode(false, t.Logf) - test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Could not get NodeFromFileInfo for path: %q", testPath)) test.OK(t, meta.Close()) return testPath, nodeFromFileInfo @@ -474,14 +474,14 @@ func TestRestoreExtendedAttributes(t *testing.T) { if node.Type == data.NodeTypeFile || node.Type == data.NodeTypeDir { handle, err = windows.CreateFile(utf16Path, windows.FILE_READ_EA, 0, nil, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) } - test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error opening file/directory for: %q", testPath)) defer func() { err := windows.Close(handle) - test.OK(t, errors.Wrapf(err, "Error closing file for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error closing file for: %q", testPath)) }() extAttr, err := fgetEA(handle) - test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting extended attributes for: %q", testPath)) test.Equals(t, len(node.ExtendedAttributes), len(extAttr)) for _, expectedExtAttr := range node.ExtendedAttributes { diff --git a/internal/fs/node_xattr.go b/internal/fs/node_xattr.go index 71ecf92c1..016ec6e3a 100644 --- a/internal/fs/node_xattr.go +++ b/internal/fs/node_xattr.go @@ -109,7 +109,7 @@ func nodeFillExtendedAttributes(node *data.Node, path string, ignoreListError bo for _, attr := range xattrs { attrVal, err := getxattr(path, attr) if err != nil { - warnf("can not obtain extended attribute %v for %v: %v\n", attr, path, err) + warnf("can not obtain extended attribute %q for %q: %v\n", attr, path, err) continue } attr := data.ExtendedAttribute{ diff --git a/internal/fs/priv_windows_test.go b/internal/fs/priv_windows_test.go index 504cc678f..9ed5bc913 100644 --- a/internal/fs/priv_windows_test.go +++ b/internal/fs/priv_windows_test.go @@ -17,7 +17,7 @@ func TestBackupPrivilegeBypassACL(t *testing.T) { // Read-only Open/OpenFile should automatically use FILE_FLAG_BACKUP_SEMANTICS since Go v1.20. testfile, err := os.Open(testPath) - test.OK(t, errors.Wrapf(err, "failed to open file for reading: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to open file for reading: %q", testPath)) test.OK(t, testfile.Close()) } @@ -26,7 +26,7 @@ func TestRestorePrivilegeBypassACL(t *testing.T) { // Writable OpenFile needs explicit FILE_FLAG_BACKUP_SEMANTICS. testfile, err := os.OpenFile(testPath, os.O_WRONLY|windows.O_FILE_FLAG_BACKUP_SEMANTICS, 0) - test.OK(t, errors.Wrapf(err, "failed to open file for writing: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to open file for writing: %q", testPath)) test.OK(t, testfile.Close()) } @@ -43,7 +43,7 @@ func testGetRestrictedFilePath(t *testing.T) string { testPath := filepath.Join(tempDir, "testfile.txt") testfile, err := os.Create(testPath) - test.OK(t, errors.Wrapf(err, "failed to create temporary file: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to create temporary file: %q", testPath)) test.OK(t, testfile.Close()) // Set restricted permissions. @@ -53,7 +53,7 @@ func testGetRestrictedFilePath(t *testing.T) string { dacl, _, err := sd.DACL() test.OK(t, errors.Wrap(err, "failed to extract SD DACL")) err = windows.SetNamedSecurityInfo(testPath, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, dacl, nil) - test.OK(t, errors.Wrapf(err, "failed to set SD: %s", testPath)) + test.OK(t, errors.Wrapf(err, "failed to set SD: %q", testPath)) return testPath } diff --git a/internal/fs/sd_windows_test.go b/internal/fs/sd_windows_test.go index 56e5fde07..93efc5f96 100644 --- a/internal/fs/sd_windows_test.go +++ b/internal/fs/sd_windows_test.go @@ -45,14 +45,14 @@ func TestSetGetFolderSecurityDescriptors(t *testing.T) { func testSecurityDescriptors(t *testing.T, testSDs []string, testPath string) { for _, testSD := range testSDs { sdInputBytes, err := base64.StdEncoding.DecodeString(testSD) - test.OK(t, errors.Wrapf(err, "Error decoding SD: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error decoding SD: %q", testPath)) err = setSecurityDescriptor(testPath, &sdInputBytes) - test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error setting file security descriptor for: %q", testPath)) var sdOutputBytes *[]byte sdOutputBytes, err = getSecurityDescriptor(testPath) - test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting file security descriptor for: %q", testPath)) compareSecurityDescriptors(t, testPath, sdInputBytes, *sdOutputBytes) } diff --git a/internal/fs/sd_windows_test_helpers.go b/internal/fs/sd_windows_test_helpers.go index 14f3ead3a..2b9d259a1 100644 --- a/internal/fs/sd_windows_test_helpers.go +++ b/internal/fs/sd_windows_test_helpers.go @@ -42,13 +42,13 @@ func isAdmin() (isAdmin bool, err error) { // compareSecurityDescriptors runs tests for comparing 2 security descriptors in []byte format. func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdOutputBytes []byte) { sdInput, err := securityDescriptorBytesToStruct(sdInputBytes) - test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %q", testPath)) sdOutput, err := securityDescriptorBytesToStruct(sdOutputBytes) - test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error converting SD to struct for: %q", testPath)) isAdmin, err := isAdmin() - test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error checking if user is admin: %q", testPath)) var ownerExpected *windows.SID var defaultedOwnerExpected bool @@ -61,28 +61,28 @@ func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdO // The Dacl is set correctly whether or not application is running as admin. daclExpected, defaultedDaclExpected, err = sdInput.DACL() - test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input dacl for: %q", testPath)) if isAdmin { // If application is running as admin, all sd values including owner, group, dacl, sacl are set correctly during restore. // Hence we will use the input values for comparison with the output values. ownerExpected, defaultedOwnerExpected, err = sdInput.Owner() - test.OK(t, errors.Wrapf(err, "Error getting input owner for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input owner for: %q", testPath)) groupExpected, defaultedGroupExpected, err = sdInput.Group() - test.OK(t, errors.Wrapf(err, "Error getting input group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input group for: %q", testPath)) saclExpected, defaultedSaclExpected, err = sdInput.SACL() - test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting input sacl for: %q", testPath)) } else { // If application is not running as admin, owner and group are set as current user's SID/GID during restore and sacl is empty. // Get the current user user, err := user.Current() - test.OK(t, errors.Wrapf(err, "Could not get current user for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Could not get current user for: %q", testPath)) // Get current user's SID currentUserSID, err := windows.StringToSid(user.Uid) - test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath)) // Get current user's Group SID currentGroupSID, err := windows.StringToSid(user.Gid) - test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath)) // Set owner and group as current user's SID and GID during restore. ownerExpected = currentUserSID @@ -97,28 +97,28 @@ func compareSecurityDescriptors(t *testing.T, testPath string, sdInputBytes, sdO // Now do all the comparisons // Get owner SID from output file ownerOut, defaultedOwnerOut, err := sdOutput.Owner() - test.OK(t, errors.Wrapf(err, "Error getting output owner for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output owner for: %q", testPath)) // Compare owner SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs. test.Assert(t, ownerExpected.Equals(ownerOut), "Owner from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, ownerExpected.String(), ownerOut.String()) test.Equals(t, defaultedOwnerExpected, defaultedOwnerOut, "Defaulted for owner from SDs read from test path don't match: %s", testPath) // Get group SID from output file groupOut, defaultedGroupOut, err := sdOutput.Group() - test.OK(t, errors.Wrapf(err, "Error getting output group for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output group for: %q", testPath)) // Compare group SIDs. We must use the Equals method for comparison as a syscall is made for comparing SIDs. test.Assert(t, groupExpected.Equals(groupOut), "Group from SDs read from test path don't match: %s, cur:%s, exp: %s", testPath, groupExpected.String(), groupOut.String()) test.Equals(t, defaultedGroupExpected, defaultedGroupOut, "Defaulted for group from SDs read from test path don't match: %s", testPath) // Get dacl from output file daclOut, defaultedDaclOut, err := sdOutput.DACL() - test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output dacl for: %q", testPath)) // Compare dacls test.Equals(t, daclExpected, daclOut, "DACL from SDs read from test path don't match: %s", testPath) test.Equals(t, defaultedDaclExpected, defaultedDaclOut, "Defaulted for DACL from SDs read from test path don't match: %s", testPath) // Get sacl from output file saclOut, defaultedSaclOut, err := sdOutput.SACL() - test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %s", testPath)) + test.OK(t, errors.Wrapf(err, "Error getting output sacl for: %q", testPath)) // Compare sacls test.Equals(t, saclExpected, saclOut, "DACL from SDs read from test path don't match: %s", testPath) test.Equals(t, defaultedSaclExpected, defaultedSaclOut, "Defaulted for SACL from SDs read from test path don't match: %s", testPath) diff --git a/internal/fs/stat_darwin.go b/internal/fs/stat_darwin.go index ec94d9f8b..a9d07ee6b 100644 --- a/internal/fs/stat_darwin.go +++ b/internal/fs/stat_darwin.go @@ -44,7 +44,7 @@ func extendedStat(fi os.FileInfo) *ExtendedFileInfo { func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) { extAttribute, ok := fi.sys.(*syscall.Stat_t) if !ok { - return false, fmt.Errorf("could not determine file attributes: %s", fi.Name) + return false, fmt.Errorf("could not determine file attributes: %q", fi.Name) } const mask uint32 = unix.SF_DATALESS // 0x40000000 if extAttribute.Flags&mask == mask { diff --git a/internal/fs/stat_darwin_test.go b/internal/fs/stat_darwin_test.go index c8768e29d..6d9cfc715 100644 --- a/internal/fs/stat_darwin_test.go +++ b/internal/fs/stat_darwin_test.go @@ -86,6 +86,6 @@ func TestRecallOnDataAccessMockError(t *testing.T) { recall, err := efi.RecallOnDataAccess() rtest.Assert(t, err != nil, "err should be set", err) - rtest.Assert(t, err.Error() == "could not determine file attributes: test-file-name", "err message not correct", err) + rtest.Assert(t, err.Error() == `could not determine file attributes: "test-file-name"`, "err message not correct", err) rtest.Assert(t, recall == false, "RecallOnDataAccess should be false") } diff --git a/internal/fs/stat_windows.go b/internal/fs/stat_windows.go index bc4092df8..2e06b864a 100644 --- a/internal/fs/stat_windows.go +++ b/internal/fs/stat_windows.go @@ -45,7 +45,7 @@ func extendedStat(fi os.FileInfo) *ExtendedFileInfo { func (fi *ExtendedFileInfo) RecallOnDataAccess() (bool, error) { attrs, ok := fi.sys.(*syscall.Win32FileAttributeData) if !ok { - return false, fmt.Errorf("could not determine file attributes: %s", fi.Name) + return false, fmt.Errorf("could not determine file attributes: %q", fi.Name) } if attrs.FileAttributes&windows.FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS > 0 { diff --git a/internal/fs/vss_windows.go b/internal/fs/vss_windows.go index 01ca86774..f6378f1b3 100644 --- a/internal/fs/vss_windows.go +++ b/internal/fs/vss_windows.go @@ -969,7 +969,7 @@ func newVssSnapshot(provider string, } else if !isSupported { iVssBackupComponents.Release() return vssSnapshot{}, newVssTextError(fmt.Sprintf("Snapshots are not supported for volume "+ - "%s", volume)) + "%q", volume)) } const retryStartSnapshotSetSleep = 5 * time.Second @@ -1005,7 +1005,7 @@ func newVssSnapshot(provider string, iVssBackupComponents.Release() return vssSnapshot{}, newVssTextError(fmt.Sprintf( - "failed to enumerate mount points for volume %s: %s", volume, err)) + "failed to enumerate mount points for volume %q: %s", volume, err)) } for _, mp := range mountPoints { @@ -1072,7 +1072,7 @@ func newVssSnapshot(provider string, &info.snapshotProperties) if err != nil { msgError(mountPoint, errors.Errorf( - "VSS error: GetSnapshotProperties() for mount point %s returned error: ", + "VSS error: GetSnapshotProperties() for mount point %q returned error: ", mountPoint, err)) info.isSnapshotted = false } else { diff --git a/internal/global/global.go b/internal/global/global.go index 547f7da9e..b46723a08 100644 --- a/internal/global/global.go +++ b/internal/global/global.go @@ -215,7 +215,7 @@ func resolvePassword(opts *Options, envStr string) (string, error) { func LoadPasswordFromFile(pwdFile string) (string, error) { s, err := textfile.Read(pwdFile) if errors.Is(err, os.ErrNotExist) { - return "", errors.Fatalf("%s does not exist", pwdFile) + return "", errors.Fatalf("%q does not exist", pwdFile) } return strings.TrimSpace(string(s)), errors.Wrap(err, "Readfile") } @@ -282,7 +282,7 @@ func readRepo(gopts Options) (string, error) { s, err := textfile.Read(gopts.RepositoryFile) if errors.Is(err, os.ErrNotExist) { - return "", errors.Fatalf("%s does not exist", gopts.RepositoryFile) + return "", errors.Fatalf("%q does not exist", gopts.RepositoryFile) } if err != nil { return "", err @@ -290,7 +290,7 @@ func readRepo(gopts Options) (string, error) { repo = strings.TrimSpace(string(s)) if repo == "" { - return "", errors.Fatalf("repository file %s is empty", gopts.RepositoryFile) + return "", errors.Fatalf("repository file %q is empty", gopts.RepositoryFile) } } @@ -344,10 +344,10 @@ func hasRepositoryConfig(ctx context.Context, be backend.Backend, repo string, g fi, err := be.Stat(ctx, backend.Handle{Type: backend.ConfigFile}) if be.IsNotExist(err) { //nolint:staticcheck // capitalized error string is intentional - return fmt.Errorf("Fatal: %w: unable to open config file: %v\nIs there a repository at the following location?\n%v", ErrNoRepository, err, location.StripPassword(gopts.Backends, repo)) + return fmt.Errorf("Fatal: %w: unable to open config file: %v\nIs there a repository at the following location?\n%q", ErrNoRepository, err, location.StripPassword(gopts.Backends, repo)) } if err != nil { - return errors.Fatalf("unable to open config file: %v\n%v", err, location.StripPassword(gopts.Backends, repo)) + return errors.Fatalf("unable to open config file: %v\n%q", err, location.StripPassword(gopts.Backends, repo)) } if fi.Size == 0 { @@ -479,7 +479,7 @@ func CreateRepository(ctx context.Context, gopts Options, version uint, chunkerP be, err := innerOpenBackend(ctx, repo, gopts, gopts.Extended, true, printer) if err != nil { - return nil, errors.Fatalf("create repository at %s failed: %v", location.StripPassword(gopts.Backends, repo), err) + return nil, errors.Fatalf("create repository at %q failed: %v", location.StripPassword(gopts.Backends, repo), err) } s, err := createRepositoryInstance(be, gopts) @@ -489,7 +489,7 @@ func CreateRepository(ctx context.Context, gopts Options, version uint, chunkerP err = s.Init(ctx, version, gopts.Password, chunkerPolynomial) if err != nil { - return nil, errors.Fatalf("create key in repository at %s failed: %v", location.StripPassword(gopts.Backends, repo), err) + return nil, errors.Fatalf("create key in repository at %q failed: %v", location.StripPassword(gopts.Backends, repo), err) } return s, nil @@ -574,14 +574,14 @@ func createOrOpenBackend(ctx context.Context, scheme string, cfg any, rt http.Ro if errors.Is(err, backend.ErrNoRepository) { //nolint:staticcheck // capitalized error string is intentional - return nil, fmt.Errorf("Fatal: %w at %v: %v", ErrNoRepository, location.StripPassword(gopts.Backends, s), err) + return nil, fmt.Errorf("Fatal: %w at %q: %v", ErrNoRepository, location.StripPassword(gopts.Backends, s), err) } if err != nil { if create { // init already wraps the error message return nil, err } - return nil, errors.Fatalf("unable to open repository at %v: %v", location.StripPassword(gopts.Backends, s), err) + return nil, errors.Fatalf("unable to open repository at %q: %v", location.StripPassword(gopts.Backends, s), err) } return be, nil diff --git a/internal/global/global_test.go b/internal/global/global_test.go index 62a5cecfb..3c172d7d5 100644 --- a/internal/global/global_test.go +++ b/internal/global/global_test.go @@ -4,6 +4,7 @@ import ( "context" "os" "path/filepath" + "strconv" "strings" "testing" @@ -59,7 +60,7 @@ func TestReadRepoEmptyFile(t *testing.T) { repo, err := readRepo(Options{RepositoryFile: filename}) rtest.Assert(t, errors.IsFatal(err), "expected fatal error for empty repository file, got %v", err) rtest.Equals(t, "", repo) - rtest.Assert(t, strings.Contains(err.Error(), filename), "error should identify repository file, got %v", err) + rtest.Assert(t, strings.Contains(err.Error(), strconv.Quote(filename)), "error should identify repository file, got %v", err) }) } } diff --git a/internal/repository/upgrade_repo.go b/internal/repository/upgrade_repo.go index e2419e6eb..e52a77f76 100644 --- a/internal/repository/upgrade_repo.go +++ b/internal/repository/upgrade_repo.go @@ -74,7 +74,7 @@ func UpgradeRepo(ctx context.Context, repo *Repository, tempBaseDir string) erro backupFileName := filepath.Join(tempdir, "config") err = os.WriteFile(backupFileName, rawConfigFile, 0600) if err != nil { - return fmt.Errorf("write config file backup to %v failed: %w", tempdir, err) + return fmt.Errorf("write config file backup to %q failed: %w", tempdir, err) } // run the upgrade diff --git a/internal/restorer/restorer.go b/internal/restorer/restorer.go index 1c3482979..2fcee799e 100644 --- a/internal/restorer/restorer.go +++ b/internal/restorer/restorer.go @@ -202,7 +202,7 @@ func (res *Restorer) traverseTreeInner(ctx context.Context, target, location str nodeName := filepath.Base(filepath.Join(string(filepath.Separator), node.Name)) if nodeName != node.Name { debug.Log("node %q has invalid name %q", node.Name, nodeName) - err := res.sanitizeError(location, errors.Errorf("invalid child node name %s", node.Name)) + err := res.sanitizeError(location, errors.Errorf("invalid child node name %q", node.Name)) if err != nil { return nil, hasRestored, err } @@ -531,7 +531,7 @@ func (res *Restorer) removeUnexpectedFiles(ctx context.Context, target, location nodeLocation := filepath.Join(location, entry) if target == nodeTarget || !fs.HasPathPrefix(target, nodeTarget) { - return fmt.Errorf("skipping deletion due to invalid filename: %v", entry) + return fmt.Errorf("skipping deletion due to invalid filename: %q", entry) } // TODO pass a proper value to the isDir parameter once this becomes relevant for the filters @@ -743,10 +743,10 @@ func (res *Restorer) verifyFile(ctx context.Context, target string, node *data.N case err != nil: return nil, buf, err case !fi.Mode().IsRegular(): - return nil, buf, errors.Errorf("Expected %s to be a regular file", target) + return nil, buf, errors.Errorf("Expected %q to be a regular file", target) case int64(node.Size) != fi.Size(): if failFast { - return nil, buf, errors.Errorf("Invalid file size for %s: expected %d, got %d", + return nil, buf, errors.Errorf("Invalid file size for %q: expected %d, got %d", target, node.Size, fi.Size()) } sizeMatches = false @@ -783,7 +783,7 @@ func (res *Restorer) verifyFile(ctx context.Context, target string, node *data.N matches[i] = blobID.Equal(restic.Hash(buf)) if failFast && !matches[i] { return nil, buf, errors.Errorf( - "Unexpected content in %s, starting at offset %d", + "Unexpected content in %q, starting at offset %d", target, offset) } offset += int64(length) diff --git a/internal/restorer/restorer_test.go b/internal/restorer/restorer_test.go index 39ad6554a..117c41b1b 100644 --- a/internal/restorer/restorer_test.go +++ b/internal/restorer/restorer_test.go @@ -307,8 +307,8 @@ func TestRestorer(t *testing.T) { }, ErrorsMay: map[string]map[string]struct{}{ `/`: { - `invalid child node name ..\test`: struct{}{}, - `invalid child node name ..\..\foo\..\bar\..\xx\test2`: struct{}{}, + `invalid child node name "..\\test"`: struct{}{}, + `invalid child node name "..\\..\\foo\\..\\bar\\..\\xx\\test2"`: struct{}{}, }, }, }, @@ -321,8 +321,8 @@ func TestRestorer(t *testing.T) { }, ErrorsMay: map[string]map[string]struct{}{ `/`: { - `invalid child node name ../test`: struct{}{}, - `invalid child node name ../../foo/../bar/../xx/test2`: struct{}{}, + `invalid child node name "../test"`: struct{}{}, + `invalid child node name "../../foo/../bar/../xx/test2"`: struct{}{}, }, }, }, @@ -352,7 +352,7 @@ func TestRestorer(t *testing.T) { }, ErrorsMust: map[string]map[string]struct{}{ `/x`: { - `invalid child node name ..`: struct{}{}, + `invalid child node name ".."`: struct{}{}, }, }, }, diff --git a/internal/walker/walker.go b/internal/walker/walker.go index 0ff2f8ebb..b840a061b 100644 --- a/internal/walker/walker.go +++ b/internal/walker/walker.go @@ -100,7 +100,7 @@ func walk(ctx context.Context, repo restic.BlobLoader, prefix string, parentTree } if node.Subtree == nil { - return errors.Errorf("subtree for node %v in tree %v is nil", node.Name, p) + return errors.Errorf("subtree for node %q in tree %q is nil", node.Name, p) } subtree, err := data.LoadTree(ctx, repo, *node.Subtree) From 84a75fc09eebe3d6a5051867aa77b216756d10dc Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 13:48:56 +0100 Subject: [PATCH 05/14] generically sanitize output --- cmd/restic/main.go | 3 +- internal/ui/format.go | 54 +++++++++++++++++++++++++++ internal/ui/format_test.go | 8 ++++ internal/ui/table/table.go | 4 +- internal/ui/table/table_test.go | 20 ++++++++++ internal/ui/termstatus/status.go | 2 +- internal/ui/termstatus/status_test.go | 34 +++++++++++++++++ 7 files changed, 121 insertions(+), 4 deletions(-) diff --git a/cmd/restic/main.go b/cmd/restic/main.go index 3a192e9df..65ac1f6c9 100644 --- a/cmd/restic/main.go +++ b/cmd/restic/main.go @@ -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)) } } diff --git a/internal/ui/format.go b/internal/ui/format.go index 1a41b61a0..6ae787993 100644 --- a/internal/ui/format.go +++ b/internal/ui/format.go @@ -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 { diff --git a/internal/ui/format_test.go b/internal/ui/format_test.go index 8dcee674a..36555bfa6 100644 --- a/internal/ui/format_test.go +++ b/internal/ui/format_test.go @@ -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 diff --git a/internal/ui/table/table.go b/internal/ui/table/table.go index 80ad1eba4..b183229a3 100644 --- a/internal/ui/table/table.go +++ b/internal/ui/table/table.go @@ -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 } diff --git a/internal/ui/table/table_test.go b/internal/ui/table/table_test.go index 2902860b9..54b22276c 100644 --- a/internal/ui/table/table_test.go +++ b/internal/ui/table/table_test.go @@ -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 +----------------- `, }, } diff --git a/internal/ui/termstatus/status.go b/internal/ui/termstatus/status.go index b0b831c7f..00ede68b9 100644 --- a/internal/ui/termstatus/status.go +++ b/internal/ui/termstatus/status.go @@ -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: } } diff --git a/internal/ui/termstatus/status_test.go b/internal/ui/termstatus/status_test.go index f8a7c4f5b..1999b54c5 100644 --- a/internal/ui/termstatus/status_test.go +++ b/internal/ui/termstatus/status_test.go @@ -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 From 057a5c65d2bddca479425cc24989fbad53b52b99 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sun, 22 Nov 2026 15:21:42 +0100 Subject: [PATCH 06/14] add changelog --- changelog/unreleased/pull-22216 | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 changelog/unreleased/pull-22216 diff --git a/changelog/unreleased/pull-22216 b/changelog/unreleased/pull-22216 new file mode 100644 index 000000000..336d74fe7 --- /dev/null +++ b/changelog/unreleased/pull-22216 @@ -0,0 +1,11 @@ +Bugfix: Quote non-printable characters in text output + +Filenames and other printed text, such as hostnames, tags, and error +messages, could contain newlines or terminal control characters. Restic +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. + +https://github.com/restic/restic/pull/22216 From 79b676aa986cf67d6727261a9c0f96b4121eca31 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 15:33:35 +0100 Subject: [PATCH 07/14] cat: always use raw output This avoids quoting of JSON data. --- cmd/restic/cmd_cat.go | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/cmd/restic/cmd_cat.go b/cmd/restic/cmd_cat.go index f8a33cabd..aa6d66af5 100644 --- a/cmd/restic/cmd_cat.go +++ b/cmd/restic/cmd_cat.go @@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "io" "slices" "strings" @@ -92,16 +93,17 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te return err } - printer.S(string(buf)) - return nil + return writeWithNewline(term.OutputRaw(), buf) + case "index": buf, err := repo.LoadUnpacked(ctx, restic.IndexFile, id) if err != nil { return err } - printer.S(string(buf)) - return nil + _, err = term.OutputRaw().Write(buf) + return err + case "snapshot": sn, _, err := data.FindSnapshot(ctx, repo, repo, args[1]) if err != nil { @@ -113,8 +115,8 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te return err } - printer.S(string(buf)) - return nil + return writeWithNewline(term.OutputRaw(), buf) + case "key": key, err := repository.LoadKey(ctx, repo, id) if err != nil { @@ -126,16 +128,16 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te return err } - printer.S(string(buf)) - return nil + return writeWithNewline(term.OutputRaw(), buf) + case "masterkey": buf, err := json.MarshalIndent(repo.Key(), "", " ") if err != nil { return err } - printer.S(string(buf)) - return nil + return writeWithNewline(term.OutputRaw(), buf) + case "lock": lock, err := repository.LoadLock(ctx, repo, id) if err != nil { @@ -147,8 +149,7 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te return err } - printer.S(string(buf)) - return nil + return writeWithNewline(term.OutputRaw(), buf) case "pack": buf, err := repo.LoadRaw(ctx, restic.PackFile, id) @@ -214,3 +215,11 @@ func runCat(ctx context.Context, gopts global.Options, args []string, term ui.Te return errors.Fatal("invalid type") } } + +func writeWithNewline(w io.Writer, buf []byte) error { + if _, err := w.Write(buf); err != nil { + return err + } + _, err := w.Write([]byte{'\n'}) + return err +} From fc85e9eb9b1800564052877ec3c92aa82b7ccde7 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 15:38:28 +0100 Subject: [PATCH 08/14] find: fix printing of paths containing % (format verbs) --- cmd/restic/cmd_find.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/restic/cmd_find.go b/cmd/restic/cmd_find.go index 7ae1b3fef..7dee887a6 100644 --- a/cmd/restic/cmd_find.go +++ b/cmd/restic/cmd_find.go @@ -171,7 +171,7 @@ func (s *statefulOutput) PrintPatternNormal(path string, node *data.Node) { s.oldsn = s.newsn s.printer.P("Found matching entries in snapshot %s from %s", s.oldsn.ID().Str(), s.oldsn.Time.Local().Format(global.TimeFormat)) } - s.printer.S(formatNode(path, node, s.ListLong, s.HumanReadable)) + s.printer.S("%s", formatNode(path, node, s.ListLong, s.HumanReadable)) } func (s *statefulOutput) PrintPattern(path string, node *data.Node) { From ab38c4249713f2b11f8e44b98aeb985ff7582ffa Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 15:51:26 +0100 Subject: [PATCH 09/14] archiver: fix double path injection after quoting --- internal/archiver/archiver.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/archiver/archiver.go b/internal/archiver/archiver.go index 4d2292ed4..0e4ba978b 100644 --- a/internal/archiver/archiver.go +++ b/internal/archiver/archiver.go @@ -7,6 +7,7 @@ import ( "path" "runtime" "sort" + "strconv" "strings" "sync" "time" @@ -203,8 +204,9 @@ func (arch *Archiver) error(item string, err error) error { } // not all errors include the filepath, thus add it if it is missing - if !strings.Contains(err.Error(), item) { - err = fmt.Errorf("%v: %w", item, err) + // errors include quoted file path, so we need to quote it too + if !strings.Contains(err.Error(), item) && !strings.Contains(err.Error(), strconv.Quote(item)) { + err = fmt.Errorf("%q: %w", item, err) } errf := arch.Error(item, err) From d156f3b5f14aebbae7627c78d7abe2a8b10acf0b Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 15:56:44 +0100 Subject: [PATCH 10/14] backup: fix missing error if vss snapshot properties cannot be read --- internal/fs/vss_windows.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/fs/vss_windows.go b/internal/fs/vss_windows.go index f6378f1b3..6b63f4e32 100644 --- a/internal/fs/vss_windows.go +++ b/internal/fs/vss_windows.go @@ -1072,7 +1072,7 @@ func newVssSnapshot(provider string, &info.snapshotProperties) if err != nil { msgError(mountPoint, errors.Errorf( - "VSS error: GetSnapshotProperties() for mount point %q returned error: ", + "VSS error: GetSnapshotProperties() for mount point %q returned error: %v", mountPoint, err)) info.isSnapshotted = false } else { From 152c2720bb4e33ff50cd633c32ebc0ba513ae797 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 15:58:01 +0100 Subject: [PATCH 11/14] don't quote repository open error by default --- internal/global/global.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/global/global.go b/internal/global/global.go index b46723a08..8b555e745 100644 --- a/internal/global/global.go +++ b/internal/global/global.go @@ -344,10 +344,10 @@ func hasRepositoryConfig(ctx context.Context, be backend.Backend, repo string, g fi, err := be.Stat(ctx, backend.Handle{Type: backend.ConfigFile}) if be.IsNotExist(err) { //nolint:staticcheck // capitalized error string is intentional - return fmt.Errorf("Fatal: %w: unable to open config file: %v\nIs there a repository at the following location?\n%q", ErrNoRepository, err, location.StripPassword(gopts.Backends, repo)) + return fmt.Errorf("Fatal: %w: unable to open config file: %v\nIs there a repository at the following location?\n%v", ErrNoRepository, err, ui.Quote(location.StripPassword(gopts.Backends, repo))) } if err != nil { - return errors.Fatalf("unable to open config file: %v\n%q", err, location.StripPassword(gopts.Backends, repo)) + return errors.Fatalf("unable to open config file: %v\n%v", err, ui.Quote(location.StripPassword(gopts.Backends, repo))) } if fi.Size == 0 { From 1227b2ab7ed03af803713191270f35fe5a9f3d58 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 16:56:22 +0100 Subject: [PATCH 12/14] fix debug logs with missing parameters --- internal/archiver/archiver.go | 2 +- internal/repository/index/index.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/archiver/archiver.go b/internal/archiver/archiver.go index 0e4ba978b..52346a30b 100644 --- a/internal/archiver/archiver.go +++ b/internal/archiver/archiver.go @@ -848,7 +848,7 @@ func (arch *Archiver) loadParentTree(ctx context.Context, sn *data.Snapshot) dat } if sn.Tree == nil { - debug.Log("snapshot %v has empty tree %v", *sn.ID()) + debug.Log("snapshot %v has empty tree", *sn.ID()) return nil } diff --git a/internal/repository/index/index.go b/internal/repository/index/index.go index 9f05b92b9..4cc2e6167 100644 --- a/internal/repository/index/index.go +++ b/internal/repository/index/index.go @@ -120,7 +120,7 @@ var Full = func(idx *Index) bool { switch { case age >= indexMaxAge: - debug.Log("index %p is old enough", idx, age) + debug.Log("index %p is old enough %v", idx, age) return true case blobs >= indexMaxBlobs: debug.Log("index %p has %d blobs", idx, blobs) From 03e40607919bb96994f013dcf6ec7b924fb28fd7 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 17:05:58 +0100 Subject: [PATCH 13/14] fix invalid verbs passed to sprintf --- helpers/prepare-release/main.go | 2 +- internal/backend/rest/rest.go | 2 +- internal/checker/checker.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/helpers/prepare-release/main.go b/helpers/prepare-release/main.go index 6fced3f7c..decffbad5 100644 --- a/helpers/prepare-release/main.go +++ b/helpers/prepare-release/main.go @@ -222,7 +222,7 @@ func createChangelogRelease() { err := os.Rename(src, dest) if err != nil { - die("rename %v -> %v failed: %w", src, dest, err) + die("rename %v -> %v failed: %v", src, dest, err) } } diff --git a/internal/backend/rest/rest.go b/internal/backend/rest/rest.go index 25483c90c..5d2755c14 100644 --- a/internal/backend/rest/rest.go +++ b/internal/backend/rest/rest.go @@ -78,7 +78,7 @@ func drainAndClose(resp *http.Response) error { // return first error if err != nil { - return errors.Errorf("drain: %w", err) + return errors.Errorf("drain: %v", err) } return cerr } diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 9c748e94b..e7ab9dc23 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -208,7 +208,7 @@ func (c *Checker) checkTree(id restic.ID, tree data.TreeNodeIterator) (errs []er if errors.Is(item.Error, data.ErrTreeNotOrdered) { errs = append(errs, &Error{TreeID: id, Err: item.Error}) } else if item.Error != nil { - errs = append(errs, &Error{TreeID: id, Err: errors.Errorf("failed to decode tree %v: %w", id, item.Error)}) + errs = append(errs, &Error{TreeID: id, Err: errors.Errorf("failed to decode tree %v: %v", id, item.Error)}) break } From 7a1ac9bda0df5997c76479640236af5c4ea19677 Mon Sep 17 00:00:00 2001 From: Michael Eischer Date: Sat, 28 Nov 2026 17:53:43 +0100 Subject: [PATCH 14/14] properly encode JSON everywhere --- changelog/unreleased/pull-22216 | 4 +- cmd/restic/cmd_find.go | 4 +- cmd/restic/cmd_find_test.go | 67 +++++++++++++++++++++++++++++++++ cmd/restic/main.go | 3 +- internal/ui/format.go | 12 ++++-- internal/ui/format_test.go | 36 +++++++++++++++++- internal/ui/table/table_test.go | 12 +++--- 7 files changed, 122 insertions(+), 16 deletions(-) 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 +------------------- `, }, }