archiver.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. from binascii import hexlify
  2. from configparser import RawConfigParser
  3. import os
  4. from io import StringIO
  5. import stat
  6. import subprocess
  7. import sys
  8. import shutil
  9. import tempfile
  10. import time
  11. import unittest
  12. from hashlib import sha256
  13. from attic import xattr
  14. from attic.archive import Archive, ChunkBuffer, CHUNK_MAX
  15. from attic.archiver import Archiver
  16. from attic.cache import Cache
  17. from attic.crypto import bytes_to_long, num_aes_blocks
  18. from attic.helpers import Manifest
  19. from attic.remote import RemoteRepository, PathNotAllowed
  20. from attic.repository import Repository
  21. from attic.testsuite import AtticTestCase
  22. from attic.testsuite.mock import patch
  23. try:
  24. import llfuse
  25. has_llfuse = True
  26. except ImportError:
  27. has_llfuse = False
  28. has_lchflags = hasattr(os, 'lchflags')
  29. src_dir = os.path.join(os.getcwd(), os.path.dirname(__file__), '..')
  30. class changedir:
  31. def __init__(self, dir):
  32. self.dir = dir
  33. def __enter__(self):
  34. self.old = os.getcwd()
  35. os.chdir(self.dir)
  36. def __exit__(self, *args, **kw):
  37. os.chdir(self.old)
  38. class environment_variable:
  39. def __init__(self, **values):
  40. self.values = values
  41. self.old_values = {}
  42. def __enter__(self):
  43. for k, v in self.values.items():
  44. self.old_values[k] = os.environ.get(k)
  45. os.environ[k] = v
  46. def __exit__(self, *args, **kw):
  47. for k, v in self.old_values.items():
  48. if v is not None:
  49. os.environ[k] = v
  50. class ArchiverTestCaseBase(AtticTestCase):
  51. prefix = ''
  52. def setUp(self):
  53. os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = '1'
  54. self.archiver = Archiver()
  55. self.tmpdir = tempfile.mkdtemp()
  56. self.repository_path = os.path.join(self.tmpdir, 'repository')
  57. self.repository_location = self.prefix + self.repository_path
  58. self.input_path = os.path.join(self.tmpdir, 'input')
  59. self.output_path = os.path.join(self.tmpdir, 'output')
  60. self.keys_path = os.path.join(self.tmpdir, 'keys')
  61. self.cache_path = os.path.join(self.tmpdir, 'cache')
  62. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  63. os.environ['BORG_KEYS_DIR'] = self.keys_path
  64. os.environ['BORG_CACHE_DIR'] = self.cache_path
  65. os.mkdir(self.input_path)
  66. os.mkdir(self.output_path)
  67. os.mkdir(self.keys_path)
  68. os.mkdir(self.cache_path)
  69. with open(self.exclude_file_path, 'wb') as fd:
  70. fd.write(b'input/file2\n# A commment line, then a blank line\n\n')
  71. self._old_wd = os.getcwd()
  72. os.chdir(self.tmpdir)
  73. def tearDown(self):
  74. shutil.rmtree(self.tmpdir)
  75. os.chdir(self._old_wd)
  76. def attic(self, *args, **kw):
  77. exit_code = kw.get('exit_code', 0)
  78. fork = kw.get('fork', False)
  79. if fork:
  80. try:
  81. output = subprocess.check_output((sys.executable, '-m', 'attic.archiver') + args)
  82. ret = 0
  83. except subprocess.CalledProcessError as e:
  84. output = e.output
  85. ret = e.returncode
  86. output = os.fsdecode(output)
  87. if ret != exit_code:
  88. print(output)
  89. self.assert_equal(exit_code, ret)
  90. return output
  91. args = list(args)
  92. stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
  93. try:
  94. sys.stdin = StringIO()
  95. output = StringIO()
  96. sys.stdout = sys.stderr = output
  97. ret = self.archiver.run(args)
  98. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  99. if ret != exit_code:
  100. print(output.getvalue())
  101. self.assert_equal(exit_code, ret)
  102. return output.getvalue()
  103. finally:
  104. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  105. def create_src_archive(self, name):
  106. self.attic('create', self.repository_location + '::' + name, src_dir)
  107. class ArchiverTestCase(ArchiverTestCaseBase):
  108. def create_regular_file(self, name, size=0, contents=None):
  109. filename = os.path.join(self.input_path, name)
  110. if not os.path.exists(os.path.dirname(filename)):
  111. os.makedirs(os.path.dirname(filename))
  112. with open(filename, 'wb') as fd:
  113. if contents is None:
  114. contents = b'X' * size
  115. fd.write(contents)
  116. def create_test_files(self):
  117. """Create a minimal test case including all supported file types
  118. """
  119. # File
  120. self.create_regular_file('empty', size=0)
  121. # next code line raises OverflowError on 32bit cpu (raspberry pi 2):
  122. # 2600-01-01 > 2**64 ns
  123. #os.utime('input/empty', (19880895600, 19880895600))
  124. # thus, we better test with something not that far in future:
  125. # 2038-01-19 (1970 + 2^31 - 1 seconds) is the 32bit "deadline":
  126. os.utime('input/empty', (2**31 - 1, 2**31 - 1))
  127. self.create_regular_file('file1', size=1024 * 80)
  128. self.create_regular_file('flagfile', size=1024)
  129. # Directory
  130. self.create_regular_file('dir2/file2', size=1024 * 80)
  131. # File owner
  132. os.chown('input/file1', 100, 200)
  133. # File mode
  134. os.chmod('input/file1', 0o7755)
  135. os.chmod('input/dir2', 0o555)
  136. # Block device
  137. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  138. # Char device
  139. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  140. # Hard link
  141. os.link(os.path.join(self.input_path, 'file1'),
  142. os.path.join(self.input_path, 'hardlink'))
  143. # Symlink
  144. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  145. if xattr.is_enabled(self.input_path):
  146. xattr.setxattr(os.path.join(self.input_path, 'file1'), 'user.foo', b'bar')
  147. # XXX this always fails for me
  148. # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot
  149. # same for newer ubuntu and centos.
  150. # if this is supported just on specific platform, platform should be checked first,
  151. # so that the test setup for all tests using it does not fail here always for others.
  152. #xattr.setxattr(os.path.join(self.input_path, 'link1'), 'user.foo_symlink', b'bar_symlink', follow_symlinks=False)
  153. # FIFO node
  154. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  155. if has_lchflags:
  156. os.lchflags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP)
  157. def test_basic_functionality(self):
  158. self.create_test_files()
  159. self.attic('init', self.repository_location)
  160. self.attic('create', self.repository_location + '::test', 'input')
  161. self.attic('create', self.repository_location + '::test.2', 'input')
  162. with changedir('output'):
  163. self.attic('extract', self.repository_location + '::test')
  164. self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
  165. self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 11)
  166. self.assert_dirs_equal('input', 'output/input')
  167. info_output = self.attic('info', self.repository_location + '::test')
  168. self.assert_in('Number of files: 4', info_output)
  169. shutil.rmtree(self.cache_path)
  170. with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='1'):
  171. info_output2 = self.attic('info', self.repository_location + '::test')
  172. # info_output2 starts with some "initializing cache" text but should
  173. # end the same way as info_output
  174. assert info_output2.endswith(info_output)
  175. def _extract_repository_id(self, path):
  176. return Repository(self.repository_path).id
  177. def _set_repository_id(self, path, id):
  178. config = RawConfigParser()
  179. config.read(os.path.join(path, 'config'))
  180. config.set('repository', 'id', hexlify(id).decode('ascii'))
  181. with open(os.path.join(path, 'config'), 'w') as fd:
  182. config.write(fd)
  183. return Repository(self.repository_path).id
  184. def test_sparse_file(self):
  185. # no sparse file support on Mac OS X
  186. sparse_support = sys.platform != 'darwin'
  187. filename = os.path.join(self.input_path, 'sparse')
  188. content = b'foobar'
  189. hole_size = 5 * CHUNK_MAX # 5 full chunker buffers
  190. with open(filename, 'wb') as fd:
  191. # create a file that has a hole at the beginning and end (if the
  192. # OS and filesystem supports sparse files)
  193. fd.seek(hole_size, 1)
  194. fd.write(content)
  195. fd.seek(hole_size, 1)
  196. pos = fd.tell()
  197. fd.truncate(pos)
  198. total_len = hole_size + len(content) + hole_size
  199. st = os.stat(filename)
  200. self.assert_equal(st.st_size, total_len)
  201. if sparse_support and hasattr(st, 'st_blocks'):
  202. self.assert_true(st.st_blocks * 512 < total_len / 10) # is input sparse?
  203. self.attic('init', self.repository_location)
  204. self.attic('create', self.repository_location + '::test', 'input')
  205. with changedir('output'):
  206. self.attic('extract', '--sparse', self.repository_location + '::test')
  207. self.assert_dirs_equal('input', 'output/input')
  208. filename = os.path.join(self.output_path, 'input', 'sparse')
  209. with open(filename, 'rb') as fd:
  210. # check if file contents are as expected
  211. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  212. self.assert_equal(fd.read(len(content)), content)
  213. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  214. st = os.stat(filename)
  215. self.assert_equal(st.st_size, total_len)
  216. if sparse_support and hasattr(st, 'st_blocks'):
  217. self.assert_true(st.st_blocks * 512 < total_len / 10) # is output sparse?
  218. def test_repository_swap_detection(self):
  219. self.create_test_files()
  220. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  221. self.attic('init', '--encryption=passphrase', self.repository_location)
  222. repository_id = self._extract_repository_id(self.repository_path)
  223. self.attic('create', self.repository_location + '::test', 'input')
  224. shutil.rmtree(self.repository_path)
  225. self.attic('init', '--encryption=none', self.repository_location)
  226. self._set_repository_id(self.repository_path, repository_id)
  227. self.assert_equal(repository_id, self._extract_repository_id(self.repository_path))
  228. self.assert_raises(Cache.EncryptionMethodMismatch, lambda :self.attic('create', self.repository_location + '::test.2', 'input'))
  229. def test_repository_swap_detection2(self):
  230. self.create_test_files()
  231. self.attic('init', '--encryption=none', self.repository_location + '_unencrypted')
  232. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  233. self.attic('init', '--encryption=passphrase', self.repository_location + '_encrypted')
  234. self.attic('create', self.repository_location + '_encrypted::test', 'input')
  235. shutil.rmtree(self.repository_path + '_encrypted')
  236. os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted')
  237. self.assert_raises(Cache.RepositoryAccessAborted, lambda :self.attic('create', self.repository_location + '_encrypted::test.2', 'input'))
  238. def test_strip_components(self):
  239. self.attic('init', self.repository_location)
  240. self.create_regular_file('dir/file')
  241. self.attic('create', self.repository_location + '::test', 'input')
  242. with changedir('output'):
  243. self.attic('extract', self.repository_location + '::test', '--strip-components', '3')
  244. self.assert_true(not os.path.exists('file'))
  245. with self.assert_creates_file('file'):
  246. self.attic('extract', self.repository_location + '::test', '--strip-components', '2')
  247. with self.assert_creates_file('dir/file'):
  248. self.attic('extract', self.repository_location + '::test', '--strip-components', '1')
  249. with self.assert_creates_file('input/dir/file'):
  250. self.attic('extract', self.repository_location + '::test', '--strip-components', '0')
  251. def test_extract_include_exclude(self):
  252. self.attic('init', self.repository_location)
  253. self.create_regular_file('file1', size=1024 * 80)
  254. self.create_regular_file('file2', size=1024 * 80)
  255. self.create_regular_file('file3', size=1024 * 80)
  256. self.create_regular_file('file4', size=1024 * 80)
  257. self.attic('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  258. with changedir('output'):
  259. self.attic('extract', self.repository_location + '::test', 'input/file1', )
  260. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  261. with changedir('output'):
  262. self.attic('extract', '--exclude=input/file2', self.repository_location + '::test')
  263. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  264. with changedir('output'):
  265. self.attic('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  266. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  267. def test_exclude_caches(self):
  268. self.attic('init', self.repository_location)
  269. self.create_regular_file('file1', size=1024 * 80)
  270. self.create_regular_file('cache1/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  271. self.create_regular_file('cache2/CACHEDIR.TAG', contents=b'invalid signature')
  272. self.attic('create', '--exclude-caches', self.repository_location + '::test', 'input')
  273. with changedir('output'):
  274. self.attic('extract', self.repository_location + '::test')
  275. self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1'])
  276. self.assert_equal(sorted(os.listdir('output/input/cache2')), ['CACHEDIR.TAG'])
  277. def test_path_normalization(self):
  278. self.attic('init', self.repository_location)
  279. self.create_regular_file('dir1/dir2/file', size=1024 * 80)
  280. with changedir('input/dir1/dir2'):
  281. self.attic('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  282. output = self.attic('list', self.repository_location + '::test')
  283. self.assert_not_in('..', output)
  284. self.assert_in(' input/dir1/dir2/file', output)
  285. def test_exclude_normalization(self):
  286. self.attic('init', self.repository_location)
  287. self.create_regular_file('file1', size=1024 * 80)
  288. self.create_regular_file('file2', size=1024 * 80)
  289. with changedir('input'):
  290. self.attic('create', '--exclude=file1', self.repository_location + '::test1', '.')
  291. with changedir('output'):
  292. self.attic('extract', self.repository_location + '::test1')
  293. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  294. with changedir('input'):
  295. self.attic('create', '--exclude=./file1', self.repository_location + '::test2', '.')
  296. with changedir('output'):
  297. self.attic('extract', self.repository_location + '::test2')
  298. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  299. self.attic('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input')
  300. with changedir('output'):
  301. self.attic('extract', self.repository_location + '::test3')
  302. self.assert_equal(sorted(os.listdir('output/input')), ['file2'])
  303. def test_repeated_files(self):
  304. self.create_regular_file('file1', size=1024 * 80)
  305. self.attic('init', self.repository_location)
  306. self.attic('create', self.repository_location + '::test', 'input', 'input')
  307. def test_overwrite(self):
  308. self.create_regular_file('file1', size=1024 * 80)
  309. self.create_regular_file('dir2/file2', size=1024 * 80)
  310. self.attic('init', self.repository_location)
  311. self.attic('create', self.repository_location + '::test', 'input')
  312. # Overwriting regular files and directories should be supported
  313. os.mkdir('output/input')
  314. os.mkdir('output/input/file1')
  315. os.mkdir('output/input/dir2')
  316. with changedir('output'):
  317. self.attic('extract', self.repository_location + '::test')
  318. self.assert_dirs_equal('input', 'output/input')
  319. # But non-empty dirs should fail
  320. os.unlink('output/input/file1')
  321. os.mkdir('output/input/file1')
  322. os.mkdir('output/input/file1/dir')
  323. with changedir('output'):
  324. self.attic('extract', self.repository_location + '::test', exit_code=1)
  325. def test_rename(self):
  326. self.create_regular_file('file1', size=1024 * 80)
  327. self.create_regular_file('dir2/file2', size=1024 * 80)
  328. self.attic('init', self.repository_location)
  329. self.attic('create', self.repository_location + '::test', 'input')
  330. self.attic('create', self.repository_location + '::test.2', 'input')
  331. self.attic('extract', '--dry-run', self.repository_location + '::test')
  332. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  333. self.attic('rename', self.repository_location + '::test', 'test.3')
  334. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  335. self.attic('rename', self.repository_location + '::test.2', 'test.4')
  336. self.attic('extract', '--dry-run', self.repository_location + '::test.3')
  337. self.attic('extract', '--dry-run', self.repository_location + '::test.4')
  338. # Make sure both archives have been renamed
  339. repository = Repository(self.repository_path)
  340. manifest, key = Manifest.load(repository)
  341. self.assert_equal(len(manifest.archives), 2)
  342. self.assert_in('test.3', manifest.archives)
  343. self.assert_in('test.4', manifest.archives)
  344. def test_delete(self):
  345. self.create_regular_file('file1', size=1024 * 80)
  346. self.create_regular_file('dir2/file2', size=1024 * 80)
  347. self.attic('init', self.repository_location)
  348. self.attic('create', self.repository_location + '::test', 'input')
  349. self.attic('create', self.repository_location + '::test.2', 'input')
  350. self.attic('extract', '--dry-run', self.repository_location + '::test')
  351. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  352. self.attic('delete', self.repository_location + '::test')
  353. self.attic('extract', '--dry-run', self.repository_location + '::test.2')
  354. self.attic('delete', self.repository_location + '::test.2')
  355. # Make sure all data except the manifest has been deleted
  356. repository = Repository(self.repository_path)
  357. self.assert_equal(len(repository), 1)
  358. def test_corrupted_repository(self):
  359. self.attic('init', self.repository_location)
  360. self.create_src_archive('test')
  361. self.attic('extract', '--dry-run', self.repository_location + '::test')
  362. self.attic('check', self.repository_location)
  363. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  364. with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+') as fd:
  365. fd.seek(100)
  366. fd.write('XXXX')
  367. self.attic('check', self.repository_location, exit_code=1)
  368. def test_readonly_repository(self):
  369. self.attic('init', self.repository_location)
  370. self.create_src_archive('test')
  371. os.system('chmod -R ugo-w ' + self.repository_path)
  372. try:
  373. self.attic('extract', '--dry-run', self.repository_location + '::test')
  374. finally:
  375. # Restore permissions so shutil.rmtree is able to delete it
  376. os.system('chmod -R u+w ' + self.repository_path)
  377. def test_cmdline_compatibility(self):
  378. self.create_regular_file('file1', size=1024 * 80)
  379. self.attic('init', self.repository_location)
  380. self.attic('create', self.repository_location + '::test', 'input')
  381. output = self.attic('verify', '-v', self.repository_location + '::test')
  382. self.assert_in('"borg verify" has been deprecated', output)
  383. output = self.attic('prune', self.repository_location, '--hourly=1')
  384. self.assert_in('"--hourly" has been deprecated. Use "--keep-hourly" instead', output)
  385. def test_prune_repository(self):
  386. self.attic('init', self.repository_location)
  387. self.attic('create', self.repository_location + '::test1', src_dir)
  388. self.attic('create', self.repository_location + '::test2', src_dir)
  389. output = self.attic('prune', '-v', '--dry-run', self.repository_location, '--keep-daily=2')
  390. self.assert_in('Keeping archive: test2', output)
  391. self.assert_in('Would prune: test1', output)
  392. output = self.attic('list', self.repository_location)
  393. self.assert_in('test1', output)
  394. self.assert_in('test2', output)
  395. self.attic('prune', self.repository_location, '--keep-daily=2')
  396. output = self.attic('list', self.repository_location)
  397. self.assert_not_in('test1', output)
  398. self.assert_in('test2', output)
  399. def test_usage(self):
  400. self.assert_raises(SystemExit, lambda: self.attic())
  401. self.assert_raises(SystemExit, lambda: self.attic('-h'))
  402. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  403. def test_fuse_mount_repository(self):
  404. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  405. os.mkdir(mountpoint)
  406. self.attic('init', self.repository_location)
  407. self.create_test_files()
  408. self.attic('create', self.repository_location + '::archive', 'input')
  409. self.attic('create', self.repository_location + '::archive2', 'input')
  410. try:
  411. self.attic('mount', self.repository_location, mountpoint, fork=True)
  412. self.wait_for_mount(mountpoint)
  413. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'))
  414. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'))
  415. finally:
  416. if sys.platform.startswith('linux'):
  417. os.system('fusermount -u ' + mountpoint)
  418. else:
  419. os.system('umount ' + mountpoint)
  420. os.rmdir(mountpoint)
  421. # Give the daemon some time to exit
  422. time.sleep(.2)
  423. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  424. def test_fuse_mount_archive(self):
  425. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  426. os.mkdir(mountpoint)
  427. self.attic('init', self.repository_location)
  428. self.create_test_files()
  429. self.attic('create', self.repository_location + '::archive', 'input')
  430. try:
  431. self.attic('mount', self.repository_location + '::archive', mountpoint, fork=True)
  432. self.wait_for_mount(mountpoint)
  433. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'))
  434. finally:
  435. if sys.platform.startswith('linux'):
  436. os.system('fusermount -u ' + mountpoint)
  437. else:
  438. os.system('umount ' + mountpoint)
  439. os.rmdir(mountpoint)
  440. # Give the daemon some time to exit
  441. time.sleep(.2)
  442. def verify_aes_counter_uniqueness(self, method):
  443. seen = set() # Chunks already seen
  444. used = set() # counter values already used
  445. def verify_uniqueness():
  446. repository = Repository(self.repository_path)
  447. for key, _ in repository.open_index(repository.get_transaction_id()).iteritems():
  448. data = repository.get(key)
  449. hash = sha256(data).digest()
  450. if hash not in seen:
  451. seen.add(hash)
  452. num_blocks = num_aes_blocks(len(data) - 41)
  453. nonce = bytes_to_long(data[33:41])
  454. for counter in range(nonce, nonce + num_blocks):
  455. self.assert_not_in(counter, used)
  456. used.add(counter)
  457. self.create_test_files()
  458. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  459. self.attic('init', '--encryption=' + method, self.repository_location)
  460. verify_uniqueness()
  461. self.attic('create', self.repository_location + '::test', 'input')
  462. verify_uniqueness()
  463. self.attic('create', self.repository_location + '::test.2', 'input')
  464. verify_uniqueness()
  465. self.attic('delete', self.repository_location + '::test.2')
  466. verify_uniqueness()
  467. self.assert_equal(used, set(range(len(used))))
  468. def test_aes_counter_uniqueness_keyfile(self):
  469. self.verify_aes_counter_uniqueness('keyfile')
  470. def test_aes_counter_uniqueness_passphrase(self):
  471. self.verify_aes_counter_uniqueness('passphrase')
  472. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  473. def setUp(self):
  474. super(ArchiverCheckTestCase, self).setUp()
  475. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  476. self.attic('init', self.repository_location)
  477. self.create_src_archive('archive1')
  478. self.create_src_archive('archive2')
  479. def open_archive(self, name):
  480. repository = Repository(self.repository_path)
  481. manifest, key = Manifest.load(repository)
  482. archive = Archive(repository, key, manifest, name)
  483. return archive, repository
  484. def test_check_usage(self):
  485. output = self.attic('check', self.repository_location, exit_code=0)
  486. self.assert_in('Starting repository check', output)
  487. self.assert_in('Starting archive consistency check', output)
  488. output = self.attic('check', '--repository-only', self.repository_location, exit_code=0)
  489. self.assert_in('Starting repository check', output)
  490. self.assert_not_in('Starting archive consistency check', output)
  491. output = self.attic('check', '--archives-only', self.repository_location, exit_code=0)
  492. self.assert_not_in('Starting repository check', output)
  493. self.assert_in('Starting archive consistency check', output)
  494. def test_missing_file_chunk(self):
  495. archive, repository = self.open_archive('archive1')
  496. for item in archive.iter_items():
  497. if item[b'path'].endswith('testsuite/archiver.py'):
  498. repository.delete(item[b'chunks'][-1][0])
  499. break
  500. repository.commit()
  501. self.attic('check', self.repository_location, exit_code=1)
  502. self.attic('check', '--repair', self.repository_location, exit_code=0)
  503. self.attic('check', self.repository_location, exit_code=0)
  504. def test_missing_archive_item_chunk(self):
  505. archive, repository = self.open_archive('archive1')
  506. repository.delete(archive.metadata[b'items'][-5])
  507. repository.commit()
  508. self.attic('check', self.repository_location, exit_code=1)
  509. self.attic('check', '--repair', self.repository_location, exit_code=0)
  510. self.attic('check', self.repository_location, exit_code=0)
  511. def test_missing_archive_metadata(self):
  512. archive, repository = self.open_archive('archive1')
  513. repository.delete(archive.id)
  514. repository.commit()
  515. self.attic('check', self.repository_location, exit_code=1)
  516. self.attic('check', '--repair', self.repository_location, exit_code=0)
  517. self.attic('check', self.repository_location, exit_code=0)
  518. def test_missing_manifest(self):
  519. archive, repository = self.open_archive('archive1')
  520. repository.delete(Manifest.MANIFEST_ID)
  521. repository.commit()
  522. self.attic('check', self.repository_location, exit_code=1)
  523. output = self.attic('check', '--repair', self.repository_location, exit_code=0)
  524. self.assert_in('archive1', output)
  525. self.assert_in('archive2', output)
  526. self.attic('check', self.repository_location, exit_code=0)
  527. def test_extra_chunks(self):
  528. self.attic('check', self.repository_location, exit_code=0)
  529. repository = Repository(self.repository_location)
  530. repository.put(b'01234567890123456789012345678901', b'xxxx')
  531. repository.commit()
  532. repository.close()
  533. self.attic('check', self.repository_location, exit_code=1)
  534. self.attic('check', self.repository_location, exit_code=1)
  535. self.attic('check', '--repair', self.repository_location, exit_code=0)
  536. self.attic('check', self.repository_location, exit_code=0)
  537. self.attic('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  538. class RemoteArchiverTestCase(ArchiverTestCase):
  539. prefix = '__testsuite__:'
  540. def test_remote_repo_restrict_to_path(self):
  541. self.attic('init', self.repository_location)
  542. path_prefix = os.path.dirname(self.repository_path)
  543. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  544. self.assert_raises(PathNotAllowed, lambda: self.attic('init', self.repository_location + '_1'))
  545. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  546. self.attic('init', self.repository_location + '_2')
  547. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  548. self.attic('init', self.repository_location + '_3')