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 attrs_of(enc, klen, hashv, auth, dh, life=True, dur=28800):
    a = struct.pack(">HH", 0x8000 | 1, enc)
    if klen:
        a += struct.pack(">HH", 0x8000 | 14, klen)
    a += struct.pack(">HH", 0x8000 | 2, hashv)
    a += struct.pack(">HH", 0x8000 | 3, auth)
    a += struct.pack(">HH", 0x8000 | 4, dh)
    if life:
        a += struct.pack(">HH", 0x8000 | 11, 1)
        a += struct.pack(">HHH", 0x8000 | 12, 4, dur)
    return a


def one_transform(num, a):
    return struct.pack(">BBH", 0, 0, 8 + len(a)) + struct.pack(">BBBB", num, 1, 0, 0) + a


def build(combos, life=True):
    props = b""
    for i, (enc, klen, hashv, auth, dh) in enumerate(combos, 1):
        tr = one_transform(1, attrs_of(enc, klen, hashv, auth, dh, life))
        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(os.urandom(8), "big"), 0, 1, 0x10, 2, 0, 0, 28 + len(body)) + body


TESTS = {
    "L1": ([(7, 256, 2, 3, 2)], True),
    "L2": ([(7, 256, 2, 3, 2)], False),
    "L3": ([(7, 256, 2, 3, 2), (7, 256, 4, 3, 14)], True),
}
HOSTS = sys.argv[1:]
for ip in HOSTS:
    print("==", ip, flush=True)
    for name, (combos, life) in TESTS.items():
        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(combos, life), (ip, 500))
        try:
            d, _ = s.recvfrom(8192)
            print("  ", name, "len=%d exch=%d np=%d flag=%02x" % (len(d), d[18], d[16], d[19]), flush=True)
        except Exception as e:
            print("  ", name, "ERR", type(e).__name__, flush=True)
        s.close()
