gzip.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. """Functions that read and write gzipped files.
  2. The user of the file doesn't have to worry about the compression,
  3. but random access is not allowed."""
  4. # based on Andrew Kuchling's minigzip.py distributed with the zlib module
  5. import struct, sys, time, os
  6. import zlib
  7. import builtins
  8. import io
  9. import _compression
  10. __all__ = ["BadGzipFile", "GzipFile", "open", "compress", "decompress"]
  11. FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
  12. READ, WRITE = 1, 2
  13. _COMPRESS_LEVEL_FAST = 1
  14. _COMPRESS_LEVEL_TRADEOFF = 6
  15. _COMPRESS_LEVEL_BEST = 9
  16. def open(filename, mode="rb", compresslevel=_COMPRESS_LEVEL_BEST,
  17. encoding=None, errors=None, newline=None):
  18. """Open a gzip-compressed file in binary or text mode.
  19. The filename argument can be an actual filename (a str or bytes object), or
  20. an existing file object to read from or write to.
  21. The mode argument can be "r", "rb", "w", "wb", "x", "xb", "a" or "ab" for
  22. binary mode, or "rt", "wt", "xt" or "at" for text mode. The default mode is
  23. "rb", and the default compresslevel is 9.
  24. For binary mode, this function is equivalent to the GzipFile constructor:
  25. GzipFile(filename, mode, compresslevel). In this case, the encoding, errors
  26. and newline arguments must not be provided.
  27. For text mode, a GzipFile object is created, and wrapped in an
  28. io.TextIOWrapper instance with the specified encoding, error handling
  29. behavior, and line ending(s).
  30. """
  31. if "t" in mode:
  32. if "b" in mode:
  33. raise ValueError("Invalid mode: %r" % (mode,))
  34. else:
  35. if encoding is not None:
  36. raise ValueError("Argument 'encoding' not supported in binary mode")
  37. if errors is not None:
  38. raise ValueError("Argument 'errors' not supported in binary mode")
  39. if newline is not None:
  40. raise ValueError("Argument 'newline' not supported in binary mode")
  41. gz_mode = mode.replace("t", "")
  42. if isinstance(filename, (str, bytes, os.PathLike)):
  43. binary_file = GzipFile(filename, gz_mode, compresslevel)
  44. elif hasattr(filename, "read") or hasattr(filename, "write"):
  45. binary_file = GzipFile(None, gz_mode, compresslevel, filename)
  46. else:
  47. raise TypeError("filename must be a str or bytes object, or a file")
  48. if "t" in mode:
  49. return io.TextIOWrapper(binary_file, encoding, errors, newline)
  50. else:
  51. return binary_file
  52. def write32u(output, value):
  53. # The L format writes the bit pattern correctly whether signed
  54. # or unsigned.
  55. output.write(struct.pack("<L", value))
  56. class _PaddedFile:
  57. """Minimal read-only file object that prepends a string to the contents
  58. of an actual file. Shouldn't be used outside of gzip.py, as it lacks
  59. essential functionality."""
  60. def __init__(self, f, prepend=b''):
  61. self._buffer = prepend
  62. self._length = len(prepend)
  63. self.file = f
  64. self._read = 0
  65. def read(self, size):
  66. if self._read is None:
  67. return self.file.read(size)
  68. if self._read + size <= self._length:
  69. read = self._read
  70. self._read += size
  71. return self._buffer[read:self._read]
  72. else:
  73. read = self._read
  74. self._read = None
  75. return self._buffer[read:] + \
  76. self.file.read(size-self._length+read)
  77. def prepend(self, prepend=b''):
  78. if self._read is None:
  79. self._buffer = prepend
  80. else: # Assume data was read since the last prepend() call
  81. self._read -= len(prepend)
  82. return
  83. self._length = len(self._buffer)
  84. self._read = 0
  85. def seek(self, off):
  86. self._read = None
  87. self._buffer = None
  88. return self.file.seek(off)
  89. def seekable(self):
  90. return True # Allows fast-forwarding even in unseekable streams
  91. class BadGzipFile(OSError):
  92. """Exception raised in some cases for invalid gzip files."""
  93. class GzipFile(_compression.BaseStream):
  94. """The GzipFile class simulates most of the methods of a file object with
  95. the exception of the truncate() method.
  96. This class only supports opening files in binary mode. If you need to open a
  97. compressed file in text mode, use the gzip.open() function.
  98. """
  99. # Overridden with internal file object to be closed, if only a filename
  100. # is passed in
  101. myfileobj = None
  102. def __init__(self, filename=None, mode=None,
  103. compresslevel=_COMPRESS_LEVEL_BEST, fileobj=None, mtime=None):
  104. """Constructor for the GzipFile class.
  105. At least one of fileobj and filename must be given a
  106. non-trivial value.
  107. The new class instance is based on fileobj, which can be a regular
  108. file, an io.BytesIO object, or any other object which simulates a file.
  109. It defaults to None, in which case filename is opened to provide
  110. a file object.
  111. When fileobj is not None, the filename argument is only used to be
  112. included in the gzip file header, which may include the original
  113. filename of the uncompressed file. It defaults to the filename of
  114. fileobj, if discernible; otherwise, it defaults to the empty string,
  115. and in this case the original filename is not included in the header.
  116. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', 'wb', 'x', or
  117. 'xb' depending on whether the file will be read or written. The default
  118. is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  119. A mode of 'r' is equivalent to one of 'rb', and similarly for 'w' and
  120. 'wb', 'a' and 'ab', and 'x' and 'xb'.
  121. The compresslevel argument is an integer from 0 to 9 controlling the
  122. level of compression; 1 is fastest and produces the least compression,
  123. and 9 is slowest and produces the most compression. 0 is no compression
  124. at all. The default is 9.
  125. The mtime argument is an optional numeric timestamp to be written
  126. to the last modification time field in the stream when compressing.
  127. If omitted or None, the current time is used.
  128. """
  129. if mode and ('t' in mode or 'U' in mode):
  130. raise ValueError("Invalid mode: {!r}".format(mode))
  131. if mode and 'b' not in mode:
  132. mode += 'b'
  133. if fileobj is None:
  134. fileobj = self.myfileobj = builtins.open(filename, mode or 'rb')
  135. if filename is None:
  136. filename = getattr(fileobj, 'name', '')
  137. if not isinstance(filename, (str, bytes)):
  138. filename = ''
  139. else:
  140. filename = os.fspath(filename)
  141. origmode = mode
  142. if mode is None:
  143. mode = getattr(fileobj, 'mode', 'rb')
  144. if mode.startswith('r'):
  145. self.mode = READ
  146. raw = _GzipReader(fileobj)
  147. self._buffer = io.BufferedReader(raw)
  148. self.name = filename
  149. elif mode.startswith(('w', 'a', 'x')):
  150. if origmode is None:
  151. import warnings
  152. warnings.warn(
  153. "GzipFile was opened for writing, but this will "
  154. "change in future Python releases. "
  155. "Specify the mode argument for opening it for writing.",
  156. FutureWarning, 2)
  157. self.mode = WRITE
  158. self._init_write(filename)
  159. self.compress = zlib.compressobj(compresslevel,
  160. zlib.DEFLATED,
  161. -zlib.MAX_WBITS,
  162. zlib.DEF_MEM_LEVEL,
  163. 0)
  164. self._write_mtime = mtime
  165. else:
  166. raise ValueError("Invalid mode: {!r}".format(mode))
  167. self.fileobj = fileobj
  168. if self.mode == WRITE:
  169. self._write_gzip_header(compresslevel)
  170. @property
  171. def filename(self):
  172. import warnings
  173. warnings.warn("use the name attribute", DeprecationWarning, 2)
  174. if self.mode == WRITE and self.name[-3:] != ".gz":
  175. return self.name + ".gz"
  176. return self.name
  177. @property
  178. def mtime(self):
  179. """Last modification time read from stream, or None"""
  180. return self._buffer.raw._last_mtime
  181. def __repr__(self):
  182. s = repr(self.fileobj)
  183. return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  184. def _init_write(self, filename):
  185. self.name = filename
  186. self.crc = zlib.crc32(b"")
  187. self.size = 0
  188. self.writebuf = []
  189. self.bufsize = 0
  190. self.offset = 0 # Current file offset for seek(), tell(), etc
  191. def _write_gzip_header(self, compresslevel):
  192. self.fileobj.write(b'\037\213') # magic header
  193. self.fileobj.write(b'\010') # compression method
  194. try:
  195. # RFC 1952 requires the FNAME field to be Latin-1. Do not
  196. # include filenames that cannot be represented that way.
  197. fname = os.path.basename(self.name)
  198. if not isinstance(fname, bytes):
  199. fname = fname.encode('latin-1')
  200. if fname.endswith(b'.gz'):
  201. fname = fname[:-3]
  202. except UnicodeEncodeError:
  203. fname = b''
  204. flags = 0
  205. if fname:
  206. flags = FNAME
  207. self.fileobj.write(chr(flags).encode('latin-1'))
  208. mtime = self._write_mtime
  209. if mtime is None:
  210. mtime = time.time()
  211. write32u(self.fileobj, int(mtime))
  212. if compresslevel == _COMPRESS_LEVEL_BEST:
  213. xfl = b'\002'
  214. elif compresslevel == _COMPRESS_LEVEL_FAST:
  215. xfl = b'\004'
  216. else:
  217. xfl = b'\000'
  218. self.fileobj.write(xfl)
  219. self.fileobj.write(b'\377')
  220. if fname:
  221. self.fileobj.write(fname + b'\000')
  222. def write(self,data):
  223. self._check_not_closed()
  224. if self.mode != WRITE:
  225. import errno
  226. raise OSError(errno.EBADF, "write() on read-only GzipFile object")
  227. if self.fileobj is None:
  228. raise ValueError("write() on closed GzipFile object")
  229. if isinstance(data, bytes):
  230. length = len(data)
  231. else:
  232. # accept any data that supports the buffer protocol
  233. data = memoryview(data)
  234. length = data.nbytes
  235. if length > 0:
  236. self.fileobj.write(self.compress.compress(data))
  237. self.size += length
  238. self.crc = zlib.crc32(data, self.crc)
  239. self.offset += length
  240. return length
  241. def read(self, size=-1):
  242. self._check_not_closed()
  243. if self.mode != READ:
  244. import errno
  245. raise OSError(errno.EBADF, "read() on write-only GzipFile object")
  246. return self._buffer.read(size)
  247. def read1(self, size=-1):
  248. """Implements BufferedIOBase.read1()
  249. Reads up to a buffer's worth of data if size is negative."""
  250. self._check_not_closed()
  251. if self.mode != READ:
  252. import errno
  253. raise OSError(errno.EBADF, "read1() on write-only GzipFile object")
  254. if size < 0:
  255. size = io.DEFAULT_BUFFER_SIZE
  256. return self._buffer.read1(size)
  257. def peek(self, n):
  258. self._check_not_closed()
  259. if self.mode != READ:
  260. import errno
  261. raise OSError(errno.EBADF, "peek() on write-only GzipFile object")
  262. return self._buffer.peek(n)
  263. @property
  264. def closed(self):
  265. return self.fileobj is None
  266. def close(self):
  267. fileobj = self.fileobj
  268. if fileobj is None:
  269. return
  270. self.fileobj = None
  271. try:
  272. if self.mode == WRITE:
  273. fileobj.write(self.compress.flush())
  274. write32u(fileobj, self.crc)
  275. # self.size may exceed 2 GiB, or even 4 GiB
  276. write32u(fileobj, self.size & 0xffffffff)
  277. elif self.mode == READ:
  278. self._buffer.close()
  279. finally:
  280. myfileobj = self.myfileobj
  281. if myfileobj:
  282. self.myfileobj = None
  283. myfileobj.close()
  284. def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
  285. self._check_not_closed()
  286. if self.mode == WRITE:
  287. # Ensure the compressor's buffer is flushed
  288. self.fileobj.write(self.compress.flush(zlib_mode))
  289. self.fileobj.flush()
  290. def fileno(self):
  291. """Invoke the underlying file object's fileno() method.
  292. This will raise AttributeError if the underlying file object
  293. doesn't support fileno().
  294. """
  295. return self.fileobj.fileno()
  296. def rewind(self):
  297. '''Return the uncompressed stream file position indicator to the
  298. beginning of the file'''
  299. if self.mode != READ:
  300. raise OSError("Can't rewind in write mode")
  301. self._buffer.seek(0)
  302. def readable(self):
  303. return self.mode == READ
  304. def writable(self):
  305. return self.mode == WRITE
  306. def seekable(self):
  307. return True
  308. def seek(self, offset, whence=io.SEEK_SET):
  309. if self.mode == WRITE:
  310. if whence != io.SEEK_SET:
  311. if whence == io.SEEK_CUR:
  312. offset = self.offset + offset
  313. else:
  314. raise ValueError('Seek from end not supported')
  315. if offset < self.offset:
  316. raise OSError('Negative seek in write mode')
  317. count = offset - self.offset
  318. chunk = b'\0' * 1024
  319. for i in range(count // 1024):
  320. self.write(chunk)
  321. self.write(b'\0' * (count % 1024))
  322. elif self.mode == READ:
  323. self._check_not_closed()
  324. return self._buffer.seek(offset, whence)
  325. return self.offset
  326. def readline(self, size=-1):
  327. self._check_not_closed()
  328. return self._buffer.readline(size)
  329. class _GzipReader(_compression.DecompressReader):
  330. def __init__(self, fp):
  331. super().__init__(_PaddedFile(fp), zlib.decompressobj,
  332. wbits=-zlib.MAX_WBITS)
  333. # Set flag indicating start of a new member
  334. self._new_member = True
  335. self._last_mtime = None
  336. def _init_read(self):
  337. self._crc = zlib.crc32(b"")
  338. self._stream_size = 0 # Decompressed size of unconcatenated stream
  339. def _read_exact(self, n):
  340. '''Read exactly *n* bytes from `self._fp`
  341. This method is required because self._fp may be unbuffered,
  342. i.e. return short reads.
  343. '''
  344. data = self._fp.read(n)
  345. while len(data) < n:
  346. b = self._fp.read(n - len(data))
  347. if not b:
  348. raise EOFError("Compressed file ended before the "
  349. "end-of-stream marker was reached")
  350. data += b
  351. return data
  352. def _read_gzip_header(self):
  353. magic = self._fp.read(2)
  354. if magic == b'':
  355. return False
  356. if magic != b'\037\213':
  357. raise BadGzipFile('Not a gzipped file (%r)' % magic)
  358. (method, flag,
  359. self._last_mtime) = struct.unpack("<BBIxx", self._read_exact(8))
  360. if method != 8:
  361. raise BadGzipFile('Unknown compression method')
  362. if flag & FEXTRA:
  363. # Read & discard the extra field, if present
  364. extra_len, = struct.unpack("<H", self._read_exact(2))
  365. self._read_exact(extra_len)
  366. if flag & FNAME:
  367. # Read and discard a null-terminated string containing the filename
  368. while True:
  369. s = self._fp.read(1)
  370. if not s or s==b'\000':
  371. break
  372. if flag & FCOMMENT:
  373. # Read and discard a null-terminated string containing a comment
  374. while True:
  375. s = self._fp.read(1)
  376. if not s or s==b'\000':
  377. break
  378. if flag & FHCRC:
  379. self._read_exact(2) # Read & discard the 16-bit header CRC
  380. return True
  381. def read(self, size=-1):
  382. if size < 0:
  383. return self.readall()
  384. # size=0 is special because decompress(max_length=0) is not supported
  385. if not size:
  386. return b""
  387. # For certain input data, a single
  388. # call to decompress() may not return
  389. # any data. In this case, retry until we get some data or reach EOF.
  390. while True:
  391. if self._decompressor.eof:
  392. # Ending case: we've come to the end of a member in the file,
  393. # so finish up this member, and read a new gzip header.
  394. # Check the CRC and file size, and set the flag so we read
  395. # a new member
  396. self._read_eof()
  397. self._new_member = True
  398. self._decompressor = self._decomp_factory(
  399. **self._decomp_args)
  400. if self._new_member:
  401. # If the _new_member flag is set, we have to
  402. # jump to the next member, if there is one.
  403. self._init_read()
  404. if not self._read_gzip_header():
  405. self._size = self._pos
  406. return b""
  407. self._new_member = False
  408. # Read a chunk of data from the file
  409. buf = self._fp.read(io.DEFAULT_BUFFER_SIZE)
  410. uncompress = self._decompressor.decompress(buf, size)
  411. if self._decompressor.unconsumed_tail != b"":
  412. self._fp.prepend(self._decompressor.unconsumed_tail)
  413. elif self._decompressor.unused_data != b"":
  414. # Prepend the already read bytes to the fileobj so they can
  415. # be seen by _read_eof() and _read_gzip_header()
  416. self._fp.prepend(self._decompressor.unused_data)
  417. if uncompress != b"":
  418. break
  419. if buf == b"":
  420. raise EOFError("Compressed file ended before the "
  421. "end-of-stream marker was reached")
  422. self._add_read_data( uncompress )
  423. self._pos += len(uncompress)
  424. return uncompress
  425. def _add_read_data(self, data):
  426. self._crc = zlib.crc32(data, self._crc)
  427. self._stream_size = self._stream_size + len(data)
  428. def _read_eof(self):
  429. # We've read to the end of the file
  430. # We check that the computed CRC and size of the
  431. # uncompressed data matches the stored values. Note that the size
  432. # stored is the true file size mod 2**32.
  433. crc32, isize = struct.unpack("<II", self._read_exact(8))
  434. if crc32 != self._crc:
  435. raise BadGzipFile("CRC check failed %s != %s" % (hex(crc32),
  436. hex(self._crc)))
  437. elif isize != (self._stream_size & 0xffffffff):
  438. raise BadGzipFile("Incorrect length of data produced")
  439. # Gzip files can be padded with zeroes and still have archives.
  440. # Consume all zero bytes and set the file position to the first
  441. # non-zero byte. See http://www.gzip.org/#faq8
  442. c = b"\x00"
  443. while c == b"\x00":
  444. c = self._fp.read(1)
  445. if c:
  446. self._fp.prepend(c)
  447. def _rewind(self):
  448. super()._rewind()
  449. self._new_member = True
  450. def compress(data, compresslevel=_COMPRESS_LEVEL_BEST, *, mtime=None):
  451. """Compress data in one shot and return the compressed string.
  452. Optional argument is the compression level, in range of 0-9.
  453. """
  454. buf = io.BytesIO()
  455. with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel, mtime=mtime) as f:
  456. f.write(data)
  457. return buf.getvalue()
  458. def decompress(data):
  459. """Decompress a gzip compressed string in one shot.
  460. Return the decompressed string.
  461. """
  462. with GzipFile(fileobj=io.BytesIO(data)) as f:
  463. return f.read()
  464. def main():
  465. from argparse import ArgumentParser
  466. parser = ArgumentParser(description=
  467. "A simple command line interface for the gzip module: act like gzip, "
  468. "but do not delete the input file.")
  469. group = parser.add_mutually_exclusive_group()
  470. group.add_argument('--fast', action='store_true', help='compress faster')
  471. group.add_argument('--best', action='store_true', help='compress better')
  472. group.add_argument("-d", "--decompress", action="store_true",
  473. help="act like gunzip instead of gzip")
  474. parser.add_argument("args", nargs="*", default=["-"], metavar='file')
  475. args = parser.parse_args()
  476. compresslevel = _COMPRESS_LEVEL_TRADEOFF
  477. if args.fast:
  478. compresslevel = _COMPRESS_LEVEL_FAST
  479. elif args.best:
  480. compresslevel = _COMPRESS_LEVEL_BEST
  481. for arg in args.args:
  482. if args.decompress:
  483. if arg == "-":
  484. f = GzipFile(filename="", mode="rb", fileobj=sys.stdin.buffer)
  485. g = sys.stdout.buffer
  486. else:
  487. if arg[-3:] != ".gz":
  488. sys.exit(f"filename doesn't end in .gz: {arg!r}")
  489. f = open(arg, "rb")
  490. g = builtins.open(arg[:-3], "wb")
  491. else:
  492. if arg == "-":
  493. f = sys.stdin.buffer
  494. g = GzipFile(filename="", mode="wb", fileobj=sys.stdout.buffer,
  495. compresslevel=compresslevel)
  496. else:
  497. f = builtins.open(arg, "rb")
  498. g = open(arg + ".gz", "wb")
  499. while True:
  500. chunk = f.read(1024)
  501. if not chunk:
  502. break
  503. g.write(chunk)
  504. if g is not sys.stdout.buffer:
  505. g.close()
  506. if f is not sys.stdin.buffer:
  507. f.close()
  508. if __name__ == '__main__':
  509. main()