Index: Lib/gzip.py =================================================================== --- Lib/gzip.py (revision 78997) +++ Lib/gzip.py (working copy) @@ -45,6 +45,14 @@ """ return GzipFile(filename, mode, compresslevel) +class BadGzipFile(IOError): + """ + Exception raised if processed file seems not to be a valid gzip + archive. + """ + pass + + class GzipFile(io.BufferedIOBase): """The GzipFile class simulates most of the methods of a file object with the exception of the readinto() and truncate() methods. @@ -189,10 +197,10 @@ def _read_gzip_header(self): magic = self.fileobj.read(2) if magic != b'\037\213': - raise IOError('Not a gzipped file') + raise BadGzipFile('Not a gzipped file') method = ord( self.fileobj.read(1) ) if method != 8: - raise IOError('Unknown compression method') + raise BadGzipFile('Unknown compression method') flag = ord( self.fileobj.read(1) ) self.mtime = read32(self.fileobj) # extraflag = self.fileobj.read(1) @@ -343,10 +351,10 @@ crc32 = read32(self.fileobj) isize = read32(self.fileobj) # may exceed 2GB if crc32 != self.crc: - raise IOError("CRC check failed %s != %s" % (hex(crc32), + raise BadGzipFile("CRC check failed %s != %s" % (hex(crc32), hex(self.crc))) elif isize != (self.size & 0xffffffff): - raise IOError("Incorrect length of data produced") + raise BadGzipFile("Incorrect length of data produced") # Gzip files can be padded with zeroes and still have archives. # Consume all zero bytes and set the file position to the first Index: Lib/test/test_gzip.py =================================================================== --- Lib/test/test_gzip.py (revision 78997) +++ Lib/test/test_gzip.py (working copy) @@ -264,6 +264,16 @@ with gzip.GzipFile(self.filename, "rb") as f: d = f.read() self.assertEqual(d, data1 * 50, "Incorrect data in file") + + def test_bad_gzip_file(self): + file = open(self.filename, 'wb') + file.write(data1 * 50) + file.close() + + file = gzip.GzipFile(self.filename, 'r') + self.assertRaises(IOError, file.readlines) + self.assertRaises(gzip.BadGzipFile, file.readlines) + file.close() def test_main(verbose=None): support.run_unittest(TestGzip)