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

11
#include "libvirt/libvirt.h"
12 13 14 15 16

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
17
#ifdef WITH_XEN
18
#include <xs.h>
19
#endif
20
#include <math.h> /* for isnan() */
21 22
#include "internal.h"
#include "hash.h"
D
Daniel Veillard 已提交
23
#include "sexpr.h"
24
#include "xml.h"
25
#include "buf.h"
26
#include "xs_internal.h" /* for xenStoreDomainGetNetworkID */
27

28
#ifndef PROXY
29 30 31 32 33 34 35 36 37
/**
 * 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.
 */
38
static void
39
virXMLError(virConnectPtr conn, virErrorNumber error, const char *info, int value)
40
{
41
    const char *errmsg;
42

43 44 45 46
    if (error == VIR_ERR_OK)
        return;

    errmsg = __virErrorMsg(error, info);
47
    __virRaiseError(conn, NULL, NULL, VIR_FROM_XML, error, VIR_ERR_ERROR,
48
                    errmsg, info, NULL, value, 0, errmsg, info, value);
49 50
}

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
/**
 * 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 *
virXPathString(const char *xpath, xmlXPathContextPtr ctxt) {
    xmlXPathObjectPtr obj;
    char *ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR, 
	            "Invalid parameter to virXPathString()", 0);
        return(NULL);
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0))
        return(NULL);
    ret = strdup((char *) obj->stringval);
    xmlXPathFreeObject(obj);
    if (ret == NULL) {
        virXMLError(NULL, VIR_ERR_NO_MEMORY, "strdup", 0);
    }
    return(ret);
}

/**
 * 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
virXPathNumber(const char *xpath, xmlXPathContextPtr ctxt, double *value) {
    xmlXPathObjectPtr obj;

    if ((ctxt == NULL) || (xpath == NULL) || (value == NULL)) {
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR, 
	            "Invalid parameter to virXPathNumber()", 0);
        return(-1);
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NUMBER) ||
        (isnan(obj->floatval))) {
	xmlXPathFreeObject(obj);
	return(-1);
    }
    
    *value = obj->floatval;
    xmlXPathFreeObject(obj);
    return(0);
}

/**
 * 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,
124 125
 *         or -1 if the XPath evaluation failed or -2 if the
 *         value doesn't have a long format.
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
 */
int
virXPathLong(const char *xpath, xmlXPathContextPtr ctxt, long *value) {
    xmlXPathObjectPtr obj;
    int ret = 0;

    if ((ctxt == NULL) || (xpath == NULL) || (value == NULL)) {
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR, 
	            "Invalid parameter to virXPathNumber()", 0);
        return(-1);
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        char *conv = NULL;
	long val;

        val = strtol((const char*)obj->stringval, &conv, 10);
        if (conv == (const char*)obj->stringval) {
            ret = -2;
        } else {
	    *value = val;
	}
    } else if ((obj != NULL) && (obj->type == XPATH_NUMBER) &&
               (!(isnan(obj->floatval)))) {
	*value = (long) obj->floatval;
	if (*value != obj->floatval) {
	    ret = -2;
	}
    } else {
	ret = -1;
    }
    
    xmlXPathFreeObject(obj);
    return(ret);
}

/**
 * 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
virXPathBoolean(const char *xpath, xmlXPathContextPtr ctxt) {
    xmlXPathObjectPtr obj;
    int ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR, 
	            "Invalid parameter to virXPathBoolean()", 0);
        return(-1);
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_BOOLEAN) ||
        (obj->boolval < 0) || (obj->boolval > 1)) {
	xmlXPathFreeObject(obj);
	return(-1);
    }
    ret = obj->boolval;
    
    xmlXPathFreeObject(obj);
    return(ret);
}

/**
 * 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
virXPathNode(const char *xpath, xmlXPathContextPtr ctxt) {
    xmlXPathObjectPtr obj;
    xmlNodePtr ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR, 
	            "Invalid parameter to virXPathNode()", 0);
        return(NULL);
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr <= 0) ||
	(obj->nodesetval->nodeTab == NULL)) {
	xmlXPathFreeObject(obj);
	return(NULL);
    }
    
    ret = obj->nodesetval->nodeTab[0];
    xmlXPathFreeObject(obj);
    return(ret);
}
/**
 * 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
virXPathNodeSet(const char *xpath, xmlXPathContextPtr ctxt, xmlNodePtr **list) {
    xmlXPathObjectPtr obj;
    int ret;

    if ((ctxt == NULL) || (xpath == NULL)) {
        virXMLError(NULL, VIR_ERR_INTERNAL_ERROR, 
	            "Invalid parameter to virXPathNodeSet()", 0);
        return(-1);
    }
    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr <= 0) ||
	(obj->nodesetval->nodeTab == NULL)) {
	xmlXPathFreeObject(obj);
	if (list != NULL)
	    *list = NULL;
	return(-1);
    }
    
    ret = obj->nodesetval->nodeNr;
    if (list != NULL) {
	*list = malloc(ret * sizeof(xmlNodePtr));
	if (*list == NULL) {
	    virXMLError(NULL, VIR_ERR_NO_MEMORY, 
	                _("allocate string array"), ret * sizeof(xmlNodePtr));
	} else {
	    memcpy(*list, obj->nodesetval->nodeTab, ret * sizeof(xmlNodePtr));
	}
    }
    xmlXPathFreeObject(obj);
    return(ret);
}

271
/**
272
 * virtDomainParseXMLGraphicsDescImage:
273
 * @conn: pointer to the hypervisor connection
274 275
 * @node: node containing graphics description
 * @buf: a buffer for the result S-Expr
276
 * @xendConfigVersion: xend configuration file format
277
 *
278 279 280
 * 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
281 282 283 284
 * valid over time.
 *
 * Returns 0 in case of success, -1 in case of error
 */
285
static int virDomainParseXMLGraphicsDescImage(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf, int xendConfigVersion)
286 287 288 289 290 291 292
{
    xmlChar *graphics_type = NULL;

    graphics_type = xmlGetProp(node, BAD_CAST "type");
    if (graphics_type != NULL) {
        if (xmlStrEqual(graphics_type, BAD_CAST "sdl")) {
            virBufferAdd(buf, "(sdl 1)", 7);
293 294 295 296 297 298
            /* TODO:
             * Need to understand sdl options
             *
             *virBufferAdd(buf, "(display localhost:10.0)", 24);
             *virBufferAdd(buf, "(xauthority /root/.Xauthority)", 30);
             */
299
        }
300
        else if (xmlStrEqual(graphics_type, BAD_CAST "vnc")) {
301
            virBufferAdd(buf, "(vnc 1)", 7);
302
            if (xendConfigVersion >= 2) {
303
                xmlChar *vncport = xmlGetProp(node, BAD_CAST "port");
304 305
                xmlChar *vnclisten = xmlGetProp(node, BAD_CAST "listen");
                xmlChar *vncpasswd = xmlGetProp(node, BAD_CAST "passwd");
306
                xmlChar *keymap = xmlGetProp(node, BAD_CAST "keymap");
307
                if (vncport != NULL) {
308
                    long port = strtol((const char *)vncport, NULL, 10);
309 310
                    if (port == -1)
                        virBufferAdd(buf, "(vncunused 1)", 13);
311
                    else if (port >= 5900)
312
                        virBufferVSprintf(buf, "(vncdisplay %ld)", port - 5900);
313
                    xmlFree(vncport);
314
                }
315 316 317 318 319 320 321 322
                if (vnclisten != NULL) {
                    virBufferVSprintf(buf, "(vnclisten %s)", vnclisten);
                    xmlFree(vnclisten);
                }
                if (vncpasswd != NULL) {
                    virBufferVSprintf(buf, "(vncpasswd %s)", vncpasswd);
                    xmlFree(vncpasswd);
                }
323 324 325 326
                if (keymap != NULL) {
                    virBufferVSprintf(buf, "(keymap %s)", keymap);
                    xmlFree(keymap);
                }
327 328
            }
        }
329 330 331 332 333 334
        xmlFree(graphics_type);
    }
    return 0;
}


335 336
/**
 * virtDomainParseXMLGraphicsDescVFB:
337
 * @conn: pointer to the hypervisor connection
338 339 340
 * @node: node containing graphics description
 * @buf: a buffer for the result S-Expr
 *
341 342 343
 * 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
344 345 346 347
 * valid over time.
 *
 * Returns 0 in case of success, -1 in case of error
 */
348
static int virDomainParseXMLGraphicsDescVFB(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf)
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
{
    xmlChar *graphics_type = NULL;

    graphics_type = xmlGetProp(node, BAD_CAST "type");
    if (graphics_type != NULL) {
        virBufferAdd(buf, "(device (vkbd))", 15);
        virBufferAdd(buf, "(device (vfb ", 13);
        if (xmlStrEqual(graphics_type, BAD_CAST "sdl")) {
            virBufferAdd(buf, "(type sdl)", 10);
            /* TODO:
             * Need to understand sdl options
             *
             *virBufferAdd(buf, "(display localhost:10.0)", 24);
             *virBufferAdd(buf, "(xauthority /root/.Xauthority)", 30);
             */
        }
        else if (xmlStrEqual(graphics_type, BAD_CAST "vnc")) {
            virBufferAdd(buf, "(type vnc)", 10);
            xmlChar *vncport = xmlGetProp(node, BAD_CAST "port");
            xmlChar *vnclisten = xmlGetProp(node, BAD_CAST "listen");
            xmlChar *vncpasswd = xmlGetProp(node, BAD_CAST "passwd");
370
            xmlChar *keymap = xmlGetProp(node, BAD_CAST "keymap");
371 372 373 374
            if (vncport != NULL) {
                long port = strtol((const char *)vncport, NULL, 10);
                if (port == -1)
                    virBufferAdd(buf, "(vncunused 1)", 13);
375
                else if (port >= 5900)
376
                    virBufferVSprintf(buf, "(vncdisplay %ld)", port - 5900);
377 378 379 380 381 382 383 384 385 386
                xmlFree(vncport);
            }
            if (vnclisten != NULL) {
                virBufferVSprintf(buf, "(vnclisten %s)", vnclisten);
                xmlFree(vnclisten);
            }
            if (vncpasswd != NULL) {
                virBufferVSprintf(buf, "(vncpasswd %s)", vncpasswd);
                xmlFree(vncpasswd);
            }
387 388 389 390
            if (keymap != NULL) {
                virBufferVSprintf(buf, "(keymap %s)", keymap);
                xmlFree(keymap);
            }
391 392 393 394 395 396 397 398
        }
        virBufferAdd(buf, "))", 2);
        xmlFree(graphics_type);
    }
    return 0;
}


399
/**
400
 * virDomainParseXMLOSDescHVM:
401
 * @conn: pointer to the hypervisor connection
402
 * @node: node containing HVM OS description
403
 * @buf: a buffer for the result S-Expr
404
 * @ctxt: a path context representing the XML description
405
 * @vcpus: number of virtual CPUs to configure
406
 * @xendConfigVersion: xend configuration file format
407
 *
408 409
 * Parse the OS part of the XML description for an HVM domain and add it to
 * the S-Expr in buf. This is a temporary interface as the S-Expr interface
410 411 412 413 414 415
 * 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
416
virDomainParseXMLOSDescHVM(virConnectPtr conn, xmlNodePtr node, virBufferPtr buf, xmlXPathContextPtr ctxt, int vcpus, int xendConfigVersion)
417 418
{
    xmlNodePtr cur, txt;
419 420
    xmlChar *type = NULL;
    xmlChar *loader = NULL;
421 422
    char bootorder[5];
    int nbootorder = 0;
423
    int res;
424
    char *str;
425 426 427 428 429 430 431 432

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((type == NULL)
                && (xmlStrEqual(cur->name, BAD_CAST "type"))) {
                txt = cur->children;
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
433
                    (txt->next == NULL))
434 435 436 437 438
                    type = txt->content;
            } else if ((loader == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "loader"))) {
                txt = cur->children;
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
439
                    (txt->next == NULL))
440
                    loader = txt->content;
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
            } else if ((xmlStrEqual(cur->name, BAD_CAST "boot"))) {
                xmlChar *boot_dev = xmlGetProp(cur, BAD_CAST "dev");
                if (nbootorder == ((sizeof(bootorder)/sizeof(bootorder[0]))-1)) {
                    virXMLError(conn, VIR_ERR_XML_ERROR, "too many boot devices", 0);
                    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);
462 463 464 465
            }
        }
        cur = cur->next;
    }
466
    bootorder[nbootorder] = '\0';
467 468
    if ((type == NULL) || (!xmlStrEqual(type, BAD_CAST "hvm"))) {
        /* VIR_ERR_OS_TYPE */
469
        virXMLError(conn, VIR_ERR_OS_TYPE, (const char *) type, 0);
470 471 472 473
        return (-1);
    }
    virBufferAdd(buf, "(image (hvm ", 12);
    if (loader == NULL) {
474
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0);
475
        goto error;
476
    } else {
477
        virBufferVSprintf(buf, "(kernel '%s')", (const char *) loader);
478 479 480
    }

    /* get the device emulation model */
481 482
    str = virXPathString("string(/domain/devices/emulator[1])", ctxt);
    if (str == NULL) {
483
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0); /* TODO: error */
484 485
        goto error;
    }
486 487
    virBufferVSprintf(buf, "(device_model '%s')", str);
    xmlFree(str);
488

489 490
    virBufferVSprintf(buf, "(vcpus %d)", vcpus);

491 492
    if (nbootorder)
        virBufferVSprintf(buf, "(boot %s)", bootorder);
493

494 495 496
    /* get the 1st floppy device file */
	cur = virXPathNode("/domain/devices/disk[@device='floppy' and target/@dev='fda']/source",
                       ctxt);
497
	if (cur != NULL) {
498 499
        xmlChar *fdfile;
        fdfile = xmlGetProp(cur, BAD_CAST "file");
500
	    if (fdfile != NULL) {
501 502
            virBufferVSprintf(buf, "(fda '%s')", fdfile);
            free(fdfile);
503
	    }
504
    }
505

506 507 508
    /* get the 2nd floppy device file */
	cur = virXPathNode("/domain/devices/disk[@device='floppy' and target/@dev='fdb']/source",
                       ctxt);
509
	if (cur != NULL) {
510 511
        xmlChar *fdfile;
        fdfile = xmlGetProp(cur, BAD_CAST "file");
512
	    if (fdfile != NULL) {
513 514
            virBufferVSprintf(buf, "(fdb '%s')", fdfile);
            free(fdfile);
515
	    }
516
    }
517 518


519 520 521 522
    /* get the cdrom device file */
    /* Only XenD <= 3.0.2 wants cdrom config here */
    if (xendConfigVersion == 1) {
	    cur = virXPathNode("/domain/devices/disk[@device='cdrom' and target/@dev='hdc']/source",
523 524
	                       ctxt);
	    if (cur != NULL) {
525 526 527 528 529 530 531
            xmlChar *cdfile;

            cdfile = xmlGetProp(cur, BAD_CAST "file");
            if (cdfile != NULL) {
                virBufferVSprintf(buf, "(cdrom '%s')",
                                  (const char *)cdfile);
                xmlFree(cdfile);
532 533
            }
        }
534 535
    }

536 537 538 539 540 541 542
    if (virXPathNode("/domain/features/acpi", ctxt) != NULL)
        virBufferAdd(buf, "(acpi 1)", 8);
    if (virXPathNode("/domain/features/apic", ctxt) != NULL)
        virBufferAdd(buf, "(apic 1)", 8);
    if (virXPathNode("/domain/features/pae", ctxt) != NULL)
        virBufferAdd(buf, "(pae 1)", 7);

543 544
    res = virXPathBoolean("count(domain/devices/console) > 0", ctxt);
    if (res < 0) {
545
        virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
546
        goto error;
547
    }
548
    if (res) {
549
        virBufferAdd(buf, "(serial pty)", 12);
550
    }
551

552 553 554 555 556 557 558 559 560 561
    /* HVM graphics for xen <= 3.0.5 */
    if (xendConfigVersion < 4) {
        /* Is a graphics device specified? */
        cur = virXPathNode("/domain/devices/graphics[1]", ctxt);
        if (cur != NULL) {
            res = virDomainParseXMLGraphicsDescImage(conn, cur, buf,
                                                     xendConfigVersion);
            if (res != 0) {
                goto error;
            }
562 563 564 565 566 567
        }
    }

    virBufferAdd(buf, "))", 2);

    return (0);
568

569
 error:
570 571 572 573 574
    return(-1);
}

/**
 * virDomainParseXMLOSDescPV:
575
 * @conn: pointer to the hypervisor connection
576 577
 * @node: node containing PV OS description
 * @buf: a buffer for the result S-Expr
578
 * @ctxt: a path context representing the XML description
579
 * @xendConfigVersion: xend configuration file format
580 581 582 583 584 585 586 587 588
 *
 * Parse the OS part of the XML description for a paravirtualized domain
 * 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
589
virDomainParseXMLOSDescPV(virConnectPtr conn, xmlNodePtr node, virBufferPtr buf, xmlXPathContextPtr ctxt, int xendConfigVersion)
590
{
591 592 593 594 595 596
    xmlNodePtr cur, txt;
    const xmlChar *type = NULL;
    const xmlChar *root = NULL;
    const xmlChar *kernel = NULL;
    const xmlChar *initrd = NULL;
    const xmlChar *cmdline = NULL;
597
    int res;
598 599 600 601

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
602 603 604
            if ((type == NULL)
                && (xmlStrEqual(cur->name, BAD_CAST "type"))) {
                txt = cur->children;
605
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
606
                    (txt->next == NULL))
607 608 609 610
                    type = txt->content;
            } else if ((kernel == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "kernel"))) {
                txt = cur->children;
611
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
612
                    (txt->next == NULL))
613 614 615 616
                    kernel = txt->content;
            } else if ((root == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "root"))) {
                txt = cur->children;
617
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
618
                    (txt->next == NULL))
619 620 621 622
                    root = txt->content;
            } else if ((initrd == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "initrd"))) {
                txt = cur->children;
623
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
624
                    (txt->next == NULL))
625 626 627 628
                    initrd = txt->content;
            } else if ((cmdline == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "cmdline"))) {
                txt = cur->children;
629
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
630
                    (txt->next == NULL))
631 632 633
                    cmdline = txt->content;
            }
        }
634 635 636 637
        cur = cur->next;
    }
    if ((type != NULL) && (!xmlStrEqual(type, BAD_CAST "linux"))) {
        /* VIR_ERR_OS_TYPE */
638
        virXMLError(conn, VIR_ERR_OS_TYPE, (const char *) type, 0);
639
        return (-1);
640
    }
641
    virBufferAdd(buf, "(image (linux ", 14);
642
    if (kernel == NULL) {
643
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0);
644
        return (-1);
645
    } else {
646
        virBufferVSprintf(buf, "(kernel '%s')", (const char *) kernel);
647 648
    }
    if (initrd != NULL)
649
        virBufferVSprintf(buf, "(ramdisk '%s')", (const char *) initrd);
650
    if (root != NULL)
651
        virBufferVSprintf(buf, "(root '%s')", (const char *) root);
652
    if (cmdline != NULL)
653
        virBufferVSprintf(buf, "(args '%s')", (const char *) cmdline);
654

655
    /* PV graphics for xen <= 3.0.4 */
656
    if (xendConfigVersion < 3) {
657 658 659
        cur = virXPathNode("/domain/devices/graphics[1]", ctxt);
        if (cur != NULL) {
            res = virDomainParseXMLGraphicsDescImage(conn, cur, buf,
660
                                                     xendConfigVersion);
661 662 663
            if (res != 0) {
                goto error;
            }
664 665 666 667
        }
    }

 error:
668
    virBufferAdd(buf, "))", 2);
669
    return (0);
670 671
}

672 673 674 675 676 677 678 679 680 681
/**
 * 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
682
virCatchXMLParseError(void *ctx, const char *msg ATTRIBUTE_UNUSED, ...) {
683 684
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;

685
    if ((ctxt != NULL) &&
686
        (ctxt->lastError.level == XML_ERR_FATAL) &&
687
        (ctxt->lastError.message != NULL)) {
688
        virXMLError(NULL, VIR_ERR_XML_DETAIL, ctxt->lastError.message,
689
                    ctxt->lastError.line);
690 691 692
    }
}

693 694
/**
 * virDomainParseXMLDiskDesc:
695
 * @node: node containing disk description
696
 * @conn: pointer to the hypervisor connection
697
 * @buf: a buffer for the result S-Expr
698
 * @xendConfigVersion: xend configuration file format
699 700 701 702 703 704 705 706 707
 *
 * 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
708
virDomainParseXMLDiskDesc(virConnectPtr conn, xmlNodePtr node, virBufferPtr buf, int hvm, int xendConfigVersion)
709
{
710 711
    xmlNodePtr cur;
    xmlChar *type = NULL;
712
    xmlChar *device = NULL;
713 714
    xmlChar *source = NULL;
    xmlChar *target = NULL;
715 716
    xmlChar *drvName = NULL;
    xmlChar *drvType = NULL;
717
    int ro = 0;
718
    int shareable = 0;
719
    int typ = 0;
720
    int cdrom = 0;
721
    int isNoSrcCdrom = 0;
722
    int ret = 0;
723 724 725

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
726 727 728 729 730
        if (xmlStrEqual(type, BAD_CAST "file"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "block"))
            typ = 1;
        xmlFree(type);
731
    }
732
    device = xmlGetProp(node, BAD_CAST "device");
733

734 735 736
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
737 738 739 740 741 742 743 744 745 746
            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");
747 748 749 750 751
            } else if ((drvName == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "driver"))) {
                drvName = xmlGetProp(cur, BAD_CAST "name");
                if (drvName && !strcmp((const char *)drvName, "tap"))
                    drvType = xmlGetProp(cur, BAD_CAST "type");
752 753
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                ro = 1;
754
            } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
755
                shareable = 1;
756 757
            }
        }
758 759 760 761
        cur = cur->next;
    }

    if (source == NULL) {
762 763 764 765 766 767 768 769 770 771
        /* There is a case without the source
         * to the CD-ROM device
         */
        if (hvm &&
            device &&
            !strcmp((const char *)device, "cdrom")) {
            isNoSrcCdrom = 1;
        }
        if (!isNoSrcCdrom) {
            virXMLError(conn, VIR_ERR_NO_SOURCE, (const char *) target, 0);
772 773
            ret = -1;
            goto cleanup;
774
        }
775 776
    }
    if (target == NULL) {
777
        virXMLError(conn, VIR_ERR_NO_TARGET, (const char *) source, 0);
778 779
        ret = -1;
        goto cleanup;
780
    }
781

782 783
    /* Xend (all versions) put the floppy device config
     * under the hvm (image (os)) block
784
     */
785
    if (hvm &&
786
        device &&
787
        !strcmp((const char *)device, "floppy")) {
788
        goto cleanup;
789 790 791
    }

    /* Xend <= 3.0.2 doesn't include cdrom config here */
792
    if (hvm &&
793 794
        device &&
        !strcmp((const char *)device, "cdrom")) {
795
        if (xendConfigVersion == 1)
796
            goto cleanup;
797 798
        else
            cdrom = 1;
799 800 801 802
    }


    virBufferAdd(buf, "(device ", 8);
803 804 805 806 807 808 809 810
    /* Normally disks are in a (device (vbd ...)) block
       but blktap disks ended up in a differently named
       (device (tap ....)) block.... */
    if (drvName && !strcmp((const char *)drvName, "tap")) {
        virBufferAdd(buf, "(tap ", 5);
    } else {
        virBufferAdd(buf, "(vbd ", 5);
    }
811

812 813
    if (hvm) {
        char *tmp = (char *)target;
814
        /* Just in case user mistakenly still puts ioemu: in their XML */
815 816
        if (!strncmp((const char *) tmp, "ioemu:", 6))
            tmp += 6;
817 818 819

        /* Xend <= 3.0.2 wants a ioemu: prefix on devices for HVM */
        if (xendConfigVersion == 1)
820
            virBufferVSprintf(buf, "(dev 'ioemu:%s')", (const char *)tmp);
821
        else /* But newer does not */
822
            virBufferVSprintf(buf, "(dev '%s%s')", (const char *)tmp, cdrom ? ":cdrom" : ":disk");
823
    } else
824 825
        virBufferVSprintf(buf, "(dev '%s')", (const char *)target);

826
    if (drvName && !isNoSrcCdrom) {
827 828 829 830 831 832 833 834 835 836
        if (!strcmp((const char *)drvName, "tap")) {
            virBufferVSprintf(buf, "(uname '%s:%s:%s')",
                              (const char *)drvName,
                              (drvType ? (const char *)drvType : "aio"),
                              (const char *)source);
        } else {
            virBufferVSprintf(buf, "(uname '%s:%s')",
                              (const char *)drvName,
                              (const char *)source);
        }
837
    } else if (!isNoSrcCdrom) {
838 839 840 841 842 843 844 845
        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);
        }
846
    }
847
    if (ro == 1)
848
        virBufferVSprintf(buf, "(mode 'r')");
849 850 851 852
    else if (shareable == 1)
        virBufferVSprintf(buf, "(mode 'w!')");
    else
        virBufferVSprintf(buf, "(mode 'w')");
853

854
    virBufferAdd(buf, ")", 1);
855
    virBufferAdd(buf, ")", 1);
856 857

 cleanup:
858 859 860 861 862 863 864 865 866 867 868
    if(drvType)
        xmlFree(drvType);
    if(drvName)
        xmlFree(drvName);
    if(device)
        xmlFree(device);
    if(target)
        xmlFree(target);
    if(source)
        xmlFree(source);
    return (ret);
869 870 871 872
}

/**
 * virDomainParseXMLIfDesc:
873
 * @conn: pointer to the hypervisor connection
874
 * @node: node containing the interface description
875
 * @buf: a buffer for the result S-Expr
876
 * @xendConfigVersion: xend configuration file format
877 878 879 880 881 882 883 884 885
 *
 * 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
886
virDomainParseXMLIfDesc(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf, int hvm, int xendConfigVersion)
887
{
888 889 890 891 892
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *source = NULL;
    xmlChar *mac = NULL;
    xmlChar *script = NULL;
893
    xmlChar *ip = NULL;
894
    int typ = 0;
895
    int ret = -1;
896 897 898

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
899 900 901 902
        if (xmlStrEqual(type, BAD_CAST "bridge"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            typ = 1;
903 904
        else if (xmlStrEqual(type, BAD_CAST "network"))
            typ = 2;
905
        xmlFree(type);
906 907 908 909
    }
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
910 911 912 913
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "bridge");
914
                else if (typ == 1)
915
                    source = xmlGetProp(cur, BAD_CAST "dev");
916 917
                else
                    source = xmlGetProp(cur, BAD_CAST "network");
918 919 920 921 922 923
            } 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");
924 925 926 927 928 929 930
            } else if ((ip == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "ip"))) {
                /* XXX in future expect to need to have > 1 ip
                   address element - eg ipv4 & ipv6. For now
                   xen only supports a single address though
                   so lets ignore that complication */
                ip = xmlGetProp(cur, BAD_CAST "address");
931 932
            }
        }
933 934 935 936
        cur = cur->next;
    }

    virBufferAdd(buf, "(vif ", 5);
937 938 939 940 941 942 943 944 945 946 947 948 949 950
    if (mac != NULL) {
        unsigned int addr[12];
        int tmp = sscanf((const char *)mac,
	        "%01x%01x:%01x%01x:%01x%01x:%01x%01x:%01x%01x:%01x%01x",
                (unsigned int*)&addr[0], (unsigned int*)&addr[1],
		(unsigned int*)&addr[2], (unsigned int*)&addr[3],
		(unsigned int*)&addr[4], (unsigned int*)&addr[5],
                (unsigned int*)&addr[6], (unsigned int*)&addr[7],
		(unsigned int*)&addr[8], (unsigned int*)&addr[9],
		(unsigned int*)&addr[10], (unsigned int*)&addr[11]);
        if (tmp != 12 || strlen((const char *) mac) != 17) {
            virXMLError(conn, VIR_ERR_INVALID_MAC, (const char *) mac, 0);
            goto error;
        }
951
        virBufferVSprintf(buf, "(mac '%s')", (const char *) mac);
952
    }
953
    if (source != NULL) {
954 955
        if (typ == 0)
            virBufferVSprintf(buf, "(bridge '%s')", (const char *) source);
956
        else if (typ == 1)      /* TODO does that work like that ? */
957
            virBufferVSprintf(buf, "(dev '%s')", (const char *) source);
958 959 960 961 962 963 964 965 966 967
        else {
            virNetworkPtr network = virNetworkLookupByName(conn, (const char *) source);
            char *bridge;
            if (!network || !(bridge = virNetworkGetBridgeName(network))) {
                virXMLError(conn, VIR_ERR_NO_SOURCE, (const char *) source, 0);
                goto error;
            }
            virBufferVSprintf(buf, "(bridge '%s')", bridge);
            free(bridge);
        }
968 969 970
    }
    if (script != NULL)
        virBufferVSprintf(buf, "(script '%s')", script);
971 972
    if (ip != NULL)
        virBufferVSprintf(buf, "(ip '%s')", ip);
973 974 975 976 977
    /*
     * apparently (type ioemu) breaks paravirt drivers on HVM so skip this
     * from Xen 3.1.0
     */
    if ((hvm) && (xendConfigVersion < 4))
978
        virBufferAdd(buf, "(type ioemu)", 12);
979 980

    virBufferAdd(buf, ")", 1);
981 982
    ret = 0;
 error:
983
    if (mac != NULL)
984
        xmlFree(mac);
985
    if (source != NULL)
986
        xmlFree(source);
987
    if (script != NULL)
988
        xmlFree(script);
989 990
    if (ip != NULL)
        xmlFree(ip);
991
    return (ret);
992 993 994 995
}

/**
 * virDomainParseXMLDesc:
996
 * @conn: pointer to the hypervisor connection
997
 * @xmldesc: string with the XML description
998
 * @xendConfigVersion: xend configuration file format
999 1000 1001 1002 1003 1004 1005 1006 1007 1008
 *
 * Parse the XML description and turn it into the xend sexp needed to
 * create the comain. 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 terminatedi S-Expr string or NULL in case of error.
 *         the caller must free() the returned value.
 */
char *
1009
virDomainParseXMLDesc(virConnectPtr conn, const char *xmldesc, char **name, int xendConfigVersion)
1010
{
1011 1012
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
1013
    char *nam = NULL;
1014 1015
    virBuffer buf;
    xmlChar *prop;
1016
    xmlParserCtxtPtr pctxt;
1017 1018
    xmlXPathContextPtr ctxt = NULL;
    int i, res;
1019
    int bootloader = 0;
1020
    int hvm = 0;
1021
    unsigned int vcpus = 1;
1022
    unsigned long mem = 0, max_mem = 0;
1023 1024 1025 1026
    char *str;
    double f;
    xmlNodePtr *nodes;
    int nb_nodes;
1027 1028

    if (name != NULL)
1029
        *name = NULL;
1030 1031
    buf.content = malloc(1000);
    if (buf.content == NULL)
1032
        return (NULL);
1033 1034 1035
    buf.size = 1000;
    buf.use = 0;

1036 1037 1038 1039 1040
    pctxt = xmlNewParserCtxt();
    if ((pctxt == NULL) || (pctxt->sax == NULL)) {
        goto error;
    }

1041 1042 1043
    /* TODO pass the connection point to the error handler:
     *   pctxt->userData = virConnectPtr;
     */
1044 1045 1046 1047 1048
    pctxt->sax->error = virCatchXMLParseError;

    xml = xmlCtxtReadDoc(pctxt, (const xmlChar *) xmldesc, "domain.xml", NULL,
                         XML_PARSE_NOENT | XML_PARSE_NONET |
                         XML_PARSE_NOWARNING);
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    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")) {
1059 1060 1061 1062
            xmlFree(prop);
            goto error;
        }
        xmlFree(prop);
1063 1064 1065 1066 1067 1068 1069
    }
    virBufferAdd(&buf, "(vm ", 4);
    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        goto error;
    }
    /*
1070
     * extract some of the basics, name, memory, cpus ...
1071
     */
1072
    nam = virXPathString("string(/domain/name[1])", ctxt);
1073
    if (nam == NULL) {
1074
        virXMLError(conn, VIR_ERR_NO_NAME, xmldesc, 0);
1075
        goto error;
1076
    }
1077
    virBufferVSprintf(&buf, "(name '%s')", nam);
1078

1079 1080
    if ((virXPathNumber("number(/domain/memory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1081
        max_mem = 128;
1082
    } else {
1083
        max_mem = (f / 1024);
1084
    }
1085 1086 1087

    if ((virXPathNumber("number(/domain/currentMemory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1088 1089
        mem = max_mem;
    } else {
1090
        mem = (f / 1024);
1091 1092 1093
        if (mem > max_mem) {
            max_mem = mem;
        }
1094
    }
1095
    virBufferVSprintf(&buf, "(memory %lu)(maxmem %lu)", mem, max_mem);
1096

1097 1098 1099
    if ((virXPathNumber("number(/domain/vcpu[1])", ctxt, &f) == 0) &&
        (f > 0)) {
        vcpus = (unsigned int) f;
1100
    }
1101
    virBufferVSprintf(&buf, "(vcpus %u)", vcpus);
1102

1103 1104 1105 1106
    str = virXPathString("string(/domain/uuid[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(uuid '%s')", str);
	free(str);
1107 1108
    }

1109 1110 1111
    str = virXPathString("string(/domain/bootloader[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(bootloader '%s')", str);
1112
        /*
1113
         * if using a bootloader, the kernel and initrd strings are not
1114 1115
         * significant and should be discarded
         */
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
        bootloader = 1;
	free(str);
    }

    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);
1126
	free(str);
1127 1128
    }

1129 1130 1131 1132
    str = virXPathString("string(/domain/on_poweroff[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_poweroff '%s')", str);
	free(str);
1133 1134
    }

1135 1136 1137 1138
    str = virXPathString("string(/domain/on_reboot[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_reboot '%s')", str);
	free(str);
1139 1140
    }

1141 1142 1143 1144
    str = virXPathString("string(/domain/on_crash[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_crash '%s')", str);
	free(str);
1145 1146
    }

1147
    if (!bootloader) {
1148
        if ((node = virXPathNode("/domain/os[1]", ctxt)) != NULL) {
1149
            /* Analyze of the os description, based on HVM or PV. */
1150
            str = virXPathString("string(/domain/os/type[1])", ctxt);
1151

1152 1153
            if ((str == NULL) || (strcmp(str, "hvm"))) {
                res = virDomainParseXMLOSDescPV(conn, node,
1154 1155 1156
                                                &buf, ctxt, xendConfigVersion);
            } else {
                hvm = 1;
1157 1158
                res = virDomainParseXMLOSDescHVM(conn, node, &buf, ctxt,
		                                 vcpus, xendConfigVersion);
1159 1160
            }

1161
            if (str != NULL) free(str);
1162 1163 1164

            if (res != 0)
                goto error;
1165
        } else {
1166
            virXMLError(conn, VIR_ERR_NO_OS, nam, 0);
1167 1168
            goto error;
        }
1169 1170 1171
    }

    /* analyze of the devices */
1172 1173 1174 1175 1176
    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,
	                                    hvm, xendConfigVersion);
1177
            if (res != 0) {
1178
	        free(nodes);
1179 1180 1181
                goto error;
            }
        }
1182
        free(nodes);
1183
    }
1184

1185 1186 1187
    nb_nodes = virXPathNodeSet("/domain/devices/interface", ctxt, &nodes);
    if (nb_nodes > 0) {
        for (i = 0; i < nb_nodes; i++) {
1188
            virBufferAdd(&buf, "(device ", 8);
1189
            res = virDomainParseXMLIfDesc(conn, nodes[i], &buf, hvm, xendConfigVersion);
1190
            if (res != 0) {
1191
	        free(nodes);
1192 1193 1194 1195
                goto error;
            }
            virBufferAdd(&buf, ")", 1);
        }
1196
        free(nodes);
1197 1198
    }

1199 1200 1201 1202
    /* New style PV graphics config xen >= 3.0.4,
     * or HVM graphics config xen >= 3.0.5 */
    if ((xendConfigVersion >= 3 && !hvm) ||
        (xendConfigVersion >= 4 && hvm)) {
1203
        nb_nodes = virXPathNodeSet("/domain/devices/graphics", ctxt, &nodes);
1204
        if (nb_nodes > 0) {
1205 1206
            for (i = 0; i < nb_nodes; i++) {
                res = virDomainParseXMLGraphicsDescVFB(conn, nodes[i], &buf);
1207
                if (res != 0) {
1208
                    free(nodes);
1209 1210 1211
                    goto error;
                }
            }
1212
            free(nodes);
1213 1214 1215
        }
    }

1216

D
Daniel Veillard 已提交
1217
    virBufferAdd(&buf, ")", 1); /* closes (vm */
1218 1219 1220 1221
    buf.content[buf.use] = 0;

    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
1222
    xmlFreeParserCtxt(pctxt);
1223 1224

    if (name != NULL)
1225
        *name = nam;
1226 1227
    else
        free(nam);
1228

1229
    return (buf.content);
1230

1231
 error:
1232
    if (nam != NULL)
1233
        free(nam);
1234
    if (name != NULL)
1235
        *name = NULL;
1236 1237 1238 1239
    if (ctxt != NULL)
        xmlXPathFreeContext(ctxt);
    if (xml != NULL)
        xmlFreeDoc(xml);
1240 1241
    if (pctxt != NULL)
        xmlFreeParserCtxt(pctxt);
1242 1243
    if (buf.content != NULL)
        free(buf.content);
1244
    return (NULL);
1245
}
1246 1247

#endif /* !PROXY */
1248 1249 1250 1251



unsigned char *virParseUUID(char **ptr, const char *uuid) {
1252
    int rawuuid[VIR_UUID_BUFLEN];
1253
    const char *cur;
1254 1255 1256 1257 1258 1259
    unsigned char *dst_uuid = NULL;
    int i;

    if (uuid == NULL)
        goto error;

1260 1261 1262 1263 1264
    /*
     * do a liberal scan allowing '-' and ' ' anywhere between character
     * pairs as long as there is 32 of them in the end.
     */
    cur = uuid;
1265
    for (i = 0;i < VIR_UUID_BUFLEN;) {
1266 1267
        rawuuid[i] = 0;
        if (*cur == 0)
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
            goto error;
        if ((*cur == '-') || (*cur == ' ')) {
            cur++;
            continue;
        }
        if ((*cur >= '0') && (*cur <= '9'))
            rawuuid[i] = *cur - '0';
        else if ((*cur >= 'a') && (*cur <= 'f'))
            rawuuid[i] = *cur - 'a' + 10;
        else if ((*cur >= 'A') && (*cur <= 'F'))
            rawuuid[i] = *cur - 'A' + 10;
        else
            goto error;
        rawuuid[i] *= 16;
        cur++;
1283
        if (*cur == 0)
1284 1285 1286 1287 1288 1289 1290 1291 1292
            goto error;
        if ((*cur >= '0') && (*cur <= '9'))
            rawuuid[i] += *cur - '0';
        else if ((*cur >= 'a') && (*cur <= 'f'))
            rawuuid[i] += *cur - 'a' + 10;
        else if ((*cur >= 'A') && (*cur <= 'F'))
            rawuuid[i] += *cur - 'A' + 10;
        else
            goto error;
1293
        i++;
1294
        cur++;
1295
    }
1296 1297 1298 1299

    dst_uuid = (unsigned char *) *ptr;
    *ptr += 16;

1300
    for (i = 0; i < VIR_UUID_BUFLEN; i++)
1301 1302
        dst_uuid[i] = rawuuid[i] & 0xFF;

1303
 error:
1304
    return(dst_uuid);
1305
}
1306

1307 1308 1309
#ifndef PROXY
/**
 * virParseXMLDevice:
1310
 * @conn: pointer to the hypervisor connection
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
 * @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 *
1324
virParseXMLDevice(virConnectPtr conn, char *xmldesc, int hvm, int xendConfigVersion)
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
{
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
    virBuffer buf;

    buf.content = malloc(1000);
    if (buf.content == NULL)
        return (NULL);
    buf.size = 1000;
    buf.use = 0;
1335
    buf.content[0] = 0;
1336 1337 1338 1339 1340 1341 1342 1343 1344
    xml = xmlReadDoc((const xmlChar *) xmldesc, "domain.xml", NULL,
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
    if (xml == NULL)
        goto error;
    node = xmlDocGetRootElement(xml);
    if (node == NULL)
        goto error;
    if (xmlStrEqual(node->name, BAD_CAST "disk")) {
1345
        if (virDomainParseXMLDiskDesc(conn, node, &buf, hvm, xendConfigVersion) != 0)
1346
            goto error;
1347 1348 1349
        /* SXP is not created when device is "floppy". */
       else if (buf.use == 0)
           goto error;
1350 1351
    }
    else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
1352
        if (virDomainParseXMLIfDesc(conn, node, &buf, hvm, xendConfigVersion) != 0)
1353
            goto error;
1354 1355 1356
    } else {
        virXMLError(conn, VIR_ERR_XML_ERROR, (const char *) node->name, 0);
	goto error;
1357
    }
1358
 cleanup:
1359 1360 1361
    if (xml != NULL)
        xmlFreeDoc(xml);
    return buf.content;
1362
 error:
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
    free(buf.content);
    buf.content = NULL;
    goto cleanup;
}

/**
 * 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
virDomainXMLDevID(virDomainPtr domain, char *xmldesc, char *class, char *ref)
{
    xmlDocPtr xml = NULL;
    xmlNodePtr node, cur;
    xmlChar *attr = NULL;
1388
#ifdef WITH_XEN
1389
    char *xref;
1390
#endif /* WITH_XEN */
1391
    int ret = 0;
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404

    xml = xmlReadDoc((const xmlChar *) xmldesc, "domain.xml", NULL,
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOERROR | XML_PARSE_NOWARNING);
    if (xml == NULL)
        goto error;
    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) ||
1405
                (!xmlStrEqual(cur->name, BAD_CAST "target"))) continue;
1406 1407 1408
            attr = xmlGetProp(cur, BAD_CAST "dev");
            if (attr == NULL)
                goto error;
1409
            strcpy(ref, (char *)attr);
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            goto cleanup;
        }
    }
    else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
        strcpy(class, "vif");
        for (cur = node->children; cur != NULL; cur = cur->next) {
            if ((cur->type != XML_ELEMENT_NODE) ||
                (!xmlStrEqual(cur->name, BAD_CAST "mac"))) continue;
            attr = xmlGetProp(cur, BAD_CAST "address");
            if (attr == NULL)
                goto error;

1422
#ifdef WITH_XEN
1423
            xref = xenStoreDomainGetNetworkID(domain->conn, domain->id,
1424 1425 1426 1427 1428 1429
                                              (char *) attr);
            if (xref != NULL) {
                strcpy(ref, xref);
                free(xref);
                goto cleanup;
            }
1430 1431 1432 1433
#else /* without xen */
            /* hack to avoid the warning that domain is unused */
            if (domain->id < 0)
	        ret = -1;
1434
#endif /* WITH_XEN */
1435

1436 1437 1438
            goto error;
        }
    }
1439
 error:
1440
    ret = -1;
1441
 cleanup:
1442 1443 1444 1445 1446 1447 1448 1449
    if (xml != NULL)
        xmlFreeDoc(xml);
    if (attr != NULL)
        xmlFree(attr);
    return ret;
}
#endif /* !PROXY */

1450 1451 1452 1453 1454 1455 1456 1457
/*
 * Local variables:
 *  indent-tabs-mode: nil
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 4
 * End:
 */