| 1 |
"""Shared helpers for rsync's Python test scripts. |
| 2 |
|
| 3 |
This is the Python counterpart of testsuite/rsync.fns. It exposes only what |
| 4 |
the Python-rewritten tests actually need; grow it as more shell tests are |
| 5 |
ported. |
| 6 |
|
| 7 |
Conventions matching the shell harness: |
| 8 |
* Exit codes (see the Exit enum): 0=pass, 1=fail, 2=error, 77=skip, 78=xfail. |
| 9 |
* The runner sets these environment variables before invoking each test: |
| 10 |
scratchdir per-test scratch directory |
| 11 |
srcdir rsync source directory |
| 12 |
TOOLDIR build directory (holds the rsync binary and helpers) |
| 13 |
RSYNC the rsync command line (may include valgrind / --protocol=N) |
| 14 |
TLS_ARGS extra arguments to pass to the 'tls' helper |
| 15 |
suitedir this directory (testsuite/) |
| 16 |
""" |
| 17 |
|
| 18 |
from __future__ import annotations |
| 19 |
|
| 20 |
import atexit |
| 21 |
import fcntl |
| 22 |
import filecmp |
| 23 |
import errno |
| 24 |
import math |
| 25 |
import os |
| 26 |
import platform |
| 27 |
import re |
| 28 |
import shlex |
| 29 |
import shutil |
| 30 |
import signal |
| 31 |
import socket as _socket |
| 32 |
import stat |
| 33 |
import struct |
| 34 |
import subprocess |
| 35 |
import sys |
| 36 |
import tempfile |
| 37 |
import time |
| 38 |
from pathlib import Path |
| 39 |
|
| 40 |
from exitcodes import Exit |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
def _required(name: str) -> str: |
| 46 |
v = os.environ.get(name) |
| 47 |
if not v: |
| 48 |
sys.stderr.write( |
| 49 |
f"rsyncfns: required environment variable {name} is not set; " |
| 50 |
"run this test via runtests.py rather than directly.\n" |
| 51 |
) |
| 52 |
sys.exit(Exit.ERROR) |
| 53 |
return v |
| 54 |
|
| 55 |
|
| 56 |
SCRATCHDIR = Path(_required('scratchdir')) |
| 57 |
SRCDIR = Path(_required('srcdir')) |
| 58 |
TOOLDIR = Path(_required('TOOLDIR')) |
| 59 |
SUITEDIR = Path(os.environ.get('suitedir', SRCDIR / 'testsuite')) |
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
os.umask(0o022) |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
os.environ['HOME'] = str(SCRATCHDIR) |
| 73 |
RSYNC = _required('RSYNC') |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
RSYNC_PEER = os.environ.get('RSYNC_PEER', RSYNC) |
| 83 |
|
| 84 |
|
| 85 |
def split_rsync_cmd(cmd: str) -> list: |
| 86 |
"""Split an rsync command string into argv, tolerating spaces in the path. |
| 87 |
|
| 88 |
RSYNC may be a wrapper command ('valgrind --tool=memcheck /build/rsync'), |
| 89 |
which has to be split, or a plain path to the binary, which must not be if |
| 90 |
it contains a space -- shlex.split() would turn '/ws test/rsync' into two |
| 91 |
nonexistent programs. A path that exists is one word by definition, so |
| 92 |
check that first and only fall back to splitting for a real command line. |
| 93 |
|
| 94 |
Call this at use time, never once at import: tests such as chown-fake |
| 95 |
append ' --fake-super' to rsyncfns.RSYNC part-way through, and a cached |
| 96 |
split would keep handing back the pre-mutation command. |
| 97 |
""" |
| 98 |
if os.path.isfile(cmd): |
| 99 |
return [cmd] |
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
for m in reversed(list(re.finditer(r'\s+', cmd))): |
| 105 |
head = cmd[:m.start()] |
| 106 |
if os.path.isfile(head): |
| 107 |
return [head] + shlex.split(cmd[m.start():]) |
| 108 |
return shlex.split(cmd) |
| 109 |
|
| 110 |
|
| 111 |
def _under_valgrind(): |
| 112 |
"""True when the runner wrapped rsync in valgrind (runtests.py --valgrind). |
| 113 |
|
| 114 |
Match the wrapper's program name (first token of RSYNC or RSYNC_PEER), not a |
| 115 |
bare 'valgrind' substring, so an rsync path that merely contains the word |
| 116 |
does not false-trigger. |
| 117 |
""" |
| 118 |
for cmd in (RSYNC, RSYNC_PEER): |
| 119 |
if os.path.basename(shlex.split(cmd)[0]) == 'valgrind': |
| 120 |
return True |
| 121 |
return False |
| 122 |
|
| 123 |
|
| 124 |
|
| 125 |
|
| 126 |
TLS_ARGS = os.environ.get('TLS_ARGS', '') |
| 127 |
|
| 128 |
|
| 129 |
|
| 130 |
|
| 131 |
|
| 132 |
USE_TCP = os.environ.get('RSYNC_TEST_USE_TCP') == '1' |
| 133 |
|
| 134 |
|
| 135 |
|
| 136 |
|
| 137 |
_RACE_TIMEOUT_SET = 'race_timeout' in os.environ |
| 138 |
try: |
| 139 |
RACE_TIMEOUT = float(os.environ.get('race_timeout', '5')) |
| 140 |
except ValueError: |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
RACE_TIMEOUT = 5.0 |
| 147 |
_RACE_TIMEOUT_SET = False |
| 148 |
|
| 149 |
|
| 150 |
def race_budget(default: float = 5.0) -> float: |
| 151 |
"""Seconds this race test may spend trying to provoke an escape. |
| 152 |
|
| 153 |
A race test is a NEGATIVE oracle: it passes by *failing* to break in before |
| 154 |
the budget runs out, so it always spends the whole budget. The budget is |
| 155 |
therefore the test's runtime -- these are the suite's slowest tests, which |
| 156 |
is exactly why the knob has to work. |
| 157 |
|
| 158 |
Tests needing longer than the 5s baseline to be a credible oracle pass their |
| 159 |
own `default`. An explicit --race-timeout overrides every default, in both |
| 160 |
directions: the old `max(RACE_TIMEOUT, 10.0)` idiom ignored the option below |
| 161 |
10s, so the documented knob did nothing for most of these tests. |
| 162 |
|
| 163 |
Lowering the budget weakens the oracle (fewer flips observed = less chance |
| 164 |
of catching a regression), so the defaults here are deliberately generous. |
| 165 |
|
| 166 |
A non-positive or non-finite budget is never a legitimate request: the race |
| 167 |
loop would run zero times and the test would report PASS without testing |
| 168 |
anything. runtests.py rejects that at the command line; ignoring it here too |
| 169 |
keeps the guarantee when race_timeout arrives straight from the environment. |
| 170 |
""" |
| 171 |
if _RACE_TIMEOUT_SET and math.isfinite(RACE_TIMEOUT) and RACE_TIMEOUT > 0: |
| 172 |
return RACE_TIMEOUT |
| 173 |
return default |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
all_plus = '+++++++++' |
| 180 |
allspace = ' ' |
| 181 |
dots = '.....' |
| 182 |
|
| 183 |
|
| 184 |
TMPDIR = SCRATCHDIR |
| 185 |
FROMDIR = SCRATCHDIR / 'from' |
| 186 |
TODIR = SCRATCHDIR / 'to' |
| 187 |
CHKDIR = SCRATCHDIR / 'chk' |
| 188 |
CHKFILE = SCRATCHDIR / 'rsync.chk' |
| 189 |
OUTFILE = SCRATCHDIR / 'rsync.out' |
| 190 |
|
| 191 |
|
| 192 |
|
| 193 |
|
| 194 |
def test_fail(msg: str) -> 'None': |
| 195 |
sys.stderr.write(msg.rstrip() + '\n') |
| 196 |
sys.exit(Exit.FAIL) |
| 197 |
|
| 198 |
|
| 199 |
def test_skipped(msg: str) -> 'None': |
| 200 |
sys.stderr.write(msg.rstrip() + '\n') |
| 201 |
(TMPDIR / 'whyskipped').write_text(msg.rstrip() + '\n') |
| 202 |
sys.exit(Exit.SKIP) |
| 203 |
|
| 204 |
|
| 205 |
def test_xfail(msg: str) -> 'None': |
| 206 |
sys.stderr.write(msg.rstrip() + '\n') |
| 207 |
sys.exit(Exit.XFAIL) |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
_PORT_LOCK_PATH = '/tmp/rsync_test.lck' |
| 215 |
_port_lock_fd = None |
| 216 |
_reaped_stale = False |
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
_PORT_PID_BASE = 1 << 16 |
| 226 |
_PORT_PID_REC = 8 |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
_LOCK_MAGIC = 0x9d4f2b8a |
| 235 |
|
| 236 |
|
| 237 |
def _open_lock_file() -> int: |
| 238 |
"""Open (or create) the host-wide port-lock file, defending against a |
| 239 |
local attacker who pre-plants the well-known /tmp path. CI runs some |
| 240 |
tests under sudo, so we must never let root open/chmod an attacker- |
| 241 |
controlled target. |
| 242 |
|
| 243 |
Strategy: |
| 244 |
* Try an O_EXCL|O_CREAT create. If we win, the file is brand-new, |
| 245 |
regular, owned by us and nlink==1 -- the ONLY case where we widen |
| 246 |
the mode to 0o666 (so a second user sharing the lock can open it |
| 247 |
RDWR; the create mode is otherwise narrowed by umask). |
| 248 |
* If it already exists, open it WITHOUT O_CREAT, WITHOUT chmod, and |
| 249 |
with O_NOFOLLOW so a planted symlink fails (ELOOP) rather than |
| 250 |
being followed. Then require a pristine regular file with nlink==1, |
| 251 |
rejecting a hard link to some other (e.g. root-owned 0600) file -- |
| 252 |
O_NOFOLLOW alone does not catch hard links. |
| 253 |
""" |
| 254 |
nofollow = getattr(os, 'O_NOFOLLOW', 0) |
| 255 |
|
| 256 |
|
| 257 |
try: |
| 258 |
fd = os.open(_PORT_LOCK_PATH, |
| 259 |
os.O_CREAT | os.O_EXCL | os.O_RDWR | nofollow, 0o666) |
| 260 |
except FileExistsError: |
| 261 |
fd = None |
| 262 |
if fd is not None: |
| 263 |
try: |
| 264 |
os.fchmod(fd, 0o666) |
| 265 |
except OSError: |
| 266 |
pass |
| 267 |
_check_or_write_magic(fd) |
| 268 |
return fd |
| 269 |
|
| 270 |
|
| 271 |
try: |
| 272 |
fd = os.open(_PORT_LOCK_PATH, os.O_RDWR | nofollow) |
| 273 |
except OSError as e: |
| 274 |
test_fail(f"cannot open lock file {_PORT_LOCK_PATH}: {e} " |
| 275 |
"(refusing to follow a symlink -- possible tampering)") |
| 276 |
st = os.fstat(fd) |
| 277 |
if not stat.S_ISREG(st.st_mode) or st.st_nlink != 1: |
| 278 |
os.close(fd) |
| 279 |
test_fail(f"lock file {_PORT_LOCK_PATH} is not a pristine regular " |
| 280 |
f"file (type/nlink check failed -- possible tampering)") |
| 281 |
_check_or_write_magic(fd) |
| 282 |
return fd |
| 283 |
|
| 284 |
|
| 285 |
def _check_or_write_magic(fd: int) -> 'None': |
| 286 |
"""Validate (or stamp) the layout-version magic in bytes 0..3. |
| 287 |
|
| 288 |
Serialise on the byte-0 lock (also port 0's lock byte, never a test port) so |
| 289 |
two starting runs don't race the stamp. An all-zero header is a fresh file -- |
| 290 |
write the magic. A non-zero header that doesn't match means a stale lock file |
| 291 |
from an incompatible testsuite layout (e.g. the old 4-byte pid records); error |
| 292 |
out so we never misread its records as (pgid, pid).""" |
| 293 |
fcntl.lockf(fd, fcntl.LOCK_EX, 4, 0) |
| 294 |
try: |
| 295 |
rec = os.pread(fd, 4, 0) |
| 296 |
cur = struct.unpack('=I', rec)[0] if len(rec) == 4 else 0 |
| 297 |
if cur == 0: |
| 298 |
os.pwrite(fd, struct.pack('=I', _LOCK_MAGIC), 0) |
| 299 |
elif cur != _LOCK_MAGIC: |
| 300 |
os.close(fd) |
| 301 |
test_fail(f"lock file {_PORT_LOCK_PATH} has layout magic " |
| 302 |
f"{cur:#010x}, expected {_LOCK_MAGIC:#010x} -- a stale file " |
| 303 |
"from an incompatible testsuite. Remove it and retry.") |
| 304 |
except (OSError, struct.error): |
| 305 |
pass |
| 306 |
finally: |
| 307 |
try: |
| 308 |
fcntl.lockf(fd, fcntl.LOCK_UN, 4, 0) |
| 309 |
except OSError: |
| 310 |
pass |
| 311 |
|
| 312 |
|
| 313 |
def _record_port_proc(port: int, pgid: int, pid: int) -> 'None': |
| 314 |
"""Record (or clear, with pgid==pid==0) the test process group and rsyncd pid |
| 315 |
bound to `port`. The caller holds the port's lock. The pgid reaps the whole |
| 316 |
test (daemon + clients + flipper) with one killpg; the pid is the recycle |
| 317 |
guard (_pid_is_rsync) so we only kill a group still running our rsync.""" |
| 318 |
if _port_lock_fd is None: |
| 319 |
return |
| 320 |
try: |
| 321 |
os.pwrite(_port_lock_fd, struct.pack('=ii', pgid, pid), |
| 322 |
_PORT_PID_BASE + port * _PORT_PID_REC) |
| 323 |
except (OSError, struct.error): |
| 324 |
pass |
| 325 |
|
| 326 |
|
| 327 |
def _read_port_proc(port: int) -> 'tuple': |
| 328 |
"""Read the recorded (pgid, pid) for `port`, or (0, 0) if none. Caller holds |
| 329 |
the lock. |
| 330 |
|
| 331 |
Normalises a pid <= 1 to (0, 0): a record holding 0 / negative / garbage must |
| 332 |
NEVER be treated as a real pid (os.kill/os.killpg of 0 or -N would signal a |
| 333 |
whole process group). Only pid > 1 is a candidate, and _pid_is_rsync() still |
| 334 |
verifies it before any kill.""" |
| 335 |
if _port_lock_fd is None: |
| 336 |
return (0, 0) |
| 337 |
try: |
| 338 |
rec = os.pread(_port_lock_fd, _PORT_PID_REC, |
| 339 |
_PORT_PID_BASE + port * _PORT_PID_REC) |
| 340 |
if len(rec) != _PORT_PID_REC: |
| 341 |
return (0, 0) |
| 342 |
pgid, pid = struct.unpack('=ii', rec) |
| 343 |
except (OSError, struct.error): |
| 344 |
return (0, 0) |
| 345 |
return (pgid, pid) if pid > 1 else (0, 0) |
| 346 |
|
| 347 |
|
| 348 |
def _pid_is_rsync(pid: int) -> bool: |
| 349 |
"""True if `pid` is a live process whose command is rsync. Guards against a |
| 350 |
recycled pid before we kill it. Tries `ps -p N -o comm=` (precise, Linux/BSD/ |
| 351 |
Solaris/macOS) and falls back to plain `ps -p N` (Cygwin's ps rejects -o but |
| 352 |
still prints the command). If neither confirms it, return False (leave the |
| 353 |
process alone).""" |
| 354 |
if pid <= 1: |
| 355 |
return False |
| 356 |
if pid == os.getpid(): |
| 357 |
return False |
| 358 |
try: |
| 359 |
os.kill(pid, 0) |
| 360 |
except OSError: |
| 361 |
return False |
| 362 |
for argv in (['ps', '-p', str(pid), '-o', 'comm='], ['ps', '-p', str(pid)]): |
| 363 |
try: |
| 364 |
r = subprocess.run(argv, stdout=subprocess.PIPE, |
| 365 |
stderr=subprocess.DEVNULL, text=True, timeout=5) |
| 366 |
except (OSError, subprocess.SubprocessError): |
| 367 |
return False |
| 368 |
if r.returncode == 0: |
| 369 |
return 'rsync' in r.stdout |
| 370 |
return False |
| 371 |
|
| 372 |
|
| 373 |
def _wait_pid_gone(pid: int, timeout: float) -> bool: |
| 374 |
"""Poll up to `timeout` seconds for `pid` to stop being a live rsync. |
| 375 |
|
| 376 |
SIGKILL is asynchronous: the process may still be visible for a moment |
| 377 |
after it is signalled, so a single immediate check would call a dying |
| 378 |
process "still alive".""" |
| 379 |
deadline = time.monotonic() + timeout |
| 380 |
while True: |
| 381 |
if not _pid_is_rsync(pid): |
| 382 |
return True |
| 383 |
if time.monotonic() >= deadline: |
| 384 |
return False |
| 385 |
time.sleep(0.1) |
| 386 |
|
| 387 |
|
| 388 |
def _reap_group(pgid: int, pid: int) -> bool: |
| 389 |
"""Kill the test's whole process group (daemon + its clients + flipper) when |
| 390 |
`pid` is still a live rsync -- the portable recycle guard, so we only ever |
| 391 |
signal a group still running our rsync. killpg(pgid) sweeps the group in one |
| 392 |
shot (the test driver runs in its own session, so the group is exactly that |
| 393 |
test's tree); if the pgid is unusable, fall back to killing the daemon pid |
| 394 |
alone. |
| 395 |
|
| 396 |
Returns True only when the daemon is CONFIRMED GONE, not merely when a |
| 397 |
signal was accepted. The caller clears the port's registry entry on a True |
| 398 |
return, and that entry is the only handle anyone has on the process; on |
| 399 |
Cygwin a signal is routinely accepted by a process that then ignores it, so |
| 400 |
trusting the accept would discard the record while the port stays squatted |
| 401 |
-- leaving an occupant nothing can identify or reap. |
| 402 |
|
| 403 |
The confirmation is a bounded poll, not a single immediate check: SIGKILL is |
| 404 |
asynchronous, so a process still winding down is normal and answering |
| 405 |
"not gone" for it would make _probe_bindable() skip its retry and fail the |
| 406 |
test for a port that was about to free itself.""" |
| 407 |
if not _pid_is_rsync(pid): |
| 408 |
return False |
| 409 |
try: |
| 410 |
if pgid > 1 and pgid != os.getpgrp(): |
| 411 |
os.killpg(pgid, signal.SIGKILL) |
| 412 |
else: |
| 413 |
os.kill(pid, signal.SIGKILL) |
| 414 |
except OSError: |
| 415 |
try: |
| 416 |
os.kill(pid, signal.SIGKILL) |
| 417 |
except OSError: |
| 418 |
pass |
| 419 |
if _wait_pid_gone(pid, 2.0): |
| 420 |
return True |
| 421 |
|
| 422 |
|
| 423 |
_win_force_kill(pid) |
| 424 |
return _wait_pid_gone(pid, 2.0) |
| 425 |
|
| 426 |
|
| 427 |
def _reap_orphan_daemon(port: int) -> bool: |
| 428 |
"""Kill an orphaned test process group squatting `port`, if we can identify it. |
| 429 |
|
| 430 |
We hold the claim_ports() exclusive lock for `port`, so nothing we coordinate |
| 431 |
with owns it -- a still-bound port is an orphan a SIGKILLed run stranded (off |
| 432 |
Linux there's no PR_SET_PDEATHSIG backstop, so its --no-detach rsyncd outlives |
| 433 |
the test). start_rsyncd recorded that test's (pgid, pid); if the pid is still a |
| 434 |
live rsync, killpg the group. Returns True if it signalled something (caller |
| 435 |
re-probes the bind). Pure os/ps calls -> every platform.""" |
| 436 |
pgid, pid = _read_port_proc(port) |
| 437 |
if not _reap_group(pgid, pid): |
| 438 |
return False |
| 439 |
_record_port_proc(port, 0, 0) |
| 440 |
time.sleep(0.2) |
| 441 |
return True |
| 442 |
|
| 443 |
|
| 444 |
def _reap_stale_daemons() -> 'None': |
| 445 |
"""Intra-run sweep: kill every orphaned test rsyncd recorded in the lock file |
| 446 |
whose port-lock is free (no live test owns it), and clear its record. |
| 447 |
|
| 448 |
_reap_orphan_daemon() only fires when a NEW test claims the *same* port an |
| 449 |
orphan still squats; a daemon a SIGKILLed/timed-out test stranded on a port |
| 450 |
nothing else re-claims would otherwise linger for the whole run (off Linux |
| 451 |
there's no PR_SET_PDEATHSIG backstop), accumulating and exhausting ports until |
| 452 |
a later race test wedges. This sweeps the whole pid registry so each test |
| 453 |
process reaps the leaks left by earlier ones. |
| 454 |
|
| 455 |
Run once per test process at the first claim_ports(), BEFORE this process has |
| 456 |
recorded any daemon of its own, so it never kills our own rsyncd. A port a |
| 457 |
live concurrent test holds keeps its byte-lock, so LOCK_NB skips it; only a |
| 458 |
free-locked port with a recorded live rsync pid is a genuine orphan.""" |
| 459 |
if _port_lock_fd is None: |
| 460 |
return |
| 461 |
try: |
| 462 |
size = os.fstat(_port_lock_fd).st_size |
| 463 |
except OSError: |
| 464 |
return |
| 465 |
if size <= _PORT_PID_BASE: |
| 466 |
return |
| 467 |
try: |
| 468 |
region = os.pread(_port_lock_fd, size - _PORT_PID_BASE, _PORT_PID_BASE) |
| 469 |
except OSError: |
| 470 |
return |
| 471 |
for port in range(min(len(region) // _PORT_PID_REC, 65536)): |
| 472 |
pgid, pid = struct.unpack('=ii', region[port*_PORT_PID_REC:(port+1)*_PORT_PID_REC]) |
| 473 |
if pid <= 1: |
| 474 |
continue |
| 475 |
|
| 476 |
try: |
| 477 |
fcntl.lockf(_port_lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 1, port) |
| 478 |
except OSError: |
| 479 |
continue |
| 480 |
try: |
| 481 |
if _reap_group(pgid, pid): |
| 482 |
_record_port_proc(port, 0, 0) |
| 483 |
finally: |
| 484 |
try: |
| 485 |
fcntl.lockf(_port_lock_fd, fcntl.LOCK_UN, 1, port) |
| 486 |
except OSError: |
| 487 |
pass |
| 488 |
|
| 489 |
|
| 490 |
def _probe_bindable(port: int, _reaped: bool = False, fatal: bool = True) -> bool: |
| 491 |
"""Confirm `port` is actually free once we hold its claim_ports() lock. |
| 492 |
|
| 493 |
The byte-range lock only coordinates *live* test drivers, and the kernel |
| 494 |
releases it the instant the holding process dies -- even if that driver left |
| 495 |
an orphaned daemon still bound to the port. That happens when a run is |
| 496 |
SIGKILLed (or its ssh drops) on a platform with no parent-death backstop: |
| 497 |
rsyncfns only arms PR_SET_PDEATHSIG, which is Linux-only, so on the |
| 498 |
BSDs/Solaris/macOS a killed fleettest run can strand its rsyncd, which then |
| 499 |
squats the fixed test port. Because we recorded that rsyncd's pid in the lock |
| 500 |
file (and hold the lock now, proving it's not a live run), we can reap it and |
| 501 |
retry rather than failing -- see _reap_orphan_daemon. |
| 502 |
|
| 503 |
So actually try to bind it. SO_REUSEADDR is used so a port merely in |
| 504 |
TIME_WAIT (recently and cleanly closed) is NOT a false positive; only a |
| 505 |
live bound/listening socket -- a real squatter -- makes the bind fail. The |
| 506 |
probe socket is closed immediately, freeing the port for the daemon that is |
| 507 |
about to bind it. |
| 508 |
""" |
| 509 |
s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) |
| 510 |
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) |
| 511 |
try: |
| 512 |
s.bind(('127.0.0.1', port)) |
| 513 |
return True |
| 514 |
except OSError as e: |
| 515 |
err = e |
| 516 |
finally: |
| 517 |
s.close() |
| 518 |
|
| 519 |
if not _reaped and _reap_orphan_daemon(port): |
| 520 |
return _probe_bindable(port, _reaped=True, fatal=fatal) |
| 521 |
if not fatal: |
| 522 |
return False |
| 523 |
test_fail( |
| 524 |
f"port {port} was claimed for this run but something is still bound " |
| 525 |
f"to 127.0.0.1:{port} ({err.strerror}). The claim_ports() lock only " |
| 526 |
"serializes live test runs, so a still-bound port almost always " |
| 527 |
"means an orphaned 'rsync --daemon' from a previously killed run " |
| 528 |
f"(find it with `fstat | grep {port}` / `netstat -an | grep {port}` " |
| 529 |
"and kill it, or run `fleettest.py --cleanup`), then retry.") |
| 530 |
return False |
| 531 |
|
| 532 |
|
| 533 |
def claim_ports(*ports: int) -> 'None': |
| 534 |
"""Reserve the given TCP port numbers for the rest of this process. |
| 535 |
|
| 536 |
Uses POSIX byte-range locks on /tmp/rsync_test.lck (one byte per port, |
| 537 |
offset = port number) so that any number of tests can run in parallel |
| 538 |
without colliding on a port: if another test has already claimed any of |
| 539 |
the requested ports the call blocks until that test exits. The kernel |
| 540 |
drops POSIX advisory locks automatically when the holding process |
| 541 |
terminates, so a crashed test releases its ports without manual |
| 542 |
cleanup. |
| 543 |
|
| 544 |
Ports are claimed in sorted order, so two callers that ask for the same |
| 545 |
set in different orders can't deadlock against each other. |
| 546 |
|
| 547 |
Call once near the top of any test that binds to a specific TCP port, |
| 548 |
BEFORE the bind: |
| 549 |
|
| 550 |
from rsyncfns import claim_ports |
| 551 |
claim_ports(12873) |
| 552 |
listener = socket.socket(...) |
| 553 |
listener.bind(('127.0.0.1', 12873)) |
| 554 |
|
| 555 |
The lock file lives in /tmp so it's shared across all rsync test |
| 556 |
processes on the host. Ports outside the claim_ports() ecosystem are |
| 557 |
not protected -- nothing stops an unrelated process from binding the |
| 558 |
port. For the rsync testsuite that's fine; we just need to avoid |
| 559 |
collisions between concurrent test scripts. |
| 560 |
""" |
| 561 |
global _port_lock_fd, _reaped_stale |
| 562 |
if _port_lock_fd is None: |
| 563 |
_port_lock_fd = _open_lock_file() |
| 564 |
if not _reaped_stale: |
| 565 |
|
| 566 |
|
| 567 |
_reaped_stale = True |
| 568 |
_reap_stale_daemons() |
| 569 |
for port in sorted(ports): |
| 570 |
|
| 571 |
|
| 572 |
fcntl.lockf(_port_lock_fd, fcntl.LOCK_EX, 1, port) |
| 573 |
|
| 574 |
|
| 575 |
_probe_bindable(port) |
| 576 |
|
| 577 |
|
| 578 |
def claim_free_port(preferred: int) -> int: |
| 579 |
"""Claim `preferred`, or a nearby port if something else is squatting it. |
| 580 |
|
| 581 |
claim_ports() fails loudly on an occupied port, which is right for a test |
| 582 |
that binds the port itself: it must not silently drift away from the number |
| 583 |
it is about to bind. start_test_daemon() owns both the bind and the URL it |
| 584 |
hands back, so it can simply move instead -- and needs to, because a fixed |
| 585 |
test port can be permanently held by unrelated software on a shared CI box |
| 586 |
(a vendor service was found sitting on 13010 on the Windows/Cygwin target), |
| 587 |
which no amount of orphan reaping will free. |
| 588 |
|
| 589 |
Returns the port actually claimed. |
| 590 |
""" |
| 591 |
global _port_lock_fd, _reaped_stale |
| 592 |
if _port_lock_fd is None: |
| 593 |
_port_lock_fd = _open_lock_file() |
| 594 |
if not _reaped_stale: |
| 595 |
_reaped_stale = True |
| 596 |
_reap_stale_daemons() |
| 597 |
candidates = [preferred] + [preferred + off for off in (1000, 2000, 3000, 4000)] |
| 598 |
for port in candidates: |
| 599 |
if not 1024 < port < 65536: |
| 600 |
continue |
| 601 |
fcntl.lockf(_port_lock_fd, fcntl.LOCK_EX, 1, port) |
| 602 |
if _probe_bindable(port, fatal=False): |
| 603 |
return port |
| 604 |
test_fail( |
| 605 |
f"no usable TCP port near {preferred}: every candidate " |
| 606 |
f"({', '.join(str(p) for p in candidates)}) is bound by something " |
| 607 |
"outside the testsuite. Check with `netstat -an` and free one, or " |
| 608 |
"run `fleettest.py --cleanup` if they are stranded test daemons.") |
| 609 |
return preferred |
| 610 |
|
| 611 |
|
| 612 |
|
| 613 |
|
| 614 |
def _set_pdeathsig() -> 'None': |
| 615 |
"""Linux: ask the kernel to send SIGTERM to us if our parent dies. |
| 616 |
A no-op on every other platform. Used as preexec_fn so a kill -9 of |
| 617 |
the test process doesn't strand the rsyncd we spawned. |
| 618 |
|
| 619 |
The daemon deliberately stays in the TEST's process group: runtests.py |
| 620 |
killpg's that group when a test times out, and that is what keeps a |
| 621 |
timed-out test from stranding its daemon. Giving the daemon a group of |
| 622 |
its own would put it out of reach of that sweep; its per-connection |
| 623 |
children are handled by _daemon_children() instead.""" |
| 624 |
if not sys.platform.startswith('linux'): |
| 625 |
return |
| 626 |
try: |
| 627 |
import ctypes |
| 628 |
libc = ctypes.CDLL('libc.so.6', use_errno=True) |
| 629 |
PR_SET_PDEATHSIG = 1 |
| 630 |
libc.prctl(PR_SET_PDEATHSIG, 15, 0, 0, 0) |
| 631 |
except OSError: |
| 632 |
pass |
| 633 |
|
| 634 |
|
| 635 |
def _win_force_kill(pid: int) -> 'None': |
| 636 |
"""Cygwin last resort: terminate `pid` through Windows. |
| 637 |
|
| 638 |
Cygwin signals are cooperative -- delivered via a helper thread in the |
| 639 |
target -- so a process sitting in a Windows call ignores even SIGKILL. |
| 640 |
Such a process keeps its listening socket and cannot be reaped by any |
| 641 |
amount of kill/killpg/pkill. Map the cygwin pid to its Windows pid (the |
| 642 |
4th column of `ps -W`) and let Windows do it. A no-op elsewhere.""" |
| 643 |
if not sys.platform.startswith('cygwin'): |
| 644 |
return |
| 645 |
try: |
| 646 |
r = subprocess.run(['ps', '-W'], capture_output=True, text=True, timeout=10) |
| 647 |
except (OSError, subprocess.SubprocessError): |
| 648 |
return |
| 649 |
for line in r.stdout.splitlines(): |
| 650 |
f = line.split() |
| 651 |
if len(f) >= 4 and f[0] == str(pid): |
| 652 |
try: |
| 653 |
subprocess.run(['taskkill', '/F', '/PID', f[3]], |
| 654 |
capture_output=True, timeout=10) |
| 655 |
except (OSError, subprocess.SubprocessError): |
| 656 |
pass |
| 657 |
return |
| 658 |
|
| 659 |
|
| 660 |
def _daemon_children(pid: int) -> list: |
| 661 |
"""PIDs whose parent is `pid` -- the connection handlers rsyncd forked. |
| 662 |
|
| 663 |
Cygwin's ps understands neither -A nor -o, but `ps -W` prints |
| 664 |
PID PPID PGID WINPID as its first four columns; everywhere else POSIX |
| 665 |
`ps -A -o pid=,ppid=` does the job. Returns [] if neither works: the |
| 666 |
caller then just kills the parent, which is the old behaviour.""" |
| 667 |
argv = (['ps', '-W'] if sys.platform.startswith('cygwin') |
| 668 |
else ['ps', '-A', '-o', 'pid=,ppid=']) |
| 669 |
try: |
| 670 |
r = subprocess.run(argv, capture_output=True, text=True, timeout=10) |
| 671 |
except (OSError, subprocess.SubprocessError): |
| 672 |
return [] |
| 673 |
kids = [] |
| 674 |
for line in r.stdout.splitlines(): |
| 675 |
f = line.split() |
| 676 |
if len(f) >= 2 and f[1] == str(pid): |
| 677 |
try: |
| 678 |
kids.append(int(f[0])) |
| 679 |
except ValueError: |
| 680 |
pass |
| 681 |
return kids |
| 682 |
|
| 683 |
|
| 684 |
def _kill_pid(pid: int) -> 'None': |
| 685 |
"""SIGTERM, then SIGKILL, then -- on Cygwin -- Windows. |
| 686 |
|
| 687 |
Gated on _pid_is_rsync at every step: these pids were snapshotted before the |
| 688 |
parent was killed, so between the snapshot and the signal a child can exit |
| 689 |
and the kernel can hand its pid to something else. Re-checking that the pid |
| 690 |
is STILL a live rsync before each signal keeps a recycled pid from getting |
| 691 |
the harness to kill an unrelated process. |
| 692 |
|
| 693 |
KNOWN LIMITATION: check-then-signal is inherently a TOCTOU, so the window is |
| 694 |
narrowed to microseconds rather than closed -- the pid would have to be |
| 695 |
recycled onto ANOTHER rsync in that gap to matter. Closing it properly needs |
| 696 |
a stable process reference (pidfd, or a retained Windows handle), which is |
| 697 |
per-platform machinery this suite has to run on seven of; the same guard is |
| 698 |
what _reap_group() has always used.""" |
| 699 |
for sig in (signal.SIGTERM, signal.SIGKILL): |
| 700 |
if not _pid_is_rsync(pid): |
| 701 |
return |
| 702 |
try: |
| 703 |
os.kill(pid, sig) |
| 704 |
except OSError: |
| 705 |
return |
| 706 |
time.sleep(0.3) |
| 707 |
if _pid_is_rsync(pid): |
| 708 |
_win_force_kill(pid) |
| 709 |
|
| 710 |
|
| 711 |
def _stop_rsyncd(proc) -> 'None': |
| 712 |
"""Stop the test daemon AND the connection handlers it forked. |
| 713 |
|
| 714 |
Killing proc alone -- the only pid the Popen handle knows -- is what left |
| 715 |
the orphan: rsyncd forks a child per connection, and one still winding up |
| 716 |
or down when the test ends outlives the parent, inherits the listening |
| 717 |
socket and squats the port. Snapshot the children BEFORE killing the |
| 718 |
parent, because once it is gone they are reparented to init and no longer |
| 719 |
identifiable as ours. |
| 720 |
|
| 721 |
KNOWN LIMITATION: that is also why nothing is collected when the parent has |
| 722 |
ALREADY exited on its own (it crashed, say) while a child still holds the |
| 723 |
port -- by then the parent-child link this relies on is gone. The runner's |
| 724 |
per-test-timeout killpg covers the common case, since the daemon stays in |
| 725 |
the test's process group; `fleettest.py --cleanup` sweeps the rest.""" |
| 726 |
if proc.poll() is not None: |
| 727 |
return |
| 728 |
kids = _daemon_children(proc.pid) |
| 729 |
try: |
| 730 |
proc.terminate() |
| 731 |
proc.wait(timeout=2) |
| 732 |
except subprocess.TimeoutExpired: |
| 733 |
try: |
| 734 |
proc.kill() |
| 735 |
proc.wait(timeout=1) |
| 736 |
except (subprocess.TimeoutExpired, OSError): |
| 737 |
pass |
| 738 |
_win_force_kill(proc.pid) |
| 739 |
except OSError: |
| 740 |
pass |
| 741 |
for kid in kids: |
| 742 |
_kill_pid(kid) |
| 743 |
|
| 744 |
|
| 745 |
def _cleanup_rsyncd(proc, port: int) -> 'None': |
| 746 |
"""atexit handler: stop the daemon and clear its pid slot. A clean exit thus |
| 747 |
leaves no orphan to reap; only a SIGKILL (which skips atexit) leaves the slot |
| 748 |
set -- exactly the case _reap_orphan_daemon() needs it for. |
| 749 |
|
| 750 |
The slot is kept only while it still NAMES something reapable -- i.e. our |
| 751 |
daemon pid is somehow still a live rsync, which on Cygwin means it ignored |
| 752 |
the kill. That is the only case where the record buys a later run anything. |
| 753 |
|
| 754 |
Keying this on the port being busy instead looks safer but is worse: a port |
| 755 |
sits in TIME_WAIT after a passing test, so a plain bind fails and a record |
| 756 |
naming an already-dead pid is retained forever. Nothing ever clears such a |
| 757 |
record, and if that pid is later recycled onto an unrelated rsync the stale |
| 758 |
sweep would signal it. A record naming a dead process cannot help anyone -- |
| 759 |
every reaper rejects it at the _pid_is_rsync guard -- so clearing it is |
| 760 |
strictly better. |
| 761 |
|
| 762 |
KNOWN LIMITATION: if the daemon parent died on its own while a connection |
| 763 |
child still held the port, that child is unreachable either way -- the |
| 764 |
record only ever named the parent. `fleettest.py --cleanup` sweeps it.""" |
| 765 |
_stop_rsyncd(proc) |
| 766 |
if not _pid_is_rsync(proc.pid): |
| 767 |
_record_port_proc(port, 0, 0) |
| 768 |
|
| 769 |
|
| 770 |
def start_rsyncd(conf_path, port: int, rsync_cmd: str = None) -> 'subprocess.Popen': |
| 771 |
"""Spawn `rsync --daemon --no-detach --address=127.0.0.1 --port=N |
| 772 |
--config=conf` and return the Popen handle after the port is accepting |
| 773 |
connections. |
| 774 |
|
| 775 |
The daemon is bound to LOOPBACK ONLY (--address=127.0.0.1): without it, |
| 776 |
rsync --daemon binds 0.0.0.0 and the test modules would be reachable from |
| 777 |
the whole LAN. The daemon is killed automatically when this Python |
| 778 |
process exits (atexit). On Linux, the kernel also signals SIGTERM to the |
| 779 |
daemon if the parent dies abruptly (PR_SET_PDEATHSIG), so a SIGKILL on |
| 780 |
the test process doesn't strand the daemon either. The caller is expected |
| 781 |
to have already claim_ports()'d `port`. |
| 782 |
|
| 783 |
rsync_cmd selects the binary to run as the daemon; it defaults to |
| 784 |
RSYNC_PEER (the peer side of a two-sided run), so ordinary daemon tests |
| 785 |
get current-client <-> peer-daemon. The reverse-direction test passes |
| 786 |
rsync_cmd=RSYNC to put the current build on the daemon side and drive with |
| 787 |
the old client. |
| 788 |
|
| 789 |
This is only ever reached from start_test_daemon() in --use-tcp mode; the |
| 790 |
default (pipe) mode never starts a listening daemon. |
| 791 |
""" |
| 792 |
argv = shlex.split(rsync_cmd or RSYNC_PEER) + [ |
| 793 |
'--daemon', '--no-detach', |
| 794 |
'--address=127.0.0.1', |
| 795 |
f'--port={port}', |
| 796 |
f'--config={conf_path}', |
| 797 |
] |
| 798 |
proc = subprocess.Popen( |
| 799 |
argv, |
| 800 |
stdin=subprocess.DEVNULL, |
| 801 |
stdout=subprocess.DEVNULL, |
| 802 |
stderr=subprocess.DEVNULL, |
| 803 |
preexec_fn=_set_pdeathsig, |
| 804 |
) |
| 805 |
|
| 806 |
|
| 807 |
|
| 808 |
|
| 809 |
_record_port_proc(port, os.getpgrp(), proc.pid) |
| 810 |
atexit.register(_cleanup_rsyncd, proc, port) |
| 811 |
|
| 812 |
deadline = time.monotonic() + 10 |
| 813 |
last_err = None |
| 814 |
while time.monotonic() < deadline: |
| 815 |
if proc.poll() is not None: |
| 816 |
test_fail( |
| 817 |
f"rsyncd exited before listening on port {port} " |
| 818 |
f"(status={proc.returncode})" |
| 819 |
) |
| 820 |
try: |
| 821 |
with _socket.create_connection(('127.0.0.1', port), timeout=0.5): |
| 822 |
return proc |
| 823 |
except OSError as e: |
| 824 |
last_err = e |
| 825 |
time.sleep(0.05) |
| 826 |
|
| 827 |
_stop_rsyncd(proc) |
| 828 |
test_fail(f"rsyncd never listened on 127.0.0.1:{port}: {last_err}") |
| 829 |
|
| 830 |
|
| 831 |
def start_test_daemon(conf_path, port: int, rsync_cmd: str = None) -> str: |
| 832 |
"""Bring up the test daemon and return a URL prefix for client commands. |
| 833 |
|
| 834 |
rsync_cmd selects the daemon-side binary (default RSYNC_PEER); pass |
| 835 |
rsync_cmd=RSYNC for the reverse-direction test (current daemon, old client). |
| 836 |
|
| 837 |
This is the single seam every daemon test uses. The transport depends on |
| 838 |
the mode the runner selected: |
| 839 |
|
| 840 |
* DEFAULT (secure) -- no TCP socket at all. Sets RSYNC_CONNECT_PROG so |
| 841 |
the rsync client forks the daemon over a private stdio pipe. Returns |
| 842 |
'rsync://localhost/'. Another local user can't reach it; nothing is |
| 843 |
listening. |
| 844 |
|
| 845 |
* --use-tcp -- starts a real rsyncd bound to 127.0.0.1 on the given |
| 846 |
claim_ports()-reserved port. Returns 'rsync://localhost:PORT/'. Bound |
| 847 |
to loopback so off-host/LAN access is impossible; a same-host user |
| 848 |
could still connect during the test window, which is the documented, |
| 849 |
accepted cost of explicitly opting into TCP. |
| 850 |
|
| 851 |
Build URLs as f"{prefix}module/path". `port` is only used (and claimed) |
| 852 |
in --use-tcp mode. |
| 853 |
""" |
| 854 |
daemon_cmd = rsync_cmd or RSYNC_PEER |
| 855 |
if USE_TCP: |
| 856 |
port = claim_free_port(port) |
| 857 |
start_rsyncd(conf_path, port, daemon_cmd) |
| 858 |
return f'rsync://localhost:{port}/' |
| 859 |
|
| 860 |
|
| 861 |
os.environ['RSYNC_CONNECT_PROG'] = ( |
| 862 |
f'{rsync_path_arg(daemon_cmd)} --config={shlex.quote(str(conf_path))} --daemon') |
| 863 |
return 'rsync://localhost/' |
| 864 |
|
| 865 |
|
| 866 |
def require_tcp(reason: str) -> 'None': |
| 867 |
"""Skip the test (exit 77) unless we're in --use-tcp mode. For tests that |
| 868 |
fundamentally need a real listening socket / TCP peer and have no secure |
| 869 |
pipe equivalent (the fake-proxy listener; the reverse-DNS hostname-ACL |
| 870 |
daemon test).""" |
| 871 |
if not USE_TCP: |
| 872 |
test_skipped(reason) |
| 873 |
|
| 874 |
|
| 875 |
def require_asan(reason: str, which: str = None) -> 'None': |
| 876 |
"""Skip the test (exit 77) unless the rsync binary is AddressSanitizer- |
| 877 |
instrumented. `which` defaults to the daemon/peer command (RSYNC_PEER); |
| 878 |
pass RSYNC to check the client side. Detection runs the binary with |
| 879 |
ASAN_OPTIONS=help=1, which makes an instrumented binary print the ASan |
| 880 |
flag help banner to stderr.""" |
| 881 |
cmd = split_rsync_cmd(which or RSYNC_PEER) |
| 882 |
try: |
| 883 |
r = subprocess.run(cmd + ['--version'], |
| 884 |
env={**os.environ, 'ASAN_OPTIONS': 'help=1'}, |
| 885 |
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, |
| 886 |
timeout=15) |
| 887 |
except Exception: |
| 888 |
test_skipped(reason) |
| 889 |
return |
| 890 |
if b'AddressSanitizer' not in r.stderr: |
| 891 |
test_skipped(reason) |
| 892 |
|
| 893 |
|
| 894 |
def rsh_cmd(cmd: str = None, *opts: str) -> str: |
| 895 |
"""Build an RSYNC_RSH / --rsh value, quoted for rsync's own tokenizer. |
| 896 |
|
| 897 |
rsync splits this string on spaces itself -- honouring ' and ", see do_cmd() |
| 898 |
in main.c -- so a remote-shell path containing a space must be quoted or |
| 899 |
rsync execs only the first word. The testsuite's srcdir can contain one. |
| 900 |
""" |
| 901 |
if cmd is None: |
| 902 |
cmd = str(SRCDIR / 'support' / 'lsh.sh') |
| 903 |
return ' '.join([shlex.quote(cmd), *opts]) |
| 904 |
|
| 905 |
|
| 906 |
def rsync_path_arg(cmd: str = None) -> str: |
| 907 |
"""Value for --rsync-path, quoted for the shell that will re-parse it. |
| 908 |
|
| 909 |
--rsync-path is a command line run by the remote shell, not a filename, so |
| 910 |
rsync hands it over unquoted and the far side word-splits it. A build path |
| 911 |
containing a space therefore needs quoting here, while a wrapper command |
| 912 |
('valgrind ... /build/rsync') must stay several words. Splitting and |
| 913 |
re-joining with shlex gives both: each word is quoted only if it needs it. |
| 914 |
""" |
| 915 |
return shlex.join(split_rsync_cmd(RSYNC_PEER if cmd is None else cmd)) |
| 916 |
|
| 917 |
|
| 918 |
def rsync_argv(*args: str) -> list: |
| 919 |
"""Return the argv for invoking rsync with the given extra arguments. |
| 920 |
|
| 921 |
RSYNC may be a multi-word command (e.g. 'valgrind ... /build/rsync'); we |
| 922 |
shlex-split it so subprocess sees a proper argv list. Each *args entry |
| 923 |
is appended verbatim, so callers should pass tokens already split (no |
| 924 |
embedded option/value joined by spaces). |
| 925 |
""" |
| 926 |
return split_rsync_cmd(RSYNC) + list(args) |
| 927 |
|
| 928 |
|
| 929 |
import functools as _functools |
| 930 |
|
| 931 |
|
| 932 |
@_functools.lru_cache(maxsize=64) |
| 933 |
def rsync_supports(flag: str) -> bool: |
| 934 |
"""Does the configured rsync binary accept ``flag``? |
| 935 |
|
| 936 |
Probes by invoking ``rsync <flag> --version`` and checking the exit code + |
| 937 |
stderr. C rsync accepts every flag we'd care about and exits 0 before |
| 938 |
--version prints; other implementations (gokrazy/rsync, openrsync) reject |
| 939 |
unsupported flags with "unknown option" / "unrecognized option" / |
| 940 |
"no such option" and a non-zero exit. |
| 941 |
|
| 942 |
Used by tests that want to *optionally* pass a hardening flag like |
| 943 |
`--no-inc-recursive` (only meaningful where the implementation has |
| 944 |
incremental recursion to disable). When the probe is inconclusive (e.g. |
| 945 |
timeout) the helper returns True so tests fall back to today's C-rsync |
| 946 |
behaviour. |
| 947 |
""" |
| 948 |
try: |
| 949 |
r = subprocess.run(rsync_argv(flag, '--version'), |
| 950 |
capture_output=True, text=True, timeout=5) |
| 951 |
except (subprocess.TimeoutExpired, OSError): |
| 952 |
return True |
| 953 |
if r.returncode == 0: |
| 954 |
return True |
| 955 |
stderr = (r.stderr or '').lower() |
| 956 |
for marker in ('unknown option', 'unrecognized option', 'no such option'): |
| 957 |
if marker in stderr: |
| 958 |
return False |
| 959 |
|
| 960 |
return True |
| 961 |
|
| 962 |
|
| 963 |
def forced_protocol(): |
| 964 |
"""The protocol version pinned via --protocol=N in the RSYNC command, or |
| 965 |
None when the run isn't pinning one (so the binary negotiates its newest). |
| 966 |
Protocol-sensitive tests use this to gate sub-cases -- e.g. the split |
| 967 |
between --append and --append-verify only exists at protocol >= 30; at |
| 968 |
protocol 29 plain --append behaves like the old verifying append.""" |
| 969 |
import re |
| 970 |
m = re.search(r'--protocol[ =](\d+)', RSYNC) |
| 971 |
return int(m.group(1)) if m else None |
| 972 |
|
| 973 |
|
| 974 |
def run_rsync(*args: str, check: bool = True, |
| 975 |
capture_output: bool = False) -> subprocess.CompletedProcess: |
| 976 |
"""Run rsync with the given arguments. |
| 977 |
|
| 978 |
By default, stdout/stderr inherit (so the runner captures them in the |
| 979 |
per-test log). Set capture_output=True if the test needs to inspect the |
| 980 |
output. If check is True (the default), a non-zero exit calls |
| 981 |
test_fail() with the rsync command line. |
| 982 |
""" |
| 983 |
argv = rsync_argv(*args) |
| 984 |
if capture_output: |
| 985 |
proc = subprocess.run(argv, capture_output=True, text=True) |
| 986 |
else: |
| 987 |
proc = subprocess.run(argv) |
| 988 |
if check and proc.returncode != 0: |
| 989 |
test_fail(f"rsync exited {proc.returncode}: {' '.join(argv)}") |
| 990 |
return proc |
| 991 |
|
| 992 |
|
| 993 |
|
| 994 |
|
| 995 |
def makepath(*paths) -> 'None': |
| 996 |
"""Equivalent of rsync.fns makepath: mkdir -p, but for multiple paths.""" |
| 997 |
for p in paths: |
| 998 |
os.makedirs(p, exist_ok=True) |
| 999 |
|
| 1000 |
|
| 1001 |
def rmtree(path) -> 'None': |
| 1002 |
"""Remove a tree if it exists, ignoring missing entries.""" |
| 1003 |
p = Path(path) |
| 1004 |
if p.exists() or p.is_symlink(): |
| 1005 |
shutil.rmtree(p, ignore_errors=True) |
| 1006 |
|
| 1007 |
|
| 1008 |
def is_a_link(path) -> bool: |
| 1009 |
"""True if 'path' is a symbolic link (dangling or not).""" |
| 1010 |
return os.path.islink(path) |
| 1011 |
|
| 1012 |
|
| 1013 |
def start_path_flipper(name_a, name_b): |
| 1014 |
"""Spawn a separate PROCESS that repeatedly swaps two sibling paths |
| 1015 |
name_a <-> name_b in a tight rename loop, for TOCTOU symlink-race tests: |
| 1016 |
point one at a real directory and the other at a symlink so the shared name |
| 1017 |
keeps flipping between a directory and a symlink under a running rsync. |
| 1018 |
|
| 1019 |
A separate process (not a thread) is used deliberately: a Python thread |
| 1020 |
contends with the test's own loop for the GIL and flips far too slowly to |
| 1021 |
win the race. The swap is three renames via a scratch name in the same |
| 1022 |
directory, so the shared name is absent only for the brief instant between |
| 1023 |
two renames (rsync just gets ENOENT and retries). |
| 1024 |
|
| 1025 |
The caller should stop it with stop_flipper(), but the flipper also |
| 1026 |
self-terminates: it exits when its parent (the test process) goes away -- |
| 1027 |
os.getppid() changes once the test is reaped -- and after a hard deadline as a |
| 1028 |
backstop. Without this, a test killed before its stop_flipper() finally (a |
| 1029 |
timeout, a crash) would leak an orphan that keeps renaming paths in the shared |
| 1030 |
scratch and poisons later tests on the same box. os.getppid() is POSIX, so |
| 1031 |
this is portable across the fleet. |
| 1032 |
|
| 1033 |
Returns a subprocess.Popen; the caller must stop it with stop_flipper().""" |
| 1034 |
code = ( |
| 1035 |
"import os, sys, time\n" |
| 1036 |
"a, b = sys.argv[1], sys.argv[2]\n" |
| 1037 |
"tmp = a + '.flip'\n" |
| 1038 |
"parent = os.getppid()\n" |
| 1039 |
"deadline = time.monotonic() + 300\n" |
| 1040 |
"while os.getppid() == parent and time.monotonic() < deadline:\n" |
| 1041 |
" try:\n" |
| 1042 |
" os.rename(a, tmp); os.rename(b, a); os.rename(tmp, b)\n" |
| 1043 |
" except OSError:\n" |
| 1044 |
" pass\n" |
| 1045 |
) |
| 1046 |
return subprocess.Popen([sys.executable, '-c', code, str(name_a), str(name_b)]) |
| 1047 |
|
| 1048 |
|
| 1049 |
def stop_flipper(proc): |
| 1050 |
"""Stop a start_path_flipper()/start_c_flipper() process.""" |
| 1051 |
proc.terminate() |
| 1052 |
try: |
| 1053 |
proc.wait(timeout=2) |
| 1054 |
except subprocess.TimeoutExpired: |
| 1055 |
proc.kill() |
| 1056 |
proc.wait() |
| 1057 |
|
| 1058 |
|
| 1059 |
|
| 1060 |
|
| 1061 |
|
| 1062 |
|
| 1063 |
|
| 1064 |
|
| 1065 |
_C_FLIPPER_SRC = r''' |
| 1066 |
/* testsuite flipper: repeatedly swap two sibling names a<->b so a shared path |
| 1067 |
* keeps flipping (typically real-dir <-> symlink) under a running rsync. |
| 1068 |
* Prefers atomic renameat2(RENAME_EXCHANGE); falls back to a 3-rename dance. |
| 1069 |
* Self-terminates when its parent (the test) goes away, plus a deadline |
| 1070 |
* backstop, so a killed test never leaks an orphan that poisons later tests. |
| 1071 |
* Built on demand by rsyncfns.compile_c_flipper(); not linked into rsync. */ |
| 1072 |
#define _GNU_SOURCE 1 |
| 1073 |
#include "config.h" |
| 1074 |
#include <stdio.h> |
| 1075 |
#include <stdlib.h> |
| 1076 |
#include <string.h> |
| 1077 |
#include <unistd.h> |
| 1078 |
#include <fcntl.h> |
| 1079 |
#include <errno.h> |
| 1080 |
#include <time.h> |
| 1081 |
#include <sys/stat.h> |
| 1082 |
#if defined(__linux__) |
| 1083 |
# include <sys/syscall.h> |
| 1084 |
# ifndef RENAME_EXCHANGE |
| 1085 |
# define RENAME_EXCHANGE (1 << 1) |
| 1086 |
# endif |
| 1087 |
#endif |
| 1088 |
|
| 1089 |
static double mono(void) { |
| 1090 |
struct timespec t; |
| 1091 |
clock_gettime(CLOCK_MONOTONIC, &t); |
| 1092 |
return t.tv_sec + t.tv_nsec / 1e9; |
| 1093 |
} |
| 1094 |
|
| 1095 |
static int use_exchange = 1; |
| 1096 |
|
| 1097 |
static void flip(const char *a, const char *b) { |
| 1098 |
#if defined(__linux__) && defined(SYS_renameat2) |
| 1099 |
if (use_exchange) { |
| 1100 |
if (syscall(SYS_renameat2, AT_FDCWD, a, AT_FDCWD, b, RENAME_EXCHANGE) == 0) |
| 1101 |
return; |
| 1102 |
if (errno == ENOSYS || errno == EINVAL || errno == EOPNOTSUPP) |
| 1103 |
use_exchange = 0; /* kernel or filesystem lacks EXCHANGE */ |
| 1104 |
else |
| 1105 |
return; /* transient race error (e.g. ENOENT): retry */ |
| 1106 |
} |
| 1107 |
#endif |
| 1108 |
{ |
| 1109 |
char tmp[4096]; |
| 1110 |
if (snprintf(tmp, sizeof tmp, "%s.flip", a) >= (int)sizeof tmp) |
| 1111 |
return; /* too long: don't act on a truncated name */ |
| 1112 |
rmdir(tmp); unlink(tmp); /* clear a stale scratch from a wedged half-swap */ |
| 1113 |
if (rename(a, tmp) != 0) { |
| 1114 |
mkdir(a, 0700); /* a was consumed: recreate so the next loop swaps */ |
| 1115 |
return; |
| 1116 |
} |
| 1117 |
if (rename(b, a) != 0) |
| 1118 |
rename(tmp, a); /* b gone: restore a, retry next loop */ |
| 1119 |
else |
| 1120 |
rename(tmp, b); /* complete the swap */ |
| 1121 |
} |
| 1122 |
} |
| 1123 |
|
| 1124 |
int main(int argc, char **argv) { |
| 1125 |
if (argc < 3) { |
| 1126 |
fprintf(stderr, "usage: %s PATH_A PATH_B\n", argv[0]); |
| 1127 |
return 2; |
| 1128 |
} |
| 1129 |
const char *a = argv[1], *b = argv[2]; |
| 1130 |
pid_t parent = getppid(); |
| 1131 |
double deadline = mono() + 300.0; /* backstop if never reaped */ |
| 1132 |
while (getppid() == parent && mono() < deadline) |
| 1133 |
flip(a, b); |
| 1134 |
return 0; |
| 1135 |
} |
| 1136 |
''' |
| 1137 |
|
| 1138 |
_c_flipper_bin = None |
| 1139 |
|
| 1140 |
|
| 1141 |
def _detect_cc(): |
| 1142 |
"""The C compiler the tree was built with (so the flipper matches the |
| 1143 |
target), falling back to a plain cc/gcc/clang on PATH.""" |
| 1144 |
cc = os.environ.get('CC') |
| 1145 |
if cc: |
| 1146 |
return cc |
| 1147 |
import re |
| 1148 |
|
| 1149 |
|
| 1150 |
for d in (TOOLDIR, SRCDIR): |
| 1151 |
mk = d / 'Makefile' |
| 1152 |
if mk.is_file(): |
| 1153 |
m = re.search(r'(?m)^CC\s*=\s*(.+?)\s*$', mk.read_text()) |
| 1154 |
if m and m.group(1): |
| 1155 |
return m.group(1) |
| 1156 |
for c in ('cc', 'gcc', 'clang'): |
| 1157 |
if shutil.which(c): |
| 1158 |
return c |
| 1159 |
return None |
| 1160 |
|
| 1161 |
|
| 1162 |
def compile_c_flipper(): |
| 1163 |
"""Build (once, cached) the C flipper against the build's config.h. Returns |
| 1164 |
its path, or None if no compiler is available (caller uses the Python flipper).""" |
| 1165 |
global _c_flipper_bin |
| 1166 |
if _c_flipper_bin is not None: |
| 1167 |
return _c_flipper_bin or None |
| 1168 |
cc = _detect_cc() |
| 1169 |
src = SCRATCHDIR / 't_flipper.c' |
| 1170 |
out = SCRATCHDIR / ('t_flipper' + ('.exe' if os.name == 'nt' else '')) |
| 1171 |
if not cc: |
| 1172 |
_c_flipper_bin = '' |
| 1173 |
return None |
| 1174 |
src.write_text(_C_FLIPPER_SRC) |
| 1175 |
|
| 1176 |
|
| 1177 |
cmd = (shlex.split(cc) |
| 1178 |
+ ['-O2', f'-I{TOOLDIR}', f'-I{SRCDIR}', '-o', str(out), str(src)]) |
| 1179 |
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, |
| 1180 |
text=True) |
| 1181 |
if proc.returncode != 0 or not os.access(out, os.X_OK): |
| 1182 |
_c_flipper_bin = '' |
| 1183 |
return None |
| 1184 |
_c_flipper_bin = str(out) |
| 1185 |
return _c_flipper_bin |
| 1186 |
|
| 1187 |
|
| 1188 |
def start_c_flipper(name_a, name_b): |
| 1189 |
"""Like start_path_flipper() but execs the compiled flipper for a far higher |
| 1190 |
flip rate (a stronger RED oracle on slow filesystems). Transparently falls |
| 1191 |
back to the Python flipper where no compiler is available. Returns a Popen; |
| 1192 |
stop with stop_flipper().""" |
| 1193 |
binpath = compile_c_flipper() |
| 1194 |
if binpath: |
| 1195 |
return subprocess.Popen([binpath, str(name_a), str(name_b)]) |
| 1196 |
return start_path_flipper(name_a, name_b) |
| 1197 |
|
| 1198 |
|
| 1199 |
def cp_p(src, dst) -> 'None': |
| 1200 |
"""Equivalent of rsync.fns cp_p: copy preserving mode + timestamps.""" |
| 1201 |
shutil.copy2(src, dst) |
| 1202 |
|
| 1203 |
|
| 1204 |
def make_data_file(path, size: int) -> 'None': |
| 1205 |
"""Equivalent of rsync.fns make_data_file: create `path` with `size` |
| 1206 |
bytes of non-trivial content suitable for rsync's delta algorithm. |
| 1207 |
|
| 1208 |
Prefers /dev/urandom for speed. Falls back to a deterministic LCG |
| 1209 |
seeded from PID and the destination path so successive calls produce |
| 1210 |
distinct content -- matching the shell helper. |
| 1211 |
""" |
| 1212 |
path = str(path) |
| 1213 |
if os.path.exists('/dev/urandom'): |
| 1214 |
try: |
| 1215 |
with open('/dev/urandom', 'rb') as src, open(path, 'wb') as dst: |
| 1216 |
remaining = size |
| 1217 |
while remaining: |
| 1218 |
chunk = src.read(min(remaining, 1 << 16)) |
| 1219 |
if not chunk: |
| 1220 |
break |
| 1221 |
dst.write(chunk) |
| 1222 |
remaining -= len(chunk) |
| 1223 |
if remaining == 0: |
| 1224 |
return |
| 1225 |
except OSError: |
| 1226 |
pass |
| 1227 |
|
| 1228 |
|
| 1229 |
|
| 1230 |
|
| 1231 |
path_seed = int.from_bytes(path.encode(), 'big') & 0xFFFFFFFF |
| 1232 |
state = (os.getpid() + path_seed) % 2147483648 |
| 1233 |
with open(path, 'wb') as f: |
| 1234 |
out = bytearray(size) |
| 1235 |
for i in range(size): |
| 1236 |
state = (state * 1103515245 + 12345) % 2147483648 |
| 1237 |
out[i] = ((state >> 16) % 94) + 33 |
| 1238 |
f.write(bytes(out)) |
| 1239 |
|
| 1240 |
|
| 1241 |
def make_text_file(path, lines: int = 100) -> 'None': |
| 1242 |
"""Write a predictable, self-contained text file of `lines` lines. |
| 1243 |
|
| 1244 |
This replaces the old habit of capturing `ls -l /etc` / `ls -l /bin` |
| 1245 |
(falling back to `ls /`) into the test tree. Those tied the fixtures |
| 1246 |
to the host filesystem layout: the directories are absent or |
| 1247 |
unreadable on Android/Termux and other minimal environments, where |
| 1248 |
`ls /` fails outright, and the captured content was never |
| 1249 |
reproducible. The output here is deterministic and depends on nothing |
| 1250 |
outside the suite, so every platform builds the identical fixture. |
| 1251 |
""" |
| 1252 |
content = ''.join( |
| 1253 |
"line %06d the quick brown fox jumps over the lazy dog %d %d\n" |
| 1254 |
% (i, (i * 31) % 97, (i * 131) % 89) |
| 1255 |
for i in range(1, lines + 1) |
| 1256 |
) |
| 1257 |
with open(str(path), 'w') as f: |
| 1258 |
f.write(content) |
| 1259 |
|
| 1260 |
|
| 1261 |
def get_testuid() -> int: |
| 1262 |
return os.getuid() |
| 1263 |
|
| 1264 |
|
| 1265 |
def get_rootuid() -> int: |
| 1266 |
return 0 |
| 1267 |
|
| 1268 |
|
| 1269 |
def get_rootgid() -> int: |
| 1270 |
return 0 |
| 1271 |
|
| 1272 |
|
| 1273 |
def build_rsyncd_conf() -> 'Path': |
| 1274 |
"""Equivalent of rsync.fns build_rsyncd_conf. |
| 1275 |
|
| 1276 |
Writes $scratchdir/test-rsyncd.conf with the four standard modules |
| 1277 |
(test-from, test-to, test-scratch, test-hidden) and a $scratchdir/ |
| 1278 |
ignore23 wrapper that propagates rsync's exit status except for |
| 1279 |
code 23 (vanished/missing source files), which it eats so that the |
| 1280 |
surrounding test can tolerate the partial-transfer case. |
| 1281 |
|
| 1282 |
Returns the path to the config file. Tests typically follow up by |
| 1283 |
setting RSYNC_CONNECT_PROG so rsync forks an in-tree daemon instead |
| 1284 |
of contacting one over the network. |
| 1285 |
""" |
| 1286 |
conf = SCRATCHDIR / 'test-rsyncd.conf' |
| 1287 |
pidfile = SCRATCHDIR / 'rsyncd.pid' |
| 1288 |
logfile = SCRATCHDIR / 'rsyncd.log' |
| 1289 |
|
| 1290 |
my_uid = get_testuid() |
| 1291 |
root_uid = get_rootuid() |
| 1292 |
root_gid = get_rootgid() |
| 1293 |
|
| 1294 |
if my_uid != root_uid: |
| 1295 |
|
| 1296 |
uid_line = f"#uid = {root_uid}" |
| 1297 |
gid_line = f"#gid = {root_gid}" |
| 1298 |
else: |
| 1299 |
uid_line = f"uid = {root_uid}" |
| 1300 |
gid_line = f"gid = {root_gid}" |
| 1301 |
|
| 1302 |
conf.write_text(f"""\ |
| 1303 |
# rsyncd configuration file autogenerated by rsyncfns.build_rsyncd_conf |
| 1304 |
|
| 1305 |
pid file = {pidfile} |
| 1306 |
use chroot = no |
| 1307 |
munge symlinks = no |
| 1308 |
# Loopback only. In --use-tcp mode the daemon is also bound to 127.0.0.1 |
| 1309 |
# (start_rsyncd passes --address), so this is belt-and-suspenders; in the |
| 1310 |
# default pipe mode there is no socket to guard at all. |
| 1311 |
hosts allow = localhost 127.0.0.0/8 |
| 1312 |
log file = {logfile} |
| 1313 |
transfer logging = yes |
| 1314 |
# We don't define log format here so the test-hidden module defaults |
| 1315 |
# to the internal static string (since we had a crash trying to tweak it). |
| 1316 |
exclude = ? foobar.baz |
| 1317 |
max verbosity = 4 |
| 1318 |
{uid_line} |
| 1319 |
{gid_line} |
| 1320 |
|
| 1321 |
[test-from] |
| 1322 |
\tpath = {FROMDIR} |
| 1323 |
\tlog format = %i %h [%a] %m (%u) %l %f%L |
| 1324 |
\tread only = yes |
| 1325 |
\tcomment = r/o |
| 1326 |
|
| 1327 |
[test-to] |
| 1328 |
\tpath = {TODIR} |
| 1329 |
\tlog format = %i %h [%a] %m (%u) %l %f%L |
| 1330 |
\tread only = no |
| 1331 |
\tcomment = r/w |
| 1332 |
|
| 1333 |
[test-scratch] |
| 1334 |
\tpath = {SCRATCHDIR} |
| 1335 |
\tlog format = %i %h [%a] %m (%u) %l %f%L |
| 1336 |
\tread only = no |
| 1337 |
|
| 1338 |
[test-hidden] |
| 1339 |
\tpath = {FROMDIR} |
| 1340 |
\tlist = no |
| 1341 |
""") |
| 1342 |
|
| 1343 |
ignore23 = SCRATCHDIR / 'ignore23' |
| 1344 |
ignore23.write_text( |
| 1345 |
'#!/bin/sh\n' |
| 1346 |
'if "${@}"; then exit; fi\n' |
| 1347 |
'ret=$?\n' |
| 1348 |
'if test $ret = 23; then exit; fi\n' |
| 1349 |
'exit $ret\n' |
| 1350 |
) |
| 1351 |
ignore23.chmod(0o755) |
| 1352 |
|
| 1353 |
return conf |
| 1354 |
|
| 1355 |
|
| 1356 |
def rsync_getgroups() -> list: |
| 1357 |
"""List of group ids the test user is a member of, via the getgroups |
| 1358 |
test helper binary. Mirrors rsync.fns rsync_getgroups.""" |
| 1359 |
out = subprocess.check_output([str(TOOLDIR / 'getgroups')], text=True) |
| 1360 |
return out.split() |
| 1361 |
|
| 1362 |
|
| 1363 |
|
| 1364 |
|
| 1365 |
|
| 1366 |
|
| 1367 |
|
| 1368 |
|
| 1369 |
|
| 1370 |
|
| 1371 |
_SYSTEM = platform.system() |
| 1372 |
|
| 1373 |
|
| 1374 |
|
| 1375 |
|
| 1376 |
_CYGWIN = _SYSTEM.startswith('CYGWIN') |
| 1377 |
|
| 1378 |
|
| 1379 |
|
| 1380 |
|
| 1381 |
_LINUX_NS = _SYSTEM == 'Linux' or _CYGWIN |
| 1382 |
|
| 1383 |
|
| 1384 |
|
| 1385 |
|
| 1386 |
|
| 1387 |
|
| 1388 |
|
| 1389 |
RSYNC_PREFIX = 'rsync' |
| 1390 |
RUSR = 'rsync.nonuser' if _SYSTEM in ('Darwin', 'SunOS') else 'rsync' |
| 1391 |
|
| 1392 |
|
| 1393 |
def _xattr_full(name: str) -> str: |
| 1394 |
"""Map a logical user-xattr name to the on-disk name for this OS.""" |
| 1395 |
return ('user.' + name) if _LINUX_NS else name |
| 1396 |
|
| 1397 |
|
| 1398 |
def xattrs_supported() -> bool: |
| 1399 |
"""True if this rsync was built with xattr support AND this platform has |
| 1400 |
a way for the tests to set/list user xattrs.""" |
| 1401 |
vv = run_rsync('-VV', check=True, capture_output=True).stdout |
| 1402 |
if '"xattrs": true' not in vv: |
| 1403 |
return False |
| 1404 |
if _SYSTEM == 'Linux': |
| 1405 |
return hasattr(os, 'setxattr') |
| 1406 |
if _CYGWIN: |
| 1407 |
return shutil.which('setfattr') is not None |
| 1408 |
if _SYSTEM == 'Darwin': |
| 1409 |
return shutil.which('xattr') is not None |
| 1410 |
if _SYSTEM == 'FreeBSD': |
| 1411 |
return shutil.which('setextattr') is not None |
| 1412 |
if _SYSTEM == 'SunOS': |
| 1413 |
return shutil.which('runat') is not None |
| 1414 |
return False |
| 1415 |
|
| 1416 |
|
| 1417 |
class XattrError(OSError): |
| 1418 |
"""An xattr CLI refused an operation. |
| 1419 |
|
| 1420 |
Deliberately an OSError: on Linux xattr_set() calls os.setxattr(), where a |
| 1421 |
refusal IS an OSError, so callers write `except OSError`. Every other |
| 1422 |
platform shells out, and a bare CalledProcessError -- not an OSError -- |
| 1423 |
sails straight past that handler. A refusal the suite tolerates on Linux |
| 1424 |
would then be fatal everywhere else. |
| 1425 |
|
| 1426 |
.errno is set only when the tool named one. Most of these tools report a |
| 1427 |
message rather than a number, and guessing an errno from localised |
| 1428 |
strerror text would be worse than admitting we do not know, so a caller |
| 1429 |
that switches on .errno must cope with None. |
| 1430 |
""" |
| 1431 |
|
| 1432 |
|
| 1433 |
def _tool_errno(tool: str, msg: str) -> 'int | None': |
| 1434 |
"""The errno a tool named for itself, or None if it named none. |
| 1435 |
|
| 1436 |
Only macOS's xattr(1) reports one, as "xattr: [Errno 13] Permission |
| 1437 |
denied: '/some/path'". Match that tool's own prefix, and only on the |
| 1438 |
first line: the rest of the line is a filename, and a file can perfectly |
| 1439 |
well be called "[Errno 5]" -- searching the whole message would let the |
| 1440 |
file being operated on dictate the errno we report. |
| 1441 |
""" |
| 1442 |
if tool != 'xattr' or not msg: |
| 1443 |
return None |
| 1444 |
import re |
| 1445 |
m = re.match(r'xattr: \[Errno (\d+)\]', msg.splitlines()[0]) |
| 1446 |
return int(m.group(1)) if m else None |
| 1447 |
|
| 1448 |
|
| 1449 |
def _xattr_run(argv, **kwargs) -> 'None': |
| 1450 |
"""Run an xattr CLI, raising XattrError rather than CalledProcessError.""" |
| 1451 |
proc = subprocess.run(argv, capture_output=True, text=True, **kwargs) |
| 1452 |
if proc.returncode == 0: |
| 1453 |
return |
| 1454 |
msg = (proc.stderr or proc.stdout or '').strip() |
| 1455 |
err = XattrError(f'{argv[0]} exited {proc.returncode}' |
| 1456 |
+ (f': {msg}' if msg else '')) |
| 1457 |
err.errno = _tool_errno(argv[0], msg) |
| 1458 |
raise err |
| 1459 |
|
| 1460 |
|
| 1461 |
def xattr_set(name: str, value: str, *paths) -> 'None': |
| 1462 |
"""Set the user-namespace xattr `name` (logical) = `value` on each path. |
| 1463 |
|
| 1464 |
Raises OSError (see XattrError) on every platform if the set is refused.""" |
| 1465 |
full = _xattr_full(name) |
| 1466 |
for p in paths: |
| 1467 |
p = str(p) |
| 1468 |
if _SYSTEM == 'Linux': |
| 1469 |
os.setxattr(p, full.encode(), value.encode()) |
| 1470 |
elif _CYGWIN: |
| 1471 |
_xattr_run(['setfattr', '-n', full, '-v', value, p]) |
| 1472 |
elif _SYSTEM == 'Darwin': |
| 1473 |
_xattr_run(['xattr', '-w', full, value, p]) |
| 1474 |
elif _SYSTEM == 'FreeBSD': |
| 1475 |
_xattr_run(['setextattr', '-h', 'user', full, value, p]) |
| 1476 |
elif _SYSTEM == 'SunOS': |
| 1477 |
|
| 1478 |
|
| 1479 |
|
| 1480 |
|
| 1481 |
|
| 1482 |
_xattr_run( |
| 1483 |
['runat', p, '/bin/sh'], |
| 1484 |
input='printf %s "$XVAL" > "$XNAME"\n', |
| 1485 |
env={**os.environ, 'XNAME': full, 'XVAL': value}) |
| 1486 |
else: |
| 1487 |
raise NotImplementedError(f"xattr_set on {_SYSTEM}") |
| 1488 |
|
| 1489 |
|
| 1490 |
def xattr_dump(*paths) -> str: |
| 1491 |
"""Return a deterministic name=value dump of the user xattrs on `paths`, |
| 1492 |
for comparing a source tree against its rsync'd copy. The format only |
| 1493 |
needs to be self-consistent on a given OS (we never compare across OSes), |
| 1494 |
mirroring the per-OS xls() in the old xattrs.test.""" |
| 1495 |
if _SYSTEM == 'Linux': |
| 1496 |
|
| 1497 |
|
| 1498 |
|
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
|
| 1503 |
|
| 1504 |
out = [] |
| 1505 |
for p in paths: |
| 1506 |
sp = str(p) |
| 1507 |
names = sorted(n for n in os.listxattr(sp) if n.startswith('user.')) |
| 1508 |
if not names: |
| 1509 |
continue |
| 1510 |
out.append(f'# file: {sp}\n') |
| 1511 |
for n in names: |
| 1512 |
v = os.getxattr(sp, n).decode('utf-8', 'surrogateescape') |
| 1513 |
out.append(f'{n}="{v}"\n') |
| 1514 |
out.append('\n') |
| 1515 |
return ''.join(out) |
| 1516 |
if _CYGWIN: |
| 1517 |
|
| 1518 |
return subprocess.check_output( |
| 1519 |
['getfattr', '-d', *(str(p) for p in paths)], text=True) |
| 1520 |
if _SYSTEM == 'Darwin': |
| 1521 |
out = [] |
| 1522 |
for p in paths: |
| 1523 |
t = subprocess.check_output(['xattr', '-l', str(p)], text=True) |
| 1524 |
out.append('\n'.join(ln.lstrip(' \t') for ln in t.splitlines())) |
| 1525 |
out.append('\n') |
| 1526 |
return ''.join(out) |
| 1527 |
if _SYSTEM == 'FreeBSD': |
| 1528 |
out = [] |
| 1529 |
for p in paths: |
| 1530 |
names = subprocess.check_output( |
| 1531 |
['lsextattr', '-q', '-h', 'user', str(p)], text=True).split() |
| 1532 |
for n in sorted(names): |
| 1533 |
out.append(subprocess.check_output( |
| 1534 |
['getextattr', '-h', 'user', n, str(p)], text=True)) |
| 1535 |
return ''.join(out) |
| 1536 |
if _SYSTEM == 'SunOS': |
| 1537 |
|
| 1538 |
|
| 1539 |
|
| 1540 |
script = ('for x in *; do case "$x" in SUNWattr_*) continue;; esac; ' |
| 1541 |
'printf "%s=%s\\n" "$x" "$(cat "$x")"; done\n') |
| 1542 |
out = [] |
| 1543 |
for p in paths: |
| 1544 |
out.append(subprocess.run( |
| 1545 |
['runat', str(p), '/bin/sh'], input=script, |
| 1546 |
capture_output=True, text=True, check=True).stdout) |
| 1547 |
return ''.join(out) |
| 1548 |
raise NotImplementedError(f"xattr_dump on {_SYSTEM}") |
| 1549 |
|
| 1550 |
|
| 1551 |
def runtest(label: str, fn, *args, **kwargs): |
| 1552 |
"""Run a sub-test step with an echoed label, like rsync.fns runtest. |
| 1553 |
|
| 1554 |
The shell helper does `Test $1: $2 ... done.` -- this prints a similar |
| 1555 |
banner and propagates exceptions (which surface as a failing test). |
| 1556 |
""" |
| 1557 |
print(f"Test {label}: ", end="", flush=True) |
| 1558 |
fn(*args, **kwargs) |
| 1559 |
print("done.") |
| 1560 |
|
| 1561 |
|
| 1562 |
def cp_touch(src, dst) -> 'None': |
| 1563 |
"""Equivalent of rsync.fns cp_touch: copy preserving timestamps, then |
| 1564 |
forcibly re-touch both source and destination to identical times. |
| 1565 |
|
| 1566 |
On some filesystems cp rounds microsecond timestamps on the destination; |
| 1567 |
rsync.fns works around this by then `touch -r dst src dst`. Here we set |
| 1568 |
both src and dst to dst's mtime/atime after the copy, so a diff of the |
| 1569 |
tls output (which prints times) sees identical entries on both sides. |
| 1570 |
""" |
| 1571 |
shutil.copy2(src, dst) |
| 1572 |
if os.path.isdir(dst): |
| 1573 |
dst = os.path.join(dst, os.path.basename(src)) |
| 1574 |
st = os.stat(dst, follow_symlinks=False) |
| 1575 |
os.utime(src, ns=(st.st_atime_ns, st.st_mtime_ns), follow_symlinks=False) |
| 1576 |
os.utime(dst, ns=(st.st_atime_ns, st.st_mtime_ns), follow_symlinks=False) |
| 1577 |
|
| 1578 |
|
| 1579 |
def build_symlinks() -> 'None': |
| 1580 |
"""Equivalent of rsync.fns build_symlinks: a set of canonical relative, |
| 1581 |
absolute, dangling and unsafe symlinks under FROMDIR for symlink tests. |
| 1582 |
""" |
| 1583 |
FROMDIR.mkdir(parents=True, exist_ok=True) |
| 1584 |
(FROMDIR / 'referent').write_text( |
| 1585 |
subprocess.check_output(['date'], text=True) |
| 1586 |
) |
| 1587 |
os.symlink('referent', FROMDIR / 'relative') |
| 1588 |
os.symlink(str(FROMDIR / 'referent'), FROMDIR / 'absolute') |
| 1589 |
os.symlink('nonexistent', FROMDIR / 'dangling') |
| 1590 |
os.symlink(str(SRCDIR / 'rsync.c'), FROMDIR / 'unsafe') |
| 1591 |
|
| 1592 |
|
| 1593 |
def hands_setup() -> 'None': |
| 1594 |
"""Populate FROMDIR with a varied tree of files and directories for the |
| 1595 |
canonical 'hands' transfer test. |
| 1596 |
|
| 1597 |
All content is generated from within the suite (srcdir contents plus |
| 1598 |
make_text_file output) so the fixture is self-contained and |
| 1599 |
reproducible on every platform. |
| 1600 |
""" |
| 1601 |
rmtree(FROMDIR) |
| 1602 |
rmtree(TODIR) |
| 1603 |
TMPDIR.mkdir(parents=True, exist_ok=True) |
| 1604 |
FROMDIR.mkdir(parents=True, exist_ok=True) |
| 1605 |
TODIR.mkdir(parents=True, exist_ok=True) |
| 1606 |
|
| 1607 |
(FROMDIR / 'empty').touch() |
| 1608 |
(FROMDIR / 'emptydir').mkdir(exist_ok=True) |
| 1609 |
|
| 1610 |
|
| 1611 |
|
| 1612 |
(FROMDIR / 'filelist').write_text(rsync_ls_lR(SRCDIR)) |
| 1613 |
|
| 1614 |
|
| 1615 |
|
| 1616 |
(FROMDIR / 'nolf').write_text("This file has no trailing lf") |
| 1617 |
|
| 1618 |
old_umask = os.umask(0) |
| 1619 |
try: |
| 1620 |
os.symlink('nolf', FROMDIR / 'nolf-symlink') |
| 1621 |
finally: |
| 1622 |
os.umask(old_umask) |
| 1623 |
|
| 1624 |
|
| 1625 |
text = bytearray() |
| 1626 |
for c in sorted(SRCDIR.glob('*.c')): |
| 1627 |
text.extend(c.read_bytes()) |
| 1628 |
(FROMDIR / 'text').write_bytes(bytes(text)) |
| 1629 |
|
| 1630 |
(FROMDIR / 'dir').mkdir(exist_ok=True) |
| 1631 |
shutil.copy(FROMDIR / 'text', FROMDIR / 'dir') |
| 1632 |
(FROMDIR / 'dir' / 'subdir').mkdir(exist_ok=True) |
| 1633 |
(FROMDIR / 'dir' / 'subdir' / 'foobar.baz').write_text("some data\n") |
| 1634 |
(FROMDIR / 'dir' / 'subdir' / 'subsubdir').mkdir(exist_ok=True) |
| 1635 |
|
| 1636 |
|
| 1637 |
make_text_file(FROMDIR / 'dir' / 'subdir' / 'subsubdir' / 'etc-ltr-list', 120) |
| 1638 |
|
| 1639 |
(FROMDIR / 'dir' / 'subdir' / 'subsubdir2').mkdir(exist_ok=True) |
| 1640 |
make_text_file(FROMDIR / 'dir' / 'subdir' / 'subsubdir2' / 'bin-lt-list', 200) |
| 1641 |
|
| 1642 |
|
| 1643 |
|
| 1644 |
|
| 1645 |
def rsync_ls_lR(directory) -> str: |
| 1646 |
"""Equivalent of rsync.fns rsync_ls_lR: print a sorted ls-style listing |
| 1647 |
of `directory`, pruning .git / auto-build-save / testtmp subtrees, using |
| 1648 |
the project's `tls` helper so the output format matches the rest of the |
| 1649 |
suite. |
| 1650 |
""" |
| 1651 |
cmd = ( |
| 1652 |
"find . -name .git -prune -o -name auto-build-save -prune " |
| 1653 |
"-o -name testtmp -prune -o -print | sort | sed 's/ /\\\\ /g' | " |
| 1654 |
f"xargs '{TOOLDIR}/tls' {TLS_ARGS}" |
| 1655 |
) |
| 1656 |
|
| 1657 |
|
| 1658 |
|
| 1659 |
|
| 1660 |
|
| 1661 |
|
| 1662 |
proc = subprocess.run(['sh', '-c', cmd], capture_output=True, |
| 1663 |
encoding='utf-8', errors='backslashreplace', |
| 1664 |
cwd=str(directory)) |
| 1665 |
return proc.stdout |
| 1666 |
|
| 1667 |
|
| 1668 |
def checkit(args, expected_dir, actual_dir, skip_file_diff: bool = False, |
| 1669 |
allowed_codes=(0,)) -> 'None': |
| 1670 |
"""Run rsync with `args` (a list of extra rsync arguments) and then |
| 1671 |
verify two things: |
| 1672 |
|
| 1673 |
1. The tls-formatted listings of `expected_dir` and `actual_dir` |
| 1674 |
are identical. |
| 1675 |
2. (Unless skip_file_diff) diff -r against the two trees reports |
| 1676 |
no differences. |
| 1677 |
|
| 1678 |
`allowed_codes` is the tuple of exit codes treated as success. |
| 1679 |
Pass (0, 23) for daemon-mode transfers that may report partial- |
| 1680 |
transfer codes even when the listings still match. |
| 1681 |
|
| 1682 |
Calls test_fail() on any mismatch. Mirrors the rsync.fns checkit shell |
| 1683 |
helper; callers pass rsync arguments as a Python list rather than as a |
| 1684 |
pre-quoted command string, which avoids the shell-quoting gymnastics |
| 1685 |
that the shell version needed. |
| 1686 |
""" |
| 1687 |
expected_dir = str(expected_dir) |
| 1688 |
actual_dir = str(actual_dir) |
| 1689 |
|
| 1690 |
failed = [] |
| 1691 |
|
| 1692 |
|
| 1693 |
|
| 1694 |
ls_from = None |
| 1695 |
if '--atimes' in TLS_ARGS: |
| 1696 |
ls_from = rsync_ls_lR(expected_dir) |
| 1697 |
|
| 1698 |
print(f"Running: rsync {' '.join(args)}") |
| 1699 |
proc = subprocess.run(rsync_argv(*args)) |
| 1700 |
if proc.returncode not in allowed_codes: |
| 1701 |
failed.append(f"status={proc.returncode}") |
| 1702 |
|
| 1703 |
if ls_from is None: |
| 1704 |
ls_from = rsync_ls_lR(expected_dir) |
| 1705 |
ls_to = rsync_ls_lR(actual_dir) |
| 1706 |
|
| 1707 |
print("-------------") |
| 1708 |
print("check how the directory listings compare with diff:") |
| 1709 |
print() |
| 1710 |
if ls_from != ls_to: |
| 1711 |
ls_from_path = TMPDIR / 'ls-from' |
| 1712 |
ls_to_path = TMPDIR / 'ls-to' |
| 1713 |
ls_from_path.write_text(ls_from) |
| 1714 |
ls_to_path.write_text(ls_to) |
| 1715 |
diff = subprocess.run( |
| 1716 |
['diff', '-u', str(ls_from_path), str(ls_to_path)], |
| 1717 |
capture_output=True, text=True, |
| 1718 |
) |
| 1719 |
sys.stdout.write(diff.stdout) |
| 1720 |
failed.append("dir-diff") |
| 1721 |
|
| 1722 |
print("-------------") |
| 1723 |
print("check how the files compare with diff:") |
| 1724 |
print() |
| 1725 |
if skip_file_diff: |
| 1726 |
print(" === Skipping (as directed) ===") |
| 1727 |
else: |
| 1728 |
diff = subprocess.run(['diff', '-r', '-u', expected_dir, actual_dir]) |
| 1729 |
if diff.returncode != 0: |
| 1730 |
failed.append("file-diff") |
| 1731 |
|
| 1732 |
print("-------------") |
| 1733 |
if failed: |
| 1734 |
test_fail("Failed: " + " ".join(failed)) |
| 1735 |
|
| 1736 |
|
| 1737 |
def verify_dirs(expected_dir, actual_dir, skip_file_diff: bool = False, |
| 1738 |
label: str = '') -> 'None': |
| 1739 |
"""Verify two directory trees match: identical tls listings and |
| 1740 |
(unless skip_file_diff) identical file contents. Same comparison |
| 1741 |
logic as checkit() but with no rsync invocation -- useful when the |
| 1742 |
rsync that produced `actual_dir` had to be driven manually so that |
| 1743 |
its output could be captured for inspection.""" |
| 1744 |
expected_dir = str(expected_dir) |
| 1745 |
actual_dir = str(actual_dir) |
| 1746 |
tag = f"{label}: " if label else "" |
| 1747 |
|
| 1748 |
ls_expected = rsync_ls_lR(expected_dir) |
| 1749 |
ls_actual = rsync_ls_lR(actual_dir) |
| 1750 |
if ls_expected != ls_actual: |
| 1751 |
ls_expected_path = TMPDIR / 'ls-from' |
| 1752 |
ls_actual_path = TMPDIR / 'ls-to' |
| 1753 |
ls_expected_path.write_text(ls_expected) |
| 1754 |
ls_actual_path.write_text(ls_actual) |
| 1755 |
diff = subprocess.run( |
| 1756 |
['diff', '-u', str(ls_expected_path), str(ls_actual_path)], |
| 1757 |
capture_output=True, text=True, |
| 1758 |
) |
| 1759 |
sys.stdout.write(diff.stdout) |
| 1760 |
test_fail(f"{tag}directory listings differ between " |
| 1761 |
f"{expected_dir} and {actual_dir}") |
| 1762 |
|
| 1763 |
if not skip_file_diff: |
| 1764 |
diff = subprocess.run(['diff', '-r', '-u', expected_dir, actual_dir]) |
| 1765 |
if diff.returncode != 0: |
| 1766 |
test_fail(f"{tag}file content differs between " |
| 1767 |
f"{expected_dir} and {actual_dir}") |
| 1768 |
|
| 1769 |
|
| 1770 |
def v_filt(text: str) -> str: |
| 1771 |
"""Strip the boilerplate lines rsync emits at -v / -vv so callers can |
| 1772 |
diff only the file/directory change lines. Mirrors rsync.fns v_filt: |
| 1773 |
delete the build/progress banners, then everything from the first |
| 1774 |
blank line to end-of-text.""" |
| 1775 |
out = [] |
| 1776 |
skip_prefix = ( |
| 1777 |
'building file list ', |
| 1778 |
'sending incremental file list', |
| 1779 |
'created directory ', |
| 1780 |
'total: ', |
| 1781 |
'client charset: ', |
| 1782 |
'server charset: ', |
| 1783 |
) |
| 1784 |
for line in text.splitlines(): |
| 1785 |
if line == '': |
| 1786 |
break |
| 1787 |
if line.startswith(skip_prefix): |
| 1788 |
continue |
| 1789 |
if line == 'done': |
| 1790 |
continue |
| 1791 |
if line.endswith(' --whole-file'): |
| 1792 |
continue |
| 1793 |
out.append(line) |
| 1794 |
return '\n'.join(out) + ('\n' if out else '') |
| 1795 |
|
| 1796 |
|
| 1797 |
def checkdiff(args, expected: str, *, filter=None, allowed_codes=(0,), |
| 1798 |
direct: bool = False) -> 'None': |
| 1799 |
"""Run a command, capture its stdout, optionally pipe through `filter`, |
| 1800 |
then compare to `expected`. Mirrors rsync.fns checkdiff/checkdiff2. |
| 1801 |
|
| 1802 |
args is normally a list of rsync arguments -- the rsync binary is |
| 1803 |
prepended via rsync_argv. Pass direct=True to run `args` as a literal |
| 1804 |
command (used by tests that drive a wrapper such as BATCH.sh). |
| 1805 |
""" |
| 1806 |
if direct: |
| 1807 |
argv = list(args) |
| 1808 |
label = ' '.join(argv) |
| 1809 |
else: |
| 1810 |
argv = rsync_argv(*args) |
| 1811 |
label = 'rsync ' + ' '.join(args) |
| 1812 |
print(f"Running: {label}") |
| 1813 |
proc = subprocess.run(argv, capture_output=True, text=True) |
| 1814 |
stdout = proc.stdout |
| 1815 |
if proc.stderr: |
| 1816 |
sys.stderr.write(proc.stderr) |
| 1817 |
sys.stdout.write(stdout) |
| 1818 |
|
| 1819 |
failed = [] |
| 1820 |
if proc.returncode not in allowed_codes: |
| 1821 |
failed.append(f"status={proc.returncode}") |
| 1822 |
|
| 1823 |
if filter is not None: |
| 1824 |
stdout = filter(stdout) |
| 1825 |
|
| 1826 |
if stdout != expected: |
| 1827 |
from difflib import unified_diff |
| 1828 |
diff = unified_diff( |
| 1829 |
expected.splitlines(keepends=True), |
| 1830 |
stdout.splitlines(keepends=True), |
| 1831 |
fromfile='expected', tofile='got', |
| 1832 |
) |
| 1833 |
sys.stdout.write(''.join(diff)) |
| 1834 |
failed.append("output differs") |
| 1835 |
|
| 1836 |
if failed: |
| 1837 |
test_fail("Failed: " + " ".join(failed)) |
| 1838 |
|
| 1839 |
|
| 1840 |
def check_perms(path, expected: str) -> 'None': |
| 1841 |
"""Verify that the 9-char rwx permission string of `path` matches |
| 1842 |
`expected` (e.g. 'rwx------'). Calls test_fail() on mismatch.""" |
| 1843 |
mode = os.stat(path, follow_symlinks=False).st_mode |
| 1844 |
bits = [ |
| 1845 |
(0o400, 'r'), (0o200, 'w'), (0o100, 'x'), |
| 1846 |
(0o040, 'r'), (0o020, 'w'), (0o010, 'x'), |
| 1847 |
(0o004, 'r'), (0o002, 'w'), (0o001, 'x'), |
| 1848 |
] |
| 1849 |
chars = [c if mode & bit else '-' for bit, c in bits] |
| 1850 |
|
| 1851 |
if mode & 0o4000: |
| 1852 |
chars[2] = 's' if mode & 0o100 else 'S' |
| 1853 |
if mode & 0o2000: |
| 1854 |
chars[5] = 's' if mode & 0o010 else 'S' |
| 1855 |
if mode & 0o1000: |
| 1856 |
chars[8] = 't' if mode & 0o001 else 'T' |
| 1857 |
perms = ''.join(chars) |
| 1858 |
if perms != expected: |
| 1859 |
print(f"permissions: {perms} on {path}") |
| 1860 |
print(f"should be: {expected}") |
| 1861 |
test_fail(f"check_perms failed for {path}") |
| 1862 |
|
| 1863 |
|
| 1864 |
|
| 1865 |
|
| 1866 |
|
| 1867 |
|
| 1868 |
|
| 1869 |
|
| 1870 |
|
| 1871 |
def make_tree(root, depth: int = 3, *, data: bool = False, |
| 1872 |
content_lines: int = 20, data_size: int = 4096, |
| 1873 |
dirname: str = 'd', leaf: str = 'f'): |
| 1874 |
"""Create a layered directory tree with one regular file at every level. |
| 1875 |
|
| 1876 |
For depth=3 under `root`: |
| 1877 |
root/f0 |
| 1878 |
root/d1/f1 |
| 1879 |
root/d1/d2/f2 |
| 1880 |
root/d1/d2/d3/f3 |
| 1881 |
so an option's effect can be checked at the tree root AND >=3 levels deep |
| 1882 |
(the parent-component resolution the path restructure rewrites). |
| 1883 |
|
| 1884 |
Returns (dirs, files): `dirs` the created subdirectories outermost-first, |
| 1885 |
`files` the regular files shallow-first. Content is deterministic |
| 1886 |
(make_text_file) unless data=True (make_data_file, delta-friendly). |
| 1887 |
""" |
| 1888 |
root = Path(root) |
| 1889 |
root.mkdir(parents=True, exist_ok=True) |
| 1890 |
dirs = [] |
| 1891 |
files = [] |
| 1892 |
cur = root |
| 1893 |
for level in range(depth + 1): |
| 1894 |
f = cur / f'{leaf}{level}' |
| 1895 |
if data: |
| 1896 |
make_data_file(f, data_size) |
| 1897 |
else: |
| 1898 |
make_text_file(f, content_lines) |
| 1899 |
files.append(f) |
| 1900 |
if level < depth: |
| 1901 |
cur = cur / f'{dirname}{level + 1}' |
| 1902 |
cur.mkdir(exist_ok=True) |
| 1903 |
dirs.append(cur) |
| 1904 |
return dirs, files |
| 1905 |
|
| 1906 |
|
| 1907 |
def walk_files(root) -> list: |
| 1908 |
"""Every regular (non-symlink) file under `root`, sorted, recursively. |
| 1909 |
For asserting a per-entry property holds at every depth.""" |
| 1910 |
root = Path(root) |
| 1911 |
return sorted(p for p in root.rglob('*') |
| 1912 |
if p.is_file() and not p.is_symlink()) |
| 1913 |
|
| 1914 |
|
| 1915 |
def walk_dirs(root) -> list: |
| 1916 |
"""Every subdirectory under `root`, sorted, recursively.""" |
| 1917 |
root = Path(root) |
| 1918 |
return sorted(p for p in root.rglob('*') |
| 1919 |
if p.is_dir() and not p.is_symlink()) |
| 1920 |
|
| 1921 |
|
| 1922 |
def _tag(label: str) -> str: |
| 1923 |
return f"{label}: " if label else "" |
| 1924 |
|
| 1925 |
|
| 1926 |
def assert_same(a, b, label: str = '') -> 'None': |
| 1927 |
"""Fail unless files `a` and `b` have byte-identical content.""" |
| 1928 |
if not filecmp.cmp(str(a), str(b), shallow=False): |
| 1929 |
test_fail(f"{_tag(label)}content differs between {a} and {b}") |
| 1930 |
|
| 1931 |
|
| 1932 |
def assert_mode(path, expected_octal: int, label: str = '') -> 'None': |
| 1933 |
"""Fail unless the permission bits (low 12) of `path` equal expected_octal |
| 1934 |
(pass an int like 0o644). Does not follow symlinks.""" |
| 1935 |
mode = stat.S_IMODE(os.stat(path, follow_symlinks=False).st_mode) |
| 1936 |
if mode != expected_octal: |
| 1937 |
test_fail(f"{_tag(label)}mode {mode:04o} != expected " |
| 1938 |
f"{expected_octal:04o} on {path}") |
| 1939 |
|
| 1940 |
|
| 1941 |
def assert_mtime_close(a, b, tol: float = 1.0, label: str = '') -> 'None': |
| 1942 |
"""Fail unless the mtimes of `a` and `b` are within `tol` seconds. |
| 1943 |
`b` may be a number (an explicit epoch mtime) instead of a path.""" |
| 1944 |
ma = os.stat(a, follow_symlinks=False).st_mtime |
| 1945 |
mb = b if isinstance(b, (int, float)) else os.stat( |
| 1946 |
b, follow_symlinks=False).st_mtime |
| 1947 |
if abs(ma - mb) > tol: |
| 1948 |
test_fail(f"{_tag(label)}mtime {ma} vs {mb} differ by > {tol}s " |
| 1949 |
f"(checking {a})") |
| 1950 |
|
| 1951 |
|
| 1952 |
def assert_is_symlink(path, target: str = None, label: str = '') -> 'None': |
| 1953 |
"""Fail unless `path` is a symlink (optionally pointing exactly at |
| 1954 |
`target`).""" |
| 1955 |
if not os.path.islink(path): |
| 1956 |
test_fail(f"{_tag(label)}{path} is not a symlink") |
| 1957 |
if target is not None: |
| 1958 |
actual = os.readlink(path) |
| 1959 |
if actual != target: |
| 1960 |
test_fail(f"{_tag(label)}{path} -> {actual!r}, " |
| 1961 |
f"expected {target!r}") |
| 1962 |
|
| 1963 |
|
| 1964 |
def assert_hardlinked(a, b, label: str = '') -> 'None': |
| 1965 |
"""Fail unless `a` and `b` are the same inode (a hard link / --link-dest |
| 1966 |
result).""" |
| 1967 |
sa = os.stat(a, follow_symlinks=False) |
| 1968 |
sb = os.stat(b, follow_symlinks=False) |
| 1969 |
if (sa.st_dev, sa.st_ino) != (sb.st_dev, sb.st_ino): |
| 1970 |
test_fail(f"{_tag(label)}{a} and {b} are not hard-linked " |
| 1971 |
f"(ino {sa.st_ino} vs {sb.st_ino})") |
| 1972 |
|
| 1973 |
|
| 1974 |
def assert_not_hardlinked(a, b, label: str = '') -> 'None': |
| 1975 |
"""Fail if `a` and `b` share an inode (e.g. --copy-dest must copy, not |
| 1976 |
link).""" |
| 1977 |
sa = os.stat(a, follow_symlinks=False) |
| 1978 |
sb = os.stat(b, follow_symlinks=False) |
| 1979 |
if (sa.st_dev, sa.st_ino) == (sb.st_dev, sb.st_ino): |
| 1980 |
test_fail(f"{_tag(label)}{a} and {b} unexpectedly share " |
| 1981 |
f"inode {sa.st_ino}") |
| 1982 |
|
| 1983 |
|
| 1984 |
def assert_exists(path, label: str = '') -> 'None': |
| 1985 |
"""Fail unless `path` exists (a symlink counts even if dangling).""" |
| 1986 |
if not os.path.lexists(path): |
| 1987 |
test_fail(f"{_tag(label)}{path} does not exist") |
| 1988 |
|
| 1989 |
|
| 1990 |
def assert_not_exists(path, label: str = '') -> 'None': |
| 1991 |
"""Fail if `path` exists (a dangling symlink counts as existing).""" |
| 1992 |
if os.path.lexists(path): |
| 1993 |
test_fail(f"{_tag(label)}{path} exists but should not") |
| 1994 |
|
| 1995 |
|
| 1996 |
_psf_cache = None |
| 1997 |
|
| 1998 |
|
| 1999 |
def proc_self_fd_pins() -> bool: |
| 2000 |
"""True iff /proc/self/fd/N is a Linux-style magic symlink whose readlink |
| 2001 |
yields the open file's real path -- the primitive rrsync's realpath-vs-exec |
| 2002 |
inode-pin relies on. macOS/BSD lack the directory; Solaris HAS /proc/self/fd |
| 2003 |
but its entries are not such symlinks. Mirrors rrsync's own HAVE_PROC_SELF_FD |
| 2004 |
probe so the rrsync race test runs only where the protection actually exists |
| 2005 |
(it falls through unpinned, by design, elsewhere). Cached. |
| 2006 |
|
| 2007 |
A correct readlink does not prove the fd pins anything, and two platforms |
| 2008 |
get this wrong in opposite directions: NetBSD makes the entry a symlink for |
| 2009 |
directories only (readlink of a regular file's entry fails with EINVAL), |
| 2010 |
while Cygwin's readlink is right but opening the magic link RE-RESOLVES the |
| 2011 |
path, so a rename under a held fd reaches the replacement. Only Linux gives |
| 2012 |
the inode-bound magic link, so require that and keep the probes as a guard |
| 2013 |
for Linux-like environments without /proc.""" |
| 2014 |
global _psf_cache |
| 2015 |
if _psf_cache is not None: |
| 2016 |
return _psf_cache |
| 2017 |
if not sys.platform.startswith(('linux', 'android')): |
| 2018 |
_psf_cache = False |
| 2019 |
return _psf_cache |
| 2020 |
|
| 2021 |
def resolves(path): |
| 2022 |
try: |
| 2023 |
fd = os.open(path, os.O_RDONLY) |
| 2024 |
except OSError: |
| 2025 |
return False |
| 2026 |
try: |
| 2027 |
return os.readlink('/proc/self/fd/%d' % fd) == os.path.realpath(path) |
| 2028 |
except OSError: |
| 2029 |
return False |
| 2030 |
finally: |
| 2031 |
os.close(fd) |
| 2032 |
|
| 2033 |
_psf_cache = resolves('/') and resolves(os.path.realpath(__file__)) |
| 2034 |
return _psf_cache |
| 2035 |
|
| 2036 |
|
| 2037 |
def write_daemon_conf(modules, globals=None, *, |
| 2038 |
name: str = 'test-rsyncd.conf') -> 'Path': |
| 2039 |
"""Write a custom rsyncd.conf for daemon-parameter tests. |
| 2040 |
|
| 2041 |
`modules` is a list of (module_name, {param: value}) pairs; `globals` an |
| 2042 |
optional dict of global parameters that override the minimal defaults |
| 2043 |
(pid file / use chroot=no / hosts allow / log file / max verbosity). |
| 2044 |
Mirrors build_rsyncd_conf()'s root-aware uid/gid handling (only emitted |
| 2045 |
when running as root) and writes the same `ignore23` wrapper, but lets a |
| 2046 |
test set arbitrary parameters/modules beyond the fixed four. Returns the |
| 2047 |
config path; pair with start_test_daemon(). |
| 2048 |
""" |
| 2049 |
conf = SCRATCHDIR / name |
| 2050 |
pidfile = SCRATCHDIR / 'rsyncd.pid' |
| 2051 |
logfile = SCRATCHDIR / 'rsyncd.log' |
| 2052 |
|
| 2053 |
g = { |
| 2054 |
'pid file': str(pidfile), |
| 2055 |
'use chroot': 'no', |
| 2056 |
'hosts allow': 'localhost 127.0.0.0/8', |
| 2057 |
'log file': str(logfile), |
| 2058 |
'max verbosity': '4', |
| 2059 |
} |
| 2060 |
if globals: |
| 2061 |
g.update(globals) |
| 2062 |
if get_testuid() == get_rootuid(): |
| 2063 |
g.setdefault('uid', str(get_rootuid())) |
| 2064 |
g.setdefault('gid', str(get_rootgid())) |
| 2065 |
else: |
| 2066 |
|
| 2067 |
g.pop('uid', None) |
| 2068 |
g.pop('gid', None) |
| 2069 |
|
| 2070 |
lines = ['# autogenerated by rsyncfns.write_daemon_conf', ''] |
| 2071 |
lines += [f'{k} = {v}' for k, v in g.items()] |
| 2072 |
lines.append('') |
| 2073 |
for mod_name, params in modules: |
| 2074 |
lines.append(f'[{mod_name}]') |
| 2075 |
lines += [f'\t{k} = {v}' for k, v in params.items()] |
| 2076 |
lines.append('') |
| 2077 |
conf.write_text('\n'.join(lines) + '\n') |
| 2078 |
|
| 2079 |
ignore23 = SCRATCHDIR / 'ignore23' |
| 2080 |
if not ignore23.exists(): |
| 2081 |
ignore23.write_text( |
| 2082 |
'#!/bin/sh\n' |
| 2083 |
'if "${@}"; then exit; fi\n' |
| 2084 |
'ret=$?\n' |
| 2085 |
'if test $ret = 23; then exit; fi\n' |
| 2086 |
'exit $ret\n' |
| 2087 |
) |
| 2088 |
ignore23.chmod(0o755) |
| 2089 |
|
| 2090 |
return conf |
| 2091 |
|
| 2092 |
|
| 2093 |
|
| 2094 |
|
| 2095 |
def expect_fail(argv, text, env=None, cwd=None): |
| 2096 |
proc = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 2097 |
text=True, env=env, cwd=cwd) |
| 2098 |
out = (proc.stdout or '') + (proc.stderr or '') |
| 2099 |
if proc.returncode == 0: |
| 2100 |
test_fail(f"command unexpectedly succeeded: {argv!r}\n{out}") |
| 2101 |
if text not in out: |
| 2102 |
test_fail(f"expected {text!r} in command output:\n{out}") |
| 2103 |
return proc |
| 2104 |
|
| 2105 |
|
| 2106 |
def patched_rrsync(workdir, rsync_path=None): |
| 2107 |
|
| 2108 |
|
| 2109 |
import re |
| 2110 |
if rsync_path is None: |
| 2111 |
rsync_path = shutil.which('true') or '/usr/bin/true' |
| 2112 |
src = SRCDIR / 'support' / 'rrsync' |
| 2113 |
dst = Path(workdir) / 'rrsync-under-test' |
| 2114 |
|
| 2115 |
|
| 2116 |
|
| 2117 |
|
| 2118 |
|
| 2119 |
text, n = re.subn(r"(?m)^RSYNC\s*=.*$", |
| 2120 |
lambda _m: f"RSYNC = {rsync_path!r}", |
| 2121 |
src.read_text()) |
| 2122 |
if n != 1: |
| 2123 |
test_fail(f"patched_rrsync: expected exactly one 'RSYNC =' line in {src}, found {n}") |
| 2124 |
dst.write_text(text) |
| 2125 |
dst.chmod(0o755) |
| 2126 |
return dst |
| 2127 |
|
| 2128 |
|
| 2129 |
def run_rrsync_denied(command, expected): |
| 2130 |
base = SCRATCHDIR / expected.replace(' ', '_').replace('/', '_') |
| 2131 |
base.mkdir(parents=True, exist_ok=True) |
| 2132 |
restricted = base / 'restricted' |
| 2133 |
restricted.mkdir(exist_ok=True) |
| 2134 |
rrsync = patched_rrsync(base) |
| 2135 |
env = {**os.environ, 'SSH_ORIGINAL_COMMAND': command} |
| 2136 |
expect_fail([str(rrsync), '-ro', '-no-lock', str(restricted)], expected, env=env) |
| 2137 |
|
| 2138 |
|
| 2139 |
def make_proxy_server(port, response): |
| 2140 |
listener = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM) |
| 2141 |
listener.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1) |
| 2142 |
listener.bind(('127.0.0.1', port)) |
| 2143 |
listener.listen(1) |
| 2144 |
|
| 2145 |
def serve(): |
| 2146 |
conn, _ = listener.accept() |
| 2147 |
try: |
| 2148 |
conn.recv(65536) |
| 2149 |
conn.sendall(response) |
| 2150 |
finally: |
| 2151 |
try: |
| 2152 |
conn.close() |
| 2153 |
finally: |
| 2154 |
listener.close() |
| 2155 |
|
| 2156 |
import threading |
| 2157 |
t = threading.Thread(target=serve) |
| 2158 |
t.daemon = True |
| 2159 |
t.start() |
| 2160 |
return t |
| 2161 |
|
| 2162 |
|
| 2163 |
def run_proxy_probe(port, host, expected): |
| 2164 |
env = {**os.environ, 'RSYNC_PROXY': f'127.0.0.1:{port}'} |
| 2165 |
proc = subprocess.run( |
| 2166 |
rsync_argv(f'rsync://{host}/mod/', str(SCRATCHDIR / 'proxy-out')), |
| 2167 |
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=env) |
| 2168 |
out = (proc.stdout or '') + (proc.stderr or '') |
| 2169 |
if proc.returncode == 0: |
| 2170 |
test_fail(f"proxy probe unexpectedly succeeded:\n{out}") |
| 2171 |
if expected not in out: |
| 2172 |
test_fail(f"expected {expected!r} in proxy probe output:\n{out}") |
| 2173 |
return proc |
| 2174 |
|
| 2175 |
|
| 2176 |
def setup_chroot_inner(name): |
| 2177 |
if get_testuid() != get_rootuid(): |
| 2178 |
test_skipped("chroot /./ module regression requires root") |
| 2179 |
if _under_valgrind(): |
| 2180 |
|
| 2181 |
|
| 2182 |
|
| 2183 |
test_skipped("daemon chroot prevents valgrind from writing its per-process log") |
| 2184 |
base = SCRATCHDIR / name |
| 2185 |
outer = base / 'outer' |
| 2186 |
inner = outer / 'inner' |
| 2187 |
outside = outer / 'outside' |
| 2188 |
src = base / 'src' |
| 2189 |
rmtree(base) |
| 2190 |
makepath(inner, outside, src) |
| 2191 |
os.symlink('../outside', inner / 'linkparent') |
| 2192 |
conf = write_daemon_conf([ |
| 2193 |
('mod', {'path': str(outer) + '/./inner', 'read only': 'no', |
| 2194 |
'use chroot': 'yes', 'munge symlinks': 'no'}), |
| 2195 |
], name=f'{name}.conf') |
| 2196 |
url = start_test_daemon(conf, 12940 + (abs(hash(name)) % 200)) |
| 2197 |
return base, inner, outside, src, url |
| 2198 |
|
| 2199 |
|
| 2200 |
def run_checked(argv): |
| 2201 |
proc = subprocess.run(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) |
| 2202 |
return proc, (proc.stdout or '') + (proc.stderr or '') |
| 2203 |
|
| 2204 |
|
| 2205 |
def build_patched_rsync(name, replacements, append_cflags=None): |
| 2206 |
|
| 2207 |
|
| 2208 |
|
| 2209 |
|
| 2210 |
|
| 2211 |
|
| 2212 |
if sys.platform == 'cygwin' or platform.system().startswith('CYGWIN'): |
| 2213 |
test_skipped(f"{name}: build_patched_rsync is unreliable on Cygwin " |
| 2214 |
"(prebuilt-object staleness / -fno-common relink); the " |
| 2215 |
"patched-peer fix is validated on the POSIX targets") |
| 2216 |
if not (SRCDIR / 'Makefile').is_file(): |
| 2217 |
test_skipped(f"{name}: needs a configured rsync source tree with a Makefile") |
| 2218 |
if not shutil.which('make'): |
| 2219 |
test_skipped(f"{name}: make(1) not on PATH") |
| 2220 |
if not shutil.which('gcc') and not shutil.which('cc'): |
| 2221 |
test_skipped(f"{name}: no C compiler on PATH") |
| 2222 |
|
| 2223 |
work = SCRATCHDIR / name |
| 2224 |
rmtree(work) |
| 2225 |
shutil.copytree( |
| 2226 |
SRCDIR, work, symlinks=True, |
| 2227 |
ignore=shutil.ignore_patterns( |
| 2228 |
'testtmp', '.git', 'auto-build-save', 'autom4te.cache', '__pycache__')) |
| 2229 |
|
| 2230 |
for relpath, old, new in replacements: |
| 2231 |
path = work / relpath |
| 2232 |
text = path.read_text() |
| 2233 |
if old not in text: |
| 2234 |
test_skipped(f"{name}: could not find patch target in {relpath}: {old!r}") |
| 2235 |
path.write_text(text.replace(old, new, 1)) |
| 2236 |
|
| 2237 |
|
| 2238 |
|
| 2239 |
|
| 2240 |
|
| 2241 |
|
| 2242 |
obj = (work / relpath).with_suffix('.o') |
| 2243 |
if obj.exists(): |
| 2244 |
obj.unlink() |
| 2245 |
|
| 2246 |
|
| 2247 |
|
| 2248 |
for stale in (work / 'rsync', work / 'rsync.exe'): |
| 2249 |
if stale.exists(): |
| 2250 |
stale.unlink() |
| 2251 |
|
| 2252 |
|
| 2253 |
|
| 2254 |
|
| 2255 |
|
| 2256 |
if append_cflags: |
| 2257 |
import re |
| 2258 |
mkpath = work / 'Makefile' |
| 2259 |
mk = mkpath.read_text() |
| 2260 |
mk2 = re.sub(r'(?m)^(CFLAGS=.*)$', r'\1 ' + append_cflags, mk, count=1) |
| 2261 |
if mk2 == mk: |
| 2262 |
test_skipped(f"{name}: could not append {append_cflags!r} to CFLAGS in the Makefile") |
| 2263 |
mkpath.write_text(mk2) |
| 2264 |
|
| 2265 |
|
| 2266 |
|
| 2267 |
|
| 2268 |
for obj in work.rglob('*.o'): |
| 2269 |
obj.unlink() |
| 2270 |
|
| 2271 |
env = {**os.environ, 'CCACHE_DISABLE': '1'} |
| 2272 |
build = subprocess.run(['make', '-j2', 'rsync'], cwd=str(work), env=env, |
| 2273 |
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) |
| 2274 |
rsync = work / 'rsync' |
| 2275 |
if build.returncode != 0 or not rsync.is_file() or not os.access(rsync, os.X_OK): |
| 2276 |
test_skipped( |
| 2277 |
f"{name}: patched rsync build failed (rc={build.returncode}). " |
| 2278 |
"Tail of build output:\n" + '\n'.join(build.stdout.splitlines()[-20:])) |
| 2279 |
return rsync |
| 2280 |
|
| 2281 |
|
| 2282 |
|
| 2283 |
|
| 2284 |
|
| 2285 |
|
| 2286 |
|
| 2287 |
|
| 2288 |
|
| 2289 |
|
| 2290 |
|
| 2291 |
|
| 2292 |
|
| 2293 |
def find_attacker_uid(): |
| 2294 |
"""An untrusted uid (not 0, not the euid) for a cross-uid plant, else None.""" |
| 2295 |
import pwd |
| 2296 |
for nm in ('nobody', 'nfsnobody', 'daemon'): |
| 2297 |
try: |
| 2298 |
u = pwd.getpwnam(nm).pw_uid |
| 2299 |
except KeyError: |
| 2300 |
continue |
| 2301 |
if u != 0 and u != os.geteuid(): |
| 2302 |
return u |
| 2303 |
return None |
| 2304 |
|
| 2305 |
|
| 2306 |
def run_symlink_matrix(option, case, *, paths=('abs', 'rel'), |
| 2307 |
wheres=('leaf', 'parent'), label=''): |
| 2308 |
"""Run `case(ctx)` over the operator-path symlink matrix; assert the policy. |
| 2309 |
|
| 2310 |
`case(ctx)` plants the option's path symlink (per ctx.where/ctx.abspath), |
| 2311 |
runs rsync (honouring ctx.insecure), and returns True if the symlink was |
| 2312 |
FOLLOWED (the op escaped to ctx.outside / read an out-of-tree object). |
| 2313 |
ctx carries: base, outside, plant (fresh Paths); owner ('cross'|'self'); |
| 2314 |
att_uid; abspath ('abs'|'rel'); where ('leaf'|'parent'); insecure (bool); |
| 2315 |
and plant_link(at, target) which symlinks target->at and lchowns it to the |
| 2316 |
attacker uid when owner=='cross' (otherwise it stays euid-owned). |
| 2317 |
|
| 2318 |
Cross-uid cells need root (to own a symlink by a foreign uid) and are |
| 2319 |
skipped otherwise; same-uid cells run at any uid. |
| 2320 |
""" |
| 2321 |
import re |
| 2322 |
import types |
| 2323 |
tag = option + (f' [{label}]' if label else '') |
| 2324 |
euid = os.geteuid() |
| 2325 |
att = find_attacker_uid() if euid == 0 else None |
| 2326 |
slug = re.sub(r'[^a-z0-9]+', '-', tag.lower()).strip('-') |
| 2327 |
|
| 2328 |
for abspath in paths: |
| 2329 |
for where in wheres: |
| 2330 |
for insecure in (False, True): |
| 2331 |
owners = ('self', 'cross') if att is not None else ('self',) |
| 2332 |
for owner in owners: |
| 2333 |
base = SCRATCHDIR / (f"{slug}-{owner}-{abspath}-{where}-" |
| 2334 |
+ ('ins' if insecure else 'safe')) |
| 2335 |
rmtree(base) |
| 2336 |
base.mkdir(parents=True) |
| 2337 |
ctx = types.SimpleNamespace( |
| 2338 |
base=base, outside=base / 'outside', plant=base / 'plant', |
| 2339 |
owner=owner, att_uid=att, abspath=abspath, where=where, |
| 2340 |
insecure=insecure) |
| 2341 |
ctx.outside.mkdir() |
| 2342 |
ctx.plant.mkdir() |
| 2343 |
|
| 2344 |
def plant_link(at, target, _c=ctx): |
| 2345 |
os.symlink(target, at) |
| 2346 |
if _c.owner == 'cross': |
| 2347 |
os.lchown(at, _c.att_uid, _c.att_uid) |
| 2348 |
ctx.plant_link = plant_link |
| 2349 |
|
| 2350 |
followed = bool(case(ctx)) |
| 2351 |
expect = insecure or owner == 'self' |
| 2352 |
cell = f"{abspath} {where} {'insecure' if insecure else 'safe'}" |
| 2353 |
if followed and not expect: |
| 2354 |
test_fail( |
| 2355 |
f"{tag}: CROSS-UID {cell}: the planted symlink was " |
| 2356 |
"FOLLOWED (op escaped to outside/). An operator path " |
| 2357 |
"must refuse a symlink not owned by uid 0 or the euid.") |
| 2358 |
if not followed and expect: |
| 2359 |
why = ("--insecure-links did not restore symlink following" |
| 2360 |
if insecure else |
| 2361 |
"the operator's OWN (euid-owned) symlink was refused") |
| 2362 |
test_fail(f"{tag}: {('CROSS' if owner=='cross' else 'SAME')}" |
| 2363 |
f"-UID {cell}: {why}.") |
| 2364 |
if att is None and euid != 0: |
| 2365 |
print(f"{tag}: same-uid cells confirmed; cross-uid cells need root (skipped)") |
| 2366 |
|
| 2367 |
|
| 2368 |
def plant_operator_symlink(ctx, rel_anchor, kind='dir'): |
| 2369 |
"""Plant this cell's option-path symlink and return (option_value, escape). |
| 2370 |
|
| 2371 |
option_value is what to feed the option: an absolute path, or a name |
| 2372 |
relative to rel_anchor (the directory the option resolves a relative value |
| 2373 |
against -- e.g. the destination dir for --backup-dir/--link-dest, or the cwd |
| 2374 |
for --temp-dir). escape is the out-of-tree object the operation acts on IF |
| 2375 |
the symlink is followed. |
| 2376 |
|
| 2377 |
kind='dir' (a directory option, e.g. --backup-dir/--temp-dir/--link-dest): |
| 2378 |
leaf -> the symlink itself is the dir; escape = ctx.outside. |
| 2379 |
parent -> a parent component is the symlink; escape = ctx.outside/'sub'. |
| 2380 |
kind='file' (a file option, e.g. --log-file/--files-from/--write-batch): |
| 2381 |
leaf -> the symlink targets the out-of-tree victim file directly. |
| 2382 |
parent -> a parent component is the symlink; the leaf name is appended. |
| 2383 |
escape = ctx.outside/'victim' either way. |
| 2384 |
""" |
| 2385 |
base = ctx.plant if ctx.abspath == 'abs' else rel_anchor |
| 2386 |
if kind == 'file': |
| 2387 |
victim = ctx.outside / 'victim' |
| 2388 |
if ctx.where == 'leaf': |
| 2389 |
link = base / 'osl' |
| 2390 |
ctx.plant_link(link, victim) |
| 2391 |
return (str(link) if ctx.abspath == 'abs' else 'osl'), victim |
| 2392 |
link = base / 'opd' |
| 2393 |
ctx.plant_link(link, ctx.outside) |
| 2394 |
return ((str(link / 'victim') if ctx.abspath == 'abs' else 'opd/victim'), |
| 2395 |
victim) |
| 2396 |
if ctx.where == 'leaf': |
| 2397 |
link = base / 'osl' |
| 2398 |
ctx.plant_link(link, ctx.outside) |
| 2399 |
return (str(link) if ctx.abspath == 'abs' else 'osl'), ctx.outside |
| 2400 |
link = base / 'opd' |
| 2401 |
ctx.plant_link(link, ctx.outside) |
| 2402 |
return ((str(link / 'sub') if ctx.abspath == 'abs' else 'opd/sub'), |
| 2403 |
ctx.outside / 'sub') |
| 2404 |
|
| 2405 |
|
| 2406 |
|
| 2407 |
|
| 2408 |
|
| 2409 |
|
| 2410 |
|
| 2411 |
|
| 2412 |
|
| 2413 |
|
| 2414 |
|
| 2415 |
def acls_supported() -> bool: |
| 2416 |
"""True if this rsync was built with ACL support AND this platform has a |
| 2417 |
usable setfacl/getfacl (or macOS chmod +a). Mirrors xattrs_supported().""" |
| 2418 |
vv = run_rsync('-VV', check=True, capture_output=True).stdout |
| 2419 |
if '"ACLs": true' not in vv: |
| 2420 |
return False |
| 2421 |
if _SYSTEM in ('Linux', 'FreeBSD') or _CYGWIN: |
| 2422 |
return (shutil.which('setfacl') is not None |
| 2423 |
and shutil.which('getfacl') is not None) |
| 2424 |
if _SYSTEM == 'Darwin': |
| 2425 |
return shutil.which('chmod') is not None |
| 2426 |
return False |
| 2427 |
|
| 2428 |
|
| 2429 |
@_functools.lru_cache(maxsize=1) |
| 2430 |
def devices_supported() -> bool: |
| 2431 |
"""True if device nodes can be created here. |
| 2432 |
|
| 2433 |
euid==0 is necessary but not sufficient: a user-namespaced container |
| 2434 |
(rootless podman/docker, buildd chroots) reports euid==0 yet lacks |
| 2435 |
CAP_MKNOD, so os.mknod() of a device fails EPERM. Probe once.""" |
| 2436 |
if os.geteuid() != 0 or not hasattr(os, 'mknod'): |
| 2437 |
return False |
| 2438 |
with tempfile.TemporaryDirectory(prefix='rsync-devprobe.') as d: |
| 2439 |
try: |
| 2440 |
os.mknod(os.path.join(d, 'p'), 0o600 | stat.S_IFCHR, os.makedev(1, 3)) |
| 2441 |
except (PermissionError, OSError): |
| 2442 |
return False |
| 2443 |
return True |
| 2444 |
|
| 2445 |
|
| 2446 |
def hardlink_symlinks_supported(where=None) -> bool: |
| 2447 |
"""True if THIS FILESYSTEM can hard-link a symlink. |
| 2448 |
|
| 2449 |
rsync's own "hardlink_symlinks" capability is a build-time answer and says |
| 2450 |
nothing about the filesystem underneath: HFS+ returns ENOTSUP for |
| 2451 |
link()-ing a symlink where APFS and Linux succeed. Probe where the test |
| 2452 |
data will actually live, not where the source tree is.""" |
| 2453 |
d = tempfile.mkdtemp(prefix='rsync-hlsym.', dir=str(where) if where else None) |
| 2454 |
try: |
| 2455 |
link, hard = os.path.join(d, 's'), os.path.join(d, 'h') |
| 2456 |
os.symlink('target-need-not-exist', link) |
| 2457 |
try: |
| 2458 |
os.link(link, hard, follow_symlinks=False) |
| 2459 |
except NotImplementedError: |
| 2460 |
return False |
| 2461 |
except OSError as e: |
| 2462 |
|
| 2463 |
|
| 2464 |
|
| 2465 |
|
| 2466 |
if e.errno in (errno.ENOTSUP, getattr(errno, 'EOPNOTSUPP', errno.ENOTSUP)): |
| 2467 |
return False |
| 2468 |
raise |
| 2469 |
return True |
| 2470 |
finally: |
| 2471 |
shutil.rmtree(d, ignore_errors=True) |
| 2472 |
|
| 2473 |
|
| 2474 |
def owners_supported() -> bool: |
| 2475 |
"""True if the builder may assign mixed uid/gid (euid==0).""" |
| 2476 |
return os.geteuid() == 0 |
| 2477 |
|
| 2478 |
|
| 2479 |
def make_fifo(path) -> 'None': |
| 2480 |
"""Create a FIFO (named pipe) at `path`.""" |
| 2481 |
os.mkfifo(str(path)) |
| 2482 |
|
| 2483 |
|
| 2484 |
def make_socket(path) -> 'None': |
| 2485 |
"""Create a UNIX-domain socket inode at `path`. |
| 2486 |
|
| 2487 |
The AF_UNIX sun_path is capped at ~108 bytes, which a depth-8 absolute path |
| 2488 |
can overflow, so we chdir to the parent and bind the bare (short) basename, |
| 2489 |
restoring the cwd in a finally. The bound inode persists as an S_IFSOCK on |
| 2490 |
disk after the socket is closed.""" |
| 2491 |
path = Path(path) |
| 2492 |
old = os.getcwd() |
| 2493 |
s = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM) |
| 2494 |
try: |
| 2495 |
os.chdir(path.parent) |
| 2496 |
s.bind(path.name) |
| 2497 |
finally: |
| 2498 |
s.close() |
| 2499 |
os.chdir(old) |
| 2500 |
|
| 2501 |
|
| 2502 |
def make_device(path, kind: str, major: int, minor: int, |
| 2503 |
mode: int = 0o644) -> 'None': |
| 2504 |
"""Create a char ('c') or block ('b') device node. Caller must gate on |
| 2505 |
devices_supported() -- unprivileged this raises PermissionError.""" |
| 2506 |
fmt = stat.S_IFCHR if kind == 'c' else stat.S_IFBLK |
| 2507 |
os.mknod(str(path), mode | fmt, os.makedev(major, minor)) |
| 2508 |
|
| 2509 |
|
| 2510 |
def _acl_env() -> dict: |
| 2511 |
"""Environment for getfacl/setfacl: scrub POSIXLY_CORRECT (which alters |
| 2512 |
some getfacl builds' flag/header semantics) and pin LC_ALL=C.""" |
| 2513 |
env = dict(os.environ) |
| 2514 |
env.pop('POSIXLY_CORRECT', None) |
| 2515 |
env['LC_ALL'] = 'C' |
| 2516 |
return env |
| 2517 |
|
| 2518 |
|
| 2519 |
def acl_set(spec: str, path) -> bool: |
| 2520 |
"""Apply one ACL entry `spec` (e.g. 'u:0:rwx', 'g:0:r-x', 'd:u:0:rwx' for a |
| 2521 |
directory default entry) to `path` via setfacl. Returns True on success, |
| 2522 |
False if the filesystem rejects ACLs (EOPNOTSUPP) so the caller degrades |
| 2523 |
gracefully. macOS is not driven here (returns False).""" |
| 2524 |
if not (_SYSTEM in ('Linux', 'FreeBSD') or _CYGWIN): |
| 2525 |
return False |
| 2526 |
proc = subprocess.run(['setfacl', '-m', spec, str(path)], |
| 2527 |
capture_output=True, text=True, env=_acl_env()) |
| 2528 |
return proc.returncode == 0 |
| 2529 |
|
| 2530 |
|
| 2531 |
def _acl_sig(path) -> str: |
| 2532 |
"""Path-free signature of a node's ACL entries, for comparing two trees. |
| 2533 |
Strips getfacl's comment header (which embeds the path/owner) and sorts the |
| 2534 |
entries so the result depends only on the access/default ACL, not on where |
| 2535 |
the file lives. Empty when ACLs aren't readable here.""" |
| 2536 |
if not (_SYSTEM in ('Linux', 'FreeBSD') or _CYGWIN): |
| 2537 |
return '' |
| 2538 |
try: |
| 2539 |
out = subprocess.run(['getfacl', str(path)], capture_output=True, |
| 2540 |
text=True, env=_acl_env()).stdout |
| 2541 |
except OSError: |
| 2542 |
return '' |
| 2543 |
return ';'.join(sorted(l for l in out.splitlines() |
| 2544 |
if l.strip() and not l.startswith('#'))) |
| 2545 |
|
| 2546 |
|
| 2547 |
def _xattr_sig(path) -> str: |
| 2548 |
"""Path-free signature of a node's user xattrs, for comparing two trees. |
| 2549 |
Native on Linux (symmetric with xattr_set); getfattr with the '# file:' |
| 2550 |
header stripped on Cygwin. Returns '' elsewhere -- xattr fidelity is gated |
| 2551 |
on the Linux CI run, and tls still compares structure on every platform.""" |
| 2552 |
p = str(path) |
| 2553 |
if _SYSTEM == 'Linux': |
| 2554 |
try: |
| 2555 |
names = sorted(n for n in os.listxattr(p, follow_symlinks=False) |
| 2556 |
if n.startswith('user.')) |
| 2557 |
except OSError: |
| 2558 |
return '' |
| 2559 |
out = [] |
| 2560 |
for n in names: |
| 2561 |
try: |
| 2562 |
v = os.getxattr(p, n, follow_symlinks=False) |
| 2563 |
except OSError: |
| 2564 |
continue |
| 2565 |
out.append(n + '=' + v.decode('utf-8', 'surrogateescape')) |
| 2566 |
return ';'.join(out) |
| 2567 |
if _CYGWIN: |
| 2568 |
try: |
| 2569 |
d = subprocess.check_output( |
| 2570 |
['getfattr', '--no-dereference', '-d', p], |
| 2571 |
text=True, stderr=subprocess.DEVNULL) |
| 2572 |
except (subprocess.CalledProcessError, OSError): |
| 2573 |
return '' |
| 2574 |
return ';'.join(sorted(l for l in d.splitlines() |
| 2575 |
if l and not l.startswith('# file:'))) |
| 2576 |
return '' |
| 2577 |
|
| 2578 |
|
| 2579 |
def _variety_fill(path, size: int, key: str) -> 'None': |
| 2580 |
"""Write `size` bytes of deterministic, non-trivial content derived from |
| 2581 |
`key`, so a variety tree is byte-reproducible across separate builds.""" |
| 2582 |
import hashlib |
| 2583 |
buf = bytearray() |
| 2584 |
i = 0 |
| 2585 |
while len(buf) < size: |
| 2586 |
buf += hashlib.sha256(f'{key}:{i}'.encode()).digest() |
| 2587 |
i += 1 |
| 2588 |
with open(str(path), 'wb') as f: |
| 2589 |
f.write(bytes(buf[:size])) |
| 2590 |
|
| 2591 |
|
| 2592 |
def _all_entries(root) -> list: |
| 2593 |
"""Every entry under `root` (the root dir, real subdirs, files, specials, |
| 2594 |
and symlinks themselves) visited exactly once and WITHOUT following any |
| 2595 |
symlink. For chown/utime finalisation that must not escape the tree.""" |
| 2596 |
root = Path(root) |
| 2597 |
res = [] |
| 2598 |
for dp, dns, fns in os.walk(root): |
| 2599 |
d = Path(dp) |
| 2600 |
res.append(d) |
| 2601 |
for n in fns: |
| 2602 |
res.append(d / n) |
| 2603 |
for n in dns: |
| 2604 |
sub = d / n |
| 2605 |
if sub.is_symlink(): |
| 2606 |
res.append(sub) |
| 2607 |
return res |
| 2608 |
|
| 2609 |
|
| 2610 |
def make_variety_tree(root, *, depth: int = 8, with_acls=None, with_xattrs=None, |
| 2611 |
with_devices=None, with_owners=None, |
| 2612 |
seed: int = 0x5A17) -> dict: |
| 2613 |
"""Build a deterministic 'variety tree' rooted at `root`. |
| 2614 |
|
| 2615 |
Capability args default to None => auto-detect (xattrs_supported() etc.). |
| 2616 |
Tests pass EXPLICIT bools so the current- and old-binary source trees are |
| 2617 |
built with identical capabilities, keeping the differential comparison |
| 2618 |
apples-to-apples. Re-runnable: rmtree(root) first; `seed` drives only fixed |
| 2619 |
choices (no time/pid randomness) so two calls yield identical trees. |
| 2620 |
|
| 2621 |
Layout (caller transfers root/transfer_root/): |
| 2622 |
root/above/ real nodes ABOVE the transfer root (escape targets) |
| 2623 |
root/transfer_root d0..d{depth-1} backbone; at each level a bouquet of |
| 2624 |
every type + a symlink to every type; plus abs_links/ |
| 2625 |
(absolute links) and escape/ (../.. links that leave |
| 2626 |
the transfer root, one per above-root type). |
| 2627 |
|
| 2628 |
Returns {'transfer_root': Path, 'above_targets': {type: Path}, |
| 2629 |
'counts': {type: n}}. |
| 2630 |
""" |
| 2631 |
root = Path(root) |
| 2632 |
rmtree(root) |
| 2633 |
if with_xattrs is None: |
| 2634 |
with_xattrs = xattrs_supported() |
| 2635 |
if with_acls is None: |
| 2636 |
with_acls = acls_supported() |
| 2637 |
if with_devices is None: |
| 2638 |
with_devices = devices_supported() |
| 2639 |
if with_owners is None: |
| 2640 |
with_owners = owners_supported() |
| 2641 |
|
| 2642 |
root.mkdir(parents=True) |
| 2643 |
above = root / 'above' |
| 2644 |
above.mkdir() |
| 2645 |
troot = root / 'transfer_root' |
| 2646 |
troot.mkdir() |
| 2647 |
|
| 2648 |
counts = {} |
| 2649 |
def bump(t): |
| 2650 |
counts[t] = counts.get(t, 0) + 1 |
| 2651 |
|
| 2652 |
perm_cycle = [0o400, 0o640, 0o644, 0o600, 0o755] |
| 2653 |
|
| 2654 |
def reg(p, size, mode=0o644): |
| 2655 |
_variety_fill(p, size, f'{seed:x}:{os.path.relpath(p, root)}') |
| 2656 |
os.chmod(p, mode) |
| 2657 |
bump('file') |
| 2658 |
return p |
| 2659 |
|
| 2660 |
def mkdir1(p, mode=None): |
| 2661 |
p.mkdir() |
| 2662 |
if mode is not None: |
| 2663 |
os.chmod(p, mode) |
| 2664 |
bump('dir') |
| 2665 |
return p |
| 2666 |
|
| 2667 |
def lnk(target, p): |
| 2668 |
os.symlink(target, p) |
| 2669 |
bump('symlink') |
| 2670 |
return p |
| 2671 |
|
| 2672 |
|
| 2673 |
above_targets = {} |
| 2674 |
above_targets['dir'] = mkdir1(above / 'a_dir') |
| 2675 |
reg(above / 'a_dir' / 'inner', 256) |
| 2676 |
above_targets['file'] = reg(above / 'a_file', 8192) |
| 2677 |
above_targets['fifo'] = above / 'a_fifo'; make_fifo(above_targets['fifo']); bump('fifo') |
| 2678 |
above_targets['sock'] = above / 'a_sock'; make_socket(above_targets['sock']); bump('socket') |
| 2679 |
if with_devices: |
| 2680 |
above_targets['dev'] = above / 'a_dev_c' |
| 2681 |
make_device(above_targets['dev'], 'c', 1, 3); bump('device') |
| 2682 |
make_device(above / 'a_dev_b', 'b', 7, 0); bump('device') |
| 2683 |
above_targets['link'] = lnk('a_file', above / 'a_link') |
| 2684 |
|
| 2685 |
|
| 2686 |
cur = troot |
| 2687 |
for n in range(depth): |
| 2688 |
reg(cur / f'f{n}', 1024 * (n + 1)) |
| 2689 |
if n % 2 == 0: |
| 2690 |
os.link(cur / f'f{n}', cur / f'hl{n}') |
| 2691 |
bump('hardlink') |
| 2692 |
reg(cur / f'perm{n}', 700, perm_cycle[(seed + n) % len(perm_cycle)]) |
| 2693 |
reg(cur / f'setuid{n}', 512, 0o4755) |
| 2694 |
mkdir1(cur / f'setgid{n}', 0o2775) |
| 2695 |
mkdir1(cur / f'sticky{n}', 0o1777) |
| 2696 |
for k in range(3): |
| 2697 |
reg(cur / f'g{n}_{k}', 300) |
| 2698 |
make_fifo(cur / f'fifo{n}'); bump('fifo') |
| 2699 |
make_socket(cur / f'sk{n}'); bump('socket') |
| 2700 |
if with_devices: |
| 2701 |
make_device(cur / f'cdev{n}', 'c', 1, 5); bump('device') |
| 2702 |
make_device(cur / f'bdev{n}', 'b', 7, n); bump('device') |
| 2703 |
|
| 2704 |
lnk(f'f{n}', cur / f'ln2file{n}') |
| 2705 |
lnk(f'fifo{n}', cur / f'ln2fifo{n}') |
| 2706 |
lnk(f'sk{n}', cur / f'ln2sock{n}') |
| 2707 |
if with_devices: |
| 2708 |
lnk(f'cdev{n}', cur / f'ln2dev{n}') |
| 2709 |
lnk(f'ln2file{n}', cur / f'ln2ln{n}') |
| 2710 |
lnk(f'nonexistent_{n}', cur / f'dangling{n}') |
| 2711 |
if n < depth - 1: |
| 2712 |
nxt = mkdir1(cur / f'd{n + 1}') |
| 2713 |
lnk(f'd{n + 1}', cur / f'ln2dir{n}') |
| 2714 |
cur = nxt |
| 2715 |
|
| 2716 |
|
| 2717 |
absd = mkdir1(troot / 'abs_links') |
| 2718 |
lnk(str((troot / 'f0').resolve()), absd / 'abs_file') |
| 2719 |
lnk(str(above_targets['file'].resolve()), absd / 'abs_above') |
| 2720 |
|
| 2721 |
|
| 2722 |
escd = mkdir1(troot / 'escape') |
| 2723 |
lnk('../../above/a_dir', escd / 'esc_dir') |
| 2724 |
lnk('../../above/a_file', escd / 'esc_file') |
| 2725 |
lnk('../../above/a_fifo', escd / 'esc_fifo') |
| 2726 |
lnk('../../above/a_sock', escd / 'esc_sock') |
| 2727 |
if with_devices: |
| 2728 |
lnk('../../above/a_dev_c', escd / 'esc_dev') |
| 2729 |
lnk('../../above/a_link', escd / 'esc_link') |
| 2730 |
|
| 2731 |
lnk(f'../../../{root.name}/above/a_file', escd / 'esc_deep') |
| 2732 |
|
| 2733 |
|
| 2734 |
|
| 2735 |
if with_xattrs: |
| 2736 |
for p in walk_dirs(troot) + walk_files(troot): |
| 2737 |
try: |
| 2738 |
xattr_set('variety', os.path.basename(str(p)), p) |
| 2739 |
except OSError: |
| 2740 |
pass |
| 2741 |
|
| 2742 |
|
| 2743 |
if with_acls: |
| 2744 |
dirs = walk_dirs(troot) |
| 2745 |
files = walk_files(troot) |
| 2746 |
for i, d in enumerate(dirs): |
| 2747 |
if i % 3 == 0: |
| 2748 |
acl_set('u:0:rwx', d) |
| 2749 |
if i % 5 == 0: |
| 2750 |
acl_set('d:u:0:rwx', d) |
| 2751 |
for i, f in enumerate(files): |
| 2752 |
if i % 4 == 0: |
| 2753 |
acl_set('g:0:r-x', f) |
| 2754 |
|
| 2755 |
entries = sorted(_all_entries(root), key=lambda x: str(x)) |
| 2756 |
|
| 2757 |
|
| 2758 |
if with_owners: |
| 2759 |
idset = [(0, 0), (1, 1), (2, 2)] |
| 2760 |
for i, p in enumerate(entries): |
| 2761 |
uid, gid = idset[(seed + i) % len(idset)] |
| 2762 |
try: |
| 2763 |
os.chown(str(p), uid, gid, follow_symlinks=False) |
| 2764 |
except OSError: |
| 2765 |
pass |
| 2766 |
|
| 2767 |
|
| 2768 |
|
| 2769 |
base = 1_000_000_000 |
| 2770 |
for i, p in enumerate(entries): |
| 2771 |
t = base + (i * 7) % 1_000_000 |
| 2772 |
try: |
| 2773 |
os.utime(str(p), (t, t), follow_symlinks=False) |
| 2774 |
except (OSError, NotImplementedError, ValueError): |
| 2775 |
if not os.path.islink(str(p)): |
| 2776 |
try: |
| 2777 |
os.utime(str(p), (t, t)) |
| 2778 |
except OSError: |
| 2779 |
pass |
| 2780 |
|
| 2781 |
return {'transfer_root': troot, 'above_targets': above_targets, |
| 2782 |
'counts': counts} |
| 2783 |
|
| 2784 |
|
| 2785 |
def _rel_nonlink_entries(root) -> list: |
| 2786 |
"""Relative paths of every non-symlink entry (real dirs + non-symlink |
| 2787 |
files/specials) under `root`, sorted. Used to compare per-entry metadata |
| 2788 |
without following or descending into symlinks.""" |
| 2789 |
root = Path(root) |
| 2790 |
res = [] |
| 2791 |
for dirpath, _dirnames, filenames in os.walk(root): |
| 2792 |
d = Path(dirpath) |
| 2793 |
if d != root: |
| 2794 |
res.append(d.relative_to(root)) |
| 2795 |
for fn in filenames: |
| 2796 |
fp = d / fn |
| 2797 |
if not fp.is_symlink(): |
| 2798 |
res.append(fp.relative_to(root)) |
| 2799 |
return sorted(res, key=lambda p: str(p)) |
| 2800 |
|
| 2801 |
|
| 2802 |
def _safe_walk_files(root) -> list: |
| 2803 |
"""walk_files() variant that tolerates unreadable directories (skips them |
| 2804 |
instead of raising), for comparing trees whose mixed/foreign ownership can |
| 2805 |
leave some entries inaccessible to the current user.""" |
| 2806 |
root = Path(root) |
| 2807 |
res = [] |
| 2808 |
for dp, _dns, fns in os.walk(root): |
| 2809 |
d = Path(dp) |
| 2810 |
for n in fns: |
| 2811 |
p = d / n |
| 2812 |
try: |
| 2813 |
if p.is_file() and not p.is_symlink(): |
| 2814 |
res.append(p) |
| 2815 |
except OSError: |
| 2816 |
continue |
| 2817 |
return sorted(res, key=lambda x: str(x)) |
| 2818 |
|
| 2819 |
|
| 2820 |
def compare_trees(a, b, label: str = '', *, |
| 2821 |
with_acls: bool = True, |
| 2822 |
with_xattrs: bool = True) -> list: |
| 2823 |
"""Compare two trees WITHOUT ever opening a fifo/socket/device as a |
| 2824 |
stream. Returns a list of human-readable difference strings ([] == match); |
| 2825 |
the caller decides whether a difference is a fail or an xfail. |
| 2826 |
|
| 2827 |
Checks: (1) the tls listings (type+mode+owner+size+mtime+symlink target for |
| 2828 |
every inode); (2) byte-equality of regular files by relative path; (3) user |
| 2829 |
xattrs; (4) POSIX ACLs. Never uses `diff -r` (it blocks on specials).""" |
| 2830 |
a = Path(a) |
| 2831 |
b = Path(b) |
| 2832 |
pre = f"{label}: " if label else "" |
| 2833 |
diffs = [] |
| 2834 |
|
| 2835 |
la = rsync_ls_lR(a) |
| 2836 |
lb = rsync_ls_lR(b) |
| 2837 |
if la != lb: |
| 2838 |
import difflib |
| 2839 |
ud = ''.join(difflib.unified_diff( |
| 2840 |
la.splitlines(keepends=True), lb.splitlines(keepends=True), |
| 2841 |
fromfile=f'{a} (tls)', tofile=f'{b} (tls)')) |
| 2842 |
diffs.append(f"{pre}tls listings differ:\n{ud}") |
| 2843 |
|
| 2844 |
files_a = sorted(p.relative_to(a) for p in _safe_walk_files(a)) |
| 2845 |
files_b = sorted(p.relative_to(b) for p in _safe_walk_files(b)) |
| 2846 |
set_b = set(files_b) |
| 2847 |
if set(files_a) != set_b: |
| 2848 |
only_a = sorted(str(p) for p in set(files_a) - set_b) |
| 2849 |
only_b = sorted(str(p) for p in set_b - set(files_a)) |
| 2850 |
diffs.append(f"{pre}regular-file set differs: " |
| 2851 |
f"only in a={only_a} only in b={only_b}") |
| 2852 |
for rel in files_a: |
| 2853 |
if rel not in set_b: |
| 2854 |
continue |
| 2855 |
try: |
| 2856 |
same = filecmp.cmp(str(a / rel), str(b / rel), shallow=False) |
| 2857 |
except OSError as e: |
| 2858 |
diffs.append(f"{pre}cannot compare contents of {rel} " |
| 2859 |
f"(permission denied?): {e}") |
| 2860 |
continue |
| 2861 |
if not same: |
| 2862 |
diffs.append(f"{pre}content differs: {rel}") |
| 2863 |
|
| 2864 |
|
| 2865 |
def _hl_groups(rootp): |
| 2866 |
from collections import defaultdict |
| 2867 |
ino = defaultdict(list) |
| 2868 |
for p in _safe_walk_files(rootp): |
| 2869 |
try: |
| 2870 |
st = p.stat() |
| 2871 |
except OSError: |
| 2872 |
continue |
| 2873 |
if st.st_nlink > 1: |
| 2874 |
ino[(st.st_dev, st.st_ino)].append(str(p.relative_to(rootp))) |
| 2875 |
return sorted(tuple(sorted(v)) for v in ino.values() if len(v) > 1) |
| 2876 |
ga, gb = _hl_groups(a), _hl_groups(b) |
| 2877 |
if ga != gb: |
| 2878 |
diffs.append(f"{pre}hard-link grouping differs: a={ga} b={gb}") |
| 2879 |
|
| 2880 |
if with_xattrs or with_acls: |
| 2881 |
for rel in _rel_nonlink_entries(a): |
| 2882 |
pa = a / rel |
| 2883 |
pb = b / rel |
| 2884 |
if not pb.exists(): |
| 2885 |
continue |
| 2886 |
if with_xattrs: |
| 2887 |
xa, xb = _xattr_sig(pa), _xattr_sig(pb) |
| 2888 |
if xa != xb: |
| 2889 |
diffs.append(f"{pre}xattr differs: {rel} " |
| 2890 |
f"(a={xa!r} b={xb!r})") |
| 2891 |
if with_acls: |
| 2892 |
aa, ab = _acl_sig(pa), _acl_sig(pb) |
| 2893 |
if aa != ab: |
| 2894 |
diffs.append(f"{pre}ACL differs: {rel} " |
| 2895 |
f"(a={aa!r} b={ab!r})") |
| 2896 |
|
| 2897 |
return diffs |
| 2898 |
|
| 2899 |
|
| 2900 |
def assert_trees_equal(a, b, label: str = '', **kwargs) -> 'None': |
| 2901 |
"""compare_trees(); test_fail() on any difference.""" |
| 2902 |
diffs = compare_trees(a, b, label, **kwargs) |
| 2903 |
if diffs: |
| 2904 |
test_fail('\n'.join(diffs)) |