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