virfirewall.c 24.7 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
/*
 * virfirewall.c: integration with firewalls
 *
 * Copyright (C) 2013 Red Hat, Inc.
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *    Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#define __VIR_FIREWALL_PRIV_H_ALLOW__

#include <stdarg.h>

#include "viralloc.h"
#include "virfirewallpriv.h"
#include "virerror.h"
#include "virutil.h"
#include "virstring.h"
#include "vircommand.h"
#include "virlog.h"
#include "virdbus.h"
#include "virfile.h"
#include "virthread.h"

#define VIR_FROM_THIS VIR_FROM_FIREWALL

VIR_LOG_INIT("util.firewall");

typedef struct _virFirewallGroup virFirewallGroup;
typedef virFirewallGroup *virFirewallGroupPtr;

VIR_ENUM_DECL(virFirewallLayerCommand)
VIR_ENUM_IMPL(virFirewallLayerCommand, VIR_FIREWALL_LAYER_LAST,
              EBTABLES_PATH,
              IPTABLES_PATH,
              IP6TABLES_PATH);

VIR_ENUM_DECL(virFirewallLayerFirewallD)
VIR_ENUM_IMPL(virFirewallLayerFirewallD, VIR_FIREWALL_LAYER_LAST,
              "eb", "ipv4", "ipv6")


struct _virFirewallRule {
    virFirewallLayer layer;

    virFirewallQueryCallback queryCB;
    void *queryOpaque;
    bool ignoreErrors;

    size_t argsAlloc;
    size_t argsLen;
    char **args;
};

struct _virFirewallGroup {
    unsigned int actionFlags;
    unsigned int rollbackFlags;

    size_t naction;
    virFirewallRulePtr *action;

    size_t nrollback;
    virFirewallRulePtr *rollback;

    bool addingRollback;
};


struct _virFirewall {
    int err;

    size_t ngroups;
    virFirewallGroupPtr *groups;
    size_t currentGroup;
};

static virFirewallBackend currentBackend = VIR_FIREWALL_BACKEND_AUTOMATIC;
static virMutex ruleLock = VIR_MUTEX_INITIALIZER;

static int
virFirewallValidateBackend(virFirewallBackend backend);

static int
virFirewallOnceInit(void)
{
    return virFirewallValidateBackend(currentBackend);
}

VIR_ONCE_GLOBAL_INIT(virFirewall)

static int
virFirewallValidateBackend(virFirewallBackend backend)
{
    VIR_DEBUG("Validating backend %d", backend);
#if WITH_DBUS
    if (backend == VIR_FIREWALL_BACKEND_AUTOMATIC ||
        backend == VIR_FIREWALL_BACKEND_FIREWALLD) {
        int rv = virDBusIsServiceRegistered(VIR_FIREWALL_FIREWALLD_SERVICE);

        VIR_DEBUG("Firewalld is registered ? %d", rv);
        if (rv < 0) {
            if (rv == -2) {
                if (backend == VIR_FIREWALL_BACKEND_FIREWALLD) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("firewalld firewall backend requested, but service is not running"));
                    return -1;
                } else {
                    VIR_DEBUG("firewalld service not running, trying direct backend");
                    backend = VIR_FIREWALL_BACKEND_DIRECT;
                }
            } else {
                return -1;
            }
        } else {
            VIR_DEBUG("firewalld service running, using firewalld backend");
            backend = VIR_FIREWALL_BACKEND_FIREWALLD;
        }
    }
#else
    if (backend == VIR_FIREWALL_BACKEND_AUTOMATIC) {
        VIR_DEBUG("DBus support disabled, trying direct backend");
        backend = VIR_FIREWALL_BACKEND_DIRECT;
    } else if (backend == VIR_FIREWALL_BACKEND_FIREWALLD) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("firewalld firewall backend requested, but DBus support disabled"));
        return -1;
    }
#endif

    if (backend == VIR_FIREWALL_BACKEND_DIRECT) {
        const char *commands[] = {
            IPTABLES_PATH, IP6TABLES_PATH, EBTABLES_PATH
        };
        size_t i;

        for (i = 0; i < ARRAY_CARDINALITY(commands); i++) {
            if (!virFileIsExecutable(commands[i])) {
                virReportSystemError(errno,
                                     _("direct firewall backend requested, but %s is not available"),
                                     commands[i]);
                return -1;
            }
        }
        VIR_DEBUG("found iptables/ip6tables/ebtables, using direct backend");
    }

    currentBackend = backend;
    return 0;
}

int
virFirewallSetBackend(virFirewallBackend backend)
{
    currentBackend = backend;

    if (virFirewallInitialize() < 0)
        return -1;

    return virFirewallValidateBackend(backend);
}

static virFirewallGroupPtr
virFirewallGroupNew(void)
{
    virFirewallGroupPtr group;

    if (VIR_ALLOC(group) < 0)
        return NULL;

    return group;
}


/**
 * virFirewallNew:
 *
 * Creates a new firewall ruleset for changing rules
 * of @layer. This should be followed by a call to
 * virFirewallStartTransaction before adding
 * any rules
 *
 * Returns the new firewall ruleset
 */
virFirewallPtr virFirewallNew(void)
{
    virFirewallPtr firewall;

    if (VIR_ALLOC(firewall) < 0)
        return NULL;

    return firewall;
}


static void
virFirewallRuleFree(virFirewallRulePtr rule)
{
    size_t i;

    if (!rule)
        return;

    for (i = 0; i < rule->argsLen; i++)
        VIR_FREE(rule->args[i]);
    VIR_FREE(rule->args);
    VIR_FREE(rule);
}


static void
virFirewallGroupFree(virFirewallGroupPtr group)
{
    size_t i;

    if (!group)
        return;

    for (i = 0; i < group->naction; i++)
        virFirewallRuleFree(group->action[i]);
    VIR_FREE(group->action);

    for (i = 0; i < group->nrollback; i++)
        virFirewallRuleFree(group->rollback[i]);
    VIR_FREE(group->rollback);

    VIR_FREE(group);
}


/**
 * virFirewallFree:
 *
 * Release all memory associated with the firewall
 * ruleset
 */
void virFirewallFree(virFirewallPtr firewall)
{
    size_t i;

    if (!firewall)
        return;

    for (i = 0; i < firewall->ngroups; i++)
        virFirewallGroupFree(firewall->groups[i]);
    VIR_FREE(firewall->groups);

    VIR_FREE(firewall);
}

#define VIR_FIREWALL_RETURN_IF_ERROR(firewall)              \
    do {                                                    \
        if (!firewall || firewall->err)                     \
            return;                                         \
    } while (0)

#define VIR_FIREWALL_RULE_RETURN_IF_ERROR(firewall, rule)\
    do {                                                    \
        if (!firewall || firewall->err || !rule)            \
            return;                                         \
    } while (0)

#define VIR_FIREWALL_RETURN_NULL_IF_ERROR(firewall)         \
    do {                                                    \
        if (!firewall || firewall->err)                     \
            return NULL;                                    \
    } while (0)

#define ADD_ARG(rule, str)                                  \
    do {                                                    \
        if (VIR_RESIZE_N(rule->args,                        \
                         rule->argsAlloc,                   \
                         rule->argsLen, 1) < 0)             \
            goto no_memory;                                 \
                                                            \
        if (VIR_STRDUP(rule->args[rule->argsLen++], str) < 0) \
            goto no_memory;                                 \
    } while (0)

static virFirewallRulePtr
virFirewallAddRuleFullV(virFirewallPtr firewall,
                        virFirewallLayer layer,
                        bool ignoreErrors,
                        virFirewallQueryCallback cb,
                        void *opaque,
                        va_list args)
{
    virFirewallGroupPtr group;
    virFirewallRulePtr rule;
    char *str;

    VIR_FIREWALL_RETURN_NULL_IF_ERROR(firewall);

    if (firewall->ngroups == 0) {
P
Pavel Hrdina 已提交
310
        firewall->err = EINVAL;
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 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 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 560 561 562 563 564 565 566 567 568 569 570 571 572 573 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
        return NULL;
    }
    group = firewall->groups[firewall->currentGroup];


    if (VIR_ALLOC(rule) < 0)
        goto no_memory;

    rule->layer = layer;
    rule->queryCB = cb;
    rule->queryOpaque = opaque;
    rule->ignoreErrors = ignoreErrors;

    while ((str = va_arg(args, char *)) != NULL) {
        ADD_ARG(rule, str);
    }

    if (group->addingRollback) {
        if (VIR_APPEND_ELEMENT_COPY(group->rollback,
                                    group->nrollback,
                                    rule) < 0)
            goto no_memory;
    } else {
        if (VIR_APPEND_ELEMENT_COPY(group->action,
                                    group->naction,
                                    rule) < 0)
            goto no_memory;
    }


    return rule;

 no_memory:
    firewall->err = ENOMEM;
    virFirewallRuleFree(rule);
    return NULL;
}

/**
 * virFirewallAddRule:
 * @firewall: firewall ruleset to add to
 * @layer: the firewall layer to change
 * @...: NULL terminated list of strings for the rule
 *
 * Add any type of rule to the firewall ruleset.
 *
 * Returns the new rule
 */
virFirewallRulePtr
virFirewallAddRule(virFirewallPtr firewall,
                   virFirewallLayer layer,
                   ...)
{
    virFirewallRulePtr rule;
    va_list args;
    va_start(args, layer);
    rule = virFirewallAddRuleFullV(firewall, layer, false, NULL, NULL, args);
    va_end(args);
    return rule;
}


/**
 * virFirewallAddRuleFull:
 * @firewall: firewall ruleset to add to
 * @layer: the firewall layer to change
 * @ignoreErrors: true to ignore failure of the command
 * @cb: callback to invoke with result of query
 * @opaque: data passed into @cb
 * @...: NULL terminated list of strings for the rule
 *
 * Add any type of rule to the firewall ruleset. Any output
 * generated by the addition will be fed into the query
 * callback @cb. This callback is permitted to create new
 * rules by invoking the virFirewallAddRule method, but
 * is not permitted to start new transactions.
 *
 * If @ignoreErrors is set to TRUE, then any failure of
 * the command is ignored. If it is set to FALSE, then
 * the behaviour upon failure is determined by the flags
 * set when the transaction was started.
 *
 * Returns the new rule
 */
virFirewallRulePtr virFirewallAddRuleFull(virFirewallPtr firewall,
                                          virFirewallLayer layer,
                                          bool ignoreErrors,
                                          virFirewallQueryCallback cb,
                                          void *opaque,
                                          ...)
{
    virFirewallRulePtr rule;
    va_list args;
    va_start(args, opaque);
    rule = virFirewallAddRuleFullV(firewall, layer, ignoreErrors, cb, opaque, args);
    va_end(args);
    return rule;
}


/**
 * virFirewallRemoveRule:
 * @firewall: firewall ruleset to remove from
 * @rule: the rule to remove
 *
 * Remove a rule from the current transaction
 */
void virFirewallRemoveRule(virFirewallPtr firewall,
                           virFirewallRulePtr rule)
{
    size_t i;
    virFirewallGroupPtr group;

    /* Explicitly not checking firewall->err too,
     * because if rule was partially created
     * before hitting error we must still remove
     * it to avoid leaking 'rule'
     */
    if (!firewall)
        return;

    if (firewall->ngroups == 0)
        return;
    group = firewall->groups[firewall->currentGroup];

    if (group->addingRollback) {
        for (i = 0; i < group->nrollback; i++) {
            if (group->rollback[i] == rule) {
                VIR_DELETE_ELEMENT(group->rollback,
                                   i,
                                   group->nrollback);
                virFirewallRuleFree(rule);
                break;
            }
        }
    } else {
        for (i = 0; i < group->naction; i++) {
            if (group->action[i] == rule) {
                VIR_DELETE_ELEMENT(group->action,
                                   i,
                                   group->naction);
                virFirewallRuleFree(rule);
                return;
            }
        }
    }
}


void virFirewallRuleAddArg(virFirewallPtr firewall,
                           virFirewallRulePtr rule,
                           const char *arg)
{
    VIR_FIREWALL_RULE_RETURN_IF_ERROR(firewall, rule);

    ADD_ARG(rule, arg);

    return;

 no_memory:
    firewall->err = ENOMEM;
}


void virFirewallRuleAddArgFormat(virFirewallPtr firewall,
                                 virFirewallRulePtr rule,
                                 const char *fmt, ...)
{
    char *arg;
    va_list list;

    VIR_FIREWALL_RULE_RETURN_IF_ERROR(firewall, rule);

    va_start(list, fmt);

    if (virVasprintf(&arg, fmt, list) < 0)
        goto no_memory;

    ADD_ARG(rule, arg);

    va_end(list);

    VIR_FREE(arg);
    return;

 no_memory:
    firewall->err = ENOMEM;
    va_end(list);
    VIR_FREE(arg);
}


void virFirewallRuleAddArgSet(virFirewallPtr firewall,
                              virFirewallRulePtr rule,
                              const char *const *args)
{
    VIR_FIREWALL_RULE_RETURN_IF_ERROR(firewall, rule);

    while (*args) {
        ADD_ARG(rule, *args);
        args++;
    }

    return;

 no_memory:
    firewall->err = ENOMEM;
}


void virFirewallRuleAddArgList(virFirewallPtr firewall,
                               virFirewallRulePtr rule,
                               ...)
{
    va_list list;
    const char *str;

    VIR_FIREWALL_RULE_RETURN_IF_ERROR(firewall, rule);

    va_start(list, rule);

    while ((str = va_arg(list, char *)) != NULL) {
        ADD_ARG(rule, str);
    }

    va_end(list);

    return;

 no_memory:
    firewall->err = ENOMEM;
    va_end(list);
}


size_t virFirewallRuleGetArgCount(virFirewallRulePtr rule)
{
    if (!rule)
        return 0;
    return rule->argsLen;
}


/**
 * virFirewallStartTransaction:
 * @firewall: the firewall ruleset
 * @flags: bitset of virFirewallTransactionFlags
 *
 * Start a new transaction with associated rollback
 * block.
 *
 * Should be followed by calls to add various rules to
 * the transaction. Then virFirwallStartRollback should
 * be used to provide rules to rollback upon transaction
 * failure
 */
void virFirewallStartTransaction(virFirewallPtr firewall,
                                 unsigned int flags)
{
    virFirewallGroupPtr group;

    VIR_FIREWALL_RETURN_IF_ERROR(firewall);

    if (!(group = virFirewallGroupNew())) {
        firewall->err = ENOMEM;
        return;
    }
    group->actionFlags = flags;

    if (VIR_EXPAND_N(firewall->groups,
                     firewall->ngroups, 1) < 0) {
        firewall->err = ENOMEM;
        virFirewallGroupFree(group);
        return;
    }
    firewall->groups[firewall->ngroups - 1] = group;
    firewall->currentGroup = firewall->ngroups - 1;
}

/**
 * virFirewallBeginRollback:
 * @firewall: the firewall ruleset
 * @flags: bitset of virFirewallRollbackFlags
 *
 * Mark the beginning of a set of rules able to rollback
 * changes in this and all earlier transactions.
 *
 * Should be followed by calls to add various rules needed
 * to rollback state. Then virFirewallStartTransaction
 * should be used to indicate the beginning of the next
 * transactional ruleset.
 */
void virFirewallStartRollback(virFirewallPtr firewall,
                              unsigned int flags)
{
    virFirewallGroupPtr group;

    VIR_FIREWALL_RETURN_IF_ERROR(firewall);

    if (firewall->ngroups == 0) {
P
Pavel Hrdina 已提交
611
        firewall->err = EINVAL;
612 613 614 615 616 617 618 619 620 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 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 718 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 831 832 833 834 835 836 837 838 839 840 841 842 843 844 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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
        return;
    }

    group = firewall->groups[firewall->ngroups-1];
    group->rollbackFlags = flags;
    group->addingRollback = true;
}


static char *
virFirewallRuleToString(virFirewallRulePtr rule)
{
    const char *bin = virFirewallLayerCommandTypeToString(rule->layer);
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    size_t i;

    virBufferAdd(&buf, bin, -1);
    for (i = 0; i < rule->argsLen; i++) {
        virBufferAddLit(&buf, " ");
        virBufferAdd(&buf, rule->args[i], -1);
    }

    return virBufferContentAndReset(&buf);
}

static int
virFirewallApplyRuleDirect(virFirewallRulePtr rule,
                           bool ignoreErrors,
                           char **output)
{
    size_t i;
    const char *bin = virFirewallLayerCommandTypeToString(rule->layer);
    virCommandPtr cmd = NULL;
    int status;
    int ret = -1;
    char *error = NULL;

    if (!bin) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown firewall layer %d"),
                       rule->layer);
        goto cleanup;
    }

    cmd = virCommandNewArgList(bin, NULL);

    for (i = 0; i < rule->argsLen; i++)
        virCommandAddArg(cmd, rule->args[i]);

    virCommandSetOutputBuffer(cmd, output);
    virCommandSetErrorBuffer(cmd, &error);

    if (virCommandRun(cmd, &status) < 0)
        goto cleanup;

    if (status != 0) {
        if (ignoreErrors) {
            VIR_DEBUG("Ignoring error running command");
        } else {
            char *args = virCommandToString(cmd);
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Failed to apply firewall rules %s: %s"),
                           NULLSTR(args), NULLSTR(error));
            VIR_FREE(args);
            VIR_FREE(*output);
            goto cleanup;
        }
    }

    ret = 0;
 cleanup:
    VIR_FREE(error);
    virCommandFree(cmd);
    return ret;
}


#ifdef WITH_DBUS
static int
virFirewallApplyRuleFirewallD(virFirewallRulePtr rule,
                              bool ignoreErrors,
                              char **output)
{
    const char *ipv = virFirewallLayerFirewallDTypeToString(rule->layer);
    DBusConnection *sysbus = virDBusGetSystemBus();
    DBusMessage *reply = NULL;
    DBusError error;
    int ret = -1;

    if (!sysbus)
        return -1;

    dbus_error_init(&error);

    if (!ipv) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unknown firewall layer %d"),
                       rule->layer);
        goto cleanup;
    }

    if (virDBusCallMethod(sysbus,
                          &reply,
                          &error,
                          VIR_FIREWALL_FIREWALLD_SERVICE,
                          "/org/fedoraproject/FirewallD1",
                          "org.fedoraproject.FirewallD1.direct",
                          "passthrough",
                          "sa&s",
                          ipv,
                          (int)rule->argsLen,
                          rule->args) < 0)
        goto cleanup;

    if (dbus_error_is_set(&error)) {
        /*
         * As of firewalld-0.3.9.3-1.fc20.noarch the name and
         * message fields in the error look like
         *
         *    name="org.freedesktop.DBus.Python.dbus.exceptions.DBusException"
         * message="COMMAND_FAILED: '/sbin/iptables --table filter --delete
         *          INPUT --in-interface virbr0 --protocol udp --destination-port 53
         *          --jump ACCEPT' failed: iptables: Bad rule (does a matching rule
         *          exist in that chain?)."
         *
         * We'd like to only ignore DBus errors precisely related to the failure
         * of iptables/ebtables commands. A well designed DBus interface would
         * return specific named exceptions not the top level generic python dbus
         * exception name. With this current scheme our only option is todo a
         * sub-string match for 'COMMAND_FAILED' on the message. eg like
         *
         * if (ignoreErrors &&
         *     STREQ(error.name,
         *           "org.freedesktop.DBus.Python.dbus.exceptions.DBusException") &&
         *     STRPREFIX(error.message, "COMMAND_FAILED"))
         *    ...
         *
         * But this risks our error detecting code being broken if firewalld changes
         * ever alter the message string, so we're avoiding doing that.
         */
        if (ignoreErrors) {
            VIR_DEBUG("Ignoring error '%s': '%s'",
                      error.name, error.message);
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to apply rule '%s'"),
                           error.message);
            goto cleanup;
        }
    } else {
        if (virDBusMessageRead(reply, "s", output) < 0)
            goto cleanup;
    }

    ret = 0;

 cleanup:
    dbus_error_free(&error);
    if (reply)
        dbus_message_unref(reply);
    return ret;
}
#endif

static int
virFirewallApplyRule(virFirewallPtr firewall,
                     virFirewallRulePtr rule,
                     bool ignoreErrors)
{
    char *output = NULL;
    char **lines = NULL;
    int ret = -1;
    char *str = virFirewallRuleToString(rule);
    VIR_INFO("Applying rule '%s'", NULLSTR(str));
    VIR_FREE(str);

    if (rule->ignoreErrors)
        ignoreErrors = rule->ignoreErrors;

    switch (currentBackend) {
    case VIR_FIREWALL_BACKEND_DIRECT:
        if (virFirewallApplyRuleDirect(rule, ignoreErrors, &output) < 0)
            return -1;
        break;
#if WITH_DBUS
    case VIR_FIREWALL_BACKEND_FIREWALLD:
        if (virFirewallApplyRuleFirewallD(rule, ignoreErrors, &output) < 0)
            return -1;
        break;
#endif
    default:
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unexpected firewall engine backend"));
        return -1;
    }

    if (rule->queryCB && output) {
        if (!(lines = virStringSplit(output, "\n", -1)))
            goto cleanup;

        VIR_DEBUG("Invoking query %p with '%s'", rule->queryCB, output);
        if (rule->queryCB(firewall, (const char *const *)lines, rule->queryOpaque) < 0)
            goto cleanup;

        if (firewall->err == ENOMEM) {
            virReportOOMError();
            goto cleanup;
        }
        if (firewall->err) {
            virReportSystemError(firewall->err, "%s",
                                 _("Unable to create rule"));
            goto cleanup;
        }

    }

    ret = 0;
 cleanup:
    virStringFreeList(lines);
    VIR_FREE(output);
    return ret;
}

static int
virFirewallApplyGroup(virFirewallPtr firewall,
                      size_t idx)
{
    virFirewallGroupPtr group = firewall->groups[idx];
    bool ignoreErrors = (group->actionFlags & VIR_FIREWALL_TRANSACTION_IGNORE_ERRORS);
    size_t i;

    VIR_INFO("Starting transaction for %p flags=%x",
             group, group->actionFlags);
    firewall->currentGroup = idx;
    group->addingRollback = false;
    for (i = 0; i < group->naction; i++) {
        if (virFirewallApplyRule(firewall,
                                 group->action[i],
                                 ignoreErrors) < 0)
            return -1;
    }
    return 0;
}


static void
virFirewallRollbackGroup(virFirewallPtr firewall,
                         size_t idx)
{
    virFirewallGroupPtr group = firewall->groups[idx];
    size_t i;

    VIR_INFO("Starting rollback for group %p", group);
    firewall->currentGroup = idx;
    group->addingRollback = true;
    for (i = 0; i < group->nrollback; i++) {
        ignore_value(virFirewallApplyRule(firewall,
                                          group->rollback[i],
                                          true));
    }
}


int
virFirewallApply(virFirewallPtr firewall)
{
    size_t i, j;
    int ret = -1;

    virMutexLock(&ruleLock);
    if (virFirewallInitialize() < 0)
        goto cleanup;

    if (!firewall || firewall->err == ENOMEM) {
        virReportOOMError();
        goto cleanup;
    }
    if (firewall->err) {
        virReportSystemError(firewall->err, "%s",
                             _("Unable to create rule"));
        goto cleanup;
    }

    VIR_DEBUG("Applying groups for %p", firewall);
    for (i = 0; i < firewall->ngroups; i++) {
        if (virFirewallApplyGroup(firewall, i) < 0) {
            VIR_DEBUG("Rolling back groups upto %zu for %p", i, firewall);
            size_t first = i;
            virErrorPtr saved_error = virSaveLastError();

            /*
             * Look at any inheritance markers to figure out
             * what the first rollback group we need to apply is
             */
            for (j = 0; j < i; j++) {
                VIR_DEBUG("Checking inheritance of group %zu", i - j);
                if (firewall->groups[i - j]->rollbackFlags &
                    VIR_FIREWALL_ROLLBACK_INHERIT_PREVIOUS)
                    first = (i - j) - 1;
            }
            /*
             * Now apply all rollback groups in order
             */
            for (j = first; j <= i; j++) {
                VIR_DEBUG("Rolling back group %zu", j);
                virFirewallRollbackGroup(firewall, j);
            }

            virSetError(saved_error);
            virFreeError(saved_error);
            VIR_DEBUG("Done rolling back groups for %p", firewall);
            goto cleanup;
        }
    }
    VIR_DEBUG("Done applying groups for %p", firewall);

    ret = 0;
 cleanup:
    virMutexUnlock(&ruleLock);
    return ret;
}