gzip.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. if mode is None:
  142. mode = getattr(fileobj, 'mode', 'rb')
  143. if mode.startswith('r'):
  144. self.mode = READ
  145. raw = _GzipReader(fileobj)
  146. self._buffer = io.BufferedReader(raw)
  147. self.name = filename
  148. elif mode.startswith(('w', 'a', 'x')):
  149. self.mode = WRITE
  150. self._init_write(filename)
  151. self.compress = zlib.compressobj(compresslevel,
  152. zlib.DEFLATED,
  153. -zlib.MAX_WBITS,
  154. zlib.DEF_MEM_LEVEL,
  155. 0)
  156. self._write_mtime = mtime
  157. else:
  158. raise ValueError("Invalid mode: {!r}".format(mode))
  159. self.fileobj = fileobj
  160. if self.mode == WRITE:
  161. self._write_gzip_header(compresslevel)
  162. @property
  163. def filename(self):
  164. import warnings
  165. warnings.warn("use the name attribute", DeprecationWarning, 2)
  166. if self.mode == WRITE and self.name[-3:] != ".gz":
  167. return self.name + ".gz"
  168. return self.name
  169. @property
  170. def mtime(self):
  171. """Last modification time read from stream, or None"""
  172. return self._buffer.raw._last_mtime
  173. def __repr__(self):
  174. s = repr(self.fileobj)
  175. return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  176. def _init_write(self, filename):
  177. self.name = filename
  178. self.crc = zlib.crc32(b"")
  179. self.size = 0
  180. self.writebuf = []
  181. self.bufsize = 0
  182. self.offset = 0 # Current file offset for seek(), tell(), etc
  183. def _write_gzip_header(self, compresslevel):
  184. self.fileobj.write(b'\037\213') # magic header
  185. self.fileobj.write(b'\010') # compression method
  186. try:
  187. # RFC 1952 requires the FNAME field to be Latin-1. Do not
  188. # include filenames that cannot be represented that way.
  189. fname = os.path.basename(self.name)
  190. if not isinstance(fname, bytes):
  191. fname = fname.encode('latin-1')
  192. if fname.endswith(b'.gz'):
  193. fname = fname[:-3]
  194. except UnicodeEncodeError:
  195. fname = b''
  196. flags = 0
  197. if fname:
  198. flags = FNAME
  199. self.fileobj.write(chr(flags).encode('latin-1'))
  200. mtime = self._write_mtime
  201. if mtime is None:
  202. mtime = time.time()
  203. write32u(self.fileobj, int(mtime))
  204. if compresslevel == _COMPRESS_LEVEL_BEST:
  205. xfl = b'\002'
  206. elif compresslevel == _COMPRESS_LEVEL_FAST:
  207. xfl = b'\004'
  208. else:
  209. xfl = b'\000'
  210. self.fileobj.write(xfl)
  211. self.fileobj.write(b'\377')
  212. if fname:
  213. self.fileobj.write(fname + b'\000')
  214. def write(self,data):
  215. self._check_not_closed()
  216. if self.mode != WRITE:
  217. import errno
  218. raise OSError(errno.EBADF, "write() on read-only GzipFile object")
  219. if self.fileobj is None:
  220. raise ValueError("write() on closed GzipFile object")
  221. if isinstance(data, bytes):
  222. length = len(data)
  223. else:
  224. # accept any data that supports the buffer protocol
  225. data = memoryview(data)
  226. length = data.nbytes
  227. if length > 0:
  228. self.fileobj.write(self.compress.compress(data))
  229. self.size += length
  230. self.crc = zlib.crc32(data, self.crc)
  231. self.offset += length
  232. return length
  233. def read(self, size=-1):
  234. self._check_not_closed()
  235. if self.mode != READ:
  236. import errno
  237. raise OSError(errno.EBADF, "read() on write-only GzipFile object")
  238. return self._buffer.read(size)
  239. def read1(self, size=-1):
  240. """Implements BufferedIOBase.read1()
  241. Reads up to a buffer's worth of data if size is negative."""
  242. self._check_not_closed()
  243. if self.mode != READ:
  244. import errno
  245. raise OSError(errno.EBADF, "read1() on write-only GzipFile object")
  246. if size < 0:
  247. size = io.DEFAULT_BUFFER_SIZE
  248. return self._buffer.read1(size)
  249. def peek(self, n):
  250. self._check_not_closed()
  251. if self.mode != READ:
  252. import errno
  253. raise OSError(errno.EBADF, "peek() on write-only GzipFile object")
  254. return self._buffer.peek(n)
  255. @property
  256. def closed(self):
  257. return self.fileobj is None
  258. def close(self):
  259. fileobj = self.fileobj
  260. if fileobj is None:
  261. return
  262. self.fileobj = None
  263. try:
  264. if self.mode == WRITE:
  265. fileobj.write(self.compress.flush())
  266. write32u(fileobj, self.crc)
  267. # self.size may exceed 2 GiB, or even 4 GiB
  268. write32u(fileobj, self.size & 0xffffffff)
  269. elif self.mode == READ:
  270. self._buffer.close()
  271. finally:
  272. myfileobj = self.myfileobj
  273. if myfileobj:
  274. self.myfileobj = None
  275. myfileobj.close()
  276. def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
  277. self._check_not_closed()
  278. if self.mode == WRITE:
  279. # Ensure the compressor's buffer is flushed
  280. self.fileobj.write(self.compress.flush(zlib_mode))
  281. self.fileobj.flush()
  282. def fileno(self):
  283. """Invoke the underlying file object's fileno() method.
  284. This will raise AttributeError if the underlying file object
  285. doesn't support fileno().
  286. """
  287. return self.fileobj.fileno()
  288. def rewind(self):
  289. '''Return the uncompressed stream file position indicator to the
  290. beginning of the file'''
  291. if self.mode != READ:
  292. raise OSError("Can't rewind in write mode")
  293. self._buffer.seek(0)
  294. def readable(self):
  295. return self.mode == READ
  296. def writable(self):
  297. return self.mode == WRITE
  298. def seekable(self):
  299. return True
  300. def seek(self, offset, whence=io.SEEK_SET):
  301. if self.mode == WRITE:
  302. if whence != io.SEEK_SET:
  303. if whence == io.SEEK_CUR:
  304. offset = self.offset + offset
  305. else:
  306. raise ValueError('Seek from end not supported')
  307. if offset < self.offset:
  308. raise OSError('Negative seek in write mode')
  309. count = offset - self.offset
  310. chunk = b'\0' * 1024
  311. for i in range(count // 1024):
  312. self.write(chunk)
  313. self.write(b'\0' * (count % 1024))
  314. elif self.mode == READ:
  315. self._check_not_closed()
  316. return self._buffer.seek(offset, whence)
  317. return self.offset
  318. def readline(self, size=-1):
  319. self._check_not_closed()
  320. return self._buffer.readline(size)
  321. class _GzipReader(_compression.DecompressReader):
  322. def __init__(self, fp):
  323. super().__init__(_PaddedFile(fp), zlib.decompressobj,
  324. wbits=-zlib.MAX_WBITS)
  325. # Set flag indicating start of a new member
  326. self._new_member = True
  327. self._last_mtime = None
  328. def _init_read(self):
  329. self._crc = zlib.crc32(b"")
  330. self._stream_size = 0 # Decompressed size of unconcatenated stream
  331. def _read_exact(self, n):
  332. '''Read exactly *n* bytes from `self._fp`
  333. This method is required because self._fp may be unbuffered,
  334. i.e. return short reads.
  335. '''
  336. data = self._fp.read(n)
  337. while len(data) < n:
  338. b = self._fp.read(n - len(data))
  339. if not b:
  340. raise EOFError("Compressed file ended before the "
  341. "end-of-stream marker was reached")
  342. data += b
  343. return data
  344. def _read_gzip_header(self):
  345. magic = self._fp.read(2)
  346. if magic == b'':
  347. return False
  348. if magic != b'\037\213':
  349. raise BadGzipFile('Not a gzipped file (%r)' % magic)
  350. (method, flag,
  351. self._last_mtime) = struct.unpack("<BBIxx", self._read_exact(8))
  352. if method != 8:
  353. raise BadGzipFile('Unknown compression method')
  354. if flag & FEXTRA:
  355. # Read & discard the extra field, if present
  356. extra_len, = struct.unpack("<H", self._read_exact(2))
  357. self._read_exact(extra_len)
  358. if flag & FNAME:
  359. # Read and discard a null-terminated string containing the filename
  360. while True:
  361. s = self._fp.read(1)
  362. if not s or s==b'\000':
  363. break
  364. if flag & FCOMMENT:
  365. # Read and discard a null-terminated string containing a comment
  366. while True:
  367. s = self._fp.read(1)
  368. if not s or s==b'\000':
  369. break
  370. if flag & FHCRC:
  371. self._read_exact(2) # Read & discard the 16-bit header CRC
  372. return True
  373. def read(self, size=-1):
  374. if size < 0:
  375. return self.readall()
  376. # size=0 is special because decompress(max_length=0) is not supported
  377. if not size:
  378. return b""
  379. # For certain input data, a single
  380. # call to decompress() may not return
  381. # any data. In this case, retry until we get some data or reach EOF.
  382. while True:
  383. if self._decompressor.eof:
  384. # Ending case: we've come to the end of a member in the file,
  385. # so finish up this member, and read a new gzip header.
  386. # Check the CRC and file size, and set the flag so we read
  387. # a new member
  388. self._read_eof()
  389. self._new_member = True
  390. self._decompressor = self._decomp_factory(
  391. **self._decomp_args)
  392. if self._new_member:
  393. # If the _new_member flag is set, we have to
  394. # jump to the next member, if there is one.
  395. self._init_read()
  396. if not self._read_gzip_header():
  397. self._size = self._pos
  398. return b""
  399. self._new_member = False
  400. # Read a chunk of data from the file
  401. buf = self._fp.read(io.DEFAULT_BUFFER_SIZE)
  402. uncompress = self._decompressor.decompress(buf, size)
  403. if self._decompressor.unconsumed_tail != b"":
  404. self._fp.prepend(self._decompressor.unconsumed_tail)
  405. elif self._decompressor.unused_data != b"":
  406. # Prepend the already read bytes to the fileobj so they can
  407. # be seen by _read_eof() and _read_gzip_header()
  408. self._fp.prepend(self._decompressor.unused_data)
  409. if uncompress != b"":
  410. break
  411. if buf == b"":
  412. raise EOFError("Compressed file ended before the "
  413. "end-of-stream marker was reached")
  414. self._add_read_data( uncompress )
  415. self._pos += len(uncompress)
  416. return uncompress
  417. def _add_read_data(self, data):
  418. self._crc = zlib.crc32(data, self._crc)
  419. self._stream_size = self._stream_size + len(data)
  420. def _read_eof(self):
  421. # We've read to the end of the file
  422. # We check the that the computed CRC and size of the
  423. # uncompressed data matches the stored values. Note that the size
  424. # stored is the true file size mod 2**32.
  425. crc32, isize = struct.unpack("<II", self._read_exact(8))
  426. if crc32 != self._crc:
  427. raise BadGzipFile("CRC check failed %s != %s" % (hex(crc32),
  428. hex(self._crc)))
  429. elif isize != (self._stream_size & 0xffffffff):
  430. raise BadGzipFile("Incorrect length of data produced")
  431. # Gzip files can be padded with zeroes and still have archives.
  432. # Consume all zero bytes and set the file position to the first
  433. # non-zero byte. See http://www.gzip.org/#faq8
  434. c = b"\x00"
  435. while c == b"\x00":
  436. c = self._fp.read(1)
  437. if c:
  438. self._fp.prepend(c)
  439. def _rewind(self):
  440. super()._rewind()
  441. self._new_member = True
  442. def compress(data, compresslevel=_COMPRESS_LEVEL_BEST, *, mtime=None):
  443. """Compress data in one shot and return the compressed string.
  444. Optional argument is the compression level, in range of 0-9.
  445. """
  446. buf = io.BytesIO()
  447. with GzipFile(fileobj=buf, mode='wb', compresslevel=compresslevel, mtime=mtime) as f:
  448. f.write(data)
  449. return buf.getvalue()
  450. def decompress(data):
  451. """Decompress a gzip compressed string in one shot.
  452. Return the decompressed string.
  453. """
  454. with GzipFile(fileobj=io.BytesIO(data)) as f:
  455. return f.read()
  456. def main():
  457. from argparse import ArgumentParser
  458. parser = ArgumentParser(description=
  459. "A simple command line interface for the gzip module: act like gzip, "
  460. "but do not delete the input file.")
  461. group = parser.add_mutually_exclusive_group()
  462. group.add_argument('--fast', action='store_true', help='compress faster')
  463. group.add_argument('--best', action='store_true', help='compress better')
  464. group.add_argument("-d", "--decompress", action="store_true",
  465. help="act like gunzip instead of gzip")
  466. parser.add_argument("args", nargs="*", default=["-"], metavar='file')
  467. args = parser.parse_args()
  468. compresslevel = _COMPRESS_LEVEL_TRADEOFF
  469. if args.fast:
  470. compresslevel = _COMPRESS_LEVEL_FAST
  471. elif args.best:
  472. compresslevel = _COMPRESS_LEVEL_BEST
  473. for arg in args.args:
  474. if args.decompress:
  475. if arg == "-":
  476. f = GzipFile(filename="", mode="rb", fileobj=sys.stdin.buffer)
  477. g = sys.stdout.buffer
  478. else:
  479. if arg[-3:] != ".gz":
  480. print("filename doesn't end in .gz:", repr(arg))
  481. continue
  482. f = open(arg, "rb")
  483. g = builtins.open(arg[:-3], "wb")
  484. else:
  485. if arg == "-":
  486. f = sys.stdin.buffer
  487. g = GzipFile(filename="", mode="wb", fileobj=sys.stdout.buffer,
  488. compresslevel=compresslevel)
  489. else:
  490. f = builtins.open(arg, "rb")
  491. g = open(arg + ".gz", "wb")
  492. while True:
  493. chunk = f.read(1024)
  494. if not chunk:
  495. break
  496. g.write(chunk)
  497. if g is not sys.stdout.buffer:
  498. g.close()
  499. if f is not sys.stdin.buffer:
  500. f.close()
  501. if __name__ == '__main__':
  502. main()