diff --git a/Doc/library/gzip.rst b/Doc/library/gzip.rst index 1a2582d6a904b2..45670ced239173 100644 --- a/Doc/library/gzip.rst +++ b/Doc/library/gzip.rst @@ -173,6 +173,9 @@ The module defines the following items: Opening :class:`GzipFile` for writing without specifying the *mode* argument is deprecated. + .. versionchanged:: 3.11 + A UserWarning is now emitted when gzip files contain trailing garbage + instead of throwing a BadGzipFile error. .. function:: compress(data, compresslevel=9, *, mtime=None) @@ -202,6 +205,9 @@ The module defines the following items: .. versionchanged:: 3.11 Speed is improved by decompressing members at once in memory instead of in a streamed fashion. + .. versionchanged:: 3.11 + A UserWarning is now emitted when gzip data contains trailing garbage + instead of throwing a BadGzipFile error. .. _gzip-usage-examples: diff --git a/Lib/gzip.py b/Lib/gzip.py index 75c6ddc3f2cffb..8691aaedf6381d 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -9,6 +9,7 @@ import zlib import builtins import io +import warnings import _compression __all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"] @@ -409,18 +410,22 @@ def _read_exact(fp, n): return data -def _read_gzip_header(fp): +def _read_gzip_header(fp, first_member=True): '''Read a gzip header from `fp` and progress to the end of the header. - Returns last mtime if header was present or None otherwise. + Returns last mtime if header was present or None otherwise. Raises an + error if the magic does not match the gzip magic, unless first_member is + False, in which case it only warns about trailing garbage. ''' magic = fp.read(2) if magic == b'': return None if magic != b'\037\213': - raise BadGzipFile('Not a gzipped file (%r)' % magic) - + if first_member: + raise BadGzipFile('Not a gzipped file (%r)' % magic) + warnings.warn("Trailing garbage in gzip data ignored.") + return None (method, flag, last_mtime) = struct.unpack("