1
2
3 """GNU zip."""
4 from __future__ import print_function
5 from __future__ import absolute_import
6
7 import struct
8 import zlib
9 import binascii
10
11 from . import dpkt
12
13
14
15 GZIP_MAGIC = b'\x1f\x8b'
16
17
18 GZIP_MSTORED = 0
19 GZIP_MCOMPRESS = 1
20 GZIP_MPACKED = 2
21 GZIP_MLZHED = 3
22 GZIP_MDEFLATE = 8
23
24
25 GZIP_FTEXT = 0x01
26 GZIP_FHCRC = 0x02
27 GZIP_FEXTRA = 0x04
28 GZIP_FNAME = 0x08
29 GZIP_FCOMMENT = 0x10
30 GZIP_FENCRYPT = 0x20
31 GZIP_FRESERVED = 0xC0
32
33
34 GZIP_OS_MSDOS = 0
35 GZIP_OS_AMIGA = 1
36 GZIP_OS_VMS = 2
37 GZIP_OS_UNIX = 3
38 GZIP_OS_VMCMS = 4
39 GZIP_OS_ATARI = 5
40 GZIP_OS_OS2 = 6
41 GZIP_OS_MACOS = 7
42 GZIP_OS_ZSYSTEM = 8
43 GZIP_OS_CPM = 9
44 GZIP_OS_TOPS20 = 10
45 GZIP_OS_WIN32 = 11
46 GZIP_OS_QDOS = 12
47 GZIP_OS_RISCOS = 13
48 GZIP_OS_UNKNOWN = 255
49
50 GZIP_FENCRYPT_LEN = 12
59
60
61 -class Gzip(dpkt.Packet):
62 __byte_order__ = '<'
63 __hdr__ = (
64 ('magic', '2s', GZIP_MAGIC),
65 ('method', 'B', GZIP_MDEFLATE),
66 ('flags', 'B', 0),
67 ('mtime', 'I', 0),
68 ('xflags', 'B', 0),
69 ('os', 'B', GZIP_OS_UNIX),
70
71 ('extra', '0s', ''),
72 ('filename', '0s', ''),
73 ('comment', '0s', '')
74 )
75
106
124
126 """Compress self.data."""
127 c = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS,
128 zlib.DEF_MEM_LEVEL, 0)
129 self.data = c.compress(self.data)
130
132 """Return decompressed payload."""
133 d = zlib.decompressobj(-zlib.MAX_WBITS)
134 return d.decompress(self.data)
135
136
137 _hexdecode = binascii.a2b_hex
140
141 """This data is created with the gzip command line tool"""
142
143 @classmethod
145 cls.data = _hexdecode(b'1F8B'
146 b'080880C185560003'
147 b'68656C6C6F2E74787400'
148 b'F348CDC9C95728CF2FCA4951E40200'
149 b'41E4A9B20D000000')
150 cls.p = Gzip(cls.data)
151
154
157
159
160 assert (self.p.mtime == 0x5685c180)
161
164
167
170
173
174
175 if __name__ == '__main__':
176 import sys
177
178 gz = Gzip(open(sys.argv[1]).read())
179 print(repr(gz), repr(gz.decompress()))
180