#!/usr/bin/env python3
"""
EMV Level 2 Bench relay.

Lets the EMV Level 2 Bench web page (emvstack.dev) talk to an EMV Level 2 stack
that listens on raw TCP. The browser cannot open TCP sockets, so this relay
accepts a WebSocket on the local machine and forwards bytes, unchanged, to the
stack's host and port, in both directions.

The relay does not parse or change the protocol: framing (length header,
message type, payload) is handled by the page. Each TCP read is sent to the
page as one binary WebSocket message; the page reassembles frames from the
length header.

Usage:
    pip install websockets
    python l2bench_relay.py                       # the page chooses the stack's IP and port
    python l2bench_relay.py --target 127.0.0.1:5000 --fixed-target   # always this stack

The page asks for a stack with ws://127.0.0.1:8765/?target=HOST:PORT. Without
--fixed-target the relay connects to that address; with it, the page's choice
is ignored and --target is always used.

Stack log (optional): the page can also open ws://127.0.0.1:8765/log?target=HOST:PORT
to receive the text the stack writes on a dedicated log port, for example
    stdbuf -oL ./stack | nc -lk 5001
This connection is one way, stack to page; nothing is sent to the log port.
With --fixed-target, the log port is only reachable if --log-target is given.

Only pages from the allowed origins can connect: https://emvstack.dev, and a copy
of the site served on this machine (http://localhost or http://127.0.0.1, any port),
so the bench can be tested before the site is online:
    cd emvstack-site
    python -m http.server 8000
    then open http://localhost:8000/tools/l2-bench.html
"""
import argparse
import asyncio
import logging
import re
from urllib.parse import parse_qs, urlparse

from websockets.asyncio.server import serve

DEFAULT_ORIGINS = [
    "https://emvstack.dev",
    "https://www.emvstack.dev",
    re.compile(r"http://(localhost|127\.0\.0\.1)(:\d+)?"),  # a copy of the site served on this machine, any port
    "null",  # pages opened from a local file
    None,
]

log = logging.getLogger("l2bench-relay")


def parse_hostport(value, default_host="127.0.0.1"):
    host, _, port = value.rpartition(":")
    return (host or default_host), int(port)


async def bridge(ws, target_host, target_port):
    peer = ws.remote_address
    try:
        reader, writer = await asyncio.open_connection(target_host, target_port)
    except OSError as exc:
        log.warning("cannot reach stack at %s:%s (%s)", target_host, target_port, exc)
        await ws.close(code=1011, reason=f"stack unreachable at {target_host}:{target_port}")
        return
    log.info("page %s connected to stack %s:%s", peer, target_host, target_port)

    async def page_to_stack():
        async for message in ws:
            data = message.encode() if isinstance(message, str) else message
            writer.write(data)
            await writer.drain()

    async def stack_to_page():
        while True:
            data = await reader.read(65536)
            if not data:
                break
            await ws.send(data)

    tasks = [asyncio.create_task(page_to_stack()), asyncio.create_task(stack_to_page())]
    try:
        await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    finally:
        for t in tasks:
            t.cancel()
        writer.close()
        try:
            await writer.wait_closed()
        except OSError:
            pass
        await ws.close()
        log.info("page %s disconnected", peer)


async def log_bridge(ws, target_host, target_port):
    """One way: text written by the stack on its log port goes to the page."""
    peer = ws.remote_address
    try:
        reader, writer = await asyncio.open_connection(target_host, target_port)
    except OSError as exc:
        log.warning("cannot reach stack log port at %s:%s (%s)", target_host, target_port, exc)
        await ws.close(code=1011, reason=f"log port unreachable at {target_host}:{target_port}")
        return
    log.info("page %s receiving stack log from %s:%s", peer, target_host, target_port)

    async def drain_page():
        async for _ in ws:  # the page sends nothing on this channel; ignore anything it does
            pass

    async def stack_to_page():
        while True:
            data = await reader.read(65536)
            if not data:
                break
            await ws.send(data)

    tasks = [asyncio.create_task(drain_page()), asyncio.create_task(stack_to_page())]
    try:
        await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
    finally:
        for t in tasks:
            t.cancel()
        writer.close()
        try:
            await writer.wait_closed()
        except OSError:
            pass
        await ws.close()
        log.info("page %s stopped receiving the stack log", peer)


async def main():
    ap = argparse.ArgumentParser(description="WebSocket-to-TCP relay for the EMV Level 2 Bench page.")
    ap.add_argument("--target", default="127.0.0.1:5000", help="default stack host:port (default 127.0.0.1:5000)")
    ap.add_argument("--fixed-target", action="store_true", help="ignore the stack address sent by the page")
    ap.add_argument("--log-target", default=None, help="with --fixed-target: stack log host:port the page may read")
    ap.add_argument("--listen", default="127.0.0.1:8765", help="local WebSocket address (default 127.0.0.1:8765)")
    ap.add_argument("--allow-origin", action="append", default=[], help="extra page origin allowed to connect")
    args = ap.parse_args()

    target_host, target_port = parse_hostport(args.target)
    listen_host, listen_port = parse_hostport(args.listen)
    origins = DEFAULT_ORIGINS + args.allow_origin

    async def handler(ws):
        url = urlparse(ws.request.path)
        is_log = url.path.rstrip("/") == "/log"
        if args.fixed_target:
            if is_log:
                if not args.log_target:
                    await ws.close(code=1008, reason="log port not enabled: start the relay with --log-target HOST:PORT")
                    return
                host, port = parse_hostport(args.log_target)
            else:
                host, port = target_host, target_port
        else:
            host, port = target_host, target_port
            wanted = parse_qs(url.query).get("target", [""])[0]
            if wanted:
                try:
                    host, port = parse_hostport(wanted)
                except ValueError:
                    await ws.close(code=1008, reason="bad target, use HOST:PORT")
                    return
            elif is_log:
                await ws.close(code=1008, reason="no log port given")
                return
        await (log_bridge if is_log else bridge)(ws, host, port)

    async with serve(handler, listen_host, listen_port, origins=origins, max_size=None):
        log.info("relay listening on ws://%s:%s, %s stack %s:%s", listen_host, listen_port,
                 "always to" if args.fixed_target else "default", target_host, target_port)
        await asyncio.get_running_loop().create_future()


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        pass
