archiver.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. from binascii import unhexlify, b2a_base64
  2. from configparser import ConfigParser
  3. import errno
  4. import os
  5. from io import StringIO
  6. import random
  7. import stat
  8. import subprocess
  9. import sys
  10. import shutil
  11. import tempfile
  12. import time
  13. import unittest
  14. from unittest.mock import patch
  15. from hashlib import sha256
  16. import pytest
  17. from .. import xattr
  18. from ..archive import Archive, ChunkBuffer, CHUNK_MAX_EXP, flags_noatime, flags_normal
  19. from ..archiver import Archiver
  20. from ..cache import Cache
  21. from ..crypto import bytes_to_long, num_aes_blocks
  22. from ..helpers import Manifest, PatternMatcher, parse_pattern, EXIT_SUCCESS, EXIT_WARNING, EXIT_ERROR, bin_to_hex
  23. from ..key import RepoKey, KeyfileKey, Passphrase
  24. from ..keymanager import RepoIdMismatch, NotABorgKeyFile
  25. from ..remote import RemoteRepository, PathNotAllowed
  26. from ..repository import Repository
  27. from . import BaseTestCase, changedir, environment_variable, no_selinux
  28. from .platform import fakeroot_detected
  29. try:
  30. import llfuse
  31. has_llfuse = True or llfuse # avoids "unused import"
  32. except ImportError:
  33. has_llfuse = False
  34. has_lchflags = hasattr(os, 'lchflags')
  35. src_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
  36. def exec_cmd(*args, archiver=None, fork=False, exe=None, **kw):
  37. if fork:
  38. try:
  39. if exe is None:
  40. borg = (sys.executable, '-m', 'borg.archiver')
  41. elif isinstance(exe, str):
  42. borg = (exe, )
  43. elif not isinstance(exe, tuple):
  44. raise ValueError('exe must be None, a tuple or a str')
  45. output = subprocess.check_output(borg + args, stderr=subprocess.STDOUT)
  46. ret = 0
  47. except subprocess.CalledProcessError as e:
  48. output = e.output
  49. ret = e.returncode
  50. return ret, os.fsdecode(output)
  51. else:
  52. stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
  53. try:
  54. sys.stdin = StringIO()
  55. sys.stdout = sys.stderr = output = StringIO()
  56. if archiver is None:
  57. archiver = Archiver()
  58. archiver.exit_code = EXIT_SUCCESS
  59. args = archiver.parse_args(list(args))
  60. ret = archiver.run(args)
  61. return ret, output.getvalue()
  62. finally:
  63. sys.stdin, sys.stdout, sys.stderr = stdin, stdout, stderr
  64. # check if the binary "borg.exe" is available (for local testing a symlink to virtualenv/bin/borg should do)
  65. try:
  66. exec_cmd('help', exe='borg.exe', fork=True)
  67. BORG_EXES = ['python', 'binary', ]
  68. except FileNotFoundError:
  69. BORG_EXES = ['python', ]
  70. @pytest.fixture(params=BORG_EXES)
  71. def cmd(request):
  72. if request.param == 'python':
  73. exe = None
  74. elif request.param == 'binary':
  75. exe = 'borg.exe'
  76. else:
  77. raise ValueError("param must be 'python' or 'binary'")
  78. def exec_fn(*args, **kw):
  79. return exec_cmd(*args, exe=exe, fork=True, **kw)
  80. return exec_fn
  81. def test_return_codes(cmd, tmpdir):
  82. repo = tmpdir.mkdir('repo')
  83. input = tmpdir.mkdir('input')
  84. output = tmpdir.mkdir('output')
  85. input.join('test_file').write('content')
  86. rc, out = cmd('init', '--encryption=none', '%s' % str(repo))
  87. assert rc == EXIT_SUCCESS
  88. rc, out = cmd('create', '%s::archive' % repo, str(input))
  89. assert rc == EXIT_SUCCESS
  90. with changedir(str(output)):
  91. rc, out = cmd('extract', '%s::archive' % repo)
  92. assert rc == EXIT_SUCCESS
  93. rc, out = cmd('extract', '%s::archive' % repo, 'does/not/match')
  94. assert rc == EXIT_WARNING # pattern did not match
  95. rc, out = cmd('create', '%s::archive' % repo, str(input))
  96. assert rc == EXIT_ERROR # duplicate archive name
  97. """
  98. test_disk_full is very slow and not recommended to be included in daily testing.
  99. for this test, an empty, writable 16MB filesystem mounted on DF_MOUNT is required.
  100. for speed and other reasons, it is recommended that the underlying block device is
  101. in RAM, not a magnetic or flash disk.
  102. assuming /tmp is a tmpfs (in memory filesystem), one can use this:
  103. dd if=/dev/zero of=/tmp/borg-disk bs=16M count=1
  104. mkfs.ext4 /tmp/borg-disk
  105. mkdir /tmp/borg-mount
  106. sudo mount /tmp/borg-disk /tmp/borg-mount
  107. if the directory does not exist, the test will be skipped.
  108. """
  109. DF_MOUNT = '/tmp/borg-mount'
  110. @pytest.mark.skipif(not os.path.exists(DF_MOUNT), reason="needs a 16MB fs mounted on %s" % DF_MOUNT)
  111. def test_disk_full(cmd):
  112. def make_files(dir, count, size, rnd=True):
  113. shutil.rmtree(dir, ignore_errors=True)
  114. os.mkdir(dir)
  115. if rnd:
  116. count = random.randint(1, count)
  117. if size > 1:
  118. size = random.randint(1, size)
  119. for i in range(count):
  120. fn = os.path.join(dir, "file%03d" % i)
  121. with open(fn, 'wb') as f:
  122. data = os.urandom(size)
  123. f.write(data)
  124. with environment_variable(BORG_CHECK_I_KNOW_WHAT_I_AM_DOING='YES'):
  125. mount = DF_MOUNT
  126. assert os.path.exists(mount)
  127. repo = os.path.join(mount, 'repo')
  128. input = os.path.join(mount, 'input')
  129. reserve = os.path.join(mount, 'reserve')
  130. for j in range(100):
  131. shutil.rmtree(repo, ignore_errors=True)
  132. shutil.rmtree(input, ignore_errors=True)
  133. # keep some space and some inodes in reserve that we can free up later:
  134. make_files(reserve, 80, 100000, rnd=False)
  135. rc, out = cmd('init', repo)
  136. if rc != EXIT_SUCCESS:
  137. print('init', rc, out)
  138. assert rc == EXIT_SUCCESS
  139. try:
  140. success, i = True, 0
  141. while success:
  142. i += 1
  143. try:
  144. make_files(input, 20, 200000)
  145. except OSError as err:
  146. if err.errno == errno.ENOSPC:
  147. # already out of space
  148. break
  149. raise
  150. try:
  151. rc, out = cmd('create', '%s::test%03d' % (repo, i), input)
  152. success = rc == EXIT_SUCCESS
  153. if not success:
  154. print('create', rc, out)
  155. finally:
  156. # make sure repo is not locked
  157. shutil.rmtree(os.path.join(repo, 'lock.exclusive'), ignore_errors=True)
  158. os.remove(os.path.join(repo, 'lock.roster'))
  159. finally:
  160. # now some error happened, likely we are out of disk space.
  161. # free some space so we can expect borg to be able to work normally:
  162. shutil.rmtree(reserve, ignore_errors=True)
  163. rc, out = cmd('list', repo)
  164. if rc != EXIT_SUCCESS:
  165. print('list', rc, out)
  166. rc, out = cmd('check', '--repair', repo)
  167. if rc != EXIT_SUCCESS:
  168. print('check', rc, out)
  169. assert rc == EXIT_SUCCESS
  170. class ArchiverTestCaseBase(BaseTestCase):
  171. EXE = None # python source based
  172. FORK_DEFAULT = False
  173. prefix = ''
  174. def setUp(self):
  175. os.environ['BORG_CHECK_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  176. os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  177. os.environ['BORG_PASSPHRASE'] = 'waytooeasyonlyfortests'
  178. self.archiver = not self.FORK_DEFAULT and Archiver() or None
  179. self.tmpdir = tempfile.mkdtemp()
  180. self.repository_path = os.path.join(self.tmpdir, 'repository')
  181. self.repository_location = self.prefix + self.repository_path
  182. self.input_path = os.path.join(self.tmpdir, 'input')
  183. self.output_path = os.path.join(self.tmpdir, 'output')
  184. self.keys_path = os.path.join(self.tmpdir, 'keys')
  185. self.cache_path = os.path.join(self.tmpdir, 'cache')
  186. self.exclude_file_path = os.path.join(self.tmpdir, 'excludes')
  187. os.environ['BORG_KEYS_DIR'] = self.keys_path
  188. os.environ['BORG_CACHE_DIR'] = self.cache_path
  189. os.mkdir(self.input_path)
  190. os.chmod(self.input_path, 0o777) # avoid troubles with fakeroot / FUSE
  191. os.mkdir(self.output_path)
  192. os.mkdir(self.keys_path)
  193. os.mkdir(self.cache_path)
  194. with open(self.exclude_file_path, 'wb') as fd:
  195. fd.write(b'input/file2\n# A comment line, then a blank line\n\n')
  196. self._old_wd = os.getcwd()
  197. os.chdir(self.tmpdir)
  198. def tearDown(self):
  199. os.chdir(self._old_wd)
  200. # note: ignore_errors=True as workaround for issue #862
  201. shutil.rmtree(self.tmpdir, ignore_errors=True)
  202. def cmd(self, *args, **kw):
  203. exit_code = kw.pop('exit_code', 0)
  204. fork = kw.pop('fork', None)
  205. if fork is None:
  206. fork = self.FORK_DEFAULT
  207. ret, output = exec_cmd(*args, fork=fork, exe=self.EXE, archiver=self.archiver, **kw)
  208. if ret != exit_code:
  209. print(output)
  210. self.assert_equal(ret, exit_code)
  211. return output
  212. def create_src_archive(self, name):
  213. self.cmd('create', self.repository_location + '::' + name, src_dir)
  214. def open_archive(self, name):
  215. repository = Repository(self.repository_path, exclusive=True)
  216. with repository:
  217. manifest, key = Manifest.load(repository)
  218. archive = Archive(repository, key, manifest, name)
  219. return archive, repository
  220. class ArchiverTestCase(ArchiverTestCaseBase):
  221. def create_regular_file(self, name, size=0, contents=None):
  222. filename = os.path.join(self.input_path, name)
  223. if not os.path.exists(os.path.dirname(filename)):
  224. os.makedirs(os.path.dirname(filename))
  225. with open(filename, 'wb') as fd:
  226. if contents is None:
  227. contents = b'X' * size
  228. fd.write(contents)
  229. def create_test_files(self):
  230. """Create a minimal test case including all supported file types
  231. """
  232. # File
  233. self.create_regular_file('empty', size=0)
  234. # next code line raises OverflowError on 32bit cpu (raspberry pi 2):
  235. # 2600-01-01 > 2**64 ns
  236. # os.utime('input/empty', (19880895600, 19880895600))
  237. # thus, we better test with something not that far in future:
  238. # 2038-01-19 (1970 + 2^31 - 1 seconds) is the 32bit "deadline":
  239. os.utime('input/empty', (2**31 - 1, 2**31 - 1))
  240. self.create_regular_file('file1', size=1024 * 80)
  241. self.create_regular_file('flagfile', size=1024)
  242. # Directory
  243. self.create_regular_file('dir2/file2', size=1024 * 80)
  244. # File mode
  245. os.chmod('input/file1', 0o4755)
  246. # Hard link
  247. os.link(os.path.join(self.input_path, 'file1'),
  248. os.path.join(self.input_path, 'hardlink'))
  249. # Symlink
  250. os.symlink('somewhere', os.path.join(self.input_path, 'link1'))
  251. self.create_regular_file('fusexattr', size=1)
  252. if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path):
  253. # ironically, due to the way how fakeroot works, comparing fuse file xattrs to orig file xattrs
  254. # will FAIL if fakeroot supports xattrs, thus we only set the xattr if XATTR_FAKEROOT is False.
  255. # This is because fakeroot with xattr-support does not propagate xattrs of the underlying file
  256. # into "fakeroot space". Because the xattrs exposed by borgfs are these of an underlying file
  257. # (from fakeroots point of view) they are invisible to the test process inside the fakeroot.
  258. xattr.setxattr(os.path.join(self.input_path, 'fusexattr'), 'user.foo', b'bar')
  259. # XXX this always fails for me
  260. # ubuntu 14.04, on a TMP dir filesystem with user_xattr, using fakeroot
  261. # same for newer ubuntu and centos.
  262. # if this is supported just on specific platform, platform should be checked first,
  263. # so that the test setup for all tests using it does not fail here always for others.
  264. # xattr.setxattr(os.path.join(self.input_path, 'link1'), 'user.foo_symlink', b'bar_symlink', follow_symlinks=False)
  265. # FIFO node
  266. os.mkfifo(os.path.join(self.input_path, 'fifo1'))
  267. if has_lchflags:
  268. os.lchflags(os.path.join(self.input_path, 'flagfile'), stat.UF_NODUMP)
  269. try:
  270. # Block device
  271. os.mknod('input/bdev', 0o600 | stat.S_IFBLK, os.makedev(10, 20))
  272. # Char device
  273. os.mknod('input/cdev', 0o600 | stat.S_IFCHR, os.makedev(30, 40))
  274. # File mode
  275. os.chmod('input/dir2', 0o555) # if we take away write perms, we need root to remove contents
  276. # File owner
  277. os.chown('input/file1', 100, 200) # raises OSError invalid argument on cygwin
  278. have_root = True # we have (fake)root
  279. except PermissionError:
  280. have_root = False
  281. except OSError as e:
  282. if e.errno != errno.EINVAL:
  283. raise
  284. have_root = False
  285. return have_root
  286. def test_basic_functionality(self):
  287. have_root = self.create_test_files()
  288. self.cmd('init', self.repository_location)
  289. self.cmd('create', self.repository_location + '::test', 'input')
  290. self.cmd('create', '--stats', self.repository_location + '::test.2', 'input')
  291. with changedir('output'):
  292. self.cmd('extract', self.repository_location + '::test')
  293. list_output = self.cmd('list', '--short', self.repository_location)
  294. self.assert_in('test', list_output)
  295. self.assert_in('test.2', list_output)
  296. expected = [
  297. 'input',
  298. 'input/bdev',
  299. 'input/cdev',
  300. 'input/dir2',
  301. 'input/dir2/file2',
  302. 'input/empty',
  303. 'input/fifo1',
  304. 'input/file1',
  305. 'input/flagfile',
  306. 'input/hardlink',
  307. 'input/link1',
  308. ]
  309. if not have_root:
  310. # we could not create these device files without (fake)root
  311. expected.remove('input/bdev')
  312. expected.remove('input/cdev')
  313. if has_lchflags:
  314. # remove the file we did not backup, so input and output become equal
  315. expected.remove('input/flagfile') # this file is UF_NODUMP
  316. os.remove(os.path.join('input', 'flagfile'))
  317. list_output = self.cmd('list', '--short', self.repository_location + '::test')
  318. for name in expected:
  319. self.assert_in(name, list_output)
  320. self.assert_dirs_equal('input', 'output/input')
  321. info_output = self.cmd('info', self.repository_location + '::test')
  322. item_count = 4 if has_lchflags else 5 # one file is UF_NODUMP
  323. self.assert_in('Number of files: %d' % item_count, info_output)
  324. shutil.rmtree(self.cache_path)
  325. with environment_variable(BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK='yes'):
  326. info_output2 = self.cmd('info', self.repository_location + '::test')
  327. def filter(output):
  328. # filter for interesting "info" output, ignore cache rebuilding related stuff
  329. prefixes = ['Name:', 'Fingerprint:', 'Number of files:', 'This archive:',
  330. 'All archives:', 'Chunk index:', ]
  331. result = []
  332. for line in output.splitlines():
  333. for prefix in prefixes:
  334. if line.startswith(prefix):
  335. result.append(line)
  336. return '\n'.join(result)
  337. # the interesting parts of info_output2 and info_output should be same
  338. self.assert_equal(filter(info_output), filter(info_output2))
  339. # Search for O_NOATIME there: https://www.gnu.org/software/hurd/contributing.html - we just
  340. # skip the test on Hurd, it is not critical anyway, just testing a performance optimization.
  341. @pytest.mark.skipif(sys.platform == 'gnu0', reason="O_NOATIME is strangely broken on GNU Hurd")
  342. def test_atime(self):
  343. def has_noatime(some_file):
  344. atime_before = os.stat(some_file).st_atime_ns
  345. try:
  346. os.close(os.open(some_file, flags_noatime))
  347. except PermissionError:
  348. return False
  349. else:
  350. atime_after = os.stat(some_file).st_atime_ns
  351. noatime_used = flags_noatime != flags_normal
  352. return noatime_used and atime_before == atime_after
  353. self.create_test_files()
  354. atime, mtime = 123456780, 234567890
  355. have_noatime = has_noatime('input/file1')
  356. os.utime('input/file1', (atime, mtime))
  357. self.cmd('init', self.repository_location)
  358. self.cmd('create', self.repository_location + '::test', 'input')
  359. with changedir('output'):
  360. self.cmd('extract', self.repository_location + '::test')
  361. sti = os.stat('input/file1')
  362. sto = os.stat('output/input/file1')
  363. assert sti.st_mtime_ns == sto.st_mtime_ns == mtime * 1e9
  364. if have_noatime:
  365. assert sti.st_atime_ns == sto.st_atime_ns == atime * 1e9
  366. else:
  367. # it touched the input file's atime while backing it up
  368. assert sto.st_atime_ns == atime * 1e9
  369. def _extract_repository_id(self, path):
  370. with Repository(self.repository_path) as repository:
  371. return repository.id
  372. def _set_repository_id(self, path, id):
  373. config = ConfigParser(interpolation=None)
  374. config.read(os.path.join(path, 'config'))
  375. config.set('repository', 'id', bin_to_hex(id))
  376. with open(os.path.join(path, 'config'), 'w') as fd:
  377. config.write(fd)
  378. with Repository(self.repository_path) as repository:
  379. return repository.id
  380. def test_sparse_file(self):
  381. def is_sparse(fn, total_size, hole_size):
  382. st = os.stat(fn)
  383. assert st.st_size == total_size
  384. sparse = True
  385. if sparse and hasattr(st, 'st_blocks') and st.st_blocks * 512 >= st.st_size:
  386. sparse = False
  387. if sparse and hasattr(os, 'SEEK_HOLE') and hasattr(os, 'SEEK_DATA'):
  388. with open(fn, 'rb') as fd:
  389. # only check if the first hole is as expected, because the 2nd hole check
  390. # is problematic on xfs due to its "dynamic speculative EOF preallocation
  391. try:
  392. if fd.seek(0, os.SEEK_HOLE) != 0:
  393. sparse = False
  394. if fd.seek(0, os.SEEK_DATA) != hole_size:
  395. sparse = False
  396. except OSError:
  397. # OS/FS does not really support SEEK_HOLE/SEEK_DATA
  398. sparse = False
  399. return sparse
  400. filename = os.path.join(self.input_path, 'sparse')
  401. content = b'foobar'
  402. hole_size = 5 * (1 << CHUNK_MAX_EXP) # 5 full chunker buffers
  403. total_size = hole_size + len(content) + hole_size
  404. with open(filename, 'wb') as fd:
  405. # create a file that has a hole at the beginning and end (if the
  406. # OS and filesystem supports sparse files)
  407. fd.seek(hole_size, 1)
  408. fd.write(content)
  409. fd.seek(hole_size, 1)
  410. pos = fd.tell()
  411. fd.truncate(pos)
  412. # we first check if we could create a sparse input file:
  413. sparse_support = is_sparse(filename, total_size, hole_size)
  414. if sparse_support:
  415. # we could create a sparse input file, so creating a backup of it and
  416. # extracting it again (as sparse) should also work:
  417. self.cmd('init', self.repository_location)
  418. self.cmd('create', self.repository_location + '::test', 'input')
  419. with changedir(self.output_path):
  420. self.cmd('extract', '--sparse', self.repository_location + '::test')
  421. self.assert_dirs_equal('input', 'output/input')
  422. filename = os.path.join(self.output_path, 'input', 'sparse')
  423. with open(filename, 'rb') as fd:
  424. # check if file contents are as expected
  425. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  426. self.assert_equal(fd.read(len(content)), content)
  427. self.assert_equal(fd.read(hole_size), b'\0' * hole_size)
  428. self.assert_true(is_sparse(filename, total_size, hole_size))
  429. def test_unusual_filenames(self):
  430. filenames = ['normal', 'with some blanks', '(with_parens)', ]
  431. for filename in filenames:
  432. filename = os.path.join(self.input_path, filename)
  433. with open(filename, 'wb'):
  434. pass
  435. self.cmd('init', self.repository_location)
  436. self.cmd('create', self.repository_location + '::test', 'input')
  437. for filename in filenames:
  438. with changedir('output'):
  439. self.cmd('extract', self.repository_location + '::test', os.path.join('input', filename))
  440. assert os.path.exists(os.path.join('output', 'input', filename))
  441. def test_repository_swap_detection(self):
  442. self.create_test_files()
  443. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  444. self.cmd('init', '--encryption=repokey', self.repository_location)
  445. repository_id = self._extract_repository_id(self.repository_path)
  446. self.cmd('create', self.repository_location + '::test', 'input')
  447. shutil.rmtree(self.repository_path)
  448. self.cmd('init', '--encryption=none', self.repository_location)
  449. self._set_repository_id(self.repository_path, repository_id)
  450. self.assert_equal(repository_id, self._extract_repository_id(self.repository_path))
  451. if self.FORK_DEFAULT:
  452. self.cmd('create', self.repository_location + '::test.2', 'input', exit_code=EXIT_ERROR)
  453. else:
  454. self.assert_raises(Cache.EncryptionMethodMismatch, lambda: self.cmd('create', self.repository_location + '::test.2', 'input'))
  455. def test_repository_swap_detection2(self):
  456. self.create_test_files()
  457. self.cmd('init', '--encryption=none', self.repository_location + '_unencrypted')
  458. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  459. self.cmd('init', '--encryption=repokey', self.repository_location + '_encrypted')
  460. self.cmd('create', self.repository_location + '_encrypted::test', 'input')
  461. shutil.rmtree(self.repository_path + '_encrypted')
  462. os.rename(self.repository_path + '_unencrypted', self.repository_path + '_encrypted')
  463. if self.FORK_DEFAULT:
  464. self.cmd('create', self.repository_location + '_encrypted::test.2', 'input', exit_code=EXIT_ERROR)
  465. else:
  466. self.assert_raises(Cache.RepositoryAccessAborted, lambda: self.cmd('create', self.repository_location + '_encrypted::test.2', 'input'))
  467. def test_strip_components(self):
  468. self.cmd('init', self.repository_location)
  469. self.create_regular_file('dir/file')
  470. self.cmd('create', self.repository_location + '::test', 'input')
  471. with changedir('output'):
  472. self.cmd('extract', self.repository_location + '::test', '--strip-components', '3')
  473. self.assert_true(not os.path.exists('file'))
  474. with self.assert_creates_file('file'):
  475. self.cmd('extract', self.repository_location + '::test', '--strip-components', '2')
  476. with self.assert_creates_file('dir/file'):
  477. self.cmd('extract', self.repository_location + '::test', '--strip-components', '1')
  478. with self.assert_creates_file('input/dir/file'):
  479. self.cmd('extract', self.repository_location + '::test', '--strip-components', '0')
  480. def test_extract_include_exclude(self):
  481. self.cmd('init', self.repository_location)
  482. self.create_regular_file('file1', size=1024 * 80)
  483. self.create_regular_file('file2', size=1024 * 80)
  484. self.create_regular_file('file3', size=1024 * 80)
  485. self.create_regular_file('file4', size=1024 * 80)
  486. self.cmd('create', '--exclude=input/file4', self.repository_location + '::test', 'input')
  487. with changedir('output'):
  488. self.cmd('extract', self.repository_location + '::test', 'input/file1', )
  489. self.assert_equal(sorted(os.listdir('output/input')), ['file1'])
  490. with changedir('output'):
  491. self.cmd('extract', '--exclude=input/file2', self.repository_location + '::test')
  492. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  493. with changedir('output'):
  494. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  495. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file3'])
  496. def test_extract_include_exclude_regex(self):
  497. self.cmd('init', self.repository_location)
  498. self.create_regular_file('file1', size=1024 * 80)
  499. self.create_regular_file('file2', size=1024 * 80)
  500. self.create_regular_file('file3', size=1024 * 80)
  501. self.create_regular_file('file4', size=1024 * 80)
  502. self.create_regular_file('file333', size=1024 * 80)
  503. # Create with regular expression exclusion for file4
  504. self.cmd('create', '--exclude=re:input/file4$', self.repository_location + '::test', 'input')
  505. with changedir('output'):
  506. self.cmd('extract', self.repository_location + '::test')
  507. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333'])
  508. shutil.rmtree('output/input')
  509. # Extract with regular expression exclusion
  510. with changedir('output'):
  511. self.cmd('extract', '--exclude=re:file3+', self.repository_location + '::test')
  512. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2'])
  513. shutil.rmtree('output/input')
  514. # Combine --exclude with fnmatch and regular expression
  515. with changedir('output'):
  516. self.cmd('extract', '--exclude=input/file2', '--exclude=re:file[01]', self.repository_location + '::test')
  517. self.assert_equal(sorted(os.listdir('output/input')), ['file3', 'file333'])
  518. shutil.rmtree('output/input')
  519. # Combine --exclude-from and regular expression exclusion
  520. with changedir('output'):
  521. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, '--exclude=re:file1',
  522. '--exclude=re:file(\\d)\\1\\1$', self.repository_location + '::test')
  523. self.assert_equal(sorted(os.listdir('output/input')), ['file3'])
  524. def test_extract_include_exclude_regex_from_file(self):
  525. self.cmd('init', self.repository_location)
  526. self.create_regular_file('file1', size=1024 * 80)
  527. self.create_regular_file('file2', size=1024 * 80)
  528. self.create_regular_file('file3', size=1024 * 80)
  529. self.create_regular_file('file4', size=1024 * 80)
  530. self.create_regular_file('file333', size=1024 * 80)
  531. self.create_regular_file('aa:something', size=1024 * 80)
  532. # Create while excluding using mixed pattern styles
  533. with open(self.exclude_file_path, 'wb') as fd:
  534. fd.write(b're:input/file4$\n')
  535. fd.write(b'fm:*aa:*thing\n')
  536. self.cmd('create', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test', 'input')
  537. with changedir('output'):
  538. self.cmd('extract', self.repository_location + '::test')
  539. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2', 'file3', 'file333'])
  540. shutil.rmtree('output/input')
  541. # Exclude using regular expression
  542. with open(self.exclude_file_path, 'wb') as fd:
  543. fd.write(b're:file3+\n')
  544. with changedir('output'):
  545. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  546. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'file2'])
  547. shutil.rmtree('output/input')
  548. # Mixed exclude pattern styles
  549. with open(self.exclude_file_path, 'wb') as fd:
  550. fd.write(b're:file(\\d)\\1\\1$\n')
  551. fd.write(b'fm:nothingwillmatchthis\n')
  552. fd.write(b'*/file1\n')
  553. fd.write(b're:file2$\n')
  554. with changedir('output'):
  555. self.cmd('extract', '--exclude-from=' + self.exclude_file_path, self.repository_location + '::test')
  556. self.assert_equal(sorted(os.listdir('output/input')), ['file3'])
  557. def test_extract_with_pattern(self):
  558. self.cmd("init", self.repository_location)
  559. self.create_regular_file("file1", size=1024 * 80)
  560. self.create_regular_file("file2", size=1024 * 80)
  561. self.create_regular_file("file3", size=1024 * 80)
  562. self.create_regular_file("file4", size=1024 * 80)
  563. self.create_regular_file("file333", size=1024 * 80)
  564. self.cmd("create", self.repository_location + "::test", "input")
  565. # Extract everything with regular expression
  566. with changedir("output"):
  567. self.cmd("extract", self.repository_location + "::test", "re:.*")
  568. self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file3", "file333", "file4"])
  569. shutil.rmtree("output/input")
  570. # Extract with pattern while also excluding files
  571. with changedir("output"):
  572. self.cmd("extract", "--exclude=re:file[34]$", self.repository_location + "::test", r"re:file\d$")
  573. self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2"])
  574. shutil.rmtree("output/input")
  575. # Combine --exclude with pattern for extraction
  576. with changedir("output"):
  577. self.cmd("extract", "--exclude=input/file1", self.repository_location + "::test", "re:file[12]$")
  578. self.assert_equal(sorted(os.listdir("output/input")), ["file2"])
  579. shutil.rmtree("output/input")
  580. # Multiple pattern
  581. with changedir("output"):
  582. self.cmd("extract", self.repository_location + "::test", "fm:input/file1", "fm:*file33*", "input/file2")
  583. self.assert_equal(sorted(os.listdir("output/input")), ["file1", "file2", "file333"])
  584. def test_exclude_caches(self):
  585. self.cmd('init', self.repository_location)
  586. self.create_regular_file('file1', size=1024 * 80)
  587. self.create_regular_file('cache1/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  588. self.create_regular_file('cache2/CACHEDIR.TAG', contents=b'invalid signature')
  589. self.cmd('create', '--exclude-caches', self.repository_location + '::test', 'input')
  590. with changedir('output'):
  591. self.cmd('extract', self.repository_location + '::test')
  592. self.assert_equal(sorted(os.listdir('output/input')), ['cache2', 'file1'])
  593. self.assert_equal(sorted(os.listdir('output/input/cache2')), ['CACHEDIR.TAG'])
  594. def test_exclude_tagged(self):
  595. self.cmd('init', self.repository_location)
  596. self.create_regular_file('file1', size=1024 * 80)
  597. self.create_regular_file('tagged1/.NOBACKUP')
  598. self.create_regular_file('tagged2/00-NOBACKUP')
  599. self.create_regular_file('tagged3/.NOBACKUP/file2')
  600. self.cmd('create', '--exclude-if-present', '.NOBACKUP', '--exclude-if-present', '00-NOBACKUP', self.repository_location + '::test', 'input')
  601. with changedir('output'):
  602. self.cmd('extract', self.repository_location + '::test')
  603. self.assert_equal(sorted(os.listdir('output/input')), ['file1', 'tagged3'])
  604. def test_exclude_keep_tagged(self):
  605. self.cmd('init', self.repository_location)
  606. self.create_regular_file('file0', size=1024)
  607. self.create_regular_file('tagged1/.NOBACKUP1')
  608. self.create_regular_file('tagged1/file1', size=1024)
  609. self.create_regular_file('tagged2/.NOBACKUP2')
  610. self.create_regular_file('tagged2/file2', size=1024)
  611. self.create_regular_file('tagged3/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  612. self.create_regular_file('tagged3/file3', size=1024)
  613. self.create_regular_file('taggedall/.NOBACKUP1')
  614. self.create_regular_file('taggedall/.NOBACKUP2')
  615. self.create_regular_file('taggedall/CACHEDIR.TAG', contents=b'Signature: 8a477f597d28d172789f06886806bc55 extra stuff')
  616. self.create_regular_file('taggedall/file4', size=1024)
  617. self.cmd('create', '--exclude-if-present', '.NOBACKUP1', '--exclude-if-present', '.NOBACKUP2',
  618. '--exclude-caches', '--keep-tag-files', self.repository_location + '::test', 'input')
  619. with changedir('output'):
  620. self.cmd('extract', self.repository_location + '::test')
  621. self.assert_equal(sorted(os.listdir('output/input')), ['file0', 'tagged1', 'tagged2', 'tagged3', 'taggedall'])
  622. self.assert_equal(os.listdir('output/input/tagged1'), ['.NOBACKUP1'])
  623. self.assert_equal(os.listdir('output/input/tagged2'), ['.NOBACKUP2'])
  624. self.assert_equal(os.listdir('output/input/tagged3'), ['CACHEDIR.TAG'])
  625. self.assert_equal(sorted(os.listdir('output/input/taggedall')),
  626. ['.NOBACKUP1', '.NOBACKUP2', 'CACHEDIR.TAG', ])
  627. @pytest.mark.skipif(not xattr.XATTR_FAKEROOT, reason='Linux capabilities test, requires fakeroot >= 1.20.2')
  628. def test_extract_capabilities(self):
  629. fchown = os.fchown
  630. # We need to manually patch chown to get the behaviour Linux has, since fakeroot does not
  631. # accurately model the interaction of chown(2) and Linux capabilities, i.e. it does not remove them.
  632. def patched_fchown(fd, uid, gid):
  633. xattr.setxattr(fd, 'security.capability', None, follow_symlinks=False)
  634. fchown(fd, uid, gid)
  635. # The capability descriptor used here is valid and taken from a /usr/bin/ping
  636. capabilities = b'\x01\x00\x00\x02\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
  637. self.create_regular_file('file')
  638. xattr.setxattr('input/file', 'security.capability', capabilities)
  639. self.cmd('init', self.repository_location)
  640. self.cmd('create', self.repository_location + '::test', 'input')
  641. with changedir('output'):
  642. with patch.object(os, 'fchown', patched_fchown):
  643. self.cmd('extract', self.repository_location + '::test')
  644. assert xattr.getxattr('input/file', 'security.capability') == capabilities
  645. def test_path_normalization(self):
  646. self.cmd('init', self.repository_location)
  647. self.create_regular_file('dir1/dir2/file', size=1024 * 80)
  648. with changedir('input/dir1/dir2'):
  649. self.cmd('create', self.repository_location + '::test', '../../../input/dir1/../dir1/dir2/..')
  650. output = self.cmd('list', self.repository_location + '::test')
  651. self.assert_not_in('..', output)
  652. self.assert_in(' input/dir1/dir2/file', output)
  653. def test_exclude_normalization(self):
  654. self.cmd('init', self.repository_location)
  655. self.create_regular_file('file1', size=1024 * 80)
  656. self.create_regular_file('file2', size=1024 * 80)
  657. with changedir('input'):
  658. self.cmd('create', '--exclude=file1', self.repository_location + '::test1', '.')
  659. with changedir('output'):
  660. self.cmd('extract', self.repository_location + '::test1')
  661. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  662. with changedir('input'):
  663. self.cmd('create', '--exclude=./file1', self.repository_location + '::test2', '.')
  664. with changedir('output'):
  665. self.cmd('extract', self.repository_location + '::test2')
  666. self.assert_equal(sorted(os.listdir('output')), ['file2'])
  667. self.cmd('create', '--exclude=input/./file1', self.repository_location + '::test3', 'input')
  668. with changedir('output'):
  669. self.cmd('extract', self.repository_location + '::test3')
  670. self.assert_equal(sorted(os.listdir('output/input')), ['file2'])
  671. def test_repeated_files(self):
  672. self.create_regular_file('file1', size=1024 * 80)
  673. self.cmd('init', self.repository_location)
  674. self.cmd('create', self.repository_location + '::test', 'input', 'input')
  675. def test_overwrite(self):
  676. self.create_regular_file('file1', size=1024 * 80)
  677. self.create_regular_file('dir2/file2', size=1024 * 80)
  678. self.cmd('init', self.repository_location)
  679. self.cmd('create', self.repository_location + '::test', 'input')
  680. # Overwriting regular files and directories should be supported
  681. os.mkdir('output/input')
  682. os.mkdir('output/input/file1')
  683. os.mkdir('output/input/dir2')
  684. with changedir('output'):
  685. self.cmd('extract', self.repository_location + '::test')
  686. self.assert_dirs_equal('input', 'output/input')
  687. # But non-empty dirs should fail
  688. os.unlink('output/input/file1')
  689. os.mkdir('output/input/file1')
  690. os.mkdir('output/input/file1/dir')
  691. with changedir('output'):
  692. self.cmd('extract', self.repository_location + '::test', exit_code=1)
  693. def test_rename(self):
  694. self.create_regular_file('file1', size=1024 * 80)
  695. self.create_regular_file('dir2/file2', size=1024 * 80)
  696. self.cmd('init', self.repository_location)
  697. self.cmd('create', self.repository_location + '::test', 'input')
  698. self.cmd('create', self.repository_location + '::test.2', 'input')
  699. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  700. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  701. self.cmd('rename', self.repository_location + '::test', 'test.3')
  702. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  703. self.cmd('rename', self.repository_location + '::test.2', 'test.4')
  704. self.cmd('extract', '--dry-run', self.repository_location + '::test.3')
  705. self.cmd('extract', '--dry-run', self.repository_location + '::test.4')
  706. # Make sure both archives have been renamed
  707. with Repository(self.repository_path) as repository:
  708. manifest, key = Manifest.load(repository)
  709. self.assert_equal(len(manifest.archives), 2)
  710. self.assert_in('test.3', manifest.archives)
  711. self.assert_in('test.4', manifest.archives)
  712. def test_delete(self):
  713. self.create_regular_file('file1', size=1024 * 80)
  714. self.create_regular_file('dir2/file2', size=1024 * 80)
  715. self.cmd('init', self.repository_location)
  716. self.cmd('create', self.repository_location + '::test', 'input')
  717. self.cmd('create', self.repository_location + '::test.2', 'input')
  718. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  719. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  720. self.cmd('delete', self.repository_location + '::test')
  721. self.cmd('extract', '--dry-run', self.repository_location + '::test.2')
  722. self.cmd('delete', '--stats', self.repository_location + '::test.2')
  723. # Make sure all data except the manifest has been deleted
  724. with Repository(self.repository_path) as repository:
  725. self.assert_equal(len(repository), 1)
  726. def test_delete_repo(self):
  727. self.create_regular_file('file1', size=1024 * 80)
  728. self.create_regular_file('dir2/file2', size=1024 * 80)
  729. self.cmd('init', self.repository_location)
  730. self.cmd('create', self.repository_location + '::test', 'input')
  731. self.cmd('create', self.repository_location + '::test.2', 'input')
  732. os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'no'
  733. self.cmd('delete', self.repository_location, exit_code=2)
  734. assert os.path.exists(self.repository_path)
  735. os.environ['BORG_DELETE_I_KNOW_WHAT_I_AM_DOING'] = 'YES'
  736. self.cmd('delete', self.repository_location)
  737. # Make sure the repo is gone
  738. self.assertFalse(os.path.exists(self.repository_path))
  739. def test_corrupted_repository(self):
  740. self.cmd('init', self.repository_location)
  741. self.create_src_archive('test')
  742. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  743. self.cmd('check', self.repository_location)
  744. name = sorted(os.listdir(os.path.join(self.tmpdir, 'repository', 'data', '0')), reverse=True)[0]
  745. with open(os.path.join(self.tmpdir, 'repository', 'data', '0', name), 'r+b') as fd:
  746. fd.seek(100)
  747. fd.write(b'XXXX')
  748. self.cmd('check', self.repository_location, exit_code=1)
  749. # we currently need to be able to create a lock directory inside the repo:
  750. @pytest.mark.xfail(reason="we need to be able to create the lock directory inside the repo")
  751. def test_readonly_repository(self):
  752. self.cmd('init', self.repository_location)
  753. self.create_src_archive('test')
  754. os.system('chmod -R ugo-w ' + self.repository_path)
  755. try:
  756. self.cmd('extract', '--dry-run', self.repository_location + '::test')
  757. finally:
  758. # Restore permissions so shutil.rmtree is able to delete it
  759. os.system('chmod -R u+w ' + self.repository_path)
  760. def test_umask(self):
  761. self.create_regular_file('file1', size=1024 * 80)
  762. self.cmd('init', self.repository_location)
  763. self.cmd('create', self.repository_location + '::test', 'input')
  764. mode = os.stat(self.repository_path).st_mode
  765. self.assertEqual(stat.S_IMODE(mode), 0o700)
  766. def test_create_dry_run(self):
  767. self.cmd('init', self.repository_location)
  768. self.cmd('create', '--dry-run', self.repository_location + '::test', 'input')
  769. # Make sure no archive has been created
  770. with Repository(self.repository_path) as repository:
  771. manifest, key = Manifest.load(repository)
  772. self.assert_equal(len(manifest.archives), 0)
  773. def test_progress(self):
  774. self.create_regular_file('file1', size=1024 * 80)
  775. self.cmd('init', self.repository_location)
  776. # progress forced on
  777. output = self.cmd('create', '--progress', self.repository_location + '::test4', 'input')
  778. self.assert_in("\r", output)
  779. # progress forced off
  780. output = self.cmd('create', self.repository_location + '::test5', 'input')
  781. self.assert_not_in("\r", output)
  782. def test_file_status(self):
  783. """test that various file status show expected results
  784. clearly incomplete: only tests for the weird "unchanged" status for now"""
  785. now = time.time()
  786. self.create_regular_file('file1', size=1024 * 80)
  787. os.utime('input/file1', (now - 5, now - 5)) # 5 seconds ago
  788. self.create_regular_file('file2', size=1024 * 80)
  789. self.cmd('init', self.repository_location)
  790. output = self.cmd('create', '-v', '--list', self.repository_location + '::test', 'input')
  791. self.assert_in("A input/file1", output)
  792. self.assert_in("A input/file2", output)
  793. # should find first file as unmodified
  794. output = self.cmd('create', '-v', '--list', self.repository_location + '::test1', 'input')
  795. self.assert_in("U input/file1", output)
  796. # this is expected, although surprising, for why, see:
  797. # https://borgbackup.readthedocs.org/en/latest/faq.html#i-am-seeing-a-added-status-for-a-unchanged-file
  798. self.assert_in("A input/file2", output)
  799. def test_create_topical(self):
  800. now = time.time()
  801. self.create_regular_file('file1', size=1024 * 80)
  802. os.utime('input/file1', (now-5, now-5))
  803. self.create_regular_file('file2', size=1024 * 80)
  804. self.cmd('init', self.repository_location)
  805. # no listing by default
  806. output = self.cmd('create', self.repository_location + '::test', 'input')
  807. self.assert_not_in('file1', output)
  808. # shouldn't be listed even if unchanged
  809. output = self.cmd('create', self.repository_location + '::test0', 'input')
  810. self.assert_not_in('file1', output)
  811. # should list the file as unchanged
  812. output = self.cmd('create', '-v', '--list', '--filter=U', self.repository_location + '::test1', 'input')
  813. self.assert_in('file1', output)
  814. # should *not* list the file as changed
  815. output = self.cmd('create', '-v', '--filter=AM', self.repository_location + '::test2', 'input')
  816. self.assert_not_in('file1', output)
  817. # change the file
  818. self.create_regular_file('file1', size=1024 * 100)
  819. # should list the file as changed
  820. output = self.cmd('create', '-v', '--list', '--filter=AM', self.repository_location + '::test3', 'input')
  821. self.assert_in('file1', output)
  822. def test_create_read_special_broken_symlink(self):
  823. os.symlink('somewhere doesnt exist', os.path.join(self.input_path, 'link'))
  824. self.cmd('init', self.repository_location)
  825. archive = self.repository_location + '::test'
  826. self.cmd('create', '--read-special', archive, 'input')
  827. output = self.cmd('list', archive)
  828. assert 'input/link -> somewhere doesnt exist' in output
  829. # def test_cmdline_compatibility(self):
  830. # self.create_regular_file('file1', size=1024 * 80)
  831. # self.cmd('init', self.repository_location)
  832. # self.cmd('create', self.repository_location + '::test', 'input')
  833. # output = self.cmd('foo', self.repository_location, '--old')
  834. # self.assert_in('"--old" has been deprecated. Use "--new" instead', output)
  835. def test_prune_repository(self):
  836. self.cmd('init', self.repository_location)
  837. self.cmd('create', self.repository_location + '::test1', src_dir)
  838. self.cmd('create', self.repository_location + '::test2', src_dir)
  839. # these are not really a checkpoints, but they look like some:
  840. self.cmd('create', self.repository_location + '::test3.checkpoint', src_dir)
  841. self.cmd('create', self.repository_location + '::test3.checkpoint.1', src_dir)
  842. output = self.cmd('prune', '-v', '--list', '--dry-run', self.repository_location, '--keep-daily=2')
  843. self.assert_in('Would prune: test1', output)
  844. # must keep the latest non-checkpoint archive:
  845. self.assert_in('Keeping archive: test2', output)
  846. output = self.cmd('list', self.repository_location)
  847. self.assert_in('test1', output)
  848. self.assert_in('test2', output)
  849. self.assert_in('test3.checkpoint', output)
  850. self.assert_in('test3.checkpoint.1', output)
  851. self.cmd('prune', self.repository_location, '--keep-daily=2')
  852. output = self.cmd('list', self.repository_location)
  853. self.assert_not_in('test1', output)
  854. # the latest non-checkpoint archive must be still there:
  855. self.assert_in('test2', output)
  856. def test_prune_repository_save_space(self):
  857. self.cmd('init', self.repository_location)
  858. self.cmd('create', self.repository_location + '::test1', src_dir)
  859. self.cmd('create', self.repository_location + '::test2', src_dir)
  860. output = self.cmd('prune', '-v', '--list', '--dry-run', self.repository_location, '--keep-daily=2')
  861. self.assert_in('Keeping archive: test2', output)
  862. self.assert_in('Would prune: test1', output)
  863. output = self.cmd('list', self.repository_location)
  864. self.assert_in('test1', output)
  865. self.assert_in('test2', output)
  866. self.cmd('prune', '--save-space', self.repository_location, '--keep-daily=2')
  867. output = self.cmd('list', self.repository_location)
  868. self.assert_not_in('test1', output)
  869. self.assert_in('test2', output)
  870. def test_prune_repository_prefix(self):
  871. self.cmd('init', self.repository_location)
  872. self.cmd('create', self.repository_location + '::foo-2015-08-12-10:00', src_dir)
  873. self.cmd('create', self.repository_location + '::foo-2015-08-12-20:00', src_dir)
  874. self.cmd('create', self.repository_location + '::bar-2015-08-12-10:00', src_dir)
  875. self.cmd('create', self.repository_location + '::bar-2015-08-12-20:00', src_dir)
  876. output = self.cmd('prune', '-v', '--list', '--dry-run', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  877. self.assert_in('Keeping archive: foo-2015-08-12-20:00', output)
  878. self.assert_in('Would prune: foo-2015-08-12-10:00', output)
  879. output = self.cmd('list', self.repository_location)
  880. self.assert_in('foo-2015-08-12-10:00', output)
  881. self.assert_in('foo-2015-08-12-20:00', output)
  882. self.assert_in('bar-2015-08-12-10:00', output)
  883. self.assert_in('bar-2015-08-12-20:00', output)
  884. self.cmd('prune', self.repository_location, '--keep-daily=2', '--prefix=foo-')
  885. output = self.cmd('list', self.repository_location)
  886. self.assert_not_in('foo-2015-08-12-10:00', output)
  887. self.assert_in('foo-2015-08-12-20:00', output)
  888. self.assert_in('bar-2015-08-12-10:00', output)
  889. self.assert_in('bar-2015-08-12-20:00', output)
  890. def test_list_prefix(self):
  891. self.cmd('init', self.repository_location)
  892. self.cmd('create', self.repository_location + '::test-1', src_dir)
  893. self.cmd('create', self.repository_location + '::something-else-than-test-1', src_dir)
  894. self.cmd('create', self.repository_location + '::test-2', src_dir)
  895. output = self.cmd('list', '--prefix=test-', self.repository_location)
  896. self.assert_in('test-1', output)
  897. self.assert_in('test-2', output)
  898. self.assert_not_in('something-else', output)
  899. def test_list_list_format(self):
  900. self.cmd('init', self.repository_location)
  901. test_archive = self.repository_location + '::test'
  902. self.cmd('create', test_archive, src_dir)
  903. output_1 = self.cmd('list', test_archive)
  904. output_2 = self.cmd('list', '--list-format', '{mode} {user:6} {group:6} {size:8d} {isomtime} {path}{extra}{NEWLINE}', test_archive)
  905. output_3 = self.cmd('list', '--list-format', '{mtime:%s} {path}{NEWLINE}', test_archive)
  906. self.assertEqual(output_1, output_2)
  907. self.assertNotEqual(output_1, output_3)
  908. def test_break_lock(self):
  909. self.cmd('init', self.repository_location)
  910. self.cmd('break-lock', self.repository_location)
  911. def test_usage(self):
  912. if self.FORK_DEFAULT:
  913. self.cmd(exit_code=0)
  914. self.cmd('-h', exit_code=0)
  915. else:
  916. self.assert_raises(SystemExit, lambda: self.cmd())
  917. self.assert_raises(SystemExit, lambda: self.cmd('-h'))
  918. def test_help(self):
  919. assert 'Borg' in self.cmd('help')
  920. assert 'patterns' in self.cmd('help', 'patterns')
  921. assert 'Initialize' in self.cmd('help', 'init')
  922. assert 'positional arguments' not in self.cmd('help', 'init', '--epilog-only')
  923. assert 'This command initializes' not in self.cmd('help', 'init', '--usage-only')
  924. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  925. def test_fuse(self):
  926. def has_noatime(some_file):
  927. atime_before = os.stat(some_file).st_atime_ns
  928. try:
  929. os.close(os.open(some_file, flags_noatime))
  930. except PermissionError:
  931. return False
  932. else:
  933. atime_after = os.stat(some_file).st_atime_ns
  934. noatime_used = flags_noatime != flags_normal
  935. return noatime_used and atime_before == atime_after
  936. self.cmd('init', self.repository_location)
  937. self.create_test_files()
  938. have_noatime = has_noatime('input/file1')
  939. self.cmd('create', self.repository_location + '::archive', 'input')
  940. self.cmd('create', self.repository_location + '::archive2', 'input')
  941. if has_lchflags:
  942. # remove the file we did not backup, so input and mount become equal
  943. os.remove(os.path.join('input', 'flagfile'))
  944. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  945. # mount the whole repository, archive contents shall show up in archivename subdirs of mountpoint:
  946. with self.fuse_mount(self.repository_location, mountpoint):
  947. # bsdflags are not supported by the FUSE mount
  948. # we also ignore xattrs here, they are tested separately
  949. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive', 'input'),
  950. ignore_bsdflags=True, ignore_xattrs=True)
  951. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'archive2', 'input'),
  952. ignore_bsdflags=True, ignore_xattrs=True)
  953. # mount only 1 archive, its contents shall show up directly in mountpoint:
  954. with self.fuse_mount(self.repository_location + '::archive', mountpoint):
  955. self.assert_dirs_equal(self.input_path, os.path.join(mountpoint, 'input'),
  956. ignore_bsdflags=True, ignore_xattrs=True)
  957. # regular file
  958. in_fn = 'input/file1'
  959. out_fn = os.path.join(mountpoint, 'input', 'file1')
  960. # stat
  961. sti1 = os.stat(in_fn)
  962. sto1 = os.stat(out_fn)
  963. assert sti1.st_mode == sto1.st_mode
  964. assert sti1.st_uid == sto1.st_uid
  965. assert sti1.st_gid == sto1.st_gid
  966. assert sti1.st_size == sto1.st_size
  967. if have_noatime:
  968. assert sti1.st_atime == sto1.st_atime
  969. assert sti1.st_ctime == sto1.st_ctime
  970. assert sti1.st_mtime == sto1.st_mtime
  971. # note: there is another hardlink to this, see below
  972. assert sti1.st_nlink == sto1.st_nlink == 2
  973. # read
  974. with open(in_fn, 'rb') as in_f, open(out_fn, 'rb') as out_f:
  975. assert in_f.read() == out_f.read()
  976. # hardlink (to 'input/file1')
  977. in_fn = 'input/hardlink'
  978. out_fn = os.path.join(mountpoint, 'input', 'hardlink')
  979. sti2 = os.stat(in_fn)
  980. sto2 = os.stat(out_fn)
  981. assert sti2.st_nlink == sto2.st_nlink == 2
  982. assert sto1.st_ino == sto2.st_ino
  983. # symlink
  984. in_fn = 'input/link1'
  985. out_fn = os.path.join(mountpoint, 'input', 'link1')
  986. sti = os.stat(in_fn, follow_symlinks=False)
  987. sto = os.stat(out_fn, follow_symlinks=False)
  988. assert stat.S_ISLNK(sti.st_mode)
  989. assert stat.S_ISLNK(sto.st_mode)
  990. assert os.readlink(in_fn) == os.readlink(out_fn)
  991. # FIFO
  992. out_fn = os.path.join(mountpoint, 'input', 'fifo1')
  993. sto = os.stat(out_fn)
  994. assert stat.S_ISFIFO(sto.st_mode)
  995. # list/read xattrs
  996. try:
  997. in_fn = 'input/fusexattr'
  998. out_fn = os.path.join(mountpoint, 'input', 'fusexattr')
  999. if not xattr.XATTR_FAKEROOT and xattr.is_enabled(self.input_path):
  1000. assert no_selinux(xattr.listxattr(out_fn)) == ['user.foo', ]
  1001. assert xattr.getxattr(out_fn, 'user.foo') == b'bar'
  1002. else:
  1003. assert xattr.listxattr(out_fn) == []
  1004. try:
  1005. xattr.getxattr(out_fn, 'user.foo')
  1006. except OSError as e:
  1007. assert e.errno == llfuse.ENOATTR
  1008. else:
  1009. assert False, "expected OSError(ENOATTR), but no error was raised"
  1010. except OSError as err:
  1011. if sys.platform.startswith(('freebsd', )) and err.errno == errno.ENOTSUP:
  1012. # some systems have no xattr support on FUSE
  1013. pass
  1014. else:
  1015. raise
  1016. @unittest.skipUnless(has_llfuse, 'llfuse not installed')
  1017. def test_fuse_allow_damaged_files(self):
  1018. self.cmd('init', self.repository_location)
  1019. self.create_src_archive('archive')
  1020. # Get rid of a chunk and repair it
  1021. archive, repository = self.open_archive('archive')
  1022. with repository:
  1023. for item in archive.iter_items():
  1024. if item[b'path'].endswith('testsuite/archiver.py'):
  1025. repository.delete(item[b'chunks'][-1][0])
  1026. path = item[b'path'] # store full path for later
  1027. break
  1028. else:
  1029. assert False # missed the file
  1030. repository.commit()
  1031. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1032. mountpoint = os.path.join(self.tmpdir, 'mountpoint')
  1033. with self.fuse_mount(self.repository_location + '::archive', mountpoint):
  1034. with pytest.raises(OSError) as excinfo:
  1035. open(os.path.join(mountpoint, path))
  1036. assert excinfo.value.errno == errno.EIO
  1037. with self.fuse_mount(self.repository_location + '::archive', mountpoint, '-o', 'allow_damaged_files'):
  1038. open(os.path.join(mountpoint, path)).close()
  1039. def verify_aes_counter_uniqueness(self, method):
  1040. seen = set() # Chunks already seen
  1041. used = set() # counter values already used
  1042. def verify_uniqueness():
  1043. with Repository(self.repository_path) as repository:
  1044. for key, _ in repository.open_index(repository.get_transaction_id()).iteritems():
  1045. data = repository.get(key)
  1046. hash = sha256(data).digest()
  1047. if hash not in seen:
  1048. seen.add(hash)
  1049. num_blocks = num_aes_blocks(len(data) - 41)
  1050. nonce = bytes_to_long(data[33:41])
  1051. for counter in range(nonce, nonce + num_blocks):
  1052. self.assert_not_in(counter, used)
  1053. used.add(counter)
  1054. self.create_test_files()
  1055. os.environ['BORG_PASSPHRASE'] = 'passphrase'
  1056. self.cmd('init', '--encryption=' + method, self.repository_location)
  1057. verify_uniqueness()
  1058. self.cmd('create', self.repository_location + '::test', 'input')
  1059. verify_uniqueness()
  1060. self.cmd('create', self.repository_location + '::test.2', 'input')
  1061. verify_uniqueness()
  1062. self.cmd('delete', self.repository_location + '::test.2')
  1063. verify_uniqueness()
  1064. self.assert_equal(used, set(range(len(used))))
  1065. def test_aes_counter_uniqueness_keyfile(self):
  1066. self.verify_aes_counter_uniqueness('keyfile')
  1067. def test_aes_counter_uniqueness_passphrase(self):
  1068. self.verify_aes_counter_uniqueness('repokey')
  1069. def test_debug_dump_archive_items(self):
  1070. self.create_test_files()
  1071. self.cmd('init', self.repository_location)
  1072. self.cmd('create', self.repository_location + '::test', 'input')
  1073. with changedir('output'):
  1074. output = self.cmd('debug-dump-archive-items', self.repository_location + '::test')
  1075. output_dir = sorted(os.listdir('output'))
  1076. assert len(output_dir) > 0 and output_dir[0].startswith('000000_')
  1077. assert 'Done.' in output
  1078. def test_debug_dump_repo_objs(self):
  1079. self.create_test_files()
  1080. self.cmd('init', self.repository_location)
  1081. self.cmd('create', self.repository_location + '::test', 'input')
  1082. with changedir('output'):
  1083. output = self.cmd('debug-dump-repo-objs', self.repository_location)
  1084. output_dir = sorted(os.listdir('output'))
  1085. assert len(output_dir) > 0 and output_dir[0].startswith('000000_')
  1086. assert 'Done.' in output
  1087. def test_debug_put_get_delete_obj(self):
  1088. self.cmd('init', self.repository_location)
  1089. data = b'some data'
  1090. hexkey = sha256(data).hexdigest()
  1091. self.create_regular_file('file', contents=data)
  1092. output = self.cmd('debug-put-obj', self.repository_location, 'input/file')
  1093. assert hexkey in output
  1094. output = self.cmd('debug-get-obj', self.repository_location, hexkey, 'output/file')
  1095. assert hexkey in output
  1096. with open('output/file', 'rb') as f:
  1097. data_read = f.read()
  1098. assert data == data_read
  1099. output = self.cmd('debug-delete-obj', self.repository_location, hexkey)
  1100. assert "deleted" in output
  1101. output = self.cmd('debug-delete-obj', self.repository_location, hexkey)
  1102. assert "not found" in output
  1103. output = self.cmd('debug-delete-obj', self.repository_location, 'invalid')
  1104. assert "is invalid" in output
  1105. def test_key_export_keyfile(self):
  1106. export_file = self.output_path + '/exported'
  1107. self.cmd('init', self.repository_location, '--encryption', 'keyfile')
  1108. repo_id = self._extract_repository_id(self.repository_path)
  1109. self.cmd('key', 'export', self.repository_location, export_file)
  1110. with open(export_file, 'r') as fd:
  1111. export_contents = fd.read()
  1112. assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n')
  1113. key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0]
  1114. with open(key_file, 'r') as fd:
  1115. key_contents = fd.read()
  1116. assert key_contents == export_contents
  1117. os.unlink(key_file)
  1118. self.cmd('key', 'import', self.repository_location, export_file)
  1119. with open(key_file, 'r') as fd:
  1120. key_contents2 = fd.read()
  1121. assert key_contents2 == key_contents
  1122. def test_key_export_repokey(self):
  1123. export_file = self.output_path + '/exported'
  1124. self.cmd('init', self.repository_location, '--encryption', 'repokey')
  1125. repo_id = self._extract_repository_id(self.repository_path)
  1126. self.cmd('key', 'export', self.repository_location, export_file)
  1127. with open(export_file, 'r') as fd:
  1128. export_contents = fd.read()
  1129. assert export_contents.startswith('BORG_KEY ' + bin_to_hex(repo_id) + '\n')
  1130. with Repository(self.repository_path) as repository:
  1131. repo_key = RepoKey(repository)
  1132. repo_key.load(None, Passphrase.env_passphrase())
  1133. backup_key = KeyfileKey(None)
  1134. backup_key.load(export_file, Passphrase.env_passphrase())
  1135. assert repo_key.enc_key == backup_key.enc_key
  1136. with Repository(self.repository_path) as repository:
  1137. repository.save_key(b'')
  1138. self.cmd('key', 'import', self.repository_location, export_file)
  1139. with Repository(self.repository_path) as repository:
  1140. repo_key2 = RepoKey(repository)
  1141. repo_key2.load(None, Passphrase.env_passphrase())
  1142. assert repo_key2.enc_key == repo_key2.enc_key
  1143. def test_key_import_errors(self):
  1144. export_file = self.output_path + '/exported'
  1145. self.cmd('init', self.repository_location, '--encryption', 'keyfile')
  1146. self.cmd('key', 'import', self.repository_location, export_file, exit_code=EXIT_ERROR)
  1147. with open(export_file, 'w') as fd:
  1148. fd.write('something not a key\n')
  1149. if self.FORK_DEFAULT:
  1150. self.cmd('key', 'import', self.repository_location, export_file, exit_code=2)
  1151. else:
  1152. self.assert_raises(NotABorgKeyFile, lambda: self.cmd('key', 'import', self.repository_location, export_file))
  1153. with open(export_file, 'w') as fd:
  1154. fd.write('BORG_KEY a0a0a0\n')
  1155. if self.FORK_DEFAULT:
  1156. self.cmd('key', 'import', self.repository_location, export_file, exit_code=2)
  1157. else:
  1158. self.assert_raises(RepoIdMismatch, lambda: self.cmd('key', 'import', self.repository_location, export_file))
  1159. def test_key_export_paperkey(self):
  1160. repo_id = 'e294423506da4e1ea76e8dcdf1a3919624ae3ae496fddf905610c351d3f09239'
  1161. export_file = self.output_path + '/exported'
  1162. self.cmd('init', self.repository_location, '--encryption', 'keyfile')
  1163. self._set_repository_id(self.repository_path, unhexlify(repo_id))
  1164. key_file = self.keys_path + '/' + os.listdir(self.keys_path)[0]
  1165. with open(key_file, 'w') as fd:
  1166. fd.write(KeyfileKey.FILE_ID + ' ' + repo_id + '\n')
  1167. fd.write(b2a_base64(b'abcdefghijklmnopqrstu').decode())
  1168. self.cmd('key', 'export', '--paper', self.repository_location, export_file)
  1169. with open(export_file, 'r') as fd:
  1170. export_contents = fd.read()
  1171. assert export_contents == """To restore key use borg key import --paper /path/to/repo
  1172. BORG PAPER KEY v1
  1173. id: 2 / e29442 3506da 4e1ea7 / 25f62a 5a3d41 - 02
  1174. 1: 616263 646566 676869 6a6b6c 6d6e6f 707172 - 6d
  1175. 2: 737475 - 88
  1176. """
  1177. @unittest.skipUnless('binary' in BORG_EXES, 'no borg.exe available')
  1178. class ArchiverTestCaseBinary(ArchiverTestCase):
  1179. EXE = 'borg.exe'
  1180. FORK_DEFAULT = True
  1181. @unittest.skip('test_basic_functionality seems incompatible with fakeroot and/or the binary.')
  1182. def test_basic_functionality(self):
  1183. pass
  1184. @unittest.skip('test_overwrite seems incompatible with fakeroot and/or the binary.')
  1185. def test_overwrite(self):
  1186. pass
  1187. def test_fuse(self):
  1188. if fakeroot_detected():
  1189. unittest.skip('test_fuse with the binary is not compatible with fakeroot')
  1190. else:
  1191. super().test_fuse()
  1192. class ArchiverCheckTestCase(ArchiverTestCaseBase):
  1193. def setUp(self):
  1194. super().setUp()
  1195. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  1196. self.cmd('init', self.repository_location)
  1197. self.create_src_archive('archive1')
  1198. self.create_src_archive('archive2')
  1199. def test_check_usage(self):
  1200. output = self.cmd('check', '-v', self.repository_location, exit_code=0)
  1201. self.assert_in('Starting repository check', output)
  1202. self.assert_in('Starting archive consistency check', output)
  1203. output = self.cmd('check', '-v', '--repository-only', self.repository_location, exit_code=0)
  1204. self.assert_in('Starting repository check', output)
  1205. self.assert_not_in('Starting archive consistency check', output)
  1206. output = self.cmd('check', '-v', '--archives-only', self.repository_location, exit_code=0)
  1207. self.assert_not_in('Starting repository check', output)
  1208. self.assert_in('Starting archive consistency check', output)
  1209. output = self.cmd('check', '-v', '--archives-only', '--prefix=archive2', self.repository_location, exit_code=0)
  1210. self.assert_not_in('archive1', output)
  1211. def test_missing_file_chunk(self):
  1212. archive, repository = self.open_archive('archive1')
  1213. with repository:
  1214. for item in archive.iter_items():
  1215. if item[b'path'].endswith('testsuite/archiver.py'):
  1216. valid_chunks = item[b'chunks']
  1217. killed_chunk = valid_chunks[-1]
  1218. repository.delete(killed_chunk[0])
  1219. break
  1220. else:
  1221. self.assert_true(False) # should not happen
  1222. repository.commit()
  1223. self.cmd('check', self.repository_location, exit_code=1)
  1224. output = self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1225. self.assert_in('New missing file chunk detected', output)
  1226. self.cmd('check', self.repository_location, exit_code=0)
  1227. # check that the file in the old archives has now a different chunk list without the killed chunk
  1228. for archive_name in ('archive1', 'archive2'):
  1229. archive, repository = self.open_archive(archive_name)
  1230. with repository:
  1231. for item in archive.iter_items():
  1232. if item[b'path'].endswith('testsuite/archiver.py'):
  1233. self.assert_not_equal(valid_chunks, item[b'chunks'])
  1234. self.assert_not_in(killed_chunk, item[b'chunks'])
  1235. break
  1236. else:
  1237. self.assert_true(False) # should not happen
  1238. # do a fresh backup (that will include the killed chunk)
  1239. with patch.object(ChunkBuffer, 'BUFFER_SIZE', 10):
  1240. self.create_src_archive('archive3')
  1241. # check should be able to heal the file now:
  1242. output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0)
  1243. self.assert_in('Healed previously missing file chunk', output)
  1244. self.assert_in('testsuite/archiver.py: Completely healed previously damaged file!', output)
  1245. # check that the file in the old archives has the correct chunks again
  1246. for archive_name in ('archive1', 'archive2'):
  1247. archive, repository = self.open_archive(archive_name)
  1248. with repository:
  1249. for item in archive.iter_items():
  1250. if item[b'path'].endswith('testsuite/archiver.py'):
  1251. self.assert_equal(valid_chunks, item[b'chunks'])
  1252. break
  1253. else:
  1254. self.assert_true(False) # should not happen
  1255. def test_missing_archive_item_chunk(self):
  1256. archive, repository = self.open_archive('archive1')
  1257. with repository:
  1258. repository.delete(archive.metadata[b'items'][-5])
  1259. repository.commit()
  1260. self.cmd('check', self.repository_location, exit_code=1)
  1261. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1262. self.cmd('check', self.repository_location, exit_code=0)
  1263. def test_missing_archive_metadata(self):
  1264. archive, repository = self.open_archive('archive1')
  1265. with repository:
  1266. repository.delete(archive.id)
  1267. repository.commit()
  1268. self.cmd('check', self.repository_location, exit_code=1)
  1269. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1270. self.cmd('check', self.repository_location, exit_code=0)
  1271. def test_missing_manifest(self):
  1272. archive, repository = self.open_archive('archive1')
  1273. with repository:
  1274. repository.delete(Manifest.MANIFEST_ID)
  1275. repository.commit()
  1276. self.cmd('check', self.repository_location, exit_code=1)
  1277. output = self.cmd('check', '-v', '--repair', self.repository_location, exit_code=0)
  1278. self.assert_in('archive1', output)
  1279. self.assert_in('archive2', output)
  1280. self.cmd('check', self.repository_location, exit_code=0)
  1281. def test_extra_chunks(self):
  1282. self.cmd('check', self.repository_location, exit_code=0)
  1283. with Repository(self.repository_location, exclusive=True) as repository:
  1284. repository.put(b'01234567890123456789012345678901', b'xxxx')
  1285. repository.commit()
  1286. self.cmd('check', self.repository_location, exit_code=1)
  1287. self.cmd('check', self.repository_location, exit_code=1)
  1288. self.cmd('check', '--repair', self.repository_location, exit_code=0)
  1289. self.cmd('check', self.repository_location, exit_code=0)
  1290. self.cmd('extract', '--dry-run', self.repository_location + '::archive1', exit_code=0)
  1291. def test_empty_repository(self):
  1292. with Repository(self.repository_location, exclusive=True) as repository:
  1293. for id_ in repository.list():
  1294. repository.delete(id_)
  1295. repository.commit()
  1296. self.cmd('check', self.repository_location, exit_code=1)
  1297. @pytest.mark.skipif(sys.platform == 'cygwin', reason='remote is broken on cygwin and hangs')
  1298. class RemoteArchiverTestCase(ArchiverTestCase):
  1299. prefix = '__testsuite__:'
  1300. def test_remote_repo_restrict_to_path(self):
  1301. # restricted to repo directory itself:
  1302. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]):
  1303. self.cmd('init', self.repository_location)
  1304. # restricted to repo directory itself, fail for other directories with same prefix:
  1305. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', self.repository_path]):
  1306. self.assert_raises(PathNotAllowed, lambda: self.cmd('init', self.repository_location + '_0'))
  1307. # restricted to a completely different path:
  1308. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo']):
  1309. self.assert_raises(PathNotAllowed, lambda: self.cmd('init', self.repository_location + '_1'))
  1310. path_prefix = os.path.dirname(self.repository_path)
  1311. # restrict to repo directory's parent directory:
  1312. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', path_prefix]):
  1313. self.cmd('init', self.repository_location + '_2')
  1314. # restrict to repo directory's parent directory and another directory:
  1315. with patch.object(RemoteRepository, 'extra_test_args', ['--restrict-to-path', '/foo', '--restrict-to-path', path_prefix]):
  1316. self.cmd('init', self.repository_location + '_3')
  1317. @unittest.skip('only works locally')
  1318. def test_debug_put_get_delete_obj(self):
  1319. pass
  1320. def test_strip_components_doesnt_leak(self):
  1321. self.cmd('init', self.repository_location)
  1322. self.create_regular_file('dir/file', contents=b"test file contents 1")
  1323. self.create_regular_file('dir/file2', contents=b"test file contents 2")
  1324. self.create_regular_file('skipped-file1', contents=b"test file contents 3")
  1325. self.create_regular_file('skipped-file2', contents=b"test file contents 4")
  1326. self.create_regular_file('skipped-file3', contents=b"test file contents 5")
  1327. self.cmd('create', self.repository_location + '::test', 'input')
  1328. marker = 'cached responses left in RemoteRepository'
  1329. with changedir('output'):
  1330. res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '3')
  1331. self.assert_true(marker not in res)
  1332. with self.assert_creates_file('file'):
  1333. res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '2')
  1334. self.assert_true(marker not in res)
  1335. with self.assert_creates_file('dir/file'):
  1336. res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '1')
  1337. self.assert_true(marker not in res)
  1338. with self.assert_creates_file('input/dir/file'):
  1339. res = self.cmd('extract', "--debug", self.repository_location + '::test', '--strip-components', '0')
  1340. self.assert_true(marker not in res)
  1341. def test_get_args():
  1342. archiver = Archiver()
  1343. # everything normal:
  1344. # first param is argv as produced by ssh forced command,
  1345. # second param is like from SSH_ORIGINAL_COMMAND env variable
  1346. args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
  1347. 'borg serve --info --umask=0027')
  1348. assert args.func == archiver.do_serve
  1349. assert args.restrict_to_paths == ['/p1', '/p2']
  1350. assert args.umask == 0o027
  1351. assert args.log_level == 'info'
  1352. # trying to cheat - break out of path restriction
  1353. args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
  1354. 'borg serve --restrict-to-path=/')
  1355. assert args.restrict_to_paths == ['/p1', '/p2']
  1356. # trying to cheat - try to execute different subcommand
  1357. args = archiver.get_args(['borg', 'serve', '--restrict-to-path=/p1', '--restrict-to-path=/p2', ],
  1358. 'borg init /')
  1359. assert args.func == archiver.do_serve
  1360. class TestBuildFilter:
  1361. def test_basic(self):
  1362. matcher = PatternMatcher()
  1363. matcher.add([parse_pattern('included')], True)
  1364. filter = Archiver.build_filter(matcher)
  1365. assert filter({b'path': 'included'})
  1366. assert filter({b'path': 'included/file'})
  1367. assert not filter({b'path': 'something else'})
  1368. def test_empty(self):
  1369. matcher = PatternMatcher(fallback=True)
  1370. filter = Archiver.build_filter(matcher)
  1371. assert filter({b'path': 'anything'})
  1372. def test_strip_components(self):
  1373. matcher = PatternMatcher(fallback=True)
  1374. filter = Archiver.build_filter(matcher, strip_components=1)
  1375. assert not filter({b'path': 'shallow'})
  1376. assert not filter({b'path': 'shallow/'}) # can this even happen? paths are normalized...
  1377. assert filter({b'path': 'deep enough/file'})
  1378. assert filter({b'path': 'something/dir/file'})