Debian Codegraph @

lib-python/3/test/test_tarfile.py

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