#!/usr/bin/env python3
"""HTTP server for the POC.

Serves evil.html and victim.html on port 8000. Chrome is launched with
--host-resolver-rules so that both http://evil.com:8000/ and
http://victim.com:8000/ resolve here; the Host header distinguishes them only
for clarity in logs — the same files are served regardless.

Explicitly sets Cache-Control: max-age=0 (NOT no-store) so the attacker page
remains BFCache-eligible.
"""
import http.server
import os
import socketserver
import sys

PORT = 8000
DIRECTORY = os.path.dirname(os.path.abspath(__file__))


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=DIRECTORY, **kwargs)

    def end_headers(self):
        # Do NOT send `no-store`, which disables BFCache.
        self.send_header('Cache-Control', 'max-age=0')
        super().end_headers()

    def log_message(self, fmt, *args):
        host = self.headers.get('Host', '?')
        sys.stderr.write('[server %s] %s\n' % (host, fmt % args))


class ReusableTCPServer(socketserver.TCPServer):
    allow_reuse_address = True


if __name__ == '__main__':
    with ReusableTCPServer(('127.0.0.1', PORT), Handler) as httpd:
        sys.stderr.write('[server] listening on 127.0.0.1:%d\n' % PORT)
        httpd.serve_forever()
