Debian Codegraph @

tests/test/test_tarfile.py

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