kernel_netlink.c 44.8 KB
Newer Older
1
/*
2
Copyright 2007-2010 by Grégoire Henry, Julien Cristau and Juliusz Chroboczek
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/route.h>
#include <net/if.h>
#include <arpa/inet.h>

#include <asm/types.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
42
#include <linux/fib_rules.h>
43
#include <net/if_arp.h>
44

45 46 47 48 49
/* From <linux/if_bridge.h> */
#ifndef BRCTL_GET_BRIDGES
#define BRCTL_GET_BRIDGES 1
#endif

50
#if(__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 5)
51 52 53
#define RTA_TABLE 15
#endif

54
#include "babeld.h"
55 56
#include "kernel.h"
#include "util.h"
57
#include "interface.h"
58
#include "configuration.h"
59

60
#ifndef MAX_INTERFACES
61
#define MAX_INTERFACES 1024
62 63
#endif

64 65 66 67 68 69 70 71 72 73 74 75 76
#define GET_PLEN(p, v4) (v4) ? (p) + 96 : (p)
#define COPY_ADDR(d, rta, v4)                                           \
    do {                                                                \
        if(UNLIKELY(RTA_PAYLOAD(rta) < (v4 ? 4 : 16))) {                \
            fprintf(stderr, "truncated message.");                      \
            return -1;                                                  \
        }                                                               \
        if(v4)                                                          \
            v4tov6(d, RTA_DATA(rta));                                   \
        else                                                            \
            memcpy(d, RTA_DATA(rta), 16);                               \
    } while(0)

77
int export_table = -1, import_tables[MAX_IMPORT_TABLES], import_table_count = 0;
78

79 80 81 82 83 84 85 86 87 88 89 90 91
struct sysctl_setting {
    char *name;
    int want;
    int was;
};
#define NUM_SYSCTLS 4

static struct sysctl_setting sysctl_settings[NUM_SYSCTLS] = {
    {"/proc/sys/net/ipv6/conf/all/forwarding", 1, -1},
    {"/proc/sys/net/ipv4/conf/all/forwarding", 1, -1},
    {"/proc/sys/net/ipv6/conf/all/accept_redirects", 0, -1},
    {"/proc/sys/net/ipv4/conf/all/rp_filter", 0, -1},
};
92

93 94 95 96 97
struct old_if {
    char *ifname;
    int rp_filter;
};

98
struct old_if *old_if = NULL;
99
int num_old_if = 0;
100
int max_old_if = 0;
101

102 103
static int dgram_socket = -1;

104
#ifndef ARPHRD_ETHER
105
#warning ARPHRD_ETHER not defined, we might not support exotic link layers
106 107 108 109
#define ARPHRD_ETHER 1
#define NO_ARPHRD
#endif

110
static int filter_netlink(struct nlmsghdr *nh, struct kernel_filter *filter);
111 112


113 114 115 116 117
/* Determine an interface's hardware address, in modified EUI-64 format */
int
if_eui64(char *ifname, int ifindex, unsigned char *eui)
{
    int s, rc;
118
    struct ifreq ifr;
119 120 121

    s = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
    if(s < 0) return -1;
122 123 124
    memset(&ifr, 0, sizeof(ifr));
    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
    rc = ioctl(s, SIOCGIFHWADDR, &ifr);
125 126 127 128 129 130 131 132
    if(rc < 0) {
        int saved_errno = errno;
        close(s);
        errno = saved_errno;
        return -1;
    }
    close(s);

133 134
    switch(ifr.ifr_hwaddr.sa_family) {
    case ARPHRD_ETHER:
135
#ifndef NO_ARPHRD
136 137
    case ARPHRD_FDDI:
    case ARPHRD_IEEE802_TR:
138 139 140
    case ARPHRD_IEEE802:
#endif
    {
141 142 143 144 145 146 147 148
        unsigned char *mac;
        mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
        /* Check for null address and group and global bits */
        if(memcmp(mac, zeroes, 6) == 0 ||
           (mac[0] & 1) != 0 || (mac[0] & 2) != 0) {
            errno = ENOENT;
            return -1;
        }
149
        memcpy(eui, mac, 3);
150 151
        eui[3] = 0xFF;
        eui[4] = 0xFE;
152 153
        memcpy(eui + 5, mac + 3, 3);
        eui[0] ^= 2;
154 155
        return 1;
    }
156
#ifndef NO_ARPHRD
157 158 159 160 161 162 163 164 165 166
    case ARPHRD_EUI64:
    case ARPHRD_IEEE1394:
    case ARPHRD_INFINIBAND: {
        unsigned char *mac;
        mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
        if(memcmp(mac, zeroes, 8) == 0 ||
           (mac[0] & 1) != 0 || (mac[0] & 2) != 0) {
            errno = ENOENT;
            return -1;
        }
167
        memcpy(eui, mac, 8);
168 169 170
        eui[0] ^= 2;
        return 1;
    }
171
#endif
172 173 174
    default:
        errno = ENOENT;
        return -1;
175 176 177
    }
}

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
static int
read_proc(char *filename)
{
    char buf[100];
    int fd, rc;
    fd = open(filename, O_RDONLY);
    if(fd < 0)
        return -1;
    rc = read(fd, buf, 99);
    if(rc < 0) {
        int saved_errno = errno;
        close(fd);
        errno = saved_errno;
        return -1;
    }
    close(fd);

    if(rc == 0)
        return -1;

    buf[rc] = '\0';
    return atoi(buf);
}

static int
write_proc(char *filename, int value)
{
    char buf[100];
    int fd, rc, n;
    n = snprintf(buf, 100, "%d", value);

    fd = open(filename, O_WRONLY);
    if(fd < 0)
        return -1;

    rc = write(fd, buf, n);
    if(rc < n) {
        int saved_errno = errno;
        close(fd);
        errno = saved_errno;
        return -1;
    }

    close(fd);
    return 1;
}

struct netlink {
    unsigned short seqno;
    int sock;
    struct sockaddr_nl sockaddr;
    socklen_t socklen;
};

static struct netlink nl_command = { 0, -1, {0}, 0 };
static struct netlink nl_listen = { 0, -1, {0}, 0 };
static int nl_setup = 0;

static int
netlink_socket(struct netlink *nl, uint32_t groups)
{
    int rc;
240
    int rcvsize = 512 * 1024;
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

    nl->sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
    if(nl->sock < 0)
        return -1;

    memset(&nl->sockaddr, 0, sizeof(nl->sockaddr));
    nl->sockaddr.nl_family = AF_NETLINK;
    nl->sockaddr.nl_groups = groups;
    nl->socklen = sizeof(nl->sockaddr);

    nl->seqno = time(NULL);

    rc = fcntl(nl->sock, F_GETFL, 0);
    if(rc < 0)
        goto fail;

    rc = fcntl(nl->sock, F_SETFL, (rc | O_NONBLOCK));
    if(rc < 0)
        goto fail;

261 262 263 264 265 266 267 268 269 270 271 272 273 274
#ifdef SO_RCVBUFFORCE
    rc = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUFFORCE,
                    &rcvsize, sizeof(rcvsize));
#else
    rc = -1;
#endif
    if(rc < 0) {
        rc = setsockopt(nl->sock, SOL_SOCKET, SO_RCVBUF,
                        &rcvsize, sizeof(rcvsize));
        if(rc < 0) {
            perror("setsockopt(SO_RCVBUF)");
        }
    }

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    rc = bind(nl->sock, (struct sockaddr *)&nl->sockaddr, nl->socklen);
    if(rc < 0)
        goto fail;

    rc = getsockname(nl->sock, (struct sockaddr *)&nl->sockaddr, &nl->socklen);
    if(rc < 0)
        goto fail;

    return 0;

 fail:
    {
        int saved_errno = errno;
        close(nl->sock);
        nl->sock = -1;
        errno = saved_errno;
        return -1;
    }
}

static int
netlink_read(struct netlink *nl, struct netlink *nl_ignore, int answer,
297
             struct kernel_filter *filter)
298 299 300 301 302 303 304 305 306
{

    /* 'answer' must be true when we just have send a request on 'nl_socket' */

    /* 'nl_ignore' is used in kernel_callback to ignore message originating  */
    /*  from 'nl_command' while reading 'nl_listen'                          */

    /* Return code :                                       */
    /* -1 : error                                          */
307
    /*  0 : success                                        */
308 309 310 311 312 313 314 315

    int err;
    struct msghdr msg;
    struct sockaddr_nl nladdr;
    struct iovec iov;
    struct nlmsghdr *nh;
    int len;
    int done = 0;
316
    int skip = 0;
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

    char buf[8192];

    memset(&nladdr, 0, sizeof(nladdr));
    nladdr.nl_family = AF_NETLINK;

    memset(&msg, 0, sizeof(msg));
    msg.msg_name = &nladdr;
    msg.msg_namelen = sizeof(nladdr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    iov.iov_base = &buf;

    do {
        iov.iov_len = sizeof(buf);
        len = recvmsg(nl->sock, &msg, 0);

        if(len < 0 && (errno == EAGAIN || errno == EINTR)) {
            int rc;
337
            rc = wait_for_fd(0, nl->sock, 100);
338 339 340 341 342 343 344 345 346
            if(rc <= 0) {
                if(rc == 0)
                    errno = EAGAIN;
            } else {
                len = recvmsg(nl->sock, &msg, 0);
            }
        }

        if(len < 0) {
347
            perror("netlink_read: recvmsg()");
348
            return -1;
349 350 351 352 353 354 355 356 357
        } else if(len == 0) {
            fprintf(stderr, "netlink_read: EOF\n");
            goto socket_error;
        } else if(msg.msg_namelen != nl->socklen) {
            fprintf(stderr,
                    "netlink_read: unexpected sender address length (%d)\n",
                    msg.msg_namelen);
            goto socket_error;
        } else if(nladdr.nl_pid != 0) {
358
            kdebugf("netlink_read: message not sent by kernel.\n");
359
            return -1;
360 361
        }

362
        kdebugf("Netlink message: ");
363 364 365 366

        for(nh = (struct nlmsghdr *)buf;
            NLMSG_OK(nh, len);
            nh = NLMSG_NEXT(nh, len)) {
Matthieu Boutier's avatar
Matthieu Boutier committed
367 368
            kdebugf("%s{seq:%d}", (nh->nlmsg_flags & NLM_F_MULTI) ? "[multi] " : "",
                    nh->nlmsg_seq);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
369
            if(!answer)
370
                done = 1;
371
            if(nl_ignore && nh->nlmsg_pid == nl_ignore->sockaddr.nl_pid) {
372
                kdebugf("(ignore), ");
373 374 375
                continue;
            } else if(answer && (nh->nlmsg_pid != nl->sockaddr.nl_pid ||
                                 nh->nlmsg_seq != nl->seqno)) {
376
                kdebugf("(wrong seqno %d %d /pid %d %d), ",
377 378
                        nh->nlmsg_seq, nl->seqno,
                        nh->nlmsg_pid, nl->sockaddr.nl_pid);
379 380
                continue;
            } else if(nh->nlmsg_type == NLMSG_DONE) {
381
                kdebugf("(done)\n");
382 383 384 385 386
                done = 1;
                break;
            } else if(nh->nlmsg_type == NLMSG_ERROR) {
                struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(nh);
                if(err->error == 0) {
387
                    kdebugf("(ACK)\n");
Julien Cristau's avatar
Julien Cristau committed
388
                    return 0;
389
                } else {
390
                    kdebugf("netlink_read: %s\n", strerror(-err->error));
391 392 393
                    errno = -err->error;
                    return -1;
                }
394 395 396
            } else if(nh->nlmsg_type == RTM_NEWLINK || nh->nlmsg_type == RTM_DELLINK ) {
                kdebugf("detected an interface change via netlink - triggering babeld interface check\n");
                check_interfaces();
397 398 399
            } else if(skip) {
                kdebugf("(skip)");
            } if(filter) {
400
                kdebugf("(msg -> \"");
401
                err = filter_netlink(nh, filter);
402
                kdebugf("\" %d), ", err);
403
                if(err < 0) skip = 1;
404 405
                continue;
            }
406
            kdebugf(", ");
407
        }
408
        kdebugf("\n");
409 410 411 412

        if(msg.msg_flags & MSG_TRUNC)
            fprintf(stderr, "netlink_read: message truncated\n");

413
    } while(!done);
414

415
    return 0;
416

417 418 419 420 421 422
 socket_error:
    close(nl->sock);
    nl->sock = -1;
    errno = EIO;
    return -1;
}
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

static int
netlink_talk(struct nlmsghdr *nh)
{

    int rc;
    struct sockaddr_nl nladdr;
    struct msghdr msg;
    struct iovec iov;

    memset(&nladdr, 0, sizeof(nladdr));
    nladdr.nl_family = AF_NETLINK;
    nladdr.nl_pid = 0;

    memset(&msg, 0, sizeof(msg));
    msg.msg_name = &nladdr;
    msg.msg_namelen = sizeof(nladdr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    iov.iov_base = nh;
    iov.iov_len = nh->nlmsg_len;

    nh->nlmsg_flags |= NLM_F_ACK;
    nh->nlmsg_seq = ++nl_command.seqno;

Matthieu Boutier's avatar
Matthieu Boutier committed
449
    kdebugf("Sending seqno %d from address %p (talk)\n",
450
            nl_command.seqno, (void*)&nl_command.seqno);
Matthieu Boutier's avatar
Matthieu Boutier committed
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
    rc = sendmsg(nl_command.sock, &msg, 0);
    if(rc < 0 && (errno == EAGAIN || errno == EINTR)) {
        rc = wait_for_fd(1, nl_command.sock, 100);
        if(rc <= 0) {
            if(rc == 0)
                errno = EAGAIN;
        } else {
            rc = sendmsg(nl_command.sock, &msg, 0);
        }
    }

    if(rc < nh->nlmsg_len) {
        int saved_errno = errno;
        perror("sendmsg");
        errno = saved_errno;
        return -1;
    }

470
    rc = netlink_read(&nl_command, NULL, 1, NULL); /* ACK */
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516

    return rc;
}

static int
netlink_send_dump(int type, void *data, int len) {

    struct sockaddr_nl nladdr;
    struct msghdr msg;
    struct iovec iov[2];
    union {
        char raw[NLMSG_ALIGN(sizeof(struct nlmsghdr))];
        struct nlmsghdr nh;
    } buf;
    int rc;

    /* At least we should send an 'struct rtgenmsg' */
    if(data == NULL || len == 0) {
        errno = EIO;
        return -1;
    }

    /* And more : using anything else that 'struct rtgenmsg' is currently */
    /* ignored by the linux kernel (today: 2.6.21) because NLM_F_MATCH is */
    /* not yet implemented */

    memset(&nladdr, 0, sizeof(nladdr));
    nladdr.nl_family = AF_NETLINK;

    memset(&msg, 0, sizeof(msg));
    msg.msg_name = &nladdr;
    msg.msg_namelen = sizeof(nladdr);
    msg.msg_iov = iov;
    msg.msg_iovlen = 2;

    iov[0].iov_base = buf.raw;
    iov[0].iov_len = sizeof(buf.raw);
    iov[1].iov_base = data;
    iov[1].iov_len = len;

    memset(buf.raw, 0, sizeof(buf.raw));
    buf.nh.nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
    buf.nh.nlmsg_type = type;
    buf.nh.nlmsg_seq = ++nl_command.seqno;
    buf.nh.nlmsg_len = NLMSG_LENGTH(len);

Matthieu Boutier's avatar
Matthieu Boutier committed
517
    kdebugf("Sending seqno %d from address %p (dump)\n",
518
            nl_command.seqno, (void*)&nl_command.seqno);
Matthieu Boutier's avatar
Matthieu Boutier committed
519

520 521 522 523 524 525 526 527 528 529 530
    rc = sendmsg(nl_command.sock, &msg, 0);
    if(rc < buf.nh.nlmsg_len) {
        int saved_errno = errno;
        perror("sendmsg");
        errno = saved_errno;
        return -1;
    }

    return 0;
}

531

532
int
533
kernel_setup(int setup)
534
{
535 536
    struct sysctl_setting *s;
    int i, rc;
537 538

    if(setup) {
539 540 541
        if(export_table < 0)
            export_table = RT_TABLE_MAIN;

542 543
        if(import_table_count < 1)
            import_tables[import_table_count++] = RT_TABLE_MAIN;
544

545 546 547 548
        dgram_socket = socket(PF_INET, SOCK_DGRAM, 0);
        if(dgram_socket < 0)
            return -1;

549 550 551 552 553
        rc = netlink_socket(&nl_command, 0);
        if(rc < 0) {
            perror("netlink_socket(0)");
            return -1;
        }
554
        nl_setup = 1;
555

556
        if(skip_kernel_setup) return 1;
557

558 559 560 561 562 563 564 565 566 567 568 569 570 571
        for(i=0; i<NUM_SYSCTLS; i++) {
            s = &sysctl_settings[i];
            s->was = read_proc(s->name);
            if(s->was < 0) {
                perror("Couldn't read sysctl");
                return -1;
            }
            if(s->was != s->want) {
                rc = write_proc(s->name, s->want);
                if(rc < 0) {
                    perror("Couldn't write sysctl");
                    return -1;
                }
            }
572 573
        }

574 575
        return 1;
    } else {
576 577 578
        close(dgram_socket);
        dgram_socket = -1;

579 580 581
        close(nl_command.sock);
        nl_command.sock = -1;
        nl_setup = 0;
582

583 584
        if(skip_kernel_setup) return 1;

585 586
        for(i=0; i<NUM_SYSCTLS; i++) {
            s = &sysctl_settings[i];
587
            if(s->was >= 0 && s->was != s->want) {
588 589 590 591 592
                rc = write_proc(s->name,s->was);
                if(rc < 0) {
                    perror("Couldn't write sysctl");
                    return -1;
                }
593 594 595
            }
        }

596 597 598 599 600
        return 1;

    }
}

601 602 603 604 605 606
static inline unsigned int
rtnlgrp_to_mask(unsigned int grp)
{
    return grp ? 1 << (grp - 1) : 0;
}

607 608 609 610 611 612
int
kernel_setup_socket(int setup)
{
    int rc;

    if(setup) {
613
        rc = netlink_socket(&nl_listen,
614 615 616 617
                            rtnlgrp_to_mask(RTNLGRP_IPV6_ROUTE)
                          | rtnlgrp_to_mask(RTNLGRP_IPV4_ROUTE)
                          | rtnlgrp_to_mask(RTNLGRP_LINK)
                          | rtnlgrp_to_mask(RTNLGRP_IPV4_IFADDR)
618 619 620 621 622
                          | rtnlgrp_to_mask(RTNLGRP_IPV6_IFADDR)
    /* We monitor rules, because it can be change by third parties.  For example
       a /etc/init.d/network restart on OpenWRT flush the rules. */
                          | rtnlgrp_to_mask(RTNLGRP_IPV4_RULE)
                          | rtnlgrp_to_mask(RTNLGRP_IPV6_RULE));
623
        if(rc < 0) {
624
            perror("netlink_socket(_ROUTE | _LINK | _IFADDR | _RULE)");
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
            kernel_socket = -1;
            return -1;
        }

        kernel_socket = nl_listen.sock;

        return 1;

    } else {

        close(nl_listen.sock);
        nl_listen.sock = -1;
        kernel_socket = -1;

        return 1;

    }
}

644 645 646 647 648
static int
get_old_if(const char *ifname)
{
    int i;
    for(i = 0; i < num_old_if; i++)
649
        if(strcmp(old_if[i].ifname, ifname) == 0)
650 651 652
            return i;
    if(num_old_if >= MAX_INTERFACES)
        return -1;
653
    if(num_old_if >= max_old_if) {
654
            int n = max_old_if == 0 ? 4 : 2 * max_old_if;
655
            struct old_if *new =
656
                realloc(old_if, n * sizeof(struct old_if));
657 658 659 660 661 662 663 664
            if(new != NULL) {
                old_if = new;
                max_old_if = n;
            }
    }
    if(num_old_if >= max_old_if)
        return -1;

665 666 667 668 669 670 671
    old_if[num_old_if].ifname = strdup(ifname);
    if(old_if[num_old_if].ifname == NULL)
        return -1;
    old_if[num_old_if].rp_filter = -1;
    return num_old_if++;
}

672 673 674
int
kernel_setup_interface(int setup, const char *ifname, int ifindex)
{
675 676 677 678 679 680 681 682 683 684 685 686 687 688
    char buf[100];
    int i, rc;

    /* rp_filter has weird semantics: both all/rp_filter and ifname/rp_filter
       must be set to 0 for the rp_filter to be disabled.  Deal with it. */

    rc = snprintf(buf, 100, "/proc/sys/net/ipv4/conf/%s/rp_filter", ifname);
    if(rc < 0 || rc >= 100)
        return -1;

    i = get_old_if(ifname);
    if(setup) {
        if(i >= 0)
            old_if[i].rp_filter = read_proc(buf);
689
        if(i < 0 || old_if[i].rp_filter < 0)
690 691 692
            fprintf(stderr,
                    "Warning: cannot save old configuration for %s.\n",
                    ifname);
693 694 695 696 697
	if(old_if[i].rp_filter) {
	    rc = write_proc(buf, 0);
	    if(rc < 0)
		return -1;
	}
698
    } else {
699
        if(i >= 0 && old_if[i].rp_filter > 0)
700
            rc = write_proc(buf, old_if[i].rp_filter);
701
        else if(i < 0)
702
            rc = -1;
703 704
        else
            rc = 1;
705 706 707 708 709 710 711

        if(rc < 0)
            fprintf(stderr,
                    "Warning: cannot restore old configuration for %s.\n",
                    ifname);
    }

712 713 714
    return 1;
}

715 716 717
int
kernel_interface_operational(const char *ifname, int ifindex)
{
718 719
    struct ifreq req;
    int rc;
720
    int flags = link_detect ? (IFF_UP | IFF_RUNNING) : IFF_UP;
721 722 723 724 725 726

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
    rc = ioctl(dgram_socket, SIOCGIFFLAGS, &req);
    if(rc < 0)
        return -1;
727
    return ((req.ifr_flags & flags) == flags);
728 729
}

730
int
731
kernel_interface_ipv4(const char *ifname, int ifindex, unsigned char *addr_r)
732 733
{
    struct ifreq req;
734
    int rc;
735 736 737 738

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
    req.ifr_addr.sa_family = AF_INET;
739 740
    rc = ioctl(dgram_socket, SIOCGIFADDR, &req);
    if(rc < 0)
741 742 743 744 745 746
        return -1;

    memcpy(addr_r, &((struct sockaddr_in*)&req.ifr_addr)->sin_addr, 4);
    return 1;
}

747 748 749 750
int
kernel_interface_mtu(const char *ifname, int ifindex)
{
    struct ifreq req;
751
    int rc;
752 753 754

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
755 756
    rc = ioctl(dgram_socket, SIOCGIFMTU, &req);
    if(rc < 0)
757 758 759 760 761
        return -1;

    return req.ifr_mtu;
}

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
static int
isbridge(const char *ifname, int ifindex)
{
    char buf[256];
    int rc, i;
    unsigned long args[3];
    int indices[256];

    rc = snprintf(buf, 256, "/sys/class/net/%s", ifname);
    if(rc < 0 || rc >= 256)
        goto fallback;

    if(access(buf, R_OK) < 0)
        goto fallback;

    rc = snprintf(buf, 256, "/sys/class/net/%s/bridge", ifname);
    if(rc < 0 || rc >= 256)
        goto fallback;

    if(access(buf, F_OK) >= 0)
        return 1;
    else if(errno == ENOENT)
        return 0;

 fallback:
    args[0] = BRCTL_GET_BRIDGES;
    args[1] = (unsigned long)indices;
    args[2] = 256;

    rc = ioctl(dgram_socket, SIOCGIFBR, args);
    if(rc < 0) {
        if(errno == ENOPKG)
            return 0;
        else
            return -1;
    }

    for(i = 0; i < rc; i++) {
        if(indices[i] == ifindex)
            return 1;
    }

    return 0;
}

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
static int
isbatman(const char *ifname, int ifindex)
{
    char buf[256];
    int rc;

    rc = snprintf(buf, 256, "/sys/devices/virtual/net/%s/mesh", ifname);
    if(rc < 0 || rc >= 256)
        return -1;

    if(access(buf, F_OK) >= 0)
        return 1;

    if(errno != ENOENT)
        return -1;

    return 0;
}

826 827 828 829 830 831 832
int
kernel_interface_wireless(const char *ifname, int ifindex)
{
#ifndef SIOCGIWNAME
#define SIOCGIWNAME 0x8B01
#endif
    struct ifreq req;
833
    int rc;
834

835
    if(isbridge(ifname, ifindex) != 0 || isbatman(ifname, ifindex) != 0)
836 837
        return -1;

838 839
    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
840
    rc = ioctl(dgram_socket, SIOCGIWNAME, &req);
841 842 843 844 845 846 847 848 849 850 851 852 853
    if(rc < 0) {
        if(errno == EOPNOTSUPP || errno == EINVAL)
            rc = 0;
        else {
            perror("ioctl(SIOCGIWNAME)");
            rc = -1;
        }
    } else {
        rc = 1;
    }
    return rc;
}

854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
/* Sorry for that, but I haven't managed to get <linux/wireless.h>
   to include cleanly. */

#define SIOCGIWFREQ 0x8B05

struct iw_freq {
    int m;
    short e;
    unsigned char i;
    unsigned char flags;
};

struct iwreq_subset {
    union {
        char ifrn_name[IFNAMSIZ];
    } ifr_ifrn;

    union {
        struct iw_freq freq;
    } u;
};

static int
freq_to_chan(struct iw_freq *freq)
{
    int m = freq->m, e = freq->e;

881 882
    /* If exponent is 0, assume the channel is encoded directly in m. */
    if(e == 0 && m > 0 && m < 254)
883 884
        return m;

885 886 887 888 889 890 891
    if(e <= 6) {
        int mega, step, c, i;

        /* This encodes 1 MHz */
        mega = 1000000;
        for(i = 0; i < e; i++)
            mega /= 10;
892 893

        /* Channels 1 through 13 are 5 MHz apart, with channel 1 at 2412. */
894 895
        step = 5 * mega;
        c = 1 + (m - 2412 * mega + step / 2) / step;
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
        if(c >= 1 && c <= 13)
            return c;

        /* Channel 14 is at 2484 MHz  */
        if(c >= 14 && m < 2484 * mega + step / 2)
            return 14;

        /* 802.11a channel 36 is at 5180 MHz */
        c = 36 + (m - 5180 * mega + step / 2) / step;
        if(c >= 34 && c <= 165)
            return c;
    }

    errno = ENOENT;
    return -1;
}

int
kernel_interface_channel(const char *ifname, int ifindex)
{
    struct iwreq_subset iwreq;
    int rc;

    memset(&iwreq, 0, sizeof(iwreq));
    strncpy(iwreq.ifr_ifrn.ifrn_name, ifname, IFNAMSIZ);

    rc = ioctl(dgram_socket, SIOCGIWFREQ, &iwreq);
    if(rc >= 0)
        return freq_to_chan(&iwreq.u.freq);
    else
        return -1;
}

929 930 931 932 933 934 935 936
/* Return true if we cannot handle disambiguation ourselves. */

int
kernel_disambiguate(int v4)
{
    return !v4 && has_ipv6_subtrees;
}

937 938 939 940 941 942
int
kernel_has_ipv6_subtrees(void)
{
    return (kernel_older_than("Linux", 3, 11) == 0);
}

943
int
944 945
kernel_route(int operation, int table,
             const unsigned char *dest, unsigned short plen,
946
             const unsigned char *src, unsigned short src_plen,
947
             const unsigned char *pref_src,
948 949
             const unsigned char *gate, int ifindex, unsigned int metric,
             const unsigned char *newgate, int newifindex,
950
             unsigned int newmetric, int newtable)
951 952 953 954 955
{
    union { char raw[1024]; struct nlmsghdr nh; } buf;
    struct rtmsg *rtm;
    struct rtattr *rta;
    int len = sizeof(buf.raw);
956
    int rc, ipv4, use_src = 0;
957

958 959 960 961 962 963 964 965 966 967 968
    if(!nl_setup) {
        fprintf(stderr,"kernel_route: netlink not initialized.\n");
        errno = EIO;
        return -1;
    }

    /* if the socket has been closed after an IO error, */
    /* we try to re-open it. */
    if(nl_command.sock < 0) {
        rc = netlink_socket(&nl_command, 0);
        if(rc < 0) {
969
            int olderrno = errno;
970
            perror("kernel_route: netlink_socket()");
971
            errno = olderrno;
972 973 974 975
            return -1;
        }
    }

976 977
    /* Check that the protocol family is consistent. */
    if(plen >= 96 && v4mapped(dest)) {
978
        if(!v4mapped(gate) ||
979
           !v4mapped(src)) {
980 981 982 983
            errno = EINVAL;
            return -1;
        }
    } else {
984
        if(v4mapped(gate) || v4mapped(src)) {
985 986 987 988 989
            errno = EINVAL;
            return -1;
        }
    }

990
    if(operation == ROUTE_MODIFY) {
991 992 993
        if(newmetric == metric && memcmp(newgate, gate, 16) == 0 &&
           newifindex == ifindex)
            return 0;
994 995 996 997 998 999
        /* It would be better to add the new route before removing the
           old one, to avoid losing packets.  However, this causes
           problems with non-multipath kernels, which sometimes
           silently fail the request, causing "stuck" routes.  Let's
           stick with the naive approach, and hope that the window is
           small enough to be negligible. */
1000
        kernel_route(ROUTE_FLUSH, table, dest, plen,
1001
                     src, src_plen, pref_src,
1002
                     gate, ifindex, metric,
1003 1004
                     NULL, 0, 0, 0);
        rc = kernel_route(ROUTE_ADD, newtable, dest, plen,
1005
                          src, src_plen, pref_src,
1006
                          newgate, newifindex, newmetric,
1007
                          NULL, 0, 0, 0);
1008
        if(rc < 0) {
1009 1010 1011 1012
            if(errno == EEXIST)
                rc = 1;
            /* Should we try to re-install the flushed route on failure?
               Error handling is hard. */
1013
        }
1014 1015 1016
        return rc;
    }

1017 1018

    ipv4 = v4mapped(gate);
1019
    use_src = (!is_default(src, src_plen) && kernel_disambiguate(ipv4));
1020

1021 1022 1023 1024 1025 1026
    kdebugf("kernel_route: %s %s from %s "
            "table %d metric %d dev %d nexthop %s\n",
            operation == ROUTE_ADD ? "add" :
            operation == ROUTE_FLUSH ? "flush" : "???",
            format_prefix(dest, plen), format_prefix(src, src_plen),
            table, metric, ifindex, format_address(gate));
1027

1028 1029
    /* Unreachable default routes cause all sort of weird interactions;
       ignore them. */
1030
    if(metric >= KERNEL_INFINITY && (plen == 0 || (ipv4 && plen == 96)))
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
        return 0;

    memset(buf.raw, 0, sizeof(buf.raw));
    if(operation == ROUTE_ADD) {
        buf.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL;
        buf.nh.nlmsg_type = RTM_NEWROUTE;
    } else {
        buf.nh.nlmsg_flags = NLM_F_REQUEST;
        buf.nh.nlmsg_type = RTM_DELROUTE;
    }

    rtm = NLMSG_DATA(&buf.nh);
1043 1044
    rtm->rtm_family = ipv4 ? AF_INET : AF_INET6;
    rtm->rtm_dst_len = ipv4 ? plen - 96 : plen;
1045
    if(use_src)
1046
        rtm->rtm_src_len = src_plen;
1047
    rtm->rtm_table = table;
1048
    rtm->rtm_scope = RT_SCOPE_UNIVERSE;
1049
    if(metric < KERNEL_INFINITY) {
1050
        rtm->rtm_type = RTN_UNICAST;
1051 1052
        rtm->rtm_flags |= RTNH_F_ONLINK;
    } else
1053
        rtm->rtm_type = RTN_UNREACHABLE;
1054

1055 1056 1057 1058
    rtm->rtm_protocol = RTPROT_BABEL;

    rta = RTM_RTA(rtm);

1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    if(ipv4) {
        rta = RTA_NEXT(rta, len);
        rta->rta_len = RTA_LENGTH(sizeof(struct in_addr));
        rta->rta_type = RTA_DST;
        memcpy(RTA_DATA(rta), dest + 12, sizeof(struct in_addr));
    } else {
        rta = RTA_NEXT(rta, len);
        rta->rta_len = RTA_LENGTH(sizeof(struct in6_addr));
        rta->rta_type = RTA_DST;
        memcpy(RTA_DATA(rta), dest, sizeof(struct in6_addr));
1069
        if(use_src) {
1070 1071 1072 1073 1074
            rta = RTA_NEXT(rta, len);
            rta->rta_len = RTA_LENGTH(sizeof(struct in6_addr));
            rta->rta_type = RTA_SRC;
            memcpy(RTA_DATA(rta), src, sizeof(struct in6_addr));
        }
1075
    }
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

    rta = RTA_NEXT(rta, len);
    rta->rta_len = RTA_LENGTH(sizeof(int));
    rta->rta_type = RTA_PRIORITY;

    if(metric < KERNEL_INFINITY) {
        *(int*)RTA_DATA(rta) = metric;
        rta = RTA_NEXT(rta, len);
        rta->rta_len = RTA_LENGTH(sizeof(int));
        rta->rta_type = RTA_OIF;
        *(int*)RTA_DATA(rta) = ifindex;

1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
#define ADD_IPARG(type, addr) \
        do if(ipv4) { \
            rta = RTA_NEXT(rta, len); \
            rta->rta_len = RTA_LENGTH(sizeof(struct in_addr)); \
            rta->rta_type = type; \
            memcpy(RTA_DATA(rta), addr + 12, sizeof(struct in_addr)); \
        } else { \
            rta = RTA_NEXT(rta, len); \
            rta->rta_len = RTA_LENGTH(sizeof(struct in6_addr)); \
            rta->rta_type = type; \
            memcpy(RTA_DATA(rta), addr, sizeof(struct in6_addr)); \
        } while (0)

        ADD_IPARG(RTA_GATEWAY, gate);
        if(pref_src)
            ADD_IPARG(RTA_PREFSRC, pref_src);

#undef ADD_IPARG
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
    } else {
        *(int*)RTA_DATA(rta) = -1;
    }
    buf.nh.nlmsg_len = (char*)rta + rta->rta_len - buf.raw;

    return netlink_talk(&buf.nh);
}

static int
parse_kernel_route_rta(struct rtmsg *rtm, int len, struct kernel_route *route)
{
1117
    int table = rtm->rtm_table;
1118
    struct rtattr *rta= RTM_RTA(rtm);;
1119
    int i, is_v4;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1120

1121 1122
    len -= NLMSG_ALIGN(sizeof(*rtm));

1123
    memset(route, 0, sizeof(struct kernel_route));
1124
    if(rtm->rtm_family == AF_INET) {
1125
        /* if RTA_DST is not a TLV, that's a default destination */
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1126
        const unsigned char zeroes[4] = {0, 0, 0, 0};
1127
        v4tov6(route->prefix, zeroes);
1128
        v4tov6(route->src_prefix, zeroes);
1129
        route->plen = 96;
1130
        route->src_plen = 96;
1131
    }
1132
    route->proto = rtm->rtm_protocol;
1133

1134
    is_v4 = rtm->rtm_family == AF_INET;
1135

1136
    while(RTA_OK(rta, len)) {
1137
        switch(rta->rta_type) {
1138
        case RTA_DST:
1139 1140
            route->plen = GET_PLEN(rtm->rtm_dst_len, is_v4);
            COPY_ADDR(route->prefix, rta, is_v4);
1141
            break;
1142
        case RTA_SRC:
1143 1144
            route->src_plen = GET_PLEN(rtm->rtm_src_len, is_v4);
            COPY_ADDR(route->src_prefix, rta, is_v4);
1145
            break;
1146
        case RTA_GATEWAY:
1147
            COPY_ADDR(route->gw, rta, is_v4);
1148 1149 1150 1151 1152 1153 1154 1155 1156
            break;
        case RTA_OIF:
            route->ifindex = *(int*)RTA_DATA(rta);
            break;
        case RTA_PRIORITY:
            route->metric = *(int*)RTA_DATA(rta);
            if(route->metric < 0 || route->metric > KERNEL_INFINITY)
                route->metric = KERNEL_INFINITY;
            break;
1157
        case RTA_TABLE:
1158 1159 1160 1161 1162 1163 1164 1165
            table = *(int*)RTA_DATA(rta);
            break;
        default:
            break;
        }
        rta = RTA_NEXT(rta, len);
    }

1166 1167 1168
    for(i = 0; i < import_table_count; i++)
        if(table == import_tables[i])
            return 0;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1169

1170
    return -1;
1171 1172 1173 1174 1175 1176 1177 1178
}

static void
print_kernel_route(int add, int protocol, int type,
                   struct kernel_route *route)
{
    char ifname[IFNAMSIZ];
    char addr_prefix[INET6_ADDRSTRLEN];
1179
    char src_addr_prefix[INET6_ADDRSTRLEN];
1180 1181 1182 1183 1184 1185
    char addr_gw[INET6_ADDRSTRLEN];

    if(!inet_ntop(AF_INET6, route->prefix,
                  addr_prefix, sizeof(addr_prefix)) ||
       !inet_ntop(AF_INET6,route->gw, addr_gw, sizeof(addr_gw)) ||
       !if_indextoname(route->ifindex, ifname)) {
1186
        kdebugf("Couldn't format kernel route for printing.");
1187 1188 1189
        return;
    }

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
    if(route->src_plen >= 0) {
        if(!inet_ntop(AF_INET6, route->src_prefix,
                      src_addr_prefix, sizeof(src_addr_prefix))) {
            kdebugf("Couldn't format kernel route for printing.");
            return;
        }

        kdebugf("%s kernel route: dest: %s/%d gw: %s metric: %d if: %s "
                "(proto: %d, type: %d, from: %s/%d)",
                add == RTM_NEWROUTE ? "Add" : "Delete",
                addr_prefix, route->plen, addr_gw, route->metric, ifname,
                protocol, type, src_addr_prefix, route->src_plen);
        return;
    }

1205
    kdebugf("%s kernel route: dest: %s/%d gw: %s metric: %d if: %s "
1206 1207 1208 1209 1210 1211 1212
           "(proto: %d, type: %d)",
           add == RTM_NEWROUTE ? "Add" : "Delete",
           addr_prefix, route->plen, addr_gw, route->metric, ifname,
           protocol, type);
}

static int
1213
filter_kernel_routes(struct nlmsghdr *nh, struct kernel_route *route)
1214
{
1215
    int rc, len;
1216 1217
    struct rtmsg *rtm;

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1218
    len = nh->nlmsg_len;
1219 1220

    if(nh->nlmsg_type != RTM_NEWROUTE &&
1221
       nh->nlmsg_type != RTM_DELROUTE)
1222 1223 1224 1225 1226
        return 0;

    rtm = (struct rtmsg*)NLMSG_DATA(nh);
    len -= NLMSG_LENGTH(0);

1227
    if(rtm->rtm_protocol == RTPROT_BABEL)
1228 1229
        return 0;

1230 1231 1232 1233
    /* Ignore cached routes, advertised by some kernels (linux 3.x). */
    if(rtm->rtm_flags & RTM_F_CLONED)
        return 0;

1234
    rc = parse_kernel_route_rta(rtm, len, route);
1235 1236 1237
    if(rc < 0)
        return 0;

1238
    /* Ignore default unreachable routes; no idea where they come from. */
1239
    if(route->plen == 0 && route->metric >= KERNEL_INFINITY)
1240 1241
        return 0;

1242 1243 1244
    if(debug >= 2) {
        if(rc >= 0) {
            print_kernel_route(nh->nlmsg_type, rtm->rtm_protocol,
1245
                               rtm->rtm_type, route);
1246 1247 1248 1249 1250 1251 1252 1253 1254
        }
    }

    return 1;

}

/* This function should not return routes installed by us. */
int
1255
kernel_dump(int operation, struct kernel_filter *filter)
1256
{
1257 1258
    int i, rc;
    int families[2] = { AF_INET6, AF_INET };
1259 1260 1261
    struct rtgenmsg g;

    if(!nl_setup) {
1262
        fprintf(stderr,"kernel_dump: netlink not initialized.\n");
1263 1264 1265 1266 1267 1268 1269
        errno = EIO;
        return -1;
    }

    if(nl_command.sock < 0) {
        rc = netlink_socket(&nl_command, 0);
        if(rc < 0) {
1270
            int save = errno;
1271
            perror("kernel_dump: netlink_socket()");
1272
            errno = save;
1273 1274 1275 1276
            return -1;
        }
    }

1277 1278 1279
    for(i = 0; i < 2; i++) {
        memset(&g, 0, sizeof(g));
        g.rtgen_family = families[i];
1280 1281 1282 1283
        if(operation & CHANGE_ROUTE) {
            rc = netlink_send_dump(RTM_GETROUTE, &g, sizeof(g));
            if(rc < 0)
                return -1;
1284

1285
            rc = netlink_read(&nl_command, NULL, 1, filter);
1286 1287 1288
            if(rc < 0)
                return -1;
        }
1289

1290 1291 1292 1293 1294 1295
        memset(&g, 0, sizeof(g));
        g.rtgen_family = families[i];
        if(operation & CHANGE_RULE) {
            rc = netlink_send_dump(RTM_GETRULE, &g, sizeof(g));
            if(rc < 0)
                return -1;
1296

1297
            rc = netlink_read(&nl_command, NULL, 1, filter);
1298 1299 1300
            if(rc < 0)
                return -1;
        }
1301
    }
1302

1303 1304 1305 1306 1307 1308 1309
    if(operation & CHANGE_ADDR) {
        memset(&g, 0, sizeof(g));
        g.rtgen_family = AF_UNSPEC;
        rc = netlink_send_dump(RTM_GETADDR, &g, sizeof(g));
        if(rc < 0)
            return -1;

1310
        rc = netlink_read(&nl_command, NULL, 1, filter);
1311 1312 1313 1314
        if(rc < 0)
            return -1;
    }

1315
    return 0;
1316 1317
}

1318
static char *
1319 1320 1321 1322 1323 1324 1325 1326
parse_ifname_rta(struct ifinfomsg *info, int len)
{
    struct rtattr *rta = IFLA_RTA(info);
    char *ifname = NULL;

    len -= NLMSG_ALIGN(sizeof(*info));

    while(RTA_OK(rta, len)) {
1327
        switch(rta->rta_type) {
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        case IFLA_IFNAME:
            ifname = RTA_DATA(rta);
            break;
        default:
            break;
        }
        rta = RTA_NEXT(rta, len);
    }
    return ifname;
}

1339
static int
1340 1341 1342 1343 1344
parse_addr_rta(struct ifaddrmsg *addr, int len, struct in6_addr *res)
{
    struct rtattr *rta;
    len -= NLMSG_ALIGN(sizeof(*addr));
    rta = IFA_RTA(addr);
1345
    int is_local = 0;
1346

1347
    while(RTA_OK(rta, len)) {
1348
        switch(rta->rta_type) {
1349
        case IFA_LOCAL:
1350 1351 1352 1353 1354
            /* On some point-to-point technologies, there's both _LOCAL
               and _ADDRESS, and _ADDRESS is apparently the peer address
               while _LOCAL is the one we want. */
            is_local = 1;
            /* fallthrough */
1355 1356 1357 1358 1359 1360 1361 1362 1363
        case IFA_ADDRESS:
            switch(addr->ifa_family) {
            case AF_INET:
                if(res)
                    v4tov6(res->s6_addr, RTA_DATA(rta));
                break;
            case AF_INET6:
                if(res)
                    memcpy(res->s6_addr, RTA_DATA(rta), 16);
1364 1365
                break;
            default:
1366 1367
                kdebugf("ifaddr: unexpected address family %d\n",
                        addr->ifa_family);
1368
                return -1;
1369
                break;
1370
            }
1371
            if(is_local)
1372
                return 0;
1373 1374 1375
            break;
        default:
            break;
1376 1377 1378 1379 1380 1381
        }
        rta = RTA_NEXT(rta, len);
    }
    return 0;
}

1382
static int
1383
filter_link(struct nlmsghdr *nh, struct kernel_link *link)
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
{
    struct ifinfomsg *info;
    int len;
    int ifindex;
    unsigned int ifflags;

    len = nh->nlmsg_len;

    if(nh->nlmsg_type != RTM_NEWLINK && nh->nlmsg_type != RTM_DELLINK)
        return 0;

    info = (struct ifinfomsg*)NLMSG_DATA(nh);
    len -= NLMSG_LENGTH(0);

    ifindex = info->ifi_index;
    ifflags = info->ifi_flags;

1401 1402
    link->ifname = parse_ifname_rta(info, len);
    if(link->ifname == NULL)
1403
        return 0;
1404
    kdebugf("filter_interfaces: link change on if %s(%d): 0x%x\n",
1405 1406
            link->ifname, ifindex, (unsigned)ifflags);
    return 1;
1407 1408
}

1409 1410 1411 1412
/* If data is null, takes all addresses.  If data is not null, takes
   either link-local or global addresses depending of the value of
   data[4]. */

1413
static int
1414
filter_addresses(struct nlmsghdr *nh, struct kernel_addr *addr)
1415 1416 1417 1418 1419 1420 1421 1422
{
    int rc;
    int len;
    struct ifaddrmsg *ifa;
    char ifname[IFNAMSIZ];

    len = nh->nlmsg_len;

1423
    if(nh->nlmsg_type != RTM_NEWADDR &&
1424
       nh->nlmsg_type != RTM_DELADDR)
1425 1426 1427 1428 1429
        return 0;

    ifa = (struct ifaddrmsg *)NLMSG_DATA(nh);
    len -= NLMSG_LENGTH(0);

1430
    rc = parse_addr_rta(ifa, len, &addr->addr);
1431
    if(rc < 0)
1432
        return 0;
1433
    addr->ifindex = ifa->ifa_index;
1434

1435
    kdebugf("found address on interface %s(%d): %s\n",
1436
            if_indextoname(ifa->ifa_index, ifname), ifa->ifa_index,
1437
            format_address(addr->addr.s6_addr));
1438

1439 1440 1441
    return 1;
}

1442 1443 1444
static int
filter_kernel_rules(struct nlmsghdr *nh, struct kernel_rule *rule)
{
1445
    int len, has_priority = 0, has_table = 0;
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    struct rtmsg *rtm = NULL;
    struct rtattr *rta = NULL;
    int is_v4 = 0;

    len = nh->nlmsg_len;

    rtm = (struct rtmsg*)NLMSG_DATA(nh);
    len -= NLMSG_LENGTH(0);

    rule->src_plen = rtm->rtm_src_len;
1456
    memset(rule->src, 0, sizeof(rule->src));
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    rule->table = rtm->rtm_table;

    if(rtm->rtm_family != AF_INET && rtm->rtm_family != AF_INET6) {
        kdebugf("filter_rules: Unknown family: %d\n", rtm->rtm_family);
        return -1;
    }
    is_v4 = rtm->rtm_family == AF_INET;

    rta = RTM_RTA(rtm);
    len -= NLMSG_ALIGN(sizeof(*rtm));

    for(; RTA_OK(rta, len); rta = RTA_NEXT(rta, len)) {
        switch(rta->rta_type) {
        case FRA_UNSPEC: break;
        case FRA_SRC:
1472 1473
            rule->src_plen = GET_PLEN(rtm->rtm_src_len, is_v4);
            COPY_ADDR(rule->src, rta, is_v4);
1474 1475 1476 1477 1478 1479 1480
            break;
        case FRA_PRIORITY:
            rule->priority = *(unsigned int*)RTA_DATA(rta);
            has_priority = 1;
            break;
        case FRA_TABLE:
            rule->table = *(int*)RTA_DATA(rta);
1481
            has_table = 1;
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
            break;
        default:
            kdebugf("filter_rules: Unknown rule attribute: %d.\n",
                    rta->rta_type);
            break;
        }
    }

    kdebugf("filter_rules: from %s prio %d table %d\n",
            format_prefix(rule->src, rule->src_plen),
            has_priority ? rule->priority : -1, rule->table);

1494
    if(!has_priority || !has_table)
1495 1496 1497 1498 1499
        return 0;

    return 1;
}

1500
static int
1501
filter_netlink(struct nlmsghdr *nh, struct kernel_filter *filter)
1502 1503
{
    int rc;
1504 1505
    union {
        struct kernel_route route;
1506
        struct kernel_addr addr;
1507
        struct kernel_link link;
1508
        struct kernel_rule rule;
1509
    } u;
1510

1511 1512 1513
    switch(nh->nlmsg_type) {
    case RTM_NEWROUTE:
    case RTM_DELROUTE:
1514 1515 1516 1517
        if(!filter->route) break;
        rc = filter_kernel_routes(nh, &u.route);
        if(rc <= 0) break;
        return filter->route(&u.route, filter->route_closure);
1518 1519
    case RTM_NEWLINK:
    case RTM_DELLINK:
1520 1521 1522 1523
        if(!filter->link) break;
        rc = filter_link(nh, &u.link);
        if(rc <= 0) break;
        return filter->link(&u.link, filter->link_closure);
1524 1525
    case RTM_NEWADDR:
    case RTM_DELADDR:
1526 1527 1528 1529
        if(!filter->addr) break;
        rc = filter_addresses(nh, &u.addr);
        if(rc <= 0) break;
        return filter->addr(&u.addr, filter->addr_closure);
1530 1531
    case RTM_NEWRULE:
    case RTM_DELRULE:
1532 1533 1534 1535
        if(!filter->rule) break;
        rc = filter_kernel_rules(nh, &u.rule);
        if(rc <= 0) break;
        return filter->rule(&u.rule, filter->rule_closure);
1536 1537 1538 1539
    default:
        kdebugf("filter_netlink: unexpected message type %d\n",
                nh->nlmsg_type);
        break;
1540 1541 1542 1543
    }
    return 0;
}

1544
int
1545
kernel_callback(struct kernel_filter *filter)
1546 1547 1548
{
    int rc;

1549
    kdebugf("\nReceived changes in kernel tables.\n");
Julien Cristau's avatar
Julien Cristau committed
1550

1551