kernel_netlink.c 31.1 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 42

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>

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

47 48 49
#include "babel.h"
#include "kernel.h"
#include "util.h"
50
#include "network.h"
51

52 53
int export_table = -1, import_table = -1;

54
static int old_forwarding = -1;
55
static int old_ipv4_forwarding = -1;
56
static int old_accept_redirects = -1;
57
static int old_rp_filter = -1;
58

59 60
static int dgram_socket = -1;

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 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
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;
207
            rc = wait_for_fd(0, nl->sock, 100);
208 209 210 211 212 213 214 215 216
            if(rc <= 0) {
                if(rc == 0)
                    errno = EAGAIN;
            } else {
                len = recvmsg(nl->sock, &msg, 0);
            }
        }

        if(len < 0) {
217
            perror("netlink_read: recvmsg()");
218 219 220 221 222 223 224 225 226 227
            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) {
228
            kdebugf("netlink_read: message not sent by kernel.\n");
229 230 231
            return 2;
        }

232
        kdebugf("Netlink message: ");
233 234 235 236

        for(nh = (struct nlmsghdr *)buf;
            NLMSG_OK(nh, len);
            nh = NLMSG_NEXT(nh, len)) {
237
            kdebugf("%s", (nh->nlmsg_flags & NLM_F_MULTI) ? "[multi] " : "");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
238
            if(!answer)
239
                done = 1;
240
            if(nl_ignore && nh->nlmsg_pid == nl_ignore->sockaddr.nl_pid) {
241
                kdebugf("(ignore), ");
242 243 244
                continue;
            } else if(answer && (nh->nlmsg_pid != nl->sockaddr.nl_pid ||
                                 nh->nlmsg_seq != nl->seqno)) {
245
                kdebugf("(wrong seqno %d %d /pid %d %d), ",
246 247 248 249
                       nh->nlmsg_seq, nl->seqno,
                       nh->nlmsg_pid, nl->sockaddr.nl_pid);
                continue;
            } else if(nh->nlmsg_type == NLMSG_DONE) {
250
                kdebugf("(done)\n");
251 252 253 254 255
                done = 1;
                break;
            } else if(nh->nlmsg_type == NLMSG_ERROR) {
                struct nlmsgerr *err = (struct nlmsgerr *)NLMSG_DATA(nh);
                if(err->error == 0) {
256
                    kdebugf("(ACK)\n");
Julien Cristau's avatar
Julien Cristau committed
257
                    return 0;
258 259 260 261 262 263 264
                } else {
                    errno = -err->error;
                    perror("netlink_read");
                    errno = -err->error;
                    return -1;
                }
            } else if(fn) {
265
                kdebugf("(msg -> \"");
266
                err = fn(nh,data);
267
                kdebugf("\" %d), ", err);
268 269 270 271
                if(err < 0) return err;
                interesting = interesting || err;
                continue;
            }
272
            kdebugf(", ");
273
        }
274
        kdebugf("\n");
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 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

        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
392
kernel_setup(int setup)
393 394 395 396
{
    int rc;

    if(setup) {
397 398 399 400 401 402
        if(export_table < 0)
            export_table = RT_TABLE_MAIN;

        if(import_table < 0)
            import_table = RT_TABLE_MAIN;

403 404 405 406
        dgram_socket = socket(PF_INET, SOCK_DGRAM, 0);
        if(dgram_socket < 0)
            return -1;

407 408 409 410 411
        rc = netlink_socket(&nl_command, 0);
        if(rc < 0) {
            perror("netlink_socket(0)");
            return -1;
        }
412
        nl_setup = 1;
413 414 415 416 417 418 419 420 421 422 423 424 425

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

426 427 428 429 430 431
        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;
        }
432

433 434 435 436
        rc = write_proc("/proc/sys/net/ipv4/conf/all/forwarding", 1);
        if(rc < 0) {
            perror("Couldn't write IPv4 forwarding knob.");
            return -1;
437 438 439
        }


440 441 442 443 444 445 446 447 448 449 450 451
        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;
        }
452 453 454 455 456 457 458 459 460 461 462 463 464 465

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

466 467
        return 1;
    } else {
468 469 470
        close(dgram_socket);
        dgram_socket = -1;

471 472 473 474
        if(old_forwarding >= 0) {
            rc = write_proc("/proc/sys/net/ipv6/conf/all/forwarding",
                            old_forwarding);
            if(rc < 0) {
475
                perror("Couldn't write forwarding knob.\n");
476 477 478
                return -1;
            }
        }
479 480 481 482 483 484 485 486 487 488

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

489 490 491 492 493 494 495 496 497
        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;
            }
        }

498 499 500 501 502 503 504 505 506
        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;
            }
        }

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        close(nl_command.sock);
        nl_command.sock = -1;

        nl_setup = 0;
        return 1;

    }
}

int
kernel_setup_socket(int setup)
{
    int rc;

    if(setup) {
522 523 524
        rc = netlink_socket(&nl_listen,
                RTMGRP_IPV6_ROUTE | RTMGRP_IPV4_ROUTE
              | RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR);
525
        if(rc < 0) {
526
            perror("netlink_socket(RTMGRP_ROUTE | RTMGRP_LINK | RTMGRP_IFADDR)");
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
            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;
}

552 553 554
int
kernel_interface_operational(const char *ifname, int ifindex)
{
555 556
    struct ifreq req;
    int rc;
557
    int flags = link_detect ? (IFF_UP | IFF_RUNNING) : IFF_UP;
558 559 560 561 562 563 564

    memset(&req, 0, sizeof(req));
    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;
565
    return ((req.ifr_flags & flags) == flags);
566 567
}

568
int
569
kernel_interface_ipv4(const char *ifname, int ifindex, unsigned char *addr_r)
570 571
{
    struct ifreq req;
572
    int rc;
573 574 575 576

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
    req.ifr_addr.sa_family = AF_INET;
577 578
    rc = ioctl(dgram_socket, SIOCGIFADDR, &req);
    if(rc < 0)
579 580 581 582 583 584
        return -1;

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

585 586 587 588
int
kernel_interface_mtu(const char *ifname, int ifindex)
{
    struct ifreq req;
589
    int rc;
590 591 592

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
593 594
    rc = ioctl(dgram_socket, SIOCGIFMTU, &req);
    if(rc < 0)
595 596 597 598 599 600 601 602 603 604 605 606
        return -1;

    return req.ifr_mtu;
}

int
kernel_interface_wireless(const char *ifname, int ifindex)
{
#ifndef SIOCGIWNAME
#define SIOCGIWNAME 0x8B01
#endif
    struct ifreq req;
607
    int rc;
608 609 610

    memset(&req, 0, sizeof(req));
    strncpy(req.ifr_name, ifname, sizeof(req.ifr_name));
611
    rc = ioctl(dgram_socket, SIOCGIWNAME, &req);
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
    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);
636 637
    int rc, ipv4;

638 639 640 641 642 643 644 645 646 647 648
    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) {
649
            int olderrno = errno;
650
            perror("kernel_route: netlink_socket()");
651
            errno = olderrno;
652 653 654 655
            return -1;
        }
    }

656 657 658 659 660 661 662 663 664 665 666 667 668
    /* 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;
        }
    }

669
    ipv4 = v4mapped(gate);
670

671
    if(operation == ROUTE_MODIFY) {
672 673 674
        if(newmetric == metric && memcmp(newgate, gate, 16) == 0 &&
           newifindex == ifindex)
            return 0;
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
        /* 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;
        }
699 700 701
        return rc;
    }

702
    kdebugf("kernel_route: %s %s/%d metric %d dev %d nexthop %s\n",
703 704 705 706 707
           operation == ROUTE_ADD ? "add" :
           operation == ROUTE_FLUSH ? "flush" : "???",
           format_address(dest), plen, metric, ifindex,
           format_address(gate));

708 709
    /* Unreachable default routes cause all sort of weird interactions;
       ignore them. */
710
    if(metric >= KERNEL_INFINITY && (plen == 0 || (ipv4 && plen == 96)))
711 712 713 714 715 716 717 718 719 720 721 722
        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);
723 724
    rtm->rtm_family = ipv4 ? AF_INET : AF_INET6;
    rtm->rtm_dst_len = ipv4 ? plen - 96 : plen;
725
    rtm->rtm_table = export_table;
726 727 728 729 730 731
    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;
732
    rtm->rtm_flags |= RTNH_F_ONLINK;
733 734 735

    rta = RTM_RTA(rtm);

736 737 738 739 740 741 742 743 744 745 746
    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));
    }
747 748 749 750 751 752 753 754 755 756 757 758

    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;

759 760 761 762 763 764 765 766 767 768 769
        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));
        }
770 771 772 773 774 775 776 777 778 779 780
    } 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)
{
781
    int table = rtm->rtm_table;
782 783 784 785 786 787
    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;
788
    if(rtm->rtm_family == AF_INET) route->plen += 96;
789 790
    route->metric = KERNEL_INFINITY;
    route->ifindex = 0;
791
    route->proto = rtm->rtm_protocol;
792

793 794 795 796 797 798 799 800 801 802
#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)

803 804 805
    while(RTA_OK(rta, len)) {
        switch (rta->rta_type) {
        case RTA_DST:
806
            COPY_ADDR(route->prefix, RTA_DATA(rta));
807 808
            break;
        case RTA_GATEWAY:
809
            COPY_ADDR(route->gw, RTA_DATA(rta));
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
            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);
    }
827
#undef COPY_ADDR
828

829
    if(table != import_table)
830
        return -1;
831

832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
    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)) {
847
        kdebugf("Couldn't format kernel route for printing.");
848 849 850
        return;
    }

851
    kdebugf("%s kernel route: dest: %s/%d gw: %s metric: %d if: %s "
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
           "(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
869
    int len;
870 871 872 873 874

    struct rtmsg *rtm;

    if(data) {
        void **args = (void**)data;
875 876 877
        maxroutes = *(int*)args[0];
        routes = (struct kernel_route *)args[1];
        found = (int*)args[2];
878 879
    }

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
880
    len = nh->nlmsg_len;
881 882 883 884 885 886 887 888 889 890 891 892 893 894

    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;

895
    if(rtm->rtm_src_len != 0)
896 897 898 899 900 901 902 903 904 905 906
        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;

907 908
    if(martian_prefix(current_route->prefix, current_route->plen))
        return 0;
909

910 911 912 913
    /* Ignore default unreachable routes; no idea where they come from. */
    if(current_route->plen == 0 && current_route->metric >= KERNEL_INFINITY)
        return 0;

914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
    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
929
kernel_routes(struct kernel_route *routes, int maxroutes)
930
{
931
    int i, rc;
932 933
    int maxr = maxroutes;
    int found = 0;
934
    void *data[3] = { &maxr, routes, &found };
935
    int families[2] = { AF_INET6, AF_INET };
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
    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;
        }
    }

952 953 954 955 956 957
    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;
958

959 960
        rc = netlink_read(&nl_command, NULL, 1,
                          filter_kernel_routes, (void *)data);
961

962 963 964
        if(rc < 0)
            return -1;
    }
965 966 967 968

    return found;
}

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
char *
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;
}

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

int
filter_link(struct nlmsghdr *nh, void *data)
{
    struct ifinfomsg *info;
    int len;
    int ifindex;
    char *ifname;
    unsigned int ifflags;
    int i;

    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);
    kdebugf("filter_interfaces: link change on if %s(%d): %s\n",
            ifname, ifindex, parse_ifflags(ifflags));
    for (i = 0; i < numnets; i++) {
        if (!strcmp(nets[i].ifname, ifname)) {
            return 1;
        }
    }
    return 0;
}

int
filter_addresses(struct nlmsghdr *nh, void *data)
{
    int rc;
1060 1061
    int maxroutes = 0;
    struct kernel_route *routes = NULL;
1062 1063 1064 1065 1066 1067 1068 1069
    struct in6_addr addr;
    int *found = NULL;
    int len;
    struct ifaddrmsg *ifa;
    char ifname[IFNAMSIZ];

    if (data) {
        void **args = (void **)data;
1070 1071
        maxroutes = *(int *)args[0];
        routes = (struct kernel_route*)args[1];
1072 1073 1074 1075 1076
        found = (int *)args[2];
    }

    len = nh->nlmsg_len;

1077
    if (data && *found >= maxroutes)
1078 1079 1080 1081 1082 1083 1084 1085 1086
        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);

1087
    rc = parse_addr_rta(ifa, len, &addr);
1088 1089 1090
    if (rc < 0)
        return 0;

1091
    if (IN6_IS_ADDR_LINKLOCAL(&addr))
1092 1093 1094
        return 0;

    kdebugf("found address on interface %s(%d): %s\n",
1095
            if_indextoname(ifa->ifa_index, ifname), ifa->ifa_index,
1096 1097 1098 1099 1100 1101 1102
            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;
1103
        route->ifindex = ifa->ifa_index;
1104
        route->proto = RTPROT_BABEL_LOCAL;
1105 1106 1107 1108
        memset(route->gw, 0, 16);
        *found = (*found)+1;
    }

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 1140 1141 1142 1143 1144 1145
    return 1;
}

int
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
1146
kernel_addresses(struct kernel_route *routes, int maxroutes)
1147
{
1148
    int maxr = maxroutes;
1149
    int found = 0;
1150
    void *data[] = { &maxr, routes, &found, NULL};
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
    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) {
            perror("kernel_addresses: netlink_socket()");
            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;
}

1182
int
1183
kernel_callback(int (*fn)(int, void*), void *closure)
1184 1185
{
    int rc;
1186
    int changed;
1187

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

1190 1191 1192 1193 1194 1195 1196
    if(nl_listen.sock < 0) {
        rc = kernel_setup_socket(1);
        if(rc < 0) {
            perror("kernel_callback: kernel_setup_socket(1)");
            return -1;
        }
    }
1197
    rc = netlink_read(&nl_listen, &nl_command, 0, filter_netlink, &changed);
1198 1199 1200 1201 1202 1203 1204

    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)
1205
        return fn(changed, closure);
1206 1207 1208

    return 0;
}