From c21010528829eea42ffcfa82c9f5aa6a319083c1 Mon Sep 17 00:00:00 2001 From: Chandragupt Singh Date: Wed, 3 Jun 2026 22:47:15 +0530 Subject: [PATCH 01/10] delete: preserve empty dirs in --backup-dir when deleting; add regression test --- delete.c | 22 +++++- testsuite/backup-empty-dir_test.py | 107 +++++++++++++++++++++++++++++ 2 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 testsuite/backup-empty-dir_test.py diff --git a/delete.c b/delete.c index 4a52122d3..ffda1b3f3 100644 --- a/delete.c +++ b/delete.c @@ -159,8 +159,26 @@ enum delret delete_item(char *fbuf, uint16 mode, uint16 flags) } if (S_ISDIR(mode)) { - what = "rmdir"; - ok = do_rmdir_at(fbuf) == 0; + ok = 0; + if (make_backups > 0 && !(flags & DEL_FOR_BACKUP) && backup_dir) { + char *buf = get_backup_name(fbuf); + if (buf && do_rename_at(fbuf, buf) == 0) { + if (INFO_GTE(BACKUP, 1)) + rprintf(FINFO, "backed up %s to %s\n", fbuf, buf); + what = "rename"; + ok = 1; + } else if (buf && errno != EEXIST && errno != ENOTEMPTY + && errno != EISDIR) { + /* Rename failed for an unexpected reason (e.g. EXDEV). + * Warn and fall through to rmdir. */ + rprintf(FWARNING, "skipping backup of directory %s: %s\n", + fbuf, strerror(errno)); + } + } + if (!ok) { + what = "rmdir"; + ok = do_rmdir_at(fbuf) == 0; + } } else { if (make_backups > 0 && !(flags & DEL_FOR_BACKUP) && (backup_dir || !is_backup_file(fbuf))) { what = "make_backup"; diff --git a/testsuite/backup-empty-dir_test.py b/testsuite/backup-empty-dir_test.py new file mode 100644 index 000000000..5833c46f4 --- /dev/null +++ b/testsuite/backup-empty-dir_test.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +# Regression test for issue #842: +# rsync --backup --backup-dir --delete must preserve empty directories +# in --backup-dir rather than silently removing them. + +import re +import subprocess + +from rsyncfns import ( + FROMDIR, TODIR, TMPDIR, + assert_exists, assert_not_exists, + makepath, rmtree, + run_rsync, rsync_argv, test_fail, +) + +bakdir = TMPDIR / 'bak' + + +# --------------------------------------------------------------------------- +# Phase 1: basic reproducer from issue #842. +# src/ is empty; dst/sub/empty_dir/ and dst/sub/file.txt get deleted. +# Both must land in backup-dir, not be silently discarded. +# --------------------------------------------------------------------------- +makepath(FROMDIR, TODIR / 'sub' / 'empty_dir', bakdir) +(TODIR / 'sub' / 'file.txt').write_text('data\n') + +proc = subprocess.run( + rsync_argv('-r', '--delete', '--backup', f'--backup-dir={bakdir}', + '--info=backup', f'{FROMDIR}/', f'{TODIR}/'), + capture_output=True, text=True, +) +if proc.returncode != 0: + test_fail(f'rsync failed (phase 1): {proc.stderr}') +output = proc.stdout + proc.stderr + +assert_exists(bakdir / 'sub' / 'file.txt', label='phase1: file.txt in backup-dir') +assert_exists(bakdir / 'sub' / 'empty_dir', label='phase1: empty_dir in backup-dir') +if not (bakdir / 'sub' / 'empty_dir').is_dir(): + test_fail('phase1: backup-dir/sub/empty_dir must be a directory') +assert_not_exists(TODIR / 'sub', label='phase1: dst/sub removed after sync') + +if not re.search(r'backed up sub/empty_dir to ', output, re.MULTILINE): + test_fail('phase1: no "backed up sub/empty_dir" log line in rsync output') + + +# --------------------------------------------------------------------------- +# Phase 2: collision safety (steadytao concern, issue #842). +# File backups create backup_dir/sub/ first. The subsequent attempt to back +# up sub/ itself must not wipe those already-preserved child files. +# --------------------------------------------------------------------------- +rmtree(FROMDIR); rmtree(TODIR); rmtree(bakdir) +makepath(FROMDIR, TODIR / 'sub' / 'empty_dir', bakdir) +(TODIR / 'sub' / 'file1.txt').write_text('file1\n') +(TODIR / 'sub' / 'file2.txt').write_text('file2\n') + +run_rsync('-r', '--delete', '--backup', f'--backup-dir={bakdir}', + f'{FROMDIR}/', f'{TODIR}/') + +assert_exists(bakdir / 'sub' / 'file1.txt', label='phase2: file1.txt survives') +assert_exists(bakdir / 'sub' / 'file2.txt', label='phase2: file2.txt survives') +assert_exists(bakdir / 'sub' / 'empty_dir', label='phase2: empty_dir in backup-dir') +assert_not_exists(TODIR / 'sub', label='phase2: dst/sub removed after sync') + + +# --------------------------------------------------------------------------- +# Phase 3: nested empty directories (a/b/c). +# --------------------------------------------------------------------------- +rmtree(FROMDIR); rmtree(TODIR); rmtree(bakdir) +makepath(FROMDIR, TODIR / 'a' / 'b' / 'c', bakdir) + +run_rsync('-r', '--delete', '--backup', f'--backup-dir={bakdir}', + f'{FROMDIR}/', f'{TODIR}/') + +assert_exists(bakdir / 'a' / 'b' / 'c', label='phase3: a/b/c in backup-dir') +if not (bakdir / 'a' / 'b' / 'c').is_dir(): + test_fail('phase3: backup-dir/a/b/c must be a directory') +assert_not_exists(TODIR / 'a', label='phase3: dst/a removed after sync') + + +# --------------------------------------------------------------------------- +# Phase 4: no regression without --backup-dir. +# Empty dir must still be deleted; no empty_dir~ artefact must appear. +# --------------------------------------------------------------------------- +rmtree(FROMDIR); rmtree(TODIR) +makepath(FROMDIR, TODIR / 'empty_dir') + +run_rsync('-r', '--delete', '--backup', f'{FROMDIR}/', f'{TODIR}/') + +assert_not_exists(TODIR / 'empty_dir', label='phase4: empty_dir removed without --backup-dir') +assert_not_exists(TODIR / 'empty_dir~', label='phase4: no empty_dir~ created') + + +# --------------------------------------------------------------------------- +# Phase 5: --delete-delay variant. +# Deletions are queued and executed after the transfer; the backup path +# in delete_item() must still be reached for empty directories. +# --------------------------------------------------------------------------- +rmtree(FROMDIR); rmtree(TODIR); rmtree(bakdir) +makepath(FROMDIR, TODIR / 'sub' / 'empty_dir', bakdir) +(TODIR / 'sub' / 'file.txt').write_text('data\n') + +run_rsync('-r', '--delete-delay', '--backup', f'--backup-dir={bakdir}', + f'{FROMDIR}/', f'{TODIR}/') + +assert_exists(bakdir / 'sub' / 'empty_dir', label='phase5: empty_dir backed up with --delete-delay') +assert_exists(bakdir / 'sub' / 'file.txt', label='phase5: file.txt backed up with --delete-delay') +assert_not_exists(TODIR / 'sub', label='phase5: dst/sub removed after sync') From 75a743cbaba850b8bedb9ee0388cc8551431a54d Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Sat, 6 Jun 2026 06:35:06 +1000 Subject: [PATCH 02/10] testsuite: check that only the right files go into backup this demonstrates a subtle bug in PR 967 --- testsuite/backup-pinned-dir_test.py | 62 +++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 testsuite/backup-pinned-dir_test.py diff --git a/testsuite/backup-pinned-dir_test.py b/testsuite/backup-pinned-dir_test.py new file mode 100644 index 000000000..fc59fb5af --- /dev/null +++ b/testsuite/backup-pinned-dir_test.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +# Regression test for the bug in PR #967. +# +# PR #967 makes delete_item() rename a directory into --backup-dir before +# falling back to rmdir, so empty dirs are preserved in the backup tree +# (issue #842). The rename branch fires whenever DEL_DIR_IS_EMPTY is set, +# but that flag is NOT proof of emptiness: delete_dir_contents() sets it on +# a child even when the child's own content deletion returned DR_NOT_EMPTY +# (a grandchild survived). do_rmdir_at() was safe there -- it fails with +# ENOTEMPTY -- but do_rename_at() happily moves the whole non-empty subtree +# into the backup-dir. +# +# A "protect" filter (P) pins a file against deletion, leaving its parent +# non-empty. rsync must leave that file where it is. With the PR bug, the +# pinned parent gets renamed wholesale into --backup-dir, relocating data +# rsync deliberately chose not to delete. +# +# Correct behaviour (master): the protected file stays in the destination. +# Buggy behaviour (PR #967): the protected file is moved into --backup-dir. + +from rsyncfns import ( + FROMDIR, TODIR, TMPDIR, + assert_exists, assert_not_exists, + makepath, rmtree, run_rsync, test_fail, +) + +bakdir = TMPDIR / 'bak' + +# The pinned file must be the ONLY thing in its nested directory, and that +# directory must have no sibling whose own backup would pre-create the +# backup-dir counterpart -- otherwise the rename collides (EEXIST/ENOTEMPTY) +# and harmlessly falls back to rmdir, masking the bug. 'sibling.txt' lives +# one level up so it creates bak/sub/ but not bak/sub/inner/. +rmtree(FROMDIR); rmtree(TODIR); rmtree(bakdir) +makepath(FROMDIR, TODIR / 'sub' / 'inner', bakdir) +(TODIR / 'sub' / 'inner' / 'keep.txt').write_text('keepme\n') +(TODIR / 'sub' / 'sibling.txt').write_text('sib\n') + +# src is empty: everything under dst/ is extraneous and would be deleted, +# except sub/inner/keep.txt which the protect filter pins in place. +run_rsync('-r', '--delete', '--backup', f'--backup-dir={bakdir}', + '--filter=P sub/inner/keep.txt', + f'{FROMDIR}/', f'{TODIR}/') + +# The protected file must remain exactly where it was. +assert_exists(TODIR / 'sub' / 'inner' / 'keep.txt', + label='protected keep.txt must stay in the destination') + +# ...and must NOT have been relocated into the backup-dir. +assert_not_exists(bakdir / 'sub' / 'inner' / 'keep.txt', + label='protected keep.txt must NOT be moved into backup-dir') + +# Its pinned parent directory must also remain in place. +assert_exists(TODIR / 'sub' / 'inner', + label='pinned dir sub/inner must stay in the destination') + +# The non-pinned sibling should still be backed up normally. +assert_exists(bakdir / 'sub' / 'sibling.txt', + label='non-pinned sibling.txt backed up as usual') + +if not (TODIR / 'sub' / 'inner' / 'keep.txt').is_file(): + test_fail('protected file was relocated by the backup-dir rename (PR #967 bug)') From 37466f4d2ebb3b83074f118cabc7ee8dc2532f8a Mon Sep 17 00:00:00 2001 From: Chandragupt Singh Date: Sat, 6 Jun 2026 20:39:15 +0530 Subject: [PATCH 03/10] delete: use rmdir+mkdir instead of rename to safely back up empty dirs --- delete.c | 21 ++++++--------------- 1 file changed, 6 insertions(+), 15 deletions(-) diff --git a/delete.c b/delete.c index ffda1b3f3..b5361a7f9 100644 --- a/delete.c +++ b/delete.c @@ -159,26 +159,17 @@ enum delret delete_item(char *fbuf, uint16 mode, uint16 flags) } if (S_ISDIR(mode)) { - ok = 0; - if (make_backups > 0 && !(flags & DEL_FOR_BACKUP) && backup_dir) { + what = "rmdir"; + ok = do_rmdir_at(fbuf) == 0; + if (ok && make_backups > 0 && !(flags & DEL_FOR_BACKUP) && backup_dir) { char *buf = get_backup_name(fbuf); - if (buf && do_rename_at(fbuf, buf) == 0) { + if (buf && do_mkdir_at(buf, ACCESSPERMS) == 0) { if (INFO_GTE(BACKUP, 1)) rprintf(FINFO, "backed up %s to %s\n", fbuf, buf); - what = "rename"; - ok = 1; - } else if (buf && errno != EEXIST && errno != ENOTEMPTY - && errno != EISDIR) { - /* Rename failed for an unexpected reason (e.g. EXDEV). - * Warn and fall through to rmdir. */ - rprintf(FWARNING, "skipping backup of directory %s: %s\n", - fbuf, strerror(errno)); + } else if (buf && errno != EEXIST && errno != EISDIR) { + rsyserr(FWARNING, errno, "backup mkdir %s failed", buf); } } - if (!ok) { - what = "rmdir"; - ok = do_rmdir_at(fbuf) == 0; - } } else { if (make_backups > 0 && !(flags & DEL_FOR_BACKUP) && (backup_dir || !is_backup_file(fbuf))) { what = "make_backup"; From d8e6057eef11b573ba8a5e1f81213b61d62af0c3 Mon Sep 17 00:00:00 2001 From: Chandragupt Singh Date: Sun, 7 Jun 2026 02:49:52 +0530 Subject: [PATCH 04/10] delete: treat EEXIST like ENOTEMPTY for rmdir on Solaris --- delete.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/delete.c b/delete.c index b5361a7f9..9a42293ef 100644 --- a/delete.c +++ b/delete.c @@ -203,7 +203,7 @@ enum delret delete_item(char *fbuf, uint16 mode, uint16 flags) } ret = DR_SUCCESS; } else { - if (S_ISDIR(mode) && errno == ENOTEMPTY) { + if (S_ISDIR(mode) && (errno == ENOTEMPTY || errno == EEXIST)) { rprintf(FINFO, "cannot delete non-empty directory: %s\n", fbuf); ret = DR_NOT_EMPTY; From 1591e662fd7c8483c38be987a5f8cf83086e63e7 Mon Sep 17 00:00:00 2001 From: Zen Dodd Date: Mon, 23 Nov 2026 19:57:52 +1100 Subject: [PATCH 05/10] backup: reconcile directory xattrs and preserve replacement behaviour --- NEWS.md | 5 ++- backup.c | 2 +- delete.c | 11 +++--- .../backup-deleted-directory-attributes.py | 14 ++++++- .../transfer/backup-deleted-directories.py | 36 ++++++++++++++---- xattrs.c | 37 +++++++++++++++---- 6 files changed, 80 insertions(+), 25 deletions(-) diff --git a/NEWS.md b/NEWS.md index 7f4090373..341788fef 100644 --- a/NEWS.md +++ b/NEWS.md @@ -31,8 +31,9 @@ initial buffer. - Report buffered diagnostic and logfile write failures instead of returning success after dropping output. -- Preserve directories and their requested attributes when deleting them - with `--backup-dir`. Leave the original directory in place if its backup fails. +- Preserve directories and their requested attributes in `--backup-dir` + when removing them during a deletion pass. Leave the original directory + in place if its backup fails. ## 3.5 maintenance line diff --git a/backup.c b/backup.c index d2d24ac53..dc8ce1f15 100644 --- a/backup.c +++ b/backup.c @@ -251,7 +251,7 @@ static BOOL copy_directory_backup_attrs(const char *fname, int source_fd, if (preserve_xattrs) { backup_fd = backup_source_fd(backup); if ((backup_fd < 0 && backup_metadata_hardened()) - || copy_xattrs(fname, source_fd, backup, backup_fd) < 0) + || reconcile_backup_xattrs(fname, source_fd, backup, backup_fd) < 0) goto cleanup; } #endif diff --git a/delete.c b/delete.c index 970a0fe66..bbed672de 100644 --- a/delete.c +++ b/delete.c @@ -93,7 +93,7 @@ static int directory_backup_stat(const char *path, uint16 mode, uint16 flags, int error; if (!S_ISDIR(mode) || make_backups <= 0 || !backup_dir - || dry_run || (flags & DEL_FOR_BACKUP)) + || dry_run || (flags & (DEL_FOR_BACKUP | DEL_MAKE_ROOM))) return 0; if ((am_root < 0 ? x_lstat(path, st, NULL) : do_lstat_at(path, st)) == 0) { @@ -125,7 +125,7 @@ static void restore_directory_backup_mode(const char *path, const STRUCT_STAT *o * DR_NOT_EMPTY. Note that fname must point to a MAXPATHLEN buffer! (The * buffer is used for recursion, but returned unchanged.) */ -static enum delret delete_dir_contents(char *fname, uint16 flags) +static enum delret delete_dir_contents(char *fname, uint16 flags, BOOL back_up_dirs) { struct file_list *dirlist; enum delret ret; @@ -191,7 +191,7 @@ static enum delret delete_dir_contents(char *fname, uint16 flags) } strlcpy(p, fp->basename, remainder); - back_up = directory_backup_stat(fname, fp->mode, flags, &st); + back_up = back_up_dirs ? directory_backup_stat(fname, fp->mode, flags, &st) : 0; if (back_up < 0) { if (errno != ENOENT) ret = DR_NOT_EMPTY; @@ -201,7 +201,7 @@ static enum delret delete_dir_contents(char *fname, uint16 flags) restore_mode = del_chmod(fname, fp->mode | S_IWUSR) == 0 && back_up; /* Save stack by recursing to ourself directly. */ if (S_ISDIR(fp->mode) - && delete_dir_contents(fname, flags | DEL_RECURSE) != DR_SUCCESS) { + && delete_dir_contents(fname, flags | DEL_RECURSE, back_up_dirs) != DR_SUCCESS) { ret = DR_NOT_EMPTY; if (back_up) { if (restore_mode) @@ -262,7 +262,8 @@ static enum delret delete_item_with_stat(char *fbuf, uint16 mode, uint16 flags, * delete_dir_contents() always calls us w/DEL_DIR_IS_EMPTY. */ ignore_perishable = 1; /* If DEL_RECURSE is not set, this just reports emptiness. */ - ret = delete_dir_contents(fbuf, flags); + /* Replacing a directory must not start backing up its subdirectories. */ + ret = delete_dir_contents(fbuf, flags, backup_stat != NULL); ignore_perishable = 0; if (ret == DR_NOT_EMPTY || ret == DR_AT_LIMIT) goto check_ret; diff --git a/testsuite/tests/metadata/backup-deleted-directory-attributes.py b/testsuite/tests/metadata/backup-deleted-directory-attributes.py index a276f317e..f25a863ea 100644 --- a/testsuite/tests/metadata/backup-deleted-directory-attributes.py +++ b/testsuite/tests/metadata/backup-deleted-directory-attributes.py @@ -4,7 +4,7 @@ from harness.filesystem import acl_get, acl_set from harness.results import test_fail from harness.rsync import run_rsync -from harness.xattrs import get_value, set_value +from harness.xattrs import dump_values, get_value, set_value @requires(features={'backup_metadata', 'linux_acl'}, transports={'pipe'}, @@ -18,9 +18,15 @@ def test(context: TestContext): test_fail('cannot set directory ACL') value = 'data' * 500 set_value('backup-directory', value, old) + saved = backup / 'old' + saved.mkdir(parents=True) + set_value('backup-directory', 'previous value', saved) + set_value('backup-stale', 'previous snapshot', saved) + set_value('backup-excluded', 'keep this', saved) + set_value('backup-excluded', 'do not copy this', old) run_rsync('-aAX', '--delete', '--backup', f'--backup-dir={backup}', + '--filter=-x user.backup-excluded', f'{context.source}/', f'{dest}/') - saved = backup / 'old' if old.exists(): test_fail('backed-up directory is still present at the destination') if not saved.is_dir(): @@ -29,6 +35,10 @@ def test(context: TestContext): test_fail('the directory backup lost its access ACL') if get_value('backup-directory', saved) != value.encode(): test_fail('the directory backup lost the large extended attribute') + if get_value('backup-excluded', saved) != b'keep this': + test_fail('the directory backup changed an excluded extended attribute') + if 'user.backup-stale=' in dump_values(saved): + test_fail('the directory backup retained a stale extended attribute') if __name__ == '__main__': diff --git a/testsuite/tests/transfer/backup-deleted-directories.py b/testsuite/tests/transfer/backup-deleted-directories.py index 91c149052..3cc94021a 100644 --- a/testsuite/tests/transfer/backup-deleted-directories.py +++ b/testsuite/tests/transfer/backup-deleted-directories.py @@ -13,13 +13,14 @@ def test(context: TestContext): src = context.source src.mkdir() - def transfer(dst, backup, delete_mode, *options, status=0): - args = ['-a', delete_mode, '--backup', *options] + def transfer(dst, backup, *options, status=0): + args = ['-a', '--backup', *options] if backup is not None: args.append(f'--backup-dir={backup}') result = run_rsync(*args, f'{src}/', f'{dst}/', capture_output=True, check=False) if result.returncode != status: - test_fail(f'{dst.name}: expected exit {status}, got {result.returncode}: {result.stderr}') + case = dst.relative_to(context.scratch) + test_fail(f'{case}: expected exit {status}, got {result.returncode}: {result.stderr}') for mode in ('--delete-before', '--delete-during', '--delete-delay', '--delete-after'): root = context.scratch / mode[2:] @@ -74,15 +75,23 @@ def transfer(dst, backup, delete_mode, *options, status=0): empty.chmod(0o551) os.utime(empty, (1_501_234_567, 1_501_234_567)) backup.mkdir() - if collision == 'unwritable': - backup.chmod(0o500) - elif collision in ('file', 'nested-file'): + if collision in ('file', 'nested-file'): (backup / name).parent.mkdir(parents=True, exist_ok=True) (backup / name).write_bytes(b'occupied') - else: + elif collision == 'symlink': (root / 'other').mkdir() (backup / 'empty').symlink_to(root / 'other', target_is_directory=True) try: + if collision == 'unwritable': + backup.chmod(0o500) + probe = backup / 'write-probe' + try: + probe.mkdir() + except PermissionError: + pass + else: + probe.rmdir() + continue transfer(dst, backup, '--delete-during', status=23) finally: backup.chmod(0o700) @@ -101,6 +110,19 @@ def transfer(dst, backup, delete_mode, *options, status=0): if list(dst.iterdir()): test_fail('backup suffix mode changed how empty directories are deleted') + (src / 'entry').write_bytes(b'new contents') + for case, subdir in (('replace-empty', 'entry'), ('replace-nested', 'entry/empty')): + root = context.scratch / case + dst, backup = root / 'dest', root / 'backup' + (dst / subdir).mkdir(parents=True) + backup.mkdir() + (backup / 'entry').write_bytes(b'previous backup') + transfer(dst, backup, '--force') + if (dst / 'entry').read_bytes() != b'new contents': + test_fail(f'{case}: replacement did not reach the destination') + if (backup / 'entry').read_bytes() != b'previous backup': + test_fail(f'{case}: directory replacement changed the previous backup') + if __name__ == '__main__': run(test) diff --git a/xattrs.c b/xattrs.c index 73478c184..409356bda 100644 --- a/xattrs.c +++ b/xattrs.c @@ -240,13 +240,13 @@ static char *get_xattr_data(const char *fname, int fd, const char *name, size_t return ptr; } -static int rsync_xal_get(const char *fname, int fd, item_list *xalp) +static int rsync_xal_get(const char *fname, int fd, item_list *xalp, BOOL local_backup) { ssize_t list_len, name_len; size_t datum_len, name_offset; char *name, *ptr; #ifdef HAVE_LINUX_XATTRS - int user_only = am_sender ? 0 : !am_root; + int user_only = !am_sender && (local_backup ? am_root <= 0 : !am_root); #endif rsync_xa *rxa; int count; @@ -283,7 +283,7 @@ static int rsync_xal_get(const char *fname, int fd, item_list *xalp) if (!(ptr = get_xattr_data(fname, fd, name, &datum_len, 0))) return -1; - if (datum_len > MAX_FULL_DATUM) { + if (!local_backup && datum_len > MAX_FULL_DATUM) { /* For large datums, we store a flag and a checksum. */ name_offset = 1 + MAX_XATTR_DIGEST_LEN; sum_init(xattr_sum_nni, checksum_seed); @@ -344,7 +344,7 @@ int get_xattr(const char *fname, int fd, stat_x *sxp) } else if (IS_MISSING_FILE(sxp->st)) return 0; - if (rsync_xal_get(fname, fd, sxp->xattr) < 0) { + if (rsync_xal_get(fname, fd, sxp->xattr, False) < 0) { free_xattr(sxp); return -1; } @@ -990,7 +990,8 @@ void uncache_tmp_xattrs(void) /* Apply the wanted xattr set to fname. When fd >= 0, the list/set/remove ops * that target fname go through that held fd (sys_f*xattr) so a parent-symlink * race can't redirect them; the abbreviated-value compare still reads the basis - * via the fnamecmp path. fd < 0 keeps the path-based behavior. */ + * via the fnamecmp path. fd < 0 keeps the path-based behavior. A NULL sxp + * means the caller handles timestamps separately. */ static int rsync_xal_set(const char *fname, item_list *xalp, const char *fnamecmp, stat_x *sxp, int fd) { @@ -1012,6 +1013,10 @@ static int rsync_xal_set(const char *fname, item_list *xalp, name = rxas[i].name; if (XATTR_ABBREV(rxas[i])) { + if (!fnamecmp) { + errno = EINVAL; + return -1; + } /* See if the fnamecmp version is identical. */ len = name_len = rxas[i].name_len; if ((ptr = get_xattr_data(fnamecmp, -1, name, &len, 1)) == NULL) { @@ -1044,7 +1049,7 @@ static int rsync_xal_set(const char *fname, item_list *xalp, "rsync_xal_set: %ssetxattr(%s,\"%s\") failed", fd >= 0 ? "f" : "l", full_fname(fname), name); ret = -1; - } else /* make sure caller sets mtime */ + } else if (sxp) /* make sure caller sets mtime */ sxp->st.st_mtime = (time_t)-1; if (am_generator) { /* generator items stay abbreviated */ @@ -1066,7 +1071,7 @@ static int rsync_xal_set(const char *fname, item_list *xalp, "rsync_xal_set: %ssetxattr(%s,\"%s\") failed", fd >= 0 ? "f" : "l", full_fname(fname), name); ret = -1; - } else /* make sure caller sets mtime */ + } else if (sxp) /* make sure caller sets mtime */ sxp->st.st_mtime = (time_t)-1; } @@ -1101,7 +1106,7 @@ static int rsync_xal_set(const char *fname, item_list *xalp, "rsync_xal_set: %sremovexattr(%s,\"%s\") failed", fd >= 0 ? "f" : "l", full_fname(fname), name); ret = -1; - } else /* make sure caller sets mtime */ + } else if (sxp) /* make sure caller sets mtime */ sxp->st.st_mtime = (time_t)-1; } } @@ -1109,6 +1114,22 @@ static int rsync_xal_set(const char *fname, item_list *xalp, return ret; } +/* A reused backup directory needs the selected set, not an additive copy. + * Keep full values and finish reading before changing the backup. */ +int reconcile_backup_xattrs(const char *source, int source_fd, const char *dest, int dest_fd) +{ + item_list attrs = EMPTY_ITEM_LIST; + int ret = rsync_xal_get(source, source_fd, &attrs, True); + int save_errno; + + if (ret == 0) + ret = rsync_xal_set(dest, &attrs, NULL, NULL, dest_fd); + save_errno = errno; + rsync_xal_free(&attrs); + errno = save_errno; + return ret; +} + /* Set extended attributes on indicated filename. When fd >= 0 it is a held, * O_NOFOLLOW-opened fd for fname (a regular file or directory) and the xattr * ops go through it (fsetxattr/fremovexattr/flistxattr) so a parent-symlink From 57ef2a79f2dbd86d3a9d6b86fb8ce807690c51a3 Mon Sep 17 00:00:00 2001 From: Chandragupt Singh Date: Mon, 23 Nov 2026 16:33:18 +0530 Subject: [PATCH 06/10] backup: skip ungrantable groups when backing up directories 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. --- backup.c | 4 ++ .../transfer/backup-deleted-directories.py | 46 +++++++++++++++++++ uidlist.c | 2 +- 3 files changed, 51 insertions(+), 1 deletion(-) diff --git a/backup.c b/backup.c index dc8ce1f15..a605a01c8 100644 --- a/backup.c +++ b/backup.c @@ -148,6 +148,8 @@ static BOOL copy_valid_path(const char *fname) struct file_struct *file; if (!(file = make_file(rel, NULL, NULL, 0, NO_FILTERS))) continue; + if (!am_root && !is_in_group(sx.st.st_gid)) + file->flags |= FLAG_SKIP_GROUP; #if defined SUPPORT_ACLS || defined SUPPORT_XATTRS { /* read the source dir's ACL/xattr through a confined fd */ int bfd = backup_source_fd(rel); @@ -240,6 +242,8 @@ static BOOL copy_directory_backup_attrs(const char *fname, int source_fd, goto cleanup; } source.st = *original; + if (!am_root && !is_in_group(original->st_gid)) + file->flags |= FLAG_SKIP_GROUP; #ifdef SUPPORT_ACLS if (preserve_acls) { if (get_acl_fdat(source_fd, -1, NULL, fname, &source) < 0) diff --git a/testsuite/tests/transfer/backup-deleted-directories.py b/testsuite/tests/transfer/backup-deleted-directories.py index 3cc94021a..93f6ff49d 100644 --- a/testsuite/tests/transfer/backup-deleted-directories.py +++ b/testsuite/tests/transfer/backup-deleted-directories.py @@ -1,7 +1,10 @@ #!/usr/bin/env python3 import os +import shutil import stat +import tempfile +from pathlib import Path from harness import TestContext, requires, run from harness.results import test_fail @@ -104,6 +107,49 @@ def transfer(dst, backup, *options, status=0): elif collision in ('file', 'nested-file') and (backup / name).read_bytes() != b'occupied': test_fail(f'{collision}: failed backup overwrote an existing file') + # As with --group, a non-root backup must skip a group the user cannot + # grant (setgid shares, BSD/macOS inherited groups) rather than fail. + if os.geteuid() == 0: + foreign = next(g for g in range(54321, 65534) if g not in os.getgroups()) + parent, extra = context.scratch / 'foreign-group', ['--no-super'] + parent.mkdir() + else: + try: + parent, extra = Path(tempfile.mkdtemp(prefix='rsync-foreign-', dir='/tmp')), [] + except OSError: + parent = None + if parent is not None: + foreign = parent.stat().st_gid + if foreign in os.getgroups(): + shutil.rmtree(parent) + parent = None + if parent is not None: + try: + dst, backup = parent / 'dest', context.scratch / 'foreign-group-backup' + inner = dst / 'old' / 'empty' + inner.mkdir(parents=True) + snapshots = {} + for path in (inner, inner.parent): + if os.geteuid() == 0: + os.chown(path, -1, foreign) + os.utime(path, (1_501_234_567, 1_501_234_567)) + snapshots[path.relative_to(dst)] = path.stat() + result = run_rsync('-a', '--backup', '--delete-during', *extra, + f'--backup-dir={backup}', f'{src}/', f'{dst}/', + capture_output=True, check=False) + if result.returncode != 0: + test_fail(f'foreign-group: expected exit 0, got {result.returncode}: {result.stderr}') + if inner.parent.exists(): + test_fail('foreign-group: directory was not deleted') + for name, original in snapshots.items(): + actual = (backup / name).stat() + if (actual.st_mode, actual.st_mtime) != (original.st_mode, original.st_mtime): + test_fail(f'foreign-group: backup did not preserve metadata for {name}') + if actual.st_gid == foreign: + test_fail(f'foreign-group: backup of {name} kept an ungrantable group') + finally: + shutil.rmtree(parent) + dst = context.scratch / 'suffix-only' (dst / 'empty').mkdir(parents=True) transfer(dst, None, '--delete-during') diff --git a/uidlist.c b/uidlist.c index 5c1096ad7..3df1713a3 100644 --- a/uidlist.c +++ b/uidlist.c @@ -192,7 +192,7 @@ int group_to_gid(const char *name, gid_t *gid_p, BOOL num_ok) return 1; } -static int is_in_group(gid_t gid) +int is_in_group(gid_t gid) { #ifdef HAVE_GETGROUPS static gid_t last_in; From 2d7988ff79a71364beee9cad5cbe1e03aeefabcc Mon Sep 17 00:00:00 2001 From: Zen Dodd Date: Tue, 24 Nov 2026 09:07:07 +1100 Subject: [PATCH 07/10] backup: preserve directory metadata across backup reuse --- backup.c | 245 ++++++++++++++++-- generator.c | 13 +- rsync.1.md | 8 + .../backup-deleted-directory-attributes.py | 20 ++ .../transfer/backup-deleted-directories.py | 53 +++- .../tests/transfer/backup-readonly-reuse.py | 76 ++++++ 6 files changed, 386 insertions(+), 29 deletions(-) create mode 100644 testsuite/tests/transfer/backup-readonly-reuse.py diff --git a/backup.c b/backup.c index a605a01c8..5d2c8b22f 100644 --- a/backup.c +++ b/backup.c @@ -22,6 +22,7 @@ #include "ifuncs.h" extern int am_root; +extern int dry_run; extern int preserve_acls; extern int preserve_xattrs; extern int preserve_devices; @@ -29,6 +30,7 @@ extern int preserve_specials; extern int preserve_links; extern int safe_symlinks; extern int backup_dir_len; +extern int backup_suffix_len; extern unsigned int backup_dir_remainder; extern int operator_path_resolve; extern char backup_dir_buf[MAXPATHLEN]; @@ -61,6 +63,137 @@ int backup_source_fd(const char *path) return -1; } +struct backup_dir_access { + int fd; + mode_t mode; +}; + +/* Change only an owned directory beneath the checked backup root. The fd + * keeps mode restoration tied to the same directory, not to its name. */ +static BOOL allow_backup_dir_write(struct backup_dir_access *access) +{ +#if defined HAVE_CHMOD && defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY + STRUCT_STAT st, root_st, pinned; + char root[MAXPATHLEN]; + int root_fd, fd, save_errno; + + if (dry_run || !operator_path_resolve || !backup_dir || am_root > 0 + || !backup_dir_buf[backup_dir_len]) + return True; + if (do_lstat_at(backup_dir_buf, &st) < 0 || !S_ISDIR(st.st_mode) + || st.st_uid != MY_UID() || st.st_mode & S_IWUSR) + return True; + /* A chmod may silently clear an ungrantable setgid bit. */ + if (st.st_mode & S_ISGID && !is_in_group(st.st_gid)) + return True; + + memcpy(root, backup_dir_buf, backup_dir_len); + root[backup_dir_len] = '\0'; + if ((root_fd = open_no_attacker_symlinks_dirfd(root)) < 0) + goto failed; + if (do_fstat(root_fd, &root_st) < 0) + fd = -1; + else if (root_st.st_dev == st.st_dev && root_st.st_ino == st.st_ino) { + close(root_fd); + return True; + } else + fd = secure_relative_open_at_beneath(root_fd, backup_dir_buf + backup_dir_len, + O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, 0); + save_errno = errno; + close(root_fd); + errno = save_errno; + if (fd < 0) + goto failed; + if (do_fstat(fd, &pinned) < 0) + goto close_failed; + if (pinned.st_dev != st.st_dev || pinned.st_ino != st.st_ino + || pinned.st_mode != st.st_mode || pinned.st_uid != st.st_uid || pinned.st_gid != st.st_gid) { + errno = EINVAL; + goto close_failed; + } + if (do_chmod_attrs(backup_dir_buf, (st.st_mode & CHMOD_BITS) | S_IWUSR, fd, -1, NULL, False) < 0) + goto close_failed; + access->fd = fd; + access->mode = st.st_mode & CHMOD_BITS; + return True; + + close_failed: + save_errno = errno; + close(fd); + errno = save_errno; + failed: + save_errno = errno; + rsyserr(FERROR_XFER, save_errno, "cannot make backup directory %s writable", full_fname(backup_dir_buf)); + errno = save_errno; + return False; +#else + (void)access; + return True; +#endif +} + +static BOOL allow_backup_parent_write(struct backup_dir_access *access) +{ + char *slash; + BOOL ok; + + if (!backup_dir || !(slash = strrchr(backup_dir_buf + backup_dir_len, '/'))) + return True; + *slash = '\0'; + ok = allow_backup_dir_write(access); + *slash = '/'; + return ok; +} + +static BOOL restore_backup_dir_mode(struct backup_dir_access *access) +{ +#ifdef HAVE_CHMOD + if (access->fd >= 0) { + int save_errno = errno; + int ret = do_chmod_attrs(backup_dir_buf, access->mode, access->fd, -1, NULL, False); + int error = errno; + + close(access->fd); + access->fd = -1; + if (ret < 0) { + rsyserr(FERROR_XFER, error, "cannot restore backup directory mode for %s", + full_fname(backup_dir_buf)); + errno = error; + return False; + } + errno = save_errno; + } +#else + (void)access; +#endif + return True; +} + +static int mkdir_backup_dir(void) +{ + struct backup_dir_access parent = {.fd = -1}; + int ret = do_mkdir_at(backup_dir_buf, ACCESSPERMS); + int save_errno = errno; + + if (ret == 0 || (errno != EACCES && errno != EPERM)) + return ret; + if (!allow_backup_parent_write(&parent)) + return -1; + if (parent.fd < 0) { + errno = save_errno; + return ret; + } + ret = do_mkdir_at(backup_dir_buf, ACCESSPERMS); + return restore_backup_dir_mode(&parent) ? ret : -1; +} + +static void backup_suffix_collision(void) +{ + rprintf(FERROR_XFER, "backup path %s is both a directory and a suffixed backup name\n", + full_fname(backup_dir_buf)); + errno = EEXIST; +} + /* Returns -1 on error, 0 on missing dir, and 1 on present dir. */ static int validate_backup_dir(void) { @@ -73,8 +206,23 @@ static int validate_backup_dir(void) return -1; } if (!S_ISDIR(st.st_mode)) { + struct backup_dir_access parent = {.fd = -1}; int flags = get_del_for_flag(st.st_mode) | DEL_FOR_BACKUP | DEL_RECURSE; - if (delete_item(backup_dir_buf, st.st_mode, flags) == 0) + const char *relative = backup_dir_buf + backup_dir_len; + const char *slash = strrchr(relative, '/'); + const char *name = slash ? slash + 1 : relative; + size_t len = strlen(name); + int ret; + + if (backup_suffix_len && len > (size_t)backup_suffix_len + && strcmp(name + len - backup_suffix_len, backup_suffix) == 0) { + backup_suffix_collision(); + return -1; + } + if (!allow_backup_parent_write(&parent)) + return -1; + ret = delete_item(backup_dir_buf, st.st_mode, flags); + if (restore_backup_dir_mode(&parent) && ret == 0) return 0; return -1; } @@ -85,10 +233,10 @@ static int validate_backup_dir(void) * backup_dir_buf. Any new directories (compared to the prior backup * path) are ensured to exist as directories, replacing anything else * that may be in the way (e.g. a symlink). */ -static BOOL copy_valid_path(const char *fname) +static BOOL copy_valid_path(const char *fname, const char *suffix) { const char *f; - const char *const parts[] = { fname, backup_suffix }; + const char *const parts[] = { fname, suffix }; int val; BOOL ret = True; stat_x sx; @@ -126,7 +274,7 @@ static BOOL copy_valid_path(const char *fname) for ( ; b; name = b + 1, b = strchr(name, '/')) { *b = '\0'; - while (do_mkdir_at(backup_dir_buf, ACCESSPERMS) < 0) { + while (mkdir_backup_dir() < 0) { if (errno == EEXIST) { val = validate_backup_dir(); if (val > 0) @@ -192,10 +340,9 @@ static BOOL copy_valid_path(const char *fname) return ret; } -/* Make a complete pathname for backup file and verify any new path elements. */ -char *get_backup_name(const char *fname) +static char *backup_name(const char *fname, const char *suffix) { - const char *const parts[] = { fname, backup_suffix }; + const char *const parts[] = { fname, suffix }; if (backup_dir) { static int initialized = 0; @@ -214,7 +361,7 @@ char *get_backup_name(const char *fname) initialized = 1; } /* copy fname into backup_dir_buf while validating the dirs. */ - if (copy_valid_path(fname)) + if (copy_valid_path(fname, suffix)) return backup_dir_buf; /* copy_valid_path() has printed an error message. */ return NULL; @@ -227,6 +374,48 @@ char *get_backup_name(const char *fname) return NULL; } +/* Make a complete pathname for a file backup and verify its parents. */ +char *get_backup_name(const char *fname) +{ + return backup_name(fname, backup_suffix); +} + +int copy_inplace_backup(const char *fname, mode_t mode) +{ + struct backup_dir_access parent = {.fd = -1}; + int ret; + + if (!allow_backup_parent_write(&parent)) + return -1; + ret = copy_file(fname, backup_dir_buf, -1, mode); + return restore_backup_dir_mode(&parent) ? ret : -1; +} + +int open_inplace_backup(void) +{ + struct backup_dir_access parent = {.fd = -1}; + const char *what = "unlink"; + int fd = -1, error; + + if (!allow_backup_parent_write(&parent)) + return -1; + if (robust_unlink(backup_dir_buf) == 0 || errno == ENOENT) { + what = "open"; + fd = do_open_at(backup_dir_buf, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600); + } + error = errno; + if (!restore_backup_dir_mode(&parent)) { + if (fd >= 0) + close(fd); + return -1; + } + if (fd < 0) { + rsyserr(FERROR_XFER, error, "%s %s", what, full_fname(backup_dir_buf)); + errno = error; + } + return fd; +} + static BOOL copy_directory_backup_attrs(const char *fname, int source_fd, const char *backup, STRUCT_STAT *original) { @@ -253,9 +442,17 @@ static BOOL copy_directory_backup_attrs(const char *fname, int source_fd, #endif #ifdef SUPPORT_XATTRS if (preserve_xattrs) { - backup_fd = backup_source_fd(backup); - if ((backup_fd < 0 && backup_metadata_hardened()) - || reconcile_backup_xattrs(fname, source_fd, backup, backup_fd) < 0) + struct backup_dir_access target = {.fd = -1}; + int xattr_ret; + + if (!allow_backup_dir_write(&target)) + goto cleanup; + backup_fd = target.fd >= 0 ? target.fd : backup_source_fd(backup); + xattr_ret = backup_fd < 0 && backup_metadata_hardened() ? -1 + : reconcile_backup_xattrs(fname, source_fd, backup, backup_fd); + if (target.fd >= 0) + backup_fd = -1; + if (!restore_backup_dir_mode(&target) || xattr_ret < 0) goto cleanup; } #endif @@ -296,9 +493,10 @@ BOOL make_directory_backup(const char *fname, STRUCT_STAT *original) } operator_path_resolve = 1; - if (!(backup = get_backup_name(fname))) + /* Directory metadata belongs to the same path as its child backups. */ + if (!(backup = backup_name(fname, ""))) goto done; - if (do_mkdir_at(backup, ACCESSPERMS) < 0 && errno != EEXIST) + if (mkdir_backup_dir() < 0 && errno != EEXIST) goto done; if (do_lstat_at(backup, &dest) < 0) goto done; @@ -361,11 +559,11 @@ static inline int link_or_rename(const char *from, const char *to, /* Hard-link, rename, or copy an item to the backup name. Returns 0 for * failure, 1 if item was moved, 2 if item was duplicated or hard linked * into backup area, or 3 if item doesn't exist or isn't a regular file. */ -static int make_backup_inner(const char *fname, BOOL prefer_rename) +static int make_backup_inner(const char *fname, BOOL prefer_rename, struct backup_dir_access *parent) { stat_x sx; struct file_struct *file; - int save_preserve_xattrs; + int save_preserve_xattrs, save_errno; char *buf; int ret = 0; @@ -414,10 +612,22 @@ static int make_backup_inner(const char *fname, BOOL prefer_rename) * linking is possible. */ if ((ret = link_or_rename(fname, buf, prefer_rename, &sx.st)) != 0) goto success; + save_errno = errno; + if (!allow_backup_parent_write(parent)) + return 0; + if (parent->fd >= 0) { + if ((ret = link_or_rename(fname, buf, prefer_rename, &sx.st)) != 0) + goto success; + } else + errno = save_errno; if (errno == EEXIST || errno == EISDIR) { STRUCT_STAT bakst; if (do_lstat_at(buf, &bakst) == 0) { int flags = get_del_for_flag(bakst.st_mode) | DEL_FOR_BACKUP | DEL_RECURSE; + if (backup_dir && backup_suffix_len && S_ISDIR(bakst.st_mode)) { + backup_suffix_collision(); + return 0; + } if (delete_item(buf, bakst.st_mode, flags) != 0) return 0; } @@ -535,6 +745,7 @@ static int make_backup_inner(const char *fname, BOOL prefer_rename) int make_backup(const char *fname, BOOL prefer_rename) { + struct backup_dir_access parent = {.fd = -1}; int ret; /* The --backup-dir is an operator-supplied path: resolve it (and the * tail/rename beneath it) with the ownership walk so a foreign-owned @@ -542,7 +753,9 @@ int make_backup(const char *fname, BOOL prefer_rename) * absolute and relative alike. --insecure-links / "insecure links =" * restores legacy following. */ operator_path_resolve = 1; - ret = make_backup_inner(fname, prefer_rename); + ret = make_backup_inner(fname, prefer_rename, &parent); + if (!restore_backup_dir_mode(&parent)) + ret = 0; operator_path_resolve = 0; return ret; } diff --git a/generator.c b/generator.c index 4823844bb..e9cf3c11a 100644 --- a/generator.c +++ b/generator.c @@ -2620,7 +2620,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, operator_path_resolve = 0; goto pretend_missing; } - if (copy_file(fname, backupptr, -1, back_file->mode) < 0) { + if (copy_inplace_backup(fname, back_file->mode) < 0) { operator_path_resolve = 0; unmake_file(back_file); back_file = NULL; @@ -2666,17 +2666,8 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, operator_path_resolve = 0; goto pretend_missing; } - if (robust_unlink(backupptr) && errno != ENOENT) { + if ((f_copy = open_inplace_backup()) < 0) { operator_path_resolve = 0; - rsyserr(FERROR_XFER, errno, "unlink %s", - full_fname(backupptr)); - unmake_file(back_file); - back_file = NULL; - goto cleanup; - } - if ((f_copy = do_open_at(backupptr, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600)) < 0) { - operator_path_resolve = 0; - rsyserr(FERROR_XFER, errno, "open %s", full_fname(backupptr)); unmake_file(back_file); back_file = NULL; goto cleanup; diff --git a/rsync.1.md b/rsync.1.md index 7160a8532..11a3bbcbd 100644 --- a/rsync.1.md +++ b/rsync.1.md @@ -1180,6 +1180,14 @@ sign) if you want the local shell to expand it. using the [`--suffix`](#opt) option (otherwise the files backed up in the specified directory will keep their original filenames). + During deletion, directory backups use the same names as the directories + holding their backed-up contents. The suffix applies to non-directory + backups. If a suffixed backup and a directory need the same path, rsync + reports the conflict without replacing the existing backup. When reusing + an owned backup subdirectory, rsync may temporarily make it writable and + restore its mode after the backup operation. This does not change the + permissions of DIR. + Note that if you specify a relative path, the backup directory will be relative to the destination directory, so you probably want to specify either an absolute path or a path that starts with "../". If an rsync diff --git a/testsuite/tests/metadata/backup-deleted-directory-attributes.py b/testsuite/tests/metadata/backup-deleted-directory-attributes.py index f25a863ea..9cfded29b 100644 --- a/testsuite/tests/metadata/backup-deleted-directory-attributes.py +++ b/testsuite/tests/metadata/backup-deleted-directory-attributes.py @@ -1,5 +1,8 @@ #!/usr/bin/env python3 +import os +import stat + from harness import TestContext, requires, run from harness.filesystem import acl_get, acl_set from harness.results import test_fail @@ -40,6 +43,23 @@ def test(context: TestContext): if 'user.backup-stale=' in dump_values(saved): test_fail('the directory backup retained a stale extended attribute') + if os.geteuid() != 0: + old.mkdir() + set_value('backup-directory', 'next value', old) + old.chmod(0o555) + saved.chmod(0o555) + try: + run_rsync('-aX', '--delete', f'--backup-dir={backup}', + f'{context.source}/', f'{dest}/') + if old.exists() or get_value('backup-directory', saved) != b'next value': + test_fail('rsync did not update the xattrs on the reused read-only directory') + if stat.S_IMODE(saved.stat().st_mode) != 0o555: + test_fail('updating the backup xattrs changed the saved mode') + finally: + for path in (old, saved): + if path.is_dir(): + path.chmod(0o755) + if __name__ == '__main__': run(test) diff --git a/testsuite/tests/transfer/backup-deleted-directories.py b/testsuite/tests/transfer/backup-deleted-directories.py index 93f6ff49d..b53721a52 100644 --- a/testsuite/tests/transfer/backup-deleted-directories.py +++ b/testsuite/tests/transfer/backup-deleted-directories.py @@ -109,8 +109,9 @@ def transfer(dst, backup, *options, status=0): # As with --group, a non-root backup must skip a group the user cannot # grant (setgid shares, BSD/macOS inherited groups) rather than fail. + groups = {os.getegid(), *os.getgroups()} if os.geteuid() == 0: - foreign = next(g for g in range(54321, 65534) if g not in os.getgroups()) + foreign = next(g for g in range(54321, 65534) if g not in groups) parent, extra = context.scratch / 'foreign-group', ['--no-super'] parent.mkdir() else: @@ -120,7 +121,7 @@ def transfer(dst, backup, *options, status=0): parent = None if parent is not None: foreign = parent.stat().st_gid - if foreign in os.getgroups(): + if foreign in groups: shutil.rmtree(parent) parent = None if parent is not None: @@ -156,6 +157,54 @@ def transfer(dst, backup, *options, status=0): if list(dst.iterdir()): test_fail('backup suffix mode changed how empty directories are deleted') + dst, backup = context.scratch / 'with-suffix', context.scratch / 'suffixed-backup' + empty, sibling = dst / 'entry', dst / 'entry.saved' + empty.mkdir(parents=True) + sibling.mkdir() + (sibling / 'data').write_bytes(b'previous contents') + empty.chmod(0o700) + sibling.chmod(0o751) + os.utime(empty, (1_501_234_567, 1_501_234_567)) + os.utime(sibling, (1_505_432_109, 1_505_432_109)) + transfer(dst, backup, '--delete-during', '--suffix=.saved') + for name, mode, mtime in (('entry', 0o700, 1_501_234_567), + ('entry.saved', 0o751, 1_505_432_109)): + path = backup / name + if not path.is_dir(): + test_fail(f'suffix: missing backup directory for {name}') + actual = path.stat() + if (stat.S_IMODE(actual.st_mode), actual.st_mtime) != (mode, mtime): + test_fail(f'suffix: directory metadata does not match {name}') + if (backup / 'entry.saved' / 'data.saved').read_bytes() != b'previous contents': + test_fail('suffix: the file did not keep its suffixed backup name') + if list(dst.iterdir()) or (backup / 'entry.saved.saved').exists(): + test_fail('suffix: incorrect directory deletion or an extra backup directory') + + for first in ('file', 'directory'): + root = context.scratch / f'suffix-{first}-first' + dst, backup = root / 'dest', root / 'backup' + dst.mkdir(parents=True) + entry, directory = dst / 'entry', dst / 'entry.saved' + saved = backup / 'entry.saved' + if first == 'file': + entry.write_bytes(b'previous file') + else: + directory.mkdir() + directory.chmod(0o751) + transfer(dst, backup, '--delete-during', '--suffix=.saved') + if first == 'file': + directory.mkdir() + child = directory / 'data' + child.write_bytes(b'new directory entry') + else: + entry.write_bytes(b'new file') + transfer(dst, backup, '--delete-during', '--suffix=.saved', status=23) + if first == 'file': + if saved.read_bytes() != b'previous file' or child.read_bytes() != b'new directory entry': + test_fail('suffix: creating a directory replaced a previous file backup') + elif stat.S_IMODE(saved.stat().st_mode) != 0o751 or entry.read_bytes() != b'new file': + test_fail('suffix: backing up a file replaced a previous directory backup') + (src / 'entry').write_bytes(b'new contents') for case, subdir in (('replace-empty', 'entry'), ('replace-nested', 'entry/empty')): root = context.scratch / case diff --git a/testsuite/tests/transfer/backup-readonly-reuse.py b/testsuite/tests/transfer/backup-readonly-reuse.py new file mode 100644 index 000000000..adf39fd77 --- /dev/null +++ b/testsuite/tests/transfer/backup-readonly-reuse.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +import os +import stat + +from harness import TestContext, requires, run +from harness.results import test_fail, test_skipped +from harness.rsync import run_rsync + + +@requires(features={'nonroot'}, transports={'pipe'}, mutates={'filesystem', 'process'}, + tags={'transfer', 'regression'}) +def test(context: TestContext): + if os.geteuid() == 0: + test_skipped('requires non-root directory permissions', capability='nonroot') + + source = context.source + destination = context.destination + backup = context.scratch / 'backup' + outer = destination / 'outer' + saved = backup / 'outer' + source.mkdir() + outer.mkdir(parents=True) + (outer / 'first').write_bytes(b'first backup') + outer.chmod(0o555) + args = ('-a', f'--backup-dir={backup}', '--delete-during') + + def check_saved_mode(): + if stat.S_IMODE(saved.stat().st_mode) != 0o555: + test_fail('rsync did not preserve the saved directory mode') + + try: + run_rsync(*args, f'{source}/', f'{destination}/') + check_saved_mode() + if outer.exists() or (saved / 'first').read_bytes() != b'first backup': + test_fail('the initial deletion was not backed up') + + (source / 'outer').mkdir() + nested = outer / 'nested' + nested.mkdir(parents=True) + (nested / 'second').write_bytes(b'second backup') + run_rsync(*args, f'{source}/', f'{destination}/') + check_saved_mode() + if nested.exists() or (saved / 'nested' / 'second').read_bytes() != b'second backup': + test_fail('the next run did not back up a deletion beneath the saved directory') + if (saved / 'first').read_bytes() != b'first backup': + test_fail('reusing the directory changed an earlier backup') + + collision = outer / 'first' + collision.mkdir() + result = run_rsync(*args, f'{source}/', f'{destination}/', capture_output=True, check=False) + if result.returncode != 23 or not collision.is_dir(): + test_fail('a failed directory backup did not preserve the original') + check_saved_mode() + if (saved / 'first').read_bytes() != b'first backup': + test_fail('the collision changed an earlier backup') + collision.rmdir() + + for option in ('--whole-file', '--no-whole-file'): + name = option[2:] + (outer / name).write_bytes(b'previous contents') + (source / 'outer' / name).write_bytes(b'new') + run_rsync(*args, '--inplace', option, f'{source}/', f'{destination}/') + check_saved_mode() + if (saved / name).read_bytes() != b'previous contents': + test_fail(f'{option}: the earlier contents were not backed up') + if (outer / name).read_bytes() != b'new': + test_fail(f'{option}: the updated contents were not transferred') + finally: + for path in (outer, saved): + if path.is_dir(): + path.chmod(stat.S_IMODE(path.stat().st_mode) | stat.S_IWUSR) + + +if __name__ == '__main__': + run(test) From 7495f2399265aa2986c5ac1903c41df4a41e88b7 Mon Sep 17 00:00:00 2001 From: Zen Dodd Date: Tue, 24 Nov 2026 14:25:12 +1100 Subject: [PATCH 08/10] backup: restore temporary access and reuse unsearchable directories --- backup.c | 400 +++++++++++++----- cleanup.c | 2 + generator.c | 37 +- main.c | 1 + receiver.c | 10 +- rsync.1.md | 7 +- rsync.c | 15 +- testsuite/fixtures/backup-mode-interrupt.c | 31 ++ .../tests/transfer/backup-mode-interrupt.py | 52 +++ .../tests/transfer/backup-readonly-reuse.py | 68 +++ .../tests/transfer/backup-readonly-xattr.py | 57 +++ util1.c | 15 +- 12 files changed, 545 insertions(+), 150 deletions(-) create mode 100644 testsuite/fixtures/backup-mode-interrupt.c create mode 100644 testsuite/tests/transfer/backup-mode-interrupt.py create mode 100644 testsuite/tests/transfer/backup-readonly-xattr.py diff --git a/backup.c b/backup.c index 5d2c8b22f..592760b96 100644 --- a/backup.c +++ b/backup.c @@ -68,24 +68,142 @@ struct backup_dir_access { mode_t mode; }; +#if defined HAVE_CHMOD && defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY +#define BACKUP_DIR_ACCESS 1 +/* One entry per path component plus a short-lived write or metadata grant. */ +static struct backup_dir_access backup_access[MAXPATHLEN / 2 + 2]; +static volatile sig_atomic_t backup_access_count; +static int backup_lock_fd = -1; +static int backup_lock_error; +#endif + +void init_backup_access(void) +{ +#ifdef BACKUP_DIR_ACCESS + FILE *lock_file; + + /* The generator and receiver inherit one anonymous file. Record locks + * on it are process-owned and disappear if either process exits. */ + if (backup_dir && !dry_run && am_root <= 0) { + if (!(lock_file = tmpfile())) + backup_lock_error = errno; + else { + backup_lock_fd = dup(fileno(lock_file)); + if (backup_lock_fd >= 0 && fcntl(backup_lock_fd, F_SETFD, FD_CLOEXEC) < 0) { + backup_lock_error = errno; + close(backup_lock_fd); + backup_lock_fd = -1; + } else if (backup_lock_fd < 0) + backup_lock_error = errno; + fclose(lock_file); + } + } +#endif +} + +static BOOL lock_backup_access(void) +{ +#ifdef BACKUP_DIR_ACCESS + if (backup_lock_fd >= 0) { + struct flock lock = {.l_type = F_WRLCK, .l_whence = SEEK_SET}; + int ret; + + do { + ret = fcntl(backup_lock_fd, F_SETLKW, &lock); + } while (ret < 0 && errno == EINTR); + if (ret < 0) { + rsyserr(FERROR_XFER, errno, "cannot lock backup directory access"); + return False; + } + } +#endif + return True; +} + +static int backup_access_mark(void) +{ +#ifdef BACKUP_DIR_ACCESS + return backup_access_count; +#else + return 0; +#endif +} + +static BOOL restore_backup_access(int mark) +{ +#ifdef BACKUP_DIR_ACCESS + int saved_errno = errno, error = 0; + + while (backup_access_count > mark) { + const struct backup_dir_access *access = &backup_access[backup_access_count - 1]; + int ret; + + do { + ret = fchmod(access->fd, access->mode); + } while (ret < 0 && errno == EINTR); + if (ret < 0 && !error) + error = errno; + backup_access_count--; + close(access->fd); + } + if (error) { + rsyserr(FERROR_XFER, error, "cannot restore backup directory mode for %s", + full_fname(backup_dir_buf)); + errno = error; + return False; + } + errno = saved_errno; +#else + (void)mark; +#endif + return True; +} + +BOOL end_backup_access(void) +{ + BOOL ok = restore_backup_access(0); +#ifdef BACKUP_DIR_ACCESS + int saved_errno = errno; + + if (backup_lock_fd >= 0) { + struct flock lock = {.l_type = F_UNLCK, .l_whence = SEEK_SET}; + if (fcntl(backup_lock_fd, F_SETLK, &lock) < 0) { + int error = errno; + rsyserr(FERROR_XFER, error, "cannot unlock backup directory access"); + errno = error; + return False; + } + } + errno = saved_errno; +#endif + return ok; +} + /* Change only an owned directory beneath the checked backup root. The fd * keeps mode restoration tied to the same directory, not to its name. */ -static BOOL allow_backup_dir_write(struct backup_dir_access *access) +#ifdef BACKUP_DIR_ACCESS +static int allow_backup_dir_access(const STRUCT_STAT *st, mode_t permission) { -#if defined HAVE_CHMOD && defined AT_FDCWD && defined O_NOFOLLOW && defined O_DIRECTORY - STRUCT_STAT st, root_st, pinned; + STRUCT_STAT root_st, pinned; char root[MAXPATHLEN]; - int root_fd, fd, save_errno; + int root_fd, fd, save_errno, mark; if (dry_run || !operator_path_resolve || !backup_dir || am_root > 0 - || !backup_dir_buf[backup_dir_len]) - return True; - if (do_lstat_at(backup_dir_buf, &st) < 0 || !S_ISDIR(st.st_mode) - || st.st_uid != MY_UID() || st.st_mode & S_IWUSR) - return True; + || !backup_dir_buf[backup_dir_len] || !S_ISDIR(st->st_mode) + || st->st_uid != MY_UID() || (st->st_mode & permission) == permission) + return 0; /* A chmod may silently clear an ungrantable setgid bit. */ - if (st.st_mode & S_ISGID && !is_in_group(st.st_gid)) - return True; + if (st->st_mode & S_ISGID && !is_in_group(st->st_gid)) + return 0; + if (backup_lock_fd < 0) { + errno = backup_lock_error ? backup_lock_error : ENOTSUP; + goto failed; + } + mark = backup_access_count; + if (mark >= (int)(sizeof backup_access / sizeof backup_access[0])) { + errno = ENAMETOOLONG; + goto failed; + } memcpy(root, backup_dir_buf, backup_dir_len); root[backup_dir_len] = '\0'; @@ -93,9 +211,9 @@ static BOOL allow_backup_dir_write(struct backup_dir_access *access) goto failed; if (do_fstat(root_fd, &root_st) < 0) fd = -1; - else if (root_st.st_dev == st.st_dev && root_st.st_ino == st.st_ino) { + else if (root_st.st_dev == st->st_dev && root_st.st_ino == st->st_ino) { close(root_fd); - return True; + return 0; } else fd = secure_relative_open_at_beneath(root_fd, backup_dir_buf + backup_dir_len, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, 0); @@ -106,16 +224,22 @@ static BOOL allow_backup_dir_write(struct backup_dir_access *access) goto failed; if (do_fstat(fd, &pinned) < 0) goto close_failed; - if (pinned.st_dev != st.st_dev || pinned.st_ino != st.st_ino - || pinned.st_mode != st.st_mode || pinned.st_uid != st.st_uid || pinned.st_gid != st.st_gid) { + if (pinned.st_dev != st->st_dev || pinned.st_ino != st->st_ino + || pinned.st_mode != st->st_mode || pinned.st_uid != st->st_uid || pinned.st_gid != st->st_gid) { errno = EINVAL; goto close_failed; } - if (do_chmod_attrs(backup_dir_buf, (st.st_mode & CHMOD_BITS) | S_IWUSR, fd, -1, NULL, False) < 0) + /* Publish before chmod so exit cleanup also sees an interrupted grant. */ + backup_access[mark].fd = fd; + backup_access[mark].mode = st->st_mode & CHMOD_BITS; + backup_access_count = mark + 1; + if (do_chmod_attrs(backup_dir_buf, (st->st_mode & CHMOD_BITS) | permission, fd, -1, NULL, False) < 0) { + save_errno = errno; + backup_access_count = mark; + errno = save_errno; goto close_failed; - access->fd = fd; - access->mode = st.st_mode & CHMOD_BITS; - return True; + } + return 1; close_failed: save_errno = errno; @@ -123,68 +247,56 @@ static BOOL allow_backup_dir_write(struct backup_dir_access *access) errno = save_errno; failed: save_errno = errno; - rsyserr(FERROR_XFER, save_errno, "cannot make backup directory %s writable", full_fname(backup_dir_buf)); + rsyserr(FERROR_XFER, save_errno, "cannot make backup directory %s %s", full_fname(backup_dir_buf), + permission == S_IXUSR ? "searchable" : "writable"); errno = save_errno; - return False; + return -1; +} +#endif + +static int allow_backup_dir_mode(mode_t permission) +{ +#ifdef BACKUP_DIR_ACCESS + STRUCT_STAT st; + + if (!dry_run && operator_path_resolve && backup_dir && am_root <= 0 + && backup_dir_buf[backup_dir_len] && do_lstat_at(backup_dir_buf, &st) == 0) + return allow_backup_dir_access(&st, permission); #else - (void)access; - return True; + (void)permission; #endif + return 0; } -static BOOL allow_backup_parent_write(struct backup_dir_access *access) +static int allow_backup_parent_write(void) { char *slash; - BOOL ok; + int ret; if (!backup_dir || !(slash = strrchr(backup_dir_buf + backup_dir_len, '/'))) - return True; + return 0; *slash = '\0'; - ok = allow_backup_dir_write(access); + ret = allow_backup_dir_mode(S_IWUSR); *slash = '/'; - return ok; -} - -static BOOL restore_backup_dir_mode(struct backup_dir_access *access) -{ -#ifdef HAVE_CHMOD - if (access->fd >= 0) { - int save_errno = errno; - int ret = do_chmod_attrs(backup_dir_buf, access->mode, access->fd, -1, NULL, False); - int error = errno; - - close(access->fd); - access->fd = -1; - if (ret < 0) { - rsyserr(FERROR_XFER, error, "cannot restore backup directory mode for %s", - full_fname(backup_dir_buf)); - errno = error; - return False; - } - errno = save_errno; - } -#else - (void)access; -#endif - return True; + return ret; } static int mkdir_backup_dir(void) { - struct backup_dir_access parent = {.fd = -1}; + int mark = backup_access_mark(); int ret = do_mkdir_at(backup_dir_buf, ACCESSPERMS); - int save_errno = errno; + int error = errno, granted; if (ret == 0 || (errno != EACCES && errno != EPERM)) return ret; - if (!allow_backup_parent_write(&parent)) + if ((granted = allow_backup_parent_write()) < 0) return -1; - if (parent.fd < 0) { - errno = save_errno; + if (!granted) { + errno = error; return ret; } ret = do_mkdir_at(backup_dir_buf, ACCESSPERMS); - return restore_backup_dir_mode(&parent) ? ret : -1; + return restore_backup_access(mark) ? ret : -1; } static void backup_suffix_collision(void) @@ -206,26 +318,29 @@ static int validate_backup_dir(void) return -1; } if (!S_ISDIR(st.st_mode)) { - struct backup_dir_access parent = {.fd = -1}; int flags = get_del_for_flag(st.st_mode) | DEL_FOR_BACKUP | DEL_RECURSE; const char *relative = backup_dir_buf + backup_dir_len; const char *slash = strrchr(relative, '/'); const char *name = slash ? slash + 1 : relative; size_t len = strlen(name); - int ret; + int ret, mark = backup_access_mark(); if (backup_suffix_len && len > (size_t)backup_suffix_len && strcmp(name + len - backup_suffix_len, backup_suffix) == 0) { backup_suffix_collision(); return -1; } - if (!allow_backup_parent_write(&parent)) + if (allow_backup_parent_write() < 0) return -1; ret = delete_item(backup_dir_buf, st.st_mode, flags); - if (restore_backup_dir_mode(&parent) && ret == 0) + if (restore_backup_access(mark) && ret == 0) return 0; return -1; } +#ifdef BACKUP_DIR_ACCESS + if (allow_backup_dir_access(&st, S_IXUSR) < 0) + return -1; +#endif return 1; } @@ -235,24 +350,35 @@ static int validate_backup_dir(void) * that may be in the way (e.g. a symlink). */ static BOOL copy_valid_path(const char *fname, const char *suffix) { - const char *f; const char *const parts[] = { fname, suffix }; int val; BOOL ret = True; + STRUCT_STAT parent; stat_x sx; char *b, *rel = backup_dir_buf + backup_dir_len, *name = rel; - for (f = fname, b = rel; *f && *f == *b; f++, b++) { - if (*b == '/') - name = b + 1; - } - if (stringjoin(rel, backup_dir_remainder, parts, sizeof parts / sizeof parts[0]) >= backup_dir_remainder) { rprintf(FERROR, "backup filename too long\n"); - *name = '\0'; return False; } + /* A searchable parent proves the whole prefix is usable. Walk from + * the root only to prepare missing or inaccessible components. */ + if ((b = strrchr(rel, '/')) == NULL) + return True; + *b = '\0'; + val = do_lstat_at(backup_dir_buf, &parent); +#ifdef BACKUP_DIR_ACCESS + if (val == 0 && S_ISDIR(parent.st_mode) + && allow_backup_dir_access(&parent, S_IXUSR) < 0) { + *b = '/'; + return False; + } +#endif + *b = '/'; + if (val == 0 && S_ISDIR(parent.st_mode)) + return True; + for ( ; ; name = b + 1) { if ((b = strchr(name, '/')) == NULL) return True; @@ -278,7 +404,7 @@ static BOOL copy_valid_path(const char *fname, const char *suffix) if (errno == EEXIST) { val = validate_backup_dir(); if (val > 0) - break; + goto next; if (val == 0) continue; } else @@ -295,7 +421,7 @@ static BOOL copy_valid_path(const char *fname, const char *suffix) else { struct file_struct *file; if (!(file = make_file(rel, NULL, NULL, 0, NO_FILTERS))) - continue; + goto next; if (!am_root && !is_in_group(sx.st.st_gid)) file->flags |= FLAG_SKIP_GROUP; #if defined SUPPORT_ACLS || defined SUPPORT_XATTRS @@ -325,6 +451,11 @@ static BOOL copy_valid_path(const char *fname, const char *suffix) unmake_file(file); } + if (allow_backup_dir_mode(S_IXUSR) < 0) { + ret = False; + goto cleanup; + } + next: *b = '/'; } @@ -374,48 +505,83 @@ static char *backup_name(const char *fname, const char *suffix) return NULL; } -/* Make a complete pathname for a file backup and verify its parents. */ +/* Produce a name without creating directories for a basis lookup. */ char *get_backup_name(const char *fname) { - return backup_name(fname, backup_suffix); + char *buf = backup_dir ? backup_dir_buf + backup_dir_len : backup_dir_buf; + size_t size = backup_dir ? backup_dir_remainder : MAXPATHLEN; + const char *const parts[] = { fname, backup_suffix }; + + if (stringjoin(buf, size, parts, sizeof parts / sizeof parts[0]) < size) + return backup_dir_buf; + errno = ENAMETOOLONG; + return NULL; } -int copy_inplace_backup(const char *fname, mode_t mode) +/* Keep search access while the caller opens an existing backup or sets its + * attributes. A read must not create or replace a backup directory. */ +BOOL begin_backup_read(void) { - struct backup_dir_access parent = {.fd = -1}; - int ret; + int save = operator_path_resolve; + char *part, *slash; + BOOL ok = False; - if (!allow_backup_parent_write(&parent)) - return -1; - ret = copy_file(fname, backup_dir_buf, -1, mode); - return restore_backup_dir_mode(&parent) ? ret : -1; +#ifndef BACKUP_DIR_ACCESS + return True; +#endif + if (!backup_dir || am_root > 0 || dry_run) + return True; + if (!lock_backup_access()) + return False; + + operator_path_resolve = 1; + for (part = backup_dir_buf + backup_dir_len; (slash = strchr(part, '/')); part = slash + 1) { + int ret; + + *slash = '\0'; + ret = allow_backup_dir_mode(S_IXUSR); + *slash = '/'; + if (ret < 0) + goto done; + } + ok = True; + done: + operator_path_resolve = save; + if (!ok) + end_backup_access(); + return ok; } -int open_inplace_backup(void) +int open_inplace_backup(const char *fname, mode_t mode) { - struct backup_dir_access parent = {.fd = -1}; - const char *what = "unlink"; - int fd = -1, error; + int save = operator_path_resolve, fd = -1; - if (!allow_backup_parent_write(&parent)) - return -1; - if (robust_unlink(backup_dir_buf) == 0 || errno == ENOENT) { - what = "open"; - fd = do_open_at(backup_dir_buf, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600); - } - error = errno; - if (!restore_backup_dir_mode(&parent)) { + operator_path_resolve = 1; + if (lock_backup_access() && backup_name(fname, backup_suffix) && allow_backup_parent_write() >= 0) + fd = open_copy_destination(backup_dir_buf, mode); + if (!end_backup_access()) { if (fd >= 0) close(fd); - return -1; - } - if (fd < 0) { - rsyserr(FERROR_XFER, error, "%s %s", what, full_fname(backup_dir_buf)); - errno = error; + fd = -1; } + operator_path_resolve = save; return fd; } +int copy_inplace_backup(const char *fname, mode_t mode) +{ + int ifd = open_copy_source(fname); + int ofd; + + if (ifd < 0) + return -1; + ofd = open_inplace_backup(fname, mode); + if (ofd >= 0) + return copy_file_from_fd(fname, ifd, backup_dir_buf, ofd, mode); + close(ifd); + return -1; +} + static BOOL copy_directory_backup_attrs(const char *fname, int source_fd, const char *backup, STRUCT_STAT *original) { @@ -442,17 +608,22 @@ static BOOL copy_directory_backup_attrs(const char *fname, int source_fd, #endif #ifdef SUPPORT_XATTRS if (preserve_xattrs) { - struct backup_dir_access target = {.fd = -1}; - int xattr_ret; + int xattr_ret, mark = backup_access_mark(); + int granted = allow_backup_dir_mode(S_IWUSR); - if (!allow_backup_dir_write(&target)) + if (granted < 0) goto cleanup; - backup_fd = target.fd >= 0 ? target.fd : backup_source_fd(backup); +#ifdef BACKUP_DIR_ACCESS + if (granted) + backup_fd = backup_access[mark].fd; + else +#endif + backup_fd = backup_source_fd(backup); xattr_ret = backup_fd < 0 && backup_metadata_hardened() ? -1 : reconcile_backup_xattrs(fname, source_fd, backup, backup_fd); - if (target.fd >= 0) + if (granted) backup_fd = -1; - if (!restore_backup_dir_mode(&target) || xattr_ret < 0) + if (!restore_backup_access(mark) || xattr_ret < 0) goto cleanup; } #endif @@ -494,7 +665,7 @@ BOOL make_directory_backup(const char *fname, STRUCT_STAT *original) operator_path_resolve = 1; /* Directory metadata belongs to the same path as its child backups. */ - if (!(backup = backup_name(fname, ""))) + if (!lock_backup_access() || !(backup = backup_name(fname, ""))) goto done; if (mkdir_backup_dir() < 0 && errno != EEXIST) goto done; @@ -511,6 +682,8 @@ BOOL make_directory_backup(const char *fname, STRUCT_STAT *original) rprintf(FINFO, "backed up %s to %s\n", fname, backup); done: + if (!end_backup_access()) + ok = False; if (!ok) rsyserr(FERROR_XFER, errno ? errno : EIO, "backup directory %s failed", full_fname(fname)); if (source_fd >= 0) @@ -559,11 +732,11 @@ static inline int link_or_rename(const char *from, const char *to, /* Hard-link, rename, or copy an item to the backup name. Returns 0 for * failure, 1 if item was moved, 2 if item was duplicated or hard linked * into backup area, or 3 if item doesn't exist or isn't a regular file. */ -static int make_backup_inner(const char *fname, BOOL prefer_rename, struct backup_dir_access *parent) +static int make_backup_inner(const char *fname, BOOL prefer_rename) { stat_x sx; struct file_struct *file; - int save_preserve_xattrs, save_errno; + int save_preserve_xattrs, save_errno, granted; char *buf; int ret = 0; @@ -572,7 +745,7 @@ static int make_backup_inner(const char *fname, BOOL prefer_rename, struct backu if (x_lstat(fname, &sx.st, NULL) < 0) return 3; - if (!(buf = get_backup_name(fname))) + if (!(buf = backup_name(fname, backup_suffix))) return 0; #ifdef SUPPORT_LINKS @@ -613,9 +786,9 @@ static int make_backup_inner(const char *fname, BOOL prefer_rename, struct backu if ((ret = link_or_rename(fname, buf, prefer_rename, &sx.st)) != 0) goto success; save_errno = errno; - if (!allow_backup_parent_write(parent)) + if ((granted = allow_backup_parent_write()) < 0) return 0; - if (parent->fd >= 0) { + if (granted) { if ((ret = link_or_rename(fname, buf, prefer_rename, &sx.st)) != 0) goto success; } else @@ -745,17 +918,16 @@ static int make_backup_inner(const char *fname, BOOL prefer_rename, struct backu int make_backup(const char *fname, BOOL prefer_rename) { - struct backup_dir_access parent = {.fd = -1}; - int ret; + int save = operator_path_resolve, ret; /* The --backup-dir is an operator-supplied path: resolve it (and the * tail/rename beneath it) with the ownership walk so a foreign-owned * symlink component is refused while the operator's own is followed -- * absolute and relative alike. --insecure-links / "insecure links =" * restores legacy following. */ operator_path_resolve = 1; - ret = make_backup_inner(fname, prefer_rename, &parent); - if (!restore_backup_dir_mode(&parent)) + ret = lock_backup_access() ? make_backup_inner(fname, prefer_rename) : 0; + if (!end_backup_access()) ret = 0; - operator_path_resolve = 0; + operator_path_resolve = save; return ret; } diff --git a/cleanup.c b/cleanup.c index 38aafb3d0..918cb1a2b 100644 --- a/cleanup.c +++ b/cleanup.c @@ -116,6 +116,8 @@ NORETURN void _exit_cleanup(int code, const char *file, int line) exit_line = line < 0 ? -line : line; } + end_backup_access(); + /* If this is the exit at the end of the run, the server side * should not attempt to output a message (see log_exit()). */ if (am_server && code == 0) diff --git a/generator.c b/generator.c index e9cf3c11a..a30377e43 100644 --- a/generator.c +++ b/generator.c @@ -2607,26 +2607,14 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, if (read_batch || whole_file) { if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) { - /* The --backup-dir (backupptr) is an operator path; this in-place - * backup bypasses make_backup(), so set operator_path_resolve here - * too -- get_backup_name() (make_path) and copy_file() then resolve - * it with the ownership walk instead of following any symlink. */ - operator_path_resolve = 1; - if (!(backupptr = get_backup_name(fname))) { - operator_path_resolve = 0; - goto cleanup; - } - if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) { - operator_path_resolve = 0; + if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) goto pretend_missing; - } if (copy_inplace_backup(fname, back_file->mode) < 0) { - operator_path_resolve = 0; unmake_file(back_file); back_file = NULL; goto cleanup; } - operator_path_resolve = 0; + backupptr = get_backup_name(fname); } goto notify_others; } @@ -2655,24 +2643,14 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, } if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) { - /* Operator --backup-dir, bypassing make_backup(): resolve get_backup_name() - * (make_path), the unlink and the create with the ownership walk. */ - operator_path_resolve = 1; - if (!(backupptr = get_backup_name(fname))) { - operator_path_resolve = 0; - goto cleanup; - } - if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) { - operator_path_resolve = 0; + if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) goto pretend_missing; - } - if ((f_copy = open_inplace_backup()) < 0) { - operator_path_resolve = 0; + if ((f_copy = open_inplace_backup(fname, 0600)) < 0) { unmake_file(back_file); back_file = NULL; goto cleanup; } - operator_path_resolve = 0; + backupptr = get_backup_name(fname); fnamecmp_type = FNAMECMP_BACKUP; } @@ -2763,7 +2741,10 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, * try_dests_reg). The static --backup-dir escape is already closed; a * parent-symlink flipped in after the confined create races only these * chmod/chown/times -- a documented residual. */ - set_file_attrs(backupptr, back_file, NULL, NULL, 0); + if (begin_backup_read()) { + set_file_attrs(backupptr, back_file, NULL, NULL, 0); + end_backup_access(); + } preserve_xattrs = save_preserve_xattrs; if (INFO_GTE(BACKUP, 1)) { rprintf(FINFO, "backed up %s to %s\n", diff --git a/main.c b/main.c index 52c6d9791..f4851fcba 100644 --- a/main.c +++ b/main.c @@ -1056,6 +1056,7 @@ static int do_recv(int f_in, int f_out, char *local_name) if (backup_dir_len > 1) backup_dir_buf[backup_dir_len-1] = '/'; } + init_backup_access(); if (tmpdir) { STRUCT_STAT st; diff --git a/receiver.c b/receiver.c index 0c1cc07f3..7599964a5 100644 --- a/receiver.c +++ b/receiver.c @@ -1095,7 +1095,11 @@ int recv_files(int f_in, int f_out, char *local_name) * trusted absolute fnamecmp (e.g. an absolute --partial-dir basis). */ { int bdfd; - if (fnamecmp_type == FNAMECMP_PARTIAL_DIR + BOOL backup_basis = fnamecmp_type == FNAMECMP_BACKUP && inplace && make_backups > 0; + + if (backup_basis && !begin_backup_read()) + fd1 = -1; + else if (fnamecmp_type == FNAMECMP_PARTIAL_DIR && fnamecmp && *fnamecmp != '/') { /* The relative partial path contains peer-derived directory * components. It is not an operator-trusted path as a whole. */ @@ -1120,6 +1124,10 @@ int recv_files(int f_in, int f_out, char *local_name) fd1 = secure_basis_open(basedir, fnamecmp, O_RDONLY, 0); operator_path_resolve = 0; } + if (backup_basis && !end_backup_access() && fd1 >= 0) { + close(fd1); + fd1 = -1; + } } if (fnamecmp_type == FNAMECMP_PARTIAL_DIR && fd1 == -1) { /* The sender may claim a partial basis even when the generator's diff --git a/rsync.1.md b/rsync.1.md index 8e69654b0..062f5be7c 100644 --- a/rsync.1.md +++ b/rsync.1.md @@ -1184,9 +1184,10 @@ sign) if you want the local shell to expand it. holding their backed-up contents. The suffix applies to non-directory backups. If a suffixed backup and a directory need the same path, rsync reports the conflict without replacing the existing backup. When reusing - an owned backup subdirectory, rsync may temporarily make it writable and - restore its mode after the backup operation. This does not change the - permissions of DIR. + an owned backup subdirectory, rsync may temporarily grant itself search or + write access and restore the directory's mode after the backup operation. + This does not change the permissions of DIR. An uncatchable termination or + system failure can leave the temporary access in place. Note that if you specify a relative path, the backup directory will be relative to the destination directory, so you probably want to specify diff --git a/rsync.c b/rsync.c index 1ed460cec..89eca9d2d 100644 --- a/rsync.c +++ b/rsync.c @@ -30,6 +30,7 @@ extern int dry_run; extern int preserve_acls; extern int preserve_xattrs; +extern char backup_dir_buf[MAXPATHLEN]; extern int preserve_perms; extern int preserve_executability; extern int preserve_mtimes; @@ -915,6 +916,7 @@ int finish_transfer(const char *fname, const char *fnametmp, int overwriting_basis) { int ret; + BOOL backup_basis = False; const char *temp_copy_name = partialptr && *partialptr != '/' ? partialptr : NULL; if (inplace) { @@ -928,8 +930,9 @@ int finish_transfer(const char *fname, const char *fnametmp, int ok = make_backup(fname, False); if (!ok) exit_cleanup(RERR_FILEIO); - if (ok == 1 && fnamecmp == fname) + if (ok == 1 && fnamecmp == fname) { fnamecmp = get_backup_name(fname); + } } /* Change permissions before putting the file into place. An absolute @@ -937,10 +940,15 @@ int finish_transfer(const char *fname, const char *fnametmp, * dirfd, so resolve its metadata through the ownership walk (op_pin); a * flipped temp-dir parent then can't redirect the chmod/chown/times/etc. * (in-tree temps keep their held dirfd, so op_pin stays off there). */ + backup_basis = preserve_xattrs && fnamecmp == backup_dir_buf; + if (backup_basis && !begin_backup_read()) + return 0; operator_path_resolve = 1; set_file_attrs(fnametmp, file, NULL, fnamecmp, ok_to_set_time ? ATTRS_ACCURATE_TIME : ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME | ATTRS_SKIP_CRTIME); operator_path_resolve = 0; + if (backup_basis && !end_backup_access()) + return 0; /* move tmp file over real file */ if (DEBUG_GTE(RECV, 1)) @@ -964,8 +972,13 @@ int finish_transfer(const char *fname, const char *fnametmp, fnametmp = temp_copy_name ? temp_copy_name : fname; do_set_file_attrs: + backup_basis = preserve_xattrs && fnamecmp == backup_dir_buf; + if (backup_basis && !begin_backup_read()) + return 0; set_file_attrs(fnametmp, file, NULL, fnamecmp, ok_to_set_time ? ATTRS_ACCURATE_TIME : ATTRS_SKIP_MTIME | ATTRS_SKIP_ATIME | ATTRS_SKIP_CRTIME); + if (backup_basis && !end_backup_access()) + return 0; if (temp_copy_name) { if (do_rename_at(fnametmp, fname) < 0) { diff --git a/testsuite/fixtures/backup-mode-interrupt.c b/testsuite/fixtures/backup-mode-interrupt.c new file mode 100644 index 000000000..e8ac74998 --- /dev/null +++ b/testsuite/fixtures/backup-mode-interrupt.c @@ -0,0 +1,31 @@ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include + +int fchmod(int fd, mode_t mode) +{ + static int (*real_fchmod)(int, mode_t); + const char *path = getenv("RSYNC_TEST_BACKUP_DIR"); + struct stat before, target; + int ret; + + if (!real_fchmod) + real_fchmod = dlsym(RTLD_NEXT, "fchmod"); + if (!real_fchmod) { + errno = ENOSYS; + return -1; + } + ret = real_fchmod(fd, mode); + if (ret == 0 && path && (mode & S_IWUSR) + && fstat(fd, &before) == 0 && stat(path, &target) == 0 + && before.st_dev == target.st_dev && before.st_ino == target.st_ino) { + static const char marker[] = "test: backup directory made writable\n"; + (void)write(STDERR_FILENO, marker, sizeof marker - 1); + raise(SIGUSR1); + } + return ret; +} diff --git a/testsuite/tests/transfer/backup-mode-interrupt.py b/testsuite/tests/transfer/backup-mode-interrupt.py new file mode 100644 index 000000000..8719de16f --- /dev/null +++ b/testsuite/tests/transfer/backup-mode-interrupt.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 + +import os +import stat +import subprocess + +from harness import TestContext, requires, run +from harness.results import test_fail, test_skipped +from harness.rsync import rsync_argv, under_valgrind + + +@requires(features={'linux_interpose', 'nonroot'}, transports={'pipe'}, + mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) +def test(context: TestContext): + if under_valgrind(): + test_skipped('requires direct fchmod interposition', capability='linux_interpose') + + fixture = context.repository / 'testsuite/fixtures/backup-mode-interrupt.c' + library = context.scratch / 'backup-mode-interrupt.so' + build = subprocess.run(['cc', '-shared', '-fPIC', '-o', str(library), str(fixture), '-ldl'], + capture_output=True, text=True, timeout=30) + if build.returncode: + test_fail(f'cannot build permission interruption hook: {build.stderr}') + + source = context.source / 'outer' + destination = context.destination / 'outer' + backup = context.scratch / 'backup' + saved = backup / 'outer' + for path in (source, destination, saved): + path.mkdir(parents=True) + (source / 'file').write_bytes(b'replacement data') + (destination / 'file').write_bytes(b'original') + saved.chmod(0o555) + env = {**os.environ, 'LD_PRELOAD': str(library), 'RSYNC_TEST_BACKUP_DIR': str(saved)} + try: + result = subprocess.run( + rsync_argv('-a', '--inplace', '--whole-file', f'--backup-dir={backup}', + f'{context.source}/', f'{context.destination}/'), + env=env, capture_output=True, text=True, timeout=20, + ) + if result.returncode == 0 or 'test: backup directory made writable' not in result.stderr: + test_fail(f'rsync did not take the interrupted permission path:\n{result.stderr}') + if stat.S_IMODE(saved.stat().st_mode) != 0o555: + test_fail('handled shutdown left the backup directory writable') + if (destination / 'file').read_bytes() != b'original': + test_fail('the receiver updated the original before backing it up') + finally: + saved.chmod(0o700) + + +if __name__ == '__main__': + run(test) diff --git a/testsuite/tests/transfer/backup-readonly-reuse.py b/testsuite/tests/transfer/backup-readonly-reuse.py index adf39fd77..7b48305a7 100644 --- a/testsuite/tests/transfer/backup-readonly-reuse.py +++ b/testsuite/tests/transfer/backup-readonly-reuse.py @@ -8,6 +8,72 @@ from harness.rsync import run_rsync +def check_search_access(context): + source = context.source / 'search' + destination = context.destination / 'search' + backup = context.scratch / 'search-backup' + outer = destination / 'outer' + nested = outer / 'nested' + saved = backup / 'outer' + saved_nested = saved / 'nested' + source.mkdir() + outer.mkdir(parents=True) + outer.chmod(0o400) + args = ('-a', f'--backup-dir={backup}', '--delete-during') + + def check_backups(name, data): + if stat.S_IMODE(saved.stat().st_mode) != 0o400: + test_fail('rsync did not restore the saved outer directory mode') + saved.chmod(0o500) + try: + if stat.S_IMODE(saved_nested.stat().st_mode) != 0o400: + test_fail('rsync did not restore the saved nested directory mode') + saved_nested.chmod(0o500) + try: + if (saved_nested / name).read_bytes() != data: + test_fail(f'wrong backup contents for {name}') + finally: + saved_nested.chmod(0o400) + finally: + saved.chmod(0o400) + + try: + run_rsync(*args, f'{source}/', f'{destination}/') + if outer.exists() or stat.S_IMODE(saved.stat().st_mode) != 0o400: + test_fail('rsync did not back up the unsearchable empty directory') + + nested.mkdir(parents=True) + nested.chmod(0o400) + (source / 'outer').mkdir() + run_rsync(*args, f'{source}/', f'{destination}/') + if nested.exists(): + test_fail('rsync did not back up a directory beneath the saved one') + + (source / 'outer' / 'nested').mkdir() + nested.mkdir() + (nested / 'removed').write_bytes(b'deleted content') + run_rsync(*args, f'{source}/', f'{destination}/') + check_backups('removed', b'deleted content') + if (nested / 'removed').exists(): + test_fail('rsync did not delete the backed-up file') + + old = b'a' * 700 + b'b' * 700 + b'c' * 700 + new = b'b' * 700 + b'd' * 700 + b'a' * 700 + b'!' + for option in ('--whole-file', '--no-whole-file'): + name = option[2:] + (nested / name).write_bytes(old) + (source / 'outer' / 'nested' / name).write_bytes(new) + run_rsync(*args, '--inplace', option, f'{source}/', f'{destination}/') + check_backups(name, old) + if (nested / name).read_bytes() != new: + test_fail(f'{option}: rsync did not install the new contents') + check_backups('removed', b'deleted content') + finally: + for path in (outer, nested, saved, saved_nested): + if path.is_dir(): + path.chmod(0o700) + + @requires(features={'nonroot'}, transports={'pipe'}, mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) def test(context: TestContext): @@ -71,6 +137,8 @@ def check_saved_mode(): if path.is_dir(): path.chmod(stat.S_IMODE(path.stat().st_mode) | stat.S_IWUSR) + check_search_access(context) + if __name__ == '__main__': run(test) diff --git a/testsuite/tests/transfer/backup-readonly-xattr.py b/testsuite/tests/transfer/backup-readonly-xattr.py new file mode 100644 index 000000000..3c0f12e94 --- /dev/null +++ b/testsuite/tests/transfer/backup-readonly-xattr.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python3 + +import os +import stat + +from harness import TestContext, requires, run +from harness.results import test_fail, test_skipped +from harness.rsync import run_rsync +from harness.xattrs import get_value, is_supported, set_value + + +@requires(features={'backup_metadata', 'nonroot'}, transports={'pipe'}, + mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) +def test(context: TestContext): + if os.geteuid() == 0: + test_skipped('requires non-root directory permissions', capability='nonroot') + if not is_supported(): + test_skipped('xattrs are unavailable', capability='backup_metadata') + + source = context.source / 'outer' / 'nested' + destination = context.destination / 'outer' / 'nested' + backup = context.scratch / 'backup' + saved = backup / 'outer' / 'nested' + for directory in (source, destination, saved): + directory.mkdir(parents=True) + old = destination / 'file' + new = source / 'file' + old.write_bytes(b'previous data') + new.write_bytes(b'updated data') + value = 'same large xattr value ' * 16 + set_value('backup-test', value, old, new) + saved.chmod(0o400) + args = ('-aX', f'--backup-dir={backup}', f'{context.source}/', f'{context.destination}/') + + try: + for options in (('--inplace', '--no-whole-file'), ('--no-inplace',)): + run_rsync(*args[:2], *options, *args[2:]) + if old.read_bytes() != new.read_bytes(): + test_fail(f'{options}: the updated file was not installed') + if get_value('backup-test', old) != value.encode(): + test_fail(f'{options}: the transferred xattr was lost') + if stat.S_IMODE(saved.stat().st_mode) != 0o400: + test_fail(f'{options}: the saved directory mode changed') + saved.chmod(0o500) + try: + if get_value('backup-test', saved / 'file') != value.encode(): + test_fail(f'{options}: the backup xattr was lost') + finally: + saved.chmod(0o400) + new.write_bytes(new.read_bytes() + b'!') + finally: + if saved.is_dir(): + saved.chmod(0o700) + + +if __name__ == '__main__': + run(test) diff --git a/util1.c b/util1.c index 9e30145b7..dd094b190 100644 --- a/util1.c +++ b/util1.c @@ -344,7 +344,7 @@ static int safe_read(int desc, char *ptr, size_t len) } /* Remove existing file @dest and reopen, creating a new file with @mode */ -static int unlink_and_reopen(const char *dest, mode_t mode) +int open_copy_destination(const char *dest, mode_t mode) { int ofd; @@ -388,7 +388,7 @@ static int unlink_and_reopen(const char *dest, mode_t mode) * * This is used in conjunction with the --temp-dir, --backup, and * --copy-dest options. */ -int copy_file(const char *source, const char *dest, int tmpfilefd, mode_t mode) +int open_copy_source(const char *source) { int ifd; @@ -434,6 +434,15 @@ int copy_file(const char *source, const char *dest, int tmpfilefd, mode_t mode) return -1; } + return ifd; +} + +int copy_file(const char *source, const char *dest, int tmpfilefd, mode_t mode) +{ + int ifd = open_copy_source(source); + + if (ifd < 0) + return -1; return copy_file_from_fd(source, ifd, dest, tmpfilefd, mode); } @@ -448,7 +457,7 @@ int copy_file_from_fd(const char *source, int ifd, const char *dest, int tmpfile if (tmpfilefd >= 0) { ofd = tmpfilefd; } else { - ofd = unlink_and_reopen(dest, mode); + ofd = open_copy_destination(dest, mode); if (ofd < 0) { int save_errno = errno; close(ifd); From 920c14af2951def066fe0ee1623b56d31ddecc39 Mon Sep 17 00:00:00 2001 From: Zen Dodd Date: Tue, 24 Nov 2026 17:03:45 +1100 Subject: [PATCH 09/10] backup: preserve deleted directories and reject incomplete backups --- NEWS.md | 3 + backup.c | 99 +++++++++++++---- clientserver.c | 3 + delete.c | 14 +++ generator.c | 62 ++++------- main.c | 2 +- receiver.c | 3 + rsync.1.md | 2 + testsuite/fixtures/backup-delta-failures.c | 92 ++++++++++++++++ testsuite/fixtures/backup-delta-size-change.c | 52 +++++++++ testsuite/fixtures/backup-lock-unavailable.c | 9 ++ .../daemon/daemon-chroot-backup-access.py | 100 ++++++++++++++++++ .../tests/path/operator-path-backup-dir.py | 2 +- .../tests/transfer/backup-delta-basis.py | 35 ++++++ .../tests/transfer/backup-delta-failures.py | 65 ++++++++++++ .../transfer/backup-delta-size-change.py | 59 +++++++++++ .../tests/transfer/backup-lock-unavailable.py | 55 ++++++++++ .../tests/transfer/backup-mode-interrupt.py | 2 + .../tests/transfer/backup-readonly-xattr.py | 4 +- util1.c | 59 ++++++++--- xattrs.c | 24 ++++- 21 files changed, 662 insertions(+), 84 deletions(-) create mode 100644 testsuite/fixtures/backup-delta-failures.c create mode 100644 testsuite/fixtures/backup-delta-size-change.c create mode 100644 testsuite/fixtures/backup-lock-unavailable.c create mode 100644 testsuite/tests/daemon/daemon-chroot-backup-access.py create mode 100644 testsuite/tests/transfer/backup-delta-basis.py create mode 100644 testsuite/tests/transfer/backup-delta-failures.py create mode 100644 testsuite/tests/transfer/backup-delta-size-change.py create mode 100644 testsuite/tests/transfer/backup-lock-unavailable.py diff --git a/NEWS.md b/NEWS.md index 3466a79b3..d01174fd1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -43,6 +43,9 @@ - Preserve directories and their requested attributes in `--backup-dir` when removing them during a deletion pass. Leave the original directory in place if its backup fails. +- Treat xattr copy errors as file-copy failures. Refuse an in-place delta + update before changing its destination when copying the backup fails to + write, copy xattrs or close. - Send keepalives during file-list checksumming on multiplexed streams. Client uploads using protocols below 30 cannot send these keepalives. diff --git a/backup.c b/backup.c index 592760b96..eec4b5a4a 100644 --- a/backup.c +++ b/backup.c @@ -77,27 +77,30 @@ static int backup_lock_fd = -1; static int backup_lock_error; #endif -void init_backup_access(void) +void init_backup_access(BOOL before_chroot) { #ifdef BACKUP_DIR_ACCESS FILE *lock_file; /* The generator and receiver inherit one anonymous file. Record locks * on it are process-owned and disappear if either process exits. */ - if (backup_dir && !dry_run && am_root <= 0) { - if (!(lock_file = tmpfile())) + if (backup_lock_fd >= 0 || (!before_chroot && (!backup_dir || dry_run || am_root > 0))) + return; + backup_lock_error = 0; + if (!(lock_file = tmpfile())) + backup_lock_error = errno; + else { + backup_lock_fd = dup(fileno(lock_file)); + if (backup_lock_fd >= 0 && fcntl(backup_lock_fd, F_SETFD, FD_CLOEXEC) < 0) { backup_lock_error = errno; - else { - backup_lock_fd = dup(fileno(lock_file)); - if (backup_lock_fd >= 0 && fcntl(backup_lock_fd, F_SETFD, FD_CLOEXEC) < 0) { - backup_lock_error = errno; - close(backup_lock_fd); - backup_lock_fd = -1; - } else if (backup_lock_fd < 0) - backup_lock_error = errno; - fclose(lock_file); - } + close(backup_lock_fd); + backup_lock_fd = -1; + } else if (backup_lock_fd < 0) + backup_lock_error = errno; + fclose(lock_file); } +#else + (void)before_chroot; #endif } @@ -214,9 +217,15 @@ static int allow_backup_dir_access(const STRUCT_STAT *st, mode_t permission) else if (root_st.st_dev == st->st_dev && root_st.st_ino == st->st_ino) { close(root_fd); return 0; - } else + } else { + int save = operator_path_resolve; + + /* The verified root fd is the boundary for this relative walk. */ + operator_path_resolve = 0; fd = secure_relative_open_at_beneath(root_fd, backup_dir_buf + backup_dir_len, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC, 0); + operator_path_resolve = save; + } save_errno = errno; close(root_fd); errno = save_errno; @@ -518,6 +527,47 @@ char *get_backup_name(const char *fname) return NULL; } +/* Open the selected backup under the operator path policy. */ +int open_backup_basis(const char *name) +{ + int save = operator_path_resolve, fd, error; + + if (!backup_dir || name != backup_dir_buf) { + errno = EINVAL; + return -1; + } + operator_path_resolve = 1; + fd = do_open_at(name, O_RDONLY, 0); + error = errno; + operator_path_resolve = save; + if (fd >= 0 && fcntl(fd, F_SETFD, FD_CLOEXEC) < 0) { + error = errno; + close(fd); + fd = -1; + } + errno = error; + return fd; +} + +/* Some targets need pathname access for symlink or unreadable-leaf xattrs. + * Check the parent under the active policy before retaining that legacy read. */ +BOOL backup_basis_path_fallback(const char *name, int open_error) +{ + STRUCT_STAT st; + int save = operator_path_resolve, ret, error; + + if (!backup_dir || name != backup_dir_buf) + return False; + operator_path_resolve = 1; + ret = do_lstat_at(name, &st); + error = errno; + operator_path_resolve = save; + if (ret == 0 && (S_ISLNK(st.st_mode) || open_error == EACCES || open_error == EPERM)) + return True; + errno = ret < 0 ? error : open_error; + return False; +} + /* Keep search access while the caller opens an existing backup or sets its * attributes. A read must not create or replace a backup directory. */ BOOL begin_backup_read(void) @@ -552,7 +602,7 @@ BOOL begin_backup_read(void) return ok; } -int open_inplace_backup(const char *fname, mode_t mode) +static int open_inplace_backup(const char *fname, mode_t mode) { int save = operator_path_resolve, fd = -1; @@ -568,16 +618,27 @@ int open_inplace_backup(const char *fname, mode_t mode) return fd; } -int copy_inplace_backup(const char *fname, mode_t mode) +int copy_inplace_backup(const char *fname, int source_fd, mode_t mode, OFF_T max_len) { - int ifd = open_copy_source(fname); + /* A delta backup must use the inode later used for checksums. */ + int ifd = source_fd >= 0 ? dup(source_fd) : open_copy_source(fname); int ofd; - if (ifd < 0) + if (ifd < 0) { + if (source_fd >= 0) + rsyserr(FERROR_XFER, errno, "cannot duplicate backup source %s", full_fname(fname)); return -1; + } + if (source_fd >= 0 && lseek(ifd, 0, SEEK_SET) < 0) { + int error = errno; + rsyserr(FERROR_XFER, error, "cannot rewind backup source %s", full_fname(fname)); + close(ifd); + errno = error; + return -1; + } ofd = open_inplace_backup(fname, mode); if (ofd >= 0) - return copy_file_from_fd(fname, ifd, backup_dir_buf, ofd, mode); + return copy_file_from_fd(fname, ifd, backup_dir_buf, ofd, mode, max_len); close(ifd); return -1; } diff --git a/clientserver.c b/clientserver.c index 7b06e5c14..ceb45d4c1 100644 --- a/clientserver.c +++ b/clientserver.c @@ -1081,6 +1081,8 @@ static int rsync_module(int f_in, int f_out, int i, const char *addr, const char /* Save gcov counters before chroot makes the build tree unreachable. * Work after chroot cannot be recorded in those files. */ gcov_flush(); + if (!read_only) + init_backup_access(True); if (chroot(module_chdir)) { rsyserr(FLOG, errno, "chroot(\"%s\") failed", module_chdir); io_printf(f_out, "@ERROR: chroot failed\n"); @@ -1524,6 +1526,7 @@ int start_daemon(int f_in, int f_out) if (*p) { log_init(0); /* Make use we've initialized syslog before chrooting. */ tzset(); + init_backup_access(True); if (chroot(p) < 0) { rsyserr(FLOG, errno, "daemon chroot(\"%s\") failed", p); return -1; diff --git a/delete.c b/delete.c index bbed672de..024b5fd6f 100644 --- a/delete.c +++ b/delete.c @@ -289,6 +289,20 @@ static enum delret delete_item_with_stat(char *fbuf, uint16 mode, uint16 flags, if (make_backups > 0 && !(flags & DEL_FOR_BACKUP) && (backup_dir || !is_backup_file(fbuf))) { what = "make_backup"; ok = make_backup(fbuf, True); + if (!ok) { + int error = errno; + STRUCT_STAT current; + + /* ENOENT can name the backup path rather than the original. */ + if (error == ENOENT && do_lstat_at(fbuf, ¤t) < 0 && errno == ENOENT) { + ret = DR_SUCCESS; + goto check_ret; + } + rsyserr(FERROR_XFER, error ? error : EIO, + "delete_file: make_backup(%s) failed", fbuf); + ret = DR_FAILURE; + goto check_ret; + } if (ok == 2) { what = "unlink"; ok = del_unlink(fbuf) == 0; diff --git a/generator.c b/generator.c index a30377e43..f002185e9 100644 --- a/generator.c +++ b/generator.c @@ -845,7 +845,7 @@ static void sum_sizes_sqroot(struct sum_struct *sum, int64 len) * * Generate approximately one checksum every block_len bytes. */ -static int generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy) +static int generate_and_send_sums(int fd, OFF_T len, int f_out) { int32 i; struct map_struct *mapbuf; @@ -857,7 +857,7 @@ static int generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy) return -1; write_sum_head(f_out, &sum); - if (append_mode > 0 && f_copy < 0) + if (append_mode > 0) return 0; if (len > 0) @@ -874,12 +874,6 @@ static int generate_and_send_sums(int fd, OFF_T len, int f_out, int f_copy) len -= n1; offset += n1; - if (f_copy >= 0) { - full_write(f_copy, map, n1); - if (append_mode > 0) - continue; - } - sum1 = get_checksum1(map, n1); get_checksum2(map, n1, sum2); @@ -1040,7 +1034,7 @@ static int copy_altdest_file(const char *src, const char *dest, struct file_stru copy_to = buf; } cleanup_set(copy_to, NULL, NULL, -1, -1); - ok = fd_r >= 0 ? copy_file_from_fd(src, fd_r, copy_to, fd_w, file->mode) + ok = fd_r >= 0 ? copy_file_from_fd(src, fd_r, copy_to, fd_w, file->mode, -1) : copy_file(src, copy_to, fd_w, file->mode); if (ok < 0) { if (INFO_GTE(COPY, 1)) { @@ -1882,7 +1876,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, static int fresh_link_fallback_flist = -1; #endif struct file_struct *fuzzy_file = NULL; - int fd = -1, f_copy = -1; + int fd = -1; stat_x sx = {0}, real_sx = {0}; STRUCT_STAT partial_st; struct file_struct *back_file = NULL; @@ -2609,7 +2603,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) { if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) goto pretend_missing; - if (copy_inplace_backup(fname, back_file->mode) < 0) { + if (copy_inplace_backup(fname, -1, back_file->mode, -1) < 0) { unmake_file(back_file); back_file = NULL; goto cleanup; @@ -2645,7 +2639,14 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, if (inplace && make_backups > 0 && fnamecmp_type == FNAMECMP_FNAME) { if (!(back_file = make_file(fname, NULL, NULL, 0, NO_FILTERS))) goto pretend_missing; - if ((f_copy = open_inplace_backup(fname, 0600)) < 0) { + if (copy_inplace_backup(fname, fd, back_file->mode, sx.st.st_size) < 0) { + unmake_file(back_file); + back_file = NULL; + goto cleanup; + } + /* dup() shares the file offset; map_file() starts reading at zero. */ + if (do_lseek(fd, 0, SEEK_SET) != 0) { + rsyserr(FERROR_XFER, errno, "cannot rewind delta basis %s", full_fname(fname)); unmake_file(back_file); back_file = NULL; goto cleanup; @@ -2700,7 +2701,7 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, else if (sx.st.st_size <= 0) { write_sum_head(f_out, NULL); } else { - if (generate_and_send_sums(fd, sx.st.st_size, f_out, f_copy) < 0) { + if (generate_and_send_sums(fd, sx.st.st_size, f_out) < 0) { rprintf(FWARNING, "WARNING: file is too large for checksum sending: %s\n", fnamecmp); @@ -2712,40 +2713,15 @@ static void recv_generator(char *fname, struct file_struct *file, int ndx, if (fd >= 0) close(fd); if (back_file) { - int save_preserve_xattrs = preserve_xattrs; -#ifdef SUPPORT_XATTRS - /* The delta-backup path wrote backupptr via the held f_copy, so - * copy its xattrs through that fd here. The whole-file/inplace - * path (f_copy < 0) backed it up via copy_file(), which already - * copied the xattrs through its own held fd -- don't repeat it - * with a path-based set a parent-symlink race could redirect. */ - if (preserve_xattrs && f_copy >= 0) { - /* Read fname's xattrs through a confined fd so the copy onto the - * held backup fd can't be fed an out-of-module source by a raced - * parent symlink; a hardened race skips rather than path-reads. */ - int bfd = backup_source_fd(fname); - if (!backup_metadata_hardened() || bfd >= 0) - copy_xattrs(fname, bfd, backupptr, f_copy); - if (bfd >= 0) - close(bfd); - preserve_xattrs = 0; - } -#endif - if (f_copy >= 0) - close(f_copy); - /* backupptr's data/xattrs were written safely (confined create under - * operator_path_resolve, held-fd xattr copy above). This metadata set - * re-resolves backupptr by path and is NOT wrapped in operator mode: - * set_file_attrs() also drives the path-based xattr set whose held-fd - * race-fix operator mode would defeat (cf. the copy-dest note in - * try_dests_reg). The static --backup-dir escape is already closed; a - * parent-symlink flipped in after the confined create races only these - * chmod/chown/times -- a documented residual. */ + int save_resolve = operator_path_resolve; + /* The backup data and xattrs were written through held descriptors. + * Pin the backup inode before applying its remaining attributes. */ if (begin_backup_read()) { + operator_path_resolve = 1; set_file_attrs(backupptr, back_file, NULL, NULL, 0); + operator_path_resolve = save_resolve; end_backup_access(); } - preserve_xattrs = save_preserve_xattrs; if (INFO_GTE(BACKUP, 1)) { rprintf(FINFO, "backed up %s to %s\n", fname, backupptr); diff --git a/main.c b/main.c index f4851fcba..96006ffb5 100644 --- a/main.c +++ b/main.c @@ -1056,7 +1056,7 @@ static int do_recv(int f_in, int f_out, char *local_name) if (backup_dir_len > 1) backup_dir_buf[backup_dir_len-1] = '/'; } - init_backup_access(); + init_backup_access(False); if (tmpdir) { STRUCT_STAT st; diff --git a/receiver.c b/receiver.c index 7599964a5..5db2f010d 100644 --- a/receiver.c +++ b/receiver.c @@ -75,6 +75,7 @@ extern struct name_num_item *xfer_sum_nni; extern int xfer_sum_len; extern int use_secure_symlinks; extern int operator_path_resolve; +extern char *backup_dir; static struct bitbag *delayed_bits = NULL; static int phase = 0, redoing = 0; @@ -1099,6 +1100,8 @@ int recv_files(int f_in, int f_out, char *local_name) if (backup_basis && !begin_backup_read()) fd1 = -1; + else if (backup_basis && backup_dir) + fd1 = open_backup_basis(fnamecmp); else if (fnamecmp_type == FNAMECMP_PARTIAL_DIR && fnamecmp && *fnamecmp != '/') { /* The relative partial path contains peer-derived directory diff --git a/rsync.1.md b/rsync.1.md index 062f5be7c..ca6bb2a83 100644 --- a/rsync.1.md +++ b/rsync.1.md @@ -1188,6 +1188,8 @@ sign) if you want the local shell to expand it. write access and restore the directory's mode after the backup operation. This does not change the permissions of DIR. An uncatchable termination or system failure can leave the temporary access in place. + A failed file-backup copy can leave an incomplete file at its backup name; + a failed transfer does not establish a complete snapshot. Note that if you specify a relative path, the backup directory will be relative to the destination directory, so you probably want to specify diff --git a/testsuite/fixtures/backup-delta-failures.c b/testsuite/fixtures/backup-delta-failures.c new file mode 100644 index 000000000..c22795e59 --- /dev/null +++ b/testsuite/fixtures/backup-delta-failures.c @@ -0,0 +1,92 @@ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#include + +static int backup_fd(int fd) +{ + const char *path = getenv("RSYNC_TEST_BACKUP_FILE"); + struct stat open_file, backup; + + return path && fstat(fd, &open_file) == 0 && stat(path, &backup) == 0 + && open_file.st_dev == backup.st_dev && open_file.st_ino == backup.st_ino; +} + +static void mark_failure(void) +{ + const char *marker = getenv("RSYNC_TEST_BACKUP_MARKER"); + int mark = marker ? open(marker, O_WRONLY | O_CREAT | O_EXCL, 0600) : -1; + if (mark >= 0) + close(mark); +} + +ssize_t write(int fd, const void *buf, size_t count) +{ + static ssize_t (*real_write)(int, const void *, size_t); + static int injected; + const char *failure = getenv("RSYNC_TEST_BACKUP_FAILURE"); + + if (!real_write) + real_write = dlsym(RTLD_NEXT, "write"); + if (!real_write) { + errno = EIO; + return -1; + } + if (!injected && failure && strcmp(failure, "write") == 0 && backup_fd(fd)) { + injected = 1; + mark_failure(); + errno = ENOSPC; + return -1; + } + return real_write(fd, buf, count); +} + +int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) +{ + static int (*real_fsetxattr)(int, const char *, const void *, size_t, int); + static int injected; + const char *failure = getenv("RSYNC_TEST_BACKUP_FAILURE"); + + if (!real_fsetxattr) + real_fsetxattr = dlsym(RTLD_NEXT, "fsetxattr"); + if (!real_fsetxattr) { + errno = EIO; + return -1; + } + if (!injected && failure && strcmp(failure, "xattr") == 0 && backup_fd(fd)) { + injected = 1; + mark_failure(); + errno = ENOSPC; + return -1; + } + return real_fsetxattr(fd, name, value, size, flags); +} + +int close(int fd) +{ + static int (*real_close)(int); + static int injected; + const char *failure = getenv("RSYNC_TEST_BACKUP_FAILURE"); + int ret; + + if (!real_close) + real_close = dlsym(RTLD_NEXT, "close"); + if (!real_close) { + errno = EIO; + return -1; + } + if (!injected && failure && strcmp(failure, "close") == 0 && backup_fd(fd)) { + injected = 1; + mark_failure(); + ret = real_close(fd); + if (ret == 0) + errno = ENOSPC; + return ret == 0 ? -1 : ret; + } + return real_close(fd); +} diff --git a/testsuite/fixtures/backup-delta-size-change.c b/testsuite/fixtures/backup-delta-size-change.c new file mode 100644 index 000000000..1ef9df327 --- /dev/null +++ b/testsuite/fixtures/backup-delta-size-change.c @@ -0,0 +1,52 @@ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include + +ssize_t read(int fd, void *buf, size_t count) +{ + static ssize_t (*real_read)(int, void *, size_t); + static int changed; + const char *path = getenv("RSYNC_TEST_OLD_FILE"); + const char *marker = getenv("RSYNC_TEST_CHANGE_MARKER"); + const char *mutation = getenv("RSYNC_TEST_BACKUP_MUTATION"); + struct stat open_file, original; + ssize_t ret; + int change_fd, mark, ok = 0; + char extra[8192]; + + if (!real_read) + real_read = dlsym(RTLD_NEXT, "read"); + if (!real_read) { + errno = EIO; + return -1; + } + ret = real_read(fd, buf, count); + if (changed || ret <= 0 || !path || !mutation || fstat(fd, &open_file) < 0 + || stat(path, &original) < 0 || open_file.st_dev != original.st_dev + || open_file.st_ino != original.st_ino) + return ret; + changed = 1; + if (strcmp(mutation, "shrink") == 0) { + change_fd = open(path, O_WRONLY); + if (change_fd >= 0) { + ok = ftruncate(change_fd, 8192) == 0; + close(change_fd); + } + } else if (strcmp(mutation, "grow") == 0) { + memset(extra, 'z', sizeof extra); + change_fd = open(path, O_WRONLY | O_APPEND); + if (change_fd >= 0) { + ok = write(change_fd, extra, sizeof extra) == sizeof extra; + close(change_fd); + } + } + mark = ok && marker ? open(marker, O_WRONLY | O_CREAT | O_EXCL, 0600) : -1; + if (mark >= 0) + close(mark); + return ret; +} diff --git a/testsuite/fixtures/backup-lock-unavailable.c b/testsuite/fixtures/backup-lock-unavailable.c new file mode 100644 index 000000000..898674866 --- /dev/null +++ b/testsuite/fixtures/backup-lock-unavailable.c @@ -0,0 +1,9 @@ +#define _GNU_SOURCE 1 +#include +#include + +FILE *tmpfile(void) +{ + errno = ENOENT; + return NULL; +} diff --git a/testsuite/tests/daemon/daemon-chroot-backup-access.py b/testsuite/tests/daemon/daemon-chroot-backup-access.py new file mode 100644 index 000000000..64702aa86 --- /dev/null +++ b/testsuite/tests/daemon/daemon-chroot-backup-access.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 + +import ctypes +import grp +import os +import pwd +import stat + +from harness import TestContext, requires, run +from harness.daemon import start_test_daemon +from harness.daemon_config import write_daemon_conf +from harness.results import test_fail, test_skipped +from harness.rsync import run_rsync, under_valgrind + + +@requires(features={'chroot', 'root'}, transports={'pipe'}, + mutates={'filesystem', 'process'}, tags={'daemon', 'regression'}) +def test(context: TestContext): + if os.geteuid() != 0: + test_skipped('requires root to chroot and select the module uid', capability='root') + if under_valgrind(): + test_skipped('daemon chroot hides Valgrind log files', capability='chroot') + pid = os.fork() + if pid == 0: + os._exit(0 if ctypes.CDLL(None, use_errno=True).chroot(b'/') == 0 else 1) + _, status = os.waitpid(pid, 0) + if not os.WIFEXITED(status) or os.WEXITSTATUS(status): + test_skipped('chroot is unavailable', capability='chroot') + + account = pwd.getpwnam('nobody') + if account.pw_uid < 0 or account.pw_gid < 0: + account = pwd.getpwnam('daemon') + group = grp.getgrgid(account.pw_gid).gr_name + for scope in ('module', 'daemon'): + base = context.scratch / scope + source = base / 'source' + root = base / 'root' + module = base / 'module' if scope == 'module' else root / 'module' + module_path = str(module) if scope == 'module' else '/module' + backup_path = '/backups' + original = module / 'dest' / 'outer' / 'old' + saved = module / 'backups' / 'outer' + source.mkdir(parents=True) + original.parent.mkdir(parents=True) + saved.mkdir(parents=True) + original.write_bytes(b'previous contents') + original_mode = stat.S_IMODE(original.parent.stat().st_mode) + for path in (module, module / 'dest', original.parent, original, + module / 'backups', saved): + os.chown(path, account.pw_uid, account.pw_gid) + saved.chmod(0o555) + if (module / 'tmp').exists() or (scope == 'daemon' and (root / 'tmp').exists()): + test_fail('the chroot unexpectedly contains a temporary directory') + + config = write_daemon_conf([('files', { + 'path': module_path, 'use chroot': 'yes' if scope == 'module' else 'no', + 'read only': 'no', + 'uid': account.pw_name if scope == 'module' else str(account.pw_uid), + 'gid': group if scope == 'module' else str(account.pw_gid), + })], global_options={'daemon chroot': str(root)} if scope == 'daemon' else None, + name=f'{scope}-chroot.conf') + url = start_test_daemon(config, 12977) + result = run_rsync('-a', '--delete-during', '--backup', + f'--backup-dir={backup_path}', f'{source}/', + f'{url}files/dest/', capture_output=True, check=False) + if result.returncode: + test_fail(f'{scope} chroot backup exited {result.returncode}: {result.stderr}') + if original.exists() or (saved / 'old').read_bytes() != b'previous contents': + test_fail(f'{scope} chroot did not save the deleted file') + if stat.S_IMODE(saved.stat().st_mode) != original_mode: + test_fail(f'{scope} chroot did not preserve the saved directory mode') + + old_data = b'a' * 700 + b'b' * 700 + b'c' * 700 + new_data = b'b' * 700 + b'd' * 700 + b'a' * 700 + b'!' + source_file = source / 'outer' / 'current' + dest_file = original.parent / 'current' + source_file.parent.mkdir() + dest_file.parent.mkdir() + source_file.write_bytes(new_data) + dest_file.write_bytes(old_data) + for path in (dest_file.parent, dest_file): + os.chown(path, account.pw_uid, account.pw_gid) + relative_saved = module / 'dest' / 'backups' / 'outer' + relative_saved.mkdir(parents=True) + for path in (relative_saved.parent, relative_saved): + os.chown(path, account.pw_uid, account.pw_gid) + relative_saved.chmod(0o400) + result = run_rsync('-a', '--inplace', '--no-whole-file', + '--backup-dir=backups', f'{source}/', + f'{url}files/dest/', capture_output=True, check=False) + if result.returncode: + test_fail(f'{scope} chroot delta exited {result.returncode}: {result.stderr}') + if dest_file.read_bytes() != new_data or (relative_saved / 'current').read_bytes() != old_data: + test_fail(f'{scope} chroot delta lost the current file or its backup') + if stat.S_IMODE(relative_saved.stat().st_mode) != 0o400: + test_fail(f'{scope} chroot delta changed the saved directory mode') + + +if __name__ == '__main__': + run(test) diff --git a/testsuite/tests/path/operator-path-backup-dir.py b/testsuite/tests/path/operator-path-backup-dir.py index 3423ff50c..731e4d55b 100644 --- a/testsuite/tests/path/operator-path-backup-dir.py +++ b/testsuite/tests/path/operator-path-backup-dir.py @@ -22,7 +22,7 @@ def case(ctx): backup, _ = plant_operator_symlink(ctx, dest) args = ['-a', '--backup', f'--backup-dir={backup}'] if inplace: - args.append('--inplace') + args.extend(('--inplace', '--no-whole-file')) if ctx.insecure: args.append('--insecure-links') subprocess.run(rsync_argv(*args, 'src/', 'dest/'), cwd=ctx.base, diff --git a/testsuite/tests/transfer/backup-delta-basis.py b/testsuite/tests/transfer/backup-delta-basis.py new file mode 100644 index 000000000..6db866735 --- /dev/null +++ b/testsuite/tests/transfer/backup-delta-basis.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 + +import re + +from harness import TestContext, requires, run +from harness.results import test_fail +from harness.rsync import run_rsync + + +@requires(transports={'pipe'}, mutates={'filesystem', 'process'}, + tags={'transfer', 'regression'}) +def test(context: TestContext): + source = context.source + destination = context.destination + backup = context.scratch / 'backup' + source.mkdir() + destination.mkdir() + backup.mkdir() + old = bytes((i * 73 + 19) % 251 + 1 for i in range(128 * 1024)) + (destination / 'file').write_bytes(old) + (source / 'file').write_bytes(old + b'!') + result = run_rsync('-a', '--inplace', '--no-whole-file', '--stats', + f'--backup-dir={backup}', f'{source}/', f'{destination}/', + capture_output=True) + match = re.search(r'^Matched data: ([0-9,]+) bytes$', result.stdout, re.MULTILINE) + if not match or int(match.group(1).replace(',', '')) < len(old) // 2: + test_fail(f'the delta did not match its saved basis:\n{result.stdout}') + if (destination / 'file').read_bytes() != old + b'!': + test_fail('the destination has incorrect contents') + if (backup / 'file').read_bytes() != old: + test_fail('the backup has incorrect contents') + + +if __name__ == '__main__': + run(test) diff --git a/testsuite/tests/transfer/backup-delta-failures.py b/testsuite/tests/transfer/backup-delta-failures.py new file mode 100644 index 000000000..b28915527 --- /dev/null +++ b/testsuite/tests/transfer/backup-delta-failures.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 + +import os +import subprocess + +from harness import TestContext, requires, run +from harness.results import test_fail, test_skipped +from harness.rsync import rsync_argv, under_valgrind +from harness.xattrs import is_supported as xattrs_supported + + +@requires(features={'linux_interpose'}, transports={'pipe'}, + mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) +def test(context: TestContext): + if under_valgrind(): + test_skipped('requires direct write interposition', capability='linux_interpose') + + fixture = context.repository / 'testsuite/fixtures/backup-delta-failures.c' + library = context.scratch / 'backup-delta-failures.so' + build = subprocess.run(['cc', '-shared', '-fPIC', '-o', str(library), str(fixture), '-ldl'], + capture_output=True, text=True, timeout=30) + if build.returncode: + test_fail(f'cannot build backup write hook: {build.stderr}') + + old = b'a' * 4096 + b'b' * 4096 + new = b'a' * 4096 + b'c' * 4097 + for failure in ('write', 'xattr', 'close'): + if failure == 'xattr' and not xattrs_supported(): + continue + base = context.scratch / failure + source = base / 'source' / 'outer' + destination = base / 'destination' / 'outer' + backup = base / 'backup' + source.mkdir(parents=True) + destination.mkdir(parents=True) + backup.mkdir() + (source / 'file').write_bytes(new) + (destination / 'file').write_bytes(old) + if failure == 'xattr': + os.setxattr(source / 'file', 'user.backup_error', b'value') + os.setxattr(destination / 'file', 'user.backup_error', b'value') + saved = backup / 'outer' / 'file' + marker = base / 'failure-triggered' + env = {**os.environ, 'LD_PRELOAD': str(library), + 'RSYNC_TEST_BACKUP_FILE': str(saved), + 'RSYNC_TEST_BACKUP_MARKER': str(marker), + 'RSYNC_TEST_BACKUP_FAILURE': failure} + args = ['-a', '--inplace', '--no-whole-file', f'--backup-dir={backup}'] + if failure == 'xattr': + args.append('-X') + + result = subprocess.run( + rsync_argv(*args, f'{base / "source"}/', f'{base / "destination"}/'), + env=env, capture_output=True, text=True, timeout=20, + ) + if not marker.exists(): + test_fail(f'{failure}: the backup failure hook did not run') + if result.returncode == 0: + test_fail(f'{failure}: failed backup was reported as a successful transfer') + if (destination / 'file').read_bytes() != old: + test_fail(f'{failure}: destination changed after its backup failed') + + +if __name__ == '__main__': + run(test) diff --git a/testsuite/tests/transfer/backup-delta-size-change.py b/testsuite/tests/transfer/backup-delta-size-change.py new file mode 100644 index 000000000..7e1d7560f --- /dev/null +++ b/testsuite/tests/transfer/backup-delta-size-change.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python3 + +import os +import subprocess + +from harness import TestContext, requires, run +from harness.results import test_fail, test_skipped +from harness.rsync import rsync_argv, under_valgrind + + +@requires(features={'linux_interpose'}, transports={'pipe'}, + mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) +def test(context: TestContext): + if under_valgrind(): + test_skipped('requires direct read interposition', capability='linux_interpose') + + fixture = context.repository / 'testsuite/fixtures/backup-delta-size-change.c' + library = context.scratch / 'backup-delta-size-change.so' + build = subprocess.run(['cc', '-shared', '-fPIC', '-o', str(library), str(fixture), '-ldl'], + capture_output=True, text=True, timeout=30) + if build.returncode: + test_fail(f'cannot build size-change hook: {build.stderr}') + + old = b'a' * 16384 + new = b'b' * 16385 + for mutation in ('grow', 'shrink'): + base = context.scratch / mutation + source = base / 'source' / 'outer' + destination = base / 'destination' / 'outer' + backup = base / 'backup' + source.mkdir(parents=True) + destination.mkdir(parents=True) + backup.mkdir() + (source / 'file').write_bytes(new) + original = destination / 'file' + original.write_bytes(old) + marker = base / 'changed' + env = {**os.environ, 'LD_PRELOAD': str(library), + 'RSYNC_TEST_OLD_FILE': str(original), + 'RSYNC_TEST_CHANGE_MARKER': str(marker), + 'RSYNC_TEST_BACKUP_MUTATION': mutation} + result = subprocess.run( + rsync_argv('-a', '--inplace', '--no-whole-file', f'--backup-dir={backup}', + f'{base / "source"}/', f'{base / "destination"}/'), + env=env, capture_output=True, text=True, timeout=20, + ) + if not marker.exists(): + test_fail(f'{mutation}: the old destination did not change during backup') + if mutation == 'grow': + if result.returncode or (backup / 'outer' / 'file').read_bytes() != old: + test_fail(f'growth was not capped at the captured size: {result.stderr}') + if original.read_bytes() != new: + test_fail('the updated file has incorrect contents after growth') + elif result.returncode == 0 or original.read_bytes() != old[:8192]: + test_fail(f'short input allowed the in-place update: {result.stderr}') + + +if __name__ == '__main__': + run(test) diff --git a/testsuite/tests/transfer/backup-lock-unavailable.py b/testsuite/tests/transfer/backup-lock-unavailable.py new file mode 100644 index 000000000..1c5bf360e --- /dev/null +++ b/testsuite/tests/transfer/backup-lock-unavailable.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 + +import os +import stat +import subprocess + +from harness import TestContext, requires, run +from harness.results import test_fail, test_skipped +from harness.rsync import rsync_argv, under_valgrind + + +@requires(features={'linux_interpose', 'nonroot'}, transports={'pipe'}, + mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) +def test(context: TestContext): + if os.geteuid() == 0: + test_skipped('requires non-root directory permissions', capability='nonroot') + if under_valgrind(): + test_skipped('requires direct tmpfile interposition', capability='linux_interpose') + + fixture = context.repository / 'testsuite/fixtures/backup-lock-unavailable.c' + library = context.scratch / 'backup-lock-unavailable.so' + build = subprocess.run(['cc', '-shared', '-fPIC', '-o', str(library), str(fixture)], + capture_output=True, text=True, timeout=30) + if build.returncode: + test_fail(f'cannot build lock failure hook: {build.stderr}') + + source = context.source + destination = context.destination + backup = context.scratch / 'backup' + original = destination / 'outer' / 'old' + saved = backup / 'outer' + source.mkdir() + original.parent.mkdir(parents=True) + saved.mkdir(parents=True) + original.write_bytes(b'previous contents') + saved.chmod(0o555) + env = {**os.environ, 'LD_PRELOAD': str(library)} + try: + result = subprocess.run( + rsync_argv('-a', '--delete-during', f'--backup-dir={backup}', + f'{source}/', f'{destination}/'), + env=env, capture_output=True, text=True, timeout=20, + ) + if result.returncode != 23 or original.read_bytes() != b'previous contents': + test_fail(f'failed backup changed the original: {result.returncode} {result.stderr}') + if stat.S_IMODE(saved.stat().st_mode) != 0o555: + test_fail('failed file backup changed the saved parent directory mode') + if (saved / 'old').exists(): + test_fail('failed backup published a file') + finally: + saved.chmod(0o700) + + +if __name__ == '__main__': + run(test) diff --git a/testsuite/tests/transfer/backup-mode-interrupt.py b/testsuite/tests/transfer/backup-mode-interrupt.py index 8719de16f..a3c1fdf6f 100644 --- a/testsuite/tests/transfer/backup-mode-interrupt.py +++ b/testsuite/tests/transfer/backup-mode-interrupt.py @@ -12,6 +12,8 @@ @requires(features={'linux_interpose', 'nonroot'}, transports={'pipe'}, mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) def test(context: TestContext): + if os.geteuid() == 0: + test_skipped('requires non-root directory permissions', capability='nonroot') if under_valgrind(): test_skipped('requires direct fchmod interposition', capability='linux_interpose') diff --git a/testsuite/tests/transfer/backup-readonly-xattr.py b/testsuite/tests/transfer/backup-readonly-xattr.py index 3c0f12e94..da581da63 100644 --- a/testsuite/tests/transfer/backup-readonly-xattr.py +++ b/testsuite/tests/transfer/backup-readonly-xattr.py @@ -9,13 +9,13 @@ from harness.xattrs import get_value, is_supported, set_value -@requires(features={'backup_metadata', 'nonroot'}, transports={'pipe'}, +@requires(features={'xattr_runtime', 'nonroot'}, transports={'pipe'}, mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) def test(context: TestContext): if os.geteuid() == 0: test_skipped('requires non-root directory permissions', capability='nonroot') if not is_supported(): - test_skipped('xattrs are unavailable', capability='backup_metadata') + test_skipped('xattrs are unavailable', capability='xattr_runtime') source = context.source / 'outer' / 'nested' destination = context.destination / 'outer' / 'nested' diff --git a/util1.c b/util1.c index dd094b190..9c276e2c8 100644 --- a/util1.c +++ b/util1.c @@ -443,14 +443,16 @@ int copy_file(const char *source, const char *dest, int tmpfilefd, mode_t mode) if (ifd < 0) return -1; - return copy_file_from_fd(source, ifd, dest, tmpfilefd, mode); + return copy_file_from_fd(source, ifd, dest, tmpfilefd, mode, -1); } /* Own the already-open input; source is used only for diagnostics and - * attribute reporting. Destination handling is the same as copy_file(). */ -int copy_file_from_fd(const char *source, int ifd, const char *dest, int tmpfilefd, mode_t mode) + * attribute reporting. A nonnegative max_len copies exactly that many bytes + * and refuses a short input; a negative value copies through EOF. */ +int copy_file_from_fd(const char *source, int ifd, const char *dest, int tmpfilefd, + mode_t mode, OFF_T max_len) { - int ofd, len; + int ofd, len = 0; char buf[1024 * 8]; OFF_T prealloc_len = 0, offset = 0; @@ -475,14 +477,24 @@ int copy_file_from_fd(const char *source, int ifd, const char *dest, int tmpfile if (do_fstat(ifd, &srcst) < 0) rsyserr(FWARNING, errno, "fstat %s", full_fname(source)); else if (srcst.st_size > 0) { - prealloc_len = do_fallocate(ofd, 0, srcst.st_size); - if (prealloc_len < 0) - rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(dest)); + OFF_T reserve_len = max_len >= 0 && srcst.st_size > max_len + ? max_len : srcst.st_size; + if (reserve_len > 0) { + prealloc_len = do_fallocate(ofd, 0, reserve_len); + if (prealloc_len < 0) + rsyserr(FWARNING, errno, "do_fallocate %s", full_fname(dest)); + } } } #endif - while ((len = safe_read(ifd, buf, sizeof buf)) > 0) { + while (max_len < 0 || offset < max_len) { + size_t wanted = sizeof buf; + if (max_len >= 0 && max_len - offset < (OFF_T)wanted) + wanted = (size_t)(max_len - offset); + len = safe_read(ifd, buf, (int)wanted); + if (len <= 0) + break; if (full_write(ofd, buf, len) < 0) { int save_errno = errno; rsyserr(FERROR_XFER, errno, "write %s", full_fname(dest)); @@ -494,6 +506,14 @@ int copy_file_from_fd(const char *source, int ifd, const char *dest, int tmpfile offset += len; } + if (len == 0 && max_len >= 0 && offset < max_len) { + errno = EIO; + rsyserr(FERROR_XFER, errno, "source %s shrank while copying", full_fname(source)); + close(ifd); + close(ofd); + return -1; + } + if (len < 0) { int save_errno = errno; rsyserr(FERROR_XFER, errno, "read %s", full_fname(source)); @@ -516,23 +536,28 @@ int copy_file_from_fd(const char *source, int ifd, const char *dest, int tmpfile #endif } +#ifdef SUPPORT_XATTRS + /* Read the source xattrs through the held source fd (ifd) and set them + * through ofd while both are still held, so a parent-symlink race can't + * redirect the read out of tree or the write onto a file outside it. */ + if (preserve_xattrs && copy_xattrs(source, ifd, dest, ofd) < 0) { + int save_errno = errno; + close(ofd); + close(ifd); + errno = save_errno; + return -1; + } +#endif + if (do_fsync && fsync(ofd) < 0) { int save_errno = errno; rsyserr(FERROR, errno, "fsync failed on %s", full_fname(dest)); close(ofd); - close(ifd); /* ifd is held open until after the xattr copy below */ + close(ifd); errno = save_errno; return -1; } -#ifdef SUPPORT_XATTRS - /* Read the source xattrs through the held source fd (ifd) and set them - * through ofd while both are still held, so a parent-symlink race can't - * redirect the read out of tree or the write onto a file outside it. */ - if (preserve_xattrs) - copy_xattrs(source, ifd, dest, ofd); -#endif - if (close(ifd) < 0) { rsyserr(FWARNING, errno, "close failed on %s", full_fname(source)); diff --git a/xattrs.c b/xattrs.c index 409356bda..1baeb66d3 100644 --- a/xattrs.c +++ b/xattrs.c @@ -38,6 +38,8 @@ extern int preserve_devices; extern int preserve_specials; extern int checksum_seed; extern int saw_xattr_filter; +extern char *backup_dir; +extern char backup_dir_buf[MAXPATHLEN]; extern struct name_num_item *xattr_sum_nni; extern int xattr_sum_len; @@ -1004,6 +1006,8 @@ static int rsync_xal_set(const char *fname, item_list *xalp, #endif size_t name_len; int ret = 0; + int basis_fd = -1; + BOOL path_only_basis = False; /* This puts the current name list into the "namebuf" buffer. */ if ((list_len = get_xattr_names(fname, fd)) < 0) @@ -1017,9 +1021,25 @@ static int rsync_xal_set(const char *fname, item_list *xalp, errno = EINVAL; return -1; } + if (backup_dir && fnamecmp == backup_dir_buf && basis_fd < 0 && !path_only_basis) { + if (symlink_optout_allowed() && backup_basis_path_fallback(fnamecmp, 0)) + path_only_basis = True; + else + basis_fd = open_backup_basis(fnamecmp); + if (!path_only_basis && basis_fd < 0) { + int open_error = errno; + if (backup_basis_path_fallback(fnamecmp, open_error)) + path_only_basis = True; + else { + rsyserr(FERROR_XFER, errno, "cannot open backup basis %s", + full_fname(fnamecmp)); + return -1; + } + } + } /* See if the fnamecmp version is identical. */ len = name_len = rxas[i].name_len; - if ((ptr = get_xattr_data(fnamecmp, -1, name, &len, 1)) == NULL) { + if ((ptr = get_xattr_data(fnamecmp, basis_fd, name, &len, 1)) == NULL) { still_abbrev: if (am_generator) continue; @@ -1111,6 +1131,8 @@ static int rsync_xal_set(const char *fname, item_list *xalp, } } + if (basis_fd >= 0) + close(basis_fd); return ret; } From 1cdd21a1ae3cb100a078743d721ae9ca103b70d4 Mon Sep 17 00:00:00 2001 From: Zen Dodd Date: Tue, 24 Nov 2026 17:31:40 +1100 Subject: [PATCH 10/10] testsuite: trigger backup size changes during the copy --- testsuite/fixtures/backup-delta-size-change.c | 41 +++++++++++-------- .../transfer/backup-delta-size-change.py | 15 ++++--- 2 files changed, 35 insertions(+), 21 deletions(-) diff --git a/testsuite/fixtures/backup-delta-size-change.c b/testsuite/fixtures/backup-delta-size-change.c index 1ef9df327..deefece7e 100644 --- a/testsuite/fixtures/backup-delta-size-change.c +++ b/testsuite/fixtures/backup-delta-size-change.c @@ -7,46 +7,55 @@ #include #include -ssize_t read(int fd, void *buf, size_t count) +ssize_t write(int fd, const void *buf, size_t count) { - static ssize_t (*real_read)(int, void *, size_t); + static ssize_t (*real_write)(int, const void *, size_t); static int changed; - const char *path = getenv("RSYNC_TEST_OLD_FILE"); + const char *basis = getenv("RSYNC_TEST_OLD_FILE"); + const char *backup = getenv("RSYNC_TEST_BACKUP_FILE"); const char *marker = getenv("RSYNC_TEST_CHANGE_MARKER"); const char *mutation = getenv("RSYNC_TEST_BACKUP_MUTATION"); - struct stat open_file, original; + struct stat open_file, saved_file, original; ssize_t ret; - int change_fd, mark, ok = 0; + int change_fd, mark, saved_errno, ok = 0; char extra[8192]; - if (!real_read) - real_read = dlsym(RTLD_NEXT, "read"); - if (!real_read) { + if (!real_write) + real_write = dlsym(RTLD_NEXT, "write"); + if (!real_write) { errno = EIO; return -1; } - ret = real_read(fd, buf, count); - if (changed || ret <= 0 || !path || !mutation || fstat(fd, &open_file) < 0 - || stat(path, &original) < 0 || open_file.st_dev != original.st_dev - || open_file.st_ino != original.st_ino) + ret = real_write(fd, buf, count); + if (changed || ret <= 0 || !basis || !backup || !marker || !mutation) return ret; + + /* The backup write identifies the copy phase regardless of how libc reads. */ + saved_errno = errno; + if (fstat(fd, &open_file) < 0 || stat(backup, &saved_file) < 0 + || open_file.st_dev != saved_file.st_dev || open_file.st_ino != saved_file.st_ino + || stat(basis, &original) < 0 || open_file.st_size >= original.st_size) + goto done; + changed = 1; if (strcmp(mutation, "shrink") == 0) { - change_fd = open(path, O_WRONLY); + change_fd = open(basis, O_WRONLY); if (change_fd >= 0) { ok = ftruncate(change_fd, 8192) == 0; close(change_fd); } } else if (strcmp(mutation, "grow") == 0) { memset(extra, 'z', sizeof extra); - change_fd = open(path, O_WRONLY | O_APPEND); + change_fd = open(basis, O_WRONLY | O_APPEND); if (change_fd >= 0) { - ok = write(change_fd, extra, sizeof extra) == sizeof extra; + ok = real_write(change_fd, extra, sizeof extra) == sizeof extra; close(change_fd); } } - mark = ok && marker ? open(marker, O_WRONLY | O_CREAT | O_EXCL, 0600) : -1; + mark = ok ? open(marker, O_WRONLY | O_CREAT | O_EXCL, 0600) : -1; if (mark >= 0) close(mark); + done: + errno = saved_errno; return ret; } diff --git a/testsuite/tests/transfer/backup-delta-size-change.py b/testsuite/tests/transfer/backup-delta-size-change.py index 7e1d7560f..da56f5d3b 100644 --- a/testsuite/tests/transfer/backup-delta-size-change.py +++ b/testsuite/tests/transfer/backup-delta-size-change.py @@ -12,7 +12,7 @@ mutates={'filesystem', 'process'}, tags={'transfer', 'regression'}) def test(context: TestContext): if under_valgrind(): - test_skipped('requires direct read interposition', capability='linux_interpose') + test_skipped('requires direct write interposition', capability='linux_interpose') fixture = context.repository / 'testsuite/fixtures/backup-delta-size-change.c' library = context.scratch / 'backup-delta-size-change.so' @@ -33,10 +33,12 @@ def test(context: TestContext): backup.mkdir() (source / 'file').write_bytes(new) original = destination / 'file' + saved = backup / 'outer' / 'file' original.write_bytes(old) marker = base / 'changed' env = {**os.environ, 'LD_PRELOAD': str(library), 'RSYNC_TEST_OLD_FILE': str(original), + 'RSYNC_TEST_BACKUP_FILE': str(saved), 'RSYNC_TEST_CHANGE_MARKER': str(marker), 'RSYNC_TEST_BACKUP_MUTATION': mutation} result = subprocess.run( @@ -45,14 +47,17 @@ def test(context: TestContext): env=env, capture_output=True, text=True, timeout=20, ) if not marker.exists(): - test_fail(f'{mutation}: the old destination did not change during backup') + test_fail(f'{mutation}: the fixture did not change the basis during a partial backup write') if mutation == 'grow': - if result.returncode or (backup / 'outer' / 'file').read_bytes() != old: + if result.returncode or saved.read_bytes() != old: test_fail(f'growth was not capped at the captured size: {result.stderr}') if original.read_bytes() != new: test_fail('the updated file has incorrect contents after growth') - elif result.returncode == 0 or original.read_bytes() != old[:8192]: - test_fail(f'short input allowed the in-place update: {result.stderr}') + else: + if result.returncode != 23 or 'shrank while copying' not in result.stderr: + test_fail(f'expected a short-copy failure, got exit {result.returncode}: {result.stderr}') + if original.read_bytes() != old[:8192]: + test_fail('short input allowed the in-place update') if __name__ == '__main__':