import asyncio, os, re, ssl

ADC = '/root/recon/ns_adc.tsv'
OUT = '/root/recon/ns_ver.tsv'
POS = '/root/recon/ns_ver.pos'
CONC = 60
TIMEOUT = 8

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ctx.set_ciphers('DEFAULT@SECLEVEL=1')

VER_RE = re.compile(r'version="(\d+\.\d+\.\d+\.\d+)"')
NS_RE = re.compile(r'\bNS(\d{2})\.(\d{1,2})[: ]+[Bb]uild[: ]+([\d.]+)')


async def fetch(ip, path):
    r, w = await asyncio.wait_for(asyncio.open_connection(ip, 443, ssl=ctx, server_hostname=ip), TIMEOUT)
    req = ('GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)\r\n'
           'Accept: */*\r\nConnection: close\r\n\r\n' % (path, ip)).encode()
    w.write(req)
    await w.drain()
    data = b''
    while len(data) < 40000:
        try:
            c = await asyncio.wait_for(r.read(8192), TIMEOUT)
        except Exception:
            break
        if not c:
            break
        data += c
    w.close()
    return data


def head(d):
    return d.split(b'\r\n\r\n', 1)


async def work(ip, sem):
    async with sem:
        plug, nsver, gcode, dloc = '-', '-', '?', ''
        try:
            d = await fetch(ip, '/vpn/pluginlist.xml')
            h, _, b = d.partition(b'\r\n\r\n')
            m = VER_RE.search(b.decode('latin1', 'replace'))
            if m:
                plug = m.group(1)
        except Exception as e:
            plug = 'E:' + type(e).__name__
        try:
            d = await fetch(ip, '/vpn/index.html')
            h, _, b = d.partition(b'\r\n\r\n')
            status = h.split(b'\r\n')[0].decode('latin1', 'replace')
            gcode = status.split(' ')[1] if len(status.split(' ')) > 1 else '?'
            for line in h.split(b'\r\n'):
                if line.lower().startswith(b'location:'):
                    dloc = line.split(b':', 1)[1].strip().decode('latin1', '')
            m = NS_RE.search(d.decode('latin1', 'replace'))
            if m:
                nsver = 'NS%s.%s build %s' % (m.group(1), m.group(2), m.group(3))
        except Exception as e:
            gcode = 'E:' + type(e).__name__
        return '%s\t%s\t%s\t%s\t%s' % (ip, plug, nsver, gcode, dloc[:60])


async def main():
    ips = []
    for line in open(ADC):
        f = line.split('\t')
        if len(f) < 4:
            continue
        paths = f[3]
        if '/vpn/index.html:302' in paths or '/logon/LogonPoint/tmindex.html:200' in paths:
            ips.append(f[0])
    start = 0
    if os.path.exists(POS):
        try:
            start = int(open(POS).read().strip() or 0)
        except Exception:
            start = 0
    print('gateway candidates %d resume %d' % (len(ips), start), flush=True)
    sem = asyncio.Semaphore(CONC)
    with open(OUT, 'a', buffering=1) as f:
        for i in range(start, len(ips), 300):
            chunk = ips[i:i + 300]
            res = await asyncio.gather(*[work(ip, sem) for ip in chunk])
            for r in res:
                f.write(r + '\n')
            open(POS, 'w').write(str(i + 300))
            if (i // 300) % 5 == 0:
                print('done', i + len(chunk), flush=True)
    print('finished', flush=True)

asyncio.run(main())
