kernel_netlink.c 34 KB
Newer Older
1
/*
2
Copyright 2007, 2008 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/if_bridge.h>
43
#include <netinet/ether.h>
44

45 46 47 48
#if (__GLIBC__ < 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ <= 5)
#define RTA_TABLE 15
#endif

49 50 51
#include "babel.h"
#include "kernel.h"
#include "util.h"
52
#include "network.h"
53

54 55
int export_table = -1, import_table = -1;

56
static int old_forwarding = -1;
57
static int old_ipv4_forwarding = -1;
58
static int old_accept_redirects = -1;
59
static int old_rp_filter = -1;
60

61 62
static int dgram_socket = -1;

63 64 65 66 67
/* Determine an interface's hardware address, in modified EUI-64 format */
int
if_eui64(char *ifname, int ifindex, unsigned char *eui)
{
    int s, rc;
68
    struct ifreq ifr;
69 70 71

    s = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
    if(s < 0) return -1;
72 73 74
    memset(&ifr, 0, sizeof(ifr));
    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
    rc = ioctl(s, SIOCGIFHWADDR, &ifr);
75 76 77 78 79 80 81 82
    if(rc < 0) {
        int saved_errno = errno;
        close(s);
        errno = saved_errno;
        return -1;
    }
    close(s);

83 84
    switch(ifr.ifr_hwaddr.sa_family) {
    case ARPHRD_ETHER:
85 86
    case ARPHRD_FDDI:
    case ARPHRD_IEEE802_TR:
87 88 89 90 91 92 93 94 95
    case ARPHRD_IEEE802: {
        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;
        }
96
        memcpy(eui, mac, 3);
97 98
        eui[3] = 0xFF;
        eui[4] = 0xFE;
99 100
        memcpy(eui + 5, mac + 3, 3);
        eui[0] ^= 2;
101 102
        return 1;
    }
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    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;
        }
        memcpy(eui, mac, 64);
        eui[0] ^= 2;
        return 1;
    }
    default:
        errno = ENOENT;
        return -1;
120 121 122
    }
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
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;

    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;

    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,
             int (*fn)(struct nlmsghdr *nh, void *data), void *data)
{

    /* '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                                          */
    /*  0 : if(fn) found_interesting; else found_ack;      */
    /*  1 : only if(fn) nothing interesting has been found */
    /*  2 : nothing found, retry                           */

    int err;
    struct msghdr msg;
    struct sockaddr_nl nladdr;
    struct iovec iov;
    struct nlmsghdr *nh;
    int len;
    int interesting = 0;
    int done = 0;

    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;
269
            rc = wait_for_fd(0, nl->sock, 100);
270 271 272 273 274 275 276 277 278
            if(rc <= 0) {
                if(rc == 0)
                    errno = EAGAIN;
            } else {
                len = recvmsg(nl->sock, &msg, 0);
            }
        }

        if(len < 0) {
279
            perror("netlink_read: recvmsg()");
280 281 282 283 284 285 286 287 288 289
            return 2;
        } 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) {
290
            kdebugf("netlink_read: message not sent by kernel.\n");
291 292 293
            return 2;
        }

294
        kdebugf("Netlink message: ");
295 296 297 298

        for(nh = (struct nlmsghdr *)buf;
            NLMSG_OK(nh, len);
            nh = NLMSG_NEXT(nh, len)) {
299
            kdebugf("%s", (nh->nlmsg_flags & NLM_F_MULTI) ? "[multi] " : "");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
300
            if(!answer)
301
                done = 1;
302
            if(nl_ignore && nh->nlmsg_pid == nl_ignore->sockaddr.nl_pid) {
303
                kdebugf("(ignore), ");
304 305 306
                continue;
            } else if(answer && (nh->nlmsg_pid != nl->sockaddr.nl_pid ||
                                 nh->nlmsg_seq != nl->seqno)) {
307
                kdebugf("(wrong seqno %d %d /pid %d %d), ",
308 309 310 311
                       nh->nlmsg_seq, nl->seqno,
                       nh->nlmsg_pid, nl->sockaddr.nl_pid);
                continue;
            } else if(nh->nlmsg_type == NLMSG_DONE) {
312
                kdebugf("(done)\n");
313 314 315 316 317
                done = 1;
                break;
            } else if(nh->nlmsg_type == NLMSG_ERROR) {
                struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(nh);
                if(err->error == 0) {
318
                    kdebugf("(ACK)\n");
Julien Cristau's avatar
Julien Cristau committed
319
                    return 0;
320 321 322 323 324 325 326
                } else {
                    errno = -err->error;
                    perror("netlink_read");
                    errno = -err->error;
                    return -1;
                }
            } else if(fn) {
327
                kdebugf("(msg -> \"");
328
                err = fn(nh,data);
329
                kdebugf("\" %d), ", err);
330 331 332 333
                if(err < 0) return err;
                interesting = interesting || err;
                continue;
            }
334
            kdebugf(", ");
335
        }
336
        kdebugf("\n");
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 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 449 450 451 452 453

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

    } while (!done);

    return interesting;

    socket_error:
        close(nl->sock);
        nl->sock = -1;
        errno = EIO;
        return -1;
    }

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;

    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;
    }

    rc = netlink_read(&nl_command, NULL, 1, NULL, NULL); /* ACK */

    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);

    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;
}

int
454
kernel_setup(int setup)
455 456 457 458
{
    int rc;

    if(setup) {
459 460 461 462 463 464
        if(export_table < 0)
            export_table = RT_TABLE_MAIN;

        if(import_table < 0)
            import_table = RT_TABLE_MAIN;

465 466 467 468
        dgram_socket = socket(PF_INET, SOCK_DGRAM, 0);
        if(dgram_socket < 0)
            return -1;

469 470 471 472 473
        rc = netlink_socket(&nl_command, 0);
        if(rc < 0) {
            perror("netlink_socket(0)");
            return -1;
        }
474
        nl_setup = 1;
475 476 477 478 479 480 481 482 483 484 485 486 487

        old_forwarding = read_proc("/proc/sys/net/ipv6/conf/all/forwarding");
        if(old_forwarding < 0) {
            perror("Couldn't read forwarding knob.");
            return -1;
        }

        rc = write_proc("/proc/sys/net/ipv6/conf/all/forwarding", 1);
        if(rc < 0) {
            perror("Couldn't write forwarding knob.");
            return -1;
        }

488 489 490 491 492 493
        old_ipv4_forwarding =
            read_proc("/proc/sys/net/ipv4/conf/all/forwarding");
        if(old_ipv4_forwarding < 0) {
            perror("Couldn't read IPv4 forwarding knob.");
            return -1;
        }
494

495 496 497 498
        rc = write_proc("/proc/sys/net/ipv4/conf/all/forwarding", 1);
        if(rc < 0) {
            perror("Couldn't write IPv4 forwarding knob.");
            return -1;
499 500 501
        }


502 503 504 505 506 507 508 509 510 511 512 513
        old_accept_redirects =
            read_proc("/proc/sys/net/ipv6/conf/all/accept_redirects");
        if(old_accept_redirects < 0) {
            perror("Couldn't read accept_redirects knob.");
            return -1;
        }

        rc = write_proc("/proc/sys/net/ipv6/conf/all/accept_redirects", 0);
        if(rc < 0) {
            perror("Couldn't write accept_redirects knob.");
            return -1;
        }
514 515 516 517 518 519 520 521 522 523 524 525 526 527

        old_rp_filter =
            read_proc("/proc/sys/net/ipv4/conf/all/rp_filter");
        if(old_rp_filter < 0) {
            perror("Couldn't read rp_filter knob.");
            return -1;
        }

        rc = write_proc("/proc/sys/net/ipv4/conf/all/rp_filter", 0);
        if(rc < 0) {
            perror("Couldn't write rp_filter knob.");
            return -1;
        }

528 529
        return 1;
    } else {
530 531 532
        close(dgram_socket);
        dgram_socket = -1;

533 534 535 536
        if(old_forwarding >= 0) {
            rc = write_proc("/proc/sys/net/ipv6/conf/all/forwarding",
                            old_forwarding);
            if(rc < 0) {
537
                perror("Couldn't write forwarding knob.\n");
538 539 540
                return -1;
            }
        }
541 542 543 544 545 546 547 548 549 550

        if(old_ipv4_forwarding >= 0) {
            rc = write_proc("/proc/sys/net/ipv4/conf/all/forwarding",
                            old_ipv4_forwarding);
            if(rc < 0) {
                perror("Couldn't write IPv4 forwarding knob.\n");
                return -1;
            }
        }

551 552 553 554 555 556 557 558 559
        if(old_accept_redirects >= 0) {
            rc = write_proc("/proc/sys/net/ipv6/conf/all/accept_redirects",
                            old_accept_redirects);
            if(rc < 0) {
                perror("Couldn't write accept_redirects knob.\n");
                return -1;
            }
        }

560 561 562 563 564 565 566 567 568
        if(old_rp_filter >= 0) {
            rc = write_proc("/proc/sys/net/ipv4/conf/all/rp_filter",
                            old_accept_redirects);
            if(rc < 0) {
                perror("Couldn't write rp_filter knob.\n");
                return -1;
            }
        }

569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
        close(nl_command.sock);
        nl_command.sock = -1;

        nl_setup = 0;
        return 1;

    }
}

int
kernel_setup_socket(int setup)
{
    int rc;

    if(setup) {
584 585 586
        rc = netlink_socket(&nl_listen,
                RTMGRP_IPV6_ROUTE | RTMGRP_IPV4_ROUTE
              | RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR);
587
        if(rc < 0) {
588
            perror("netlink_socket(RTMGRP_ROUTE | RTMGRP_LINK | RTMGRP_IFADDR)");
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
            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;

    }
}

int
kernel_setup_interface(int setup, const char *ifname, int ifindex)
{
    return 1;
}

614 615 616
int
kernel_interface_operational(const char *ifname, int ifindex)
{
617 618
    struct ifreq req;
    int rc;
619
    int flags = link_detect ? (IFF_UP | IFF_RUNNING) : IFF_UP;
620 621 622 623 624 625

    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;
626
    return ((req.ifr_flags & flags) == flags);
627 628
}

629
int
630
kernel_interface_ipv4(const char *ifname, int ifindex, unsigned char *addr_r)
631 632
{
    struct ifreq req;
633
    int rc;
634 635 636 637

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
    req.ifr_addr.sa_family = AF_INET;
638 639
    rc = ioctl(dgram_socket, SIOCGIFADDR, &req);
    if(rc < 0)
640 641 642 643 644 645
        return -1;

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

646 647 648 649
int
kernel_interface_mtu(const char *ifname, int ifindex)
{
    struct ifreq req;
650
    int rc;
651 652 653

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
654 655
    rc = ioctl(dgram_socket, SIOCGIFMTU, &req);
    if(rc < 0)
656 657 658 659 660
        return -1;

    return req.ifr_mtu;
}

661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
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;
}

706 707 708 709 710 711 712
int
kernel_interface_wireless(const char *ifname, int ifindex)
{
#ifndef SIOCGIWNAME
#define SIOCGIWNAME 0x8B01
#endif
    struct ifreq req;
713
    int rc;
714

715 716 717 718 719
    if(isbridge(ifname, ifindex) != 0) {
        /* Give up. */
        return -1;
    }

720 721
    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
722
    rc = ioctl(dgram_socket, SIOCGIWNAME, &req);
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
    if(rc < 0) {
        if(errno == EOPNOTSUPP || errno == EINVAL)
            rc = 0;
        else {
            perror("ioctl(SIOCGIWNAME)");
            rc = -1;
        }
    } else {
        rc = 1;
    }
    return rc;
}

int
kernel_route(int operation, const unsigned char *dest, unsigned short plen,
             const unsigned char *gate, int ifindex, unsigned int metric,
             const unsigned char *newgate, int newifindex,
             unsigned int newmetric)
{

    union { char raw[1024]; struct nlmsghdr nh; } buf;
    struct rtmsg *rtm;
    struct rtattr *rta;
    int len = sizeof(buf.raw);
747 748
    int rc, ipv4;

749 750 751 752 753 754 755 756 757 758 759
    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) {
760
            int olderrno = errno;
761
            perror("kernel_route: netlink_socket()");
762
            errno = olderrno;
763 764 765 766
            return -1;
        }
    }

767 768 769 770 771 772 773 774 775 776 777 778 779
    /* Check that the protocol family is consistent. */
    if(plen >= 96 && v4mapped(dest)) {
        if(!v4mapped(gate)) {
            errno = EINVAL;
            return -1;
        }
    } else {
        if(v4mapped(gate)) {
            errno = EINVAL;
            return -1;
        }
    }

780
    ipv4 = v4mapped(gate);
781

782
    if(operation == ROUTE_MODIFY) {
783 784 785
        if(newmetric == metric && memcmp(newgate, gate, 16) == 0 &&
           newifindex == ifindex)
            return 0;
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
        /* It is better to add the new route before removing the old
           one, to avoid losing packets.  However, this only appears
           to work if the metrics are different. */
        if(newmetric != metric) {
            rc = kernel_route(ROUTE_ADD, dest, plen,
                              newgate, newifindex, newmetric,
                              NULL, 0, 0);
            if(rc < 0 && errno != EEXIST)
                return rc;
            rc = kernel_route(ROUTE_FLUSH, dest, plen,
                              gate, ifindex, metric,
                              NULL, 0, 0);
            if(rc < 0 && (errno == ENOENT || errno == ESRCH))
                rc = 1;
        } else {
            rc = kernel_route(ROUTE_FLUSH, dest, plen,
                              gate, ifindex, metric,
                              NULL, 0, 0);
            rc = kernel_route(ROUTE_ADD, dest, plen,
                              newgate, newifindex, newmetric,
                              NULL, 0, 0);
            if(rc < 0 && errno == EEXIST)
                rc = 1;
        }
810 811 812
        return rc;
    }

813
    kdebugf("kernel_route: %s %s/%d metric %d dev %d nexthop %s\n",
814 815 816 817 818
           operation == ROUTE_ADD ? "add" :
           operation == ROUTE_FLUSH ? "flush" : "???",
           format_address(dest), plen, metric, ifindex,
           format_address(gate));

819 820
    /* Unreachable default routes cause all sort of weird interactions;
       ignore them. */
821
    if(metric >= KERNEL_INFINITY && (plen == 0 || (ipv4 && plen == 96)))
822 823 824 825 826 827 828 829 830 831 832 833
        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);
834 835
    rtm->rtm_family = ipv4 ? AF_INET : AF_INET6;
    rtm->rtm_dst_len = ipv4 ? plen - 96 : plen;
836
    rtm->rtm_table = export_table;
837 838 839 840 841 842
    rtm->rtm_scope = RT_SCOPE_UNIVERSE;
    if(metric < KERNEL_INFINITY)
        rtm->rtm_type = RTN_UNICAST;
    else
        rtm->rtm_type = RTN_UNREACHABLE;
    rtm->rtm_protocol = RTPROT_BABEL;
843
    rtm->rtm_flags |= RTNH_F_ONLINK;
844 845 846

    rta = RTM_RTA(rtm);

847 848 849 850 851 852 853 854 855 856 857
    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));
    }
858 859 860 861 862 863 864 865 866 867 868 869

    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;

870 871 872 873 874 875 876 877 878 879 880
        if(ipv4) {
            rta = RTA_NEXT(rta, len);
            rta->rta_len = RTA_LENGTH(sizeof(struct in_addr));
            rta->rta_type = RTA_GATEWAY;
            memcpy(RTA_DATA(rta), gate + 12, sizeof(struct in_addr));
        } else {
            rta = RTA_NEXT(rta, len);
            rta->rta_len = RTA_LENGTH(sizeof(struct in6_addr));
            rta->rta_type = RTA_GATEWAY;
            memcpy(RTA_DATA(rta), gate, sizeof(struct in6_addr));
        }
881 882 883 884 885 886 887 888 889 890 891
    } 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)
{
892
    int table = rtm->rtm_table;
893 894 895 896 897 898
    struct rtattr *rta= RTM_RTA(rtm);;
    len -= NLMSG_ALIGN(sizeof(*rtm));

    memset(&route->prefix, 0, sizeof(struct in6_addr));
    memset(&route->gw, 0, sizeof(struct in6_addr));
    route->plen = rtm->rtm_dst_len;
899
    if(rtm->rtm_family == AF_INET) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
900
        const unsigned char zeroes[4] = {0, 0, 0, 0};
901 902 903 904
        v4tov6(route->prefix, zeroes);
        route->plen += 96;
    }

905
    route->metric = 0;
906
    route->ifindex = 0;
907
    route->proto = rtm->rtm_protocol;
908

909 910 911 912 913 914 915 916 917 918
#define COPY_ADDR(d, s) \
    do { \
        if(rtm->rtm_family == AF_INET6) \
            memcpy(d, s, 16); \
        else if(rtm->rtm_family == AF_INET) \
            v4tov6(d, s); \
        else \
            return -1; \
    } while(0)

919 920 921
    while(RTA_OK(rta, len)) {
        switch (rta->rta_type) {
        case RTA_DST:
922
            COPY_ADDR(route->prefix, RTA_DATA(rta));
923 924
            break;
        case RTA_GATEWAY:
925
            COPY_ADDR(route->gw, RTA_DATA(rta));
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
            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;
       case RTA_TABLE:
            table = *(int*)RTA_DATA(rta);
            break;
        default:
            break;
        }
        rta = RTA_NEXT(rta, len);
    }
943
#undef COPY_ADDR
944

945
    if(table != import_table)
946
        return -1;
947

948 949 950 951 952 953 954 955 956 957 958 959 960 961 962
    return 0;
}

static void
print_kernel_route(int add, int protocol, int type,
                   struct kernel_route *route)
{
    char ifname[IFNAMSIZ];
    char addr_prefix[INET6_ADDRSTRLEN];
    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)) {
963
        kdebugf("Couldn't format kernel route for printing.");
964 965 966
        return;
    }

967
    kdebugf("%s kernel route: dest: %s/%d gw: %s metric: %d if: %s "
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
           "(proto: %d, type: %d)",
           add == RTM_NEWROUTE ? "Add" : "Delete",
           addr_prefix, route->plen, addr_gw, route->metric, ifname,
           protocol, type);
}

static int
filter_kernel_routes(struct nlmsghdr *nh, void *data)
{
    int rc;

    struct kernel_route *current_route;
    struct kernel_route route;

    int maxroutes = 0;
    struct kernel_route *routes = NULL;
    int *found = NULL;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
985
    int len;
986 987 988 989 990

    struct rtmsg *rtm;

    if(data) {
        void **args = (void**)data;
991 992 993
        maxroutes = *(int*)args[0];
        routes = (struct kernel_route *)args[1];
        found = (int*)args[2];
994 995
    }

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
996
    len = nh->nlmsg_len;
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010

    if(data && *found >= maxroutes)
        return 0;

    if(nh->nlmsg_type != RTM_NEWROUTE &&
       (data || nh->nlmsg_type != RTM_DELROUTE))
        return 0;

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

    if(rtm->rtm_protocol == RTPROT_BOOT || rtm->rtm_protocol == RTPROT_BABEL)
        return 0;

1011
    if(rtm->rtm_src_len != 0)
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        return 0;

    if(data)
        current_route = &routes[*found];
    else
        current_route = &route;

    rc = parse_kernel_route_rta(rtm, len, current_route);
    if(rc < 0)
        return 0;

1023 1024
    if(martian_prefix(current_route->prefix, current_route->plen))
        return 0;
1025

1026 1027 1028 1029
    /* Ignore default unreachable routes; no idea where they come from. */
    if(current_route->plen == 0 && current_route->metric >= KERNEL_INFINITY)
        return 0;

1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    if(debug >= 2) {
        if(rc >= 0) {
            print_kernel_route(nh->nlmsg_type, rtm->rtm_protocol,
                               rtm->rtm_type, current_route);
        }
    }

    if (data) *found = (*found)+1;

    return 1;

}

/* This function should not return routes installed by us. */
int
1045
kernel_routes(struct kernel_route *routes, int maxroutes)
1046
{
1047
    int i, rc;
1048 1049
    int maxr = maxroutes;
    int found = 0;
1050
    void *data[3] = { &maxr, routes, &found };
1051
    int families[2] = { AF_INET6, AF_INET };
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
    struct rtgenmsg g;

    if(!nl_setup) {
        fprintf(stderr,"kernel_routes: netlink not initialized.\n");
        errno = EIO;
        return -1;
    }

    if(nl_command.sock < 0) {
        rc = netlink_socket(&nl_command, 0);
        if(rc < 0) {
            perror("kernel_routes: netlink_socket()");
            return -1;
        }
    }

1068 1069 1070 1071 1072 1073
    for(i = 0; i < 2; i++) {
        memset(&g, 0, sizeof(g));
        g.rtgen_family = families[i];
        rc = netlink_send_dump(RTM_GETROUTE, &g, sizeof(g));
        if(rc < 0)
            return -1;
1074

1075 1076
        rc = netlink_read(&nl_command, NULL, 1,
                          filter_kernel_routes, (void *)data);
1077

1078 1079 1080
        if(rc < 0)
            return -1;
    }
1081 1082 1083 1084

    return found;
}

1085
static char *
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
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)) {
        switch (rta->rta_type) {
        case IFLA_IFNAME:
            ifname = RTA_DATA(rta);
            break;
        default:
            break;
        }
        rta = RTA_NEXT(rta, len);
    }
    return ifname;
}

1106
static int
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
parse_addr_rta(struct ifaddrmsg *addr, int len, struct in6_addr *res)
{
    struct rtattr *rta;
    len -= NLMSG_ALIGN(sizeof(*addr));
    rta = IFA_RTA(addr);

    while (RTA_OK(rta, len)) {
        switch(rta->rta_type) {
            case IFA_LOCAL:
            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);
                        break;
                    default:
                        kdebugf("ifaddr: unexpected address family %d\n", addr->ifa_family);
                        return -1;
                        break;
                }
                break;
            default:
                break;
        }
        rta = RTA_NEXT(rta, len);
    }
    return 0;
}

1140
static int
1141 1142 1143 1144 1145 1146 1147
filter_link(struct nlmsghdr *nh, void *data)
{
    struct ifinfomsg *info;
    int len;
    int ifindex;
    char *ifname;
    unsigned int ifflags;
1148
    struct network *net;
1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161

    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;

    ifname = parse_ifname_rta(info, len);
1162 1163
    if(ifname == NULL)
        return 0;
1164 1165
    kdebugf("filter_interfaces: link change on if %s(%d): 0x%x\n",
            ifname, ifindex, (unsigned)ifflags);
1166 1167
    FOR_ALL_NETS(net) {
        if (strcmp(net->ifname, ifname) == 0)
1168 1169 1170 1171 1172
            return 1;
    }
    return 0;
}

1173
static int
1174 1175 1176
filter_addresses(struct nlmsghdr *nh, void *data)
{
    int rc;
1177 1178
    int maxroutes = 0;
    struct kernel_route *routes = NULL;
1179 1180 1181 1182 1183
    struct in6_addr addr;
    int *found = NULL;
    int len;
    struct ifaddrmsg *ifa;
    char ifname[IFNAMSIZ];
1184
    int ifindex = 0;
1185 1186 1187

    if (data) {
        void **args = (void **)data;
1188 1189
        maxroutes = *(int *)args[0];
        routes = (struct kernel_route*)args[1];
1190
        found = (int *)args[2];
1191
        ifindex = args[3] ? 0 : *(int*)args[3];
1192 1193 1194 1195
    }

    len = nh->nlmsg_len;

1196
    if (data && *found >= maxroutes)
1197 1198 1199 1200 1201 1202 1203 1204 1205
        return 0;

    if (nh->nlmsg_type != RTM_NEWADDR &&
            (data || nh->nlmsg_type != RTM_DELADDR))
        return 0;

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

1206
    rc = parse_addr_rta(ifa, len, &addr);
1207 1208 1209
    if (rc < 0)
        return 0;

1210
    if (IN6_IS_ADDR_LINKLOCAL(&addr))
1211 1212
        return 0;

1213 1214 1215
    if (ifindex && ifa->ifa_index != ifindex)
        return 0;

1216
    kdebugf("found address on interface %s(%d): %s\n",
1217
            if_indextoname(ifa->ifa_index, ifname), ifa->ifa_index,
1218 1219 1220 1221 1222 1223 1224
            format_address(addr.s6_addr));

    if (data) {
        struct kernel_route *route = &routes[*found];
        memcpy(route->prefix, addr.s6_addr, 16);
        route->plen = 128;
        route->metric = 0;
1225
        route->ifindex = ifa->ifa_index;
1226
        route->proto = RTPROT_BABEL_LOCAL;
1227 1228 1229 1230
        memset(route->gw, 0, 16);
        *found = (*found)+1;
    }

1231 1232 1233
    return 1;
}

1234
static int
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
filter_netlink(struct nlmsghdr *nh, void *data)
{
    int rc;
    int *changed = data;

    switch (nh->nlmsg_type) {
        case RTM_NEWROUTE:
        case RTM_DELROUTE:
            rc = filter_kernel_routes(nh, NULL);
            if (changed && rc > 0)
                *changed |= CHANGE_ROUTE;
            return rc;
        case RTM_NEWLINK:
        case RTM_DELLINK:
            rc = filter_link(nh, NULL);
            if (changed && rc > 0)
                *changed |= CHANGE_LINK;
            return rc;
        case RTM_NEWADDR:
        case RTM_DELADDR:
            rc = filter_addresses(nh, NULL);
            if (changed && rc > 0)
                *changed |= CHANGE_ADDR;
            return rc;
        default:
            kdebugf("filter_netlink: unexpected message type %d\n",
                    nh->nlmsg_type);
            break;
    }
    return 0;
}

int
1268 1269
kernel_addresses(char *ifname, int ifindex,
                 struct kernel_route *routes, int maxroutes)
1270
{
1271
    int maxr = maxroutes;
1272
    int found = 0;
1273
    void *data[] = { &maxr, routes, &found, &ifindex, NULL};
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
    struct rtgenmsg g;
    int rc;

    if (!nl_setup) {
        fprintf(stderr, "kernel_addresses: netlink not initialized.\n");
        errno = ENOSYS;
        return -1;
    }

    if (nl_command.sock < 0) {
        rc = netlink_socket(&nl_command, 0);
        if (rc < 0) {
1286
            int save = errno;
1287
            perror("kernel_addresses: netlink_socket()");
1288
            errno = save;
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
            return -1;
        }
    }

    memset(&g, 0, sizeof(g));
    g.rtgen_family = AF_UNSPEC;
    rc = netlink_send_dump(RTM_GETADDR, &g, sizeof(g));
    if (rc < 0)
        return -1;

    rc = netlink_read(&nl_command, NULL, 1, filter_addresses, (void*)data);

    if (rc < 0)
        return -1;

    return found;
}

1307
int
1308
kernel_callback(int (*fn)(int, void*), void *closure)
1309 1310
{
    int rc;
1311
    int changed = 0;
1312

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

1315 1316 1317 1318 1319 1320 1321
    if(nl_listen.sock < 0) {
        rc = kernel_setup_socket(1);
        if(rc < 0) {
            perror("kernel_callback: kernel_setup_socket(1)");
            return -1;
        }
    }
1322
    rc = netlink_read(&nl_listen, &nl_command, 0, filter_netlink, &changed);
1323 1324 1325 1326 1327 1328 1329

    if(rc < 0 && nl_listen.sock < 0)
      kernel_setup_socket(1);

    /* if netlink return 0 (found something interesting) */
    /* or -1 (i.e. IO error), we call... back ! */
    if(rc)
1330
        return fn(changed, closure);
1331 1332 1333

    return 0;
}