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

47
#define MAX_BRIDGE_ID 256
48 49
#define VIR_FROM_THIS VIR_FROM_NETWORK

50 51 52 53
VIR_ENUM_DECL(virNetworkForward)

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

56
virNetworkObjPtr virNetworkFindByUUID(const virNetworkObjListPtr nets,
57 58
                                      const unsigned char *uuid)
{
59 60
    unsigned int i;

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

    return NULL;
}

71
virNetworkObjPtr virNetworkFindByName(const virNetworkObjListPtr nets,
72 73
                                      const char *name)
{
74 75
    unsigned int i;

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

    return NULL;
}


87 88 89 90 91
static void
virPortGroupDefClear(virPortGroupDefPtr def)
{
    VIR_FREE(def->name);
    VIR_FREE(def->virtPortProfile);
92
    virNetDevBandwidthFree(def->bandwidth);
93
    def->bandwidth = NULL;
94 95 96 97 98 99 100 101
}

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

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
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);
}

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

150 151
void virNetworkDefFree(virNetworkDefPtr def)
{
152
    int ii;
153 154 155 156 157 158

    if (!def)
        return;

    VIR_FREE(def->name);
    VIR_FREE(def->bridge);
159
    VIR_FREE(def->domain);
160

161 162 163 164 165
    for (ii = 0 ; ii < def->nForwardPfs && def->forwardPfs ; ii++) {
        virNetworkForwardIfDefClear(&def->forwardPfs[ii]);
    }
    VIR_FREE(def->forwardPfs);

166 167 168 169 170
    for (ii = 0 ; ii < def->nForwardIfs && def->forwardIfs ; ii++) {
        virNetworkForwardIfDefClear(&def->forwardIfs[ii]);
    }
    VIR_FREE(def->forwardIfs);

171 172
    for (ii = 0 ; ii < def->nips && def->ips ; ii++) {
        virNetworkIpDefClear(&def->ips[ii]);
173
    }
174
    VIR_FREE(def->ips);
175

176 177 178 179 180
    for (ii = 0; ii < def->nPortGroups && def->portGroups; ii++) {
        virPortGroupDefClear(&def->portGroups[ii]);
    }
    VIR_FREE(def->portGroups);

181 182
    virNetworkDNSDefFree(def->dns);

183 184
    VIR_FREE(def->virtPortProfile);

185
    virNetDevBandwidthFree(def->bandwidth);
186

187 188 189 190 191 192 193 194 195 196 197
    VIR_FREE(def);
}

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

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

198 199
    virMutexDestroy(&net->lock);

200 201 202
    VIR_FREE(net);
}

203 204 205 206 207 208 209 210 211 212 213
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;
}

214
virNetworkObjPtr virNetworkAssignDef(virNetworkObjListPtr nets,
215 216 217 218
                                     const virNetworkDefPtr def)
{
    virNetworkObjPtr network;

219
    if ((network = virNetworkFindByName(nets, def->name))) {
D
Daniel P. Berrange 已提交
220
        if (!virNetworkObjIsActive(network)) {
221 222 223
            virNetworkDefFree(network->def);
            network->def = def;
        } else {
224
            virNetworkDefFree(network->newDef);
225 226 227 228 229 230 231
            network->newDef = def;
        }

        return network;
    }

    if (VIR_ALLOC(network) < 0) {
232
        virReportOOMError();
233 234
        return NULL;
    }
235
    if (virMutexInit(&network->lock) < 0) {
236 237
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
238 239 240
        VIR_FREE(network);
        return NULL;
    }
241
    virNetworkObjLock(network);
242 243
    network->def = def;

244
    if (VIR_REALLOC_N(nets->objs, nets->count + 1) < 0) {
245
        virReportOOMError();
246 247 248 249 250 251
        VIR_FREE(network);
        return NULL;
    }

    nets->objs[nets->count] = network;
    nets->count++;
252 253 254 255 256

    return network;

}

257
void virNetworkRemoveInactive(virNetworkObjListPtr nets,
258 259
                              const virNetworkObjPtr net)
{
260
    unsigned int i;
261

262
    virNetworkObjUnlock(net);
263
    for (i = 0 ; i < nets->count ; i++) {
264
        virNetworkObjLock(nets->objs[i]);
265
        if (nets->objs[i] == net) {
266
            virNetworkObjUnlock(nets->objs[i]);
267
            virNetworkObjFree(nets->objs[i]);
268

269 270 271
            if (i < (nets->count - 1))
                memmove(nets->objs + i, nets->objs + i + 1,
                        sizeof(*(nets->objs)) * (nets->count - (i + 1)));
272

273 274 275 276 277 278 279
            if (VIR_REALLOC_N(nets->objs, nets->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            nets->count--;

            break;
        }
280
        virNetworkObjUnlock(nets->objs[i]);
281
    }
282 283
}

284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
/* 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++) {
300
        if (VIR_SOCKET_ADDR_IS_FAMILY(&def->ips[ii].address, family)
301 302 303 304 305 306 307 308
            && (n-- <= 0)) {
            return &def->ips[ii];
        }
    }
    /* failed to find enough of the right family */
    return NULL;
}

L
Laine Stump 已提交
309 310 311
/* return number of 1 bits in netmask for the network's ipAddress,
 * or -1 on error
 */
312
int virNetworkIpDefPrefix(const virNetworkIpDefPtr def)
L
Laine Stump 已提交
313
{
314 315
    if (def->prefix > 0) {
        return def->prefix;
316 317 318
    } 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 已提交
319 320 321 322 323 324
        /* 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
325
            = ntohl(def->address.data.inet4.sin_addr.s_addr) >> 24;
L
Laine Stump 已提交
326 327 328 329 330 331 332 333 334 335 336
        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;
337
    } else if (VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6)) {
338
        return 64;
L
Laine Stump 已提交
339 340 341 342 343 344 345 346
    }
    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)
 */
347 348
int virNetworkIpDefNetmask(const virNetworkIpDefPtr def,
                           virSocketAddrPtr netmask)
L
Laine Stump 已提交
349
{
350
    if (VIR_SOCKET_ADDR_IS_FAMILY(&def->netmask, AF_INET)) {
L
Laine Stump 已提交
351 352 353 354
        *netmask = def->netmask;
        return 0;
    }

355
    return virSocketAddrPrefixToNetmask(virNetworkIpDefPrefix(def), netmask,
356
                                        VIR_SOCKET_ADDR_FAMILY(&def->address));
L
Laine Stump 已提交
357 358
}

359 360

static int
361 362
virNetworkDHCPRangeDefParseXML(const char *networkName,
                               virNetworkIpDefPtr def,
363 364
                               xmlNodePtr node)
{
365 366 367 368 369

    xmlNodePtr cur;

    cur = node->children;
    while (cur != NULL) {
370 371
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "range")) {
372 373 374
            char *start, *end;
            virSocketAddr saddr, eaddr;
            int range;
375

376
            if (!(start = virXMLPropString(cur, "start"))) {
377 378 379
                cur = cur->next;
                continue;
            }
380 381
            if (!(end = virXMLPropString(cur, "end"))) {
                VIR_FREE(start);
382
                cur = cur->next;
383 384 385
                continue;
            }

386
            if (virSocketAddrParse(&saddr, start, AF_UNSPEC) < 0) {
387 388
                VIR_FREE(start);
                VIR_FREE(end);
389
                return -1;
390
            }
391
            if (virSocketAddrParse(&eaddr, end, AF_UNSPEC) < 0) {
392 393
                VIR_FREE(start);
                VIR_FREE(end);
394
                return -1;
395 396
            }

397
            range = virSocketAddrGetRange(&saddr, &eaddr);
398
            if (range < 0) {
399 400 401
                virReportError(VIR_ERR_XML_ERROR,
                               _("Invalid dhcp range '%s' to '%s' in network '%s'"),
                               start, end, networkName);
402 403
                VIR_FREE(start);
                VIR_FREE(end);
404
                return -1;
405
            }
E
Eric Blake 已提交
406 407
            VIR_FREE(start);
            VIR_FREE(end);
408

409
            if (VIR_REALLOC_N(def->ranges, def->nranges + 1) < 0) {
410
                virReportOOMError();
411 412
                return -1;
            }
413 414
            def->ranges[def->nranges].start = saddr;
            def->ranges[def->nranges].end = eaddr;
415 416 417
            def->nranges++;
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {
418
            char *mac = NULL, *name = NULL, *ip;
419
            virMacAddr addr;
420
            virSocketAddr inaddr;
421

422
            mac = virXMLPropString(cur, "mac");
423
            if (mac != NULL) {
424
                if (virMacAddrParse(mac, &addr) < 0) {
425 426 427
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Cannot parse MAC address '%s' in network '%s'"),
                                   mac, networkName);
428 429 430
                    VIR_FREE(mac);
                    return -1;
                }
431
                if (virMacAddrIsMulticast(&addr)) {
432 433 434
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("expected unicast mac address, found multicast '%s' in network '%s'"),
                                   (const char *)mac, networkName);
435 436 437
                    VIR_FREE(mac);
                    return -1;
                }
438
            }
439
            name = virXMLPropString(cur, "name");
440
            if ((name != NULL) && (!c_isalpha(name[0]))) {
441 442 443
                virReportError(VIR_ERR_XML_ERROR,
                               _("Cannot use name address '%s' in network '%s'"),
                               name, networkName);
444
                VIR_FREE(mac);
445
                VIR_FREE(name);
446
                return -1;
447 448 449 450 451
            }
            /*
             * You need at least one MAC address or one host name
             */
            if ((mac == NULL) && (name == NULL)) {
452 453 454
                virReportError(VIR_ERR_XML_ERROR,
                               _("Static host definition in network '%s' must have mac or name attribute"),
                               networkName);
455
                return -1;
456
            }
457
            ip = virXMLPropString(cur, "ip");
458
            if ((ip == NULL) ||
459
                (virSocketAddrParse(&inaddr, ip, AF_UNSPEC) < 0)) {
460 461 462
                virReportError(VIR_ERR_XML_ERROR,
                               _("Missing IP address in static host definition for network '%s'"),
                               networkName);
463 464 465
                VIR_FREE(ip);
                VIR_FREE(mac);
                VIR_FREE(name);
466
                return -1;
467
            }
E
Eric Blake 已提交
468
            VIR_FREE(ip);
469 470 471
            if (VIR_REALLOC_N(def->hosts, def->nhosts + 1) < 0) {
                VIR_FREE(mac);
                VIR_FREE(name);
472
                virReportOOMError();
473 474
                return -1;
            }
475 476
            def->hosts[def->nhosts].mac = mac;
            def->hosts[def->nhosts].name = name;
477
            def->hosts[def->nhosts].ip = inaddr;
478
            def->nhosts++;
479 480 481

        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "bootp")) {
482 483
            char *file;
            char *server;
484
            virSocketAddr inaddr;
485
            memset(&inaddr, 0, sizeof(inaddr));
486

487
            if (!(file = virXMLPropString(cur, "file"))) {
488 489 490
                cur = cur->next;
                continue;
            }
491
            server = virXMLPropString(cur, "server");
492

493
            if (server &&
494
                virSocketAddrParse(&inaddr, server, AF_UNSPEC) < 0) {
E
Eric Blake 已提交
495 496
                VIR_FREE(file);
                VIR_FREE(server);
497
                return -1;
E
Eric Blake 已提交
498
            }
499

500
            def->bootfile = file;
501
            def->bootserver = inaddr;
E
Eric Blake 已提交
502
            VIR_FREE(server);
503 504 505 506 507 508 509 510
        }

        cur = cur->next;
    }

    return 0;
}

511 512 513 514 515 516 517 518 519 520
static int
virNetworkDNSHostsDefParseXML(virNetworkDNSDefPtr def,
                              xmlNodePtr node)
{
    xmlNodePtr cur;
    char *ip;
    virSocketAddr inaddr;
    int ret = -1;

    if (!(ip = virXMLPropString(node, "ip")) ||
521
        (virSocketAddrParse(&inaddr, ip, AF_UNSPEC) < 0)) {
522
        virReportError(VIR_ERR_XML_DETAIL, "%s",
523
                       _("Missing IP address in DNS host definition"));
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 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        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;
}

568 569 570 571 572
static int
virNetworkDNSSrvDefParseXML(virNetworkDNSDefPtr def,
                            xmlNodePtr cur,
                            xmlXPathContextPtr ctxt)
{
573 574 575 576
    char *domain = NULL;
    char *service = NULL;
    char *protocol = NULL;
    char *target = NULL;
577 578 579 580 581 582
    int port;
    int priority;
    int weight;
    int ret = 0;

    if (!(service = virXMLPropString(cur, "service"))) {
583 584
        virReportError(VIR_ERR_XML_DETAIL,
                       "%s", _("Missing required service attribute in dns srv record"));
585 586 587 588
        goto error;
    }

    if (strlen(service) > DNS_RECORD_LENGTH_SRV) {
589 590 591
        virReportError(VIR_ERR_XML_DETAIL,
                       _("Service name is too long, limit is %d bytes"),
                       DNS_RECORD_LENGTH_SRV);
592 593 594 595
        goto error;
    }

    if (!(protocol = virXMLPropString(cur, "protocol"))) {
596 597
        virReportError(VIR_ERR_XML_DETAIL,
                       _("Missing required protocol attribute in dns srv record '%s'"), service);
598 599 600 601 602
        goto error;
    }

    /* Check whether protocol value is the supported one */
    if (STRNEQ(protocol, "tcp") && (STRNEQ(protocol, "udp"))) {
603 604
        virReportError(VIR_ERR_XML_DETAIL,
                       _("Invalid protocol attribute value '%s'"), protocol);
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
        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;
}

659 660
static int
virNetworkDNSDefParseXML(virNetworkDNSDefPtr *dnsdef,
661 662
                         xmlNodePtr node,
                         xmlXPathContextPtr ctxt)
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
{
    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"))) {
680 681
                virReportError(VIR_ERR_XML_DETAIL,
                               "%s", _("Missing required name attribute in dns txt record"));
682 683 684
                goto error;
            }
            if (!(value = virXMLPropString(cur, "value"))) {
685 686
                virReportError(VIR_ERR_XML_DETAIL,
                               _("Missing required value attribute in dns txt record '%s'"), name);
687 688 689 690
                goto error;
            }

            if (strchr(name, ' ') != NULL) {
691 692
                virReportError(VIR_ERR_XML_DETAIL,
                               _("spaces are not allowed in DNS TXT record names (name is '%s')"), name);
693 694 695 696 697 698 699 700 701 702 703 704 705
                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;
706 707 708 709 710
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "srv")) {
            ret = virNetworkDNSSrvDefParseXML(def, cur, ctxt);
            if (ret < 0)
                goto error;
711 712 713 714 715
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {
            ret = virNetworkDNSHostsDefParseXML(def, cur);
            if (ret < 0)
                goto error;
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
        }

        cur = cur->next;
    }

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

733
static int
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
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) {
763
        if (virSocketAddrParse(&def->address, address, AF_UNSPEC) < 0) {
764 765 766
            virReportError(VIR_ERR_XML_ERROR,
                           _("Bad address '%s' in definition of network '%s'"),
                           address, networkName);
767 768
            goto error;
        }
769

770
    }
771

772 773
    /* validate family vs. address */
    if (def->family == NULL) {
774 775
        if (!(VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET) ||
              VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_UNSPEC))) {
776 777 778
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("no family specified for non-IPv4 address '%s' in network '%s'"),
                           address, networkName);
779 780 781
            goto error;
        }
    } else if (STREQ(def->family, "ipv4")) {
782
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
783 784 785
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("family 'ipv4' specified for non-IPv4 address '%s' in network '%s'"),
                           address, networkName);
786 787 788
            goto error;
        }
    } else if (STREQ(def->family, "ipv6")) {
789
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6)) {
790 791 792
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("family 'ipv6' specified for non-IPv6 address '%s' in network '%s'"),
                           address, networkName);
793 794 795
            goto error;
        }
    } else {
796 797 798
        virReportError(VIR_ERR_XML_ERROR,
                       _("Unrecognized family '%s' in definition of network '%s'"),
                       def->family, networkName);
799 800
        goto error;
    }
801

802 803 804 805
    /* parse/validate netmask */
    if (netmask) {
        if (address == NULL) {
            /* netmask is meaningless without an address */
806 807 808
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("netmask specified without address in network '%s'"),
                           networkName);
809 810 811
            goto error;
        }

812
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
813 814 815
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("netmask not supported for address '%s' in network '%s' (IPv4 only)"),
                           address, networkName);
816 817 818 819 820
            goto error;
        }

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

827
        if (virSocketAddrParse(&def->netmask, netmask, AF_UNSPEC) < 0)
828 829
            goto error;

830
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->netmask, AF_INET)) {
831 832 833
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("network '%s' has invalid netmask '%s' for address '%s' (both must be IPv4)"),
                           networkName, netmask, address);
834 835 836 837
            goto error;
        }
    }

838
    if (VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
839 840 841 842 843
        /* parse IPv4-related info */
        cur = node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE &&
                xmlStrEqual(cur->name, BAD_CAST "dhcp")) {
844
                result = virNetworkDHCPRangeDefParseXML(networkName, def, cur);
845 846 847 848 849 850 851 852 853 854 855 856 857
                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;
858 859
            }

860
            cur = cur->next;
861
        }
862
    }
863

864 865 866 867 868
    result = 0;

error:
    if (result < 0) {
        virNetworkIpDefClear(def);
869
    }
870 871 872 873 874
    VIR_FREE(address);
    VIR_FREE(netmask);

    ctxt->node = save;
    return result;
875 876
}

877 878 879 880 881 882 883 884 885 886 887 888
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;
889
    xmlNodePtr bandwidth_node;
890 891 892 893 894 895 896 897 898 899 900 901 902 903
    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 &&
904
        (!(def->virtPortProfile = virNetDevVPortProfileParse(virtPortNode))))
905 906
        goto error;

907 908
    bandwidth_node = virXPathNode("./bandwidth", ctxt);
    if (bandwidth_node &&
909
        !(def->bandwidth = virNetDevBandwidthParse(bandwidth_node))) {
910 911 912
        goto error;
    }

913 914 915 916 917 918 919 920 921 922 923
    result = 0;
error:
    if (result < 0) {
        virPortGroupDefClear(def);
    }
    VIR_FREE(isDefault);

    ctxt->node = save;
    return result;
}

924
static virNetworkDefPtr
925
virNetworkDefParseXML(xmlXPathContextPtr ctxt)
926 927 928
{
    virNetworkDefPtr def;
    char *tmp;
929
    char *stp = NULL;
930
    xmlNodePtr *ipNodes = NULL;
931 932
    xmlNodePtr *portGroupNodes = NULL;
    xmlNodePtr *forwardIfNodes = NULL;
933
    xmlNodePtr *forwardPfNodes = NULL;
934
    xmlNodePtr dnsNode = NULL;
935 936
    xmlNodePtr virtPortNode = NULL;
    xmlNodePtr forwardNode = NULL;
937
    int nIps, nPortGroups, nForwardIfs, nForwardPfs;
938 939
    char *forwardDev = NULL;
    xmlNodePtr save = ctxt->node;
940
    xmlNodePtr bandwidthNode = NULL;
941 942

    if (VIR_ALLOC(def) < 0) {
943
        virReportOOMError();
944 945 946 947
        return NULL;
    }

    /* Extract network name */
948
    def->name = virXPathString("string(./name[1])", ctxt);
949
    if (!def->name) {
950
        virReportError(VIR_ERR_NO_NAME, NULL);
951 952 953 954
        goto error;
    }

    /* Extract network uuid */
955
    tmp = virXPathString("string(./uuid[1])", ctxt);
956
    if (!tmp) {
957
        if (virUUIDGenerate(def->uuid)) {
958 959
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Failed to generate UUID"));
960 961 962 963 964
            goto error;
        }
    } else {
        if (virUUIDParse(tmp, def->uuid) < 0) {
            VIR_FREE(tmp);
965 966
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("malformed uuid element"));
967 968 969 970 971
            goto error;
        }
        VIR_FREE(tmp);
    }

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

975
    if ((bandwidthNode = virXPathNode("./bandwidth", ctxt)) != NULL &&
976
        (def->bandwidth = virNetDevBandwidthParse(bandwidthNode)) == NULL)
977 978
        goto error;

979
    /* Parse bridge information */
980
    def->bridge = virXPathString("string(./bridge[1]/@name)", ctxt);
981
    stp = virXPathString("string(./bridge[1]/@stp)", ctxt);
982

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

986 987
    tmp = virXPathString("string(./mac[1]/@address)", ctxt);
    if (tmp) {
988
        if (virMacAddrParse(tmp, &def->mac) < 0) {
989 990 991
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid bridge mac address '%s' in network '%s'"),
                           tmp, def->name);
992 993 994
            VIR_FREE(tmp);
            goto error;
        }
995
        if (virMacAddrIsMulticast(&def->mac)) {
996 997 998
            virReportError(VIR_ERR_XML_ERROR,
                           _("Invalid multicast bridge mac address '%s' in network '%s'"),
                           tmp, def->name);
999 1000 1001
            VIR_FREE(tmp);
            goto error;
        }
1002 1003 1004 1005
        VIR_FREE(tmp);
        def->mac_specified = true;
    }

1006 1007
    dnsNode = virXPathNode("./dns", ctxt);
    if (dnsNode != NULL) {
1008
        if (virNetworkDNSDefParseXML(&def->dns, dnsNode, ctxt) < 0)
1009 1010 1011
            goto error;
    }

1012 1013
    virtPortNode = virXPathNode("./virtualport", ctxt);
    if (virtPortNode &&
1014
        (!(def->virtPortProfile = virNetDevVPortProfileParse(virtPortNode))))
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
        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);

1040
    nIps = virXPathNodeSet("./ip", ctxt, &ipNodes);
1041 1042 1043
    if (nIps < 0)
        goto error;

1044 1045
    if (nIps > 0) {
        int ii;
1046

1047 1048 1049
        /* allocate array to hold all the addrs */
        if (VIR_ALLOC_N(def->ips, nIps) < 0) {
            virReportOOMError();
1050 1051
            goto error;
        }
1052 1053 1054 1055 1056 1057 1058
        /* 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++;
1059
        }
1060
    }
E
Eric Blake 已提交
1061
    VIR_FREE(ipNodes);
1062

1063 1064 1065 1066 1067 1068 1069
    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);
1070 1071
        if (tmp) {
            if ((def->forwardType = virNetworkForwardTypeFromString(tmp)) < 0) {
1072 1073
                virReportError(VIR_ERR_XML_ERROR,
                               _("unknown forwarding type '%s'"), tmp);
1074 1075 1076 1077 1078 1079 1080 1081
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        } else {
            def->forwardType = VIR_NETWORK_FORWARD_NAT;
        }

1082
        forwardDev = virXPathString("string(./@dev)", ctxt);
1083

1084 1085
        /* all of these modes can use a pool of physical interfaces */
        nForwardIfs = virXPathNodeSet("./interface", ctxt, &forwardIfNodes);
1086 1087 1088
        nForwardPfs = virXPathNodeSet("./pf", ctxt, &forwardPfNodes);

        if (nForwardIfs < 0 || nForwardPfs < 0) {
1089
            virReportError(VIR_ERR_XML_ERROR, "%s",
1090
                           _("No interface pool or SRIOV physical device given"));
1091
            goto error;
1092 1093 1094 1095 1096 1097 1098 1099 1100
        }

        if (nForwardPfs == 1) {
            if (VIR_ALLOC_N(def->forwardPfs, nForwardPfs) < 0) {
                virReportOOMError();
                goto error;
            }

            if (forwardDev) {
1101
                virReportError(VIR_ERR_XML_ERROR, "%s",
1102
                               _("A forward Dev should not be used when using a SRIOV PF"));
1103 1104
                goto error;
            }
1105

1106 1107
            forwardDev = virXMLPropString(*forwardPfNodes, "dev");
            if (!forwardDev) {
1108 1109 1110
                virReportError(VIR_ERR_XML_ERROR,
                               _("Missing required dev attribute in network '%s' pf element"),
                               def->name);
1111 1112 1113 1114 1115 1116 1117 1118
                goto error;
            }

            def->forwardPfs->usageCount = 0;
            def->forwardPfs->dev = forwardDev;
            forwardDev = NULL;
            def->nForwardPfs++;
        } else if (nForwardPfs > 1) {
1119
            virReportError(VIR_ERR_XML_ERROR, "%s",
1120
                           _("Use of more than one physical interface is not allowed"));
1121 1122 1123
            goto error;
        }
        if (nForwardIfs > 0 || forwardDev) {
1124
            int ii;
1125

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
            /* 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) {
1143 1144 1145
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Missing required dev attribute in network '%s' forward interface element"),
                                   def->name);
1146 1147 1148 1149 1150 1151 1152
                    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)) {
1153 1154 1155 1156
                        virReportError(VIR_ERR_XML_ERROR,
                                       _("forward dev '%s' must match first interface element dev '%s' in network '%s'"),
                                       def->forwardIfs[0].dev,
                                       forwardDev, def->name);
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
                        goto error;
                    }
                    VIR_FREE(forwardDev);
                    continue;
                }

                def->forwardIfs[ii].dev = forwardDev;
                forwardDev = NULL;
                def->forwardIfs[ii].usageCount = 0;
                def->nForwardIfs++;
            }
        }
1169 1170
        VIR_FREE(forwardDev);
        VIR_FREE(forwardPfNodes);
1171 1172 1173 1174 1175 1176 1177 1178 1179
        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) {
1180 1181 1182 1183
                virReportError(VIR_ERR_XML_ERROR,
                               _("%s forwarding requested, but no IP address provided for network '%s'"),
                               virNetworkForwardTypeToString(def->forwardType),
                               def->name);
1184 1185 1186
                goto error;
            }
            if (def->nForwardIfs > 1) {
1187 1188 1189
                virReportError(VIR_ERR_XML_ERROR,
                               _("multiple forwarding interfaces specified for network '%s', only one is supported"),
                               def->name);
1190 1191 1192 1193 1194 1195 1196 1197
                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) {
1198 1199 1200 1201
                virReportError(VIR_ERR_XML_ERROR,
                               _("bridge name not allowed in %s mode (network '%s')"),
                               virNetworkForwardTypeToString(def->forwardType),
                               def->name);
1202 1203 1204 1205 1206
                goto error;
            }
            /* fall through to next case */
        case VIR_NETWORK_FORWARD_BRIDGE:
            if (def->delay || stp) {
1207 1208 1209 1210
                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);
1211 1212 1213 1214 1215 1216 1217
                goto error;
            }
            break;
        }
    }
    VIR_FREE(stp);
    ctxt->node = save;
1218 1219 1220
    return def;

 error:
1221
    VIR_FREE(stp);
1222
    virNetworkDefFree(def);
E
Eric Blake 已提交
1223
    VIR_FREE(ipNodes);
1224 1225
    VIR_FREE(portGroupNodes);
    VIR_FREE(forwardIfNodes);
1226
    VIR_FREE(forwardPfNodes);
1227 1228
    VIR_FREE(forwardDev);
    ctxt->node = save;
1229 1230 1231
    return NULL;
}

J
Jiri Denemark 已提交
1232 1233 1234
static virNetworkDefPtr
virNetworkDefParse(const char *xmlStr,
                   const char *filename)
1235
{
J
Jiri Denemark 已提交
1236
    xmlDocPtr xml;
1237
    virNetworkDefPtr def = NULL;
1238

1239
    if ((xml = virXMLParse(filename, xmlStr, _("(network_definition)")))) {
J
Jiri Denemark 已提交
1240 1241
        def = virNetworkDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1242 1243 1244 1245 1246
    }

    return def;
}

J
Jiri Denemark 已提交
1247
virNetworkDefPtr virNetworkDefParseString(const char *xmlStr)
1248
{
J
Jiri Denemark 已提交
1249 1250
    return virNetworkDefParse(xmlStr, NULL);
}
1251

J
Jiri Denemark 已提交
1252 1253 1254
virNetworkDefPtr virNetworkDefParseFile(const char *filename)
{
    return virNetworkDefParse(NULL, filename);
1255 1256 1257
}


1258
virNetworkDefPtr virNetworkDefParseNode(xmlDocPtr xml,
1259 1260 1261 1262 1263 1264
                                        xmlNodePtr root)
{
    xmlXPathContextPtr ctxt = NULL;
    virNetworkDefPtr def = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "network")) {
1265 1266 1267 1268
        virReportError(VIR_ERR_XML_ERROR,
                       _("unexpected root element <%s>, "
                         "expecting <network>"),
                       root->name);
1269 1270 1271 1272 1273
        return NULL;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1274
        virReportOOMError();
1275 1276 1277 1278
        goto cleanup;
    }

    ctxt->node = root;
1279
    def = virNetworkDefParseXML(ctxt);
1280 1281 1282 1283 1284 1285

cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
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);
    }

1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
    for (i = 0 ; i < def->nsrvrecords ; i++) {
        if (def->srvrecords[i].service && def->srvrecords[i].protocol) {
            virBufferAsprintf(buf, "    <srv service='%s' protocol='%s'",
                                  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");
        }
    }

1325 1326 1327 1328
    if (def->nhosts) {
        int ii, j;

        for (ii = 0 ; ii < def->nhosts; ii++) {
1329
            char *ip = virSocketAddrFormat(&def->hosts[ii].ip);
1330 1331 1332 1333 1334 1335 1336 1337

            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");
1338
            VIR_FREE(ip);
1339 1340 1341
        }
    }

1342 1343 1344 1345 1346
    virBufferAddLit(buf, "  </dns>\n");
out:
    return result;
}

1347 1348 1349 1350 1351 1352 1353 1354 1355
static int
virNetworkIpDefFormat(virBufferPtr buf,
                      const virNetworkIpDefPtr def)
{
    int result = -1;

    virBufferAddLit(buf, "  <ip");

    if (def->family) {
1356
        virBufferAsprintf(buf, " family='%s'", def->family);
1357
    }
1358 1359
    if (VIR_SOCKET_ADDR_VALID(&def->address)) {
        char *addr = virSocketAddrFormat(&def->address);
1360 1361
        if (!addr)
            goto error;
1362
        virBufferAsprintf(buf, " address='%s'", addr);
1363 1364
        VIR_FREE(addr);
    }
1365 1366
    if (VIR_SOCKET_ADDR_VALID(&def->netmask)) {
        char *addr = virSocketAddrFormat(&def->netmask);
1367 1368
        if (!addr)
            goto error;
1369
        virBufferAsprintf(buf, " netmask='%s'", addr);
1370 1371 1372
        VIR_FREE(addr);
    }
    if (def->prefix > 0) {
1373
        virBufferAsprintf(buf," prefix='%u'", def->prefix);
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
    }
    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++) {
1385
            char *saddr = virSocketAddrFormat(&def->ranges[ii].start);
1386 1387
            if (!saddr)
                goto error;
1388
            char *eaddr = virSocketAddrFormat(&def->ranges[ii].end);
1389 1390 1391 1392
            if (!eaddr) {
                VIR_FREE(saddr);
                goto error;
            }
1393
            virBufferAsprintf(buf, "      <range start='%s' end='%s' />\n",
1394 1395 1396 1397 1398 1399 1400
                              saddr, eaddr);
            VIR_FREE(saddr);
            VIR_FREE(eaddr);
        }
        for (ii = 0 ; ii < def->nhosts ; ii++) {
            virBufferAddLit(buf, "      <host ");
            if (def->hosts[ii].mac)
1401
                virBufferAsprintf(buf, "mac='%s' ", def->hosts[ii].mac);
1402
            if (def->hosts[ii].name)
1403
                virBufferAsprintf(buf, "name='%s' ", def->hosts[ii].name);
1404 1405
            if (VIR_SOCKET_ADDR_VALID(&def->hosts[ii].ip)) {
                char *ipaddr = virSocketAddrFormat(&def->hosts[ii].ip);
1406 1407
                if (!ipaddr)
                    goto error;
1408
                virBufferAsprintf(buf, "ip='%s' ", ipaddr);
1409 1410 1411 1412 1413 1414 1415
                VIR_FREE(ipaddr);
            }
            virBufferAddLit(buf, "/>\n");
        }
        if (def->bootfile) {
            virBufferEscapeString(buf, "      <bootp file='%s' ",
                                  def->bootfile);
1416 1417
            if (VIR_SOCKET_ADDR_VALID(&def->bootserver)) {
                char *ipaddr = virSocketAddrFormat(&def->bootserver);
1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
                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;
}

1436
static int
1437 1438 1439 1440 1441 1442 1443 1444
virPortGroupDefFormat(virBufferPtr buf,
                      const virPortGroupDefPtr def)
{
    virBufferAsprintf(buf, "  <portgroup name='%s'", def->name);
    if (def->isDefault) {
        virBufferAddLit(buf, " default='yes'");
    }
    virBufferAddLit(buf, ">\n");
1445
    virBufferAdjustIndent(buf, 4);
1446 1447
    if (virNetDevVPortProfileFormat(def->virtPortProfile, buf) < 0)
        return -1;
1448
    virNetDevBandwidthFormat(def->bandwidth, buf);
1449
    virBufferAdjustIndent(buf, -4);
1450
    virBufferAddLit(buf, "  </portgroup>\n");
1451
    return 0;
1452 1453
}

1454
char *virNetworkDefFormat(const virNetworkDefPtr def, unsigned int flags)
1455 1456 1457 1458
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    unsigned char *uuid;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1459
    int ii;
1460 1461 1462 1463 1464 1465

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

    uuid = def->uuid;
    virUUIDFormat(uuid, uuidstr);
1466
    virBufferAsprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
1467 1468

    if (def->forwardType != VIR_NETWORK_FORWARD_NONE) {
1469 1470 1471
        const char *dev = NULL;
        if (!def->nForwardPfs)
            dev = virNetworkDefForwardIf(def, 0);
1472
        const char *mode = virNetworkForwardTypeToString(def->forwardType);
1473 1474

        if (!mode) {
1475 1476 1477
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown forward type %d in network '%s'"),
                           def->forwardType, def->name);
1478 1479 1480
            goto error;
        }
        virBufferAddLit(&buf, "  <forward");
1481
        virBufferEscapeString(&buf, " dev='%s'", dev);
1482
        virBufferAsprintf(&buf, " mode='%s'%s>\n", mode,
1483 1484 1485 1486 1487 1488
                          (def->nForwardIfs || def->nForwardPfs) ? "" : "/");

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

1490 1491
        if (def->nForwardIfs &&
            (!def->nForwardPfs || !(flags & VIR_NETWORK_XML_INACTIVE))) {
1492
            for (ii = 0; ii < def->nForwardIfs; ii++) {
1493 1494
                virBufferEscapeString(&buf, "    <interface dev='%s'/>\n",
                                      def->forwardIfs[ii].dev);
1495 1496
            }
        }
1497 1498
        if (def->nForwardPfs || def->nForwardIfs)
            virBufferAddLit(&buf, "  </forward>\n");
1499 1500
    }

1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
    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);
    }


1517 1518
    if (def->mac_specified) {
        char macaddr[VIR_MAC_STRING_BUFLEN];
1519
        virMacAddrFormat(&def->mac, macaddr);
1520
        virBufferAsprintf(&buf, "  <mac address='%s'/>\n", macaddr);
1521
    }
1522

1523
    if (def->domain)
1524
        virBufferAsprintf(&buf, "  <domain name='%s'/>\n", def->domain);
1525

1526 1527 1528
    if (virNetworkDNSDefFormat(&buf, def->dns) < 0)
        goto error;

1529
    virBufferAdjustIndent(&buf, 2);
1530
    if (virNetDevBandwidthFormat(def->bandwidth, &buf) < 0)
1531
        goto error;
1532
    virBufferAdjustIndent(&buf, -2);
1533

1534 1535 1536
    for (ii = 0; ii < def->nips; ii++) {
        if (virNetworkIpDefFormat(&buf, &def->ips[ii]) < 0)
            goto error;
1537 1538
    }

1539
    virBufferAdjustIndent(&buf, 2);
1540 1541
    if (virNetDevVPortProfileFormat(def->virtPortProfile, &buf) < 0)
        goto error;
1542
    virBufferAdjustIndent(&buf, -2);
1543 1544

    for (ii = 0; ii < def->nPortGroups; ii++)
1545 1546
        if (virPortGroupDefFormat(&buf, &def->portGroups[ii]) < 0)
            goto error;
1547

1548 1549 1550 1551 1552 1553 1554 1555
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
        goto no_memory;

    return virBufferContentAndReset(&buf);

 no_memory:
1556
    virReportOOMError();
1557
  error:
1558
    virBufferFreeAndReset(&buf);
1559 1560 1561
    return NULL;
}

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
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;
}

1578
int virNetworkSaveXML(const char *configDir,
1579 1580
                      virNetworkDefPtr def,
                      const char *xml)
1581
{
1582
    char *configFile = NULL;
1583
    int ret = -1;
1584

1585
    if ((configFile = virNetworkConfigFile(configDir, def->name)) == NULL)
1586 1587
        goto cleanup;

1588 1589
    if (virFileMakePath(configDir) < 0) {
        virReportSystemError(errno,
1590 1591
                             _("cannot create config directory '%s'"),
                             configDir);
1592 1593 1594
        goto cleanup;
    }

1595
    ret = virXMLSaveFile(configFile, def->name, "net-edit", xml);
1596 1597

 cleanup:
1598 1599 1600 1601
    VIR_FREE(configFile);
    return ret;
}

1602
int virNetworkSaveConfig(const char *configDir,
1603 1604 1605 1606 1607
                         virNetworkDefPtr def)
{
    int ret = -1;
    char *xml;

1608
    if (!(xml = virNetworkDefFormat(def, 0)))
1609 1610
        goto cleanup;

1611
    if (virNetworkSaveXML(configDir, def, xml))
1612 1613 1614 1615 1616
        goto cleanup;

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

1620

1621
virNetworkObjPtr virNetworkLoadConfig(virNetworkObjListPtr nets,
1622 1623
                                      const char *configDir,
                                      const char *autostartDir,
1624
                                      const char *name)
1625 1626 1627 1628 1629 1630
{
    char *configFile = NULL, *autostartLink = NULL;
    virNetworkDefPtr def = NULL;
    virNetworkObjPtr net;
    int autostart;

1631
    if ((configFile = virNetworkConfigFile(configDir, name)) == NULL)
1632
        goto error;
1633
    if ((autostartLink = virNetworkConfigFile(autostartDir, name)) == NULL)
1634 1635 1636 1637 1638
        goto error;

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

1639
    if (!(def = virNetworkDefParseFile(configFile)))
1640 1641
        goto error;

1642
    if (!STREQ(name, def->name)) {
1643 1644 1645 1646
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Network config filename '%s'"
                         " does not match network name '%s'"),
                       configFile, def->name);
1647 1648 1649
        goto error;
    }

1650 1651 1652 1653 1654 1655 1656 1657 1658 1659
    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;
    }
1660

1661
    if (!(net = virNetworkAssignDef(nets, def)))
1662 1663 1664
        goto error;

    net->autostart = autostart;
1665
    net->persistent = 1;
1666

1667 1668 1669
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);

1670 1671 1672 1673 1674 1675 1676 1677 1678
    return net;

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

1679
int virNetworkLoadAllConfigs(virNetworkObjListPtr nets,
1680 1681 1682 1683 1684 1685 1686 1687 1688
                             const char *configDir,
                             const char *autostartDir)
{
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(configDir))) {
        if (errno == ENOENT)
            return 0;
1689
        virReportSystemError(errno,
1690 1691
                             _("Failed to open dir '%s'"),
                             configDir);
1692 1693 1694 1695
        return -1;
    }

    while ((entry = readdir(dir))) {
1696 1697
        virNetworkObjPtr net;

1698 1699 1700
        if (entry->d_name[0] == '.')
            continue;

1701
        if (!virFileStripSuffix(entry->d_name, ".xml"))
1702 1703 1704 1705
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
1706
        net = virNetworkLoadConfig(nets,
1707 1708 1709 1710 1711
                                   configDir,
                                   autostartDir,
                                   entry->d_name);
        if (net)
            virNetworkObjUnlock(net);
1712 1713 1714 1715 1716 1717 1718
    }

    closedir(dir);

    return 0;
}

1719
int virNetworkDeleteConfig(const char *configDir,
1720
                           const char *autostartDir,
1721 1722
                           virNetworkObjPtr net)
{
1723 1724
    char *configFile = NULL;
    char *autostartLink = NULL;
R
Ryota Ozaki 已提交
1725
    int ret = -1;
1726

1727
    if ((configFile = virNetworkConfigFile(configDir, net->def->name)) == NULL)
1728
        goto error;
1729
    if ((autostartLink = virNetworkConfigFile(autostartDir, net->def->name)) == NULL)
1730
        goto error;
1731 1732

    /* Not fatal if this doesn't work */
1733
    unlink(autostartLink);
1734

1735
    if (unlink(configFile) < 0) {
1736
        virReportSystemError(errno,
1737
                             _("cannot remove config file '%s'"),
1738 1739
                             configFile);
        goto error;
1740 1741
    }

R
Ryota Ozaki 已提交
1742
    ret = 0;
1743 1744 1745 1746

error:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
R
Ryota Ozaki 已提交
1747
    return ret;
1748 1749
}

1750
char *virNetworkConfigFile(const char *dir,
1751 1752 1753 1754 1755
                           const char *name)
{
    char *ret = NULL;

    if (virAsprintf(&ret, "%s/%s.xml", dir, name) < 0) {
1756
        virReportOOMError();
1757 1758 1759 1760
        return NULL;
    }

    return ret;
1761
}
D
Daniel P. Berrange 已提交
1762

1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781
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;
}

1782
char *virNetworkAllocateBridge(const virNetworkObjListPtr nets,
1783
                               const char *template)
1784 1785 1786 1787 1788
{

    int id = 0;
    char *newname;

1789 1790 1791
    if (!template)
        template = "virbr%d";

1792
    do {
1793 1794 1795 1796 1797
        if (virAsprintf(&newname, template, id) < 0) {
            virReportOOMError();
            return NULL;
        }
        if (!virNetworkBridgeInUse(nets, newname, NULL)) {
1798 1799
            return newname;
        }
1800
        VIR_FREE(newname);
1801 1802

        id++;
1803
    } while (id <= MAX_BRIDGE_ID);
1804

1805 1806 1807
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("Bridge generation exceeded max id %d"),
                   MAX_BRIDGE_ID);
1808 1809 1810
    return NULL;
}

1811
int virNetworkSetBridgeName(const virNetworkObjListPtr nets,
1812 1813
                            virNetworkDefPtr def,
                            int check_collision) {
1814 1815 1816

    int ret = -1;

1817
    if (def->bridge && !strstr(def->bridge, "%d")) {
1818 1819 1820 1821 1822
        /* 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)) {
1823 1824 1825
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("bridge name '%s' already in use."),
                           def->bridge);
1826 1827 1828 1829
            goto error;
        }
    } else {
        /* Allocate a bridge name */
1830
        if (!(def->bridge = virNetworkAllocateBridge(nets, def->bridge)))
1831 1832 1833 1834 1835 1836 1837
            goto error;
    }

    ret = 0;
error:
    return ret;
}
1838

1839

1840 1841 1842 1843 1844 1845
void virNetworkSetBridgeMacAddr(virNetworkDefPtr def)
{
    if (!def->mac_specified) {
        /* if the bridge doesn't have a mac address explicitly defined,
         * autogenerate a random one.
         */
1846
        virMacAddrGenerate((unsigned char[]){ 0x52, 0x54, 0 },
1847
                           &def->mac);
1848 1849 1850 1851
        def->mac_specified = true;
    }
}

1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
/*
 * 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);
1878 1879 1880
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("network '%s' is already defined with uuid %s"),
                           vm->def->name, uuidstr);
1881 1882 1883 1884 1885 1886
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if VM is already active, refuse it */
            if (virNetworkObjIsActive(vm)) {
1887 1888 1889
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("network is already active as '%s'"),
                               vm->def->name);
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900
                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);
1901 1902 1903
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("network '%s' already exists with uuid %s"),
                           def->name, uuidstr);
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915
            goto cleanup;
        }
    }

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


1916 1917
void virNetworkObjLock(virNetworkObjPtr obj)
{
1918
    virMutexLock(&obj->lock);
1919 1920 1921 1922
}

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