network_conf.c 52.0 KB
Newer Older
1 2 3
/*
 * network_conf.c: network XML handling
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2006-2011 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

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
#include "network.h"
38 39 40 41 42
#include "memory.h"
#include "xml.h"
#include "uuid.h"
#include "util.h"
#include "buf.h"
43
#include "c-ctype.h"
E
Eric Blake 已提交
44
#include "virfile.h"
45

46
#define MAX_BRIDGE_ID 256
47 48
#define VIR_FROM_THIS VIR_FROM_NETWORK

49 50 51 52
VIR_ENUM_DECL(virNetworkForward)

VIR_ENUM_IMPL(virNetworkForward,
              VIR_NETWORK_FORWARD_LAST,
53
              "none", "nat", "route", "bridge", "private", "vepa", "passthrough" )
54

55
#define virNetworkReportError(code, ...)                                \
56
    virReportErrorHelper(VIR_FROM_NETWORK, code, __FILE__,              \
57
                         __FUNCTION__, __LINE__, __VA_ARGS__)
58

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

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

    return NULL;
}

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

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

    return NULL;
}


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

static void
virNetworkForwardIfDefClear(virNetworkForwardIfDefPtr def)
{
    VIR_FREE(def->dev);
}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
static void virNetworkIpDefClear(virNetworkIpDefPtr def)
{
    int ii;

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

    for (ii = 0 ; ii < def->nhosts && def->hosts ; ii++) {
        VIR_FREE(def->hosts[ii].mac);
        VIR_FREE(def->hosts[ii].name);
    }

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

122 123 124 125 126 127 128 129 130
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);
            }
        }
131
        VIR_FREE(def->txtrecords);
132 133 134 135 136 137 138
        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);
            }
        }
139
        VIR_FREE(def->hosts);
140 141 142 143
        VIR_FREE(def);
    }
}

144 145
void virNetworkDefFree(virNetworkDefPtr def)
{
146
    int ii;
147 148 149 150 151 152

    if (!def)
        return;

    VIR_FREE(def->name);
    VIR_FREE(def->bridge);
153
    VIR_FREE(def->domain);
154

155 156 157 158 159
    for (ii = 0 ; ii < def->nForwardIfs && def->forwardIfs ; ii++) {
        virNetworkForwardIfDefClear(&def->forwardIfs[ii]);
    }
    VIR_FREE(def->forwardIfs);

160 161
    for (ii = 0 ; ii < def->nips && def->ips ; ii++) {
        virNetworkIpDefClear(&def->ips[ii]);
162
    }
163
    VIR_FREE(def->ips);
164

165 166 167 168 169
    for (ii = 0; ii < def->nPortGroups && def->portGroups; ii++) {
        virPortGroupDefClear(&def->portGroups[ii]);
    }
    VIR_FREE(def->portGroups);

170 171
    virNetworkDNSDefFree(def->dns);

172 173
    VIR_FREE(def->virtPortProfile);

174 175
    virBandwidthDefFree(def->bandwidth);

176 177 178 179 180 181 182 183 184 185 186
    VIR_FREE(def);
}

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

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

187 188
    virMutexDestroy(&net->lock);

189 190 191
    VIR_FREE(net);
}

192 193 194 195 196 197 198 199 200 201 202
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;
}

203
virNetworkObjPtr virNetworkAssignDef(virNetworkObjListPtr nets,
204 205 206 207
                                     const virNetworkDefPtr def)
{
    virNetworkObjPtr network;

208
    if ((network = virNetworkFindByName(nets, def->name))) {
D
Daniel P. Berrange 已提交
209
        if (!virNetworkObjIsActive(network)) {
210 211 212
            virNetworkDefFree(network->def);
            network->def = def;
        } else {
213
            virNetworkDefFree(network->newDef);
214 215 216 217 218 219 220
            network->newDef = def;
        }

        return network;
    }

    if (VIR_ALLOC(network) < 0) {
221
        virReportOOMError();
222 223
        return NULL;
    }
224
    if (virMutexInit(&network->lock) < 0) {
225
        virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
226 227 228 229
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(network);
        return NULL;
    }
230
    virNetworkObjLock(network);
231 232
    network->def = def;

233
    if (VIR_REALLOC_N(nets->objs, nets->count + 1) < 0) {
234
        virReportOOMError();
235 236 237 238 239 240
        VIR_FREE(network);
        return NULL;
    }

    nets->objs[nets->count] = network;
    nets->count++;
241 242 243 244 245

    return network;

}

246
void virNetworkRemoveInactive(virNetworkObjListPtr nets,
247 248
                              const virNetworkObjPtr net)
{
249
    unsigned int i;
250

251
    virNetworkObjUnlock(net);
252
    for (i = 0 ; i < nets->count ; i++) {
253
        virNetworkObjLock(nets->objs[i]);
254
        if (nets->objs[i] == net) {
255
            virNetworkObjUnlock(nets->objs[i]);
256
            virNetworkObjFree(nets->objs[i]);
257

258 259 260
            if (i < (nets->count - 1))
                memmove(nets->objs + i, nets->objs + i + 1,
                        sizeof(*(nets->objs)) * (nets->count - (i + 1)));
261

262 263 264 265 266 267 268
            if (VIR_REALLOC_N(nets->objs, nets->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            nets->count--;

            break;
        }
269
        virNetworkObjUnlock(nets->objs[i]);
270
    }
271 272
}

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
/* 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++) {
        if (VIR_SOCKET_IS_FAMILY(&def->ips[ii].address, family)
            && (n-- <= 0)) {
            return &def->ips[ii];
        }
    }
    /* failed to find enough of the right family */
    return NULL;
}

L
Laine Stump 已提交
298 299 300
/* return number of 1 bits in netmask for the network's ipAddress,
 * or -1 on error
 */
301
int virNetworkIpDefPrefix(const virNetworkIpDefPtr def)
L
Laine Stump 已提交
302
{
303 304 305
    if (def->prefix > 0) {
        return def->prefix;
    } else if (VIR_SOCKET_HAS_ADDR(&def->netmask)) {
L
Laine Stump 已提交
306
        return virSocketGetNumNetmaskBits(&def->netmask);
307
    } else if (VIR_SOCKET_IS_FAMILY(&def->address, AF_INET)) {
L
Laine Stump 已提交
308 309 310 311 312 313
        /* 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
314
            = ntohl(def->address.data.inet4.sin_addr.s_addr) >> 24;
L
Laine Stump 已提交
315 316 317 318 319 320 321 322 323 324 325
        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;
326 327
    } else if (VIR_SOCKET_IS_FAMILY(&def->address, AF_INET6)) {
        return 64;
L
Laine Stump 已提交
328 329 330 331 332 333 334 335
    }
    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)
 */
336 337
int virNetworkIpDefNetmask(const virNetworkIpDefPtr def,
                           virSocketAddrPtr netmask)
L
Laine Stump 已提交
338 339 340 341 342 343
{
    if (VIR_SOCKET_IS_FAMILY(&def->netmask, AF_INET)) {
        *netmask = def->netmask;
        return 0;
    }

344 345
    return virSocketAddrPrefixToNetmask(virNetworkIpDefPrefix(def), netmask,
                                        VIR_SOCKET_FAMILY(&def->address));
L
Laine Stump 已提交
346 347
}

348 349

static int
350 351
virNetworkDHCPRangeDefParseXML(const char *networkName,
                               virNetworkIpDefPtr def,
352 353
                               xmlNodePtr node)
{
354 355 356 357 358

    xmlNodePtr cur;

    cur = node->children;
    while (cur != NULL) {
359 360
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "range")) {
361 362 363
            char *start, *end;
            virSocketAddr saddr, eaddr;
            int range;
364

365
            if (!(start = virXMLPropString(cur, "start"))) {
366 367 368
                cur = cur->next;
                continue;
            }
369 370
            if (!(end = virXMLPropString(cur, "end"))) {
                VIR_FREE(start);
371
                cur = cur->next;
372 373 374
                continue;
            }

375
            if (virSocketParseAddr(start, &saddr, AF_UNSPEC) < 0) {
376 377
                VIR_FREE(start);
                VIR_FREE(end);
378
                return -1;
379
            }
380
            if (virSocketParseAddr(end, &eaddr, AF_UNSPEC) < 0) {
381 382
                VIR_FREE(start);
                VIR_FREE(end);
383
                return -1;
384 385 386 387
            }

            range = virSocketGetRange(&saddr, &eaddr);
            if (range < 0) {
388
                virNetworkReportError(VIR_ERR_XML_ERROR,
389 390
                                      _("Invalid dhcp range '%s' to '%s' in network '%s'"),
                                      start, end, networkName);
391 392
                VIR_FREE(start);
                VIR_FREE(end);
393
                return -1;
394
            }
E
Eric Blake 已提交
395 396
            VIR_FREE(start);
            VIR_FREE(end);
397

398
            if (VIR_REALLOC_N(def->ranges, def->nranges + 1) < 0) {
399
                virReportOOMError();
400 401
                return -1;
            }
402 403
            def->ranges[def->nranges].start = saddr;
            def->ranges[def->nranges].end = eaddr;
404 405 406
            def->nranges++;
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {
407
            char *mac, *name, *ip;
408
            unsigned char addr[6];
409
            virSocketAddr inaddr;
410

411
            mac = virXMLPropString(cur, "mac");
412
            if ((mac != NULL) &&
413
                (virParseMacAddr(mac, &addr[0]) != 0)) {
414
                virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
415 416
                                      _("Cannot parse MAC address '%s' in network '%s'"),
                                      mac, networkName);
417 418
                VIR_FREE(mac);
            }
419
            name = virXMLPropString(cur, "name");
420
            if ((name != NULL) && (!c_isalpha(name[0]))) {
421
                virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
422 423
                                      _("Cannot use name address '%s' in network '%s'"),
                                      name, networkName);
424 425 426 427 428 429
                VIR_FREE(name);
            }
            /*
             * You need at least one MAC address or one host name
             */
            if ((mac == NULL) && (name == NULL)) {
430 431 432 433
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("Static host definition in network '%s' must have mac or name attribute"),
                                      networkName);
                return -1;
434
            }
435
            ip = virXMLPropString(cur, "ip");
436 437 438 439 440
            if ((ip == NULL) ||
                (virSocketParseAddr(ip, &inaddr, AF_UNSPEC) < 0)) {
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("Missing IP address in static host definition for network '%s'"),
                                      networkName);
441 442 443
                VIR_FREE(ip);
                VIR_FREE(mac);
                VIR_FREE(name);
444
                return -1;
445
            }
E
Eric Blake 已提交
446
            VIR_FREE(ip);
447 448 449
            if (VIR_REALLOC_N(def->hosts, def->nhosts + 1) < 0) {
                VIR_FREE(mac);
                VIR_FREE(name);
450
                virReportOOMError();
451 452
                return -1;
            }
453 454
            def->hosts[def->nhosts].mac = mac;
            def->hosts[def->nhosts].name = name;
455
            def->hosts[def->nhosts].ip = inaddr;
456
            def->nhosts++;
457 458 459

        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "bootp")) {
460 461
            char *file;
            char *server;
462
            virSocketAddr inaddr;
463
            memset(&inaddr, 0, sizeof(inaddr));
464

465
            if (!(file = virXMLPropString(cur, "file"))) {
466 467 468
                cur = cur->next;
                continue;
            }
469
            server = virXMLPropString(cur, "server");
470

471
            if (server &&
E
Eric Blake 已提交
472 473 474
                virSocketParseAddr(server, &inaddr, AF_UNSPEC) < 0) {
                VIR_FREE(file);
                VIR_FREE(server);
475
                return -1;
E
Eric Blake 已提交
476
            }
477

478
            def->bootfile = file;
479
            def->bootserver = inaddr;
E
Eric Blake 已提交
480
            VIR_FREE(server);
481 482 483 484 485 486 487 488
        }

        cur = cur->next;
    }

    return 0;
}

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
static int
virNetworkDNSHostsDefParseXML(virNetworkDNSDefPtr def,
                              xmlNodePtr node)
{
    xmlNodePtr cur;
    char *ip;
    virSocketAddr inaddr;
    int ret = -1;

    if (def->hosts == NULL) {
        if (VIR_ALLOC(def->hosts) < 0) {
            virReportOOMError();
            goto error;
        }
        def->nhosts = 0;
    }

    if (!(ip = virXMLPropString(node, "ip")) ||
        (virSocketParseAddr(ip, &inaddr, AF_UNSPEC) < 0)) {
        virNetworkReportError(VIR_ERR_XML_DETAIL,
                              _("Missing IP address in DNS host definition"));
        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;
}

554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 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
static int
virNetworkDNSDefParseXML(virNetworkDNSDefPtr *dnsdef,
                         xmlNodePtr node)
{
    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"))) {
                virNetworkReportError(VIR_ERR_XML_DETAIL,
                                      "%s", _("Missing required name attribute in dns txt record"));
                goto error;
            }
            if (!(value = virXMLPropString(cur, "value"))) {
                virNetworkReportError(VIR_ERR_XML_DETAIL,
                                      _("Missing required value attribute in dns txt record '%s'"), name);
                goto error;
            }

            if (strchr(name, ' ') != NULL) {
                virNetworkReportError(VIR_ERR_XML_DETAIL,
                                      _("spaces are not allowed in DNS TXT record names (name is '%s')"), name);
                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;
600 601 602 603 604
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {
            ret = virNetworkDNSHostsDefParseXML(def, cur);
            if (ret < 0)
                goto error;
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
        }

        cur = cur->next;
    }

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

622
static int
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
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) {
        if (virSocketParseAddr(address, &def->address, AF_UNSPEC) < 0) {
            virNetworkReportError(VIR_ERR_XML_ERROR,
                                  _("Bad address '%s' in definition of network '%s'"),
                                  address, networkName);
            goto error;
        }
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
    /* validate family vs. address */
    if (def->family == NULL) {
        if (!(VIR_SOCKET_IS_FAMILY(&def->address, AF_INET) ||
              VIR_SOCKET_IS_FAMILY(&def->address, AF_UNSPEC))) {
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("no family specified for non-IPv4 address address '%s' in network '%s'"),
                                  address, networkName);
            goto error;
        }
    } else if (STREQ(def->family, "ipv4")) {
        if (!VIR_SOCKET_IS_FAMILY(&def->address, AF_INET)) {
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("family 'ipv4' specified for non-IPv4 address '%s' in network '%s'"),
                                  address, networkName);
            goto error;
        }
    } else if (STREQ(def->family, "ipv6")) {
        if (!VIR_SOCKET_IS_FAMILY(&def->address, AF_INET6)) {
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("family 'ipv6' specified for non-IPv6 address '%s' in network '%s'"),
                                  address, networkName);
            goto error;
        }
    } else {
        virNetworkReportError(VIR_ERR_XML_ERROR,
                              _("Unrecognized family '%s' in definition of network '%s'"),
                              def->family, networkName);
        goto error;
    }
690

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
    /* parse/validate netmask */
    if (netmask) {
        if (address == NULL) {
            /* netmask is meaningless without an address */
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("netmask specified without address in network '%s'"),
                                  networkName);
            goto error;
        }

        if (!VIR_SOCKET_IS_FAMILY(&def->address, AF_INET)) {
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("netmask not supported for address '%s' in network '%s' (IPv4 only)"),
                                  address, networkName);
            goto error;
        }

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

        if (virSocketParseAddr(netmask, &def->netmask, AF_UNSPEC) < 0)
            goto error;

        if (!VIR_SOCKET_IS_FAMILY(&def->netmask, AF_INET)) {
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("network '%s' has invalid netmask '%s' for address '%s' (both must be IPv4)"),
                                  networkName, netmask, address);
            goto error;
        }
    }

    if (VIR_SOCKET_IS_FAMILY(&def->address, AF_INET)) {
        /* parse IPv4-related info */
        cur = node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE &&
                xmlStrEqual(cur->name, BAD_CAST "dhcp")) {
733
                result = virNetworkDHCPRangeDefParseXML(networkName, def, cur);
734 735 736 737 738 739 740 741 742 743 744 745 746
                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;
747 748
            }

749
            cur = cur->next;
750
        }
751
    }
752

753 754 755 756 757
    result = 0;

error:
    if (result < 0) {
        virNetworkIpDefClear(def);
758
    }
759 760 761 762 763
    VIR_FREE(address);
    VIR_FREE(netmask);

    ctxt->node = save;
    return result;
764 765
}

766 767 768 769 770 771 772 773 774 775 776 777
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;
778
    xmlNodePtr bandwidth_node;
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
    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 &&
        (virVirtualPortProfileParseXML(virtPortNode,
                                       &def->virtPortProfile) < 0)) {
        goto error;
    }

798 799 800 801 802 803
    bandwidth_node = virXPathNode("./bandwidth", ctxt);
    if (bandwidth_node &&
        !(def->bandwidth = virBandwidthDefParseNode(bandwidth_node))) {
        goto error;
    }

804 805 806 807 808 809 810 811 812 813 814
    result = 0;
error:
    if (result < 0) {
        virPortGroupDefClear(def);
    }
    VIR_FREE(isDefault);

    ctxt->node = save;
    return result;
}

815
static virNetworkDefPtr
816
virNetworkDefParseXML(xmlXPathContextPtr ctxt)
817 818 819
{
    virNetworkDefPtr def;
    char *tmp;
820
    char *stp = NULL;
821
    xmlNodePtr *ipNodes = NULL;
822 823
    xmlNodePtr *portGroupNodes = NULL;
    xmlNodePtr *forwardIfNodes = NULL;
824
    xmlNodePtr dnsNode = NULL;
825 826 827 828 829
    xmlNodePtr virtPortNode = NULL;
    xmlNodePtr forwardNode = NULL;
    int nIps, nPortGroups, nForwardIfs;
    char *forwardDev = NULL;
    xmlNodePtr save = ctxt->node;
830
    xmlNodePtr bandwidthNode = NULL;
831 832

    if (VIR_ALLOC(def) < 0) {
833
        virReportOOMError();
834 835 836 837
        return NULL;
    }

    /* Extract network name */
838
    def->name = virXPathString("string(./name[1])", ctxt);
839
    if (!def->name) {
840
        virNetworkReportError(VIR_ERR_NO_NAME, NULL);
841 842 843 844
        goto error;
    }

    /* Extract network uuid */
845
    tmp = virXPathString("string(./uuid[1])", ctxt);
846
    if (!tmp) {
847
        if (virUUIDGenerate(def->uuid)) {
848
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
849
                                  "%s", _("Failed to generate UUID"));
850 851 852 853 854
            goto error;
        }
    } else {
        if (virUUIDParse(tmp, def->uuid) < 0) {
            VIR_FREE(tmp);
855
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
856 857 858 859 860 861
                                  "%s", _("malformed uuid element"));
            goto error;
        }
        VIR_FREE(tmp);
    }

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

865 866 867 868
    if ((bandwidthNode = virXPathNode("./bandwidth", ctxt)) != NULL &&
        (def->bandwidth = virBandwidthDefParseNode(bandwidthNode)) == NULL)
        goto error;

869
    /* Parse bridge information */
870
    def->bridge = virXPathString("string(./bridge[1]/@name)", ctxt);
871
    stp = virXPathString("string(./bridge[1]/@stp)", ctxt);
872

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

876 877 878 879 880 881 882 883 884 885 886 887 888
    tmp = virXPathString("string(./mac[1]/@address)", ctxt);
    if (tmp) {
        if (virParseMacAddr(tmp, def->mac) < 0) {
            virNetworkReportError(VIR_ERR_XML_ERROR,
                                  _("Invalid bridge mac address '%s' in network '%s'"),
                                  tmp, def->name);
            VIR_FREE(tmp);
            goto error;
        }
        VIR_FREE(tmp);
        def->mac_specified = true;
    }

889 890 891 892 893 894
    dnsNode = virXPathNode("./dns", ctxt);
    if (dnsNode != NULL) {
        if (virNetworkDNSDefParseXML(&def->dns, dnsNode) < 0)
            goto error;
    }

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 921 922 923 924
    virtPortNode = virXPathNode("./virtualport", ctxt);
    if (virtPortNode &&
        (virVirtualPortProfileParseXML(virtPortNode,
                                       &def->virtPortProfile) < 0)) {
        goto error;
    }

    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);

925
    nIps = virXPathNodeSet("./ip", ctxt, &ipNodes);
926 927 928
    if (nIps < 0)
        goto error;

929 930
    if (nIps > 0) {
        int ii;
931

932 933 934
        /* allocate array to hold all the addrs */
        if (VIR_ALLOC_N(def->ips, nIps) < 0) {
            virReportOOMError();
935 936
            goto error;
        }
937 938 939 940 941 942 943
        /* 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++;
944
        }
945
    }
E
Eric Blake 已提交
946
    VIR_FREE(ipNodes);
947

948 949 950 951 952 953 954
    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);
955 956
        if (tmp) {
            if ((def->forwardType = virNetworkForwardTypeFromString(tmp)) < 0) {
957
                virNetworkReportError(VIR_ERR_XML_ERROR,
958 959 960 961 962 963 964 965 966
                                      _("unknown forwarding type '%s'"), tmp);
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        } else {
            def->forwardType = VIR_NETWORK_FORWARD_NAT;
        }

967
        forwardDev = virXPathString("string(./@dev)", ctxt);
968

969 970 971 972 973 974 975
        /* all of these modes can use a pool of physical interfaces */
        nForwardIfs = virXPathNodeSet("./interface", ctxt, &forwardIfNodes);
        if (nForwardIfs < 0)
            goto error;

        if ((nForwardIfs > 0) || forwardDev) {
            int ii;
976

977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 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 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
            /* allocate array to hold all the portgroups */
            if (VIR_ALLOC_N(def->forwardIfs, MAX(nForwardIfs, 1)) < 0) {
                virReportOOMError();
                goto error;
            }

            if (forwardDev) {
                def->forwardIfs[0].usageCount = 0;
                def->forwardIfs[0].dev = forwardDev;
                forwardDev = NULL;
                def->nForwardIfs++;
            }

            /* parse each forwardIf */
            for (ii = 0; ii < nForwardIfs; ii++) {
                forwardDev = virXMLPropString(forwardIfNodes[ii], "dev");
                if (!forwardDev) {
                    virNetworkReportError(VIR_ERR_XML_ERROR,
                                          _("Missing required dev attribute in network '%s' forward interface element"),
                                          def->name);
                    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. */
                    if (STRNEQ(forwardDev, def->forwardIfs[0].dev)) {
                        virNetworkReportError(VIR_ERR_XML_ERROR,
                                              _("forward dev '%s' must match first interface element dev '%s' in network '%s'"),
                                              def->forwardIfs[0].dev,
                                              forwardDev, def->name);
                        goto error;
                    }
                    VIR_FREE(forwardDev);
                    continue;
                }

                def->forwardIfs[ii].dev = forwardDev;
                forwardDev = NULL;
                def->forwardIfs[ii].usageCount = 0;
                def->nForwardIfs++;
            }
        }
        VIR_FREE(forwardIfNodes);

        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) {
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("%s forwarding requested, but no IP address provided for network '%s'"),
                                      virNetworkForwardTypeToString(def->forwardType),
                                      def->name);
                goto error;
            }
            if (def->nForwardIfs > 1) {
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("multiple forwarding interfaces specified for network '%s', only one is supported"),
                                      def->name);
                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:
            if (def->bridge) {
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("bridge name not allowed in %s mode (network '%s'"),
                                      virNetworkForwardTypeToString(def->forwardType),
                                      def->name);
                goto error;
            }
            /* fall through to next case */
        case VIR_NETWORK_FORWARD_BRIDGE:
            if (def->delay || stp) {
                virNetworkReportError(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);
                goto error;
            }
            break;
        }
    }
    VIR_FREE(stp);
    ctxt->node = save;
1067 1068 1069
    return def;

 error:
1070
    VIR_FREE(stp);
1071
    virNetworkDefFree(def);
E
Eric Blake 已提交
1072
    VIR_FREE(ipNodes);
1073 1074 1075 1076
    VIR_FREE(portGroupNodes);
    VIR_FREE(forwardIfNodes);
    VIR_FREE(forwardDev);
    ctxt->node = save;
1077 1078 1079
    return NULL;
}

J
Jiri Denemark 已提交
1080 1081 1082
static virNetworkDefPtr
virNetworkDefParse(const char *xmlStr,
                   const char *filename)
1083
{
J
Jiri Denemark 已提交
1084
    xmlDocPtr xml;
1085
    virNetworkDefPtr def = NULL;
1086

J
Jiri Denemark 已提交
1087 1088 1089
    if ((xml = virXMLParse(filename, xmlStr, "network.xml"))) {
        def = virNetworkDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1090 1091 1092 1093 1094
    }

    return def;
}

J
Jiri Denemark 已提交
1095
virNetworkDefPtr virNetworkDefParseString(const char *xmlStr)
1096
{
J
Jiri Denemark 已提交
1097 1098
    return virNetworkDefParse(xmlStr, NULL);
}
1099

J
Jiri Denemark 已提交
1100 1101 1102
virNetworkDefPtr virNetworkDefParseFile(const char *filename)
{
    return virNetworkDefParse(NULL, filename);
1103 1104 1105
}


1106
virNetworkDefPtr virNetworkDefParseNode(xmlDocPtr xml,
1107 1108 1109 1110 1111 1112
                                        xmlNodePtr root)
{
    xmlXPathContextPtr ctxt = NULL;
    virNetworkDefPtr def = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "network")) {
1113
        virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
1114 1115 1116 1117 1118 1119
                              "%s", _("incorrect root element"));
        return NULL;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1120
        virReportOOMError();
1121 1122 1123 1124
        goto cleanup;
    }

    ctxt->node = root;
1125
    def = virNetworkDefParseXML(ctxt);
1126 1127 1128 1129 1130 1131

cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
static int
virNetworkDNSDefFormat(virBufferPtr buf,
                       virNetworkDNSDefPtr def)
{
    int result = 0;
    int i;

    if (def == NULL)
        goto out;

    virBufferAddLit(buf, "  <dns>\n");

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

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
    if (def->nhosts) {
        int ii, j;

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

            virBufferAsprintf(buf, "    <host ip='%s'>\n", ip);

            for (j = 0; j < def->hosts[ii].nnames; j++)
                virBufferAsprintf(buf, "      <hostname>%s</hostname>\n",
                                               def->hosts[ii].names[j]);

            virBufferAsprintf(buf, "    </host>\n");
1163
            VIR_FREE(ip);
1164 1165 1166
        }
    }

1167 1168 1169 1170 1171
    virBufferAddLit(buf, "  </dns>\n");
out:
    return result;
}

1172 1173 1174 1175 1176 1177 1178 1179 1180
static int
virNetworkIpDefFormat(virBufferPtr buf,
                      const virNetworkIpDefPtr def)
{
    int result = -1;

    virBufferAddLit(buf, "  <ip");

    if (def->family) {
1181
        virBufferAsprintf(buf, " family='%s'", def->family);
1182 1183 1184 1185 1186
    }
    if (VIR_SOCKET_HAS_ADDR(&def->address)) {
        char *addr = virSocketFormatAddr(&def->address);
        if (!addr)
            goto error;
1187
        virBufferAsprintf(buf, " address='%s'", addr);
1188 1189 1190 1191 1192 1193
        VIR_FREE(addr);
    }
    if (VIR_SOCKET_HAS_ADDR(&def->netmask)) {
        char *addr = virSocketFormatAddr(&def->netmask);
        if (!addr)
            goto error;
1194
        virBufferAsprintf(buf, " netmask='%s'", addr);
1195 1196 1197
        VIR_FREE(addr);
    }
    if (def->prefix > 0) {
1198
        virBufferAsprintf(buf," prefix='%u'", def->prefix);
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
    }
    virBufferAddLit(buf, ">\n");

    if (def->tftproot) {
        virBufferEscapeString(buf, "    <tftp root='%s' />\n",
                              def->tftproot);
    }
    if ((def->nranges || def->nhosts)) {
        int ii;
        virBufferAddLit(buf, "    <dhcp>\n");
        for (ii = 0 ; ii < def->nranges ; ii++) {
            char *saddr = virSocketFormatAddr(&def->ranges[ii].start);
            if (!saddr)
                goto error;
            char *eaddr = virSocketFormatAddr(&def->ranges[ii].end);
            if (!eaddr) {
                VIR_FREE(saddr);
                goto error;
            }
1218
            virBufferAsprintf(buf, "      <range start='%s' end='%s' />\n",
1219 1220 1221 1222 1223 1224 1225
                              saddr, eaddr);
            VIR_FREE(saddr);
            VIR_FREE(eaddr);
        }
        for (ii = 0 ; ii < def->nhosts ; ii++) {
            virBufferAddLit(buf, "      <host ");
            if (def->hosts[ii].mac)
1226
                virBufferAsprintf(buf, "mac='%s' ", def->hosts[ii].mac);
1227
            if (def->hosts[ii].name)
1228
                virBufferAsprintf(buf, "name='%s' ", def->hosts[ii].name);
1229 1230 1231 1232
            if (VIR_SOCKET_HAS_ADDR(&def->hosts[ii].ip)) {
                char *ipaddr = virSocketFormatAddr(&def->hosts[ii].ip);
                if (!ipaddr)
                    goto error;
1233
                virBufferAsprintf(buf, "ip='%s' ", ipaddr);
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
                VIR_FREE(ipaddr);
            }
            virBufferAddLit(buf, "/>\n");
        }
        if (def->bootfile) {
            virBufferEscapeString(buf, "      <bootp file='%s' ",
                                  def->bootfile);
            if (VIR_SOCKET_HAS_ADDR(&def->bootserver)) {
                char *ipaddr = virSocketFormatAddr(&def->bootserver);
                if (!ipaddr)
                    goto error;
                virBufferEscapeString(buf, "server='%s' ", ipaddr);
                VIR_FREE(ipaddr);
            }
            virBufferAddLit(buf, "/>\n");
        }

        virBufferAddLit(buf, "    </dhcp>\n");
    }

    virBufferAddLit(buf, "  </ip>\n");

    result = 0;
error:
    return result;
}

1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
static void
virPortGroupDefFormat(virBufferPtr buf,
                      const virPortGroupDefPtr def)
{
    virBufferAsprintf(buf, "  <portgroup name='%s'", def->name);
    if (def->isDefault) {
        virBufferAddLit(buf, " default='yes'");
    }
    virBufferAddLit(buf, ">\n");
    virVirtualPortProfileFormat(buf, def->virtPortProfile, "    ");
1271
    virBandwidthDefFormat(buf, def->bandwidth, "    ");
1272 1273 1274
    virBufferAddLit(buf, "  </portgroup>\n");
}

1275
char *virNetworkDefFormat(const virNetworkDefPtr def)
1276 1277 1278 1279
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    unsigned char *uuid;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1280
    int ii;
1281 1282 1283 1284 1285 1286

    virBufferAddLit(&buf, "<network>\n");
    virBufferEscapeString(&buf, "  <name>%s</name>\n", def->name);

    uuid = def->uuid;
    virUUIDFormat(uuid, uuidstr);
1287
    virBufferAsprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
1288 1289

    if (def->forwardType != VIR_NETWORK_FORWARD_NONE) {
1290
        const char *dev = virNetworkDefForwardIf(def, 0);
1291
        const char *mode = virNetworkForwardTypeToString(def->forwardType);
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310

        if (!mode) {
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
                                  _("Unknown forward type %d in network '%s'"),
                                  def->forwardType, def->name);
            goto error;
        }
        virBufferAddLit(&buf, "  <forward");
        if (dev)
            virBufferEscapeString(&buf, " dev='%s'", dev);
        virBufferAsprintf(&buf, " mode='%s'%s>\n", mode,
                          def->nForwardIfs ? "" : "/");

        if (def->nForwardIfs) {
            for (ii = 0; ii < def->nForwardIfs; ii++) {
                if (def->forwardIfs[ii].dev) {
                    virBufferEscapeString(&buf, "    <interface dev='%s'/>\n",
                                          def->forwardIfs[ii].dev);
                }
1311
            }
1312
            virBufferAddLit(&buf, "  </forward>\n");
1313 1314 1315
        }
    }

1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    if (def->forwardType == VIR_NETWORK_FORWARD_NONE ||
         def->forwardType == VIR_NETWORK_FORWARD_NAT ||
         def->forwardType == VIR_NETWORK_FORWARD_ROUTE) {

        virBufferAddLit(&buf, "  <bridge");
        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) {
       virBufferEscapeString(&buf, "  <bridge name='%s' />\n", def->bridge);
    }


1332 1333 1334
    if (def->mac_specified) {
        char macaddr[VIR_MAC_STRING_BUFLEN];
        virFormatMacAddr(def->mac, macaddr);
1335
        virBufferAsprintf(&buf, "  <mac address='%s'/>\n", macaddr);
1336
    }
1337

1338
    if (def->domain)
1339
        virBufferAsprintf(&buf, "  <domain name='%s'/>\n", def->domain);
1340

1341 1342 1343
    if (virNetworkDNSDefFormat(&buf, def->dns) < 0)
        goto error;

1344 1345 1346
    if (virBandwidthDefFormat(&buf, def->bandwidth, "  ") < 0)
        goto error;

1347 1348 1349
    for (ii = 0; ii < def->nips; ii++) {
        if (virNetworkIpDefFormat(&buf, &def->ips[ii]) < 0)
            goto error;
1350 1351
    }

1352 1353 1354 1355 1356
    virVirtualPortProfileFormat(&buf, def->virtPortProfile, "  ");

    for (ii = 0; ii < def->nPortGroups; ii++)
        virPortGroupDefFormat(&buf, &def->portGroups[ii]);

1357 1358 1359 1360 1361 1362 1363 1364
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
        goto no_memory;

    return virBufferContentAndReset(&buf);

 no_memory:
1365
    virReportOOMError();
1366
  error:
1367
    virBufferFreeAndReset(&buf);
1368 1369 1370
    return NULL;
}

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
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;
}

1387
int virNetworkSaveXML(const char *configDir,
1388 1389
                      virNetworkDefPtr def,
                      const char *xml)
1390
{
1391
    char *configFile = NULL;
1392 1393 1394
    int fd = -1, ret = -1;
    size_t towrite;

1395
    if ((configFile = virNetworkConfigFile(configDir, def->name)) == NULL)
1396 1397
        goto cleanup;

1398 1399
    if (virFileMakePath(configDir) < 0) {
        virReportSystemError(errno,
1400 1401
                             _("cannot create config directory '%s'"),
                             configDir);
1402 1403 1404
        goto cleanup;
    }

1405
    if ((fd = open(configFile,
1406 1407
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1408
        virReportSystemError(errno,
1409
                             _("cannot create config file '%s'"),
1410
                             configFile);
1411 1412 1413
        goto cleanup;
    }

1414 1415
    virEmitXMLWarning(fd, def->name, "net-edit");

1416 1417
    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) < 0) {
1418
        virReportSystemError(errno,
1419
                             _("cannot write config file '%s'"),
1420
                             configFile);
1421 1422 1423
        goto cleanup;
    }

1424
    if (VIR_CLOSE(fd) < 0) {
1425
        virReportSystemError(errno,
1426
                             _("cannot save config file '%s'"),
1427
                             configFile);
1428 1429 1430 1431 1432 1433
        goto cleanup;
    }

    ret = 0;

 cleanup:
1434
    VIR_FORCE_CLOSE(fd);
1435

1436 1437 1438 1439 1440
    VIR_FREE(configFile);

    return ret;
}

1441
int virNetworkSaveConfig(const char *configDir,
1442 1443 1444 1445 1446
                         virNetworkDefPtr def)
{
    int ret = -1;
    char *xml;

1447
    if (!(xml = virNetworkDefFormat(def)))
1448 1449
        goto cleanup;

1450
    if (virNetworkSaveXML(configDir, def, xml))
1451 1452 1453 1454 1455
        goto cleanup;

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

1459

1460
virNetworkObjPtr virNetworkLoadConfig(virNetworkObjListPtr nets,
1461 1462
                                      const char *configDir,
                                      const char *autostartDir,
1463
                                      const char *name)
1464 1465 1466 1467 1468 1469
{
    char *configFile = NULL, *autostartLink = NULL;
    virNetworkDefPtr def = NULL;
    virNetworkObjPtr net;
    int autostart;

1470
    if ((configFile = virNetworkConfigFile(configDir, name)) == NULL)
1471
        goto error;
1472
    if ((autostartLink = virNetworkConfigFile(autostartDir, name)) == NULL)
1473 1474 1475 1476 1477
        goto error;

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

1478
    if (!(def = virNetworkDefParseFile(configFile)))
1479 1480
        goto error;

1481
    if (!STREQ(name, def->name)) {
1482
        virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
1483 1484 1485 1486 1487 1488
                              _("Network config filename '%s'"
                                " does not match network name '%s'"),
                              configFile, def->name);
        goto error;
    }

1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    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;
    }
1499

1500
    if (!(net = virNetworkAssignDef(nets, def)))
1501 1502 1503
        goto error;

    net->autostart = autostart;
1504
    net->persistent = 1;
1505

1506 1507 1508
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);

1509 1510 1511 1512 1513 1514 1515 1516 1517
    return net;

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

1518
int virNetworkLoadAllConfigs(virNetworkObjListPtr nets,
1519 1520 1521 1522 1523 1524 1525 1526 1527
                             const char *configDir,
                             const char *autostartDir)
{
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(configDir))) {
        if (errno == ENOENT)
            return 0;
1528
        virReportSystemError(errno,
1529 1530
                             _("Failed to open dir '%s'"),
                             configDir);
1531 1532 1533 1534
        return -1;
    }

    while ((entry = readdir(dir))) {
1535 1536
        virNetworkObjPtr net;

1537 1538 1539
        if (entry->d_name[0] == '.')
            continue;

1540
        if (!virFileStripSuffix(entry->d_name, ".xml"))
1541 1542 1543 1544
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
1545
        net = virNetworkLoadConfig(nets,
1546 1547 1548 1549 1550
                                   configDir,
                                   autostartDir,
                                   entry->d_name);
        if (net)
            virNetworkObjUnlock(net);
1551 1552 1553 1554 1555 1556 1557
    }

    closedir(dir);

    return 0;
}

1558
int virNetworkDeleteConfig(const char *configDir,
1559
                           const char *autostartDir,
1560 1561
                           virNetworkObjPtr net)
{
1562 1563
    char *configFile = NULL;
    char *autostartLink = NULL;
R
Ryota Ozaki 已提交
1564
    int ret = -1;
1565

1566
    if ((configFile = virNetworkConfigFile(configDir, net->def->name)) == NULL)
1567
        goto error;
1568
    if ((autostartLink = virNetworkConfigFile(autostartDir, net->def->name)) == NULL)
1569
        goto error;
1570 1571

    /* Not fatal if this doesn't work */
1572
    unlink(autostartLink);
1573

1574
    if (unlink(configFile) < 0) {
1575
        virReportSystemError(errno,
1576
                             _("cannot remove config file '%s'"),
1577 1578
                             configFile);
        goto error;
1579 1580
    }

R
Ryota Ozaki 已提交
1581
    ret = 0;
1582 1583 1584 1585

error:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
R
Ryota Ozaki 已提交
1586
    return ret;
1587 1588
}

1589
char *virNetworkConfigFile(const char *dir,
1590 1591 1592 1593 1594
                           const char *name)
{
    char *ret = NULL;

    if (virAsprintf(&ret, "%s/%s.xml", dir, name) < 0) {
1595
        virReportOOMError();
1596 1597 1598 1599
        return NULL;
    }

    return ret;
1600
}
D
Daniel P. Berrange 已提交
1601

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
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;
}

1621
char *virNetworkAllocateBridge(const virNetworkObjListPtr nets,
1622
                               const char *template)
1623 1624 1625 1626 1627
{

    int id = 0;
    char *newname;

1628 1629 1630
    if (!template)
        template = "virbr%d";

1631
    do {
1632 1633 1634 1635 1636
        if (virAsprintf(&newname, template, id) < 0) {
            virReportOOMError();
            return NULL;
        }
        if (!virNetworkBridgeInUse(nets, newname, NULL)) {
1637 1638
            return newname;
        }
1639
        VIR_FREE(newname);
1640 1641

        id++;
1642
    } while (id <= MAX_BRIDGE_ID);
1643

1644
    virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
1645 1646 1647 1648 1649
                          _("Bridge generation exceeded max id %d"),
                          MAX_BRIDGE_ID);
    return NULL;
}

1650
int virNetworkSetBridgeName(const virNetworkObjListPtr nets,
1651 1652
                            virNetworkDefPtr def,
                            int check_collision) {
1653 1654 1655

    int ret = -1;

1656
    if (def->bridge && !strstr(def->bridge, "%d")) {
1657 1658 1659 1660 1661
        /* 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)) {
1662 1663 1664
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
                                  _("bridge name '%s' already in use."),
                                  def->bridge);
1665 1666 1667 1668
            goto error;
        }
    } else {
        /* Allocate a bridge name */
1669
        if (!(def->bridge = virNetworkAllocateBridge(nets, def->bridge)))
1670 1671 1672 1673 1674 1675 1676
            goto error;
    }

    ret = 0;
error:
    return ret;
}
1677

1678

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
void virNetworkSetBridgeMacAddr(virNetworkDefPtr def)
{
    if (!def->mac_specified) {
        /* if the bridge doesn't have a mac address explicitly defined,
         * autogenerate a random one.
         */
        virGenerateMacAddr((unsigned char[]){ 0x52, 0x54, 0 },
                           def->mac);
        def->mac_specified = true;
    }
}

1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754
/*
 * 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);
            virNetworkReportError(VIR_ERR_OPERATION_FAILED,
                                  _("network '%s' is already defined with uuid %s"),
                                  vm->def->name, uuidstr);
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if VM is already active, refuse it */
            if (virNetworkObjIsActive(vm)) {
                virNetworkReportError(VIR_ERR_OPERATION_INVALID,
                                      _("network is already active as '%s'"),
                                      vm->def->name);
                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);
            virNetworkReportError(VIR_ERR_OPERATION_FAILED,
                                  _("network '%s' already exists with uuid %s"),
                                  def->name, uuidstr);
            goto cleanup;
        }
    }

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


1755 1756
void virNetworkObjLock(virNetworkObjPtr obj)
{
1757
    virMutexLock(&obj->lock);
1758 1759 1760 1761
}

void virNetworkObjUnlock(virNetworkObjPtr obj)
{
1762
    virMutexUnlock(&obj->lock);
D
Daniel P. Berrange 已提交
1763
}