Refine encoding support

- Push decoding down into the LRU cache
- Cope gracefully with corrupted data and incorrect encoding headers
This commit is contained in:
Aldo Cortesi 2011-07-17 10:25:25 +12:00
parent 7ec03e45a5
commit ce41046786
3 changed files with 17 additions and 6 deletions

View File

@ -306,7 +306,8 @@ class ConnectionView(WWrap):
else: else:
e = "identity" e = "identity"
return self.master._cached_conn_text( return self.master._cached_conn_text(
encoding.decode(e, conn.content), e,
conn.content,
tuple([tuple(i) for i in conn.headers.lst]), tuple([tuple(i) for i in conn.headers.lst]),
viewmode viewmode
) )
@ -965,7 +966,10 @@ class ConsoleMaster(flow.FlowMaster):
return self._view_conn_raw(content, txt) return self._view_conn_raw(content, txt)
@utils.LRUCache(20) @utils.LRUCache(20)
def _cached_conn_text(self, content, hdrItems, viewmode): def _cached_conn_text(self, e, rawcontent, hdrItems, viewmode):
content = encoding.decode(e, rawcontent)
if content is None:
content = rawcontent
hdr = [] hdr = []
hdr.extend( hdr.extend(
format_keyvals( format_keyvals(

View File

@ -14,7 +14,6 @@ def decode(encoding, content):
"gzip": decode_gzip, "gzip": decode_gzip,
"deflate": decode_deflate, "deflate": decode_deflate,
} }
return encoding_map.get(encoding, decode_identity)(content) return encoding_map.get(encoding, decode_identity)(content)
def decode_identity(content): def decode_identity(content):
@ -26,7 +25,10 @@ def decode_identity(content):
def decode_gzip(content): def decode_gzip(content):
gfile = gzip.GzipFile(fileobj=cStringIO.StringIO(content)) gfile = gzip.GzipFile(fileobj=cStringIO.StringIO(content))
return gfile.read() try:
return gfile.read()
except IOError:
return None
def decode_deflate(content): def decode_deflate(content):
""" """
@ -38,6 +40,9 @@ def decode_deflate(content):
http://bugs.python.org/issue5784 http://bugs.python.org/issue5784
""" """
try: try:
return zlib.decompress(content) try:
return zlib.decompress(content)
except zlib.error:
return zlib.decompress(content, -15)
except zlib.error: except zlib.error:
return zlib.decompress(content, -15) return None

View File

@ -18,11 +18,13 @@ class udecode_gzip(libpry.AutoTree):
gf.write('string') gf.write('string')
gf.close() gf.close()
assert 'string' == encoding.decode('gzip', s.getvalue()) assert 'string' == encoding.decode('gzip', s.getvalue())
assert None == encoding.decode("gzip", "bogus")
class udecode_deflate(libpry.AutoTree): class udecode_deflate(libpry.AutoTree):
def test_simple(self): def test_simple(self):
assert 'string' == encoding.decode('deflate', zlib.compress('string')) assert 'string' == encoding.decode('deflate', zlib.compress('string'))
assert 'string' == encoding.decode('deflate', zlib.compress('string')[2:-4]) assert 'string' == encoding.decode('deflate', zlib.compress('string')[2:-4])
assert None == encoding.decode("deflate", "bogus")
tests = [ tests = [
udecode_identity(), udecode_identity(),