#!/usr/bin/env python3
"""
Serves the Chrome-side IDN probe page (chrome_idn_probe.html) and a /redirect
endpoint that returns 302 Location: https://straße.de/x  -- the
"server-supplied redirect" trigger path described in the report
(net/url_request/url_request_job.cc:199 -> GURL::Resolve -> DoIdnHost).

Usage:
    python3 server.py            # listens on :8080
"""
import http.server
import os
import socketserver

PORT = 8080
ROOT = os.path.dirname(os.path.abspath(__file__))

# UTF-8 bytes for "https://straße.de/x" (U+00DF as 0xC3 0x9F).
REDIRECT_LOCATION = b"https://stra\xc3\x9fe.de/x"


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

    def do_GET(self):
        if self.path.startswith("/redirect"):
            self.send_response(302)
            # send_header() latin-1-encodes, which round-trips our raw bytes.
            self.send_header("Location", REDIRECT_LOCATION.decode("latin-1"))
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        if self.path in ("/", "/poc.html"):
            self.path = "/chrome_idn_probe.html"
        return super().do_GET()

    do_HEAD = do_GET


if __name__ == "__main__":
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(("", PORT), Handler) as httpd:
        print(f"serving on http://localhost:{PORT}/")
        print(f"  /poc.html   -> Chrome-side WHATWG URL canonicalisation probe")
        print(f"  /redirect   -> 302 Location: https://stra\\u00DFe.de/x")
        httpd.serve_forever()
