#!/usr/bin/env python3
"""ps4tunnel — dials out from your network to the bench and holds the line open.

Run it on the phone (Termux) or any computer in the same network as the PS4.
It makes one outgoing connection to the bench, then relays every connection the
bench asks for to the address it names. Nothing is opened on your router, and
nothing inside your network is reachable from outside unless this program is
running and the bench asks for it.

    python ps4tunnel.py                 # connects to the default bench
    python ps4tunnel.py --host 172.105.74.41 --port 9100 --token ...

Leave it running while the bench works. Ctrl-C to stop.
"""
import argparse
import socket
import sys
import threading
import time

DEFAULT_HOST = "172.105.74.41"
DEFAULT_PORT = 9100
DEFAULT_TOKEN = "9f2c1d7a4b6e8035"

send_lock = threading.Lock()


def send_frame(sock, header, payload=b""):
    with send_lock:
        sock.sendall(header.encode() + payload)


def pump(sock, remote, cid):
    """Local socket -> tunnel."""
    try:
        while True:
            data = sock.recv(32768)
            if not data:
                break
            send_frame(remote, f"D {cid} {len(data)}\n", data)
    except OSError:
        pass
    finally:
        try:
            sock.close()
        except OSError:
            pass
        send_frame(remote, f"Z {cid}\n")


def handle_connect(remote, cid, host, port):
    try:
        sock = socket.create_connection((host, port), timeout=10)
        sock.settimeout(None)
    except OSError as exc:
        send_frame(remote, f"E {cid} {exc.__class__.__name__}\n")
        print(f"  {host}:{port} refused ({exc})", flush=True)
        return
    send_frame(remote, f"A {cid} ok\n")
    print(f"  open {host}:{port}", flush=True)
    threading.Thread(target=pump, args=(sock, remote, cid), daemon=True).start()
    CHANNELS[cid] = sock


CHANNELS = {}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--host", default=DEFAULT_HOST)
    ap.add_argument("--port", type=int, default=DEFAULT_PORT)
    ap.add_argument("--token", default=DEFAULT_TOKEN)
    args = ap.parse_args()

    while True:
        try:
            remote = socket.create_connection((args.host, args.port), timeout=15)
            remote.settimeout(None)      # the line stays idle for minutes at a time
            remote.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
            remote.sendall(f"TUNNEL {args.token}\n".encode())
            print(f"connected to the bench at {args.host}:{args.port}", flush=True)
            buf = b""
            while True:
                data = remote.recv(65536)
                if not data:
                    break
                buf += data
                while True:
                    nl = buf.find(b"\n")
                    if nl < 0:
                        break
                    head = buf[:nl].decode("ascii", "replace")
                    parts = head.split(" ")
                    if parts[0] == "D":
                        need = nl + 1 + int(parts[2])
                        if len(buf) < need:
                            break
                        payload = buf[nl + 1:need]
                        buf = buf[need:]
                        sock = CHANNELS.get(int(parts[1]))
                        if sock:
                            try:
                                sock.sendall(payload)
                            except OSError:
                                CHANNELS.pop(int(parts[1]), None)
                        continue
                    if parts[0] == "C":
                        buf = buf[nl + 1:]
                        cid, host, port = int(parts[1]), parts[2], int(parts[3])
                        threading.Thread(target=handle_connect,
                                         args=(remote, cid, host, port), daemon=True).start()
                        continue
                    if parts[0] == "Z":
                        buf = buf[nl + 1:]
                        sock = CHANNELS.pop(int(parts[1]), None)
                        if sock:
                            try:
                                sock.close()
                            except OSError:
                                pass
                        continue
                    buf = buf[nl + 1:]
        except OSError as exc:
            print(f"link lost ({exc}); reconnecting in 5s", flush=True)
        except KeyboardInterrupt:
            print("stopped", flush=True)
            return 0
        time.sleep(5)


if __name__ == "__main__":
    sys.exit(main())
