nwfilter_dhcpsnoop.c 61.9 KB
Newer Older
S
Stefan Berger 已提交
1 2 3 4
/*
 * nwfilter_dhcpsnoop.c: support for DHCP snooping used by a VM
 *                       on an interface
 *
5
 * Copyright (C) 2012 Red Hat, Inc.
S
Stefan Berger 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 * Copyright (C) 2011,2012 IBM Corp.
 *
 * Authors:
 *    David L Stevens <dlstevens@us.ibm.com>
 *    Stefan Berger <stefanb@linux.vnet.ibm.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
23
 * License along with this library.  If not, see
O
Osier Yang 已提交
24
 * <http://www.gnu.org/licenses/>.
S
Stefan Berger 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 *
 * Based in part on work by Stefan Berger <stefanb@us.ibm.com>
 */

/*
 * Note about testing:
 *   On the host run in a shell:
 *      while :; do kill -SIGHUP `pidof libvirtd` ; echo "HUP $RANDOM"; sleep 20; done
 *
 *   Inside a couple of VMs that for example use the 'clean-traffic' filter:
 *      while :; do kill -SIGTERM `pidof dhclient`; dhclient eth0 ; ifconfig eth0; done
 *
 *   On the host check the lease file and that it's periodically shortened:
 *      cat /var/run/libvirt/network/nwfilter.leases ; date +%s
 *
 *   On the host also check that the ebtables rules 'look' ok:
 *      ebtables -t nat -L
 */
#include <config.h>

#ifdef HAVE_LIBPCAP
# include <pcap.h>
#endif

#include <fcntl.h>
D
Dwight Engen 已提交
50
#include <poll.h>
S
Stefan Berger 已提交
51 52 53 54 55 56

#include <arpa/inet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
#include <net/if.h>

57
#include "viralloc.h"
58
#include "virlog.h"
S
Stefan Berger 已提交
59
#include "datatypes.h"
60
#include "virerror.h"
S
Stefan Berger 已提交
61 62 63
#include "conf/domain_conf.h"
#include "nwfilter_gentech_driver.h"
#include "nwfilter_dhcpsnoop.h"
64
#include "nwfilter_ipaddrmap.h"
S
Stefan Berger 已提交
65 66 67
#include "virnetdev.h"
#include "virfile.h"
#include "viratomic.h"
68
#include "virthreadpool.h"
S
Stefan Berger 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81
#include "configmake.h"
#include "virtime.h"

#define VIR_FROM_THIS VIR_FROM_NWFILTER

#ifdef HAVE_LIBPCAP

# define LEASEFILE LOCALSTATEDIR "/run/libvirt/network/nwfilter.leases"
# define TMPLEASEFILE LOCALSTATEDIR "/run/libvirt/network/nwfilter.ltmp"

struct virNWFilterSnoopState {
    /* lease file */
    int                  leaseFD;
82 83 84
    int                  nLeases; /* number of active leases */
    int                  wLeases; /* number of written leases */
    int                  nThreads; /* number of running threads */
S
Stefan Berger 已提交
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
    /* thread management */
    virHashTablePtr      snoopReqs;
    virHashTablePtr      ifnameToKey;
    virMutex             snoopLock;  /* protects SnoopReqs and IfNameToKey */
    virHashTablePtr      active;
    virMutex             activeLock; /* protects Active */
};

# define virNWFilterSnoopLock() \
    do { \
        virMutexLock(&virNWFilterSnoopState.snoopLock); \
    } while (0)
# define virNWFilterSnoopUnlock() \
    do { \
        virMutexUnlock(&virNWFilterSnoopState.snoopLock); \
    } while (0)
# define virNWFilterSnoopActiveLock() \
    do { \
        virMutexLock(&virNWFilterSnoopState.activeLock); \
    } while (0)
# define virNWFilterSnoopActiveUnlock() \
    do { \
        virMutexUnlock(&virNWFilterSnoopState.activeLock); \
    } while (0)

# define VIR_IFKEY_LEN   ((VIR_UUID_STRING_BUFLEN) + (VIR_MAC_STRING_BUFLEN))

typedef struct _virNWFilterSnoopReq virNWFilterSnoopReq;
typedef virNWFilterSnoopReq *virNWFilterSnoopReqPtr;

typedef struct _virNWFilterSnoopIPLease virNWFilterSnoopIPLease;
typedef virNWFilterSnoopIPLease *virNWFilterSnoopIPLeasePtr;

typedef enum {
    THREAD_STATUS_NONE,
    THREAD_STATUS_OK,
    THREAD_STATUS_FAIL,
} virNWFilterSnoopThreadStatus;

struct _virNWFilterSnoopReq {
    /*
     * reference counter: while the req is on the
     * publicSnoopReqs hash, the refctr may only
     * be modified with the SnoopLock held
     */
130
    int                                  refctr;
S
Stefan Berger 已提交
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

    virNWFilterTechDriverPtr             techdriver;
    char                                *ifname;
    int                                  ifindex;
    const char                          *linkdev;
    enum virDomainNetType                nettype;
    char                                 ifkey[VIR_IFKEY_LEN];
    virMacAddr                           macaddr;
    const char                          *filtername;
    virNWFilterHashTablePtr              vars;
    virNWFilterDriverStatePtr            driver;
    /* start and end of lease list, ordered by lease time */
    virNWFilterSnoopIPLeasePtr           start;
    virNWFilterSnoopIPLeasePtr           end;
    char                                *threadkey;

    virNWFilterSnoopThreadStatus         threadStatus;
    virCond                              threadStatusCond;

    int                                  jobCompletionStatus;
    /* the number of submitted jobs in the worker's queue */
    /*
     * protect those members that can change while the
     * req is on the public SnoopReq hash and
     * at least one reference is held:
     * - ifname
     * - threadkey
     * - start
     * - end
     * - a lease while it is on the list
     * - threadStatus
     * (for refctr, see above)
     */
    virMutex                             lock;
};

/*
 * Note about lock-order:
 * 1st: virNWFilterSnoopLock()
 * 2nd: virNWFilterSnoopReqLock(req)
 *
 * Rationale: Former protects the SnoopReqs hash, latter its contents
 */

struct _virNWFilterSnoopIPLease {
    virSocketAddr              ipAddress;
    virSocketAddr              ipServer;
    virNWFilterSnoopReqPtr     snoopReq;
    unsigned int               timeout;
    /* timer list */
    virNWFilterSnoopIPLeasePtr prev;
    virNWFilterSnoopIPLeasePtr next;
};

typedef struct _virNWFilterSnoopEthHdr virNWFilterSnoopEthHdr;
typedef virNWFilterSnoopEthHdr *virNWFilterSnoopEthHdrPtr;

struct _virNWFilterSnoopEthHdr {
    virMacAddr eh_dst;
    virMacAddr eh_src;
    uint16_t eh_type;
    uint8_t eh_data[];
} ATTRIBUTE_PACKED;

typedef struct _virNWFilterSnoopDHCPHdr virNWFilterSnoopDHCPHdr;
typedef virNWFilterSnoopDHCPHdr *virNWFilterSnoopDHCPHdrPtr;

struct _virNWFilterSnoopDHCPHdr {
    uint8_t   d_op;
    uint8_t   d_htype;
    uint8_t   d_hlen;
    uint8_t   d_hops;
    uint32_t  d_xid;
    uint16_t  d_secs;
    uint16_t  d_flags;
    uint32_t  d_ciaddr;
    uint32_t  d_yiaddr;
    uint32_t  d_siaddr;
    uint32_t  d_giaddr;
    uint8_t   d_chaddr[16];
    char      d_sname[64];
    char      d_file[128];
    uint8_t   d_opts[];
} ATTRIBUTE_PACKED;

/* DHCP options */

# define DHCPO_PAD         0
# define DHCPO_LEASE      51     /* lease time in secs */
# define DHCPO_MTYPE      53     /* message type */
# define DHCPO_END       255     /* end of options */

/* DHCP message types */
# define DHCPDECLINE     4
# define DHCPACK         5
# define DHCPRELEASE     7

# define MIN_VALID_DHCP_PKT_SIZE \
    (offsetof(virNWFilterSnoopEthHdr, eh_data) + \
     sizeof(struct udphdr) + \
     offsetof(virNWFilterSnoopDHCPHdr, d_opts))

# define PCAP_PBUFSIZE              576 /* >= IP/TCP/DHCP headers */
# define PCAP_READ_MAXERRS          25 /* retries on failing device */
# define PCAP_FLOOD_TIMEOUT_MS      10 /* ms */

typedef struct _virNWFilterDHCPDecodeJob virNWFilterDHCPDecodeJob;
typedef virNWFilterDHCPDecodeJob *virNWFilterDHCPDecodeJobPtr;

struct _virNWFilterDHCPDecodeJob {
    unsigned char packet[PCAP_PBUFSIZE];
    int caplen;
    bool fromVM;
244
    int *qCtr;
S
Stefan Berger 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
};

# define DHCP_PKT_RATE          10 /* pkts/sec */
# define DHCP_PKT_BURST         50 /* pkts/sec */
# define DHCP_BURST_INTERVAL_S  10 /* sec */

# define PCAP_BUFFERSIZE        (DHCP_PKT_BURST * PCAP_PBUFSIZE / 2)

# define MAX_QUEUED_JOBS        (DHCP_PKT_BURST + 2 * DHCP_PKT_RATE)

typedef struct _virNWFilterSnoopRateLimitConf virNWFilterSnoopRateLimitConf;
typedef virNWFilterSnoopRateLimitConf *virNWFilterSnoopRateLimitConfPtr;

struct _virNWFilterSnoopRateLimitConf {
    time_t prev;
    unsigned int pkt_ctr;
    time_t burst;
    const unsigned int rate;
    const unsigned int burstRate;
    const unsigned int burstInterval;
};

typedef struct _virNWFilterSnoopPcapConf virNWFilterSnoopPcapConf;
typedef virNWFilterSnoopPcapConf *virNWFilterSnoopPcapConfPtr;

struct _virNWFilterSnoopPcapConf {
    pcap_t *handle;
    const pcap_direction_t dir;
    const char *filter;
    virNWFilterSnoopRateLimitConf rateLimit; /* indep. rate limiters */
275
    int qCtr; /* number of jobs in the worker's queue */
S
Stefan Berger 已提交
276 277 278 279 280 281 282
    const unsigned int maxQSize;
    unsigned long long penaltyTimeoutAbs;
};

/* local function prototypes */
static int virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
                                       virSocketAddrPtr ipaddr,
283 284
                                       bool update_leasefile,
                                       bool instantiate);
S
Stefan Berger 已提交
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 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 454 455 456 457 458 459 460 461 462 463 464 465 466

static void virNWFilterSnoopReqLock(virNWFilterSnoopReqPtr req);
static void virNWFilterSnoopReqUnlock(virNWFilterSnoopReqPtr req);

static void virNWFilterSnoopLeaseFileLoad(void);
static void virNWFilterSnoopLeaseFileSave(virNWFilterSnoopIPLeasePtr ipl);

/* local variables */
static struct virNWFilterSnoopState virNWFilterSnoopState = {
    .leaseFD = -1,
};

static const unsigned char dhcp_magic[4] = { 99, 130, 83, 99 };


static char *
virNWFilterSnoopActivate(virNWFilterSnoopReqPtr req)
{
    char *key;

    if (virAsprintf(&key, "%p-%d", req, req->ifindex) < 0) {
        virReportOOMError();
        return NULL;
    }

    virNWFilterSnoopActiveLock();

    if (virHashAddEntry(virNWFilterSnoopState.active, key, (void *)0x1) < 0) {
        VIR_FREE(key);
    }

    virNWFilterSnoopActiveUnlock();

    return key;
}

static void
virNWFilterSnoopCancel(char **threadKey)
{
    if (*threadKey == NULL)
        return;

    virNWFilterSnoopActiveLock();

    ignore_value(virHashRemoveEntry(virNWFilterSnoopState.active, *threadKey));
    VIR_FREE(*threadKey);

    virNWFilterSnoopActiveUnlock();
}

static bool
virNWFilterSnoopIsActive(char *threadKey)
{
    void *entry;

    if (threadKey == NULL)
        return 0;

    virNWFilterSnoopActiveLock();

    entry = virHashLookup(virNWFilterSnoopState.active, threadKey);

    virNWFilterSnoopActiveUnlock();

    return entry != NULL;
}

/*
 * virNWFilterSnoopListAdd - add an IP lease to a list
 */
static void
virNWFilterSnoopListAdd(virNWFilterSnoopIPLeasePtr plnew,
                        virNWFilterSnoopIPLeasePtr *start,
                        virNWFilterSnoopIPLeasePtr *end)
{
    virNWFilterSnoopIPLeasePtr pl;

    plnew->next = plnew->prev = NULL;

    if (!*start) {
        *start = *end = plnew;
        return;
    }

    for (pl = *end; pl && plnew->timeout < pl->timeout;
         pl = pl->prev)
        /* empty */ ;

    if (!pl) {
        plnew->next = *start;
        *start = plnew;
    } else {
        plnew->next = pl->next;
        pl->next = plnew;
    }

    plnew->prev = pl;

    if (plnew->next)
        plnew->next->prev = plnew;
    else
        *end = plnew;
}

/*
 * virNWFilterSnoopListDel - remove an IP lease from a list
 */
static void
virNWFilterSnoopListDel(virNWFilterSnoopIPLeasePtr ipl,
                        virNWFilterSnoopIPLeasePtr *start,
                        virNWFilterSnoopIPLeasePtr *end)
{
    if (ipl->prev)
        ipl->prev->next = ipl->next;
    else
        *start = ipl->next;

    if (ipl->next)
        ipl->next->prev = ipl->prev;
    else
        *end = ipl->prev;

    ipl->next = ipl->prev = NULL;
}

/*
 * virNWFilterSnoopLeaseTimerAdd - add an IP lease to the timer list
 */
static void
virNWFilterSnoopIPLeaseTimerAdd(virNWFilterSnoopIPLeasePtr plnew)
{
    virNWFilterSnoopReqPtr req = plnew->snoopReq;

    /* protect req->start / req->end */
    virNWFilterSnoopReqLock(req);

    virNWFilterSnoopListAdd(plnew, &req->start, &req->end);

    virNWFilterSnoopReqUnlock(req);
}

/*
 * virNWFilterSnoopLeaseTimerDel - remove an IP lease from the timer list
 */
static void
virNWFilterSnoopIPLeaseTimerDel(virNWFilterSnoopIPLeasePtr ipl)
{
    virNWFilterSnoopReqPtr req = ipl->snoopReq;

    /* protect req->start / req->end */
    virNWFilterSnoopReqLock(req);

    virNWFilterSnoopListDel(ipl, &req->start, &req->end);

    virNWFilterSnoopReqUnlock(req);

    ipl->timeout = 0;
}

/*
 * virNWFilterSnoopInstallRule - install rule for a lease
 *
 * @instantiate: when calling this function in a loop, indicate
 *               the last call with 'true' here so that the
 *               rules all get instantiated
 *               Always calling this with 'true' is fine, but less
 *               efficient.
 */
static int
virNWFilterSnoopIPLeaseInstallRule(virNWFilterSnoopIPLeasePtr ipl,
                                   bool instantiate)
{
    char *ipaddr;
    int rc = -1;
    virNWFilterSnoopReqPtr req;

    ipaddr = virSocketAddrFormat(&ipl->ipAddress);
    if (!ipaddr)
        return -1;

    req = ipl->snoopReq;

467
    /* protect req->ifname */
S
Stefan Berger 已提交
468 469
    virNWFilterSnoopReqLock(req);

470
    if (virNWFilterIPAddrMapAddIPAddr(req->ifname, ipaddr) < 0)
S
Stefan Berger 已提交
471
        goto exit_snooprequnlock;
472 473 474

    /* ipaddr now belongs to the map */
    ipaddr = NULL;
S
Stefan Berger 已提交
475 476 477 478 479 480 481 482 483 484 485 486 487 488

    if (!instantiate) {
        rc = 0;
        goto exit_snooprequnlock;
    }

    /* instantiate the filters */

    if (req->ifname)
        rc = virNWFilterInstantiateFilterLate(NULL,
                                              req->ifname,
                                              req->ifindex,
                                              req->linkdev,
                                              req->nettype,
489
                                              &req->macaddr,
S
Stefan Berger 已提交
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 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
                                              req->filtername,
                                              req->vars,
                                              req->driver);

exit_snooprequnlock:
    virNWFilterSnoopReqUnlock(req);

    VIR_FREE(ipaddr);

    return rc;
}

/*
 * virNWFilterSnoopIPLeaseUpdate - update the timeout on an IP lease
 */
static void
virNWFilterSnoopIPLeaseUpdate(virNWFilterSnoopIPLeasePtr ipl, time_t timeout)
{
    if (timeout < ipl->timeout)
        return;  /* no take-backs */

    virNWFilterSnoopIPLeaseTimerDel(ipl);
    ipl->timeout = timeout;
    virNWFilterSnoopIPLeaseTimerAdd(ipl);
}

/*
 * virNWFilterSnoopGetByIP - lookup IP lease by IP address
 */
static virNWFilterSnoopIPLeasePtr
virNWFilterSnoopIPLeaseGetByIP(virNWFilterSnoopIPLeasePtr start,
                               virSocketAddrPtr ipaddr)
{
    virNWFilterSnoopIPLeasePtr pl;

    for (pl = start;
         pl && !virSocketAddrEqual(&pl->ipAddress, ipaddr);
         pl = pl->next)
        /* empty */ ;
    return pl;
}

/*
 * virNWFilterSnoopReqLeaseTimerRun - run the IP lease timeout list
 */
static unsigned int
virNWFilterSnoopReqLeaseTimerRun(virNWFilterSnoopReqPtr req)
{
    time_t now = time(0);
539
    bool is_last = false;
S
Stefan Berger 已提交
540 541 542 543

    /* protect req->start */
    virNWFilterSnoopReqLock(req);

544 545 546 547 548 549 550
    while (req->start && req->start->timeout <= now) {
        if (req->start->next == NULL ||
            req->start->next->timeout > now)
            is_last = true;
        virNWFilterSnoopReqLeaseDel(req, &req->start->ipAddress, true,
                                    is_last);
    }
S
Stefan Berger 已提交
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575

    virNWFilterSnoopReqUnlock(req);

    return 0;
}

/*
 * Get a reference to the given Snoop request
 */
static void
virNWFilterSnoopReqGet(virNWFilterSnoopReqPtr req)
{
    virAtomicIntInc(&req->refctr);
}

/*
 * Create a new Snoop request. Initialize it with the given
 * interface key. The caller must release the request with a call
 * to virNWFilerSnoopReqPut(req).
 */
static virNWFilterSnoopReqPtr
virNWFilterSnoopReqNew(const char *ifkey)
{
    virNWFilterSnoopReqPtr req;

E
Eric Blake 已提交
576
    if (ifkey == NULL || strlen(ifkey) != VIR_IFKEY_LEN - 1) {
577 578 579 580
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("virNWFilterSnoopReqNew called with invalid "
                         "key \"%s\" (%zu)"),
                       ifkey ? ifkey : "",
581
                       ifkey ? strlen(ifkey) : 0);
S
Stefan Berger 已提交
582 583 584 585 586 587 588 589 590 591
        return NULL;
    }

    if (VIR_ALLOC(req) < 0) {
        virReportOOMError();
        return NULL;
    }

    req->threadStatus = THREAD_STATUS_NONE;

592
    if (virStrcpyStatic(req->ifkey, ifkey) == NULL ||
S
Stefan Berger 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
        virMutexInitRecursive(&req->lock) < 0)
        goto err_free_req;

    if (virCondInit(&req->threadStatusCond) < 0)
        goto err_destroy_mutex;

    virNWFilterSnoopReqGet(req);

    return req;

err_destroy_mutex:
    virMutexDestroy(&req->lock);

err_free_req:
    VIR_FREE(req);

    return NULL;
}

/*
 * Free a snoop request unless it is still referenced.
 * All its associated leases are also freed.
 * The lease file is NOT rewritten.
 */
static void
virNWFilterSnoopReqFree(virNWFilterSnoopReqPtr req)
{
    virNWFilterSnoopIPLeasePtr ipl;

    if (!req)
        return;

625
    if (virAtomicIntGet(&req->refctr) != 0)
S
Stefan Berger 已提交
626 627 628 629
        return;

    /* free all leases */
    for (ipl = req->start; ipl; ipl = req->start)
630
        virNWFilterSnoopReqLeaseDel(req, &ipl->ipAddress, false, false);
S
Stefan Berger 已提交
631 632 633 634 635 636 637 638

    /* free all req data */
    VIR_FREE(req->ifname);
    VIR_FREE(req->linkdev);
    VIR_FREE(req->filtername);
    virNWFilterHashTableFree(req->vars);

    virMutexDestroy(&req->lock);
639
    virCondDestroy(&req->threadStatusCond);
S
Stefan Berger 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 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 706 707 708 709 710 711 712 713 714 715 716 717

    VIR_FREE(req);
}

/*
 * Lock a Snoop request 'req'
 */
static void
virNWFilterSnoopReqLock(virNWFilterSnoopReqPtr req)
{
    virMutexLock(&req->lock);
}

/*
 * Unlock a Snoop request 'req'
 */
static void
virNWFilterSnoopReqUnlock(virNWFilterSnoopReqPtr req)
{
    virMutexUnlock(&req->lock);
}

/*
 * virNWFilterSnoopReqRelease - hash table free function to kill a request
 */
static void
virNWFilterSnoopReqRelease(void *req0, const void *name ATTRIBUTE_UNUSED)
{
    virNWFilterSnoopReqPtr req = req0;

    if (!req)
        return;

    /* protect req->threadkey */
    virNWFilterSnoopReqLock(req);

    if (req->threadkey)
        virNWFilterSnoopCancel(&req->threadkey);

    virNWFilterSnoopReqUnlock(req);

    virNWFilterSnoopReqFree(req);
}

/*
 * virNWFilterSnoopReqGetByIFKey
 *
 * Get a Snoop request given an interface key; caller must release
 * the Snoop request with a call to virNWFilterSnoopReqPut()
 */
static virNWFilterSnoopReqPtr
virNWFilterSnoopReqGetByIFKey(const char *ifkey)
{
    virNWFilterSnoopReqPtr req;

    virNWFilterSnoopLock();

    req = virHashLookup(virNWFilterSnoopState.snoopReqs, ifkey);
    if (req)
        virNWFilterSnoopReqGet(req);

    virNWFilterSnoopUnlock();

    return req;
}

/*
 * Drop the reference to the Snoop request. Don't use the req
 * after this call.
 */
static void
virNWFilterSnoopReqPut(virNWFilterSnoopReqPtr req)
{
    if (!req)
        return;

    virNWFilterSnoopLock();

718
    if (virAtomicIntDecAndTest(&req->refctr)) {
S
Stefan Berger 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 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 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
        /*
         * delete the request:
         * - if we don't find req on the global list anymore
         *   (this happens during SIGHUP)
         * we would keep the request:
         * - if we still have a valid lease, keep the req for restarts
         */
        if (virHashLookup(virNWFilterSnoopState.snoopReqs, req->ifkey) != req) {
            virNWFilterSnoopReqRelease(req, NULL);
        } else if (!req->start || req->start->timeout < time(0)) {
            ignore_value(virHashRemoveEntry(virNWFilterSnoopState.snoopReqs,
                                            req->ifkey));
        }
    }

    virNWFilterSnoopUnlock();
}

/*
 * virNWFilterSnoopReqLeaseAdd - create or update an IP lease
 */
static int
virNWFilterSnoopReqLeaseAdd(virNWFilterSnoopReqPtr req,
                            virNWFilterSnoopIPLeasePtr plnew,
                            bool update_leasefile)
{
    virNWFilterSnoopIPLeasePtr pl;

    plnew->snoopReq = req;

    /* protect req->start and the lease */
    virNWFilterSnoopReqLock(req);

    pl = virNWFilterSnoopIPLeaseGetByIP(req->start, &plnew->ipAddress);

    if (pl) {
        virNWFilterSnoopIPLeaseUpdate(pl, plnew->timeout);

        virNWFilterSnoopReqUnlock(req);

        goto exit;
    }

    virNWFilterSnoopReqUnlock(req);

    if (VIR_ALLOC(pl) < 0) {
        virReportOOMError();
        return -1;
    }
    *pl = *plnew;

    /* protect req->threadkey */
    virNWFilterSnoopReqLock(req);

    if (req->threadkey && virNWFilterSnoopIPLeaseInstallRule(pl, true) < 0) {
        virNWFilterSnoopReqUnlock(req);
        VIR_FREE(pl);
        return -1;
    }

    virNWFilterSnoopReqUnlock(req);

    /* put the lease on the req's list */
    virNWFilterSnoopIPLeaseTimerAdd(pl);

    virAtomicIntInc(&virNWFilterSnoopState.nLeases);

exit:
    if (update_leasefile)
        virNWFilterSnoopLeaseFileSave(pl);

    return 0;
}

/*
 * Restore a Snoop request -- walk its list of leases
 * and re-build the filtering rules with them
 */
static int
virNWFilterSnoopReqRestore(virNWFilterSnoopReqPtr req)
{
    int ret = 0;
    virNWFilterSnoopIPLeasePtr ipl;

    /* protect req->start */
    virNWFilterSnoopReqLock(req);

    for (ipl = req->start; ipl; ipl = ipl->next) {
        /* instantiate the rules at the last lease */
        bool is_last = (ipl->next == NULL);
        if (virNWFilterSnoopIPLeaseInstallRule(ipl, is_last) < 0) {
            ret = -1;
            break;
        }
    }

    virNWFilterSnoopReqUnlock(req);

    return ret;
}

/*
 * virNWFilterSnoopReqLeaseDel - delete an IP lease
 *
 * @update_leasefile: set to 'true' if the lease expired or the lease
 *                    was returned to the DHCP server and therefore
 *                    this has to be noted in the lease file.
 *                    set to 'false' for any other reason such as for
 *                    example when calling only to free the lease's
 *                    memory or when calling this function while reading
 *                    leases from the file.
 *
831 832 833 834 835 836
 * @instantiate: when calling this function in a loop, indicate
 *               the last call with 'true' here so that the
 *               rules all get instantiated
 *               Always calling this with 'true' is fine, but less
 *               efficient.
 *
S
Stefan Berger 已提交
837 838 839 840
 * Returns 0 on success, -1 if the instantiation of the rules failed
 */
static int
virNWFilterSnoopReqLeaseDel(virNWFilterSnoopReqPtr req,
841 842
                            virSocketAddrPtr ipaddr, bool update_leasefile,
                            bool instantiate)
S
Stefan Berger 已提交
843 844 845
{
    int ret = 0;
    virNWFilterSnoopIPLeasePtr ipl;
846 847
    char *ipstr = NULL;
    int ipAddrLeft;
S
Stefan Berger 已提交
848

849
    /* protect req->start, req->ifname and the lease */
S
Stefan Berger 已提交
850 851 852 853 854 855
    virNWFilterSnoopReqLock(req);

    ipl = virNWFilterSnoopIPLeaseGetByIP(req->start, ipaddr);
    if (ipl == NULL)
        goto lease_not_found;

856 857 858 859 860 861
    ipstr = virSocketAddrFormat(&ipl->ipAddress);
    if (!ipstr) {
        ret = -1;
        goto lease_not_found;
    }

S
Stefan Berger 已提交
862
    virNWFilterSnoopIPLeaseTimerDel(ipl);
863
    /* lease is off the list now */
S
Stefan Berger 已提交
864

865 866 867 868 869 870 871 872 873 874 875 876 877 878
    if (update_leasefile)
        virNWFilterSnoopLeaseFileSave(ipl);

    ipAddrLeft = virNWFilterIPAddrMapDelIPAddr(req->ifname, ipstr);

    if (!req->threadkey || !instantiate)
        goto skip_instantiate;

    if (ipAddrLeft) {
        ret = virNWFilterInstantiateFilterLate(NULL,
                                               req->ifname,
                                               req->ifindex,
                                               req->linkdev,
                                               req->nettype,
879
                                               &req->macaddr,
880 881 882 883
                                               req->filtername,
                                               req->vars,
                                               req->driver);
    } else {
S
Stefan Berger 已提交
884 885 886 887
        const virNWFilterVarValuePtr dhcpsrvrs =
            virHashLookup(req->vars->hashTable, NWFILTER_VARNAME_DHCPSERVER);

        if (req->techdriver &&
888
            req->techdriver->applyDHCPOnlyRules(req->ifname, &req->macaddr,
S
Stefan Berger 已提交
889
                                                dhcpsrvrs, false) < 0) {
890
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
891
                           _("virNWFilterSnoopListDel failed"));
S
Stefan Berger 已提交
892 893 894 895
            ret = -1;
        }

    }
896 897

skip_instantiate:
S
Stefan Berger 已提交
898 899
    VIR_FREE(ipl);

900
    virAtomicIntDecAndTest(&virNWFilterSnoopState.nLeases);
S
Stefan Berger 已提交
901 902

lease_not_found:
903 904
    VIR_FREE(ipstr);

S
Stefan Berger 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 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
    virNWFilterSnoopReqUnlock(req);

    return ret;
}

static int
virNWFilterSnoopDHCPGetOpt(virNWFilterSnoopDHCPHdrPtr pd, int len,
                           uint8_t *pmtype, uint32_t *pleasetime)
{
    int oind, olen;
    int oend;
    uint32_t nwint;

    olen = len - sizeof(*pd);
    oind = 0;

    if (olen < 4)               /* bad magic */
        return -1;

    if (memcmp(dhcp_magic, pd->d_opts, sizeof(dhcp_magic)) != 0)
        return -1;              /* bad magic */

    oind += sizeof(dhcp_magic);

    oend = 0;

    *pmtype = 0;
    *pleasetime = 0;

    while (oind < olen) {
        switch (pd->d_opts[oind]) {
        case DHCPO_LEASE:
            if (olen - oind < 6)
                goto malformed;
            if (*pleasetime)
                return -1;  /* duplicate lease time */
            memcpy(&nwint, (char *)pd->d_opts + oind + 2, sizeof(nwint));
            *pleasetime = ntohl(nwint);
            break;
        case DHCPO_MTYPE:
            if (olen - oind < 3)
                goto malformed;
            if (*pmtype)
                return -1;  /* duplicate message type */
            *pmtype = pd->d_opts[oind + 2];
            break;
        case DHCPO_PAD:
            oind++;
            continue;
        case DHCPO_END:
            oend = 1;
            break;
        default:
            if (olen - oind < 2)
                goto malformed;
        }
        if (oend)
            break;
        oind += pd->d_opts[oind + 1] + 2;
    }
    return 0;
malformed:
    VIR_WARN("got lost in the options!");
    return -1;
}

/*
 * Decode the DHCP options
 *
 * Returns 0 in case of full success.
 * Returns -2 in case of some error with the packet.
 * Returns -1 in case of error with the installation of rules
 */
static int
virNWFilterSnoopDHCPDecode(virNWFilterSnoopReqPtr req,
                           virNWFilterSnoopEthHdrPtr pep,
                           int len, bool fromVM)
{
    struct iphdr *pip;
    struct udphdr *pup;
    virNWFilterSnoopDHCPHdrPtr pd;
    virNWFilterSnoopIPLease ipl;
    uint8_t mtype;
    uint32_t leasetime;
    uint32_t nwint;

    /* go through the protocol headers */
    switch (ntohs(pep->eh_type)) {
    case ETHERTYPE_IP:
994
        VIR_WARNINGS_NO_CAST_ALIGN;
S
Stefan Berger 已提交
995
        pip = (struct iphdr *) pep->eh_data;
996
        VIR_WARNINGS_RESET;
S
Stefan Berger 已提交
997 998 999 1000 1001 1002 1003 1004 1005
        len -= offsetof(virNWFilterSnoopEthHdr, eh_data);
        break;
    default:
        return -2;
    }

    if (len < 0)
        return -2;

1006
    VIR_WARNINGS_NO_CAST_ALIGN
S
Stefan Berger 已提交
1007
    pup = (struct udphdr *) ((char *) pip + (pip->ihl << 2));
1008
    VIR_WARNINGS_RESET
S
Stefan Berger 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017
    len -= pip->ihl << 2;
    if (len < 0)
        return -2;

    pd = (virNWFilterSnoopDHCPHdrPtr) ((char *) pup + sizeof(*pup));
    len -= sizeof(*pup);
    if (len < 0)
        return -2;                 /* invalid packet length */

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    /*
     * some DHCP servers send their responses as MAC broadcast replies
     * filter messages from the server also by the destination MAC
     * inside the DHCP response
     */
    if (!fromVM) {
        if (virMacAddrCmpRaw(&req->macaddr,
                             (unsigned char *)&pd->d_chaddr) != 0)
            return -2;
    }

S
Stefan Berger 已提交
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 1060 1061 1062 1063 1064 1065 1066 1067 1068
    if (virNWFilterSnoopDHCPGetOpt(pd, len, &mtype, &leasetime) < 0)
        return -2;

    memset(&ipl, 0, sizeof(ipl));

    memcpy(&nwint, &pd->d_yiaddr, sizeof(nwint));
    virSocketAddrSetIPv4Addr(&ipl.ipAddress, ntohl(nwint));

    memcpy(&nwint, &pd->d_siaddr, sizeof(nwint));
    virSocketAddrSetIPv4Addr(&ipl.ipServer, ntohl(nwint));

    if (leasetime == ~0)
        ipl.timeout = ~0;
    else
        ipl.timeout = time(0) + leasetime;

    ipl.snoopReq = req;

    /* check that the type of message comes from the right direction */
    switch (mtype) {
    case DHCPACK:
    case DHCPDECLINE:
        if (fromVM)
            return -2;
        break;
    case DHCPRELEASE:
        if (!fromVM)
            return -2;
        break;
    default:
        break;
    }

    switch (mtype) {
    case DHCPACK:
        if (virNWFilterSnoopReqLeaseAdd(req, &ipl, true) < 0)
            return -1;
        break;
    case DHCPDECLINE:
    case DHCPRELEASE:
1069
        if (virNWFilterSnoopReqLeaseDel(req, &ipl.ipAddress, true, true) < 0)
S
Stefan Berger 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
            return -1;
        break;
    default:
        return -2;
    }

    return 0;
}

static pcap_t *
virNWFilterSnoopDHCPOpen(const char *ifname, virMacAddr *mac,
                         const char *filter, pcap_direction_t dir)
{
    pcap_t *handle = NULL;
    struct bpf_program fp;
    char pcap_errbuf[PCAP_ERRBUF_SIZE];
    char *ext_filter = NULL;
    char macaddr[VIR_MAC_STRING_BUFLEN];

1089
    virMacAddrFormat(mac, macaddr);
S
Stefan Berger 已提交
1090 1091 1092 1093 1094 1095 1096 1097

    if (dir == PCAP_D_IN /* from VM */) {
        /*
         * don't want to hear about another VM's DHCP requests
         *
         * extend the filter with the macaddr of the VM; filter the
         * more unlikely parameters first, then go for the MAC
         */
1098 1099 1100 1101 1102
        if (virAsprintf(&ext_filter,
                        "%s and ether src %s", filter, macaddr) < 0) {
            virReportOOMError();
            return NULL;
        }
S
Stefan Berger 已提交
1103
    } else {
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
        /*
         * Some DHCP servers respond via MAC broadcast; we rely on later
         * filtering of responses by comparing the MAC address inside the
         * DHCP response against the one of the VM. Assuming that the
         * bridge learns the VM's MAC address quickly this should not
         * generate much more traffic than if we filtered by VM and
         * braodcast MAC as well
         */
        if (virAsprintf(&ext_filter, "%s", filter) < 0) {
            virReportOOMError();
            return NULL;
        }
S
Stefan Berger 已提交
1116 1117 1118 1119 1120
    }

    handle = pcap_create(ifname, pcap_errbuf);

    if (handle == NULL) {
1121 1122
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("pcap_create failed"));
S
Stefan Berger 已提交
1123 1124 1125 1126 1127 1128
        goto cleanup_nohandle;
    }

    if (pcap_set_snaplen(handle, PCAP_PBUFSIZE) < 0 ||
        pcap_set_buffer_size(handle, PCAP_BUFFERSIZE) < 0 ||
        pcap_activate(handle) < 0) {
1129 1130
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("setup of pcap handle failed"));
S
Stefan Berger 已提交
1131 1132 1133 1134
        goto cleanup;
    }

    if (pcap_compile(handle, &fp, ext_filter, 1, PCAP_NETMASK_UNKNOWN) != 0) {
1135 1136
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pcap_compile: %s"), pcap_geterr(handle));
S
Stefan Berger 已提交
1137 1138 1139 1140
        goto cleanup;
    }

    if (pcap_setfilter(handle, &fp) != 0) {
1141 1142
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pcap_setfilter: %s"), pcap_geterr(handle));
S
Stefan Berger 已提交
1143 1144 1145 1146
        goto cleanup_freecode;
    }

    if (pcap_setdirection(handle, dir) < 0) {
1147 1148 1149
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pcap_setdirection: %s"),
                       pcap_geterr(handle));
S
Stefan Berger 已提交
1150 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
        goto cleanup_freecode;
    }

    pcap_freecode(&fp);
    VIR_FREE(ext_filter);

    return handle;

cleanup_freecode:
    pcap_freecode(&fp);
cleanup:
    pcap_close(handle);
cleanup_nohandle:
    VIR_FREE(ext_filter);

    return NULL;
}

/*
 * Worker function to decode the DHCP message and with that
 * also do the time-consuming work of instantiating the filters
 */
static void virNWFilterDHCPDecodeWorker(void *jobdata, void *opaque)
{
    virNWFilterSnoopReqPtr req = opaque;
    virNWFilterDHCPDecodeJobPtr job = jobdata;
    virNWFilterSnoopEthHdrPtr packet = (virNWFilterSnoopEthHdrPtr)job->packet;

    if (virNWFilterSnoopDHCPDecode(req, packet,
                                   job->caplen, job->fromVM) == -1) {
        req->jobCompletionStatus = -1;

1182 1183 1184
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Instantiation of rules failed on "
                         "interface '%s'"), req->ifname);
S
Stefan Berger 已提交
1185
    }
1186
    virAtomicIntDecAndTest(job->qCtr);
S
Stefan Berger 已提交
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
    VIR_FREE(job);
}

/*
 * Submit a job to the worker thread doing the time-consuming work...
 */
static int
virNWFilterSnoopDHCPDecodeJobSubmit(virThreadPoolPtr pool,
                                    virNWFilterSnoopEthHdrPtr pep,
                                    int len, pcap_direction_t dir,
1197
                                    int *qCtr)
S
Stefan Berger 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 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 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
{
    virNWFilterDHCPDecodeJobPtr job;
    int ret;

    if (len <= MIN_VALID_DHCP_PKT_SIZE || len > sizeof(job->packet))
        return 0;

    if (VIR_ALLOC(job) < 0) {
        virReportOOMError();
        return -1;
    }

    memcpy(job->packet, pep, len);
    job->caplen = len;
    job->fromVM = (dir == PCAP_D_IN);
    job->qCtr = qCtr;

    ret = virThreadPoolSendJob(pool, 0, job);

    if (ret == 0)
        virAtomicIntInc(qCtr);
    else
        VIR_FREE(job);

    return ret;
}

/*
 * virNWFilterSnoopRateLimit -- limit the rate of jobs submitted to the
 *                              worker thread
 *
 * Help defend the worker thread from being flooded with likely bogus packets
 * sent by the VM.
 *
 * rl: The state of the rate limiter
 *
 * Returns the delta of packets compared to the rate, i.e. if the rate
 * is 4 (pkts/s) and we now have received 5 within a second, it would
 * return 1. If the number of packets is below the rate, it returns 0.
 */
static unsigned int
virNWFilterSnoopRateLimit(virNWFilterSnoopRateLimitConfPtr rl)
{
    time_t now = time(0);
    int diff;
# define IN_BURST(n,b) ((n)-(b) <= 1) /* bursts span 2 discrete seconds */

    if (rl->prev != now && !IN_BURST(now, rl->burst)) {
        rl->prev = now;
        rl->pkt_ctr = 1;
    } else {
        rl->pkt_ctr++;
        if (rl->pkt_ctr >= rl->rate) {
            if (IN_BURST(now, rl->burst)) {
                /* in a burst */
                diff = rl->pkt_ctr - rl->burstRate;
                if (diff > 0)
                    return diff;
                return 0;
            }
            if (rl->prev - rl->burst > rl->burstInterval) {
                /* this second will start a new burst */
                rl->burst = rl->prev;
                return 0;
            }
            /* previous burst is too close */
            return rl->pkt_ctr - rl->rate;
        }
    }

    return 0;
}

/*
 * virNWFilterSnoopRatePenalty
 *
 * @pc: pointer to the virNWFilterSnoopPcapConf
 * @diff: the amount of pkts beyond the rate, i.e., if the rate is 10
 *        and 13 pkts have been received now in one seconds, then
 *        this should be 3.
 *
 * Adjusts the timeout the virNWFilterSnooPcapConf will be penalized for
 * sending too many packets.
 */
static void
virNWFilterSnoopRatePenalty(virNWFilterSnoopPcapConfPtr pc,
                            unsigned int diff, unsigned int limit)
{
    if (diff > limit) {
        unsigned long long now;

        if (virTimeMillisNowRaw(&now) < 0) {
            usleep(PCAP_FLOOD_TIMEOUT_MS); /* 1 ms */
            pc->penaltyTimeoutAbs = 0;
        } else {
            /* don't listen to the fd for 1 ms */
            pc->penaltyTimeoutAbs = now + PCAP_FLOOD_TIMEOUT_MS;
        }
    }
}

static int
virNWFilterSnoopAdjustPoll(virNWFilterSnoopPcapConfPtr pc,
                           size_t nPc, struct pollfd *pfd,
                           int *pollTo)
{
    int ret = 0;
    size_t i;
    int tmp;
    unsigned long long now = 0;

    *pollTo = -1;

    for (i = 0; i < nPc; i++) {
        if (pc[i].penaltyTimeoutAbs != 0) {
            if (now == 0) {
                if (virTimeMillisNow(&now) < 0) {
                    ret = -1;
                    break;
                }
            }

            if (now < pc[i].penaltyTimeoutAbs) {
                /* don't listen to incoming data on the fd for some time */
                pfd[i].events &= ~POLLIN;
                /*
                 * calc the max. time to spend in poll() until adjustments
                 * to the pollfd array are needed again.
                 */
                tmp = pc[i].penaltyTimeoutAbs - now;
                if (*pollTo == -1 || tmp < *pollTo)
                    *pollTo = tmp;
            } else {
                /* listen again to the fd */
                pfd[i].events |= POLLIN;

                pc[i].penaltyTimeoutAbs = 0;
            }
        }
    }

    return ret;
}

/*
 * The DHCP snooping thread. It spends most of its time in the pcap
 * library and if it gets suitable packets, it submits them to the worker
 * thread for processing.
 */
static void
virNWFilterDHCPSnoopThread(void *req0)
{
    virNWFilterSnoopReqPtr req = req0;
    struct pcap_pkthdr *hdr;
    virNWFilterSnoopEthHdrPtr packet;
    int ifindex = 0;
    int errcount = 0;
    int tmp = -1, i, rv, n, pollTo;
    char *threadkey = NULL;
    virThreadPoolPtr worker = NULL;
    time_t last_displayed = 0, last_displayed_queue = 0;
    virNWFilterSnoopPcapConf pcapConf[] = {
        {
            .dir = PCAP_D_IN, /* from VM */
            .filter = "dst port 67 and src port 68",
            .rateLimit = {
                .prev = time(0),
                .rate = DHCP_PKT_RATE,
                .burstRate = DHCP_PKT_BURST,
                .burstInterval = DHCP_BURST_INTERVAL_S,
            },
            .maxQSize = MAX_QUEUED_JOBS,
        }, {
            .dir = PCAP_D_OUT, /* to VM */
            .filter = "src port 67 and dst port 68",
            .rateLimit = {
                .prev = time(0),
                .rate = DHCP_PKT_RATE,
                .burstRate = DHCP_PKT_BURST,
                .burstInterval = DHCP_BURST_INTERVAL_S,
            },
            .maxQSize = MAX_QUEUED_JOBS,
        },
    };
    struct pollfd fds[] = {
        {
            /* get a POLLERR if interface goes down or disappears */
            .events = POLLIN | POLLERR,
        }, {
            .events = POLLIN | POLLERR,
        },
    };
    bool error = false;

    /* whoever started us increased the reference counter for the req for us */

    /* protect req->ifname & req->threadkey */
    virNWFilterSnoopReqLock(req);

    if (req->ifname && req->threadkey) {
        for (i = 0; i < ARRAY_CARDINALITY(pcapConf); i++) {
            pcapConf[i].handle =
                virNWFilterSnoopDHCPOpen(req->ifname, &req->macaddr,
                                         pcapConf[i].filter,
                                         pcapConf[i].dir);
1403
            if (!pcapConf[i].handle) {
S
Stefan Berger 已提交
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487
                error = true;
                break;
            }
            fds[i].fd = pcap_fileno(pcapConf[i].handle);
        }
        tmp = virNetDevGetIndex(req->ifname, &ifindex);
        threadkey = strdup(req->threadkey);
        worker = virThreadPoolNew(1, 1, 0,
                                  virNWFilterDHCPDecodeWorker,
                                  req);
    }

    /* let creator know how well we initialized */
    if (error == true || !threadkey || tmp < 0 || !worker ||
        ifindex != req->ifindex)
        req->threadStatus = THREAD_STATUS_FAIL;
    else
        req->threadStatus = THREAD_STATUS_OK;

    virCondSignal(&req->threadStatusCond);

    virNWFilterSnoopReqUnlock(req);

    if (req->threadStatus != THREAD_STATUS_OK)
        goto exit;

    while (!error) {
        if (virNWFilterSnoopAdjustPoll(pcapConf,
                                       ARRAY_CARDINALITY(pcapConf),
                                       fds, &pollTo) < 0) {
            break;
        }

        n = poll(fds, ARRAY_CARDINALITY(fds), pollTo);

        if (n < 0) {
            if (errno != EAGAIN && errno != EINTR)
                error = true;
        }

        virNWFilterSnoopReqLeaseTimerRun(req);

        /*
         * Check whether we were cancelled or whether
         * a previously submitted job failed.
         */
        if (!virNWFilterSnoopIsActive(threadkey) ||
            req->jobCompletionStatus != 0)
            goto exit;

        for (i = 0; n > 0 && i < ARRAY_CARDINALITY(fds); i++) {
            if (!fds[i].revents)
                continue;

            fds[i].revents = 0;
            n--;

            rv = pcap_next_ex(pcapConf[i].handle, &hdr,
                              (const u_char **)&packet);

            if (rv < 0) {
                /* error reading from socket */
                tmp = -1;

                /* protect req->ifname */
                virNWFilterSnoopReqLock(req);

                if (req->ifname)
                    tmp = virNetDevValidateConfig(req->ifname, NULL, ifindex);

                virNWFilterSnoopReqUnlock(req);

                if (tmp <= 0) {
                    error = true;
                    break;
                }

                if (++errcount > PCAP_READ_MAXERRS) {
                    pcap_close(pcapConf[i].handle);
                    pcapConf[i].handle = NULL;

                    /* protect req->ifname */
                    virNWFilterSnoopReqLock(req);

1488 1489 1490 1491
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("interface '%s' failing; "
                                     "reopening"),
                                   req->ifname);
S
Stefan Berger 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
                    if (req->ifname)
                        pcapConf[i].handle =
                            virNWFilterSnoopDHCPOpen(req->ifname, &req->macaddr,
                                                     pcapConf[i].filter,
                                                     pcapConf[i].dir);

                    virNWFilterSnoopReqUnlock(req);

                    if (!pcapConf[i].handle) {
                        error = true;
                        break;
                    }
                }
                continue;
            }

            errcount = 0;

            if (rv) {
                unsigned int diff;

                /* submit packet to worker thread */
1514
                if (virAtomicIntGet(&pcapConf[i].qCtr) >
S
Stefan Berger 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
                    pcapConf[i].maxQSize) {
                    if (last_displayed_queue - time(0) > 10) {
                        last_displayed_queue = time(0);
                        VIR_WARN("Worker thread for interface '%s' has a "
                                 "job queue that is too long\n",
                                 req->ifname);
                    }
                    continue;
                }

                diff = virNWFilterSnoopRateLimit(&pcapConf[i].rateLimit);
                if (diff > 0) {
                    virNWFilterSnoopRatePenalty(&pcapConf[i], diff,
                                                DHCP_PKT_RATE);
                    /* rate-limited warnings */
                    if (time(0) - last_displayed > 10) {
                         last_displayed = time(0);
                         VIR_WARN("Too many DHCP packets on interface '%s'",
                                  req->ifname);
                    }
                    continue;
                }

                if (virNWFilterSnoopDHCPDecodeJobSubmit(worker, packet,
                                                      hdr->caplen,
                                                      pcapConf[i].dir,
                                                      &pcapConf[i].qCtr) < 0) {
1542 1543 1544
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Job submission failed on "
                                     "interface '%s'"), req->ifname);
S
Stefan Berger 已提交
1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
                    error = true;
                    break;
                }
            }
        } /* for all fds */
    } /* while (!error) */

    /* protect IfNameToKey */
    virNWFilterSnoopLock();

    /* protect req->ifname & req->threadkey */
    virNWFilterSnoopReqLock(req);

    virNWFilterSnoopCancel(&req->threadkey);

    ignore_value(virHashRemoveEntry(virNWFilterSnoopState.ifnameToKey,
                                    req->ifname));

    VIR_FREE(req->ifname);

    virNWFilterSnoopReqUnlock(req);
    virNWFilterSnoopUnlock();

exit:
    virThreadPoolFree(worker);

    virNWFilterSnoopReqPut(req);

    VIR_FREE(threadkey);

    for (i = 0; i < ARRAY_CARDINALITY(pcapConf); i++) {
        if (pcapConf[i].handle)
            pcap_close(pcapConf[i].handle);
    }

1580
    virAtomicIntDecAndTest(&virNWFilterSnoopState.nThreads);
S
Stefan Berger 已提交
1581 1582 1583 1584 1585 1586

    return;
}

static void
virNWFilterSnoopIFKeyFMT(char *ifkey, const unsigned char *vmuuid,
1587
                         const virMacAddrPtr macaddr)
S
Stefan Berger 已提交
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599
{
    virUUIDFormat(vmuuid, ifkey);
    ifkey[VIR_UUID_STRING_BUFLEN - 1] = '-';
    virMacAddrFormat(macaddr, ifkey + VIR_UUID_STRING_BUFLEN);
}

int
virNWFilterDHCPSnoopReq(virNWFilterTechDriverPtr techdriver,
                        const char *ifname,
                        const char *linkdev,
                        enum virDomainNetType nettype,
                        const unsigned char *vmuuid,
1600
                        const virMacAddrPtr macaddr,
S
Stefan Berger 已提交
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
                        const char *filtername,
                        virNWFilterHashTablePtr filterparams,
                        virNWFilterDriverStatePtr driver)
{
    virNWFilterSnoopReqPtr req;
    bool isnewreq;
    char ifkey[VIR_IFKEY_LEN];
    int tmp;
    virThread thread;
    virNWFilterVarValuePtr dhcpsrvrs;

    virNWFilterSnoopIFKeyFMT(ifkey, vmuuid, macaddr);

    req = virNWFilterSnoopReqGetByIFKey(ifkey);
    isnewreq = (req == NULL);
    if (!isnewreq) {
        if (req->threadkey) {
            virNWFilterSnoopReqPut(req);
            return 0;
        }
        /* a recycled req may still have filtername and vars */
        VIR_FREE(req->filtername);
        virNWFilterHashTableFree(req->vars);
    } else {
        req = virNWFilterSnoopReqNew(ifkey);
        if (!req)
            return -1;
    }

    req->driver = driver;
    req->techdriver = techdriver;
    tmp = virNetDevGetIndex(ifname, &req->ifindex);
    req->linkdev = linkdev ? strdup(linkdev) : NULL;
    req->nettype = nettype;
    req->ifname = strdup(ifname);
1636
    virMacAddrSet(&req->macaddr, macaddr);
S
Stefan Berger 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646
    req->filtername = strdup(filtername);
    req->vars = virNWFilterHashTableCreate(0);

    if (!req->ifname || !req->filtername || !req->vars || tmp < 0 ||
        (linkdev != NULL && req->linkdev == NULL)) {
        virReportOOMError();
        goto exit_snoopreqput;
    }

    /* check that all tools are available for applying the filters (late) */
1647
    if (!techdriver->canApplyBasicRules()) {
1648 1649 1650 1651
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("IP parameter must be provided since "
                         "snooping the IP address does not work "
                         "possibly due to missing tools"));
S
Stefan Berger 已提交
1652 1653 1654 1655 1656 1657
        goto exit_snoopreqput;
    }

    dhcpsrvrs = virHashLookup(filterparams->hashTable,
                              NWFILTER_VARNAME_DHCPSERVER);

1658
    if (techdriver->applyDHCPOnlyRules(req->ifname, &req->macaddr,
S
Stefan Berger 已提交
1659
                                       dhcpsrvrs, false) < 0) {
1660
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1661 1662
                       _("applyDHCPOnlyRules "
                         "failed - spoofing not protected!"));
S
Stefan Berger 已提交
1663 1664 1665 1666
        goto exit_snoopreqput;
    }

    if (virNWFilterHashTablePutAll(filterparams, req->vars) < 0) {
1667 1668 1669
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("virNWFilterDHCPSnoopReq: can't copy variables"
                         " on if %s"), ifkey);
S
Stefan Berger 已提交
1670 1671 1672 1673 1674 1675 1676
        goto exit_snoopreqput;
    }

    virNWFilterSnoopLock();

    if (virHashAddEntry(virNWFilterSnoopState.ifnameToKey, ifname,
                        req->ifkey) < 0) {
1677 1678 1679 1680
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("virNWFilterDHCPSnoopReq ifname map failed"
                         " on interface \"%s\" key \"%s\""), ifname,
                       ifkey);
S
Stefan Berger 已提交
1681 1682 1683 1684 1685
        goto exit_snoopunlock;
    }

    if (isnewreq &&
        virHashAddEntry(virNWFilterSnoopState.snoopReqs, ifkey, req) < 0) {
1686 1687 1688 1689
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("virNWFilterDHCPSnoopReq req add failed on"
                         " interface \"%s\" ifkey \"%s\""), ifname,
                       ifkey);
S
Stefan Berger 已提交
1690 1691 1692 1693 1694 1695 1696 1697
        goto exit_rem_ifnametokey;
    }

    /* prevent thread from holding req */
    virNWFilterSnoopReqLock(req);

    if (virThreadCreate(&thread, false, virNWFilterDHCPSnoopThread,
                        req) != 0) {
1698 1699 1700
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("virNWFilterDHCPSnoopReq virThreadCreate "
                         "failed on interface '%s'"), ifname);
S
Stefan Berger 已提交
1701 1702 1703 1704 1705 1706 1707
        goto exit_snoopreq_unlock;
    }

    virAtomicIntInc(&virNWFilterSnoopState.nThreads);

    req->threadkey = virNWFilterSnoopActivate(req);
    if (!req->threadkey) {
1708 1709 1710
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Activation of snoop request failed on "
                         "interface '%s'"), req->ifname);
S
Stefan Berger 已提交
1711 1712 1713 1714
        goto exit_snoopreq_unlock;
    }

    if (virNWFilterSnoopReqRestore(req) < 0) {
1715 1716 1717
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Restoring of leases failed on "
                         "interface '%s'"), req->ifname);
S
Stefan Berger 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
        goto exit_snoop_cancel;
    }

    /* sync with thread */
    if (virCondWait(&req->threadStatusCond, &req->lock) < 0 ||
        req->threadStatus != THREAD_STATUS_OK)
        goto exit_snoop_cancel;

    virNWFilterSnoopReqUnlock(req);

    virNWFilterSnoopUnlock();

    /* do not 'put' the req -- the thread will do this */

    return 0;

exit_snoop_cancel:
    virNWFilterSnoopCancel(&req->threadkey);
exit_snoopreq_unlock:
    virNWFilterSnoopReqUnlock(req);
exit_rem_ifnametokey:
    virHashRemoveEntry(virNWFilterSnoopState.ifnameToKey, ifname);
exit_snoopunlock:
    virNWFilterSnoopUnlock();
exit_snoopreqput:
    virNWFilterSnoopReqPut(req);

    return -1;
}

static void
virNWFilterSnoopLeaseFileClose(void)
{
    VIR_FORCE_CLOSE(virNWFilterSnoopState.leaseFD);
}

static void
virNWFilterSnoopLeaseFileOpen(void)
{
    virNWFilterSnoopLeaseFileClose();

    virNWFilterSnoopState.leaseFD = open(LEASEFILE, O_CREAT|O_RDWR|O_APPEND,
                                         0644);
}

/*
 * Write a single lease to the given file.
 *
 */
static int
virNWFilterSnoopLeaseFileWrite(int lfd, const char *ifkey,
                               virNWFilterSnoopIPLeasePtr ipl)
{
    char *lbuf = NULL;
    char *ipstr, *dhcpstr;
    int len;
    int ret = 0;

    ipstr = virSocketAddrFormat(&ipl->ipAddress);
    dhcpstr = virSocketAddrFormat(&ipl->ipServer);

    if (!dhcpstr || !ipstr) {
        ret = -1;
        goto cleanup;
    }

    /* time intf ip dhcpserver */
    len = virAsprintf(&lbuf, "%u %s %s %s\n", ipl->timeout,
                      ifkey, ipstr, dhcpstr);

    if (len < 0) {
        virReportOOMError();
        ret = -1;
        goto cleanup;
    }

    if (safewrite(lfd, lbuf, len) != len) {
        virReportSystemError(errno, "%s", _("lease file write failed"));
        ret = -1;
        goto cleanup;
    }

    ignore_value(fsync(lfd));

cleanup:
    VIR_FREE(lbuf);
    VIR_FREE(dhcpstr);
    VIR_FREE(ipstr);

    return ret;
}

/*
 * Append a single lease to the end of the lease file.
 * To keep a limited number of dead leases, re-read the lease
 * file if the threshold of active leases versus written ones
 * exceeds a threshold.
 */
static void
virNWFilterSnoopLeaseFileSave(virNWFilterSnoopIPLeasePtr ipl)
{
    virNWFilterSnoopReqPtr req = ipl->snoopReq;

    virNWFilterSnoopLock();

    if (virNWFilterSnoopState.leaseFD < 0)
        virNWFilterSnoopLeaseFileOpen();
    if (virNWFilterSnoopLeaseFileWrite(virNWFilterSnoopState.leaseFD,
                                       req->ifkey, ipl) < 0)
        goto err_exit;

    /* keep dead leases at < ~95% of file size */
    if (virAtomicIntInc(&virNWFilterSnoopState.wLeases) >=
1831
        virAtomicIntGet(&virNWFilterSnoopState.nLeases) * 20)
S
Stefan Berger 已提交
1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
        virNWFilterSnoopLeaseFileLoad();   /* load & refresh lease file */

err_exit:
    virNWFilterSnoopUnlock();
}

/*
 * Have requests removed that have no leases.
 * Remove all expired leases.
 * Call this function with the SnoopLock held.
 */
static int
virNWFilterSnoopPruneIter(const void *payload,
                          const void *name ATTRIBUTE_UNUSED,
                          const void *data ATTRIBUTE_UNUSED)
{
    const virNWFilterSnoopReqPtr req = (virNWFilterSnoopReqPtr)payload;
    bool del_req;

    /* clean up orphaned, expired leases */

    /* protect req->threadkey */
    virNWFilterSnoopReqLock(req);

    if (!req->threadkey)
        virNWFilterSnoopReqLeaseTimerRun(req);

    /*
     * have the entry removed if it has no leases and no one holds a ref
     */
1862
    del_req = ((req->start == NULL) && (virAtomicIntGet(&req->refctr) == 0));
S
Stefan Berger 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955

    virNWFilterSnoopReqUnlock(req);

    return del_req;
}

/*
 * Iterator to write all leases of a single request to a file.
 * Call this function with the SnoopLock held.
 */
static void
virNWFilterSnoopSaveIter(void *payload,
                         const void *name ATTRIBUTE_UNUSED,
                         void *data)
{
    virNWFilterSnoopReqPtr req = payload;
    int tfd = *(int *)data;
    virNWFilterSnoopIPLeasePtr ipl;

    /* protect req->start */
    virNWFilterSnoopReqLock(req);

    for (ipl = req->start; ipl; ipl = ipl->next)
        ignore_value(virNWFilterSnoopLeaseFileWrite(tfd, req->ifkey, ipl));

    virNWFilterSnoopReqUnlock(req);
}

/*
 * Write all valid leases into a temporary file and then
 * rename the file to the final file.
 * Call this function with the SnoopLock held.
 */
static void
virNWFilterSnoopLeaseFileRefresh(void)
{
    int tfd;

    if (unlink(TMPLEASEFILE) < 0 && errno != ENOENT)
        virReportSystemError(errno, _("unlink(\"%s\")"), TMPLEASEFILE);

    /* lease file loaded, delete old one */
    tfd = open(TMPLEASEFILE, O_CREAT|O_RDWR|O_TRUNC|O_EXCL, 0644);
    if (tfd < 0) {
        virReportSystemError(errno, _("open(\"%s\")"), TMPLEASEFILE);
        return;
    }

    if (virNWFilterSnoopState.snoopReqs) {
        /* clean up the requests */
        virHashRemoveSet(virNWFilterSnoopState.snoopReqs,
                         virNWFilterSnoopPruneIter, NULL);
        /* now save them */
        virHashForEach(virNWFilterSnoopState.snoopReqs,
                       virNWFilterSnoopSaveIter, (void *)&tfd);
    }

    if (VIR_CLOSE(tfd) < 0) {
        virReportSystemError(errno, _("unable to close %s"), TMPLEASEFILE);
        /* assuming the old lease file is still better, skip the renaming */
        goto skip_rename;
    }

    if (rename(TMPLEASEFILE, LEASEFILE) < 0) {
        virReportSystemError(errno, _("rename(\"%s\", \"%s\")"),
                             TMPLEASEFILE, LEASEFILE);
        ignore_value(unlink(TMPLEASEFILE));
    }
    virAtomicIntSet(&virNWFilterSnoopState.wLeases, 0);

skip_rename:
    virNWFilterSnoopLeaseFileOpen();
}


static void
virNWFilterSnoopLeaseFileLoad(void)
{
    char line[256], ifkey[VIR_IFKEY_LEN];
    char ipstr[INET_ADDRSTRLEN], srvstr[INET_ADDRSTRLEN];
    virNWFilterSnoopIPLease ipl;
    virNWFilterSnoopReqPtr req;
    time_t now;
    FILE *fp;
    int ln = 0, tmp;

    /* protect the lease file */
    virNWFilterSnoopLock();

    fp = fopen(LEASEFILE, "r");
    time(&now);
    while (fp && fgets(line, sizeof(line), fp)) {
        if (line[strlen(line)-1] != '\n') {
1956 1957 1958
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("virNWFilterSnoopLeaseFileLoad lease file "
                             "line %d corrupt"), ln);
S
Stefan Berger 已提交
1959 1960 1961 1962 1963 1964
            break;
        }
        ln++;
        /* key len 55 = "VMUUID"+'-'+"MAC" */
        if (sscanf(line, "%u %55s %16s %16s", &ipl.timeout,
                   ifkey, ipstr, srvstr) < 4) {
1965 1966 1967
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("virNWFilterSnoopLeaseFileLoad lease file "
                             "line %d corrupt"), ln);
S
Stefan Berger 已提交
1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
            break;
        }
        if (ipl.timeout && ipl.timeout < now)
            continue;
        req = virNWFilterSnoopReqGetByIFKey(ifkey);
        if (!req) {
            req = virNWFilterSnoopReqNew(ifkey);
            if (!req)
               break;

            tmp = virHashAddEntry(virNWFilterSnoopState.snoopReqs, ifkey, req);

            if (tmp < 0) {
                virNWFilterSnoopReqPut(req);
1982 1983 1984
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("virNWFilterSnoopLeaseFileLoad req add"
                                 " failed on interface \"%s\""), ifkey);
S
Stefan Berger 已提交
1985 1986 1987 1988 1989
                continue;
            }
        }

        if (virSocketAddrParseIPv4(&ipl.ipAddress, ipstr) < 0) {
1990 1991 1992
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("line %d corrupt ipaddr \"%s\""),
                           ln, ipstr);
S
Stefan Berger 已提交
1993 1994 1995 1996 1997 1998 1999 2000 2001
            virNWFilterSnoopReqPut(req);
            continue;
        }
        ignore_value(virSocketAddrParseIPv4(&ipl.ipServer, srvstr));
        ipl.snoopReq = req;

        if (ipl.timeout)
            virNWFilterSnoopReqLeaseAdd(req, &ipl, false);
        else
2002
            virNWFilterSnoopReqLeaseDel(req, &ipl.ipAddress, false, false);
S
Stefan Berger 已提交
2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019

        virNWFilterSnoopReqPut(req);
    }

    VIR_FORCE_FCLOSE(fp);

    virNWFilterSnoopLeaseFileRefresh();

    virNWFilterSnoopUnlock();
}

/*
 * Wait until all threads have ended.
 */
static void
virNWFilterSnoopJoinThreads(void)
{
2020
    while (virAtomicIntGet(&virNWFilterSnoopState.nThreads) != 0) {
S
Stefan Berger 已提交
2021
        VIR_WARN("Waiting for snooping threads to terminate: %u\n",
2022
                 virAtomicIntGet(&virNWFilterSnoopState.nThreads));
S
Stefan Berger 已提交
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
        usleep(1000 * 1000);
    }
}

/*
 * Iterator to remove a request, repeatedly called on one
 * request after another.
 * The requests' ifname is freed allowing for an association
 * of the Snoop request's leases with the same VM under a
 * different interface name at a later time.
 */
static int
virNWFilterSnoopRemAllReqIter(const void *payload,
                              const void *name ATTRIBUTE_UNUSED,
                              const void *data ATTRIBUTE_UNUSED)
{
    const virNWFilterSnoopReqPtr req = (virNWFilterSnoopReqPtr)payload;

    /* protect req->ifname */
    virNWFilterSnoopReqLock(req);

    if (req->ifname) {
        ignore_value(virHashRemoveEntry(virNWFilterSnoopState.ifnameToKey,
                                        req->ifname));

2048 2049 2050 2051 2052 2053 2054
        /*
         * Remove all IP addresses known to be associated with this
         * interface so that a new thread will be started on this
         * interface
         */
        virNWFilterIPAddrMapDelIPAddr(req->ifname, NULL);

S
Stefan Berger 已提交
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
        VIR_FREE(req->ifname);
    }

    virNWFilterSnoopReqUnlock(req);

    /* removal will call virNWFilterSnoopCancel() */
    return 1;
}


/*
 * Terminate all threads; keep the SnoopReqs hash allocated
 */
static void
virNWFilterSnoopEndThreads(void)
{
    virNWFilterSnoopLock();
    virHashRemoveSet(virNWFilterSnoopState.snoopReqs,
                     virNWFilterSnoopRemAllReqIter,
                     NULL);
    virNWFilterSnoopUnlock();
}

int
virNWFilterDHCPSnoopInit(void)
{
    if (virNWFilterSnoopState.snoopReqs)
        return 0;

2084 2085
    VIR_DEBUG("Initializing DHCP snooping");

S
Stefan Berger 已提交
2086
    if (virMutexInitRecursive(&virNWFilterSnoopState.snoopLock) < 0 ||
2087
        virMutexInit(&virNWFilterSnoopState.activeLock) < 0)
S
Stefan Berger 已提交
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
        return -1;

    virNWFilterSnoopState.ifnameToKey = virHashCreate(0, NULL);
    virNWFilterSnoopState.active = virHashCreate(0, NULL);
    virNWFilterSnoopState.snoopReqs =
        virHashCreate(0, virNWFilterSnoopReqRelease);

    if (!virNWFilterSnoopState.ifnameToKey ||
        !virNWFilterSnoopState.snoopReqs ||
        !virNWFilterSnoopState.active) {
        virReportOOMError();
        goto err_exit;
    }

    virNWFilterSnoopLeaseFileLoad();
    virNWFilterSnoopLeaseFileOpen();

    return 0;

err_exit:
    virHashFree(virNWFilterSnoopState.ifnameToKey);
    virNWFilterSnoopState.ifnameToKey = NULL;

    virHashFree(virNWFilterSnoopState.snoopReqs);
    virNWFilterSnoopState.snoopReqs = NULL;

    virHashFree(virNWFilterSnoopState.active);
    virNWFilterSnoopState.active = NULL;

    return -1;
}

void
virNWFilterDHCPSnoopEnd(const char *ifname)
{
    char *ifkey = NULL;

    virNWFilterSnoopLock();

    if (!virNWFilterSnoopState.snoopReqs)
        goto cleanup;

    if (ifname) {
        ifkey = (char *)virHashLookup(virNWFilterSnoopState.ifnameToKey,
                                      ifname);
        if (!ifkey) {
2134 2135
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("ifname \"%s\" not in key map"), ifname);
S
Stefan Berger 已提交
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
            goto cleanup;
        }

        ignore_value(virHashRemoveEntry(virNWFilterSnoopState.ifnameToKey,
                                        ifname));
    }

    if (ifkey) {
        virNWFilterSnoopReqPtr req;

        req = virNWFilterSnoopReqGetByIFKey(ifkey);
        if (!req) {
2148 2149
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("ifkey \"%s\" has no req"), ifkey);
S
Stefan Berger 已提交
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
            goto cleanup;
        }

        /* protect req->ifname & req->threadkey */
        virNWFilterSnoopReqLock(req);

        /* keep valid lease req; drop interface association */
        virNWFilterSnoopCancel(&req->threadkey);

        VIR_FREE(req->ifname);

        virNWFilterSnoopReqUnlock(req);

        virNWFilterSnoopReqPut(req);
    } else {                      /* free all of them */
        virNWFilterSnoopLeaseFileClose();

        virHashRemoveAll(virNWFilterSnoopState.ifnameToKey);

        /* tell the threads to terminate */
        virNWFilterSnoopEndThreads();

        virNWFilterSnoopLeaseFileLoad();
    }

cleanup:
    virNWFilterSnoopUnlock();
}

void
virNWFilterDHCPSnoopShutdown(void)
{
    virNWFilterSnoopEndThreads();
    virNWFilterSnoopJoinThreads();

    virNWFilterSnoopLock();

    virNWFilterSnoopLeaseFileClose();
    virHashFree(virNWFilterSnoopState.ifnameToKey);
    virHashFree(virNWFilterSnoopState.snoopReqs);

    virNWFilterSnoopUnlock();

    virNWFilterSnoopActiveLock();
    virHashFree(virNWFilterSnoopState.active);
    virNWFilterSnoopActiveUnlock();
}

#else /* HAVE_LIBPCAP */

int
virNWFilterDHCPSnoopInit(void)
{
2203 2204
    VIR_DEBUG("No DHCP snooping support available");
    return 0;
S
Stefan Berger 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
}

void
virNWFilterDHCPSnoopEnd(const char *ifname ATTRIBUTE_UNUSED)
{
    return;
}

void
virNWFilterDHCPSnoopShutdown(void)
{
    return;
}

int
virNWFilterDHCPSnoopReq(virNWFilterTechDriverPtr techdriver ATTRIBUTE_UNUSED,
                        const char *ifname ATTRIBUTE_UNUSED,
                        const char *linkdev ATTRIBUTE_UNUSED,
                        enum virDomainNetType nettype ATTRIBUTE_UNUSED,
                        const unsigned char *vmuuid ATTRIBUTE_UNUSED,
2225
                        const virMacAddrPtr macaddr ATTRIBUTE_UNUSED,
S
Stefan Berger 已提交
2226 2227 2228 2229
                        const char *filtername ATTRIBUTE_UNUSED,
                        virNWFilterHashTablePtr filterparams ATTRIBUTE_UNUSED,
                        virNWFilterDriverStatePtr driver ATTRIBUTE_UNUSED)
{
2230 2231 2232 2233
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("libvirt was not compiled with libpcap and \""
                     NWFILTER_VARNAME_CTRL_IP_LEARNING
                     "='dhcp'\" requires it."));
S
Stefan Berger 已提交
2234 2235 2236
    return -1;
}
#endif /* HAVE_LIBPCAP */