bridge_driver.c 47.9 KB
Newer Older
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
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

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

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

66 67
#define VIR_FROM_THIS VIR_FROM_NETWORK

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

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

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

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

85 86 87

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

95 96
static int networkShutdown(void);

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

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

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

105 106 107
static struct network_driver *driverState = NULL;


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

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

144 145 146
            /* Finally try and read dnsmasq pid if any */
            if ((obj->def->ipAddress ||
                 obj->def->nranges) &&
147 148 149 150 151 152 153 154 155 156
                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;

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

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


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

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

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

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

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

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

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

        if (!userdir)
            goto error;
221

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

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

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

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

    VIR_FREE(base);

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

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


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

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

267 268
    networkDriverUnlock(driverState);

269 270
    return 0;

271
out_of_memory:
272
    virReportOOMError();
273 274

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

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

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

317 318 319
    if (!driverState)
        return 0;

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

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

342 343
    networkDriverLock(driverState);

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

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

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

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

359 360 361 362 363 364
    VIR_FREE(driverState);

    return 0;
}


365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
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]);
        if ((host->mac) && (host->ip))
            dnsmasqAddDhcpHost(dctx, host->mac, host->ip, host->name);
    }

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

    return 1;
}


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

    /*
     * 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
     */
415 416 417 418 419 420

    len =
        1 + /* dnsmasq */
        1 + /* --strict-order */
        1 + /* --bind-interfaces */
        (network->def->domain?2:0) + /* --domain name */
421
        2 + /* --pid-file /var/run/libvirt/network/$NAME.pid */
422 423 424 425 426
        2 + /* --conf-file "" */
        /*2 + *//* --interface virbr0 */
        2 + /* --except-interface lo */
        2 + /* --listen-address 10.0.0.1 */
        (2 * network->def->nranges) + /* --dhcp-range 10.0.0.2,10.0.0.254 */
427 428
        /* --dhcp-lease-max=xxx if needed */
        (network->def->nranges ? 0 : 1) +
429 430
        /* --dhcp-hostsfile=/var/lib/dnsmasq/$NAME.hostsfile */
        (network->def->nhosts > 0 ? 1 : 0) +
431 432
        /* --enable-tftp --tftp-root /srv/tftp */
        (network->def->tftproot ? 3 : 0) +
433
        /* --dhcp-boot pxeboot.img[,,12.34.56.78] */
434
        (network->def->bootfile ? 2 : 0) +
435 436 437 438 439 440 441 442 443 444
        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)

445 446 447
#define APPEND_ARG_LIT(v, n, s) \
        (v)[(n)] = s

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    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);
    }

464 465 466
    if (virAsprintf(&pidfileArg, "--pid-file=%s", pidfile) < 0)
        goto no_memory;
    APPEND_ARG_LIT(*argv, i++, pidfileArg);
467

468
    APPEND_ARG(*argv, i++, "--conf-file=");
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
    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");
    APPEND_ARG(*argv, i++, network->def->ipAddress);

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

    for (r = 0 ; r < network->def->nranges ; r++) {
        snprintf(buf, sizeof(buf), "%s,%s",
                 network->def->ranges[r].start,
                 network->def->ranges[r].end);

        APPEND_ARG(*argv, i++, "--dhcp-range");
        APPEND_ARG(*argv, i++, buf);
493 494 495 496 497 498
        nbleases += network->def->ranges[r].size;
    }

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

501 502 503
    if (network->def->nhosts > 0) {
        dnsmasqContext *dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
        char *hostsfileArg;
504

505 506 507 508 509 510 511 512 513 514 515 516
        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);
517 518
    }

519 520 521 522 523 524
    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) {
525 526 527 528 529
        snprintf(buf, sizeof(buf), "%s%s%s",
                 network->def->bootfile,
                 network->def->bootserver ? ",," : "",
                 network->def->bootserver ? network->def->bootserver : "");

530
        APPEND_ARG(*argv, i++, "--dhcp-boot");
531
        APPEND_ARG(*argv, i++, buf);
532 533
    }

534 535 536 537 538
#undef APPEND_ARG

    return 0;

 no_memory:
539
    if (*argv) {
540 541 542 543
        for (i = 0; (*argv)[i]; i++)
            VIR_FREE((*argv)[i]);
        VIR_FREE(*argv);
    }
544
    virReportOOMError();
545 546 547 548 549
    return -1;
}


static int
550
dhcpStartDhcpDaemon(virNetworkObjPtr network)
551 552
{
    const char **argv;
553 554 555 556
    char *pidfile;
    int ret = -1, i, err;

    network->dnsmasqPid = -1;
557 558

    if (network->def->ipAddress == NULL) {
559 560
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot start dhcp daemon without IP address for server"));
561 562 563
        return -1;
    }

L
Laine Stump 已提交
564
    if ((err = virFileMakePath(NETWORK_PID_DIR)) != 0) {
565
        virReportSystemError(err,
566 567 568 569
                             _("cannot create directory %s"),
                             NETWORK_PID_DIR);
        return -1;
    }
L
Laine Stump 已提交
570
    if ((err = virFileMakePath(NETWORK_STATE_DIR)) != 0) {
571
        virReportSystemError(err,
572 573 574 575 576 577
                             _("cannot create directory %s"),
                             NETWORK_STATE_DIR);
        return -1;
    }

    if (!(pidfile = virFilePid(NETWORK_PID_DIR, network->def->name))) {
578
        virReportOOMError();
579 580 581
        return -1;
    }

582
    argv = NULL;
583
    if (networkBuildDnsmasqArgv(network, pidfile, &argv) < 0) {
584
        VIR_FREE(pidfile);
585
        return -1;
586 587
    }

588
    if (virRun(argv, NULL) < 0)
589 590 591 592 593 594 595 596 597 598 599 600 601
        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;
602

603
    ret = 0;
604

605 606
cleanup:
    VIR_FREE(pidfile);
607 608 609 610 611 612 613 614
    for (i = 0; argv[i]; i++)
        VIR_FREE(argv[i]);
    VIR_FREE(argv);

    return ret;
}

static int
615 616
networkAddMasqueradingIptablesRules(struct network_driver *driver,
                                    virNetworkObjPtr network) {
617 618 619 620 621 622
    int err;
    /* allow forwarding packets from the bridge interface */
    if ((err = iptablesAddForwardAllowOut(driver->iptables,
                                          network->def->network,
                                          network->def->bridge,
                                          network->def->forwardDev))) {
623
        virReportSystemError(err,
624 625
                             _("failed to add iptables rule to allow forwarding from '%s'"),
                             network->def->bridge);
626 627 628 629 630 631 632 633
        goto masqerr1;
    }

    /* allow forwarding packets to the bridge interface if they are part of an existing connection */
    if ((err = iptablesAddForwardAllowRelatedIn(driver->iptables,
                                         network->def->network,
                                         network->def->bridge,
                                         network->def->forwardDev))) {
634
        virReportSystemError(err,
635 636
                             _("failed to add iptables rule to allow forwarding to '%s'"),
                             network->def->bridge);
637 638 639 640 641 642 643
        goto masqerr2;
    }

    /* enable masquerading */
    if ((err = iptablesAddForwardMasquerade(driver->iptables,
                                            network->def->network,
                                            network->def->forwardDev))) {
644
        virReportSystemError(err,
645 646
                             _("failed to add iptables rule to enable masquerading to '%s'\n"),
                             network->def->forwardDev ? network->def->forwardDev : NULL);
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
        goto masqerr3;
    }

    return 1;

 masqerr3:
    iptablesRemoveForwardAllowRelatedIn(driver->iptables,
                                 network->def->network,
                                 network->def->bridge,
                                 network->def->forwardDev);
 masqerr2:
    iptablesRemoveForwardAllowOut(driver->iptables,
                                  network->def->network,
                                  network->def->bridge,
                                  network->def->forwardDev);
 masqerr1:
    return 0;
}

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

    /* allow routing packets to the bridge interface */
    if ((err = iptablesAddForwardAllowIn(driver->iptables,
                                         network->def->network,
                                         network->def->bridge,
                                         network->def->forwardDev))) {
686
        virReportSystemError(err,
687 688
                             _("failed to add iptables rule to allow routing to '%s'"),
                             network->def->bridge);
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
        goto routeerr2;
    }

    return 1;


 routeerr2:
    iptablesRemoveForwardAllowOut(driver->iptables,
                                  network->def->network,
                                  network->def->bridge,
                                  network->def->forwardDev);
 routeerr1:
    return 0;
}

static int
705 706
networkAddIptablesRules(struct network_driver *driver,
                        virNetworkObjPtr network) {
707 708 709 710
    int err;

    /* allow DHCP requests through to dnsmasq */
    if ((err = iptablesAddTcpInput(driver->iptables, network->def->bridge, 67))) {
711
        virReportSystemError(err,
712 713
                             _("failed to add iptables rule to allow DHCP requests from '%s'"),
                             network->def->bridge);
714 715 716 717
        goto err1;
    }

    if ((err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 67))) {
718
        virReportSystemError(err,
719 720
                             _("failed to add iptables rule to allow DHCP requests from '%s'"),
                             network->def->bridge);
721 722 723 724 725
        goto err2;
    }

    /* allow DNS requests through to dnsmasq */
    if ((err = iptablesAddTcpInput(driver->iptables, network->def->bridge, 53))) {
726
        virReportSystemError(err,
727 728
                             _("failed to add iptables rule to allow DNS requests from '%s'"),
                             network->def->bridge);
729 730 731 732
        goto err3;
    }

    if ((err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 53))) {
733
        virReportSystemError(err,
734 735
                             _("failed to add iptables rule to allow DNS requests from '%s'"),
                             network->def->bridge);
736 737 738 739 740 741 742
        goto err4;
    }


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

    if ((err = iptablesAddForwardRejectOut(driver->iptables, network->def->bridge))) {
743
        virReportSystemError(err,
744 745
                             _("failed to add iptables rule to block outbound traffic from '%s'"),
                             network->def->bridge);
746 747 748 749
        goto err5;
    }

    if ((err = iptablesAddForwardRejectIn(driver->iptables, network->def->bridge))) {
750
        virReportSystemError(err,
751 752
                             _("failed to add iptables rule to block inbound traffic to '%s'"),
                             network->def->bridge);
753 754 755 756 757
        goto err6;
    }

    /* Allow traffic between guests on the same bridge */
    if ((err = iptablesAddForwardAllowCross(driver->iptables, network->def->bridge))) {
758
        virReportSystemError(err,
759 760
                             _("failed to add iptables rule to allow cross bridge traffic on '%s'"),
                             network->def->bridge);
761 762 763 764 765 766
        goto err7;
    }


    /* If masquerading is enabled, set up the rules*/
    if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT &&
767
        !networkAddMasqueradingIptablesRules(driver, network))
768 769 770
        goto err8;
    /* else if routing is enabled, set up the rules*/
    else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE &&
771
             !networkAddRoutingIptablesRules(driver, network))
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
        goto err8;

    return 1;

 err8:
    iptablesRemoveForwardAllowCross(driver->iptables,
                                    network->def->bridge);
 err7:
    iptablesRemoveForwardRejectIn(driver->iptables,
                                  network->def->bridge);
 err6:
    iptablesRemoveForwardRejectOut(driver->iptables,
                                   network->def->bridge);
 err5:
    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) {
    if (network->def->forwardType != VIR_NETWORK_FORWARD_NONE) {
801 802 803 804
        if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT) {
            iptablesRemoveForwardMasquerade(driver->iptables,
                                                network->def->network,
                                                network->def->forwardDev);
805 806 807 808
            iptablesRemoveForwardAllowRelatedIn(driver->iptables,
                                                network->def->network,
                                                network->def->bridge,
                                                network->def->forwardDev);
809
        } else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE)
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
            iptablesRemoveForwardAllowIn(driver->iptables,
                                         network->def->network,
                                         network->def->bridge,
                                         network->def->forwardDev);

        iptablesRemoveForwardAllowOut(driver->iptables,
                                      network->def->network,
                                      network->def->bridge,
                                      network->def->forwardDev);
    }
    iptablesRemoveForwardAllowCross(driver->iptables, network->def->bridge);
    iptablesRemoveForwardRejectIn(driver->iptables, network->def->bridge);
    iptablesRemoveForwardRejectOut(driver->iptables, network->def->bridge);
    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);
}

829 830 831 832 833 834 835 836 837 838 839 840
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]);
841
            if (!networkAddIptablesRules(driver, driver->networks.objs[i])) {
842 843 844 845 846 847 848 849
                /* failed to add but already logged */
            }
        }

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

850
/* Enable IP Forwarding. Return 0 for success, -1 for failure. */
851 852 853
static int
networkEnableIpForwarding(void)
{
M
Mark McLoughlin 已提交
854
    return virFileWriteStr("/proc/sys/net/ipv4/ip_forward", "1\n");
855 856
}

857 858
#define SYSCTL_PATH "/proc/sys"

859
static int networkDisableIPV6(virNetworkObjPtr network)
860 861 862 863 864
{
    char *field = NULL;
    int ret = -1;

    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/disable_ipv6", network->def->bridge) < 0) {
865
        virReportOOMError();
866 867 868
        goto cleanup;
    }

869 870 871 872 873 874
    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;
    }

875
    if (virFileWriteStr(field, "1") < 0) {
876
        virReportSystemError(errno,
877 878 879 880 881 882
                             _("cannot enable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/accept_ra", network->def->bridge) < 0) {
883
        virReportOOMError();
884 885 886 887
        goto cleanup;
    }

    if (virFileWriteStr(field, "0") < 0) {
888
        virReportSystemError(errno,
889 890 891 892 893 894
                             _("cannot disable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

    if (virAsprintf(&field, SYSCTL_PATH "/net/ipv6/conf/%s/autoconf", network->def->bridge) < 0) {
895
        virReportOOMError();
896 897 898 899
        goto cleanup;
    }

    if (virFileWriteStr(field, "1") < 0) {
900
        virReportSystemError(errno,
901 902 903 904 905 906 907 908 909 910
                             _("cannot enable %s"), field);
        goto cleanup;
    }

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

911 912 913
static int networkStartNetworkDaemon(struct network_driver *driver,
                                     virNetworkObjPtr network)
{
914 915
    int err;

D
Daniel P. Berrange 已提交
916
    if (virNetworkObjIsActive(network)) {
917 918
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("network is already active"));
919 920 921
        return -1;
    }

922
    if ((err = brAddBridge(driver->brctl, network->def->bridge))) {
923
        virReportSystemError(err,
924 925
                             _("cannot create bridge '%s'"),
                             network->def->bridge);
926 927 928
        return -1;
    }

929
    if (networkDisableIPV6(network) < 0)
930 931
        goto err_delbr;

932 933 934 935 936 937 938 939
    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;

    if (network->def->ipAddress &&
        (err = brSetInetAddress(driver->brctl, network->def->bridge, network->def->ipAddress))) {
940
        virReportSystemError(err,
941 942
                             _("cannot set IP address on bridge '%s' to '%s'"),
                             network->def->bridge, network->def->ipAddress);
943 944 945 946 947
        goto err_delbr;
    }

    if (network->def->netmask &&
        (err = brSetInetNetmask(driver->brctl, network->def->bridge, network->def->netmask))) {
948
        virReportSystemError(err,
949 950
                             _("cannot set netmask on bridge '%s' to '%s'"),
                             network->def->bridge, network->def->netmask);
951 952 953
        goto err_delbr;
    }

954
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 1))) {
955
        virReportSystemError(err,
956 957
                             _("failed to bring the bridge '%s' up"),
                             network->def->bridge);
958 959 960
        goto err_delbr;
    }

961
    if (!networkAddIptablesRules(driver, network))
962 963 964
        goto err_delbr1;

    if (network->def->forwardType != VIR_NETWORK_FORWARD_NONE &&
965
        networkEnableIpForwarding() < 0) {
966
        virReportSystemError(errno, "%s",
967
                             _("failed to enable IP forwarding"));
968 969 970
        goto err_delbr2;
    }

971 972
    if ((network->def->ipAddress ||
         network->def->nranges) &&
973
        dhcpStartDhcpDaemon(network) < 0)
974 975
        goto err_delbr2;

976 977

    /* Persist the live configuration now we have bridge info  */
978
    if (virNetworkSaveConfig(NETWORK_STATE_DIR, network->def) < 0) {
979 980 981
        goto err_kill;
    }

982 983 984 985
    network->active = 1;

    return 0;

986 987 988 989 990 991
 err_kill:
    if (network->dnsmasqPid > 0) {
        kill(network->dnsmasqPid, SIGTERM);
        network->dnsmasqPid = -1;
    }

992 993 994 995
 err_delbr2:
    networkRemoveIptablesRules(driver, network);

 err_delbr1:
996
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
997
        char ebuf[1024];
998
        VIR_WARN(_("Failed to bring down bridge '%s' : %s"),
999
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1000 1001 1002 1003
    }

 err_delbr:
    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
1004
        char ebuf[1024];
1005
        VIR_WARN(_("Failed to delete bridge '%s' : %s"),
1006
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1007 1008 1009 1010 1011 1012
    }

    return -1;
}


1013 1014 1015
static int networkShutdownNetworkDaemon(struct network_driver *driver,
                                        virNetworkObjPtr network)
{
1016
    int err;
1017
    char *stateFile;
1018

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

D
Daniel P. Berrange 已提交
1021
    if (!virNetworkObjIsActive(network))
1022 1023
        return 0;

1024
    stateFile = virNetworkConfigFile(NETWORK_STATE_DIR, network->def->name);
1025 1026 1027 1028 1029 1030
    if (!stateFile)
        return -1;

    unlink(stateFile);
    VIR_FREE(stateFile);

1031 1032 1033 1034 1035
    if (network->dnsmasqPid > 0)
        kill(network->dnsmasqPid, SIGTERM);

    networkRemoveIptablesRules(driver, network);

1036
    char ebuf[1024];
1037
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
1038
        VIR_WARN(_("Failed to bring down bridge '%s' : %s"),
1039
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1040 1041 1042
    }

    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
1043
        VIR_WARN(_("Failed to delete bridge '%s' : %s"),
1044
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
1045 1046
    }

1047
    /* See if its still alive and really really kill it */
1048
    if (network->dnsmasqPid > 0 &&
1049
        (kill(network->dnsmasqPid, 0) == 0))
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        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;
}


1065 1066 1067 1068 1069
static virNetworkPtr networkLookupByUUID(virConnectPtr conn,
                                         const unsigned char *uuid) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;
1070

1071
    networkDriverLock(driver);
1072
    network = virNetworkFindByUUID(&driver->networks, uuid);
1073
    networkDriverUnlock(driver);
1074
    if (!network) {
1075 1076
        networkReportError(VIR_ERR_NO_NETWORK,
                           "%s", _("no network with matching uuid"));
1077
        goto cleanup;
1078 1079
    }

1080 1081 1082
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
1083 1084
    if (network)
        virNetworkObjUnlock(network);
1085
    return ret;
1086 1087
}

1088 1089 1090 1091 1092 1093
static virNetworkPtr networkLookupByName(virConnectPtr conn,
                                         const char *name) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;

1094
    networkDriverLock(driver);
1095
    network = virNetworkFindByName(&driver->networks, name);
1096
    networkDriverUnlock(driver);
1097
    if (!network) {
1098 1099
        networkReportError(VIR_ERR_NO_NETWORK,
                           _("no network with matching name '%s'"), name);
1100
        goto cleanup;
1101 1102
    }

1103 1104 1105
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
1106 1107
    if (network)
        virNetworkObjUnlock(network);
1108
    return ret;
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
}

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) {
1127
    int nactive = 0, i;
1128
    struct network_driver *driver = conn->networkPrivateData;
1129

1130 1131 1132
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1133
        if (virNetworkObjIsActive(driver->networks.objs[i]))
1134
            nactive++;
1135 1136 1137
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
1138

1139 1140 1141 1142
    return nactive;
}

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

1146
    networkDriverLock(driver);
1147
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
1148
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1149
        if (virNetworkObjIsActive(driver->networks.objs[i])) {
1150
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
1151
                virNetworkObjUnlock(driver->networks.objs[i]);
1152
                virReportOOMError();
1153 1154 1155 1156
                goto cleanup;
            }
            got++;
        }
1157
        virNetworkObjUnlock(driver->networks.objs[i]);
1158
    }
1159 1160
    networkDriverUnlock(driver);

1161 1162 1163
    return got;

 cleanup:
1164
    networkDriverUnlock(driver);
1165 1166 1167 1168 1169 1170
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

static int networkNumDefinedNetworks(virConnectPtr conn) {
1171
    int ninactive = 0, i;
1172
    struct network_driver *driver = conn->networkPrivateData;
1173

1174 1175 1176
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1177
        if (!virNetworkObjIsActive(driver->networks.objs[i]))
1178
            ninactive++;
1179 1180 1181
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
1182

1183 1184 1185 1186
    return ninactive;
}

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

1190
    networkDriverLock(driver);
1191
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
1192
        virNetworkObjLock(driver->networks.objs[i]);
D
Daniel P. Berrange 已提交
1193
        if (!virNetworkObjIsActive(driver->networks.objs[i])) {
1194
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
1195
                virNetworkObjUnlock(driver->networks.objs[i]);
1196
                virReportOOMError();
1197 1198 1199 1200
                goto cleanup;
            }
            got++;
        }
1201
        virNetworkObjUnlock(driver->networks.objs[i]);
1202
    }
1203
    networkDriverUnlock(driver);
1204 1205 1206
    return got;

 cleanup:
1207
    networkDriverUnlock(driver);
1208 1209 1210 1211 1212
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

1213 1214 1215

static int networkIsActive(virNetworkPtr net)
{
1216
    struct network_driver *driver = net->conn->networkPrivateData;
1217 1218 1219 1220 1221 1222 1223
    virNetworkObjPtr obj;
    int ret = -1;

    networkDriverLock(driver);
    obj = virNetworkFindByUUID(&driver->networks, net->uuid);
    networkDriverUnlock(driver);
    if (!obj) {
1224
        networkReportError(VIR_ERR_NO_NETWORK, NULL);
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
        goto cleanup;
    }
    ret = virNetworkObjIsActive(obj);

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

static int networkIsPersistent(virNetworkPtr net)
{
1237
    struct network_driver *driver = net->conn->networkPrivateData;
1238 1239 1240 1241 1242 1243 1244
    virNetworkObjPtr obj;
    int ret = -1;

    networkDriverLock(driver);
    obj = virNetworkFindByUUID(&driver->networks, net->uuid);
    networkDriverUnlock(driver);
    if (!obj) {
1245
        networkReportError(VIR_ERR_NO_NETWORK, NULL);
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
        goto cleanup;
    }
    ret = obj->persistent;

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


1257
static virNetworkPtr networkCreate(virConnectPtr conn, const char *xml) {
1258
    struct network_driver *driver = conn->networkPrivateData;
1259
    virNetworkDefPtr def;
1260
    virNetworkObjPtr network = NULL;
1261
    virNetworkPtr ret = NULL;
1262

1263 1264
    networkDriverLock(driver);

1265
    if (!(def = virNetworkDefParseString(xml)))
1266
        goto cleanup;
1267

1268
    if (virNetworkSetBridgeName(&driver->networks, def, 1))
1269 1270
        goto cleanup;

1271
    if (!(network = virNetworkAssignDef(&driver->networks,
1272 1273 1274
                                        def)))
        goto cleanup;
    def = NULL;
1275

1276
    if (networkStartNetworkDaemon(driver, network) < 0) {
1277 1278
        virNetworkRemoveInactive(&driver->networks,
                                 network);
1279
        network = NULL;
1280
        goto cleanup;
1281 1282
    }

1283 1284 1285 1286
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
1287 1288 1289
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1290
    return ret;
1291 1292 1293
}

static virNetworkPtr networkDefine(virConnectPtr conn, const char *xml) {
1294
    struct network_driver *driver = conn->networkPrivateData;
1295
    virNetworkDefPtr def;
1296
    virNetworkObjPtr network = NULL;
1297
    virNetworkPtr ret = NULL;
1298

1299 1300
    networkDriverLock(driver);

1301
    if (!(def = virNetworkDefParseString(xml)))
1302
        goto cleanup;
1303

1304
    if (virNetworkSetBridgeName(&driver->networks, def, 1))
1305 1306
        goto cleanup;

1307
    if (!(network = virNetworkAssignDef(&driver->networks,
1308 1309 1310
                                        def)))
        goto cleanup;
    def = NULL;
1311

1312 1313
    network->persistent = 1;

1314
    if (virNetworkSaveConfig(driver->networkConfigDir,
1315
                             network->newDef ? network->newDef : network->def) < 0) {
1316 1317
        virNetworkRemoveInactive(&driver->networks,
                                 network);
1318
        network = NULL;
1319
        goto cleanup;
1320 1321
    }

1322 1323 1324 1325 1326 1327 1328 1329 1330
    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);
    }

1331 1332 1333 1334
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
1335 1336 1337
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1338
    return ret;
1339 1340 1341
}

static int networkUndefine(virNetworkPtr net) {
1342
    struct network_driver *driver = net->conn->networkPrivateData;
1343
    virNetworkObjPtr network = NULL;
1344
    int ret = -1;
1345

1346 1347
    networkDriverLock(driver);

1348
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1349
    if (!network) {
1350
        networkReportError(VIR_ERR_INVALID_NETWORK,
1351 1352
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1353 1354
    }

D
Daniel P. Berrange 已提交
1355
    if (virNetworkObjIsActive(network)) {
1356
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1357 1358
                           "%s", _("network is still active"));
        goto cleanup;
1359 1360
    }

1361
    if (virNetworkDeleteConfig(driver->networkConfigDir,
1362 1363
                               driver->networkAutostartDir,
                               network) < 0)
1364
        goto cleanup;
1365

1366 1367 1368 1369 1370 1371 1372 1373 1374
    if (network->def->nhosts > 0) {
        dnsmasqContext *dctx = dnsmasqContextNew(network->def->name, DNSMASQ_STATE_DIR);
        if (dctx == NULL)
            goto cleanup;

        dnsmasqDelete(dctx);
        dnsmasqContextFree(dctx);
    }

1375 1376
    virNetworkRemoveInactive(&driver->networks,
                             network);
1377
    network = NULL;
1378
    ret = 0;
1379

1380
cleanup:
1381 1382 1383
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1384
    return ret;
1385 1386 1387
}

static int networkStart(virNetworkPtr net) {
1388 1389 1390
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1391

1392
    networkDriverLock(driver);
1393
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1394

1395
    if (!network) {
1396
        networkReportError(VIR_ERR_INVALID_NETWORK,
1397 1398
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1399 1400
    }

1401
    ret = networkStartNetworkDaemon(driver, network);
1402 1403

cleanup:
1404 1405
    if (network)
        virNetworkObjUnlock(network);
1406
    networkDriverUnlock(driver);
1407
    return ret;
1408 1409 1410
}

static int networkDestroy(virNetworkPtr net) {
1411 1412 1413
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1414

1415
    networkDriverLock(driver);
1416
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1417

1418
    if (!network) {
1419
        networkReportError(VIR_ERR_INVALID_NETWORK,
1420 1421
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1422 1423
    }

D
Daniel P. Berrange 已提交
1424
    if (!virNetworkObjIsActive(network)) {
1425
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1426 1427 1428 1429
                           "%s", _("network is not active"));
        goto cleanup;
    }

1430
    ret = networkShutdownNetworkDaemon(driver, network);
1431
    if (!network->persistent) {
1432 1433 1434 1435
        virNetworkRemoveInactive(&driver->networks,
                                 network);
        network = NULL;
    }
1436

1437
cleanup:
1438 1439
    if (network)
        virNetworkObjUnlock(network);
1440
    networkDriverUnlock(driver);
1441 1442 1443 1444
    return ret;
}

static char *networkDumpXML(virNetworkPtr net, int flags ATTRIBUTE_UNUSED) {
1445 1446 1447
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *ret = NULL;
1448

1449
    networkDriverLock(driver);
1450
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1451 1452
    networkDriverUnlock(driver);

1453
    if (!network) {
1454
        networkReportError(VIR_ERR_INVALID_NETWORK,
1455 1456
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1457 1458
    }

1459
    ret = virNetworkDefFormat(network->def);
1460 1461

cleanup:
1462 1463
    if (network)
        virNetworkObjUnlock(network);
1464
    return ret;
1465 1466 1467
}

static char *networkGetBridgeName(virNetworkPtr net) {
1468 1469 1470 1471
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *bridge = NULL;

1472
    networkDriverLock(driver);
1473
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1474 1475
    networkDriverUnlock(driver);

1476
    if (!network) {
1477
        networkReportError(VIR_ERR_INVALID_NETWORK,
1478 1479
                           "%s", _("no network with matching id"));
        goto cleanup;
1480 1481
    }

1482
    if (!(network->def->bridge)) {
1483
        networkReportError(VIR_ERR_INTERNAL_ERROR,
1484 1485 1486 1487 1488
                           _("network '%s' does not have a bridge name."),
                           network->def->name);
        goto cleanup;
    }

1489
    bridge = strdup(network->def->bridge);
1490
    if (!bridge)
1491
        virReportOOMError();
1492 1493

cleanup:
1494 1495
    if (network)
        virNetworkObjUnlock(network);
1496 1497 1498 1499 1500
    return bridge;
}

static int networkGetAutostart(virNetworkPtr net,
                             int *autostart) {
1501 1502 1503
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1504

1505
    networkDriverLock(driver);
1506
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1507
    networkDriverUnlock(driver);
1508
    if (!network) {
1509 1510
        networkReportError(VIR_ERR_INVALID_NETWORK,
                           "%s", _("no network with matching uuid"));
1511
        goto cleanup;
1512 1513 1514
    }

    *autostart = network->autostart;
1515
    ret = 0;
1516

1517
cleanup:
1518 1519
    if (network)
        virNetworkObjUnlock(network);
1520
    return ret;
1521 1522 1523
}

static int networkSetAutostart(virNetworkPtr net,
1524
                               int autostart) {
1525 1526
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
1527
    char *configFile = NULL, *autostartLink = NULL;
1528
    int ret = -1;
1529

1530
    networkDriverLock(driver);
1531
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1532

1533
    if (!network) {
1534 1535
        networkReportError(VIR_ERR_INVALID_NETWORK,
                           "%s", _("no network with matching uuid"));
1536
        goto cleanup;
1537 1538
    }

1539
    if (!network->persistent) {
1540 1541
        networkReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("cannot set autostart for transient network"));
1542 1543 1544
        goto cleanup;
    }

1545 1546
    autostart = (autostart != 0);

1547
    if (network->autostart != autostart) {
1548
        if ((configFile = virNetworkConfigFile(driver->networkConfigDir, network->def->name)) == NULL)
1549
            goto cleanup;
1550
        if ((autostartLink = virNetworkConfigFile(driver->networkAutostartDir, network->def->name)) == NULL)
1551 1552
            goto cleanup;

1553
        if (autostart) {
1554
            if (virFileMakePath(driver->networkAutostartDir)) {
1555
                virReportSystemError(errno,
1556 1557
                                     _("cannot create autostart directory '%s'"),
                                     driver->networkAutostartDir);
1558 1559
                goto cleanup;
            }
1560

1561
            if (symlink(configFile, autostartLink) < 0) {
1562
                virReportSystemError(errno,
1563
                                     _("Failed to create symlink '%s' to '%s'"),
1564
                                     autostartLink, configFile);
1565 1566 1567
                goto cleanup;
            }
        } else {
1568
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1569
                virReportSystemError(errno,
1570
                                     _("Failed to delete symlink '%s'"),
1571
                                     autostartLink);
1572 1573
                goto cleanup;
            }
1574 1575
        }

1576
        network->autostart = autostart;
1577
    }
1578
    ret = 0;
1579

1580
cleanup:
1581 1582
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
1583 1584
    if (network)
        virNetworkObjUnlock(network);
1585
    networkDriverUnlock(driver);
1586
    return ret;
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
}


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 */
1609 1610
    networkIsActive,
    networkIsPersistent,
1611 1612 1613
};

static virStateDriver networkStateDriver = {
1614
    "Network",
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
    networkStartup,
    networkShutdown,
    networkReload,
    networkActive,
};

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