#!/usr/bin/env python3
"""443 multiplexer v3: SSH / SSH-over-TLS (stunnel) / TLS (mtg) / HTTP (pac).
DPI-proof: with the home ISP only TLS-like flows pass on 443, so SSH is
wrapped in TLS (stunnel on 127.0.0.1:4455) and selected by SNI.
"""
import socket, select, threading

LISTEN = ("0.0.0.0", 443)
BACKENDS = {
    "ssh":     ("127.0.0.1", 22),      # raw SSH (for VPN / abroad)
    "ssh_tls": ("127.0.0.1", 4455),    # SSH-over-TLS (stunnel terminator)
    "pac_tls": ("127.0.0.1", 4456),    # PAC-over-TLS (stunnel terminator)
    "socks_tls": ("127.0.0.1", 4457),  # SOCKS5-over-TLS (stunnel terminator)
    "tls":     ("127.0.0.1", 4443),    # mtg (Telegram FakeTLS)
    "http":    ("127.0.0.1", 8444),    # PAC server
}
SSH_SNI = "ssh.vpn.sohanev.ru"
PAC_SNI = "pac.vpn.sohanev.ru"
SOCKS_SNI = "clients1.google.com"


def parse_sni(head):
    """Extract SNI from TLS ClientHello bytes; None if not parseable."""
    try:
        if len(head) < 5 or head[0] != 0x16:
            return None
        pos = 5  # content_type(1) + version(2) + length(2)
        if head[pos] != 0x01:  # handshake type must be ClientHello
            return None
        pos += 4              # handshake_type(1) + handshake_length(3)
        pos += 2              # client_version
        pos += 32             # random
        sl = head[pos]
        pos += 1 + sl         # session_id
        cs_len = int.from_bytes(head[pos:pos + 2], "big")
        pos += 2 + cs_len     # cipher_suites
        cm_len = head[pos]
        pos += 1 + cm_len     # compression_methods
        if pos + 2 > len(head):
            return None
        ext_len = int.from_bytes(head[pos:pos + 2], "big")
        pos += 2
        end = pos + ext_len
        while pos + 4 <= end and pos + 4 <= len(head):
            etype = int.from_bytes(head[pos:pos + 2], "big")
            elen = int.from_bytes(head[pos + 2:pos + 4], "big")
            pos += 4
            if pos + elen > len(head) or pos + elen > end:
                break
            if etype == 0:  # server_name
                data = head[pos:pos + elen]
                if len(data) >= 5:
                    nl = int.from_bytes(data[3:5], "big")
                    name = data[5:5 + nl]
                    return name.decode("ascii", "ignore") if name else None
            pos += elen
        return None
    except Exception:
        return None


def route(head):
    if head.startswith(b"SSH-"):
        return BACKENDS["ssh"]
    if head[0] == 0x16:
        sni = (parse_sni(head) or "").lower()
        # универсально: <proto>.vpn.sohanev.ru ИЛИ <proto>.litnets.vpn.sohanev.ru
        if sni.endswith(".vpn.sohanev.ru") or sni.endswith(".litnets.vpn.sohanev.ru"):
            proto = sni.split(".")[0]
            m = {"ssh": "ssh_tls", "pac": "pac_tls", "socks": "socks_tls"}
            if proto in m:
                return BACKENDS[m[proto]]
        if sni == SOCKS_SNI:
            return BACKENDS["socks_tls"]
        return BACKENDS["tls"]
    if head.upper().startswith((b"GET ", b"POST ", b"HEAD ", b"OPTIONS ")):
        return BACKENDS["http"]
    return BACKENDS["tls"]


def pipe(a, b):
    try:
        while True:
            data = a.recv(65536)
            if not data:
                break
            b.sendall(data)
    except Exception:
        pass
    finally:
        for s in (a, b):
            try:
                s.close()
            except Exception:
                pass


def handle(conn):
    try:
        conn.settimeout(10)
        head = conn.recv(2048)
        if not head:
            conn.close()
            return
        target = route(head)
        try:
            import time as _time
            with open('/var/log/sslh.log', 'a') as _f:
                _f.write('%s sni=%s -> %s\n' % (_time.strftime('%H:%M:%S'), parse_sni(head) or head[:3], target))
        except Exception:
            pass
        up = socket.create_connection(target, timeout=10)
        up.settimeout(None)
        conn.settimeout(None)
        up.sendall(head)
        threading.Thread(target=pipe, args=(conn, up), daemon=True).start()
        pipe(up, conn)
    except Exception:
        try:
            conn.close()
        except Exception:
            pass


def main():
    srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind(LISTEN)
    srv.listen(256)
    while True:
        conn, _ = srv.accept()
        threading.Thread(target=handle, args=(conn,), daemon=True).start()


if __name__ == "__main__":
    main()
