gzip.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 io
  8. import __builtin__
  9. __all__ = ["GzipFile","open"]
  10. FTEXT, FHCRC, FEXTRA, FNAME, FCOMMENT = 1, 2, 4, 8, 16
  11. READ, WRITE = 1, 2
  12. def write32u(output, value):
  13. # The L format writes the bit pattern correctly whether signed
  14. # or unsigned.
  15. output.write(struct.pack("<L", value))
  16. def read32(input):
  17. return struct.unpack("<I", input.read(4))[0]
  18. def open(filename, mode="rb", compresslevel=9):
  19. """Shorthand for GzipFile(filename, mode, compresslevel).
  20. The filename argument is required; mode defaults to 'rb'
  21. and compresslevel defaults to 9.
  22. """
  23. return GzipFile(filename, mode, compresslevel)
  24. class GzipFile(io.BufferedIOBase):
  25. """The GzipFile class simulates most of the methods of a file object with
  26. the exception of the readinto() and truncate() methods.
  27. """
  28. myfileobj = None
  29. max_read_chunk = 10 * 1024 * 1024 # 10Mb
  30. def __init__(self, filename=None, mode=None,
  31. compresslevel=9, fileobj=None, mtime=None):
  32. """Constructor for the GzipFile class.
  33. At least one of fileobj and filename must be given a
  34. non-trivial value.
  35. The new class instance is based on fileobj, which can be a regular
  36. file, a StringIO object, or any other object which simulates a file.
  37. It defaults to None, in which case filename is opened to provide
  38. a file object.
  39. When fileobj is not None, the filename argument is only used to be
  40. included in the gzip file header, which may include the original
  41. filename of the uncompressed file. It defaults to the filename of
  42. fileobj, if discernible; otherwise, it defaults to the empty string,
  43. and in this case the original filename is not included in the header.
  44. The mode argument can be any of 'r', 'rb', 'a', 'ab', 'w', or 'wb',
  45. depending on whether the file will be read or written. The default
  46. is the mode of fileobj if discernible; otherwise, the default is 'rb'.
  47. Be aware that only the 'rb', 'ab', and 'wb' values should be used
  48. for cross-platform portability.
  49. The compresslevel argument is an integer from 0 to 9 controlling the
  50. level of compression; 1 is fastest and produces the least compression,
  51. and 9 is slowest and produces the most compression. 0 is no compression
  52. at all. The default is 9.
  53. The mtime argument is an optional numeric timestamp to be written
  54. to the stream when compressing. All gzip compressed streams
  55. are required to contain a timestamp. If omitted or None, the
  56. current time is used. This module ignores the timestamp when
  57. decompressing; however, some programs, such as gunzip, make use
  58. of it. The format of the timestamp is the same as that of the
  59. return value of time.time() and of the st_mtime member of the
  60. object returned by os.stat().
  61. """
  62. # Make sure we don't inadvertently enable universal newlines on the
  63. # underlying file object - in read mode, this causes data corruption.
  64. if mode:
  65. mode = mode.replace('U', '')
  66. # guarantee the file is opened in binary mode on platforms
  67. # that care about that sort of thing
  68. if mode and 'b' not in mode:
  69. mode += 'b'
  70. if fileobj is None:
  71. fileobj = self.myfileobj = __builtin__.open(filename, mode or 'rb')
  72. if filename is None:
  73. # Issue #13781: os.fdopen() creates a fileobj with a bogus name
  74. # attribute. Avoid saving this in the gzip header's filename field.
  75. if hasattr(fileobj, 'name') and fileobj.name != '<fdopen>':
  76. filename = fileobj.name
  77. else:
  78. filename = ''
  79. if mode is None:
  80. if hasattr(fileobj, 'mode'): mode = fileobj.mode
  81. else: mode = 'rb'
  82. if mode[0:1] == 'r':
  83. self.mode = READ
  84. # Set flag indicating start of a new member
  85. self._new_member = True
  86. # Buffer data read from gzip file. extrastart is offset in
  87. # stream where buffer starts. extrasize is number of
  88. # bytes remaining in buffer from current stream position.
  89. self.extrabuf = ""
  90. self.extrasize = 0
  91. self.extrastart = 0
  92. self.name = filename
  93. # Starts small, scales exponentially
  94. self.min_readsize = 100
  95. elif mode[0:1] == 'w' or mode[0:1] == 'a':
  96. self.mode = WRITE
  97. self._init_write(filename)
  98. self.compress = zlib.compressobj(compresslevel,
  99. zlib.DEFLATED,
  100. -zlib.MAX_WBITS,
  101. zlib.DEF_MEM_LEVEL,
  102. 0)
  103. else:
  104. raise IOError, "Mode " + mode + " not supported"
  105. self.fileobj = fileobj
  106. self.offset = 0
  107. self.mtime = mtime
  108. if self.mode == WRITE:
  109. self._write_gzip_header()
  110. @property
  111. def filename(self):
  112. import warnings
  113. warnings.warn("use the name attribute", DeprecationWarning, 2)
  114. if self.mode == WRITE and self.name[-3:] != ".gz":
  115. return self.name + ".gz"
  116. return self.name
  117. def __repr__(self):
  118. s = repr(self.fileobj)
  119. return '<gzip ' + s[1:-1] + ' ' + hex(id(self)) + '>'
  120. def _check_closed(self):
  121. """Raises a ValueError if the underlying file object has been closed.
  122. """
  123. if self.closed:
  124. raise ValueError('I/O operation on closed file.')
  125. def _init_write(self, filename):
  126. self.name = filename
  127. self.crc = zlib.crc32("") & 0xffffffffL
  128. self.size = 0
  129. self.writebuf = []
  130. self.bufsize = 0
  131. def _write_gzip_header(self):
  132. self.fileobj.write('\037\213') # magic header
  133. self.fileobj.write('\010') # compression method
  134. try:
  135. # RFC 1952 requires the FNAME field to be Latin-1. Do not
  136. # include filenames that cannot be represented that way.
  137. fname = os.path.basename(self.name)
  138. if not isinstance(fname, str):
  139. fname = fname.encode('latin-1')
  140. if fname.endswith('.gz'):
  141. fname = fname[:-3]
  142. except UnicodeEncodeError:
  143. fname = ''
  144. flags = 0
  145. if fname:
  146. flags = FNAME
  147. self.fileobj.write(chr(flags))
  148. mtime = self.mtime
  149. if mtime is None:
  150. mtime = time.time()
  151. write32u(self.fileobj, long(mtime))
  152. self.fileobj.write('\002')
  153. self.fileobj.write('\377')
  154. if fname:
  155. self.fileobj.write(fname + '\000')
  156. def _init_read(self):
  157. self.crc = zlib.crc32("") & 0xffffffffL
  158. self.size = 0
  159. def _read_gzip_header(self):
  160. magic = self.fileobj.read(2)
  161. if magic != '\037\213':
  162. raise IOError, 'Not a gzipped file'
  163. method = ord( self.fileobj.read(1) )
  164. if method != 8:
  165. raise IOError, 'Unknown compression method'
  166. flag = ord( self.fileobj.read(1) )
  167. self.mtime = read32(self.fileobj)
  168. # extraflag = self.fileobj.read(1)
  169. # os = self.fileobj.read(1)
  170. self.fileobj.read(2)
  171. if flag & FEXTRA:
  172. # Read & discard the extra field, if present
  173. xlen = ord(self.fileobj.read(1))
  174. xlen = xlen + 256*ord(self.fileobj.read(1))
  175. self.fileobj.read(xlen)
  176. if flag & FNAME:
  177. # Read and discard a null-terminated string containing the filename
  178. while True:
  179. s = self.fileobj.read(1)
  180. if not s or s=='\000':
  181. break
  182. if flag & FCOMMENT:
  183. # Read and discard a null-terminated string containing a comment
  184. while True:
  185. s = self.fileobj.read(1)
  186. if not s or s=='\000':
  187. break
  188. if flag & FHCRC:
  189. self.fileobj.read(2) # Read & discard the 16-bit header CRC
  190. def write(self,data):
  191. self._check_closed()
  192. if self.mode != WRITE:
  193. import errno
  194. raise IOError(errno.EBADF, "write() on read-only GzipFile object")
  195. if self.fileobj is None:
  196. raise ValueError, "write() on closed GzipFile object"
  197. # Convert data type if called by io.BufferedWriter.
  198. if isinstance(data, memoryview):
  199. data = data.tobytes()
  200. if len(data) > 0:
  201. self.fileobj.write(self.compress.compress(data))
  202. self.size += len(data)
  203. self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
  204. self.offset += len(data)
  205. return len(data)
  206. def read(self, size=-1):
  207. self._check_closed()
  208. if self.mode != READ:
  209. import errno
  210. raise IOError(errno.EBADF, "read() on write-only GzipFile object")
  211. if self.extrasize <= 0 and self.fileobj is None:
  212. return ''
  213. readsize = 1024
  214. if size < 0: # get the whole thing
  215. try:
  216. while True:
  217. self._read(readsize)
  218. readsize = min(self.max_read_chunk, readsize * 2)
  219. except EOFError:
  220. size = self.extrasize
  221. else: # just get some more of it
  222. try:
  223. while size > self.extrasize:
  224. self._read(readsize)
  225. readsize = min(self.max_read_chunk, readsize * 2)
  226. except EOFError:
  227. if size > self.extrasize:
  228. size = self.extrasize
  229. offset = self.offset - self.extrastart
  230. chunk = self.extrabuf[offset: offset + size]
  231. self.extrasize = self.extrasize - size
  232. self.offset += size
  233. return chunk
  234. def _unread(self, buf):
  235. self.extrasize = len(buf) + self.extrasize
  236. self.offset -= len(buf)
  237. def _read(self, size=1024):
  238. if self.fileobj is None:
  239. raise EOFError, "Reached EOF"
  240. if self._new_member:
  241. # If the _new_member flag is set, we have to
  242. # jump to the next member, if there is one.
  243. #
  244. # First, check if we're at the end of the file;
  245. # if so, it's time to stop; no more members to read.
  246. pos = self.fileobj.tell() # Save current position
  247. self.fileobj.seek(0, 2) # Seek to end of file
  248. if pos == self.fileobj.tell():
  249. raise EOFError, "Reached EOF"
  250. else:
  251. self.fileobj.seek( pos ) # Return to original position
  252. self._init_read()
  253. self._read_gzip_header()
  254. self.decompress = zlib.decompressobj(-zlib.MAX_WBITS)
  255. self._new_member = False
  256. # Read a chunk of data from the file
  257. buf = self.fileobj.read(size)
  258. # If the EOF has been reached, flush the decompression object
  259. # and mark this object as finished.
  260. if buf == "":
  261. uncompress = self.decompress.flush()
  262. self._read_eof()
  263. self._add_read_data( uncompress )
  264. raise EOFError, 'Reached EOF'
  265. uncompress = self.decompress.decompress(buf)
  266. self._add_read_data( uncompress )
  267. if self.decompress.unused_data != "":
  268. # Ending case: we've come to the end of a member in the file,
  269. # so seek back to the start of the unused data, finish up
  270. # this member, and read a new gzip header.
  271. # (The number of bytes to seek back is the length of the unused
  272. # data, minus 8 because _read_eof() will rewind a further 8 bytes)
  273. self.fileobj.seek( -len(self.decompress.unused_data)+8, 1)
  274. # Check the CRC and file size, and set the flag so we read
  275. # a new member on the next call
  276. self._read_eof()
  277. self._new_member = True
  278. def _add_read_data(self, data):
  279. self.crc = zlib.crc32(data, self.crc) & 0xffffffffL
  280. offset = self.offset - self.extrastart
  281. self.extrabuf = self.extrabuf[offset:] + data
  282. self.extrasize = self.extrasize + len(data)
  283. self.extrastart = self.offset
  284. self.size = self.size + len(data)
  285. def _read_eof(self):
  286. # We've read to the end of the file, so we have to rewind in order
  287. # to reread the 8 bytes containing the CRC and the file size.
  288. # We check the that the computed CRC and size of the
  289. # uncompressed data matches the stored values. Note that the size
  290. # stored is the true file size mod 2**32.
  291. self.fileobj.seek(-8, 1)
  292. crc32 = read32(self.fileobj)
  293. isize = read32(self.fileobj) # may exceed 2GB
  294. if crc32 != self.crc:
  295. raise IOError("CRC check failed %s != %s" % (hex(crc32),
  296. hex(self.crc)))
  297. elif isize != (self.size & 0xffffffffL):
  298. raise IOError, "Incorrect length of data produced"
  299. # Gzip files can be padded with zeroes and still have archives.
  300. # Consume all zero bytes and set the file position to the first
  301. # non-zero byte. See http://www.gzip.org/#faq8
  302. c = "\x00"
  303. while c == "\x00":
  304. c = self.fileobj.read(1)
  305. if c:
  306. self.fileobj.seek(-1, 1)
  307. @property
  308. def closed(self):
  309. return self.fileobj is None
  310. def close(self):
  311. fileobj = self.fileobj
  312. if fileobj is None:
  313. return
  314. self.fileobj = None
  315. try:
  316. if self.mode == WRITE:
  317. fileobj.write(self.compress.flush())
  318. write32u(fileobj, self.crc)
  319. # self.size may exceed 2GB, or even 4GB
  320. write32u(fileobj, self.size & 0xffffffffL)
  321. finally:
  322. myfileobj = self.myfileobj
  323. if myfileobj:
  324. self.myfileobj = None
  325. myfileobj.close()
  326. def flush(self,zlib_mode=zlib.Z_SYNC_FLUSH):
  327. self._check_closed()
  328. if self.mode == WRITE:
  329. # Ensure the compressor's buffer is flushed
  330. self.fileobj.write(self.compress.flush(zlib_mode))
  331. self.fileobj.flush()
  332. def fileno(self):
  333. """Invoke the underlying file object's fileno() method.
  334. This will raise AttributeError if the underlying file object
  335. doesn't support fileno().
  336. """
  337. return self.fileobj.fileno()
  338. def rewind(self):
  339. '''Return the uncompressed stream file position indicator to the
  340. beginning of the file'''
  341. if self.mode != READ:
  342. raise IOError("Can't rewind in write mode")
  343. self.fileobj.seek(0)
  344. self._new_member = True
  345. self.extrabuf = ""
  346. self.extrasize = 0
  347. self.extrastart = 0
  348. self.offset = 0
  349. def readable(self):
  350. return self.mode == READ
  351. def writable(self):
  352. return self.mode == WRITE
  353. def seekable(self):
  354. return True
  355. def seek(self, offset, whence=0):
  356. if whence:
  357. if whence == 1:
  358. offset = self.offset + offset
  359. else:
  360. raise ValueError('Seek from end not supported')
  361. if self.mode == WRITE:
  362. if offset < self.offset:
  363. raise IOError('Negative seek in write mode')
  364. count = offset - self.offset
  365. for i in xrange(count // 1024):
  366. self.write(1024 * '\0')
  367. self.write((count % 1024) * '\0')
  368. elif self.mode == READ:
  369. if offset < self.offset:
  370. # for negative seek, rewind and do positive seek
  371. self.rewind()
  372. count = offset - self.offset
  373. for i in xrange(count // 1024):
  374. self.read(1024)
  375. self.read(count % 1024)
  376. return self.offset
  377. def readline(self, size=-1):
  378. if size < 0:
  379. # Shortcut common case - newline found in buffer.
  380. offset = self.offset - self.extrastart
  381. i = self.extrabuf.find('\n', offset) + 1
  382. if i > 0:
  383. self.extrasize -= i - offset
  384. self.offset += i - offset
  385. return self.extrabuf[offset: i]
  386. size = sys.maxint
  387. readsize = self.min_readsize
  388. else:
  389. readsize = size
  390. bufs = []
  391. while size != 0:
  392. c = self.read(readsize)
  393. i = c.find('\n')
  394. # We set i=size to break out of the loop under two
  395. # conditions: 1) there's no newline, and the chunk is
  396. # larger than size, or 2) there is a newline, but the
  397. # resulting line would be longer than 'size'.
  398. if (size <= i) or (i == -1 and len(c) > size):
  399. i = size - 1
  400. if i >= 0 or c == '':
  401. bufs.append(c[:i + 1]) # Add portion of last chunk
  402. self._unread(c[i + 1:]) # Push back rest of chunk
  403. break
  404. # Append chunk to list, decrease 'size',
  405. bufs.append(c)
  406. size = size - len(c)
  407. readsize = min(size, readsize * 2)
  408. if readsize > self.min_readsize:
  409. self.min_readsize = min(readsize, self.min_readsize * 2, 512)
  410. return ''.join(bufs) # Return resulting line
  411. def _test():
  412. # Act like gzip; with -d, act like gunzip.
  413. # The input file is not deleted, however, nor are any other gzip
  414. # options or features supported.
  415. args = sys.argv[1:]
  416. decompress = args and args[0] == "-d"
  417. if decompress:
  418. args = args[1:]
  419. if not args:
  420. args = ["-"]
  421. for arg in args:
  422. if decompress:
  423. if arg == "-":
  424. f = GzipFile(filename="", mode="rb", fileobj=sys.stdin)
  425. g = sys.stdout
  426. else:
  427. if arg[-3:] != ".gz":
  428. print "filename doesn't end in .gz:", repr(arg)
  429. continue
  430. f = open(arg, "rb")
  431. g = __builtin__.open(arg[:-3], "wb")
  432. else:
  433. if arg == "-":
  434. f = sys.stdin
  435. g = GzipFile(filename="", mode="wb", fileobj=sys.stdout)
  436. else:
  437. f = __builtin__.open(arg, "rb")
  438. g = open(arg + ".gz", "wb")
  439. while True:
  440. chunk = f.read(1024)
  441. if not chunk:
  442. break
  443. g.write(chunk)
  444. if g is not sys.stdout:
  445. g.close()
  446. if f is not sys.stdin:
  447. f.close()
  448. if __name__ == '__main__':
  449. _test()