import asyncio, os, struct, sys

SRC = '/root/recon/gw_all.txt'
OUT = '/root/recon/dtls.tsv'
POS = '/root/recon/dtls.pos'
CONC = 500
WAIT = 2.5


def client_hello():
    body = bytearray()
    body += b'\xfe\xfd'                      # client_version DTLS 1.2
    body += os.urandom(32)                   # random
    body += b'\x00'                          # session id len
    body += b'\x00'                          # cookie len
    suites = [0xc02f, 0xc02b, 0xc030, 0xc02c, 0x009e, 0x009c, 0x0035, 0x002f]
    body += struct.pack('>H', len(suites) * 2)
    for s in suites:
        body += struct.pack('>H', s)
    body += b'\x01\x00'                      # compression methods
    body += b'\x00\x00'                      # no extensions
    hs = bytearray()
    hs += b'\x01'                            # ClientHello
    hs += struct.pack('>I', len(body))[1:]   # length 3 bytes
    hs += struct.pack('>H', 0)               # message_seq
    hs += struct.pack('>I', 0)[1:]           # fragment_offset
    hs += struct.pack('>I', len(body))[1:]   # fragment_length
    hs += body
    rec = bytearray()
    rec += b'\x16'                           # handshake
    rec += b'\xfe\xfd'                       # DTLS 1.2
    rec += struct.pack('>H', 0)              # epoch
    rec += struct.pack('>I', 0)[1:] + b'\x00'  # seq 6 bytes
    rec += struct.pack('>H', len(hs))
    rec += hs
    return bytes(rec)


async def probe(ip, sem):
    async with sem:
        loop = asyncio.get_event_loop()
        t = None
        try:
            t, _ = await loop.create_datagram_endpoint(Proto, remote_addr=(ip, 443))
            t.sendto(client_hello())
            data = await asyncio.wait_for(t._protocol.fut, WAIT)
            ok = len(data) >= 13 and data[0] in (20, 21, 22) and data[1] == 0xfe
            return '%s\t%s\n' % (ip, 'DTLS' if ok else '-')
        except Exception:
            return '%s\t-\n' % ip
        finally:
            if t:
                t.close()


class Proto(asyncio.DatagramProtocol):
    def __init__(self):
        self.fut = asyncio.get_event_loop().create_future()

    def datagram_received(self, data, addr):
        if not self.fut.done():
            self.fut.set_result(data)


async def _recv(t):
    return await t._protocol.fut


async def main():
    ips = [l.split()[0] for l in open(SRC) if l.strip()]
    start = 0
    if os.path.exists(POS):
        start = int(open(POS).read().strip() or 0)
    print('ips %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), 500):
            chunk = ips[i:i + 500]
            res = await asyncio.gather(*[probe(ip, sem) for ip in chunk])
            for r in res:
                f.write(r)
            open(POS, 'w').write(str(i + 500))
            print('done', i + len(chunk), flush=True)
    print('finished', flush=True)

asyncio.run(main())
