#!/usr/bin/env python3
"""
Multi-port HTTP server for the fenced-frame permissions-policy bypass POC.

Serves on:
  - http://localhost:18080  (publisher / top-level origin "T")
  - http://localhost:18081  (ad-tech / nested embedder origin "E")

Both ports serve from the current directory but with different
Permissions-Policy headers depending on the path.
"""
import http.server
import socketserver
import threading
import sys
import os

class Handler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # Required for fenced frame content documents.
        self.send_header('Supports-Loading-Mode', 'fenced-frame')
        # Top-level publisher opts OUT of attribution-reporting.
        # (Leaves shared-storage / shared-storage-select-url at default *.)
        if self.path.startswith('/top.html'):
            self.send_header('Permissions-Policy', 'attribution-reporting=()')
        super().end_headers()

    def guess_type(self, path):
        if path.endswith('.js'):
            return 'application/javascript'
        return super().guess_type(path)

    def log_message(self, fmt, *args):
        sys.stderr.write("[server:%d] %s\n" % (self.server.server_address[1], fmt % args))


class ReusableTCPServer(socketserver.TCPServer):
    allow_reuse_address = True


def serve(port):
    httpd = ReusableTCPServer(("127.0.0.1", port), Handler)
    sys.stderr.write("[server] listening on http://localhost:%d/\n" % port)
    httpd.serve_forever()


if __name__ == '__main__':
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    for p in (18080, 18081):
        threading.Thread(target=serve, args=(p,), daemon=True).start()
    threading.Event().wait()
