network_conf.c 89.4 KB
Newer Older
1 2 3
/*
 * network_conf.c: network XML handling
 *
4
 * Copyright (C) 2006-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 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
O
Osier Yang 已提交
18 19
 * License along with this library;  If not, see
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

26
#include <unistd.h>
27 28
#include <arpa/inet.h>
#include <sys/types.h>
A
Atsushi SAKAI 已提交
29
#include <sys/stat.h>
30
#include <fcntl.h>
31
#include <string.h>
32 33
#include <dirent.h>

34
#include "virterror_internal.h"
35
#include "datatypes.h"
36
#include "network_conf.h"
37 38
#include "netdev_vport_profile_conf.h"
#include "netdev_bandwidth_conf.h"
39
#include "netdev_vlan_conf.h"
40 41 42 43 44
#include "memory.h"
#include "xml.h"
#include "uuid.h"
#include "util.h"
#include "buf.h"
45
#include "c-ctype.h"
E
Eric Blake 已提交
46
#include "virfile.h"
47

48
#define MAX_BRIDGE_ID 256
49 50
#define VIR_FROM_THIS VIR_FROM_NETWORK

51 52
VIR_ENUM_IMPL(virNetworkForward,
              VIR_NETWORK_FORWARD_LAST,
53 54 55 56 57 58
              "none", "nat", "route", "bridge", "private", "vepa", "passthrough", "hostdev")

VIR_ENUM_DECL(virNetworkForwardHostdevDevice)
VIR_ENUM_IMPL(virNetworkForwardHostdevDevice,
              VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_LAST,
              "none", "pci", "netdev")
59

60
virNetworkObjPtr virNetworkFindByUUID(const virNetworkObjListPtr nets,
61 62
                                      const unsigned char *uuid)
{
63 64
    unsigned int i;

65 66
    for (i = 0 ; i < nets->count ; i++) {
        virNetworkObjLock(nets->objs[i]);
67 68
        if (!memcmp(nets->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return nets->objs[i];
69 70
        virNetworkObjUnlock(nets->objs[i]);
    }
71 72 73 74

    return NULL;
}

75
virNetworkObjPtr virNetworkFindByName(const virNetworkObjListPtr nets,
76 77
                                      const char *name)
{
78 79
    unsigned int i;

80 81
    for (i = 0 ; i < nets->count ; i++) {
        virNetworkObjLock(nets->objs[i]);
82 83
        if (STREQ(nets->objs[i]->def->name, name))
            return nets->objs[i];
84 85
        virNetworkObjUnlock(nets->objs[i]);
    }
86 87 88 89 90

    return NULL;
}


91 92 93 94 95
static void
virPortGroupDefClear(virPortGroupDefPtr def)
{
    VIR_FREE(def->name);
    VIR_FREE(def->virtPortProfile);
96
    virNetDevBandwidthFree(def->bandwidth);
97
    virNetDevVlanClear(&def->vlan);
98
    def->bandwidth = NULL;
99 100 101 102 103
}

static void
virNetworkForwardIfDefClear(virNetworkForwardIfDefPtr def)
{
104 105
    if (def->type == VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV)
        VIR_FREE(def->device.dev);
106 107
}

108 109 110 111 112 113
static void
virNetworkForwardPfDefClear(virNetworkForwardPfDefPtr def)
{
    VIR_FREE(def->dev);
}

114 115 116 117 118 119 120
static void
virNetworkDHCPHostDefClear(virNetworkDHCPHostDefPtr def)
{
    VIR_FREE(def->mac);
    VIR_FREE(def->name);
}

121 122 123 124 125 126 127
static void virNetworkIpDefClear(virNetworkIpDefPtr def)
{
    int ii;

    VIR_FREE(def->family);
    VIR_FREE(def->ranges);

128 129
    for (ii = 0 ; ii < def->nhosts && def->hosts ; ii++)
        virNetworkDHCPHostDefClear(&def->hosts[ii]);
130 131 132 133 134 135

    VIR_FREE(def->hosts);
    VIR_FREE(def->tftproot);
    VIR_FREE(def->bootfile);
}

136 137 138 139 140 141 142 143 144
static void virNetworkDNSDefFree(virNetworkDNSDefPtr def)
{
    if (def) {
        if (def->txtrecords) {
            while (def->ntxtrecords--) {
                VIR_FREE(def->txtrecords[def->ntxtrecords].name);
                VIR_FREE(def->txtrecords[def->ntxtrecords].value);
            }
        }
145
        VIR_FREE(def->txtrecords);
146 147 148 149 150 151 152
        if (def->nhosts) {
            while (def->nhosts--) {
                while (def->hosts[def->nhosts].nnames--)
                    VIR_FREE(def->hosts[def->nhosts].names[def->hosts[def->nhosts].nnames]);
                VIR_FREE(def->hosts[def->nhosts].names);
            }
        }
153
        VIR_FREE(def->hosts);
154 155 156 157 158 159 160 161 162
        if (def->nsrvrecords) {
            while (def->nsrvrecords--) {
                VIR_FREE(def->srvrecords[def->nsrvrecords].domain);
                VIR_FREE(def->srvrecords[def->nsrvrecords].service);
                VIR_FREE(def->srvrecords[def->nsrvrecords].protocol);
                VIR_FREE(def->srvrecords[def->nsrvrecords].target);
            }
        }
        VIR_FREE(def->srvrecords);
163 164 165 166
        VIR_FREE(def);
    }
}

167 168
void virNetworkDefFree(virNetworkDefPtr def)
{
169
    int ii;
170 171 172 173 174 175

    if (!def)
        return;

    VIR_FREE(def->name);
    VIR_FREE(def->bridge);
176
    VIR_FREE(def->domain);
177

178
    for (ii = 0 ; ii < def->nForwardPfs && def->forwardPfs ; ii++) {
179
        virNetworkForwardPfDefClear(&def->forwardPfs[ii]);
180 181 182
    }
    VIR_FREE(def->forwardPfs);

183 184 185 186 187
    for (ii = 0 ; ii < def->nForwardIfs && def->forwardIfs ; ii++) {
        virNetworkForwardIfDefClear(&def->forwardIfs[ii]);
    }
    VIR_FREE(def->forwardIfs);

188 189
    for (ii = 0 ; ii < def->nips && def->ips ; ii++) {
        virNetworkIpDefClear(&def->ips[ii]);
190
    }
191
    VIR_FREE(def->ips);
192

193 194 195 196 197
    for (ii = 0; ii < def->nPortGroups && def->portGroups; ii++) {
        virPortGroupDefClear(&def->portGroups[ii]);
    }
    VIR_FREE(def->portGroups);

198 199
    virNetworkDNSDefFree(def->dns);

200 201
    VIR_FREE(def->virtPortProfile);

202
    virNetDevBandwidthFree(def->bandwidth);
203
    virNetDevVlanClear(&def->vlan);
204 205 206 207 208 209 210 211 212 213 214
    VIR_FREE(def);
}

void virNetworkObjFree(virNetworkObjPtr net)
{
    if (!net)
        return;

    virNetworkDefFree(net->def);
    virNetworkDefFree(net->newDef);

215 216
    virMutexDestroy(&net->lock);

217 218 219
    VIR_FREE(net);
}

220 221 222 223 224 225 226 227 228 229 230
void virNetworkObjListFree(virNetworkObjListPtr nets)
{
    unsigned int i;

    for (i = 0 ; i < nets->count ; i++)
        virNetworkObjFree(nets->objs[i]);

    VIR_FREE(nets->objs);
    nets->count = 0;
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
/*
 * virNetworkObjAssignDef:
 * @network: the network object to update
 * @def: the new NetworkDef (will be consumed by this function iff successful)
 * @live: is this new def the "live" version, or the "persistent" version
 *
 * Replace the appropriate copy of the given network's NetworkDef
 * with def. Use "live" and current state of the network to determine
 * which to replace.
 *
 * Returns 0 on success, -1 on failure.
 */
int
virNetworkObjAssignDef(virNetworkObjPtr network,
                       const virNetworkDefPtr def,
                       bool live)
247
{
248 249
    if (virNetworkObjIsActive(network)) {
        if (live) {
250 251
            virNetworkDefFree(network->def);
            network->def = def;
252 253
        } else if (network->persistent) {
            /* save current configuration to be restored on network shutdown */
254
            virNetworkDefFree(network->newDef);
255
            network->newDef = def;
256 257 258 259 260
        } else {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("cannot save persistent config of transient "
                             "network '%s'"), network->def->name);
            return -1;
261
        }
262 263 264 265 266 267 268 269 270 271 272 273
    } else if (!live) {
        virNetworkDefFree(network->newDef); /* should be unnecessary */
        virNetworkDefFree(network->def);
        network->def = def;
    } else {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("cannot save live config of inactive "
                         "network '%s'"), network->def->name);
        return -1;
    }
    return 0;
}
274

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
/*
 * virNetworkAssignDef:
 * @nets: list of all networks
 * @def: the new NetworkDef (will be consumed by this function iff successful)
 * @live: is this new def the "live" version, or the "persistent" version
 *
 * Either replace the appropriate copy of the NetworkDef with name
 * matching def->name or, if not found, create a new NetworkObj with
 * def. For an existing network, use "live" and current state of the
 * network to determine which to replace.
 *
 * Returns -1 on failure, 0 on success.
 */
virNetworkObjPtr
virNetworkAssignDef(virNetworkObjListPtr nets,
                    const virNetworkDefPtr def,
                    bool live)
{
    virNetworkObjPtr network;

    if ((network = virNetworkFindByName(nets, def->name))) {
        if (virNetworkObjAssignDef(network, def, live) < 0) {
            return NULL;
        }
299 300 301
        return network;
    }

302 303 304 305 306
    if (VIR_REALLOC_N(nets->objs, nets->count + 1) < 0) {
        virReportOOMError();
        return NULL;
    }

307
    if (VIR_ALLOC(network) < 0) {
308
        virReportOOMError();
309 310
        return NULL;
    }
311
    if (virMutexInit(&network->lock) < 0) {
312 313
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
314 315 316
        VIR_FREE(network);
        return NULL;
    }
317
    virNetworkObjLock(network);
318 319
    network->def = def;

320 321
    nets->objs[nets->count] = network;
    nets->count++;
322 323 324 325 326

    return network;

}

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
/*
 * virNetworkObjSetDefTransient:
 * @network: network object pointer
 * @live: if true, run this operation even for an inactive network.
 *   this allows freely updated network->def with runtime defaults
 *   before starting the network, which will be discarded on network
 *   shutdown. Any cleanup paths need to be sure to handle newDef if
 *   the network is never started.
 *
 * Mark the active network config as transient. Ensures live-only update
 * operations do not persist past network destroy.
 *
 * Returns 0 on success, -1 on failure
 */
int
virNetworkObjSetDefTransient(virNetworkObjPtr network, bool live)
{
    if (!virNetworkObjIsActive(network) && !live)
        return 0;

    if (!network->persistent || network->newDef)
        return 0;

    network->newDef = virNetworkDefCopy(network->def, VIR_NETWORK_XML_INACTIVE);
    return network->newDef ? 0 : -1;
}

/*
 * virNetworkObjGetPersistentDef:
 * @network: network object pointer
 *
 * Return the persistent network configuration. If network is transient,
 * return the running config.
 *
 * Returns NULL on error, virNetworkDefPtr on success.
 */
virNetworkDefPtr
virNetworkObjGetPersistentDef(virNetworkObjPtr network)
{
    if (network->newDef)
        return network->newDef;
    else
        return network->def;
}

/*
 * virNetworkObjReplacePersistentDef:
 * @network: network object pointer
 * @def: new virNetworkDef to replace current persistent config
 *
 * Replace the "persistent" network configuration with the given new
 * virNetworkDef. This pays attention to whether or not the network
 * is active.
 *
 * Returns -1 on error, 0 on success
 */
int
virNetworkObjReplacePersistentDef(virNetworkObjPtr network,
                                  virNetworkDefPtr def)
{
    if (virNetworkObjIsActive(network)) {
        virNetworkDefFree(network->newDef);
        network->newDef = def;
    } else {
        virNetworkDefFree(network->def);
        network->def = def;
    }
    return 0;
}

/*
 * virNetworkDefCopy:
 * @def: NetworkDef to copy
 * @flags: VIR_NETWORK_XML_INACTIVE if appropriate
 *
 * make a deep copy of the given NetworkDef
 *
 * Returns a new NetworkDef on success, or NULL on failure.
 */
virNetworkDefPtr
virNetworkDefCopy(virNetworkDefPtr def, unsigned int flags)
{
    char *xml = NULL;
    virNetworkDefPtr newDef = NULL;

    if (!def) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("NULL NetworkDef"));
        return NULL;
    }

    /* deep copy with a format/parse cycle */
    if (!(xml = virNetworkDefFormat(def, flags)))
        goto cleanup;
    newDef = virNetworkDefParseString(xml);
cleanup:
    VIR_FREE(xml);
    return newDef;
}

/*
 * virNetworkConfigChangeSetup:
 *
 * 1) checks whether network state is consistent with the requested
 *    type of modification.
 *
 * 3) make sure there are separate "def" and "newDef" copies of
 *    networkDef if appropriate.
 *
 * Returns 0 on success, -1 on error.
 */
int
virNetworkConfigChangeSetup(virNetworkObjPtr network, unsigned int flags)
{
    bool isActive;
    int ret = -1;

    isActive = virNetworkObjIsActive(network);

    if (!isActive && (flags & VIR_NETWORK_UPDATE_AFFECT_LIVE)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("network is not running"));
        goto cleanup;
    }

    if (flags & VIR_NETWORK_UPDATE_AFFECT_CONFIG) {
        if (!network->persistent) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot change persistent config of a "
                             "transient network"));
            goto cleanup;
        }
        /* this should already have been done by the driver, but do it
         * anyway just in case.
         */
        if (isActive && (virNetworkObjSetDefTransient(network, false) < 0))
            goto cleanup;
    }

    ret = 0;
cleanup:
    return ret;
}

471
void virNetworkRemoveInactive(virNetworkObjListPtr nets,
472 473
                              const virNetworkObjPtr net)
{
474
    unsigned int i;
475

476
    virNetworkObjUnlock(net);
477
    for (i = 0 ; i < nets->count ; i++) {
478
        virNetworkObjLock(nets->objs[i]);
479
        if (nets->objs[i] == net) {
480
            virNetworkObjUnlock(nets->objs[i]);
481
            virNetworkObjFree(nets->objs[i]);
482

483 484 485
            if (i < (nets->count - 1))
                memmove(nets->objs + i, nets->objs + i + 1,
                        sizeof(*(nets->objs)) * (nets->count - (i + 1)));
486

487 488 489 490 491 492 493
            if (VIR_REALLOC_N(nets->objs, nets->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            nets->count--;

            break;
        }
494
        virNetworkObjUnlock(nets->objs[i]);
495
    }
496 497
}

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
/* return ips[index], or NULL if there aren't enough ips */
virNetworkIpDefPtr
virNetworkDefGetIpByIndex(const virNetworkDefPtr def,
                          int family, size_t n)
{
    int ii;

    if (!def->ips || n >= def->nips)
        return NULL;

    if (family == AF_UNSPEC) {
        return &def->ips[n];
    }

    /* find the nth ip of type "family" */
    for (ii = 0; ii < def->nips; ii++) {
514
        if (VIR_SOCKET_ADDR_IS_FAMILY(&def->ips[ii].address, family)
515 516 517 518 519 520 521 522
            && (n-- <= 0)) {
            return &def->ips[ii];
        }
    }
    /* failed to find enough of the right family */
    return NULL;
}

L
Laine Stump 已提交
523 524 525
/* return number of 1 bits in netmask for the network's ipAddress,
 * or -1 on error
 */
526
int virNetworkIpDefPrefix(const virNetworkIpDefPtr def)
L
Laine Stump 已提交
527
{
528 529
    if (def->prefix > 0) {
        return def->prefix;
530 531 532
    } else if (VIR_SOCKET_ADDR_VALID(&def->netmask)) {
        return virSocketAddrGetNumNetmaskBits(&def->netmask);
    } else if (VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
L
Laine Stump 已提交
533 534 535 536 537 538
        /* Return the natural prefix for the network's ip address.
         * On Linux we could use the IN_CLASSx() macros, but those
         * aren't guaranteed on all platforms, so we just deal with
         * the bits ourselves.
         */
        unsigned char octet
539
            = ntohl(def->address.data.inet4.sin_addr.s_addr) >> 24;
L
Laine Stump 已提交
540 541 542 543 544 545 546 547 548 549 550
        if ((octet & 0x80) == 0) {
            /* Class A network */
            return 8;
        } else if ((octet & 0xC0) == 0x80) {
            /* Class B network */
            return 16;
        } else if ((octet & 0xE0) == 0xC0) {
            /* Class C network */
            return 24;
        }
        return -1;
551
    } else if (VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6)) {
552
        return 64;
L
Laine Stump 已提交
553 554 555 556 557 558 559 560
    }
    return -1;
}

/* Fill in a virSocketAddr with the proper netmask for this
 * definition, based on either the definition's netmask, or its
 * prefix. Return -1 on error (and set the netmask family to AF_UNSPEC)
 */
561 562
int virNetworkIpDefNetmask(const virNetworkIpDefPtr def,
                           virSocketAddrPtr netmask)
L
Laine Stump 已提交
563
{
564
    if (VIR_SOCKET_ADDR_IS_FAMILY(&def->netmask, AF_INET)) {
L
Laine Stump 已提交
565 566 567 568
        *netmask = def->netmask;
        return 0;
    }

569
    return virSocketAddrPrefixToNetmask(virNetworkIpDefPrefix(def), netmask,
570
                                        VIR_SOCKET_ADDR_FAMILY(&def->address));
L
Laine Stump 已提交
571 572
}

573 574

static int
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 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 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
virNetworkDHCPRangeDefParse(const char *networkName,
                            xmlNodePtr node,
                            virNetworkDHCPRangeDefPtr range)
{


    char *start = NULL, *end = NULL;
    int ret = -1;

    if (!(start = virXMLPropString(node, "start"))) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Missing 'start' attribute in dhcp range for network '%s'"),
                       networkName);
        goto cleanup;
    }
    if (virSocketAddrParse(&range->start, start, AF_UNSPEC) < 0)
        goto cleanup;

    if (!(end = virXMLPropString(node, "end"))) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Missing 'end' attribute in dhcp range for network '%s'"),
                       networkName);
        goto cleanup;
    }
    if (virSocketAddrParse(&range->end, end, AF_UNSPEC) < 0)
        goto cleanup;

    /* do a sanity check of the range */
    if (virSocketAddrGetRange(&range->start, &range->end) < 0) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Invalid dhcp range '%s' to '%s' in network '%s'"),
                       start, end, networkName);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VIR_FREE(start);
    VIR_FREE(end);
    return ret;
}

static int
virNetworkDHCPHostDefParse(const char *networkName,
                           xmlNodePtr node,
                           virNetworkDHCPHostDefPtr host,
                           bool partialOkay)
{
    char *mac = NULL, *name = NULL, *ip = NULL;
    virMacAddr addr;
    virSocketAddr inaddr;
    int ret = -1;

    mac = virXMLPropString(node, "mac");
    if (mac != NULL) {
        if (virMacAddrParse(mac, &addr) < 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Cannot parse MAC address '%s' in network '%s'"),
                           mac, networkName);
            goto cleanup;
        }
        if (virMacAddrIsMulticast(&addr)) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("expected unicast mac address, found "
                             "multicast '%s' in network '%s'"),
                           (const char *)mac, networkName);
            goto cleanup;
        }
    }

    name = virXMLPropString(node, "name");
    if (name && (!c_isalpha(name[0]))) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Cannot use name address '%s' in network '%s'"),
                       name, networkName);
        goto cleanup;
    }

    ip = virXMLPropString(node, "ip");
    if (ip && (virSocketAddrParse(&inaddr, ip, AF_UNSPEC) < 0)) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Invalid IP address in static host definition "
                         "for network '%s'"),
                       networkName);
        goto cleanup;
    }

    if (partialOkay) {
        /* for search/match, you just need one of the three */
        if (!(mac || name || ip)) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("At least one of name, mac, or ip attribute "
                             "must be specified for static host definition "
                             "in network '%s' "),
                           networkName);
        }
    } else {
        /* normal usage - you need at least one MAC address or one host name */
        if (!(mac || name)) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Static host definition in network '%s' "
                             "must have mac or name attribute"),
                           networkName);
            goto cleanup;
        }
        if (!ip) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("Missing IP address in static host definition "
                             "for network '%s'"),
                           networkName);
            goto cleanup;
        }
    }

    host->mac = mac;
    mac = NULL;
    host->name = name;
    name = NULL;
    if (ip)
        host->ip = inaddr;
    ret = 0;

cleanup:
    VIR_FREE(mac);
    VIR_FREE(name);
    VIR_FREE(ip);
    return ret;
}

static int
virNetworkDHCPDefParse(const char *networkName,
                       virNetworkIpDefPtr def,
                       xmlNodePtr node)
709
{
710 711 712 713 714

    xmlNodePtr cur;

    cur = node->children;
    while (cur != NULL) {
715 716
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "range")) {
717

718
            if (VIR_REALLOC_N(def->ranges, def->nranges + 1) < 0) {
719
                virReportOOMError();
720 721
                return -1;
            }
722 723 724 725
            if (virNetworkDHCPRangeDefParse(networkName, cur,
                                            &def->ranges[def->nranges]) < 0) {
                return -1;
            }
726
            def->nranges++;
727

728 729 730 731
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {

            if (VIR_REALLOC_N(def->hosts, def->nhosts + 1) < 0) {
732
                virReportOOMError();
733 734
                return -1;
            }
735 736 737 738 739
            if (virNetworkDHCPHostDefParse(networkName, cur,
                                           &def->hosts[def->nhosts],
                                           false) < 0) {
                return -1;
            }
740
            def->nhosts++;
741 742 743

        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "bootp")) {
744 745
            char *file;
            char *server;
746
            virSocketAddr inaddr;
747
            memset(&inaddr, 0, sizeof(inaddr));
748

749
            if (!(file = virXMLPropString(cur, "file"))) {
750 751 752
                cur = cur->next;
                continue;
            }
753
            server = virXMLPropString(cur, "server");
754

755
            if (server &&
756
                virSocketAddrParse(&inaddr, server, AF_UNSPEC) < 0) {
E
Eric Blake 已提交
757 758
                VIR_FREE(file);
                VIR_FREE(server);
759
                return -1;
E
Eric Blake 已提交
760
            }
761

762
            def->bootfile = file;
763
            def->bootserver = inaddr;
E
Eric Blake 已提交
764
            VIR_FREE(server);
765 766 767 768 769 770 771 772
        }

        cur = cur->next;
    }

    return 0;
}

773 774 775 776 777 778 779 780 781 782
static int
virNetworkDNSHostsDefParseXML(virNetworkDNSDefPtr def,
                              xmlNodePtr node)
{
    xmlNodePtr cur;
    char *ip;
    virSocketAddr inaddr;
    int ret = -1;

    if (!(ip = virXMLPropString(node, "ip")) ||
783
        (virSocketAddrParse(&inaddr, ip, AF_UNSPEC) < 0)) {
784
        virReportError(VIR_ERR_XML_DETAIL, "%s",
785
                       _("Missing IP address in DNS host definition"));
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829
        VIR_FREE(ip);
        goto error;
    }
    VIR_FREE(ip);

    if (VIR_REALLOC_N(def->hosts, def->nhosts + 1) < 0) {
        virReportOOMError();
        goto error;
    }

    def->hosts[def->nhosts].ip = inaddr;
    def->hosts[def->nhosts].nnames = 0;

    if (VIR_ALLOC(def->hosts[def->nhosts].names) < 0) {
        virReportOOMError();
        goto error;
    }

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "hostname")) {
              if (cur->children != NULL) {
                  if (VIR_REALLOC_N(def->hosts[def->nhosts].names, def->hosts[def->nhosts].nnames + 1) < 0) {
                      virReportOOMError();
                      goto error;
                  }

                  def->hosts[def->nhosts].names[def->hosts[def->nhosts].nnames] = strdup((char *)cur->children->content);
                  def->hosts[def->nhosts].nnames++;
              }
        }

        cur = cur->next;
    }

    def->nhosts++;

    ret = 0;

error:
    return ret;
}

830 831 832 833 834
static int
virNetworkDNSSrvDefParseXML(virNetworkDNSDefPtr def,
                            xmlNodePtr cur,
                            xmlXPathContextPtr ctxt)
{
835 836 837 838
    char *domain = NULL;
    char *service = NULL;
    char *protocol = NULL;
    char *target = NULL;
839 840 841 842 843 844
    int port;
    int priority;
    int weight;
    int ret = 0;

    if (!(service = virXMLPropString(cur, "service"))) {
845 846
        virReportError(VIR_ERR_XML_DETAIL,
                       "%s", _("Missing required service attribute in dns srv record"));
847 848 849 850
        goto error;
    }

    if (strlen(service) > DNS_RECORD_LENGTH_SRV) {
851 852 853
        virReportError(VIR_ERR_XML_DETAIL,
                       _("Service name is too long, limit is %d bytes"),
                       DNS_RECORD_LENGTH_SRV);
854 855 856 857
        goto error;
    }

    if (!(protocol = virXMLPropString(cur, "protocol"))) {
858 859
        virReportError(VIR_ERR_XML_DETAIL,
                       _("Missing required protocol attribute in dns srv record '%s'"), service);
860 861 862 863 864
        goto error;
    }

    /* Check whether protocol value is the supported one */
    if (STRNEQ(protocol, "tcp") && (STRNEQ(protocol, "udp"))) {
865 866
        virReportError(VIR_ERR_XML_DETAIL,
                       _("Invalid protocol attribute value '%s'"), protocol);
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
        goto error;
    }

    if (VIR_REALLOC_N(def->srvrecords, def->nsrvrecords + 1) < 0) {
        virReportOOMError();
        goto error;
    }

    def->srvrecords[def->nsrvrecords].service = service;
    def->srvrecords[def->nsrvrecords].protocol = protocol;
    def->srvrecords[def->nsrvrecords].domain = NULL;
    def->srvrecords[def->nsrvrecords].target = NULL;
    def->srvrecords[def->nsrvrecords].port = 0;
    def->srvrecords[def->nsrvrecords].priority = 0;
    def->srvrecords[def->nsrvrecords].weight = 0;

    /* Following attributes are optional but we had to make sure they're NULL above */
    if ((target = virXMLPropString(cur, "target")) && (domain = virXMLPropString(cur, "domain"))) {
        xmlNodePtr save_ctxt = ctxt->node;

        ctxt->node = cur;
        if (virXPathInt("string(./@port)", ctxt, &port))
            def->srvrecords[def->nsrvrecords].port = port;

        if (virXPathInt("string(./@priority)", ctxt, &priority))
            def->srvrecords[def->nsrvrecords].priority = priority;

        if (virXPathInt("string(./@weight)", ctxt, &weight))
            def->srvrecords[def->nsrvrecords].weight = weight;
        ctxt->node = save_ctxt;

        def->srvrecords[def->nsrvrecords].domain = domain;
        def->srvrecords[def->nsrvrecords].target = target;
        def->srvrecords[def->nsrvrecords].port = port;
        def->srvrecords[def->nsrvrecords].priority = priority;
        def->srvrecords[def->nsrvrecords].weight = weight;
    }

    def->nsrvrecords++;

    goto cleanup;

error:
    VIR_FREE(domain);
    VIR_FREE(service);
    VIR_FREE(protocol);
    VIR_FREE(target);

    ret = -1;

cleanup:
    return ret;
}

921 922
static int
virNetworkDNSDefParseXML(virNetworkDNSDefPtr *dnsdef,
923 924
                         xmlNodePtr node,
                         xmlXPathContextPtr ctxt)
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941
{
    xmlNodePtr cur;
    int ret = -1;
    char *name = NULL;
    char *value = NULL;
    virNetworkDNSDefPtr def = NULL;

    if (VIR_ALLOC(def) < 0) {
        virReportOOMError();
        goto error;
    }

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "txt")) {
            if (!(name = virXMLPropString(cur, "name"))) {
942 943
                virReportError(VIR_ERR_XML_DETAIL,
                               "%s", _("Missing required name attribute in dns txt record"));
944 945 946
                goto error;
            }
            if (!(value = virXMLPropString(cur, "value"))) {
947 948
                virReportError(VIR_ERR_XML_DETAIL,
                               _("Missing required value attribute in dns txt record '%s'"), name);
949 950 951 952
                goto error;
            }

            if (strchr(name, ' ') != NULL) {
953 954
                virReportError(VIR_ERR_XML_DETAIL,
                               _("spaces are not allowed in DNS TXT record names (name is '%s')"), name);
955 956 957 958 959 960 961 962 963 964 965 966 967
                goto error;
            }

            if (VIR_REALLOC_N(def->txtrecords, def->ntxtrecords + 1) < 0) {
                virReportOOMError();
                goto error;
            }

            def->txtrecords[def->ntxtrecords].name = name;
            def->txtrecords[def->ntxtrecords].value = value;
            def->ntxtrecords++;
            name = NULL;
            value = NULL;
968 969 970 971 972
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "srv")) {
            ret = virNetworkDNSSrvDefParseXML(def, cur, ctxt);
            if (ret < 0)
                goto error;
973 974 975 976 977
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {
            ret = virNetworkDNSHostsDefParseXML(def, cur);
            if (ret < 0)
                goto error;
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
        }

        cur = cur->next;
    }

    ret = 0;
error:
    if (ret < 0) {
        VIR_FREE(name);
        VIR_FREE(value);
        virNetworkDNSDefFree(def);
    } else {
        *dnsdef = def;
    }
    return ret;
}

995
static int
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
virNetworkIPParseXML(const char *networkName,
                     virNetworkIpDefPtr def,
                     xmlNodePtr node,
                     xmlXPathContextPtr ctxt)
{
    /*
     * virNetworkIpDef object is already allocated as part of an array.
     * On failure clear it out, but don't free it.
     */

    xmlNodePtr cur, save;
    char *address = NULL, *netmask = NULL;
    unsigned long prefix;
    int result = -1;

    save = ctxt->node;
    ctxt->node = node;

    /* grab raw data from XML */
    def->family = virXPathString("string(./@family)", ctxt);
    address = virXPathString("string(./@address)", ctxt);
    if (virXPathULong("string(./@prefix)", ctxt, &prefix) < 0)
        def->prefix = 0;
    else
        def->prefix = prefix;

    netmask = virXPathString("string(./@netmask)", ctxt);

    if (address) {
1025
        if (virSocketAddrParse(&def->address, address, AF_UNSPEC) < 0) {
1026 1027 1028
            virReportError(VIR_ERR_XML_ERROR,
                           _("Bad address '%s' in definition of network '%s'"),
                           address, networkName);
1029 1030
            goto error;
        }
1031

1032
    }
1033

1034 1035
    /* validate family vs. address */
    if (def->family == NULL) {
1036 1037
        if (!(VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET) ||
              VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_UNSPEC))) {
1038 1039 1040
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("no family specified for non-IPv4 address '%s' in network '%s'"),
                           address, networkName);
1041 1042 1043
            goto error;
        }
    } else if (STREQ(def->family, "ipv4")) {
1044
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
1045 1046 1047
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("family 'ipv4' specified for non-IPv4 address '%s' in network '%s'"),
                           address, networkName);
1048 1049 1050
            goto error;
        }
    } else if (STREQ(def->family, "ipv6")) {
1051
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6)) {
1052 1053 1054
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("family 'ipv6' specified for non-IPv6 address '%s' in network '%s'"),
                           address, networkName);
1055 1056 1057
            goto error;
        }
    } else {
1058 1059 1060
        virReportError(VIR_ERR_XML_ERROR,
                       _("Unrecognized family '%s' in definition of network '%s'"),
                       def->family, networkName);
1061 1062
        goto error;
    }
1063

1064 1065 1066 1067
    /* parse/validate netmask */
    if (netmask) {
        if (address == NULL) {
            /* netmask is meaningless without an address */
1068 1069 1070
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("netmask specified without address in network '%s'"),
                           networkName);
1071 1072 1073
            goto error;
        }

1074
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
1075 1076 1077
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("netmask not supported for address '%s' in network '%s' (IPv4 only)"),
                           address, networkName);
1078 1079 1080 1081 1082
            goto error;
        }

        if (def->prefix > 0) {
            /* can't have both netmask and prefix at the same time */
1083 1084 1085
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("network '%s' cannot have both prefix='%u' and a netmask"),
                           networkName, def->prefix);
1086 1087 1088
            goto error;
        }

1089
        if (virSocketAddrParse(&def->netmask, netmask, AF_UNSPEC) < 0)
1090 1091
            goto error;

1092
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->netmask, AF_INET)) {
1093 1094 1095
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("network '%s' has invalid netmask '%s' for address '%s' (both must be IPv4)"),
                           networkName, netmask, address);
1096 1097 1098 1099
            goto error;
        }
    }

1100
    if (VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
1101 1102 1103 1104 1105
        /* parse IPv4-related info */
        cur = node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE &&
                xmlStrEqual(cur->name, BAD_CAST "dhcp")) {
1106
                result = virNetworkDHCPDefParse(networkName, def, cur);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
                if (result)
                    goto error;

            } else if (cur->type == XML_ELEMENT_NODE &&
                       xmlStrEqual(cur->name, BAD_CAST "tftp")) {
                char *root;

                if (!(root = virXMLPropString(cur, "root"))) {
                    cur = cur->next;
                    continue;
                }

                def->tftproot = (char *)root;
1120 1121
            }

1122
            cur = cur->next;
1123
        }
1124
    }
1125

1126 1127 1128 1129 1130
    result = 0;

error:
    if (result < 0) {
        virNetworkIpDefClear(def);
1131
    }
1132 1133 1134 1135 1136
    VIR_FREE(address);
    VIR_FREE(netmask);

    ctxt->node = save;
    return result;
1137 1138
}

1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150
static int
virNetworkPortGroupParseXML(virPortGroupDefPtr def,
                            xmlNodePtr node,
                            xmlXPathContextPtr ctxt)
{
    /*
     * virPortGroupDef object is already allocated as part of an array.
     * On failure clear it out, but don't free it.
     */

    xmlNodePtr save;
    xmlNodePtr virtPortNode;
1151
    xmlNodePtr vlanNode;
1152
    xmlNodePtr bandwidth_node;
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
    char *isDefault = NULL;

    int result = -1;

    save = ctxt->node;
    ctxt->node = node;

    /* grab raw data from XML */
    def->name = virXPathString("string(./@name)", ctxt);
    isDefault = virXPathString("string(./@default)", ctxt);
    def->isDefault = isDefault && STRCASEEQ(isDefault, "yes");

    virtPortNode = virXPathNode("./virtualport", ctxt);
    if (virtPortNode &&
1167
        (!(def->virtPortProfile = virNetDevVPortProfileParse(virtPortNode, 0)))) {
1168
        goto error;
1169
    }
1170

1171 1172
    bandwidth_node = virXPathNode("./bandwidth", ctxt);
    if (bandwidth_node &&
1173
        !(def->bandwidth = virNetDevBandwidthParse(bandwidth_node))) {
1174 1175 1176
        goto error;
    }

1177 1178 1179 1180
    vlanNode = virXPathNode("./vlan", ctxt);
    if (vlanNode && virNetDevVlanParse(vlanNode, ctxt, &def->vlan) < 0)
        goto error;

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    result = 0;
error:
    if (result < 0) {
        virPortGroupDefClear(def);
    }
    VIR_FREE(isDefault);

    ctxt->node = save;
    return result;
}

1192
static virNetworkDefPtr
1193
virNetworkDefParseXML(xmlXPathContextPtr ctxt)
1194 1195 1196
{
    virNetworkDefPtr def;
    char *tmp;
1197
    char *stp = NULL;
1198
    xmlNodePtr *ipNodes = NULL;
1199 1200
    xmlNodePtr *portGroupNodes = NULL;
    xmlNodePtr *forwardIfNodes = NULL;
1201
    xmlNodePtr *forwardPfNodes = NULL;
1202
    xmlNodePtr *forwardAddrNodes = NULL;
1203
    xmlNodePtr dnsNode = NULL;
1204 1205
    xmlNodePtr virtPortNode = NULL;
    xmlNodePtr forwardNode = NULL;
1206
    int nIps, nPortGroups, nForwardIfs, nForwardPfs, nForwardAddrs;
1207
    char *forwardDev = NULL;
1208 1209
    char *forwardManaged = NULL;
    char *type = NULL;
1210
    xmlNodePtr save = ctxt->node;
1211
    xmlNodePtr bandwidthNode = NULL;
1212
    xmlNodePtr vlanNode;
1213 1214

    if (VIR_ALLOC(def) < 0) {
1215
        virReportOOMError();
1216 1217 1218 1219
        return NULL;
    }

    /* Extract network name */
1220
    def->name = virXPathString("string(./name[1])", ctxt);
1221
    if (!def->name) {
1222
        virReportError(VIR_ERR_NO_NAME, NULL);
1223 1224 1225 1226
        goto error;
    }

    /* Extract network uuid */
1227
    tmp = virXPathString("string(./uuid[1])", ctxt);
1228
    if (!tmp) {
1229
        if (virUUIDGenerate(def->uuid)) {
1230 1231
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to generate UUID"));
1232 1233 1234 1235 1236
            goto error;
        }
    } else {
        if (virUUIDParse(tmp, def->uuid) < 0) {
            VIR_FREE(tmp);
1237 1238
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("malformed uuid element"));
1239 1240 1241
            goto error;
        }
        VIR_FREE(tmp);
M
Matthias Bolte 已提交
1242
        def->uuid_specified = true;
1243 1244
    }

1245
    /* Parse network domain information */
1246
    def->domain = virXPathString("string(./domain[1]/@name)", ctxt);
1247

1248
    if ((bandwidthNode = virXPathNode("./bandwidth", ctxt)) != NULL &&
1249
        (def->bandwidth = virNetDevBandwidthParse(bandwidthNode)) == NULL)
1250 1251
        goto error;

1252 1253 1254 1255
    vlanNode = virXPathNode("./vlan", ctxt);
    if (vlanNode && virNetDevVlanParse(vlanNode, ctxt, &def->vlan) < 0)
        goto error;

1256
    /* Parse bridge information */
1257
    def->bridge = virXPathString("string(./bridge[1]/@name)", ctxt);
1258
    stp = virXPathString("string(./bridge[1]/@stp)", ctxt);
1259

1260
    if (virXPathULong("string(./bridge[1]/@delay)", ctxt, &def->delay) < 0)
1261 1262
        def->delay = 0;

1263 1264
    tmp = virXPathString("string(./mac[1]/@address)", ctxt);
    if (tmp) {
1265
        if (virMacAddrParse(tmp, &def->mac) < 0) {
1266 1267 1268
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid bridge mac address '%s' in network '%s'"),
                           tmp, def->name);
1269 1270 1271
            VIR_FREE(tmp);
            goto error;
        }
1272
        if (virMacAddrIsMulticast(&def->mac)) {
1273 1274 1275
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid multicast bridge mac address '%s' in network '%s'"),
                           tmp, def->name);
1276 1277 1278
            VIR_FREE(tmp);
            goto error;
        }
1279 1280 1281 1282
        VIR_FREE(tmp);
        def->mac_specified = true;
    }

1283 1284
    dnsNode = virXPathNode("./dns", ctxt);
    if (dnsNode != NULL) {
1285
        if (virNetworkDNSDefParseXML(&def->dns, dnsNode, ctxt) < 0)
1286 1287 1288
            goto error;
    }

1289 1290
    virtPortNode = virXPathNode("./virtualport", ctxt);
    if (virtPortNode &&
1291 1292
        (!(def->virtPortProfile = virNetDevVPortProfileParse(virtPortNode,
                                                             VIR_VPORT_XML_REQUIRE_TYPE)))) {
1293
        goto error;
1294
    }
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318

    nPortGroups = virXPathNodeSet("./portgroup", ctxt, &portGroupNodes);
    if (nPortGroups < 0)
        goto error;

    if (nPortGroups > 0) {
        int ii;

        /* allocate array to hold all the portgroups */
        if (VIR_ALLOC_N(def->portGroups, nPortGroups) < 0) {
            virReportOOMError();
            goto error;
        }
        /* parse each portgroup */
        for (ii = 0; ii < nPortGroups; ii++) {
            int ret = virNetworkPortGroupParseXML(&def->portGroups[ii],
                                                  portGroupNodes[ii], ctxt);
            if (ret < 0)
                goto error;
            def->nPortGroups++;
        }
    }
    VIR_FREE(portGroupNodes);

1319
    nIps = virXPathNodeSet("./ip", ctxt, &ipNodes);
1320 1321 1322
    if (nIps < 0)
        goto error;

1323 1324
    if (nIps > 0) {
        int ii;
1325

1326 1327 1328
        /* allocate array to hold all the addrs */
        if (VIR_ALLOC_N(def->ips, nIps) < 0) {
            virReportOOMError();
1329 1330
            goto error;
        }
1331 1332 1333 1334 1335 1336 1337
        /* parse each addr */
        for (ii = 0; ii < nIps; ii++) {
            int ret = virNetworkIPParseXML(def->name, &def->ips[ii],
                                           ipNodes[ii], ctxt);
            if (ret < 0)
                goto error;
            def->nips++;
1338
        }
1339
    }
E
Eric Blake 已提交
1340
    VIR_FREE(ipNodes);
1341

1342 1343 1344 1345 1346 1347 1348
    forwardNode = virXPathNode("./forward", ctxt);
    if (!forwardNode) {
        def->forwardType = VIR_NETWORK_FORWARD_NONE;
        def->stp = (stp && STREQ(stp, "off")) ? 0 : 1;
    } else {
        ctxt->node = forwardNode;
        tmp = virXPathString("string(./@mode)", ctxt);
1349 1350
        if (tmp) {
            if ((def->forwardType = virNetworkForwardTypeFromString(tmp)) < 0) {
1351 1352
                virReportError(VIR_ERR_XML_ERROR,
                               _("unknown forwarding type '%s'"), tmp);
1353 1354 1355 1356 1357 1358 1359 1360
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        } else {
            def->forwardType = VIR_NETWORK_FORWARD_NAT;
        }

1361
        forwardDev = virXPathString("string(./@dev)", ctxt);
1362 1363 1364 1365 1366
        forwardManaged = virXPathString("string(./@managed)", ctxt);
        if(forwardManaged != NULL) {
            if (STRCASEEQ(forwardManaged, "yes"))
                def->managed = 1;
        }
1367

1368 1369
        /* all of these modes can use a pool of physical interfaces */
        nForwardIfs = virXPathNodeSet("./interface", ctxt, &forwardIfNodes);
1370
        nForwardPfs = virXPathNodeSet("./pf", ctxt, &forwardPfNodes);
1371
        nForwardAddrs = virXPathNodeSet("./address", ctxt, &forwardAddrNodes);
1372

1373
        if (nForwardIfs < 0 || nForwardPfs < 0 || nForwardAddrs < 0) {
1374
            virReportError(VIR_ERR_XML_ERROR, "%s",
1375
                           _("No interface pool or SRIOV physical device given"));
1376
            goto error;
1377 1378
        }

1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
        if ((nForwardIfs > 0) && (nForwardAddrs > 0)) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Address and interface attributes are mutually exclusive"));
            goto error;
        }

        if ((nForwardPfs > 0) && ((nForwardIfs > 0) || (nForwardAddrs > 0))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Address/interface attributes and Physical function are mutually exclusive "));
            goto error;
        }

1391 1392 1393 1394 1395 1396 1397
        if (nForwardPfs == 1) {
            if (VIR_ALLOC_N(def->forwardPfs, nForwardPfs) < 0) {
                virReportOOMError();
                goto error;
            }

            if (forwardDev) {
1398
                virReportError(VIR_ERR_XML_ERROR, "%s",
1399
                               _("A forward Dev should not be used when using a SRIOV PF"));
1400 1401
                goto error;
            }
1402

1403 1404
            forwardDev = virXMLPropString(*forwardPfNodes, "dev");
            if (!forwardDev) {
1405 1406 1407
                virReportError(VIR_ERR_XML_ERROR,
                               _("Missing required dev attribute in network '%s' pf element"),
                               def->name);
1408 1409 1410 1411 1412 1413 1414
                goto error;
            }

            def->forwardPfs->dev = forwardDev;
            forwardDev = NULL;
            def->nForwardPfs++;
        } else if (nForwardPfs > 1) {
1415
            virReportError(VIR_ERR_XML_ERROR, "%s",
1416
                           _("Use of more than one physical interface is not allowed"));
1417 1418
            goto error;
        }
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
        if (nForwardAddrs > 0) {
            int ii;

            if (VIR_ALLOC_N(def->forwardIfs, nForwardAddrs) < 0) {
                virReportOOMError();
                goto error;
            }

            if (forwardDev) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("A forward Dev should not be used when using address attribute"));
                goto error;
            }

            for (ii = 0; ii < nForwardAddrs; ii++) {
                type = virXMLPropString(forwardAddrNodes[ii], "type");

                if (type) {
                    if ((def->forwardIfs[ii].type = virNetworkForwardHostdevDeviceTypeFromString(type)) < 0) {
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("unknown address type '%s'"), type);
                        goto error;
                    }
                } else {
                    virReportError(VIR_ERR_XML_ERROR,
                                   "%s", _("No type specified for device address"));
                    goto error;
                }

                switch (def->forwardIfs[ii].type) {
                case VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_PCI:
                    if (virDevicePCIAddressParseXML(forwardAddrNodes[ii], &(def->forwardIfs[ii].device.pci)) < 0)
                        goto error;
                    break;

                /* Add USB case here */

                default:
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("unknown address type '%s'"), type);
                    goto error;
                }
                VIR_FREE(type);
                def->nForwardIfs++;
            }
        }
        else if (nForwardIfs > 0 || forwardDev) {
1466
            int ii;
1467

1468 1469 1470 1471 1472 1473 1474
            /* allocate array to hold all the portgroups */
            if (VIR_ALLOC_N(def->forwardIfs, MAX(nForwardIfs, 1)) < 0) {
                virReportOOMError();
                goto error;
            }

            if (forwardDev) {
1475 1476
                def->forwardIfs[0].device.dev = forwardDev;
                def->forwardIfs[0].type = VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV;
1477 1478 1479 1480 1481 1482 1483 1484
                forwardDev = NULL;
                def->nForwardIfs++;
            }

            /* parse each forwardIf */
            for (ii = 0; ii < nForwardIfs; ii++) {
                forwardDev = virXMLPropString(forwardIfNodes[ii], "dev");
                if (!forwardDev) {
1485 1486 1487
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Missing required dev attribute in network '%s' forward interface element"),
                                   def->name);
1488 1489 1490 1491 1492 1493
                    goto error;
                }

                if ((ii == 0) && (def->nForwardIfs == 1)) {
                    /* both forwardDev and an interface element are present.
                     * If they don't match, it's an error. */
1494
                    if (STRNEQ(forwardDev, def->forwardIfs[0].device.dev)) {
1495 1496
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("forward dev '%s' must match first interface element dev '%s' in network '%s'"),
1497
                                       def->forwardIfs[0].device.dev,
1498
                                       forwardDev, def->name);
1499 1500 1501 1502 1503 1504
                        goto error;
                    }
                    VIR_FREE(forwardDev);
                    continue;
                }

1505
                def->forwardIfs[ii].device.dev = forwardDev;
1506
                forwardDev = NULL;
1507
                def->forwardIfs[ii].type = VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_NETDEV;
1508 1509 1510
                def->nForwardIfs++;
            }
        }
1511
        VIR_FREE(type);
1512
        VIR_FREE(forwardDev);
1513
        VIR_FREE(forwardManaged);
1514
        VIR_FREE(forwardPfNodes);
1515
        VIR_FREE(forwardIfNodes);
1516
        VIR_FREE(forwardAddrNodes);
1517 1518 1519 1520 1521 1522 1523
        switch (def->forwardType) {
        case VIR_NETWORK_FORWARD_ROUTE:
        case VIR_NETWORK_FORWARD_NAT:
            /* It's pointless to specify L3 forwarding without specifying
             * the network we're on.
             */
            if (def->nips == 0) {
1524 1525 1526 1527
                virReportError(VIR_ERR_XML_ERROR,
                               _("%s forwarding requested, but no IP address provided for network '%s'"),
                               virNetworkForwardTypeToString(def->forwardType),
                               def->name);
1528 1529 1530
                goto error;
            }
            if (def->nForwardIfs > 1) {
1531 1532 1533
                virReportError(VIR_ERR_XML_ERROR,
                               _("multiple forwarding interfaces specified for network '%s', only one is supported"),
                               def->name);
1534 1535 1536 1537 1538 1539 1540
                goto error;
            }
            def->stp = (stp && STREQ(stp, "off")) ? 0 : 1;
            break;
        case VIR_NETWORK_FORWARD_PRIVATE:
        case VIR_NETWORK_FORWARD_VEPA:
        case VIR_NETWORK_FORWARD_PASSTHROUGH:
1541
        case VIR_NETWORK_FORWARD_HOSTDEV:
1542
            if (def->bridge) {
1543 1544 1545 1546
                virReportError(VIR_ERR_XML_ERROR,
                               _("bridge name not allowed in %s mode (network '%s')"),
                               virNetworkForwardTypeToString(def->forwardType),
                               def->name);
1547 1548 1549 1550 1551
                goto error;
            }
            /* fall through to next case */
        case VIR_NETWORK_FORWARD_BRIDGE:
            if (def->delay || stp) {
1552 1553 1554 1555
                virReportError(VIR_ERR_XML_ERROR,
                               _("bridge delay/stp options only allowed in route, nat, and isolated mode, not in %s (network '%s')"),
                               virNetworkForwardTypeToString(def->forwardType),
                               def->name);
1556 1557 1558 1559 1560 1561 1562
                goto error;
            }
            break;
        }
    }
    VIR_FREE(stp);
    ctxt->node = save;
1563 1564 1565
    return def;

 error:
1566
    VIR_FREE(stp);
1567
    virNetworkDefFree(def);
E
Eric Blake 已提交
1568
    VIR_FREE(ipNodes);
1569 1570
    VIR_FREE(portGroupNodes);
    VIR_FREE(forwardIfNodes);
1571
    VIR_FREE(forwardPfNodes);
1572 1573
    VIR_FREE(forwardDev);
    ctxt->node = save;
1574 1575 1576
    return NULL;
}

J
Jiri Denemark 已提交
1577 1578 1579
static virNetworkDefPtr
virNetworkDefParse(const char *xmlStr,
                   const char *filename)
1580
{
J
Jiri Denemark 已提交
1581
    xmlDocPtr xml;
1582
    virNetworkDefPtr def = NULL;
1583

1584
    if ((xml = virXMLParse(filename, xmlStr, _("(network_definition)")))) {
J
Jiri Denemark 已提交
1585 1586
        def = virNetworkDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1587 1588 1589 1590 1591
    }

    return def;
}

J
Jiri Denemark 已提交
1592
virNetworkDefPtr virNetworkDefParseString(const char *xmlStr)
1593
{
J
Jiri Denemark 已提交
1594 1595
    return virNetworkDefParse(xmlStr, NULL);
}
1596

J
Jiri Denemark 已提交
1597 1598 1599
virNetworkDefPtr virNetworkDefParseFile(const char *filename)
{
    return virNetworkDefParse(NULL, filename);
1600 1601 1602
}


1603
virNetworkDefPtr virNetworkDefParseNode(xmlDocPtr xml,
1604 1605 1606 1607 1608 1609
                                        xmlNodePtr root)
{
    xmlXPathContextPtr ctxt = NULL;
    virNetworkDefPtr def = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "network")) {
1610 1611 1612 1613
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <network>"),
                       root->name);
1614 1615 1616 1617 1618
        return NULL;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1619
        virReportOOMError();
1620 1621 1622 1623
        goto cleanup;
    }

    ctxt->node = root;
1624
    def = virNetworkDefParseXML(ctxt);
1625 1626 1627 1628 1629 1630

cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
static int
virNetworkDNSDefFormat(virBufferPtr buf,
                       virNetworkDNSDefPtr def)
{
    int result = 0;
    int i;

    if (def == NULL)
        goto out;

1641 1642
    virBufferAddLit(buf, "<dns>\n");
    virBufferAdjustIndent(buf, 2);
1643 1644

    for (i = 0 ; i < def->ntxtrecords ; i++) {
1645
        virBufferAsprintf(buf, "<txt name='%s' value='%s' />\n",
1646 1647 1648 1649
                              def->txtrecords[i].name,
                              def->txtrecords[i].value);
    }

1650 1651
    for (i = 0 ; i < def->nsrvrecords ; i++) {
        if (def->srvrecords[i].service && def->srvrecords[i].protocol) {
1652
            virBufferAsprintf(buf, "<srv service='%s' protocol='%s'",
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
                                  def->srvrecords[i].service,
                                  def->srvrecords[i].protocol);

            if (def->srvrecords[i].domain)
                virBufferAsprintf(buf, " domain='%s'", def->srvrecords[i].domain);
            if (def->srvrecords[i].target)
                virBufferAsprintf(buf, " target='%s'", def->srvrecords[i].target);
            if (def->srvrecords[i].port)
                virBufferAsprintf(buf, " port='%d'", def->srvrecords[i].port);
            if (def->srvrecords[i].priority)
                virBufferAsprintf(buf, " priority='%d'", def->srvrecords[i].priority);
            if (def->srvrecords[i].weight)
                virBufferAsprintf(buf, " weight='%d'", def->srvrecords[i].weight);

            virBufferAsprintf(buf, "/>\n");
        }
    }

1671 1672 1673 1674
    if (def->nhosts) {
        int ii, j;

        for (ii = 0 ; ii < def->nhosts; ii++) {
1675
            char *ip = virSocketAddrFormat(&def->hosts[ii].ip);
1676

1677 1678
            virBufferAsprintf(buf, "<host ip='%s'>\n", ip);
            virBufferAdjustIndent(buf, 2);
1679
            for (j = 0; j < def->hosts[ii].nnames; j++)
1680 1681
                virBufferAsprintf(buf, "<hostname>%s</hostname>\n",
                                  def->hosts[ii].names[j]);
1682

1683 1684
            virBufferAdjustIndent(buf, -2);
            virBufferAsprintf(buf, "</host>\n");
1685
            VIR_FREE(ip);
1686 1687
        }
    }
1688 1689
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</dns>\n");
1690 1691 1692 1693
out:
    return result;
}

1694 1695 1696 1697 1698 1699
static int
virNetworkIpDefFormat(virBufferPtr buf,
                      const virNetworkIpDefPtr def)
{
    int result = -1;

1700
    virBufferAddLit(buf, "<ip");
1701 1702

    if (def->family) {
1703
        virBufferAsprintf(buf, " family='%s'", def->family);
1704
    }
1705 1706
    if (VIR_SOCKET_ADDR_VALID(&def->address)) {
        char *addr = virSocketAddrFormat(&def->address);
1707 1708
        if (!addr)
            goto error;
1709
        virBufferAsprintf(buf, " address='%s'", addr);
1710 1711
        VIR_FREE(addr);
    }
1712 1713
    if (VIR_SOCKET_ADDR_VALID(&def->netmask)) {
        char *addr = virSocketAddrFormat(&def->netmask);
1714 1715
        if (!addr)
            goto error;
1716
        virBufferAsprintf(buf, " netmask='%s'", addr);
1717 1718 1719
        VIR_FREE(addr);
    }
    if (def->prefix > 0) {
1720
        virBufferAsprintf(buf," prefix='%u'", def->prefix);
1721 1722
    }
    virBufferAddLit(buf, ">\n");
1723
    virBufferAdjustIndent(buf, 2);
1724 1725

    if (def->tftproot) {
1726
        virBufferEscapeString(buf, "<tftp root='%s' />\n",
1727 1728 1729 1730
                              def->tftproot);
    }
    if ((def->nranges || def->nhosts)) {
        int ii;
1731 1732 1733
        virBufferAddLit(buf, "<dhcp>\n");
        virBufferAdjustIndent(buf, 2);

1734
        for (ii = 0 ; ii < def->nranges ; ii++) {
1735
            char *saddr = virSocketAddrFormat(&def->ranges[ii].start);
1736 1737
            if (!saddr)
                goto error;
1738
            char *eaddr = virSocketAddrFormat(&def->ranges[ii].end);
1739 1740 1741 1742
            if (!eaddr) {
                VIR_FREE(saddr);
                goto error;
            }
1743
            virBufferAsprintf(buf, "<range start='%s' end='%s' />\n",
1744 1745 1746 1747 1748
                              saddr, eaddr);
            VIR_FREE(saddr);
            VIR_FREE(eaddr);
        }
        for (ii = 0 ; ii < def->nhosts ; ii++) {
1749
            virBufferAddLit(buf, "<host ");
1750
            if (def->hosts[ii].mac)
1751
                virBufferAsprintf(buf, "mac='%s' ", def->hosts[ii].mac);
1752
            if (def->hosts[ii].name)
1753
                virBufferAsprintf(buf, "name='%s' ", def->hosts[ii].name);
1754 1755
            if (VIR_SOCKET_ADDR_VALID(&def->hosts[ii].ip)) {
                char *ipaddr = virSocketAddrFormat(&def->hosts[ii].ip);
1756 1757
                if (!ipaddr)
                    goto error;
1758
                virBufferAsprintf(buf, "ip='%s' ", ipaddr);
1759 1760 1761 1762 1763
                VIR_FREE(ipaddr);
            }
            virBufferAddLit(buf, "/>\n");
        }
        if (def->bootfile) {
1764
            virBufferEscapeString(buf, "<bootp file='%s' ",
1765
                                  def->bootfile);
1766 1767
            if (VIR_SOCKET_ADDR_VALID(&def->bootserver)) {
                char *ipaddr = virSocketAddrFormat(&def->bootserver);
1768 1769 1770 1771 1772 1773
                if (!ipaddr)
                    goto error;
                virBufferEscapeString(buf, "server='%s' ", ipaddr);
                VIR_FREE(ipaddr);
            }
            virBufferAddLit(buf, "/>\n");
1774

1775 1776
        }

1777 1778
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</dhcp>\n");
1779 1780
    }

1781 1782
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</ip>\n");
1783 1784 1785 1786 1787 1788

    result = 0;
error:
    return result;
}

1789
static int
1790 1791 1792
virPortGroupDefFormat(virBufferPtr buf,
                      const virPortGroupDefPtr def)
{
1793
    virBufferAsprintf(buf, "<portgroup name='%s'", def->name);
1794 1795 1796 1797
    if (def->isDefault) {
        virBufferAddLit(buf, " default='yes'");
    }
    virBufferAddLit(buf, ">\n");
1798
    virBufferAdjustIndent(buf, 2);
1799 1800
    if (virNetDevVlanFormat(&def->vlan, buf) < 0)
        return -1;
1801 1802
    if (virNetDevVPortProfileFormat(def->virtPortProfile, buf) < 0)
        return -1;
1803
    virNetDevBandwidthFormat(def->bandwidth, buf);
1804 1805
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</portgroup>\n");
1806
    return 0;
1807 1808
}

1809
char *virNetworkDefFormat(const virNetworkDefPtr def, unsigned int flags)
1810 1811 1812 1813
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    unsigned char *uuid;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1814
    int ii;
1815

1816 1817 1818 1819 1820
    virBufferAddLit(&buf, "<network");
    if (!(flags & VIR_NETWORK_XML_INACTIVE) && (def->connections > 0)) {
        virBufferAsprintf(&buf, " connections='%d'", def->connections);
    }
    virBufferAddLit(&buf, ">\n");
1821 1822
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
1823 1824 1825

    uuid = def->uuid;
    virUUIDFormat(uuid, uuidstr);
1826
    virBufferAsprintf(&buf, "<uuid>%s</uuid>\n", uuidstr);
1827 1828

    if (def->forwardType != VIR_NETWORK_FORWARD_NONE) {
1829 1830 1831
        const char *dev = NULL;
        if (!def->nForwardPfs)
            dev = virNetworkDefForwardIf(def, 0);
1832
        const char *mode = virNetworkForwardTypeToString(def->forwardType);
1833 1834

        if (!mode) {
1835 1836 1837
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown forward type %d in network '%s'"),
                           def->forwardType, def->name);
1838 1839
            goto error;
        }
1840
        virBufferAddLit(&buf, "<forward");
1841
        virBufferEscapeString(&buf, " dev='%s'", dev);
1842 1843 1844 1845 1846 1847 1848 1849
        virBufferAsprintf(&buf, " mode='%s'", mode);
        if (def->forwardType == VIR_NETWORK_FORWARD_HOSTDEV) {
            if (def->managed == 1)
                virBufferAddLit(&buf, " managed='yes'");
            else
                virBufferAddLit(&buf, " managed='no'");
        }
        virBufferAsprintf(&buf, "%s>\n",
1850
                          (def->nForwardIfs || def->nForwardPfs) ? "" : "/");
1851
        virBufferAdjustIndent(&buf, 2);
1852 1853 1854

        /* For now, hard-coded to at most 1 forwardPfs */
        if (def->nForwardPfs)
1855
            virBufferEscapeString(&buf, "<pf dev='%s'/>\n",
1856
                                  def->forwardPfs[0].dev);
1857

1858 1859
        if (def->nForwardIfs &&
            (!def->nForwardPfs || !(flags & VIR_NETWORK_XML_INACTIVE))) {
1860
            for (ii = 0; ii < def->nForwardIfs; ii++) {
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
                if (def->forwardType != VIR_NETWORK_FORWARD_HOSTDEV) {
                    virBufferEscapeString(&buf, "<interface dev='%s'",
                                          def->forwardIfs[ii].device.dev);
                    if (!(flags & VIR_NETWORK_XML_INACTIVE) &&
                        (def->forwardIfs[ii].connections > 0)) {
                        virBufferAsprintf(&buf, " connections='%d'",
                                          def->forwardIfs[ii].connections);
                    }
                    virBufferAddLit(&buf, "/>\n");
                }
                else {
                    if (def->forwardIfs[ii].type ==  VIR_NETWORK_FORWARD_HOSTDEV_DEVICE_PCI) {
                        if (virDevicePCIAddressFormat(&buf,
                                                      def->forwardIfs[ii].device.pci,
                                                      true) < 0)
                            goto error;
                    }
1878
                }
1879 1880
            }
        }
1881
        virBufferAdjustIndent(&buf, -2);
1882
        if (def->nForwardPfs || def->nForwardIfs)
1883
            virBufferAddLit(&buf, "</forward>\n");
1884 1885
    }

1886 1887 1888 1889
    if (def->forwardType == VIR_NETWORK_FORWARD_NONE ||
         def->forwardType == VIR_NETWORK_FORWARD_NAT ||
         def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {

1890
        virBufferAddLit(&buf, "<bridge");
1891 1892 1893 1894 1895 1896 1897
        if (def->bridge)
            virBufferEscapeString(&buf, " name='%s'", def->bridge);
        virBufferAsprintf(&buf, " stp='%s' delay='%ld' />\n",
                          def->stp ? "on" : "off",
                          def->delay);
    } else if (def->forwardType == VIR_NETWORK_FORWARD_BRIDGE &&
               def->bridge) {
1898
       virBufferEscapeString(&buf, "<bridge name='%s' />\n", def->bridge);
1899 1900 1901
    }


1902 1903
    if (def->mac_specified) {
        char macaddr[VIR_MAC_STRING_BUFLEN];
1904
        virMacAddrFormat(&def->mac, macaddr);
1905
        virBufferAsprintf(&buf, "<mac address='%s'/>\n", macaddr);
1906
    }
1907

1908
    if (def->domain)
1909
        virBufferAsprintf(&buf, "<domain name='%s'/>\n", def->domain);
1910

1911 1912 1913
    if (virNetworkDNSDefFormat(&buf, def->dns) < 0)
        goto error;

1914 1915
    if (virNetDevVlanFormat(&def->vlan, &buf) < 0)
        goto error;
1916
    if (virNetDevBandwidthFormat(def->bandwidth, &buf) < 0)
1917 1918
        goto error;

1919 1920 1921
    for (ii = 0; ii < def->nips; ii++) {
        if (virNetworkIpDefFormat(&buf, &def->ips[ii]) < 0)
            goto error;
1922 1923
    }

1924 1925
    if (virNetDevVPortProfileFormat(def->virtPortProfile, &buf) < 0)
        goto error;
1926 1927

    for (ii = 0; ii < def->nPortGroups; ii++)
1928 1929
        if (virPortGroupDefFormat(&buf, &def->portGroups[ii]) < 0)
            goto error;
1930

1931
    virBufferAdjustIndent(&buf, -2);
1932 1933 1934 1935 1936 1937 1938 1939
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
        goto no_memory;

    return virBufferContentAndReset(&buf);

 no_memory:
1940
    virReportOOMError();
1941
  error:
1942
    virBufferFreeAndReset(&buf);
1943 1944 1945
    return NULL;
}

1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
virPortGroupDefPtr virPortGroupFindByName(virNetworkDefPtr net,
                                          const char *portgroup)
{
    int ii;
    for (ii = 0; ii < net->nPortGroups; ii++) {
        if (portgroup) {
            if (STREQ(portgroup, net->portGroups[ii].name))
                return &net->portGroups[ii];
        } else {
            if (net->portGroups[ii].isDefault)
                return &net->portGroups[ii];
        }
    }
    return NULL;
}

1962
int virNetworkSaveXML(const char *configDir,
1963 1964
                      virNetworkDefPtr def,
                      const char *xml)
1965
{
1966
    char *configFile = NULL;
1967
    int ret = -1;
1968

1969
    if ((configFile = virNetworkConfigFile(configDir, def->name)) == NULL)
1970 1971
        goto cleanup;

1972 1973
    if (virFileMakePath(configDir) < 0) {
        virReportSystemError(errno,
1974 1975
                             _("cannot create config directory '%s'"),
                             configDir);
1976 1977 1978
        goto cleanup;
    }

1979
    ret = virXMLSaveFile(configFile, def->name, "net-edit", xml);
1980 1981

 cleanup:
1982 1983 1984 1985
    VIR_FREE(configFile);
    return ret;
}

1986
int virNetworkSaveConfig(const char *configDir,
1987 1988 1989 1990 1991
                         virNetworkDefPtr def)
{
    int ret = -1;
    char *xml;

1992
    if (!(xml = virNetworkDefFormat(def, VIR_NETWORK_XML_INACTIVE)))
1993 1994
        goto cleanup;

1995
    if (virNetworkSaveXML(configDir, def, xml))
1996 1997 1998 1999 2000
        goto cleanup;

    ret = 0;
cleanup:
    VIR_FREE(xml);
2001 2002 2003
    return ret;
}

2004

2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
int virNetworkSaveStatus(const char *statusDir,
                         virNetworkObjPtr network)
{
    int ret = -1;
    char *xml;

    if (!(xml = virNetworkDefFormat(network->def, 0)))
        goto cleanup;

    if (virNetworkSaveXML(statusDir, network->def, xml))
        goto cleanup;

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

2023
virNetworkObjPtr virNetworkLoadConfig(virNetworkObjListPtr nets,
2024 2025
                                      const char *configDir,
                                      const char *autostartDir,
2026
                                      const char *name)
2027 2028 2029 2030 2031 2032
{
    char *configFile = NULL, *autostartLink = NULL;
    virNetworkDefPtr def = NULL;
    virNetworkObjPtr net;
    int autostart;

2033
    if ((configFile = virNetworkConfigFile(configDir, name)) == NULL)
2034
        goto error;
2035
    if ((autostartLink = virNetworkConfigFile(autostartDir, name)) == NULL)
2036 2037 2038 2039 2040
        goto error;

    if ((autostart = virFileLinkPointsTo(autostartLink, configFile)) < 0)
        goto error;

2041
    if (!(def = virNetworkDefParseFile(configFile)))
2042 2043
        goto error;

2044
    if (!STREQ(name, def->name)) {
2045 2046 2047 2048
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Network config filename '%s'"
                         " does not match network name '%s'"),
                       configFile, def->name);
2049 2050 2051
        goto error;
    }

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
    if (def->forwardType == VIR_NETWORK_FORWARD_NONE ||
        def->forwardType == VIR_NETWORK_FORWARD_NAT ||
        def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {

        /* Generate a bridge if none is specified, but don't check for collisions
         * if a bridge is hardcoded, so the network is at least defined.
         */
        if (virNetworkSetBridgeName(nets, def, 0))
            goto error;
    }
2062

2063
    if (!(net = virNetworkAssignDef(nets, def, false)))
2064 2065 2066
        goto error;

    net->autostart = autostart;
2067
    net->persistent = 1;
2068

2069 2070 2071
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);

2072 2073 2074 2075 2076 2077 2078 2079 2080
    return net;

error:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    virNetworkDefFree(def);
    return NULL;
}

2081
int virNetworkLoadAllConfigs(virNetworkObjListPtr nets,
2082 2083 2084 2085 2086 2087 2088 2089 2090
                             const char *configDir,
                             const char *autostartDir)
{
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(configDir))) {
        if (errno == ENOENT)
            return 0;
2091
        virReportSystemError(errno,
2092 2093
                             _("Failed to open dir '%s'"),
                             configDir);
2094 2095 2096 2097
        return -1;
    }

    while ((entry = readdir(dir))) {
2098 2099
        virNetworkObjPtr net;

2100 2101 2102
        if (entry->d_name[0] == '.')
            continue;

2103
        if (!virFileStripSuffix(entry->d_name, ".xml"))
2104 2105 2106 2107
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
2108
        net = virNetworkLoadConfig(nets,
2109 2110 2111 2112 2113
                                   configDir,
                                   autostartDir,
                                   entry->d_name);
        if (net)
            virNetworkObjUnlock(net);
2114 2115 2116 2117 2118 2119 2120
    }

    closedir(dir);

    return 0;
}

2121
int virNetworkDeleteConfig(const char *configDir,
2122
                           const char *autostartDir,
2123 2124
                           virNetworkObjPtr net)
{
2125 2126
    char *configFile = NULL;
    char *autostartLink = NULL;
R
Ryota Ozaki 已提交
2127
    int ret = -1;
2128

2129
    if ((configFile = virNetworkConfigFile(configDir, net->def->name)) == NULL)
2130
        goto error;
2131
    if ((autostartLink = virNetworkConfigFile(autostartDir, net->def->name)) == NULL)
2132
        goto error;
2133 2134

    /* Not fatal if this doesn't work */
2135
    unlink(autostartLink);
2136

2137
    if (unlink(configFile) < 0) {
2138
        virReportSystemError(errno,
2139
                             _("cannot remove config file '%s'"),
2140 2141
                             configFile);
        goto error;
2142 2143
    }

R
Ryota Ozaki 已提交
2144
    ret = 0;
2145 2146 2147 2148

error:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
R
Ryota Ozaki 已提交
2149
    return ret;
2150 2151
}

2152
char *virNetworkConfigFile(const char *dir,
2153 2154 2155 2156 2157
                           const char *name)
{
    char *ret = NULL;

    if (virAsprintf(&ret, "%s/%s.xml", dir, name) < 0) {
2158
        virReportOOMError();
2159 2160 2161 2162
        return NULL;
    }

    return ret;
2163
}
D
Daniel P. Berrange 已提交
2164

2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
int virNetworkBridgeInUse(const virNetworkObjListPtr nets,
                          const char *bridge,
                          const char *skipname)
{
    unsigned int i;
    unsigned int ret = 0;

    for (i = 0 ; i < nets->count ; i++) {
        virNetworkObjLock(nets->objs[i]);
        if (nets->objs[i]->def->bridge &&
            STREQ(nets->objs[i]->def->bridge, bridge) &&
            !(skipname && STREQ(nets->objs[i]->def->name, skipname)))
                ret = 1;
        virNetworkObjUnlock(nets->objs[i]);
    }

    return ret;
}

2184
char *virNetworkAllocateBridge(const virNetworkObjListPtr nets,
2185
                               const char *template)
2186 2187 2188 2189 2190
{

    int id = 0;
    char *newname;

2191 2192 2193
    if (!template)
        template = "virbr%d";

2194
    do {
2195 2196 2197 2198 2199
        if (virAsprintf(&newname, template, id) < 0) {
            virReportOOMError();
            return NULL;
        }
        if (!virNetworkBridgeInUse(nets, newname, NULL)) {
2200 2201
            return newname;
        }
2202
        VIR_FREE(newname);
2203 2204

        id++;
2205
    } while (id <= MAX_BRIDGE_ID);
2206

2207 2208 2209
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Bridge generation exceeded max id %d"),
                   MAX_BRIDGE_ID);
2210 2211 2212
    return NULL;
}

2213
int virNetworkSetBridgeName(const virNetworkObjListPtr nets,
2214 2215
                            virNetworkDefPtr def,
                            int check_collision) {
2216 2217 2218

    int ret = -1;

2219
    if (def->bridge && !strstr(def->bridge, "%d")) {
2220 2221 2222 2223 2224
        /* We may want to skip collision detection in this case (ex. when
         * loading configs at daemon startup, so the network is at least
         * defined. */
        if (check_collision &&
            virNetworkBridgeInUse(nets, def->bridge, def->name)) {
2225 2226 2227
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("bridge name '%s' already in use."),
                           def->bridge);
2228 2229 2230 2231
            goto error;
        }
    } else {
        /* Allocate a bridge name */
2232
        if (!(def->bridge = virNetworkAllocateBridge(nets, def->bridge)))
2233 2234 2235 2236 2237 2238 2239
            goto error;
    }

    ret = 0;
error:
    return ret;
}
2240

2241

2242 2243 2244 2245 2246 2247
void virNetworkSetBridgeMacAddr(virNetworkDefPtr def)
{
    if (!def->mac_specified) {
        /* if the bridge doesn't have a mac address explicitly defined,
         * autogenerate a random one.
         */
2248
        virMacAddrGenerate((unsigned char[]){ 0x52, 0x54, 0 },
2249
                           &def->mac);
2250 2251 2252 2253
        def->mac_specified = true;
    }
}

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
/* NetworkObj backend of the virNetworkUpdate API */

static void
virNetworkDefUpdateNoSupport(virNetworkDefPtr def, const char *section)
{
    virReportError(VIR_ERR_NO_SUPPORT,
                   _("can't update '%s' section of network '%s'"),
                   section, def->name);
}

static int
virNetworkDefUpdateCheckElementName(virNetworkDefPtr def,
                                    xmlNodePtr node,
                                    const char *section)
{
    if (!xmlStrEqual(node->name, BAD_CAST section)) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected element <%s>, expecting <%s>, "
                         "while updating network '%s'"),
                       node->name, section, def->name);
        return -1;
    }
    return 0;
}

static int
virNetworkDefUpdateBridge(virNetworkDefPtr def,
                          unsigned int command ATTRIBUTE_UNUSED,
                          int parentIndex ATTRIBUTE_UNUSED,
                          xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                          /* virNetworkUpdateFlags */
                          unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "bridge");
    return -1;
}

static int
virNetworkDefUpdateDomain(virNetworkDefPtr def,
                          unsigned int command ATTRIBUTE_UNUSED,
                          int parentIndex ATTRIBUTE_UNUSED,
                          xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                          /* virNetworkUpdateFlags */
                          unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "domain");
    return -1;
}

static int
virNetworkDefUpdateIP(virNetworkDefPtr def,
                      unsigned int command ATTRIBUTE_UNUSED,
                      int parentIndex ATTRIBUTE_UNUSED,
                      xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                      /* virNetworkUpdateFlags */
                      unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "ip");
    return -1;
}

2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
static virNetworkIpDefPtr
virNetworkIpDefByIndex(virNetworkDefPtr def, int parentIndex)
{
    virNetworkIpDefPtr ipdef = NULL;
    int ii;

    /* first find which ip element's dhcp host list to work on */
    if (parentIndex >= 0) {
        ipdef = virNetworkDefGetIpByIndex(def, AF_UNSPEC, parentIndex);
        if (!(ipdef &&
              VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->address, AF_INET))) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("couldn't update dhcp host entry - "
                             "no <ip family='ipv4'> "
                             "element found at index %d in network '%s'"),
                           parentIndex, def->name);
        }
        return ipdef;
    }

    /* -1 means "find the most appropriate", which in this case
     * means the one and only <ip> that has <dhcp> element
     */
    for (ii = 0;
         (ipdef = virNetworkDefGetIpByIndex(def, AF_UNSPEC, ii));
         ii++) {
        if (VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->address, AF_INET) &&
            (ipdef->nranges || ipdef->nhosts)) {
            break;
        }
    }
    if (!ipdef)
        ipdef = virNetworkDefGetIpByIndex(def, AF_INET, 0);
    if (!ipdef) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("couldn't update dhcp host entry - "
                         "no <ip family='ipv4'> "
                         "element found in network '%s'"), def->name);
    }
    return ipdef;
}

2357 2358
static int
virNetworkDefUpdateIPDHCPHost(virNetworkDefPtr def,
2359 2360 2361
                              unsigned int command,
                              int parentIndex,
                              xmlXPathContextPtr ctxt,
2362 2363 2364
                              /* virNetworkUpdateFlags */
                              unsigned int fflags ATTRIBUTE_UNUSED)
{
2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
    int ii, ret = -1;
    virNetworkIpDefPtr ipdef = virNetworkIpDefByIndex(def, parentIndex);
    virNetworkDHCPHostDef host;

    memset(&host, 0, sizeof(host));

    if (virNetworkDefUpdateCheckElementName(def, ctxt->node, "host") < 0)
        goto cleanup;

    /* ipdef is the ip element that needs its host array updated */
    if (!ipdef)
        goto cleanup;

    /* parse the xml into a virNetworkDHCPHostDef */
    if (command == VIR_NETWORK_UPDATE_COMMAND_MODIFY) {

        if (virNetworkDHCPHostDefParse(def->name, ctxt->node, &host, false) < 0)
            goto cleanup;

        /* search for the entry with this (mac|name),
         * and update the IP+(mac|name) */
        for (ii = 0; ii < ipdef->nhosts; ii++) {
            if ((host.mac &&
                 !virMacAddrCompare(host.mac, ipdef->hosts[ii].mac)) ||
                (host.name &&
                 STREQ_NULLABLE(host.name, ipdef->hosts[ii].name))) {
                break;
            }
        }

        if (ii == ipdef->nhosts) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("couldn't locate an existing dhcp host entry with "
                             "\"mac='%s'\" in network '%s'"),
                           host.mac, def->name);
            goto cleanup;
        }

        /* clear the existing hosts entry, move the new one in its place,
         * then clear out the extra copy to get rid of the duplicate pointers
         * to its data (mac and name strings).
         */
        virNetworkDHCPHostDefClear(&ipdef->hosts[ii]);
        ipdef->hosts[ii] = host;
        memset(&host, 0, sizeof(host));

    } else if ((command == VIR_NETWORK_UPDATE_COMMAND_ADD_FIRST) ||
               (command == VIR_NETWORK_UPDATE_COMMAND_ADD_LAST)) {

        if (virNetworkDHCPHostDefParse(def->name, ctxt->node, &host, true) < 0)
            goto cleanup;

        /* log error if an entry with same name/address/ip already exists */
        for (ii = 0; ii < ipdef->nhosts; ii++) {
            if ((host.mac &&
                 !virMacAddrCompare(host.mac, ipdef->hosts[ii].mac)) ||
                (host.name &&
                 STREQ_NULLABLE(host.name, ipdef->hosts[ii].name)) ||
                (VIR_SOCKET_ADDR_VALID(&host.ip) &&
                 virSocketAddrEqual(&host.ip, &ipdef->hosts[ii].ip))) {
                char *ip = virSocketAddrFormat(&host.ip);

                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("there is an existing dhcp host entry in "
                                 "network '%s' that matches "
                                 "\"<host mac='%s' name='%s' ip='%s'/>\""),
                               def->name, host.mac, host.name,
                               ip ? ip : "unknown");
                VIR_FREE(ip);
                goto cleanup;
            }
        }
        /* add to beginning/end of list */
        if (VIR_REALLOC_N(ipdef->hosts, ipdef->nhosts +1) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        if (command == VIR_NETWORK_UPDATE_COMMAND_ADD_LAST) {

            ipdef->hosts[ipdef->nhosts] = host;
            ipdef->nhosts++;
            memset(&host, 0, sizeof(host));

        } else { /* implied (command == VIR_NETWORK_UPDATE_COMMAND_ADD_FIRST) */

            memmove(ipdef->hosts + 1, ipdef->hosts,
                    sizeof(ipdef->hosts) * ipdef->nhosts);
            ipdef->hosts[0] = host;
            ipdef->nhosts++;
            memset(&host, 0, sizeof(host));
        }

    } else if (command == VIR_NETWORK_UPDATE_COMMAND_DELETE) {

        if (virNetworkDHCPHostDefParse(def->name, ctxt->node, &host, false) < 0)
            goto cleanup;

        /* find matching entry - all specified attributes must match */
        for (ii = 0; ii < ipdef->nhosts; ii++) {
            if ((!host.mac ||
                 !virMacAddrCompare(host.mac, ipdef->hosts[ii].mac)) &&
                (!host.name ||
                 STREQ_NULLABLE(host.name, ipdef->hosts[ii].name)) &&
                (!VIR_SOCKET_ADDR_VALID(&host.ip) ||
                 virSocketAddrEqual(&host.ip, &ipdef->hosts[ii].ip))) {
                break;
            }
        }
        if (ii == ipdef->nhosts) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("couldn't locate a matching dhcp host entry "
                             "in network '%s'"), def->name);
            goto cleanup;
        }

        /* remove it */
        virNetworkDHCPHostDefClear(&ipdef->hosts[ii]);
        memmove(ipdef->hosts + ii, ipdef->hosts + ii + 1,
                sizeof(ipdef->hosts) * ipdef->nhosts - ii - 1);
        ipdef->nhosts--;
        ignore_value(VIR_REALLOC_N(ipdef->hosts, ipdef->nhosts));
    }

    ret = 0;
cleanup:
    virNetworkDHCPHostDefClear(&host);
    return ret;
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727
}

static int
virNetworkDefUpdateIPDHCPRange(virNetworkDefPtr def,
                               unsigned int command ATTRIBUTE_UNUSED,
                               int parentIndex ATTRIBUTE_UNUSED,
                               xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                               /* virNetworkUpdateFlags */
                               unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "ip dhcp range");
    return -1;
}

static int
virNetworkDefUpdateForward(virNetworkDefPtr def,
                           unsigned int command ATTRIBUTE_UNUSED,
                           int parentIndex ATTRIBUTE_UNUSED,
                           xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                           /* virNetworkUpdateFlags */
                           unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "forward");
    return -1;
}

static int
virNetworkDefUpdateForwardInterface(virNetworkDefPtr def,
                                    unsigned int command ATTRIBUTE_UNUSED,
                                    int parentIndex ATTRIBUTE_UNUSED,
                                    xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                                    /* virNetworkUpdateFlags */
                                    unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "forward interface");
    return -1;
}

static int
virNetworkDefUpdateForwardPF(virNetworkDefPtr def,
                             unsigned int command ATTRIBUTE_UNUSED,
                             int parentIndex ATTRIBUTE_UNUSED,
                             xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                             /* virNetworkUpdateFlags */
                             unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "forward pf");
    return -1;
}

static int
virNetworkDefUpdatePortgroup(virNetworkDefPtr def,
                             unsigned int command ATTRIBUTE_UNUSED,
                             int parentIndex ATTRIBUTE_UNUSED,
                             xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                             /* virNetworkUpdateFlags */
                             unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "portgroup");
    return -1;
}

static int
virNetworkDefUpdateDNSHost(virNetworkDefPtr def,
                           unsigned int command ATTRIBUTE_UNUSED,
                           int parentIndex ATTRIBUTE_UNUSED,
                           xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                           /* virNetworkUpdateFlags */
                           unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "dns host");
    return -1;
}

static int
virNetworkDefUpdateDNSTxt(virNetworkDefPtr def,
                          unsigned int command ATTRIBUTE_UNUSED,
                          int parentIndex ATTRIBUTE_UNUSED,
                          xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                          /* virNetworkUpdateFlags */
                          unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "dns txt");
    return -1;
}

static int
virNetworkDefUpdateDNSSrv(virNetworkDefPtr def,
                          unsigned int command ATTRIBUTE_UNUSED,
                          int parentIndex ATTRIBUTE_UNUSED,
                          xmlXPathContextPtr ctxt ATTRIBUTE_UNUSED,
                          /* virNetworkUpdateFlags */
                          unsigned int fflags ATTRIBUTE_UNUSED)
{
    virNetworkDefUpdateNoSupport(def, "dns txt");
    return -1;
}

static int
virNetworkDefUpdateSection(virNetworkDefPtr def,
                           unsigned int command, /* virNetworkUpdateCommand */
                           unsigned int section, /* virNetworkUpdateSection */
                           int parentIndex,
                           const char *xml,
                           unsigned int flags)  /* virNetworkUpdateFlags */
{
    int ret = -1;
    xmlDocPtr doc;
    xmlXPathContextPtr ctxt = NULL;

    if (!(doc = virXMLParseStringCtxt(xml, _("network_update_xml"), &ctxt)))
        goto cleanup;

    switch (section) {
    case VIR_NETWORK_SECTION_BRIDGE:
       ret = virNetworkDefUpdateBridge(def, command, parentIndex, ctxt, flags);
        break;

    case VIR_NETWORK_SECTION_DOMAIN:
        ret = virNetworkDefUpdateDomain(def, command, parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_IP:
        ret = virNetworkDefUpdateIP(def, command, parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_IP_DHCP_HOST:
        ret = virNetworkDefUpdateIPDHCPHost(def, command,
                                            parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_IP_DHCP_RANGE:
        ret = virNetworkDefUpdateIPDHCPRange(def, command,
                                             parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_FORWARD:
        ret = virNetworkDefUpdateForward(def, command,
                                         parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_FORWARD_INTERFACE:
        ret = virNetworkDefUpdateForwardInterface(def, command,
                                                  parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_FORWARD_PF:
        ret = virNetworkDefUpdateForwardPF(def, command,
                                           parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_PORTGROUP:
        ret = virNetworkDefUpdatePortgroup(def, command,
                                           parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_DNS_HOST:
        ret = virNetworkDefUpdateDNSHost(def, command,
                                         parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_DNS_TXT:
        ret = virNetworkDefUpdateDNSTxt(def, command, parentIndex, ctxt, flags);
        break;
    case VIR_NETWORK_SECTION_DNS_SRV:
        ret = virNetworkDefUpdateDNSSrv(def, command, parentIndex, ctxt, flags);
        break;
    default:
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("can't update unrecognized section of network"));
        break;
    }

cleanup:
    xmlFreeDoc(doc);
    xmlXPathFreeContext(ctxt);
    return ret;
}

/*
 * virNetworkObjUpdate:
 *
 * Apply the supplied update to the given virNetworkObj. Except for
 * @network pointing to an actual network object rather than the
 * opaque virNetworkPtr, parameters are identical to the public API
 * virNetworkUpdate.
 *
 * The original virNetworkDefs are copied, and all modifications made
 * to these copies. The originals are replaced with the copies only
 * after success has been guaranteed.
 *
 * Returns: -1 on error, 0 on success.
 */
int
virNetworkObjUpdate(virNetworkObjPtr network,
                    unsigned int command, /* virNetworkUpdateCommand */
                    unsigned int section, /* virNetworkUpdateSection */
                    int parentIndex,
                    const char *xml,
                    unsigned int flags)  /* virNetworkUpdateFlags */
{
    int ret = -1;
    virNetworkDefPtr def = NULL;

    /* normalize config data, and check for common invalid requests. */
    if (virNetworkConfigChangeSetup(network, flags) < 0)
       goto cleanup;

    if (flags & VIR_NETWORK_UPDATE_AFFECT_LIVE) {
        /* work on a copy of the def */
        if (!(def = virNetworkDefCopy(network->def, 0)))
            goto cleanup;
        if (virNetworkDefUpdateSection(def, command, section,
                                       parentIndex, xml, flags) < 0) {
            goto cleanup;
        }
        /* successfully modified copy, now replace original */
        virNetworkDefFree(network->def);
        network->def = def;
        def = NULL;
    }

    if (flags & VIR_NETWORK_UPDATE_AFFECT_CONFIG) {
        /* work on a copy of the def */
        if (!(def = virNetworkDefCopy(virNetworkObjGetPersistentDef(network),
                                      VIR_NETWORK_XML_INACTIVE))) {
            goto cleanup;
        }
        if (virNetworkDefUpdateSection(def, command, section,
                                       parentIndex, xml, flags) < 0) {
            goto cleanup;
        }
        /* successfully modified copy, now replace original */
        if (virNetworkObjReplacePersistentDef(network, def) < 0)
           goto cleanup;
        def = NULL;
    }

    ret = 0;
cleanup:
    virNetworkDefFree(def);
    return ret;
}

2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753
/*
 * virNetworkObjIsDuplicate:
 * @doms : virNetworkObjListPtr to search
 * @def  : virNetworkDefPtr definition of network to lookup
 * @check_active: If true, ensure that network is not active
 *
 * Returns: -1 on error
 *          0 if network is new
 *          1 if network is a duplicate
 */
int
virNetworkObjIsDuplicate(virNetworkObjListPtr doms,
                         virNetworkDefPtr def,
                         unsigned int check_active)
{
    int ret = -1;
    int dupVM = 0;
    virNetworkObjPtr vm = NULL;

    /* See if a VM with matching UUID already exists */
    vm = virNetworkFindByUUID(doms, def->uuid);
    if (vm) {
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
2754 2755 2756
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("network '%s' is already defined with uuid %s"),
                           vm->def->name, uuidstr);
2757 2758 2759 2760 2761 2762
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if VM is already active, refuse it */
            if (virNetworkObjIsActive(vm)) {
2763 2764 2765
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("network is already active as '%s'"),
                               vm->def->name);
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
                goto cleanup;
            }
        }

        dupVM = 1;
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        vm = virNetworkFindByName(doms, def->name);
        if (vm) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
2777 2778 2779
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("network '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
            goto cleanup;
        }
    }

    ret = dupVM;
cleanup:
    if (vm)
        virNetworkObjUnlock(vm);
    return ret;
}


2792 2793
void virNetworkObjLock(virNetworkObjPtr obj)
{
2794
    virMutexLock(&obj->lock);
2795 2796 2797 2798
}

void virNetworkObjUnlock(virNetworkObjPtr obj)
{
2799
    virMutexUnlock(&obj->lock);
D
Daniel P. Berrange 已提交
2800
}
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891

#define MATCH(FLAG) (flags & (FLAG))
static bool
virNetworkMatch (virNetworkObjPtr netobj,
                 unsigned int flags)
{
    /* filter by active state */
    if (MATCH(VIR_CONNECT_LIST_NETWORKS_FILTERS_ACTIVE) &&
        !((MATCH(VIR_CONNECT_LIST_NETWORKS_ACTIVE) &&
           virNetworkObjIsActive(netobj)) ||
          (MATCH(VIR_CONNECT_LIST_NETWORKS_INACTIVE) &&
           !virNetworkObjIsActive(netobj))))
        return false;

    /* filter by persistence */
    if (MATCH(VIR_CONNECT_LIST_NETWORKS_FILTERS_PERSISTENT) &&
        !((MATCH(VIR_CONNECT_LIST_NETWORKS_PERSISTENT) &&
           netobj->persistent) ||
          (MATCH(VIR_CONNECT_LIST_NETWORKS_TRANSIENT) &&
           !netobj->persistent)))
        return false;

    /* filter by autostart option */
    if (MATCH(VIR_CONNECT_LIST_NETWORKS_FILTERS_AUTOSTART) &&
        !((MATCH(VIR_CONNECT_LIST_NETWORKS_AUTOSTART) &&
           netobj->autostart) ||
          (MATCH(VIR_CONNECT_LIST_NETWORKS_NO_AUTOSTART) &&
           !netobj->autostart)))
        return false;

    return true;
}
#undef MATCH

int
virNetworkList(virConnectPtr conn,
               virNetworkObjList netobjs,
               virNetworkPtr **nets,
               unsigned int flags)
{
    virNetworkPtr *tmp_nets = NULL;
    virNetworkPtr net = NULL;
    int nnets = 0;
    int ret = -1;
    int i;

    if (nets) {
        if (VIR_ALLOC_N(tmp_nets, netobjs.count + 1) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

    for (i = 0; i < netobjs.count; i++) {
        virNetworkObjPtr netobj = netobjs.objs[i];
        virNetworkObjLock(netobj);
        if (virNetworkMatch(netobj, flags)) {
            if (nets) {
                if (!(net = virGetNetwork(conn,
                                          netobj->def->name,
                                          netobj->def->uuid))) {
                    virNetworkObjUnlock(netobj);
                    goto cleanup;
                }
                tmp_nets[nnets] = net;
            }
            nnets++;
        }
        virNetworkObjUnlock(netobj);
    }

    if (tmp_nets) {
        /* trim the array to the final size */
        ignore_value(VIR_REALLOC_N(tmp_nets, nnets + 1));
        *nets = tmp_nets;
        tmp_nets = NULL;
    }

    ret = nnets;

cleanup:
    if (tmp_nets) {
        for (i = 0; i < nnets; i++) {
            if (tmp_nets[i])
                virNetworkFree(tmp_nets[i]);
        }
    }

    VIR_FREE(tmp_nets);
    return ret;
}