Files
smeta-web/gge_tools.py
anorandClaude Opus 4.8 fd5eb5ed1c fix(security): defusedxml для парса user-XML (пентест XXE-DOS-01)
Половина XML-парсеров была на defusedxml, половина на сыром xml.etree (тот же
паттерн «guard точечно»). Хост-side парсеры (_preprocess_xlsx, xlsx_utils) крутятся
без mem-капа → billion-laughs = память-DoS всего сервера. Все parse/fromstring
user-XML (.gge/.xlsx) переведены на defusedxml (forbid_dtd). Создание XML (ET.Element
в gge_deep) осталось на stdlib. Хирургически — заменены только вызовы, не модуль.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-19 13:36:50 +10:00

430 lines
17 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""gge_tools — работа с архивами .gge (XML смет ГГЭ) и xlsx-реестрами.
Универсальный, без привязки к конкретной задаче (ИГИ/ТС). Чат-агент
сам комбинирует tools для нужного сценария.
Зависимости: openpyxl + stdlib (zipfile, xml.etree, json). Без plotly,
sentence-transformers и т.п. — работает в sandbox-контейнере.
"""
from __future__ import annotations
import json
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
def _decode_zip_name(info: zipfile.ZipInfo) -> str:
"""Python 3 zipfile авто-декодирует cp437 если флаг UTF-8 (0x800) не задан.
Реальные байты могут быть в UTF-8 (macOS `zip`) или cp866 (Windows-архиватор).
Пробуем оба, берём результат без replacement chars."""
if info.flag_bits & 0x800:
return info.filename
try:
raw = info.filename.encode('cp437')
except UnicodeEncodeError:
return info.filename
for codec in ('utf-8', 'cp866'):
try:
decoded = raw.decode(codec)
if '�' not in decoded:
return decoded
except UnicodeDecodeError:
continue
return info.filename
def extract_archive(zip_path: Path, target_dir: Path) -> dict:
"""Распаковать zip с .gge файлами в target_dir. Сохраняет древовидную
структуру внутри архива. Корректно декодирует cp866-имена.
Возвращает: {target: <abs path>, total_files: N, gge_files: M, skipped: K}
"""
import os
# Лимиты против zip-бомбы: пишем в host-диск (/data), --memory контейнера не спасает.
MAX_BYTES = 5 * 1024 ** 3 # 5 ГБ распакованного
MAX_FILES = 50000
target_dir.mkdir(parents=True, exist_ok=True)
target_resolved = target_dir.resolve()
total = gge = skipped = 0
written_bytes = 0
aborted = False
with zipfile.ZipFile(zip_path) as z:
for info in z.infolist():
if info.is_dir():
continue
total += 1
if total > MAX_FILES or written_bytes > MAX_BYTES:
aborted = True
break
name = _decode_zip_name(info).replace('\\', '/')
# path traversal guard
out = (target_dir / name).resolve()
try:
out.relative_to(target_resolved)
except ValueError:
skipped += 1
continue
out.parent.mkdir(parents=True, exist_ok=True)
try:
with z.open(info) as src, open(out, 'wb') as dst:
while chunk := src.read(64 * 1024):
written_bytes += len(chunk)
if written_bytes > MAX_BYTES:
aborted = True
break
dst.write(chunk)
if name.lower().endswith('.gge'):
gge += 1
except Exception:
skipped += 1
if aborted:
break
return {
'target': str(target_dir),
'total_files': total,
'gge_files': gge,
'skipped': skipped,
'aborted': aborted,
}
def parse_gge_file(path: Path) -> dict:
"""Извлечь данные одной сметы из .gge XML.
Возвращает: code, name, schema_kind ('local' | 'object' | 'unknown'),
has_excavation, has_transport_summary, totals (всё что есть в
EstimatePrice/Summary), positions (список dict с name/code/quantity/
unit/price_total из <Cost>; для перевозочных позиций <Transport>
тоже включаем).
"""
try:
tree = _safe_parse(str(path))
except (ET.ParseError, OSError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
root = tree.getroot()
schema_loc = root.attrib.get(
'{http://www.w3.org/2001/XMLSchema-instance}noNamespaceSchemaLocation', '')
if 'LocalEstimate' in schema_loc:
schema_kind = 'local'
elif 'ObjectEstimate' in schema_loc:
schema_kind = 'object'
else:
schema_kind = 'unknown'
code = (root.findtext('.//Estimate/Num') or '').strip()
name = (root.findtext('.//Estimate/Name') or '').strip()
# Totals: EstimatePrice/Summary
totals: dict[str, float] = {}
summary = root.find('.//EstimatePrice/Summary')
if summary is not None:
for child in summary:
if len(list(child)) > 0:
# Materials/Total etc.
for sub in child:
if sub.text:
try:
totals[f'{child.tag}.{sub.tag}'] = float(sub.text.strip())
except ValueError:
pass
elif child.text:
try:
totals[child.tag] = float(child.text.strip())
except ValueError:
pass
# Positions: Item/Cost (work) + Item/Transport (carrier line)
positions: list[dict] = []
has_excavation = False
for it in root.iter('Item'):
for kind_tag in ('Cost', 'Transport'):
node = it.find(kind_tag)
if node is None:
continue
pname = (node.findtext('Name') or '').strip()
if not pname:
continue
pcode = (node.findtext('Code') or '').strip()
qty = node.findtext('Quantity') or ''
unit = (node.findtext('Unit') or '').strip()
ptcur = node.findtext('PriceTotalCur') or ''
direct = node.findtext('.//Totals/Current/Direct') or ''
try: qty_f = float(qty) if qty else 0.0
except ValueError: qty_f = 0.0
try: pt_f = float(ptcur) if ptcur else 0.0
except ValueError: pt_f = 0.0
try: dir_f = float(direct) if direct else 0.0
except ValueError: dir_f = 0.0
positions.append({
'kind': kind_tag.lower(), # 'cost' | 'transport'
'name': pname,
'code': pcode,
'quantity': qty_f,
'unit': unit,
'price_total_cur': pt_f,
'direct': dir_f,
})
if 'разработка грунта' in pname.lower():
has_excavation = True
has_transport_summary = (totals.get('Transport', 0.0) > 0)
return {
'path': str(path),
'code': code,
'name': name,
'schema_kind': schema_kind,
'has_excavation': has_excavation,
'has_transport_summary': has_transport_summary,
'totals': totals,
'positions': positions,
}
def xls_cell_str(cell, datemode) -> str:
"""Значение ячейки .xls (xlrd) → человекочитаемая строка. xlrd отдаёт числа и
даты как float: целое 5→'5.0', дата→серийник (43831.0). Форматируем по ctype."""
import xlrd
v = cell.value
if cell.ctype == xlrd.XL_CELL_DATE:
try:
dt = xlrd.xldate.xldate_as_datetime(v, datemode)
if dt.hour == dt.minute == dt.second == 0:
return dt.strftime("%d.%m.%Y")
return dt.strftime("%d.%m.%Y %H:%M")
except Exception:
return str(v)
if cell.ctype == xlrd.XL_CELL_NUMBER and float(v).is_integer():
return str(int(v))
return str(v)
def _ru_float(s: str) -> float:
"""ГРАНД пишет десятичные с запятой (Data.xml) или точкой (Properties.txt)."""
if not s:
return 0.0
try:
return float(s.strip().replace(' ', '').replace(',', '.'))
except (ValueError, AttributeError):
return 0.0
def _safe_xml_root(data: bytes):
"""Разобрать XML из байтов, устойчиво к XXE/billion-laughs. defusedxml если
есть (хост/dev), иначе stdlib (минимальный sandbox). data — БАЙТЫ: кодировка
берётся из XML-декларации (windows-1251 у ГРАНД)."""
try:
from defusedxml.ElementTree import fromstring as _fromstring
return _fromstring(data)
except ImportError:
return _safe_fromstring(data)
def parse_gsfx_file(path: Path) -> dict:
"""Разобрать .gsfx (ГРАНД-Смета, новый формат). .gsfx — это zip с
Properties.txt (шапка+итог, cp1251) + Data.xml (позиции, windows-1251) + Data.sign.
Возвращает: code (Attribs.LocNum), name (ConName/Description), region, total
(Properties.Total), positions [{code=@Code, name=@Caption, unit=@Units,
quantity=Quantity/@Result}], positions_count.
"""
try:
with zipfile.ZipFile(str(path)) as z:
names = z.namelist()
props_name = next((n for n in names if n.lower().endswith('.txt')), None)
data_name = next((n for n in names if n.lower().endswith('.xml')), None)
props_raw = z.read(props_name) if props_name else b''
data_raw = z.read(data_name) if data_name else b''
except (zipfile.BadZipFile, OSError, KeyError) as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
# Properties.txt — key=value, шапка и итог.
props: dict[str, str] = {}
for line in props_raw.decode('cp1251', 'replace').splitlines():
if '=' in line:
k, v = line.split('=', 1)
props[k.strip()] = v.strip()
code = props.get('Attribs.LocNum', '').strip()
name = (props.get('Attribs.ConName') or props.get('Attribs.Description') or '').strip()
region = props.get('RegionInfo.RegionName', '').strip()
total = _ru_float(props.get('Total', ''))
# Data.xml — позиции сметы.
positions: list[dict] = []
if data_raw:
try:
root = _safe_xml_root(data_raw)
except ET.ParseError as e:
return {'error': f'Data.xml ParseError: {e}', 'path': str(path),
'format': 'gsfx', 'code': code, 'name': name, 'total': total}
for pos in root.iter('Position'):
pcode = (pos.attrib.get('Code') or '').strip()
pname = (pos.attrib.get('Caption') or '').strip()
unit = (pos.attrib.get('Units') or '').strip()
qty_el = pos.find('Quantity')
qty = (qty_el.attrib.get('Result') if qty_el is not None else '') or ''
qty_f = _ru_float(qty)
if pname or pcode:
positions.append({'code': pcode, 'name': pname,
'unit': unit, 'quantity': qty_f})
return {
'path': str(path),
'format': 'gsfx',
'code': code,
'name': name,
'region': region,
'total': total,
'positions_count': len(positions),
'positions': positions,
}
def parse_arp_file(path: Path) -> dict:
"""Разобрать .arp/.arps (АРПС 1.10 — открытый текстовый формат обмена смет,
Smeta.RU / ПК АВС). Кодировка cp866, поля через '#', первое поле = тип записи.
Тип 3 — шапка сметы: [4]=шифр, [5]=название, [14]=итог.
Тип 20 — позиция: [2]=обоснование (первый токен = шифр расценки), [3]=ед.изм,
[4]=наименование, [15]=стоимость позиции. Объём НЕ извлекаем — его поле в АРПС
неоднозначно, лучше не давать выдуманное число.
"""
try:
raw = Path(path).read_bytes()
except OSError as e:
return {'error': f'{type(e).__name__}: {e}', 'path': str(path)}
text = raw.decode('cp866', 'replace')
code = name = ''
total = 0.0
positions: list[dict] = []
for line in text.splitlines():
if not line or '#' not in line:
continue
f = line.split('#')
rec = f[0]
if rec == '3' and len(f) > 5:
code = f[4].strip()
name = f[5].strip()
if len(f) > 14:
total = _ru_float(f[14])
elif rec == '20' and len(f) > 4:
just = f[2].strip()
pcode = just.split(' ')[0] if just else ''
unit = f[3].strip()
pname = f[4].strip()
ptotal = _ru_float(f[15]) if len(f) > 15 else 0.0
if pname or pcode:
positions.append({'code': pcode, 'name': pname,
'unit': unit, 'total': ptotal})
return {
'path': str(path),
'format': 'arp',
'code': code,
'name': name,
'total': total,
'positions_count': len(positions),
'positions': positions,
}
def index_gge_directory(dir_path: Path, save_index_to: Path | None = None) -> dict:
"""Пройти все .gge в dir_path рекурсивно, распарсить.
Returns: {by_code: {code: {has_excavation, has_transport_summary,
name, total_rub, schema_kind, path}}, summary: {...}, parse_errors: N}.
Если save_index_to задан — пишет полный индекс (с positions) в JSON.
Возврат компактнее (без positions), чтобы влез в MCP-ответ.
"""
files = sorted(p for p in dir_path.rglob('*.gge'))
by_code: dict[str, dict] = {}
full_index: dict[str, dict] = {}
parse_errors = 0
schemas: dict[str, int] = {}
excav = transp = 0
rub_sum = 0.0
for f in files:
data = parse_gge_file(f)
if 'error' in data:
parse_errors += 1
continue
code = data['code']
if not code:
continue
# Сводный (компактный) вид без positions для MCP-ответа.
compact = {
'name': data['name'],
'schema_kind': data['schema_kind'],
'has_excavation': data['has_excavation'],
'has_transport_summary': data['has_transport_summary'],
'total_rub': data['totals'].get('Total') or data['totals'].get('Price') or 0.0,
'transport_rub': data['totals'].get('Transport', 0.0),
'path': data['path'],
}
prev = by_code.get(code)
if prev is None or compact['total_rub'] > prev['total_rub']:
by_code[code] = compact
full_index[code] = data
schemas[data['schema_kind']] = schemas.get(data['schema_kind'], 0) + 1
if data['has_excavation']:
excav += 1
if data['has_transport_summary']:
transp += 1
rub_sum += compact['total_rub']
summary = {
'files_total': len(files),
'parse_errors': parse_errors,
'unique_codes': len(by_code),
'schemas': schemas,
'with_excavation': excav,
'with_transport_summary': transp,
'sum_total_rub': rub_sum,
}
if save_index_to is not None:
save_index_to.write_text(
json.dumps({'by_code': full_index, 'summary': summary},
ensure_ascii=False),
encoding='utf-8',
)
return {'by_code': by_code, 'summary': summary}
def update_xlsx_cells(src_path: Path, out_path: Path, sheet: str,
updates: list[dict]) -> dict:
"""Записать список ячеек в xlsx.
updates: [{"row": 5, "col": "E" | 5, "value": "ИГИ"}, ...]
Сохраняет копию в out_path. Не трогает остальной контент книги.
"""
import openpyxl
wb = openpyxl.load_workbook(str(src_path))
if sheet not in wb.sheetnames:
return {'error': f'Лист «{sheet}» не найден',
'available_sheets': wb.sheetnames}
ws = wb[sheet]
written = 0
skipped = 0
for u in updates:
try:
row = int(u['row'])
col = u['col']
if isinstance(col, str):
col_idx = openpyxl.utils.column_index_from_string(col)
else:
col_idx = int(col)
ws.cell(row, col_idx).value = u.get('value')
written += 1
except (KeyError, ValueError, TypeError):
skipped += 1
wb.save(str(out_path))
return {
'output_path': str(out_path),
'sheet': sheet,
'cells_written': written,
'cells_skipped': skipped,
}