"""Shared utilities for xlsx/zip processing across batch modules.""" import os import zipfile import xml.etree.ElementTree as ET from defusedxml.ElementTree import parse as _safe_parse, fromstring as _safe_fromstring # XXE/billion-laughs-safe (пентест XXE-DOS-01) from pathlib import Path # Кап на РАСПАКОВАННЫЙ объём xlsx перед openpyxl (пентест FILE-02): xlsx = zip, маленький # файл может иметь гигантский sharedStrings.xml → openpyxl грузит его в RAM → OOM хоста # (у хостовых вызовов нет mem-лимита, в отличие от контейнера). read_only openpyxl НЕ # спасает (sharedStrings читается целиком). Проверяем central directory zip (не распаковывая). MAX_XLSX_UNCOMPRESSED = int(os.environ.get("MAX_XLSX_UNCOMPRESSED", str(300 * 1024 * 1024))) def assert_xlsx_not_bomb(path, max_uncompressed: int = MAX_XLSX_UNCOMPRESSED) -> None: """Отклонить xlsx-бомбу ДО openpyxl. Real смета — единицы МБ; кап 300МБ щедрый.""" try: with zipfile.ZipFile(str(path)) as z: total = sum(i.file_size for i in z.infolist()) except zipfile.BadZipFile: return # не zip/битый — пусть openpyxl сам вернёт ошибку формата if total > max_uncompressed: raise ValueError(f"xlsx слишком большой в распаковке ({total} байт) — отклонён") def read_xlsx_xml(path: str, max_rows: int = 50) -> dict: """Read xlsx via XML (handles broken styles). Returns {sheet_name: [[row], ...]}.""" result = {} try: z = zipfile.ZipFile(path) ns = {'s': 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'} # Shared strings strings = [] try: ss = _safe_parse(z.open('xl/sharedStrings.xml')).getroot() for si in ss.findall('.//s:si', ns): strings.append(''.join(t.text or '' for t in si.findall('.//s:t', ns))) except KeyError: pass # Sheet names and rels wb = _safe_parse(z.open('xl/workbook.xml')).getroot() rels = _safe_parse(z.open('xl/_rels/workbook.xml.rels')).getroot() rid_map = {} for r in rels.iter(): rid = r.get('Id', '') tgt = r.get('Target', '') if rid and tgt: rid_map[rid] = tgt for sheet in wb.findall('.//s:sheet', ns): name = sheet.get('name', '') rid = sheet.attrib.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id', '') target = rid_map.get(rid, '') if not target: continue if target.startswith('/'): sheet_path = target.lstrip('/') elif target.startswith('xl/'): sheet_path = target else: sheet_path = f'xl/{target}' try: sheet_xml = _safe_parse(z.open(sheet_path)).getroot() except KeyError: continue rows = [] for row_el in sheet_xml.findall('.//s:row', ns): row_num = int(row_el.get('r', len(rows) + 1)) while len(rows) < row_num - 1: rows.append([]) if len(rows) >= max_rows: break row_data = [''] * 26 # A-Z for c in row_el.findall('s:c', ns): ref = c.get('r', '') cell_type = c.get('t', '') v = c.find('s:v', ns) val = v.text if v is not None else '' if cell_type == 's' and val.isdigit(): idx = int(val) val = strings[idx] if idx < len(strings) else val elif cell_type == 'inlineStr': is_el = c.find('s:is', ns) if is_el is not None: val = ''.join(t.text or '' for t in is_el.findall('.//s:t', ns)) col_letters = ''.join(ch for ch in ref if ch.isalpha()) col_idx = 0 for ch in col_letters.upper(): col_idx = col_idx * 26 + (ord(ch) - ord('A')) if col_idx < len(row_data): row_data[col_idx] = val while row_data and row_data[-1] == '': row_data.pop() rows.append(row_data) result[name] = rows z.close() except Exception as e: result['_error'] = str(e) return result def extract_zip(zip_path: str, dest_dir: str) -> list[str]: """Extract zip and return list of xlsx/gge/esw files. Handles Cyrillic filenames: Python's zipfile decodes names as CP437 when the UTF-8 flag is not set. We detect and fix this. """ with zipfile.ZipFile(zip_path) as z: for info in z.infolist(): if not (info.flag_bits & 0x800): # Try CP437→UTF-8 first, then CP437→CP866 (Windows Russian OEM) for target_enc in ('utf-8', 'cp866'): try: fixed = info.filename.encode('cp437').decode(target_enc) info.filename = fixed break except (UnicodeDecodeError, UnicodeEncodeError): continue basename = Path(info.filename).name if basename.startswith('._') or '__MACOSX' in info.filename: continue z.extract(info, dest_dir) SMETA_EXTENSIONS = {'.xlsx', '.xls', '.gge', '.esw', '.xml'} files = [] for f in Path(dest_dir).rglob('*'): if f.is_file() and f.suffix.lower() in SMETA_EXTENSIONS \ and not f.name.startswith('~$') and not f.name.startswith('._'): files.append(str(f)) return sorted(files)