import asyncio, socket, collections
import aiohttp

UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
IPS = [l.split("\t")[0] for l in open("/root/recon/bdui_full.tsv") if l.strip()]


def rdns(ip):
    try:
        return socket.gethostbyaddr(ip)[0]
    except Exception:
        return ""


async def probe(sess, ip):
    rec = {"ip": ip, "code": 0, "srv": "", "esg": 0, "host": ""}
    for scheme in ("https", "http"):
        try:
            async with sess.get(f"{scheme}://{ip}/cgi-mod/index.cgi", ssl=False,
                                allow_redirects=False) as r:
                body = await r.content.read(30000)
                rec["code"] = r.status
                rec["srv"] = r.headers.get("Server", "")
                rec["esg"] = 1 if b'name="password_entry"' in body else 0
                if rec["code"] in (200, 302, 401, 403):
                    break
        except Exception:
            continue
    return rec


async def main():
    loop = asyncio.get_running_loop()
    tout = aiohttp.ClientTimeout(total=18, connect=7, sock_read=12)
    sem = asyncio.Semaphore(10)
    async with aiohttp.ClientSession(timeout=tout, headers=UA) as s:
        async def g(ip):
            async with sem:
                r = await probe(s, ip)
            r["host"] = await loop.run_in_executor(None, rdns, ip)
            if not r["srv"] and r["esg"]:
                r["srv"] = "(no header, ESG form)"
            cat = ("ESG" if r["esg"] else
                   "CloudGen" if "CloudGen" in r["srv"] else
                   "BarracudaServer" if "BarracudaServer" in r["srv"] else
                   "Blocked/404" if r["code"] == 404 else
                   "other")
            r["cat"] = cat
            return r
        res = await asyncio.gather(*[g(ip) for ip in IPS])
    res.sort(key=lambda x: (x["cat"], x["ip"]))
    cnt = collections.Counter(x["cat"] for x in res)
    print("TOTAL", len(res), dict(cnt))
    for cat in ("ESG", "CloudGen", "BarracudaServer", "Blocked/404", "other"):
        print(f"\n--- {cat} ---")
        for r in res:
            if r["cat"] == cat:
                print(f"  {r['ip']:16s} {r['code']:>4} {r['srv'][:30]:30s} {r['host'][:55]}")
    with open("/root/recon/bdui_final.tsv", "w") as f:
        for r in res:
            f.write("\t".join([r["ip"], str(r["code"]), r["srv"], str(r["esg"]),
                               r["host"], r["cat"]]) + "\n")

asyncio.run(main())
