import asyncio, re, struct
import aiohttp

ips = [l.strip() for l in open('bt_nover.txt') if l.strip()]
SEM = asyncio.Semaphore(15)
OUT = open('bt_versions2.tsv', 'w')
LOCK = asyncio.Lock()
HDR = re.compile(rb'^(0 Successful\n.+\n\d+\n)')


def parse(b):
    m = HDR.match(b)
    if not m:
        return None
    d = b[m.end():]
    if b'Thank you for using BeyondTrust' not in d or len(d) < 12:
        return None
    magic, _, _, t1, ln, t2 = struct.unpack('>IBHBBB', d[:10])
    if magic != 0x42524446 or t1 != 0x91 or t2 != 0x81 or not 3 <= ln <= 20:
        return None
    return d[10:10 + ln - 1].decode('ascii', 'replace')


async def one(s, ip):
    b = b''
    for timeout in (20, 45):
        try:
            async with SEM:
                async with s.get('https://%s/get_rdf?comp=sdcust&locale_code=en-us' % ip,
                                 ssl=False, timeout=aiohttp.ClientTimeout(total=timeout)) as r:
                    b = await r.read() if r.status == 200 else b''
            if b:
                break
        except Exception:
            b = b''
    v = parse(b) if b else None
    async with LOCK:
        OUT.write('%s\t%s\n' % (ip, v or '-'))
        OUT.flush()


async def main():
    conn = aiohttp.TCPConnector(limit=15, force_close=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        await asyncio.gather(*[one(s, ip) for ip in ips])
    OUT.close()
    print('DONE', len(ips), flush=True)

asyncio.run(main())
