Debian Codegraph @

mechanize/_gzip.py

raw symbols SCIP
1 from __future__ import absolute_import
2
3 import struct
4 import zlib
5 from io import DEFAULT_BUFFER_SIZE
6
7 from ._urllib2_fork import BaseHandler
8 from .polyglot import is_py2
9
10
11 CRC_MASK = 0xffffffff
12 if is_py2:
13 CRC_MASK = long(CRC_MASK)
14
15
16 def gzip_prefix():
17 # See http://www.gzip.org/zlib/rfc-gzip.html
18 return b''.join((
19 b'\x1f\x8b', # ID1 and ID2: gzip marker
20 b'\x08', # CM: compression method
21 b'\x00', # FLG: none set
22 # MTIME: 4 bytes, set to zero so as not to leak timezone information
23 b'\0\0\0\0',
24 b'\x02', # XFL: max compression, slowest algo
25 b'\xff', # OS: unknown
26 ))
27
28
29 def compress_readable_output(src_file, compress_level=6):
30 crc = zlib.crc32(b"")
31 size = 0
32 zobj = zlib.compressobj(compress_level, zlib.DEFLATED, -zlib.MAX_WBITS,
33 zlib.DEF_MEM_LEVEL, zlib.Z_DEFAULT_STRATEGY)
34 prefix_written = False
35 while True:
36 data = src_file.read(DEFAULT_BUFFER_SIZE)
37 if not data:
38 break
39 size += len(data)
40 crc = zlib.crc32(data, crc)
41 data = zobj.compress(data)
42 if not prefix_written:
43 prefix_written = True
44 data = gzip_prefix() + data
45 yield data
46 yield zobj.flush() + struct.pack(b"<LL", crc & CRC_MASK, size)
47
48
49 def read_amt(f, amt):
50 ans = b''
51 while len(ans) < amt:
52 extra = f.read(amt - len(ans))
53 if not extra:
54 raise EOFError('Unexpected end of compressed stream')
55 ans += extra
56 return ans
57
58
59 class UnzipWrapper:
60 def __init__(self, fp):
61 self.__decoder = zlib.decompressobj(-zlib.MAX_WBITS)
62 self.__data = b''
63 self.__crc = zlib.crc32(self.__data) & CRC_MASK
64 self.__fp = fp
65 self.__size = 0
66 self.__is_fully_read = False
67
68 def read(self, sz=-1):
69 amt_read = 0
70 ans = []
71 if self.__data:
72 if sz < 0 or len(self.__data) < sz:
73 ans.append(self.__data)
74 amt_read += len(self.__data)
75 self.__data = b''
76 else:
77 self.__data, ret = self.__data[sz:], self.__data[:sz]
78 return ret
79
80 if not self.__is_fully_read:
81 while not self.__decoder.unused_data and (sz < 0 or amt_read < sz):
82 chunk = self.__fp.read(1024)
83 if chunk:
84 if self.__decoder.unconsumed_tail:
85 chunk = self.__decoder.unconsumed_tail + chunk
86 chunk = self.__decoder.decompress(chunk)
87 ans.append(chunk)
88 amt_read += len(chunk)
89 self.__size += len(chunk)
90 self.__crc = zlib.crc32(chunk, self.__crc)
91 else:
92 if not self.__decoder.unused_data:
93 raise ValueError(
94 'unexpected end of compressed gzip data,'
95 ' before reading trailer')
96 break
97
98 if self.__decoder.unused_data:
99 # End of compressed stream reached
100 tail = self.__decoder.unused_data
101 if len(tail) < 8:
102 tail += read_amt(self.__fp, 8 - len(tail))
103 # ignore any extra bytes after end of compressed stream
104 self.__fp.read()
105 # check CRC, ignore size mismatch
106 crc, size = struct.unpack(b'<LL', tail)
107 if (crc & CRC_MASK) != (self.__crc & CRC_MASK):
108 raise ValueError(
109 'gzip stream is corrupted, CRC does not match')
110 self.__is_fully_read = True
111
112 ans = b''.join(ans)
113 if len(ans) > sz and sz > -1:
114 ans, self.__data = ans[:sz], ans[sz:]
115 return ans
116
117 def readline(self, sz=-1):
118 # Dont care about making this efficient
119 data = self.read()
120 idx = data.find(b'\n')
121 if idx > 0:
122 if sz < 0 or idx < sz:
123 line, self.__data = data[:idx + 1], data[idx + 1:]
124 else:
125 line, self.__data = data[:sz], data[sz:]
126 else:
127 if sz > -1:
128 line, self.__data = data[:sz], data[sz:]
129 else:
130 line = data
131 return line
132
133 def close(self):
134 self.__fp.close()
135
136 def fileno(self):
137 return self.__fp.fileno()
138
139 def __iter__(self):
140 ans = self.readline()
141 if ans:
142 yield ans
143
144 def next(self):
145 ans = self.readline()
146 if not ans:
147 raise StopIteration()
148 return ans
149
150
151 def create_gzip_decompressor(zipped_file):
152 prefix = read_amt(zipped_file, 10)
153 if prefix[:2] != b'\x1f\x8b':
154 raise ValueError('gzip stream has incorrect magic bytes: %r' %
155 prefix[:2])
156 if prefix[2:3] != b'\x08':
157 raise ValueError('gzip stream has unknown compression method: %r' %
158 prefix[2])
159 flag = ord(prefix[3:4])
160 if flag & 4: # extra
161 extra_amt = read_amt(zipped_file, 2)
162 extra_amt = ord(extra_amt[0]) + 256 * ord(extra_amt[1])
163 if extra_amt:
164 read_amt(zipped_file, extra_amt)
165 if flag & 8: # filename
166 while read_amt(zipped_file, 1) != b'\0':
167 continue
168 if flag & 16: # comment
169 while read_amt(zipped_file, 1) != b'\0':
170 continue
171 if flag & 2: # crc
172 read_amt(zipped_file, 2)
173 return UnzipWrapper(zipped_file)
174
175
176 class HTTPGzipProcessor(BaseHandler):
177 handler_order = 200 # response processing before HTTPEquivProcessor
178
179 def __init__(self, request_gzip=False):
180 self.request_gzip = request_gzip
181
182 def __copy__(self):
183 return self.__class__(self.request_gzip)
184
185 def http_request(self, request):
186 if self.request_gzip:
187 existing = [
188 x.strip().lower()
189 for x in request.get_header('Accept-Encoding', '').split(',')
190 ]
191 if 'gzip' not in existing:
192 existing.append('gzip')
193 request.add_header("Accept-Encoding",
194 ', '.join(filter(None, existing)))
195 return request
196
197 def http_response(self, request, response):
198 # post-process response
199 h = response.info()
200 enc_hdrs = h.getheaders("Content-encoding")
201 for enc_hdr in enc_hdrs:
202 if "gzip" in enc_hdr:
203 response._set_fp(create_gzip_decompressor(response.fp))
204 del h['Content-encoding']
205 del h['Content-length']
206 return response
207
208 https_response = http_response
209 https_request = http_request