nwfilter_gentech_driver.c 29.8 KB
Newer Older
1 2 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
/*
 * nwfilter_gentech_driver.c: generic technology driver
 *
 * Copyright (C) 2010 IBM Corp.
 * Copyright (C) 2010 Stefan Berger
 *
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Stefan Berger <stefanb@us.ibm.com>
 */

#include <config.h>

#include "internal.h"

#include "memory.h"
#include "logging.h"
30
#include "interface.h"
31 32 33 34
#include "domain_conf.h"
#include "virterror_internal.h"
#include "nwfilter_gentech_driver.h"
#include "nwfilter_ebiptables_driver.h"
35
#include "nwfilter_learnipaddr.h"
36 37 38 39 40 41


#define VIR_FROM_THIS VIR_FROM_NWFILTER


#define NWFILTER_STD_VAR_MAC "MAC"
42 43 44
#define NWFILTER_STD_VAR_IP  "IP"

static int _virNWFilterTeardownFilter(const char *ifname);
45 46 47 48 49 50 51 52


static virNWFilterTechDriverPtr filter_tech_drivers[] = {
    &ebiptables_driver,
    NULL
};


53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
void virNWFilterTechDriversInit() {
    int i = 0;
    while (filter_tech_drivers[i]) {
        if (!(filter_tech_drivers[i]->flags & TECHDRV_FLAG_INITIALIZED))
            filter_tech_drivers[i]->init();
        i++;
    }
}


void virNWFilterTechDriversShutdown() {
    int i = 0;
    while (filter_tech_drivers[i]) {
        if ((filter_tech_drivers[i]->flags & TECHDRV_FLAG_INITIALIZED))
            filter_tech_drivers[i]->shutdown();
        i++;
    }
}


73 74 75 76
virNWFilterTechDriverPtr
virNWFilterTechDriverForName(const char *name) {
    int i = 0;
    while (filter_tech_drivers[i]) {
77 78 79
       if (STREQ(filter_tech_drivers[i]->name, name)) {
           if ((filter_tech_drivers[i]->flags & TECHDRV_FLAG_INITIALIZED) == 0)
               break;
80
           return filter_tech_drivers[i];
81
       }
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
       i++;
    }
    return NULL;
}


/**
 * virNWFilterRuleInstAddData:
 * @res : pointer to virNWFilterRuleInst object collecting the instantiation
 *        data of a single firewall rule.
 * @data : the opaque data that the driver wants to add
 *
 * Add instantiation data to a firewall rule. An instantiated firewall
 * rule may hold multiple data structure representing its instantiation
 * data. This may for example be the case if a rule has been defined
 * for bidirectional traffic and data needs to be added to the incoming
 * and outgoing chains.
 *
 * Returns 0 in case of success, 1 in case of an error with the error
 * message attached to the virConnect object.
 */
int
104
virNWFilterRuleInstAddData(virNWFilterRuleInstPtr res,
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
                           void *data)
{
    if (VIR_REALLOC_N(res->data, res->ndata+1) < 0) {
        virReportOOMError();
        return 1;
    }
    res->data[res->ndata++] = data;
    return 0;
}


static void
virNWFilterRuleInstFree(virNWFilterRuleInstPtr inst)
{
    int i;
    if (!inst)
        return;

    for (i = 0; i < inst->ndata; i++)
        inst->techdriver->freeRuleInstance(inst->data[i]);

    VIR_FREE(inst->data);
    VIR_FREE(inst);
}


/**
 * virNWFilterVarHashmapAddStdValues:
 * @tables: pointer to hash tabel to add values to
 * @macaddr: The string of the MAC address to add to the hash table,
 *    may be NULL
136 137
 * @ipaddr: The string of the IP address to add to the hash table;
 *    may be NULL
138 139 140 141 142 143 144
 *
 * Returns 0 in case of success, 1 in case an error happened with
 * error having been reported.
 *
 * Adds a couple of standard keys (MAC, IP) to the hash table.
 */
static int
145
virNWFilterVarHashmapAddStdValues(virNWFilterHashTablePtr table,
146 147
                                  char *macaddr,
                                  char *ipaddr)
148 149 150 151 152
{
    if (macaddr) {
        if (virHashAddEntry(table->hashTable,
                            NWFILTER_STD_VAR_MAC,
                            macaddr) < 0) {
153
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
154 155 156 157 158
                                   "%s", _("Could not add variable 'MAC' to hashmap"));
            return 1;
        }
    }

159 160 161 162 163 164 165 166 167 168
    if (ipaddr) {
        if (virHashAddEntry(table->hashTable,
                            NWFILTER_STD_VAR_IP,
                            ipaddr) < 0) {
            virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
                                   "%s", _("Could not add variable 'IP' to hashmap"));
            return 1;
        }
    }

169 170 171 172 173 174 175
    return 0;
}


/**
 * virNWFilterCreateVarHashmap:
 * @macaddr: pointer to string containing formatted MAC address of interface
176 177
 * @ipaddr: pointer to string containing formatted IP address used by
 *          VM on this interface; may be NULL
178 179
 *
 * Create a hashmap used for evaluating the firewall rules. Initializes
180
 * it with the standard variable 'MAC' and 'IP' if provided.
181 182 183 184 185
 *
 * Returns pointer to hashmap, NULL if an error occcurred and error message
 * is attached to the virConnect object.
 */
virNWFilterHashTablePtr
186
virNWFilterCreateVarHashmap(char *macaddr, char *ipaddr) {
187 188 189 190 191 192
    virNWFilterHashTablePtr table = virNWFilterHashTableCreate(0);
    if (!table) {
        virReportOOMError();
        return NULL;
    }

193
    if (virNWFilterVarHashmapAddStdValues(table, macaddr, ipaddr)) {
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        virNWFilterHashTableFree(table);
        return NULL;
    }
    return table;
}


/**
 * virNWFilterRuleInstantiate:
 * @conn: pointer to virConnect object
 * @techdriver: the driver to use for instantiation
 * @filter: The filter the rule is part of
 * @rule : The rule that is to be instantiated
 * @ifname: The name of the interface
 * @vars: map containing variable names and value used for instantiation
 *
 * Returns virNWFilterRuleInst object on success, NULL on error with
 * error reported.
 *
 * Instantiate a single rule. Return a pointer to virNWFilterRuleInst
 * object that will hold an array of driver-specific data resulting
 * from the instantiation. Returns NULL on error with error reported.
 */
static virNWFilterRuleInstPtr
virNWFilterRuleInstantiate(virConnectPtr conn,
                           virNWFilterTechDriverPtr techdriver,
                           enum virDomainNetType nettype,
                           virNWFilterDefPtr filter,
                           virNWFilterRuleDefPtr rule,
                           const char *ifname,
                           virNWFilterHashTablePtr vars)
{
    int rc;
    int i;
    virNWFilterRuleInstPtr ret;

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

    ret->techdriver = techdriver;

    rc = techdriver->createRuleInstance(conn, nettype, filter,
                                        rule, ifname, vars, ret);

    if (rc) {
        for (i = 0; i < ret->ndata; i++)
            techdriver->freeRuleInstance(ret->data[i]);
        VIR_FREE(ret);
        ret = NULL;
    }

    return ret;
}


/**
 * virNWFilterCreateVarsFrom:
 * @vars1: pointer to hash table
 * @vars2: pointer to hash table
 *
 * Returns pointer to new hashtable or NULL in case of error with
 * error already reported.
 *
 * Creates a new hash table with contents of var1 and var2 added where
 * contents of var2 will overwrite those of var1.
 */
static virNWFilterHashTablePtr
263
virNWFilterCreateVarsFrom(virNWFilterHashTablePtr vars1,
264 265 266 267 268 269 270 271
                          virNWFilterHashTablePtr vars2)
{
    virNWFilterHashTablePtr res = virNWFilterHashTableCreate(0);
    if (!res) {
        virReportOOMError();
        return NULL;
    }

272
    if (virNWFilterHashTablePutAll(vars1, res))
273 274
        goto err_exit;

275
    if (virNWFilterHashTablePutAll(vars2, res))
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
        goto err_exit;

    return res;

err_exit:
    virNWFilterHashTableFree(res);
    return NULL;
}


/**
 * _virNWFilterPoolInstantiateRec:
 * @conn: pointer to virConnect object
 * @techdriver: The driver to use for instantiation
 * @filter: The filter to instantiate
 * @ifname: The name of the interface to apply the rules to
 * @vars: A map holding variable names and values used for instantiating
 *  the filter and its subfilters.
 * @nEntries: number of virNWFilterInst objects collected
 * @insts: pointer to array for virNWFilterIns object pointers
 * @useNewFilter: instruct whether to use a newDef pointer rather than a
 *  def ptr which is useful during a filter update
 * @foundNewFilter: pointer to int indivating whether a newDef pointer was
 *  ever used; variable expected to be initialized to 0 by caller
 *
 * Returns 0 on success, a value otherwise.
 *
 * Recursively instantiate a filter by instantiating the given filter along
 * with all its subfilters in a depth-first traversal of the tree of
 * referenced filters. The name of the interface to which the rules belong
 * must be provided. Apply the values of variables as needed. Terminate with
 * error when a referenced filter is missing or a variable could not be
 * resolved -- among other reasons.
 */
static int
_virNWFilterInstantiateRec(virConnectPtr conn,
                           virNWFilterTechDriverPtr techdriver,
                           enum virDomainNetType nettype,
                           virNWFilterDefPtr filter,
                           const char *ifname,
                           virNWFilterHashTablePtr vars,
                           int *nEntries,
                           virNWFilterRuleInstPtr **insts,
319 320
                           enum instCase useNewFilter, int *foundNewFilter,
                           virNWFilterDriverStatePtr driver)
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
{
    virNWFilterPoolObjPtr obj;
    int rc = 0;
    int i;
    virNWFilterRuleInstPtr inst;
    virNWFilterDefPtr next_filter;

    for (i = 0; i < filter->nentries; i++) {
        virNWFilterRuleDefPtr    rule = filter->filterEntries[i]->rule;
        virNWFilterIncludeDefPtr inc  = filter->filterEntries[i]->include;
        if (rule) {
            inst = virNWFilterRuleInstantiate(conn,
                                              techdriver,
                                              nettype,
                                              filter,
                                              rule,
                                              ifname,
                                              vars);
            if (!inst) {
                rc = 1;
                break;
            }

            if (VIR_REALLOC_N(*insts, (*nEntries)+1) < 0) {
                virReportOOMError();
                rc = 1;
                break;
            }

            (*insts)[(*nEntries)++] = inst;

        } else if (inc) {
353
            VIR_DEBUG("Instantiating filter %s", inc->filterref);
354 355 356 357 358
            obj = virNWFilterPoolObjFindByName(&driver->pools,
                                               inc->filterref);
            if (obj) {

                if (obj->wantRemoved) {
359
                    virNWFilterReportError(VIR_ERR_NO_NWFILTER,
360 361 362 363 364 365 366 367 368
                                           _("Filter '%s' is in use."),
                                           inc->filterref);
                    rc = 1;
                    virNWFilterPoolObjUnlock(obj);
                    break;
                }

                // create a temporary hashmap for depth-first tree traversal
                virNWFilterHashTablePtr tmpvars =
369
                                      virNWFilterCreateVarsFrom(inc->params,
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
                                                                vars);
                if (!tmpvars) {
                    virReportOOMError();
                    rc = 1;
                    virNWFilterPoolObjUnlock(obj);
                    break;
                }

                next_filter = obj->def;

                switch (useNewFilter) {
                case INSTANTIATE_FOLLOW_NEWFILTER:
                    if (obj->newDef) {
                        next_filter = obj->newDef;
                        *foundNewFilter = 1;
                    }
                break;
                case INSTANTIATE_ALWAYS:
                break;
                }

                rc = _virNWFilterInstantiateRec(conn,
                                                techdriver,
                                                nettype,
                                                next_filter,
                                                ifname,
                                                tmpvars,
                                                nEntries, insts,
                                                useNewFilter,
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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
                                                foundNewFilter,
                                                driver);

                virNWFilterHashTableFree(tmpvars);

                virNWFilterPoolObjUnlock(obj);
                if (rc)
                    break;
            } else {
                virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("referenced filter '%s' is missing"),
                                       inc->filterref);
                rc = 1;
                break;
            }
        }
    }
    return rc;
}


static int
virNWFilterDetermineMissingVarsRec(virConnectPtr conn,
                                   virNWFilterDefPtr filter,
                                   virNWFilterHashTablePtr vars,
                                   virNWFilterHashTablePtr missing_vars,
                                   int useNewFilter,
                                   virNWFilterDriverStatePtr driver)
{
    virNWFilterPoolObjPtr obj;
    int rc = 0;
    int i, j;
    virNWFilterDefPtr next_filter;

    for (i = 0; i < filter->nentries; i++) {
        virNWFilterRuleDefPtr    rule = filter->filterEntries[i]->rule;
        virNWFilterIncludeDefPtr inc  = filter->filterEntries[i]->include;
        if (rule) {
            // check all variables of this rule
            for (j = 0; j < rule->nvars; j++) {
                if (!virHashLookup(vars->hashTable, rule->vars[j])) {
                    virNWFilterHashTablePut(missing_vars, rule->vars[j],
                                            strdup("1"), 1);
                }
            }
        } else if (inc) {
            VIR_DEBUG("Following filter %s\n", inc->filterref);
            obj = virNWFilterPoolObjFindByName(&driver->pools,
                                               inc->filterref);
            if (obj) {

                if (obj->wantRemoved) {
                    virNWFilterReportError(VIR_ERR_NO_NWFILTER,
                                           _("Filter '%s' is in use."),
                                           inc->filterref);
                    rc = 1;
                    virNWFilterPoolObjUnlock(obj);
                    break;
                }

                // create a temporary hashmap for depth-first tree traversal
                virNWFilterHashTablePtr tmpvars =
                                      virNWFilterCreateVarsFrom(inc->params,
                                                                vars);
                if (!tmpvars) {
                    virReportOOMError();
                    rc = 1;
                    virNWFilterPoolObjUnlock(obj);
                    break;
                }

                next_filter = obj->def;

                switch (useNewFilter) {
                case INSTANTIATE_FOLLOW_NEWFILTER:
                    if (obj->newDef) {
                        next_filter = obj->newDef;
                    }
                break;
                case INSTANTIATE_ALWAYS:
                break;
                }

                rc = virNWFilterDetermineMissingVarsRec(conn,
                                                        next_filter,
                                                        tmpvars,
                                                        missing_vars,
                                                        useNewFilter,
                                                        driver);
488 489 490 491 492 493 494

                virNWFilterHashTableFree(tmpvars);

                virNWFilterPoolObjUnlock(obj);
                if (rc)
                    break;
            } else {
495
                virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
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 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
                                       _("referenced filter '%s' is missing"),
                                       inc->filterref);
                rc = 1;
                break;
            }
        }
    }
    return rc;
}


static int
virNWFilterRuleInstancesToArray(int nEntries,
                                virNWFilterRuleInstPtr *insts,
                                void ***ptrs,
                                int *nptrs)
{
    int i,j;

    *nptrs = 0;

    for (j = 0; j < nEntries; j++)
        (*nptrs) += insts[j]->ndata;

    if ((*nptrs) == 0)
        return 0;

    if (VIR_ALLOC_N((*ptrs), (*nptrs)) < 0) {
        virReportOOMError();
        return 1;
    }

    (*nptrs) = 0;

    for (j = 0; j < nEntries; j++)
        for (i = 0; i < insts[j]->ndata; i++)
            (*ptrs)[(*nptrs)++] = insts[j]->data[i];

    return 0;
}


/**
 * virNWFilterInstantiate:
 * @conn: pointer to virConnect object
 * @techdriver: The driver to use for instantiation
 * @filter: The filter to instantiate
 * @ifname: The name of the interface to apply the rules to
 * @vars: A map holding variable names and values used for instantiating
 *  the filter and its subfilters.
 *
 * Returns 0 on success, a value otherwise.
 *
 * Instantiate a filter by instantiating the filter itself along with
 * all its subfilters in a depth-first traversal of the tree of referenced
 * filters. The name of the interface to which the rules belong must be
 * provided. Apply the values of variables as needed.
 */
static int
virNWFilterInstantiate(virConnectPtr conn,
                       virNWFilterTechDriverPtr techdriver,
                       enum virDomainNetType nettype,
                       virNWFilterDefPtr filter,
                       const char *ifname,
560
                       const char *linkdev,
561 562
                       virNWFilterHashTablePtr vars,
                       enum instCase useNewFilter, int *foundNewFilter,
563 564 565
                       bool teardownOld,
                       const unsigned char *macaddr,
                       virNWFilterDriverStatePtr driver)
566 567 568 569 570 571 572 573
{
    int rc;
    int j, nptrs;
    int nEntries = 0;
    virNWFilterRuleInstPtr *insts = NULL;
    void **ptrs = NULL;
    int instantiate = 1;

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    virNWFilterLockFilterUpdates();

    virNWFilterHashTablePtr missing_vars = virNWFilterHashTableCreate(0);
    if (!missing_vars) {
        virReportOOMError();
        rc = 1;
        goto err_exit;
    }

    rc = virNWFilterDetermineMissingVarsRec(conn,
                                            filter,
                                            vars,
                                            missing_vars,
                                            useNewFilter,
                                            driver);
    if (rc)
        goto err_exit;

    if (virHashSize(missing_vars->hashTable) == 1) {
        if (virHashLookup(missing_vars->hashTable,
                          NWFILTER_STD_VAR_IP) != NULL) {
            if (virNWFilterLookupLearnReq(ifname) == NULL) {
                rc = virNWFilterLearnIPAddress(ifname,
                                               linkdev,
                                               nettype, macaddr,
                                               filter->name,
                                               vars, driver,
                                               DETECT_DHCP|DETECT_STATIC);
            }
            goto err_exit;
        }
        rc = 1;
        goto err_exit;
    } else if (virHashSize(missing_vars->hashTable) > 1) {
        rc = 1;
        goto err_exit;
    }

612 613 614 615 616 617 618
    rc = _virNWFilterInstantiateRec(conn,
                                    techdriver,
                                    nettype,
                                    filter,
                                    ifname,
                                    vars,
                                    &nEntries, &insts,
619 620
                                    useNewFilter, foundNewFilter,
                                    driver);
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

    if (rc)
        goto err_exit;

    switch (useNewFilter) {
    case INSTANTIATE_FOLLOW_NEWFILTER:
        instantiate = *foundNewFilter;
    break;
    case INSTANTIATE_ALWAYS:
        instantiate = 1;
    break;
    }

    if (instantiate) {

        rc = virNWFilterRuleInstancesToArray(nEntries, insts,
                                             &ptrs, &nptrs);
        if (rc)
            goto err_exit;

        rc = techdriver->applyNewRules(conn, ifname, nptrs, ptrs);

        if (teardownOld && rc == 0)
            techdriver->tearOldRules(conn, ifname);

        VIR_FREE(ptrs);
    }

err_exit:

651 652
    virNWFilterUnlockFilterUpdates();

653 654 655 656 657
    for (j = 0; j < nEntries; j++)
        virNWFilterRuleInstFree(insts[j]);

    VIR_FREE(insts);

658 659
    virNWFilterHashTableFree(missing_vars);

660 661 662 663 664
    return rc;
}


static int
665 666 667 668 669 670 671 672 673 674
__virNWFilterInstantiateFilter(virConnectPtr conn,
                               bool teardownOld,
                               const char *ifname,
                               const char *linkdev,
                               enum virDomainNetType nettype,
                               const unsigned char *macaddr,
                               const char *filtername,
                               virNWFilterHashTablePtr filterparams,
                               enum instCase useNewFilter,
                               virNWFilterDriverStatePtr driver)
675 676 677 678 679 680 681 682 683 684
{
    int rc;
    const char *drvname = EBIPTABLES_DRIVER_ID;
    virNWFilterTechDriverPtr techdriver;
    virNWFilterPoolObjPtr obj;
    virNWFilterHashTablePtr vars, vars1;
    virNWFilterDefPtr filter;
    char vmmacaddr[VIR_MAC_STRING_BUFLEN] = {0};
    int foundNewFilter = 0;
    char *str_macaddr = NULL;
685 686
    const char *ipaddr;
    char *str_ipaddr = NULL;
687 688 689 690

    techdriver = virNWFilterTechDriverForName(drvname);

    if (!techdriver) {
691
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
692 693 694 695 696 697
                               _("Could not get access to ACL tech "
                               "driver '%s'"),
                               drvname);
        return 1;
    }

698
    VIR_DEBUG("filter name: %s", filtername);
699

700
    obj = virNWFilterPoolObjFindByName(&driver->pools, filtername);
701
    if (!obj) {
702
        virNWFilterReportError(VIR_ERR_NO_NWFILTER,
703
                               _("Could not find filter '%s'"),
704
                               filtername);
705 706 707 708
        return 1;
    }

    if (obj->wantRemoved) {
709
        virNWFilterReportError(VIR_ERR_NO_NWFILTER,
710
                               _("Filter '%s' is in use."),
711
                               filtername);
712 713 714 715
        rc = 1;
        goto err_exit;
    }

716
    virFormatMacAddr(macaddr, vmmacaddr);
717 718 719 720 721 722 723
    str_macaddr = strdup(vmmacaddr);
    if (!str_macaddr) {
        virReportOOMError();
        rc = 1;
        goto err_exit;
    }

724 725 726 727 728 729 730 731 732 733 734
    ipaddr = virNWFilterGetIpAddrForIfname(ifname);
    if (ipaddr) {
        str_ipaddr = strdup(ipaddr);
        if (!str_ipaddr) {
            virReportOOMError();
            rc = 1;
            goto err_exit;
        }
    }

    vars1 = virNWFilterCreateVarHashmap(str_macaddr, str_ipaddr);
735 736 737 738 739 740
    if (!vars1) {
        rc = 1;
        goto err_exit;
    }

    str_macaddr = NULL;
741
    str_ipaddr = NULL;
742

743
    vars = virNWFilterCreateVarsFrom(vars1,
744
                                     filterparams);
745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    if (!vars) {
        rc = 1;
        goto err_exit_vars1;
    }

    filter = obj->def;

    switch (useNewFilter) {
    case INSTANTIATE_FOLLOW_NEWFILTER:
        if (obj->newDef) {
            filter = obj->newDef;
            foundNewFilter = 1;
        }
    break;

    case INSTANTIATE_ALWAYS:
    break;
    }

    rc = virNWFilterInstantiate(conn,
                                techdriver,
766
                                nettype,
767
                                filter,
768 769
                                ifname,
                                linkdev,
770 771
                                vars,
                                useNewFilter, &foundNewFilter,
772 773 774
                                teardownOld,
                                macaddr,
                                driver);
775 776 777 778 779 780 781 782 783

    virNWFilterHashTableFree(vars);

err_exit_vars1:
    virNWFilterHashTableFree(vars1);

err_exit:
    virNWFilterPoolObjUnlock(obj);

784
    VIR_FREE(str_ipaddr);
785 786 787 788 789 790
    VIR_FREE(str_macaddr);

    return rc;
}


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 831 832 833 834 835
static int
_virNWFilterInstantiateFilter(virConnectPtr conn,
                              const virDomainNetDefPtr net,
                              bool teardownOld,
                              enum instCase useNewFilter)
{
    const char *linkdev = (net->type == VIR_DOMAIN_NET_TYPE_DIRECT)
                          ? net->data.direct.linkdev
                          : NULL;
    return __virNWFilterInstantiateFilter(conn,
                                          teardownOld,
                                          net->ifname,
                                          linkdev,
                                          net->type,
                                          net->mac,
                                          net->filter,
                                          net->filterparams,
                                          useNewFilter,
                                          conn->nwfilterPrivateData);
}


int
virNWFilterInstantiateFilterLate(virConnectPtr conn,
                                 const char *ifname,
                                 const char *linkdev,
                                 enum virDomainNetType nettype,
                                 const unsigned char *macaddr,
                                 const char *filtername,
                                 virNWFilterHashTablePtr filterparams,
                                 virNWFilterDriverStatePtr driver)
{
    int rc;
    rc = __virNWFilterInstantiateFilter(conn,
                                        1,
                                        ifname,
                                        linkdev,
                                        nettype,
                                        macaddr,
                                        filtername,
                                        filterparams,
                                        INSTANTIATE_ALWAYS,
                                        driver);
    if (rc) {
        //something went wrong... 'DOWN' the interface
836
        if (ifaceDown(ifname)) {
837 838 839 840 841 842 843 844
            // assuming interface disappeared...
            _virNWFilterTeardownFilter(ifname);
        }
    }
    return rc;
}


845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
int
virNWFilterInstantiateFilter(virConnectPtr conn,
                             const virDomainNetDefPtr net)
{
    return _virNWFilterInstantiateFilter(conn, net,
                                         1,
                                         INSTANTIATE_ALWAYS);
}


int
virNWFilterUpdateInstantiateFilter(virConnectPtr conn,
                                   const virDomainNetDefPtr net)
{
    return _virNWFilterInstantiateFilter(conn, net,
                                         0,
                                         INSTANTIATE_FOLLOW_NEWFILTER);
}

int virNWFilterRollbackUpdateFilter(virConnectPtr conn,
                                    const virDomainNetDefPtr net)
{
    const char *drvname = EBIPTABLES_DRIVER_ID;
    virNWFilterTechDriverPtr techdriver;
    techdriver = virNWFilterTechDriverForName(drvname);
    if (!techdriver) {
871
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
                               _("Could not get access to ACL tech "
                               "driver '%s'"),
                               drvname);
        return 1;
    }

    return techdriver->tearNewRules(conn, net->ifname);
}


int
virNWFilterTearOldFilter(virConnectPtr conn,
                         virDomainNetDefPtr net)
{
    const char *drvname = EBIPTABLES_DRIVER_ID;
    virNWFilterTechDriverPtr techdriver;
    techdriver = virNWFilterTechDriverForName(drvname);
    if (!techdriver) {
890
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
891 892 893 894 895 896 897 898 899 900
                               _("Could not get access to ACL tech "
                               "driver '%s'"),
                               drvname);
        return 1;
    }

    return techdriver->tearOldRules(conn, net->ifname);
}


901 902
static int
_virNWFilterTeardownFilter(const char *ifname)
903 904 905 906 907 908
{
    const char *drvname = EBIPTABLES_DRIVER_ID;
    virNWFilterTechDriverPtr techdriver;
    techdriver = virNWFilterTechDriverForName(drvname);

    if (!techdriver) {
909
        virNWFilterReportError(VIR_ERR_INTERNAL_ERROR,
910 911 912 913 914
                               _("Could not get access to ACL tech "
                               "driver '%s'"),
                               drvname);
        return 1;
    }
915
    techdriver->allTeardown(ifname);
916

917
    virNWFilterDelIpAddrForIfname(ifname);
918 919 920

    return 0;
}
921 922


923 924 925 926 927 928 929
int
virNWFilterTeardownFilter(const virDomainNetDefPtr net)
{
    return _virNWFilterTeardownFilter(net->ifname);
}


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
void
virNWFilterDomainFWUpdateCB(void *payload,
                            const char *name ATTRIBUTE_UNUSED,
                            void *data)
{
    virDomainObjPtr obj = payload;
    virDomainDefPtr vm = obj->def;
    struct domUpdateCBStruct *cb = data;
    int i;

    virDomainObjLock(obj);

    if (virDomainObjIsActive(obj)) {
        for (i = 0; i < vm->nnets; i++) {
            virDomainNetDefPtr net = vm->nets[i];
            if ((net->filter) && (net->ifname)) {
                switch (cb->step) {
                case STEP_APPLY_NEW:
                    cb->err = virNWFilterUpdateInstantiateFilter(cb->conn,
                                                                 net);
                    break;

                case STEP_TEAR_NEW:
                    cb->err = virNWFilterRollbackUpdateFilter(cb->conn, net);
                    break;

                case STEP_TEAR_OLD:
                    cb->err = virNWFilterTearOldFilter(cb->conn, net);
                    break;
                }
                if (cb->err)
                    break;
            }
        }
    }

    virDomainObjUnlock(obj);
}