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