#!/usr/bin/env python3
"""
Serves two cross-origin sites on the local network so an Android device on the
same LAN can reach them:
  - "evil"  -> http://<host-ip>:8000/evil.html
  - "bank"  -> http://<host-ip>:8001/bank.html

Two distinct ports => two distinct origins => cross-origin navigation forces a
RenderFrameHost swap and the old RFH enters BackForwardCache.
"""

import http.server
import os
import socket
import socketserver
import threading

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


def detect_lan_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.connect(("8.8.8.8", 80))
        return s.getsockname()[0]
    except OSError:
        return "127.0.0.1"
    finally:
        s.close()


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

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


def serve(port):
    with socketserver.TCPServer(("0.0.0.0", port), Handler) as httpd:
        httpd.allow_reuse_address = True
        httpd.serve_forever()


if __name__ == "__main__":
    ip = detect_lan_ip()
    print(f"[*] evil origin : http://{ip}:8000/evil.html")
    print(f"[*] bank origin : http://{ip}:8001/bank.html")
    threading.Thread(target=serve, args=(8001,), daemon=True).start()
    serve(8000)
