#!/usr/bin/env python3
"""Run a bounded HTTP proxy capture. stdout is JSONL; target output is suppressed."""

import argparse
import json
import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time


class CaptureError(Exception):
    pass


def emit(**data):
    print(json.dumps(data, ensure_ascii=False), flush=True)


def read_status(path):
    try:
        return json.loads(path.read_text(encoding='utf-8'))
    except (OSError, ValueError):
        return {}


def private_create(path):
    # O_EXCL rejects existing files and symlinks, including dangling symlinks.
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    os.close(fd)


def available_port(port):
    with socket.socket() as sock:
        sock.bind(('127.0.0.1', port))
        return sock.getsockname()[1]


def stop_target(process):
    if process is None or process.poll() is not None:
        return
    if os.name == 'nt':
        subprocess.run(['taskkill', '/pid', str(process.pid), '/T', '/F'],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
    else:
        # Keep the inherited process group: minimal-agent's Bash kills that group
        # on cancellation. A new session here would escape the host's cleanup.
        table = subprocess.check_output(['ps', '-axo', 'pid=,ppid='], text=True)
        pairs = [tuple(map(int, line.split())) for line in table.splitlines() if line.strip()]
        owned = {process.pid}
        while True:
            children = {pid for pid, parent in pairs if parent in owned}
            if children <= owned:
                break
            owned |= children
        # Stop descendants before the parent can reparent them. These commands
        # must remain foreground; daemonizing/double-forking targets aren't supported.
        for pid in sorted(owned - {process.pid}, reverse=True):
            try:
                os.kill(pid, signal.SIGKILL)
            except ProcessLookupError:
                pass
        process.terminate()
    try:
        process.wait(timeout=2)
    except subprocess.TimeoutExpired:
        process.kill()
        process.wait(timeout=2)


def parser_for_cli():
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest='action', required=True)
    check = sub.add_parser('check')
    check.add_argument('--port', type=int, default=8080)
    check.add_argument('--mitmdump', default='mitmdump', help='Executable name or absolute path')
    for name in ('run', 'listen'):
        cmd = sub.add_parser(name)
        cmd.add_argument('--port', type=int, default=8080, help='Loopback port; 0 chooses a free port')
        cmd.add_argument('--mitmdump', default='mitmdump')
        cmd.add_argument('--duration', type=int, default=30, help='Capture seconds after readiness (1..540)')
        cmd.add_argument('--host', help='Exact hostname and subdomains; no URL, port or wildcard')
        cmd.add_argument('--output', required=True, help='New JSONL file; never overwritten')
        cmd.add_argument('--ca-dir', help='Private mitmproxy CA directory; defaults beside output')
        cmd.add_argument('--upstream-ca', help='PEM CA bundle for an authorized private upstream server')
        cmd.add_argument('--include-json-bodies', action='store_true')
        cmd.add_argument('--max-flows', type=int, default=1000)
        cmd.add_argument('--max-output-bytes', type=int, default=10 * 1024 * 1024)
        if name == 'run':
            cmd.add_argument('--trust-ca', action='store_true', help='Set CA environment variables for this child only')
            cmd.add_argument('command', nargs=argparse.REMAINDER)
    return parser


def execute(args, binary):
    output = Path(os.path.abspath(os.path.expanduser(args.output)))
    status_path = Path(str(output) + '.status.json')
    output.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    # Reserve both names before launching anything. Never touch an existing file.
    private_create(output)
    try:
        private_create(status_path)
    except OSError:
        output.unlink()
        raise
    status_path.write_text(json.dumps({'state': 'starting', 'finished': False}), encoding='utf-8')
    cert_dir = Path(args.ca_dir).expanduser().absolute() if args.ca_dir else output.parent / 'mitmproxy-ca'
    if cert_dir.is_symlink():
        raise CaptureError('CA directory must not be a symlink')
    cert_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
    if os.name != 'nt':
        cert_dir.chmod(0o700)
    # Loading arbitrary scripts/options from a reused config would defeat the
    # guarantees of the wrapper. CA files may be reused; config files may not.
    if any((cert_dir / name).exists() for name in ('config.yaml', 'config.yml')):
        raise CaptureError('Use a dedicated CA directory without mitmproxy config.yaml/config.yml')
    cert = cert_dir / 'mitmproxy-ca-cert.pem'
    upstream_ca = Path(args.upstream_ca).expanduser().resolve(strict=True) if args.upstream_ca else None
    port = available_port(args.port)
    proxy_url = f'http://127.0.0.1:{port}'
    interrupted = []
    old_signals = {}
    for sig in (signal.SIGINT, signal.SIGTERM):
        old_signals[sig] = signal.signal(sig, lambda number, _frame: interrupted.append(number))
    proxy = target = None
    target_code = None
    reason = 'failed'
    error = None
    with tempfile.TemporaryDirectory(prefix='network-debug-') as runtime:
        stop_file = Path(runtime) / 'stop'
        env = os.environ.copy()
        env.update(PYTHONDONTWRITEBYTECODE='1',
                   NETWORK_CAPTURE_OUTPUT=str(output), NETWORK_CAPTURE_STATUS=str(status_path),
                   NETWORK_CAPTURE_STOP=str(stop_file), NETWORK_CAPTURE_HOST=args.host or '',
                   NETWORK_CAPTURE_JSON_BODIES='1' if args.include_json_bodies else '0',
                   NETWORK_CAPTURE_MAX_FLOWS=str(args.max_flows),
                   NETWORK_CAPTURE_MAX_BYTES=str(args.max_output_bytes))
        command = [binary, '--mode', 'regular', '--listen-host', '127.0.0.1',
                   '--listen-port', str(port), '--set', f'confdir={cert_dir}',
                   '--set', 'flow_detail=0', '--set', 'termlog_verbosity=error',
                   '--set', 'rawtcp=false', '--set', 'http3=false',
                   '--set', 'connection_strategy=lazy', '--set', 'onboarding=false',
                   '-s', str(Path(__file__).with_name('flow_addon.py'))]
        if upstream_ca:
            command += ['--set', f'ssl_verify_upstream_trusted_ca={upstream_ca}']
        try:
            proxy = subprocess.Popen(command, env=env, stdin=subprocess.DEVNULL,
                                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            deadline = time.monotonic() + 20
            while True:
                startup = read_status(status_path)
                if interrupted:
                    raise CaptureError('interrupted during startup')
                if proxy.poll() is not None or startup.get('error') or startup.get('finished'):
                    raise CaptureError('mitmdump startup failed; check its version, port and addon compatibility')
                if startup.get('ready'):
                    break
                if time.monotonic() >= deadline:
                    raise CaptureError('addon readiness timeout; no successful capture was established')
                time.sleep(0.05)
            if not cert.is_file():
                raise CaptureError('mitmproxy CA certificate was not generated')
            emit(status='listening', proxy=proxy_url, output=str(output),
                 status_file=str(status_path), ca_cert=str(cert), duration=args.duration)
            deadline = time.monotonic() + args.duration
            if args.action == 'run':
                child_env = os.environ.copy()
                for key in ('HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', 'ALL_PROXY', 'all_proxy'):
                    child_env[key] = proxy_url
                child_env.update(NO_PROXY='', no_proxy='', NETWORK_CAPTURE_CA=str(cert))
                if args.trust_ca:
                    for key in ('SSL_CERT_FILE', 'REQUESTS_CA_BUNDLE', 'CURL_CA_BUNDLE', 'NODE_EXTRA_CA_CERTS'):
                        child_env[key] = str(cert)
                target = subprocess.Popen(args.command, env=child_env, stdin=subprocess.DEVNULL,
                                          stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            while True:
                if interrupted:
                    reason = 'interrupted'
                    break
                state = read_status(status_path)
                if state.get('error') or proxy.poll() is not None:
                    raise CaptureError('capture engine failed; see status_file for structured state')
                if target is not None and target.poll() is not None:
                    target_code = target.returncode
                    reason = 'target_exited'
                    break
                if time.monotonic() >= deadline:
                    reason = 'duration_elapsed'
                    break
                time.sleep(0.05)
        except (OSError, CaptureError) as exc:
            # Never copy target/proxy logs or network contents into the tool result.
            error = str(exc) if isinstance(exc, CaptureError) else type(exc).__name__
        finally:
            try:
                stop_target(target)
                if target is not None and target_code is None:
                    target_code = target.returncode
            except (OSError, subprocess.SubprocessError):
                error = error or 'target_cleanup_failed'
                if target and target.poll() is None:
                    target.kill()
                    target.wait(timeout=2)
            if proxy and proxy.poll() is None:
                # Cooperative stop works on Windows too and lets done() flush
                # incomplete requests and active WebSocket counters.
                stop_file.touch()
                try:
                    proxy.wait(timeout=5)
                except subprocess.TimeoutExpired:
                    proxy.terminate()
                    try:
                        proxy.wait(timeout=2)
                    except subprocess.TimeoutExpired:
                        proxy.kill()
                        proxy.wait(timeout=2)
                    error = error or 'capture_shutdown_timeout'
            for sig, previous in old_signals.items():
                signal.signal(sig, previous)
    state = read_status(status_path)
    if not state.get('finished'):
        error = error or 'capture_not_finalized'
    if state.get('error'):
        error = error or state['error']
    emit(status='failed' if error else 'stopped', reason=reason, error=error,
         output=str(output), status_file=str(status_path), target_exit_code=target_code,
         flows=state.get('flows', 0), records=state.get('records', 0),
         incomplete=state.get('incomplete', 0), truncated=state.get('truncated', False),
         empty=state.get('records', 0) == 0)
    if interrupted:
        return 128 + interrupted[0]
    if error:
        return 2
    if target is not None and reason == 'duration_elapsed':
        return 124
    return 0 if target_code is None else (target_code if target_code >= 0 else 128 - target_code)


def main(argv=None):
    parser = parser_for_cli()
    args = parser.parse_args(argv)
    if not 0 <= args.port <= 65535:
        parser.error('port must be 0..65535')
    binary = shutil.which(args.mitmdump)
    try:
        if args.action == 'check':
            try:
                port = available_port(args.port)
            except OSError:
                port = None
            emit(python=sys.version.split()[0], mitmdump=binary, port=args.port,
                 port_free=port is not None, ready=binary is not None and port is not None)
            return 0 if binary and port is not None else 2
        if not binary:
            raise CaptureError('mitmdump is unavailable; install it in an isolated environment or pass --mitmdump')
        if not 1 <= args.duration <= 540:
            parser.error('duration must be 1..540 seconds; reserve time for startup and cleanup')
        if not 1 <= args.max_flows <= 10000 or not 1024 <= args.max_output_bytes <= 100 * 1024 * 1024:
            parser.error('max-flows must be 1..10000; max-output-bytes must be 1024..104857600')
        if args.host:
            import ipaddress
            try:
                args.host = str(ipaddress.ip_address(args.host))
            except ValueError:
                import re
                args.host = args.host.rstrip('.').encode('idna').decode().lower()
                if not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?', args.host):
                    parser.error('host must be a hostname or IP address, not a URL, port or wildcard')
        if args.action == 'run':
            args.command = args.command[1:] if args.command[:1] == ['--'] else args.command
            if not args.command:
                parser.error('run requires -- followed by a foreground target command')
        return execute(args, binary)
    except (OSError, ValueError, CaptureError) as exc:
        emit(status='failed', error=str(exc) if isinstance(exc, CaptureError) else type(exc).__name__)
        return 2


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