gzip.py 20 KB

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