#!/usr/bin/env python3
"""ottervpn browser proxy: the encrypted proxy behind the ottervpn browser extension.

The browser talks to this server over TLS. Sites are reached from this server's address.
Nothing about which sites you visit is logged or reported. Every 30 seconds the proxy tells
ottervpn which accounts were active (so they earn shells) and fetches the list of allowed keys,
which arrive only as SHA-256 hashes.
"""
import asyncio, base64, hashlib, ipaddress, json, os, socket, ssl, sys, urllib.request

API = os.environ["OTTER_API"].rstrip("/")
TOKEN = os.environ["OTTER_TOKEN"]
NODE = os.environ["OTTER_NODE"]
HOST = os.environ.get("OTTER_PROXY_HOST", "")
PORT = int(os.environ.get("OTTER_PROXY_PORT", "443"))
CERT = os.environ.get("OTTER_PROXY_CERT", "")
KEY = os.environ.get("OTTER_PROXY_KEY", "")
INTERVAL = int(os.environ.get("OTTER_PROXY_INTERVAL", "30"))

allowed = {}   # sha256("user:key") -> user
usage = {}     # user -> [bytes down, bytes up] since the last report
BLOCKED_PORTS = {25, 465, 587}  # no mail sending through the proxy
PRIVATE = [ipaddress.ip_network(n) for n in (
    "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12",
    "192.168.0.0/16", "224.0.0.0/4", "240.0.0.0/4", "::/128", "::1/128", "fc00::/7", "fe80::/10")]


def call(method, path, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(API + path, data=data, method=method, headers={
        "Authorization": "Bearer " + TOKEN, "content-type": "application/json", "user-agent": "ottervpn-proxy/1"})
    with urllib.request.urlopen(req, timeout=15) as r:
        return json.loads(r.read() or b"{}")


def who(header):
    """Returns the account for a valid Proxy-Authorization header, else None."""
    if not header.lower().startswith("basic "):
        return None
    try:
        pair = base64.b64decode(header[6:].strip()).decode()
    except Exception:
        return None
    return allowed.get(hashlib.sha256(pair.encode()).hexdigest())


async def public_ip(host, port):
    """Resolves host and returns the first public address, so the proxy can't be pointed at private networks."""
    try:
        infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM)
    except socket.gaierror:
        return None
    # Prefer IPv4 so every site sees the server's one public address (the one ottervpn knows), then fall back to IPv6.
    infos = sorted(infos, key=lambda i: 0 if i[0] == socket.AF_INET else 1)
    for _fam, _t, _p, _c, addr in infos:
        ip = ipaddress.ip_address(addr[0])
        if not any(ip in net for net in PRIVATE):
            return addr[0]
    return None


async def pipe(reader, writer, user, slot):
    try:
        while True:
            data = await reader.read(65536)
            if not data:
                break
            usage.setdefault(user, [0, 0])[slot] += len(data)
            writer.write(data)
            await writer.drain()
    except Exception:
        pass
    finally:
        try:
            writer.close()
        except Exception:
            pass


async def reply(w, code, text, extra=""):
    w.write(f"HTTP/1.1 {code} {text}\r\n{extra}Content-Length: 0\r\nConnection: close\r\n\r\n".encode())
    try:
        await w.drain()
    finally:
        w.close()


async def handle(r, w):
    try:
        head = await asyncio.wait_for(r.readuntil(b"\r\n\r\n"), 20)
    except Exception:
        w.close()
        return
    lines = head.decode("latin-1").split("\r\n")
    try:
        method, target, version = lines[0].split(" ", 2)
    except ValueError:
        return await reply(w, 400, "Bad Request")
    headers = []
    auth = ""
    for line in lines[1:]:
        if ":" not in line:
            continue
        k, v = line.split(":", 1)
        if k.strip().lower() == "proxy-authorization":
            auth = v.strip()
        elif k.strip().lower() not in ("proxy-connection", "connection", "keep-alive"):
            headers.append(f"{k.strip()}: {v.strip()}")
    user = who(auth)
    if not user:
        return await reply(w, 407, "Proxy Authentication Required", 'Proxy-Authenticate: Basic realm="ottervpn"\r\n')

    if method == "CONNECT":
        host, _, port = target.rpartition(":")
        host = host.strip("[]")
    elif target.startswith("http://"):
        hostport, _, path = target[7:].partition("/")
        host, _, port = hostport.rpartition(":") if ":" in hostport.rsplit("]", 1)[-1] else (hostport, "", "80")
        host = host.strip("[]")
    else:
        return await reply(w, 400, "Bad Request")
    try:
        port = int(port)
    except ValueError:
        return await reply(w, 400, "Bad Request")
    if port in BLOCKED_PORTS or not 0 < port < 65536:
        return await reply(w, 403, "Forbidden")
    ip = await public_ip(host, port)
    if not ip:
        return await reply(w, 502, "Bad Gateway")
    try:
        ur, uw = await asyncio.wait_for(asyncio.open_connection(ip, port), 15)
    except Exception:
        return await reply(w, 502, "Bad Gateway")

    if method == "CONNECT":
        w.write(b"HTTP/1.1 200 Connection Established\r\n\r\n")
        await w.drain()
    else:
        head = f"{method} /{path} {version}\r\n" + "".join(h + "\r\n" for h in headers) + "Connection: close\r\n\r\n"
        uw.write(head.encode("latin-1"))
        await uw.drain()
    await asyncio.gather(pipe(r, uw, user, 1), pipe(ur, w, user, 0))


async def sync_forever():
    loop = asyncio.get_running_loop()
    while True:
        try:
            data = await loop.run_in_executor(None, call, "GET", "/api/node/proxy-users?id=" + NODE)
            fresh = {x["h"]: x["u"] for x in data.get("users", [])}
            allowed.clear()
            allowed.update(fresh)
            active = [{"u": u, "rx": v[0], "tx": v[1]} for u, v in usage.items() if v[0] or v[1]]
            usage.clear()
            await loop.run_in_executor(None, call, "POST", "/api/node/proxy-report", {"id": NODE, "users": active})
        except Exception as e:  # keep serving through API blips
            print(f"sync failed: {e}", file=sys.stderr, flush=True)
        await asyncio.sleep(INTERVAL)


async def main():
    loop = asyncio.get_running_loop()
    loop.set_exception_handler(lambda _loop, _ctx: None)  # dropped TLS handshakes are normal on a public port
    ctx = None
    if CERT:
        ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
        ctx.minimum_version = ssl.TLSVersion.TLSv1_2
        ctx.load_cert_chain(CERT, KEY)
    if HOST:
        await loop.run_in_executor(None, call, "POST", "/api/node/proxy", {"id": NODE, "host": HOST, "port": PORT})
    data = await loop.run_in_executor(None, call, "GET", "/api/node/proxy-users?id=" + NODE)
    allowed.update({x["h"]: x["u"] for x in data.get("users", [])})
    server = await asyncio.start_server(handle, None, PORT, ssl=ctx, limit=65536)
    asyncio.create_task(sync_forever())
    print(f"ottervpn proxy on port {PORT} ({'TLS' if ctx else 'plain, testing only'}), {len(allowed)} accounts", flush=True)
    async with server:
        await server.serve_forever()


if __name__ == "__main__":
    asyncio.run(main())
