#!/usr/bin/env python3
# FROZEN: not started by openfut-fut.sh (see its SERVERS array); identity is NOT
# sourced from fut_account.py here. The live pair is lsx_responder_v2.py +
# blaze_responder_v3b.py -- edit those. Kept for reference/bisecting only.
"""FIFA17 Blaze redirector RESPONDER + second-hop Fire2 capture.
- TLS on 42127: answers POST /redirector/getServerInstance with a
  <serverinstanceinfo> pointing the client at 127.0.0.1:BLAZE_PORT (secure=0).
- Plain TCP on BLAZE_PORT: logs the client's second-hop Fire2/Heat2 handshake.
All XML schema is a clean-room best-guess from the client's own TDF field names;
iterate based on client reaction (re-POST = parse reject; connect on BLAZE_PORT = success).
"""
import socket, ssl, threading, time, binascii

HOST="127.0.0.1"; REDIR_PORT=42127; BLAZE_PORT=42130
BLAZE_IP_STR="127.0.0.1"; BLAZE_IP_U32=(127<<24)|1   # 2130706433
LOG="/tmp/blaze_responder.log"

def log(m):
    line=f"[{time.strftime('%H:%M:%S')}] {m}"
    print(line,flush=True)
    open(LOG,"a").write(line+"\n")

def build_response():
    # Confirmed schema (clean-room, MEC Catalyst): ServerInstanceInfo.address is a
    # ServerAddress union -> Heat2 XML union = <address member="N"><valu>...</valu></address>.
    # member="0" = ipAddress variant {hostname, ip(uint32 decimal), port(uint16)}.
    body=(
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<serverinstanceinfo>\n'
        '\t<address member="0">\n'
        '\t\t<valu>\n'
        f'\t\t\t<hostname>{BLAZE_IP_STR}</hostname>\n'
        f'\t\t\t<ip>{BLAZE_IP_U32}</ip>\n'
        f'\t\t\t<port>{BLAZE_PORT}</port>\n'
        '\t\t</valu>\n'
        '\t</address>\n'
        '\t<secure>0</secure>\n'
        '\t<trialservicename></trialservicename>\n'
        '\t<defaultdnsaddress>0</defaultdnsaddress>\n'
        '</serverinstanceinfo>\n'
    )
    b=body.encode()
    hdr=(f"HTTP/1.1 200 OK\r\nContent-Type: application/xml\r\n"
         f"Content-Length: {len(b)}\r\nConnection: close\r\n\r\n").encode()
    return hdr+b

ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ctx.load_cert_chain("redir_cert.pem","redir_key.pem")
ctx.minimum_version=ssl.TLSVersion.TLSv1
ctx.set_ciphers("ALL:@SECLEVEL=0")

def redir_handle(raw,addr):
    try:
        tls=ctx.wrap_socket(raw,server_side=True)
    except ssl.SSLError as e:
        log(f"REDIR REJECTED {addr}: {e}"); raw.close(); return
    log(f"REDIR TLS-OK {addr} cipher={tls.cipher()[0]}")
    try:
        tls.settimeout(8)
        req=b""
        while b"\r\n\r\n" not in req:
            c=tls.recv(4096)
            if not c: break
            req+=c
        # read body per content-length
        if b"content-length:" in req.lower():
            hdr,_,rest=req.partition(b"\r\n\r\n")
            cl=int([l.split(b":")[1] for l in hdr.split(b"\r\n") if l.lower().startswith(b"content-length")][0])
            while len(rest)<cl:
                c=tls.recv(4096)
                if not c: break
                rest+=c
            req=hdr+b"\r\n\r\n"+rest
        line0=req.split(b"\r\n",1)[0].decode(errors="replace")
        log(f"REDIR REQ {addr}: {line0}")
        resp=build_response()
        tls.sendall(resp)
        log(f"REDIR SENT {addr} {len(resp)}B serverinstanceinfo -> {BLAZE_IP_STR}:{BLAZE_PORT}")
        time.sleep(0.3)
        tls.close()
    except Exception as e:
        log(f"REDIR ERR {addr}: {e}")

def blaze_handle(raw,addr):
    log(f"*** BLAZE 2nd-HOP CONNECT from {addr}  (client accepted our redirect!) ***")
    try:
        raw.settimeout(8)
        blob=b""
        while len(blob)<65536:
            c=raw.recv(4096)
            if not c: break
            blob+=c
            # Fire2 frames are short; log as we go
            if len(blob)>=16 and len(c)<4096: break
        if blob:
            fn=f"/tmp/blaze_fire2_{addr[1]}.bin"
            open(fn,"wb").write(blob)
            log(f"BLAZE FIRE2 {len(blob)}B -> {fn}")
            log("HEX:\n"+"\n".join(f"  {i:04x}: {binascii.hexlify(blob[i:i+16]).decode()}" for i in range(0,min(len(blob),192),16)))
        else:
            log(f"BLAZE connect but no bytes from {addr}")
        raw.close()
    except Exception as e:
        log(f"BLAZE ERR {addr}: {e}")

def serve(port,handler,name):
    s=socket.socket(); s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    s.bind((HOST,port)); s.listen(16)
    log(f"{name} listening on {HOST}:{port}")
    while True:
        c,a=s.accept()
        threading.Thread(target=handler,args=(c,a),daemon=True).start()

log("=== RESPONDER START ===")
threading.Thread(target=serve,args=(BLAZE_PORT,blaze_handle,"BLAZE"),daemon=True).start()
serve(REDIR_PORT,redir_handle,"REDIR")
