]> granicus.if.org Git - python/commitdiff
Issue #28449: tarfile.open() with mode "r" or "r:" now tries to open a tar
authorSerhiy Storchaka <storchaka@gmail.com>
Sun, 30 Oct 2016 18:52:55 +0000 (20:52 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Sun, 30 Oct 2016 18:52:55 +0000 (20:52 +0200)
file with compression before trying to open it without compression.  Otherwise
it had 50% chance failed with ignore_zeros=True.

Lib/tarfile.py
Lib/test/test_tarfile.py
Misc/NEWS

index be688005f456d6a60e4f2d3c758fc03300ac6b14..adf91d53823bb5a87ee682cc2518090db4f4deb6 100644 (file)
@@ -1665,7 +1665,9 @@ class TarFile(object):
 
         if mode in ("r", "r:*"):
             # Find out which *open() is appropriate for opening the file.
-            for comptype in cls.OPEN_METH:
+            def not_compressed(comptype):
+                return cls.OPEN_METH[comptype] == 'taropen'
+            for comptype in sorted(cls.OPEN_METH, key=not_compressed):
                 func = getattr(cls, cls.OPEN_METH[comptype])
                 if fileobj is not None:
                     saved_pos = fileobj.tell()
index 3f9e9960b716de5d7ac3802f185f24f26da62f4c..89bd738aea0da2186ecb3588ef8bb8db480c128c 100644 (file)
@@ -2,7 +2,9 @@ import sys
 import os
 import shutil
 import StringIO
+from binascii import unhexlify
 from hashlib import md5
+from random import Random
 import errno
 
 import unittest
@@ -276,12 +278,17 @@ class CommonReadTest(ReadTest):
         else:
             _open = open
 
+        # generate 512 pseudorandom bytes
+        data = unhexlify('%1024x' % Random(0).getrandbits(512*8))
         for char in ('\0', 'a'):
             # Test if EOFHeaderError ('\0') and InvalidHeaderError ('a')
             # are ignored correctly.
             with _open(tmpname, "wb") as fobj:
                 fobj.write(char * 1024)
-                fobj.write(tarfile.TarInfo("foo").tobuf())
+                tarinfo = tarfile.TarInfo("foo")
+                tarinfo.size = len(data)
+                fobj.write(tarinfo.tobuf())
+                fobj.write(data)
 
             tar = tarfile.open(tmpname, mode="r", ignore_zeros=True)
             try:
index 12c3da2b7cfbd6cba2cfae50187366e01e5dc303..760a6ea132792e097ab55c2ea29c07353de5862d 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -60,6 +60,10 @@ Core and Builtins
 Library
 -------
 
+- Issue #28449: tarfile.open() with mode "r" or "r:" now tries to open a tar
+  file with compression before trying to open it without compression.  Otherwise
+  it had 50% chance failed with ignore_zeros=True.
+
 - Issue #25464: Fixed HList.header_exists() in Tix module by adding
   a workaround to Tix library bug.