#!/usr/bin/env python3
"""
Probe: can we get a large rx headroom onto a TUN port on kernel 5.15
without netkit?

OVS datapath.c does:
    new_headroom = netdev_get_fwd_headroom(vport->dev)   # = dev->needed_headroom
    if (new_headroom > dp->max_headroom) ovs_update_headroom(dp, new_headroom)
    netdev_set_rx_headroom(vport->dev, dp->max_headroom) # -> tun_set_headroom()

So any OVS port with a large needed_headroom raises the headroom on every
other port, including a TUN. netkit was used only because it lets
userspace set needed_headroom directly. This probe tries other devices.
"""
import socket, struct, subprocess, sys, os

NETLINK_GENERIC = 16
NETLINK_ROUTE = 0
RTM_NEWLINK = 16
NLM_F_REQUEST, NLM_F_ACK, NLM_F_EXCL, NLM_F_CREATE = 1, 4, 0x200, 0x400
IFLA_IFNAME, IFLA_LINKINFO = 3, 18
IFLA_INFO_KIND, IFLA_INFO_DATA = 1, 2

def nla(t, v):
    l = 4 + len(v)
    return struct.pack("HH", l, t) + v + b"\x00" * ((4 - l % 4) % 4)

def cstr(s):
    return s.encode() + b"\x00"

class Genl:
    def __init__(self):
        self.s = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, NETLINK_GENERIC)
        self.s.settimeout(5)
        self.seq = 1
    def fam(self, name):
        attr = nla(2, cstr(name))
        body = struct.pack("BBH", 3, 1, 0) + attr
        self.s.send(struct.pack("IHHII", 16 + len(body), 0x10, 1, self.seq, 0) + body)
        d = self.s.recv(8192)
        ln, typ, fl, seq, pid = struct.unpack("IHHII", d[:16])
        if typ == 2:
            return None
        off = 20
        while off < ln:
            alen, atype = struct.unpack_from("HH", d, off)
            if atype == 1:
                return struct.unpack_from("H", d, off + 4)[0]
            off += (alen + 3) & ~3
        return None
    def req(self, famid, cmd, payload):
        body = struct.pack("BBH", cmd, 1, 0) + payload
        self.s.send(struct.pack("IHHII", 16 + len(body), famid, 1, self.seq, 0) + body)
        d = self.s.recv(65535)
        ln, typ, fl, seq, pid = struct.unpack("IHHII", d[:16])
        if typ == 2:
            return struct.unpack_from("i", d, 16)[0]
        return 0

def rtnl_newlink(name, kind, data=b""):
    ifinfo = struct.pack("=BBHiII", socket.AF_UNSPEC, 0, 0, 0, 0, 0xFFFFFFFF)
    li = nla(IFLA_INFO_KIND, cstr(kind))
    if data:
        li += nla(IFLA_INFO_DATA, data)
    payload = ifinfo + nla(IFLA_IFNAME, cstr(name)) + nla(IFLA_LINKINFO, li)
    s = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, NETLINK_ROUTE)
    s.settimeout(5)
    hdr = struct.pack("IHHII", 16 + len(payload), RTM_NEWLINK,
                      NLM_F_REQUEST | NLM_F_ACK | NLM_F_EXCL | NLM_F_CREATE, 1, 0)
    s.send(hdr + payload)
    d = s.recv(65535)
    s.close()
    if len(d) < 20 or struct.unpack_from("H", d, 4)[0] != 2:
        return -999
    return struct.unpack_from("i", d, 16)[0]

def run(cmd):
    r = subprocess.run(cmd, capture_output=True, text=True)
    return r.returncode, r.stdout + r.stderr

def main():
    print("kernel:", os.uname().release)
    g = Genl()
    dp_fam = g.fam("ovs_datapath")
    vp_fam = g.fam("ovs_vport")
    print("ovs_datapath family:", dp_fam, " ovs_vport family:", vp_fam)
    if not dp_fam:
        print("OVS not available")
        return 1

    # TUN device that will receive the headroom
    import fcntl
    TUNSETIFF = 0x400454CA
    IFF_TUN, IFF_NO_PI = 0x0001, 0x1000
    fd = os.open("/dev/net/tun", os.O_RDWR)
    ifr = struct.pack("16sH", b"pt0", IFF_TUN | IFF_NO_PI)
    fcntl.ioctl(fd, TUNSETIFF, ifr)
    print("created tun pt0")

    # Try several device kinds that might expose a large needed_headroom
    candidates = [
        ("veth", b""),
        ("vxlan", nla(1, struct.pack("I", 42)) + nla(2, struct.pack("I", 4789)) + nla(4, struct.pack("I", 1))),
    ]
    for kind, data in candidates:
        rc = rtnl_newlink(f"p{kind[:3]}", kind, data)
        print(f"  create {kind}: rc={rc}")

    # Build the datapath and add ports
    rc = g.req(dp_fam, 1, nla(1, cstr("pdp")))  # OVS_DP_CMD_NEW, OVS_DP_ATTR_NAME
    print("datapath create rc:", rc)
    dp_ifidx = socket.if_nametoindex("pdp")
    print("datapath ifindex:", dp_ifidx)

    # add tun as port 1
    def vport_payload(ifidx, port_no, name):
        return (nla(1, struct.pack("I", port_no)) +
                nla(2, cstr(name)) +
                nla(3, struct.pack("I", 2)) +          # OVS_VPORT_TYPE_NETDEV
                nla(4, struct.pack("I", ifidx)) +
                nla(5, struct.pack("I", dp_ifidx)))    # OVS_VPORT_ATTR_UPCALL_PID
    rc = g.req(vp_fam, 1, vport_payload(socket.if_nametoindex("pt0"), 1, "pt0"))
    print("add tun vport rc:", rc)

    print("done")
    return 0

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