xml.c 63.4 KB
Newer Older
1 2 3
/*
 * xml.c: XML based interfaces for the libvir library
 *
4
 * Copyright (C) 2005, 2007, 2008 Red Hat, Inc.
5 6 7 8 9 10
 *
 * See COPYING.LIB for the License of this software
 *
 * Daniel Veillard <veillard@redhat.com>
 */

11
#include <config.h>
12

13
#include "libvirt/libvirt.h"
14 15 16 17 18

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
19
#include <limits.h>
20
#ifdef WITH_XEN
21
#include <xs.h>
22
#endif
23
#include <math.h>               /* for isnan() */
24 25
#include "internal.h"
#include "hash.h"
D
Daniel Veillard 已提交
26
#include "sexpr.h"
27
#include "xml.h"
28
#include "buf.h"
29
#include "util.h"
30
#include "xs_internal.h"        /* for xenStoreDomainGetNetworkID */
31
#include "xen_unified.h"
D
Daniel Veillard 已提交
32
#include "xend_internal.h"      /* for is_sound_* functions */
33

34 35 36 37 38 39 40 41 42
/**
 * virXMLError:
 * @conn: a connection if any
 * @error: the error number
 * @info: information/format string
 * @value: extra integer parameter for the error string
 *
 * Report an error coming from the XML module.
 */
43
static void
44 45
virXMLError(virConnectPtr conn, virErrorNumber error, const char *info,
            int value)
46
{
47
    const char *errmsg;
48

49 50 51 52
    if (error == VIR_ERR_OK)
        return;

    errmsg = __virErrorMsg(error, info);
53
    __virRaiseError(conn, NULL, NULL, VIR_FROM_XML, error, VIR_ERR_ERROR,
54
                    errmsg, info, NULL, value, 0, errmsg, info, value);
55 56
}

57 58 59 60 61
/************************************************************************
 *									*
 * Parser and converter for the CPUset strings used in libvirt		*
 *									*
 ************************************************************************/
62
#if WITH_XEN
63 64 65 66 67 68 69 70 71 72 73
/**
 * parseCpuNumber:
 * @str: pointer to the char pointer used
 * @maxcpu: maximum CPU number allowed
 *
 * Parse a CPU number
 *
 * Returns the CPU number or -1 in case of error. @str will be
 *         updated to skip the number.
 */
static int
74 75
parseCpuNumber(const char **str, int maxcpu)
{
76 77 78 79
    int ret = 0;
    const char *cur = *str;

    if ((*cur < '0') || (*cur > '9'))
80
        return (-1);
81 82 83

    while ((*cur >= '0') && (*cur <= '9')) {
        ret = ret * 10 + (*cur - '0');
84
        if (ret >= maxcpu)
85 86
            return (-1);
        cur++;
87 88
    }
    *str = cur;
89
    return (ret);
90 91 92
}

/**
93
 * virSaveCpuSet:
94 95 96 97 98 99 100 101 102
 * @conn: connection
 * @cpuset: pointer to a char array for the CPU set
 * @maxcpu: number of elements available in @cpuset
 *
 * Serialize the cpuset to a string
 *
 * Returns the new string NULL in case of error. The string need to be
 *         freed by the caller.
 */
103 104
char *
virSaveCpuSet(virConnectPtr conn, char *cpuset, int maxcpu)
105
{
106
    virBuffer buf = VIR_BUFFER_INITIALIZER;
107 108 109
    int start, cur;
    int first = 1;

110 111
    if ((cpuset == NULL) || (maxcpu <= 0) || (maxcpu > 100000))
        return (NULL);
112 113 114 115 116

    cur = 0;
    start = -1;
    while (cur < maxcpu) {
        if (cpuset[cur]) {
117 118 119 120
            if (start == -1)
                start = cur;
        } else if (start != -1) {
            if (!first)
121
                virBufferAddLit(&buf, ",");
122
            else
123 124
                first = 0;
            if (cur == start + 1)
125
                virBufferVSprintf(&buf, "%d", start);
126
            else
127
                virBufferVSprintf(&buf, "%d-%d", start, cur - 1);
128 129 130
            start = -1;
        }
        cur++;
131 132
    }
    if (start != -1) {
133
        if (!first)
134
            virBufferAddLit(&buf, ",");
135
        if (maxcpu == start + 1)
136
            virBufferVSprintf(&buf, "%d", start);
137
        else
138
            virBufferVSprintf(&buf, "%d-%d", start, maxcpu - 1);
139
    }
140 141 142 143 144 145 146

    if (virBufferError(&buf)) {
        virXMLError(conn, VIR_ERR_NO_MEMORY, _("allocate buffer"), 1000);
        return NULL;
    }

    return virBufferContentAndReset(&buf);
147 148 149 150
}

/**
 * virParseCpuSet:
151
 * @conn: connection
152 153 154 155 156 157 158 159 160 161 162 163 164 165
 * @str: pointer to a CPU set string pointer
 * @sep: potential character used to mark the end of string if not 0
 * @cpuset: pointer to a char array for the CPU set
 * @maxcpu: number of elements available in @cpuset
 *
 * Parse the cpu set, it will set the value for enabled CPUs in the @cpuset
 * to 1, and 0 otherwise. The syntax allows coma separated entries each
 * can be either a CPU number, ^N to unset that CPU or N-M for ranges.
 *
 * Returns the number of CPU found in that set, or -1 in case of error.
 *         @cpuset is modified accordingly to the value parsed.
 *         @str is updated to the end of the part parsed
 */
int
166 167
virParseCpuSet(virConnectPtr conn, const char **str, char sep,
               char *cpuset, int maxcpu)
168 169 170 171 172 173
{
    const char *cur;
    int ret = 0;
    int i, start, last;
    int neg = 0;

174 175 176
    if ((str == NULL) || (cpuset == NULL) || (maxcpu <= 0) ||
        (maxcpu > 100000))
        return (-1);
177 178

    cur = *str;
179
    virSkipSpaces(&cur);
180 181 182 183
    if (*cur == 0)
        goto parse_error;

    /* initialize cpumap to all 0s */
184 185
    for (i = 0; i < maxcpu; i++)
        cpuset[i] = 0;
186 187 188
    ret = 0;

    while ((*cur != 0) && (*cur != sep)) {
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        /*
         * 3 constructs are allowed:
         *     - N   : a single CPU number
         *     - N-M : a range of CPU numbers with N < M
         *     - ^N  : remove a single CPU number from the current set
         */
        if (*cur == '^') {
            cur++;
            neg = 1;
        }

        if ((*cur < '0') || (*cur > '9'))
            goto parse_error;
        start = parseCpuNumber(&cur, maxcpu);
        if (start < 0)
            goto parse_error;
205
        virSkipSpaces(&cur);
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
        if ((*cur == ',') || (*cur == 0) || (*cur == sep)) {
            if (neg) {
                if (cpuset[start] == 1) {
                    cpuset[start] = 0;
                    ret--;
                }
            } else {
                if (cpuset[start] == 0) {
                    cpuset[start] = 1;
                    ret++;
                }
            }
        } else if (*cur == '-') {
            if (neg)
                goto parse_error;
            cur++;
222
            virSkipSpaces(&cur);
223 224 225 226 227 228 229 230 231
            last = parseCpuNumber(&cur, maxcpu);
            if (last < start)
                goto parse_error;
            for (i = start; i <= last; i++) {
                if (cpuset[i] == 0) {
                    cpuset[i] = 1;
                    ret++;
                }
            }
232
            virSkipSpaces(&cur);
233 234 235
        }
        if (*cur == ',') {
            cur++;
236
            virSkipSpaces(&cur);
237 238 239 240 241
            neg = 0;
        } else if ((*cur == 0) || (*cur == sep)) {
            break;
        } else
            goto parse_error;
242 243
    }
    *str = cur;
244
    return (ret);
245

246
  parse_error:
247
    virXMLError(conn, VIR_ERR_XEN_CALL,
248 249
                _("topology cpuset syntax error"), 0);
    return (-1);
250 251 252
}


253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
/**
 * virConvertCpuSet:
 * @conn: connection
 * @str: pointer to a Xen or user provided CPU set string pointer
 * @maxcpu: number of CPUs on the node, if 0 4096 will be used
 *
 * Parse the given CPU set string and convert it to a range based
 * string.
 *
 * Returns a new string which must be freed by the caller or NULL in
 *         case of error.
 */
char *
virConvertCpuSet(virConnectPtr conn, const char *str, int maxcpu) {
    int ret;
    char *res, *cpuset;
    const char *cur = str;

    if (str == NULL)
        return(NULL);

    if (maxcpu <= 0)
        maxcpu = 4096;

277
    cpuset = calloc(maxcpu, sizeof(*cpuset));
278
    if (cpuset == NULL) {
279 280
        virXMLError(conn, VIR_ERR_NO_MEMORY, _("allocate buffer"), 0);
        return(NULL);
281
    }
282

283 284 285
    ret = virParseCpuSet(conn, &cur, 0, cpuset, maxcpu);
    if (ret < 0) {
        free(cpuset);
286
        return(NULL);
287 288 289 290 291
    }
    res = virSaveCpuSet(conn, cpuset, maxcpu);
    free(cpuset);
    return (res);
}
D
Daniel Veillard 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

/**
 * virBuildSoundStringFromXML
 * @sound buffer to populate
 * @len size of preallocated buffer 'sound'
 * @ctxt xml context to pull sound info from
 *
 * Builds a string of the form m1,m2,m3 from the different sound models
 * in the xml. String must be free'd by caller.
 *
 * Returns string on success, NULL on error
 */
char * virBuildSoundStringFromXML(virConnectPtr conn,
                                  xmlXPathContextPtr ctxt) {

    int nb_nodes, size = 256;
    char *sound;
    xmlNodePtr *nodes = NULL;

    if (!(sound = calloc(1, size+1))) {
        virXMLError(conn, VIR_ERR_NO_MEMORY,
                    _("failed to allocate sound string"), 0);
        return NULL;
    }

    nb_nodes = virXPathNodeSet("/domain/devices/sound", ctxt, &nodes);
    if (nb_nodes > 0) {
        int i;
        for (i = 0; i < nb_nodes && size > 0; i++) {
            char *model = NULL;
            int collision = 0;

            model = (char *) xmlGetProp(nodes[i], (xmlChar *) "model");
            if (!model) {
                virXMLError(conn, VIR_ERR_XML_ERROR,
                            _("no model for sound device"), 0);
                goto error;
            }

            if (!is_sound_model_valid(model)) {
                virXMLError(conn, VIR_ERR_XML_ERROR,
                            _("unknown sound model type"), 0);
                free(model);
                goto error;
            }

            // Check for duplicates in currently built string
            if (*sound)
                collision = is_sound_model_conflict(model, sound);

            // If no collision, add to string
            if (!collision) {
                if (*sound && (size >= (strlen(model) + 1))) {
                    strncat(sound, ",", size--);
                } else if (*sound || size < strlen(model)) {
                    free(model);
                    continue;
                }
                strncat(sound, model, size);
                size -= strlen(model);
            }

            free(model);
        }
    }
    free(nodes);
    return sound;

  error:
    free(nodes);
    return NULL;
}
364
#endif /* WITH_XEN */
365
#ifndef PROXY
366 367 368 369 370 371 372

/************************************************************************
 *									*
 * Wrappers around libxml2 XPath specific functions			*
 *									*
 ************************************************************************/

373 374 375 376 377 378 379 380 381 382 383
/**
 * virXPathString:
 * @xpath: the XPath string to evaluate
 * @ctxt: an XPath context
 *
 * Convenience function to evaluate an XPath string
 *
 * Returns a new string which must be deallocated by the caller or NULL
 *         if the evaluation failed.
 */
char *
384 385
virXPathString(const char *xpath, xmlXPathContextPtr ctxt)
{
386 387 388 389
    xmlXPathObjectPtr obj;
    char *ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
390
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR,
391
                    _("Invalid parameter to virXPathString()"), 0);
392
        return (NULL);
393 394 395
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
D
Daniel P. Berrange 已提交
396
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
397
        xmlXPathFreeObject(obj);
398
        return (NULL);
D
Daniel P. Berrange 已提交
399
    }
400 401 402
    ret = strdup((char *) obj->stringval);
    xmlXPathFreeObject(obj);
    if (ret == NULL) {
403
        virXMLError(NULL, VIR_ERR_NO_MEMORY, _("strdup failed"), 0);
404
    }
405
    return (ret);
406 407 408 409 410 411 412 413 414 415 416 417 418 419
}

/**
 * virXPathNumber:
 * @xpath: the XPath string to evaluate
 * @ctxt: an XPath context
 * @value: the returned double value
 *
 * Convenience function to evaluate an XPath number
 *
 * Returns 0 in case of success in which case @value is set,
 *         or -1 if the evaluation failed.
 */
int
420 421
virXPathNumber(const char *xpath, xmlXPathContextPtr ctxt, double *value)
{
422 423 424
    xmlXPathObjectPtr obj;

    if ((ctxt == NULL) || (xpath == NULL) || (value == NULL)) {
425
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR,
426
                    _("Invalid parameter to virXPathNumber()"), 0);
427
        return (-1);
428 429 430 431
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NUMBER) ||
        (isnan(obj->floatval))) {
432 433
        xmlXPathFreeObject(obj);
        return (-1);
434
    }
435

436 437
    *value = obj->floatval;
    xmlXPathFreeObject(obj);
438
    return (0);
439 440 441 442 443 444 445 446 447 448 449
}

/**
 * virXPathLong:
 * @xpath: the XPath string to evaluate
 * @ctxt: an XPath context
 * @value: the returned long value
 *
 * Convenience function to evaluate an XPath number
 *
 * Returns 0 in case of success in which case @value is set,
450 451
 *         or -1 if the XPath evaluation failed or -2 if the
 *         value doesn't have a long format.
452 453
 */
int
454 455
virXPathLong(const char *xpath, xmlXPathContextPtr ctxt, long *value)
{
456 457 458 459
    xmlXPathObjectPtr obj;
    int ret = 0;

    if ((ctxt == NULL) || (xpath == NULL) || (value == NULL)) {
460
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR,
461
                    _("Invalid parameter to virXPathNumber()"), 0);
462
        return (-1);
463 464 465 466 467
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        char *conv = NULL;
468
        long val;
469

470 471
        val = strtol((const char *) obj->stringval, &conv, 10);
        if (conv == (const char *) obj->stringval) {
472 473
            ret = -2;
        } else {
474 475
            *value = val;
        }
476 477
    } else if ((obj != NULL) && (obj->type == XPATH_NUMBER) &&
               (!(isnan(obj->floatval)))) {
478 479 480 481
        *value = (long) obj->floatval;
        if (*value != obj->floatval) {
            ret = -2;
        }
482
    } else {
483
        ret = -1;
484
    }
485

486
    xmlXPathFreeObject(obj);
487
    return (ret);
488 489 490 491 492 493 494 495 496 497 498 499
}

/**
 * virXPathBoolean:
 * @xpath: the XPath string to evaluate
 * @ctxt: an XPath context
 *
 * Convenience function to evaluate an XPath boolean
 *
 * Returns 0 if false, 1 if true, or -1 if the evaluation failed.
 */
int
500 501
virXPathBoolean(const char *xpath, xmlXPathContextPtr ctxt)
{
502 503 504 505
    xmlXPathObjectPtr obj;
    int ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
506
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR,
507
                    _("Invalid parameter to virXPathBoolean()"), 0);
508
        return (-1);
509 510 511 512
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_BOOLEAN) ||
        (obj->boolval < 0) || (obj->boolval > 1)) {
513 514
        xmlXPathFreeObject(obj);
        return (-1);
515 516
    }
    ret = obj->boolval;
517

518
    xmlXPathFreeObject(obj);
519
    return (ret);
520 521 522 523 524 525 526 527 528 529 530 531 532
}

/**
 * virXPathNode:
 * @xpath: the XPath string to evaluate
 * @ctxt: an XPath context
 *
 * Convenience function to evaluate an XPath node set and returning
 * only one node, the first one in the set if any
 *
 * Returns a pointer to the node or NULL if the evaluation failed.
 */
xmlNodePtr
533 534
virXPathNode(const char *xpath, xmlXPathContextPtr ctxt)
{
535 536 537 538
    xmlXPathObjectPtr obj;
    xmlNodePtr ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
539
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR,
540
                    _("Invalid parameter to virXPathNode()"), 0);
541
        return (NULL);
542 543 544 545
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr <= 0) ||
546 547 548
        (obj->nodesetval->nodeTab == NULL)) {
        xmlXPathFreeObject(obj);
        return (NULL);
549
    }
550

551 552
    ret = obj->nodesetval->nodeTab[0];
    xmlXPathFreeObject(obj);
553
    return (ret);
554
}
555

556 557 558 559 560 561 562 563 564 565 566 567
/**
 * virXPathNodeSet:
 * @xpath: the XPath string to evaluate
 * @ctxt: an XPath context
 * @list: the returned list of nodes (or NULL if only count matters)
 *
 * Convenience function to evaluate an XPath node set
 *
 * Returns the number of nodes found in which case @list is set (and
 *         must be freed) or -1 if the evaluation failed.
 */
int
568 569 570
virXPathNodeSet(const char *xpath, xmlXPathContextPtr ctxt,
                xmlNodePtr ** list)
{
571 572 573 574
    xmlXPathObjectPtr obj;
    int ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
575
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR,
576
                    _("Invalid parameter to virXPathNodeSet()"), 0);
577
        return (-1);
578 579 580 581
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr <= 0) ||
582 583 584 585 586
        (obj->nodesetval->nodeTab == NULL)) {
        xmlXPathFreeObject(obj);
        if (list != NULL)
            *list = NULL;
        return (-1);
587
    }
588

589 590
    ret = obj->nodesetval->nodeNr;
    if (list != NULL) {
591
        *list = malloc(ret * sizeof(**list));
592 593 594
        if (*list == NULL) {
            virXMLError(NULL, VIR_ERR_NO_MEMORY,
                        _("allocate string array"),
595
                        ret * sizeof(**list));
596 597 598 599
        } else {
            memcpy(*list, obj->nodesetval->nodeTab,
                   ret * sizeof(xmlNodePtr));
        }
600 601
    }
    xmlXPathFreeObject(obj);
602
    return (ret);
603 604
}

605 606 607 608 609
/************************************************************************
 *									*
 * Converter functions to go from the XML tree to an S-Expr for Xen	*
 *									*
 ************************************************************************/
610
#if WITH_XEN
611
/**
612
 * virtDomainParseXMLGraphicsDescImage:
613
 * @conn: pointer to the hypervisor connection
614 615
 * @node: node containing graphics description
 * @buf: a buffer for the result S-Expr
616
 * @xendConfigVersion: xend configuration file format
617
 *
618 619 620
 * Parse the graphics part of the XML description and add it to the S-Expr
 * in buf.  This is a temporary interface as the S-Expr interface will be
 * replaced by XML-RPC in the future. However the XML format should stay
621 622 623 624
 * valid over time.
 *
 * Returns 0 in case of success, -1 in case of error
 */
625 626 627 628
static int
virDomainParseXMLGraphicsDescImage(virConnectPtr conn ATTRIBUTE_UNUSED,
                                   xmlNodePtr node, virBufferPtr buf,
                                   int xendConfigVersion)
629 630 631 632 633 634
{
    xmlChar *graphics_type = NULL;

    graphics_type = xmlGetProp(node, BAD_CAST "type");
    if (graphics_type != NULL) {
        if (xmlStrEqual(graphics_type, BAD_CAST "sdl")) {
635
            virBufferAddLit(buf, "(sdl 1)");
636 637 638
            /* TODO:
             * Need to understand sdl options
             *
639 640
             *virBufferAddLit(buf, "(display localhost:10.0)");
             *virBufferAddLit(buf, "(xauthority /root/.Xauthority)");
641
             */
642
        } else if (xmlStrEqual(graphics_type, BAD_CAST "vnc")) {
643
            virBufferAddLit(buf, "(vnc 1)");
644
            if (xendConfigVersion >= 2) {
645
                xmlChar *vncport = xmlGetProp(node, BAD_CAST "port");
646 647
                xmlChar *vnclisten = xmlGetProp(node, BAD_CAST "listen");
                xmlChar *vncpasswd = xmlGetProp(node, BAD_CAST "passwd");
648
                xmlChar *keymap = xmlGetProp(node, BAD_CAST "keymap");
649

650
                if (vncport != NULL) {
651 652
                    long port = strtol((const char *) vncport, NULL, 10);

653
                    if (port == -1)
654
                        virBufferAddLit(buf, "(vncunused 1)");
655
                    else if (port >= 5900)
656 657
                        virBufferVSprintf(buf, "(vncdisplay %ld)",
                                          port - 5900);
658
                    xmlFree(vncport);
659
                }
660 661 662 663 664 665 666 667
                if (vnclisten != NULL) {
                    virBufferVSprintf(buf, "(vnclisten %s)", vnclisten);
                    xmlFree(vnclisten);
                }
                if (vncpasswd != NULL) {
                    virBufferVSprintf(buf, "(vncpasswd %s)", vncpasswd);
                    xmlFree(vncpasswd);
                }
668 669 670 671
                if (keymap != NULL) {
                    virBufferVSprintf(buf, "(keymap %s)", keymap);
                    xmlFree(keymap);
                }
672 673
            }
        }
674 675 676 677 678 679
        xmlFree(graphics_type);
    }
    return 0;
}


680 681
/**
 * virtDomainParseXMLGraphicsDescVFB:
682
 * @conn: pointer to the hypervisor connection
683 684 685
 * @node: node containing graphics description
 * @buf: a buffer for the result S-Expr
 *
686 687 688
 * Parse the graphics part of the XML description and add it to the S-Expr
 * in buf.  This is a temporary interface as the S-Expr interface will be
 * replaced by XML-RPC in the future. However the XML format should stay
689 690 691 692
 * valid over time.
 *
 * Returns 0 in case of success, -1 in case of error
 */
693 694 695
static int
virDomainParseXMLGraphicsDescVFB(virConnectPtr conn ATTRIBUTE_UNUSED,
                                 xmlNodePtr node, virBufferPtr buf)
696 697 698 699 700
{
    xmlChar *graphics_type = NULL;

    graphics_type = xmlGetProp(node, BAD_CAST "type");
    if (graphics_type != NULL) {
701 702
        virBufferAddLit(buf, "(device (vkbd))");
        virBufferAddLit(buf, "(device (vfb ");
703
        if (xmlStrEqual(graphics_type, BAD_CAST "sdl")) {
704
            virBufferAddLit(buf, "(type sdl)");
705 706 707
            /* TODO:
             * Need to understand sdl options
             *
708 709
             *virBufferAddLit(buf, "(display localhost:10.0)");
             *virBufferAddLit(buf, "(xauthority /root/.Xauthority)");
710
             */
711
        } else if (xmlStrEqual(graphics_type, BAD_CAST "vnc")) {
712
            virBufferAddLit(buf, "(type vnc)");
713 714 715
            xmlChar *vncport = xmlGetProp(node, BAD_CAST "port");
            xmlChar *vnclisten = xmlGetProp(node, BAD_CAST "listen");
            xmlChar *vncpasswd = xmlGetProp(node, BAD_CAST "passwd");
716
            xmlChar *keymap = xmlGetProp(node, BAD_CAST "keymap");
717

718
            if (vncport != NULL) {
719 720
                long port = strtol((const char *) vncport, NULL, 10);

721
                if (port == -1)
722
                    virBufferAddLit(buf, "(vncunused 1)");
723
                else if (port >= 5900)
724 725
                    virBufferVSprintf(buf, "(vncdisplay %ld)",
                                      port - 5900);
726 727 728 729 730 731 732 733 734 735
                xmlFree(vncport);
            }
            if (vnclisten != NULL) {
                virBufferVSprintf(buf, "(vnclisten %s)", vnclisten);
                xmlFree(vnclisten);
            }
            if (vncpasswd != NULL) {
                virBufferVSprintf(buf, "(vncpasswd %s)", vncpasswd);
                xmlFree(vncpasswd);
            }
736 737 738 739
            if (keymap != NULL) {
                virBufferVSprintf(buf, "(keymap %s)", keymap);
                xmlFree(keymap);
            }
740
        }
741
        virBufferAddLit(buf, "))");
742 743 744 745 746 747
        xmlFree(graphics_type);
    }
    return 0;
}


748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
int
virDomainParseXMLOSDescHVMChar(virConnectPtr conn,
                               char *buf,
                               size_t buflen,
                               xmlNodePtr node)
{
    xmlChar *type = NULL;
    xmlChar *path = NULL;
    xmlChar *bindHost = NULL;
    xmlChar *bindService = NULL;
    xmlChar *connectHost = NULL;
    xmlChar *connectService = NULL;
    xmlChar *mode = NULL;
    xmlChar *protocol = NULL;
    xmlNodePtr cur;

    type = xmlGetProp(node, BAD_CAST "type");

    if (type != NULL) {
        cur = node->children;
        while (cur != NULL) {
            if (cur->type == XML_ELEMENT_NODE) {
                if (xmlStrEqual(cur->name, BAD_CAST "source")) {
                    if (mode == NULL)
                        mode = xmlGetProp(cur, BAD_CAST "mode");

                    if (STREQ((const char *)type, "dev") ||
                        STREQ((const char *)type, "file") ||
                        STREQ((const char *)type, "pipe") ||
                        STREQ((const char *)type, "unix")) {
                        if (path == NULL)
                            path = xmlGetProp(cur, BAD_CAST "path");

                    } else if (STREQ((const char *)type, "udp") ||
                               STREQ((const char *)type, "tcp")) {
                        if (mode == NULL ||
                            STREQ((const char *)mode, "connect")) {

                            if (connectHost == NULL)
                                connectHost = xmlGetProp(cur, BAD_CAST "host");
                            if (connectService == NULL)
                                connectService = xmlGetProp(cur, BAD_CAST "service");
                        } else {
                            if (bindHost == NULL)
                                bindHost = xmlGetProp(cur, BAD_CAST "host");
                            if (bindService == NULL)
                                bindService = xmlGetProp(cur, BAD_CAST "service");
                        }

                        if (STREQ((const char*)type, "udp")) {
                            xmlFree(mode);
                            mode = NULL;
                        }
                    }
                } else if (xmlStrEqual(cur->name, BAD_CAST "protocol")) {
                    if (protocol == NULL)
                        protocol = xmlGetProp(cur, BAD_CAST "type");
                }
            }
            cur = cur->next;
        }
    }

    if (type == NULL ||
        STREQ((const char *)type, "pty")) {
        strncpy(buf, "pty", buflen);
    } else if (STREQ((const char *)type, "null") ||
               STREQ((const char *)type, "stdio") ||
               STREQ((const char *)type, "vc")) {
        snprintf(buf, buflen, "%s", type);
    } else if (STREQ((const char *)type, "file") ||
               STREQ((const char *)type, "dev") ||
               STREQ((const char *)type, "pipe")) {
        if (path == NULL) {
            virXMLError(conn, VIR_ERR_XML_ERROR,
                        _("Missing source path attribute for char device"), 0);
            goto cleanup;
        }

        if (STREQ((const char *)type, "dev"))
            strncpy(buf, (const char *)path, buflen);
        else
            snprintf(buf, buflen, "%s:%s", type, path);
    } else if (STREQ((const char *)type, "tcp")) {
        int telnet = 0;
        if (protocol != NULL &&
            STREQ((const char *)protocol, "telnet"))
            telnet = 1;

        if (mode == NULL ||
            STREQ((const char *)mode, "connect")) {
            if (connectHost == NULL) {
                virXMLError(conn, VIR_ERR_INTERNAL_ERROR,
                            _("Missing source host attribute for char device"), 0);
                goto cleanup;
            }
            if (connectService == NULL) {
                virXMLError(conn, VIR_ERR_INTERNAL_ERROR,
                            _("Missing source service attribute for char device"), 0);
                goto cleanup;
            }

            snprintf(buf, buflen, "%s:%s:%s",
                     (telnet ? "telnet" : "tcp"),
                     connectHost, connectService);
        } else {
            if (bindHost == NULL) {
                virXMLError(conn, VIR_ERR_INTERNAL_ERROR,
                            _("Missing source host attribute for char device"), 0);
                goto cleanup;
            }
            if (bindService == NULL) {
                virXMLError(conn, VIR_ERR_INTERNAL_ERROR,
                            _("Missing source service attribute for char device"), 0);
                goto cleanup;
            }

            snprintf(buf, buflen, "%s:%s:%s,listen",
                     (telnet ? "telnet" : "tcp"),
                     bindHost, bindService);
        }
    } else if (STREQ((const char *)type, "udp")) {
        if (connectService == NULL) {
            virXMLError(conn, VIR_ERR_XML_ERROR,
                        _("Missing source service attribute for char device"), 0);
            goto cleanup;
        }

        snprintf(buf, buflen, "udp:%s:%s@%s:%s",
                 connectHost ? (const char *)connectHost : "",
                 connectService,
                 bindHost ? (const char *)bindHost : "",
                 bindService ? (const char *)bindService : "");
    } else if (STREQ((const char *)type, "unix")) {
        if (path == NULL) {
            virXMLError(conn, VIR_ERR_XML_ERROR,
                        _("Missing source path attribute for char device"), 0);
            goto cleanup;
        }

        if (mode == NULL ||
            STREQ((const char *)mode, "connect")) {
            snprintf(buf, buflen, "%s:%s", type, path);
        } else {
            snprintf(buf, buflen, "%s:%s,listen", type, path);
        }
    }
    buf[buflen-1] = '\0';

    xmlFree(mode);
    xmlFree(protocol);
    xmlFree(type);
    xmlFree(bindHost);
    xmlFree(bindService);
    xmlFree(connectHost);
    xmlFree(connectService);
    xmlFree(path);

    return 0;

cleanup:
    xmlFree(mode);
    xmlFree(protocol);
    xmlFree(type);
    xmlFree(bindHost);
    xmlFree(bindService);
    xmlFree(connectHost);
    xmlFree(connectService);
    xmlFree(path);
    return -1;
}

920
/**
921
 * virDomainParseXMLOSDescHVM:
922
 * @conn: pointer to the hypervisor connection
923
 * @node: node containing HVM OS description
924
 * @buf: a buffer for the result S-Expr
925
 * @ctxt: a path context representing the XML description
926
 * @vcpus: number of virtual CPUs to configure
927
 * @xendConfigVersion: xend configuration file format
928
 * @hasKernel: whether the domain is booting from a kernel
929
 *
930 931
 * Parse the OS part of the XML description for a HVM domain
 * and add it to the S-Expr in buf.
932 933 934 935
 *
 * Returns 0 in case of success, -1 in case of error.
 */
static int
936 937
virDomainParseXMLOSDescHVM(virConnectPtr conn, xmlNodePtr node,
                           virBufferPtr buf, xmlXPathContextPtr ctxt,
938 939
                           int vcpus, int xendConfigVersion,
                           int hasKernel)
940 941
{
    xmlNodePtr cur, txt;
942
    xmlNodePtr *nodes = NULL;
943
    xmlChar *loader = NULL;
944 945
    char bootorder[5];
    int nbootorder = 0;
946
    int res, nb_nodes;
947
    char *str;
948 949 950 951

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
952 953
            if ((loader == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "loader"))) {
954 955
                txt = cur->children;
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
956
                    (txt->next == NULL))
957
                    loader = txt->content;
958 959
            } else if ((xmlStrEqual(cur->name, BAD_CAST "boot"))) {
                xmlChar *boot_dev = xmlGetProp(cur, BAD_CAST "dev");
960 961 962 963

                if (nbootorder ==
                    ((sizeof(bootorder) / sizeof(bootorder[0])) - 1)) {
                    virXMLError(conn, VIR_ERR_XML_ERROR,
964
                                _("too many boot devices"), 0);
965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
                    return (-1);
                }
                if (xmlStrEqual(boot_dev, BAD_CAST "fd")) {
                    bootorder[nbootorder++] = 'a';
                } else if (xmlStrEqual(boot_dev, BAD_CAST "cdrom")) {
                    bootorder[nbootorder++] = 'd';
                } else if (xmlStrEqual(boot_dev, BAD_CAST "network")) {
                    bootorder[nbootorder++] = 'n';
                } else if (xmlStrEqual(boot_dev, BAD_CAST "hd")) {
                    bootorder[nbootorder++] = 'c';
                } else {
                    xmlFree(boot_dev);
                    /* Any other type of boot dev is unsupported right now */
                    virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
                    return (-1);
                }
                xmlFree(boot_dev);
982 983 984 985
            }
        }
        cur = cur->next;
    }
986 987 988 989 990 991 992
    /*
     * XenD always needs boot order defined for HVM, even if
     * booting off a kernel + initrd, so force to 'c' if nothing
     * else is specified
     */
    if (nbootorder == 0)
        bootorder[nbootorder++] = 'c';
993
    bootorder[nbootorder] = '\0';
994

995
    if (loader == NULL) {
996
        virXMLError(conn, VIR_ERR_INTERNAL_ERROR, _("no HVM domain loader"), 0);
997
        return -1;
998 999
    }

1000
    /*
1001 1002 1003 1004 1005 1006 1007 1008 1009
     * Originally XenD abused the 'kernel' parameter for the HVM
     * firmware. New XenD allows HVM guests to boot from a kernel
     * and if this is enabled, the HVM firmware must use the new
     * 'loader' parameter
     */
    if (hasKernel) {
        virBufferVSprintf(buf, "(loader '%s')", (const char *) loader);
    } else {
        virBufferVSprintf(buf, "(kernel '%s')", (const char *) loader);
1010 1011
    }

1012 1013
    virBufferVSprintf(buf, "(vcpus %d)", vcpus);

1014 1015
    if (nbootorder)
        virBufferVSprintf(buf, "(boot %s)", bootorder);
1016

1017
    /* get the 1st floppy device file */
1018 1019 1020 1021
    cur = virXPathNode(
         "/domain/devices/disk[@device='floppy' and target/@dev='fda']/source",
         ctxt);
    if (cur != NULL) {
1022
        xmlChar *fdfile;
1023

1024
        fdfile = xmlGetProp(cur, BAD_CAST "file");
1025
        if (fdfile != NULL) {
1026 1027
            virBufferVSprintf(buf, "(fda '%s')", fdfile);
            free(fdfile);
1028
        }
1029
    }
1030

1031
    /* get the 2nd floppy device file */
1032 1033 1034 1035
    cur = virXPathNode(
         "/domain/devices/disk[@device='floppy' and target/@dev='fdb']/source",
         ctxt);
    if (cur != NULL) {
1036
        xmlChar *fdfile;
1037

1038
        fdfile = xmlGetProp(cur, BAD_CAST "file");
1039
        if (fdfile != NULL) {
1040 1041
            virBufferVSprintf(buf, "(fdb '%s')", fdfile);
            free(fdfile);
1042
        }
1043
    }
1044

1045 1046 1047
    /* get the cdrom device file */
    /* Only XenD <= 3.0.2 wants cdrom config here */
    if (xendConfigVersion == 1) {
1048
        cur = virXPathNode(
1049
          "/domain/devices/disk[@device='cdrom' and target/@dev='hdc']/source",
1050 1051
             ctxt);
        if (cur != NULL) {
1052 1053 1054 1055 1056
            xmlChar *cdfile;

            cdfile = xmlGetProp(cur, BAD_CAST "file");
            if (cdfile != NULL) {
                virBufferVSprintf(buf, "(cdrom '%s')",
1057
                                  (const char *) cdfile);
1058
                xmlFree(cdfile);
1059 1060
            }
        }
1061 1062
    }

1063
    if (virXPathNode("/domain/features/acpi", ctxt) != NULL)
1064
        virBufferAddLit(buf, "(acpi 1)");
1065
    if (virXPathNode("/domain/features/apic", ctxt) != NULL)
1066
        virBufferAddLit(buf, "(apic 1)");
1067
    if (virXPathNode("/domain/features/pae", ctxt) != NULL)
1068
        virBufferAddLit(buf, "(pae 1)");
1069

1070
    virBufferAddLit(buf, "(usb 1)");
1071 1072 1073
    nb_nodes = virXPathNodeSet("/domain/devices/input", ctxt, &nodes);
    if (nb_nodes > 0) {
        int i;
1074

1075 1076 1077 1078
        for (i = 0; i < nb_nodes; i++) {
            xmlChar *itype = NULL, *bus = NULL;
            int isMouse = 1;

1079
            itype = xmlGetProp(nodes[i], (xmlChar *) "type");
1080 1081 1082 1083

            if (!itype) {
                goto error;
            }
1084
            if (!strcmp((const char *) itype, "tablet"))
1085
                isMouse = 0;
1086
            else if (strcmp((const char *) itype, "mouse")) {
1087
                xmlFree(itype);
1088 1089
                virXMLError(conn, VIR_ERR_XML_ERROR,
                            _("invalid input device"), 0);
1090 1091 1092 1093
                goto error;
            }
            xmlFree(itype);

1094
            bus = xmlGetProp(nodes[i], (xmlChar *) "bus");
1095 1096 1097 1098
            if (!bus) {
                if (!isMouse) {
                    /* Nothing - implicit ps2 */
                } else {
1099
                    virBufferAddLit(buf, "(usbdevice tablet)");
1100 1101
                }
            } else {
1102
                if (!strcmp((const char *) bus, "ps2")) {
1103 1104
                    if (!isMouse) {
                        xmlFree(bus);
1105 1106
                        virXMLError(conn, VIR_ERR_XML_ERROR,
                                    _("invalid input device"), 0);
1107 1108 1109
                        goto error;
                    }
                    /* Nothing - implicit ps2 */
1110
                } else if (!strcmp((const char *) bus, "usb")) {
1111
                    if (isMouse)
1112
                        virBufferAddLit(buf, "(usbdevice mouse)");
1113
                    else
1114
                        virBufferAddLit(buf, "(usbdevice tablet)");
1115 1116 1117 1118 1119 1120 1121 1122
                }
            }
            xmlFree(bus);
        }
        free(nodes);
        nodes = NULL;
    }

1123 1124 1125 1126 1127
    cur = virXPathNode("/domain/devices/parallel[1]", ctxt);
    if (cur != NULL) {
        char scratch[PATH_MAX];
        if (virDomainParseXMLOSDescHVMChar(conn, scratch, sizeof(scratch), cur) < 0)
            goto error;
1128
        virBufferVSprintf(buf, "(parallel %s)", scratch);
1129
    } else {
1130
        virBufferAddLit(buf, "(parallel none)");
1131
    }
1132 1133 1134 1135 1136 1137

    cur = virXPathNode("/domain/devices/serial[1]", ctxt);
    if (cur != NULL) {
        char scratch[PATH_MAX];
        if (virDomainParseXMLOSDescHVMChar(conn, scratch, sizeof(scratch), cur) < 0)
            goto error;
1138
        virBufferVSprintf(buf, "(serial %s)", scratch);
1139 1140 1141 1142 1143 1144 1145
    } else {
        res = virXPathBoolean("count(domain/devices/console) > 0", ctxt);
        if (res < 0) {
            virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
            goto error;
        }
        if (res) {
1146
            virBufferAddLit(buf, "(serial pty)");
1147
        } else {
1148
            virBufferAddLit(buf, "(serial none)");
1149
        }
1150
    }
1151

D
Daniel Veillard 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160
    cur = virXPathNode("/domain/devices/sound", ctxt);
    if (cur) {
        char *soundstr;
        if (!(soundstr = virBuildSoundStringFromXML(conn, ctxt)))
            goto error;
        virBufferVSprintf(buf, "(soundhw '%s')", soundstr);
        free(soundstr);
    }

1161
    str = virXPathString("string(/domain/clock/@offset)", ctxt);
1162 1163
    if (str != NULL && STREQ(str, "localtime")) {
        virBufferAddLit(buf, "(localtime 1)");
1164
    }
1165
    free(str);
1166

1167
    return (0);
1168

1169
  error:
1170
    free(nodes);
1171
    return (-1);
1172 1173
}

1174

1175
/**
1176
 * virDomainParseXMLOSDescKernel:
1177
 * @conn: pointer to the hypervisor connection
1178 1179 1180
 * @node: node containing PV OS description
 * @buf: a buffer for the result S-Expr
 *
1181 1182
 * Parse the OS part of the XML description for a domain using a direct
 * kernel and initrd to boot.
1183 1184 1185 1186
 *
 * Returns 0 in case of success, -1 in case of error.
 */
static int
1187 1188 1189
virDomainParseXMLOSDescKernel(virConnectPtr conn ATTRIBUTE_UNUSED,
                              xmlNodePtr node,
                              virBufferPtr buf)
1190
{
1191 1192 1193 1194 1195 1196 1197 1198 1199
    xmlNodePtr cur, txt;
    const xmlChar *root = NULL;
    const xmlChar *kernel = NULL;
    const xmlChar *initrd = NULL;
    const xmlChar *cmdline = NULL;

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
1200 1201
            if ((kernel == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "kernel"))) {
1202
                txt = cur->children;
1203
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
1204
                    (txt->next == NULL))
1205 1206 1207 1208
                    kernel = txt->content;
            } else if ((root == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "root"))) {
                txt = cur->children;
1209
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
1210
                    (txt->next == NULL))
1211 1212 1213 1214
                    root = txt->content;
            } else if ((initrd == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "initrd"))) {
                txt = cur->children;
1215
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
1216
                    (txt->next == NULL))
1217 1218 1219 1220
                    initrd = txt->content;
            } else if ((cmdline == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "cmdline"))) {
                txt = cur->children;
1221
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
1222
                    (txt->next == NULL))
1223 1224 1225
                    cmdline = txt->content;
            }
        }
1226 1227
        cur = cur->next;
    }
1228

1229 1230
    virBufferVSprintf(buf, "(kernel '%s')", (const char *) kernel);

1231
    if (initrd != NULL)
1232
        virBufferVSprintf(buf, "(ramdisk '%s')", (const char *) initrd);
1233
    if (root != NULL)
1234
        virBufferVSprintf(buf, "(root '%s')", (const char *) root);
1235
    if (cmdline != NULL)
1236
        virBufferVSprintf(buf, "(args '%s')", (const char *) cmdline);
1237

1238
    return (0);
1239 1240
}

1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
/**
 * virCatchXMLParseError:
 * @ctx: the context
 * @msg: the error message
 * @...: extra arguments
 *
 * SAX callback on parsing errors, act as a gate for libvirt own
 * error reporting.
 */
static void
1251 1252
virCatchXMLParseError(void *ctx, const char *msg ATTRIBUTE_UNUSED, ...)
{
1253 1254
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;

1255
    if ((ctxt != NULL) &&
1256
        (ctxt->lastError.level == XML_ERR_FATAL) &&
1257
        (ctxt->lastError.message != NULL)) {
1258
        virXMLError(NULL, VIR_ERR_XML_DETAIL, ctxt->lastError.message,
1259
                    ctxt->lastError.line);
1260 1261 1262
    }
}

1263 1264
/**
 * virDomainParseXMLDiskDesc:
1265
 * @node: node containing disk description
1266
 * @conn: pointer to the hypervisor connection
1267
 * @buf: a buffer for the result S-Expr
1268
 * @xendConfigVersion: xend configuration file format
1269 1270 1271 1272 1273 1274 1275 1276 1277
 *
 * Parse the one disk in the XML description and add it to the S-Expr in buf
 * This is a temporary interface as the S-Expr interface
 * will be replaced by XML-RPC in the future. However the XML format should
 * stay valid over time.
 *
 * Returns 0 in case of success, -1 in case of error.
 */
static int
1278 1279
virDomainParseXMLDiskDesc(virConnectPtr conn, xmlNodePtr node,
                          virBufferPtr buf, int hvm, int xendConfigVersion)
1280
{
1281 1282
    xmlNodePtr cur;
    xmlChar *type = NULL;
1283
    xmlChar *device = NULL;
1284 1285
    xmlChar *source = NULL;
    xmlChar *target = NULL;
1286 1287
    xmlChar *drvName = NULL;
    xmlChar *drvType = NULL;
1288
    int ro = 0;
1289
    int shareable = 0;
1290
    int typ = 0;
1291
    int cdrom = 0;
1292
    int isNoSrcCdrom = 0;
1293
    int ret = 0;
1294 1295 1296

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
1297 1298 1299 1300 1301
        if (xmlStrEqual(type, BAD_CAST "file"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "block"))
            typ = 1;
        xmlFree(type);
1302
    }
1303
    device = xmlGetProp(node, BAD_CAST "device");
1304

1305 1306 1307
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {

                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "file");
                else
                    source = xmlGetProp(cur, BAD_CAST "dev");
            } else if ((target == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "target"))) {
                target = xmlGetProp(cur, BAD_CAST "dev");
1318 1319 1320
            } else if ((drvName == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "driver"))) {
                drvName = xmlGetProp(cur, BAD_CAST "name");
1321
                if (drvName && !strcmp((const char *) drvName, "tap"))
1322
                    drvType = xmlGetProp(cur, BAD_CAST "type");
1323 1324
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                ro = 1;
1325
            } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
1326
                shareable = 1;
1327 1328
            }
        }
1329 1330 1331 1332
        cur = cur->next;
    }

    if (source == NULL) {
1333 1334 1335
        /* There is a case without the source
         * to the CD-ROM device
         */
1336
        if (hvm && device && !strcmp((const char *) device, "cdrom")) {
1337 1338 1339 1340
            isNoSrcCdrom = 1;
        }
        if (!isNoSrcCdrom) {
            virXMLError(conn, VIR_ERR_NO_SOURCE, (const char *) target, 0);
1341 1342
            ret = -1;
            goto cleanup;
1343
        }
1344 1345
    }
    if (target == NULL) {
1346
        virXMLError(conn, VIR_ERR_NO_TARGET, (const char *) source, 0);
1347 1348
        ret = -1;
        goto cleanup;
1349
    }
1350

1351 1352
    /* Xend (all versions) put the floppy device config
     * under the hvm (image (os)) block
1353
     */
1354
    if (hvm && device && !strcmp((const char *) device, "floppy")) {
1355
        goto cleanup;
1356 1357 1358
    }

    /* Xend <= 3.0.2 doesn't include cdrom config here */
1359
    if (hvm && device && !strcmp((const char *) device, "cdrom")) {
1360
        if (xendConfigVersion == 1)
1361
            goto cleanup;
1362 1363
        else
            cdrom = 1;
1364 1365 1366
    }


1367
    virBufferAddLit(buf, "(device ");
1368
    /* Normally disks are in a (device (vbd ...)) block
1369 1370 1371
     * but blktap disks ended up in a differently named
     * (device (tap ....)) block.... */
    if (drvName && !strcmp((const char *) drvName, "tap")) {
1372
        virBufferAddLit(buf, "(tap ");
1373
    } else {
1374
        virBufferAddLit(buf, "(vbd ");
1375
    }
1376

1377
    if (hvm) {
1378 1379
        char *tmp = (char *) target;

1380
        /* Just in case user mistakenly still puts ioemu: in their XML */
1381 1382
        if (!strncmp((const char *) tmp, "ioemu:", 6))
            tmp += 6;
1383 1384 1385

        /* Xend <= 3.0.2 wants a ioemu: prefix on devices for HVM */
        if (xendConfigVersion == 1)
1386 1387 1388 1389
            virBufferVSprintf(buf, "(dev 'ioemu:%s')", (const char *) tmp);
        else                    /* But newer does not */
            virBufferVSprintf(buf, "(dev '%s%s')", (const char *) tmp,
                              cdrom ? ":cdrom" : ":disk");
1390
    } else
1391
        virBufferVSprintf(buf, "(dev '%s')", (const char *) target);
1392

1393
    if (drvName && !isNoSrcCdrom) {
1394
        if (!strcmp((const char *) drvName, "tap")) {
1395
            virBufferVSprintf(buf, "(uname '%s:%s:%s')",
1396 1397 1398
                              (const char *) drvName,
                              (drvType ? (const char *) drvType : "aio"),
                              (const char *) source);
1399 1400
        } else {
            virBufferVSprintf(buf, "(uname '%s:%s')",
1401 1402
                              (const char *) drvName,
                              (const char *) source);
1403
        }
1404
    } else if (!isNoSrcCdrom) {
1405 1406 1407 1408 1409 1410 1411 1412
        if (typ == 0)
            virBufferVSprintf(buf, "(uname 'file:%s')", source);
        else if (typ == 1) {
            if (source[0] == '/')
                virBufferVSprintf(buf, "(uname 'phy:%s')", source);
            else
                virBufferVSprintf(buf, "(uname 'phy:/dev/%s')", source);
        }
1413
    }
1414
    if (ro == 1)
1415
        virBufferAddLit(buf, "(mode 'r')");
1416
    else if (shareable == 1)
1417
        virBufferAddLit(buf, "(mode 'w!')");
1418
    else
1419
        virBufferAddLit(buf, "(mode 'w')");
1420

1421 1422
    virBufferAddLit(buf, ")");
    virBufferAddLit(buf, ")");
1423

1424
  cleanup:
1425 1426 1427 1428 1429
    xmlFree(drvType);
    xmlFree(drvName);
    xmlFree(device);
    xmlFree(target);
    xmlFree(source);
1430
    return (ret);
1431 1432 1433 1434
}

/**
 * virDomainParseXMLIfDesc:
1435
 * @conn: pointer to the hypervisor connection
1436
 * @node: node containing the interface description
1437
 * @buf: a buffer for the result S-Expr
1438
 * @xendConfigVersion: xend configuration file format
1439 1440 1441 1442 1443 1444 1445 1446 1447
 *
 * Parse the one interface the XML description and add it to the S-Expr in buf
 * This is a temporary interface as the S-Expr interface
 * will be replaced by XML-RPC in the future. However the XML format should
 * stay valid over time.
 *
 * Returns 0 in case of success, -1 in case of error.
 */
static int
1448 1449 1450
virDomainParseXMLIfDesc(virConnectPtr conn ATTRIBUTE_UNUSED,
                        xmlNodePtr node, virBufferPtr buf, int hvm,
                        int xendConfigVersion)
1451
{
1452 1453 1454 1455 1456
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *source = NULL;
    xmlChar *mac = NULL;
    xmlChar *script = NULL;
1457
    xmlChar *model = NULL;
1458
    xmlChar *ip = NULL;
1459
    int typ = 0;
1460
    int ret = -1;
1461 1462 1463

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
1464 1465 1466 1467
        if (xmlStrEqual(type, BAD_CAST "bridge"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            typ = 1;
1468 1469
        else if (xmlStrEqual(type, BAD_CAST "network"))
            typ = 2;
1470
        xmlFree(type);
1471 1472 1473 1474
    }
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
1475 1476 1477 1478
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "bridge");
1479
                else if (typ == 1)
1480
                    source = xmlGetProp(cur, BAD_CAST "dev");
1481 1482
                else
                    source = xmlGetProp(cur, BAD_CAST "network");
1483 1484 1485 1486 1487 1488
            } else if ((mac == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "mac"))) {
                mac = xmlGetProp(cur, BAD_CAST "address");
            } else if ((script == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "script"))) {
                script = xmlGetProp(cur, BAD_CAST "path");
1489 1490 1491
            } else if ((model == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "model"))) {
                model = xmlGetProp(cur, BAD_CAST "type");
1492 1493 1494
            } else if ((ip == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "ip"))) {
                /* XXX in future expect to need to have > 1 ip
1495 1496 1497
                 * address element - eg ipv4 & ipv6. For now
                 * xen only supports a single address though
                 * so lets ignore that complication */
1498
                ip = xmlGetProp(cur, BAD_CAST "address");
1499 1500
            }
        }
1501 1502 1503
        cur = cur->next;
    }

1504
    virBufferAddLit(buf, "(vif ");
1505
    if (mac != NULL) {
1506 1507
        unsigned char addr[6];
        if (virParseMacAddr((const char*) mac, addr) == -1) {
1508 1509 1510
            virXMLError(conn, VIR_ERR_INVALID_MAC, (const char *) mac, 0);
            goto error;
        }
1511
        virBufferVSprintf(buf, "(mac '%s')", (const char *) mac);
1512
    }
1513
    if (source != NULL) {
1514 1515
        if (typ == 0)
            virBufferVSprintf(buf, "(bridge '%s')", (const char *) source);
1516
        else if (typ == 1)      /* TODO does that work like that ? */
1517
            virBufferVSprintf(buf, "(dev '%s')", (const char *) source);
1518
        else {
1519 1520
            virNetworkPtr network =
                virNetworkLookupByName(conn, (const char *) source);
1521
            char *bridge;
1522

1523
            if (!network || !(bridge = virNetworkGetBridgeName(network))) {
1524 1525
                if (network)
                    virNetworkFree(network);
1526 1527
                virXMLError(conn, VIR_ERR_NO_SOURCE, (const char *) source,
                            0);
1528 1529
                goto error;
            }
1530
            virNetworkFree(network);
1531 1532 1533
            virBufferVSprintf(buf, "(bridge '%s')", bridge);
            free(bridge);
        }
1534 1535 1536
    }
    if (script != NULL)
        virBufferVSprintf(buf, "(script '%s')", script);
1537 1538
    if (model != NULL)
        virBufferVSprintf(buf, "(model '%s')", model);
1539 1540
    if (ip != NULL)
        virBufferVSprintf(buf, "(ip '%s')", ip);
1541 1542 1543 1544 1545
    /*
     * apparently (type ioemu) breaks paravirt drivers on HVM so skip this
     * from Xen 3.1.0
     */
    if ((hvm) && (xendConfigVersion < 4))
1546
        virBufferAddLit(buf, "(type ioemu)");
1547

1548
    virBufferAddLit(buf, ")");
1549
    ret = 0;
1550
  error:
1551 1552 1553 1554
    xmlFree(mac);
    xmlFree(source);
    xmlFree(script);
    xmlFree(ip);
1555
    xmlFree(model);
1556
    return (ret);
1557 1558 1559 1560
}

/**
 * virDomainParseXMLDesc:
1561
 * @conn: pointer to the hypervisor connection
1562
 * @xmldesc: string with the XML description
1563
 * @xendConfigVersion: xend configuration file format
1564 1565
 *
 * Parse the XML description and turn it into the xend sexp needed to
D
Daniel Veillard 已提交
1566
 * create the domain. This is a temporary interface as the S-Expr interface
1567 1568 1569 1570 1571 1572 1573
 * will be replaced by XML-RPC in the future. However the XML format should
 * stay valid over time.
 *
 * Returns the 0 terminatedi S-Expr string or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
1574 1575
virDomainParseXMLDesc(virConnectPtr conn, const char *xmldesc, char **name,
                      int xendConfigVersion)
1576
{
1577 1578
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
1579
    char *nam = NULL;
1580
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1581
    xmlChar *prop;
1582
    xmlParserCtxtPtr pctxt;
1583 1584
    xmlXPathContextPtr ctxt = NULL;
    int i, res;
1585
    int bootloader = 0;
1586
    int hvm = 0;
1587
    unsigned int vcpus = 1;
1588
    unsigned long mem = 0, max_mem = 0;
1589 1590 1591 1592
    char *str;
    double f;
    xmlNodePtr *nodes;
    int nb_nodes;
1593 1594

    if (name != NULL)
1595
        *name = NULL;
1596

1597 1598 1599 1600 1601
    pctxt = xmlNewParserCtxt();
    if ((pctxt == NULL) || (pctxt->sax == NULL)) {
        goto error;
    }

1602 1603 1604
    /* TODO pass the connection point to the error handler:
     *   pctxt->userData = virConnectPtr;
     */
1605 1606
    pctxt->sax->error = virCatchXMLParseError;

1607 1608
    xml = xmlCtxtReadDoc(pctxt, (const xmlChar *) xmldesc, "domain.xml",
                         NULL, XML_PARSE_NOENT | XML_PARSE_NONET |
1609
                         XML_PARSE_NOWARNING);
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
    if (xml == NULL) {
        goto error;
    }
    node = xmlDocGetRootElement(xml);
    if ((node == NULL) || (!xmlStrEqual(node->name, BAD_CAST "domain")))
        goto error;

    prop = xmlGetProp(node, BAD_CAST "type");
    if (prop != NULL) {
        if (!xmlStrEqual(prop, BAD_CAST "xen")) {
1620 1621 1622 1623
            xmlFree(prop);
            goto error;
        }
        xmlFree(prop);
1624
    }
1625
    virBufferAddLit(&buf, "(vm ");
1626 1627 1628 1629 1630
    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        goto error;
    }
    /*
1631
     * extract some of the basics, name, memory, cpus ...
1632
     */
1633
    nam = virXPathString("string(/domain/name[1])", ctxt);
1634
    if (nam == NULL) {
1635
        virXMLError(conn, VIR_ERR_NO_NAME, xmldesc, 0);
1636
        goto error;
1637
    }
1638
    virBufferVSprintf(&buf, "(name '%s')", nam);
1639

1640 1641
    if ((virXPathNumber("number(/domain/memory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1642
        max_mem = 128;
1643
    } else {
1644
        max_mem = (f / 1024);
1645
    }
1646

1647 1648
    if ((virXPathNumber("number(/domain/currentMemory[1])", ctxt, &f) < 0)
        || (f < MIN_XEN_GUEST_SIZE * 1024)) {
1649 1650
        mem = max_mem;
    } else {
1651
        mem = (f / 1024);
1652 1653 1654
        if (mem > max_mem) {
            max_mem = mem;
        }
1655
    }
1656
    virBufferVSprintf(&buf, "(memory %lu)(maxmem %lu)", mem, max_mem);
1657

1658 1659 1660
    if ((virXPathNumber("number(/domain/vcpu[1])", ctxt, &f) == 0) &&
        (f > 0)) {
        vcpus = (unsigned int) f;
1661
    }
1662
    virBufferVSprintf(&buf, "(vcpus %u)", vcpus);
1663

1664 1665 1666
    str = virXPathString("string(/domain/vcpu/@cpuset)", ctxt);
    if (str != NULL) {
        int maxcpu = xenNbCpus(conn);
1667 1668 1669 1670 1671 1672 1673 1674 1675
        char *cpuset = NULL;
        char *ranges = NULL;
        const char *cur = str;

        /*
         * Parse the CPUset attribute given in libvirt format and reserialize
         * it in a range format guaranteed to be understood by Xen.
         */
        if (maxcpu > 0) {
1676
            cpuset = malloc(maxcpu * sizeof(*cpuset));
1677 1678 1679
            if (cpuset != NULL) {
                res = virParseCpuSet(conn, &cur, 0, cpuset, maxcpu);
                if (res > 0) {
1680
                    ranges = virSaveCpuSet(conn, cpuset, maxcpu);
1681 1682 1683 1684 1685 1686
                    if (ranges != NULL) {
                        virBufferVSprintf(&buf, "(cpus '%s')", ranges);
                        free(ranges);
                    }
                }
                free(cpuset);
1687
                if (res < 0)
1688
                    goto error;
1689 1690 1691 1692
            } else {
                virXMLError(conn, VIR_ERR_NO_MEMORY, xmldesc, 0);
            }
        }
1693 1694 1695
        free(str);
    }

1696 1697 1698
    str = virXPathString("string(/domain/uuid[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(uuid '%s')", str);
1699
        free(str);
1700 1701
    }

1702 1703 1704
    str = virXPathString("string(/domain/bootloader[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(bootloader '%s')", str);
1705
        /*
1706
         * if using a bootloader, the kernel and initrd strings are not
1707 1708
         * significant and should be discarded
         */
1709
        bootloader = 1;
1710 1711 1712
        free(str);
    } else if (virXPathNumber("count(/domain/bootloader)", ctxt, &f) == 0
               && (f > 0)) {
1713
        virBufferAddLit(&buf, "(bootloader)");
D
Daniel P. Berrange 已提交
1714 1715 1716 1717
        /*
         * if using a bootloader, the kernel and initrd strings are not
         * significant and should be discarded
         */
1718
        bootloader = 1;
1719 1720 1721 1722 1723 1724 1725 1726
    }

    str = virXPathString("string(/domain/bootloader_args[1])", ctxt);
    if (str != NULL && bootloader) {
        /*
         * ignore the bootloader_args value unless a bootloader was specified
         */
        virBufferVSprintf(&buf, "(bootloader_args '%s')", str);
1727
        free(str);
1728 1729
    }

1730 1731 1732
    str = virXPathString("string(/domain/on_poweroff[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_poweroff '%s')", str);
1733
        free(str);
1734 1735
    }

1736 1737 1738
    str = virXPathString("string(/domain/on_reboot[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_reboot '%s')", str);
1739
        free(str);
1740 1741
    }

1742 1743 1744
    str = virXPathString("string(/domain/on_crash[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_crash '%s')", str);
1745
        free(str);
1746 1747
    }

1748
    if (!bootloader) {
1749
        if ((node = virXPathNode("/domain/os[1]", ctxt)) != NULL) {
1750 1751
            int has_kernel = 0;

1752
            /* Analyze of the os description, based on HVM or PV. */
1753
            str = virXPathString("string(/domain/os/type[1])", ctxt);
1754
            if ((str != NULL) && STREQ(str, "hvm"))
1755
                hvm = 1;
1756 1757
            xmlFree(str);
            str = NULL;
1758

1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
            if (hvm)
                virBufferAddLit(&buf, "(image (hvm ");
            else
                virBufferAddLit(&buf, "(image (linux ");

            if (virXPathBoolean("count(/domain/os/kernel) > 0", ctxt)) {
                if (virDomainParseXMLOSDescKernel(conn, node,
                                                  &buf) != 0)
                    goto error;
                has_kernel = 1;
            }
1770

1771 1772 1773 1774 1775
            if (hvm &&
                virDomainParseXMLOSDescHVM(conn, node,
                                           &buf, ctxt, vcpus,
                                           xendConfigVersion,
                                           has_kernel) != 0)
1776
                goto error;
1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797

            /* get the device emulation model */
            str = virXPathString("string(/domain/devices/emulator[1])", ctxt);
            if (str != NULL) {
                virBufferVSprintf(&buf, "(device_model '%s')", str);
                xmlFree(str);
                str = NULL;
            }

            /* PV graphics for xen <= 3.0.4, or HVM graphics for xen <= 3.1.0 */
            if ((!hvm && xendConfigVersion < 3) ||
                (hvm && xendConfigVersion < 4)) {
                xmlNodePtr cur;
                cur = virXPathNode("/domain/devices/graphics[1]", ctxt);
                if (cur != NULL &&
                    virDomainParseXMLGraphicsDescImage(conn, cur, &buf,
                                                       xendConfigVersion) != 0)
                    goto error;
            }

            virBufferAddLit(&buf, "))");
1798
        } else {
1799
            virXMLError(conn, VIR_ERR_NO_OS, nam, 0);
1800 1801
            goto error;
        }
1802 1803 1804
    }

    /* analyze of the devices */
1805 1806 1807 1808
    nb_nodes = virXPathNodeSet("/domain/devices/disk", ctxt, &nodes);
    if (nb_nodes > 0) {
        for (i = 0; i < nb_nodes; i++) {
            res = virDomainParseXMLDiskDesc(conn, nodes[i], &buf,
1809
                                            hvm, xendConfigVersion);
1810
            if (res != 0) {
1811
                free(nodes);
1812 1813 1814
                goto error;
            }
        }
1815
        free(nodes);
1816
    }
1817

1818 1819 1820
    nb_nodes = virXPathNodeSet("/domain/devices/interface", ctxt, &nodes);
    if (nb_nodes > 0) {
        for (i = 0; i < nb_nodes; i++) {
1821
            virBufferAddLit(&buf, "(device ");
1822 1823 1824
            res =
                virDomainParseXMLIfDesc(conn, nodes[i], &buf, hvm,
                                        xendConfigVersion);
1825
            if (res != 0) {
1826
                free(nodes);
1827 1828
                goto error;
            }
1829
            virBufferAddLit(&buf, ")");
1830
        }
1831
        free(nodes);
1832 1833
    }

1834 1835 1836 1837
    /* New style PV graphics config xen >= 3.0.4,
     * or HVM graphics config xen >= 3.0.5 */
    if ((xendConfigVersion >= 3 && !hvm) ||
        (xendConfigVersion >= 4 && hvm)) {
1838
        nb_nodes = virXPathNodeSet("/domain/devices/graphics", ctxt, &nodes);
1839
        if (nb_nodes > 0) {
1840 1841
            for (i = 0; i < nb_nodes; i++) {
                res = virDomainParseXMLGraphicsDescVFB(conn, nodes[i], &buf);
1842
                if (res != 0) {
1843
                    free(nodes);
1844 1845 1846
                    goto error;
                }
            }
1847
            free(nodes);
1848 1849 1850
        }
    }

1851

1852
    virBufferAddLit(&buf, ")"); /* closes (vm */
1853 1854 1855

    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
1856
    xmlFreeParserCtxt(pctxt);
1857 1858

    if (name != NULL)
1859
        *name = nam;
1860 1861
    else
        free(nam);
1862

1863 1864 1865 1866 1867 1868
    if (virBufferError(&buf)) {
        virXMLError(conn, VIR_ERR_NO_MEMORY, _("allocate buffer"), 0);
        return NULL;
    }

    return virBufferContentAndReset(&buf);
1869

1870
  error:
1871
    free(nam);
1872
    if (name != NULL)
1873
        *name = NULL;
1874
    xmlXPathFreeContext(ctxt);
1875 1876
    if (xml != NULL)
        xmlFreeDoc(xml);
1877 1878
    if (pctxt != NULL)
        xmlFreeParserCtxt(pctxt);
1879
    free(virBufferContentAndReset(&buf));
1880
    return (NULL);
1881
}
1882

1883 1884
/**
 * virParseXMLDevice:
1885
 * @conn: pointer to the hypervisor connection
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
 * @xmldesc: string with the XML description
 * @hvm: 1 for fully virtualized guest, 0 for paravirtualized
 * @xendConfigVersion: xend configuration file format
 *
 * Parse the XML description and turn it into the xend sexp needed to
 * create the device. This is a temporary interface as the S-Expr interface
 * will be replaced by XML-RPC in the future. However the XML format should
 * stay valid over time.
 *
 * Returns the 0-terminated S-Expr string, or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
1899 1900
virParseXMLDevice(virConnectPtr conn, const char *xmldesc, int hvm,
                  int xendConfigVersion)
1901 1902 1903
{
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
1904
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1905

1906
    xml = xmlReadDoc((const xmlChar *) xmldesc, "device.xml", NULL,
1907 1908
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
1909 1910
    if (xml == NULL) {
        virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
1911
        goto error;
1912
    }
1913 1914 1915 1916
    node = xmlDocGetRootElement(xml);
    if (node == NULL)
        goto error;
    if (xmlStrEqual(node->name, BAD_CAST "disk")) {
1917
        if (virDomainParseXMLDiskDesc(conn, node, &buf, hvm,
1918
                                      xendConfigVersion) != 0)
1919
            goto error;
1920 1921
    } else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
        if (virDomainParseXMLIfDesc(conn, node, &buf, hvm,
1922
                                    xendConfigVersion) != 0)
1923
            goto error;
1924 1925
    } else {
        virXMLError(conn, VIR_ERR_XML_ERROR, (const char *) node->name, 0);
1926
        goto error;
1927
    }
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937

    xmlFreeDoc(xml);

    if (virBufferError(&buf)) {
        virXMLError(conn, VIR_ERR_NO_MEMORY, _("allocate buffer"), 0);
        return NULL;
    }

    return virBufferContentAndReset(&buf);

1938
  error:
1939 1940 1941
    free(virBufferContentAndReset(&buf));
    xmlFreeDoc(xml);
    return NULL;
1942 1943
}

1944

1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
/**
 * virDomainXMLDevID:
 * @domain: pointer to domain object
 * @xmldesc: string with the XML description
 * @class: Xen device class "vbd" or "vif" (OUT)
 * @ref: Xen device reference (OUT)
 *
 * Set class according to XML root, and:
 *  - if disk, copy in ref the target name from description
 *  - if network, get MAC address from description, scan XenStore and
 *    copy in ref the corresponding vif number.
 *
 * Returns 0 in case of success, -1 in case of failure.
 */
int
1960 1961
virDomainXMLDevID(virDomainPtr domain, const char *xmldesc, char *class,
                  char *ref, int ref_len)
1962 1963 1964 1965
{
    xmlDocPtr xml = NULL;
    xmlNodePtr node, cur;
    xmlChar *attr = NULL;
1966

1967
    char *xref;
1968
    int ret = 0;
1969

1970
    xml = xmlReadDoc((const xmlChar *) xmldesc, "device.xml", NULL,
1971 1972
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
1973 1974
    if (xml == NULL) {
        virXMLError(NULL, VIR_ERR_XML_ERROR, NULL, 0);
1975
        goto error;
1976
    }
1977 1978 1979 1980 1981 1982 1983
    node = xmlDocGetRootElement(xml);
    if (node == NULL)
        goto error;
    if (xmlStrEqual(node->name, BAD_CAST "disk")) {
        strcpy(class, "vbd");
        for (cur = node->children; cur != NULL; cur = cur->next) {
            if ((cur->type != XML_ELEMENT_NODE) ||
1984 1985
                (!xmlStrEqual(cur->name, BAD_CAST "target")))
                continue;
1986 1987 1988
            attr = xmlGetProp(cur, BAD_CAST "dev");
            if (attr == NULL)
                goto error;
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
            xref = xenStoreDomainGetDiskID(domain->conn, domain->id,
                                              (char *) attr);
            if (xref != NULL) {
                strncpy(ref, xref, ref_len);
                free(xref);
                ref[ref_len - 1] = '\0';
                goto cleanup;
            }
            /* hack to avoid the warning that domain is unused */
            if (domain->id < 0)
                ret = -1;

            goto error;
2002
        }
2003
    } else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
2004 2005 2006
        strcpy(class, "vif");
        for (cur = node->children; cur != NULL; cur = cur->next) {
            if ((cur->type != XML_ELEMENT_NODE) ||
2007 2008
                (!xmlStrEqual(cur->name, BAD_CAST "mac")))
                continue;
2009 2010 2011 2012
            attr = xmlGetProp(cur, BAD_CAST "address");
            if (attr == NULL)
                goto error;

2013
            xref = xenStoreDomainGetNetworkID(domain->conn, domain->id,
2014 2015
                                              (char *) attr);
            if (xref != NULL) {
2016
                strncpy(ref, xref, ref_len);
2017
                free(xref);
2018
                ref[ref_len - 1] = '\0';
2019 2020
                goto cleanup;
            }
2021 2022
            /* hack to avoid the warning that domain is unused */
            if (domain->id < 0)
2023
                ret = -1;
2024

2025 2026
            goto error;
        }
2027 2028
    } else {
        virXMLError(NULL, VIR_ERR_XML_ERROR, (const char *) node->name, 0);
2029
    }
2030
  error:
2031
    ret = -1;
2032
  cleanup:
2033 2034
    if (xml != NULL)
        xmlFreeDoc(xml);
2035
    xmlFree(attr);
2036 2037
    return ret;
}
2038
#endif /* WITH_XEN */
2039
#endif /* !PROXY */