Skip to content

fix(receiver): rmdir a directory obstacle instead of backing it up - #7597

Closed
oferchen wants to merge 3 commits into
masterfrom
fix/obstacle-dir-removal
Closed

oferchen wants to merge 3 commits into
masterfrom
fix/obstacle-dir-removal

Conversation

@oferchen

@oferchen oferchen commented Sep 1, 2026

Copy link
Copy Markdown
Owner

What

A directory standing where the receiver has to create a symlink, FIFO, socket, or device node was neither removed nor reported. The five backup_existing_before_replace call sites in links.rs / special.rs each did:

Ok(false) => { let _ = fast_io::unlink_via_sandbox_or_fallback(.., UnlinkFlags::File); }
Err(e)    => { debug_log!(Recv, 1, "failed to back up existing obstacle …"); continue; }

File-only, so it structurally cannot rmdir a directory by any route; the result discarded; the failure on a verbosity gate with no MessageCode and no effect on the exit code.

Why the removal and the reporting are ONE change

Upstream decides this in one place, and the decision is ordered:

/* generator.c:2469 */
int skip_atomic, dir_in_the_way = del_for_flag && S_ISDIR(sxp->st.st_mode);
if (!del_for_flag || dir_in_the_way || tmpdir || !get_tmpname(tmpname, fname, True))
        skip_atomic = 1;
...
if (make_backups > 0 && !dir_in_the_way) {          /* :2477 */
        if (!make_backup(fname, skip_atomic)) return 0;
} else if (skip_atomic) {                           /* :2480 */
        int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0;
        if (delete_item(fname, sxp->st.st_mode, del_opts | del_for_flag) != 0) return 0;
}

dir_in_the_way forces skip_atomic, so a directory obstacle reaches delete_item whether or not --backup is set — the make_backup arm is unreachable for it in either mode. delete_item then splits on the same test one level down: the rmdir arm at delete.c:222-226, the make_backup/unlink arm in the else at delete.c:227-238.

Two consequences, and they are what make this a single commit:

  1. A guard on the backup path cannot work. It could only cover the --backup-on half; the four --backup-off shapes in the table below would still be decided in links.rs/special.rs. That is a divergence from upstream's structure by construction, not by taste.

  2. The reporting alone is a regression. Measured by mutation, with the removal disabled and the diagnostics in place, a symlink over an empty directory gives:

    rsync: [receiver] delete_file: unlink(obstacle) failed: Operation not permitted (1)
    could not make way for new symlink: obstacle
    left: Some(23)   right: Some(0)
    

    — exit 23 on a shape 3.5.0 completes at exit 0.

So the five call sites now share one make_way_for_replacement, which owns both arms and emits upstream's diagnostics itself. backup_existing_before_replace is now called from exactly one place.

Measured

rsync 3.5.0 (protocol 32) vs oc, over a real --server child on both ends (-e wrapper, --rsync-path pinning both sides). Not the local-copy executor: that path refuses a directory obstacle in its own error type (local_copy/error.rs:427) and exercises none of this.

--backup off, -rlDI, source obstacle replacing dst/obstacle/:

src kind obstacle rsync 3.5.0 oc before oc after
symlink empty dir 0, symlink placed 12 server error: File exists (17), dir kept 0, symlink placed
symlink non-empty dir 23 + two diagnostics 12, dir kept 23 + same two diagnostics
fifo empty dir 0, fifo placed 0 SILENT, dir kept 0, fifo placed
fifo non-empty dir 23 + two diagnostics 0 SILENT, dir kept 23 + same two diagnostics

Three things in that table are worse than the exit codes suggest:

  • Both FIFO rows reported success while losing the node. Silent data loss, not a loud failure.
  • The failing rows abandoned the rest of the batch. The sibling file upstream transfers at exit 23 was never written.
  • Under --backup, oc RENAMED the directory into the backup area (--backup-dir=bak → bak/obstacle), which upstream never does. A wrong-data outcome at exit 0, which no exit-code assertion could have caught. Now removed.

The two regular file rows of the same matrix (12 vs 0/23) are the DEL_FOR_FILE site at generator.c:2148 and are deliberately untouched here — see "Relationship to the wider obstacle-removal work" below.

Also verified by strace of the server child, on the exact shape the failing testsuite cell hits (--backup-dir equal to the obstacle):

linkat(AT_FDCWD, ".../dst/a", AT_FDCWD, ".../dst/a/a", 0) = -1 EPERM
renameat(AT_FDCWD, ".../dst/a", AT_FDCWD, ".../dst/a/a")  = -1 EINVAL

…and then nothing. No rmdir, no symlinkat, no output at -vvv --debug=RECV5,BACKUP5.

Diagnostics

Upstream's text and routing, per arm:

  • populated directory → cannot delete non-empty directory: %s at FINFO (delete.c:178-181), then could not make way for new %s: %s at FERROR_XFER (delete.c:283-285). The FERROR_XFER sets the peer's got_xfer_error (log.c:310-311), which lifts a zero exit to RERR_PARTIAL (cleanup.c:217-218).
  • other rmdir/unlink errno → delete_file: rmdir(...) failed / unlink(...) failed at FERROR_XFER (delete.c:264-266), then the same refusal line.
  • ENOENT → not a failure; upstream maps it to DR_SUCCESS (delete.c:268-269) and creates the replacement.
  • backup-arm failure → keep_backup failed: <path> at FERROR, not FERROR_XFER. Upstream leaves got_xfer_error clear on that arm (backup.c:400-401), so the exit code is unchanged there.

The noun comes from the new entry's type, not the obstacle's (generator.c:2041-2047 picks DEL_FOR_DEVICE/DEL_FOR_SPECIAL; delete.c:275-282 turns it into the word), so a FIFO says special file where a symlink says symlink.

The obstacle type is read from the same sandbox-anchored fstatat the removal is anchored on (new LstatOutcome::is_dir), so a TOCTOU swap between classifying and removing cannot make the two disagree.

Test

tests/directory_obstacle_removal.rs, six cells, all through a real --server child.

Mutation-proven, each half reverted in turn:

mutation red green
reporting restored to the swallow (removal intact) the 3 refusal cells (23 → 0, no diagnostics) the 3 removal cells
removal arm deleted (reporting intact) 5 of 6, incl. an_empty_directory_obstacle_is_removed_for_a_symlink at 23 where upstream is 0 1

The FIFO-over-empty-directory cell is the one that separates the halves: it is green under the first mutation and red under the second, so it distinguishes "the removal works" from "the removal now fails loudly instead of silently". Nothing else in the set does.

The non-vacuity companion is a_directory_obstacle_is_removed_not_backed_up_under_backup: a shape upstream completes at exit 0 must still exit 0 after the change, and must not leave the directory in the backup area.

Regression surface. One existing unit test had to move: receiver::tests::munge_symlinks::create_symlinks_surfaces_non_eacces_error planted an empty directory at the leaf to make symlinkat return EEXIST, and closed with assert!(dest.join("blocked").is_dir(), "the planted directory must persist") — an assertion on the defect. Its invariant (non-EACCES → Err) is real and kept; the fixture now plants a regular file where a path component belongs, giving ENOTDIR. delete_item only ever clears the leaf, so no obstacle removal can make way for that one.

Verification

  • Full 3.5.0 python suite, 345 cells, nonroot, aarch64 Linux: 253 pass / 6 fail / 86 skip. The six failures are exactly the six the expect manifest already names (basis-xname-traversal, batch-only-remove-source-regression, filter-merge-content-echo, partial-protected-regular-retry-linux, rrsync-backup-dir-inband-pivot, rrsync-merge-file-confine). No row moves in either direction, so tools/ci/upstream-3.5.0-expect.{nonroot,root}.txt are unchanged.
  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --all-features --no-deps -- -D warnings — no finding in any changed file.
  • cargo nextest run --workspace --all-features — 32881 tests, 32880 passed. The one failure is xtask … backdated_tree_populates_and_backdates_the_root, a pre-existing macOS-host failure (touch -d @1614830767: BSD touch rejects the @epoch form), unrelated to this change.
  • tools/ci/citation_drift_audit.py — exit 0.

rrsync-backup-dir-inband-pivot: 2 of 3 assertions flipped, and the third is named

This is the cell that motivated the change. It has three assertions past the escape check. Before: all three failed at the first one. After:

assertion before after
got.returncode != 0 rc=0 ❌ rc=12 ✅
pivot == '../outside' None ❌ '../outside' ✅
'/proc/self/fd/' in got.stderr ❌ ❌ still

The mechanism now works end to end: the rmdir frees the name (so the transfer's own symlink is planted, pivot='../outside') and destroys the inode rrsync holds on fd 5, so the later authorized_keys backup opens a deleted directory and fails. 3.5.0 does exactly this and exits 11 at rsync.c:894-896.

The remaining assertion is not obstacle-removal territory, and there are two independent reasons for it:

  1. The failure is ENOENT, and pipeline/receiver.rs:445/508 reaches commit_failure only on the is_permission_error branch; ENOENT takes the fatal return Err(e) instead, so the upstream-shaped line is never rendered.
  2. Even on that branch the operand would be wrong: disk_commit/process/commit.rs:110-116 passes attach_commit_op(CommitOp::Backup, &begin.file_path, e) — the pre-image, not the backup destination. The comment at pipeline/receiver.rs:316-320 already documents this ("oc names the pre-image only; the backup destination is chosen inside make_backup and is not carried back on the error"), so /proc/self/fd/5/authorized_keys would still not appear.

Both belong to #7582 ("abort with 11 when a commit-path backup fails"), which routes the fatal backup failure through commit_failure and flushes the queued line. The manifest row is left at fail rather than re-baselined.

Relationship to the wider obstacle-removal work

The general missing removal is upstream's delete_item(… DEL_FOR_FILE) at generator.c:2148, which covers a regular file landing on an obstacle. That is a different call site and is not touched here — the two regular file rows of the matrix above are unchanged (12 where upstream is 0 or 23). This change builds the shared decision function with both of delete_item's arms, so routing that site onto it later is a call-site change rather than a reconciliation of two overlapping mechanisms. #7583's write_devices && stype == FT_DEVICE carve-out is the other half of that line and is orthogonal to both.

Known residual, measured and deliberately out of scope

generator.c:2481 computes int del_opts = delete_mode || force_delete ? DEL_RECURSE : 0, so under --delete or --force upstream removes a populated directory obstacle recursively and completes at exit 0. Measured against 3.5.0: --force, --delete, and both together each give rc=0 with the symlink in place, where this arm refuses at 23.

Neither flag is reachable from the receiver. --force is parsed and discarded by the server arg parser (cli/src/frontend/server/flags.rs:615, "--force" => {}) and has no field in ParsedServerFlags. Wiring it is a server-arg and config change, not an obstacle-removal one. Before this change the same shape aborted the whole transfer at 12 with the sibling files unsent, so the refusal is strictly closer to upstream, not a new divergence. Recorded in the module doc so it is not rediscovered as a surprise.

A directory standing where the receiver has to create a symlink, FIFO,
socket, or device node was neither removed nor reported. oc backed it
up when `--backup` was on, tried a `File`-only unlink when it was off,
discarded the result either way, and routed the failure to a
verbosity-gated `debug_log!`.

Upstream decides this in one place. `atomic_create` sets
`dir_in_the_way` (generator.c:2469), which also forces `skip_atomic`,
so a directory obstacle reaches `delete_item` whether or not `--backup`
is set - the `make_backup` arm is unreachable for it in either mode.
`delete_item` splits the same way one level down: the `rmdir` arm at
delete.c:222-226, the `make_backup`/`unlink` arm in the `else` at
delete.c:227-238.

That is why the removal and the reporting are one change. A guard added
to the backup path could only cover the `--backup`-on half; the four
`--backup`-off shapes below would still be decided in links.rs and
special.rs. And the reporting alone is a regression: with the removal
disabled but the diagnostics in place, a symlink over an EMPTY
directory exits 23 with `delete_file: unlink(obstacle) failed` where
3.5.0 exits 0. Measured by mutation, not argued.

The five `backup_existing_before_replace` call sites in links.rs and
special.rs now share one `make_way_for_replacement`, which owns both
arms and emits upstream's diagnostics itself.

Measured against rsync 3.5.0 (protocol 32) over a real `--server` child
on both ends, `--backup` off:

  src kind | obstacle      | 3.5.0                | oc before
  ---------|---------------|----------------------|---------------------
  symlink  | empty dir     | 0, symlink placed    | 12, dir kept
  symlink  | non-empty dir | 23 + two diagnostics | 12, dir kept
  fifo     | empty dir     | 0, fifo placed       | 0 SILENT, dir kept
  fifo     | non-empty dir | 23 + two diagnostics | 0 SILENT, dir kept

The failing rows also abandoned the rest of the batch: the sibling file
upstream transfers at exit 23 was never written. Both FIFO rows
reported success while losing the node - silent data loss, not a loud
failure. All four now match 3.5.0 in exit code and in text.

Under `--backup` with a sibling backup dir, oc RENAMED the directory
into the backup area, which upstream never does: a wrong-data outcome
at exit 0 that no exit-code assertion could catch. It is now removed.

The full 3.5.0 python suite (345 cells, nonroot) reports exactly the
six failures the expect manifest already names, so no row moves in
either direction and the manifest is unchanged.

Known residual, measured and out of scope: generator.c:2481 sets
`DEL_RECURSE` under `--delete`/`--force`, so upstream removes a
POPULATED directory obstacle recursively and exits 0. `--force` is
parsed and discarded by the server arg parser
(cli/src/frontend/server/flags.rs:615) and has no field in
`ParsedServerFlags`, so the receiver cannot see it. Wiring it is a
server-arg change. The refusal here is still closer to upstream than
the pre-change abort at 12.
The EACCES cross-site note opened with a line-initial dash, so rustdoc -
and `clippy::doc_lazy_continuation` under `-D warnings` - read it as a
list item whose two following lines are lazy continuations. That is a
hard error on the required fmt + clippy gate, raised twice at
munge_symlinks.rs:124-125.

Prose only, and the claim is unchanged: one fail-loud regression per
site is still sufficient because both sites share the same
upstream-parity rule (`PermissionDenied` is the only non-fatal class).
No behaviour, no test, no manifest row moves.

`cargo clippy --workspace --all-targets --all-features -- -D warnings`
is clean with only this hunk applied, and no other file on this branch
carries the same dash-then-continuation shape. A file no `mod`
declaration reaches is never compiled, so it cannot raise this lint
either - unlike a formatting diff, there is no invisible second site.
`create_specials` is the only constructor of `MakeWayFor::Device` and
`MakeWayFor::Special`, and it is `#[cfg(unix)]` - Windows has no `mknod`
path. On Windows both variants are therefore unconstructible, and
`dead_code` fires:

    error: variants `Device` and `Special` are never constructed
      --> crates/transfer/src/receiver/directory/obstacle.rs:81:5
    = note: `-D dead-code` implied by `-D warnings`

ci.yml sets `RUSTFLAGS: "-D warnings"` at workflow scope, and the
`windows-test` job runs `cargo nextest run --locked -p transfer
--all-features`, so this is a hard failure of a required cell rather
than a warning.

Reproduced and fixed against a cross-check:
`RUSTFLAGS="-D warnings" cargo check -p transfer --all-targets
--all-features --target x86_64-pc-windows-gnu` errors before and is
clean after. `Symlink` stays ungated - the Windows symlink creator
constructs it.
@oferchen

oferchen commented Sep 1, 2026

Copy link
Copy Markdown
Owner Author

Measured: this branch appears SUPERSEDED by master. Recommend closing rather than rebasing.

I picked this up as a conflicting PR and attempted the rebase in a scratch branch (no worktree touched, rebase aborted, nothing pushed). Reporting what the conflict actually is, because it is not an ordinary two-sided merge.

The conflict shape is the tell. Rebasing 1faf3c46f onto master (92e50abcc) produces four conflicts, and two of them are add/add:

CONFLICT (add/add): crates/transfer/src/receiver/directory/obstacle.rs
CONFLICT (add/add): tests/directory_obstacle_removal.rs

Both files already exist on master. An add/add on the two files a PR exists to introduce means master gained them independently.

Direction of the diff settles it. git diff origin/master 1faf3c46f over those two files:

 crates/transfer/src/receiver/directory/obstacle.rs |  29 +---
 tests/directory_obstacle_removal.rs                | 162 +--------------------
 2 files changed, 5 insertions(+), 186 deletions(-)

Master → PR head is +5 / -186. The branch holds strictly less than master. Merging it would delete 186 lines of currently-shipping code and tests.

The 5 lines the branch has and master does not are all doc prose — no code:

//! stands where a symlink, FIFO, socket, or device node has to be created.
    /// Clears whatever stands at `existing` so a fresh non-regular entry can be
    /// created there, reporting any refusal the way upstream reports it.
//! A directory standing where a symlink or special file has to be created is
//! removed, never backed up - and a populated one is refused out loud.

So there is no functional residue to salvage: the substance landed, and master's wording has since moved on.

Recommendation: close this PR as superseded. If any of that doc wording is preferred over master's, it is a separate one-file docs change, not a rebase of this branch.

⚠ Caveat on scope: I compared only the two add/add files, since those are the ones the PR exists to add. If you believe the branch carries substance in the other two conflicted files (receiver/directory/mod.rs, receiver/tests/munge_symlinks.rs), that is worth checking before closing — I did not diff those, and a --stat on the whole branch would not distinguish supersession from divergence.

@oferchen

oferchen commented Sep 1, 2026

Copy link
Copy Markdown
Owner Author

This PR is SUPERSEDED, not merely conflicting — rebasing it would regress master.

The conflict shape is the tell: two of the three files conflict add/add, meaning master
already has a file at each path.

CONFLICT (content):  crates/transfer/src/receiver/directory/mod.rs
CONFLICT (add/add):  crates/transfer/src/receiver/directory/obstacle.rs
CONFLICT (add/add):  tests/directory_obstacle_removal.rs

Both files landed on master via a different PR — #7602, commit 81c158629
(fix(receiver): remove a non-regular obstacle before a file transfer).

Diffing master's copies against this branch's (direction: master → this PR):

file delta
crates/transfer/src/receiver/directory/obstacle.rs 3 insertions, 16 deletions
tests/directory_obstacle_removal.rs 2 insertions, 160 deletions

This branch is a strict subset. Resolving the conflict in its favour would remove 176
lines of production code and tests that master already carries, so the 70 green checks here
are green against a tree that no longer reflects the intended end state.

Recommend closing as superseded by #7602 rather than rebasing. If some hunk here is genuinely
absent from master, it should be extracted as its own small PR on top of current master — the
--stat deltas above say the residual is subtractive, not additive, but a hunk-level read
would settle it definitively before anything is discarded.

@oferchen

oferchen commented Sep 1, 2026

Copy link
Copy Markdown
Owner Author

Closing as superseded: master already carries this work, merged via #7602.

The conflict shape is the evidence. Both sides ADD the same new files - obstacle.rs and tests/directory_obstacle_removal.rs - which is the signature of supersession, not of divergence: two branches that independently introduced the same construct, one of which landed first. Divergent work conflicts on modified lines, not on whole new files existing twice for the same reason.

Rebasing would mean hand-resolving add/add conflicts on files present on both sides for identical reasons, and arriving at an empty residual. Closing records that outcome directly.

The work itself is not lost - it is on master. If a residual behaviour from this branch turns out to be missing from #7602's version, that is a fresh, separately-scoped change rather than a rebase of this one.

@oferchen oferchen closed this Sep 1, 2026
oferchen added a commit that referenced this pull request Sep 2, 2026
`## [Unreleased]` last covered the #7304-#7522 era. Measured against the 60
most recently merged pull requests, 44 were absent; of the most recent 45,
43 were absent. Nothing from #7574 onward was recorded at all.

Each entry is derived from what the pull request actually landed - the merge
commit and the body - not from its title. Three cases where those differ:

  * #7616 ships far more than the doc-alias correction its body describes:
    the `upstream_version` pin moves to 3.5.0 and `--version` starts naming
    `quic`, `sd-notify`, `vmsplice` and `send_zc`.
  * #7618 also adds the pull-request rustdoc-link job its body says was
    filed separately, which is what closes the master-only-gate recurrence.
  * #7602's squash carries the closed #7597 as its first commit, so the
    directory-obstacle half is recorded under #7602.

#7587 is deliberately not recorded. Its merge commit is empty: the change
had already landed as #7563, which the section already names.

Entries extend the existing Keep a Changelog groups and the bold
sub-groupings. Clusters that are one story carry one entry with several
references: the FERROR_XFER routing and its two-phase drain (#7576, #7581),
the connection-FSM close edge and the accept loop that outlives a session
error (#7579, #7590), the three detaching daemon suites (#7578, #7588,
#7592), the io_uring and SEND_ZC work (#7593, #7600, #7610), the citation
retargets (#7601, #7603, #7604), and the accept-loop pin flake (#7615,
#7620).

Only `## [Unreleased]` is touched; every released section, including the
3.4.4 statements that were correct when written, is byte-identical.
@oferchen
oferchen deleted the fix/obstacle-dir-removal branch September 16, 2026 08:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant