Fix wrong netlink port id check
authorToshiaki Makita <makita.toshiaki@lab.ntt.co.jp>
Mon, 31 Jul 2017 11:20:55 +0000 (20:20 +0900)
committerBrenden Blanco <bblanco@gmail.com>
Tue, 1 Aug 2017 16:36:43 +0000 (09:36 -0700)
As per man netlink, nlmsg_pid is not process id and in fact a value
different from process id can be used.

  bpf: Wrong pid -1615084642, expected 24407

This problem can be triggered by using pyroute2 with bcc.

Signed-off-by: Toshiaki Makita <makita.toshiaki@lab.ntt.co.jp>
src/cc/libbpf.c

index 906e44f..8b88795 100644 (file)
@@ -725,6 +725,7 @@ int bpf_attach_xdp(const char *dev_name, int progfd, uint32_t flags) {
     } req;
     struct nlmsghdr *nh;
     struct nlmsgerr *err;
+    socklen_t addrlen;
 
     memset(&sa, 0, sizeof(sa));
     sa.nl_family = AF_NETLINK;
@@ -740,6 +741,17 @@ int bpf_attach_xdp(const char *dev_name, int progfd, uint32_t flags) {
         goto cleanup;
     }
 
+    addrlen = sizeof(sa);
+    if (getsockname(sock, (struct sockaddr *)&sa, &addrlen) < 0) {
+        fprintf(stderr, "bpf: get sock name of netlink: %s\n", strerror(errno));
+        goto cleanup;
+    }
+
+    if (addrlen != sizeof(sa)) {
+        fprintf(stderr, "bpf: wrong netlink address length: %d\n", addrlen);
+        goto cleanup;
+    }
+
     memset(&req, 0, sizeof(req));
     req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
     req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
@@ -790,9 +802,9 @@ int bpf_attach_xdp(const char *dev_name, int progfd, uint32_t flags) {
 
     for (nh = (struct nlmsghdr *)buf; NLMSG_OK(nh, len);
          nh = NLMSG_NEXT(nh, len)) {
-        if (nh->nlmsg_pid != getpid()) {
+        if (nh->nlmsg_pid != sa.nl_pid) {
             fprintf(stderr, "bpf: Wrong pid %d, expected %d\n",
-                   nh->nlmsg_pid, getpid());
+                   nh->nlmsg_pid, sa.nl_pid);
             errno = EBADMSG;
             goto cleanup;
         }