Debian Codegraph @

tests/test/test_tarfile.py

raw
1 import errno
2 import sys
3 import os
4 import io
5 from hashlib import sha256
6 from contextlib import contextmanager, ExitStack
7 from random import Random
8 import pathlib
9 import shutil
10 import re
11 import warnings
12 import stat
13
14 import unittest
15 import unittest.mock
16 from backports.zstd import tarfile
17
18 from test import archiver_tests
19 from test import support
20 from test.support import os_helper
21 from test.support import script_helper
22 from test.support import warnings_helper
23
24 # Check for our compression modules.
25 try:
26 import gzip
27 except ImportError:
28 gzip = None
29 try:
30 import zlib
31 except ImportError:
32 zlib = None
33 try:
34 import bz2
35 except ImportError:
36 bz2 = None
37 try:
38 import lzma
39 except ImportError:
40 lzma = None
41 from backports import zstd
42
43 # backportszstd: specific test conditions
44 try:
45 os.path.realpath("a\x00b")
46 except ValueError:
47 gh_106242_support = True
48 else:
49 gh_106242_support = False
50 try:
51 os.path.realpath("a", strict=os.path.ALLOW_MISSING)
52 except (AttributeError, TypeError):
53 gh_135034_support = False
54 else:
55 gh_135034_support = True
56
57 def sha256sum(data):
58 return sha256(data).hexdigest()
59
60 TEMPDIR = os.path.abspath(os_helper.TESTFN) + "-tardir"
61 tarextdir = TEMPDIR + '-extract-test'
62 tarname = support.findfile("testtar.tar", subdir="archivetestdata")
63 gzipname = os.path.join(TEMPDIR, "testtar.tar.gz")
64 bz2name = os.path.join(TEMPDIR, "testtar.tar.bz2")
65 xzname = os.path.join(TEMPDIR, "testtar.tar.xz")
66 zstname = os.path.join(TEMPDIR, "testtar.tar.zst")
67 tmpname = os.path.join(TEMPDIR, "tmp.tar")
68 dotlessname = os.path.join(TEMPDIR, "testtar")
69 SPACE = b" "
70
71 sha256_regtype = (
72 "e09e4bc8b3c9d9177e77256353b36c159f5f040531bbd4b024a8f9b9196c71ce"
73 )
74 sha256_sparse = (
75 "4f05a776071146756345ceee937b33fc5644f5a96b9780d1c7d6a32cdf164d7b"
76 )
77
78
79 class TarTest:
80 tarname = tarname
81 suffix = ''
82 open = io.FileIO
83 taropen = tarfile.TarFile.taropen
84
85 @property
86 def mode(self):
87 return self.prefix + self.suffix
88
89 @support.requires_gzip()
90 class GzipTest:
91 tarname = gzipname
92 suffix = 'gz'
93 open = gzip.GzipFile if gzip else None
94 taropen = tarfile.TarFile.gzopen
95
96 @support.requires_bz2()
97 class Bz2Test:
98 tarname = bz2name
99 suffix = 'bz2'
100 open = bz2.BZ2File if bz2 else None
101 taropen = tarfile.TarFile.bz2open
102
103 @support.requires_lzma()
104 class LzmaTest:
105 tarname = xzname
106 suffix = 'xz'
107 open = lzma.LZMAFile if lzma else None
108 taropen = tarfile.TarFile.xzopen
109
110 @support.requires_zstd()
111 class ZstdTest:
112 tarname = zstname
113 suffix = 'zst'
114 open = zstd.ZstdFile if zstd else None
115 taropen = tarfile.TarFile.zstopen
116
117 class ReadTest(TarTest):
118
119 prefix = "r:"
120
121 def setUp(self):
122 self.tar = tarfile.open(self.tarname, mode=self.mode,
123 encoding="iso8859-1")
124
125 def tearDown(self):
126 self.tar.close()
127
128 class StreamModeTest(ReadTest):
129
130 # Only needs to change how the tarfile is opened to set
131 # stream mode
132 def setUp(self):
133 self.tar = tarfile.open(self.tarname, mode=self.mode,
134 encoding="iso8859-1",
135 stream=True)
136
137 class UstarReadTest(ReadTest, unittest.TestCase):
138
139 def test_fileobj_regular_file(self):
140 tarinfo = self.tar.getmember("ustar/regtype")
141 with self.tar.extractfile(tarinfo) as fobj:
142 data = fobj.read()
143 self.assertEqual(len(data), tarinfo.size,
144 "regular file extraction failed")
145 self.assertEqual(sha256sum(data), sha256_regtype,
146 "regular file extraction failed")
147
148 def test_fileobj_readlines(self):
149 self.tar.extract("ustar/regtype", TEMPDIR, filter='data')
150 tarinfo = self.tar.getmember("ustar/regtype")
151 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
152 lines1 = fobj1.readlines()
153
154 with self.tar.extractfile(tarinfo) as fobj:
155 fobj2 = io.TextIOWrapper(fobj)
156 lines2 = fobj2.readlines()
157 self.assertEqual(lines1, lines2,
158 "fileobj.readlines() failed")
159 self.assertEqual(len(lines2), 114,
160 "fileobj.readlines() failed")
161 self.assertEqual(lines2[83],
162 "I will gladly admit that Python is not the fastest "
163 "running scripting language.\n",
164 "fileobj.readlines() failed")
165
166 def test_fileobj_iter(self):
167 self.tar.extract("ustar/regtype", TEMPDIR, filter='data')
168 tarinfo = self.tar.getmember("ustar/regtype")
169 with open(os.path.join(TEMPDIR, "ustar/regtype"), "r") as fobj1:
170 lines1 = fobj1.readlines()
171 with self.tar.extractfile(tarinfo) as fobj2:
172 lines2 = list(io.TextIOWrapper(fobj2))
173 self.assertEqual(lines1, lines2,
174 "fileobj.__iter__() failed")
175
176 def test_fileobj_seek(self):
177 self.tar.extract("ustar/regtype", TEMPDIR,
178 filter='data')
179 with open(os.path.join(TEMPDIR, "ustar/regtype"), "rb") as fobj:
180 data = fobj.read()
181
182 tarinfo = self.tar.getmember("ustar/regtype")
183 with self.tar.extractfile(tarinfo) as fobj:
184 text = fobj.read()
185 fobj.seek(0)
186 self.assertEqual(0, fobj.tell(),
187 "seek() to file's start failed")
188 fobj.seek(2048, 0)
189 self.assertEqual(2048, fobj.tell(),
190 "seek() to absolute position failed")
191 fobj.seek(-1024, 1)
192 self.assertEqual(1024, fobj.tell(),
193 "seek() to negative relative position failed")
194 fobj.seek(1024, 1)
195 self.assertEqual(2048, fobj.tell(),
196 "seek() to positive relative position failed")
197 s = fobj.read(10)
198 self.assertEqual(s, data[2048:2058],
199 "read() after seek failed")
200 fobj.seek(0, 2)
201 self.assertEqual(tarinfo.size, fobj.tell(),
202 "seek() to file's end failed")
203 self.assertEqual(fobj.read(), b"",
204 "read() at file's end did not return empty string")
205 fobj.seek(-tarinfo.size, 2)
206 self.assertEqual(0, fobj.tell(),
207 "relative seek() to file's end failed")
208 fobj.seek(512)
209 s1 = fobj.readlines()
210 fobj.seek(512)
211 s2 = fobj.readlines()
212 self.assertEqual(s1, s2,
213 "readlines() after seek failed")
214 fobj.seek(0)
215 self.assertEqual(len(fobj.readline()), fobj.tell(),
216 "tell() after readline() failed")
217 fobj.seek(512)
218 self.assertEqual(len(fobj.readline()) + 512, fobj.tell(),
219 "tell() after seek() and readline() failed")
220 fobj.seek(0)
221 line = fobj.readline()
222 self.assertEqual(fobj.read(), data[len(line):],
223 "read() after readline() failed")
224
225 def test_fileobj_text(self):
226 with self.tar.extractfile("ustar/regtype") as fobj:
227 fobj = io.TextIOWrapper(fobj)
228 data = fobj.read().encode("iso8859-1")
229 self.assertEqual(sha256sum(data), sha256_regtype)
230 try:
231 fobj.seek(100)
232 except AttributeError:
233 # Issue #13815: seek() complained about a missing
234 # flush() method.
235 self.fail("seeking failed in text mode")
236
237 # Test if symbolic and hard links are resolved by extractfile(). The
238 # test link members each point to a regular member whose data is
239 # supposed to be exported.
240 def _test_fileobj_link(self, lnktype, regtype):
241 with self.tar.extractfile(lnktype) as a, \
242 self.tar.extractfile(regtype) as b:
243 self.assertEqual(a.name, b.name)
244
245 def test_fileobj_link1(self):
246 self._test_fileobj_link("ustar/lnktype", "ustar/regtype")
247
248 def test_fileobj_link2(self):
249 self._test_fileobj_link("./ustar/linktest2/lnktype",
250 "ustar/linktest1/regtype")
251
252 def test_fileobj_symlink1(self):
253 self._test_fileobj_link("ustar/symtype", "ustar/regtype")
254
255 def test_fileobj_symlink2(self):
256 self._test_fileobj_link("./ustar/linktest2/symtype",
257 "ustar/linktest1/regtype")
258
259 def test_issue14160(self):
260 self._test_fileobj_link("symtype2", "ustar/regtype")
261
262 def test_add_dir_getmember(self):
263 # bpo-21987
264 self.add_dir_and_getmember('bar')
265 self.add_dir_and_getmember('a'*101)
266
267 @unittest.skipUnless(hasattr(os, "getuid") and hasattr(os, "getgid"),
268 "Missing getuid or getgid implementation")
269 def add_dir_and_getmember(self, name):
270 def filter(tarinfo):
271 tarinfo.uid = tarinfo.gid = 100
272 return tarinfo
273
274 with os_helper.temp_cwd():
275 with tarfile.open(tmpname, 'w') as tar:
276 tar.format = tarfile.USTAR_FORMAT
277 try:
278 os.mkdir(name)
279 tar.add(name, filter=filter)
280 finally:
281 os.rmdir(name)
282 with tarfile.open(tmpname) as tar:
283 self.assertEqual(
284 tar.getmember(name),
285 tar.getmember(name + '/')
286 )
287
288 class GzipUstarReadTest(GzipTest, UstarReadTest):
289 pass
290
291 class Bz2UstarReadTest(Bz2Test, UstarReadTest):
292 pass
293
294 class LzmaUstarReadTest(LzmaTest, UstarReadTest):
295 pass
296
297 class ZstdUstarReadTest(ZstdTest, UstarReadTest):
298 pass
299
300 class ListTest(ReadTest, unittest.TestCase):
301
302 # Override setUp to use default encoding (UTF-8)
303 def setUp(self):
304 self.tar = tarfile.open(self.tarname, mode=self.mode)
305
306 def test_list(self):
307 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
308 with support.swap_attr(sys, 'stdout', tio):
309 self.tar.list(verbose=False)
310 out = tio.detach().getvalue()
311 self.assertIn(b'ustar/conttype', out)
312 self.assertIn(b'ustar/regtype', out)
313 self.assertIn(b'ustar/lnktype', out)
314 self.assertIn(b'ustar' + (b'/12345' * 40) + b'67/longname', out)
315 self.assertIn(b'./ustar/linktest2/symtype', out)
316 self.assertIn(b'./ustar/linktest2/lnktype', out)
317 # Make sure it puts trailing slash for directory
318 self.assertIn(b'ustar/dirtype/', out)
319 self.assertIn(b'ustar/dirtype-with-size/', out)
320 # Make sure it is able to print unencodable characters
321 def conv(b):
322 s = b.decode(self.tar.encoding, 'surrogateescape')
323 return s.encode('ascii', 'backslashreplace')
324 self.assertIn(conv(b'ustar/umlauts-\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
325 self.assertIn(conv(b'misc/regtype-hpux-signed-chksum-'
326 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
327 self.assertIn(conv(b'misc/regtype-old-v7-signed-chksum-'
328 b'\xc4\xd6\xdc\xe4\xf6\xfc\xdf'), out)
329 self.assertIn(conv(b'pax/bad-pax-\xe4\xf6\xfc'), out)
330 self.assertIn(conv(b'pax/hdrcharset-\xe4\xf6\xfc'), out)
331 # Make sure it prints files separated by one newline without any
332 # 'ls -l'-like accessories if verbose flag is not being used
333 # ...
334 # ustar/conttype
335 # ustar/regtype
336 # ...
337 self.assertRegex(out, br'ustar/conttype ?\r?\n'
338 br'ustar/regtype ?\r?\n')
339 # Make sure it does not print the source of link without verbose flag
340 self.assertNotIn(b'link to', out)
341 self.assertNotIn(b'->', out)
342
343 def test_list_verbose(self):
344 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
345 with support.swap_attr(sys, 'stdout', tio):
346 self.tar.list(verbose=True)
347 out = tio.detach().getvalue()
348 # Make sure it prints files separated by one newline with 'ls -l'-like
349 # accessories if verbose flag is being used
350 # ...
351 # ?rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/conttype
352 # -rw-r--r-- tarfile/tarfile 7011 2003-01-06 07:19:43 ustar/regtype
353 # drwxr-xr-x tarfile/tarfile 0 2003-01-05 15:19:43 ustar/dirtype/
354 # ...
355 #
356 # Array of values to modify the regex below:
357 # ((file_type, file_permissions, file_length), ...)
358 type_perm_lengths = (
359 (br'\?', b'rw-r--r--', b'7011'), (b'-', b'rw-r--r--', b'7011'),
360 (b'd', b'rwxr-xr-x', b'0'), (b'd', b'rwxr-xr-x', b'255'),
361 (br'\?', b'rw-r--r--', b'0'), (b'l', b'rwxrwxrwx', b'0'),
362 (b'b', b'rw-rw----', b'3,0'), (b'c', b'rw-rw-rw-', b'1,3'),
363 (b'p', b'rw-r--r--', b'0'))
364 self.assertRegex(out, b''.join(
365 [(tp + (br'%s tarfile/tarfile\s+%s ' % (perm, ln) +
366 br'\d{4}-\d\d-\d\d\s+\d\d:\d\d:\d\d '
367 br'ustar/\w+type[/>\sa-z-]*\n')) for tp, perm, ln
368 in type_perm_lengths]))
369 # Make sure it prints the source of link with verbose flag
370 self.assertIn(b'ustar/symtype -> regtype', out)
371 self.assertIn(b'./ustar/linktest2/symtype -> ../linktest1/regtype', out)
372 self.assertIn(b'./ustar/linktest2/lnktype link to '
373 b'./ustar/linktest1/regtype', out)
374 self.assertIn(b'gnu' + (b'/123' * 125) + b'/longlink link to gnu' +
375 (b'/123' * 125) + b'/longname', out)
376 self.assertIn(b'pax' + (b'/123' * 125) + b'/longlink link to pax' +
377 (b'/123' * 125) + b'/longname', out)
378
379 def test_list_members(self):
380 tio = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
381 def members(tar):
382 for tarinfo in tar.getmembers():
383 if 'reg' in tarinfo.name:
384 yield tarinfo
385 with support.swap_attr(sys, 'stdout', tio):
386 self.tar.list(verbose=False, members=members(self.tar))
387 out = tio.detach().getvalue()
388 self.assertIn(b'ustar/regtype', out)
389 self.assertNotIn(b'ustar/conttype', out)
390
391
392 class GzipListTest(GzipTest, ListTest):
393 pass
394
395
396 class Bz2ListTest(Bz2Test, ListTest):
397 pass
398
399
400 class LzmaListTest(LzmaTest, ListTest):
401 pass
402
403 class ZstdListTest(ZstdTest, ListTest):
404 pass
405
406 class CommonReadTest(ReadTest):
407
408 def test_is_tarfile_erroneous(self):
409 with open(tmpname, "wb"):
410 pass
411
412 # is_tarfile works on filenames
413 self.assertFalse(tarfile.is_tarfile(tmpname))
414
415 # is_tarfile works on path-like objects
416 self.assertFalse(tarfile.is_tarfile(os_helper.FakePath(tmpname)))
417
418 # is_tarfile works on file objects
419 with open(tmpname, "rb") as fobj:
420 self.assertFalse(tarfile.is_tarfile(fobj))
421
422 # is_tarfile works on file-like objects
423 self.assertFalse(tarfile.is_tarfile(io.BytesIO(b"invalid")))
424
425 def test_is_tarfile_valid(self):
426 # is_tarfile works on filenames
427 self.assertTrue(tarfile.is_tarfile(self.tarname))
428
429 # is_tarfile works on path-like objects
430 self.assertTrue(tarfile.is_tarfile(os_helper.FakePath(self.tarname)))
431
432 # is_tarfile works on file objects
433 with open(self.tarname, "rb") as fobj:
434 self.assertTrue(tarfile.is_tarfile(fobj))
435
436 # is_tarfile works on file-like objects
437 with open(self.tarname, "rb") as fobj:
438 self.assertTrue(tarfile.is_tarfile(io.BytesIO(fobj.read())))
439
440 def test_is_tarfile_keeps_position(self):
441 # Test for issue44289: tarfile.is_tarfile() modifies
442 # file object's current position
443 with open(self.tarname, "rb") as fobj:
444 tarfile.is_tarfile(fobj)
445 self.assertEqual(fobj.tell(), 0)
446
447 with open(self.tarname, "rb") as fobj:
448 file_like = io.BytesIO(fobj.read())
449 tarfile.is_tarfile(file_like)
450 self.assertEqual(file_like.tell(), 0)
451
452 def test_empty_tarfile(self):
453 # Test for issue6123: Allow opening empty archives.
454 # This test checks if tarfile.open() is able to open an empty tar
455 # archive successfully. Note that an empty tar archive is not the
456 # same as an empty file!
457 with tarfile.open(tmpname, self.mode.replace("r", "w")):
458 pass
459 try:
460 tar = tarfile.open(tmpname, self.mode)
461 tar.getnames()
462 except tarfile.ReadError:
463 self.fail("tarfile.open() failed on empty archive")
464 else:
465 self.assertListEqual(tar.getmembers(), [])
466 finally:
467 tar.close()
468
469 def test_non_existent_tarfile(self):
470 # Test for issue11513: prevent non-existent gzipped tarfiles raising
471 # multiple exceptions.
472 with self.assertRaisesRegex(FileNotFoundError, "xxx"):
473 tarfile.open("xxx", self.mode)
474
475 def test_null_tarfile(self):
476 # Test for issue6123: Allow opening empty archives.
477 # This test guarantees that tarfile.open() does not treat an empty
478 # file as an empty tar archive.
479 with open(tmpname, "wb"):
480 pass
481 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, self.mode)
482 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname)
483
484 def test_ignore_zeros(self):
485 # Test TarFile's ignore_zeros option.
486 # generate 512 pseudorandom bytes
487 data = Random(0).randbytes(512)
488 for char in (b'\0', b'a'):
489 # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
490 # are ignored correctly.
491 with self.open(tmpname, "w") as fobj:
492 fobj.write(char * 1024)
493 tarinfo = tarfile.TarInfo("foo")
494 tarinfo.size = len(data)
495 fobj.write(tarinfo.tobuf())
496 fobj.write(data)
497
498 tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
499 try:
500 self.assertListEqual(tar.getnames(), ["foo"],
501 "ignore_zeros=True should have skipped the %r-blocks" %
502 char)
503 finally:
504 tar.close()
505
506 def test_premature_end_of_archive(self):
507 for size in (512, 600, 1024, 1200):
508 with tarfile.open(tmpname, "w:") as tar:
509 t = tarfile.TarInfo("foo")
510 t.size = 1024
511 tar.addfile(t, io.BytesIO(b"a" * 1024))
512
513 with open(tmpname, "r+b") as fobj:
514 fobj.truncate(size)
515
516 with tarfile.open(tmpname) as tar:
517 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
518 for t in tar:
519 pass
520
521 with tarfile.open(tmpname) as tar:
522 t = tar.next()
523
524 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
525 tar.extract(t, TEMPDIR, filter='data')
526
527 with self.assertRaisesRegex(tarfile.ReadError, "unexpected end of data"):
528 tar.extractfile(t).read()
529
530 def test_length_zero_header(self):
531 # bpo-39017 (CVE-2019-20907): reading a zero-length header should fail
532 # with an exception
533 with self.assertRaisesRegex(tarfile.ReadError, "file could not be opened successfully"):
534 with tarfile.open(support.findfile('recursion.tar', subdir='archivetestdata')):
535 pass
536
537 def test_extractfile_attrs(self):
538 # gh-74468: TarFile.name must name a file, not a parent archive.
539 file = self.tar.getmember('ustar/regtype')
540 with self.tar.extractfile(file) as fobj:
541 self.assertEqual(fobj.name, 'ustar/regtype')
542 self.assertRaises(AttributeError, fobj.fileno)
543 self.assertEqual(fobj.mode, 'rb')
544 self.assertIs(fobj.readable(), True)
545 self.assertIs(fobj.writable(), False)
546 if self.is_stream:
547 self.assertRaises(AttributeError, fobj.seekable)
548 else:
549 self.assertIs(fobj.seekable(), True)
550 self.assertIs(fobj.closed, False)
551 self.assertIs(fobj.closed, True)
552 self.assertEqual(fobj.name, 'ustar/regtype')
553 self.assertRaises(AttributeError, fobj.fileno)
554 self.assertEqual(fobj.mode, 'rb')
555 self.assertIs(fobj.readable(), True)
556 self.assertIs(fobj.writable(), False)
557 if self.is_stream:
558 self.assertRaises(AttributeError, fobj.seekable)
559 else:
560 self.assertIs(fobj.seekable(), True)
561
562
563 class MiscReadTestBase(CommonReadTest):
564 is_stream = False
565
566 def test_no_name_argument(self):
567 with open(self.tarname, "rb") as fobj:
568 self.assertIsInstance(fobj.name, str)
569 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
570 if sys.version_info >= (3, 13):
571 self.assertIsInstance(tar.name, str)
572 self.assertEqual(tar.name, os.path.abspath(fobj.name))
573
574 def test_no_name_attribute(self):
575 with open(self.tarname, "rb") as fobj:
576 data = fobj.read()
577 fobj = io.BytesIO(data)
578 self.assertRaises(AttributeError, getattr, fobj, "name")
579 tar = tarfile.open(fileobj=fobj, mode=self.mode)
580 self.assertIsNone(tar.name)
581
582 def test_empty_name_attribute(self):
583 with open(self.tarname, "rb") as fobj:
584 data = fobj.read()
585 fobj = io.BytesIO(data)
586 fobj.name = ""
587 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
588 self.assertIsNone(tar.name)
589
590 def test_int_name_attribute(self):
591 # Issue 21044: tarfile.open() should handle fileobj with an integer
592 # 'name' attribute.
593 fd = os.open(self.tarname, os.O_RDONLY)
594 with open(fd, 'rb') as fobj:
595 self.assertIsInstance(fobj.name, int)
596 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
597 self.assertIsNone(tar.name)
598
599 def test_bytes_name_attribute(self):
600 tarname = os.fsencode(self.tarname)
601 with open(tarname, 'rb') as fobj:
602 self.assertIsInstance(fobj.name, bytes)
603 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
604 if sys.version_info >= (3, 13):
605 self.assertIsInstance(tar.name, bytes)
606 self.assertEqual(tar.name, os.path.abspath(fobj.name))
607
608 def test_pathlike_name(self, tarname=None):
609 if tarname is None:
610 tarname = self.tarname
611 expected = os.path.abspath(tarname)
612 tarname = os_helper.FakePath(tarname)
613 with tarfile.open(tarname, mode=self.mode) as tar:
614 self.assertEqual(tar.name, expected)
615 with self.taropen(tarname) as tar:
616 self.assertEqual(tar.name, expected)
617 with tarfile.TarFile.open(tarname, mode=self.mode) as tar:
618 self.assertEqual(tar.name, expected)
619 if self.suffix == '':
620 with tarfile.TarFile(tarname, mode='r') as tar:
621 self.assertEqual(tar.name, expected)
622
623 def test_pathlike_bytes_name(self):
624 self.test_pathlike_name(os.fsencode(self.tarname))
625
626 def test_illegal_mode_arg(self):
627 with open(tmpname, 'wb'):
628 pass
629 with self.assertRaisesRegex(ValueError, 'mode must be '):
630 tar = self.taropen(tmpname, 'q')
631 with self.assertRaisesRegex(ValueError, 'mode must be '):
632 tar = self.taropen(tmpname, 'rw')
633 with self.assertRaisesRegex(ValueError, 'mode must be '):
634 tar = self.taropen(tmpname, '')
635
636 def test_fileobj_with_offset(self):
637 # Skip the first member and store values from the second member
638 # of the testtar.
639 tar = tarfile.open(self.tarname, mode=self.mode)
640 try:
641 tar.next()
642 t = tar.next()
643 name = t.name
644 offset = t.offset
645 with tar.extractfile(t) as f:
646 data = f.read()
647 finally:
648 tar.close()
649
650 # Open the testtar and seek to the offset of the second member.
651 with self.open(self.tarname) as fobj:
652 fobj.seek(offset)
653
654 # Test if the tarfile starts with the second member.
655 with tar.open(self.tarname, mode="r:", fileobj=fobj) as tar:
656 t = tar.next()
657 self.assertEqual(t.name, name)
658 # Read to the end of fileobj and test if seeking back to the
659 # beginning works.
660 tar.getmembers()
661 self.assertEqual(tar.extractfile(t).read(), data,
662 "seek back did not work")
663
664 def test_fail_comp(self):
665 # For Gzip and Bz2 Tests: fail with a ReadError on an uncompressed file.
666 self.assertRaises(tarfile.ReadError, tarfile.open, tarname, self.mode)
667 with open(tarname, "rb") as fobj:
668 self.assertRaises(tarfile.ReadError, tarfile.open,
669 fileobj=fobj, mode=self.mode)
670
671 def test_v7_dirtype(self):
672 # Test old style dirtype member (bug #1336623):
673 # Old V7 tars create directory members using an AREGTYPE
674 # header with a "/" appended to the filename field.
675 tarinfo = self.tar.getmember("misc/dirtype-old-v7")
676 self.assertEqual(tarinfo.type, tarfile.DIRTYPE,
677 "v7 dirtype failed")
678
679 def test_xstar_type(self):
680 # The xstar format stores extra atime and ctime fields inside the
681 # space reserved for the prefix field. The prefix field must be
682 # ignored in this case, otherwise it will mess up the name.
683 try:
684 self.tar.getmember("misc/regtype-xstar")
685 except KeyError:
686 self.fail("failed to find misc/regtype-xstar (mangled prefix?)")
687
688 def test_check_members(self):
689 for tarinfo in self.tar:
690 self.assertEqual(int(tarinfo.mtime), 0o7606136617,
691 "wrong mtime for %s" % tarinfo.name)
692 if not tarinfo.name.startswith("ustar/"):
693 continue
694 self.assertEqual(tarinfo.uname, "tarfile",
695 "wrong uname for %s" % tarinfo.name)
696
697 def test_find_members(self):
698 self.assertEqual(self.tar.getmembers()[-1].name, "misc/eof",
699 "could not find all members")
700
701 @unittest.skipUnless(hasattr(os, "link"),
702 "Missing hardlink implementation")
703 @os_helper.skip_unless_symlink
704 def test_extract_hardlink(self):
705 # Test hardlink extraction (e.g. bug #857297).
706 with tarfile.open(tarname, errorlevel=1, encoding="iso8859-1") as tar:
707 tar.extract("ustar/regtype", TEMPDIR, filter='data')
708 self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/regtype"))
709
710 tar.extract("ustar/lnktype", TEMPDIR, filter='data')
711 self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/lnktype"))
712 with open(os.path.join(TEMPDIR, "ustar/lnktype"), "rb") as f:
713 data = f.read()
714 self.assertEqual(sha256sum(data), sha256_regtype)
715
716 tar.extract("ustar/symtype", TEMPDIR, filter='data')
717 self.addCleanup(os_helper.unlink, os.path.join(TEMPDIR, "ustar/symtype"))
718 with open(os.path.join(TEMPDIR, "ustar/symtype"), "rb") as f:
719 data = f.read()
720 self.assertEqual(sha256sum(data), sha256_regtype)
721
722 @os_helper.skip_unless_working_chmod
723 def test_extractall(self):
724 # Test if extractall() correctly restores directory permissions
725 # and times (see issue1735).
726 tar = tarfile.open(tarname, encoding="iso8859-1")
727 DIR = os.path.join(TEMPDIR, "extractall")
728 os.mkdir(DIR)
729 try:
730 directories = [t for t in tar if t.isdir()]
731 tar.extractall(DIR, directories, filter='fully_trusted')
732 for tarinfo in directories:
733 path = os.path.join(DIR, tarinfo.name)
734 if sys.platform != "win32":
735 # Win32 has no support for fine grained permissions.
736 self.assertEqual(tarinfo.mode & 0o777,
737 os.stat(path).st_mode & 0o777,
738 tarinfo.name)
739 def format_mtime(mtime):
740 if isinstance(mtime, float):
741 return "{} ({})".format(mtime, mtime.hex())
742 else:
743 return "{!r} (int)".format(mtime)
744 file_mtime = os.path.getmtime(path)
745 errmsg = "tar mtime {0} != file time {1} of path {2!a}".format(
746 format_mtime(tarinfo.mtime),
747 format_mtime(file_mtime),
748 path)
749 self.assertEqual(tarinfo.mtime, file_mtime, errmsg)
750 finally:
751 tar.close()
752 os_helper.rmtree(DIR)
753
754 @staticmethod
755 def test_extractall_default_filter():
756 # Test that the default filter is now "data", and the other filter types are not used.
757 DIR = pathlib.Path(TEMPDIR) / "extractall_default_filter"
758 with (
759 os_helper.temp_dir(DIR),
760 tarfile.open(tarname, encoding="iso8859-1") as tar,
761 unittest.mock.patch("backports.zstd.tarfile.data_filter", wraps=tarfile.data_filter) as mock_data_filter,
762 unittest.mock.patch("backports.zstd.tarfile.tar_filter", wraps=tarfile.tar_filter) as mock_tar_filter,
763 unittest.mock.patch("backports.zstd.tarfile.fully_trusted_filter", wraps=tarfile.fully_trusted_filter) as mock_ft_filter
764 ):
765 directories = [t for t in tar if t.isdir()]
766 tar.extractall(DIR, directories)
767
768 mock_data_filter.assert_called()
769 mock_ft_filter.assert_not_called()
770 mock_tar_filter.assert_not_called()
771
772 @os_helper.skip_unless_working_chmod
773 def test_extract_directory(self):
774 dirtype = "ustar/dirtype"
775 DIR = os.path.join(TEMPDIR, "extractdir")
776 os.mkdir(DIR)
777 try:
778 with tarfile.open(tarname, encoding="iso8859-1") as tar:
779 tarinfo = tar.getmember(dirtype)
780 tar.extract(tarinfo, path=DIR, filter='fully_trusted')
781 extracted = os.path.join(DIR, dirtype)
782 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
783 if sys.platform != "win32":
784 self.assertEqual(os.stat(extracted).st_mode & 0o777, 0o755)
785 finally:
786 os_helper.rmtree(DIR)
787
788 def test_extractall_pathlike_dir(self):
789 DIR = os.path.join(TEMPDIR, "extractall")
790 with os_helper.temp_dir(DIR), \
791 tarfile.open(tarname, encoding="iso8859-1") as tar:
792 directories = [t for t in tar if t.isdir()]
793 tar.extractall(os_helper.FakePath(DIR), directories, filter='fully_trusted')
794 for tarinfo in directories:
795 path = os.path.join(DIR, tarinfo.name)
796 self.assertEqual(os.path.getmtime(path), tarinfo.mtime)
797
798 def test_extract_pathlike_dir(self):
799 dirtype = "ustar/dirtype"
800 DIR = os.path.join(TEMPDIR, "extractall")
801 with os_helper.temp_dir(DIR), \
802 tarfile.open(tarname, encoding="iso8859-1") as tar:
803 tarinfo = tar.getmember(dirtype)
804 tar.extract(tarinfo, path=os_helper.FakePath(DIR), filter='fully_trusted')
805 extracted = os.path.join(DIR, dirtype)
806 self.assertEqual(os.path.getmtime(extracted), tarinfo.mtime)
807
808 def test_init_close_fobj(self):
809 # Issue #7341: Close the internal file object in the TarFile
810 # constructor in case of an error. For the test we rely on
811 # the fact that opening an empty file raises a ReadError.
812 empty = os.path.join(TEMPDIR, "empty")
813 with open(empty, "wb") as fobj:
814 fobj.write(b"")
815
816 try:
817 tar = object.__new__(tarfile.TarFile)
818 try:
819 tar.__init__(empty)
820 except tarfile.ReadError:
821 self.assertTrue(tar.fileobj.closed)
822 else:
823 self.fail("ReadError not raised")
824 finally:
825 os_helper.unlink(empty)
826
827 def test_parallel_iteration(self):
828 # Issue #16601: Restarting iteration over tarfile continued
829 # from where it left off.
830 with tarfile.open(self.tarname) as tar:
831 for m1, m2 in zip(tar, tar):
832 self.assertEqual(m1.offset, m2.offset)
833 self.assertEqual(m1.get_info(), m2.get_info())
834
835 @unittest.skipIf(zlib is None, "requires zlib")
836 def test_zlib_error_does_not_leak(self):
837 # bpo-39039: tarfile.open allowed zlib exceptions to bubble up when
838 # parsing certain types of invalid data
839 with unittest.mock.patch("backports.zstd.tarfile.TarInfo.fromtarfile") as mock:
840 mock.side_effect = zlib.error
841 with self.assertRaises(tarfile.ReadError):
842 tarfile.open(self.tarname)
843
844 def test_next_on_empty_tarfile(self):
845 fd = io.BytesIO()
846 tf = tarfile.open(fileobj=fd, mode="w")
847 tf.close()
848
849 fd.seek(0)
850 with tarfile.open(fileobj=fd, mode="r|") as tf:
851 self.assertEqual(tf.next(), None)
852
853 fd.seek(0)
854 with tarfile.open(fileobj=fd, mode="r") as tf:
855 self.assertEqual(tf.next(), None)
856
857 def _setup_symlink_to_target(self, temp_dirpath):
858 target_filepath = os.path.join(temp_dirpath, "target")
859 ustar_dirpath = os.path.join(temp_dirpath, "ustar")
860 hardlink_filepath = os.path.join(ustar_dirpath, "lnktype")
861 with open(target_filepath, "wb") as f:
862 f.write(b"target")
863 os.makedirs(ustar_dirpath)
864 os.symlink(target_filepath, hardlink_filepath)
865 return target_filepath, hardlink_filepath
866
867 def _assert_on_file_content(self, filepath, digest):
868 with open(filepath, "rb") as f:
869 data = f.read()
870 self.assertEqual(sha256sum(data), digest)
871
872 @unittest.skipUnless(
873 hasattr(os, "link"), "Missing hardlink implementation"
874 )
875 @os_helper.skip_unless_symlink
876 def test_extract_hardlink_on_symlink(self):
877 """
878 This test verifies that extracting a hardlink will not follow an
879 existing symlink after a FileExistsError on os.link.
880 """
881 with os_helper.temp_dir() as DIR:
882 target_filepath, hardlink_filepath = self._setup_symlink_to_target(DIR)
883 with tarfile.open(tarname, encoding="iso8859-1") as tar:
884 tar.extract("ustar/regtype", DIR, filter="data")
885 tar.extract("ustar/lnktype", DIR, filter="data")
886 self._assert_on_file_content(target_filepath, sha256sum(b"target"))
887 self._assert_on_file_content(hardlink_filepath, sha256_regtype)
888
889 @unittest.skipUnless(
890 hasattr(os, "link"), "Missing hardlink implementation"
891 )
892 @os_helper.skip_unless_symlink
893 def test_extractall_hardlink_on_symlink(self):
894 """
895 This test verifies that extracting a hardlink will not follow an
896 existing symlink after a FileExistsError on os.link.
897 """
898 with os_helper.temp_dir() as DIR:
899 target_filepath, hardlink_filepath = self._setup_symlink_to_target(DIR)
900 with tarfile.open(tarname, encoding="iso8859-1") as tar:
901 tar.extractall(
902 DIR, members=["ustar/regtype", "ustar/lnktype"], filter="data",
903 )
904 self._assert_on_file_content(target_filepath, sha256sum(b"target"))
905 self._assert_on_file_content(hardlink_filepath, sha256_regtype)
906
907
908 class GzipReadTestBase:
909
910 def test_read_with_extra_field(self):
911 with open(self.tarname, 'rb') as f:
912 data = bytearray(f.read())
913 flags = data[3]
914 self.assertEqual(flags, 8)
915 data[3] = flags | 4
916 data[10:10] = b'\x05\x00extra'
917 with open(tmpname, 'wb') as f:
918 f.write(data)
919 print(self.mode)
920 with tarfile.open(tmpname, mode=self.mode):
921 pass
922
923 def test_read_with_file_comment(self):
924 with open(self.tarname, 'rb') as f:
925 data = bytearray(f.read())
926 flags = data[3]
927 self.assertEqual(flags, 8)
928 data[3] = flags | 16
929 i = data.index(0, 10) + 1
930 data[i:i] = b'comment\x00'
931 with open(tmpname, 'wb') as f:
932 f.write(data)
933 with tarfile.open(tmpname, mode=self.mode):
934 pass
935
936
937 class MiscReadTest(MiscReadTestBase, unittest.TestCase):
938 test_fail_comp = None
939
940 class GzipMiscReadTest(GzipTest, GzipReadTestBase, MiscReadTestBase, unittest.TestCase):
941 pass
942
943 class Bz2MiscReadTest(Bz2Test, MiscReadTestBase, unittest.TestCase):
944 pass
945
946 class LzmaMiscReadTest(LzmaTest, MiscReadTestBase, unittest.TestCase):
947 pass
948
949 class ZstdMiscReadTest(ZstdTest, MiscReadTestBase, unittest.TestCase):
950 pass
951
952 class StreamReadTest(CommonReadTest, unittest.TestCase):
953
954 prefix="r|"
955 is_stream = True
956
957 def test_read_through(self):
958 # Issue #11224: A poorly designed _FileInFile.read() method
959 # caused seeking errors with stream tar files.
960 for tarinfo in self.tar:
961 if not tarinfo.isreg():
962 continue
963 with self.tar.extractfile(tarinfo) as fobj:
964 while True:
965 try:
966 buf = fobj.read(512)
967 except tarfile.StreamError:
968 self.fail("simple read-through using "
969 "TarFile.extractfile() failed")
970 if not buf:
971 break
972
973 def test_fileobj_regular_file(self):
974 tarinfo = self.tar.next() # get "regtype" (can't use getmember)
975 with self.tar.extractfile(tarinfo) as fobj:
976 data = fobj.read()
977 self.assertEqual(len(data), tarinfo.size,
978 "regular file extraction failed")
979 self.assertEqual(sha256sum(data), sha256_regtype,
980 "regular file extraction failed")
981
982 def test_provoke_stream_error(self):
983 tarinfos = self.tar.getmembers()
984 with self.tar.extractfile(tarinfos[0]) as f: # read the first member
985 self.assertRaises(tarfile.StreamError, f.read)
986
987 def test_compare_members(self):
988 tar1 = tarfile.open(tarname, encoding="iso8859-1")
989 try:
990 tar2 = self.tar
991
992 while True:
993 t1 = tar1.next()
994 t2 = tar2.next()
995 if t1 is None:
996 break
997 self.assertIsNotNone(t2, "stream.next() failed.")
998
999 if t2.islnk() or t2.issym():
1000 with self.assertRaises(tarfile.StreamError):
1001 tar2.extractfile(t2)
1002 continue
1003
1004 v1 = tar1.extractfile(t1)
1005 v2 = tar2.extractfile(t2)
1006 if v1 is None:
1007 continue
1008 self.assertIsNotNone(v2, "stream.extractfile() failed")
1009 self.assertEqual(v1.read(), v2.read(),
1010 "stream extraction failed")
1011 finally:
1012 tar1.close()
1013
1014 class GzipStreamReadTest(GzipTest, GzipReadTestBase, StreamReadTest):
1015 pass
1016
1017 class Bz2StreamReadTest(Bz2Test, StreamReadTest):
1018 pass
1019
1020 class LzmaStreamReadTest(LzmaTest, StreamReadTest):
1021 pass
1022
1023 class ZstdStreamReadTest(ZstdTest, StreamReadTest):
1024 pass
1025
1026 class TarStreamModeReadTest(StreamModeTest, unittest.TestCase):
1027
1028 def test_stream_mode_no_cache(self):
1029 for _ in self.tar:
1030 pass
1031 self.assertEqual(self.tar.members, [])
1032
1033 class GzipStreamModeReadTest(GzipTest, TarStreamModeReadTest):
1034 pass
1035
1036 class Bz2StreamModeReadTest(Bz2Test, TarStreamModeReadTest):
1037 pass
1038
1039 class LzmaStreamModeReadTest(LzmaTest, TarStreamModeReadTest):
1040 pass
1041
1042 class ZstdStreamModeReadTest(ZstdTest, TarStreamModeReadTest):
1043 pass
1044
1045 class DetectReadTest(TarTest, unittest.TestCase):
1046 def _testfunc_file(self, name, mode):
1047 try:
1048 tar = tarfile.open(name, mode)
1049 except tarfile.ReadError as e:
1050 self.fail()
1051 else:
1052 tar.close()
1053
1054 def _testfunc_fileobj(self, name, mode):
1055 try:
1056 with open(name, "rb") as f:
1057 tar = tarfile.open(name, mode, fileobj=f)
1058 except tarfile.ReadError as e:
1059 self.fail()
1060 else:
1061 tar.close()
1062
1063 def _test_modes(self, testfunc):
1064 if self.suffix:
1065 with self.assertRaises(tarfile.ReadError):
1066 tarfile.open(tarname, mode="r:" + self.suffix)
1067 with self.assertRaises(tarfile.ReadError):
1068 tarfile.open(tarname, mode="r|" + self.suffix)
1069 with self.assertRaises(tarfile.ReadError):
1070 tarfile.open(self.tarname, mode="r:")
1071 with self.assertRaises(tarfile.ReadError):
1072 tarfile.open(self.tarname, mode="r|")
1073 testfunc(self.tarname, "r")
1074 testfunc(self.tarname, "r:" + self.suffix)
1075 testfunc(self.tarname, "r:*")
1076 testfunc(self.tarname, "r|" + self.suffix)
1077 testfunc(self.tarname, "r|*")
1078
1079 def test_detect_file(self):
1080 self._test_modes(self._testfunc_file)
1081
1082 def test_detect_fileobj(self):
1083 self._test_modes(self._testfunc_fileobj)
1084
1085 class GzipDetectReadTest(GzipTest, DetectReadTest):
1086 pass
1087
1088 class Bz2DetectReadTest(Bz2Test, DetectReadTest):
1089 def test_detect_stream_bz2(self):
1090 # Originally, tarfile's stream detection looked for the string
1091 # "BZh91" at the start of the file. This is incorrect because
1092 # the '9' represents the blocksize (900,000 bytes). If the file was
1093 # compressed using another blocksize autodetection fails.
1094 with open(tarname, "rb") as fobj:
1095 data = fobj.read()
1096
1097 # Compress with blocksize 100,000 bytes, the file starts with "BZh11".
1098 with bz2.BZ2File(tmpname, "wb", compresslevel=1) as fobj:
1099 fobj.write(data)
1100
1101 self._testfunc_file(tmpname, "r|*")
1102
1103 class LzmaDetectReadTest(LzmaTest, DetectReadTest):
1104 pass
1105
1106 class ZstdDetectReadTest(ZstdTest, DetectReadTest):
1107 pass
1108
1109 class GzipBrokenHeaderCorrectException(GzipTest, unittest.TestCase):
1110 """
1111 See: https://github.com/python/cpython/issues/107396
1112 """
1113 def runTest(self):
1114 f = io.BytesIO(
1115 b'\x1f\x8b' # header
1116 b'\x08' # compression method
1117 b'\x04' # flags
1118 b'\0\0\0\0\0\0' # timestamp, compression data, OS ID
1119 b'\0\x01' # size
1120 b'\0\0\0\0\0' # corrupt data (zeros)
1121 )
1122 with self.assertRaises(tarfile.ReadError):
1123 tarfile.open(fileobj=f, mode='r|gz')
1124
1125
1126 class MemberReadTest(ReadTest, unittest.TestCase):
1127
1128 def _test_member(self, tarinfo, chksum=None, **kwargs):
1129 if chksum is not None:
1130 with self.tar.extractfile(tarinfo) as f:
1131 self.assertEqual(sha256sum(f.read()), chksum,
1132 "wrong sha256sum for %s" % tarinfo.name)
1133
1134 kwargs["mtime"] = 0o7606136617
1135 kwargs["uid"] = 1000
1136 kwargs["gid"] = 100
1137 if "old-v7" not in tarinfo.name:
1138 # V7 tar can't handle alphabetic owners.
1139 kwargs["uname"] = "tarfile"
1140 kwargs["gname"] = "tarfile"
1141 for k, v in kwargs.items():
1142 self.assertEqual(getattr(tarinfo, k), v,
1143 "wrong value in %s field of %s" % (k, tarinfo.name))
1144
1145 def test_find_regtype(self):
1146 tarinfo = self.tar.getmember("ustar/regtype")
1147 self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
1148
1149 def test_find_conttype(self):
1150 tarinfo = self.tar.getmember("ustar/conttype")
1151 self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
1152
1153 def test_find_dirtype(self):
1154 tarinfo = self.tar.getmember("ustar/dirtype")
1155 self._test_member(tarinfo, size=0)
1156
1157 def test_find_dirtype_with_size(self):
1158 tarinfo = self.tar.getmember("ustar/dirtype-with-size")
1159 self._test_member(tarinfo, size=255)
1160
1161 def test_find_lnktype(self):
1162 tarinfo = self.tar.getmember("ustar/lnktype")
1163 self._test_member(tarinfo, size=0, linkname="ustar/regtype")
1164
1165 def test_find_symtype(self):
1166 tarinfo = self.tar.getmember("ustar/symtype")
1167 self._test_member(tarinfo, size=0, linkname="regtype")
1168
1169 def test_find_blktype(self):
1170 tarinfo = self.tar.getmember("ustar/blktype")
1171 self._test_member(tarinfo, size=0, devmajor=3, devminor=0)
1172
1173 def test_find_chrtype(self):
1174 tarinfo = self.tar.getmember("ustar/chrtype")
1175 self._test_member(tarinfo, size=0, devmajor=1, devminor=3)
1176
1177 def test_find_fifotype(self):
1178 tarinfo = self.tar.getmember("ustar/fifotype")
1179 self._test_member(tarinfo, size=0)
1180
1181 def test_find_sparse(self):
1182 tarinfo = self.tar.getmember("ustar/sparse")
1183 self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
1184
1185 def test_find_gnusparse(self):
1186 tarinfo = self.tar.getmember("gnu/sparse")
1187 self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
1188
1189 def test_find_gnusparse_00(self):
1190 tarinfo = self.tar.getmember("gnu/sparse-0.0")
1191 self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
1192
1193 def test_find_gnusparse_01(self):
1194 tarinfo = self.tar.getmember("gnu/sparse-0.1")
1195 self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
1196
1197 def test_find_gnusparse_10(self):
1198 tarinfo = self.tar.getmember("gnu/sparse-1.0")
1199 self._test_member(tarinfo, size=86016, chksum=sha256_sparse)
1200
1201 def test_find_umlauts(self):
1202 tarinfo = self.tar.getmember("ustar/umlauts-"
1203 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
1204 self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
1205
1206 def test_find_ustar_longname(self):
1207 name = "ustar/" + "12345/" * 39 + "1234567/longname"
1208 self.assertIn(name, self.tar.getnames())
1209
1210 def test_find_regtype_oldv7(self):
1211 tarinfo = self.tar.getmember("misc/regtype-old-v7")
1212 self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
1213
1214 def test_find_pax_umlauts(self):
1215 self.tar.close()
1216 self.tar = tarfile.open(self.tarname, mode=self.mode,
1217 encoding="iso8859-1")
1218 tarinfo = self.tar.getmember("pax/umlauts-"
1219 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
1220 self._test_member(tarinfo, size=7011, chksum=sha256_regtype)
1221
1222
1223 class LongnameTest:
1224
1225 def test_read_longname(self):
1226 # Test reading of longname (bug #1471427).
1227 longname = self.subdir + "/" + "123/" * 125 + "longname"
1228 try:
1229 tarinfo = self.tar.getmember(longname)
1230 except KeyError:
1231 self.fail("longname not found")
1232 self.assertNotEqual(tarinfo.type, tarfile.DIRTYPE,
1233 "read longname as dirtype")
1234
1235 def test_read_longlink(self):
1236 longname = self.subdir + "/" + "123/" * 125 + "longname"
1237 longlink = self.subdir + "/" + "123/" * 125 + "longlink"
1238 try:
1239 tarinfo = self.tar.getmember(longlink)
1240 except KeyError:
1241 self.fail("longlink not found")
1242 self.assertEqual(tarinfo.linkname, longname, "linkname wrong")
1243
1244 def test_truncated_longname(self):
1245 longname = self.subdir + "/" + "123/" * 125 + "longname"
1246 tarinfo = self.tar.getmember(longname)
1247 offset = tarinfo.offset
1248 self.tar.fileobj.seek(offset)
1249 fobj = io.BytesIO(self.tar.fileobj.read(3 * 512))
1250 with self.assertRaises(tarfile.ReadError):
1251 tarfile.open(name="foo.tar", fileobj=fobj)
1252
1253 def test_header_offset(self):
1254 # Test if the start offset of the TarInfo object includes
1255 # the preceding extended header.
1256 longname = self.subdir + "/" + "123/" * 125 + "longname"
1257 offset = self.tar.getmember(longname).offset
1258 with open(tarname, "rb") as fobj:
1259 fobj.seek(offset)
1260 tarinfo = tarfile.TarInfo.frombuf(fobj.read(512),
1261 "iso8859-1", "strict")
1262 self.assertEqual(tarinfo.type, self.longnametype)
1263
1264 def test_longname_directory(self):
1265 # Test reading a longlink directory. Issue #47231.
1266 longdir = ('a' * 101) + '/'
1267 with os_helper.temp_cwd():
1268 with tarfile.open(tmpname, 'w') as tar:
1269 tar.format = self.format
1270 try:
1271 os.mkdir(longdir)
1272 tar.add(longdir)
1273 finally:
1274 os.rmdir(longdir.rstrip("/"))
1275 with tarfile.open(tmpname) as tar:
1276 self.assertIsNotNone(tar.getmember(longdir))
1277 self.assertIsNotNone(tar.getmember(longdir.removesuffix('/')))
1278
1279 def test_longname_file_not_directory(self):
1280 # Test reading a longname file and ensure it is not handled as a directory
1281 # Issue #141707
1282 buf = io.BytesIO()
1283 with tarfile.open(mode='w', fileobj=buf, format=self.format) as tar:
1284 ti = tarfile.TarInfo()
1285 ti.type = tarfile.AREGTYPE
1286 ti.name = ('a' * 99) + '/' + ('b' * 3)
1287 tar.addfile(ti)
1288
1289 expected = {t.name: t.type for t in tar.getmembers()}
1290
1291 buf.seek(0)
1292 with tarfile.open(mode='r', fileobj=buf) as tar:
1293 actual = {t.name: t.type for t in tar.getmembers()}
1294
1295 self.assertEqual(expected, actual)
1296
1297
1298 class GNUReadTest(LongnameTest, ReadTest, unittest.TestCase):
1299
1300 subdir = "gnu"
1301 longnametype = tarfile.GNUTYPE_LONGNAME
1302 format = tarfile.GNU_FORMAT
1303
1304 # Since 3.2 tarfile is supposed to accurately restore sparse members and
1305 # produce files with holes. This is what we actually want to test here.
1306 # Unfortunately, not all platforms/filesystems support sparse files, and
1307 # even on platforms that do it is non-trivial to make reliable assertions
1308 # about holes in files. Therefore, we first do one basic test which works
1309 # an all platforms, and after that a test that will work only on
1310 # platforms/filesystems that prove to support sparse files.
1311 def _test_sparse_file(self, name):
1312 self.tar.extract(name, TEMPDIR, filter='data')
1313 filename = os.path.join(TEMPDIR, name)
1314 with open(filename, "rb") as fobj:
1315 data = fobj.read()
1316 self.assertEqual(sha256sum(data), sha256_sparse,
1317 "wrong sha256sum for %s" % name)
1318
1319 if self._fs_supports_holes():
1320 s = os.stat(filename)
1321 self.assertLess(s.st_blocks * 512, s.st_size)
1322
1323 def test_sparse_file_old(self):
1324 self._test_sparse_file("gnu/sparse")
1325
1326 def test_sparse_file_00(self):
1327 self._test_sparse_file("gnu/sparse-0.0")
1328
1329 def test_sparse_file_01(self):
1330 self._test_sparse_file("gnu/sparse-0.1")
1331
1332 def test_sparse_file_10(self):
1333 self._test_sparse_file("gnu/sparse-1.0")
1334
1335 @staticmethod
1336 def _fs_supports_holes():
1337 # Return True if the platform knows the st_blocks stat attribute and
1338 # uses st_blocks units of 512 bytes, and if the filesystem is able to
1339 # store holes of 4 KiB in files.
1340 #
1341 # The function returns False if page size is larger than 4 KiB.
1342 # For example, ppc64 uses pages of 64 KiB.
1343 if sys.platform.startswith(("linux", "android")):
1344 # Linux evidentially has 512 byte st_blocks units.
1345 name = os.path.join(TEMPDIR, "sparse-test")
1346 with open(name, "wb") as fobj:
1347 # Seek to "punch a hole" of 4 KiB
1348 fobj.seek(4096)
1349 fobj.write(b'x' * 4096)
1350 fobj.truncate()
1351 s = os.stat(name)
1352 os_helper.unlink(name)
1353 return (s.st_blocks * 512 < s.st_size)
1354 else:
1355 return False
1356
1357
1358 class PaxReadTest(LongnameTest, ReadTest, unittest.TestCase):
1359
1360 subdir = "pax"
1361 longnametype = tarfile.XHDTYPE
1362 format = tarfile.PAX_FORMAT
1363
1364 def test_pax_global_headers(self):
1365 tar = tarfile.open(tarname, encoding="iso8859-1")
1366 try:
1367 tarinfo = tar.getmember("pax/regtype1")
1368 self.assertEqual(tarinfo.uname, "foo")
1369 self.assertEqual(tarinfo.gname, "bar")
1370 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
1371 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
1372
1373 tarinfo = tar.getmember("pax/regtype2")
1374 self.assertEqual(tarinfo.uname, "")
1375 self.assertEqual(tarinfo.gname, "bar")
1376 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
1377 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
1378
1379 tarinfo = tar.getmember("pax/regtype3")
1380 self.assertEqual(tarinfo.uname, "tarfile")
1381 self.assertEqual(tarinfo.gname, "tarfile")
1382 self.assertEqual(tarinfo.pax_headers.get("VENDOR.umlauts"),
1383 "\xc4\xd6\xdc\xe4\xf6\xfc\xdf")
1384 finally:
1385 tar.close()
1386
1387 def test_pax_number_fields(self):
1388 # All following number fields are read from the pax header.
1389 tar = tarfile.open(tarname, encoding="iso8859-1")
1390 try:
1391 tarinfo = tar.getmember("pax/regtype4")
1392 self.assertEqual(tarinfo.size, 7011)
1393 self.assertEqual(tarinfo.uid, 123)
1394 self.assertEqual(tarinfo.gid, 123)
1395 self.assertEqual(tarinfo.mtime, 1041808783.0)
1396 self.assertEqual(type(tarinfo.mtime), float)
1397 self.assertEqual(float(tarinfo.pax_headers["atime"]), 1041808783.0)
1398 self.assertEqual(float(tarinfo.pax_headers["ctime"]), 1041808783.0)
1399 finally:
1400 tar.close()
1401
1402 def test_pax_header_bad_formats(self):
1403 # The fields from the pax header have priority over the
1404 # TarInfo.
1405 pax_header_replacements = (
1406 b" foo=bar\n",
1407 b"0 \n",
1408 b"1 \n",
1409 b"2 \n",
1410 b"3 =\n",
1411 b"4 =a\n",
1412 b"1000000 foo=bar\n",
1413 b"0 foo=bar\n",
1414 b"-12 foo=bar\n",
1415 b"000000000000000000000000036 foo=bar\n",
1416 )
1417 pax_headers = {"foo": "bar"}
1418
1419 for replacement in pax_header_replacements:
1420 with self.subTest(header=replacement):
1421 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
1422 encoding="iso8859-1")
1423 try:
1424 t = tarfile.TarInfo()
1425 t.name = "pax" # non-ASCII
1426 t.uid = 1
1427 t.pax_headers = pax_headers
1428 tar.addfile(t)
1429 finally:
1430 tar.close()
1431
1432 with open(tmpname, "rb") as f:
1433 data = f.read()
1434 self.assertIn(b"11 foo=bar\n", data)
1435 data = data.replace(b"11 foo=bar\n", replacement)
1436
1437 with open(tmpname, "wb") as f:
1438 f.truncate()
1439 f.write(data)
1440
1441 with self.assertRaisesRegex(tarfile.ReadError, r"method tar: ReadError\('invalid header'\)"):
1442 tarfile.open(tmpname, encoding="iso8859-1")
1443
1444
1445 class WriteTestBase(TarTest):
1446 # Put all write tests in here that are supposed to be tested
1447 # in all possible mode combinations.
1448
1449 def test_fileobj_no_close(self):
1450 fobj = io.BytesIO()
1451 with tarfile.open(fileobj=fobj, mode=self.mode) as tar:
1452 tar.addfile(tarfile.TarInfo("foo"))
1453 self.assertFalse(fobj.closed, "external fileobjs must never closed")
1454 # Issue #20238: Incomplete gzip output with mode="w:gz"
1455 data = fobj.getvalue()
1456 del tar
1457 support.gc_collect()
1458 self.assertFalse(fobj.closed)
1459 self.assertEqual(data, fobj.getvalue())
1460
1461 def test_eof_marker(self):
1462 # Make sure an end of archive marker is written (two zero blocks).
1463 # tarfile insists on aligning archives to a 20 * 512 byte recordsize.
1464 # So, we create an archive that has exactly 10240 bytes without the
1465 # marker, and has 20480 bytes once the marker is written.
1466 with tarfile.open(tmpname, self.mode) as tar:
1467 t = tarfile.TarInfo("foo")
1468 t.size = tarfile.RECORDSIZE - tarfile.BLOCKSIZE
1469 tar.addfile(t, io.BytesIO(b"a" * t.size))
1470
1471 with self.open(tmpname, "rb") as fobj:
1472 self.assertEqual(len(fobj.read()), tarfile.RECORDSIZE * 2)
1473
1474
1475 class WriteTest(WriteTestBase, unittest.TestCase):
1476
1477 prefix = "w:"
1478
1479 def test_100_char_name(self):
1480 # The name field in a tar header stores strings of at most 100 chars.
1481 # If a string is shorter than 100 chars it has to be padded with '\0',
1482 # which implies that a string of exactly 100 chars is stored without
1483 # a trailing '\0'.
1484 name = "0123456789" * 10
1485 tar = tarfile.open(tmpname, self.mode)
1486 try:
1487 t = tarfile.TarInfo(name)
1488 tar.addfile(t)
1489 finally:
1490 tar.close()
1491
1492 tar = tarfile.open(tmpname)
1493 try:
1494 self.assertEqual(tar.getnames()[0], name,
1495 "failed to store 100 char filename")
1496 finally:
1497 tar.close()
1498
1499 def test_tar_size(self):
1500 # Test for bug #1013882.
1501 tar = tarfile.open(tmpname, self.mode)
1502 try:
1503 path = os.path.join(TEMPDIR, "file")
1504 with open(path, "wb") as fobj:
1505 fobj.write(b"aaa")
1506 tar.add(path)
1507 finally:
1508 tar.close()
1509 self.assertGreater(os.path.getsize(tmpname), 0,
1510 "tarfile is empty")
1511
1512 # The test_*_size tests test for bug #1167128.
1513 def test_file_size(self):
1514 tar = tarfile.open(tmpname, self.mode)
1515 try:
1516 path = os.path.join(TEMPDIR, "file")
1517 with open(path, "wb"):
1518 pass
1519 tarinfo = tar.gettarinfo(path)
1520 self.assertEqual(tarinfo.size, 0)
1521
1522 with open(path, "wb") as fobj:
1523 fobj.write(b"aaa")
1524 tarinfo = tar.gettarinfo(path)
1525 self.assertEqual(tarinfo.size, 3)
1526 finally:
1527 tar.close()
1528
1529 def test_directory_size(self):
1530 path = os.path.join(TEMPDIR, "directory")
1531 os.mkdir(path)
1532 try:
1533 tar = tarfile.open(tmpname, self.mode)
1534 try:
1535 tarinfo = tar.gettarinfo(path)
1536 self.assertEqual(tarinfo.size, 0)
1537 finally:
1538 tar.close()
1539 finally:
1540 os_helper.rmdir(path)
1541
1542 # mock the following:
1543 # os.listdir: so we know that files are in the wrong order
1544 def test_ordered_recursion(self):
1545 path = os.path.join(TEMPDIR, "directory")
1546 os.mkdir(path)
1547 open(os.path.join(path, "1"), "a").close()
1548 open(os.path.join(path, "2"), "a").close()
1549 try:
1550 tar = tarfile.open(tmpname, self.mode)
1551 try:
1552 with unittest.mock.patch('os.listdir') as mock_listdir:
1553 mock_listdir.return_value = ["2", "1"]
1554 tar.add(path)
1555 paths = []
1556 for m in tar.getmembers():
1557 paths.append(os.path.split(m.name)[-1])
1558 self.assertEqual(paths, ["directory", "1", "2"]);
1559 finally:
1560 tar.close()
1561 finally:
1562 os_helper.unlink(os.path.join(path, "1"))
1563 os_helper.unlink(os.path.join(path, "2"))
1564 os_helper.rmdir(path)
1565
1566 def test_gettarinfo_pathlike_name(self):
1567 with tarfile.open(tmpname, self.mode) as tar:
1568 path = os.path.join(TEMPDIR, "file")
1569 with open(path, "wb") as fobj:
1570 fobj.write(b"aaa")
1571 tarinfo = tar.gettarinfo(os_helper.FakePath(path))
1572 tarinfo2 = tar.gettarinfo(path)
1573 self.assertIsInstance(tarinfo.name, str)
1574 self.assertEqual(tarinfo.name, tarinfo2.name)
1575 self.assertEqual(tarinfo.size, 3)
1576
1577 @unittest.skipUnless(hasattr(os, "link"),
1578 "Missing hardlink implementation")
1579 def test_link_size(self):
1580 link = os.path.join(TEMPDIR, "link")
1581 target = os.path.join(TEMPDIR, "link_target")
1582 with open(target, "wb") as fobj:
1583 fobj.write(b"aaa")
1584 try:
1585 os.link(target, link)
1586 except PermissionError as e:
1587 self.skipTest('os.link(): %s' % e)
1588 try:
1589 tar = tarfile.open(tmpname, self.mode)
1590 try:
1591 # Record the link target in the inodes list.
1592 tar.gettarinfo(target)
1593 tarinfo = tar.gettarinfo(link)
1594 self.assertEqual(tarinfo.size, 0)
1595 finally:
1596 tar.close()
1597 finally:
1598 os_helper.unlink(target)
1599 os_helper.unlink(link)
1600
1601 @os_helper.skip_unless_symlink
1602 def test_symlink_size(self):
1603 path = os.path.join(TEMPDIR, "symlink")
1604 os.symlink("link_target", path)
1605 try:
1606 tar = tarfile.open(tmpname, self.mode)
1607 try:
1608 tarinfo = tar.gettarinfo(path)
1609 self.assertEqual(tarinfo.size, 0)
1610 finally:
1611 tar.close()
1612 finally:
1613 os_helper.unlink(path)
1614
1615 def test_add_self(self):
1616 # Test for #1257255.
1617 dstname = os.path.abspath(tmpname)
1618 tar = tarfile.open(tmpname, self.mode)
1619 try:
1620 self.assertEqual(tar.name, dstname,
1621 "archive name must be absolute")
1622 tar.add(dstname)
1623 self.assertEqual(tar.getnames(), [],
1624 "added the archive to itself")
1625
1626 with os_helper.change_cwd(TEMPDIR):
1627 tar.add(dstname)
1628 self.assertEqual(tar.getnames(), [],
1629 "added the archive to itself")
1630 finally:
1631 tar.close()
1632
1633 def test_filter(self):
1634 tempdir = os.path.join(TEMPDIR, "filter")
1635 os.mkdir(tempdir)
1636 try:
1637 for name in ("foo", "bar", "baz"):
1638 name = os.path.join(tempdir, name)
1639 os_helper.create_empty_file(name)
1640
1641 def filter(tarinfo):
1642 if os.path.basename(tarinfo.name) == "bar":
1643 return
1644 tarinfo.uid = 123
1645 tarinfo.uname = "foo"
1646 return tarinfo
1647
1648 tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1")
1649 try:
1650 tar.add(tempdir, arcname="empty_dir", filter=filter)
1651 finally:
1652 tar.close()
1653
1654 # Verify that filter is a keyword-only argument
1655 with self.assertRaises(TypeError):
1656 tar.add(tempdir, "empty_dir", True, None, filter)
1657
1658 tar = tarfile.open(tmpname, "r")
1659 try:
1660 for tarinfo in tar:
1661 self.assertEqual(tarinfo.uid, 123)
1662 self.assertEqual(tarinfo.uname, "foo")
1663 self.assertEqual(len(tar.getmembers()), 3)
1664 finally:
1665 tar.close()
1666 finally:
1667 os_helper.rmtree(tempdir)
1668
1669 # Guarantee that stored pathnames are not modified. Don't
1670 # remove ./ or ../ or double slashes. Still make absolute
1671 # pathnames relative.
1672 # For details see bug #6054.
1673 def _test_pathname(self, path, cmp_path=None, dir=False):
1674 # Create a tarfile with an empty member named path
1675 # and compare the stored name with the original.
1676 foo = os.path.join(TEMPDIR, "foo")
1677 if not dir:
1678 os_helper.create_empty_file(foo)
1679 else:
1680 os.mkdir(foo)
1681
1682 tar = tarfile.open(tmpname, self.mode)
1683 try:
1684 tar.add(foo, arcname=path)
1685 finally:
1686 tar.close()
1687
1688 tar = tarfile.open(tmpname, "r")
1689 try:
1690 t = tar.next()
1691 finally:
1692 tar.close()
1693
1694 if not dir:
1695 os_helper.unlink(foo)
1696 else:
1697 os_helper.rmdir(foo)
1698
1699 self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
1700
1701
1702 @os_helper.skip_unless_symlink
1703 def test_extractall_symlinks(self):
1704 # Test if extractall works properly when tarfile contains symlinks
1705 tempdir = os.path.join(TEMPDIR, "testsymlinks")
1706 temparchive = os.path.join(TEMPDIR, "testsymlinks.tar")
1707 os.mkdir(tempdir)
1708 try:
1709 source_file = os.path.join(tempdir,'source')
1710 target_file = os.path.join(tempdir,'symlink')
1711 with open(source_file,'w') as f:
1712 f.write('something\n')
1713 os.symlink(source_file, target_file)
1714 with tarfile.open(temparchive, 'w') as tar:
1715 tar.add(source_file, arcname="source")
1716 tar.add(target_file, arcname="symlink")
1717 # Let's extract it to the location which contains the symlink
1718 with tarfile.open(temparchive, errorlevel=2) as tar:
1719 # this should not raise OSError: [Errno 17] File exists
1720 try:
1721 tar.extractall(path=tempdir,
1722 filter='fully_trusted')
1723 except OSError:
1724 self.fail("extractall failed with symlinked files")
1725 finally:
1726 os_helper.unlink(temparchive)
1727 os_helper.rmtree(tempdir)
1728
1729 def test_pathnames(self):
1730 self._test_pathname("foo")
1731 self._test_pathname(os.path.join("foo", ".", "bar"))
1732 self._test_pathname(os.path.join("foo", "..", "bar"))
1733 self._test_pathname(os.path.join(".", "foo"))
1734 self._test_pathname(os.path.join(".", "foo", "."))
1735 self._test_pathname(os.path.join(".", "foo", ".", "bar"))
1736 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1737 self._test_pathname(os.path.join(".", "foo", "..", "bar"))
1738 self._test_pathname(os.path.join("..", "foo"))
1739 self._test_pathname(os.path.join("..", "foo", ".."))
1740 self._test_pathname(os.path.join("..", "foo", ".", "bar"))
1741 self._test_pathname(os.path.join("..", "foo", "..", "bar"))
1742
1743 self._test_pathname("foo" + os.sep + os.sep + "bar")
1744 self._test_pathname("foo" + os.sep + os.sep, "foo", dir=True)
1745
1746 def test_abs_pathnames(self):
1747 if sys.platform == "win32":
1748 self._test_pathname("C:\\foo", "foo")
1749 else:
1750 self._test_pathname("/foo", "foo")
1751 self._test_pathname("///foo", "foo")
1752
1753 def test_cwd(self):
1754 # Test adding the current working directory.
1755 with os_helper.change_cwd(TEMPDIR):
1756 tar = tarfile.open(tmpname, self.mode)
1757 try:
1758 tar.add(".")
1759 finally:
1760 tar.close()
1761
1762 tar = tarfile.open(tmpname, "r")
1763 try:
1764 for t in tar:
1765 if t.name != ".":
1766 self.assertTrue(t.name.startswith("./"))
1767 finally:
1768 tar.close()
1769
1770 def test_open_nonwritable_fileobj(self):
1771 for exctype in OSError, EOFError, RuntimeError:
1772 class BadFile(io.BytesIO):
1773 first = True
1774 def write(self, data):
1775 if self.first:
1776 self.first = False
1777 raise exctype
1778
1779 f = BadFile()
1780 with (
1781 warnings_helper.check_no_resource_warning(self),
1782 self.assertRaises(exctype),
1783 ):
1784 tarfile.open(tmpname, self.mode, fileobj=f,
1785 format=tarfile.PAX_FORMAT,
1786 pax_headers={'non': 'empty'})
1787 self.assertFalse(f.closed)
1788
1789 def test_missing_fileobj(self):
1790 with tarfile.open(tmpname, self.mode) as tar:
1791 tarinfo = tar.gettarinfo(tarname)
1792 with self.assertRaises(ValueError):
1793 tar.addfile(tarinfo)
1794
1795
1796 class GzipWriteTest(GzipTest, WriteTest):
1797 pass
1798
1799
1800 class Bz2WriteTest(Bz2Test, WriteTest):
1801 pass
1802
1803
1804 class LzmaWriteTest(LzmaTest, WriteTest):
1805 pass
1806
1807 class ZstdWriteTest(ZstdTest, WriteTest):
1808 pass
1809
1810 class StreamWriteTest(WriteTestBase, unittest.TestCase):
1811
1812 prefix = "w|"
1813 decompressor = None
1814
1815 def test_stream_padding(self):
1816 # Test for bug #1543303.
1817 tar = tarfile.open(tmpname, self.mode)
1818 tar.close()
1819 if self.decompressor:
1820 dec = self.decompressor()
1821 with open(tmpname, "rb") as fobj:
1822 data = fobj.read()
1823 data = dec.decompress(data)
1824 self.assertFalse(dec.unused_data, "found trailing data")
1825 else:
1826 with self.open(tmpname) as fobj:
1827 data = fobj.read()
1828 self.assertEqual(data.count(b"\0"), tarfile.RECORDSIZE,
1829 "incorrect zero padding")
1830
1831 @unittest.skipUnless(sys.platform != "win32" and hasattr(os, "umask"),
1832 "Missing umask implementation")
1833 @unittest.skipIf(
1834 support.is_emscripten or support.is_wasi,
1835 "Emscripten's/WASI's umask is a stub."
1836 )
1837 def test_file_mode(self):
1838 # Test for issue #8464: Create files with correct
1839 # permissions.
1840 if os.path.exists(tmpname):
1841 os_helper.unlink(tmpname)
1842
1843 original_umask = os.umask(0o022)
1844 try:
1845 tar = tarfile.open(tmpname, self.mode)
1846 tar.close()
1847 mode = os.stat(tmpname).st_mode & 0o777
1848 self.assertEqual(mode, 0o644, "wrong file permissions")
1849 finally:
1850 os.umask(original_umask)
1851
1852 def test_pathlike_name(self):
1853 expected_name = os.path.abspath(tmpname)
1854 tarpath = os_helper.FakePath(tmpname)
1855
1856 for func in (tarfile.open, tarfile.TarFile.open):
1857 with self.subTest():
1858 with func(tarpath, self.mode) as tar:
1859 self.assertEqual(tar.name, expected_name)
1860 os_helper.unlink(tmpname)
1861
1862
1863 class GzipStreamWriteTest(GzipTest, StreamWriteTest):
1864 def test_source_directory_not_leaked(self):
1865 """
1866 Ensure the source directory is not included in the tar header
1867 per bpo-41316.
1868 """
1869 tarfile.open(tmpname, self.mode).close()
1870 payload = pathlib.Path(tmpname).read_text(encoding='latin-1')
1871 assert os.path.dirname(tmpname) not in payload
1872
1873
1874 class Bz2StreamWriteTest(Bz2Test, StreamWriteTest):
1875 decompressor = bz2.BZ2Decompressor if bz2 else None
1876
1877 class LzmaStreamWriteTest(LzmaTest, StreamWriteTest):
1878 decompressor = lzma.LZMADecompressor if lzma else None
1879
1880 class ZstdStreamWriteTest(ZstdTest, StreamWriteTest):
1881 decompressor = zstd.ZstdDecompressor if zstd else None
1882
1883 class _CompressedWriteTest(TarTest):
1884 # This is not actually a standalone test.
1885 # It does not inherit WriteTest because it only makes sense with gz,bz2
1886 source = (b"And we move to Bristol where they have a special, " +
1887 b"Very Silly candidate")
1888
1889 def _compressed_tar(self, compresslevel):
1890 fobj = io.BytesIO()
1891 with tarfile.open(tmpname, self.mode, fobj,
1892 compresslevel=compresslevel) as tarfl:
1893 tarfl.addfile(tarfile.TarInfo("foo"), io.BytesIO(self.source))
1894 return fobj
1895
1896 def _test_bz2_header(self, compresslevel):
1897 fobj = self._compressed_tar(compresslevel)
1898 self.assertEqual(fobj.getvalue()[0:10],
1899 b"BZh%d1AY&SY" % compresslevel)
1900
1901 def _test_gz_header(self, compresslevel):
1902 fobj = self._compressed_tar(compresslevel)
1903 self.assertEqual(fobj.getvalue()[:3], b"\x1f\x8b\x08")
1904
1905 class Bz2CompressWriteTest(Bz2Test, _CompressedWriteTest, unittest.TestCase):
1906 prefix = "w:"
1907 def test_compression_levels(self):
1908 self._test_bz2_header(1)
1909 self._test_bz2_header(5)
1910 self._test_bz2_header(9)
1911
1912 class Bz2CompressStreamWriteTest(Bz2Test, _CompressedWriteTest,
1913 unittest.TestCase):
1914 prefix = "w|"
1915 def test_compression_levels(self):
1916 self._test_bz2_header(1)
1917 self._test_bz2_header(5)
1918 self._test_bz2_header(9)
1919
1920 class GzCompressWriteTest(GzipTest, _CompressedWriteTest, unittest.TestCase):
1921 prefix = "w:"
1922 def test_compression_levels(self):
1923 self._test_gz_header(1)
1924 self._test_gz_header(5)
1925 self._test_gz_header(9)
1926
1927 class GzCompressStreamWriteTest(GzipTest, _CompressedWriteTest,
1928 unittest.TestCase):
1929 prefix = "w|"
1930 def test_compression_levels(self):
1931 self._test_gz_header(1)
1932 self._test_gz_header(5)
1933 self._test_gz_header(9)
1934
1935 class CompressLevelRaises(unittest.TestCase):
1936 def test_compresslevel_wrong_modes(self):
1937 compresslevel = 5
1938 fobj = io.BytesIO()
1939 with self.assertRaises(TypeError):
1940 tarfile.open(tmpname, "w:", fobj, compresslevel=compresslevel)
1941
1942 @support.requires_bz2()
1943 def test_wrong_compresslevels(self):
1944 # BZ2 checks that the compresslevel is in [1,9]. gz does not
1945 fobj = io.BytesIO()
1946 with self.assertRaises(ValueError):
1947 tarfile.open(tmpname, "w:bz2", fobj, compresslevel=0)
1948 with self.assertRaises(ValueError):
1949 tarfile.open(tmpname, "w:bz2", fobj, compresslevel=10)
1950 with self.assertRaises(ValueError):
1951 tarfile.open(tmpname, "w|bz2", fobj, compresslevel=10)
1952
1953 class GNUWriteTest(unittest.TestCase):
1954 # This testcase checks for correct creation of GNU Longname
1955 # and Longlink extended headers (cp. bug #812325).
1956
1957 def _length(self, s):
1958 blocks = len(s) // 512 + 1
1959 return blocks * 512
1960
1961 def _calc_size(self, name, link=None):
1962 # Initial tar header
1963 count = 512
1964
1965 if len(name) > tarfile.LENGTH_NAME:
1966 # GNU longname extended header + longname
1967 count += 512
1968 count += self._length(name)
1969 if link is not None and len(link) > tarfile.LENGTH_LINK:
1970 # GNU longlink extended header + longlink
1971 count += 512
1972 count += self._length(link)
1973 return count
1974
1975 def _test(self, name, link=None):
1976 tarinfo = tarfile.TarInfo(name)
1977 if link:
1978 tarinfo.linkname = link
1979 tarinfo.type = tarfile.LNKTYPE
1980
1981 tar = tarfile.open(tmpname, "w")
1982 try:
1983 tar.format = tarfile.GNU_FORMAT
1984 tar.addfile(tarinfo)
1985
1986 v1 = self._calc_size(name, link)
1987 v2 = tar.offset
1988 self.assertEqual(v1, v2, "GNU longname/longlink creation failed")
1989 finally:
1990 tar.close()
1991
1992 tar = tarfile.open(tmpname)
1993 try:
1994 member = tar.next()
1995 self.assertIsNotNone(member,
1996 "unable to read longname member")
1997 self.assertEqual(tarinfo.name, member.name,
1998 "unable to read longname member")
1999 self.assertEqual(tarinfo.linkname, member.linkname,
2000 "unable to read longname member")
2001 finally:
2002 tar.close()
2003
2004 def test_longname_1023(self):
2005 self._test(("longnam/" * 127) + "longnam")
2006
2007 def test_longname_1024(self):
2008 self._test(("longnam/" * 127) + "longname")
2009
2010 def test_longname_1025(self):
2011 self._test(("longnam/" * 127) + "longname_")
2012
2013 def test_longlink_1023(self):
2014 self._test("name", ("longlnk/" * 127) + "longlnk")
2015
2016 def test_longlink_1024(self):
2017 self._test("name", ("longlnk/" * 127) + "longlink")
2018
2019 def test_longlink_1025(self):
2020 self._test("name", ("longlnk/" * 127) + "longlink_")
2021
2022 def test_longnamelink_1023(self):
2023 self._test(("longnam/" * 127) + "longnam",
2024 ("longlnk/" * 127) + "longlnk")
2025
2026 def test_longnamelink_1024(self):
2027 self._test(("longnam/" * 127) + "longname",
2028 ("longlnk/" * 127) + "longlink")
2029
2030 def test_longnamelink_1025(self):
2031 self._test(("longnam/" * 127) + "longname_",
2032 ("longlnk/" * 127) + "longlink_")
2033
2034
2035 class DeviceHeaderTest(WriteTestBase, unittest.TestCase):
2036
2037 prefix = "w:"
2038
2039 def test_headers_written_only_for_device_files(self):
2040 # Regression test for bpo-18819.
2041 tempdir = os.path.join(TEMPDIR, "device_header_test")
2042 os.mkdir(tempdir)
2043 try:
2044 tar = tarfile.open(tmpname, self.mode)
2045 try:
2046 input_blk = tarfile.TarInfo(name="my_block_device")
2047 input_reg = tarfile.TarInfo(name="my_regular_file")
2048 input_blk.type = tarfile.BLKTYPE
2049 input_reg.type = tarfile.REGTYPE
2050 tar.addfile(input_blk)
2051 tar.addfile(input_reg)
2052 finally:
2053 tar.close()
2054
2055 # devmajor and devminor should be *interpreted* as 0 in both...
2056 tar = tarfile.open(tmpname, "r")
2057 try:
2058 output_blk = tar.getmember("my_block_device")
2059 output_reg = tar.getmember("my_regular_file")
2060 finally:
2061 tar.close()
2062 self.assertEqual(output_blk.devmajor, 0)
2063 self.assertEqual(output_blk.devminor, 0)
2064 self.assertEqual(output_reg.devmajor, 0)
2065 self.assertEqual(output_reg.devminor, 0)
2066
2067 # ...but the fields should not actually be set on regular files:
2068 with open(tmpname, "rb") as infile:
2069 buf = infile.read()
2070 buf_blk = buf[output_blk.offset:output_blk.offset_data]
2071 buf_reg = buf[output_reg.offset:output_reg.offset_data]
2072 # See `struct posixheader` in GNU docs for byte offsets:
2073 # <https://www.gnu.org/software/tar/manual/html_node/Standard.html>
2074 device_headers = slice(329, 329 + 16)
2075 self.assertEqual(buf_blk[device_headers], b"0000000\0" * 2)
2076 self.assertEqual(buf_reg[device_headers], b"\0" * 16)
2077 finally:
2078 os_helper.rmtree(tempdir)
2079
2080
2081 class CreateTest(WriteTestBase, unittest.TestCase):
2082
2083 prefix = "x:"
2084
2085 file_path = os.path.join(TEMPDIR, "spameggs42")
2086
2087 def setUp(self):
2088 os_helper.unlink(tmpname)
2089
2090 @classmethod
2091 def setUpClass(cls):
2092 with open(cls.file_path, "wb") as fobj:
2093 fobj.write(b"aaa")
2094
2095 @classmethod
2096 def tearDownClass(cls):
2097 os_helper.unlink(cls.file_path)
2098
2099 def test_create(self):
2100 with tarfile.open(tmpname, self.mode) as tobj:
2101 tobj.add(self.file_path)
2102
2103 with self.taropen(tmpname) as tobj:
2104 names = tobj.getnames()
2105 self.assertEqual(len(names), 1)
2106 self.assertIn('spameggs42', names[0])
2107
2108 def test_create_existing(self):
2109 with tarfile.open(tmpname, self.mode) as tobj:
2110 tobj.add(self.file_path)
2111
2112 with self.assertRaises(FileExistsError):
2113 tobj = tarfile.open(tmpname, self.mode)
2114
2115 with self.taropen(tmpname) as tobj:
2116 names = tobj.getnames()
2117 self.assertEqual(len(names), 1)
2118 self.assertIn('spameggs42', names[0])
2119
2120 def test_create_taropen(self):
2121 with self.taropen(tmpname, "x") as tobj:
2122 tobj.add(self.file_path)
2123
2124 with self.taropen(tmpname) as tobj:
2125 names = tobj.getnames()
2126 self.assertEqual(len(names), 1)
2127 self.assertIn('spameggs42', names[0])
2128
2129 def test_create_existing_taropen(self):
2130 with self.taropen(tmpname, "x") as tobj:
2131 tobj.add(self.file_path)
2132
2133 with self.assertRaises(FileExistsError):
2134 with self.taropen(tmpname, "x"):
2135 pass
2136
2137 with self.taropen(tmpname) as tobj:
2138 names = tobj.getnames()
2139 self.assertEqual(len(names), 1)
2140 self.assertIn("spameggs42", names[0])
2141
2142 def test_create_pathlike_name(self):
2143 with tarfile.open(os_helper.FakePath(tmpname), self.mode) as tobj:
2144 self.assertIsInstance(tobj.name, str)
2145 self.assertEqual(tobj.name, os.path.abspath(tmpname))
2146 tobj.add(os_helper.FakePath(self.file_path))
2147 names = tobj.getnames()
2148 self.assertEqual(len(names), 1)
2149 self.assertIn('spameggs42', names[0])
2150
2151 with self.taropen(tmpname) as tobj:
2152 names = tobj.getnames()
2153 self.assertEqual(len(names), 1)
2154 self.assertIn('spameggs42', names[0])
2155
2156 def test_create_taropen_pathlike_name(self):
2157 with self.taropen(os_helper.FakePath(tmpname), "x") as tobj:
2158 self.assertIsInstance(tobj.name, str)
2159 self.assertEqual(tobj.name, os.path.abspath(tmpname))
2160 tobj.add(os_helper.FakePath(self.file_path))
2161 names = tobj.getnames()
2162 self.assertEqual(len(names), 1)
2163 self.assertIn('spameggs42', names[0])
2164
2165 with self.taropen(tmpname) as tobj:
2166 names = tobj.getnames()
2167 self.assertEqual(len(names), 1)
2168 self.assertIn('spameggs42', names[0])
2169
2170
2171 class GzipCreateTest(GzipTest, CreateTest):
2172
2173 def test_create_with_compresslevel(self):
2174 with tarfile.open(tmpname, self.mode, compresslevel=1) as tobj:
2175 tobj.add(self.file_path)
2176 with tarfile.open(tmpname, 'r:gz', compresslevel=1) as tobj:
2177 pass
2178
2179
2180 class Bz2CreateTest(Bz2Test, CreateTest):
2181
2182 def test_create_with_compresslevel(self):
2183 with tarfile.open(tmpname, self.mode, compresslevel=1) as tobj:
2184 tobj.add(self.file_path)
2185 with tarfile.open(tmpname, 'r:bz2', compresslevel=1) as tobj:
2186 pass
2187
2188
2189 class LzmaCreateTest(LzmaTest, CreateTest):
2190
2191 # Unlike gz and bz2, xz uses the preset keyword instead of compresslevel.
2192 # It does not allow for preset to be specified when reading.
2193 def test_create_with_preset(self):
2194 with tarfile.open(tmpname, self.mode, preset=1) as tobj:
2195 tobj.add(self.file_path)
2196
2197
2198 class ZstdCreateTest(ZstdTest, CreateTest):
2199
2200 # Unlike gz and bz2, zstd uses the level keyword instead of compresslevel.
2201 # It does not allow for level to be specified when reading.
2202 def test_create_with_level(self):
2203 with tarfile.open(tmpname, self.mode, level=1) as tobj:
2204 tobj.add(self.file_path)
2205
2206 class CreateWithXModeTest(CreateTest):
2207
2208 prefix = "x"
2209
2210 test_create_taropen = None
2211 test_create_existing_taropen = None
2212
2213
2214 @unittest.skipUnless(hasattr(os, "link"), "Missing hardlink implementation")
2215 class HardlinkTest(unittest.TestCase):
2216 # Test the creation of LNKTYPE (hardlink) members in an archive.
2217
2218 def setUp(self):
2219 self.foo = os.path.join(TEMPDIR, "foo")
2220 self.bar = os.path.join(TEMPDIR, "bar")
2221
2222 with open(self.foo, "wb") as fobj:
2223 fobj.write(b"foo")
2224
2225 try:
2226 os.link(self.foo, self.bar)
2227 except PermissionError as e:
2228 self.skipTest('os.link(): %s' % e)
2229
2230 self.tar = tarfile.open(tmpname, "w")
2231 self.tar.add(self.foo)
2232
2233 def tearDown(self):
2234 self.tar.close()
2235 os_helper.unlink(self.foo)
2236 os_helper.unlink(self.bar)
2237
2238 def test_add_twice(self):
2239 # The same name will be added as a REGTYPE every
2240 # time regardless of st_nlink.
2241 tarinfo = self.tar.gettarinfo(self.foo)
2242 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
2243 "add file as regular failed")
2244
2245 def test_add_hardlink(self):
2246 tarinfo = self.tar.gettarinfo(self.bar)
2247 self.assertEqual(tarinfo.type, tarfile.LNKTYPE,
2248 "add file as hardlink failed")
2249
2250 def test_dereference_hardlink(self):
2251 self.tar.dereference = True
2252 tarinfo = self.tar.gettarinfo(self.bar)
2253 self.assertEqual(tarinfo.type, tarfile.REGTYPE,
2254 "dereferencing hardlink failed")
2255
2256
2257 class PaxWriteTest(GNUWriteTest):
2258
2259 def _test(self, name, link=None):
2260 # See GNUWriteTest.
2261 tarinfo = tarfile.TarInfo(name)
2262 if link:
2263 tarinfo.linkname = link
2264 tarinfo.type = tarfile.LNKTYPE
2265
2266 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT)
2267 try:
2268 tar.addfile(tarinfo)
2269 finally:
2270 tar.close()
2271
2272 tar = tarfile.open(tmpname)
2273 try:
2274 if link:
2275 l = tar.getmembers()[0].linkname
2276 self.assertEqual(link, l, "PAX longlink creation failed")
2277 else:
2278 n = tar.getmembers()[0].name
2279 self.assertEqual(name, n, "PAX longname creation failed")
2280 finally:
2281 tar.close()
2282
2283 def test_pax_global_header(self):
2284 pax_headers = {
2285 "foo": "bar",
2286 "uid": "0",
2287 "mtime": "1.23",
2288 "test": "\xe4\xf6\xfc",
2289 "\xe4\xf6\xfc": "test"}
2290
2291 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
2292 pax_headers=pax_headers)
2293 try:
2294 tar.addfile(tarfile.TarInfo("test"))
2295 finally:
2296 tar.close()
2297
2298 # Test if the global header was written correctly.
2299 tar = tarfile.open(tmpname, encoding="iso8859-1")
2300 try:
2301 self.assertEqual(tar.pax_headers, pax_headers)
2302 self.assertEqual(tar.getmembers()[0].pax_headers, pax_headers)
2303 # Test if all the fields are strings.
2304 for key, val in tar.pax_headers.items():
2305 self.assertIsNot(type(key), bytes)
2306 self.assertIsNot(type(val), bytes)
2307 if key in tarfile.PAX_NUMBER_FIELDS:
2308 try:
2309 tarfile.PAX_NUMBER_FIELDS[key](val)
2310 except (TypeError, ValueError):
2311 self.fail("unable to convert pax header field")
2312 finally:
2313 tar.close()
2314
2315 def test_pax_extended_header(self):
2316 # The fields from the pax header have priority over the
2317 # TarInfo.
2318 pax_headers = {"path": "foo", "uid": "123"}
2319
2320 tar = tarfile.open(tmpname, "w", format=tarfile.PAX_FORMAT,
2321 encoding="iso8859-1")
2322 try:
2323 t = tarfile.TarInfo()
2324 t.name = "\xe4\xf6\xfc" # non-ASCII
2325 t.uid = 8**8 # too large
2326 t.pax_headers = pax_headers
2327 tar.addfile(t)
2328 finally:
2329 tar.close()
2330
2331 tar = tarfile.open(tmpname, encoding="iso8859-1")
2332 try:
2333 t = tar.getmembers()[0]
2334 self.assertEqual(t.pax_headers, pax_headers)
2335 self.assertEqual(t.name, "foo")
2336 self.assertEqual(t.uid, 123)
2337 finally:
2338 tar.close()
2339
2340 def test_create_pax_header(self):
2341 # The ustar header should contain values that can be
2342 # represented reasonably, even if a better (e.g. higher
2343 # precision) version is set in the pax header.
2344 # Issue #45863
2345
2346 # values that should be kept
2347 t = tarfile.TarInfo()
2348 t.name = "foo"
2349 t.mtime = 1000.1
2350 t.size = 100
2351 t.uid = 123
2352 t.gid = 124
2353 info = t.get_info()
2354 header = t.create_pax_header(info, encoding="iso8859-1")
2355 self.assertEqual(info['name'], "foo")
2356 # mtime should be rounded to nearest second
2357 self.assertIsInstance(info['mtime'], int)
2358 self.assertEqual(info['mtime'], 1000)
2359 self.assertEqual(info['size'], 100)
2360 self.assertEqual(info['uid'], 123)
2361 self.assertEqual(info['gid'], 124)
2362 self.assertEqual(header,
2363 b'././@PaxHeader' + bytes(86) \
2364 + b'0000000\x000000000\x000000000\x0000000000020\x0000000000000\x00010205\x00 x' \
2365 + bytes(100) + b'ustar\x0000'+ bytes(247) \
2366 + b'16 mtime=1000.1\n' + bytes(496) + b'foo' + bytes(97) \
2367 + b'0000644\x000000173\x000000174\x0000000000144\x0000000001750\x00006516\x00 0' \
2368 + bytes(100) + b'ustar\x0000' + bytes(247))
2369
2370 # values that should be changed
2371 t = tarfile.TarInfo()
2372 t.name = "foo\u3374" # can't be represented in ascii
2373 t.mtime = 10**10 # too big
2374 t.size = 10**10 # too big
2375 t.uid = 8**8 # too big
2376 t.gid = 8**8+1 # too big
2377 info = t.get_info()
2378 header = t.create_pax_header(info, encoding="iso8859-1")
2379 # name is kept as-is in info but should be added to pax header
2380 self.assertEqual(info['name'], "foo\u3374")
2381 self.assertEqual(info['mtime'], 0)
2382 self.assertEqual(info['size'], 0)
2383 self.assertEqual(info['uid'], 0)
2384 self.assertEqual(info['gid'], 0)
2385 self.assertEqual(header,
2386 b'././@PaxHeader' + bytes(86) \
2387 + b'0000000\x000000000\x000000000\x0000000000130\x0000000000000\x00010207\x00 x' \
2388 + bytes(100) + b'ustar\x0000' + bytes(247) \
2389 + b'15 path=foo\xe3\x8d\xb4\n16 uid=16777216\n' \
2390 + b'16 gid=16777217\n20 size=10000000000\n' \
2391 + b'21 mtime=10000000000\n'+ bytes(424) + b'foo?' + bytes(96) \
2392 + b'0000644\x000000000\x000000000\x0000000000000\x0000000000000\x00006540\x00 0' \
2393 + bytes(100) + b'ustar\x0000' + bytes(247))
2394
2395
2396 class UnicodeTest:
2397
2398 def test_iso8859_1_filename(self):
2399 self._test_unicode_filename("iso8859-1")
2400
2401 def test_utf7_filename(self):
2402 self._test_unicode_filename("utf7")
2403
2404 def test_utf8_filename(self):
2405 self._test_unicode_filename("utf-8")
2406
2407 def _test_unicode_filename(self, encoding):
2408 tar = tarfile.open(tmpname, "w", format=self.format,
2409 encoding=encoding, errors="strict")
2410 try:
2411 name = "\xe4\xf6\xfc"
2412 tar.addfile(tarfile.TarInfo(name))
2413 finally:
2414 tar.close()
2415
2416 tar = tarfile.open(tmpname, encoding=encoding)
2417 try:
2418 self.assertEqual(tar.getmembers()[0].name, name)
2419 finally:
2420 tar.close()
2421
2422 def test_unicode_filename_error(self):
2423 tar = tarfile.open(tmpname, "w", format=self.format,
2424 encoding="ascii", errors="strict")
2425 try:
2426 tarinfo = tarfile.TarInfo()
2427
2428 tarinfo.name = "\xe4\xf6\xfc"
2429 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
2430
2431 tarinfo.name = "foo"
2432 tarinfo.uname = "\xe4\xf6\xfc"
2433 self.assertRaises(UnicodeError, tar.addfile, tarinfo)
2434 finally:
2435 tar.close()
2436
2437 def test_unicode_argument(self):
2438 tar = tarfile.open(tarname, "r",
2439 encoding="iso8859-1", errors="strict")
2440 try:
2441 for t in tar:
2442 self.assertIs(type(t.name), str)
2443 self.assertIs(type(t.linkname), str)
2444 self.assertIs(type(t.uname), str)
2445 self.assertIs(type(t.gname), str)
2446 finally:
2447 tar.close()
2448
2449 def test_uname_unicode(self):
2450 t = tarfile.TarInfo("foo")
2451 t.uname = "\xe4\xf6\xfc"
2452 t.gname = "\xe4\xf6\xfc"
2453
2454 tar = tarfile.open(tmpname, mode="w", format=self.format,
2455 encoding="iso8859-1")
2456 try:
2457 tar.addfile(t)
2458 finally:
2459 tar.close()
2460
2461 tar = tarfile.open(tmpname, encoding="iso8859-1")
2462 try:
2463 t = tar.getmember("foo")
2464 self.assertEqual(t.uname, "\xe4\xf6\xfc")
2465 self.assertEqual(t.gname, "\xe4\xf6\xfc")
2466
2467 if self.format != tarfile.PAX_FORMAT:
2468 tar.close()
2469 tar = tarfile.open(tmpname, encoding="ascii")
2470 t = tar.getmember("foo")
2471 self.assertEqual(t.uname, "\udce4\udcf6\udcfc")
2472 self.assertEqual(t.gname, "\udce4\udcf6\udcfc")
2473 finally:
2474 tar.close()
2475
2476
2477 class UstarUnicodeTest(UnicodeTest, unittest.TestCase):
2478
2479 format = tarfile.USTAR_FORMAT
2480
2481 # Test whether the utf-8 encoded version of a filename exceeds the 100
2482 # bytes name field limit (every occurrence of '\xff' will be expanded to 2
2483 # bytes).
2484 def test_unicode_name1(self):
2485 self._test_ustar_name("0123456789" * 10)
2486 self._test_ustar_name("0123456789" * 10 + "0", ValueError)
2487 self._test_ustar_name("0123456789" * 9 + "01234567\xff")
2488 self._test_ustar_name("0123456789" * 9 + "012345678\xff", ValueError)
2489
2490 def test_unicode_name2(self):
2491 self._test_ustar_name("0123456789" * 9 + "012345\xff\xff")
2492 self._test_ustar_name("0123456789" * 9 + "0123456\xff\xff", ValueError)
2493
2494 # Test whether the utf-8 encoded version of a filename exceeds the 155
2495 # bytes prefix + '/' + 100 bytes name limit.
2496 def test_unicode_longname1(self):
2497 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 10)
2498 self._test_ustar_name("0123456789" * 15 + "0123/4" + "0123456789" * 10, ValueError)
2499 self._test_ustar_name("0123456789" * 15 + "012\xff/" + "0123456789" * 10)
2500 self._test_ustar_name("0123456789" * 15 + "0123\xff/" + "0123456789" * 10, ValueError)
2501
2502 def test_unicode_longname2(self):
2503 self._test_ustar_name("0123456789" * 15 + "01\xff/2" + "0123456789" * 10, ValueError)
2504 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/" + "0123456789" * 10, ValueError)
2505
2506 def test_unicode_longname3(self):
2507 self._test_ustar_name("0123456789" * 15 + "01\xff\xff/2" + "0123456789" * 10, ValueError)
2508 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "01234567\xff")
2509 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345678\xff", ValueError)
2510
2511 def test_unicode_longname4(self):
2512 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "012345\xff\xff")
2513 self._test_ustar_name("0123456789" * 15 + "01234/" + "0123456789" * 9 + "0123456\xff\xff", ValueError)
2514
2515 def _test_ustar_name(self, name, exc=None):
2516 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
2517 t = tarfile.TarInfo(name)
2518 if exc is None:
2519 tar.addfile(t)
2520 else:
2521 self.assertRaises(exc, tar.addfile, t)
2522
2523 if exc is None:
2524 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
2525 for t in tar:
2526 self.assertEqual(name, t.name)
2527 break
2528
2529 # Test the same as above for the 100 bytes link field.
2530 def test_unicode_link1(self):
2531 self._test_ustar_link("0123456789" * 10)
2532 self._test_ustar_link("0123456789" * 10 + "0", ValueError)
2533 self._test_ustar_link("0123456789" * 9 + "01234567\xff")
2534 self._test_ustar_link("0123456789" * 9 + "012345678\xff", ValueError)
2535
2536 def test_unicode_link2(self):
2537 self._test_ustar_link("0123456789" * 9 + "012345\xff\xff")
2538 self._test_ustar_link("0123456789" * 9 + "0123456\xff\xff", ValueError)
2539
2540 def _test_ustar_link(self, name, exc=None):
2541 with tarfile.open(tmpname, "w", format=self.format, encoding="utf-8") as tar:
2542 t = tarfile.TarInfo("foo")
2543 t.linkname = name
2544 if exc is None:
2545 tar.addfile(t)
2546 else:
2547 self.assertRaises(exc, tar.addfile, t)
2548
2549 if exc is None:
2550 with tarfile.open(tmpname, "r", encoding="utf-8") as tar:
2551 for t in tar:
2552 self.assertEqual(name, t.linkname)
2553 break
2554
2555
2556 class GNUUnicodeTest(UnicodeTest, unittest.TestCase):
2557
2558 format = tarfile.GNU_FORMAT
2559
2560 def test_bad_pax_header(self):
2561 # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
2562 # without a hdrcharset=BINARY header.
2563 for encoding, name in (
2564 ("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
2565 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
2566 with tarfile.open(tarname, encoding=encoding,
2567 errors="surrogateescape") as tar:
2568 try:
2569 t = tar.getmember(name)
2570 except KeyError:
2571 self.fail("unable to read bad GNU tar pax header")
2572
2573
2574 class PAXUnicodeTest(UnicodeTest, unittest.TestCase):
2575
2576 format = tarfile.PAX_FORMAT
2577
2578 # PAX_FORMAT ignores encoding in write mode.
2579 test_unicode_filename_error = None
2580
2581 def test_binary_header(self):
2582 # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
2583 for encoding, name in (
2584 ("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
2585 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
2586 with tarfile.open(tarname, encoding=encoding,
2587 errors="surrogateescape") as tar:
2588 try:
2589 t = tar.getmember(name)
2590 except KeyError:
2591 self.fail("unable to read POSIX.1-2008 binary header")
2592
2593
2594 class AppendTestBase:
2595 # Test append mode (cp. patch #1652681).
2596
2597 def setUp(self):
2598 self.tarname = tmpname
2599 if os.path.exists(self.tarname):
2600 os_helper.unlink(self.tarname)
2601
2602 def _create_testtar(self, mode="w:"):
2603 with tarfile.open(tarname, encoding="iso8859-1") as src:
2604 t = src.getmember("ustar/regtype")
2605 t.name = "foo"
2606 with src.extractfile(t) as f:
2607 with tarfile.open(self.tarname, mode) as tar:
2608 tar.addfile(t, f)
2609
2610 def test_append_compressed(self):
2611 self._create_testtar("w:" + self.suffix)
2612 self.assertRaises(tarfile.ReadError, tarfile.open, tmpname, "a")
2613
2614 class AppendTest(AppendTestBase, unittest.TestCase):
2615 test_append_compressed = None
2616
2617 def _add_testfile(self, fileobj=None):
2618 with tarfile.open(self.tarname, "a", fileobj=fileobj) as tar:
2619 tar.addfile(tarfile.TarInfo("bar"))
2620
2621 def _test(self, names=["bar"], fileobj=None):
2622 with tarfile.open(self.tarname, fileobj=fileobj) as tar:
2623 self.assertEqual(tar.getnames(), names)
2624
2625 def test_non_existing(self):
2626 self._add_testfile()
2627 self._test()
2628
2629 def test_empty(self):
2630 tarfile.open(self.tarname, "w:").close()
2631 self._add_testfile()
2632 self._test()
2633
2634 def test_empty_fileobj(self):
2635 fobj = io.BytesIO(b"\0" * 1024)
2636 self._add_testfile(fobj)
2637 fobj.seek(0)
2638 self._test(fileobj=fobj)
2639
2640 def test_fileobj(self):
2641 self._create_testtar()
2642 with open(self.tarname, "rb") as fobj:
2643 data = fobj.read()
2644 fobj = io.BytesIO(data)
2645 self._add_testfile(fobj)
2646 fobj.seek(0)
2647 self._test(names=["foo", "bar"], fileobj=fobj)
2648
2649 def test_existing(self):
2650 self._create_testtar()
2651 self._add_testfile()
2652 self._test(names=["foo", "bar"])
2653
2654 # Append mode is supposed to fail if the tarfile to append to
2655 # does not end with a zero block.
2656 def _test_error(self, data):
2657 with open(self.tarname, "wb") as fobj:
2658 fobj.write(data)
2659 self.assertRaises(tarfile.ReadError, self._add_testfile)
2660
2661 def test_null(self):
2662 self._test_error(b"")
2663
2664 def test_incomplete(self):
2665 self._test_error(b"\0" * 13)
2666
2667 def test_premature_eof(self):
2668 data = tarfile.TarInfo("foo").tobuf()
2669 self._test_error(data)
2670
2671 def test_trailing_garbage(self):
2672 data = tarfile.TarInfo("foo").tobuf()
2673 self._test_error(data + b"\0" * 13)
2674
2675 def test_invalid(self):
2676 self._test_error(b"a" * 512)
2677
2678 class GzipAppendTest(GzipTest, AppendTestBase, unittest.TestCase):
2679 pass
2680
2681 class Bz2AppendTest(Bz2Test, AppendTestBase, unittest.TestCase):
2682 pass
2683
2684 class LzmaAppendTest(LzmaTest, AppendTestBase, unittest.TestCase):
2685 pass
2686
2687 class ZstdAppendTest(ZstdTest, AppendTestBase, unittest.TestCase):
2688 pass
2689
2690 class LimitsTest(unittest.TestCase):
2691
2692 def test_ustar_limits(self):
2693 # 100 char name
2694 tarinfo = tarfile.TarInfo("0123456789" * 10)
2695 tarinfo.tobuf(tarfile.USTAR_FORMAT)
2696
2697 # 101 char name that cannot be stored
2698 tarinfo = tarfile.TarInfo("0123456789" * 10 + "0")
2699 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
2700
2701 # 256 char name with a slash at pos 156
2702 tarinfo = tarfile.TarInfo("123/" * 62 + "longname")
2703 tarinfo.tobuf(tarfile.USTAR_FORMAT)
2704
2705 # 256 char name that cannot be stored
2706 tarinfo = tarfile.TarInfo("1234567/" * 31 + "longname")
2707 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
2708
2709 # 512 char name
2710 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
2711 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
2712
2713 # 512 char linkname
2714 tarinfo = tarfile.TarInfo("longlink")
2715 tarinfo.linkname = "123/" * 126 + "longname"
2716 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
2717
2718 # uid > 8 digits
2719 tarinfo = tarfile.TarInfo("name")
2720 tarinfo.uid = 0o10000000
2721 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.USTAR_FORMAT)
2722
2723 def test_gnu_limits(self):
2724 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
2725 tarinfo.tobuf(tarfile.GNU_FORMAT)
2726
2727 tarinfo = tarfile.TarInfo("longlink")
2728 tarinfo.linkname = "123/" * 126 + "longname"
2729 tarinfo.tobuf(tarfile.GNU_FORMAT)
2730
2731 # uid >= 256 ** 7
2732 tarinfo = tarfile.TarInfo("name")
2733 tarinfo.uid = 0o4000000000000000000
2734 self.assertRaises(ValueError, tarinfo.tobuf, tarfile.GNU_FORMAT)
2735
2736 def test_pax_limits(self):
2737 tarinfo = tarfile.TarInfo("123/" * 126 + "longname")
2738 tarinfo.tobuf(tarfile.PAX_FORMAT)
2739
2740 tarinfo = tarfile.TarInfo("longlink")
2741 tarinfo.linkname = "123/" * 126 + "longname"
2742 tarinfo.tobuf(tarfile.PAX_FORMAT)
2743
2744 tarinfo = tarfile.TarInfo("name")
2745 tarinfo.uid = 0o4000000000000000000
2746 tarinfo.tobuf(tarfile.PAX_FORMAT)
2747
2748
2749 class MiscTest(unittest.TestCase):
2750
2751 def test_char_fields(self):
2752 self.assertEqual(tarfile.stn("foo", 8, "ascii", "strict"),
2753 b"foo\0\0\0\0\0")
2754 self.assertEqual(tarfile.stn("foobar", 3, "ascii", "strict"),
2755 b"foo")
2756 self.assertEqual(tarfile.nts(b"foo\0\0\0\0\0", "ascii", "strict"),
2757 "foo")
2758 self.assertEqual(tarfile.nts(b"foo\0bar\0", "ascii", "strict"),
2759 "foo")
2760
2761 def test_read_number_fields(self):
2762 # Issue 13158: Test if GNU tar specific base-256 number fields
2763 # are decoded correctly.
2764 self.assertEqual(tarfile.nti(b"0000001\x00"), 1)
2765 self.assertEqual(tarfile.nti(b"7777777\x00"), 0o7777777)
2766 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\x00\x20\x00\x00"),
2767 0o10000000)
2768 self.assertEqual(tarfile.nti(b"\x80\x00\x00\x00\xff\xff\xff\xff"),
2769 0xffffffff)
2770 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\xff"),
2771 -1)
2772 self.assertEqual(tarfile.nti(b"\xff\xff\xff\xff\xff\xff\xff\x9c"),
2773 -100)
2774 self.assertEqual(tarfile.nti(b"\xff\x00\x00\x00\x00\x00\x00\x00"),
2775 -0x100000000000000)
2776
2777 # Issue 24514: Test if empty number fields are converted to zero.
2778 self.assertEqual(tarfile.nti(b"\0"), 0)
2779 self.assertEqual(tarfile.nti(b" \0"), 0)
2780
2781 def test_write_number_fields(self):
2782 self.assertEqual(tarfile.itn(1), b"0000001\x00")
2783 self.assertEqual(tarfile.itn(0o7777777), b"7777777\x00")
2784 self.assertEqual(tarfile.itn(0o10000000, format=tarfile.GNU_FORMAT),
2785 b"\x80\x00\x00\x00\x00\x20\x00\x00")
2786 self.assertEqual(tarfile.itn(0xffffffff, format=tarfile.GNU_FORMAT),
2787 b"\x80\x00\x00\x00\xff\xff\xff\xff")
2788 self.assertEqual(tarfile.itn(-1, format=tarfile.GNU_FORMAT),
2789 b"\xff\xff\xff\xff\xff\xff\xff\xff")
2790 self.assertEqual(tarfile.itn(-100, format=tarfile.GNU_FORMAT),
2791 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2792 self.assertEqual(tarfile.itn(-0x100000000000000,
2793 format=tarfile.GNU_FORMAT),
2794 b"\xff\x00\x00\x00\x00\x00\x00\x00")
2795
2796 # Issue 32713: Test if itn() supports float values outside the
2797 # non-GNU format range
2798 self.assertEqual(tarfile.itn(-100.0, format=tarfile.GNU_FORMAT),
2799 b"\xff\xff\xff\xff\xff\xff\xff\x9c")
2800 self.assertEqual(tarfile.itn(8 ** 12 + 0.0, format=tarfile.GNU_FORMAT),
2801 b"\x80\x00\x00\x10\x00\x00\x00\x00")
2802 self.assertEqual(tarfile.nti(tarfile.itn(-0.1, format=tarfile.GNU_FORMAT)), 0)
2803
2804 def test_number_field_limits(self):
2805 with self.assertRaises(ValueError):
2806 tarfile.itn(-1, 8, tarfile.USTAR_FORMAT)
2807 with self.assertRaises(ValueError):
2808 tarfile.itn(0o10000000, 8, tarfile.USTAR_FORMAT)
2809 with self.assertRaises(ValueError):
2810 tarfile.itn(-0x10000000001, 6, tarfile.GNU_FORMAT)
2811 with self.assertRaises(ValueError):
2812 tarfile.itn(0x10000000000, 6, tarfile.GNU_FORMAT)
2813
2814 def test__all__(self):
2815 not_exported = {
2816 'version', 'grp', 'pwd', 'symlink_exception', 'NUL', 'BLOCKSIZE',
2817 'RECORDSIZE', 'GNU_MAGIC', 'POSIX_MAGIC', 'LENGTH_NAME',
2818 'LENGTH_LINK', 'LENGTH_PREFIX', 'REGTYPE', 'AREGTYPE', 'LNKTYPE',
2819 'SYMTYPE', 'CHRTYPE', 'BLKTYPE', 'DIRTYPE', 'FIFOTYPE', 'CONTTYPE',
2820 'GNUTYPE_LONGNAME', 'GNUTYPE_LONGLINK', 'GNUTYPE_SPARSE',
2821 'XHDTYPE', 'XGLTYPE', 'SOLARIS_XHDTYPE', 'SUPPORTED_TYPES',
2822 'REGULAR_TYPES', 'GNU_TYPES', 'PAX_FIELDS', 'PAX_NAME_FIELDS',
2823 'PAX_NUMBER_FIELDS', 'stn', 'nts', 'nti', 'itn', 'calc_chksums',
2824 'copyfileobj', 'filemode', 'EmptyHeaderError',
2825 'TruncatedHeaderError', 'EOFHeaderError', 'InvalidHeaderError',
2826 'SubsequentHeaderError', 'ExFileObject', 'main'}
2827 support.check__all__(self, tarfile, not_exported=not_exported)
2828
2829 def test_useful_error_message_when_modules_missing(self):
2830 fname = os.path.join(os.path.dirname(__file__), 'archivetestdata', 'testtar.tar.xz')
2831 with self.assertRaises(tarfile.ReadError) as excinfo:
2832 error = tarfile.CompressionError('lzma module is not available'),
2833 with unittest.mock.patch.object(tarfile.TarFile, 'xzopen', side_effect=error):
2834 tarfile.open(fname)
2835
2836 self.assertIn(
2837 "\n- method xz: CompressionError('lzma module is not available')\n",
2838 str(excinfo.exception),
2839 )
2840
2841 @unittest.skipUnless(os_helper.can_symlink(), 'requires symlink support')
2842 @unittest.skipUnless(hasattr(os, 'chmod'), "missing os.chmod")
2843 @unittest.mock.patch('os.chmod')
2844 def test_deferred_directory_attributes_update(self, mock_chmod):
2845 # Regression test for gh-127987: setting attributes on arbitrary files
2846 tempdir = os.path.join(TEMPDIR, 'test127987')
2847 def mock_chmod_side_effect(path, mode, **kwargs):
2848 target_path = os.path.realpath(path)
2849 if os.path.commonpath([target_path, tempdir]) != tempdir:
2850 raise Exception("should not try to chmod anything outside the destination", target_path)
2851 mock_chmod.side_effect = mock_chmod_side_effect
2852
2853 outside_tree_dir = os.path.join(TEMPDIR, 'outside_tree_dir')
2854 with ArchiveMaker() as arc:
2855 arc.add('x', symlink_to='.')
2856 arc.add('x', type=tarfile.DIRTYPE, mode='?rwsrwsrwt')
2857 arc.add('x', symlink_to=outside_tree_dir)
2858
2859 os.makedirs(outside_tree_dir)
2860 try:
2861 arc.open().extractall(path=tempdir, filter='tar')
2862 finally:
2863 os_helper.rmtree(outside_tree_dir)
2864 os_helper.rmtree(tempdir)
2865
2866
2867 class CommandLineTest(unittest.TestCase):
2868
2869 def tarfilecmd(self, *args, **kwargs):
2870 rc, out, err = script_helper.assert_python_ok('-m', 'backports.zstd.tarfile', *args,
2871 **kwargs)
2872 return out.replace(os.linesep.encode(), b'\n')
2873
2874 def tarfilecmd_failure(self, *args):
2875 return script_helper.assert_python_failure('-m', 'backports.zstd.tarfile', *args)
2876
2877 def make_simple_tarfile(self, tar_name):
2878 files = [support.findfile('tokenize_tests.txt',
2879 subdir='tokenizedata'),
2880 support.findfile('tokenize_tests-no-coding-cookie-'
2881 'and-utf8-bom-sig-only.txt',
2882 subdir='tokenizedata')]
2883 self.addCleanup(os_helper.unlink, tar_name)
2884 with tarfile.open(tar_name, 'w') as tf:
2885 for tardata in files:
2886 tf.add(tardata, arcname=os.path.basename(tardata))
2887
2888 def make_evil_tarfile(self, tar_name):
2889 self.addCleanup(os_helper.unlink, tar_name)
2890 with tarfile.open(tar_name, 'w') as tf:
2891 benign = tarfile.TarInfo('benign')
2892 tf.addfile(benign, fileobj=io.BytesIO(b''))
2893 evil = tarfile.TarInfo('../evil')
2894 tf.addfile(evil, fileobj=io.BytesIO(b''))
2895
2896 def test_bad_use(self):
2897 rc, out, err = self.tarfilecmd_failure()
2898 self.assertEqual(out, b'')
2899 self.assertIn(b'usage', err.lower())
2900 self.assertIn(b'error', err.lower())
2901 self.assertIn(b'required', err.lower())
2902 rc, out, err = self.tarfilecmd_failure('-l', '')
2903 self.assertEqual(out, b'')
2904 self.assertNotEqual(err.strip(), b'')
2905
2906 def test_test_command(self):
2907 for tar_name in testtarnames:
2908 for opt in '-t', '--test':
2909 out = self.tarfilecmd(opt, tar_name)
2910 self.assertEqual(out, b'')
2911
2912 def test_test_command_verbose(self):
2913 for tar_name in testtarnames:
2914 for opt in '-v', '--verbose':
2915 out = self.tarfilecmd(opt, '-t', tar_name,
2916 PYTHONIOENCODING='utf-8')
2917 self.assertIn(b'is a tar archive.\n', out)
2918
2919 def test_test_command_invalid_file(self):
2920 zipname = support.findfile('zipdir.zip', subdir='archivetestdata')
2921 rc, out, err = self.tarfilecmd_failure('-t', zipname)
2922 self.assertIn(b' is not a tar archive.', err)
2923 self.assertEqual(out, b'')
2924 self.assertEqual(rc, 1)
2925
2926 for tar_name in testtarnames:
2927 with self.subTest(tar_name=tar_name):
2928 with open(tar_name, 'rb') as f:
2929 data = f.read()
2930 try:
2931 with open(tmpname, 'wb') as f:
2932 f.write(data[:511])
2933 rc, out, err = self.tarfilecmd_failure('-t', tmpname)
2934 self.assertEqual(out, b'')
2935 self.assertEqual(rc, 1)
2936 finally:
2937 os_helper.unlink(tmpname)
2938
2939 def test_list_command(self):
2940 for tar_name in testtarnames:
2941 with support.captured_stdout() as t:
2942 with tarfile.open(tar_name, 'r') as tf:
2943 tf.list(verbose=False)
2944 expected = t.getvalue().encode('ascii', 'backslashreplace')
2945 for opt in '-l', '--list':
2946 out = self.tarfilecmd(opt, tar_name,
2947 PYTHONIOENCODING='ascii')
2948 self.assertEqual(out, expected)
2949
2950 def test_list_command_verbose(self):
2951 for tar_name in testtarnames:
2952 with support.captured_stdout() as t:
2953 with tarfile.open(tar_name, 'r') as tf:
2954 tf.list(verbose=True)
2955 expected = t.getvalue().encode('ascii', 'backslashreplace')
2956 for opt in '-v', '--verbose':
2957 out = self.tarfilecmd(opt, '-l', tar_name,
2958 PYTHONIOENCODING='ascii')
2959 self.assertEqual(out, expected)
2960
2961 def test_list_command_invalid_file(self):
2962 zipname = support.findfile('zipdir.zip', subdir='archivetestdata')
2963 rc, out, err = self.tarfilecmd_failure('-l', zipname)
2964 self.assertIn(b' is not a tar archive.', err)
2965 self.assertEqual(out, b'')
2966 self.assertEqual(rc, 1)
2967
2968 def test_create_command(self):
2969 files = [support.findfile('tokenize_tests.txt',
2970 subdir='tokenizedata'),
2971 support.findfile('tokenize_tests-no-coding-cookie-'
2972 'and-utf8-bom-sig-only.txt',
2973 subdir='tokenizedata')]
2974 for opt in '-c', '--create':
2975 try:
2976 out = self.tarfilecmd(opt, tmpname, *files)
2977 self.assertEqual(out, b'')
2978 with tarfile.open(tmpname) as tar:
2979 tar.getmembers()
2980 finally:
2981 os_helper.unlink(tmpname)
2982
2983 def test_create_command_verbose(self):
2984 files = [support.findfile('tokenize_tests.txt',
2985 subdir='tokenizedata'),
2986 support.findfile('tokenize_tests-no-coding-cookie-'
2987 'and-utf8-bom-sig-only.txt',
2988 subdir='tokenizedata')]
2989 for opt in '-v', '--verbose':
2990 try:
2991 out = self.tarfilecmd(opt, '-c', tmpname, *files,
2992 PYTHONIOENCODING='utf-8')
2993 self.assertIn(b' file created.', out)
2994 with tarfile.open(tmpname) as tar:
2995 tar.getmembers()
2996 finally:
2997 os_helper.unlink(tmpname)
2998
2999 def test_create_command_dotless_filename(self):
3000 files = [support.findfile('tokenize_tests.txt', subdir='tokenizedata')]
3001 try:
3002 out = self.tarfilecmd('-c', dotlessname, *files)
3003 self.assertEqual(out, b'')
3004 with tarfile.open(dotlessname) as tar:
3005 tar.getmembers()
3006 finally:
3007 os_helper.unlink(dotlessname)
3008
3009 def test_create_command_dot_started_filename(self):
3010 tar_name = os.path.join(TEMPDIR, ".testtar")
3011 files = [support.findfile('tokenize_tests.txt', subdir='tokenizedata')]
3012 try:
3013 out = self.tarfilecmd('-c', tar_name, *files)
3014 self.assertEqual(out, b'')
3015 with tarfile.open(tar_name) as tar:
3016 tar.getmembers()
3017 finally:
3018 os_helper.unlink(tar_name)
3019
3020 def test_create_command_compressed(self):
3021 files = [support.findfile('tokenize_tests.txt',
3022 subdir='tokenizedata'),
3023 support.findfile('tokenize_tests-no-coding-cookie-'
3024 'and-utf8-bom-sig-only.txt',
3025 subdir='tokenizedata')]
3026 for filetype in (GzipTest, Bz2Test, LzmaTest, ZstdTest):
3027 if not filetype.open:
3028 continue
3029 try:
3030 tar_name = tmpname + '.' + filetype.suffix
3031 out = self.tarfilecmd('-c', tar_name, *files)
3032 with filetype.taropen(tar_name) as tar:
3033 tar.getmembers()
3034 finally:
3035 os_helper.unlink(tar_name)
3036
3037 def test_extract_command(self):
3038 self.make_simple_tarfile(tmpname)
3039 for opt in '-e', '--extract':
3040 try:
3041 with os_helper.temp_cwd(tarextdir):
3042 out = self.tarfilecmd(opt, tmpname)
3043 self.assertEqual(out, b'')
3044 finally:
3045 os_helper.rmtree(tarextdir)
3046
3047 def test_extract_command_verbose(self):
3048 self.make_simple_tarfile(tmpname)
3049 for opt in '-v', '--verbose':
3050 try:
3051 with os_helper.temp_cwd(tarextdir):
3052 out = self.tarfilecmd(opt, '-e', tmpname,
3053 PYTHONIOENCODING='utf-8')
3054 self.assertIn(b' file is extracted.', out)
3055 finally:
3056 os_helper.rmtree(tarextdir)
3057
3058 def test_extract_command_filter(self):
3059 self.make_evil_tarfile(tmpname)
3060 # Make an inner directory, so the member named '../evil'
3061 # is still extracted into `tarextdir`
3062 destdir = os.path.join(tarextdir, 'dest')
3063 os.mkdir(tarextdir)
3064 try:
3065 with os_helper.temp_cwd(destdir):
3066 self.tarfilecmd_failure('-e', tmpname,
3067 '-v',
3068 '--filter', 'data')
3069 out = self.tarfilecmd('-e', tmpname,
3070 '-v',
3071 '--filter', 'fully_trusted',
3072 PYTHONIOENCODING='utf-8')
3073 self.assertIn(b' file is extracted.', out)
3074 finally:
3075 os_helper.rmtree(tarextdir)
3076
3077 def test_extract_command_different_directory(self):
3078 self.make_simple_tarfile(tmpname)
3079 try:
3080 with os_helper.temp_cwd(tarextdir):
3081 out = self.tarfilecmd('-e', tmpname, 'spamdir')
3082 self.assertEqual(out, b'')
3083 finally:
3084 os_helper.rmtree(tarextdir)
3085
3086 def test_extract_command_invalid_file(self):
3087 zipname = support.findfile('zipdir.zip', subdir='archivetestdata')
3088 with os_helper.temp_cwd(tarextdir):
3089 rc, out, err = self.tarfilecmd_failure('-e', zipname)
3090 self.assertIn(b' is not a tar archive.', err)
3091 self.assertEqual(out, b'')
3092 self.assertEqual(rc, 1)
3093
3094
3095 class ContextManagerTest(unittest.TestCase):
3096
3097 def test_basic(self):
3098 with tarfile.open(tarname) as tar:
3099 self.assertFalse(tar.closed, "closed inside runtime context")
3100 self.assertTrue(tar.closed, "context manager failed")
3101
3102 def test_closed(self):
3103 # The __enter__() method is supposed to raise OSError
3104 # if the TarFile object is already closed.
3105 tar = tarfile.open(tarname)
3106 tar.close()
3107 with self.assertRaises(OSError):
3108 with tar:
3109 pass
3110
3111 def test_exception(self):
3112 # Test if the OSError exception is passed through properly.
3113 with self.assertRaises(Exception) as exc:
3114 with tarfile.open(tarname) as tar:
3115 raise OSError
3116 self.assertIsInstance(exc.exception, OSError,
3117 "wrong exception raised in context manager")
3118 self.assertTrue(tar.closed, "context manager failed")
3119
3120 def test_no_eof(self):
3121 # __exit__() must not write end-of-archive blocks if an
3122 # exception was raised.
3123 try:
3124 with tarfile.open(tmpname, "w") as tar:
3125 raise Exception
3126 except:
3127 pass
3128 self.assertEqual(os.path.getsize(tmpname), 0,
3129 "context manager wrote an end-of-archive block")
3130 self.assertTrue(tar.closed, "context manager failed")
3131
3132 def test_eof(self):
3133 # __exit__() must write end-of-archive blocks, i.e. call
3134 # TarFile.close() if there was no error.
3135 with tarfile.open(tmpname, "w"):
3136 pass
3137 self.assertNotEqual(os.path.getsize(tmpname), 0,
3138 "context manager wrote no end-of-archive block")
3139
3140 def test_fileobj(self):
3141 # Test that __exit__() did not close the external file
3142 # object.
3143 with open(tmpname, "wb") as fobj:
3144 try:
3145 with tarfile.open(fileobj=fobj, mode="w") as tar:
3146 raise Exception
3147 except:
3148 pass
3149 self.assertFalse(fobj.closed, "external file object was closed")
3150 self.assertTrue(tar.closed, "context manager failed")
3151
3152
3153 @unittest.skipIf(hasattr(os, "link"), "requires os.link to be missing")
3154 class LinkEmulationTest(ReadTest, unittest.TestCase):
3155
3156 # Test for issue #8741 regression. On platforms that do not support
3157 # symbolic or hard links tarfile tries to extract these types of members
3158 # as the regular files they point to.
3159 def _test_link_extraction(self, name):
3160 self.tar.extract(name, TEMPDIR, filter='fully_trusted')
3161 with open(os.path.join(TEMPDIR, name), "rb") as f:
3162 data = f.read()
3163 self.assertEqual(sha256sum(data), sha256_regtype)
3164
3165 # See issues #1578269, #8879, and #17689 for some history on these skips
3166 @unittest.skipIf(hasattr(os.path, "islink"),
3167 "Skip emulation - has os.path.islink but not os.link")
3168 def test_hardlink_extraction1(self):
3169 self._test_link_extraction("ustar/lnktype")
3170
3171 @unittest.skipIf(hasattr(os.path, "islink"),
3172 "Skip emulation - has os.path.islink but not os.link")
3173 def test_hardlink_extraction2(self):
3174 self._test_link_extraction("./ustar/linktest2/lnktype")
3175
3176 @unittest.skipIf(hasattr(os, "symlink"),
3177 "Skip emulation if symlink exists")
3178 def test_symlink_extraction1(self):
3179 self._test_link_extraction("ustar/symtype")
3180
3181 @unittest.skipIf(hasattr(os, "symlink"),
3182 "Skip emulation if symlink exists")
3183 def test_symlink_extraction2(self):
3184 self._test_link_extraction("./ustar/linktest2/symtype")
3185
3186
3187 class Bz2PartialReadTest(Bz2Test, unittest.TestCase):
3188 # Issue5068: The _BZ2Proxy.read() method loops forever
3189 # on an empty or partial bzipped file.
3190
3191 def _test_partial_input(self, mode):
3192 class MyBytesIO(io.BytesIO):
3193 hit_eof = False
3194 def read(self, n):
3195 if self.hit_eof:
3196 raise AssertionError("infinite loop detected in "
3197 "tarfile.open()")
3198 self.hit_eof = self.tell() == len(self.getvalue())
3199 return super(MyBytesIO, self).read(n)
3200 def seek(self, *args):
3201 self.hit_eof = False
3202 return super(MyBytesIO, self).seek(*args)
3203
3204 data = bz2.compress(tarfile.TarInfo("foo").tobuf())
3205 for x in range(len(data) + 1):
3206 try:
3207 tarfile.open(fileobj=MyBytesIO(data[:x]), mode=mode)
3208 except tarfile.ReadError:
3209 pass # we have no interest in ReadErrors
3210
3211 def test_partial_input(self):
3212 self._test_partial_input("r")
3213
3214 def test_partial_input_bz2(self):
3215 self._test_partial_input("r:bz2")
3216
3217
3218 def root_is_uid_gid_0():
3219 try:
3220 import pwd, grp
3221 except ImportError:
3222 return False
3223 if pwd.getpwuid(0)[0] != 'root':
3224 return False
3225 if grp.getgrgid(0)[0] != 'root':
3226 return False
3227 return True
3228
3229
3230 @unittest.skipUnless(hasattr(os, 'chown'), "missing os.chown")
3231 @unittest.skipUnless(hasattr(os, 'geteuid'), "missing os.geteuid")
3232 class NumericOwnerTest(unittest.TestCase):
3233 # mock the following:
3234 # os.chown: so we can test what's being called
3235 # os.chmod: so the modes are not actually changed. if they are, we can't
3236 # delete the files/directories
3237 # os.geteuid: so we can lie and say we're root (uid = 0)
3238
3239 @staticmethod
3240 def _make_test_archive(filename_1, dirname_1, filename_2):
3241 # the file contents to write
3242 fobj = io.BytesIO(b"content")
3243
3244 # create a tar file with a file, a directory, and a file within that
3245 # directory. Assign various .uid/.gid values to them
3246 items = [(filename_1, 99, 98, tarfile.REGTYPE, fobj),
3247 (dirname_1, 77, 76, tarfile.DIRTYPE, None),
3248 (filename_2, 88, 87, tarfile.REGTYPE, fobj),
3249 ]
3250 with tarfile.open(tmpname, 'w') as tarfl:
3251 for name, uid, gid, typ, contents in items:
3252 t = tarfile.TarInfo(name)
3253 t.uid = uid
3254 t.gid = gid
3255 t.uname = 'root'
3256 t.gname = 'root'
3257 t.type = typ
3258 tarfl.addfile(t, contents)
3259
3260 # return the full pathname to the tar file
3261 return tmpname
3262
3263 @staticmethod
3264 @contextmanager
3265 def _setup_test(mock_geteuid):
3266 mock_geteuid.return_value = 0 # lie and say we're root
3267 fname = 'numeric-owner-testfile'
3268 dirname = 'dir'
3269
3270 # the names we want stored in the tarfile
3271 filename_1 = fname
3272 dirname_1 = dirname
3273 filename_2 = os.path.join(dirname, fname)
3274
3275 # create the tarfile with the contents we're after
3276 tar_filename = NumericOwnerTest._make_test_archive(filename_1,
3277 dirname_1,
3278 filename_2)
3279
3280 # open the tarfile for reading. yield it and the names of the items
3281 # we stored into the file
3282 with tarfile.open(tar_filename) as tarfl:
3283 yield tarfl, filename_1, dirname_1, filename_2
3284
3285 @unittest.mock.patch('os.chown')
3286 @unittest.mock.patch('os.chmod')
3287 @unittest.mock.patch('os.geteuid')
3288 def test_extract_with_numeric_owner(self, mock_geteuid, mock_chmod,
3289 mock_chown):
3290 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _,
3291 filename_2):
3292 tarfl.extract(filename_1, TEMPDIR, numeric_owner=True,
3293 filter='fully_trusted')
3294 tarfl.extract(filename_2 , TEMPDIR, numeric_owner=True,
3295 filter='fully_trusted')
3296
3297 # convert to filesystem paths
3298 f_filename_1 = os.path.join(TEMPDIR, filename_1)
3299 f_filename_2 = os.path.join(TEMPDIR, filename_2)
3300
3301 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
3302 unittest.mock.call(f_filename_2, 88, 87),
3303 ],
3304 any_order=True)
3305
3306 @unittest.mock.patch('os.chown')
3307 @unittest.mock.patch('os.chmod')
3308 @unittest.mock.patch('os.geteuid')
3309 def test_extractall_with_numeric_owner(self, mock_geteuid, mock_chmod,
3310 mock_chown):
3311 with self._setup_test(mock_geteuid) as (tarfl, filename_1, dirname_1,
3312 filename_2):
3313 tarfl.extractall(TEMPDIR, numeric_owner=True,
3314 filter='fully_trusted')
3315
3316 # convert to filesystem paths
3317 f_filename_1 = os.path.join(TEMPDIR, filename_1)
3318 f_dirname_1 = os.path.join(TEMPDIR, dirname_1)
3319 f_filename_2 = os.path.join(TEMPDIR, filename_2)
3320
3321 mock_chown.assert_has_calls([unittest.mock.call(f_filename_1, 99, 98),
3322 unittest.mock.call(f_dirname_1, 77, 76),
3323 unittest.mock.call(f_filename_2, 88, 87),
3324 ],
3325 any_order=True)
3326
3327 # this test requires that uid=0 and gid=0 really be named 'root'. that's
3328 # because the uname and gname in the test file are 'root', and extract()
3329 # will look them up using pwd and grp to find their uid and gid, which we
3330 # test here to be 0.
3331 @unittest.skipUnless(root_is_uid_gid_0(),
3332 'uid=0,gid=0 must be named "root"')
3333 @unittest.mock.patch('os.chown')
3334 @unittest.mock.patch('os.chmod')
3335 @unittest.mock.patch('os.geteuid')
3336 def test_extract_without_numeric_owner(self, mock_geteuid, mock_chmod,
3337 mock_chown):
3338 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
3339 tarfl.extract(filename_1, TEMPDIR, numeric_owner=False,
3340 filter='fully_trusted')
3341
3342 # convert to filesystem paths
3343 f_filename_1 = os.path.join(TEMPDIR, filename_1)
3344
3345 mock_chown.assert_called_with(f_filename_1, 0, 0)
3346
3347 @unittest.mock.patch('os.geteuid')
3348 def test_keyword_only(self, mock_geteuid):
3349 with self._setup_test(mock_geteuid) as (tarfl, filename_1, _, _):
3350 self.assertRaises(TypeError,
3351 tarfl.extract, filename_1, TEMPDIR, False, True)
3352
3353
3354 class ReplaceTests(ReadTest, unittest.TestCase):
3355 def test_replace_name(self):
3356 member = self.tar.getmember('ustar/regtype')
3357 replaced = member.replace(name='misc/other')
3358 self.assertEqual(replaced.name, 'misc/other')
3359 self.assertEqual(member.name, 'ustar/regtype')
3360 self.assertEqual(self.tar.getmember('ustar/regtype').name,
3361 'ustar/regtype')
3362
3363 def test_replace_deep(self):
3364 member = self.tar.getmember('pax/regtype1')
3365 replaced = member.replace()
3366 replaced.pax_headers['gname'] = 'not-bar'
3367 self.assertEqual(member.pax_headers['gname'], 'bar')
3368 self.assertEqual(
3369 self.tar.getmember('pax/regtype1').pax_headers['gname'], 'bar')
3370
3371 def test_replace_shallow(self):
3372 member = self.tar.getmember('pax/regtype1')
3373 replaced = member.replace(deep=False)
3374 replaced.pax_headers['gname'] = 'not-bar'
3375 self.assertEqual(member.pax_headers['gname'], 'not-bar')
3376 self.assertEqual(
3377 self.tar.getmember('pax/regtype1').pax_headers['gname'], 'not-bar')
3378
3379 def test_replace_all(self):
3380 member = self.tar.getmember('ustar/regtype')
3381 for attr_name in ('name', 'mtime', 'mode', 'linkname',
3382 'uid', 'gid', 'uname', 'gname'):
3383 with self.subTest(attr_name=attr_name):
3384 replaced = member.replace(**{attr_name: None})
3385 self.assertEqual(getattr(replaced, attr_name), None)
3386 self.assertNotEqual(getattr(member, attr_name), None)
3387
3388 def test_replace_internal(self):
3389 member = self.tar.getmember('ustar/regtype')
3390 with self.assertRaises(TypeError):
3391 member.replace(offset=123456789)
3392
3393
3394 class NoneInfoExtractTests(ReadTest):
3395 # These mainly check that all kinds of members are extracted successfully
3396 # if some metadata is None.
3397 # Some of the methods do additional spot checks.
3398
3399 # We also test that the default filters can deal with None.
3400
3401 extraction_filter = None
3402
3403 @classmethod
3404 def setUpClass(cls):
3405 tar = tarfile.open(tarname, mode='r', encoding="iso8859-1")
3406 cls.control_dir = pathlib.Path(TEMPDIR) / "extractall_ctrl"
3407 tar.errorlevel = 0
3408 with ExitStack() as cm:
3409 if cls.extraction_filter is None:
3410 if sys.version_info >= (3, 11):
3411 cm.enter_context(warnings.catch_warnings(
3412 action="ignore", category=DeprecationWarning))
3413 else:
3414 cm.enter_context(warnings.catch_warnings())
3415 tar.extractall(cls.control_dir, filter=cls.extraction_filter)
3416 tar.close()
3417 cls.control_paths = set(
3418 p.relative_to(cls.control_dir)
3419 for p in pathlib.Path(cls.control_dir).glob('**/*'))
3420
3421 @classmethod
3422 def tearDownClass(cls):
3423 shutil.rmtree(cls.control_dir)
3424
3425 def check_files_present(self, directory):
3426 got_paths = set(
3427 p.relative_to(directory)
3428 for p in pathlib.Path(directory).glob('**/*'))
3429 if self.extraction_filter in (None, 'data'):
3430 # The 'data' filter is expected to reject special files
3431 for path in 'ustar/fifotype', 'ustar/blktype', 'ustar/chrtype':
3432 got_paths.discard(pathlib.Path(path))
3433 self.assertEqual(self.control_paths, got_paths)
3434
3435 @contextmanager
3436 def extract_with_none(self, *attr_names):
3437 DIR = pathlib.Path(TEMPDIR) / "extractall_none"
3438 self.tar.errorlevel = 0
3439 for member in self.tar.getmembers():
3440 for attr_name in attr_names:
3441 setattr(member, attr_name, None)
3442 with os_helper.temp_dir(DIR):
3443 self.tar.extractall(DIR, filter='fully_trusted')
3444 self.check_files_present(DIR)
3445 yield DIR
3446
3447 def test_extractall_none_mtime(self):
3448 # mtimes of extracted files should be later than 'now' -- the mtime
3449 # of a previously created directory.
3450 now = pathlib.Path(TEMPDIR).stat().st_mtime
3451 with self.extract_with_none('mtime') as DIR:
3452 for path in pathlib.Path(DIR).glob('**/*'):
3453 with self.subTest(path=path):
3454 try:
3455 mtime = path.stat().st_mtime
3456 except OSError:
3457 # Some systems can't stat symlinks, ignore those
3458 if not path.is_symlink():
3459 raise
3460 else:
3461 self.assertGreaterEqual(path.stat().st_mtime, now)
3462
3463 def test_extractall_none_mode(self):
3464 # modes of directories and regular files should match the mode
3465 # of a "normally" created directory or regular file
3466 dir_mode = pathlib.Path(TEMPDIR).stat().st_mode
3467 regular_file = pathlib.Path(TEMPDIR) / 'regular_file'
3468 regular_file.write_text('')
3469 regular_file_mode = regular_file.stat().st_mode
3470 with self.extract_with_none('mode') as DIR:
3471 for path in pathlib.Path(DIR).glob('**/*'):
3472 with self.subTest(path=path):
3473 if path.is_dir():
3474 self.assertEqual(path.stat().st_mode, dir_mode)
3475 elif path.is_file():
3476 self.assertEqual(path.stat().st_mode,
3477 regular_file_mode)
3478
3479 def test_extractall_none_uid(self):
3480 with self.extract_with_none('uid'):
3481 pass
3482
3483 def test_extractall_none_gid(self):
3484 with self.extract_with_none('gid'):
3485 pass
3486
3487 def test_extractall_none_uname(self):
3488 with self.extract_with_none('uname'):
3489 pass
3490
3491 def test_extractall_none_gname(self):
3492 with self.extract_with_none('gname'):
3493 pass
3494
3495 def test_extractall_none_ownership(self):
3496 with self.extract_with_none('uid', 'gid', 'uname', 'gname'):
3497 pass
3498
3499 class NoneInfoExtractTests_Data(NoneInfoExtractTests, unittest.TestCase):
3500 extraction_filter = 'data'
3501
3502 class NoneInfoExtractTests_FullyTrusted(NoneInfoExtractTests,
3503 unittest.TestCase):
3504 extraction_filter = 'fully_trusted'
3505
3506 class NoneInfoExtractTests_Tar(NoneInfoExtractTests, unittest.TestCase):
3507 extraction_filter = 'tar'
3508
3509 class NoneInfoExtractTests_Default(NoneInfoExtractTests,
3510 unittest.TestCase):
3511 extraction_filter = None
3512
3513 class NoneInfoTests_Misc(unittest.TestCase):
3514 def test_add(self):
3515 # When addfile() encounters None metadata, it raises a ValueError
3516 bio = io.BytesIO()
3517 for tarformat in (tarfile.USTAR_FORMAT, tarfile.GNU_FORMAT,
3518 tarfile.PAX_FORMAT):
3519 with self.subTest(tarformat=tarformat):
3520 tar = tarfile.open(fileobj=bio, mode='w', format=tarformat)
3521 tarinfo = tar.gettarinfo(tarname)
3522 try:
3523 with open(tarname, 'rb') as f:
3524 tar.addfile(tarinfo, f)
3525 except Exception:
3526 if tarformat == tarfile.USTAR_FORMAT:
3527 # In the old, limited format, adding might fail for
3528 # reasons like the UID being too large
3529 pass
3530 else:
3531 raise
3532 else:
3533 for attr_name in ('mtime', 'mode', 'uid', 'gid',
3534 'uname', 'gname'):
3535 with self.subTest(attr_name=attr_name):
3536 replaced = tarinfo.replace(**{attr_name: None})
3537 with self.assertRaisesRegex(ValueError,
3538 f"{attr_name}"):
3539 with open(tarname, 'rb') as f:
3540 tar.addfile(replaced, f)
3541
3542 def test_list(self):
3543 # Change some metadata to None, then compare list() output
3544 # word-for-word. We want list() to not raise, and to only change
3545 # printout for the affected piece of metadata.
3546 # (n.b.: some contents of the test archive are hardcoded.)
3547 for attr_names in ({'mtime'}, {'mode'}, {'uid'}, {'gid'},
3548 {'uname'}, {'gname'},
3549 {'uid', 'uname'}, {'gid', 'gname'}):
3550 with (self.subTest(attr_names=attr_names),
3551 tarfile.open(tarname, encoding="iso8859-1") as tar):
3552 tio_prev = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
3553 with support.swap_attr(sys, 'stdout', tio_prev):
3554 tar.list()
3555 for member in tar.getmembers():
3556 for attr_name in attr_names:
3557 setattr(member, attr_name, None)
3558 tio_new = io.TextIOWrapper(io.BytesIO(), 'ascii', newline='\n')
3559 with support.swap_attr(sys, 'stdout', tio_new):
3560 tar.list()
3561 for expected, got in zip(tio_prev.detach().getvalue().split(),
3562 tio_new.detach().getvalue().split()):
3563 if attr_names == {'mtime'} and re.match(rb'2003-01-\d\d', expected):
3564 self.assertEqual(got, b'????-??-??')
3565 elif attr_names == {'mtime'} and re.match(rb'\d\d:\d\d:\d\d', expected):
3566 self.assertEqual(got, b'??:??:??')
3567 elif attr_names == {'mode'} and re.match(
3568 rb'.([r-][w-][x-]){3}', expected):
3569 self.assertEqual(got, b'??????????')
3570 elif attr_names == {'uname'} and expected.startswith(
3571 (b'tarfile/', b'lars/', b'foo/')):
3572 exp_user, exp_group = expected.split(b'/')
3573 got_user, got_group = got.split(b'/')
3574 self.assertEqual(got_group, exp_group)
3575 self.assertRegex(got_user, b'[0-9]+')
3576 elif attr_names == {'gname'} and expected.endswith(
3577 (b'/tarfile', b'/users', b'/bar')):
3578 exp_user, exp_group = expected.split(b'/')
3579 got_user, got_group = got.split(b'/')
3580 self.assertEqual(got_user, exp_user)
3581 self.assertRegex(got_group, b'[0-9]+')
3582 elif attr_names == {'uid'} and expected.startswith(
3583 (b'1000/')):
3584 exp_user, exp_group = expected.split(b'/')
3585 got_user, got_group = got.split(b'/')
3586 self.assertEqual(got_group, exp_group)
3587 self.assertEqual(got_user, b'None')
3588 elif attr_names == {'gid'} and expected.endswith((b'/100')):
3589 exp_user, exp_group = expected.split(b'/')
3590 got_user, got_group = got.split(b'/')
3591 self.assertEqual(got_user, exp_user)
3592 self.assertEqual(got_group, b'None')
3593 elif attr_names == {'uid', 'uname'} and expected.startswith(
3594 (b'tarfile/', b'lars/', b'foo/', b'1000/')):
3595 exp_user, exp_group = expected.split(b'/')
3596 got_user, got_group = got.split(b'/')
3597 self.assertEqual(got_group, exp_group)
3598 self.assertEqual(got_user, b'None')
3599 elif attr_names == {'gname', 'gid'} and expected.endswith(
3600 (b'/tarfile', b'/users', b'/bar', b'/100')):
3601 exp_user, exp_group = expected.split(b'/')
3602 got_user, got_group = got.split(b'/')
3603 self.assertEqual(got_user, exp_user)
3604 self.assertEqual(got_group, b'None')
3605 else:
3606 # In other cases the output should be the same
3607 self.assertEqual(expected, got)
3608
3609 def _filemode_to_int(mode):
3610 """Inverse of `stat.filemode` (for permission bits)
3611
3612 Using mode strings rather than numbers makes the later tests more readable.
3613 """
3614 str_mode = mode[1:]
3615 result = (
3616 {'r': stat.S_IRUSR, '-': 0}[str_mode[0]]
3617 | {'w': stat.S_IWUSR, '-': 0}[str_mode[1]]
3618 | {'x': stat.S_IXUSR, '-': 0,
3619 's': stat.S_IXUSR | stat.S_ISUID,
3620 'S': stat.S_ISUID}[str_mode[2]]
3621 | {'r': stat.S_IRGRP, '-': 0}[str_mode[3]]
3622 | {'w': stat.S_IWGRP, '-': 0}[str_mode[4]]
3623 | {'x': stat.S_IXGRP, '-': 0,
3624 's': stat.S_IXGRP | stat.S_ISGID,
3625 'S': stat.S_ISGID}[str_mode[5]]
3626 | {'r': stat.S_IROTH, '-': 0}[str_mode[6]]
3627 | {'w': stat.S_IWOTH, '-': 0}[str_mode[7]]
3628 | {'x': stat.S_IXOTH, '-': 0,
3629 't': stat.S_IXOTH | stat.S_ISVTX,
3630 'T': stat.S_ISVTX}[str_mode[8]]
3631 )
3632 # check we did this right
3633 assert stat.filemode(result)[1:] == mode[1:]
3634
3635 return result
3636
3637 class ArchiveMaker:
3638 """Helper to create a tar file with specific contents
3639
3640 Usage:
3641
3642 with ArchiveMaker() as t:
3643 t.add('filename', ...)
3644
3645 with t.open() as tar:
3646 ... # `tar` is now a TarFile with 'filename' in it!
3647 """
3648 def __init__(self, **kwargs):
3649 self.bio = io.BytesIO()
3650 self.tar_kwargs = dict(kwargs)
3651
3652 def __enter__(self):
3653 self.tar_w = tarfile.TarFile(mode='w', fileobj=self.bio, **self.tar_kwargs)
3654 return self
3655
3656 def __exit__(self, *exc):
3657 self.tar_w.close()
3658 self.contents = self.bio.getvalue()
3659 self.bio = None
3660
3661 def add(self, name, *, type=None, symlink_to=None, hardlink_to=None,
3662 mode=None, size=None, content=None, **kwargs):
3663 """Add a member to the test archive. Call within `with`.
3664
3665 Provides many shortcuts:
3666 - default `type` is based on symlink_to, hardlink_to, and trailing `/`
3667 in name (which is stripped)
3668 - size & content defaults are based on each other
3669 - content can be str or bytes
3670 - mode should be textual ('-rwxrwxrwx')
3671
3672 (add more! this is unstable internal test-only API)
3673 """
3674 name = str(name)
3675 tarinfo = tarfile.TarInfo(name).replace(**kwargs)
3676 if content is not None:
3677 if isinstance(content, str):
3678 content = content.encode()
3679 size = len(content)
3680 if size is not None:
3681 tarinfo.size = size
3682 if content is None:
3683 content = bytes(tarinfo.size)
3684 if mode:
3685 tarinfo.mode = _filemode_to_int(mode)
3686 if symlink_to is not None:
3687 type = tarfile.SYMTYPE
3688 tarinfo.linkname = str(symlink_to)
3689 if hardlink_to is not None:
3690 type = tarfile.LNKTYPE
3691 tarinfo.linkname = str(hardlink_to)
3692 if name.endswith('/') and type is None:
3693 type = tarfile.DIRTYPE
3694 if type is not None:
3695 tarinfo.type = type
3696 if tarinfo.isreg():
3697 fileobj = io.BytesIO(content)
3698 else:
3699 fileobj = None
3700 self.tar_w.addfile(tarinfo, fileobj)
3701
3702 def open(self, **kwargs):
3703 """Open the resulting archive as TarFile. Call after `with`."""
3704 bio = io.BytesIO(self.contents)
3705 return tarfile.open(fileobj=bio, **kwargs)
3706
3707 # Under WASI, `os_helper.can_symlink` is False to make
3708 # `skip_unless_symlink` skip symlink tests. "
3709 # But in the following tests we use can_symlink to *determine* which
3710 # behavior is expected.
3711 # Like other symlink tests, skip these on WASI for now.
3712 if support.is_wasi:
3713 def symlink_test(f):
3714 return unittest.skip("WASI: Skip symlink test for now")(f)
3715 else:
3716 def symlink_test(f):
3717 return f
3718
3719
3720 class TestExtractionFilters(unittest.TestCase):
3721
3722 # A temporary directory for the extraction results.
3723 # All files that "escape" the destination path should still end
3724 # up in this directory.
3725 outerdir = pathlib.Path(TEMPDIR) / 'outerdir'
3726
3727 # The destination for the extraction, within `outerdir`
3728 destdir = outerdir / 'dest'
3729
3730 @classmethod
3731 def setUpClass(cls):
3732 # Posix and Windows have different pathname resolution:
3733 # either symlink or a '..' component resolve first.
3734 # Let's see which we are on.
3735 if os_helper.can_symlink():
3736 testpath = os.path.join(TEMPDIR, 'resolution_test')
3737 os.mkdir(testpath)
3738
3739 # testpath/current links to `.` which is all of:
3740 # - `testpath`
3741 # - `testpath/current`
3742 # - `testpath/current/current`
3743 # - etc.
3744 os.symlink('.', os.path.join(testpath, 'current'))
3745
3746 # we'll test where `testpath/current/../file` ends up
3747 with open(os.path.join(testpath, 'current', '..', 'file'), 'w'):
3748 pass
3749
3750 if os.path.exists(os.path.join(testpath, 'file')):
3751 # Windows collapses 'current\..' to '.' first, leaving
3752 # 'testpath\file'
3753 cls.dotdot_resolves_early = True
3754 elif os.path.exists(os.path.join(testpath, '..', 'file')):
3755 # Posix resolves 'current' to '.' first, leaving
3756 # 'testpath/../file'
3757 cls.dotdot_resolves_early = False
3758 else:
3759 raise AssertionError('Could not determine link resolution')
3760 else:
3761 cls.dotdot_resolves_early = False
3762
3763 @contextmanager
3764 def check_context(self, tar, filter, *, check_flag=True):
3765 """Extracts `tar` to `self.destdir` and allows checking the result
3766
3767 If an error occurs, it must be checked using `expect_exception`
3768
3769 Otherwise, all resulting files must be checked using `expect_file`,
3770 except the destination directory itself and parent directories of
3771 other files.
3772 When checking directories, do so before their contents.
3773
3774 A file called 'flag' is made in outerdir (i.e. outside destdir)
3775 before extraction; it should not be altered nor should its contents
3776 be read/copied.
3777 """
3778 with os_helper.temp_dir(self.outerdir):
3779 flag_path = self.outerdir / 'flag'
3780 flag_path.write_text('capture me')
3781 try:
3782 tar.extractall(self.destdir, filter=filter)
3783 except Exception as exc:
3784 self.raised_exception = exc
3785 self.reraise_exception = True
3786 self.expected_paths = set()
3787 else:
3788 self.raised_exception = None
3789 self.reraise_exception = False
3790 self.expected_paths = set(self.outerdir.glob('**/*'))
3791 self.expected_paths.discard(self.destdir)
3792 self.expected_paths.discard(flag_path)
3793 try:
3794 yield self
3795 finally:
3796 tar.close()
3797 if self.reraise_exception:
3798 raise self.raised_exception
3799 self.assertEqual(self.expected_paths, set())
3800 if check_flag:
3801 self.assertEqual(flag_path.read_text(), 'capture me')
3802 else:
3803 assert filter == 'fully_trusted'
3804
3805 def expect_file(self, name, type=None, symlink_to=None, mode=None,
3806 size=None, content=None):
3807 """Check a single file. See check_context."""
3808 if self.raised_exception:
3809 raise self.raised_exception
3810 # use normpath() rather than resolve() so we don't follow symlinks
3811 path = pathlib.Path(os.path.normpath(self.destdir / name))
3812 self.assertIn(path, self.expected_paths)
3813 self.expected_paths.remove(path)
3814 if mode is not None and os_helper.can_chmod() and os.name != 'nt':
3815 got = stat.filemode(stat.S_IMODE(path.stat().st_mode))
3816 self.assertEqual(got, mode)
3817 if type is None and isinstance(name, str) and name.endswith('/'):
3818 type = tarfile.DIRTYPE
3819 if symlink_to is not None:
3820 got = (self.destdir / name).readlink()
3821 expected = pathlib.Path(symlink_to)
3822 # The symlink might be the same (textually) as what we expect,
3823 # but some systems change the link to an equivalent path, so
3824 # we fall back to samefile().
3825 try:
3826 if expected != got:
3827 self.assertTrue(got.samefile(expected))
3828 except Exception as e:
3829 # attach a note, so it's shown even if `samefile` fails
3830 e.add_note(f'{expected=}, {got=}')
3831 raise
3832 elif type == tarfile.REGTYPE or type is None:
3833 self.assertTrue(path.is_file())
3834 elif type == tarfile.DIRTYPE:
3835 self.assertTrue(path.is_dir())
3836 elif type == tarfile.FIFOTYPE:
3837 self.assertTrue(path.is_fifo())
3838 elif type == tarfile.SYMTYPE:
3839 self.assertTrue(path.is_symlink())
3840 else:
3841 raise NotImplementedError(type)
3842 if size is not None:
3843 self.assertEqual(path.stat().st_size, size)
3844 if content is not None:
3845 self.assertEqual(path.read_text(), content)
3846 for parent in path.parents:
3847 self.expected_paths.discard(parent)
3848
3849 def expect_any_tree(self, name):
3850 """Check a directory; forget about its contents."""
3851 tree_path = (self.destdir / name).resolve()
3852 self.expect_file(tree_path, type=tarfile.DIRTYPE)
3853 self.expected_paths = {
3854 p for p in self.expected_paths
3855 if tree_path not in p.parents
3856 }
3857
3858 def expect_exception(self, exc_type, message_re='.'):
3859 with self.assertRaisesRegex(exc_type, message_re):
3860 if self.raised_exception is not None:
3861 raise self.raised_exception
3862 self.reraise_exception = False
3863 return self.raised_exception
3864
3865 def test_benign_file(self):
3866 with ArchiveMaker() as arc:
3867 arc.add('benign.txt')
3868 for filter in 'fully_trusted', 'tar', 'data':
3869 with self.check_context(arc.open(), filter):
3870 self.expect_file('benign.txt')
3871
3872 def test_absolute(self):
3873 # Test handling a member with an absolute path
3874 # Inspired by 'absolute1' in https://github.com/jwilk/traversal-archives
3875 with ArchiveMaker() as arc:
3876 arc.add(self.outerdir / 'escaped.evil')
3877
3878 with self.check_context(arc.open(), 'fully_trusted'):
3879 self.expect_file('../escaped.evil')
3880
3881 for filter in 'tar', 'data':
3882 with self.check_context(arc.open(), filter):
3883 if str(self.outerdir).startswith('/'):
3884 # We strip leading slashes, as e.g. GNU tar does
3885 # (without --absolute-filenames).
3886 outerdir_stripped = str(self.outerdir).lstrip('/')
3887 self.expect_file(f'{outerdir_stripped}/escaped.evil')
3888 else:
3889 # On this system, absolute paths don't have leading
3890 # slashes.
3891 # So, there's nothing to strip. We refuse to unpack
3892 # to an absolute path, nonetheless.
3893 self.expect_exception(
3894 tarfile.AbsolutePathError,
3895 """['"].*escaped.evil['"] has an absolute path""")
3896
3897 @symlink_test
3898 def test_parent_symlink(self):
3899 # Test interplaying symlinks
3900 # Inspired by 'dirsymlink2a' in jwilk/traversal-archives
3901 with ArchiveMaker() as arc:
3902
3903 # `current` links to `.` which is both:
3904 # - the destination directory
3905 # - `current` itself
3906 arc.add('current', symlink_to='.')
3907
3908 # effectively points to ./../
3909 arc.add('parent', symlink_to='current/..')
3910
3911 arc.add('parent/evil')
3912
3913 if os_helper.can_symlink():
3914 with self.check_context(arc.open(), 'fully_trusted'):
3915 if self.raised_exception is not None:
3916 # Windows will refuse to create a file that's a symlink to itself
3917 # (and tarfile doesn't swallow that exception)
3918 self.expect_exception(FileExistsError)
3919 # The other cases will fail with this error too.
3920 # Skip the rest of this test.
3921 return
3922 else:
3923 self.expect_file('current', symlink_to='.')
3924 self.expect_file('parent', symlink_to='current/..')
3925 self.expect_file('../evil')
3926
3927 with self.check_context(arc.open(), 'tar'):
3928 self.expect_exception(
3929 tarfile.OutsideDestinationError,
3930 """'parent/evil' would be extracted to ['"].*evil['"], """
3931 + "which is outside the destination")
3932
3933 with self.check_context(arc.open(), 'data'):
3934 if self.dotdot_resolves_early:
3935 # 'current/../..' normalises to '..', which is rejected.
3936 self.expect_exception(
3937 tarfile.LinkOutsideDestinationError,
3938 """'parent' would link to ['"].*outerdir['"], """
3939 + "which is outside the destination")
3940 else:
3941 # 'current/..' normalises to '.'; the rewritten link is
3942 # created and 'parent/evil' lands harmlessly inside the
3943 # destination.
3944 self.expect_file('current', symlink_to='.')
3945 self.expect_file('parent', symlink_to='.')
3946 self.expect_file('evil')
3947
3948 else:
3949 # No symlink support. The symlinks are ignored.
3950 with self.check_context(arc.open(), 'fully_trusted'):
3951 self.expect_file('parent/evil')
3952 with self.check_context(arc.open(), 'tar'):
3953 self.expect_file('parent/evil')
3954 with self.check_context(arc.open(), 'data'):
3955 self.expect_file('parent/evil')
3956
3957 @unittest.skipIf(not gh_135034_support, 'requires gh-135034')
3958 @unittest.skipIf(sys.version_info < (3, 11), "Requires Python 3.11")
3959 @symlink_test
3960 @os_helper.skip_unless_symlink
3961 def test_realpath_limit_attack(self):
3962 # (CVE-2025-4517)
3963
3964 with ArchiveMaker() as arc:
3965 # populate the symlinks and dirs that expand in os.path.realpath()
3966 # The component length is chosen so that in common cases, the unexpanded
3967 # path fits in PATH_MAX, but it overflows when the final symlink
3968 # is expanded
3969 steps = "abcdefghijklmnop"
3970 if sys.platform == 'win32':
3971 component = 'd' * 25
3972 elif 'PC_PATH_MAX' in os.pathconf_names:
3973 max_path_len = os.pathconf(self.outerdir.parent, "PC_PATH_MAX")
3974 path_sep_len = 1
3975 dest_len = len(str(self.destdir)) + path_sep_len
3976 component_len = (max_path_len - dest_len) // (len(steps) + path_sep_len)
3977 component = 'd' * component_len
3978 else:
3979 raise NotImplementedError("Need to guess component length for {sys.platform}")
3980 path = ""
3981 step_path = ""
3982 for i in steps:
3983 arc.add(os.path.join(path, component), type=tarfile.DIRTYPE,
3984 mode='drwxrwxrwx')
3985 arc.add(os.path.join(path, i), symlink_to=component)
3986 path = os.path.join(path, component)
3987 step_path = os.path.join(step_path, i)
3988 # create the final symlink that exceeds PATH_MAX and simply points
3989 # to the top dir.
3990 # this link will never be expanded by
3991 # os.path.realpath(strict=False), nor anything after it.
3992 linkpath = os.path.join(*steps, "l"*254)
3993 parent_segments = [".."] * len(steps)
3994 arc.add(linkpath, symlink_to=os.path.join(*parent_segments))
3995 # make a symlink outside to keep the tar command happy
3996 arc.add("escape", symlink_to=os.path.join(linkpath, ".."))
3997 # use the symlinks above, that are not checked, to create a hardlink
3998 # to a file outside of the destination path
3999 arc.add("flaglink", hardlink_to=os.path.join("escape", "flag"))
4000 # now that we have the hardlink we can overwrite the file
4001 arc.add("flaglink", content='overwrite')
4002 # we can also create new files as well!
4003 arc.add("escape/newfile", content='new')
4004
4005 with (self.subTest('fully_trusted'),
4006 self.check_context(arc.open(), filter='fully_trusted',
4007 check_flag=False)):
4008 if sys.platform == 'win32':
4009 self.expect_exception((FileNotFoundError, FileExistsError))
4010 elif self.raised_exception:
4011 # Cannot symlink/hardlink: tarfile falls back to getmember()
4012 self.expect_exception(KeyError)
4013 # Otherwise, this block should never enter.
4014 else:
4015 self.expect_any_tree(component)
4016 self.expect_file('flaglink', content='overwrite')
4017 self.expect_file('../newfile', content='new')
4018 self.expect_file('escape', type=tarfile.SYMTYPE)
4019 self.expect_file('a', symlink_to=component)
4020
4021 for filter in 'tar', 'data':
4022 with self.subTest(filter), self.check_context(arc.open(), filter=filter):
4023 exc = self.expect_exception((OSError, KeyError))
4024 if isinstance(exc, OSError):
4025 if sys.platform == 'win32':
4026 # 3: ERROR_PATH_NOT_FOUND
4027 # 5: ERROR_ACCESS_DENIED
4028 # 206: ERROR_FILENAME_EXCED_RANGE
4029 self.assertIn(exc.winerror, (3, 5, 206))
4030 else:
4031 self.assertEqual(exc.errno, errno.ENAMETOOLONG)
4032
4033 @symlink_test
4034 def test_parent_symlink2(self):
4035 # Test interplaying symlinks
4036 # Inspired by 'dirsymlink2b' in jwilk/traversal-archives
4037
4038 with ArchiveMaker() as arc:
4039
4040 # `current` links to `.` which is both the destination directory
4041 # and `current` itself
4042 arc.add('current', symlink_to='.')
4043
4044 # `current/parent` is also available as `./parent`,
4045 # and effectively points to `./../`
4046 arc.add('current/parent', symlink_to='..')
4047
4048 arc.add('parent/evil')
4049
4050 with self.check_context(arc.open(), 'fully_trusted'):
4051 if os_helper.can_symlink():
4052 self.expect_file('current', symlink_to='.')
4053 self.expect_file('parent', symlink_to='..')
4054 self.expect_file('../evil')
4055 else:
4056 self.expect_file('current/')
4057 self.expect_file('parent/evil')
4058
4059 with self.check_context(arc.open(), 'tar'):
4060 if os_helper.can_symlink():
4061 # Fail when extracting a file outside destination
4062 self.expect_exception(
4063 tarfile.OutsideDestinationError,
4064 "'parent/evil' would be extracted to "
4065 + """['"].*evil['"], which is outside """
4066 + "the destination")
4067 else:
4068 self.expect_file('current/')
4069 self.expect_file('parent/evil')
4070
4071 with self.check_context(arc.open(), 'data'):
4072 if os_helper.can_symlink():
4073 if self.dotdot_resolves_early:
4074 # Fail when extracting a file outside destination
4075 self.expect_exception(
4076 tarfile.OutsideDestinationError,
4077 "'parent/evil' would be extracted to "
4078 + """['"].*evil['"], which is outside """
4079 + "the destination")
4080 else:
4081 # Fail as soon as we have a symlink outside the destination
4082 self.expect_exception(
4083 tarfile.LinkOutsideDestinationError,
4084 "'current/parent' would link to "
4085 + """['"].*outerdir['"], which is outside """
4086 + "the destination")
4087 else:
4088 self.expect_file('current/')
4089 self.expect_file('parent/evil')
4090
4091 @symlink_test
4092 def test_absolute_symlink(self):
4093 # Test symlink to an absolute path
4094 # Inspired by 'dirsymlink' in jwilk/traversal-archives
4095 with ArchiveMaker() as arc:
4096 arc.add('parent', symlink_to=self.outerdir)
4097 arc.add('parent/evil')
4098
4099 with self.check_context(arc.open(), 'fully_trusted'):
4100 if os_helper.can_symlink():
4101 self.expect_file('parent', symlink_to=self.outerdir)
4102 self.expect_file('../evil')
4103 else:
4104 self.expect_file('parent/evil')
4105
4106 with self.check_context(arc.open(), 'tar'):
4107 if os_helper.can_symlink():
4108 self.expect_exception(
4109 tarfile.OutsideDestinationError,
4110 "'parent/evil' would be extracted to "
4111 + """['"].*evil['"], which is outside """
4112 + "the destination")
4113 else:
4114 self.expect_file('parent/evil')
4115
4116 with self.check_context(arc.open(), 'data'):
4117 self.expect_exception(
4118 tarfile.AbsoluteLinkError,
4119 "'parent' is a link to an absolute path")
4120
4121 def test_absolute_hardlink(self):
4122 # Test hardlink to an absolute path
4123 # Inspired by 'dirsymlink' in https://github.com/jwilk/traversal-archives
4124 with ArchiveMaker() as arc:
4125 arc.add('parent', hardlink_to=self.outerdir / 'foo')
4126
4127 with self.check_context(arc.open(), 'fully_trusted'):
4128 self.expect_exception(KeyError, ".*foo. not found")
4129
4130 with self.check_context(arc.open(), 'tar'):
4131 self.expect_exception(KeyError, ".*foo. not found")
4132
4133 with self.check_context(arc.open(), 'data'):
4134 self.expect_exception(
4135 tarfile.AbsoluteLinkError,
4136 "'parent' is a link to an absolute path")
4137
4138 @symlink_test
4139 def test_sly_relative0(self):
4140 # Inspired by 'relative0' in jwilk/traversal-archives
4141 with ArchiveMaker() as arc:
4142 # points to `../../tmp/moo`
4143 arc.add('../moo', symlink_to='..//tmp/moo')
4144
4145 try:
4146 with self.check_context(arc.open(), filter='fully_trusted'):
4147 if os_helper.can_symlink():
4148 if isinstance(self.raised_exception, FileExistsError):
4149 # XXX TarFile happens to fail creating a parent
4150 # directory.
4151 # This might be a bug, but fixing it would hurt
4152 # security.
4153 # Note that e.g. GNU `tar` rejects '..' components,
4154 # so you could argue this is an invalid archive and we
4155 # just raise an bad type of exception.
4156 self.expect_exception(FileExistsError)
4157 else:
4158 self.expect_file('../moo', symlink_to='..//tmp/moo')
4159 else:
4160 # The symlink can't be extracted and is ignored
4161 pass
4162 except FileExistsError:
4163 pass
4164
4165 for filter in 'tar', 'data':
4166 with self.check_context(arc.open(), filter):
4167 self.expect_exception(
4168 tarfile.OutsideDestinationError,
4169 "'../moo' would be extracted to "
4170 + "'.*moo', which is outside "
4171 + "the destination")
4172
4173 @symlink_test
4174 def test_sly_relative2(self):
4175 # Inspired by 'relative2' in jwilk/traversal-archives
4176 with ArchiveMaker() as arc:
4177 arc.add('tmp/')
4178 arc.add('tmp/../../moo', symlink_to='tmp/../..//tmp/moo')
4179
4180 with self.check_context(arc.open(), 'fully_trusted'):
4181 self.expect_file('tmp', type=tarfile.DIRTYPE)
4182 if os_helper.can_symlink():
4183 self.expect_file('../moo', symlink_to='tmp/../../tmp/moo')
4184
4185 for filter in 'tar', 'data':
4186 with self.check_context(arc.open(), filter):
4187 self.expect_exception(
4188 tarfile.OutsideDestinationError,
4189 "'tmp/../../moo' would be extracted to "
4190 + """['"].*moo['"], which is outside the """
4191 + "destination")
4192
4193 @symlink_test
4194 @os_helper.skip_unless_symlink
4195 def test_normpath_realpath_mismatch(self):
4196 # The link-target check must validate the value that will actually
4197 # be written to disk (the normalised linkname), not the original.
4198 # Here 'a' is a symlink to a deep nonexistent path, so realpath()
4199 # of 'a/../../...' stays inside the destination while normpath()
4200 # collapses 'a/..' lexically and escapes.
4201 depth = len(self.destdir.parts) + 5
4202 deep = '/'.join(f'p{i}' for i in range(depth))
4203 sneaky = 'a/' + '../' * depth + 'flag'
4204 for kind in 'symlink_to', 'hardlink_to':
4205 with self.subTest(kind):
4206 with ArchiveMaker() as arc:
4207 arc.add('a', symlink_to=deep)
4208 arc.add('escape', **{kind: sneaky})
4209 with self.check_context(arc.open(), 'data'):
4210 self.expect_exception(
4211 tarfile.LinkOutsideDestinationError)
4212
4213 @symlink_test
4214 @os_helper.skip_unless_symlink
4215 def test_symlink_trailing_slash(self):
4216 # A trailing slash on a symlink member's name must not cause the
4217 # link target to be resolved relative to the wrong directory.
4218 with ArchiveMaker() as arc:
4219 t = tarfile.TarInfo('x/')
4220 t.type = tarfile.SYMTYPE
4221 t.linkname = '..'
4222 arc.tar_w.addfile(t)
4223 arc.add('x/escaped', content='hi')
4224
4225 with self.check_context(arc.open(), 'data'):
4226 self.expect_exception(tarfile.LinkOutsideDestinationError)
4227
4228 @symlink_test
4229 @os_helper.skip_unless_symlink
4230 def test_link_at_destination(self):
4231 # A link member whose name resolves to the destination directory
4232 # itself must be rejected: otherwise the destination is replaced
4233 # by a symlink and later members can be redirected through it.
4234 for name in '', '.', './':
4235 with ArchiveMaker() as arc:
4236 t = tarfile.TarInfo(name)
4237 t.type = tarfile.SYMTYPE
4238 t.linkname = '.'
4239 arc.tar_w.addfile(t)
4240
4241 with self.check_context(arc.open(), 'data'):
4242 self.expect_exception(tarfile.OutsideDestinationError)
4243
4244 @symlink_test
4245 @os_helper.skip_unless_symlink
4246 def test_empty_name_symlink_chain(self):
4247 # Regression test for a chain of empty-named symlinks that
4248 # incrementally redirects the destination outwards.
4249 with ArchiveMaker() as arc:
4250 for name, target in [('', ''), ('a/', '..'),
4251 ('', 'dummy'), ('', 'a'),
4252 ('b/', '..'),
4253 ('', 'dummy'), ('', 'a/b')]:
4254 t = tarfile.TarInfo(name)
4255 t.type = tarfile.SYMTYPE
4256 t.linkname = target
4257 arc.tar_w.addfile(t)
4258 arc.add('escaped', content='hi')
4259
4260 with self.check_context(arc.open(), 'data'):
4261 self.expect_exception(tarfile.FilterError)
4262
4263 @symlink_test
4264 def test_deep_symlink(self):
4265 # Test that symlinks and hardlinks inside a directory
4266 # point to the correct file (`target` of size 3).
4267 # If links aren't supported we get a copy of the file.
4268 with ArchiveMaker() as arc:
4269 arc.add('targetdir/target', size=3)
4270 # a hardlink's linkname is relative to the archive
4271 arc.add('linkdir/hardlink', hardlink_to=os.path.join(
4272 'targetdir', 'target'))
4273 # a symlink's linkname is relative to the link's directory
4274 arc.add('linkdir/symlink', symlink_to=os.path.join(
4275 '..', 'targetdir', 'target'))
4276
4277 for filter in 'tar', 'data', 'fully_trusted':
4278 with self.check_context(arc.open(), filter):
4279 self.expect_file('targetdir/target', size=3)
4280 self.expect_file('linkdir/hardlink', size=3)
4281 if os_helper.can_symlink():
4282 self.expect_file('linkdir/symlink', size=3,
4283 symlink_to='../targetdir/target')
4284 else:
4285 self.expect_file('linkdir/symlink', size=3)
4286
4287 @symlink_test
4288 def test_chains(self):
4289 # Test chaining of symlinks/hardlinks.
4290 # Symlinks are created before the files they point to.
4291 with ArchiveMaker() as arc:
4292 arc.add('linkdir/symlink', symlink_to='hardlink')
4293 arc.add('symlink2', symlink_to=os.path.join(
4294 'linkdir', 'hardlink2'))
4295 arc.add('targetdir/target', size=3)
4296 arc.add('linkdir/hardlink', hardlink_to=os.path.join('targetdir', 'target'))
4297 arc.add('linkdir/hardlink2', hardlink_to=os.path.join('linkdir', 'symlink'))
4298
4299 for filter in 'tar', 'data', 'fully_trusted':
4300 with self.check_context(arc.open(), filter):
4301 self.expect_file('targetdir/target', size=3)
4302 self.expect_file('linkdir/hardlink', size=3)
4303 self.expect_file('linkdir/hardlink2', size=3)
4304 if os_helper.can_symlink():
4305 self.expect_file('linkdir/symlink', size=3,
4306 symlink_to='hardlink')
4307 self.expect_file('symlink2', size=3,
4308 symlink_to='linkdir/hardlink2')
4309 else:
4310 self.expect_file('linkdir/symlink', size=3)
4311 self.expect_file('symlink2', size=3)
4312
4313 @symlink_test
4314 def test_sneaky_hardlink_fallback(self):
4315 # (CVE-2025-4330)
4316 # Test that when hardlink extraction falls back to extracting members
4317 # from the archive, the extracted member is (re-)filtered.
4318 with ArchiveMaker() as arc:
4319 # Create a directory structure so the c/escape symlink stays
4320 # inside the path
4321 arc.add("a/t/dummy")
4322 # Create b/ directory
4323 arc.add("b/")
4324 # Point "c" to the bottom of the tree in "a"
4325 arc.add("c", symlink_to=os.path.join("a", "t"))
4326 # link to non-existant location under "a"
4327 arc.add("c/escape", symlink_to=os.path.join("..", "..",
4328 "link_here"))
4329 # Move "c" to point to "b" ("c/escape" no longer exists)
4330 arc.add("c", symlink_to="b")
4331 # Attempt to create a hard link to "c/escape". Since it doesn't
4332 # exist it will attempt to extract "cescape" but at "boom".
4333 arc.add("boom", hardlink_to=os.path.join("c", "escape"))
4334
4335 with self.check_context(arc.open(), 'data'):
4336 if not os_helper.can_symlink():
4337 # When 'c/escape' is extracted, 'c' is a regular
4338 # directory, and 'c/escape' *would* point outside
4339 # the destination if symlinks were allowed.
4340 self.expect_exception(
4341 tarfile.LinkOutsideDestinationError)
4342 elif sys.platform == "win32":
4343 # On Windows, 'c/escape' points outside the destination
4344 self.expect_exception(tarfile.LinkOutsideDestinationError)
4345 else:
4346 e = self.expect_exception(
4347 tarfile.LinkFallbackError,
4348 "link 'boom' would be extracted as a copy of "
4349 + "'c/escape', which was rejected")
4350 self.assertIsInstance(e.__cause__,
4351 tarfile.LinkOutsideDestinationError)
4352 for filter in 'tar', 'fully_trusted':
4353 with self.subTest(filter), self.check_context(arc.open(), filter):
4354 if not os_helper.can_symlink():
4355 self.expect_file("a/t/dummy")
4356 self.expect_file("b/")
4357 self.expect_file("c/")
4358 else:
4359 self.expect_file("a/t/dummy")
4360 self.expect_file("b/")
4361 self.expect_file("a/t/escape", symlink_to='../../link_here')
4362 self.expect_file("boom", symlink_to='../../link_here')
4363 self.expect_file("c", symlink_to='b')
4364
4365 @symlink_test
4366 def test_exfiltration_via_symlink(self):
4367 # (CVE-2025-4138)
4368 # Test changing symlinks that result in a symlink pointing outside
4369 # the extraction directory, unless prevented by 'data' filter's
4370 # normalization.
4371 with ArchiveMaker() as arc:
4372 arc.add("escape", symlink_to=os.path.join('link', 'link', '..', '..', 'link-here'))
4373 arc.add("link", symlink_to='./')
4374
4375 for filter in 'tar', 'data', 'fully_trusted':
4376 with self.check_context(arc.open(), filter):
4377 if os_helper.can_symlink():
4378 self.expect_file("link", symlink_to='./')
4379 if filter == 'data':
4380 self.expect_file("escape", symlink_to='link-here')
4381 else:
4382 self.expect_file("escape",
4383 symlink_to='link/link/../../link-here')
4384 else:
4385 # Nothing is extracted.
4386 pass
4387
4388 @symlink_test
4389 def test_chmod_outside_dir(self):
4390 # (CVE-2024-12718)
4391 # Test that members used for delayed updates of directory metadata
4392 # are (re-)filtered.
4393 with ArchiveMaker() as arc:
4394 # "pwn" is a veeeery innocent symlink:
4395 arc.add("a/pwn", symlink_to='.')
4396 # But now "pwn" is also a directory, so it's scheduled to have its
4397 # metadata updated later:
4398 arc.add("a/pwn/", mode='drwxrwxrwx')
4399 # Oops, "pwn" is not so innocent any more:
4400 arc.add("a/pwn", symlink_to='x/../')
4401 # Newly created symlink points to the dest dir,
4402 # so it's OK for the "data" filter.
4403 arc.add('a/x', symlink_to=('../'))
4404 # But now "pwn" points outside the dest dir
4405
4406 for filter in 'tar', 'data', 'fully_trusted':
4407 with self.check_context(arc.open(), filter) as cc:
4408 if not os_helper.can_symlink():
4409 self.expect_file("a/pwn/")
4410 elif filter == 'data':
4411 self.expect_file("a/x", symlink_to='../')
4412 self.expect_file("a/pwn", symlink_to='.')
4413 else:
4414 self.expect_file("a/x", symlink_to='../')
4415 self.expect_file("a/pwn", symlink_to='x/../')
4416 if sys.platform != "win32":
4417 st_mode = cc.outerdir.stat().st_mode
4418 self.assertNotEqual(st_mode & 0o777, 0o777)
4419
4420 def test_link_fallback_normalizes(self):
4421 # Make sure hardlink fallbacks work for non-normalized paths for all
4422 # filters
4423 with ArchiveMaker() as arc:
4424 arc.add("dir/")
4425 arc.add("dir/../afile")
4426 arc.add("link1", hardlink_to='dir/../afile')
4427 arc.add("link2", hardlink_to='dir/../dir/../afile')
4428
4429 for filter in 'tar', 'data', 'fully_trusted':
4430 with self.check_context(arc.open(), filter) as cc:
4431 self.expect_file("dir/")
4432 self.expect_file("afile")
4433 self.expect_file("link1")
4434 self.expect_file("link2")
4435
4436 def test_modes(self):
4437 # Test how file modes are extracted
4438 # (Note that the modes are ignored on platforms without working chmod)
4439 with ArchiveMaker() as arc:
4440 arc.add('all_bits', mode='?rwsrwsrwt')
4441 arc.add('perm_bits', mode='?rwxrwxrwx')
4442 arc.add('exec_group_other', mode='?rw-rwxrwx')
4443 arc.add('read_group_only', mode='?---r-----')
4444 arc.add('no_bits', mode='?---------')
4445 arc.add('dir/', mode='?---rwsrwt')
4446 arc.add('dir_all_bits/', mode='?rwsrwsrwt')
4447
4448 # On some systems, setting the uid, gid, and/or sticky bit is a no-ops.
4449 # Check which bits we can set, so we can compare tarfile machinery to
4450 # a simple chmod.
4451 tmp_filename = os.path.join(TEMPDIR, "tmp.file")
4452 with open(tmp_filename, 'w'):
4453 pass
4454 try:
4455 new_mode = (os.stat(tmp_filename).st_mode
4456 | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)
4457 try:
4458 os.chmod(tmp_filename, new_mode)
4459 except OSError as exc:
4460 if exc.errno == getattr(errno, "EFTYPE", 0):
4461 # gh-108948: On FreeBSD, regular users cannot set
4462 # the sticky bit.
4463 self.skipTest("chmod() failed with EFTYPE: "
4464 "regular users cannot set sticky bit")
4465 else:
4466 raise
4467
4468 got_mode = os.stat(tmp_filename).st_mode
4469 _t_file = 't' if (got_mode & stat.S_ISVTX) else 'x'
4470 _suid_file = 's' if (got_mode & stat.S_ISUID) else 'x'
4471 _sgid_file = 's' if (got_mode & stat.S_ISGID) else 'x'
4472 finally:
4473 os.unlink(tmp_filename)
4474
4475 os.mkdir(tmp_filename)
4476 new_mode = (os.stat(tmp_filename).st_mode
4477 | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)
4478 os.chmod(tmp_filename, new_mode)
4479 got_mode = os.stat(tmp_filename).st_mode
4480 _t_dir = 't' if (got_mode & stat.S_ISVTX) else 'x'
4481 _suid_dir = 's' if (got_mode & stat.S_ISUID) else 'x'
4482 _sgid_dir = 's' if (got_mode & stat.S_ISGID) else 'x'
4483 os.rmdir(tmp_filename)
4484
4485 with self.check_context(arc.open(), 'fully_trusted'):
4486 self.expect_file('all_bits',
4487 mode=f'?rw{_suid_file}rw{_sgid_file}rw{_t_file}')
4488 self.expect_file('perm_bits', mode='?rwxrwxrwx')
4489 self.expect_file('exec_group_other', mode='?rw-rwxrwx')
4490 self.expect_file('read_group_only', mode='?---r-----')
4491 self.expect_file('no_bits', mode='?---------')
4492 self.expect_file('dir/', mode=f'?---rw{_sgid_dir}rw{_t_dir}')
4493 self.expect_file('dir_all_bits/',
4494 mode=f'?rw{_suid_dir}rw{_sgid_dir}rw{_t_dir}')
4495
4496 with self.check_context(arc.open(), 'tar'):
4497 self.expect_file('all_bits', mode='?rwxr-xr-x')
4498 self.expect_file('perm_bits', mode='?rwxr-xr-x')
4499 self.expect_file('exec_group_other', mode='?rw-r-xr-x')
4500 self.expect_file('read_group_only', mode='?---r-----')
4501 self.expect_file('no_bits', mode='?---------')
4502 self.expect_file('dir/', mode='?---r-xr-x')
4503 self.expect_file('dir_all_bits/', mode='?rwxr-xr-x')
4504
4505 with self.check_context(arc.open(), 'data'):
4506 normal_dir_mode = stat.filemode(stat.S_IMODE(
4507 self.outerdir.stat().st_mode))
4508 self.expect_file('all_bits', mode='?rwxr-xr-x')
4509 self.expect_file('perm_bits', mode='?rwxr-xr-x')
4510 self.expect_file('exec_group_other', mode='?rw-r--r--')
4511 self.expect_file('read_group_only', mode='?rw-r-----')
4512 self.expect_file('no_bits', mode='?rw-------')
4513 self.expect_file('dir/', mode=normal_dir_mode)
4514 self.expect_file('dir_all_bits/', mode=normal_dir_mode)
4515
4516 def test_pipe(self):
4517 # Test handling of a special file
4518 with ArchiveMaker() as arc:
4519 arc.add('foo', type=tarfile.FIFOTYPE)
4520
4521 for filter in 'fully_trusted', 'tar':
4522 with self.check_context(arc.open(), filter):
4523 if hasattr(os, 'mkfifo'):
4524 self.expect_file('foo', type=tarfile.FIFOTYPE)
4525 else:
4526 # The pipe can't be extracted and is skipped.
4527 pass
4528
4529 with self.check_context(arc.open(), 'data'):
4530 self.expect_exception(
4531 tarfile.SpecialFileError,
4532 "'foo' is a special file")
4533
4534 def test_special_files(self):
4535 # Creating device files is tricky. Instead of attempting that let's
4536 # only check the filter result.
4537 for special_type in tarfile.FIFOTYPE, tarfile.CHRTYPE, tarfile.BLKTYPE:
4538 tarinfo = tarfile.TarInfo('foo')
4539 tarinfo.type = special_type
4540 trusted = tarfile.fully_trusted_filter(tarinfo, '')
4541 self.assertIs(trusted, tarinfo)
4542 tar = tarfile.tar_filter(tarinfo, '')
4543 self.assertEqual(tar.type, special_type)
4544 with self.assertRaises(tarfile.SpecialFileError) as cm:
4545 tarfile.data_filter(tarinfo, '')
4546 self.assertIsInstance(cm.exception.tarinfo, tarfile.TarInfo)
4547 self.assertEqual(cm.exception.tarinfo.name, 'foo')
4548
4549 def test_fully_trusted_filter(self):
4550 # The 'fully_trusted' filter returns the original TarInfo objects.
4551 with tarfile.TarFile.open(tarname) as tar:
4552 for tarinfo in tar.getmembers():
4553 filtered = tarfile.fully_trusted_filter(tarinfo, '')
4554 self.assertIs(filtered, tarinfo)
4555
4556 def test_tar_filter(self):
4557 # The 'tar' filter returns TarInfo objects with the same name/type.
4558 # (It can also fail for particularly "evil" input, but we don't have
4559 # that in the test archive.)
4560 with tarfile.TarFile.open(tarname, encoding="iso8859-1") as tar:
4561 for tarinfo in tar.getmembers():
4562 try:
4563 filtered = tarfile.tar_filter(tarinfo, '')
4564 except UnicodeEncodeError:
4565 continue
4566 self.assertIs(filtered.name, tarinfo.name)
4567 self.assertIs(filtered.type, tarinfo.type)
4568
4569 def test_data_filter(self):
4570 # The 'data' filter either raises, or returns TarInfo with the same
4571 # name/type.
4572 with tarfile.TarFile.open(tarname, encoding="iso8859-1") as tar:
4573 for tarinfo in tar.getmembers():
4574 try:
4575 filtered = tarfile.data_filter(tarinfo, '')
4576 except (tarfile.FilterError, UnicodeEncodeError):
4577 continue
4578 self.assertIs(filtered.name, tarinfo.name)
4579 self.assertIs(filtered.type, tarinfo.type)
4580
4581 @unittest.skipIf(not gh_106242_support, 'requires gh-106242')
4582 @unittest.skipIf(sys.platform == 'win32', 'requires native bytes paths')
4583 def test_filter_unencodable(self):
4584 # Sanity check using a valid path.
4585 tarinfo = tarfile.TarInfo(os_helper.TESTFN)
4586 filtered = tarfile.tar_filter(tarinfo, '')
4587 self.assertIs(filtered.name, tarinfo.name)
4588 filtered = tarfile.data_filter(tarinfo, '')
4589 self.assertIs(filtered.name, tarinfo.name)
4590
4591 tarinfo = tarfile.TarInfo('test\x00')
4592 self.assertRaises(ValueError, tarfile.tar_filter, tarinfo, '')
4593 self.assertRaises(ValueError, tarfile.data_filter, tarinfo, '')
4594 tarinfo = tarfile.TarInfo('\ud800')
4595 self.assertRaises(UnicodeEncodeError, tarfile.tar_filter, tarinfo, '')
4596 self.assertRaises(UnicodeEncodeError, tarfile.data_filter, tarinfo, '')
4597
4598 @unittest.skipIf(sys.platform == 'win32', 'requires native bytes paths')
4599 def test_extract_unencodable(self):
4600 # Create a member with name \xed\xa0\x80 which is UTF-8 encoded
4601 # lone surrogate \ud800.
4602 with ArchiveMaker(encoding='ascii', errors='surrogateescape') as arc:
4603 arc.add('\udced\udca0\udc80')
4604 with os_helper.temp_cwd() as tmp:
4605 tar = arc.open(encoding='utf-8', errors='surrogatepass',
4606 errorlevel=1)
4607 self.assertEqual(tar.getnames(), ['\ud800'])
4608 with self.assertRaises(UnicodeEncodeError):
4609 tar.extractall()
4610 self.assertEqual(os.listdir(), [])
4611
4612 tar = arc.open(encoding='utf-8', errors='surrogatepass',
4613 errorlevel=0, debug=1)
4614 with support.captured_stderr() as stderr:
4615 tar.extractall()
4616 self.assertEqual(os.listdir(), [])
4617 self.assertIn('tarfile: UnicodeEncodeError ', stderr.getvalue())
4618
4619 def test_change_default_filter_on_instance(self):
4620 tar = tarfile.TarFile(tarname, 'r')
4621 def strict_filter(tarinfo, path):
4622 if tarinfo.name == 'ustar/regtype':
4623 return tarinfo
4624 else:
4625 return None
4626 tar.extraction_filter = strict_filter
4627 with self.check_context(tar, None):
4628 self.expect_file('ustar/regtype')
4629
4630 def test_change_default_filter_on_class(self):
4631 def strict_filter(tarinfo, path):
4632 if tarinfo.name == 'ustar/regtype':
4633 return tarinfo
4634 else:
4635 return None
4636 tar = tarfile.TarFile(tarname, 'r')
4637 with support.swap_attr(tarfile.TarFile, 'extraction_filter',
4638 staticmethod(strict_filter)):
4639 with self.check_context(tar, None):
4640 self.expect_file('ustar/regtype')
4641
4642 def test_change_default_filter_on_subclass(self):
4643 class TarSubclass(tarfile.TarFile):
4644 def extraction_filter(self, tarinfo, path):
4645 if tarinfo.name == 'ustar/regtype':
4646 return tarinfo
4647 else:
4648 return None
4649
4650 tar = TarSubclass(tarname, 'r')
4651 with self.check_context(tar, None):
4652 self.expect_file('ustar/regtype')
4653
4654 def test_change_default_filter_to_string(self):
4655 tar = tarfile.TarFile(tarname, 'r')
4656 tar.extraction_filter = 'data'
4657 with self.check_context(tar, None):
4658 self.expect_exception(TypeError)
4659
4660 def test_custom_filter(self):
4661 def custom_filter(tarinfo, path):
4662 self.assertIs(path, self.destdir)
4663 if tarinfo.name == 'move_this':
4664 return tarinfo.replace(name='moved')
4665 if tarinfo.name == 'ignore_this':
4666 return None
4667 return tarinfo
4668
4669 with ArchiveMaker() as arc:
4670 arc.add('move_this')
4671 arc.add('ignore_this')
4672 arc.add('keep')
4673 with self.check_context(arc.open(), custom_filter):
4674 self.expect_file('moved')
4675 self.expect_file('keep')
4676
4677 def test_bad_filter_name(self):
4678 with ArchiveMaker() as arc:
4679 arc.add('foo')
4680 with self.check_context(arc.open(), 'bad filter name'):
4681 self.expect_exception(ValueError)
4682
4683 def test_stateful_filter(self):
4684 # Stateful filters should be possible.
4685 # (This doesn't really test tarfile. Rather, it demonstrates
4686 # that third parties can implement a stateful filter.)
4687 class StatefulFilter:
4688 def __enter__(self):
4689 self.num_files_processed = 0
4690 return self
4691
4692 def __call__(self, tarinfo, path):
4693 try:
4694 tarinfo = tarfile.data_filter(tarinfo, path)
4695 except tarfile.FilterError:
4696 return None
4697 self.num_files_processed += 1
4698 return tarinfo
4699
4700 def __exit__(self, *exc_info):
4701 self.done = True
4702
4703 with ArchiveMaker() as arc:
4704 arc.add('good')
4705 arc.add('bad', symlink_to='/')
4706 arc.add('good')
4707 with StatefulFilter() as custom_filter:
4708 with self.check_context(arc.open(), custom_filter):
4709 self.expect_file('good')
4710 self.assertEqual(custom_filter.num_files_processed, 2)
4711 self.assertEqual(custom_filter.done, True)
4712
4713 def test_errorlevel(self):
4714 def extracterror_filter(tarinfo, path):
4715 raise tarfile.ExtractError('failed with ExtractError')
4716 def filtererror_filter(tarinfo, path):
4717 raise tarfile.FilterError('failed with FilterError')
4718 def oserror_filter(tarinfo, path):
4719 raise OSError('failed with OSError')
4720 def tarerror_filter(tarinfo, path):
4721 raise tarfile.TarError('failed with base TarError')
4722 def valueerror_filter(tarinfo, path):
4723 raise ValueError('failed with ValueError')
4724
4725 with ArchiveMaker() as arc:
4726 arc.add('file')
4727
4728 # If errorlevel is 0, errors affected by errorlevel are ignored
4729
4730 with self.check_context(arc.open(errorlevel=0), extracterror_filter):
4731 pass
4732
4733 with self.check_context(arc.open(errorlevel=0), filtererror_filter):
4734 pass
4735
4736 with self.check_context(arc.open(errorlevel=0), oserror_filter):
4737 pass
4738
4739 with self.check_context(arc.open(errorlevel=0), tarerror_filter):
4740 self.expect_exception(tarfile.TarError)
4741
4742 with self.check_context(arc.open(errorlevel=0), valueerror_filter):
4743 self.expect_exception(ValueError)
4744
4745 # If 1, all fatal errors are raised
4746
4747 with self.check_context(arc.open(errorlevel=1), extracterror_filter):
4748 pass
4749
4750 with self.check_context(arc.open(errorlevel=1), filtererror_filter):
4751 self.expect_exception(tarfile.FilterError)
4752
4753 with self.check_context(arc.open(errorlevel=1), oserror_filter):
4754 self.expect_exception(OSError)
4755
4756 with self.check_context(arc.open(errorlevel=1), tarerror_filter):
4757 self.expect_exception(tarfile.TarError)
4758
4759 with self.check_context(arc.open(errorlevel=1), valueerror_filter):
4760 self.expect_exception(ValueError)
4761
4762 # If 2, all non-fatal errors are raised as well.
4763
4764 with self.check_context(arc.open(errorlevel=2), extracterror_filter):
4765 self.expect_exception(tarfile.ExtractError)
4766
4767 with self.check_context(arc.open(errorlevel=2), filtererror_filter):
4768 self.expect_exception(tarfile.FilterError)
4769
4770 with self.check_context(arc.open(errorlevel=2), oserror_filter):
4771 self.expect_exception(OSError)
4772
4773 with self.check_context(arc.open(errorlevel=2), tarerror_filter):
4774 self.expect_exception(tarfile.TarError)
4775
4776 with self.check_context(arc.open(errorlevel=2), valueerror_filter):
4777 self.expect_exception(ValueError)
4778
4779 # We only handle ExtractionError, FilterError & OSError specially.
4780
4781 with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):
4782 self.expect_exception(TypeError) # errorlevel is not int
4783
4784
4785 class OverwriteTests(archiver_tests.OverwriteTests, unittest.TestCase):
4786 testdir = os.path.join(TEMPDIR, "testoverwrite")
4787
4788 @classmethod
4789 def setUpClass(cls):
4790 p = cls.ar_with_file = os.path.join(TEMPDIR, 'tar-with-file.tar')
4791 cls.addClassCleanup(os_helper.unlink, p)
4792 with tarfile.open(p, 'w') as tar:
4793 t = tarfile.TarInfo('test')
4794 t.size = 10
4795 tar.addfile(t, io.BytesIO(b'newcontent'))
4796
4797 p = cls.ar_with_dir = os.path.join(TEMPDIR, 'tar-with-dir.tar')
4798 cls.addClassCleanup(os_helper.unlink, p)
4799 with tarfile.open(p, 'w') as tar:
4800 tar.addfile(tar.gettarinfo(os.curdir, 'test'))
4801
4802 p = os.path.join(TEMPDIR, 'tar-with-implicit-dir.tar')
4803 cls.ar_with_implicit_dir = p
4804 cls.addClassCleanup(os_helper.unlink, p)
4805 with tarfile.open(p, 'w') as tar:
4806 t = tarfile.TarInfo('test/file')
4807 t.size = 10
4808 tar.addfile(t, io.BytesIO(b'newcontent'))
4809
4810 def open(self, path):
4811 return tarfile.open(path, 'r')
4812
4813 def extractall(self, ar):
4814 ar.extractall(self.testdir, filter='fully_trusted')
4815
4816
4817 class OffsetValidationTests(unittest.TestCase):
4818 tarname = tmpname
4819 invalid_posix_header = (
4820 # name: 100 bytes
4821 tarfile.NUL * tarfile.LENGTH_NAME
4822 # mode, space, null terminator: 8 bytes
4823 + b"000755" + SPACE + tarfile.NUL
4824 # uid, space, null terminator: 8 bytes
4825 + b"000001" + SPACE + tarfile.NUL
4826 # gid, space, null terminator: 8 bytes
4827 + b"000001" + SPACE + tarfile.NUL
4828 # size, space: 12 bytes
4829 + b"\xff" * 11 + SPACE
4830 # mtime, space: 12 bytes
4831 + tarfile.NUL * 11 + SPACE
4832 # chksum: 8 bytes
4833 + b"0011407" + tarfile.NUL
4834 # type: 1 byte
4835 + tarfile.REGTYPE
4836 # linkname: 100 bytes
4837 + tarfile.NUL * tarfile.LENGTH_LINK
4838 # magic: 6 bytes, version: 2 bytes
4839 + tarfile.POSIX_MAGIC
4840 # uname: 32 bytes
4841 + tarfile.NUL * 32
4842 # gname: 32 bytes
4843 + tarfile.NUL * 32
4844 # devmajor, space, null terminator: 8 bytes
4845 + tarfile.NUL * 6 + SPACE + tarfile.NUL
4846 # devminor, space, null terminator: 8 bytes
4847 + tarfile.NUL * 6 + SPACE + tarfile.NUL
4848 # prefix: 155 bytes
4849 + tarfile.NUL * tarfile.LENGTH_PREFIX
4850 # padding: 12 bytes
4851 + tarfile.NUL * 12
4852 )
4853 invalid_gnu_header = (
4854 # name: 100 bytes
4855 tarfile.NUL * tarfile.LENGTH_NAME
4856 # mode, null terminator: 8 bytes
4857 + b"0000755" + tarfile.NUL
4858 # uid, null terminator: 8 bytes
4859 + b"0000001" + tarfile.NUL
4860 # gid, space, null terminator: 8 bytes
4861 + b"0000001" + tarfile.NUL
4862 # size, space: 12 bytes
4863 + b"\xff" * 11 + SPACE
4864 # mtime, space: 12 bytes
4865 + tarfile.NUL * 11 + SPACE
4866 # chksum: 8 bytes
4867 + b"0011327" + tarfile.NUL
4868 # type: 1 byte
4869 + tarfile.REGTYPE
4870 # linkname: 100 bytes
4871 + tarfile.NUL * tarfile.LENGTH_LINK
4872 # magic: 8 bytes
4873 + tarfile.GNU_MAGIC
4874 # uname: 32 bytes
4875 + tarfile.NUL * 32
4876 # gname: 32 bytes
4877 + tarfile.NUL * 32
4878 # devmajor, null terminator: 8 bytes
4879 + tarfile.NUL * 8
4880 # devminor, null terminator: 8 bytes
4881 + tarfile.NUL * 8
4882 # padding: 167 bytes
4883 + tarfile.NUL * 167
4884 )
4885 invalid_v7_header = (
4886 # name: 100 bytes
4887 tarfile.NUL * tarfile.LENGTH_NAME
4888 # mode, space, null terminator: 8 bytes
4889 + b"000755" + SPACE + tarfile.NUL
4890 # uid, space, null terminator: 8 bytes
4891 + b"000001" + SPACE + tarfile.NUL
4892 # gid, space, null terminator: 8 bytes
4893 + b"000001" + SPACE + tarfile.NUL
4894 # size, space: 12 bytes
4895 + b"\xff" * 11 + SPACE
4896 # mtime, space: 12 bytes
4897 + tarfile.NUL * 11 + SPACE
4898 # chksum: 8 bytes
4899 + b"0010070" + tarfile.NUL
4900 # type: 1 byte
4901 + tarfile.REGTYPE
4902 # linkname: 100 bytes
4903 + tarfile.NUL * tarfile.LENGTH_LINK
4904 # padding: 255 bytes
4905 + tarfile.NUL * 255
4906 )
4907 valid_gnu_header = tarfile.TarInfo("filename").tobuf(tarfile.GNU_FORMAT)
4908 data_block = b"\xff" * tarfile.BLOCKSIZE
4909
4910 def _write_buffer(self, buffer):
4911 with open(self.tarname, "wb") as f:
4912 f.write(buffer)
4913
4914 def _get_members(self, ignore_zeros=None):
4915 with open(self.tarname, "rb") as f:
4916 with tarfile.open(
4917 mode="r", fileobj=f, ignore_zeros=ignore_zeros
4918 ) as tar:
4919 return tar.getmembers()
4920
4921 def _assert_raises_read_error_exception(self):
4922 with self.assertRaisesRegex(
4923 tarfile.ReadError, "file could not be opened successfully"
4924 ):
4925 self._get_members()
4926
4927 def test_invalid_offset_header_validations(self):
4928 for tar_format, invalid_header in (
4929 ("posix", self.invalid_posix_header),
4930 ("gnu", self.invalid_gnu_header),
4931 ("v7", self.invalid_v7_header),
4932 ):
4933 with self.subTest(format=tar_format):
4934 self._write_buffer(invalid_header)
4935 self._assert_raises_read_error_exception()
4936
4937 def test_early_stop_at_invalid_offset_header(self):
4938 buffer = self.valid_gnu_header + self.invalid_gnu_header + self.valid_gnu_header
4939 self._write_buffer(buffer)
4940 members = self._get_members()
4941 self.assertEqual(len(members), 1)
4942 self.assertEqual(members[0].name, "filename")
4943 self.assertEqual(members[0].offset, 0)
4944
4945 def test_ignore_invalid_archive(self):
4946 # 3 invalid headers with their respective data
4947 buffer = (self.invalid_gnu_header + self.data_block) * 3
4948 self._write_buffer(buffer)
4949 members = self._get_members(ignore_zeros=True)
4950 self.assertEqual(len(members), 0)
4951
4952 def test_ignore_invalid_offset_headers(self):
4953 for first_block, second_block, expected_offset in (
4954 (
4955 (self.valid_gnu_header),
4956 (self.invalid_gnu_header + self.data_block),
4957 0,
4958 ),
4959 (
4960 (self.invalid_gnu_header + self.data_block),
4961 (self.valid_gnu_header),
4962 1024,
4963 ),
4964 ):
4965 self._write_buffer(first_block + second_block)
4966 members = self._get_members(ignore_zeros=True)
4967 self.assertEqual(len(members), 1)
4968 self.assertEqual(members[0].name, "filename")
4969 self.assertEqual(members[0].offset, expected_offset)
4970
4971
4972 def setUpModule():
4973 os_helper.unlink(TEMPDIR)
4974 os.makedirs(TEMPDIR)
4975
4976 global testtarnames
4977 testtarnames = [tarname]
4978 with open(tarname, "rb") as fobj:
4979 data = fobj.read()
4980
4981 # Create compressed tarfiles.
4982 for c in GzipTest, Bz2Test, LzmaTest, ZstdTest:
4983 if c.open:
4984 os_helper.unlink(c.tarname)
4985 testtarnames.append(c.tarname)
4986 with c.open(c.tarname, "wb") as tar:
4987 tar.write(data)
4988
4989 def tearDownModule():
4990 if os.path.exists(TEMPDIR):
4991 os_helper.rmtree(TEMPDIR)
4992
4993 if __name__ == "__main__":
4994 unittest.main()