bridge_driver.c 58.3 KB
Newer Older
1
/*
2
 * bridge_driver.c: core driver methods for managing network
3
 *
4
 * Copyright (C) 2006-2010 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 52 53 54 55 56 57
#include "network_conf.h"
#include "driver.h"
#include "event.h"
#include "buf.h"
#include "util.h"
#include "memory.h"
#include "uuid.h"
#include "iptables.h"
#include "bridge.h"
58
#include "logging.h"
59
#include "dnsmasq.h"
60
#include "util/network.h"
61

62 63
#define NETWORK_PID_DIR LOCAL_STATE_DIR "/run/libvirt/network"
#define NETWORK_STATE_DIR LOCAL_STATE_DIR "/lib/libvirt/network"
64

65
#define DNSMASQ_STATE_DIR LOCAL_STATE_DIR "/lib/libvirt/dnsmasq"
66

67 68
#define VIR_FROM_THIS VIR_FROM_NETWORK

69
#define networkReportError(code, ...)                                   \
70
    virReportErrorHelper(NULL, VIR_FROM_NETWORK, code, __FILE__,        \
71
                         __FUNCTION__, __LINE__, __VA_ARGS__)
72

73 74
/* Main driver state */
struct network_driver {
75
    virMutex lock;
76

77
    virNetworkObjList networks;
78 79 80 81 82 83 84 85

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

86 87 88

static void networkDriverLock(struct network_driver *driver)
{
89
    virMutexLock(&driver->lock);
90 91 92
}
static void networkDriverUnlock(struct network_driver *driver)
{
93
    virMutexUnlock(&driver->lock);
94 95
}

96 97
static int networkShutdown(void);

98 99
static int networkStartNetworkDaemon(struct network_driver *driver,
                                     virNetworkObjPtr network);
100

101 102
static int networkShutdownNetworkDaemon(struct network_driver *driver,
                                        virNetworkObjPtr network);
103

104 105
static void networkReloadIptablesRules(struct network_driver *driver);

106 107 108
static struct network_driver *driverState = NULL;


109 110 111 112 113 114 115 116 117 118 119
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);

120
        if ((config = virNetworkConfigFile(NETWORK_STATE_DIR,
121 122 123 124 125 126 127 128 129 130 131 132
                                           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 */
133
        tmp = virNetworkDefParseFile(config);
134 135 136 137 138 139 140 141 142 143 144
        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;

145
            /* Finally try and read dnsmasq pid if any */
146
            if ((VIR_SOCKET_HAS_ADDR(&obj->def->ipAddress) ||
147
                 obj->def->nranges) &&
148 149 150 151 152 153 154 155 156 157
                virFileReadPid(NETWORK_PID_DIR, obj->def->name,
                               &obj->dnsmasqPid) == 0) {

                /* Check its still alive */
                if (kill(obj->dnsmasqPid, 0) != 0)
                    obj->dnsmasqPid = -1;

#ifdef __linux__
                char *pidpath;

158
                if (virAsprintf(&pidpath, "/proc/%d/exe", obj->dnsmasqPid) < 0) {
159
                    virReportOOMError();
160 161
                    goto cleanup;
                }
162 163 164 165 166 167 168
                if (virFileLinkPointsTo(pidpath, DNSMASQ) == 0)
                    obj->dnsmasqPid = -1;
                VIR_FREE(pidpath);
#endif
            }
        }

169
    cleanup:
170 171 172 173 174
        virNetworkObjUnlock(obj);
    }
}


175 176 177
static void
networkAutostartConfigs(struct network_driver *driver) {
    unsigned int i;
178

179
    for (i = 0 ; i < driver->networks.count ; i++) {
180
        virNetworkObjLock(driver->networks.objs[i]);
181
        if (driver->networks.objs[i]->autostart &&
D
Daniel P. Berrange 已提交
182
            !virNetworkObjIsActive(driver->networks.objs[i]) &&
183
            networkStartNetworkDaemon(driver, driver->networks.objs[i]) < 0) {
184
            /* failed to start but already logged */
185
        }
186
        virNetworkObjUnlock(driver->networks.objs[i]);
187 188 189 190 191 192 193 194 195
    }
}

/**
 * networkStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
196
networkStartup(int privileged) {
197 198
    uid_t uid = geteuid();
    char *base = NULL;
199
    int err;
200 201

    if (VIR_ALLOC(driverState) < 0)
202
        goto error;
203

204 205 206 207
    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        goto error;
    }
208 209
    networkDriverLock(driverState);

210
    if (privileged) {
211 212
        if (virAsprintf(&driverState->logDir,
                        "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
213 214 215 216 217
            goto out_of_memory;

        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
            goto out_of_memory;
    } else {
218
        char *userdir = virGetUserDirectory(uid);
219 220 221

        if (!userdir)
            goto error;
222

223
        if (virAsprintf(&driverState->logDir,
224 225
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
226
            goto out_of_memory;
227
        }
228

229 230
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
231 232
            goto out_of_memory;
        }
233
        VIR_FREE(userdir);
234 235 236 237 238
    }

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

242 243
    if (virAsprintf(&driverState->networkAutostartDir, "%s/qemu/networks/autostart",
                    base) == -1)
244 245 246 247
        goto out_of_memory;

    VIR_FREE(base);

248
    if ((err = brInit(&driverState->brctl))) {
249
        virReportSystemError(err, "%s",
250 251 252 253 254
                             _("cannot initialize bridge support"));
        goto error;
    }

    if (!(driverState->iptables = iptablesContextNew())) {
255
        goto out_of_memory;
256 257 258
    }


259
    if (virNetworkLoadAllConfigs(&driverState->networks,
260
                                 driverState->networkConfigDir,
261 262 263
                                 driverState->networkAutostartDir) < 0)
        goto error;

264
    networkFindActiveConfigs(driverState);
265
    networkReloadIptablesRules(driverState);
266 267
    networkAutostartConfigs(driverState);

268 269
    networkDriverUnlock(driverState);

270 271
    return 0;

272
out_of_memory:
273
    virReportOOMError();
274 275

error:
276 277 278
    if (driverState)
        networkDriverUnlock(driverState);

279
    VIR_FREE(base);
280
    networkShutdown();
281 282 283 284 285 286 287 288 289 290 291
    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) {
292 293 294
    if (!driverState)
        return 0;

295
    networkDriverLock(driverState);
296
    virNetworkLoadAllConfigs(&driverState->networks,
297 298
                             driverState->networkConfigDir,
                             driverState->networkAutostartDir);
299
    networkReloadIptablesRules(driverState);
300
    networkAutostartConfigs(driverState);
301
    networkDriverUnlock(driverState);
302 303 304 305 306 307 308 309 310 311 312 313 314
    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) {
315
    unsigned int i;
316
    int active = 0;
317

318 319 320
    if (!driverState)
        return 0;

321
    networkDriverLock(driverState);
322 323
    for (i = 0 ; i < driverState->networks.count ; i++) {
        virNetworkObjPtr net = driverState->networks.objs[i];
324
        virNetworkObjLock(net);
D
Daniel P. Berrange 已提交
325
        if (virNetworkObjIsActive(net))
326
            active = 1;
327
        virNetworkObjUnlock(net);
328
    }
329
    networkDriverUnlock(driverState);
330
    return active;
331 332 333 334 335 336 337 338 339 340 341 342
}

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

343 344
    networkDriverLock(driverState);

345
    /* free inactive networks */
346
    virNetworkObjListFree(&driverState->networks);
347 348 349 350 351 352 353 354 355 356

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

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

357
    networkDriverUnlock(driverState);
358
    virMutexDestroy(&driverState->lock);
359

360 361 362 363 364 365
    VIR_FREE(driverState);

    return 0;
}


366 367 368 369 370 371 372 373 374 375 376 377
static int
networkSaveDnsmasqHostsfile(virNetworkObjPtr network,
                            dnsmasqContext *dctx,
                            bool force)
{
    unsigned int i;

    if (! force && virFileExists(dctx->hostsfile->path))
        return 1;

    for (i = 0 ; i < network->def->nhosts ; i++) {
        virNetworkDHCPHostDefPtr host = &(network->def->hosts[i]);
378 379
        if ((host->mac) && VIR_SOCKET_HAS_ADDR(&host->ip))
            dnsmasqAddDhcpHost(dctx, host->mac, &host->ip, host->name);
380 381 382 383 384 385 386 387 388
    }

    if (dnsmasqSave(dctx) < 0)
        return 0;

    return 1;
}


389
static int
390
networkBuildDnsmasqArgv(virNetworkObjPtr network,
391 392
                        const char *pidfile,
                        const char ***argv) {
393
    int i, len, r;
394
    int nbleases = 0;
395 396
    char *pidfileArg;
    char buf[1024];
397
    unsigned int ranges;
398
    char *ipAddr;
399 400 401 402 403 404 405 406 407

    /*
     * 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.
     */
    ranges = network->def->nranges;
    if (!ranges && network->def->nhosts)
        ranges = 1;
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

    /*
     * NB, be careful about syntax for dnsmasq options in long format
     *
     * 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,
     * without reading the dnsmasq source :-( The manpages is not
     * very explicit on this
     */
427 428 429 430 431 432

    len =
        1 + /* dnsmasq */
        1 + /* --strict-order */
        1 + /* --bind-interfaces */
        (network->def->domain?2:0) + /* --domain name */
433
        2 + /* --pid-file /var/run/libvirt/network/$NAME.pid */
434 435 436 437
        2 + /* --conf-file "" */
        /*2 + *//* --interface virbr0 */
        2 + /* --except-interface lo */
        2 + /* --listen-address 10.0.0.1 */
438
        (2 * ranges) + /* --dhcp-range 10.0.0.2,10.0.0.254 */
439
        /* --dhcp-lease-max=xxx if needed */
440
        (network->def->nranges ? 1 : 0) +
441
        /* --dhcp-no-override if needed */
442
        (ranges ? 1 : 0) +
443 444
        /* --dhcp-hostsfile=/var/lib/dnsmasq/$NAME.hostsfile */
        (network->def->nhosts > 0 ? 1 : 0) +
445 446
        /* --enable-tftp --tftp-root /srv/tftp */
        (network->def->tftproot ? 3 : 0) +
447
        /* --dhcp-boot pxeboot.img[,,12.34.56.78] */
448
        (network->def->bootfile ? 2 : 0) +
449 450 451 452 453 454 455 456 457 458
        1;  /* NULL */

    if (VIR_ALLOC_N(*argv, len) < 0)
        goto no_memory;

#define APPEND_ARG(v, n, s) do {     \
        if (!((v)[(n)] = strdup(s))) \
            goto no_memory;          \
    } while (0)

459 460 461
#define APPEND_ARG_LIT(v, n, s) \
        (v)[(n)] = s

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    i = 0;

    APPEND_ARG(*argv, i++, DNSMASQ);

    /*
     * Needed to ensure dnsmasq uses same algorithm for processing
     * multiple namedriver entries in /etc/resolv.conf as GLibC.
     */
    APPEND_ARG(*argv, i++, "--strict-order");
    APPEND_ARG(*argv, i++, "--bind-interfaces");

    if (network->def->domain) {
       APPEND_ARG(*argv, i++, "--domain");
       APPEND_ARG(*argv, i++, network->def->domain);
    }

478 479 480
    if (virAsprintf(&pidfileArg, "--pid-file=%s", pidfile) < 0)
        goto no_memory;
    APPEND_ARG_LIT(*argv, i++, pidfileArg);
481

482
    APPEND_ARG(*argv, i++, "--conf-file=");
483 484 485 486 487 488 489 490 491 492 493 494
    APPEND_ARG(*argv, i++, "");

    /*
     * XXX does not actually work, due to some kind of
     * race condition setting up ipv6 addresses on the
     * interface. A sleep(10) makes it work, but that's
     * clearly not practical
     *
     * APPEND_ARG(*argv, i++, "--interface");
     * APPEND_ARG(*argv, i++, network->def->bridge);
     */
    APPEND_ARG(*argv, i++, "--listen-address");
495 496 497
    if (!(ipAddr = virSocketFormatAddr(&network->def->ipAddress)))
        goto error;
    APPEND_ARG_LIT(*argv, i++, ipAddr);
498 499 500 501 502

    APPEND_ARG(*argv, i++, "--except-interface");
    APPEND_ARG(*argv, i++, "lo");

    for (r = 0 ; r < network->def->nranges ; r++) {
503 504 505 506 507 508 509 510 511 512 513 514 515 516
        char *saddr = virSocketFormatAddr(&network->def->ranges[r].start);
        if (!saddr)
            goto error;
        char *eaddr = virSocketFormatAddr(&network->def->ranges[r].end);
        if (!eaddr) {
            VIR_FREE(saddr);
            goto error;
        }
        char *range;
        int rc = virAsprintf(&range, "%s,%s", saddr, eaddr);
        VIR_FREE(saddr);
        VIR_FREE(eaddr);
        if (rc < 0)
            goto no_memory;
517
        APPEND_ARG(*argv, i++, "--dhcp-range");
518 519 520
        APPEND_ARG_LIT(*argv, i++, range);
        nbleases += virSocketGetRange(&network->def->ranges[r].start,
                                      &network->def->ranges[r].end);
521 522
    }

523
    if (!network->def->nranges && network->def->nhosts) {
524 525 526 527 528 529 530 531
        char *ipaddr = virSocketFormatAddr(&network->def->ipAddress);
        if (!ipaddr)
            goto error;
        char *range;
        int rc = virAsprintf(&range, "%s,static", ipaddr);
        VIR_FREE(ipaddr);
        if (rc < 0)
            goto no_memory;
532 533

        APPEND_ARG(*argv, i++, "--dhcp-range");
534
        APPEND_ARG_LIT(*argv, i++, range);
535 536
    }

537 538 539
    if (network->def->nranges > 0) {
        snprintf(buf, sizeof(buf), "--dhcp-lease-max=%d", nbleases);
        APPEND_ARG(*argv, i++, buf);
540 541
    }

542 543 544
    if (ranges)
        APPEND_ARG(*argv, i++, "--dhcp-no-override");

545 546 547
    if (network->def->nhosts > 0) {
        dnsmasqContext *dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
        char *hostsfileArg;
548

549 550 551 552 553 554 555 556 557 558 559 560
        if (dctx == NULL)
            goto no_memory;

        if (networkSaveDnsmasqHostsfile(network, dctx, false)) {
            if (virAsprintf(&hostsfileArg, "--dhcp-hostsfile=%s", dctx->hostsfile->path) < 0) {
                dnsmasqContextFree(dctx);
                goto no_memory;
            }
            APPEND_ARG_LIT(*argv, i++, hostsfileArg);
        }

        dnsmasqContextFree(dctx);
561 562
    }

563 564 565 566 567 568
    if (network->def->tftproot) {
        APPEND_ARG(*argv, i++, "--enable-tftp");
        APPEND_ARG(*argv, i++, "--tftp-root");
        APPEND_ARG(*argv, i++, network->def->tftproot);
    }
    if (network->def->bootfile) {
569 570 571 572 573 574 575 576 577 578 579 580 581
        char *ipaddr = NULL;
        if (VIR_SOCKET_HAS_ADDR(&network->def->bootserver)) {
            if (!(ipaddr = virSocketFormatAddr(&network->def->bootserver)))
                goto error;
        }
        char *boot;
        int rc = virAsprintf(&boot, "%s%s%s",
                             network->def->bootfile,
                             ipaddr ? ",," : "",
                             ipaddr ? ipaddr : "");
        VIR_FREE(ipaddr);
        if (rc < 0)
            goto no_memory;
582

583
        APPEND_ARG(*argv, i++, "--dhcp-boot");
584
        APPEND_ARG_LIT(*argv, i++, boot);
585 586
    }

587 588 589 590 591
#undef APPEND_ARG

    return 0;

 no_memory:
592 593
    virReportOOMError();
  error:
594
    if (*argv) {
595 596 597 598 599 600 601 602 603
        for (i = 0; (*argv)[i]; i++)
            VIR_FREE((*argv)[i]);
        VIR_FREE(*argv);
    }
    return -1;
}


static int
604
dhcpStartDhcpDaemon(virNetworkObjPtr network)
605 606
{
    const char **argv;
607 608 609 610
    char *pidfile;
    int ret = -1, i, err;

    network->dnsmasqPid = -1;
611

612
    if (!VIR_SOCKET_IS_FAMILY(&network->def->ipAddress, AF_INET)) {
613
        networkReportError(VIR_ERR_INTERNAL_ERROR,
614
                           "%s", _("cannot start dhcp daemon without IPv4 address for server"));
615 616 617
        return -1;
    }

L
Laine Stump 已提交
618
    if ((err = virFileMakePath(NETWORK_PID_DIR)) != 0) {
619
        virReportSystemError(err,
620 621 622 623
                             _("cannot create directory %s"),
                             NETWORK_PID_DIR);
        return -1;
    }
L
Laine Stump 已提交
624
    if ((err = virFileMakePath(NETWORK_STATE_DIR)) != 0) {
625
        virReportSystemError(err,
626 627 628 629 630 631
                             _("cannot create directory %s"),
                             NETWORK_STATE_DIR);
        return -1;
    }

    if (!(pidfile = virFilePid(NETWORK_PID_DIR, network->def->name))) {
632
        virReportOOMError();
633 634 635
        return -1;
    }

636
    argv = NULL;
637
    if (networkBuildDnsmasqArgv(network, pidfile, &argv) < 0) {
638
        VIR_FREE(pidfile);
639
        return -1;
640 641
    }

642
    if (virRun(argv, NULL) < 0)
643 644 645 646 647 648 649 650 651 652 653 654 655
        goto cleanup;

    /*
     * 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 virRun exits
     * it has waitpid'd and guaranteed the proess has started
     * and written a pid
     */

    if (virFileReadPid(NETWORK_PID_DIR, network->def->name,
                       &network->dnsmasqPid) < 0)
        goto cleanup;
656

657
    ret = 0;
658

659 660
cleanup:
    VIR_FREE(pidfile);
661 662 663 664 665 666 667 668
    for (i = 0; argv[i]; i++)
        VIR_FREE(argv[i]);
    VIR_FREE(argv);

    return ret;
}

static int
669 670
networkAddMasqueradingIptablesRules(struct network_driver *driver,
                                    virNetworkObjPtr network) {
671 672 673
    int err;
    /* allow forwarding packets from the bridge interface */
    if ((err = iptablesAddForwardAllowOut(driver->iptables,
674 675
                                          &network->def->ipAddress,
                                          &network->def->netmask,
676 677
                                          network->def->bridge,
                                          network->def->forwardDev))) {
678
        virReportSystemError(err,
679 680
                             _("failed to add iptables rule to allow forwarding from '%s'"),
                             network->def->bridge);
681 682 683 684 685
        goto masqerr1;
    }

    /* allow forwarding packets to the bridge interface if they are part of an existing connection */
    if ((err = iptablesAddForwardAllowRelatedIn(driver->iptables,
686 687 688 689
                                                &network->def->ipAddress,
                                                &network->def->netmask,
                                                network->def->bridge,
                                                network->def->forwardDev))) {
690
        virReportSystemError(err,
691 692
                             _("failed to add iptables rule to allow forwarding to '%s'"),
                             network->def->bridge);
693 694 695
        goto masqerr2;
    }

696 697 698 699 700
    /*
     * Enable masquerading.
     *
     * We need to end up with 3 rules in the table in this order
     *
E
Eric Blake 已提交
701 702
     *  1. protocol=tcp with sport mapping restriction
     *  2. protocol=udp with sport mapping restriction
703 704 705
     *  3. generic any protocol
     *
     * The sport mappings are required, because default IPtables
E
Eric Blake 已提交
706
     * MASQUERADE maintain port numbers unchanged where possible.
707 708 709 710 711 712 713 714 715 716 717 718 719
     *
     * 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 */
720
    if ((err = iptablesAddForwardMasquerade(driver->iptables,
721 722
                                            &network->def->ipAddress,
                                            &network->def->netmask,
723 724
                                            network->def->forwardDev,
                                            NULL))) {
725
        virReportSystemError(err,
726
                             _("failed to add iptables rule to enable masquerading to '%s'"),
727
                             network->def->forwardDev ? network->def->forwardDev : NULL);
728 729 730
        goto masqerr3;
    }

731 732
    /* UDP with a source port restriction */
    if ((err = iptablesAddForwardMasquerade(driver->iptables,
733 734
                                            &network->def->ipAddress,
                                            &network->def->netmask,
735 736 737 738 739 740 741 742 743 744
                                            network->def->forwardDev,
                                            "udp"))) {
        virReportSystemError(err,
                             _("failed to add iptables rule to enable UDP masquerading to '%s'"),
                             network->def->forwardDev ? network->def->forwardDev : NULL);
        goto masqerr4;
    }

    /* TCP with a source port restriction */
    if ((err = iptablesAddForwardMasquerade(driver->iptables,
745 746
                                            &network->def->ipAddress,
                                            &network->def->netmask,
747 748 749 750 751 752 753 754
                                            network->def->forwardDev,
                                            "tcp"))) {
        virReportSystemError(err,
                             _("failed to add iptables rule to enable TCP masquerading to '%s'"),
                             network->def->forwardDev ? network->def->forwardDev : NULL);
        goto masqerr5;
    }

755 756
    return 1;

757 758
 masqerr5:
    iptablesRemoveForwardMasquerade(driver->iptables,
759 760
                                    &network->def->ipAddress,
                                    &network->def->netmask,
761 762 763 764
                                    network->def->forwardDev,
                                    "udp");
 masqerr4:
    iptablesRemoveForwardMasquerade(driver->iptables,
765 766
                                    &network->def->ipAddress,
                                    &network->def->netmask,
767 768
                                    network->def->forwardDev,
                                    NULL);
769 770
 masqerr3:
    iptablesRemoveForwardAllowRelatedIn(driver->iptables,
771 772 773 774
                                        &network->def->ipAddress,
                                        &network->def->netmask,
                                        network->def->bridge,
                                        network->def->forwardDev);
775 776
 masqerr2:
    iptablesRemoveForwardAllowOut(driver->iptables,
777 778
                                  &network->def->ipAddress,
                                  &network->def->netmask,
779 780 781 782 783 784 785
                                  network->def->bridge,
                                  network->def->forwardDev);
 masqerr1:
    return 0;
}

static int
786 787
networkAddRoutingIptablesRules(struct network_driver *driver,
                               virNetworkObjPtr network) {
788 789 790
    int err;
    /* allow routing packets from the bridge interface */
    if ((err = iptablesAddForwardAllowOut(driver->iptables,
791 792
                                          &network->def->ipAddress,
                                          &network->def->netmask,
793 794
                                          network->def->bridge,
                                          network->def->forwardDev))) {
795
        virReportSystemError(err,
796 797
                             _("failed to add iptables rule to allow routing from '%s'"),
                             network->def->bridge);
798 799 800 801 802
        goto routeerr1;
    }

    /* allow routing packets to the bridge interface */
    if ((err = iptablesAddForwardAllowIn(driver->iptables,
803 804
                                         &network->def->ipAddress,
                                         &network->def->netmask,
805 806
                                         network->def->bridge,
                                         network->def->forwardDev))) {
807
        virReportSystemError(err,
808 809
                             _("failed to add iptables rule to allow routing to '%s'"),
                             network->def->bridge);
810 811 812 813 814 815 816 817
        goto routeerr2;
    }

    return 1;


 routeerr2:
    iptablesRemoveForwardAllowOut(driver->iptables,
818 819
                                  &network->def->ipAddress,
                                  &network->def->netmask,
820 821 822 823 824 825 826
                                  network->def->bridge,
                                  network->def->forwardDev);
 routeerr1:
    return 0;
}

static int
827 828
networkAddIptablesRules(struct network_driver *driver,
                        virNetworkObjPtr network) {
829 830 831 832
    int err;

    /* allow DHCP requests through to dnsmasq */
    if ((err = iptablesAddTcpInput(driver->iptables, network->def->bridge, 67))) {
833
        virReportSystemError(err,
834 835
                             _("failed to add iptables rule to allow DHCP requests from '%s'"),
                             network->def->bridge);
836 837 838 839
        goto err1;
    }

    if ((err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 67))) {
840
        virReportSystemError(err,
841 842
                             _("failed to add iptables rule to allow DHCP requests from '%s'"),
                             network->def->bridge);
843 844 845 846 847
        goto err2;
    }

    /* allow DNS requests through to dnsmasq */
    if ((err = iptablesAddTcpInput(driver->iptables, network->def->bridge, 53))) {
848
        virReportSystemError(err,
849 850
                             _("failed to add iptables rule to allow DNS requests from '%s'"),
                             network->def->bridge);
851 852 853 854
        goto err3;
    }

    if ((err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 53))) {
855
        virReportSystemError(err,
856 857
                             _("failed to add iptables rule to allow DNS requests from '%s'"),
                             network->def->bridge);
858 859 860
        goto err4;
    }

861 862 863 864 865 866 867 868 869
    /* allow TFTP requests through to dnsmasq */
    if (network->def->tftproot &&
        (err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 69))) {
        virReportSystemError(err,
                             _("failed to add iptables rule to allow TFTP requests from '%s'"),
                             network->def->bridge);
        goto err4tftp;
    }

870 871 872 873

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

    if ((err = iptablesAddForwardRejectOut(driver->iptables, network->def->bridge))) {
874
        virReportSystemError(err,
875 876
                             _("failed to add iptables rule to block outbound traffic from '%s'"),
                             network->def->bridge);
877 878 879 880
        goto err5;
    }

    if ((err = iptablesAddForwardRejectIn(driver->iptables, network->def->bridge))) {
881
        virReportSystemError(err,
882 883
                             _("failed to add iptables rule to block inbound traffic to '%s'"),
                             network->def->bridge);
884 885 886 887 888
        goto err6;
    }

    /* Allow traffic between guests on the same bridge */
    if ((err = iptablesAddForwardAllowCross(driver->iptables, network->def->bridge))) {
889
        virReportSystemError(err,
890 891
                             _("failed to add iptables rule to allow cross bridge traffic on '%s'"),
                             network->def->bridge);
892 893 894 895 896 897
        goto err7;
    }


    /* If masquerading is enabled, set up the rules*/
    if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT &&
898
        !networkAddMasqueradingIptablesRules(driver, network))
899 900 901
        goto err8;
    /* else if routing is enabled, set up the rules*/
    else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE &&
902
             !networkAddRoutingIptablesRules(driver, network))
903 904
        goto err8;

905 906 907 908 909 910
    /* 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).
     */

911 912
    if ((VIR_SOCKET_HAS_ADDR(&network->def->ipAddress) ||
         network->def->nranges) &&
913 914 915 916 917 918 919
        (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);
        VIR_WARN0("May need to update iptables package & kernel to support CHECKSUM rule.");
    }

920 921 922 923 924 925 926 927 928 929 930 931
    return 1;

 err8:
    iptablesRemoveForwardAllowCross(driver->iptables,
                                    network->def->bridge);
 err7:
    iptablesRemoveForwardRejectIn(driver->iptables,
                                  network->def->bridge);
 err6:
    iptablesRemoveForwardRejectOut(driver->iptables,
                                   network->def->bridge);
 err5:
932 933 934 935
    if (network->def->tftproot) {
        iptablesRemoveUdpInput(driver->iptables, network->def->bridge, 69);
    }
 err4tftp:
936 937 938 939 940 941 942 943 944 945 946 947 948 949
    iptablesRemoveUdpInput(driver->iptables, network->def->bridge, 53);
 err4:
    iptablesRemoveTcpInput(driver->iptables, network->def->bridge, 53);
 err3:
    iptablesRemoveUdpInput(driver->iptables, network->def->bridge, 67);
 err2:
    iptablesRemoveTcpInput(driver->iptables, network->def->bridge, 67);
 err1:
    return 0;
}

static void
networkRemoveIptablesRules(struct network_driver *driver,
                         virNetworkObjPtr network) {
950 951
    if (VIR_SOCKET_HAS_ADDR(&network->def->ipAddress) ||
        network->def->nranges) {
952 953 954
        iptablesRemoveOutputFixUdpChecksum(driver->iptables,
                                           network->def->bridge, 68);
    }
955
    if (network->def->forwardType != VIR_NETWORK_FORWARD_NONE) {
956 957
        if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT) {
            iptablesRemoveForwardMasquerade(driver->iptables,
958 959
                                            &network->def->ipAddress,
                                            &network->def->netmask,
960 961 962
                                            network->def->forwardDev,
                                            "tcp");
            iptablesRemoveForwardMasquerade(driver->iptables,
963 964
                                            &network->def->ipAddress,
                                            &network->def->netmask,
965 966 967
                                            network->def->forwardDev,
                                            "udp");
            iptablesRemoveForwardMasquerade(driver->iptables,
968 969
                                            &network->def->ipAddress,
                                            &network->def->netmask,
970 971
                                            network->def->forwardDev,
                                            NULL);
972
            iptablesRemoveForwardAllowRelatedIn(driver->iptables,
973 974
                                                &network->def->ipAddress,
                                                &network->def->netmask,
975 976
                                                network->def->bridge,
                                                network->def->forwardDev);
977
        } else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE)
978
            iptablesRemoveForwardAllowIn(driver->iptables,
979 980
                                         &network->def->ipAddress,
                                         &network->def->netmask,
981 982 983 984
                                         network->def->bridge,
                                         network->def->forwardDev);

        iptablesRemoveForwardAllowOut(driver->iptables,
985 986
                                      &network->def->ipAddress,
                                      &network->def->netmask,
987 988 989 990 991 992
                                      network->def->bridge,
                                      network->def->forwardDev);
    }
    iptablesRemoveForwardAllowCross(driver->iptables, network->def->bridge);
    iptablesRemoveForwardRejectIn(driver->iptables, network->def->bridge);
    iptablesRemoveForwardRejectOut(driver->iptables, network->def->bridge);
993
    iptablesRemoveUdpInput(driver->iptables, network->def->bridge, 69);
994 995 996 997 998 999
    iptablesRemoveUdpInput(driver->iptables, network->def->bridge, 53);
    iptablesRemoveTcpInput(driver->iptables, network->def->bridge, 53);
    iptablesRemoveUdpInput(driver->iptables, network->def->bridge, 67);
    iptablesRemoveTcpInput(driver->iptables, network->def->bridge, 67);
}

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
static void
networkReloadIptablesRules(struct network_driver *driver)
{
    unsigned int i;

    VIR_INFO0(_("Reloading iptables rules"));

    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);

        if (virNetworkObjIsActive(driver->networks.objs[i])) {
            networkRemoveIptablesRules(driver, driver->networks.objs[i]);
1012
            if (!networkAddIptablesRules(driver, driver->networks.objs[i])) {
1013 1014 1015 1016 1017 1018 1019 1020
                /* failed to add but already logged */
            }
        }

        virNetworkObjUnlock(driver->networks.objs[i]);
    }
}

1021
/* Enable IP Forwarding. Return 0 for success, -1 for failure. */
1022 1023 1024
static int
networkEnableIpForwarding(void)
{
M
Mark McLoughlin 已提交
1025
    return virFileWriteStr("/proc/sys/net/ipv4/ip_forward", "1\n");
1026 1027
}

1028 1029
#define SYSCTL_PATH "/proc/sys"

1030
static int networkDisableIPV6(virNetworkObjPtr network)
1031 1032 1033 1034 1035
{
    char *field = NULL;
    int ret = -1;

    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/disable_ipv6", network->def->bridge) < 0) {
1036
        virReportOOMError();
1037 1038 1039
        goto cleanup;
    }

1040 1041 1042 1043 1044 1045
    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;
    }

1046
    if (virFileWriteStr(field, "1") < 0) {
1047
        virReportSystemError(errno,
1048 1049 1050 1051 1052 1053
                             _("cannot enable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra", network->def->bridge) < 0) {
1054
        virReportOOMError();
1055 1056 1057 1058
        goto cleanup;
    }

    if (virFileWriteStr(field, "0") < 0) {
1059
        virReportSystemError(errno,
1060 1061 1062 1063 1064 1065
                             _("cannot disable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/autoconf", network->def->bridge) < 0) {
1066
        virReportOOMError();
1067 1068 1069 1070
        goto cleanup;
    }

    if (virFileWriteStr(field, "1") < 0) {
1071
        virReportSystemError(errno,
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
                             _("cannot enable %s"), field);
        goto cleanup;
    }

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

1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
#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
 */
static int networkCheckRouteCollision(virNetworkObjPtr network)
{
    int ret = -1, len;
    unsigned int net_dest;
    char *cur, *buf = NULL;
    enum {MAX_ROUTE_SIZE = 1024*64};

1095 1096
    if (!VIR_SOCKET_IS_FAMILY(&network->def->ipAddress, AF_INET) ||
        !VIR_SOCKET_IS_FAMILY(&network->def->netmask, AF_INET)) {
1097
        /* Only support collision check for IPv4 */
1098
        return 0;
1099 1100
    }

1101 1102
    net_dest = (network->def->ipAddress.data.inet4.sin_addr.s_addr &
                network->def->netmask.data.inet4.sin_addr.s_addr);
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154

    /* Read whole routing table into memory */
    if ((len = virFileReadAll(PROC_NET_ROUTE, MAX_ROUTE_SIZE, &buf)) < 0)
        goto error;

    /* 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;
        int num;

        /* 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;

        if ((net_dest == addr_val) &&
1155
            (network->def->netmask.data.inet4.sin_addr.s_addr == mask_val)) {
1156
            networkReportError(VIR_ERR_INTERNAL_ERROR,
1157 1158
                               _("Network is already in use by interface %s"),
                               iface);
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
            goto error;
        }
    }

out:
    ret = 0;
error:
    VIR_FREE(buf);
    return ret;
}

1170 1171 1172
static int networkStartNetworkDaemon(struct network_driver *driver,
                                     virNetworkObjPtr network)
{
1173
    int err;
1174
    virErrorPtr save_err;
1175

D
Daniel P. Berrange 已提交
1176
    if (virNetworkObjIsActive(network)) {
1177 1178
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("network is already active"));
1179 1180 1181
        return -1;
    }

1182 1183 1184 1185
    /* Check to see if network collides with an existing route */
    if (networkCheckRouteCollision(network) < 0)
        return -1;

1186
    if ((err = brAddBridge(driver->brctl, network->def->bridge))) {
1187
        virReportSystemError(err,
1188 1189
                             _("cannot create bridge '%s'"),
                             network->def->bridge);
1190 1191 1192
        return -1;
    }

1193
    if (networkDisableIPV6(network) < 0)
1194 1195
        goto err_delbr;

1196 1197 1198 1199 1200 1201
    if (brSetForwardDelay(driver->brctl, network->def->bridge, network->def->delay) < 0)
        goto err_delbr;

    if (brSetEnableSTP(driver->brctl, network->def->bridge, network->def->stp ? 1 : 0) < 0)
        goto err_delbr;

1202 1203 1204
    if (VIR_SOCKET_HAS_ADDR(&network->def->ipAddress) &&
        (err = brSetInetAddress(driver->brctl, network->def->bridge,
                                &network->def->ipAddress))) {
1205
        virReportSystemError(err,
1206 1207
                             _("cannot set IP address on bridge '%s'"),
                             network->def->bridge);
1208 1209 1210
        goto err_delbr;
    }

1211 1212 1213
    if (VIR_SOCKET_HAS_ADDR(&network->def->netmask) &&
        (err = brSetInetNetmask(driver->brctl, network->def->bridge,
                                &network->def->netmask))) {
1214
        virReportSystemError(err,
1215 1216
                             _("cannot set netmask on bridge '%s'"),
                             network->def->bridge);
1217 1218 1219
        goto err_delbr;
    }

1220
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 1))) {
1221
        virReportSystemError(err,
1222 1223
                             _("failed to bring the bridge '%s' up"),
                             network->def->bridge);
1224 1225 1226
        goto err_delbr;
    }

1227
    if (!networkAddIptablesRules(driver, network))
1228 1229 1230
        goto err_delbr1;

    if (network->def->forwardType != VIR_NETWORK_FORWARD_NONE &&
1231
        networkEnableIpForwarding() < 0) {
1232
        virReportSystemError(errno, "%s",
1233
                             _("failed to enable IP forwarding"));
1234 1235 1236
        goto err_delbr2;
    }

1237
    if ((VIR_SOCKET_HAS_ADDR(&network->def->ipAddress) ||
1238
         network->def->nranges) &&
1239
        dhcpStartDhcpDaemon(network) < 0)
1240 1241
        goto err_delbr2;

1242 1243

    /* Persist the live configuration now we have bridge info  */
1244
    if (virNetworkSaveConfig(NETWORK_STATE_DIR, network->def) < 0) {
1245 1246 1247
        goto err_kill;
    }

1248 1249 1250 1251
    network->active = 1;

    return 0;

1252 1253 1254 1255 1256 1257
 err_kill:
    if (network->dnsmasqPid > 0) {
        kill(network->dnsmasqPid, SIGTERM);
        network->dnsmasqPid = -1;
    }

1258
 err_delbr2:
1259
    save_err = virSaveLastError();
1260
    networkRemoveIptablesRules(driver, network);
1261 1262 1263 1264
    if (save_err) {
        virSetError(save_err);
        virFreeError(save_err);
    }
1265 1266

 err_delbr1:
1267
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
1268
        char ebuf[1024];
1269
        VIR_WARN("Failed to bring down bridge '%s' : %s",
1270
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1271 1272 1273 1274
    }

 err_delbr:
    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
1275
        char ebuf[1024];
1276
        VIR_WARN("Failed to delete bridge '%s' : %s",
1277
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1278 1279 1280 1281 1282 1283
    }

    return -1;
}


1284 1285 1286
static int networkShutdownNetworkDaemon(struct network_driver *driver,
                                        virNetworkObjPtr network)
{
1287
    int err;
1288
    char *stateFile;
1289

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

D
Daniel P. Berrange 已提交
1292
    if (!virNetworkObjIsActive(network))
1293 1294
        return 0;

1295
    stateFile = virNetworkConfigFile(NETWORK_STATE_DIR, network->def->name);
1296 1297 1298 1299 1300 1301
    if (!stateFile)
        return -1;

    unlink(stateFile);
    VIR_FREE(stateFile);

1302 1303 1304 1305 1306
    if (network->dnsmasqPid > 0)
        kill(network->dnsmasqPid, SIGTERM);

    networkRemoveIptablesRules(driver, network);

1307
    char ebuf[1024];
1308
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
1309
        VIR_WARN("Failed to bring down bridge '%s' : %s",
1310
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1311 1312 1313
    }

    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
1314
        VIR_WARN("Failed to delete bridge '%s' : %s",
1315
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1316 1317
    }

1318
    /* See if its still alive and really really kill it */
1319
    if (network->dnsmasqPid > 0 &&
1320
        (kill(network->dnsmasqPid, 0) == 0))
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
        kill(network->dnsmasqPid, SIGKILL);

    network->dnsmasqPid = -1;
    network->active = 0;

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

    return 0;
}


1336 1337 1338 1339 1340
static virNetworkPtr networkLookupByUUID(virConnectPtr conn,
                                         const unsigned char *uuid) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;
1341

1342
    networkDriverLock(driver);
1343
    network = virNetworkFindByUUID(&driver->networks, uuid);
1344
    networkDriverUnlock(driver);
1345
    if (!network) {
1346 1347
        networkReportError(VIR_ERR_NO_NETWORK,
                           "%s", _("no network with matching uuid"));
1348
        goto cleanup;
1349 1350
    }

1351 1352 1353
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
1354 1355
    if (network)
        virNetworkObjUnlock(network);
1356
    return ret;
1357 1358
}

1359 1360 1361 1362 1363 1364
static virNetworkPtr networkLookupByName(virConnectPtr conn,
                                         const char *name) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;

1365
    networkDriverLock(driver);
1366
    network = virNetworkFindByName(&driver->networks, name);
1367
    networkDriverUnlock(driver);
1368
    if (!network) {
1369 1370
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"), name);
1371
        goto cleanup;
1372 1373
    }

1374 1375 1376
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
1377 1378
    if (network)
        virNetworkObjUnlock(network);
1379
    return ret;
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
}

static virDrvOpenStatus networkOpenNetwork(virConnectPtr conn,
                                           virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                           int flags ATTRIBUTE_UNUSED) {
    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) {
1398
    int nactive = 0, i;
1399
    struct network_driver *driver = conn->networkPrivateData;
1400

1401 1402 1403
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1404
        if (virNetworkObjIsActive(driver->networks.objs[i]))
1405
            nactive++;
1406 1407 1408
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
1409

1410 1411 1412 1413
    return nactive;
}

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

1417
    networkDriverLock(driver);
1418
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
1419
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1420
        if (virNetworkObjIsActive(driver->networks.objs[i])) {
1421
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
1422
                virNetworkObjUnlock(driver->networks.objs[i]);
1423
                virReportOOMError();
1424 1425 1426 1427
                goto cleanup;
            }
            got++;
        }
1428
        virNetworkObjUnlock(driver->networks.objs[i]);
1429
    }
1430 1431
    networkDriverUnlock(driver);

1432 1433 1434
    return got;

 cleanup:
1435
    networkDriverUnlock(driver);
1436 1437 1438 1439 1440 1441
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

static int networkNumDefinedNetworks(virConnectPtr conn) {
1442
    int ninactive = 0, i;
1443
    struct network_driver *driver = conn->networkPrivateData;
1444

1445 1446 1447
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1448
        if (!virNetworkObjIsActive(driver->networks.objs[i]))
1449
            ninactive++;
1450 1451 1452
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
1453

1454 1455 1456 1457
    return ninactive;
}

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

1461
    networkDriverLock(driver);
1462
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
1463
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1464
        if (!virNetworkObjIsActive(driver->networks.objs[i])) {
1465
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
1466
                virNetworkObjUnlock(driver->networks.objs[i]);
1467
                virReportOOMError();
1468 1469 1470 1471
                goto cleanup;
            }
            got++;
        }
1472
        virNetworkObjUnlock(driver->networks.objs[i]);
1473
    }
1474
    networkDriverUnlock(driver);
1475 1476 1477
    return got;

 cleanup:
1478
    networkDriverUnlock(driver);
1479 1480 1481 1482 1483
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

1484 1485 1486

static int networkIsActive(virNetworkPtr net)
{
1487
    struct network_driver *driver = net->conn->networkPrivateData;
1488 1489 1490 1491 1492 1493 1494
    virNetworkObjPtr obj;
    int ret = -1;

    networkDriverLock(driver);
    obj = virNetworkFindByUUID(&driver->networks, net->uuid);
    networkDriverUnlock(driver);
    if (!obj) {
1495
        networkReportError(VIR_ERR_NO_NETWORK, NULL);
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
        goto cleanup;
    }
    ret = virNetworkObjIsActive(obj);

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

static int networkIsPersistent(virNetworkPtr net)
{
1508
    struct network_driver *driver = net->conn->networkPrivateData;
1509 1510 1511 1512 1513 1514 1515
    virNetworkObjPtr obj;
    int ret = -1;

    networkDriverLock(driver);
    obj = virNetworkFindByUUID(&driver->networks, net->uuid);
    networkDriverUnlock(driver);
    if (!obj) {
1516
        networkReportError(VIR_ERR_NO_NETWORK, NULL);
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
        goto cleanup;
    }
    ret = obj->persistent;

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


1528
static virNetworkPtr networkCreate(virConnectPtr conn, const char *xml) {
1529
    struct network_driver *driver = conn->networkPrivateData;
1530
    virNetworkDefPtr def;
1531
    virNetworkObjPtr network = NULL;
1532
    virNetworkPtr ret = NULL;
1533

1534 1535
    networkDriverLock(driver);

1536
    if (!(def = virNetworkDefParseString(xml)))
1537
        goto cleanup;
1538

1539 1540 1541
    if (virNetworkObjIsDuplicate(&driver->networks, def, 1) < 0)
        goto cleanup;

1542
    if (virNetworkSetBridgeName(&driver->networks, def, 1))
1543 1544
        goto cleanup;

1545
    if (!(network = virNetworkAssignDef(&driver->networks,
1546 1547 1548
                                        def)))
        goto cleanup;
    def = NULL;
1549

1550
    if (networkStartNetworkDaemon(driver, network) < 0) {
1551 1552
        virNetworkRemoveInactive(&driver->networks,
                                 network);
1553
        network = NULL;
1554
        goto cleanup;
1555 1556
    }

1557 1558 1559 1560
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
1561 1562 1563
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1564
    return ret;
1565 1566 1567
}

static virNetworkPtr networkDefine(virConnectPtr conn, const char *xml) {
1568
    struct network_driver *driver = conn->networkPrivateData;
1569
    virNetworkDefPtr def;
1570
    virNetworkObjPtr network = NULL;
1571
    virNetworkPtr ret = NULL;
1572

1573 1574
    networkDriverLock(driver);

1575
    if (!(def = virNetworkDefParseString(xml)))
1576
        goto cleanup;
1577

E
Eric Blake 已提交
1578
    if (virNetworkObjIsDuplicate(&driver->networks, def, 0) < 0)
1579 1580
        goto cleanup;

1581
    if (virNetworkSetBridgeName(&driver->networks, def, 1))
1582 1583
        goto cleanup;

1584
    if (!(network = virNetworkAssignDef(&driver->networks,
1585 1586 1587
                                        def)))
        goto cleanup;
    def = NULL;
1588

1589 1590
    network->persistent = 1;

1591
    if (virNetworkSaveConfig(driver->networkConfigDir,
1592
                             network->newDef ? network->newDef : network->def) < 0) {
1593 1594
        virNetworkRemoveInactive(&driver->networks,
                                 network);
1595
        network = NULL;
1596
        goto cleanup;
1597 1598
    }

1599 1600 1601 1602 1603 1604 1605 1606 1607
    if (network->def->nhosts > 0) {
        dnsmasqContext *dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
        if (dctx == NULL)
            goto cleanup;

        networkSaveDnsmasqHostsfile(network, dctx, true);
        dnsmasqContextFree(dctx);
    }

1608 1609 1610 1611
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
1612 1613 1614
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1615
    return ret;
1616 1617 1618
}

static int networkUndefine(virNetworkPtr net) {
1619
    struct network_driver *driver = net->conn->networkPrivateData;
1620
    virNetworkObjPtr network = NULL;
1621
    int ret = -1;
1622

1623 1624
    networkDriverLock(driver);

1625
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1626
    if (!network) {
1627
        networkReportError(VIR_ERR_INVALID_NETWORK,
1628 1629
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1630 1631
    }

D
Daniel P. Berrange 已提交
1632
    if (virNetworkObjIsActive(network)) {
1633
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1634 1635
                           "%s", _("network is still active"));
        goto cleanup;
1636 1637
    }

1638
    if (virNetworkDeleteConfig(driver->networkConfigDir,
1639 1640
                               driver->networkAutostartDir,
                               network) < 0)
1641
        goto cleanup;
1642

1643 1644 1645 1646 1647 1648 1649 1650 1651
    if (network->def->nhosts > 0) {
        dnsmasqContext *dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
        if (dctx == NULL)
            goto cleanup;

        dnsmasqDelete(dctx);
        dnsmasqContextFree(dctx);
    }

1652 1653
    virNetworkRemoveInactive(&driver->networks,
                             network);
1654
    network = NULL;
1655
    ret = 0;
1656

1657
cleanup:
1658 1659 1660
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1661
    return ret;
1662 1663 1664
}

static int networkStart(virNetworkPtr net) {
1665 1666 1667
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1668

1669
    networkDriverLock(driver);
1670
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1671

1672
    if (!network) {
1673
        networkReportError(VIR_ERR_INVALID_NETWORK,
1674 1675
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1676 1677
    }

1678
    ret = networkStartNetworkDaemon(driver, network);
1679 1680

cleanup:
1681 1682
    if (network)
        virNetworkObjUnlock(network);
1683
    networkDriverUnlock(driver);
1684
    return ret;
1685 1686 1687
}

static int networkDestroy(virNetworkPtr net) {
1688 1689 1690
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1691

1692
    networkDriverLock(driver);
1693
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1694

1695
    if (!network) {
1696
        networkReportError(VIR_ERR_INVALID_NETWORK,
1697 1698
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1699 1700
    }

D
Daniel P. Berrange 已提交
1701
    if (!virNetworkObjIsActive(network)) {
1702
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1703 1704 1705 1706
                           "%s", _("network is not active"));
        goto cleanup;
    }

1707
    ret = networkShutdownNetworkDaemon(driver, network);
1708
    if (!network->persistent) {
1709 1710 1711 1712
        virNetworkRemoveInactive(&driver->networks,
                                 network);
        network = NULL;
    }
1713

1714
cleanup:
1715 1716
    if (network)
        virNetworkObjUnlock(network);
1717
    networkDriverUnlock(driver);
1718 1719 1720 1721
    return ret;
}

static char *networkDumpXML(virNetworkPtr net, int flags ATTRIBUTE_UNUSED) {
1722 1723 1724
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *ret = NULL;
1725

1726
    networkDriverLock(driver);
1727
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1728 1729
    networkDriverUnlock(driver);

1730
    if (!network) {
1731
        networkReportError(VIR_ERR_INVALID_NETWORK,
1732 1733
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1734 1735
    }

1736
    ret = virNetworkDefFormat(network->def);
1737 1738

cleanup:
1739 1740
    if (network)
        virNetworkObjUnlock(network);
1741
    return ret;
1742 1743 1744
}

static char *networkGetBridgeName(virNetworkPtr net) {
1745 1746 1747 1748
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *bridge = NULL;

1749
    networkDriverLock(driver);
1750
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1751 1752
    networkDriverUnlock(driver);

1753
    if (!network) {
1754
        networkReportError(VIR_ERR_INVALID_NETWORK,
1755 1756
                           "%s", _("no network with matching id"));
        goto cleanup;
1757 1758
    }

1759
    if (!(network->def->bridge)) {
1760
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1761 1762 1763 1764 1765
                           _("network '%s' does not have a bridge name."),
                           network->def->name);
        goto cleanup;
    }

1766
    bridge = strdup(network->def->bridge);
1767
    if (!bridge)
1768
        virReportOOMError();
1769 1770

cleanup:
1771 1772
    if (network)
        virNetworkObjUnlock(network);
1773 1774 1775 1776 1777
    return bridge;
}

static int networkGetAutostart(virNetworkPtr net,
                             int *autostart) {
1778 1779 1780
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1781

1782
    networkDriverLock(driver);
1783
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1784
    networkDriverUnlock(driver);
1785
    if (!network) {
1786 1787
        networkReportError(VIR_ERR_INVALID_NETWORK,
                           "%s", _("no network with matching uuid"));
1788
        goto cleanup;
1789 1790 1791
    }

    *autostart = network->autostart;
1792
    ret = 0;
1793

1794
cleanup:
1795 1796
    if (network)
        virNetworkObjUnlock(network);
1797
    return ret;
1798 1799 1800
}

static int networkSetAutostart(virNetworkPtr net,
1801
                               int autostart) {
1802 1803
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
1804
    char *configFile = NULL, *autostartLink = NULL;
1805
    int ret = -1;
1806

1807
    networkDriverLock(driver);
1808
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1809

1810
    if (!network) {
1811 1812
        networkReportError(VIR_ERR_INVALID_NETWORK,
                           "%s", _("no network with matching uuid"));
1813
        goto cleanup;
1814 1815
    }

1816
    if (!network->persistent) {
1817 1818
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot set autostart for transient network"));
1819 1820 1821
        goto cleanup;
    }

1822 1823
    autostart = (autostart != 0);

1824
    if (network->autostart != autostart) {
1825
        if ((configFile = virNetworkConfigFile(driver->networkConfigDir, network->def->name)) == NULL)
1826
            goto cleanup;
1827
        if ((autostartLink = virNetworkConfigFile(driver->networkAutostartDir, network->def->name)) == NULL)
1828 1829
            goto cleanup;

1830
        if (autostart) {
1831
            if (virFileMakePath(driver->networkAutostartDir)) {
1832
                virReportSystemError(errno,
1833 1834
                                     _("cannot create autostart directory '%s'"),
                                     driver->networkAutostartDir);
1835 1836
                goto cleanup;
            }
1837

1838
            if (symlink(configFile, autostartLink) < 0) {
1839
                virReportSystemError(errno,
1840
                                     _("Failed to create symlink '%s' to '%s'"),
1841
                                     autostartLink, configFile);
1842 1843 1844
                goto cleanup;
            }
        } else {
1845
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1846
                virReportSystemError(errno,
1847
                                     _("Failed to delete symlink '%s'"),
1848
                                     autostartLink);
1849 1850
                goto cleanup;
            }
1851 1852
        }

1853
        network->autostart = autostart;
1854
    }
1855
    ret = 0;
1856

1857
cleanup:
1858 1859
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
1860 1861
    if (network)
        virNetworkObjUnlock(network);
1862
    networkDriverUnlock(driver);
1863
    return ret;
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
}


static virNetworkDriver networkDriver = {
    "Network",
    networkOpenNetwork, /* open */
    networkCloseNetwork, /* close */
    networkNumNetworks, /* numOfNetworks */
    networkListNetworks, /* listNetworks */
    networkNumDefinedNetworks, /* numOfDefinedNetworks */
    networkListDefinedNetworks, /* listDefinedNetworks */
    networkLookupByUUID, /* networkLookupByUUID */
    networkLookupByName, /* networkLookupByName */
    networkCreate, /* networkCreateXML */
    networkDefine, /* networkDefineXML */
    networkUndefine, /* networkUndefine */
    networkStart, /* networkCreate */
    networkDestroy, /* networkDestroy */
    networkDumpXML, /* networkDumpXML */
    networkGetBridgeName, /* networkGetBridgeName */
    networkGetAutostart, /* networkGetAutostart */
    networkSetAutostart, /* networkSetAutostart */
1886 1887
    networkIsActive,
    networkIsPersistent,
1888 1889 1890
};

static virStateDriver networkStateDriver = {
1891
    "Network",
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
    networkStartup,
    networkShutdown,
    networkReload,
    networkActive,
};

int networkRegister(void) {
    virRegisterNetworkDriver(&networkDriver);
    virRegisterStateDriver(&networkStateDriver);
    return 0;
}