Mark
Mark

Reputation: 6484

retrieve neighbour entry via struct rt

I'm working on a kernel module code, where I need to peek in to the routing table to fetch ARP table entry for my daddr:

       |--------------------------------------------------|
-------+ enp0s1 192.168.2.0/24      192.168.3.0/24 enp0s2 +-----
       |--------------------------------------------------|

For example, I need to obtain neighbour entry for 192.168.3.111, and this entry has been permanently added in the table:

% ip neigh  add 192.168.3.111 lladdr 00:11:22:33:44:55 dev enp0s2 nud permanent
% ip neigh sh
...
192.168.3.111 dev enp0s2 lladdr 00:11:22:33:44:55 PERMANENT
% ip route show
...
192.168.3.0/24 dev enp0s2 proto kernel scope link src 192.168.3.2

I came up with the following code:

struct rtable *rt;
struct flowi4 fl4;
struct dst_entry dst;
struct neighbour *neigh;
u8 mac[ETH_ALEN];

...
memset(&fl4, 0, sizeof fl4);
fl4.daddr = daddr;
fl4.flowi4_proto = IPPROTO_UDP;

rt = ip_route_output_key(net, &fl4);
if (IS_ERR(rt))
    goto err;

...
dst = rt->dst;
neigh = dst_neigh_lookup(&dst, &fl4.daddr);
if (!neigh) {
   ...
}

neigh_ha_snapshot(mac, neigh, neigh->dev);
neigh_release(neigh);
ip_rt_put(rt);

However neigh_ha_snapshot does not return correct MAC address, in fact I think it returns garbage, sometimes ff:ff:ff:ff:ff:ff, sometimes multicast 01:xx:xx:xx:xx:xx.

What am I doing wrong?

Upvotes: 0

Views: 532

Answers (1)

Mark
Mark

Reputation: 6484

The issue is fixed as follows:

neigh = dst_neigh_lookup(&rt->dst, &fl4.daddr);

So instead of having struct dst_entry object on the stack, assigning a value from rt and passing a pointer to it in dst_neigh_lookup(), just pass a a pointer to dst member in the current rt object.

The reason is withing the following code:

static inline struct neighbour *dst_neigh_lookup(const struct dst_entry *dst, const void *daddr)
{
        struct neighbour *n = dst->ops->neigh_lookup(dst, NULL, daddr);
        return IS_ERR(n) ? NULL : n;
}

where neigh_lookup is initialized to function ipv4_neigh_lookup() defined in net/ipv4/route.c :

static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst,
                                           struct sk_buff *skb,
                                           const void *daddr)
{
        struct net_device *dev = dst->dev;
        const __be32 *pkey = daddr;
        const struct rtable *rt;
        struct neighbour *n;

        rt = (const struct rtable *) dst;
        ...
}

From this point rt is bogus and so is the rest.

Upvotes: 1

Related Questions