diff --git a/README.md b/README.md index b7b6e04..dbee4ae 100644 --- a/README.md +++ b/README.md @@ -90,3 +90,28 @@ For an integration test against Rsync 3.x, run The test uses temporary directories only and checks that a dry run changes nothing, that a subsequent copy matches the planned counts, and that another comparison then finds no changes. + + +### Rsync space preflight (2026.10.09.r001) + +The read-only dry run reports transfer volume separately from a conservative +additional-space estimate. The estimate sums positive growth of transferred +regular files, adds the largest transferred file as temporary-copy headroom, +and reserves 64 KiB per changed entry plus 1% (at least 64 MiB). Replacement +credit is limited to the smaller of the existing logical size and allocated +blocks; hardlinks and known Linux CoW filesystems (ZFS, Btrfs, XFS) receive no +replacement credit. Shrinking files and `--delete-delay` deletions never reduce +the estimate. Consequently renamed backup generations still require space for +the new generation before the old generation is deleted. + +Rsync-escaped filenames are decoded once. Incomplete statistics, unreadable +paths, ambiguous source basenames, destination symlinks and nested destination +filesystems stop preflight with “not reliably determinable”, rather than a +misleading “insufficient space”. The check never creates a destination or starts +a real transfer. Existing job options and the explicit skip-check override are +unchanged. Results appear in the job's existing live log in the WebGUI. + +This remains an estimate, not a reservation: concurrent writers, quotas, +filesystem-specific allocation/compression and changes after the dry run can +still cause a later write failure. Production rsync errors remain authoritative. +Tests using real rsync run only in temporary fixtures via `URBM_TEST_RSYNC`. diff --git a/dist/urbm-2026.10.09.r001-x86_64-1.txz b/dist/urbm-2026.10.09.r001-x86_64-1.txz new file mode 100644 index 0000000..a7a31ec Binary files /dev/null and b/dist/urbm-2026.10.09.r001-x86_64-1.txz differ diff --git a/dist/urbm-2026.10.09.r001-x86_64-1.txz.sha256 b/dist/urbm-2026.10.09.r001-x86_64-1.txz.sha256 new file mode 100644 index 0000000..bd80599 --- /dev/null +++ b/dist/urbm-2026.10.09.r001-x86_64-1.txz.sha256 @@ -0,0 +1 @@ +b9cde8f34560cc4a5a5699f9f2ed2e0b8fe72d625dcb63c65ea1240aeeaf44de urbm-2026.10.09.r001-x86_64-1.txz diff --git a/dist/urbm.plg b/dist/urbm.plg index ef03f08..c2430d3 100644 --- a/dist/urbm.plg +++ b/dist/urbm.plg @@ -2,13 +2,19 @@ - + - + ]> +### 2026.10.09.r001 +- Estimate additional Rsync destination space separately from transfer volume. +- Account for replacement files, sparse allocation, temporary copies and a safety reserve; never credit delayed deletions early. +- Decode escaped filenames safely and fail clearly when a read-only estimate is incomplete or ambiguous. +- Add regression and real-rsync tests without changing existing jobs or deletion settings. + ### 2026.09.28.r001 - Label job automation separately from run results: manual, enabled or disabled instead of misleading success/cancelled badges. - Display manual and disabled jobs neutrally and explain scheduling state in tooltips. diff --git a/internal/rsync/rsync.go b/internal/rsync/rsync.go index 486f0a9..1d58e00 100644 --- a/internal/rsync/rsync.go +++ b/internal/rsync/rsync.go @@ -8,6 +8,7 @@ import ( "io" "os" "os/exec" + "path/filepath" "regexp" "strconv" "strings" @@ -44,9 +45,11 @@ type Progress struct { } type Summary struct { - Bytes int64 - Files int64 - Deleted int64 + Bytes int64 + Files int64 + Deleted int64 + RequiredBytes int64 + SpaceUnknown string } var ( @@ -124,10 +127,21 @@ func (r *Runner) Run(ctx context.Context, runID string, job model.Job, callback // Estimate performs rsync's complete comparison without writing destination data. func (r *Runner) Estimate(ctx context.Context, runID string, job model.Job) (Summary, error) { job.Rsync.DryRun = true + if _, err := os.Stat(job.Rsync.Target); err != nil { + return Summary{}, fmt.Errorf("rsync preflight: target unavailable: %w", err) + } + seen := make(map[string]bool) + for _, source := range job.Sources { + name := filepath.Base(filepath.Clean(source.Path)) + if seen[name] { + return Summary{}, fmt.Errorf("rsync preflight: ambiguous destination directory %q", name) + } + seen[name] = true + } args := Arguments(job) for index, arg := range args { if strings.HasPrefix(arg, "--out-format=") { - args[index] = "--out-format=" + args[index] = "--out-format=SPACE|%i|%l|%n" } } cmd := exec.CommandContext(ctx, r.binary(), args...) @@ -159,11 +173,20 @@ func (r *Runner) Estimate(ctx context.Context, runID string, job model.Job) (Sum unregister := r.register(runID, cmd.Process) defer unregister() var summary Summary + space := newSpaceEstimate(job.Rsync.Target) done := make(chan struct{}) go func() { - scanOutput(stdout, func(line string) { + scanner := bufio.NewScanner(stdout) + scanner.Buffer(make([]byte, 64*1024), 2*1024*1024) + for scanner.Scan() { + line := scanner.Text() summary.parseLine(line) - }) + space.consume(line) + } + if err := scanner.Err(); err != nil { + space.problem = err.Error() + _, _ = io.Copy(io.Discard, stdout) + } close(done) }() stderrDone := make(chan []byte, 1) @@ -178,6 +201,7 @@ func (r *Runner) Estimate(ctx context.Context, runID string, job model.Job) (Sum } return Summary{}, fmt.Errorf("rsync preflight: %s", strings.TrimSpace(string(errBytes))) } + summary.RequiredBytes, summary.SpaceUnknown = space.finish(summary) return summary, nil } diff --git a/internal/rsync/rsync_test.go b/internal/rsync/rsync_test.go index a44a5cf..c427699 100644 --- a/internal/rsync/rsync_test.go +++ b/internal/rsync/rsync_test.go @@ -74,7 +74,7 @@ func TestRunnerReadsFinalStats(t *testing.T) { var err error var changes []string if estimate { - summary, err = runner.Estimate(context.Background(), "test", model.Job{}) + summary, err = runner.Estimate(context.Background(), "test", model.Job{Rsync: model.RsyncOptions{Target: t.TempDir()}}) } else { summary, err = runner.Run(context.Background(), "test", model.Job{}, func(p Progress) { if p.CurrentFile != "" { @@ -139,7 +139,7 @@ func TestRealRsyncDryRunAndCopy(t *testing.T) { t.Fatal("dry run deleted a file") } estimate, err := runner.Estimate(context.Background(), "test", job) - if err != nil || estimate != summary { + if err != nil || estimate.Bytes != summary.Bytes || estimate.Files != summary.Files || estimate.Deleted != summary.Deleted || estimate.SpaceUnknown != "" { t.Fatalf("estimate differs: %+v %v", estimate, err) } job.Rsync.DryRun = false diff --git a/internal/rsync/space.go b/internal/rsync/space.go new file mode 100644 index 0000000..c3747fc --- /dev/null +++ b/internal/rsync/space.go @@ -0,0 +1,178 @@ +package rsync + +import ( + "math" + "os" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +// The upper bound is independent of transfer order: all positive growth plus +// one complete temporary file. Shrinks and end-of-run deletions earn no credit. +// Old sparse files earn only their allocated bytes, never their logical size. +type spaceEstimate struct { + target string + growth, largest, files, bytes, entries int64 + problem string + sawStats bool + sawFiles bool + device uint64 +} + +func newSpaceEstimate(target string) *spaceEstimate { + p, err := filepath.EvalSymlinks(target) + e := &spaceEstimate{target: p} + if err != nil { + e.problem = "Zielpfad nicht lesbar: " + err.Error() + } + if err == nil { + info, statErr := os.Stat(p) + if statErr != nil { + e.problem = statErr.Error() + } else if st, ok := info.Sys().(*syscall.Stat_t); ok { + e.device = uint64(st.Dev) + } else { + e.problem = "Zieldateisystem nicht bestimmbar" + } + } + return e +} + +// rsync escapes control/non-ASCII bytes as \#ooo. Decode exactly once: a literal +// backslash preceding #ooo is itself escaped, so recursive decoding is unsafe. +func decodeRsyncName(s string) string { + var b strings.Builder + for i := 0; i < len(s); { + if i+5 <= len(s) && s[i] == '\\' && s[i+1] == '#' { + if n, err := strconv.ParseUint(s[i+2:i+5], 8, 8); err == nil { + b.WriteByte(byte(n)) + i += 5 + continue + } + } + b.WriteByte(s[i]) + i++ + } + return b.String() +} + +func (e *spaceEstimate) add(dst *int64, n int64) { + if n < 0 || *dst > math.MaxInt64-n { + e.problem = "Größenüberlauf" + return + } + *dst += n +} + +func (e *spaceEstimate) consume(line string) { + if bytesPattern.MatchString(line) { + e.sawStats = true + } + if filesPattern.MatchString(line) { + e.sawFiles = true + } + if !strings.HasPrefix(line, "SPACE|") || e.problem != "" { + return + } + parts := strings.SplitN(line, "|", 4) + if len(parts) != 4 || len(parts[1]) != 11 { + e.problem = "Ungültige Rsync-Dateiliste" + return + } + code := parts[1] + if strings.HasPrefix(code, "*deleting") { + return + } + e.add(&e.entries, 1) + size, err := strconv.ParseInt(parts[2], 10, 64) + if err != nil || size < 0 { + e.problem = "Ungültige Dateigröße" + return + } + if code[1] != 'f' || (code[0] != '>' && code[0] != '<') { + return + } + rel := decodeRsyncName(parts[3]) + if filepath.IsAbs(rel) || strings.ContainsRune(rel, 0) { + e.problem = "Ungültiger Ziel-Dateipfad" + return + } + clean := filepath.Clean(rel) + if clean == ".." || strings.HasPrefix(clean, ".."+string(os.PathSeparator)) { + e.problem = "Ziel-Dateipfad verlässt das Ziel" + return + } + // Never follow an existing destination symlink, including intermediate ones. + // A missing ancestor simply means that rsync will create the directory tree. + path := e.target + components := strings.Split(clean, string(os.PathSeparator)) + var old os.FileInfo + for i, c := range components { + path = filepath.Join(path, c) + info, err := os.Lstat(path) + if os.IsNotExist(err) { + break + } + if err != nil { + e.problem = "Zieldatei nicht prüfbar: " + err.Error() + return + } + if st, ok := info.Sys().(*syscall.Stat_t); !ok || uint64(st.Dev) != e.device { + e.problem = "Weiteres Dateisystem im Zielpfad" + return + } + if info.Mode()&os.ModeSymlink != 0 { + e.problem = "Symlink im Zielpfad; Platzbedarf nicht sicher bestimmbar" + return + } + if i < len(components)-1 && !info.IsDir() { + e.problem = "Dateitypwechsel im Zielpfad" + return + } + if i == len(components)-1 { + old = info + } + } + var reclaim int64 + if old != nil && old.Mode().IsRegular() { + stat, ok := old.Sys().(*syscall.Stat_t) + if !ok { + e.problem = "Belegter Zielspeicher nicht ermittelbar" + return + } + if mayReclaimBlocks(path) && stat.Nlink == 1 && stat.Blocks >= 0 && stat.Blocks <= math.MaxInt64/512 { + reclaim = min(old.Size(), stat.Blocks*512) + } + } // Directory/special-file replacement: no space credit. + e.add(&e.files, 1) + e.add(&e.bytes, size) + e.add(&e.growth, max(int64(0), size-reclaim)) + e.largest = max(e.largest, size) +} + +func (e *spaceEstimate) finish(s Summary) (int64, string) { + if e.problem != "" { + return 0, e.problem + } + if !e.sawStats || !e.sawFiles || e.files != s.Files || e.bytes != s.Bytes { + return 0, "Rsync-Dateiliste und Abschlussstatistik sind unvollständig oder widersprüchlich" + } + if e.entries == 0 { + return 0, "" + } + required := e.growth + e.add(&required, e.largest) + // Budget allocation rounding/metadata for changed entries, plus 1% or 64 MiB. + if e.entries > math.MaxInt64/(64*1024) { + return 0, "Zu viele Dateieinträge" + } + e.add(&required, e.entries*64*1024) + reserve := max(int64(64*1024*1024), required/100) + e.add(&required, reserve) + if e.problem != "" { + return 0, e.problem + } + return required, "" +} diff --git a/internal/rsync/space_linux.go b/internal/rsync/space_linux.go new file mode 100644 index 0000000..fd0cca1 --- /dev/null +++ b/internal/rsync/space_linux.go @@ -0,0 +1,19 @@ +//go:build linux + +package rsync + +import "syscall" + +// CoW snapshots/reflinks can retain replaced extents. Do not credit old blocks +// on these filesystems, even when a file has only one directory hardlink. +func mayReclaimBlocks(path string) bool { + var st syscall.Statfs_t + if syscall.Statfs(path, &st) != nil { + return false + } + switch uint64(st.Type) { + case 0x2fc12fc1, 0x9123683e, 0x58465342: // ZFS, Btrfs, XFS + return false + } + return true +} diff --git a/internal/rsync/space_other.go b/internal/rsync/space_other.go new file mode 100644 index 0000000..a3c01eb --- /dev/null +++ b/internal/rsync/space_other.go @@ -0,0 +1,6 @@ +//go:build !linux + +package rsync + +// Non-Linux builds are used for development; production runs on Unraid/Linux. +func mayReclaimBlocks(path string) bool { return true } diff --git a/internal/rsync/space_test.go b/internal/rsync/space_test.go new file mode 100644 index 0000000..1f2c2d4 --- /dev/null +++ b/internal/rsync/space_test.go @@ -0,0 +1,166 @@ +package rsync + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + "git.casaderoll.de/michael/urbm/internal/model" +) + +func TestSpaceReplacementsGrowthAndDeletes(t *testing.T) { + for _, tc := range []struct { + name string + old, new int + count int + growth int64 + }{ + {"same sized replacements", 8192, 8192, 3, 0}, + {"growth", 4096, 8192, 2, 8192}, + {"shrink", 8192, 4096, 2, 0}, + {"new files", 0, 8192, 2, 16384}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + e := newSpaceEstimate(dir) + for i := 0; i < tc.count; i++ { + name := fmt.Sprintf("file%d", i) + if tc.old > 0 { + if err := os.WriteFile(filepath.Join(dir, name), make([]byte, tc.old), 0600); err != nil { + t.Fatal(err) + } + } + e.consume(fmt.Sprintf("SPACE|>f.st......|%d|%s", tc.new, name)) + } + e.consume("SPACE|*deleting |999999999|old") + e.consume(fmt.Sprintf("Total transferred file size: %d bytes", tc.new*tc.count)) + e.consume(fmt.Sprintf("Number of regular files transferred: %d", tc.count)) + required, why := e.finish(Summary{Files: int64(tc.count), Bytes: int64(tc.new * tc.count)}) + if why != "" || e.growth != tc.growth { + t.Fatalf("growth=%d required=%d why=%s", e.growth, required, why) + } + want := tc.growth + int64(tc.new) + int64(tc.count)*65536 + 64*1024*1024 + if required != want { + t.Fatalf("got %d want %d", required, want) + } + }) + } +} + +func TestSpaceEscapedNamesAndSymlinks(t *testing.T) { + dir := t.TempDir() + name := "ä | line\ntrail " + if err := os.WriteFile(filepath.Join(dir, name), make([]byte, 8192), 0600); err != nil { + t.Fatal(err) + } + e := newSpaceEstimate(dir) + e.consume("SPACE|>f.st......|8192|\\#303\\#244 | line\\#012trail ") + if e.problem != "" || e.growth != 0 { + t.Fatalf("%+v", e) + } + if decodeRsyncName(`literal\#134#012`) != "literal\\#012" { + t.Fatal("recursive escape decoding") + } + if err := os.Symlink(t.TempDir(), filepath.Join(dir, "link")); err != nil { + t.Fatal(err) + } + e.consume("SPACE|>f+++++++++|2|link/file") + if e.problem == "" { + t.Fatal("followed destination symlink") + } +} + +func TestSpaceUnknownAndSparseHardlinks(t *testing.T) { + dir := t.TempDir() + e := newSpaceEstimate(dir) + if _, why := e.finish(Summary{}); why == "" { + t.Fatal("missing statistics accepted") + } + e.sawStats = true + if _, why := e.finish(Summary{Files: 1}); why == "" { + t.Fatal("missing file records accepted") + } + f, err := os.Create(filepath.Join(dir, "sparse")) + if err != nil { + t.Fatal(err) + } + if err = f.Truncate(1024 * 1024); err != nil { + t.Fatal(err) + } + f.Close() + e.consume("SPACE|>f.st......|1048576|sparse") + if e.growth == 0 { + t.Fatal("credited sparse logical size") + } + if err = os.WriteFile(filepath.Join(dir, "one"), make([]byte, 8192), 0600); err != nil { + t.Fatal(err) + } + if err = os.Link(filepath.Join(dir, "one"), filepath.Join(dir, "two")); err != nil { + t.Fatal(err) + } + e = newSpaceEstimate(dir) + e.consume("SPACE|>f.st......|8192|one") + if e.growth != 8192 { + t.Fatal("credited shared hardlink") + } + e = newSpaceEstimate(dir) + e.consume("SPACE|>f+++++++++|1|../escape") + if e.problem == "" { + t.Fatal("accepted traversal") + } +} + +func TestRealRsyncSpaceEstimate(t *testing.T) { + binary := os.Getenv("URBM_TEST_RSYNC") + if binary == "" { + t.Skip("requires rsync 3.x") + } + root := t.TempDir() + source := filepath.Join(root, "source") + target := filepath.Join(root, "target") + os.Mkdir(source, 0700) + os.Mkdir(target, 0700) + os.Mkdir(filepath.Join(target, "source"), 0700) + for _, name := range []string{"normal", "ä | newline\ntrailing ", `literal\#012`} { + os.WriteFile(filepath.Join(source, name), make([]byte, 8192), 0600) + os.WriteFile(filepath.Join(target, "source", name), make([]byte, 4096), 0600) + } + os.WriteFile(filepath.Join(source, "new"), []byte("new"), 0600) + os.WriteFile(filepath.Join(target, "source", "obsolete"), make([]byte, 8192), 0600) + job := model.Job{Sources: []model.Source{{Path: source}}, Rsync: model.RsyncOptions{Target: target, Overwrite: true, Delete: true, PreserveTimes: true, PreserveLinks: true}} + runner := Runner{Binary: binary} + estimate, err := runner.Estimate(context.Background(), "space", job) + if err != nil || estimate.SpaceUnknown != "" || estimate.Files != 4 || estimate.Bytes != 24579 { + t.Fatalf("%+v %v", estimate, err) + } + // Bound does not subtract the obsolete file and credits existing allocations. + want := int64(3*4096 + 3 + 8192 + 4*65536 + 64*1024*1024) + if estimate.RequiredBytes < want || estimate.RequiredBytes > want+2*65536 { + t.Fatalf("unexpected bound %+v", estimate) + } + if _, err = os.Stat(filepath.Join(target, "source", "obsolete")); err != nil { + t.Fatal("dry run deleted file") + } + if _, err = os.Stat(filepath.Join(target, "source", "new")); !os.IsNotExist(err) { + t.Fatal("dry run wrote file") + } + if _, err = runner.Run(context.Background(), "copy", job, nil); err != nil { + t.Fatal(err) + } + estimate, err = runner.Estimate(context.Background(), "unchanged", job) + if err != nil || estimate.SpaceUnknown != "" || estimate.Bytes != 0 { + t.Fatalf("%+v %v", estimate, err) + } + // A missing target must never be created by the preflight. + job.Rsync.Target = filepath.Join(root, "missing") + estimate, err = runner.Estimate(context.Background(), "missing", job) + if err == nil && !strings.Contains(estimate.SpaceUnknown, "Zielpfad") { + t.Fatalf("%+v %v", estimate, err) + } + if _, err = os.Stat(job.Rsync.Target); !os.IsNotExist(err) { + t.Fatal("created target") + } +} diff --git a/internal/service/service.go b/internal/service/service.go index ab58d12..fa4925a 100644 --- a/internal/service/service.go +++ b/internal/service/service.go @@ -1171,10 +1171,13 @@ func (s *Service) executeRsync(ctx context.Context, run model.Run) (result model if err != nil { return failed(run, "environment", "read rsync target capacity: "+err.Error()) } - appendLiveLog(&live, fmt.Sprintf("Rsync-Vorabprüfung: %s zu übertragen, %s am Ziel frei", formatBytes(estimate.Bytes), formatBytes(available))) + if estimate.SpaceUnknown != "" { + return failed(run, "environment", "Rsync-Platzbedarf nicht zuverlässig bestimmbar: "+estimate.SpaceUnknown+". Es wurden keine Zieldaten verändert.") + } + appendLiveLog(&live, fmt.Sprintf("Rsync-Vorabprüfung: %s Übertragungsmenge; bis zu %s zusätzlich benötigt (inklusive temporärer Dateikopie und Reserve); %s am Ziel frei. Löschungen am Ende sind nicht als freier Platz angerechnet.", formatBytes(estimate.Bytes), formatBytes(estimate.RequiredBytes), formatBytes(available))) s.updateActive(live) - if estimate.Bytes > available { - return failed(run, "environment", fmt.Sprintf("Rsync-Ziel hat nicht genügend freien Speicher: ungefähr %s für %d Dateien erforderlich, aber nur %s frei unter %s", formatBytes(estimate.Bytes), estimate.Files, formatBytes(available), job.Rsync.Target)) + if estimate.RequiredBytes > available { + return failed(run, "environment", fmt.Sprintf("Rsync-Ziel hat nicht genügend freien Speicher: ungefähr %s für %d Dateien erforderlich, aber nur %s frei unter %s", formatBytes(estimate.RequiredBytes), estimate.Files, formatBytes(available), job.Rsync.Target)) } } if job.Rsync.DryRun { diff --git a/plugin/urbm.plg b/plugin/urbm.plg index 2fb68c8..31323a7 100644 --- a/plugin/urbm.plg +++ b/plugin/urbm.plg @@ -2,13 +2,19 @@ - + ]> +### 2026.10.09.r001 +- Estimate additional Rsync destination space separately from transfer volume. +- Account for replacement files, sparse allocation, temporary copies and a safety reserve; never credit delayed deletions early. +- Decode escaped filenames safely and fail clearly when a read-only estimate is incomplete or ambiguous. +- Add regression and real-rsync tests without changing existing jobs or deletion settings. + ### 2026.09.28.r001 - Label job automation separately from run results: manual, enabled or disabled instead of misleading success/cancelled badges. - Display manual and disabled jobs neutrally and explain scheduling state in tooltips. diff --git a/webgui/URBM.page b/webgui/URBM.page index 4cbcbe5..74be9e6 100644 --- a/webgui/URBM.page +++ b/webgui/URBM.page @@ -8,7 +8,7 @@ Tag="URBM Unraid Restic Backup Manager backup snapshots restore" ---