import asyncio, os, struct, sys, time

CP_VID = bytes.fromhex("F4ED19E0C114EB516FAAAC0EE37DAF2807B4381F")
CCC_VID = bytes.fromhex("DEFB99E69A9F1F6E06F15006B1F166AE")
FRAG_VID = bytes.fromhex("4048B7D56EBCE88525E7DE7F00D6C2D3")
HDR = 28


def pl(nxt, body):
    return struct.pack(">BBH", nxt, 0, 4 + len(body)) + body


def sa_payload():
    a = struct.pack(">HH", 0x8000 | 1, 7)      # AES
    a += struct.pack(">HH", 0x8000 | 2, 2)     # SHA1
    a += struct.pack(">HH", 0x8000 | 3, 3)     # RSA-SIG
    a += struct.pack(">HH", 0x8000 | 4, 2)     # DH2
    a += struct.pack(">HH", 0x8000 | 14, 256)  # key length
    a += struct.pack(">HH", 0x8000 | 11, 1)    # life type seconds
    a += struct.pack(">HH", 0x0000 | 12, 4) + struct.pack(">I", 28800)
    tr = struct.pack(">BBH", 0, 0, 8 + len(a)) + struct.pack(">BBBB", 1, 1, 0, 0) + a
    prop = struct.pack(">BBHBBBB", 0, 0, 8 + len(tr), 1, 1, 0, 1) + tr
    return struct.pack(">II", 1, 1) + prop


SA = sa_payload()


def build(cookie):
    body = pl(13, SA)
    body += pl(13, CP_VID + struct.pack(">IIIII", 2, 0, 0, 0, 0))
    body += pl(13, CCC_VID)
    body += pl(0, FRAG_VID)
    return struct.pack(">QQBBBBII", int.from_bytes(cookie, "big"), 0, 1, 0x10, 2, 0, 0, HDR + len(body)) + body


def parse(data):
    off, cur = HDR, data[16]
    vids = []
    while cur and off + 4 <= len(data):
        nxt, _, ln = struct.unpack(">BBH", data[off:off + 4])
        if ln < 4 or off + ln > len(data):
            break
        if cur == 13:
            vids.append(data[off + 4:off + ln])
        cur = nxt
        off += ln
    cp = any(v.startswith(CP_VID) for v in vids)
    ccc = any(v.startswith(CCC_VID) for v in vids)
    return cp, ccc, [v[:20].hex() for v in vids]


class Proto(asyncio.DatagramProtocol):
    def __init__(self, out):
        self.out = out
        self.n = 0
        self.cp = 0

    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        if len(data) < HDR:
            return
        try:
            cp, ccc, vids = parse(data)
            self.n += 1
            if cp:
                self.cp += 1
            self.out.write("%s\t%d\t%d\t%d\t%d\t%d\t%d\t%s\n" % (
                addr[0], len(data), data[18], data[19], 1 if cp else 0, 1 if ccc else 0,
                struct.unpack(">I", data[20:24])[0], ",".join(vids)[:200]))
            self.out.flush()
        except Exception:
            pass


async def main():
    src, dst = sys.argv[1], sys.argv[2]
    rate = int(sys.argv[3]) if len(sys.argv) > 3 else 3000
    out = open(dst, "w")
    loop = asyncio.get_running_loop()
    tr, proto = await loop.create_datagram_endpoint(lambda: Proto(out), local_addr=("0.0.0.0", 500))
    batch = max(1, rate // 20)
    sent = 0
    t0 = time.time()
    for line in open(src):
        parts = line.split()
        if not parts:
            continue
        ip = parts[3] if len(parts) > 3 else parts[-1]
        if not ip or ip[0] == "#":
            continue
        tr.sendto(build(os.urandom(8)), (ip, 500))
        sent += 1
        if sent % batch == 0:
            await asyncio.sleep(0.05)
            if sent % (batch * 20) == 0:
                el = time.time() - t0
                print("sent %d replies %d cp %d rate %.0f/s" % (sent, proto.n, proto.cp, sent / el), flush=True)
    await asyncio.sleep(15)
    tr.close()
    out.close()
    print("sent %d replies %d cp %d secs %.0f" % (sent, proto.n, proto.cp, time.time() - t0), flush=True)


asyncio.run(main())
