network_conf.c 58.9 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 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 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
#define virNetworkReportError(code, ...)                                \
57
    virReportErrorHelper(VIR_FROM_NETWORK, code, __FILE__,              \
58
                         __FUNCTION__, __LINE__, __VA_ARGS__)
59

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

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

    return NULL;
}

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

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

    return NULL;
}


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

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

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
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);
}

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

154 155
void virNetworkDefFree(virNetworkDefPtr def)
{
156
    int ii;
157 158 159 160 161 162

    if (!def)
        return;

    VIR_FREE(def->name);
    VIR_FREE(def->bridge);
163
    VIR_FREE(def->domain);
164

165 166 167 168 169
    for (ii = 0 ; ii < def->nForwardPfs && def->forwardPfs ; ii++) {
        virNetworkForwardIfDefClear(&def->forwardPfs[ii]);
    }
    VIR_FREE(def->forwardPfs);

170 171 172 173 174
    for (ii = 0 ; ii < def->nForwardIfs && def->forwardIfs ; ii++) {
        virNetworkForwardIfDefClear(&def->forwardIfs[ii]);
    }
    VIR_FREE(def->forwardIfs);

175 176
    for (ii = 0 ; ii < def->nips && def->ips ; ii++) {
        virNetworkIpDefClear(&def->ips[ii]);
177
    }
178
    VIR_FREE(def->ips);
179

180 181 182 183 184
    for (ii = 0; ii < def->nPortGroups && def->portGroups; ii++) {
        virPortGroupDefClear(&def->portGroups[ii]);
    }
    VIR_FREE(def->portGroups);

185 186
    virNetworkDNSDefFree(def->dns);

187 188
    VIR_FREE(def->virtPortProfile);

189
    virNetDevBandwidthFree(def->bandwidth);
190

191 192 193 194 195 196 197 198 199 200 201
    VIR_FREE(def);
}

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

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

202 203
    virMutexDestroy(&net->lock);

204 205 206
    VIR_FREE(net);
}

207 208 209 210 211 212 213 214 215 216 217
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;
}

218
virNetworkObjPtr virNetworkAssignDef(virNetworkObjListPtr nets,
219 220 221 222
                                     const virNetworkDefPtr def)
{
    virNetworkObjPtr network;

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

        return network;
    }

    if (VIR_ALLOC(network) < 0) {
236
        virReportOOMError();
237 238
        return NULL;
    }
239
    if (virMutexInit(&network->lock) < 0) {
240
        virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
241 242 243 244
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(network);
        return NULL;
    }
245
    virNetworkObjLock(network);
246 247
    network->def = def;

248
    if (VIR_REALLOC_N(nets->objs, nets->count + 1) < 0) {
249
        virReportOOMError();
250 251 252 253 254 255
        VIR_FREE(network);
        return NULL;
    }

    nets->objs[nets->count] = network;
    nets->count++;
256 257 258 259 260

    return network;

}

261
void virNetworkRemoveInactive(virNetworkObjListPtr nets,
262 263
                              const virNetworkObjPtr net)
{
264
    unsigned int i;
265

266
    virNetworkObjUnlock(net);
267
    for (i = 0 ; i < nets->count ; i++) {
268
        virNetworkObjLock(nets->objs[i]);
269
        if (nets->objs[i] == net) {
270
            virNetworkObjUnlock(nets->objs[i]);
271
            virNetworkObjFree(nets->objs[i]);
272

273 274 275
            if (i < (nets->count - 1))
                memmove(nets->objs + i, nets->objs + i + 1,
                        sizeof(*(nets->objs)) * (nets->count - (i + 1)));
276

277 278 279 280 281 282 283
            if (VIR_REALLOC_N(nets->objs, nets->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            nets->count--;

            break;
        }
284
        virNetworkObjUnlock(nets->objs[i]);
285
    }
286 287
}

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

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

359
    return virSocketAddrPrefixToNetmask(virNetworkIpDefPrefix(def), netmask,
360
                                        VIR_SOCKET_ADDR_FAMILY(&def->address));
L
Laine Stump 已提交
361 362
}

363 364

static int
365 366
virNetworkDHCPRangeDefParseXML(const char *networkName,
                               virNetworkIpDefPtr def,
367 368
                               xmlNodePtr node)
{
369 370 371 372 373

    xmlNodePtr cur;

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

380
            if (!(start = virXMLPropString(cur, "start"))) {
381 382 383
                cur = cur->next;
                continue;
            }
384 385
            if (!(end = virXMLPropString(cur, "end"))) {
                VIR_FREE(start);
386
                cur = cur->next;
387 388 389
                continue;
            }

390
            if (virSocketAddrParse(&saddr, start, AF_UNSPEC) < 0) {
391 392
                VIR_FREE(start);
                VIR_FREE(end);
393
                return -1;
394
            }
395
            if (virSocketAddrParse(&eaddr, end, AF_UNSPEC) < 0) {
396 397
                VIR_FREE(start);
                VIR_FREE(end);
398
                return -1;
399 400
            }

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

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

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

        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "bootp")) {
486 487
            char *file;
            char *server;
488
            virSocketAddr inaddr;
489
            memset(&inaddr, 0, sizeof(inaddr));
490

491
            if (!(file = virXMLPropString(cur, "file"))) {
492 493 494
                cur = cur->next;
                continue;
            }
495
            server = virXMLPropString(cur, "server");
496

497
            if (server &&
498
                virSocketAddrParse(&inaddr, server, AF_UNSPEC) < 0) {
E
Eric Blake 已提交
499 500
                VIR_FREE(file);
                VIR_FREE(server);
501
                return -1;
E
Eric Blake 已提交
502
            }
503

504
            def->bootfile = file;
505
            def->bootserver = inaddr;
E
Eric Blake 已提交
506
            VIR_FREE(server);
507 508 509 510 511 512 513 514
        }

        cur = cur->next;
    }

    return 0;
}

515 516 517 518 519 520 521 522 523 524
static int
virNetworkDNSHostsDefParseXML(virNetworkDNSDefPtr def,
                              xmlNodePtr node)
{
    xmlNodePtr cur;
    char *ip;
    virSocketAddr inaddr;
    int ret = -1;

    if (!(ip = virXMLPropString(node, "ip")) ||
525
        (virSocketAddrParse(&inaddr, ip, AF_UNSPEC) < 0)) {
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 568 569 570 571
        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;
}

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
static int
virNetworkDNSSrvDefParseXML(virNetworkDNSDefPtr def,
                            xmlNodePtr cur,
                            xmlXPathContextPtr ctxt)
{
    char *domain;
    char *service;
    char *protocol;
    char *target;
    int port;
    int priority;
    int weight;
    int ret = 0;

    if (!(service = virXMLPropString(cur, "service"))) {
        virNetworkReportError(VIR_ERR_XML_DETAIL,
                              "%s", _("Missing required service attribute in dns srv record"));
        goto error;
    }

    if (strlen(service) > DNS_RECORD_LENGTH_SRV) {
        char *name = NULL;

        virAsprintf(&name, _("Service name is too long, limit is %d bytes"), DNS_RECORD_LENGTH_SRV);
        virNetworkReportError(VIR_ERR_XML_DETAIL,
                              "%s", name);
E
Eric Blake 已提交
598
        VIR_FREE(name);
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
        goto error;
    }

    if (!(protocol = virXMLPropString(cur, "protocol"))) {
        virNetworkReportError(VIR_ERR_XML_DETAIL,
                              _("Missing required protocol attribute in dns srv record '%s'"), service);
        goto error;
    }

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

666 667
static int
virNetworkDNSDefParseXML(virNetworkDNSDefPtr *dnsdef,
668 669
                         xmlNodePtr node,
                         xmlXPathContextPtr ctxt)
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
{
    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;
713 714 715 716 717
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "srv")) {
            ret = virNetworkDNSSrvDefParseXML(def, cur, ctxt);
            if (ret < 0)
                goto error;
718 719 720 721 722
        } else if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "host")) {
            ret = virNetworkDNSHostsDefParseXML(def, cur);
            if (ret < 0)
                goto error;
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
        }

        cur = cur->next;
    }

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

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

777
    }
778

779 780
    /* validate family vs. address */
    if (def->family == NULL) {
781 782
        if (!(VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET) ||
              VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_UNSPEC))) {
783
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
784
                                  _("no family specified for non-IPv4 address '%s' in network '%s'"),
785 786 787 788
                                  address, networkName);
            goto error;
        }
    } else if (STREQ(def->family, "ipv4")) {
789
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
790 791 792 793 794 795
            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")) {
796
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6)) {
797 798 799 800 801 802 803 804 805 806 807
            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;
    }
808

809 810 811 812 813 814 815 816 817 818
    /* 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;
        }

819
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) {
820 821 822 823 824 825 826 827 828 829 830 831 832 833
            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;
        }

834
        if (virSocketAddrParse(&def->netmask, netmask, AF_UNSPEC) < 0)
835 836
            goto error;

837
        if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->netmask, AF_INET)) {
838 839 840 841 842 843 844
            virNetworkReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                  _("network '%s' has invalid netmask '%s' for address '%s' (both must be IPv4)"),
                                  networkName, netmask, address);
            goto error;
        }
    }

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

867
            cur = cur->next;
868
        }
869
    }
870

871 872 873 874 875
    result = 0;

error:
    if (result < 0) {
        virNetworkIpDefClear(def);
876
    }
877 878 879 880 881
    VIR_FREE(address);
    VIR_FREE(netmask);

    ctxt->node = save;
    return result;
882 883
}

884 885 886 887 888 889 890 891 892 893 894 895
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;
896
    xmlNodePtr bandwidth_node;
897 898 899 900 901 902 903 904 905 906 907 908 909 910
    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 &&
911
        (!(def->virtPortProfile = virNetDevVPortProfileParse(virtPortNode))))
912 913
        goto error;

914 915
    bandwidth_node = virXPathNode("./bandwidth", ctxt);
    if (bandwidth_node &&
916
        !(def->bandwidth = virNetDevBandwidthParse(bandwidth_node))) {
917 918 919
        goto error;
    }

920 921 922 923 924 925 926 927 928 929 930
    result = 0;
error:
    if (result < 0) {
        virPortGroupDefClear(def);
    }
    VIR_FREE(isDefault);

    ctxt->node = save;
    return result;
}

931
static virNetworkDefPtr
932
virNetworkDefParseXML(xmlXPathContextPtr ctxt)
933 934 935
{
    virNetworkDefPtr def;
    char *tmp;
936
    char *stp = NULL;
937
    xmlNodePtr *ipNodes = NULL;
938 939
    xmlNodePtr *portGroupNodes = NULL;
    xmlNodePtr *forwardIfNodes = NULL;
940
    xmlNodePtr *forwardPfNodes = NULL;
941
    xmlNodePtr dnsNode = NULL;
942 943
    xmlNodePtr virtPortNode = NULL;
    xmlNodePtr forwardNode = NULL;
944
    int nIps, nPortGroups, nForwardIfs, nForwardPfs;
945 946
    char *forwardDev = NULL;
    xmlNodePtr save = ctxt->node;
947
    xmlNodePtr bandwidthNode = NULL;
948 949

    if (VIR_ALLOC(def) < 0) {
950
        virReportOOMError();
951 952 953 954
        return NULL;
    }

    /* Extract network name */
955
    def->name = virXPathString("string(./name[1])", ctxt);
956
    if (!def->name) {
957
        virNetworkReportError(VIR_ERR_NO_NAME, NULL);
958 959 960 961
        goto error;
    }

    /* Extract network uuid */
962
    tmp = virXPathString("string(./uuid[1])", ctxt);
963
    if (!tmp) {
964
        if (virUUIDGenerate(def->uuid)) {
965
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
966
                                  "%s", _("Failed to generate UUID"));
967 968 969 970 971
            goto error;
        }
    } else {
        if (virUUIDParse(tmp, def->uuid) < 0) {
            VIR_FREE(tmp);
972
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
973 974 975 976 977 978
                                  "%s", _("malformed uuid element"));
            goto error;
        }
        VIR_FREE(tmp);
    }

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

982
    if ((bandwidthNode = virXPathNode("./bandwidth", ctxt)) != NULL &&
983
        (def->bandwidth = virNetDevBandwidthParse(bandwidthNode)) == NULL)
984 985
        goto error;

986
    /* Parse bridge information */
987
    def->bridge = virXPathString("string(./bridge[1]/@name)", ctxt);
988
    stp = virXPathString("string(./bridge[1]/@stp)", ctxt);
989

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

993 994
    tmp = virXPathString("string(./mac[1]/@address)", ctxt);
    if (tmp) {
995
        if (virMacAddrParse(tmp, def->mac) < 0) {
996 997 998 999 1000 1001
            virNetworkReportError(VIR_ERR_XML_ERROR,
                                  _("Invalid bridge mac address '%s' in network '%s'"),
                                  tmp, def->name);
            VIR_FREE(tmp);
            goto error;
        }
1002 1003 1004 1005 1006 1007 1008
        if (virMacAddrIsMulticast(def->mac)) {
            virNetworkReportError(VIR_ERR_XML_ERROR,
                                 _("Invalid multicast bridge mac address '%s' in network '%s'"),
                                 tmp, def->name);
            VIR_FREE(tmp);
            goto error;
        }
1009 1010 1011 1012
        VIR_FREE(tmp);
        def->mac_specified = true;
    }

1013 1014
    dnsNode = virXPathNode("./dns", ctxt);
    if (dnsNode != NULL) {
1015
        if (virNetworkDNSDefParseXML(&def->dns, dnsNode, ctxt) < 0)
1016 1017 1018
            goto error;
    }

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

1047
    nIps = virXPathNodeSet("./ip", ctxt, &ipNodes);
1048 1049 1050
    if (nIps < 0)
        goto error;

1051 1052
    if (nIps > 0) {
        int ii;
1053

1054 1055 1056
        /* allocate array to hold all the addrs */
        if (VIR_ALLOC_N(def->ips, nIps) < 0) {
            virReportOOMError();
1057 1058
            goto error;
        }
1059 1060 1061 1062 1063 1064 1065
        /* 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++;
1066
        }
1067
    }
E
Eric Blake 已提交
1068
    VIR_FREE(ipNodes);
1069

1070 1071 1072 1073 1074 1075 1076
    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);
1077 1078
        if (tmp) {
            if ((def->forwardType = virNetworkForwardTypeFromString(tmp)) < 0) {
1079
                virNetworkReportError(VIR_ERR_XML_ERROR,
1080 1081 1082 1083 1084 1085 1086 1087 1088
                                      _("unknown forwarding type '%s'"), tmp);
                VIR_FREE(tmp);
                goto error;
            }
            VIR_FREE(tmp);
        } else {
            def->forwardType = VIR_NETWORK_FORWARD_NAT;
        }

1089
        forwardDev = virXPathString("string(./@dev)", ctxt);
1090

1091 1092
        /* all of these modes can use a pool of physical interfaces */
        nForwardIfs = virXPathNodeSet("./interface", ctxt, &forwardIfNodes);
1093 1094 1095 1096 1097
        nForwardPfs = virXPathNodeSet("./pf", ctxt, &forwardPfNodes);

        if (nForwardIfs < 0 || nForwardPfs < 0) {
            virNetworkReportError(VIR_ERR_XML_ERROR,
                                  _("No interface pool or SRIOV physical device given"));
1098
            goto error;
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        }

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

            if (forwardDev) {
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("A forward Dev should not be used when using a SRIOV PF"));
                goto error;
            }
1112

1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
            forwardDev = virXMLPropString(*forwardPfNodes, "dev");
            if (!forwardDev) {
                virNetworkReportError(VIR_ERR_XML_ERROR,
                                      _("Missing required dev attribute in network '%s' pf element"),
                                      def->name);
                goto error;
            }

            def->forwardPfs->usageCount = 0;
            def->forwardPfs->dev = forwardDev;
            forwardDev = NULL;
            def->nForwardPfs++;
        } else if (nForwardPfs > 1) {
            virNetworkReportError(VIR_ERR_XML_ERROR,
                                  _("Use of more than one physical interface is not allowed"));
            goto error;
        }
        if (nForwardIfs > 0 || forwardDev) {
1131
            int ii;
1132

1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
            /* 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++;
            }
        }
1176 1177
        VIR_FREE(forwardDev);
        VIR_FREE(forwardPfNodes);
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        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;
1225 1226 1227
    return def;

 error:
1228
    VIR_FREE(stp);
1229
    virNetworkDefFree(def);
E
Eric Blake 已提交
1230
    VIR_FREE(ipNodes);
1231 1232
    VIR_FREE(portGroupNodes);
    VIR_FREE(forwardIfNodes);
1233
    VIR_FREE(forwardPfNodes);
1234 1235
    VIR_FREE(forwardDev);
    ctxt->node = save;
1236 1237 1238
    return NULL;
}

J
Jiri Denemark 已提交
1239 1240 1241
static virNetworkDefPtr
virNetworkDefParse(const char *xmlStr,
                   const char *filename)
1242
{
J
Jiri Denemark 已提交
1243
    xmlDocPtr xml;
1244
    virNetworkDefPtr def = NULL;
1245

1246
    if ((xml = virXMLParse(filename, xmlStr, _("(network_definition)")))) {
J
Jiri Denemark 已提交
1247 1248
        def = virNetworkDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1249 1250 1251 1252 1253
    }

    return def;
}

J
Jiri Denemark 已提交
1254
virNetworkDefPtr virNetworkDefParseString(const char *xmlStr)
1255
{
J
Jiri Denemark 已提交
1256 1257
    return virNetworkDefParse(xmlStr, NULL);
}
1258

J
Jiri Denemark 已提交
1259 1260 1261
virNetworkDefPtr virNetworkDefParseFile(const char *filename)
{
    return virNetworkDefParse(NULL, filename);
1262 1263 1264
}


1265
virNetworkDefPtr virNetworkDefParseNode(xmlDocPtr xml,
1266 1267 1268 1269 1270 1271
                                        xmlNodePtr root)
{
    xmlXPathContextPtr ctxt = NULL;
    virNetworkDefPtr def = NULL;

    if (!xmlStrEqual(root->name, BAD_CAST "network")) {
1272 1273 1274 1275
        virNetworkReportError(VIR_ERR_XML_ERROR,
                              _("unexpected root element <%s>, "
                                "expecting <network>"),
                              root->name);
1276 1277 1278 1279 1280
        return NULL;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1281
        virReportOOMError();
1282 1283 1284 1285
        goto cleanup;
    }

    ctxt->node = root;
1286
    def = virNetworkDefParseXML(ctxt);
1287 1288 1289 1290 1291 1292

cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310
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);
    }

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
    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");
        }
    }

1332 1333 1334 1335
    if (def->nhosts) {
        int ii, j;

        for (ii = 0 ; ii < def->nhosts; ii++) {
1336
            char *ip = virSocketAddrFormat(&def->hosts[ii].ip);
1337 1338 1339 1340 1341 1342 1343 1344

            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");
1345
            VIR_FREE(ip);
1346 1347 1348
        }
    }

1349 1350 1351 1352 1353
    virBufferAddLit(buf, "  </dns>\n");
out:
    return result;
}

1354 1355 1356 1357 1358 1359 1360 1361 1362
static int
virNetworkIpDefFormat(virBufferPtr buf,
                      const virNetworkIpDefPtr def)
{
    int result = -1;

    virBufferAddLit(buf, "  <ip");

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

1443
static int
1444 1445 1446 1447 1448 1449 1450 1451
virPortGroupDefFormat(virBufferPtr buf,
                      const virPortGroupDefPtr def)
{
    virBufferAsprintf(buf, "  <portgroup name='%s'", def->name);
    if (def->isDefault) {
        virBufferAddLit(buf, " default='yes'");
    }
    virBufferAddLit(buf, ">\n");
1452
    virBufferAdjustIndent(buf, 4);
1453 1454
    if (virNetDevVPortProfileFormat(def->virtPortProfile, buf) < 0)
        return -1;
1455
    virNetDevBandwidthFormat(def->bandwidth, buf);
1456
    virBufferAdjustIndent(buf, -4);
1457
    virBufferAddLit(buf, "  </portgroup>\n");
1458
    return 0;
1459 1460
}

1461
char *virNetworkDefFormat(const virNetworkDefPtr def, unsigned int flags)
1462 1463 1464 1465
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    unsigned char *uuid;
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1466
    int ii;
1467 1468 1469 1470 1471 1472

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

    uuid = def->uuid;
    virUUIDFormat(uuid, uuidstr);
1473
    virBufferAsprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
1474 1475

    if (def->forwardType != VIR_NETWORK_FORWARD_NONE) {
1476 1477 1478
        const char *dev = NULL;
        if (!def->nForwardPfs)
            dev = virNetworkDefForwardIf(def, 0);
1479
        const char *mode = virNetworkForwardTypeToString(def->forwardType);
1480 1481 1482 1483 1484 1485 1486 1487

        if (!mode) {
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
                                  _("Unknown forward type %d in network '%s'"),
                                  def->forwardType, def->name);
            goto error;
        }
        virBufferAddLit(&buf, "  <forward");
1488
        virBufferEscapeString(&buf, " dev='%s'", dev);
1489
        virBufferAsprintf(&buf, " mode='%s'%s>\n", mode,
1490 1491 1492 1493 1494 1495
                          (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);
1496

1497 1498
        if (def->nForwardIfs &&
            (!def->nForwardPfs || !(flags & VIR_NETWORK_XML_INACTIVE))) {
1499
            for (ii = 0; ii < def->nForwardIfs; ii++) {
1500 1501
                virBufferEscapeString(&buf, "    <interface dev='%s'/>\n",
                                      def->forwardIfs[ii].dev);
1502 1503
            }
        }
1504 1505
        if (def->nForwardPfs || def->nForwardIfs)
            virBufferAddLit(&buf, "  </forward>\n");
1506 1507
    }

1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
    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);
    }


1524 1525
    if (def->mac_specified) {
        char macaddr[VIR_MAC_STRING_BUFLEN];
1526
        virMacAddrFormat(def->mac, macaddr);
1527
        virBufferAsprintf(&buf, "  <mac address='%s'/>\n", macaddr);
1528
    }
1529

1530
    if (def->domain)
1531
        virBufferAsprintf(&buf, "  <domain name='%s'/>\n", def->domain);
1532

1533 1534 1535
    if (virNetworkDNSDefFormat(&buf, def->dns) < 0)
        goto error;

1536
    virBufferAdjustIndent(&buf, 2);
1537
    if (virNetDevBandwidthFormat(def->bandwidth, &buf) < 0)
1538
        goto error;
1539
    virBufferAdjustIndent(&buf, -2);
1540

1541 1542 1543
    for (ii = 0; ii < def->nips; ii++) {
        if (virNetworkIpDefFormat(&buf, &def->ips[ii]) < 0)
            goto error;
1544 1545
    }

1546
    virBufferAdjustIndent(&buf, 2);
1547 1548
    if (virNetDevVPortProfileFormat(def->virtPortProfile, &buf) < 0)
        goto error;
1549
    virBufferAdjustIndent(&buf, -2);
1550 1551

    for (ii = 0; ii < def->nPortGroups; ii++)
1552 1553
        if (virPortGroupDefFormat(&buf, &def->portGroups[ii]) < 0)
            goto error;
1554

1555 1556 1557 1558 1559 1560 1561 1562
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
        goto no_memory;

    return virBufferContentAndReset(&buf);

 no_memory:
1563
    virReportOOMError();
1564
  error:
1565
    virBufferFreeAndReset(&buf);
1566 1567 1568
    return NULL;
}

1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584
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;
}

1585
int virNetworkSaveXML(const char *configDir,
1586 1587
                      virNetworkDefPtr def,
                      const char *xml)
1588
{
1589
    char *configFile = NULL;
1590
    int ret = -1;
1591

1592
    if ((configFile = virNetworkConfigFile(configDir, def->name)) == NULL)
1593 1594
        goto cleanup;

1595 1596
    if (virFileMakePath(configDir) < 0) {
        virReportSystemError(errno,
1597 1598
                             _("cannot create config directory '%s'"),
                             configDir);
1599 1600 1601
        goto cleanup;
    }

1602
    ret = virXMLSaveFile(configFile, def->name, "net-edit", xml);
1603 1604

 cleanup:
1605 1606 1607 1608
    VIR_FREE(configFile);
    return ret;
}

1609
int virNetworkSaveConfig(const char *configDir,
1610 1611 1612 1613 1614
                         virNetworkDefPtr def)
{
    int ret = -1;
    char *xml;

1615
    if (!(xml = virNetworkDefFormat(def, 0)))
1616 1617
        goto cleanup;

1618
    if (virNetworkSaveXML(configDir, def, xml))
1619 1620 1621 1622 1623
        goto cleanup;

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

1627

1628
virNetworkObjPtr virNetworkLoadConfig(virNetworkObjListPtr nets,
1629 1630
                                      const char *configDir,
                                      const char *autostartDir,
1631
                                      const char *name)
1632 1633 1634 1635 1636 1637
{
    char *configFile = NULL, *autostartLink = NULL;
    virNetworkDefPtr def = NULL;
    virNetworkObjPtr net;
    int autostart;

1638
    if ((configFile = virNetworkConfigFile(configDir, name)) == NULL)
1639
        goto error;
1640
    if ((autostartLink = virNetworkConfigFile(autostartDir, name)) == NULL)
1641 1642 1643 1644 1645
        goto error;

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

1646
    if (!(def = virNetworkDefParseFile(configFile)))
1647 1648
        goto error;

1649
    if (!STREQ(name, def->name)) {
1650
        virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
1651 1652 1653 1654 1655 1656
                              _("Network config filename '%s'"
                                " does not match network name '%s'"),
                              configFile, def->name);
        goto error;
    }

1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
    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;
    }
1667

1668
    if (!(net = virNetworkAssignDef(nets, def)))
1669 1670 1671
        goto error;

    net->autostart = autostart;
1672
    net->persistent = 1;
1673

1674 1675 1676
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);

1677 1678 1679 1680 1681 1682 1683 1684 1685
    return net;

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

1686
int virNetworkLoadAllConfigs(virNetworkObjListPtr nets,
1687 1688 1689 1690 1691 1692 1693 1694 1695
                             const char *configDir,
                             const char *autostartDir)
{
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(configDir))) {
        if (errno == ENOENT)
            return 0;
1696
        virReportSystemError(errno,
1697 1698
                             _("Failed to open dir '%s'"),
                             configDir);
1699 1700 1701 1702
        return -1;
    }

    while ((entry = readdir(dir))) {
1703 1704
        virNetworkObjPtr net;

1705 1706 1707
        if (entry->d_name[0] == '.')
            continue;

1708
        if (!virFileStripSuffix(entry->d_name, ".xml"))
1709 1710 1711 1712
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
1713
        net = virNetworkLoadConfig(nets,
1714 1715 1716 1717 1718
                                   configDir,
                                   autostartDir,
                                   entry->d_name);
        if (net)
            virNetworkObjUnlock(net);
1719 1720 1721 1722 1723 1724 1725
    }

    closedir(dir);

    return 0;
}

1726
int virNetworkDeleteConfig(const char *configDir,
1727
                           const char *autostartDir,
1728 1729
                           virNetworkObjPtr net)
{
1730 1731
    char *configFile = NULL;
    char *autostartLink = NULL;
R
Ryota Ozaki 已提交
1732
    int ret = -1;
1733

1734
    if ((configFile = virNetworkConfigFile(configDir, net->def->name)) == NULL)
1735
        goto error;
1736
    if ((autostartLink = virNetworkConfigFile(autostartDir, net->def->name)) == NULL)
1737
        goto error;
1738 1739

    /* Not fatal if this doesn't work */
1740
    unlink(autostartLink);
1741

1742
    if (unlink(configFile) < 0) {
1743
        virReportSystemError(errno,
1744
                             _("cannot remove config file '%s'"),
1745 1746
                             configFile);
        goto error;
1747 1748
    }

R
Ryota Ozaki 已提交
1749
    ret = 0;
1750 1751 1752 1753

error:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
R
Ryota Ozaki 已提交
1754
    return ret;
1755 1756
}

1757
char *virNetworkConfigFile(const char *dir,
1758 1759 1760 1761 1762
                           const char *name)
{
    char *ret = NULL;

    if (virAsprintf(&ret, "%s/%s.xml", dir, name) < 0) {
1763
        virReportOOMError();
1764 1765 1766 1767
        return NULL;
    }

    return ret;
1768
}
D
Daniel P. Berrange 已提交
1769

1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
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;
}

1789
char *virNetworkAllocateBridge(const virNetworkObjListPtr nets,
1790
                               const char *template)
1791 1792 1793 1794 1795
{

    int id = 0;
    char *newname;

1796 1797 1798
    if (!template)
        template = "virbr%d";

1799
    do {
1800 1801 1802 1803 1804
        if (virAsprintf(&newname, template, id) < 0) {
            virReportOOMError();
            return NULL;
        }
        if (!virNetworkBridgeInUse(nets, newname, NULL)) {
1805 1806
            return newname;
        }
1807
        VIR_FREE(newname);
1808 1809

        id++;
1810
    } while (id <= MAX_BRIDGE_ID);
1811

1812
    virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
1813 1814 1815 1816 1817
                          _("Bridge generation exceeded max id %d"),
                          MAX_BRIDGE_ID);
    return NULL;
}

1818
int virNetworkSetBridgeName(const virNetworkObjListPtr nets,
1819 1820
                            virNetworkDefPtr def,
                            int check_collision) {
1821 1822 1823

    int ret = -1;

1824
    if (def->bridge && !strstr(def->bridge, "%d")) {
1825 1826 1827 1828 1829
        /* 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)) {
1830 1831 1832
            virNetworkReportError(VIR_ERR_INTERNAL_ERROR,
                                  _("bridge name '%s' already in use."),
                                  def->bridge);
1833 1834 1835 1836
            goto error;
        }
    } else {
        /* Allocate a bridge name */
1837
        if (!(def->bridge = virNetworkAllocateBridge(nets, def->bridge)))
1838 1839 1840 1841 1842 1843 1844
            goto error;
    }

    ret = 0;
error:
    return ret;
}
1845

1846

1847 1848 1849 1850 1851 1852
void virNetworkSetBridgeMacAddr(virNetworkDefPtr def)
{
    if (!def->mac_specified) {
        /* if the bridge doesn't have a mac address explicitly defined,
         * autogenerate a random one.
         */
1853
        virMacAddrGenerate((unsigned char[]){ 0x52, 0x54, 0 },
1854 1855 1856 1857 1858
                           def->mac);
        def->mac_specified = true;
    }
}

1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922
/*
 * 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;
}


1923 1924
void virNetworkObjLock(virNetworkObjPtr obj)
{
1925
    virMutexLock(&obj->lock);
1926 1927 1928 1929
}

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