Skip to content

backup: preserve deleted directories and fail on copy errors - #967

Merged
steadytao merged 17 commits into
RsyncProject:masterfrom
x15sr71:fix/backup-empty-dir-delete
Nov 24, 2026
Merged

steadytao merged 17 commits into
RsyncProject:masterfrom
x15sr71:fix/backup-empty-dir-delete

Conversation

@x15sr71

@x15sr71 x15sr71 commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Also fixes #842

Summary

Preserve deleted directories and their requested metadata in --backup-dir without replacing existing child backups or moving protected contents. Leave the original directory in place if its backup fails and restore any temporary permissions used to access saved directories. Complete the backup copy before starting an in-place delta update. If writing, copying extended attributes or closing the backup fails, report the error and leave the destination file unchanged.

@tridge

tridge commented Jun 5, 2026

Copy link
Copy Markdown
Member

@x15sr71 thanks for the PR! There is a subtle bug with it in the handling of files that should not go into the backup dir. I've added another test to the PR that demonstrates the bug

@x15sr71

x15sr71 commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the catch! Switched to rmdir-first, as if anything survived inside it naturally fails, then mkdir in backup-dir. All tests pass.

@x15sr71

x15sr71 commented Jun 6, 2026

Copy link
Copy Markdown
Contributor Author

Pushed a fix for the Solaris CI failure in the last CI run - Solaris returns EEXIST instead of ENOTEMPTY from rmdir() on non-empty directories, both are POSIX-valid. Added EEXIST to the existing check so it maps to DR_NOT_EMPTY correctly. Updated the PR description. Could you approve the workflows when you get a chance?

@x15sr71

x15sr71 commented Jun 14, 2026 •

Copy link
Copy Markdown
Contributor Author

@tridge The NetBSD failure is in daemon-access, the wo module was missing from the daemon listing, which is unrelated to this PR's delete/backup path. Both backup-empty-dir and backup-pinned-dir pass on NetBSD. Could you re-run it when you get a chance to see if it reproduces? Thanks!

@x15sr71

x15sr71 commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor Author

@tridge, pinging in case this got buried — the run results are no longer visible on the PR checks tab, so linking the only failed run from the last workflow run for reference: NetBSD run #394

Could you approve a workflow re-run when you get a chance? Thanks!

P.S. Happy to rebase and squash the merge commits if you'd like — the history would just be your test commit and mine.

Comment thread delete.c Resolved
Comment thread testsuite/backup-pinned-dir_test.py Resolved
@tridge
tridge force-pushed the fix/backup-empty-dir-delete branch from 3cfc8f4 to d8e6057 Compare July 20, 2026 01:44

@tridge tridge left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated review — generated by OpenAI Codex. Findings were reproduced
locally but not exhaustively hand-verified.

The rmdir-first direction is sound (the successful rmdir() is the atomic
emptiness proof, so a non-empty or protected-survivor directory is left intact),
and the Solaris EEXIST handling is correct (POSIX permits EEXIST or
ENOTEMPTY for a non-empty rmdir()/unlinkat(AT_REMOVEDIR); the wrapper's
parent-open path has no other normal source of EEXIST). Nested a/b/c works —
deletion is deepest-first, so when c is removed the destination parents still
exist and get_backup_name()/copy_valid_path() create backup/a/b; no ENOENT
gap. The make_backups > 0 / DEL_FOR_BACKUP / backup_dir guards are correct,
and --delete-delay/--delete-after/--force all reach the same path.

Three issues should be fixed before this is release-ready; the first two are
data-loss paths.

1. Backup failure after rmdir() is treated as success

In delete_item()'s S_ISDIR branch, a successful rmdir() sets ok, but a
subsequent failure of get_backup_name() or do_mkdir_at() never clears it.
Reproduced:

  • Unwritable --backup-dir: the empty directory is removed, no backup is
    created, a warning is printed, and rsync exits 0.
  • Blocked intermediate backup component: get_backup_name() returns NULL
    after the directory was already removed; rsync exits 23 but the directory is
    already gone.

File contents cannot be lost (the directory was proven empty), but the directory
object and its metadata are lost despite --backup. This differs from the
non-directory path, where a make_backup() failure aborts the deletion. Suggest
creating the backup directory before the rmdir() (so a failure leaves the
source in place), or otherwise propagating the failure instead of deleting.

2. EEXIST from the backup mkdir() accepts a non-directory

The EEXIST/EISDIR tolerance does not check the existing object's type.
Reproduced: with a regular file already at backup-dir/empty, dst/empty/ is
deleted, the stale regular file remains, no directory backup is created, and
rsync exits 0. Tolerating an existing directory is required (children may have
been backed up during the same recursive deletion), but a regular file or symlink
must not be accepted — it needs type validation and DEL_FOR_BACKUP collision
handling (or failure propagation).

3. Directory attributes are not preserved

The leaf is recreated with ACCESSPERMS only; an -aAX probe changed an empty
directory from mode 0701 to 0775 and lost its mtime, xattrs, and ownership.
Nested parents fare only slightly better: copy_valid_path() transfers their
attributes initially, but creating child backup directories dirties their mtimes,
and the EEXIST path does not restore them, so nested directory mtimes are lost.
Since copy_valid_path() explicitly attempts to transfer directory settings,
this reads as a defect rather than an intentional placeholder-directory policy.

Tests

Both new tests pass on HEAD and are non-vacuous (basic case, child-collision
preservation, nested dirs, suffix-mode regression, --delete-delay). Missing
coverage: an existing regular file/symlink at the backup leaf; a backup
mkdir()/get_backup_name() failure and its exit code; and mode/owner/mtime/
xattr/ACL preservation. backup-pinned-dir's comments still describe the earlier
rename-based implementation and should be updated.

@dr-who

dr-who commented Jul 20, 2026

Copy link
Copy Markdown
Member

I went through this one carefully — reproduced the bug, mutation-tested the new hunk against the tests that ship with it, and checked whether the existing backup machinery could do the job instead. Summary: the shape of the fix is right, but it is partial — the backed-up directory loses its mode and timestamps.

The bug is real, and this code is needed

Confirmed on master: with --backup --backup-dir --delete, dst/sub/file.txt lands in the backup dir but dst/sub/edir/ is silently dropped.

I also checked whether routing directories through the existing make_backup() would be the cleaner fix, since it already handles the backup-dir path creation and starts with link_or_rename() — and rename() moves a directory wholesale, metadata and all. It would be wrong here. A directory that still holds a protect-filtered survivor must stay put; rename() would move it and the protected file into the backup tree. The rmdir()-first approach in this PR is the correct emptiness proof, and I verified master and this PR both keep the protected file in place. So the structure is right.

The gap: metadata is not preserved

do_mkdir_at(buf, ACCESSPERMS) creates a fresh directory rather than preserving the one being deleted:

mode (orig 0751) mtime (orig 2019-03-04)
master dir lost entirely —
this PR 0755 today

For --backup, whose purpose is to keep what was there, that seems worth fixing. It is a small change — capture the stat before the rmdir() (which is what destroys it), then use it:

STRUCT_STAT dir_st;
int want_backup = make_backups > 0 && !(flags & DEL_FOR_BACKUP) && backup_dir;
int have_st = want_backup && do_lstat_at(fbuf, &dir_st) == 0;

what = "rmdir";
ok = do_rmdir_at(fbuf) == 0;
if (ok && want_backup) {
        char *buf = get_backup_name(fbuf);
        mode_t bmode = have_st ? dir_st.st_mode & CHMOD_BITS : ACCESSPERMS;
        if (buf && do_mkdir_at(buf, bmode) == 0) {
                if (have_st)
                        set_times(buf, &dir_st);
                ...

I tried that locally: mode 0751 and mtime 2019-03-04 both preserved, this PR's own backup-empty-dir and backup-pinned-dir tests still pass, full suite 109 passed / 0 failed.

Mutation testing of the new hunk

Eleven small edits to the added code, each rebuilt and run against backup-empty-dir, backup-pinned-dir, backup, backup-deep, delete, delete-deep. 4 killed, 7 survived. The interesting survivors:

  • ACCESSPERMS → 0 (mode 000) and → 0700 both survive. Nothing asserts anything about the backed-up directory's mode or times — the tests only check that the path exists. That is the gap above, confirmed from the other direction.
  • Reverting the Solaris || errno == EEXIST survives everything, which is expected — Linux rmdir() returns ENOTEMPTY, so no test on this CI can exercise it. It is an unverifiable change riding along with an unrelated fix; it may be worth splitting out so it can be justified on its own.
  • Dropping EEXIST/EISDIR from the mkdir-failure filter survives, so the Phase-2 collision case isn't actually asserting that no spurious warning is emitted.

One I want to explicitly not overclaim: dropping the ok && guard also survived, but I could not construct a case where it changes behaviour — a directory holding a protected file returns DR_NOT_EMPTY from delete_dir_contents() and goto check_ret happens before this block is reached. So that guard looks defensive rather than load-bearing.

Suggestions

  1. Preserve the directory's mode and times (patch above) — otherwise the "backup" is a new empty directory rather than the one that was deleted.
  2. Add a mode/mtime assertion to the test; without one, the metadata behaviour is entirely unpinned (two mutants prove it).
  3. Consider splitting the Solaris EEXIST change into its own commit, since nothing here can verify it.
  4. Minor, and possibly deliberate: --backup without --backup-dir (suffix mode) still drops empty dirs, since the new block requires backup_dir. The file branch handles both (backup_dir || !is_backup_file(...)), so the asymmetry may be worth a note either way.

@steadytao steadytao added the Bug Confirmed incorrect behaviour or failure label Nov 23, 2026
@steadytao steadytao added this to the 4.0.0 milestone Nov 23, 2026
@x15sr71

x15sr71 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @steadytao for picking this up and finishing it. Backing up before the rmdir with attribute preservation is a much better shape than where I'd left it.

I tested this branch as non-root on Ubuntu 24.04 (aarch64) and macOS, comparing against master on Ubuntu, and found one regression. If a deleted directory belongs to a group the user isn't a member of, the new ATTRS_REQUIRE_SUCCESS turns the chgrp EPERM into a backup failure. The directory is then never removed and every run exits 23. This happens with setgid shared dirs on Linux, and on BSD/macOS, where dirs inherit the parent's group. Per --group in the manpage, non-root rsync only preserves groups the user belongs to. Normal transfers enforce that via FLAG_SKIP_GROUP (uidlist.c:284), but the entry built locally with make_file() never sets it.

Repro, as a non-root user who is not in the users group:

sudo mkdir -m 2777 /tmp/share && sudo chgrp users /tmp/share
mkdir -p /tmp/src /tmp/share/dst/old/empty
./rsync -a --delete --backup --backup-dir=$HOME/bk /tmp/src/ /tmp/share/dst/

With this PR's build, the first run fails like this:

rsync: [generator] chgrp "/home/ubuntu/bk/old" failed: Operation not permitted (1)
rsync: [generator] chgrp "/home/ubuntu/bk/old/empty" failed: Operation not permitted (1)
rsync: [generator] backup directory "/tmp/share/dst/old/empty" failed: Operation not permitted (1)
cannot delete non-empty directory: old
rsync error: some files/attrs were not transferred (see previous errors) (code 23)

Every later run also exits 23 and leaves old/ and old/empty in place. Only the bk/old chgrp line goes away, because that directory now exists.

For comparison, master exits 0 but drops both directories without backing them up (the original #842 behaviour).

The fix I tested is small and follows what normal transfers already do. Right after the make_file() call in two functions in backup.c, it sets FLAG_SKIP_GROUP when rsync isn't running as root and the user isn't a member of the source directory's group. It uses the existing is_in_group() helper from uidlist.c, which only needs to stop being static. set_file_attrs() then skips the chgrp, as it does for any other non-member group. The check is needed in two places:

  • In copy_directory_backup_attrs(), using the original directory's gid. This stops the backup failing, so the directories are deleted and backed up with mode and mtime still preserved.
  • In copy_valid_path(), using the gid of the directory it is copying settings from. This is needed for a clean exit 0. Without it, the backup's parent dirs, like bk/old here, still log the chgrp error. Master already shows that error when it backs up a file from inside a foreign-group directory.

With both changes the repro exits 0 on every run.

If you're happy with this approach, I'd be glad to push it as a commit on top of yours, with a regression test for the foreign-group case.

@steadytao

Copy link
Copy Markdown
Member

@x15sr71 please do! Apologies for taking over; I have limited time among other projects and just trying to get through the large backlog.

A non-root receiver only preserves groups the user belongs to (see
--group), and normal transfers enforce this with FLAG_SKIP_GROUP.  The
file entries that backup.c builds locally with make_file() never set it,
so with ATTRS_REQUIRE_SUCCESS a chgrp EPERM made the directory backup
fail: the deleted directory was kept and every run exited 23.  This hits
setgid shared directories on Linux and inherited groups on BSD/macOS.

Set FLAG_SKIP_GROUP for such groups in copy_directory_backup_attrs() and
in copy_valid_path(), which also stops a spurious chgrp error when
creating backup parent directories.  Add a regression test for the
foreign-group case.
@steadytao steadytao self-assigned this Nov 23, 2026
@x15sr71

x15sr71 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

No apology needed at all, thanks for all the work on the backlog!

Pushed 57ef2a7. copy_directory_backup_attrs() and copy_valid_path() now set FLAG_SKIP_GROUP when rsync isn't root and the user isn't in the directory's group, as normal transfers do for --group. is_in_group() is no longer static so backup.c can use it.

The regression test is a new section in backup-deleted-directories.py. As root it uses a gid root isn't in, with --no-super. As non-root it uses a /tmp parent whose group the user can't grant (as on macOS/BSD), and skips that section otherwise. It checks for exit 0, deletion, preserved mode and mtime, and that the foreign group isn't applied. Without the fix it fails both as root (foreign group applied) and as non-root on macOS (exit 23).

Ran the full suite with and without the fix on Ubuntu 24.04 (aarch64) as root and on macOS. The only difference is this test, which now passes. As non-root on Ubuntu that section is skipped (no ungrantable group is available), and there are no new failures.

Separately, two file-backup paths have the same chgrp issue on master, because their make_file() entries don't set FLAG_SKIP_GROUP either:

  • make_backup()'s copy fallback, used when the rename fails, e.g. with --backup-dir on another filesystem.
  • The --inplace backup copy in generator.c, which always copies, even on the same filesystem.

In both, a file whose group the user isn't in is backed up correctly, but rsync logs the chgrp EPERM and exits 23. They're unrelated to this PR, so I'm happy to send a small follow-up PR for them if that's useful.

Could you approve the CI run when you get a chance? Let me know if anything else needs changing!

@steadytao

Copy link
Copy Markdown
Member

Quite late for me now. Will review tomorrow.

@steadytao

Copy link
Copy Markdown
Member

hmmm some light fixes then this will be good to merge. thank you for your work.

@steadytao

Copy link
Copy Markdown
Member

Will continue later on, few more things.

@steadytao

Copy link
Copy Markdown
Member

Alrighty this has grown quite a bit beyond the scope of #842 but there were some substantial issues that were incredibly adjacent so I have decided to fix all at once. Title and desc will be updated very soon.

@steadytao steadytao changed the title delete: preserve empty dirs in --backup-dir when deleting backup: preserve deleted directories and fail on copy errors Nov 24, 2026
@steadytao steadytao removed their assignment Nov 24, 2026
@steadytao
steadytao merged commit ebe5e2d into RsyncProject:master Nov 24, 2026
79 of 82 checks passed
@steadytao

Copy link
Copy Markdown
Member

Thank you for your initial work @x15sr71

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Bug Confirmed incorrect behaviour or failure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

--backup does not keep empty directories in --backup-dir

4 participants