import socket, struct, time, os, sys, json

def tcp(host, port, timeout=3.0):
    t0=time.time()
    s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(timeout)
    try:
        s.connect((host, port))
        dt=time.time()-t0
        return ("OPEN", round(dt,3), "")
    except socket.timeout:
        return ("TIMEOUT", round(time.time()-t0,3), "")
    except OSError as e:
        return ("ERR", round(time.time()-t0,3), "%s:%s"%(getattr(e,'errno',None), e.strerror or str(e)))
    finally:
        try: s.close()
        except: pass

def pg_sslprobe(host, port, timeout=4.0):
    # send PostgreSQL SSLRequest (len=8, code=80877103) - NOT credentials
    try:
        s=socket.socket(); s.settimeout(timeout); s.connect((host,port))
        s.sendall(struct.pack("!II",8,80877103))
        b=s.recv(1)
        s.close()
        return "SSLRequest_resp=%r"%(b,)
    except Exception as e:
        return "SSLRequest_err=%r"%e

def http_get(url, timeout=4.0, headers=None):
    import urllib.request, urllib.error
    try:
        req=urllib.request.Request(url, headers=headers or {})
        r=urllib.request.urlopen(req, timeout=timeout)
        b=r.read(300)
        return "HTTP%d %r"%(r.status, b[:250])
    except urllib.error.HTTPError as e:
        try: b=e.read(250)
        except: b=b""
        return "HTTP%d %r"%(e.code, b[:200])
    except Exception as e:
        return "ERR %r"%e

# ---- 0. network identity ----
print("###HOSTNAME", socket.gethostname())
for f in ["/proc/net/route","/proc/net/fib_trie","/etc/resolv.conf","/etc/hosts","/proc/net/if_inet6"]:
    print("###FILE", f)
    try:
        print(open(f).read()[:2500])
    except Exception as e:
        print("ERR", e)

# ---- 1. TCP reachability matrix ----
print("###TCPMATRIX")
targets=[
 ("litellm-postgres",       "10.222.220.27", 5432),
 ("litellm-gateway",        "10.222.42.25",  4000),
 ("console-backend",        "10.222.26.231", 3000),
 ("k8s-apiserver",          "10.222.0.1",    443),
 ("k8s-apiserver-80",       "10.222.0.1",    80),
 ("kube-dns-tcp",           "10.222.0.10",   53),
 ("hermes-bridge",          "10.222.205.28", 8770),
 ("hermes-gateway",         "10.222.205.28", 8642),
 ("hermes-webdav",          "10.222.205.28", 8090),
 ("presidio-analyzer",      "10.222.172.151",3000),
 ("own-svc-i26301full",     "10.222.96.183", 80),
 ("own-svc-i26301servd",    "10.222.104.99", 80),
 ("docker-host",            "172.17.0.1",    2375),
 ("docker-host-tls",        "172.17.0.1",    2376),
 ("slirp-gw",               "10.0.2.2",      22),
 ("metadata-linklocal",     "169.254.169.254",80),
 ("aliyun-metadata",        "100.100.100.200",80),
]
for name,h,p in targets:
    r=tcp(h,p)
    print("TCP %-20s %s:%s -> %s %ss %s"%(name,h,p,r[0],r[1],r[2]))

# ---- 2. postgres protocol touch (no creds) ----
print("###PG_PROTO")
print("pg10.222.220.27:5432", pg_sslprobe("10.222.220.27",5432))

# ---- 3. cluster DNS test (query kube-dns directly) ----
def dns_query(server, name, timeout=3.0):
    # build a standard A query
    tid=0x1234
    flags=0x0100
    header=struct.pack("!HHHHHH", tid, flags, 1,0,0,0)
    q=b"".join(struct.pack("B",len(p))+p.encode() for p in name.split("."))+b"\x00"
    pkt=header+q+struct.pack("!HH",1,1)
    s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(timeout)
    try:
        s.sendto(pkt,(server,53))
        data,_=s.recvfrom(512)
    except Exception as e:
        return "ERR %r"%e
    finally:
        try:s.close()
        except:pass
    if len(data)<12: return "SHORT"
    ancount=struct.unpack("!H",data[6:8])[0]
    return "rcode=%d ancount=%d"%(data[3]&0xf, ancount)

print("###DNS_PROBE via 10.222.0.10:53")
for n in ["console-backend.agentek.svc.cluster.local","litellm-gateway.agentek.svc.cluster.local","litellm-postgres.agentek.svc.cluster.local","kubernetes.default.svc.cluster.local","hermes.agentek.svc.cluster.local"]:
    print("DNS",n,"->",dns_query("10.222.0.10",n))

# ---- 4. cloud metadata / IAM ----
print("###CLOUD_METADATA")
eps=[
 ("AWS-root", "http://169.254.169.254/latest/meta-data/", None),
 ("AWS-iam-hint", "http://169.254.169.254/latest/meta-data/iam/security-credentials/", None),
 ("AWS-identity-doc", "http://169.254.169.254/latest/dynamic/instance-identity/document", None),
 ("GCP", "http://169.254.169.254/computeMetadata/v1/instance/id", {"Metadata-Flavor":"Google"}),
 ("GCP-alt", "http://metadata.google.internal/computeMetadata/v1/instance/id", {"Metadata-Flavor":"Google"}),
 ("Azure", "http://169.254.169.254/metadata/instance?api-version=2021-02-01", {"Metadata":"true"}),
 ("DigitalOcean", "http://169.254.169.254/metadata/v1/id", None),
 ("OpenStack", "http://169.254.169.254/openstack/2018-08-27/meta_data.json", None),
 ("Hetzner", "http://169.254.169.254/hetzner/v1/metadata", None),
 ("Aliyun", "http://100.100.100.200/latest/meta-data/", None),
 ("Aliyun-id", "http://100.100.100.200/latest/meta-data/instance-id", None),
 ("100.100.100.100", "http://100.100.100.100/latest/meta-data/", None),
]
for name,u,hdr in eps:
    print("META %-18s %s -> %s"%(name,u,http_get(u,4.0,hdr)))

# AWS token via PUT (read-only IMDSv2 token), then list role, fetch creds MASKED
print("###AWS_IMDSV2")
import urllib.request
try:
    req=urllib.request.Request("http://169.254.169.254/latest/api/token", data=b"", method="PUT",
        headers={"X-aws-ec2-metadata-token-ttl-seconds":"60"})
    tok=urllib.request.urlopen(req, timeout=4).read().decode()
    print("IMDSV2_TOKEN_OK len=%d"%len(tok))
    req=urllib.request.Request("http://169.254.169.254/latest/meta-data/iam/security-credentials/",
        headers={"X-aws-ec2-metadata-token":tok})
    role=urllib.request.urlopen(req,timeout=4).read().decode().strip()
    print("AWS_ROLE=%r"%role)
    if role and "<" not in role and len(role)<200:
        req=urllib.request.Request("http://169.254.169.254/latest/meta-data/iam/security-credentials/"+role,
            headers={"X-aws-ec2-metadata-token":tok})
        cred=json.loads(urllib.request.urlopen(req,timeout=4).read().decode())
        print("AWS_CRED_PRESENT type=%s akid=%s... secretlen=%d tokenlen=%d exp=%s"%(cred.get("Code"), str(cred.get("AccessKeyId"))[:6], len(str(cred.get("SecretAccessKey",""))), len(str(cred.get("Token",""))), cred.get("Expiration")))
except Exception as e:
    print("IMDSV2_err", repr(e)[:200])

print("###DONE")
