import os, socket, struct, sys

CP = bytes.fromhex("F4ED19E0C114EB516FAAAC0EE37DAF2807B4381F")
CCC = bytes.fromhex("DEFB99E69A9F1F6E06F15006B1F166AE")
FRAG = bytes.fromhex("4048B7D56EBCE88525E7DE7F00D6C2D3")


def pl(n, t, b):
    return struct.pack(">BBH", n, t, 4 + len(b)) + b


def transform(num, enc, klen, hashv, auth, dh):
    attrs = struct.pack(">HH", 0x8000 | 1, enc)
    if klen:
        attrs += struct.pack(">HH", 0x8000 | 14, klen)
    attrs += struct.pack(">HH", 0x8000 | 2, hashv)
    attrs += struct.pack(">HH", 0x8000 | 3, auth)
    attrs += struct.pack(">HH", 0x8000 | 4, dh)
    return struct.pack(">BBH", 0, 0, 8 + len(attrs)) + struct.pack(">BBBB", num, 1, 0, 0) + attrs


VARIANTS = {
    "A": [(7, 256, 2, 3, 2)],
    "B": [(7, 256, 4, 3, 14)],
    "C": [(7, 128, 4, 3, 14)],
    "D": [(7, 256, 4, 3, 19)],
    "E": [(5, 192, 2, 3, 2)],
    "F": [(7, 256, 2, 3, 5)],
    "G": [(7, 256, 4, 3, 5)],
    "H": [(7, 256, 2, 3, 2), (7, 256, 4, 3, 14), (5, 192, 2, 3, 2), (7, 128, 2, 3, 14)],
    "I": [(7, 256, 2, 3, 2), (5, 192, 2, 3, 2)],
}


def build(name, cookie):
    trs = VARIANTS[name]
    props = b""
    for i, (enc, klen, hashv, auth, dh) in enumerate(trs, 1):
        tr = transform(1, enc, klen, hashv, auth, dh)
        props += struct.pack(">BBHBBBB", 0, 0, 8 + len(tr), i, 1, 0, 1) + tr
    sa = struct.pack(">II", 1, 1) + props
    body = pl(13, 1, sa) + pl(13, 13, CP + struct.pack(">IIIII", 2, 0, 0, 0, 0)) + pl(13, 13, CCC) + pl(0, 13, FRAG)
    return struct.pack(">QQBBBBII", int.from_bytes(cookie, "big"), 0, 1, 0x10, 2, 0, 0, 28 + len(body)) + body


def probe(ip, name):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.bind(("0.0.0.0", 500))
    except OSError:
        s.bind(("0.0.0.0", 0))
    s.settimeout(4)
    ck = os.urandom(8)
    s.sendto(build(name, ck), (ip, 500))
    try:
        while True:
            d, _ = s.recvfrom(8192)
            if d[0:8] != ck:
                continue
            return "len=%d exch=%d np=%d flags=%02x" % (len(d), d[18], d[16], d[19])
    except Exception as e:
        return "ERR %s" % type(e).__name__
    finally:
        s.close()


for ip in sys.argv[1:]:
    print("==", ip, flush=True)
    for name in VARIANTS:
        print("  ", name, probe(ip, name), flush=True)
