Debian Codegraph @

Lib/test/test_tarfile.py

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