#!/usr/bin/env python3
"""
Serves victim.html on :8080 and attacker.html on :8081 so the two are
cross-origin.  Rewrites the ATTACKER_ORIGIN placeholder in victim.html to
point at the attacker port on whatever host the request arrived on (so it
works over adb-reverse / LAN IP / localhost equally).
"""
import http.server, socketserver, threading, os, sys

ROOT = os.path.dirname(os.path.abspath(__file__))
VICTIM_PORT, ATTACKER_PORT = 8080, 8081

class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *a, **kw):
        super().__init__(*a, directory=ROOT, **kw)

    def do_GET(self):
        if self.path in ("/", "/victim.html"):
            host = self.headers.get("Host", "localhost:8080").split(":")[0]
            with open(os.path.join(ROOT, "victim.html"), "rb") as f:
                body = f.read().replace(
                    b"ATTACKER_ORIGIN",
                    f"http://{host}:{ATTACKER_PORT}".encode())
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
            return
        if self.path == "/login":
            self.send_response(200); self.end_headers()
            self.wfile.write(b"ok")
            return
        return super().do_GET()

    do_POST = do_GET

def serve(port):
    class TS(socketserver.ThreadingMixIn, http.server.HTTPServer):
        allow_reuse_address = True
    TS(("0.0.0.0", port), Handler).serve_forever()

if __name__ == "__main__":
    threading.Thread(target=serve, args=(ATTACKER_PORT,), daemon=True).start()
    print(f"[+] victim   -> http://<host>:{VICTIM_PORT}/victim.html")
    print(f"[+] attacker -> http://<host>:{ATTACKER_PORT}/attacker.html")
    serve(VICTIM_PORT)
