xml.c 48.0 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 "xs_internal.h" /* for xenStoreDomainGetNetworkID */
26

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

41 42 43 44
    if (error == VIR_ERR_OK)
        return;

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

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
#ifndef PROXY
/**
 * 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,
123 124
 *         or -1 if the XPath evaluation failed or -2 if the
 *         value doesn't have a long format.
125 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);
}
#endif /* !PROXY */

271 272 273
/**
 * virBufferGrow:
 * @buf:  the buffer
274
 * @len:  the minimum free size to allocate on top of existing used space
275
 *
276
 * Grow the available space of an XML buffer to at least @len bytes.
277 278 279 280
 *
 * Returns the new available space or -1 in case of error
 */
static int
281 282
virBufferGrow(virBufferPtr buf, unsigned int len)
{
283 284 285
    int size;
    char *newbuf;

286 287 288 289
    if (buf == NULL)
        return (-1);
    if (len + buf->use < buf->size)
        return (0);
290 291 292 293 294

    size = buf->use + len + 1000;

    newbuf = (char *) realloc(buf->content, size);
    if (newbuf == NULL) {
295
        virXMLError(NULL, VIR_ERR_NO_MEMORY, _("growing buffer"), size);
296
        return (-1);
297 298 299
    }
    buf->content = newbuf;
    buf->size = size;
300
    return (buf->size - buf->use);
301 302 303 304 305 306 307 308 309 310 311 312 313
}

/**
 * virBufferAdd:
 * @buf:  the buffer to dump
 * @str:  the string
 * @len:  the number of bytes to add
 *
 * Add a string range to an XML buffer. if len == -1, the length of
 * str is recomputed to the full string.
 *
 * Returns 0 successful, -1 in case of internal or API error.
 */
D
Daniel Veillard 已提交
314
int
315 316
virBufferAdd(virBufferPtr buf, const char *str, int len)
{
317 318 319
    unsigned int needSize;

    if ((str == NULL) || (buf == NULL)) {
320
        return -1;
321
    }
322 323
    if (len == 0)
        return 0;
324 325 326 327 328

    if (len < 0)
        len = strlen(str);

    needSize = buf->use + len + 2;
329
    if (needSize > buf->size) {
330
        if (!virBufferGrow(buf, needSize - buf->use)) {
331
            return (-1);
332 333
        }
    }
K
Karel Zak 已提交
334
    /* XXX: memmove() is 2x slower than memcpy(), do we really need it? */
335 336 337
    memmove(&buf->content[buf->use], str, len);
    buf->use += len;
    buf->content[buf->use] = 0;
338
    return (0);
339 340
}

K
Karel Zak 已提交
341 342 343 344 345 346
virBufferPtr
virBufferNew(unsigned int size)
{
    virBufferPtr buf;

    if (!(buf = malloc(sizeof(*buf)))) {
347
        virXMLError(NULL, VIR_ERR_NO_MEMORY, _("allocate new buffer"), sizeof(*buf));
K
Karel Zak 已提交
348 349 350
        return NULL;
    }
    if (size && (buf->content = malloc(size))==NULL) {
351
        virXMLError(NULL, VIR_ERR_NO_MEMORY, _("allocate buffer content"), size);
K
Karel Zak 已提交
352 353 354 355 356 357 358 359
        free(buf);
        return NULL;
    }
    buf->size = size;
    buf->use = 0;

    return buf;
}
360

K
Karel Zak 已提交
361 362 363 364
void
virBufferFree(virBufferPtr buf)
{
    if (buf) {
K
Karel Zak 已提交
365
        if (buf->content)
366 367
            free(buf->content);
        free(buf);
K
Karel Zak 已提交
368 369 370
    }
}

371 372 373 374 375 376 377 378 379 380
/**
 * virBufferVSprintf:
 * @buf:  the buffer to dump
 * @format:  the format
 * @argptr:  the variable list of arguments
 *
 * Do a formatted print to an XML buffer.
 *
 * Returns 0 successful, -1 in case of internal or API error.
 */
D
Daniel Veillard 已提交
381
int
382 383
virBufferVSprintf(virBufferPtr buf, const char *format, ...)
{
384 385 386 387
    int size, count;
    va_list locarg, argptr;

    if ((format == NULL) || (buf == NULL)) {
388
        return (-1);
389 390 391 392 393 394
    }
    size = buf->size - buf->use - 1;
    va_start(argptr, format);
    va_copy(locarg, argptr);
    while (((count = vsnprintf(&buf->content[buf->use], size, format,
                               locarg)) < 0) || (count >= size - 1)) {
395 396 397 398 399 400 401
        buf->content[buf->use] = 0;
        va_end(locarg);
        if (virBufferGrow(buf, 1000) < 0) {
            return (-1);
        }
        size = buf->size - buf->use - 1;
        va_copy(locarg, argptr);
402 403 404 405
    }
    va_end(locarg);
    buf->use += count;
    buf->content[buf->use] = 0;
406
    return (0);
407 408
}

K
Karel Zak 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422
/**
 * virBufferStrcat:
 * @buf:  the buffer to dump
 * @argptr:  the variable list of strings, the last argument must be NULL
 *
 * Concatenate strings to an XML buffer.
 *
 * Returns 0 successful, -1 in case of internal or API error.
 */
int
virBufferStrcat(virBufferPtr buf, ...)
{
    va_list ap;
    char *str;
423

K
Karel Zak 已提交
424
    va_start(ap, buf);
425

K
Karel Zak 已提交
426 427 428 429 430
    while ((str = va_arg(ap, char *)) != NULL) {
        unsigned int len = strlen(str);
        unsigned int needSize = buf->use + len + 2;

        if (needSize > buf->size) {
431
            if (!virBufferGrow(buf, needSize - buf->use))
432 433
                return -1;
        }
K
Karel Zak 已提交
434 435 436 437 438 439 440 441
        memcpy(&buf->content[buf->use], str, len);
        buf->use += len;
        buf->content[buf->use] = 0;
    }
    va_end(ap);
    return 0;
}

D
Daniel Veillard 已提交
442

443
#ifndef PROXY
444
/**
445
 * virtDomainParseXMLGraphicsDescImage:
446
 * @conn: pointer to the hypervisor connection
447 448
 * @node: node containing graphics description
 * @buf: a buffer for the result S-Expr
449
 * @xendConfigVersion: xend configuration file format
450
 *
451 452 453
 * 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
454 455 456 457
 * valid over time.
 *
 * Returns 0 in case of success, -1 in case of error
 */
458
static int virDomainParseXMLGraphicsDescImage(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf, int xendConfigVersion)
459 460 461 462 463 464 465
{
    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);
466 467 468 469 470 471
            /* TODO:
             * Need to understand sdl options
             *
             *virBufferAdd(buf, "(display localhost:10.0)", 24);
             *virBufferAdd(buf, "(xauthority /root/.Xauthority)", 30);
             */
472
        }
473
        else if (xmlStrEqual(graphics_type, BAD_CAST "vnc")) {
474
            virBufferAdd(buf, "(vnc 1)", 7);
475
            if (xendConfigVersion >= 2) {
476
                xmlChar *vncport = xmlGetProp(node, BAD_CAST "port");
477 478
                xmlChar *vnclisten = xmlGetProp(node, BAD_CAST "listen");
                xmlChar *vncpasswd = xmlGetProp(node, BAD_CAST "passwd");
479
                xmlChar *keymap = xmlGetProp(node, BAD_CAST "keymap");
480
                if (vncport != NULL) {
481
                    long port = strtol((const char *)vncport, NULL, 10);
482 483
                    if (port == -1)
                        virBufferAdd(buf, "(vncunused 1)", 13);
484
                    else if (port >= 5900)
485
                        virBufferVSprintf(buf, "(vncdisplay %ld)", port - 5900);
486
                    xmlFree(vncport);
487
                }
488 489 490 491 492 493 494 495
                if (vnclisten != NULL) {
                    virBufferVSprintf(buf, "(vnclisten %s)", vnclisten);
                    xmlFree(vnclisten);
                }
                if (vncpasswd != NULL) {
                    virBufferVSprintf(buf, "(vncpasswd %s)", vncpasswd);
                    xmlFree(vncpasswd);
                }
496 497 498 499
                if (keymap != NULL) {
                    virBufferVSprintf(buf, "(keymap %s)", keymap);
                    xmlFree(keymap);
                }
500 501
            }
        }
502 503 504 505 506 507
        xmlFree(graphics_type);
    }
    return 0;
}


508 509
/**
 * virtDomainParseXMLGraphicsDescVFB:
510
 * @conn: pointer to the hypervisor connection
511 512 513
 * @node: node containing graphics description
 * @buf: a buffer for the result S-Expr
 *
514 515 516
 * 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
517 518 519 520
 * valid over time.
 *
 * Returns 0 in case of success, -1 in case of error
 */
521
static int virDomainParseXMLGraphicsDescVFB(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf)
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
{
    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");
543
            xmlChar *keymap = xmlGetProp(node, BAD_CAST "keymap");
544 545 546 547
            if (vncport != NULL) {
                long port = strtol((const char *)vncport, NULL, 10);
                if (port == -1)
                    virBufferAdd(buf, "(vncunused 1)", 13);
548
                else if (port >= 5900)
549
                    virBufferVSprintf(buf, "(vncdisplay %ld)", port - 5900);
550 551 552 553 554 555 556 557 558 559
                xmlFree(vncport);
            }
            if (vnclisten != NULL) {
                virBufferVSprintf(buf, "(vnclisten %s)", vnclisten);
                xmlFree(vnclisten);
            }
            if (vncpasswd != NULL) {
                virBufferVSprintf(buf, "(vncpasswd %s)", vncpasswd);
                xmlFree(vncpasswd);
            }
560 561 562 563
            if (keymap != NULL) {
                virBufferVSprintf(buf, "(keymap %s)", keymap);
                xmlFree(keymap);
            }
564 565 566 567 568 569 570 571
        }
        virBufferAdd(buf, "))", 2);
        xmlFree(graphics_type);
    }
    return 0;
}


572
/**
573
 * virDomainParseXMLOSDescHVM:
574
 * @conn: pointer to the hypervisor connection
575
 * @node: node containing HVM OS description
576
 * @buf: a buffer for the result S-Expr
577
 * @ctxt: a path context representing the XML description
578
 * @vcpus: number of virtual CPUs to configure
579
 * @xendConfigVersion: xend configuration file format
580
 *
581 582
 * 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
583 584 585 586 587 588
 * 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
virDomainParseXMLOSDescHVM(virConnectPtr conn, xmlNodePtr node, virBufferPtr buf, xmlXPathContextPtr ctxt, int vcpus, int xendConfigVersion)
590 591
{
    xmlNodePtr cur, txt;
592 593
    xmlChar *type = NULL;
    xmlChar *loader = NULL;
594 595
    char bootorder[5];
    int nbootorder = 0;
596
    int res;
597
    char *str;
598 599 600 601 602 603 604 605

    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) &&
606
                    (txt->next == NULL))
607 608 609 610 611
                    type = txt->content;
            } else if ((loader == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "loader"))) {
                txt = cur->children;
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
612
                    (txt->next == NULL))
613
                    loader = txt->content;
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
            } 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);
635 636 637 638
            }
        }
        cur = cur->next;
    }
639
    bootorder[nbootorder] = '\0';
640 641
    if ((type == NULL) || (!xmlStrEqual(type, BAD_CAST "hvm"))) {
        /* VIR_ERR_OS_TYPE */
642
        virXMLError(conn, VIR_ERR_OS_TYPE, (const char *) type, 0);
643 644 645 646
        return (-1);
    }
    virBufferAdd(buf, "(image (hvm ", 12);
    if (loader == NULL) {
647
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0);
648
        goto error;
649
    } else {
650
        virBufferVSprintf(buf, "(kernel '%s')", (const char *) loader);
651 652 653
    }

    /* get the device emulation model */
654 655
    str = virXPathString("string(/domain/devices/emulator[1])", ctxt);
    if (str == NULL) {
656
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0); /* TODO: error */
657 658
        goto error;
    }
659 660
    virBufferVSprintf(buf, "(device_model '%s')", str);
    xmlFree(str);
661

662 663
    virBufferVSprintf(buf, "(vcpus %d)", vcpus);

664 665
    if (nbootorder)
        virBufferVSprintf(buf, "(boot %s)", bootorder);
666

667 668 669
    /* get the 1st floppy device file */
	cur = virXPathNode("/domain/devices/disk[@device='floppy' and target/@dev='fda']/source",
                       ctxt);
670
	if (cur != NULL) {
671 672
        xmlChar *fdfile;
        fdfile = xmlGetProp(cur, BAD_CAST "file");
673
	    if (fdfile != NULL) {
674 675
            virBufferVSprintf(buf, "(fda '%s')", fdfile);
            free(fdfile);
676
	    }
677
    }
678

679 680 681
    /* get the 2nd floppy device file */
	cur = virXPathNode("/domain/devices/disk[@device='floppy' and target/@dev='fdb']/source",
                       ctxt);
682
	if (cur != NULL) {
683 684
        xmlChar *fdfile;
        fdfile = xmlGetProp(cur, BAD_CAST "file");
685
	    if (fdfile != NULL) {
686 687
            virBufferVSprintf(buf, "(fdb '%s')", fdfile);
            free(fdfile);
688
	    }
689
    }
690 691


692 693 694 695
    /* 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",
696 697
	                       ctxt);
	    if (cur != NULL) {
698 699 700 701 702 703 704
            xmlChar *cdfile;

            cdfile = xmlGetProp(cur, BAD_CAST "file");
            if (cdfile != NULL) {
                virBufferVSprintf(buf, "(cdrom '%s')",
                                  (const char *)cdfile);
                xmlFree(cdfile);
705 706
            }
        }
707 708
    }

709 710 711 712 713 714 715
    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);

716 717
    res = virXPathBoolean("count(domain/devices/console) > 0", ctxt);
    if (res < 0) {
718
        virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
719
        goto error;
720
    }
721
    if (res) {
722
        virBufferAdd(buf, "(serial pty)", 12);
723
    }
724

725 726 727 728 729 730 731 732 733 734
    /* 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;
            }
735 736 737 738 739 740
        }
    }

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

    return (0);
741

742
 error:
743 744 745 746 747
    return(-1);
}

/**
 * virDomainParseXMLOSDescPV:
748
 * @conn: pointer to the hypervisor connection
749 750
 * @node: node containing PV OS description
 * @buf: a buffer for the result S-Expr
751
 * @ctxt: a path context representing the XML description
752
 * @xendConfigVersion: xend configuration file format
753 754 755 756 757 758 759 760 761
 *
 * 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
762
virDomainParseXMLOSDescPV(virConnectPtr conn, xmlNodePtr node, virBufferPtr buf, xmlXPathContextPtr ctxt, int xendConfigVersion)
763
{
764 765 766 767 768 769
    xmlNodePtr cur, txt;
    const xmlChar *type = NULL;
    const xmlChar *root = NULL;
    const xmlChar *kernel = NULL;
    const xmlChar *initrd = NULL;
    const xmlChar *cmdline = NULL;
770
    int res;
771 772 773 774

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
775 776 777
            if ((type == NULL)
                && (xmlStrEqual(cur->name, BAD_CAST "type"))) {
                txt = cur->children;
778
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
779
                    (txt->next == NULL))
780 781 782 783
                    type = txt->content;
            } else if ((kernel == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "kernel"))) {
                txt = cur->children;
784
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
785
                    (txt->next == NULL))
786 787 788 789
                    kernel = txt->content;
            } else if ((root == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "root"))) {
                txt = cur->children;
790
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
791
                    (txt->next == NULL))
792 793 794 795
                    root = txt->content;
            } else if ((initrd == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "initrd"))) {
                txt = cur->children;
796
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
797
                    (txt->next == NULL))
798 799 800 801
                    initrd = txt->content;
            } else if ((cmdline == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "cmdline"))) {
                txt = cur->children;
802
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
803
                    (txt->next == NULL))
804 805 806
                    cmdline = txt->content;
            }
        }
807 808 809 810
        cur = cur->next;
    }
    if ((type != NULL) && (!xmlStrEqual(type, BAD_CAST "linux"))) {
        /* VIR_ERR_OS_TYPE */
811
        virXMLError(conn, VIR_ERR_OS_TYPE, (const char *) type, 0);
812
        return (-1);
813
    }
814
    virBufferAdd(buf, "(image (linux ", 14);
815
    if (kernel == NULL) {
816
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0);
817
        return (-1);
818
    } else {
819
        virBufferVSprintf(buf, "(kernel '%s')", (const char *) kernel);
820 821
    }
    if (initrd != NULL)
822
        virBufferVSprintf(buf, "(ramdisk '%s')", (const char *) initrd);
823
    if (root != NULL)
824
        virBufferVSprintf(buf, "(root '%s')", (const char *) root);
825
    if (cmdline != NULL)
826
        virBufferVSprintf(buf, "(args '%s')", (const char *) cmdline);
827

828
    /* PV graphics for xen <= 3.0.4 */
829
    if (xendConfigVersion < 3) {
830 831 832
        cur = virXPathNode("/domain/devices/graphics[1]", ctxt);
        if (cur != NULL) {
            res = virDomainParseXMLGraphicsDescImage(conn, cur, buf,
833
                                                     xendConfigVersion);
834 835 836
            if (res != 0) {
                goto error;
            }
837 838 839 840
        }
    }

 error:
841
    virBufferAdd(buf, "))", 2);
842
    return (0);
843 844
}

845 846 847 848 849 850 851 852 853 854
/**
 * 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
855
virCatchXMLParseError(void *ctx, const char *msg ATTRIBUTE_UNUSED, ...) {
856 857
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;

858
    if ((ctxt != NULL) &&
859
        (ctxt->lastError.level == XML_ERR_FATAL) &&
860
        (ctxt->lastError.message != NULL)) {
861
        virXMLError(NULL, VIR_ERR_XML_DETAIL, ctxt->lastError.message,
862
                    ctxt->lastError.line);
863 864 865
    }
}

866 867
/**
 * virDomainParseXMLDiskDesc:
868
 * @node: node containing disk description
869
 * @conn: pointer to the hypervisor connection
870
 * @buf: a buffer for the result S-Expr
871
 * @xendConfigVersion: xend configuration file format
872 873 874 875 876 877 878 879 880
 *
 * 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
881
virDomainParseXMLDiskDesc(virConnectPtr conn, xmlNodePtr node, virBufferPtr buf, int hvm, int xendConfigVersion)
882
{
883 884
    xmlNodePtr cur;
    xmlChar *type = NULL;
885
    xmlChar *device = NULL;
886 887
    xmlChar *source = NULL;
    xmlChar *target = NULL;
888 889
    xmlChar *drvName = NULL;
    xmlChar *drvType = NULL;
890
    int ro = 0;
891
    int shareable = 0;
892
    int typ = 0;
893
    int cdrom = 0;
894
    int isNoSrcCdrom = 0;
895 896 897

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
898 899 900 901 902
        if (xmlStrEqual(type, BAD_CAST "file"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "block"))
            typ = 1;
        xmlFree(type);
903
    }
904
    device = xmlGetProp(node, BAD_CAST "device");
905

906 907 908
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
909 910 911 912 913 914 915 916 917 918
            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");
919 920 921 922 923
            } 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");
924 925
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                ro = 1;
926
            } else if (xmlStrEqual(cur->name, BAD_CAST "shareable")) {
927
                shareable = 1;
928 929
            }
        }
930 931 932 933
        cur = cur->next;
    }

    if (source == NULL) {
934 935 936 937 938 939 940 941 942 943
        /* 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);
944

945 946 947 948 949 950
            if (target != NULL)
                xmlFree(target);
            if (device != NULL)
                xmlFree(device);
            return (-1);
        }
951 952
    }
    if (target == NULL) {
953
        virXMLError(conn, VIR_ERR_NO_TARGET, (const char *) source, 0);
954 955
        if (source != NULL)
            xmlFree(source);
956 957
        if (device != NULL)
            xmlFree(device);
958
        return (-1);
959
    }
960

961 962
    /* Xend (all versions) put the floppy device config
     * under the hvm (image (os)) block
963
     */
964
    if (hvm &&
965
        device &&
966
        !strcmp((const char *)device, "floppy")) {
967
        goto cleanup;
968 969 970
    }

    /* Xend <= 3.0.2 doesn't include cdrom config here */
971
    if (hvm &&
972 973
        device &&
        !strcmp((const char *)device, "cdrom")) {
974
        if (xendConfigVersion == 1)
975
            goto cleanup;
976 977
        else
            cdrom = 1;
978 979 980 981
    }


    virBufferAdd(buf, "(device ", 8);
982 983 984 985 986 987 988 989
    /* 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);
    }
990

991 992
    if (hvm) {
        char *tmp = (char *)target;
993
        /* Just in case user mistakenly still puts ioemu: in their XML */
994 995
        if (!strncmp((const char *) tmp, "ioemu:", 6))
            tmp += 6;
996 997 998

        /* Xend <= 3.0.2 wants a ioemu: prefix on devices for HVM */
        if (xendConfigVersion == 1)
999
            virBufferVSprintf(buf, "(dev 'ioemu:%s')", (const char *)tmp);
1000
        else /* But newer does not */
1001
            virBufferVSprintf(buf, "(dev '%s%s')", (const char *)tmp, cdrom ? ":cdrom" : ":disk");
1002
    } else
1003 1004
        virBufferVSprintf(buf, "(dev '%s')", (const char *)target);

1005
    if (drvName && !isNoSrcCdrom) {
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        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);
        }
1016
    } else if (!isNoSrcCdrom) {
1017 1018 1019 1020 1021 1022 1023 1024
        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);
        }
1025
    }
1026
    if (ro == 1)
1027
        virBufferVSprintf(buf, "(mode 'r')");
1028 1029 1030 1031
    else if (shareable == 1)
        virBufferVSprintf(buf, "(mode 'w!')");
    else
        virBufferVSprintf(buf, "(mode 'w')");
1032

1033
    virBufferAdd(buf, ")", 1);
1034
    virBufferAdd(buf, ")", 1);
1035 1036

 cleanup:
1037 1038
    xmlFree(drvType);
    xmlFree(drvName);
1039
    xmlFree(device);
1040 1041
    xmlFree(target);
    xmlFree(source);
1042
    return (0);
1043 1044 1045 1046
}

/**
 * virDomainParseXMLIfDesc:
1047
 * @conn: pointer to the hypervisor connection
1048
 * @node: node containing the interface description
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
 * @buf: a buffer for the result S-Expr
 *
 * 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
1059
virDomainParseXMLIfDesc(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf, int hvm)
1060
{
1061 1062 1063 1064 1065
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *source = NULL;
    xmlChar *mac = NULL;
    xmlChar *script = NULL;
1066
    xmlChar *ip = NULL;
1067
    int typ = 0;
1068
    int ret = -1;
1069 1070 1071

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
1072 1073 1074 1075
        if (xmlStrEqual(type, BAD_CAST "bridge"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            typ = 1;
1076 1077
        else if (xmlStrEqual(type, BAD_CAST "network"))
            typ = 2;
1078
        xmlFree(type);
1079 1080 1081 1082
    }
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
1083 1084 1085 1086
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "bridge");
1087
                else if (typ == 1)
1088
                    source = xmlGetProp(cur, BAD_CAST "dev");
1089 1090
                else
                    source = xmlGetProp(cur, BAD_CAST "network");
1091 1092 1093 1094 1095 1096
            } 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");
1097 1098 1099 1100 1101 1102 1103
            } 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");
1104 1105
            }
        }
1106 1107 1108 1109 1110
        cur = cur->next;
    }

    virBufferAdd(buf, "(vif ", 5);
    if (mac != NULL)
1111
        virBufferVSprintf(buf, "(mac '%s')", (const char *) mac);
1112
    if (source != NULL) {
1113 1114
        if (typ == 0)
            virBufferVSprintf(buf, "(bridge '%s')", (const char *) source);
1115
        else if (typ == 1)      /* TODO does that work like that ? */
1116
            virBufferVSprintf(buf, "(dev '%s')", (const char *) source);
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
        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);
        }
1127 1128 1129
    }
    if (script != NULL)
        virBufferVSprintf(buf, "(script '%s')", script);
1130 1131
    if (ip != NULL)
        virBufferVSprintf(buf, "(ip '%s')", ip);
1132 1133
    if (hvm)
        virBufferAdd(buf, "(type ioemu)", 12);
1134 1135

    virBufferAdd(buf, ")", 1);
1136 1137
    ret = 0;
 error:
1138
    if (mac != NULL)
1139
        xmlFree(mac);
1140
    if (source != NULL)
1141
        xmlFree(source);
1142
    if (script != NULL)
1143
        xmlFree(script);
1144 1145
    if (ip != NULL)
        xmlFree(ip);
1146
    return (ret);
1147 1148 1149 1150
}

/**
 * virDomainParseXMLDesc:
1151
 * @conn: pointer to the hypervisor connection
1152
 * @xmldesc: string with the XML description
1153
 * @xendConfigVersion: xend configuration file format
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
 *
 * 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 *
1164
virDomainParseXMLDesc(virConnectPtr conn, const char *xmldesc, char **name, int xendConfigVersion)
1165
{
1166 1167
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
1168
    char *nam = NULL;
1169 1170
    virBuffer buf;
    xmlChar *prop;
1171
    xmlParserCtxtPtr pctxt;
1172 1173
    xmlXPathContextPtr ctxt = NULL;
    int i, res;
1174
    int bootloader = 0;
1175
    int hvm = 0;
1176
    unsigned int vcpus = 1;
1177
    unsigned long mem = 0, max_mem = 0;
1178 1179 1180 1181
    char *str;
    double f;
    xmlNodePtr *nodes;
    int nb_nodes;
1182 1183

    if (name != NULL)
1184
        *name = NULL;
1185 1186
    buf.content = malloc(1000);
    if (buf.content == NULL)
1187
        return (NULL);
1188 1189 1190
    buf.size = 1000;
    buf.use = 0;

1191 1192 1193 1194 1195
    pctxt = xmlNewParserCtxt();
    if ((pctxt == NULL) || (pctxt->sax == NULL)) {
        goto error;
    }

1196 1197 1198
    /* TODO pass the connection point to the error handler:
     *   pctxt->userData = virConnectPtr;
     */
1199 1200 1201 1202 1203
    pctxt->sax->error = virCatchXMLParseError;

    xml = xmlCtxtReadDoc(pctxt, (const xmlChar *) xmldesc, "domain.xml", NULL,
                         XML_PARSE_NOENT | XML_PARSE_NONET |
                         XML_PARSE_NOWARNING);
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    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")) {
1214 1215 1216 1217
            xmlFree(prop);
            goto error;
        }
        xmlFree(prop);
1218 1219 1220 1221 1222 1223 1224
    }
    virBufferAdd(&buf, "(vm ", 4);
    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        goto error;
    }
    /*
1225
     * extract some of the basics, name, memory, cpus ...
1226
     */
1227
    nam = virXPathString("string(/domain/name[1])", ctxt);
1228
    if (nam == NULL) {
1229
        virXMLError(conn, VIR_ERR_NO_NAME, xmldesc, 0);
1230
        goto error;
1231
    }
1232
    virBufferVSprintf(&buf, "(name '%s')", nam);
1233

1234 1235
    if ((virXPathNumber("number(/domain/memory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1236
        max_mem = 128;
1237
    } else {
1238
        max_mem = (f / 1024);
1239
    }
1240 1241 1242

    if ((virXPathNumber("number(/domain/currentMemory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1243 1244
        mem = max_mem;
    } else {
1245
        mem = (f / 1024);
1246 1247 1248
        if (mem > max_mem) {
            max_mem = mem;
        }
1249
    }
1250
    virBufferVSprintf(&buf, "(memory %lu)(maxmem %lu)", mem, max_mem);
1251

1252 1253 1254
    if ((virXPathNumber("number(/domain/vcpu[1])", ctxt, &f) == 0) &&
        (f > 0)) {
        vcpus = (unsigned int) f;
1255
    }
1256
    virBufferVSprintf(&buf, "(vcpus %u)", vcpus);
1257

1258 1259 1260 1261
    str = virXPathString("string(/domain/uuid[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(uuid '%s')", str);
	free(str);
1262 1263
    }

1264 1265 1266
    str = virXPathString("string(/domain/bootloader[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(bootloader '%s')", str);
1267 1268 1269 1270
        /*
         * if using pygrub, the kernel and initrd strings are not
         * significant and should be discarded
         */
1271
        if (strstr(str, "pygrub"))
1272 1273 1274
            bootloader = 2;
        else
            bootloader = 1;
1275
	free(str);
1276 1277
    }

1278 1279 1280 1281
    str = virXPathString("string(/domain/on_poweroff[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_poweroff '%s')", str);
	free(str);
1282 1283
    }

1284 1285 1286 1287
    str = virXPathString("string(/domain/on_reboot[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_reboot '%s')", str);
	free(str);
1288 1289
    }

1290 1291 1292 1293
    str = virXPathString("string(/domain/on_crash[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_crash '%s')", str);
	free(str);
1294 1295
    }

1296
    if (bootloader != 2) {
1297
        if ((node = virXPathNode("/domain/os[1]", ctxt)) != NULL) {
1298
            /* Analyze of the os description, based on HVM or PV. */
1299
	    str = virXPathString("string(/domain/os/type[1])", ctxt);
1300

1301 1302
            if ((str == NULL) || (strcmp(str, "hvm"))) {
                res = virDomainParseXMLOSDescPV(conn, node,
1303 1304 1305
                                                &buf, ctxt, xendConfigVersion);
            } else {
                hvm = 1;
1306 1307
                res = virDomainParseXMLOSDescHVM(conn, node, &buf, ctxt,
		                                 vcpus, xendConfigVersion);
1308 1309
            }

1310
            if (str != NULL) free(str);
1311 1312 1313 1314

            if (res != 0)
                goto error;
        } else if (bootloader == 0) {
1315
            virXMLError(conn, VIR_ERR_NO_OS, nam, 0);
1316 1317
            goto error;
        }
1318 1319 1320
    }

    /* analyze of the devices */
1321 1322 1323 1324 1325
    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);
1326
            if (res != 0) {
1327
	        free(nodes);
1328 1329 1330
                goto error;
            }
        }
1331
        free(nodes);
1332
    }
1333

1334 1335 1336
    nb_nodes = virXPathNodeSet("/domain/devices/interface", ctxt, &nodes);
    if (nb_nodes > 0) {
        for (i = 0; i < nb_nodes; i++) {
1337
            virBufferAdd(&buf, "(device ", 8);
1338
            res = virDomainParseXMLIfDesc(conn, nodes[i], &buf, hvm);
1339
            if (res != 0) {
1340
	        free(nodes);
1341 1342 1343 1344
                goto error;
            }
            virBufferAdd(&buf, ")", 1);
        }
1345
        free(nodes);
1346 1347
    }

1348 1349 1350 1351
    /* New style PV graphics config xen >= 3.0.4,
     * or HVM graphics config xen >= 3.0.5 */
    if ((xendConfigVersion >= 3 && !hvm) ||
        (xendConfigVersion >= 4 && hvm)) {
1352
        nb_nodes = virXPathNodeSet("/domain/devices/graphics", ctxt, &nodes);
1353
        if (nb_nodes > 0) {
1354 1355
            for (i = 0; i < nb_nodes; i++) {
                res = virDomainParseXMLGraphicsDescVFB(conn, nodes[i], &buf);
1356
                if (res != 0) {
1357
                    free(nodes);
1358 1359 1360
                    goto error;
                }
            }
1361
            free(nodes);
1362 1363 1364
        }
    }

1365

D
Daniel Veillard 已提交
1366
    virBufferAdd(&buf, ")", 1); /* closes (vm */
1367 1368 1369 1370
    buf.content[buf.use] = 0;

    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
1371
    xmlFreeParserCtxt(pctxt);
1372 1373

    if (name != NULL)
1374
        *name = nam;
1375 1376
    else
        free(nam);
1377

1378
    return (buf.content);
1379

1380
 error:
1381
    if (nam != NULL)
1382
        free(nam);
1383
    if (name != NULL)
1384
        *name = NULL;
1385 1386 1387 1388
    if (ctxt != NULL)
        xmlXPathFreeContext(ctxt);
    if (xml != NULL)
        xmlFreeDoc(xml);
1389 1390
    if (pctxt != NULL)
        xmlFreeParserCtxt(pctxt);
1391 1392
    if (buf.content != NULL)
        free(buf.content);
1393
    return (NULL);
1394
}
1395 1396

#endif /* !PROXY */
1397 1398 1399 1400



unsigned char *virParseUUID(char **ptr, const char *uuid) {
1401
    int rawuuid[VIR_UUID_BUFLEN];
1402
    const char *cur;
1403 1404 1405 1406 1407 1408
    unsigned char *dst_uuid = NULL;
    int i;

    if (uuid == NULL)
        goto error;

1409 1410 1411 1412 1413
    /*
     * do a liberal scan allowing '-' and ' ' anywhere between character
     * pairs as long as there is 32 of them in the end.
     */
    cur = uuid;
1414
    for (i = 0;i < VIR_UUID_BUFLEN;) {
1415 1416
        rawuuid[i] = 0;
        if (*cur == 0)
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
            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++;
1432
        if (*cur == 0)
1433 1434 1435 1436 1437 1438 1439 1440 1441
            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;
1442
        i++;
1443
        cur++;
1444
    }
1445 1446 1447 1448

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

1449
    for (i = 0; i < VIR_UUID_BUFLEN; i++)
1450 1451
        dst_uuid[i] = rawuuid[i] & 0xFF;

1452
 error:
1453
    return(dst_uuid);
1454
}
1455

1456 1457 1458
#ifndef PROXY
/**
 * virParseXMLDevice:
1459
 * @conn: pointer to the hypervisor connection
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
 * @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 *
1473
virParseXMLDevice(virConnectPtr conn, char *xmldesc, int hvm, int xendConfigVersion)
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
{
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
    virBuffer buf;

    buf.content = malloc(1000);
    if (buf.content == NULL)
        return (NULL);
    buf.size = 1000;
    buf.use = 0;
    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")) {
1493
        if (virDomainParseXMLDiskDesc(conn, node, &buf, hvm, xendConfigVersion) != 0)
1494 1495 1496
            goto error;
    }
    else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
1497
        if (virDomainParseXMLIfDesc(conn, node, &buf, hvm) != 0)
1498 1499
            goto error;
    }
1500
 cleanup:
1501 1502 1503
    if (xml != NULL)
        xmlFreeDoc(xml);
    return buf.content;
1504
 error:
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    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;
1530
#ifdef WITH_XEN
1531
    char *xref;
1532
#endif /* WITH_XEN */
1533
    int ret = 0;
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546

    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) ||
1547
                (!xmlStrEqual(cur->name, BAD_CAST "target"))) continue;
1548 1549 1550
            attr = xmlGetProp(cur, BAD_CAST "dev");
            if (attr == NULL)
                goto error;
1551
            strcpy(ref, (char *)attr);
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
            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;

1564
#ifdef WITH_XEN
1565
            xref = xenStoreDomainGetNetworkID(domain->conn, domain->id,
1566 1567 1568 1569 1570 1571
                                              (char *) attr);
            if (xref != NULL) {
                strcpy(ref, xref);
                free(xref);
                goto cleanup;
            }
1572 1573 1574 1575
#else /* without xen */
            /* hack to avoid the warning that domain is unused */
            if (domain->id < 0)
	        ret = -1;
1576
#endif /* WITH_XEN */
1577

1578 1579 1580
            goto error;
        }
    }
1581
 error:
1582
    ret = -1;
1583
 cleanup:
1584 1585 1586 1587 1588 1589 1590 1591
    if (xml != NULL)
        xmlFreeDoc(xml);
    if (attr != NULL)
        xmlFree(attr);
    return ret;
}
#endif /* !PROXY */

1592 1593 1594 1595 1596 1597 1598 1599
/*
 * Local variables:
 *  indent-tabs-mode: nil
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 4
 * End:
 */