Merge pull request #22216 from MichaelEischer/quote-ui-output

Ensure paths etc. are quoted in terminal output
This commit is contained in:
Michael Eischer authored and GitHub committed 2026-11-28 20:53:43 +01:00
commit 0cd0df6346
73 files changed
+631 -203

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
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 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
+5 -5
View File
@@ -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
}
@@ -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)
@@ -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)
+21 -12
View File
@@ -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
}
+5 -1
View File
@@ -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)
},
}
+21
View File
@@ -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)
}
+1 -1
View File
@@ -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 {
+5 -5
View File
@@ -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++
}
@@ -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) {
@@ -210,17 +210,17 @@ 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++
}
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))
}
+97
View File
@@ -0,0 +1,97 @@
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"
)
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])
}
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)
})
}
+1 -1
View File
@@ -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))
+1 -1
View File
@@ -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{
+5
View File
@@ -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 }}")
+1 -1
View File
@@ -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 {
+8 -8
View File
@@ -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)
@@ -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
}
+3 -3
View File
@@ -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))
}
}
+2 -2
View File
@@ -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
}
+6 -6
View File
@@ -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, ", ") + ")"
+3 -3
View File
@@ -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)
}
+22
View File
@@ -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)
+4 -2
View File
@@ -23,6 +23,7 @@ import (
"github.com/restic/restic/internal/feature"
"github.com/restic/restic/internal/global"
"github.com/restic/restic/internal/repository"
"github.com/restic/restic/internal/ui"
"github.com/restic/restic/internal/ui/termstatus"
)
@@ -167,15 +168,16 @@ 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, "%v\n", message)
_, _ = fmt.Fprintf(os.Stderr, "%s\n", ui.EscapeControls(message))
}
}
+1 -1
View File
@@ -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)
}
}
+10 -8
View File
@@ -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)
@@ -272,7 +274,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 +385,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 +549,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 +672,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 +782,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
}
@@ -846,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
}
+2 -2
View File
@@ -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
}
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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
+1 -1
View File
@@ -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
}
+1 -1
View File
@@ -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
}
+3 -2
View File
@@ -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"
)
@@ -134,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.
@@ -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))))
}
}
}
+10
View File
@@ -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)
}
+2 -1
View File
@@ -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.
+5 -3
View File
@@ -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, ", ")
}
+13
View File
@@ -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)
}
+12
View File
@@ -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)
}
+3 -1
View File
@@ -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.
+6
View File
@@ -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())
}
+5 -5
View File
@@ -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
}
+7 -3
View File
@@ -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)
}
}
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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()
+3 -3
View File
@@ -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 {
+7 -14
View File
@@ -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 "":`,
},
},
}
+2 -2
View File
@@ -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")
}
+3 -2
View File
@@ -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))
}
}
}
+17 -17
View File
@@ -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)
}
}
}
+14 -14
View File
@@ -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 {
+1 -1
View File
@@ -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{
+4 -4
View File
@@ -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
}
+3 -3
View File
@@ -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)
}
+14 -14
View File
@@ -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)
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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")
}
+1 -1
View File
@@ -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 {
+3 -3
View File
@@ -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: %v",
mountPoint, err))
info.isSnapshotted = false
} else {
+9 -9
View File
@@ -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%v", ErrNoRepository, err, ui.Quote(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%v", err, ui.Quote(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
+2 -1
View File
@@ -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)
})
}
}
+1 -1
View File
@@ -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)
+2 -1
View File
@@ -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 "<Key nil>"
}
return fmt.Sprintf("<Key of %s@%s, created on %s>", k.Username, k.Hostname, k.Created)
return fmt.Sprintf("<Key of %s@%s, created on %s>", ui.Quote(k.Username), ui.Quote(k.Hostname), k.Created)
}
// ID returns an identifier for the key.
+2 -1
View File
@@ -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())
+23
View File
@@ -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>", (*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, "<Key of alice@box, created on 2020-01-02 03:04:05 +0000 UTC>", ordinary)
hostile := (&Key{Username: "a\nb", Hostname: "box", Created: created}).String()
rtest.Equals(t, `<Key of "a\nb"@box, created on 2020-01-02 03:04:05 +0000 UTC>`, hostile)
}
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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)
+5 -5
View File
@@ -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{}{},
},
},
},
+1 -1
View File
@@ -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))
}
+6
View File
@@ -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)
}
+68
View File
@@ -6,8 +6,11 @@ import (
"fmt"
"math/bits"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf16"
"unicode/utf8"
"golang.org/x/text/width"
@@ -146,6 +149,71 @@ 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
}
// EscapeControls replaces terminal control characters with escape sequences.
// Newlines and tabs are preserved so multi-line messages keep their layout.
// 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
}
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 if r <= 0xffff {
fmt.Fprintf(&b, `\u%04x`, r)
} else {
r1, r2 := utf16.EncodeRune(r)
fmt.Fprintf(&b, `\u%04x\u%04x`, r1, r2)
}
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 {
+47
View File
@@ -1,7 +1,9 @@
package ui
import (
"encoding/json"
"strconv"
"strings"
"testing"
rtest "github.com/restic/restic/internal/test"
@@ -129,6 +131,51 @@ 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 TestEscapeControlsKeepsLayout(t *testing.T) {
in := "PID 1 on host\n\tstack"
rtest.Equals(t, in, EscapeControls(in))
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
+3 -3
View File
@@ -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))
}
}
+14 -7
View File
@@ -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)
}
+2 -2
View File
@@ -130,7 +130,7 @@ func (t *Table) Write(w io.Writer) error {
return err
}
row = append(row, buf.String())
row = append(row, ui.EscapeControls(buf.String()))
buf.Reset()
}
lines = append(lines, row)
@@ -198,7 +198,7 @@ func (t *Table) Write(w io.Writer) error {
if len(t.footer) > 0 {
// write the footer
for _, line := range t.footer {
err := t.PrintFooter(w, line)
err := t.PrintFooter(w, ui.EscapeControls(line))
if err != nil {
return err
}
+20
View File
@@ -155,6 +155,26 @@ foo 2018-08-19 22:22:22 xxx other /home/user/other
foo 2018-08-19 22:22:22 xxx other /home/user/other
bar
------------------------------------------------------------
`,
},
{
func(t testing.TB) *Table {
table := New()
table.AddColumn("host", "{{.Host}}")
table.AddColumn("tags", `{{join .Tags "\n"}}`)
table.AddRow(struct {
Host string
Tags []string
}{"host\x1b[2J", []string{"ok", "a\nb"}})
return table
},
`
host tags
-------------------
host\u001b[2J ok
a
b
-------------------
`,
},
}
+1 -1
View File
@@ -377,7 +377,7 @@ func (t *terminal) print(line string, isErr bool) {
}
select {
case t.msg <- message{line: line, err: isErr}:
case t.msg <- message{line: ui.EscapeControls(line), err: isErr}:
case <-t.closed:
}
}
+34
View File
@@ -11,6 +11,7 @@ import (
tty "github.com/restic/restic/internal/terminal"
rtest "github.com/restic/restic/internal/test"
"github.com/restic/restic/internal/ui"
)
func TestSetStatus(t *testing.T) {
@@ -116,6 +117,39 @@ func TestPrint(t *testing.T) {
rtest.Equals(t, exp, buf.String())
}
func TestPrintErrorEscapesControls(t *testing.T) {
buf, term, cancel := setupStatusTest()
const (
cl = tty.PosixControlClearLine
home = tty.PosixControlMoveCursorHome
)
hostile := "esc \x1b[2J del \x7f c1 \u009b tag \U000e0067 bad \xff"
term.Print("out " + hostile)
term.Error("err " + hostile)
// Newlines and tabs are part of the message layout and must survive.
term.Print("keep\n\ttabs")
term.Error("already\n")
exp := home + cl + ui.EscapeControls("out "+hostile+"\n")
exp += home + cl + ui.EscapeControls("err "+hostile+"\n")
exp += home + cl + "keep\n\ttabs\n"
exp += home + cl + "already\n"
cancel()
<-term.closed
got := buf.String()
rtest.Equals(t, exp, got)
// Clear-line uses ESC [2K, so a raw ESC byte is expected. The hostile sequence is not.
rtest.Assert(t, !strings.Contains(got, "\x1b[2J"), "raw CSI in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\x7f'), "raw DEL in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\u009b'), "raw C1 CSI in %q", got)
rtest.Assert(t, !strings.ContainsRune(got, '\U000e0067'), "raw tag in %q", got)
rtest.Assert(t, !strings.Contains(got, "\xff"), "raw invalid UTF-8 in %q", got)
}
func TestSanitizeLines(t *testing.T) {
var tests = []struct {
input []string
+1 -1
View File
@@ -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)