bridge_driver.c 102.7 KB
Newer Older
1
/*
2
 * bridge_driver.c: core driver methods for managing network
3
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2006-2011 Red Hat, Inc.
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
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/utsname.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
#include <pwd.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/ioctl.h>

46
#include "virterror_internal.h"
47
#include "datatypes.h"
48
#include "bridge_driver.h"
49 50 51
#include "network_conf.h"
#include "driver.h"
#include "buf.h"
52
#include "virpidfile.h"
53
#include "util.h"
54
#include "command.h"
55 56 57 58
#include "memory.h"
#include "uuid.h"
#include "iptables.h"
#include "bridge.h"
59
#include "interface.h"
60
#include "logging.h"
61
#include "dnsmasq.h"
62
#include "util/network.h"
63
#include "configmake.h"
64
#include "ignore-value.h"
65

66 67
#define NETWORK_PID_DIR LOCALSTATEDIR "/run/libvirt/network"
#define NETWORK_STATE_DIR LOCALSTATEDIR "/lib/libvirt/network"
68

69
#define DNSMASQ_STATE_DIR LOCALSTATEDIR "/lib/libvirt/dnsmasq"
70
#define RADVD_STATE_DIR LOCALSTATEDIR "/lib/libvirt/radvd"
71

72 73
#define VIR_FROM_THIS VIR_FROM_NETWORK

74
#define networkReportError(code, ...)                                   \
75
    virReportErrorHelper(VIR_FROM_NETWORK, code, __FILE__,              \
76
                         __FUNCTION__, __LINE__, __VA_ARGS__)
77

78 79
/* Main driver state */
struct network_driver {
80
    virMutex lock;
81

82
    virNetworkObjList networks;
83 84 85 86 87 88 89 90

    iptablesContext *iptables;
    brControl *brctl;
    char *networkConfigDir;
    char *networkAutostartDir;
    char *logDir;
};

91 92 93

static void networkDriverLock(struct network_driver *driver)
{
94
    virMutexLock(&driver->lock);
95 96 97
}
static void networkDriverUnlock(struct network_driver *driver)
{
98
    virMutexUnlock(&driver->lock);
99 100
}

101 102
static int networkShutdown(void);

103 104 105 106 107 108 109
static int networkStartNetwork(struct network_driver *driver,
                               virNetworkObjPtr network);

static int networkShutdownNetwork(struct network_driver *driver,
                                  virNetworkObjPtr network);

static int networkStartNetworkVirtual(struct network_driver *driver,
110
                                     virNetworkObjPtr network);
111

112 113 114 115 116 117 118
static int networkShutdownNetworkVirtual(struct network_driver *driver,
                                        virNetworkObjPtr network);

static int networkStartNetworkExternal(struct network_driver *driver,
                                     virNetworkObjPtr network);

static int networkShutdownNetworkExternal(struct network_driver *driver,
119
                                        virNetworkObjPtr network);
120

121 122
static void networkReloadIptablesRules(struct network_driver *driver);

123 124
static struct network_driver *driverState = NULL;

125
static char *
126
networkDnsmasqLeaseFileNameDefault(const char *netname)
127 128 129
{
    char *leasefile;

130 131
    ignore_value(virAsprintf(&leasefile, DNSMASQ_STATE_DIR "/%s.leases",
                             netname));
132 133 134
    return leasefile;
}

135 136 137
networkDnsmasqLeaseFileNameFunc networkDnsmasqLeaseFileName =
    networkDnsmasqLeaseFileNameDefault;

138 139 140 141 142 143
static char *
networkRadvdPidfileBasename(const char *netname)
{
    /* this is simple but we want to be sure it's consistently done */
    char *pidfilebase;

144
    ignore_value(virAsprintf(&pidfilebase, "%s-radvd", netname));
145 146 147 148 149 150 151 152
    return pidfilebase;
}

static char *
networkRadvdConfigFileName(const char *netname)
{
    char *configfile;

153 154
    ignore_value(virAsprintf(&configfile, RADVD_STATE_DIR "/%s-radvd.conf",
                             netname));
155 156
    return configfile;
}
157

158 159 160
static char *
networkBridgeDummyNicName(const char *brname)
{
161
    static const char dummyNicSuffix[] = "-nic";
162 163
    char *nicname;

164 165 166 167 168 169 170
    if (strlen(brname) + sizeof(dummyNicSuffix) > IFNAMSIZ) {
        /* because the length of an ifname is limited to IFNAMSIZ-1
         * (usually 15), and we're adding 4 more characters, we must
         * truncate the original name to 11 to fit. In order to catch
         * a possible numeric ending (eg virbr0, virbr1, etc), we grab
         * the first 8 and last 3 characters of the string.
         */
171 172 173 174 175
        ignore_value(virAsprintf(&nicname, "%.*s%s%s",
                                 /* space for last 3 chars + "-nic" + NULL */
                                 (int)(IFNAMSIZ - (3 + sizeof(dummyNicSuffix))),
                                 brname, brname + strlen(brname) - 3,
                                 dummyNicSuffix));
176
    } else {
177
        ignore_value(virAsprintf(&nicname, "%s%s", brname, dummyNicSuffix));
178
    }
179 180 181
    return nicname;
}

182 183 184 185 186 187 188 189 190 191 192
static void
networkFindActiveConfigs(struct network_driver *driver) {
    unsigned int i;

    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjPtr obj = driver->networks.objs[i];
        virNetworkDefPtr tmp;
        char *config;

        virNetworkObjLock(obj);

193
        if ((config = virNetworkConfigFile(NETWORK_STATE_DIR,
194 195 196 197 198 199 200 201 202 203 204 205
                                           obj->def->name)) == NULL) {
            virNetworkObjUnlock(obj);
            continue;
        }

        if (access(config, R_OK) < 0) {
            VIR_FREE(config);
            virNetworkObjUnlock(obj);
            continue;
        }

        /* Try and load the live config */
206
        tmp = virNetworkDefParseFile(config);
207 208 209 210 211 212 213 214 215 216 217
        VIR_FREE(config);
        if (tmp) {
            obj->newDef = obj->def;
            obj->def = tmp;
        }

        /* If bridge exists, then mark it active */
        if (obj->def->bridge &&
            brHasBridge(driver->brctl, obj->def->bridge) == 0) {
            obj->active = 1;

218 219
            /* Try and read dnsmasq/radvd pids if any */
            if (obj->def->ips && (obj->def->nips > 0)) {
220 221 222 223
                char *radvdpidbase;

                ignore_value(virPidFileReadIfAlive(NETWORK_PID_DIR, obj->def->name,
                                                   &obj->dnsmasqPid, DNSMASQ));
224

225
                if (!(radvdpidbase = networkRadvdPidfileBasename(obj->def->name))) {
226
                    virReportOOMError();
227 228
                    goto cleanup;
                }
229 230
                ignore_value(virPidFileReadIfAlive(NETWORK_PID_DIR, radvdpidbase,
                                                   &obj->radvdPid, RADVD));
231
                VIR_FREE(radvdpidbase);
232 233 234
            }
        }

235
    cleanup:
236 237 238 239 240
        virNetworkObjUnlock(obj);
    }
}


241 242 243
static void
networkAutostartConfigs(struct network_driver *driver) {
    unsigned int i;
244

245
    for (i = 0 ; i < driver->networks.count ; i++) {
246
        virNetworkObjLock(driver->networks.objs[i]);
247
        if (driver->networks.objs[i]->autostart &&
248 249
            !virNetworkObjIsActive(driver->networks.objs[i])) {
            if (networkStartNetwork(driver, driver->networks.objs[i]) < 0) {
250
            /* failed to start but already logged */
251
            }
252
        }
253
        virNetworkObjUnlock(driver->networks.objs[i]);
254 255 256 257 258 259 260 261 262
    }
}

/**
 * networkStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
263
networkStartup(int privileged) {
264 265
    uid_t uid = geteuid();
    char *base = NULL;
266
    int err;
267 268

    if (VIR_ALLOC(driverState) < 0)
269
        goto error;
270

271 272 273 274
    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        goto error;
    }
275 276
    networkDriverLock(driverState);

277
    if (privileged) {
278
        if (virAsprintf(&driverState->logDir,
279
                        "%s/log/libvirt/qemu", LOCALSTATEDIR) == -1)
280 281
            goto out_of_memory;

282
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
283 284
            goto out_of_memory;
    } else {
285
        char *userdir = virGetUserDirectory(uid);
286 287 288

        if (!userdir)
            goto error;
289

290
        if (virAsprintf(&driverState->logDir,
291 292
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
293
            goto out_of_memory;
294
        }
295

296 297
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
298 299
            goto out_of_memory;
        }
300
        VIR_FREE(userdir);
301 302 303 304 305
    }

    /* Configuration paths are either ~/.libvirt/qemu/... (session) or
     * /etc/libvirt/qemu/... (system).
     */
306
    if (virAsprintf(&driverState->networkConfigDir, "%s/qemu/networks", base) == -1)
307 308
        goto out_of_memory;

309 310
    if (virAsprintf(&driverState->networkAutostartDir, "%s/qemu/networks/autostart",
                    base) == -1)
311 312 313 314
        goto out_of_memory;

    VIR_FREE(base);

315
    if ((err = brInit(&driverState->brctl))) {
316
        virReportSystemError(err, "%s",
317 318 319 320 321
                             _("cannot initialize bridge support"));
        goto error;
    }

    if (!(driverState->iptables = iptablesContextNew())) {
322
        goto out_of_memory;
323 324 325
    }


326
    if (virNetworkLoadAllConfigs(&driverState->networks,
327
                                 driverState->networkConfigDir,
328 329 330
                                 driverState->networkAutostartDir) < 0)
        goto error;

331
    networkFindActiveConfigs(driverState);
332
    networkReloadIptablesRules(driverState);
333 334
    networkAutostartConfigs(driverState);

335 336
    networkDriverUnlock(driverState);

337 338
    return 0;

339
out_of_memory:
340
    virReportOOMError();
341 342

error:
343 344 345
    if (driverState)
        networkDriverUnlock(driverState);

346
    VIR_FREE(base);
347
    networkShutdown();
348 349 350 351 352 353 354 355 356 357 358
    return -1;
}

/**
 * networkReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
networkReload(void) {
359 360 361
    if (!driverState)
        return 0;

362
    networkDriverLock(driverState);
363
    virNetworkLoadAllConfigs(&driverState->networks,
364 365
                             driverState->networkConfigDir,
                             driverState->networkAutostartDir);
366
    networkReloadIptablesRules(driverState);
367
    networkAutostartConfigs(driverState);
368
    networkDriverUnlock(driverState);
369 370 371 372 373 374 375 376 377 378 379 380 381
    return 0;
}

/**
 * networkActive:
 *
 * Checks if the QEmu daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
networkActive(void) {
382
    unsigned int i;
383
    int active = 0;
384

385 386 387
    if (!driverState)
        return 0;

388
    networkDriverLock(driverState);
389 390
    for (i = 0 ; i < driverState->networks.count ; i++) {
        virNetworkObjPtr net = driverState->networks.objs[i];
391
        virNetworkObjLock(net);
D
Daniel P. Berrange 已提交
392
        if (virNetworkObjIsActive(net))
393
            active = 1;
394
        virNetworkObjUnlock(net);
395
    }
396
    networkDriverUnlock(driverState);
397
    return active;
398 399 400 401 402 403 404 405 406 407 408 409
}

/**
 * networkShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
networkShutdown(void) {
    if (!driverState)
        return -1;

410 411
    networkDriverLock(driverState);

412
    /* free inactive networks */
413
    virNetworkObjListFree(&driverState->networks);
414 415 416 417 418 419 420 421 422 423

    VIR_FREE(driverState->logDir);
    VIR_FREE(driverState->networkConfigDir);
    VIR_FREE(driverState->networkAutostartDir);

    if (driverState->brctl)
        brShutdown(driverState->brctl);
    if (driverState->iptables)
        iptablesContextFree(driverState->iptables);

424
    networkDriverUnlock(driverState);
425
    virMutexDestroy(&driverState->lock);
426

427 428 429 430 431 432
    VIR_FREE(driverState);

    return 0;
}


433 434 435 436
static int
networkBuildDnsmasqHostsfile(dnsmasqContext *dctx,
                             virNetworkIpDefPtr ipdef,
                             virNetworkDNSDefPtr dnsdef)
437
{
438
    unsigned int i, j;
439

440 441 442
    for (i = 0; i < ipdef->nhosts; i++) {
        virNetworkDHCPHostDefPtr host = &(ipdef->hosts[i]);
        if ((host->mac) && VIR_SOCKET_HAS_ADDR(&host->ip))
443 444
            if (dnsmasqAddDhcpHost(dctx, host->mac, &host->ip, host->name) < 0)
                return -1;
445
    }
446

447 448 449 450 451
    if (dnsdef) {
        for (i = 0; i < dnsdef->nhosts; i++) {
            virNetworkDNSHostsDefPtr host = &(dnsdef->hosts[i]);
            if (VIR_SOCKET_HAS_ADDR(&host->ip)) {
                for (j = 0; j < host->nnames; j++)
452 453
                    if (dnsmasqAddHost(dctx, &host->ip, host->names[j]) < 0)
                        return -1;
454 455
            }
        }
456 457
    }

458
    return 0;
459 460 461
}


462
static int
463
networkBuildDnsmasqArgv(virNetworkObjPtr network,
464
                        virNetworkIpDefPtr ipdef,
465
                        const char *pidfile,
466 467 468
                        virCommandPtr cmd,
                        dnsmasqContext *dctx)
{
469
    int r, ret = -1;
470
    int nbleases = 0;
471 472
    int ii;
    virNetworkIpDefPtr tmpipdef;
473 474

    /*
475
     * NB, be careful about syntax for dnsmasq options in long format.
476 477 478 479 480 481 482 483 484 485 486 487 488
     *
     * If the flag has a mandatory argument, it can be given using
     * either syntax:
     *
     *     --foo bar
     *     --foo=bar
     *
     * If the flag has a optional argument, it *must* be given using
     * the syntax:
     *
     *     --foo=bar
     *
     * It is hard to determine whether a flag is optional or not,
489 490
     * without reading the dnsmasq source :-( The manpage is not
     * very explicit on this.
491
     */
492 493 494 495 496

    /*
     * Needed to ensure dnsmasq uses same algorithm for processing
     * multiple namedriver entries in /etc/resolv.conf as GLibC.
     */
497
    virCommandAddArgList(cmd, "--strict-order", "--bind-interfaces", NULL);
498

499 500
    if (network->def->domain)
        virCommandAddArgList(cmd, "--domain", network->def->domain, NULL);
501

502 503
    if (pidfile)
        virCommandAddArgPair(cmd, "--pid-file", pidfile);
504

505
    /* *no* conf file */
506
    virCommandAddArg(cmd, "--conf-file=");
507

508 509 510
    virCommandAddArgList(cmd,
                         "--except-interface", "lo",
                         NULL);
511

512 513
    /* If this is an isolated network, set the default route option
     * (3) to be empty to avoid setting a default route that's
514 515 516 517
     * guaranteed to not work, and set --no-resolv so that no dns
     * requests are forwarded on to the dns server listed in the
     * host's /etc/resolv.conf (since this could be used as a channel
     * to build a connection to the outside).
518
     */
519 520 521 522
    if (network->def->forwardType == VIR_NETWORK_FORWARD_NONE) {
        virCommandAddArgList(cmd, "--dhcp-option=3",
                             "--no-resolv", NULL);
    }
523

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    if (network->def->dns != NULL) {
        virNetworkDNSDefPtr dns = network->def->dns;
        int i;

        for (i = 0; i < dns->ntxtrecords; i++) {
            char *record = NULL;
            if (virAsprintf(&record, "%s,%s",
                            dns->txtrecords[i].name,
                            dns->txtrecords[i].value) < 0) {
                virReportOOMError();
                goto cleanup;
            }

            virCommandAddArgPair(cmd, "--txt-record", record);
            VIR_FREE(record);
        }
    }

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    /*
     * --interface does not actually work with dnsmasq < 2.47,
     * due to DAD for ipv6 addresses on the interface.
     *
     * virCommandAddArgList(cmd, "--interface", ipdef->bridge, NULL);
     *
     * So listen on all defined IPv[46] addresses
     */
    for (ii = 0;
         (tmpipdef = virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, ii));
         ii++) {
        char *ipaddr = virSocketFormatAddr(&tmpipdef->address);
        if (!ipaddr)
            goto cleanup;
        virCommandAddArgList(cmd, "--listen-address", ipaddr, NULL);
        VIR_FREE(ipaddr);
    }

560
    if (ipdef) {
561 562 563 564 565 566 567 568 569 570 571
        for (r = 0 ; r < ipdef->nranges ; r++) {
            char *saddr = virSocketFormatAddr(&ipdef->ranges[r].start);
            if (!saddr)
                goto cleanup;
            char *eaddr = virSocketFormatAddr(&ipdef->ranges[r].end);
            if (!eaddr) {
                VIR_FREE(saddr);
                goto cleanup;
            }
            virCommandAddArg(cmd, "--dhcp-range");
            virCommandAddArgFormat(cmd, "%s,%s", saddr, eaddr);
572
            VIR_FREE(saddr);
573 574 575
            VIR_FREE(eaddr);
            nbleases += virSocketGetRange(&ipdef->ranges[r].start,
                                          &ipdef->ranges[r].end);
576
        }
577

578 579 580 581 582 583 584 585 586 587 588 589 590
        /*
         * For static-only DHCP, i.e. with no range but at least one host element,
         * we have to add a special --dhcp-range option to enable the service in
         * dnsmasq.
         */
        if (!ipdef->nranges && ipdef->nhosts) {
            char *bridgeaddr = virSocketFormatAddr(&ipdef->address);
            if (!bridgeaddr)
                goto cleanup;
            virCommandAddArg(cmd, "--dhcp-range");
            virCommandAddArgFormat(cmd, "%s,static", bridgeaddr);
            VIR_FREE(bridgeaddr);
        }
591

592
        if (ipdef->nranges > 0) {
593 594 595 596 597
            char *leasefile = networkDnsmasqLeaseFileName(network->def->name);
            if (!leasefile)
                goto cleanup;
            virCommandAddArgFormat(cmd, "--dhcp-leasefile=%s", leasefile);
            VIR_FREE(leasefile);
598 599
            virCommandAddArgFormat(cmd, "--dhcp-lease-max=%d", nbleases);
        }
600

601 602
        if (ipdef->nranges || ipdef->nhosts)
            virCommandAddArg(cmd, "--dhcp-no-override");
603

604 605 606 607
        /* add domain to any non-qualified hostnames in /etc/hosts or addn-hosts */
        if (network->def->domain)
           virCommandAddArg(cmd, "--expand-hosts");

608 609 610 611 612 613 614 615 616
        if (networkBuildDnsmasqHostsfile(dctx, ipdef, network->def->dns) < 0)
            goto cleanup;

        if (dctx->hostsfile->nhosts)
            virCommandAddArgPair(cmd, "--dhcp-hostsfile",
                                 dctx->hostsfile->path);
        if (dctx->addnhostsfile->nhosts)
            virCommandAddArgPair(cmd, "--addn-hosts",
                                 dctx->addnhostsfile->path);
617

618 619 620 621 622 623 624 625 626
        if (ipdef->tftproot) {
            virCommandAddArgList(cmd, "--enable-tftp",
                                 "--tftp-root", ipdef->tftproot,
                                 NULL);
        }
        if (ipdef->bootfile) {
            virCommandAddArg(cmd, "--dhcp-boot");
            if (VIR_SOCKET_HAS_ADDR(&ipdef->bootserver)) {
                char *bootserver = virSocketFormatAddr(&ipdef->bootserver);
627

628 629 630 631 632 633 634 635
                if (!bootserver)
                    goto cleanup;
                virCommandAddArgFormat(cmd, "%s%s%s",
                                       ipdef->bootfile, ",,", bootserver);
                VIR_FREE(bootserver);
            } else {
                virCommandAddArg(cmd, ipdef->bootfile);
            }
636
        }
637 638
    }

639 640 641
    ret = 0;
cleanup:
    return ret;
642 643
}

644 645
int
networkBuildDhcpDaemonCommandLine(virNetworkObjPtr network, virCommandPtr *cmdout,
646
                                  char *pidfile, dnsmasqContext *dctx)
647
{
648
    virCommandPtr cmd = NULL;
649
    int ret = -1, ii;
650
    virNetworkIpDefPtr ipdef;
651 652

    network->dnsmasqPid = -1;
653

654 655 656 657 658 659 660
    /* Look for first IPv4 address that has dhcp defined. */
    /* We support dhcp config on 1 IPv4 interface only. */
    for (ii = 0;
         (ipdef = virNetworkDefGetIpByIndex(network->def, AF_INET, ii));
         ii++) {
        if (ipdef->nranges || ipdef->nhosts)
            break;
661
    }
662
    /* If no IPv4 addresses had dhcp info, pick the first (if there were any). */
663
    if (!ipdef)
664 665 666 667 668 669 670 671
        ipdef = virNetworkDefGetIpByIndex(network->def, AF_INET, 0);

    /* If there are no IP addresses at all (v4 or v6), return now, since
     * there won't be any address for dnsmasq to listen on anyway.
     * If there are any addresses, even if no dhcp ranges or static entries,
     * we should continue and run dnsmasq, just for the DNS capabilities.
     */
    if (!virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, 0))
672
        return 0;
673

674
    cmd = virCommandNew(DNSMASQ);
675
    if (networkBuildDnsmasqArgv(network, ipdef, pidfile, cmd, dctx) < 0) {
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
        goto cleanup;
    }

    if (cmdout)
        *cmdout = cmd;
    ret = 0;
cleanup:
    if (ret < 0)
        virCommandFree(cmd);
    return ret;
}

static int
networkStartDhcpDaemon(virNetworkObjPtr network)
{
    virCommandPtr cmd = NULL;
    char *pidfile = NULL;
    int ret = -1;
694
    dnsmasqContext *dctx = NULL;
695

696 697
    if (virFileMakePath(NETWORK_PID_DIR) < 0) {
        virReportSystemError(errno,
698 699
                             _("cannot create directory %s"),
                             NETWORK_PID_DIR);
700
        goto cleanup;
701
    }
702 703
    if (virFileMakePath(NETWORK_STATE_DIR) < 0) {
        virReportSystemError(errno,
704 705
                             _("cannot create directory %s"),
                             NETWORK_STATE_DIR);
706
        goto cleanup;
707 708
    }

709
    if (!(pidfile = virPidFileBuildPath(NETWORK_PID_DIR, network->def->name))) {
710
        virReportOOMError();
711
        goto cleanup;
712 713
    }

714 715
    if (virFileMakePath(DNSMASQ_STATE_DIR) < 0) {
        virReportSystemError(errno,
716 717 718 719 720
                             _("cannot create directory %s"),
                             DNSMASQ_STATE_DIR);
        goto cleanup;
    }

721 722 723 724 725 726 727 728 729 730
    dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
    if (dctx == NULL)
        goto cleanup;

    ret = networkBuildDhcpDaemonCommandLine(network, &cmd, pidfile, dctx);
    if (ret < 0)
        goto cleanup;

    ret = dnsmasqSave(dctx);
    if (ret < 0)
731
        goto cleanup;
732

G
Guido Günther 已提交
733 734
    ret = virCommandRun(cmd, NULL);
    if (ret < 0) {
735
        goto cleanup;
G
Guido Günther 已提交
736
    }
737 738

    /*
739 740 741 742 743
     * There really is no race here - when dnsmasq daemonizes, its
     * leader process stays around until its child has actually
     * written its pidfile. So by time virCommandRun exits it has
     * waitpid'd and guaranteed the proess has started and written a
     * pid
744 745
     */

746
    ret = virPidFileRead(NETWORK_PID_DIR, network->def->name,
747 748
                         &network->dnsmasqPid);
    if (ret < 0)
749
        goto cleanup;
750

751 752 753
    ret = 0;
cleanup:
    VIR_FREE(pidfile);
754
    virCommandFree(cmd);
755
    dnsmasqContextFree(dctx);
756 757 758
    return ret;
}

759 760 761 762 763 764 765 766 767
static int
networkStartRadvd(virNetworkObjPtr network)
{
    char *pidfile = NULL;
    char *radvdpidbase = NULL;
    virBuffer configbuf = VIR_BUFFER_INITIALIZER;;
    char *configstr = NULL;
    char *configfile = NULL;
    virCommandPtr cmd = NULL;
768
    int ret = -1, ii;
769 770 771 772
    virNetworkIpDefPtr ipdef;

    network->radvdPid = -1;

E
Eric Blake 已提交
773
    if (!virFileIsExecutable(RADVD)) {
774 775 776 777 778 779 780
        virReportSystemError(errno,
                             _("Cannot find %s - "
                               "Possibly the package isn't installed"),
                             RADVD);
        goto cleanup;
    }

781 782
    if (virFileMakePath(NETWORK_PID_DIR) < 0) {
        virReportSystemError(errno,
783 784 785 786
                             _("cannot create directory %s"),
                             NETWORK_PID_DIR);
        goto cleanup;
    }
787 788
    if (virFileMakePath(RADVD_STATE_DIR) < 0) {
        virReportSystemError(errno,
789 790 791 792 793 794 795 796 797 798
                             _("cannot create directory %s"),
                             RADVD_STATE_DIR);
        goto cleanup;
    }

    /* construct pidfile name */
    if (!(radvdpidbase = networkRadvdPidfileBasename(network->def->name))) {
        virReportOOMError();
        goto cleanup;
    }
799
    if (!(pidfile = virPidFileBuildPath(NETWORK_PID_DIR, radvdpidbase))) {
800 801 802 803 804
        virReportOOMError();
        goto cleanup;
    }

    /* create radvd config file appropriate for this network */
805
    virBufferAsprintf(&configbuf, "interface %s\n"
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
                      "{\n"
                      "  AdvSendAdvert on;\n"
                      "  AdvManagedFlag off;\n"
                      "  AdvOtherConfigFlag off;\n"
                      "\n",
                      network->def->bridge);
    for (ii = 0;
         (ipdef = virNetworkDefGetIpByIndex(network->def, AF_INET6, ii));
         ii++) {
        int prefix;
        char *netaddr;

        prefix = virNetworkIpDefPrefix(ipdef);
        if (prefix < 0) {
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("bridge  '%s' has an invalid prefix"),
                               network->def->bridge);
            goto cleanup;
        }
        if (!(netaddr = virSocketFormatAddr(&ipdef->address)))
            goto cleanup;
827
        virBufferAsprintf(&configbuf,
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
                          "  prefix %s/%d\n"
                          "  {\n"
                          "    AdvOnLink on;\n"
                          "    AdvAutonomous on;\n"
                          "    AdvRouterAddr off;\n"
                          "  };\n",
                          netaddr, prefix);
        VIR_FREE(netaddr);
    }

    virBufferAddLit(&configbuf, "};\n");

    if (virBufferError(&configbuf)) {
        virReportOOMError();
        goto cleanup;
    }
    if (!(configstr = virBufferContentAndReset(&configbuf))) {
        virReportOOMError();
        goto cleanup;
    }

    /* construct the filename */
    if (!(configfile = networkRadvdConfigFileName(network->def->name))) {
        virReportOOMError();
        goto cleanup;
    }
    /* write the file */
    if (virFileWriteStr(configfile, configstr, 0600) < 0) {
        virReportSystemError(errno,
                             _("couldn't write radvd config file '%s'"),
                             configfile);
        goto cleanup;
    }

    /* prevent radvd from daemonizing itself with "--debug 1", and use
     * a dummy pidfile name - virCommand will create the pidfile we
     * want to use (this is necessary because radvd's internal
     * daemonization and pidfile creation causes a race, and the
866
     * virPidFileRead() below will fail if we use them).
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
     * Unfortunately, it isn't possible to tell radvd to not create
     * its own pidfile, so we just let it do so, with a slightly
     * different name. Unused, but harmless.
     */
    cmd = virCommandNewArgList(RADVD, "--debug", "1",
                               "--config", configfile,
                               "--pidfile", NULL);
    virCommandAddArgFormat(cmd, "%s-bin", pidfile);

    virCommandSetPidFile(cmd, pidfile);
    virCommandDaemonize(cmd);

    if (virCommandRun(cmd, NULL) < 0)
        goto cleanup;

882
    if (virPidFileRead(NETWORK_PID_DIR, radvdpidbase,
883 884 885 886 887 888 889 890 891 892 893 894 895 896
                       &network->radvdPid) < 0)
        goto cleanup;

    ret = 0;
cleanup:
    virCommandFree(cmd);
    VIR_FREE(configfile);
    VIR_FREE(configstr);
    virBufferFreeAndReset(&configbuf);
    VIR_FREE(radvdpidbase);
    VIR_FREE(pidfile);
    return ret;
}

897
static int
898
networkAddMasqueradingIptablesRules(struct network_driver *driver,
899 900
                                    virNetworkObjPtr network,
                                    virNetworkIpDefPtr ipdef)
901 902
{
    int prefix = virNetworkIpDefPrefix(ipdef);
903
    const char *forwardIf = virNetworkDefForwardIf(network->def, 0);
904 905 906 907 908 909 910

    if (prefix < 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid prefix or netmask for '%s'"),
                           network->def->bridge);
        goto masqerr1;
    }
911

912
    /* allow forwarding packets from the bridge interface */
913
    if (iptablesAddForwardAllowOut(driver->iptables,
914
                                   &ipdef->address,
915
                                   prefix,
916
                                   network->def->bridge,
917
                                   forwardIf) < 0) {
918 919 920
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow forwarding from '%s'"),
                           network->def->bridge);
921 922 923
        goto masqerr1;
    }

924 925 926
    /* allow forwarding packets to the bridge interface if they are
     * part of an existing connection
     */
927
    if (iptablesAddForwardAllowRelatedIn(driver->iptables,
928
                                         &ipdef->address,
929
                                         prefix,
930
                                         network->def->bridge,
931
                                         forwardIf) < 0) {
932 933 934
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow forwarding to '%s'"),
                           network->def->bridge);
935 936 937
        goto masqerr2;
    }

938 939 940 941 942
    /*
     * Enable masquerading.
     *
     * We need to end up with 3 rules in the table in this order
     *
E
Eric Blake 已提交
943 944
     *  1. protocol=tcp with sport mapping restriction
     *  2. protocol=udp with sport mapping restriction
945 946 947
     *  3. generic any protocol
     *
     * The sport mappings are required, because default IPtables
E
Eric Blake 已提交
948
     * MASQUERADE maintain port numbers unchanged where possible.
949 950 951 952 953 954 955 956 957 958 959 960 961
     *
     * NFS can be configured to only "trust" port numbers < 1023.
     *
     * Guests using NAT thus need to be prevented from having port
     * numbers < 1023, otherwise they can bypass the NFS "security"
     * check on the source port number.
     *
     * Since we use '--insert' to add rules to the header of the
     * chain, we actually need to add them in the reverse of the
     * order just mentioned !
     */

    /* First the generic masquerade rule for other protocols */
962
    if (iptablesAddForwardMasquerade(driver->iptables,
963
                                     &ipdef->address,
964
                                     prefix,
965
                                     forwardIf,
966 967
                                     NULL) < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
968 969 970 971
                           forwardIf ?
                           _("failed to add iptables rule to enable masquerading to %s") :
                           _("failed to add iptables rule to enable masquerading"),
                           forwardIf);
972 973 974
        goto masqerr3;
    }

975
    /* UDP with a source port restriction */
976
    if (iptablesAddForwardMasquerade(driver->iptables,
977
                                     &ipdef->address,
978
                                     prefix,
979
                                     forwardIf,
980 981
                                     "udp") < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
982 983 984 985
                           forwardIf ?
                           _("failed to add iptables rule to enable UDP masquerading to %s") :
                           _("failed to add iptables rule to enable UDP masquerading"),
                           forwardIf);
986 987 988 989
        goto masqerr4;
    }

    /* TCP with a source port restriction */
990
    if (iptablesAddForwardMasquerade(driver->iptables,
991
                                     &ipdef->address,
992
                                     prefix,
993
                                     forwardIf,
994 995
                                     "tcp") < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
996 997 998 999
                           forwardIf ?
                           _("failed to add iptables rule to enable TCP masquerading to %s") :
                           _("failed to add iptables rule to enable TCP masquerading"),
                           forwardIf);
1000 1001 1002
        goto masqerr5;
    }

1003
    return 0;
1004

1005 1006
 masqerr5:
    iptablesRemoveForwardMasquerade(driver->iptables,
1007
                                    &ipdef->address,
1008
                                    prefix,
1009
                                    forwardIf,
1010 1011 1012
                                    "udp");
 masqerr4:
    iptablesRemoveForwardMasquerade(driver->iptables,
1013
                                    &ipdef->address,
1014
                                    prefix,
1015
                                    forwardIf,
1016
                                    NULL);
1017 1018
 masqerr3:
    iptablesRemoveForwardAllowRelatedIn(driver->iptables,
1019
                                        &ipdef->address,
1020
                                        prefix,
1021
                                        network->def->bridge,
1022
                                        forwardIf);
1023 1024
 masqerr2:
    iptablesRemoveForwardAllowOut(driver->iptables,
1025
                                  &ipdef->address,
1026
                                  prefix,
1027
                                  network->def->bridge,
1028
                                  forwardIf);
1029
 masqerr1:
1030
    return -1;
1031 1032
}

1033 1034 1035 1036 1037 1038
static void
networkRemoveMasqueradingIptablesRules(struct network_driver *driver,
                                       virNetworkObjPtr network,
                                       virNetworkIpDefPtr ipdef)
{
    int prefix = virNetworkIpDefPrefix(ipdef);
1039
    const char *forwardIf = virNetworkDefForwardIf(network->def, 0);
1040 1041 1042 1043 1044

    if (prefix >= 0) {
        iptablesRemoveForwardMasquerade(driver->iptables,
                                        &ipdef->address,
                                        prefix,
1045
                                        forwardIf,
1046 1047 1048 1049
                                        "tcp");
        iptablesRemoveForwardMasquerade(driver->iptables,
                                        &ipdef->address,
                                        prefix,
1050
                                        forwardIf,
1051 1052 1053 1054
                                        "udp");
        iptablesRemoveForwardMasquerade(driver->iptables,
                                        &ipdef->address,
                                        prefix,
1055
                                        forwardIf,
1056 1057 1058 1059 1060 1061
                                        NULL);

        iptablesRemoveForwardAllowRelatedIn(driver->iptables,
                                            &ipdef->address,
                                            prefix,
                                            network->def->bridge,
1062
                                            forwardIf);
1063 1064 1065 1066
        iptablesRemoveForwardAllowOut(driver->iptables,
                                      &ipdef->address,
                                      prefix,
                                      network->def->bridge,
1067
                                      forwardIf);
1068 1069 1070
    }
}

1071
static int
1072
networkAddRoutingIptablesRules(struct network_driver *driver,
1073
                               virNetworkObjPtr network,
1074 1075
                               virNetworkIpDefPtr ipdef)
{
1076
    int prefix = virNetworkIpDefPrefix(ipdef);
1077
    const char *forwardIf = virNetworkDefForwardIf(network->def, 0);
1078 1079 1080 1081 1082 1083 1084

    if (prefix < 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Invalid prefix or netmask for '%s'"),
                           network->def->bridge);
        goto routeerr1;
    }
1085

1086
    /* allow routing packets from the bridge interface */
1087
    if (iptablesAddForwardAllowOut(driver->iptables,
1088
                                   &ipdef->address,
1089
                                   prefix,
1090
                                   network->def->bridge,
1091
                                   forwardIf) < 0) {
1092 1093 1094
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow routing from '%s'"),
                           network->def->bridge);
1095 1096 1097 1098
        goto routeerr1;
    }

    /* allow routing packets to the bridge interface */
1099
    if (iptablesAddForwardAllowIn(driver->iptables,
1100
                                  &ipdef->address,
1101
                                  prefix,
1102
                                  network->def->bridge,
1103
                                  forwardIf) < 0) {
1104 1105 1106
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow routing to '%s'"),
                           network->def->bridge);
1107 1108 1109
        goto routeerr2;
    }

1110
    return 0;
1111

1112
routeerr2:
1113
    iptablesRemoveForwardAllowOut(driver->iptables,
1114
                                  &ipdef->address,
1115
                                  prefix,
1116
                                  network->def->bridge,
1117
                                  forwardIf);
1118
routeerr1:
1119
    return -1;
1120 1121
}

1122 1123 1124 1125 1126 1127
static void
networkRemoveRoutingIptablesRules(struct network_driver *driver,
                                  virNetworkObjPtr network,
                                  virNetworkIpDefPtr ipdef)
{
    int prefix = virNetworkIpDefPrefix(ipdef);
1128
    const char *forwardIf = virNetworkDefForwardIf(network->def, 0);
1129 1130 1131 1132 1133 1134

    if (prefix >= 0) {
        iptablesRemoveForwardAllowIn(driver->iptables,
                                     &ipdef->address,
                                     prefix,
                                     network->def->bridge,
1135
                                     forwardIf);
1136 1137 1138 1139 1140

        iptablesRemoveForwardAllowOut(driver->iptables,
                                      &ipdef->address,
                                      prefix,
                                      network->def->bridge,
1141
                                      forwardIf);
1142 1143 1144
    }
}

1145 1146 1147 1148 1149 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
/* Add all once/network rules required for IPv6 (if any IPv6 addresses are defined) */
static int
networkAddGeneralIp6tablesRules(struct network_driver *driver,
                               virNetworkObjPtr network)
{

    if (!virNetworkDefGetIpByIndex(network->def, AF_INET6, 0))
        return 0;

    /* Catch all rules to block forwarding to/from bridges */

    if (iptablesAddForwardRejectOut(driver->iptables, AF_INET6,
                                    network->def->bridge) < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add ip6tables rule to block outbound traffic from '%s'"),
                           network->def->bridge);
        goto err1;
    }

    if (iptablesAddForwardRejectIn(driver->iptables, AF_INET6,
                                   network->def->bridge) < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add ip6tables rule to block inbound traffic to '%s'"),
                           network->def->bridge);
        goto err2;
    }

    /* Allow traffic between guests on the same bridge */
    if (iptablesAddForwardAllowCross(driver->iptables, AF_INET6,
                                     network->def->bridge) < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add ip6tables rule to allow cross bridge traffic on '%s'"),
                           network->def->bridge);
        goto err3;
    }

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
    /* allow DNS over IPv6 */
    if (iptablesAddTcpInput(driver->iptables, AF_INET6,
                            network->def->bridge, 53) < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add ip6tables rule to allow DNS requests from '%s'"),
                           network->def->bridge);
        goto err4;
    }

    if (iptablesAddUdpInput(driver->iptables, AF_INET6,
                            network->def->bridge, 53) < 0) {
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add ip6tables rule to allow DNS requests from '%s'"),
                           network->def->bridge);
        goto err5;
    }

1198 1199 1200
    return 0;

    /* unwind in reverse order from the point of failure */
1201 1202 1203 1204
err5:
    iptablesRemoveTcpInput(driver->iptables, AF_INET6, network->def->bridge, 53);
err4:
    iptablesRemoveForwardAllowCross(driver->iptables, AF_INET6, network->def->bridge);
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
err3:
    iptablesRemoveForwardRejectIn(driver->iptables, AF_INET6, network->def->bridge);
err2:
    iptablesRemoveForwardRejectOut(driver->iptables, AF_INET6, network->def->bridge);
err1:
    return -1;
}

static void
networkRemoveGeneralIp6tablesRules(struct network_driver *driver,
                                  virNetworkObjPtr network)
{
    if (!virNetworkDefGetIpByIndex(network->def, AF_INET6, 0))
        return;

    iptablesRemoveForwardAllowCross(driver->iptables, AF_INET6, network->def->bridge);
    iptablesRemoveForwardRejectIn(driver->iptables, AF_INET6, network->def->bridge);
    iptablesRemoveForwardRejectOut(driver->iptables, AF_INET6, network->def->bridge);
}

1225
static int
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
networkAddGeneralIptablesRules(struct network_driver *driver,
                               virNetworkObjPtr network)
{
    int ii;
    virNetworkIpDefPtr ipv4def;

    /* First look for first IPv4 address that has dhcp or tftpboot defined. */
    /* We support dhcp config on 1 IPv4 interface only. */
    for (ii = 0;
         (ipv4def = virNetworkDefGetIpByIndex(network->def, AF_INET, ii));
         ii++) {
        if (ipv4def->nranges || ipv4def->nhosts || ipv4def->tftproot)
            break;
    }
1240 1241

    /* allow DHCP requests through to dnsmasq */
1242

1243 1244
    if (iptablesAddTcpInput(driver->iptables, AF_INET,
                            network->def->bridge, 67) < 0) {
1245 1246 1247
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow DHCP requests from '%s'"),
                           network->def->bridge);
1248 1249 1250
        goto err1;
    }

1251 1252
    if (iptablesAddUdpInput(driver->iptables, AF_INET,
                            network->def->bridge, 67) < 0) {
1253 1254 1255
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow DHCP requests from '%s'"),
                           network->def->bridge);
1256 1257 1258
        goto err2;
    }

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    /* If we are doing local DHCP service on this network, attempt to
     * add a rule that will fixup the checksum of DHCP response
     * packets back to the guests (but report failure without
     * aborting, since not all iptables implementations support it).
     */

    if (ipv4def && (ipv4def->nranges || ipv4def->nhosts) &&
        (iptablesAddOutputFixUdpChecksum(driver->iptables,
                                         network->def->bridge, 68) < 0)) {
        VIR_WARN("Could not add rule to fixup DHCP response checksums "
                 "on network '%s'.", network->def->name);
1270
        VIR_WARN("May need to update iptables package & kernel to support CHECKSUM rule.");
1271 1272
    }

1273
    /* allow DNS requests through to dnsmasq */
1274 1275
    if (iptablesAddTcpInput(driver->iptables, AF_INET,
                            network->def->bridge, 53) < 0) {
1276 1277 1278
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow DNS requests from '%s'"),
                           network->def->bridge);
1279 1280 1281
        goto err3;
    }

1282 1283
    if (iptablesAddUdpInput(driver->iptables, AF_INET,
                            network->def->bridge, 53) < 0) {
1284 1285 1286
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow DNS requests from '%s'"),
                           network->def->bridge);
1287 1288 1289
        goto err4;
    }

1290 1291
    /* allow TFTP requests through to dnsmasq if necessary */
    if (ipv4def && ipv4def->tftproot &&
1292 1293
        iptablesAddUdpInput(driver->iptables, AF_INET,
                            network->def->bridge, 69) < 0) {
1294 1295 1296
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow TFTP requests from '%s'"),
                           network->def->bridge);
1297
        goto err5;
1298 1299
    }

1300 1301
    /* Catch all rules to block forwarding to/from bridges */

1302 1303
    if (iptablesAddForwardRejectOut(driver->iptables, AF_INET,
                                    network->def->bridge) < 0) {
1304 1305 1306
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to block outbound traffic from '%s'"),
                           network->def->bridge);
1307
        goto err6;
1308 1309
    }

1310 1311
    if (iptablesAddForwardRejectIn(driver->iptables, AF_INET,
                                   network->def->bridge) < 0) {
1312 1313 1314
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to block inbound traffic to '%s'"),
                           network->def->bridge);
1315
        goto err7;
1316 1317 1318
    }

    /* Allow traffic between guests on the same bridge */
1319 1320
    if (iptablesAddForwardAllowCross(driver->iptables, AF_INET,
                                     network->def->bridge) < 0) {
1321 1322 1323
        networkReportError(VIR_ERR_SYSTEM_ERROR,
                           _("failed to add iptables rule to allow cross bridge traffic on '%s'"),
                           network->def->bridge);
1324
        goto err8;
1325 1326
    }

1327 1328 1329 1330 1331
    /* add IPv6 general rules, if needed */
    if (networkAddGeneralIp6tablesRules(driver, network) < 0) {
        goto err9;
    }

1332
    return 0;
1333

1334
    /* unwind in reverse order from the point of failure */
1335 1336
err9:
    iptablesRemoveForwardAllowCross(driver->iptables, AF_INET, network->def->bridge);
1337
err8:
1338
    iptablesRemoveForwardRejectIn(driver->iptables, AF_INET, network->def->bridge);
1339
err7:
1340
    iptablesRemoveForwardRejectOut(driver->iptables, AF_INET, network->def->bridge);
1341 1342
err6:
    if (ipv4def && ipv4def->tftproot) {
1343
        iptablesRemoveUdpInput(driver->iptables, AF_INET, network->def->bridge, 69);
1344
    }
1345
err5:
1346
    iptablesRemoveUdpInput(driver->iptables, AF_INET, network->def->bridge, 53);
1347
err4:
1348
    iptablesRemoveTcpInput(driver->iptables, AF_INET, network->def->bridge, 53);
1349
err3:
1350
    iptablesRemoveUdpInput(driver->iptables, AF_INET, network->def->bridge, 67);
1351
err2:
1352
    iptablesRemoveTcpInput(driver->iptables, AF_INET, network->def->bridge, 67);
1353
err1:
1354
    return -1;
1355 1356 1357
}

static void
1358 1359 1360 1361 1362
networkRemoveGeneralIptablesRules(struct network_driver *driver,
                                  virNetworkObjPtr network)
{
    int ii;
    virNetworkIpDefPtr ipv4def;
1363

1364 1365
    networkRemoveGeneralIp6tablesRules(driver, network);

1366 1367 1368 1369 1370
    for (ii = 0;
         (ipv4def = virNetworkDefGetIpByIndex(network->def, AF_INET, ii));
         ii++) {
        if (ipv4def->nranges || ipv4def->nhosts || ipv4def->tftproot)
            break;
1371
    }
1372

1373 1374 1375
    iptablesRemoveForwardAllowCross(driver->iptables, AF_INET, network->def->bridge);
    iptablesRemoveForwardRejectIn(driver->iptables, AF_INET, network->def->bridge);
    iptablesRemoveForwardRejectOut(driver->iptables, AF_INET, network->def->bridge);
1376
    if (ipv4def && ipv4def->tftproot) {
1377
        iptablesRemoveUdpInput(driver->iptables, AF_INET, network->def->bridge, 69);
1378
    }
1379 1380
    iptablesRemoveUdpInput(driver->iptables, AF_INET, network->def->bridge, 53);
    iptablesRemoveTcpInput(driver->iptables, AF_INET, network->def->bridge, 53);
1381 1382 1383 1384
    if (ipv4def && (ipv4def->nranges || ipv4def->nhosts)) {
        iptablesRemoveOutputFixUdpChecksum(driver->iptables,
                                           network->def->bridge, 68);
    }
1385 1386
    iptablesRemoveUdpInput(driver->iptables, AF_INET, network->def->bridge, 67);
    iptablesRemoveTcpInput(driver->iptables, AF_INET, network->def->bridge, 67);
1387 1388
}

1389 1390 1391 1392 1393
static int
networkAddIpSpecificIptablesRules(struct network_driver *driver,
                                  virNetworkObjPtr network,
                                  virNetworkIpDefPtr ipdef)
{
1394 1395 1396
    /* NB: in the case of IPv6, routing rules are added when the
     * forward mode is NAT. This is because IPv6 has no NAT.
     */
1397

1398 1399 1400 1401 1402 1403 1404 1405
    if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT) {
        if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET))
            return networkAddMasqueradingIptablesRules(driver, network, ipdef);
        else if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET6))
            return networkAddRoutingIptablesRules(driver, network, ipdef);
    } else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {
        return networkAddRoutingIptablesRules(driver, network, ipdef);
    }
1406 1407 1408 1409 1410 1411 1412 1413
    return 0;
}

static void
networkRemoveIpSpecificIptablesRules(struct network_driver *driver,
                                     virNetworkObjPtr network,
                                     virNetworkIpDefPtr ipdef)
{
1414 1415 1416 1417 1418 1419
    if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT) {
        if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET))
            networkRemoveMasqueradingIptablesRules(driver, network, ipdef);
        else if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET6))
            networkRemoveRoutingIptablesRules(driver, network, ipdef);
    } else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {
1420
        networkRemoveRoutingIptablesRules(driver, network, ipdef);
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
}

/* Add all rules for all ip addresses (and general rules) on a network */
static int
networkAddIptablesRules(struct network_driver *driver,
                        virNetworkObjPtr network)
{
    int ii;
    virNetworkIpDefPtr ipdef;

    /* Add "once per network" rules */
    if (networkAddGeneralIptablesRules(driver, network) < 0)
        return -1;

    for (ii = 0;
         (ipdef = virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, ii));
         ii++) {
        /* Add address-specific iptables rules */
        if (networkAddIpSpecificIptablesRules(driver, network, ipdef) < 0) {
            goto err;
        }
    }
    return 0;

err:
    /* The final failed call to networkAddIpSpecificIptablesRules will
     * have removed any rules it created, but we need to remove those
     * added for previous IP addresses.
     */
    while ((--ii >= 0) &&
           (ipdef = virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, ii))) {
        networkRemoveIpSpecificIptablesRules(driver, network, ipdef);
    }
    networkRemoveGeneralIptablesRules(driver, network);
    return -1;
}

/* Remove all rules for all ip addresses (and general rules) on a network */
static void
networkRemoveIptablesRules(struct network_driver *driver,
                           virNetworkObjPtr network)
{
    int ii;
    virNetworkIpDefPtr ipdef;

    for (ii = 0;
         (ipdef = virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, ii));
         ii++) {
        networkRemoveIpSpecificIptablesRules(driver, network, ipdef);
    }
    networkRemoveGeneralIptablesRules(driver, network);
}

1475 1476 1477 1478 1479
static void
networkReloadIptablesRules(struct network_driver *driver)
{
    unsigned int i;

1480
    VIR_INFO("Reloading iptables rules");
1481 1482 1483 1484

    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
        if (virNetworkObjIsActive(driver->networks.objs[i])) {
1485 1486 1487 1488
            networkRemoveIptablesRules(driver, driver->networks.objs[i]);
            if (networkAddIptablesRules(driver, driver->networks.objs[i]) < 0) {
                /* failed to add but already logged */
            }
1489 1490 1491 1492 1493
        }
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
}

1494
/* Enable IP Forwarding. Return 0 for success, -1 for failure. */
1495
static int
1496
networkEnableIpForwarding(bool enableIPv4, bool enableIPv6)
1497
{
1498 1499 1500 1501 1502 1503
    int ret = 0;
    if (enableIPv4)
        ret = virFileWriteStr("/proc/sys/net/ipv4/ip_forward", "1\n", 0);
    if (enableIPv6 && ret == 0)
        ret = virFileWriteStr("/proc/sys/net/ipv6/conf/all/forwarding", "1\n", 0);
    return ret;
1504 1505
}

1506 1507
#define SYSCTL_PATH "/proc/sys"

1508 1509
static int
networkSetIPv6Sysctls(virNetworkObjPtr network)
1510 1511 1512 1513
{
    char *field = NULL;
    int ret = -1;

1514 1515 1516 1517 1518 1519 1520 1521 1522
    if (!virNetworkDefGetIpByIndex(network->def, AF_INET6, 0)) {
        /* Only set disable_ipv6 if there are no ipv6 addresses defined for
         * the network.
         */
        if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/disable_ipv6",
                        network->def->bridge) < 0) {
            virReportOOMError();
            goto cleanup;
        }
1523

1524 1525 1526 1527 1528 1529
        if (access(field, W_OK) < 0 && errno == ENOENT) {
            VIR_DEBUG("ipv6 appears to already be disabled on %s",
                      network->def->bridge);
            ret = 0;
            goto cleanup;
        }
1530

1531 1532 1533 1534 1535 1536 1537
        if (virFileWriteStr(field, "1", 0) < 0) {
            virReportSystemError(errno,
                                 _("cannot write to %s to disable IPv6 on bridge %s"),
                                 field, network->def->bridge);
            goto cleanup;
        }
        VIR_FREE(field);
1538 1539
    }

1540 1541 1542 1543 1544 1545 1546 1547 1548
    /* The rest of the ipv6 sysctl tunables should always be set,
     * whether or not we're using ipv6 on this bridge.
     */

    /* Prevent guests from hijacking the host network by sending out
     * their own router advertisements.
     */
    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra",
                    network->def->bridge) < 0) {
1549
        virReportOOMError();
1550 1551 1552
        goto cleanup;
    }

1553
    if (virFileWriteStr(field, "0", 0) < 0) {
1554
        virReportSystemError(errno,
1555 1556 1557 1558 1559
                             _("cannot disable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

1560 1561 1562 1563 1564
    /* All interfaces used as a gateway (which is what this is, by
     * definition), must always have autoconf=0.
     */
    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/autoconf",
                    network->def->bridge) < 0) {
1565
        virReportOOMError();
1566 1567 1568
        goto cleanup;
    }

1569
    if (virFileWriteStr(field, "1", 0) < 0) {
1570
        virReportSystemError(errno,
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
                             _("cannot enable %s"), field);
        goto cleanup;
    }

    ret = 0;
cleanup:
    VIR_FREE(field);
    return ret;
}

1581 1582 1583 1584 1585 1586
#define PROC_NET_ROUTE "/proc/net/route"

/* XXX: This function can be a lot more exhaustive, there are certainly
 *      other scenarios where we can ruin host network connectivity.
 * XXX: Using a proper library is preferred over parsing /proc
 */
1587 1588
static int
networkCheckRouteCollision(virNetworkObjPtr network)
1589
{
1590
    int ret = 0, len;
1591 1592 1593 1594 1595
    char *cur, *buf = NULL;
    enum {MAX_ROUTE_SIZE = 1024*64};

    /* Read whole routing table into memory */
    if ((len = virFileReadAll(PROC_NET_ROUTE, MAX_ROUTE_SIZE, &buf)) < 0)
1596
        goto out;
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614

    /* Dropping the last character shouldn't hurt */
    if (len > 0)
        buf[len-1] = '\0';

    VIR_DEBUG("%s output:\n%s", PROC_NET_ROUTE, buf);

    if (!STRPREFIX (buf, "Iface"))
        goto out;

    /* First line is just headings, skip it */
    cur = strchr(buf, '\n');
    if (cur)
        cur++;

    while (cur) {
        char iface[17], dest[128], mask[128];
        unsigned int addr_val, mask_val;
1615 1616
        virNetworkIpDefPtr ipdef;
        int num, ii;
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644

        /* NUL-terminate the line, so sscanf doesn't go beyond a newline.  */
        char *nl = strchr(cur, '\n');
        if (nl) {
            *nl++ = '\0';
        }

        num = sscanf(cur, "%16s %127s %*s %*s %*s %*s %*s %127s",
                     iface, dest, mask);
        cur = nl;

        if (num != 3) {
            VIR_DEBUG("Failed to parse %s", PROC_NET_ROUTE);
            continue;
        }

        if (virStrToLong_ui(dest, NULL, 16, &addr_val) < 0) {
            VIR_DEBUG("Failed to convert network address %s to uint", dest);
            continue;
        }

        if (virStrToLong_ui(mask, NULL, 16, &mask_val) < 0) {
            VIR_DEBUG("Failed to convert network mask %s to uint", mask);
            continue;
        }

        addr_val &= mask_val;

1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
        for (ii = 0;
             (ipdef = virNetworkDefGetIpByIndex(network->def, AF_INET, ii));
             ii++) {

            unsigned int net_dest;
            virSocketAddr netmask;

            if (virNetworkIpDefNetmask(ipdef, &netmask) < 0) {
                VIR_WARN("Failed to get netmask of '%s'",
                         network->def->bridge);
                continue;
            }

            net_dest = (ipdef->address.data.inet4.sin_addr.s_addr &
                        netmask.data.inet4.sin_addr.s_addr);

            if ((net_dest == addr_val) &&
                (netmask.data.inet4.sin_addr.s_addr == mask_val)) {
                networkReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Network is already in use by interface %s"),
                                   iface);
                ret = -1;
                goto out;
            }
1669 1670 1671 1672 1673 1674 1675 1676
        }
    }

out:
    VIR_FREE(buf);
    return ret;
}

1677 1678 1679 1680
static int
networkAddAddrToBridge(struct network_driver *driver,
                       virNetworkObjPtr network,
                       virNetworkIpDefPtr ipdef)
1681
{
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    int prefix = virNetworkIpDefPrefix(ipdef);

    if (prefix < 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("bridge '%s' has an invalid netmask or IP address"),
                           network->def->bridge);
        return -1;
    }

    if (brAddInetAddress(driver->brctl, network->def->bridge,
                         &ipdef->address, prefix) < 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot set IP address on bridge '%s'"),
                           network->def->bridge);
        return -1;
    }

    return 0;
}

static int
1703
networkStartNetworkVirtual(struct network_driver *driver,
1704 1705 1706
                          virNetworkObjPtr network)
{
    int ii, err;
1707
    bool v4present = false, v6present = false;
1708 1709
    virErrorPtr save_err = NULL;
    virNetworkIpDefPtr ipdef;
1710
    char *macTapIfName = NULL;
1711

1712 1713
    /* Check to see if any network IP collides with an existing route */
    if (networkCheckRouteCollision(network) < 0)
1714 1715
        return -1;

1716
    /* Create and configure the bridge device */
1717
    if ((err = brAddBridge(driver->brctl, network->def->bridge))) {
1718
        virReportSystemError(err,
1719 1720
                             _("cannot create bridge '%s'"),
                             network->def->bridge);
1721 1722 1723
        return -1;
    }

1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
    if (network->def->mac_specified) {
        /* To set a mac for the bridge, we need to define a dummy tap
         * device, set its mac, then attach it to the bridge. As long
         * as its mac address is lower than any other interface that
         * gets attached, the bridge will always maintain this mac
         * address.
         */
        macTapIfName = networkBridgeDummyNicName(network->def->bridge);
        if (!macTapIfName) {
            virReportOOMError();
            goto err0;
        }
        if ((err = brAddTap(driver->brctl, network->def->bridge,
                            &macTapIfName, network->def->mac, 0, false, NULL))) {
            virReportSystemError(err,
                                 _("cannot create dummy tap device '%s' to set mac"
                                   " address on bridge '%s'"),
                                 macTapIfName, network->def->bridge);
            VIR_FREE(macTapIfName);
            goto err0;
        }
    }

1747
    /* Set bridge options */
E
Eric Blake 已提交
1748 1749
    if (brSetForwardDelay(driver->brctl, network->def->bridge,
                          network->def->delay)) {
1750 1751 1752
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot set forward delay on bridge '%s'"),
                           network->def->bridge);
1753
        goto err1;
1754 1755
    }

E
Eric Blake 已提交
1756 1757
    if (brSetEnableSTP(driver->brctl, network->def->bridge,
                       network->def->stp ? 1 : 0)) {
1758
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1759 1760
                           _("cannot set STP '%s' on bridge '%s'"),
                           network->def->stp ? "on" : "off", network->def->bridge);
1761
        goto err1;
1762 1763
    }

1764 1765 1766 1767
    /* Disable IPv6 on the bridge if there are no IPv6 addresses
     * defined, and set other IPv6 sysctl tunables appropriately.
     */
    if (networkSetIPv6Sysctls(network) < 0)
1768
        goto err1;
1769

1770 1771 1772 1773 1774 1775 1776 1777 1778
    /* Add "once per network" rules */
    if (networkAddIptablesRules(driver, network) < 0)
        goto err1;

    for (ii = 0;
         (ipdef = virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, ii));
         ii++) {
        if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET))
            v4present = true;
1779 1780
        if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET6))
            v6present = true;
1781

1782 1783 1784
        /* Add the IP address/netmask to the bridge */
        if (networkAddAddrToBridge(driver, network, ipdef) < 0) {
            goto err2;
1785
        }
1786 1787
    }

1788
    /* Bring up the bridge interface */
1789
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 1))) {
1790
        virReportSystemError(err,
1791 1792
                             _("failed to bring the bridge '%s' up"),
                             network->def->bridge);
1793
        goto err2;
1794 1795
    }

1796
    /* If forwardType != NONE, turn on global IP forwarding */
1797
    if (network->def->forwardType != VIR_NETWORK_FORWARD_NONE &&
1798
        networkEnableIpForwarding(v4present, v6present) < 0) {
1799
        virReportSystemError(errno, "%s",
1800
                             _("failed to enable IP forwarding"));
1801
        goto err3;
1802 1803
    }

1804

1805 1806
    /* start dnsmasq if there are any IP addresses (v4 or v6) */
    if ((v4present || v6present) && networkStartDhcpDaemon(network) < 0)
1807
        goto err3;
1808

1809 1810 1811 1812
    /* start radvd if there are any ipv6 addresses */
    if (v6present && networkStartRadvd(network) < 0)
        goto err4;

1813 1814 1815 1816 1817 1818 1819
    if (virBandwidthEnable(network->def->bandwidth, network->def->bridge) < 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot set bandwidth limits on %s"),
                           network->def->bridge);
        goto err5;
    }

1820
    VIR_FREE(macTapIfName);
1821 1822 1823

    return 0;

1824 1825 1826 1827 1828 1829
 err5:
    if (virBandwidthDisable(network->def->bridge, true) < 0) {
        VIR_WARN("Failed to disable QoS on %s",
                 network->def->bridge);
    }

1830 1831 1832 1833
 err4:
    if (!save_err)
        save_err = virSaveLastError();

1834 1835 1836 1837 1838
    if (network->dnsmasqPid > 0) {
        kill(network->dnsmasqPid, SIGTERM);
        network->dnsmasqPid = -1;
    }

1839 1840 1841
 err3:
    if (!save_err)
        save_err = virSaveLastError();
1842
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
1843
        char ebuf[1024];
1844
        VIR_WARN("Failed to bring down bridge '%s' : %s",
1845
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1846 1847
    }

1848 1849 1850 1851 1852 1853
 err2:
    if (!save_err)
        save_err = virSaveLastError();
    networkRemoveIptablesRules(driver, network);

 err1:
1854 1855 1856 1857 1858 1859 1860 1861 1862
    if (!save_err)
        save_err = virSaveLastError();

    if ((err = brDeleteTap(driver->brctl, macTapIfName))) {
        char ebuf[1024];
        VIR_WARN("Failed to delete dummy tap device '%s' on bridge '%s' : %s",
                 macTapIfName, network->def->bridge,
                 virStrerror(err, ebuf, sizeof ebuf));
    }
1863
    VIR_FREE(macTapIfName);
1864 1865

 err0:
1866 1867
    if (!save_err)
        save_err = virSaveLastError();
1868
    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
1869
        char ebuf[1024];
1870
        VIR_WARN("Failed to delete bridge '%s' : %s",
1871
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1872 1873
    }

1874 1875 1876 1877
    if (save_err) {
        virSetError(save_err);
        virFreeError(save_err);
    }
1878 1879 1880
    return -1;
}

1881
static int networkShutdownNetworkVirtual(struct network_driver *driver,
1882 1883
                                        virNetworkObjPtr network)
{
1884
    int err;
1885
    char ebuf[1024];
1886

1887 1888 1889 1890 1891
    if (virBandwidthDisable(network->def->bridge, true) < 0) {
        VIR_WARN("Failed to disable QoS on %s",
                 network->def->name);
    }

1892 1893 1894 1895 1896 1897 1898 1899
    if (network->radvdPid > 0) {
        char *radvdpidbase;

        kill(network->radvdPid, SIGTERM);
        /* attempt to delete the pidfile we created */
        if (!(radvdpidbase = networkRadvdPidfileBasename(network->def->name))) {
            virReportOOMError();
        } else {
1900
            virPidFileDelete(NETWORK_PID_DIR, radvdpidbase);
1901 1902 1903 1904
            VIR_FREE(radvdpidbase);
        }
    }

1905 1906 1907
    if (network->dnsmasqPid > 0)
        kill(network->dnsmasqPid, SIGTERM);

1908
    if (network->def->mac_specified) {
1909
        char *macTapIfName = networkBridgeDummyNicName(network->def->bridge);
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
        if (!macTapIfName) {
            virReportOOMError();
        } else {
            if ((err = brDeleteTap(driver->brctl, macTapIfName))) {
                VIR_WARN("Failed to delete dummy tap device '%s' on bridge '%s' : %s",
                         macTapIfName, network->def->bridge,
                         virStrerror(err, ebuf, sizeof ebuf));
            }
            VIR_FREE(macTapIfName);
        }
    }

1922
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
1923
        VIR_WARN("Failed to bring down bridge '%s' : %s",
1924
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1925 1926
    }

1927 1928
    networkRemoveIptablesRules(driver, network);

1929
    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
1930
        VIR_WARN("Failed to delete bridge '%s' : %s",
1931
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1932 1933
    }

1934
    /* See if its still alive and really really kill it */
1935
    if (network->dnsmasqPid > 0 &&
1936
        (kill(network->dnsmasqPid, 0) == 0))
1937 1938
        kill(network->dnsmasqPid, SIGKILL);
    network->dnsmasqPid = -1;
1939 1940 1941 1942 1943 1944

    if (network->radvdPid > 0 &&
        (kill(network->radvdPid, 0) == 0))
        kill(network->radvdPid, SIGKILL);
    network->radvdPid = -1;

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 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 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057
    return 0;
}

static int
networkStartNetworkExternal(struct network_driver *driver ATTRIBUTE_UNUSED,
                            virNetworkObjPtr network ATTRIBUTE_UNUSED)
{
    /* put anything here that needs to be done each time a network of
     * type BRIDGE, PRIVATE, VEPA, or PASSTHROUGH is started. On
     * failure, undo anything you've done, and return -1. On success
     * return 0.
     */
    return 0;
}

static int networkShutdownNetworkExternal(struct network_driver *driver ATTRIBUTE_UNUSED,
                                        virNetworkObjPtr network ATTRIBUTE_UNUSED)
{
    /* put anything here that needs to be done each time a network of
     * type BRIDGE, PRIVATE, VEPA, or PASSTHROUGH is shutdown. On
     * failure, undo anything you've done, and return -1. On success
     * return 0.
     */
    return 0;
}

static int
networkStartNetwork(struct network_driver *driver,
                    virNetworkObjPtr network)
{
    int ret = 0;

    if (virNetworkObjIsActive(network)) {
        networkReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("network is already active"));
        return -1;
    }

    switch (network->def->forwardType) {

    case VIR_NETWORK_FORWARD_NONE:
    case VIR_NETWORK_FORWARD_NAT:
    case VIR_NETWORK_FORWARD_ROUTE:
        ret = networkStartNetworkVirtual(driver, network);
        break;

    case VIR_NETWORK_FORWARD_BRIDGE:
    case VIR_NETWORK_FORWARD_PRIVATE:
    case VIR_NETWORK_FORWARD_VEPA:
    case VIR_NETWORK_FORWARD_PASSTHROUGH:
        ret = networkStartNetworkExternal(driver, network);
        break;
    }

    if (ret < 0)
        return ret;

    /* Persist the live configuration now that anything autogenerated
     * is setup.
     */
    if ((ret = virNetworkSaveConfig(NETWORK_STATE_DIR, network->def)) < 0) {
        goto error;
    }

    VIR_INFO("Starting up network '%s'", network->def->name);
    network->active = 1;

error:
    if (ret < 0) {
        virErrorPtr save_err = virSaveLastError();
        int save_errno = errno;
        networkShutdownNetwork(driver, network);
        virSetError(save_err);
        virFreeError(save_err);
        errno = save_errno;
    }
    return ret;
}

static int networkShutdownNetwork(struct network_driver *driver,
                                        virNetworkObjPtr network)
{
    int ret = 0;
    char *stateFile;

    VIR_INFO("Shutting down network '%s'", network->def->name);

    if (!virNetworkObjIsActive(network))
        return 0;

    stateFile = virNetworkConfigFile(NETWORK_STATE_DIR, network->def->name);
    if (!stateFile)
        return -1;

    unlink(stateFile);
    VIR_FREE(stateFile);

    switch (network->def->forwardType) {

    case VIR_NETWORK_FORWARD_NONE:
    case VIR_NETWORK_FORWARD_NAT:
    case VIR_NETWORK_FORWARD_ROUTE:
        ret = networkShutdownNetworkVirtual(driver, network);
        break;

    case VIR_NETWORK_FORWARD_BRIDGE:
    case VIR_NETWORK_FORWARD_PRIVATE:
    case VIR_NETWORK_FORWARD_VEPA:
    case VIR_NETWORK_FORWARD_PASSTHROUGH:
        ret = networkShutdownNetworkExternal(driver, network);
        break;
    }

2058 2059 2060 2061 2062 2063 2064 2065
    network->active = 0;

    if (network->newDef) {
        virNetworkDefFree(network->def);
        network->def = network->newDef;
        network->newDef = NULL;
    }

2066
    return ret;
2067 2068 2069
}


2070 2071 2072 2073 2074
static virNetworkPtr networkLookupByUUID(virConnectPtr conn,
                                         const unsigned char *uuid) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;
2075

2076
    networkDriverLock(driver);
2077
    network = virNetworkFindByUUID(&driver->networks, uuid);
2078
    networkDriverUnlock(driver);
2079
    if (!network) {
2080 2081
        networkReportError(VIR_ERR_NO_NETWORK,
                           "%s", _("no network with matching uuid"));
2082
        goto cleanup;
2083 2084
    }

2085 2086 2087
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
2088 2089
    if (network)
        virNetworkObjUnlock(network);
2090
    return ret;
2091 2092
}

2093 2094 2095 2096 2097 2098
static virNetworkPtr networkLookupByName(virConnectPtr conn,
                                         const char *name) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;

2099
    networkDriverLock(driver);
2100
    network = virNetworkFindByName(&driver->networks, name);
2101
    networkDriverUnlock(driver);
2102
    if (!network) {
2103 2104
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"), name);
2105
        goto cleanup;
2106 2107
    }

2108 2109 2110
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
2111 2112
    if (network)
        virNetworkObjUnlock(network);
2113
    return ret;
2114 2115 2116 2117
}

static virDrvOpenStatus networkOpenNetwork(virConnectPtr conn,
                                           virConnectAuthPtr auth ATTRIBUTE_UNUSED,
2118 2119 2120 2121
                                           unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
    if (!driverState)
        return VIR_DRV_OPEN_DECLINED;

    conn->networkPrivateData = driverState;
    return VIR_DRV_OPEN_SUCCESS;
}

static int networkCloseNetwork(virConnectPtr conn) {
    conn->networkPrivateData = NULL;
    return 0;
}

static int networkNumNetworks(virConnectPtr conn) {
2135
    int nactive = 0, i;
2136
    struct network_driver *driver = conn->networkPrivateData;
2137

2138 2139 2140
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
2141
        if (virNetworkObjIsActive(driver->networks.objs[i]))
2142
            nactive++;
2143 2144 2145
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
2146

2147 2148 2149 2150
    return nactive;
}

static int networkListNetworks(virConnectPtr conn, char **const names, int nnames) {
2151
    struct network_driver *driver = conn->networkPrivateData;
2152
    int got = 0, i;
2153

2154
    networkDriverLock(driver);
2155
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
2156
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
2157
        if (virNetworkObjIsActive(driver->networks.objs[i])) {
2158
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
2159
                virNetworkObjUnlock(driver->networks.objs[i]);
2160
                virReportOOMError();
2161 2162 2163 2164
                goto cleanup;
            }
            got++;
        }
2165
        virNetworkObjUnlock(driver->networks.objs[i]);
2166
    }
2167 2168
    networkDriverUnlock(driver);

2169 2170 2171
    return got;

 cleanup:
2172
    networkDriverUnlock(driver);
2173 2174 2175 2176 2177 2178
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

static int networkNumDefinedNetworks(virConnectPtr conn) {
2179
    int ninactive = 0, i;
2180
    struct network_driver *driver = conn->networkPrivateData;
2181

2182 2183 2184
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
2185
        if (!virNetworkObjIsActive(driver->networks.objs[i]))
2186
            ninactive++;
2187 2188 2189
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
2190

2191 2192 2193 2194
    return ninactive;
}

static int networkListDefinedNetworks(virConnectPtr conn, char **const names, int nnames) {
2195
    struct network_driver *driver = conn->networkPrivateData;
2196
    int got = 0, i;
2197

2198
    networkDriverLock(driver);
2199
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
2200
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
2201
        if (!virNetworkObjIsActive(driver->networks.objs[i])) {
2202
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
2203
                virNetworkObjUnlock(driver->networks.objs[i]);
2204
                virReportOOMError();
2205 2206 2207 2208
                goto cleanup;
            }
            got++;
        }
2209
        virNetworkObjUnlock(driver->networks.objs[i]);
2210
    }
2211
    networkDriverUnlock(driver);
2212 2213 2214
    return got;

 cleanup:
2215
    networkDriverUnlock(driver);
2216 2217 2218 2219 2220
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

2221 2222 2223

static int networkIsActive(virNetworkPtr net)
{
2224
    struct network_driver *driver = net->conn->networkPrivateData;
2225 2226 2227 2228 2229 2230 2231
    virNetworkObjPtr obj;
    int ret = -1;

    networkDriverLock(driver);
    obj = virNetworkFindByUUID(&driver->networks, net->uuid);
    networkDriverUnlock(driver);
    if (!obj) {
2232
        networkReportError(VIR_ERR_NO_NETWORK, NULL);
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
        goto cleanup;
    }
    ret = virNetworkObjIsActive(obj);

cleanup:
    if (obj)
        virNetworkObjUnlock(obj);
    return ret;
}

static int networkIsPersistent(virNetworkPtr net)
{
2245
    struct network_driver *driver = net->conn->networkPrivateData;
2246 2247 2248 2249 2250 2251 2252
    virNetworkObjPtr obj;
    int ret = -1;

    networkDriverLock(driver);
    obj = virNetworkFindByUUID(&driver->networks, net->uuid);
    networkDriverUnlock(driver);
    if (!obj) {
2253
        networkReportError(VIR_ERR_NO_NETWORK, NULL);
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
        goto cleanup;
    }
    ret = obj->persistent;

cleanup:
    if (obj)
        virNetworkObjUnlock(obj);
    return ret;
}


2265
static virNetworkPtr networkCreate(virConnectPtr conn, const char *xml) {
2266
    struct network_driver *driver = conn->networkPrivateData;
2267
    virNetworkDefPtr def;
2268
    virNetworkObjPtr network = NULL;
2269
    virNetworkPtr ret = NULL;
2270

2271 2272
    networkDriverLock(driver);

2273
    if (!(def = virNetworkDefParseString(xml)))
2274
        goto cleanup;
2275

2276 2277 2278
    if (virNetworkObjIsDuplicate(&driver->networks, def, 1) < 0)
        goto cleanup;

2279 2280 2281 2282 2283 2284
    /* Only the three L3 network types that are configured by libvirt
     * need to have a bridge device name / mac address provided
     */
    if (def->forwardType == VIR_NETWORK_FORWARD_NONE ||
        def->forwardType == VIR_NETWORK_FORWARD_NAT ||
        def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {
2285

2286 2287 2288 2289 2290
        if (virNetworkSetBridgeName(&driver->networks, def, 1))
            goto cleanup;

        virNetworkSetBridgeMacAddr(def);
    }
2291

2292
    if (!(network = virNetworkAssignDef(&driver->networks,
2293 2294 2295
                                        def)))
        goto cleanup;
    def = NULL;
2296

2297
    if (networkStartNetwork(driver, network) < 0) {
2298 2299
        virNetworkRemoveInactive(&driver->networks,
                                 network);
2300
        network = NULL;
2301
        goto cleanup;
2302 2303
    }

2304
    VIR_INFO("Creating network '%s'", network->def->name);
2305 2306 2307 2308
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
2309 2310 2311
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
2312
    return ret;
2313 2314 2315
}

static virNetworkPtr networkDefine(virConnectPtr conn, const char *xml) {
2316
    struct network_driver *driver = conn->networkPrivateData;
2317
    virNetworkIpDefPtr ipdef, ipv4def = NULL;
2318
    virNetworkDefPtr def;
2319
    bool freeDef = true;
2320
    virNetworkObjPtr network = NULL;
2321
    virNetworkPtr ret = NULL;
2322
    int ii;
2323
    dnsmasqContext* dctx = NULL;
2324

2325 2326
    networkDriverLock(driver);

2327
    if (!(def = virNetworkDefParseString(xml)))
2328
        goto cleanup;
2329

E
Eric Blake 已提交
2330
    if (virNetworkObjIsDuplicate(&driver->networks, def, 0) < 0)
2331 2332
        goto cleanup;

2333 2334 2335 2336 2337 2338
    /* Only the three L3 network types that are configured by libvirt
     * need to have a bridge device name / mac address provided
     */
    if (def->forwardType == VIR_NETWORK_FORWARD_NONE ||
        def->forwardType == VIR_NETWORK_FORWARD_NAT ||
        def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {
2339

2340 2341 2342 2343 2344
        if (virNetworkSetBridgeName(&driver->networks, def, 1))
            goto cleanup;

        virNetworkSetBridgeMacAddr(def);
    }
2345

2346
    if (!(network = virNetworkAssignDef(&driver->networks,
2347 2348
                                        def)))
        goto cleanup;
2349
    freeDef = false;
2350

2351 2352
    network->persistent = 1;

2353 2354
    if (virNetworkSaveConfig(driver->networkConfigDir, def) < 0) {
        virNetworkRemoveInactive(&driver->networks, network);
2355
        network = NULL;
2356
        goto cleanup;
2357 2358
    }

2359
    /* We only support dhcp on one IPv4 address per defined network */
2360
    for (ii = 0;
2361
         (ipdef = virNetworkDefGetIpByIndex(def, AF_UNSPEC, ii));
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
         ii++) {
        if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET)) {
            if (ipdef->nranges || ipdef->nhosts) {
                if (ipv4def) {
                    networkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                       "%s", _("Multiple dhcp sections found. dhcp is supported only for a single IPv4 address on each network"));
                    goto cleanup;
                } else {
                    ipv4def = ipdef;
                }
            }
        }
    }
    if (ipv4def) {
2376
        dctx = dnsmasqContextNew(def->name, DNSMASQ_STATE_DIR);
2377
        if (dctx == NULL ||
2378
            networkBuildDnsmasqHostsfile(dctx, ipv4def, def->dns) < 0 ||
2379
            dnsmasqSave(dctx) < 0)
2380 2381 2382
            goto cleanup;
    }

2383 2384
    VIR_INFO("Defining network '%s'", def->name);
    ret = virGetNetwork(conn, def->name, def->uuid);
2385 2386

cleanup:
2387 2388
    if (freeDef)
       virNetworkDefFree(def);
2389
    dnsmasqContextFree(dctx);
2390 2391 2392
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
2393
    return ret;
2394 2395 2396
}

static int networkUndefine(virNetworkPtr net) {
2397
    struct network_driver *driver = net->conn->networkPrivateData;
2398
    virNetworkObjPtr network;
2399 2400
    virNetworkIpDefPtr ipdef;
    bool dhcp_present = false, v6present = false;
2401
    int ret = -1, ii;
2402

2403 2404
    networkDriverLock(driver);

2405
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2406
    if (!network) {
2407
        networkReportError(VIR_ERR_NO_NETWORK,
2408 2409
                           "%s", _("no network with matching uuid"));
        goto cleanup;
2410 2411
    }

D
Daniel P. Berrange 已提交
2412
    if (virNetworkObjIsActive(network)) {
2413
        networkReportError(VIR_ERR_OPERATION_INVALID,
2414 2415
                           "%s", _("network is still active"));
        goto cleanup;
2416 2417
    }

2418
    if (virNetworkDeleteConfig(driver->networkConfigDir,
2419 2420
                               driver->networkAutostartDir,
                               network) < 0)
2421
        goto cleanup;
2422

2423 2424
    /* we only support dhcp on one IPv4 address per defined network */
    for (ii = 0;
2425
         (ipdef = virNetworkDefGetIpByIndex(network->def, AF_UNSPEC, ii));
2426
         ii++) {
2427 2428 2429 2430 2431 2432
        if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET)) {
            if (ipdef->nranges || ipdef->nhosts)
                dhcp_present = true;
        } else if (VIR_SOCKET_IS_FAMILY(&ipdef->address, AF_INET6)) {
            v6present = true;
        }
2433
    }
2434 2435

    if (dhcp_present) {
2436
        char *leasefile;
2437 2438 2439 2440 2441 2442
        dnsmasqContext *dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
        if (dctx == NULL)
            goto cleanup;

        dnsmasqDelete(dctx);
        dnsmasqContextFree(dctx);
2443 2444 2445 2446 2447 2448

        leasefile = networkDnsmasqLeaseFileName(network->def->name);
        if (!leasefile)
            goto cleanup;
        unlink(leasefile);
        VIR_FREE(leasefile);
2449 2450
    }

2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466
    if (v6present) {
        char *configfile = networkRadvdConfigFileName(network->def->name);

        if (!configfile) {
            virReportOOMError();
            goto cleanup;
        }
        unlink(configfile);
        VIR_FREE(configfile);

        char *radvdpidbase = networkRadvdPidfileBasename(network->def->name);

        if (!(radvdpidbase)) {
            virReportOOMError();
            goto cleanup;
        }
2467
        virPidFileDelete(NETWORK_PID_DIR, radvdpidbase);
2468 2469 2470 2471
        VIR_FREE(radvdpidbase);

    }

2472
    VIR_INFO("Undefining network '%s'", network->def->name);
2473 2474
    virNetworkRemoveInactive(&driver->networks,
                             network);
2475
    network = NULL;
2476
    ret = 0;
2477

2478
cleanup:
2479 2480 2481
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
2482
    return ret;
2483 2484 2485
}

static int networkStart(virNetworkPtr net) {
2486 2487 2488
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
2489

2490
    networkDriverLock(driver);
2491
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2492

2493
    if (!network) {
2494
        networkReportError(VIR_ERR_NO_NETWORK,
2495 2496
                           "%s", _("no network with matching uuid"));
        goto cleanup;
2497 2498
    }

2499
    ret = networkStartNetwork(driver, network);
2500 2501

cleanup:
2502 2503
    if (network)
        virNetworkObjUnlock(network);
2504
    networkDriverUnlock(driver);
2505
    return ret;
2506 2507 2508
}

static int networkDestroy(virNetworkPtr net) {
2509 2510 2511
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
2512

2513
    networkDriverLock(driver);
2514
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2515

2516
    if (!network) {
2517
        networkReportError(VIR_ERR_NO_NETWORK,
2518 2519
                           "%s", _("no network with matching uuid"));
        goto cleanup;
2520 2521
    }

D
Daniel P. Berrange 已提交
2522
    if (!virNetworkObjIsActive(network)) {
2523
        networkReportError(VIR_ERR_OPERATION_INVALID,
2524 2525 2526 2527
                           "%s", _("network is not active"));
        goto cleanup;
    }

2528
    ret = networkShutdownNetwork(driver, network);
2529
    if (!network->persistent) {
2530 2531 2532 2533
        virNetworkRemoveInactive(&driver->networks,
                                 network);
        network = NULL;
    }
2534

2535
cleanup:
2536 2537
    if (network)
        virNetworkObjUnlock(network);
2538
    networkDriverUnlock(driver);
2539 2540 2541
    return ret;
}

2542
static char *networkGetXMLDesc(virNetworkPtr net,
2543
                               unsigned int flags)
2544
{
2545 2546 2547
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *ret = NULL;
2548

2549 2550
    virCheckFlags(0, NULL);

2551
    networkDriverLock(driver);
2552
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2553 2554
    networkDriverUnlock(driver);

2555
    if (!network) {
2556
        networkReportError(VIR_ERR_NO_NETWORK,
2557 2558
                           "%s", _("no network with matching uuid"));
        goto cleanup;
2559 2560
    }

2561
    ret = virNetworkDefFormat(network->def);
2562 2563

cleanup:
2564 2565
    if (network)
        virNetworkObjUnlock(network);
2566
    return ret;
2567 2568 2569
}

static char *networkGetBridgeName(virNetworkPtr net) {
2570 2571 2572 2573
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *bridge = NULL;

2574
    networkDriverLock(driver);
2575
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2576 2577
    networkDriverUnlock(driver);

2578
    if (!network) {
2579
        networkReportError(VIR_ERR_NO_NETWORK,
2580 2581
                           "%s", _("no network with matching id"));
        goto cleanup;
2582 2583
    }

2584
    if (!(network->def->bridge)) {
2585
        networkReportError(VIR_ERR_INTERNAL_ERROR,
2586 2587 2588 2589 2590
                           _("network '%s' does not have a bridge name."),
                           network->def->name);
        goto cleanup;
    }

2591
    bridge = strdup(network->def->bridge);
2592
    if (!bridge)
2593
        virReportOOMError();
2594 2595

cleanup:
2596 2597
    if (network)
        virNetworkObjUnlock(network);
2598 2599 2600 2601 2602
    return bridge;
}

static int networkGetAutostart(virNetworkPtr net,
                             int *autostart) {
2603 2604 2605
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
2606

2607
    networkDriverLock(driver);
2608
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2609
    networkDriverUnlock(driver);
2610
    if (!network) {
2611
        networkReportError(VIR_ERR_NO_NETWORK,
2612
                           "%s", _("no network with matching uuid"));
2613
        goto cleanup;
2614 2615 2616
    }

    *autostart = network->autostart;
2617
    ret = 0;
2618

2619
cleanup:
2620 2621
    if (network)
        virNetworkObjUnlock(network);
2622
    return ret;
2623 2624 2625
}

static int networkSetAutostart(virNetworkPtr net,
2626
                               int autostart) {
2627 2628
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
2629
    char *configFile = NULL, *autostartLink = NULL;
2630
    int ret = -1;
2631

2632
    networkDriverLock(driver);
2633
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
2634

2635
    if (!network) {
2636
        networkReportError(VIR_ERR_NO_NETWORK,
2637
                           "%s", _("no network with matching uuid"));
2638
        goto cleanup;
2639 2640
    }

2641
    if (!network->persistent) {
2642
        networkReportError(VIR_ERR_OPERATION_INVALID,
2643
                           "%s", _("cannot set autostart for transient network"));
2644 2645 2646
        goto cleanup;
    }

2647 2648
    autostart = (autostart != 0);

2649
    if (network->autostart != autostart) {
2650
        if ((configFile = virNetworkConfigFile(driver->networkConfigDir, network->def->name)) == NULL)
2651
            goto cleanup;
2652
        if ((autostartLink = virNetworkConfigFile(driver->networkAutostartDir, network->def->name)) == NULL)
2653 2654
            goto cleanup;

2655
        if (autostart) {
2656
            if (virFileMakePath(driver->networkAutostartDir) < 0) {
2657
                virReportSystemError(errno,
2658 2659
                                     _("cannot create autostart directory '%s'"),
                                     driver->networkAutostartDir);
2660 2661
                goto cleanup;
            }
2662

2663
            if (symlink(configFile, autostartLink) < 0) {
2664
                virReportSystemError(errno,
2665
                                     _("Failed to create symlink '%s' to '%s'"),
2666
                                     autostartLink, configFile);
2667 2668 2669
                goto cleanup;
            }
        } else {
2670
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2671
                virReportSystemError(errno,
2672
                                     _("Failed to delete symlink '%s'"),
2673
                                     autostartLink);
2674 2675
                goto cleanup;
            }
2676 2677
        }

2678
        network->autostart = autostart;
2679
    }
2680
    ret = 0;
2681

2682
cleanup:
2683 2684
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
2685 2686
    if (network)
        virNetworkObjUnlock(network);
2687
    networkDriverUnlock(driver);
2688
    return ret;
2689 2690 2691 2692 2693
}


static virNetworkDriver networkDriver = {
    "Network",
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
    .open = networkOpenNetwork, /* 0.2.0 */
    .close = networkCloseNetwork, /* 0.2.0 */
    .numOfNetworks = networkNumNetworks, /* 0.2.0 */
    .listNetworks = networkListNetworks, /* 0.2.0 */
    .numOfDefinedNetworks = networkNumDefinedNetworks, /* 0.2.0 */
    .listDefinedNetworks = networkListDefinedNetworks, /* 0.2.0 */
    .networkLookupByUUID = networkLookupByUUID, /* 0.2.0 */
    .networkLookupByName = networkLookupByName, /* 0.2.0 */
    .networkCreateXML = networkCreate, /* 0.2.0 */
    .networkDefineXML = networkDefine, /* 0.2.0 */
    .networkUndefine = networkUndefine, /* 0.2.0 */
    .networkCreate = networkStart, /* 0.2.0 */
    .networkDestroy = networkDestroy, /* 0.2.0 */
    .networkGetXMLDesc = networkGetXMLDesc, /* 0.2.0 */
    .networkGetBridgeName = networkGetBridgeName, /* 0.2.0 */
    .networkGetAutostart = networkGetAutostart, /* 0.2.1 */
    .networkSetAutostart = networkSetAutostart, /* 0.2.1 */
    .networkIsActive = networkIsActive, /* 0.7.3 */
    .networkIsPersistent = networkIsPersistent, /* 0.7.3 */
2713 2714 2715
};

static virStateDriver networkStateDriver = {
2716
    "Network",
2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
    networkStartup,
    networkShutdown,
    networkReload,
    networkActive,
};

int networkRegister(void) {
    virRegisterNetworkDriver(&networkDriver);
    virRegisterStateDriver(&networkStateDriver);
    return 0;
}
2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798

/********************************************************/

/* Private API to deal with logical switch capabilities.
 * These functions are exported so that other parts of libvirt can
 * call them, but are not part of the public API and not in the
 * driver's function table. If we ever have more than one network
 * driver, we will need to present these functions via a second
 * "backend" function table.
 */

/* networkAllocateActualDevice:
 * @iface: the original NetDef from the domain
 *
 * Looks up the network reference by iface, allocates a physical
 * device from that network (if appropriate), and returns with the
 * virDomainActualNetDef filled in accordingly. If there are no
 * changes to be made in the netdef, then just leave the actualdef
 * empty.
 *
 * Returns 0 on success, -1 on failure.
 */
int
networkAllocateActualDevice(virDomainNetDefPtr iface)
{
    struct network_driver *driver = driverState;
    virNetworkObjPtr network;
    virNetworkDefPtr netdef;
    int ret = -1;

    if (iface->type != VIR_DOMAIN_NET_TYPE_NETWORK)
        return 0;

    virDomainActualNetDefFree(iface->data.network.actual);
    iface->data.network.actual = NULL;

    networkDriverLock(driver);
    network = virNetworkFindByName(&driver->networks, iface->data.network.name);
    networkDriverUnlock(driver);
    if (!network) {
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"),
                           iface->data.network.name);
        goto cleanup;
    }

    netdef = network->def;
    if ((netdef->forwardType == VIR_NETWORK_FORWARD_BRIDGE) &&
        netdef->bridge) {

        /* <forward type='bridge'/> <bridge name='xxx'/>
         * is VIR_DOMAIN_NET_TYPE_BRIDGE
         */

        if (VIR_ALLOC(iface->data.network.actual) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        iface->data.network.actual->type = VIR_DOMAIN_NET_TYPE_BRIDGE;
        iface->data.network.actual->data.bridge.brname = strdup(netdef->bridge);
        if (!iface->data.network.actual->data.bridge.brname) {
            virReportOOMError();
            goto cleanup;
        }

    } else if ((netdef->forwardType == VIR_NETWORK_FORWARD_BRIDGE) ||
               (netdef->forwardType == VIR_NETWORK_FORWARD_PRIVATE) ||
               (netdef->forwardType == VIR_NETWORK_FORWARD_VEPA) ||
               (netdef->forwardType == VIR_NETWORK_FORWARD_PASSTHROUGH)) {
        virVirtualPortProfileParamsPtr virtport = NULL;
2799
        virPortGroupDefPtr portgroup = NULL;
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827

        /* <forward type='bridge|private|vepa|passthrough'> are all
         * VIR_DOMAIN_NET_TYPE_DIRECT.
         */

        if (VIR_ALLOC(iface->data.network.actual) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        /* Set type=direct and appropriate <source mode='xxx'/> */
        iface->data.network.actual->type = VIR_DOMAIN_NET_TYPE_DIRECT;
        switch (netdef->forwardType) {
        case VIR_NETWORK_FORWARD_BRIDGE:
            iface->data.network.actual->data.direct.mode = VIR_MACVTAP_MODE_BRIDGE;
            break;
        case VIR_NETWORK_FORWARD_PRIVATE:
            iface->data.network.actual->data.direct.mode = VIR_MACVTAP_MODE_PRIVATE;
            break;
        case VIR_NETWORK_FORWARD_VEPA:
            iface->data.network.actual->data.direct.mode = VIR_MACVTAP_MODE_VEPA;
            break;
        case VIR_NETWORK_FORWARD_PASSTHROUGH:
            iface->data.network.actual->data.direct.mode = VIR_MACVTAP_MODE_PASSTHRU;
            break;
        }

        /* Find the most specific virtportprofile and copy it */
2828
        portgroup = virPortGroupFindByName(netdef, iface->data.network.portgroup);
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846
        if (iface->data.network.virtPortProfile) {
            virtport = iface->data.network.virtPortProfile;
        } else {
            if (portgroup)
                virtport = portgroup->virtPortProfile;
            else
                virtport = netdef->virtPortProfile;
        }
        if (virtport) {
            if (VIR_ALLOC(iface->data.network.actual->data.direct.virtPortProfile) < 0) {
                virReportOOMError();
                goto cleanup;
            }
            /* There are no pointers in a virtualPortProfile, so a shallow copy
             * is sufficient
             */
            *iface->data.network.actual->data.direct.virtPortProfile = *virtport;
        }
2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861

        /* Find the most specific bandwidth config and copy it */
        if (iface->bandwidth) {
            if (virBandwidthCopy(&iface->data.network.actual->bandwidth,
                                 iface->bandwidth) < 0) {
                goto cleanup;
            }
        } else {
            if (portgroup &&
                virBandwidthCopy(&iface->data.network.actual->bandwidth,
                                 portgroup->bandwidth) < 0) {
                goto cleanup;
            }
        }

2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
        /* If there is only a single device, just return it (caller will detect
         * any error if exclusive use is required but could not be acquired).
         */
        if (netdef->nForwardIfs == 0) {
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("network '%s' uses a direct mode, but has no forward dev and no interface pool"),
                               netdef->name);
            goto cleanup;
        } else {
            int ii;
            virNetworkForwardIfDefPtr dev = NULL;

            /* pick an interface from the pool */

            /* PASSTHROUGH mode, and PRIVATE Mode + 802.1Qbh both require
             * exclusive access to a device, so current usageCount must be
             * 0.  Other modes can share, so just search for the one with
             * the lowest usageCount.
             */
            if ((netdef->forwardType == VIR_NETWORK_FORWARD_PASSTHROUGH) ||
                ((netdef->forwardType == VIR_NETWORK_FORWARD_PRIVATE) &&
                 iface->data.network.actual->data.direct.virtPortProfile &&
                 (iface->data.network.actual->data.direct.virtPortProfile->virtPortType
                  == VIR_VIRTUALPORT_8021QBH))) {
                /* pick first dev with 0 usageCount */

                for (ii = 0; ii < netdef->nForwardIfs; ii++) {
                    if (netdef->forwardIfs[ii].usageCount == 0) {
                        dev = &netdef->forwardIfs[ii];
                        break;
                    }
                }
            } else {
                /* pick least used dev */
                dev = &netdef->forwardIfs[0];
                for (ii = 1; ii < netdef->nForwardIfs; ii++) {
                    if (netdef->forwardIfs[ii].usageCount < dev->usageCount)
                        dev = &netdef->forwardIfs[ii];
                }
            }
            /* dev points at the physical device we want to use */
            if (!dev) {
                networkReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("network '%s' requires exclusive access to interfaces, but none are available"),
                               netdef->name);
                goto cleanup;
            }
            iface->data.network.actual->data.direct.linkdev = strdup(dev->dev);
            if (!iface->data.network.actual->data.direct.linkdev) {
                virReportOOMError();
                goto cleanup;
            }
            /* we are now assured of success, so mark the allocation */
            dev->usageCount++;
            VIR_DEBUG("Using physical device %s, usageCount %d",
                      dev->dev, dev->usageCount);
        }
    }

    ret = 0;
cleanup:
    if (network)
        virNetworkObjUnlock(network);
    if (ret < 0) {
        virDomainActualNetDefFree(iface->data.network.actual);
        iface->data.network.actual = NULL;
    }
    return ret;
}

/* networkNotifyActualDevice:
 * @iface:  the domain's NetDef with an "actual" device already filled in.
 *
 * Called to notify the network driver when libvirtd is restarted and
 * finds an already running domain. If appropriate it will force an
 * allocation of the actual->direct.linkdev to get everything back in
 * order.
 *
 * Returns 0 on success, -1 on failure.
 */
int
networkNotifyActualDevice(virDomainNetDefPtr iface)
{
    struct network_driver *driver = driverState;
    virNetworkObjPtr network;
    virNetworkDefPtr netdef;
    char *actualDev;
    int ret = -1;

    if (iface->type != VIR_DOMAIN_NET_TYPE_NETWORK)
       return 0;

    if (!iface->data.network.actual ||
        (virDomainNetGetActualType(iface) != VIR_DOMAIN_NET_TYPE_DIRECT)) {
        VIR_DEBUG("Nothing to claim from network %s", iface->data.network.name);
        return 0;
    }

    networkDriverLock(driver);
    network = virNetworkFindByName(&driver->networks, iface->data.network.name);
    networkDriverUnlock(driver);
    if (!network) {
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"),
                           iface->data.network.name);
        goto cleanup;
    }

    actualDev = virDomainNetGetActualDirectDev(iface);
    if (!actualDev) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("the interface uses a direct mode, but has no source dev"));
            goto cleanup;
        }

    netdef = network->def;
    if (netdef->nForwardIfs == 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("network '%s' uses a direct mode, but has no forward dev and no interface pool"),
                           netdef->name);
        goto cleanup;
    } else {
        int ii;
        virNetworkForwardIfDefPtr dev = NULL;

        /* find the matching interface in the pool and increment its usageCount */

        for (ii = 0; ii < netdef->nForwardIfs; ii++) {
            if (STREQ(actualDev, netdef->forwardIfs[ii].dev)) {
                dev = &netdef->forwardIfs[ii];
                break;
            }
        }
        /* dev points at the physical device we want to use */
        if (!dev) {
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("network '%s' doesn't have dev='%s' in use by domain"),
                               netdef->name, actualDev);
            goto cleanup;
        }

        /* PASSTHROUGH mode, and PRIVATE Mode + 802.1Qbh both require
         * exclusive access to a device, so current usageCount must be
         * 0 in those cases.
         */
        if ((dev->usageCount > 0) &&
            ((netdef->forwardType == VIR_NETWORK_FORWARD_PASSTHROUGH) ||
             ((netdef->forwardType == VIR_NETWORK_FORWARD_PRIVATE) &&
              iface->data.network.actual->data.direct.virtPortProfile &&
              (iface->data.network.actual->data.direct.virtPortProfile->virtPortType
               == VIR_VIRTUALPORT_8021QBH)))) {
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("network '%s' claims dev='%s' is already in use by a different domain"),
                               netdef->name, actualDev);
            goto cleanup;
        }
        /* we are now assured of success, so mark the allocation */
        dev->usageCount++;
        VIR_DEBUG("Using physical device %s, usageCount %d",
                  dev->dev, dev->usageCount);
    }

    ret = 0;
cleanup:
    if (network)
        virNetworkObjUnlock(network);
    return ret;
}


/* networkReleaseActualDevice:
 * @iface:  a domain's NetDef (interface definition)
 *
 * Given a domain <interface> element that previously had its <actual>
 * element filled in (and possibly a physical device allocated to it),
 * free up the physical device for use by someone else, and free the
 * virDomainActualNetDef.
 *
 * Returns 0 on success, -1 on failure.
 */
int
networkReleaseActualDevice(virDomainNetDefPtr iface)
{
    struct network_driver *driver = driverState;
    virNetworkObjPtr network = NULL;
    virNetworkDefPtr netdef;
    char *actualDev;
    int ret = -1;

    if (iface->type != VIR_DOMAIN_NET_TYPE_NETWORK)
       return 0;

    if (!iface->data.network.actual ||
        (virDomainNetGetActualType(iface) != VIR_DOMAIN_NET_TYPE_DIRECT)) {
        VIR_DEBUG("Nothing to release to network %s", iface->data.network.name);
        ret = 0;
        goto cleanup;
    }

    networkDriverLock(driver);
    network = virNetworkFindByName(&driver->networks, iface->data.network.name);
    networkDriverUnlock(driver);
    if (!network) {
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"),
                           iface->data.network.name);
        goto cleanup;
    }

    actualDev = virDomainNetGetActualDirectDev(iface);
    if (!actualDev) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("the interface uses a direct mode, but has no source dev"));
            goto cleanup;
        }

    netdef = network->def;
    if (netdef->nForwardIfs == 0) {
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           _("network '%s' uses a direct mode, but has no forward dev and no interface pool"),
                           netdef->name);
        goto cleanup;
    } else {
        int ii;
        virNetworkForwardIfDefPtr dev = NULL;

        for (ii = 0; ii < netdef->nForwardIfs; ii++) {
            if (STREQ(actualDev, netdef->forwardIfs[ii].dev)) {
                dev = &netdef->forwardIfs[ii];
                break;
            }
        }
        /* dev points at the physical device we've been using */
        if (!dev) {
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("network '%s' doesn't have dev='%s' in use by domain"),
                               netdef->name, actualDev);
            goto cleanup;
        }

        dev->usageCount--;
        VIR_DEBUG("Releasing physical device %s, usageCount %d",
                  dev->dev, dev->usageCount);
    }

    ret = 0;
cleanup:
    if (network)
        virNetworkObjUnlock(network);
    virDomainActualNetDefFree(iface->data.network.actual);
    iface->data.network.actual = NULL;
    return ret;
}
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144

/*
 * networkGetNetworkAddress:
 * @netname: the name of a network
 * @netaddr: string representation of IP address for that network.
 *
 * Attempt to return an IP (v4) address associated with the named
 * network. If a libvirt virtual network, that will be provided in the
 * configuration. For host bridge and direct (macvtap) networks, we
 * must do an ioctl to learn the address.
 *
 * Note: This function returns the 1st IPv4 address it finds. It might
 * be useful if it was more flexible, but the current use (getting a
 * listen address for qemu's vnc/spice graphics server) can only use a
 * single address anyway.
 *
 * Returns 0 on success, and puts a string (which must be free'd by
 * the caller) into *netaddr. Returns -1 on failure or -2 if
 * completely unsupported.
 */
int
networkGetNetworkAddress(const char *netname, char **netaddr)
{
    int ret = -1;
    struct network_driver *driver = driverState;
    virNetworkObjPtr network = NULL;
    virNetworkDefPtr netdef;
    virNetworkIpDefPtr ipdef;
    virSocketAddr addr;
    virSocketAddrPtr addrptr = NULL;
3145
    char *dev_name = NULL;
3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174

    *netaddr = NULL;
    networkDriverLock(driver);
    network = virNetworkFindByName(&driver->networks, netname);
    networkDriverUnlock(driver);
    if (!network) {
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"),
                           netname);
        goto cleanup;
    }
    netdef = network->def;

    switch (netdef->forwardType) {
    case VIR_NETWORK_FORWARD_NONE:
    case VIR_NETWORK_FORWARD_NAT:
    case VIR_NETWORK_FORWARD_ROUTE:
        /* if there's an ipv4def, get it's address */
        ipdef = virNetworkDefGetIpByIndex(netdef, AF_INET, 0);
        if (!ipdef) {
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("network '%s' doesn't have an IPv4 address"),
                               netdef->name);
            break;
        }
        addrptr = &ipdef->address;
        break;

    case VIR_NETWORK_FORWARD_BRIDGE:
3175
        if ((dev_name = netdef->bridge))
3176 3177 3178 3179 3180 3181 3182 3183 3184
            break;
        /*
         * fall through if netdef->bridge wasn't set, since this is
         * also a direct-mode interface.
         */
    case VIR_NETWORK_FORWARD_PRIVATE:
    case VIR_NETWORK_FORWARD_VEPA:
    case VIR_NETWORK_FORWARD_PASSTHROUGH:
        if ((netdef->nForwardIfs > 0) && netdef->forwardIfs)
3185
            dev_name = netdef->forwardIfs[0].dev;
3186

3187
        if (!dev_name) {
3188 3189 3190 3191 3192 3193 3194
            networkReportError(VIR_ERR_INTERNAL_ERROR,
                               _("network '%s' has no associated interface or bridge"),
                               netdef->name);
        }
        break;
    }

3195 3196
    if (dev_name) {
        if (ifaceGetIPAddress(dev_name, &addr)) {
3197 3198
            virReportSystemError(errno,
                                 _("Failed to get IP address for '%s' (network '%s')"),
3199
                                 dev_name, netdef->name);
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
        } else {
            addrptr = &addr;
        }
    }

    if (addrptr &&
        (*netaddr = virSocketFormatAddr(addrptr))) {
        ret = 0;
    }

cleanup:
    if (network)
        virNetworkObjUnlock(network);
    return ret;
}