Debian Codegraph @

testsuite/chown_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # Python rewrite of testsuite/chown.test (and, via a symlink installed by
3 # the Makefile as chown-fake_test.py, of testsuite/chown-fake.test).
4 #
5 # Verifies that rsync -a + ownership-preservation sets the destination
6 # uid/gid to match the source. The "real" variant needs root to chown(2);
7 # the "fake" variant emulates ownership in the user.rsync.%stat xattr and
8 # tests --fake-super.
9
10 import os
11 import sys
12
13 import rsyncfns
14 from rsyncfns import (
15 FROMDIR, RSYNC_PREFIX, TODIR,
16 checkit, test_skipped, xattr_set, xattrs_supported,
17 )
18
19
20 # Detect fake variant by the script name we were invoked under. The
21 # Makefile creates chown-fake_test.py as a symlink to this file.
22 script_name = os.path.basename(sys.argv[0] if sys.argv[0] else __file__)
23 fake_variant = 'fake' in script_name
24
25 if fake_variant:
26 # --fake-super needs xattrs support (and a way to set them here).
27 if not xattrs_supported():
28 test_skipped("Rsync needs xattrs for fake device tests")
29 # Augment the RSYNC command and TLS_ARGS so checkit's listing path
30 # treats the xattr-encoded ownership as the file's real ownership.
31 rsyncfns.RSYNC = rsyncfns.RSYNC + ' --fake-super'
32 rsyncfns.TLS_ARGS = (rsyncfns.TLS_ARGS + ' --fake-super').strip()
33
34 def chown_or_fake(path, uid, gid):
35 # Store ownership in rsync's fake-super "%stat" xattr -- the name
36 # (RSYNC_PREFIX) and namespace vary by OS; xattr_set handles that.
37 # %stat format: "MODE DEV_MAJOR,DEV_MINOR UID:GID"
38 mode = os.stat(path).st_mode
39 xattr_set(f'{RSYNC_PREFIX}.%stat', f"{mode:o} 0,0 {uid}:{gid}", path)
40 return True
41 else:
42 rsyncfns.RSYNC = rsyncfns.RSYNC + ' --super'
43
44 my_uid = os.getuid()
45 if my_uid != 0:
46 # If a fakeroot binary is in the environment, re-exec ourselves
47 # under it -- same trick the shell test used.
48 fakeroot_path = os.environ.get('FAKEROOT_PATH')
49 if fakeroot_path and os.access(fakeroot_path, os.X_OK):
50 print("Let's try re-running the script under fakeroot...")
51 os.execv(fakeroot_path, [fakeroot_path, sys.executable, __file__])
52
53 def chown_or_fake(path, uid, gid):
54 try:
55 os.chown(path, uid, gid)
56 return True
57 except (PermissionError, OSError):
58 return False
59
60
61 FROMDIR.mkdir(parents=True, exist_ok=True)
62 name1 = FROMDIR / 'name1'
63 name2 = FROMDIR / 'name2'
64 name1.write_text("This is the file\n")
65 name2.write_text("This is the other file\n")
66
67 if not chown_or_fake(name1, 5000, 5002):
68 test_skipped("Can't chown (probably need root)")
69 if not chown_or_fake(name2, 5001, 5003):
70 test_skipped("Can't chown (probably need root)")
71
72 os.chdir(FROMDIR.parent)
73 checkit(['-aHvv', 'from/', 'to/'], FROMDIR, TODIR)