#!/usr/bin/env python3
"""connlog - log new connections over time (poll /proc/net/tcp) and report new/closed.
Usage: connlog [-i SECONDS] [-t SECONDS] [--selftest]
  Polls /proc/net/tcp and tcp6, keys each connection by local+remote+state,
  and logs every NEW connection and every CLOSED one with a timestamp.
  The twist vs watching ss: it is a connection journal — you see the churn
  (short-lived connections that come and go between snapshots) instead of
  a single frozen moment. Default: poll every 2s for 30s.
"""
import argparse
import sys
import time

STATES = {1: "ESTABLISHED", 2: "SYN_SENT", 3: "SYN_RECV", 4: "FIN_WAIT1",
          5: "FIN_WAIT2", 6: "TIME_WAIT", 7: "CLOSE", 8: "CLOSE_WAIT",
          9: "LAST_ACK", 10: "LISTEN", 11: "CLOSING"}


def parse_addr(s):
    try:
        ip_hex, port_hex = s.split(":")
    except ValueError:
        return s
    if len(ip_hex) == 8:
        b = bytes.fromhex(ip_hex)
        return f"{b[3]}.{b[2]}.{b[1]}.{b[0]}:{int(port_hex, 16)}"
    return f"[v6:{ip_hex}]:{int(port_hex, 16)}"


def snapshot():
    conns = {}
    for path in ("/proc/net/tcp", "/proc/net/tcp6"):
        try:
            with open(path) as f:
                next(f)
                for line in f:
                    parts = line.split()
                    if len(parts) < 4:
                        continue
                    try:
                        state = int(parts[3], 16)
                    except ValueError:
                        continue
                    key = (parse_addr(parts[1]), parse_addr(parts[2]), STATES.get(state, f"STATE{state}"))
                    conns[key] = True
        except OSError:
            pass
    return conns


def run(interval, total, log):
    prev = snapshot()
    log(f"baseline: {len(prev)} TCP connections tracked")
    start = time.time()
    opened = closed = 0
    while time.time() - start < total:
        time.sleep(interval)
        cur = snapshot()
        for key in cur:
            if key not in prev:
                log(f"NEW    {key[0]} -> {key[1]} [{key[2]}]")
                opened += 1
        for key in prev:
            if key not in cur:
                log(f"CLOSED {key[0]} -> {key[1]} [{key[2]}]")
                closed += 1
        prev = cur
    log(f"summary: {opened} opened, {closed} closed in {total:g}s")
    return opened, closed


def selftest():
    # Two snapshots 0.3s apart on the live tables must parse cleanly.
    a = snapshot()
    time.sleep(0.3)
    b = snapshot()
    print(f"selftest: snapshot 1: {len(a)} connections, snapshot 2: {len(b)} connections")
    opened, closed = run(0.3, 0.6, lambda msg: print(f"  {msg}"))
    print(f"selftest: parsed live /proc/net/tcp{{,6}} twice, {opened} opened / {closed} closed — OK")
    return 0


def main():
    ap = argparse.ArgumentParser(description="connlog - log new connections over time and report new/closed")
    ap.add_argument("-i", "--interval", type=float, default=2.0, help="poll interval in seconds (default 2)")
    ap.add_argument("-t", "--total", type=float, default=30.0, help="total watch time in seconds (default 30)")
    ap.add_argument("--selftest", action="store_true", help="two quick live snapshots, exit 0")
    args = ap.parse_args()
    if args.selftest:
        return selftest()

    def log(msg):
        print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)

    try:
        run(args.interval, args.total, log)
    except KeyboardInterrupt:
        print("stopped.")
    return 0


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