#!/usr/bin/env python3
"""scripting.rocks Advanced Python: standalone TCP scanner for Python 3.11+.

Default: print a plan. Add --execute to connect to explicitly allowed numeric IPs.
No DNS, service payloads, subnet expansion or browser networking.
"""

from ipaddress import ip_address, ip_network

def scan_plan(targets, ports, allowed, max_endpoints=64):
    if type(max_endpoints) is not int or not 1 <= max_endpoints <= 256:
        raise ValueError("max_endpoints must be 1..256")
    if any(not isinstance(value, list) for value in (targets, ports, allowed)):
        raise ValueError("Use lists for targets, ports and allowed prefixes")
    networks = []
    for value in allowed:
        if not isinstance(value, str) or "/" not in value or "%" in value:
            raise ValueError("Use unscoped CIDR allowlists")
        networks.append(ip_network(value.strip(), strict=True))
    addresses = set()
    for value in targets:
        if not isinstance(value, str) or "%" in value:
            raise ValueError("Use numeric unscoped IP targets")
        address = ip_address(value.strip())
        if address.is_unspecified or address.is_multicast or (address.version == 6 and address.is_link_local):
            raise ValueError("Target cannot be used by this scanner")
        if not any(address.version == network.version and address in network for network in networks):
            raise ValueError("Target is outside the allowed scope")
        addresses.add(address)
    if any(type(port) is not int or not 1 <= port <= 65535 for port in ports):
        raise ValueError("Ports must be integers 1..65535")
    unique_ports = sorted(set(ports))
    if len(addresses) * len(unique_ports) > max_endpoints:
        raise ValueError("Endpoint limit exceeded")
    return [{"address":str(address), "port":port}
            for address in sorted(addresses, key=lambda value:(value.version, int(value)))
            for port in unique_ports]


def tcp_probe(address, port, timeout_ms=500, *, socket_factory=None, clock=None):
    """Make one TCP connection, send no application data, and always close it."""
    import errno
    import socket
    import time
    endpoint = scan_plan([address], [port], ["0.0.0.0/0", "::/0"])[0]
    if type(timeout_ms) is not int or not 1 <= timeout_ms <= 5000:
        raise ValueError("timeout_ms must be 1..5000")
    socket_factory = socket_factory or socket.socket
    clock = clock or time.monotonic
    address = endpoint["address"]
    ipv6 = ip_address(address).version == 6
    family = socket.AF_INET6 if ipv6 else socket.AF_INET
    destination = (address, port, 0, 0) if ipv6 else (address, port)
    started = clock()
    state, detail = "open", ""
    try:
        with socket_factory(family, socket.SOCK_STREAM) as connection:
            connection.settimeout(timeout_ms / 1000)
            connection.connect(destination)
    except TimeoutError:
        state, detail = "timed_out", "TimeoutError"
    except ConnectionRefusedError:
        state, detail = "refused", "ConnectionRefusedError"
    except OSError as error:
        state = "timed_out" if error.errno == errno.ETIMEDOUT else "refused" if error.errno == errno.ECONNREFUSED else "error"
        detail = type(error).__name__ + (":" + str(error.errno) if error.errno is not None else "")
    return {**endpoint, "state": state,
            "elapsed_ms": round(max(0, (clock() - started) * 1000), 3), "detail": detail}


def main(argv=None):
    import argparse
    import json
    import sys
    parser = argparse.ArgumentParser(
        description="Plan a bounded TCP assessment. Connections require --execute. Use only endpoints you are authorised to assess.",
        epilog="Numeric IP targets only; no DNS, CIDR expansion, service banners or authentication. A TCP handshake does not establish application health.")
    parser.add_argument("--target", action="append", required=True, help="Explicit IPv4/IPv6 address; repeat for each target")
    parser.add_argument("--port", action="append", required=True, type=int, help="Port 1..65535; repeat as needed")
    parser.add_argument("--allow", action="append", required=True, help="Strict allowed CIDR; does not generate targets")
    parser.add_argument("--timeout-ms", type=int, default=500, help="Per-endpoint deadline, 1..5000 (default: 500)")
    parser.add_argument("--max-endpoints", type=int, default=64, help="Deduplicated plan limit, 1..256 (default: 64)")
    parser.add_argument("--execute", action="store_true", help="Perform the planned TCP connections; default is plan only")
    args = parser.parse_args(argv)
    try:
        if not 1 <= args.timeout_ms <= 5000:
            raise ValueError("timeout-ms must be 1..5000")
        plan = scan_plan(args.target, args.port, args.allow, args.max_endpoints)
    except ValueError as error:
        parser.error(str(error))
    if not args.execute:
        print(json.dumps({"mode": "plan", "timeout_ms": args.timeout_ms, "endpoints": plan}, indent=2))
        return 0
    results = []
    interrupted = False
    try:
        for endpoint in plan:
            results.append(tcp_probe(endpoint["address"], endpoint["port"], args.timeout_ms))
    except KeyboardInterrupt:
        interrupted = True
    print(json.dumps({"mode": "executed", "interrupted": interrupted,
                      "planned": len(plan), "completed": len(results), "results": results}, indent=2))
    if interrupted:
        print("Interrupted; output contains only completed observations.", file=sys.stderr)
        return 130
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
