bpo-39430: Fix race condition in lazy imports in tarfile. (GH-18161)

Use `from ... import ...` to ensure module is fully loaded before accessing its attributes.
(cherry picked from commit 9017e0bd5e)

Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
This commit is contained in:
Miss Islington (bot) 2020-01-24 12:10:52 -08:00 committed by GitHub
parent 61b3484cdf
commit 1a27435928
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 9 additions and 10 deletions

View File

@ -1629,13 +1629,12 @@ class TarFile(object):
raise ValueError("mode must be 'r', 'w' or 'x'")
try:
import gzip
gzip.GzipFile
except (ImportError, AttributeError):
from gzip import GzipFile
except ImportError:
raise CompressionError("gzip module is not available")
try:
fileobj = gzip.GzipFile(name, mode + "b", compresslevel, fileobj)
fileobj = GzipFile(name, mode + "b", compresslevel, fileobj)
except OSError:
if fileobj is not None and mode == 'r':
raise ReadError("not a gzip file")
@ -1663,12 +1662,11 @@ class TarFile(object):
raise ValueError("mode must be 'r', 'w' or 'x'")
try:
import bz2
from bz2 import BZ2File
except ImportError:
raise CompressionError("bz2 module is not available")
fileobj = bz2.BZ2File(fileobj or name, mode,
compresslevel=compresslevel)
fileobj = BZ2File(fileobj or name, mode, compresslevel=compresslevel)
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
@ -1692,15 +1690,15 @@ class TarFile(object):
raise ValueError("mode must be 'r', 'w' or 'x'")
try:
import lzma
from lzma import LZMAFile, LZMAError
except ImportError:
raise CompressionError("lzma module is not available")
fileobj = lzma.LZMAFile(fileobj or name, mode, preset=preset)
fileobj = LZMAFile(fileobj or name, mode, preset=preset)
try:
t = cls.taropen(name, mode, fileobj, **kwargs)
except (lzma.LZMAError, EOFError):
except (LZMAError, EOFError):
fileobj.close()
if mode == 'r':
raise ReadError("not an lzma file")

View File

@ -0,0 +1 @@
Fixed race condition in lazy imports in :mod:`tarfile`.