#!/usr/bin/env python3
"""Find an OPEN port to your SOCKS proxy from the hosting server.

Your SOCKS provider offers 1080, 9100-9200, and 6000-6010. The host blocks 1080
(confirmed). This scans ALL those ports to the SOCKS IP and reports which are reachable,
so you can pick an open one and ask the SOCKS provider to route on it.

Usage (on the server):
    python scan_socks_ports.py
    # or override the IP:
    SOCKS_HOST=169.197.93.90 python scan_socks_ports.py
"""
import os
import socket
import time

HOST = os.environ.get("SOCKS_HOST", "169.197.93.90")
# The ports your SOCKS provider supports.
PORTS = [1080] + list(range(9100, 9201)) + list(range(6000, 6011))
TIMEOUT = 4  # seconds per port


def check(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(TIMEOUT)
    t0 = time.time()
    try:
        s.connect((host, port))
        return "OPEN", time.time() - t0
    except ConnectionRefusedError:
        return "REFUSED", None
    except socket.timeout:
        return "TIMEOUT", None
    except Exception as e:
        return f"ERR:{type(e).__name__}", None
    finally:
        s.close()


def main():
    print(f"Scanning {HOST} across {len(PORTS)} ports (1080, 9100-9200, 6000-6010)...")
    print(f"{'PORT':>6}  {'STATE':<10}  NOTE")
    print("-" * 50)
    open_ports = []
    for p in PORTS:
        state, elapsed = check(HOST, p)
        note = f"{elapsed:.2f}s" if elapsed is not None else ""
        if state == "OPEN":
            note = f"connected in {elapsed:.2f}s  <-- USE THIS ONE"
            open_ports.append(p)
        print(f"{p:>6}  {state:<10}  {note}")
    print("-" * 50)
    if open_ports:
        print(f"\nOPEN PORTS: {open_ports}")
        print(f"Ask your SOCKS provider to give you a session on port {open_ports[0]},")
        print(f"then set the profile SOCKS to:  {HOST}:{open_ports[0]}:USER:PASS")
    else:
        print("\nNO OPEN PORTS in those ranges.")
        print("The host blocks 1080, 9100-9200, AND 6000-6010 outbound.")
        print("Options: (1) ask the host to open one of these ranges;")
        print("(2) use a SOCKS provider with a 443/80 endpoint;")
        print("(3) run an SSH tunnel on 443 to forward to the SOCKS.")


if __name__ == "__main__":
    main()
