import asyncio, ipaddress, sys

HOST = sys.argv[1] if len(sys.argv) > 1 else '10.68.16.252'
PORT = int(sys.argv[2]) if len(sys.argv) > 2 else 25


async def socks_connect(ip, port):
    r, w = await asyncio.open_connection('127.0.0.1', 1080)
    w.write(b'\x05\x01\x00')
    await w.drain()
    await r.readexactly(2)
    w.write(b'\x05\x01\x00\x01' + ipaddress.IPv4Address(ip).packed + port.to_bytes(2, 'big'))
    await w.drain()
    head = await r.readexactly(4)
    assert head[1] == 0, head
    await r.readexactly(6)
    return r, w


async def talk(r, w, cmd):
    if cmd:
        w.write(cmd.encode() + b'\r\n')
        await w.drain()
    out = []
    while True:
        try:
            line = await asyncio.wait_for(r.readline(), 8)
        except Exception:
            break
        if not line:
            break
        out.append(line.decode('utf-8', 'replace').rstrip())
        if len(line) >= 4 and line[3:4] == b' ':
            break
    print('>>', cmd if cmd else '(banner)')
    for o in out:
        print('  ', o)


async def main():
    r, w = await socks_connect(HOST, PORT)
    await talk(r, w, None)
    await talk(r, w, 'EHLO test.example.com')
    await talk(r, w, 'VRFY postmaster')
    await talk(r, w, 'EXPN staff')
    await talk(r, w, 'MAIL FROM:<test@example.com>')
    await talk(r, w, 'RCPT TO:<test@example.com>')
    await talk(r, w, 'RCPT TO:<nobody@delta.com>')
    await talk(r, w, 'QUIT')
    w.close()

asyncio.run(main())
