91 lines
3.0 KiB
Python
91 lines
3.0 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""xlsx(zip) 读写的兼容层。
|
||
|
||
背景:台账被 WPS 保存后,透视缓存的 `pivotCacheRecords*.xml` 会写成
|
||
「local header 里 size=0xFFFFFFFF + ZIP64 extra 带真实大小、central directory 却缺 ZIP64 extra」。
|
||
Python 3.11 的 zipfile 从 central 取到 0xFFFFFFFF,把条目当成 4GB,
|
||
`ZipFile.open()` 直接抛 `BadZipFile: Overlapped entries ... (possible zip bomb)`。
|
||
|
||
这里在打开后把这类 ZipInfo 的 size 修成真实值(解析 local header 的 ZIP64 extra,
|
||
取不到就用下一条目偏移反推),只改内存对象、不动文件;之后 `zf.open(info)` 可正常读。
|
||
"""
|
||
import struct
|
||
import zipfile
|
||
|
||
|
||
def _local_sizes(fp, info):
|
||
"""从 local file header 的 ZIP64 extra 取 (usize, csize),取不到返回 (None, None)。"""
|
||
fp.seek(info.header_offset)
|
||
hdr = fp.read(30)
|
||
if len(hdr) < 30 or hdr[:4] != b'PK\x03\x04':
|
||
return None, None
|
||
nlen, elen = struct.unpack('<HH', hdr[26:30])
|
||
fp.read(nlen)
|
||
extra = fp.read(elen)
|
||
usize = csize = None
|
||
i = 0
|
||
while i + 4 <= len(extra):
|
||
hid, hlen = struct.unpack('<HH', extra[i:i + 4])
|
||
body = extra[i + 4:i + 4 + hlen]
|
||
if hid == 0x0001: # ZIP64 extended information
|
||
if len(body) >= 16:
|
||
usize, csize = struct.unpack('<QQ', body[:16])
|
||
elif len(body) >= 8:
|
||
usize = struct.unpack('<Q', body[:8])[0]
|
||
i += 4 + hlen
|
||
return usize, csize
|
||
|
||
|
||
def repair_sizes(zf):
|
||
"""修 0xFFFFFFFF 的条目大小,返回修复条数。"""
|
||
fixed = 0
|
||
fp = getattr(zf, 'fp', None)
|
||
if fp is None:
|
||
return 0
|
||
try:
|
||
if not fp.seekable():
|
||
return 0
|
||
except Exception:
|
||
return 0
|
||
try:
|
||
pos = fp.tell()
|
||
except Exception:
|
||
pos = None
|
||
for info in zf.infolist():
|
||
if info.compress_size != 0xFFFFFFFF and info.file_size != 0xFFFFFFFF:
|
||
continue
|
||
usize, csize = _local_sizes(fp, info)
|
||
if csize is None:
|
||
end = getattr(info, '_end_offset', None)
|
||
if end:
|
||
head = _peek(fp, info, 26, 4) or b'\x00\x00\x00\x00'
|
||
nlen, elen = struct.unpack('<HH', head)
|
||
csize = end - (info.header_offset + 30 + nlen + elen)
|
||
if csize is None:
|
||
continue
|
||
info.compress_size = csize
|
||
if usize:
|
||
info.file_size = usize
|
||
fixed += 1
|
||
if pos is not None:
|
||
try:
|
||
fp.seek(pos)
|
||
except Exception:
|
||
pass
|
||
return fixed
|
||
|
||
|
||
def _peek(fp, info, offset, size):
|
||
try:
|
||
fp.seek(info.header_offset + offset)
|
||
return fp.read(size)
|
||
except Exception:
|
||
return None
|
||
|
||
|
||
def open_zip(path):
|
||
"""open + 修复 WPS 写坏的 zip64 条目大小,返回可正常读取的 ZipFile。"""
|
||
zf = zipfile.ZipFile(path)
|
||
repair_sizes(zf)
|
||
return zf
|