bridge_driver.c 45.8 KB
Newer Older
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
J
Jim Meyering 已提交
4
 * Copyright (C) 2006-2009 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 46
 * 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 <strings.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>

47
#include "virterror_internal.h"
48
#include "datatypes.h"
49
#include "bridge_driver.h"
50 51 52 53 54 55 56 57 58
#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"
59
#include "logging.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 65

#define VIR_FROM_THIS VIR_FROM_NETWORK

66 67
/* Main driver state */
struct network_driver {
68
    virMutex lock;
69

70
    virNetworkObjList networks;
71 72 73 74 75 76 77 78

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

79 80 81

static void networkDriverLock(struct network_driver *driver)
{
82
    virMutexLock(&driver->lock);
83 84 85
}
static void networkDriverUnlock(struct network_driver *driver)
{
86
    virMutexUnlock(&driver->lock);
87 88
}

89 90 91 92 93 94 95 96 97 98 99 100 101
static int networkShutdown(void);

static int networkStartNetworkDaemon(virConnectPtr conn,
                                   struct network_driver *driver,
                                   virNetworkObjPtr network);

static int networkShutdownNetworkDaemon(virConnectPtr conn,
                                      struct network_driver *driver,
                                      virNetworkObjPtr network);

static struct network_driver *driverState = NULL;


102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
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);

        if ((config = virNetworkConfigFile(NULL,
                                           NETWORK_STATE_DIR,
                                           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 */
        tmp = virNetworkDefParseFile(NULL, config);
        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;

139 140 141
            /* Finally try and read dnsmasq pid if any */
            if ((obj->def->ipAddress ||
                 obj->def->nranges) &&
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
                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;

                virAsprintf(&pidpath, "/proc/%d/exe", obj->dnsmasqPid);
                if (virFileLinkPointsTo(pidpath, DNSMASQ) == 0)
                    obj->dnsmasqPid = -1;
                VIR_FREE(pidpath);
#endif
            }
        }

        virNetworkObjUnlock(obj);
    }
}


165 166 167
static void
networkAutostartConfigs(struct network_driver *driver) {
    unsigned int i;
168

169
    for (i = 0 ; i < driver->networks.count ; i++) {
170
        virNetworkObjLock(driver->networks.objs[i]);
171 172 173
        if (driver->networks.objs[i]->autostart &&
            !virNetworkIsActive(driver->networks.objs[i]) &&
            networkStartNetworkDaemon(NULL, driver, driver->networks.objs[i]) < 0) {
174
            /* failed to start but already logged */
175
        }
176
        virNetworkObjUnlock(driver->networks.objs[i]);
177 178 179 180 181 182 183 184 185
    }
}

/**
 * networkStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
186
networkStartup(int privileged) {
187 188
    uid_t uid = geteuid();
    char *base = NULL;
189
    int err;
190 191

    if (VIR_ALLOC(driverState) < 0)
192
        goto error;
193

194 195 196 197
    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        goto error;
    }
198 199
    networkDriverLock(driverState);

200
    if (privileged) {
201 202
        if (virAsprintf(&driverState->logDir,
                        "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
203 204 205 206 207
            goto out_of_memory;

        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
            goto out_of_memory;
    } else {
208 209 210 211
        char *userdir = virGetUserDirectory(NULL, uid);

        if (!userdir)
            goto error;
212

213
        if (virAsprintf(&driverState->logDir,
214 215
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
216
            goto out_of_memory;
217
        }
218

219 220
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
221 222
            goto out_of_memory;
        }
223
        VIR_FREE(userdir);
224 225 226 227 228
    }

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

232 233
    if (virAsprintf(&driverState->networkAutostartDir, "%s/qemu/networks/autostart",
                    base) == -1)
234 235 236 237
        goto out_of_memory;

    VIR_FREE(base);

238 239 240 241 242 243 244
    if ((err = brInit(&driverState->brctl))) {
        virReportSystemError(NULL, err, "%s",
                             _("cannot initialize bridge support"));
        goto error;
    }

    if (!(driverState->iptables = iptablesContextNew())) {
245
        goto out_of_memory;
246 247 248
    }


249 250 251
    if (virNetworkLoadAllConfigs(NULL,
                                 &driverState->networks,
                                 driverState->networkConfigDir,
252 253 254
                                 driverState->networkAutostartDir) < 0)
        goto error;

255
    networkFindActiveConfigs(driverState);
256 257
    networkAutostartConfigs(driverState);

258 259
    networkDriverUnlock(driverState);

260 261
    return 0;

262
out_of_memory:
263
    virReportOOMError(NULL);
264 265

error:
266 267 268
    if (driverState)
        networkDriverUnlock(driverState);

269
    VIR_FREE(base);
270
    networkShutdown();
271 272 273 274 275 276 277 278 279 280 281
    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) {
282 283 284
    if (!driverState)
        return 0;

285
    networkDriverLock(driverState);
286 287 288 289 290 291
    virNetworkLoadAllConfigs(NULL,
                             &driverState->networks,
                             driverState->networkConfigDir,
                             driverState->networkAutostartDir);

     if (driverState->iptables) {
292
        VIR_INFO0(_("Reloading iptables rules\n"));
293 294 295 296
        iptablesReloadRules(driverState->iptables);
    }

    networkAutostartConfigs(driverState);
297
    networkDriverUnlock(driverState);
298 299 300 301 302 303 304 305 306 307 308 309 310
    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) {
311
    unsigned int i;
312
    int active = 0;
313

314 315 316
    if (!driverState)
        return 0;

317
    networkDriverLock(driverState);
318 319
    for (i = 0 ; i < driverState->networks.count ; i++) {
        virNetworkObjPtr net = driverState->networks.objs[i];
320
        virNetworkObjLock(net);
321 322
        if (virNetworkIsActive(net))
            active = 1;
323
        virNetworkObjUnlock(net);
324
    }
325
    networkDriverUnlock(driverState);
326
    return active;
327 328 329 330 331 332 333 334 335 336 337 338
}

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

339 340
    networkDriverLock(driverState);

341
    /* free inactive networks */
342
    virNetworkObjListFree(&driverState->networks);
343 344 345 346 347 348 349 350 351 352

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

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

353
    networkDriverUnlock(driverState);
354
    virMutexDestroy(&driverState->lock);
355

356 357 358 359 360 361 362 363
    VIR_FREE(driverState);

    return 0;
}


static int
networkBuildDnsmasqArgv(virConnectPtr conn,
364 365 366
                        virNetworkObjPtr network,
                        const char *pidfile,
                        const char ***argv) {
367
    int i, len, r;
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
    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
     */
389 390 391 392 393 394

    len =
        1 + /* dnsmasq */
        1 + /* --strict-order */
        1 + /* --bind-interfaces */
        (network->def->domain?2:0) + /* --domain name */
395
        2 + /* --pid-file /var/run/libvirt/network/$NAME.pid */
396 397 398 399 400 401 402
        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 */
        /*  --dhcp-host 01:23:45:67:89:0a,hostname,10.0.0.3 */
        (2 * network->def->nhosts) +
403 404 405 406
        /* --enable-tftp --tftp-root /srv/tftp */
        (network->def->tftproot ? 3 : 0) +
        /* --dhcp-boot pxeboot.img */
        (network->def->bootfile ? 2 : 0) +
407 408 409 410 411 412 413 414 415 416
        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)

417 418 419
#define APPEND_ARG_LIT(v, n, s) \
        (v)[(n)] = s

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
    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);
    }

436 437 438
    if (virAsprintf(&pidfileArg, "--pid-file=%s", pidfile) < 0)
        goto no_memory;
    APPEND_ARG_LIT(*argv, i++, pidfileArg);
439

440
    APPEND_ARG(*argv, i++, "--conf-file=");
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    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);
    }

    for (r = 0 ; r < network->def->nhosts ; r++) {
        virNetworkDHCPHostDefPtr host = &(network->def->hosts[r]);
        if ((host->mac) && (host->name)) {
            snprintf(buf, sizeof(buf), "%s,%s,%s",
                     host->mac, host->name, host->ip);
        } else if (host->mac) {
            snprintf(buf, sizeof(buf), "%s,%s",
                     host->mac, host->ip);
        } else if (host->name) {
            snprintf(buf, sizeof(buf), "%s,%s",
                     host->name, host->ip);
        } else
            continue;

        APPEND_ARG(*argv, i++, "--dhcp-host");
        APPEND_ARG(*argv, i++, buf);
    }

485 486 487 488 489 490 491 492 493 494
    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) {
        APPEND_ARG(*argv, i++, "--dhcp-boot");
        APPEND_ARG(*argv, i++, network->def->bootfile);
    }

495 496 497 498 499 500 501 502 503 504
#undef APPEND_ARG

    return 0;

 no_memory:
    if (argv) {
        for (i = 0; (*argv)[i]; i++)
            VIR_FREE((*argv)[i]);
        VIR_FREE(*argv);
    }
505
    virReportOOMError(conn);
506 507 508 509 510 511 512 513 514
    return -1;
}


static int
dhcpStartDhcpDaemon(virConnectPtr conn,
                    virNetworkObjPtr network)
{
    const char **argv;
515 516 517 518
    char *pidfile;
    int ret = -1, i, err;

    network->dnsmasqPid = -1;
519 520 521 522 523 524 525

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

526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
    if ((err = virFileMakePath(NETWORK_PID_DIR)) < 0) {
        virReportSystemError(conn, err,
                             _("cannot create directory %s"),
                             NETWORK_PID_DIR);
        return -1;
    }
    if ((err = virFileMakePath(NETWORK_STATE_DIR)) < 0) {
        virReportSystemError(conn, err,
                             _("cannot create directory %s"),
                             NETWORK_STATE_DIR);
        return -1;
    }

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

544
    argv = NULL;
545 546
    if (networkBuildDnsmasqArgv(conn, network, pidfile, &argv) < 0) {
        VIR_FREE(pidfile);
547
        return -1;
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
    }

    if (virRun(conn, argv, NULL) < 0)
        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;
564

565
    ret = 0;
566

567 568
cleanup:
    VIR_FREE(pidfile);
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
    for (i = 0; argv[i]; i++)
        VIR_FREE(argv[i]);
    VIR_FREE(argv);

    return ret;
}

static int
networkAddMasqueradingIptablesRules(virConnectPtr conn,
                      struct network_driver *driver,
                      virNetworkObjPtr network) {
    int err;
    /* allow forwarding packets from the bridge interface */
    if ((err = iptablesAddForwardAllowOut(driver->iptables,
                                          network->def->network,
                                          network->def->bridge,
                                          network->def->forwardDev))) {
586 587 588
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow forwarding from '%s'"),
                             network->def->bridge);
589 590 591 592 593 594 595 596
        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))) {
597 598 599
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow forwarding to '%s'"),
                             network->def->bridge);
600 601 602 603 604 605 606
        goto masqerr2;
    }

    /* enable masquerading */
    if ((err = iptablesAddForwardMasquerade(driver->iptables,
                                            network->def->network,
                                            network->def->forwardDev))) {
607 608 609
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to enable masquerading to '%s'\n"),
                             network->def->forwardDev ? network->def->forwardDev : NULL);
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
        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
networkAddRoutingIptablesRules(virConnectPtr conn,
                      struct network_driver *driver,
                      virNetworkObjPtr network) {
    int err;
    /* allow routing packets from the bridge interface */
    if ((err = iptablesAddForwardAllowOut(driver->iptables,
                                          network->def->network,
                                          network->def->bridge,
                                          network->def->forwardDev))) {
639 640 641
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow routing from '%s'"),
                             network->def->bridge);
642 643 644 645 646 647 648 649
        goto routeerr1;
    }

    /* allow routing packets to the bridge interface */
    if ((err = iptablesAddForwardAllowIn(driver->iptables,
                                         network->def->network,
                                         network->def->bridge,
                                         network->def->forwardDev))) {
650 651 652
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow routing to '%s'"),
                             network->def->bridge);
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
        goto routeerr2;
    }

    return 1;


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

static int
networkAddIptablesRules(virConnectPtr conn,
                      struct network_driver *driver,
                      virNetworkObjPtr network) {
    int err;

    /* allow DHCP requests through to dnsmasq */
    if ((err = iptablesAddTcpInput(driver->iptables, network->def->bridge, 67))) {
676 677 678
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow DHCP requests from '%s'"),
                             network->def->bridge);
679 680 681 682
        goto err1;
    }

    if ((err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 67))) {
683 684 685
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow DHCP requests from '%s'"),
                             network->def->bridge);
686 687 688 689 690
        goto err2;
    }

    /* allow DNS requests through to dnsmasq */
    if ((err = iptablesAddTcpInput(driver->iptables, network->def->bridge, 53))) {
691 692 693
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow DNS requests from '%s'"),
                             network->def->bridge);
694 695 696 697
        goto err3;
    }

    if ((err = iptablesAddUdpInput(driver->iptables, network->def->bridge, 53))) {
698 699 700
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow DNS requests from '%s'"),
                             network->def->bridge);
701 702 703 704 705 706 707
        goto err4;
    }


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

    if ((err = iptablesAddForwardRejectOut(driver->iptables, network->def->bridge))) {
708 709 710
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to block outbound traffic from '%s'"),
                             network->def->bridge);
711 712 713 714
        goto err5;
    }

    if ((err = iptablesAddForwardRejectIn(driver->iptables, network->def->bridge))) {
715 716 717
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to block inbound traffic to '%s'"),
                             network->def->bridge);
718 719 720 721 722
        goto err6;
    }

    /* Allow traffic between guests on the same bridge */
    if ((err = iptablesAddForwardAllowCross(driver->iptables, network->def->bridge))) {
723 724 725
        virReportSystemError(conn, err,
                             _("failed to add iptables rule to allow cross bridge traffic on '%s'"),
                             network->def->bridge);
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
        goto err7;
    }


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

    iptablesSaveRules(driver->iptables);

    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) {
        iptablesRemoveForwardMasquerade(driver->iptables,
                                        network->def->network,
                                        network->def->forwardDev);

        if (network->def->forwardType == VIR_NETWORK_FORWARD_NAT)
            iptablesRemoveForwardAllowRelatedIn(driver->iptables,
                                                network->def->network,
                                                network->def->bridge,
                                                network->def->forwardDev);
        else if (network->def->forwardType == VIR_NETWORK_FORWARD_ROUTE)
            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);
    iptablesSaveRules(driver->iptables);
}

798
/* Enable IP Forwarding. Return 0 for success, -1 for failure. */
799 800 801
static int
networkEnableIpForwarding(void)
{
M
Mark McLoughlin 已提交
802
    return virFileWriteStr("/proc/sys/net/ipv4/ip_forward", "1\n");
803 804
}

805 806 807 808 809 810 811 812 813 814 815 816 817
#define SYSCTL_PATH "/proc/sys"

static int networkDisableIPV6(virConnectPtr conn,
                              virNetworkObjPtr network)
{
    char *field = NULL;
    int ret = -1;

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

818 819 820 821 822 823
    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;
    }

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    if (virFileWriteStr(field, "1") < 0) {
        virReportSystemError(conn, errno,
                             _("cannot enable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

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

    if (virFileWriteStr(field, "0") < 0) {
        virReportSystemError(conn, errno,
                             _("cannot disable %s"), field);
        goto cleanup;
    }
    VIR_FREE(field);

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

    if (virFileWriteStr(field, "1") < 0) {
        virReportSystemError(conn, errno,
                             _("cannot enable %s"), field);
        goto cleanup;
    }

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

860 861 862 863 864 865 866 867 868 869 870
static int networkStartNetworkDaemon(virConnectPtr conn,
                                   struct network_driver *driver,
                                   virNetworkObjPtr network) {
    int err;

    if (virNetworkIsActive(network)) {
        networkReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("network is already active"));
        return -1;
    }

871
    if ((err = brAddBridge(driver->brctl, network->def->bridge))) {
872 873 874
        virReportSystemError(conn, err,
                             _("cannot create bridge '%s'"),
                             network->def->bridge);
875 876 877
        return -1;
    }

878 879 880
    if (networkDisableIPV6(conn, network) < 0)
        goto err_delbr;

881 882 883 884 885 886 887 888
    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))) {
889 890 891
        virReportSystemError(conn, err,
                             _("cannot set IP address on bridge '%s' to '%s'"),
                             network->def->bridge, network->def->ipAddress);
892 893 894 895 896
        goto err_delbr;
    }

    if (network->def->netmask &&
        (err = brSetInetNetmask(driver->brctl, network->def->bridge, network->def->netmask))) {
897 898 899
        virReportSystemError(conn, err,
                             _("cannot set netmask on bridge '%s' to '%s'"),
                             network->def->bridge, network->def->netmask);
900 901 902
        goto err_delbr;
    }

903
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 1))) {
904 905 906
        virReportSystemError(conn, err,
                             _("failed to bring the bridge '%s' up"),
                             network->def->bridge);
907 908 909 910 911 912 913
        goto err_delbr;
    }

    if (!networkAddIptablesRules(conn, driver, network))
        goto err_delbr1;

    if (network->def->forwardType != VIR_NETWORK_FORWARD_NONE &&
914
        networkEnableIpForwarding() < 0) {
915 916
        virReportSystemError(conn, errno, "%s",
                             _("failed to enable IP forwarding"));
917 918 919
        goto err_delbr2;
    }

920 921
    if ((network->def->ipAddress ||
         network->def->nranges) &&
922 923 924
        dhcpStartDhcpDaemon(conn, network) < 0)
        goto err_delbr2;

925 926 927 928 929 930

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

931 932 933 934
    network->active = 1;

    return 0;

935 936 937 938 939 940
 err_kill:
    if (network->dnsmasqPid > 0) {
        kill(network->dnsmasqPid, SIGTERM);
        network->dnsmasqPid = -1;
    }

941 942 943 944
 err_delbr2:
    networkRemoveIptablesRules(driver, network);

 err_delbr1:
945
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
946
        char ebuf[1024];
947
        VIR_WARN(_("Failed to bring down bridge '%s' : %s\n"),
948
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
949 950 951 952
    }

 err_delbr:
    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
953
        char ebuf[1024];
954
        VIR_WARN(_("Failed to delete bridge '%s' : %s\n"),
955
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
956 957 958 959 960 961
    }

    return -1;
}


962 963 964
static int networkShutdownNetworkDaemon(virConnectPtr conn,
                                        struct network_driver *driver,
                                        virNetworkObjPtr network) {
965
    int err;
966
    char *stateFile;
967

968
    VIR_INFO(_("Shutting down network '%s'\n"), network->def->name);
969 970 971 972

    if (!virNetworkIsActive(network))
        return 0;

973 974 975 976 977 978 979
    stateFile = virNetworkConfigFile(conn, NETWORK_STATE_DIR, network->def->name);
    if (!stateFile)
        return -1;

    unlink(stateFile);
    VIR_FREE(stateFile);

980 981 982 983 984
    if (network->dnsmasqPid > 0)
        kill(network->dnsmasqPid, SIGTERM);

    networkRemoveIptablesRules(driver, network);

985
    char ebuf[1024];
986
    if ((err = brSetInterfaceUp(driver->brctl, network->def->bridge, 0))) {
987
        VIR_WARN(_("Failed to bring down bridge '%s' : %s\n"),
988
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
989 990 991
    }

    if ((err = brDeleteBridge(driver->brctl, network->def->bridge))) {
992
        VIR_WARN(_("Failed to delete bridge '%s' : %s\n"),
993
                 network->def->bridge, virStrerror(err, ebuf, sizeof ebuf));
994 995
    }

996
    /* See if its still alive and really really kill it */
997
    if (network->dnsmasqPid > 0 &&
998
        (kill(network->dnsmasqPid, 0) == 0))
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
        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;
}


1014 1015 1016 1017 1018
static virNetworkPtr networkLookupByUUID(virConnectPtr conn,
                                         const unsigned char *uuid) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;
1019

1020
    networkDriverLock(driver);
1021
    network = virNetworkFindByUUID(&driver->networks, uuid);
1022
    networkDriverUnlock(driver);
1023 1024 1025
    if (!network) {
        networkReportError(conn, NULL, NULL, VIR_ERR_NO_NETWORK,
                         "%s", _("no network with matching uuid"));
1026
        goto cleanup;
1027 1028
    }

1029 1030 1031
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
1032 1033
    if (network)
        virNetworkObjUnlock(network);
1034
    return ret;
1035 1036
}

1037 1038 1039 1040 1041 1042
static virNetworkPtr networkLookupByName(virConnectPtr conn,
                                         const char *name) {
    struct network_driver *driver = conn->networkPrivateData;
    virNetworkObjPtr network;
    virNetworkPtr ret = NULL;

1043
    networkDriverLock(driver);
1044
    network = virNetworkFindByName(&driver->networks, name);
1045
    networkDriverUnlock(driver);
1046 1047
    if (!network) {
        networkReportError(conn, NULL, NULL, VIR_ERR_NO_NETWORK,
1048
                         _("no network with matching name '%s'"), name);
1049
        goto cleanup;
1050 1051
    }

1052 1053 1054
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
1055 1056
    if (network)
        virNetworkObjUnlock(network);
1057
    return ret;
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
}

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) {
1076
    int nactive = 0, i;
1077
    struct network_driver *driver = conn->networkPrivateData;
1078

1079 1080 1081
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
1082
        if (virNetworkIsActive(driver->networks.objs[i]))
1083
            nactive++;
1084 1085 1086
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
1087

1088 1089 1090 1091
    return nactive;
}

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

1095
    networkDriverLock(driver);
1096
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
1097
        virNetworkObjLock(driver->networks.objs[i]);
1098 1099
        if (virNetworkIsActive(driver->networks.objs[i])) {
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
1100
                virNetworkObjUnlock(driver->networks.objs[i]);
1101
                virReportOOMError(conn);
1102 1103 1104 1105
                goto cleanup;
            }
            got++;
        }
1106
        virNetworkObjUnlock(driver->networks.objs[i]);
1107
    }
1108 1109
    networkDriverUnlock(driver);

1110 1111 1112
    return got;

 cleanup:
1113
    networkDriverUnlock(driver);
1114 1115 1116 1117 1118 1119
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

static int networkNumDefinedNetworks(virConnectPtr conn) {
1120
    int ninactive = 0, i;
1121
    struct network_driver *driver = conn->networkPrivateData;
1122

1123 1124 1125
    networkDriverLock(driver);
    for (i = 0 ; i < driver->networks.count ; i++) {
        virNetworkObjLock(driver->networks.objs[i]);
1126
        if (!virNetworkIsActive(driver->networks.objs[i]))
1127
            ninactive++;
1128 1129 1130
        virNetworkObjUnlock(driver->networks.objs[i]);
    }
    networkDriverUnlock(driver);
1131

1132 1133 1134 1135
    return ninactive;
}

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

1139
    networkDriverLock(driver);
1140
    for (i = 0 ; i < driver->networks.count && got < nnames ; i++) {
1141
        virNetworkObjLock(driver->networks.objs[i]);
1142 1143
        if (!virNetworkIsActive(driver->networks.objs[i])) {
            if (!(names[got] = strdup(driver->networks.objs[i]->def->name))) {
1144
                virNetworkObjUnlock(driver->networks.objs[i]);
1145
                virReportOOMError(conn);
1146 1147 1148 1149
                goto cleanup;
            }
            got++;
        }
1150
        virNetworkObjUnlock(driver->networks.objs[i]);
1151
    }
1152
    networkDriverUnlock(driver);
1153 1154 1155
    return got;

 cleanup:
1156
    networkDriverUnlock(driver);
1157 1158 1159 1160 1161 1162
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
    return -1;
}

static virNetworkPtr networkCreate(virConnectPtr conn, const char *xml) {
1163
    struct network_driver *driver = conn->networkPrivateData;
1164
    virNetworkDefPtr def;
1165
    virNetworkObjPtr network = NULL;
1166
    virNetworkPtr ret = NULL;
1167

1168 1169
    networkDriverLock(driver);

1170
    if (!(def = virNetworkDefParseString(conn, xml)))
1171
        goto cleanup;
1172

1173
    if (virNetworkSetBridgeName(conn, &driver->networks, def, 1))
1174 1175
        goto cleanup;

1176 1177
    if (!(network = virNetworkAssignDef(conn,
                                        &driver->networks,
1178 1179 1180
                                        def)))
        goto cleanup;
    def = NULL;
1181 1182 1183 1184

    if (networkStartNetworkDaemon(conn, driver, network) < 0) {
        virNetworkRemoveInactive(&driver->networks,
                                 network);
1185
        network = NULL;
1186
        goto cleanup;
1187 1188
    }

1189 1190 1191 1192
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
1193 1194 1195
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1196
    return ret;
1197 1198 1199
}

static virNetworkPtr networkDefine(virConnectPtr conn, const char *xml) {
1200
    struct network_driver *driver = conn->networkPrivateData;
1201
    virNetworkDefPtr def;
1202
    virNetworkObjPtr network = NULL;
1203
    virNetworkPtr ret = NULL;
1204

1205 1206
    networkDriverLock(driver);

1207
    if (!(def = virNetworkDefParseString(conn, xml)))
1208
        goto cleanup;
1209

1210
    if (virNetworkSetBridgeName(conn, &driver->networks, def, 1))
1211 1212
        goto cleanup;

1213 1214
    if (!(network = virNetworkAssignDef(conn,
                                        &driver->networks,
1215 1216 1217
                                        def)))
        goto cleanup;
    def = NULL;
1218

1219 1220
    network->persistent = 1;

1221 1222
    if (virNetworkSaveConfig(conn,
                             driver->networkConfigDir,
1223
                             network->newDef ? network->newDef : network->def) < 0) {
1224 1225
        virNetworkRemoveInactive(&driver->networks,
                                 network);
1226
        network = NULL;
1227
        goto cleanup;
1228 1229
    }

1230 1231 1232 1233
    ret = virGetNetwork(conn, network->def->name, network->def->uuid);

cleanup:
    virNetworkDefFree(def);
1234 1235 1236
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1237
    return ret;
1238 1239 1240
}

static int networkUndefine(virNetworkPtr net) {
1241
    struct network_driver *driver = net->conn->networkPrivateData;
1242
    virNetworkObjPtr network = NULL;
1243
    int ret = -1;
1244

1245 1246
    networkDriverLock(driver);

1247
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1248 1249
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_DOMAIN,
1250 1251
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1252 1253 1254 1255
    }

    if (virNetworkIsActive(network)) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INTERNAL_ERROR,
1256 1257
                           "%s", _("network is still active"));
        goto cleanup;
1258 1259
    }

1260 1261 1262 1263
    if (virNetworkDeleteConfig(net->conn,
                               driver->networkConfigDir,
                               driver->networkAutostartDir,
                               network) < 0)
1264
        goto cleanup;
1265 1266 1267

    virNetworkRemoveInactive(&driver->networks,
                             network);
1268
    network = NULL;
1269
    ret = 0;
1270

1271
cleanup:
1272 1273 1274
    if (network)
        virNetworkObjUnlock(network);
    networkDriverUnlock(driver);
1275
    return ret;
1276 1277 1278
}

static int networkStart(virNetworkPtr net) {
1279 1280 1281
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1282

1283
    networkDriverLock(driver);
1284
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1285

1286 1287
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_NETWORK,
1288 1289
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1290 1291
    }

1292 1293 1294
    ret = networkStartNetworkDaemon(net->conn, driver, network);

cleanup:
1295 1296
    if (network)
        virNetworkObjUnlock(network);
1297
    networkDriverUnlock(driver);
1298
    return ret;
1299 1300 1301
}

static int networkDestroy(virNetworkPtr net) {
1302 1303 1304
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1305

1306
    networkDriverLock(driver);
1307
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1308

1309 1310
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_NETWORK,
1311 1312
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1313 1314
    }

1315 1316 1317 1318 1319 1320
    if (!virNetworkIsActive(network)) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INTERNAL_ERROR,
                           "%s", _("network is not active"));
        goto cleanup;
    }

1321
    ret = networkShutdownNetworkDaemon(net->conn, driver, network);
1322
    if (!network->persistent) {
1323 1324 1325 1326
        virNetworkRemoveInactive(&driver->networks,
                                 network);
        network = NULL;
    }
1327

1328
cleanup:
1329 1330
    if (network)
        virNetworkObjUnlock(network);
1331
    networkDriverUnlock(driver);
1332 1333 1334 1335
    return ret;
}

static char *networkDumpXML(virNetworkPtr net, int flags ATTRIBUTE_UNUSED) {
1336 1337 1338
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *ret = NULL;
1339

1340
    networkDriverLock(driver);
1341
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1342 1343
    networkDriverUnlock(driver);

1344 1345
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_NETWORK,
1346 1347
                           "%s", _("no network with matching uuid"));
        goto cleanup;
1348 1349
    }

1350 1351 1352
    ret = virNetworkDefFormat(net->conn, network->def);

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

static char *networkGetBridgeName(virNetworkPtr net) {
1359 1360 1361 1362
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    char *bridge = NULL;

1363
    networkDriverLock(driver);
1364
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1365 1366
    networkDriverUnlock(driver);

1367 1368
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_NETWORK,
1369 1370
                           "%s", _("no network with matching id"));
        goto cleanup;
1371 1372
    }

1373 1374 1375 1376 1377 1378 1379
    if (!(network->def->bridge)) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INTERNAL_ERROR,
                           _("network '%s' does not have a bridge name."),
                           network->def->name);
        goto cleanup;
    }

1380
    bridge = strdup(network->def->bridge);
1381
    if (!bridge)
1382
        virReportOOMError(net->conn);
1383 1384

cleanup:
1385 1386
    if (network)
        virNetworkObjUnlock(network);
1387 1388 1389 1390 1391
    return bridge;
}

static int networkGetAutostart(virNetworkPtr net,
                             int *autostart) {
1392 1393 1394
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
    int ret = -1;
1395

1396
    networkDriverLock(driver);
1397
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1398
    networkDriverUnlock(driver);
1399 1400 1401
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_NETWORK,
                         "%s", _("no network with matching uuid"));
1402
        goto cleanup;
1403 1404 1405
    }

    *autostart = network->autostart;
1406
    ret = 0;
1407

1408
cleanup:
1409 1410
    if (network)
        virNetworkObjUnlock(network);
1411
    return ret;
1412 1413 1414
}

static int networkSetAutostart(virNetworkPtr net,
1415
                               int autostart) {
1416 1417
    struct network_driver *driver = net->conn->networkPrivateData;
    virNetworkObjPtr network;
1418
    char *configFile = NULL, *autostartLink = NULL;
1419
    int ret = -1;
1420

1421
    networkDriverLock(driver);
1422
    network = virNetworkFindByUUID(&driver->networks, net->uuid);
1423

1424 1425 1426
    if (!network) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INVALID_NETWORK,
                         "%s", _("no network with matching uuid"));
1427
        goto cleanup;
1428 1429
    }

1430 1431 1432 1433 1434 1435
    if (!network->persistent) {
        networkReportError(net->conn, NULL, net, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient network"));
        goto cleanup;
    }

1436 1437
    autostart = (autostart != 0);

1438
    if (network->autostart != autostart) {
1439 1440 1441 1442 1443
        if ((configFile = virNetworkConfigFile(net->conn, driver->networkConfigDir, network->def->name)) == NULL)
            goto cleanup;
        if ((autostartLink = virNetworkConfigFile(net->conn, driver->networkAutostartDir, network->def->name)) == NULL)
            goto cleanup;

1444
        if (autostart) {
1445
            if (virFileMakePath(driver->networkAutostartDir)) {
1446 1447 1448
                virReportSystemError(net->conn, errno,
                                     _("cannot create autostart directory '%s'"),
                                     driver->networkAutostartDir);
1449 1450
                goto cleanup;
            }
1451

1452
            if (symlink(configFile, autostartLink) < 0) {
1453 1454
                virReportSystemError(net->conn, errno,
                                     _("Failed to create symlink '%s' to '%s'"),
1455
                                     autostartLink, configFile);
1456 1457 1458
                goto cleanup;
            }
        } else {
1459
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
1460 1461
                virReportSystemError(net->conn, errno,
                                     _("Failed to delete symlink '%s'"),
1462
                                     autostartLink);
1463 1464
                goto cleanup;
            }
1465 1466
        }

1467
        network->autostart = autostart;
1468
    }
1469
    ret = 0;
1470

1471
cleanup:
1472 1473
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
1474 1475
    if (network)
        virNetworkObjUnlock(network);
1476
    networkDriverUnlock(driver);
1477
    return ret;
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
}


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

static virStateDriver networkStateDriver = {
    networkStartup,
    networkShutdown,
    networkReload,
    networkActive,
};

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