]> arthur.barton.de Git - bup.git/blob - lib/bup/t/tmetadata.py
cirrus: allow failures on macos with python 2
[bup.git] / lib / bup / t / tmetadata.py
1
2 from __future__ import absolute_import, print_function
3 import errno, glob, grp, pwd, stat, tempfile, subprocess
4
5 from wvtest import *
6
7 from bup import git, metadata
8 from bup import vfs
9 from bup.compat import range
10 from bup.helpers import clear_errors, detect_fakeroot, is_superuser, resolve_parent
11 from bup.repo import LocalRepo
12 from bup.xstat import utime, lutime
13 from buptest import no_lingering_errors, test_tempdir
14 import bup.helpers as helpers
15
16
17 top_dir = b'../../..'
18 bup_tmp = os.path.realpath(b'../../../t/tmp')
19 bup_path = top_dir + b'/bup'
20 start_dir = os.getcwd()
21
22
23 def ex(*cmd):
24     try:
25         cmd_str = b' '.join(cmd)
26         print(cmd_str, file=sys.stderr)
27         rc = subprocess.call(cmd)
28         if rc < 0:
29             print('terminated by signal', - rc, file=sys.stderr)
30             sys.exit(1)
31         elif rc > 0:
32             print('returned exit status', rc, file=sys.stderr)
33             sys.exit(1)
34     except OSError as e:
35         print('subprocess call failed:', e, file=sys.stderr)
36         sys.exit(1)
37
38
39 def setup_testfs():
40     assert(sys.platform.startswith('linux'))
41     # Set up testfs with user_xattr, etc.
42     if subprocess.call([b'modprobe', b'loop']) != 0:
43         return False
44     subprocess.call([b'umount', b'testfs'])
45     ex(b'dd', b'if=/dev/zero', b'of=testfs.img', b'bs=1M', b'count=32')
46     ex(b'mke2fs', b'-F', b'-j', b'-m', b'0', b'testfs.img')
47     ex(b'rm', b'-rf', b'testfs')
48     os.mkdir(b'testfs')
49     ex(b'mount', b'-o', b'loop,acl,user_xattr', b'testfs.img', b'testfs')
50     # Hide, so that tests can't create risks.
51     os.chown(b'testfs', 0, 0)
52     os.chmod(b'testfs', 0o700)
53     return True
54
55
56 def cleanup_testfs():
57     subprocess.call([b'umount', b'testfs'])
58     helpers.unlink(b'testfs.img')
59
60
61 @wvtest
62 def test_clean_up_archive_path():
63     with no_lingering_errors():
64         cleanup = metadata._clean_up_path_for_archive
65         WVPASSEQ(cleanup(b'foo'), b'foo')
66         WVPASSEQ(cleanup(b'/foo'), b'foo')
67         WVPASSEQ(cleanup(b'///foo'), b'foo')
68         WVPASSEQ(cleanup(b'/foo/bar'), b'foo/bar')
69         WVPASSEQ(cleanup(b'foo/./bar'), b'foo/bar')
70         WVPASSEQ(cleanup(b'/foo/./bar'), b'foo/bar')
71         WVPASSEQ(cleanup(b'/foo/./bar/././baz'), b'foo/bar/baz')
72         WVPASSEQ(cleanup(b'/foo/./bar///././baz'), b'foo/bar/baz')
73         WVPASSEQ(cleanup(b'//./foo/./bar///././baz/.///'), b'foo/bar/baz/')
74         WVPASSEQ(cleanup(b'./foo/./.bar'), b'foo/.bar')
75         WVPASSEQ(cleanup(b'./foo/.'), b'foo')
76         WVPASSEQ(cleanup(b'./foo/..'), b'.')
77         WVPASSEQ(cleanup(b'//./..//.../..//.'), b'.')
78         WVPASSEQ(cleanup(b'//./..//..././/.'), b'...')
79         WVPASSEQ(cleanup(b'/////.'), b'.')
80         WVPASSEQ(cleanup(b'/../'), b'.')
81         WVPASSEQ(cleanup(b''), b'.')
82
83
84 @wvtest
85 def test_risky_path():
86     with no_lingering_errors():
87         risky = metadata._risky_path
88         WVPASS(risky(b'/foo'))
89         WVPASS(risky(b'///foo'))
90         WVPASS(risky(b'/../foo'))
91         WVPASS(risky(b'../foo'))
92         WVPASS(risky(b'foo/..'))
93         WVPASS(risky(b'foo/../'))
94         WVPASS(risky(b'foo/../bar'))
95         WVFAIL(risky(b'foo'))
96         WVFAIL(risky(b'foo/'))
97         WVFAIL(risky(b'foo///'))
98         WVFAIL(risky(b'./foo'))
99         WVFAIL(risky(b'foo/.'))
100         WVFAIL(risky(b'./foo/.'))
101         WVFAIL(risky(b'foo/bar'))
102         WVFAIL(risky(b'foo/./bar'))
103
104
105 @wvtest
106 def test_clean_up_extract_path():
107     with no_lingering_errors():
108         cleanup = metadata._clean_up_extract_path
109         WVPASSEQ(cleanup(b'/foo'), b'foo')
110         WVPASSEQ(cleanup(b'///foo'), b'foo')
111         WVFAIL(cleanup(b'/../foo'))
112         WVFAIL(cleanup(b'../foo'))
113         WVFAIL(cleanup(b'foo/..'))
114         WVFAIL(cleanup(b'foo/../'))
115         WVFAIL(cleanup(b'foo/../bar'))
116         WVPASSEQ(cleanup(b'foo'), b'foo')
117         WVPASSEQ(cleanup(b'foo/'), b'foo/')
118         WVPASSEQ(cleanup(b'foo///'), b'foo///')
119         WVPASSEQ(cleanup(b'./foo'), b'./foo')
120         WVPASSEQ(cleanup(b'foo/.'), b'foo/.')
121         WVPASSEQ(cleanup(b'./foo/.'), b'./foo/.')
122         WVPASSEQ(cleanup(b'foo/bar'), b'foo/bar')
123         WVPASSEQ(cleanup(b'foo/./bar'), b'foo/./bar')
124         WVPASSEQ(cleanup(b'/'), b'.')
125         WVPASSEQ(cleanup(b'./'), b'./')
126         WVPASSEQ(cleanup(b'///foo/bar'), b'foo/bar')
127         WVPASSEQ(cleanup(b'///foo/bar'), b'foo/bar')
128
129
130 @wvtest
131 def test_metadata_method():
132     with no_lingering_errors():
133         with test_tempdir(b'bup-tmetadata-') as tmpdir:
134             bup_dir = tmpdir + b'/bup'
135             data_path = tmpdir + b'/foo'
136             os.mkdir(data_path)
137             ex(b'touch', data_path + b'/file')
138             ex(b'ln', b'-s', b'file', data_path + b'/symlink')
139             test_time1 = 13 * 1000000000
140             test_time2 = 42 * 1000000000
141             utime(data_path + b'/file', (0, test_time1))
142             lutime(data_path + b'/symlink', (0, 0))
143             utime(data_path, (0, test_time2))
144             ex(bup_path, b'-d', bup_dir, b'init')
145             ex(bup_path, b'-d', bup_dir, b'index', b'-v', data_path)
146             ex(bup_path, b'-d', bup_dir, b'save', b'-tvvn', b'test', data_path)
147             git.check_repo_or_die(bup_dir)
148             repo = LocalRepo()
149             resolved = vfs.resolve(repo,
150                                    b'/test/latest' + resolve_parent(data_path),
151                                    follow=False)
152             leaf_name, leaf_item = resolved[-1]
153             m = leaf_item.meta
154             WVPASS(m.mtime == test_time2)
155             WVPASS(leaf_name == b'foo')
156             contents = tuple(vfs.contents(repo, leaf_item))
157             WVPASS(len(contents) == 3)
158             WVPASSEQ(frozenset(name for name, item in contents),
159                      frozenset((b'.', b'file', b'symlink')))
160             for name, item in contents:
161                 if name == b'file':
162                     m = item.meta
163                     WVPASS(m.mtime == test_time1)
164                 elif name == b'symlink':
165                     m = item.meta
166                     WVPASSEQ(m.symlink_target, b'file')
167                     WVPASSEQ(m.size, 4)
168                     WVPASSEQ(m.mtime, 0)
169
170
171 def _first_err():
172     if helpers.saved_errors:
173         return str(helpers.saved_errors[0])
174     return ''
175
176
177 @wvtest
178 def test_from_path_error():
179     if is_superuser() or detect_fakeroot():
180         return
181     with no_lingering_errors():
182         with test_tempdir(b'bup-tmetadata-') as tmpdir:
183             path = tmpdir + b'/foo'
184             os.mkdir(path)
185             m = metadata.from_path(path, archive_path=path, save_symlinks=True)
186             WVPASSEQ(m.path, path)
187             os.chmod(path, 0o000)
188             metadata.from_path(path, archive_path=path, save_symlinks=True)
189             if metadata.get_linux_file_attr:
190                 print('saved_errors:', helpers.saved_errors, file=sys.stderr)
191                 WVPASS(len(helpers.saved_errors) == 1)
192                 errmsg = _first_err()
193                 WVPASS(errmsg.startswith('read Linux attr'))
194                 clear_errors()
195
196
197 def _linux_attr_supported(path):
198     # Expects path to denote a regular file or a directory.
199     if not metadata.get_linux_file_attr:
200         return False
201     try:
202         metadata.get_linux_file_attr(path)
203     except OSError as e:
204         if e.errno in (errno.ENOTTY, errno.ENOSYS, errno.EOPNOTSUPP):
205             return False
206         else:
207             raise
208     return True
209
210
211 @wvtest
212 def test_apply_to_path_restricted_access():
213     if is_superuser() or detect_fakeroot():
214         return
215     if sys.platform.startswith('cygwin'):
216         return # chmod 000 isn't effective.
217     with no_lingering_errors():
218         with test_tempdir(b'bup-tmetadata-') as tmpdir:
219             parent = tmpdir + b'/foo'
220             path = parent + b'/bar'
221             os.mkdir(parent)
222             os.mkdir(path)
223             clear_errors()
224             if metadata.xattr:
225                 try:
226                     metadata.xattr.set(path, b'user.buptest', b'bup')
227                 except:
228                     print("failed to set test xattr")
229                     # ignore any failures here - maybe FS cannot do it
230                     pass
231             m = metadata.from_path(path, archive_path=path, save_symlinks=True)
232             WVPASSEQ(m.path, path)
233             os.chmod(parent, 0o000)
234             m.apply_to_path(path)
235             print('saved_errors:', helpers.saved_errors, file=sys.stderr)
236             expected_errors = ['utime: ']
237             if m.linux_attr and _linux_attr_supported(tmpdir):
238                 expected_errors.append('Linux chattr: ')
239             if metadata.xattr and m.linux_xattr:
240                 expected_errors.append("xattr.set ")
241             WVPASS(len(helpers.saved_errors) == len(expected_errors))
242             for i in range(len(expected_errors)):
243                 WVPASS(str(helpers.saved_errors[i]).startswith(expected_errors[i]))
244             clear_errors()
245
246
247 @wvtest
248 def test_restore_over_existing_target():
249     with no_lingering_errors():
250         with test_tempdir(b'bup-tmetadata-') as tmpdir:
251             path = tmpdir + b'/foo'
252             os.mkdir(path)
253             dir_m = metadata.from_path(path, archive_path=path, save_symlinks=True)
254             os.rmdir(path)
255             open(path, 'w').close()
256             file_m = metadata.from_path(path, archive_path=path, save_symlinks=True)
257             # Restore dir over file.
258             WVPASSEQ(dir_m.create_path(path, create_symlinks=True), None)
259             WVPASS(stat.S_ISDIR(os.stat(path).st_mode))
260             # Restore dir over dir.
261             WVPASSEQ(dir_m.create_path(path, create_symlinks=True), None)
262             WVPASS(stat.S_ISDIR(os.stat(path).st_mode))
263             # Restore file over dir.
264             WVPASSEQ(file_m.create_path(path, create_symlinks=True), None)
265             WVPASS(stat.S_ISREG(os.stat(path).st_mode))
266             # Restore file over file.
267             WVPASSEQ(file_m.create_path(path, create_symlinks=True), None)
268             WVPASS(stat.S_ISREG(os.stat(path).st_mode))
269             # Restore file over non-empty dir.
270             os.remove(path)
271             os.mkdir(path)
272             open(path + b'/bar', 'w').close()
273             WVEXCEPT(Exception, file_m.create_path, path, create_symlinks=True)
274             # Restore dir over non-empty dir.
275             os.remove(path + b'/bar')
276             os.mkdir(path + b'/bar')
277             WVEXCEPT(Exception, dir_m.create_path, path, create_symlinks=True)
278
279
280 from bup.metadata import read_acl
281 if not read_acl:
282     @wvtest
283     def POSIX1E_ACL_SUPPORT_IS_MISSING():
284         pass
285
286
287 from bup.metadata import xattr
288 if xattr:
289     def remove_selinux(attrs):
290         return list(filter(lambda i: not i in (b'security.selinux', ),
291                            attrs))
292
293     @wvtest
294     def test_handling_of_incorrect_existing_linux_xattrs():
295         if not is_superuser() or detect_fakeroot():
296             WVMSG('skipping test -- not superuser')
297             return
298         if not setup_testfs():
299             WVMSG('unable to load loop module; skipping dependent tests')
300             return
301         for f in glob.glob(b'testfs/*'):
302             ex(b'rm', b'-rf', f)
303         path = b'testfs/foo'
304         open(path, 'w').close()
305         xattr.set(path, b'foo', b'bar', namespace=xattr.NS_USER)
306         m = metadata.from_path(path, archive_path=path, save_symlinks=True)
307         xattr.set(path, b'baz', b'bax', namespace=xattr.NS_USER)
308         m.apply_to_path(path, restore_numeric_ids=False)
309         WVPASSEQ(remove_selinux(xattr.list(path)), [b'user.foo'])
310         WVPASSEQ(xattr.get(path, b'user.foo'), b'bar')
311         xattr.set(path, b'foo', b'baz', namespace=xattr.NS_USER)
312         m.apply_to_path(path, restore_numeric_ids=False)
313         WVPASSEQ(remove_selinux(xattr.list(path)), [b'user.foo'])
314         WVPASSEQ(xattr.get(path, b'user.foo'), b'bar')
315         xattr.remove(path, b'foo', namespace=xattr.NS_USER)
316         m.apply_to_path(path, restore_numeric_ids=False)
317         WVPASSEQ(remove_selinux(xattr.list(path)), [b'user.foo'])
318         WVPASSEQ(xattr.get(path, b'user.foo'), b'bar')
319         os.chdir(start_dir)
320         cleanup_testfs()