# -*- coding: utf-8 -*-
# gsm_log.py — addon mitmproxy CHỈ GHI LOG (không sửa request/response).
# Dùng cho lượt đo baseline qua mitm (run-01): xác nhận pinning không chặn
# và ghi telemetry thô để đối chiếu với cờ getDetectFlags.
#
# Chạy:
#   mitmdump --listen-host 0.0.0.0 --listen-port 8080 -s gsm_log.py --set log_file=E:\ios\dump_tool\runs\mitm.log
#
# Mỗi request/response ghi 1 dòng JSON: url, method, host, path, status, body (truncated).

import json, time, datetime, os

MAX_BODY = 8000
_out = None
_path = None

def _file():
    global _out, _path
    if _out is None:
        p = os.environ.get('GSM_MITM_LOG', r'E:\ios\dump_tool\runs\mitm.log')
        os.makedirs(os.path.dirname(p), exist_ok=True)
        _out = open(p, 'a', encoding='utf-8', buffering=1)
        _path = p
    return _out

def _host(flow):
    try:
        return flow.request.pretty_host
    except Exception:
        return '?'

def _body(b, enc):
    if not b:
        return ''
    if 'json' in (enc or '') or (b[:1] in (b'{', b'[')):
        try:
            return json.dumps(json.loads(b), ensure_ascii=False)[:MAX_BODY]
        except Exception:
            pass
    try:
        return b.decode('utf-8', 'replace')[:MAX_BODY]
    except Exception:
        return repr(b[:MAX_BODY])

def _rec(kind, flow, extra=None):
    rec = {
        't': datetime.datetime.now().isoformat(),
        'kind': kind,
        'method': flow.request.method,
        'url': flow.request.pretty_url,
        'host': _host(flow),
        'path': flow.request.path,
    }
    if kind in ('resp', 'both'):
        rec['status'] = getattr(flow.response, 'status_code', None) if flow.response else None
        if flow.response:
            rec['resp_body'] = _body(flow.response.get_content(), flow.response.headers.get('content-type'))
    if kind in ('req', 'both'):
        rec['req_body'] = _body(flow.request.get_content(), flow.request.headers.get('content-type'))
    if extra:
        rec.update(extra)
    _file().write(json.dumps(rec, ensure_ascii=False) + '\n')

def request(flow):
    _rec('req', flow)

def response(flow):
    _rec('resp', flow)

def tls_failed_client(flow, err):
    _file().write(json.dumps({'t': datetime.datetime.now().isoformat(), 'kind': 'TLS_FAIL',
                              'client_hello_sni': getattr(flow, 'client_hello', None) and flow.client_hello.sni,
                              'err': str(err)}, ensure_ascii=False) + '\n')

def tls_established_client(flow):
    _file().write(json.dumps({'t': datetime.datetime.now().isoformat(), 'kind': 'TLS_OK',
                              'sni': flow.client_hello.sni}, ensure_ascii=False) + '\n')
