xml.c 47.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 594
    xmlChar *type = NULL;
    xmlChar *loader = NULL;
    xmlChar *boot_dev = NULL;
595
    int res;
596
    char *str;
597 598 599 600 601 602 603 604

    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) &&
605
                    (txt->next == NULL))
606 607 608 609 610
                    type = txt->content;
            } else if ((loader == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "loader"))) {
                txt = cur->children;
                if ((txt != NULL) && (txt->type == XML_TEXT_NODE) &&
611
                    (txt->next == NULL))
612 613 614 615 616 617 618 619 620 621
                    loader = txt->content;
            } else if ((boot_dev == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "boot"))) {
                boot_dev = xmlGetProp(cur, BAD_CAST "dev");
            }
        }
        cur = cur->next;
    }
    if ((type == NULL) || (!xmlStrEqual(type, BAD_CAST "hvm"))) {
        /* VIR_ERR_OS_TYPE */
622
        virXMLError(conn, VIR_ERR_OS_TYPE, (const char *) type, 0);
623 624 625 626
        return (-1);
    }
    virBufferAdd(buf, "(image (hvm ", 12);
    if (loader == NULL) {
627
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0);
628
        goto error;
629
    } else {
630
        virBufferVSprintf(buf, "(kernel '%s')", (const char *) loader);
631 632 633
    }

    /* get the device emulation model */
634 635
    str = virXPathString("string(/domain/devices/emulator[1])", ctxt);
    if (str == NULL) {
636
        virXMLError(conn, VIR_ERR_NO_KERNEL, NULL, 0); /* TODO: error */
637 638
        goto error;
    }
639 640
    virBufferVSprintf(buf, "(device_model '%s')", str);
    xmlFree(str);
641

642 643
    virBufferVSprintf(buf, "(vcpus %d)", vcpus);

644
    if (boot_dev) {
645
        if (xmlStrEqual(boot_dev, BAD_CAST "fd")) {
646
            virBufferVSprintf(buf, "(boot a)" /*, (const char *) boot_dev*/);
647
        } else if (xmlStrEqual(boot_dev, BAD_CAST "cdrom")) {
648
            virBufferVSprintf(buf, "(boot d)" /*, (const char *) boot_dev*/);
649
        } else if (xmlStrEqual(boot_dev, BAD_CAST "hd")) {
650
            virBufferVSprintf(buf, "(boot c)" /*, (const char *) boot_dev*/);
651 652
        } else {
            /* Any other type of boot dev is unsupported right now */
653
            virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
654 655 656
        }

        /* get the 1st floppy device file */
657 658 659 660 661 662 663 664 665 666 667
	cur = virXPathNode(
	  "/domain/devices/disk[@device='floppy' and target/@dev='fda']/source",
			   ctxt);
	if (cur != NULL) {
            xmlChar *fdfile;

            fdfile = xmlGetProp(cur, BAD_CAST "file");
	    if (fdfile != NULL) {
		virBufferVSprintf(buf, "(fda '%s')", fdfile);
		free(fdfile);
	    }
668 669 670
        }

        /* get the 2nd floppy device file */
671 672 673 674 675 676
	cur = virXPathNode(
	  "/domain/devices/disk[@device='floppy' and target/@dev='fdb']/source",
			   ctxt);
	if (cur != NULL) {
            xmlChar *fdfile;

677
            fdfile = xmlGetProp(cur, BAD_CAST "file");
678 679 680 681
	    if (fdfile != NULL) {
		virBufferVSprintf(buf, "(fdb '%s')", fdfile);
		free(fdfile);
	    }
682 683 684 685 686 687
        }


        /* get the cdrom device file */
        /* Only XenD <= 3.0.2 wants cdrom config here */
        if (xendConfigVersion == 1) {
688 689 690 691 692 693
	    cur = virXPathNode(
	"/domain/devices/disk[@device='cdrom' and target/@dev='hdc']/source",
	                       ctxt);
	    if (cur != NULL) {
                xmlChar *cdfile;

694
                cdfile = xmlGetProp(cur, BAD_CAST "file");
695 696 697 698 699
		if (cdfile != NULL) {
		    virBufferVSprintf(buf, "(cdrom '%s')",
				      (const char *)cdfile);
		    xmlFree(cdfile);
		}
700 701 702
            }
        }

703
        if (virXPathNode("/domain/features/acpi", ctxt) != NULL)
704
            virBufferAdd(buf, "(acpi 1)", 8);
705
        if (virXPathNode("/domain/features/apic", ctxt) != NULL)
706
            virBufferAdd(buf, "(apic 1)", 8);
707
        if (virXPathNode("/domain/features/pae", ctxt) != NULL)
708
            virBufferAdd(buf, "(pae 1)", 7);
709 710
    }

711 712
    res = virXPathBoolean("count(domain/devices/console) > 0", ctxt);
    if (res < 0) {
713
        virXMLError(conn, VIR_ERR_XML_ERROR, NULL, 0);
714
        goto error;
715
    }
716
    if (res) {
717
        virBufferAdd(buf, "(serial pty)", 12);
718
    }
719

720
    /* Is a graphics device specified? */
721 722 723 724
    cur = virXPathNode("/domain/devices/graphics[1]", ctxt);
    if (cur != NULL) {
        res = virDomainParseXMLGraphicsDescImage(conn, cur, buf,
	                                         xendConfigVersion);
725 726
        if (res != 0) {
            goto error;
727 728 729 730 731
        }
    }

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

732 733 734
    if (boot_dev)
        xmlFree(boot_dev);

735
    return (0);
736
 error:
737 738
    if (boot_dev)
        xmlFree(boot_dev);
739 740 741 742 743
    return(-1);
}

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

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

    /* Is a graphics device specified? */
825 826
    /* Old style config before merge of PVFB */
    if (xendConfigVersion < 3) {
827 828 829 830
        cur = virXPathNode("/domain/devices/graphics[1]", ctxt);
        if (cur != NULL) {
            res = virDomainParseXMLGraphicsDescImage(conn, cur, buf,
	                                             xendConfigVersion);
831 832 833
            if (res != 0) {
                goto error;
            }
834 835 836 837
        }
    }

 error:
838
    virBufferAdd(buf, "))", 2);
839
    return (0);
840 841
}

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

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

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

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
894 895 896 897 898
        if (xmlStrEqual(type, BAD_CAST "file"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "block"))
            typ = 1;
        xmlFree(type);
899
    }
900
    device = xmlGetProp(node, BAD_CAST "device");
901

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

    if (source == NULL) {
930
        virXMLError(conn, VIR_ERR_NO_SOURCE, (const char *) target, 0);
931 932 933

        if (target != NULL)
            xmlFree(target);
934 935
        if (device != NULL)
            xmlFree(device);
936
        return (-1);
937 938
    }
    if (target == NULL) {
939
        virXMLError(conn, VIR_ERR_NO_TARGET, (const char *) source, 0);
940 941
        if (source != NULL)
            xmlFree(source);
942 943
        if (device != NULL)
            xmlFree(device);
944
        return (-1);
945
    }
946

947 948
    /* Xend (all versions) put the floppy device config
     * under the hvm (image (os)) block
949
     */
950
    if (hvm &&
951
        device &&
952
        !strcmp((const char *)device, "floppy")) {
953
        goto cleanup;
954 955 956
    }

    /* Xend <= 3.0.2 doesn't include cdrom config here */
957
    if (hvm &&
958 959
        device &&
        !strcmp((const char *)device, "cdrom")) {
960
        if (xendConfigVersion == 1)
961
            goto cleanup;
962 963
        else
            cdrom = 1;
964 965 966 967
    }


    virBufferAdd(buf, "(device ", 8);
968 969 970 971 972 973 974 975
    /* 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);
    }
976

977 978
    if (hvm) {
        char *tmp = (char *)target;
979
        /* Just in case user mistakenly still puts ioemu: in their XML */
980 981
        if (!strncmp((const char *) tmp, "ioemu:", 6))
            tmp += 6;
982 983 984

        /* Xend <= 3.0.2 wants a ioemu: prefix on devices for HVM */
        if (xendConfigVersion == 1)
985
            virBufferVSprintf(buf, "(dev 'ioemu:%s')", (const char *)tmp);
986
        else /* But newer does not */
987
            virBufferVSprintf(buf, "(dev '%s%s')", (const char *)tmp, cdrom ? ":cdrom" : ":disk");
988
    } else
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
        virBufferVSprintf(buf, "(dev '%s')", (const char *)target);

    if (drvName) {
        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);
        }
    } else {
        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);
        }
1011
    }
1012
    if (ro == 1)
1013
        virBufferVSprintf(buf, "(mode 'r')");
1014 1015 1016 1017
    else if (shareable == 1)
        virBufferVSprintf(buf, "(mode 'w!')");
    else
        virBufferVSprintf(buf, "(mode 'w')");
1018

1019
    virBufferAdd(buf, ")", 1);
1020
    virBufferAdd(buf, ")", 1);
1021 1022

 cleanup:
1023 1024
    xmlFree(drvType);
    xmlFree(drvName);
1025
    xmlFree(device);
1026 1027
    xmlFree(target);
    xmlFree(source);
1028
    return (0);
1029 1030 1031 1032
}

/**
 * virDomainParseXMLIfDesc:
1033
 * @conn: pointer to the hypervisor connection
1034
 * @node: node containing the interface description
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
 * @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
1045
virDomainParseXMLIfDesc(virConnectPtr conn ATTRIBUTE_UNUSED, xmlNodePtr node, virBufferPtr buf, int hvm)
1046
{
1047 1048 1049 1050 1051
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *source = NULL;
    xmlChar *mac = NULL;
    xmlChar *script = NULL;
1052
    xmlChar *ip = NULL;
1053
    int typ = 0;
1054
    int ret = -1;
1055 1056 1057

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
1058 1059 1060 1061
        if (xmlStrEqual(type, BAD_CAST "bridge"))
            typ = 0;
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            typ = 1;
1062 1063
        else if (xmlStrEqual(type, BAD_CAST "network"))
            typ = 2;
1064
        xmlFree(type);
1065 1066 1067 1068
    }
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
1069 1070 1071 1072
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                if (typ == 0)
                    source = xmlGetProp(cur, BAD_CAST "bridge");
1073
                else if (typ == 1)
1074
                    source = xmlGetProp(cur, BAD_CAST "dev");
1075 1076
                else
                    source = xmlGetProp(cur, BAD_CAST "network");
1077 1078 1079 1080 1081 1082
            } 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");
1083 1084 1085 1086 1087 1088 1089
            } 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");
1090 1091
            }
        }
1092 1093 1094 1095 1096
        cur = cur->next;
    }

    virBufferAdd(buf, "(vif ", 5);
    if (mac != NULL)
1097
        virBufferVSprintf(buf, "(mac '%s')", (const char *) mac);
1098
    if (source != NULL) {
1099 1100
        if (typ == 0)
            virBufferVSprintf(buf, "(bridge '%s')", (const char *) source);
1101
        else if (typ == 1)      /* TODO does that work like that ? */
1102
            virBufferVSprintf(buf, "(dev '%s')", (const char *) source);
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
        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);
        }
1113 1114 1115
    }
    if (script != NULL)
        virBufferVSprintf(buf, "(script '%s')", script);
1116 1117
    if (ip != NULL)
        virBufferVSprintf(buf, "(ip '%s')", ip);
1118 1119
    if (hvm)
        virBufferAdd(buf, "(type ioemu)", 12);
1120 1121

    virBufferAdd(buf, ")", 1);
1122 1123
    ret = 0;
 error:
1124
    if (mac != NULL)
1125
        xmlFree(mac);
1126
    if (source != NULL)
1127
        xmlFree(source);
1128
    if (script != NULL)
1129
        xmlFree(script);
1130 1131
    if (ip != NULL)
        xmlFree(ip);
1132
    return (ret);
1133 1134 1135 1136
}

/**
 * virDomainParseXMLDesc:
1137
 * @conn: pointer to the hypervisor connection
1138
 * @xmldesc: string with the XML description
1139
 * @xendConfigVersion: xend configuration file format
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
 *
 * 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 *
1150
virDomainParseXMLDesc(virConnectPtr conn, const char *xmldesc, char **name, int xendConfigVersion)
1151
{
1152 1153
    xmlDocPtr xml = NULL;
    xmlNodePtr node;
1154
    char *ret = NULL, *nam = NULL;
1155 1156
    virBuffer buf;
    xmlChar *prop;
1157
    xmlParserCtxtPtr pctxt;
1158 1159
    xmlXPathContextPtr ctxt = NULL;
    int i, res;
1160
    int bootloader = 0;
1161
    int hvm = 0;
1162
    unsigned int vcpus = 1;
1163
    unsigned long mem = 0, max_mem = 0;
1164 1165 1166 1167
    char *str;
    double f;
    xmlNodePtr *nodes;
    int nb_nodes;
1168 1169

    if (name != NULL)
1170
        *name = NULL;
1171 1172
    ret = malloc(1000);
    if (ret == NULL)
1173
        return (NULL);
1174 1175 1176 1177
    buf.content = ret;
    buf.size = 1000;
    buf.use = 0;

1178 1179 1180 1181 1182
    pctxt = xmlNewParserCtxt();
    if ((pctxt == NULL) || (pctxt->sax == NULL)) {
        goto error;
    }

1183 1184 1185
    /* TODO pass the connection point to the error handler:
     *   pctxt->userData = virConnectPtr;
     */
1186 1187 1188 1189 1190
    pctxt->sax->error = virCatchXMLParseError;

    xml = xmlCtxtReadDoc(pctxt, (const xmlChar *) xmldesc, "domain.xml", NULL,
                         XML_PARSE_NOENT | XML_PARSE_NONET |
                         XML_PARSE_NOWARNING);
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
    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")) {
1201 1202 1203 1204
            xmlFree(prop);
            goto error;
        }
        xmlFree(prop);
1205 1206 1207 1208 1209 1210 1211
    }
    virBufferAdd(&buf, "(vm ", 4);
    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        goto error;
    }
    /*
1212
     * extract some of the basics, name, memory, cpus ...
1213
     */
1214
    nam = virXPathString("string(/domain/name[1])", ctxt);
1215
    if (nam == NULL) {
1216
        virXMLError(conn, VIR_ERR_NO_NAME, xmldesc, 0);
1217
        goto error;
1218
    }
1219
    virBufferVSprintf(&buf, "(name '%s')", nam);
1220

1221 1222
    if ((virXPathNumber("number(/domain/memory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1223
        max_mem = 128;
1224
    } else {
1225
        max_mem = (f / 1024);
1226
    }
1227 1228 1229

    if ((virXPathNumber("number(/domain/currentMemory[1])", ctxt, &f) < 0) ||
        (f < MIN_XEN_GUEST_SIZE * 1024)) {
1230 1231
        mem = max_mem;
    } else {
1232
        mem = (f / 1024);
1233 1234 1235
        if (mem > max_mem) {
            max_mem = mem;
        }
1236
    }
1237
    virBufferVSprintf(&buf, "(memory %lu)(maxmem %lu)", mem, max_mem);
1238

1239 1240 1241
    if ((virXPathNumber("number(/domain/vcpu[1])", ctxt, &f) == 0) &&
        (f > 0)) {
        vcpus = (unsigned int) f;
1242
    }
1243
    virBufferVSprintf(&buf, "(vcpus %u)", vcpus);
1244

1245 1246 1247 1248
    str = virXPathString("string(/domain/uuid[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(uuid '%s')", str);
	free(str);
1249 1250
    }

1251 1252 1253
    str = virXPathString("string(/domain/bootloader[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(bootloader '%s')", str);
1254 1255 1256 1257
        /*
         * if using pygrub, the kernel and initrd strings are not
         * significant and should be discarded
         */
1258
        if (strstr(str, "pygrub"))
1259 1260 1261
            bootloader = 2;
        else
            bootloader = 1;
1262
	free(str);
1263 1264
    }

1265 1266 1267 1268
    str = virXPathString("string(/domain/on_poweroff[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_poweroff '%s')", str);
	free(str);
1269 1270
    }

1271 1272 1273 1274
    str = virXPathString("string(/domain/on_reboot[1])", ctxt);
    if (str != NULL) {
        virBufferVSprintf(&buf, "(on_reboot '%s')", str);
	free(str);
1275 1276
    }

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

1283
    if (bootloader != 2) {
1284
        if ((node = virXPathNode("/domain/os[1]", ctxt)) != NULL) {
1285
            /* Analyze of the os description, based on HVM or PV. */
1286
	    str = virXPathString("string(/domain/os/type[1])", ctxt);
1287

1288 1289
            if ((str == NULL) || (strcmp(str, "hvm"))) {
                res = virDomainParseXMLOSDescPV(conn, node,
1290 1291 1292
                                                &buf, ctxt, xendConfigVersion);
            } else {
                hvm = 1;
1293 1294
                res = virDomainParseXMLOSDescHVM(conn, node, &buf, ctxt,
		                                 vcpus, xendConfigVersion);
1295 1296
            }

1297
            if (str != NULL) free(str);
1298 1299 1300 1301

            if (res != 0)
                goto error;
        } else if (bootloader == 0) {
1302
            virXMLError(conn, VIR_ERR_NO_OS, nam, 0);
1303 1304
            goto error;
        }
1305 1306 1307
    }

    /* analyze of the devices */
1308 1309 1310 1311 1312
    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);
1313
            if (res != 0) {
1314
	        free(nodes);
1315 1316 1317
                goto error;
            }
        }
1318
	free(nodes);
1319
    }
1320

1321 1322 1323
    nb_nodes = virXPathNodeSet("/domain/devices/interface", ctxt, &nodes);
    if (nb_nodes > 0) {
        for (i = 0; i < nb_nodes; i++) {
1324
            virBufferAdd(&buf, "(device ", 8);
1325
            res = virDomainParseXMLIfDesc(conn, nodes[i], &buf, hvm);
1326
            if (res != 0) {
1327
	        free(nodes);
1328 1329 1330 1331
                goto error;
            }
            virBufferAdd(&buf, ")", 1);
        }
1332
	free(nodes);
1333 1334
    }

1335 1336
    /* New style PVFB config  - 3.0.4 merge */
    if (xendConfigVersion >= 3 && !hvm) {
1337 1338 1339 1340
        nb_nodes = virXPathNodeSet("/domain/devices/graphics", ctxt, &nodes);
	if (nb_nodes > 0) {
            for (i = 0; i < nb_nodes; i++) {
                res = virDomainParseXMLGraphicsDescVFB(conn, nodes[i], &buf);
1341
                if (res != 0) {
1342
		    free(nodes);
1343 1344 1345
                    goto error;
                }
            }
1346
	    free(nodes);
1347 1348 1349
        }
    }

1350

D
Daniel Veillard 已提交
1351
    virBufferAdd(&buf, ")", 1); /* closes (vm */
1352 1353 1354 1355
    buf.content[buf.use] = 0;

    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
1356
    xmlFreeParserCtxt(pctxt);
1357 1358

    if (name != NULL)
1359
        *name = nam;
1360 1361
    else
        free(nam);
1362

1363 1364
    return (ret);

1365
 error:
1366
    if (nam != NULL)
1367
        free(nam);
1368
    if (name != NULL)
1369
        *name = NULL;
1370 1371 1372 1373
    if (ctxt != NULL)
        xmlXPathFreeContext(ctxt);
    if (xml != NULL)
        xmlFreeDoc(xml);
1374 1375
    if (pctxt != NULL)
        xmlFreeParserCtxt(pctxt);
1376 1377
    if (ret != NULL)
        free(ret);
1378
    return (NULL);
1379
}
1380 1381

#endif /* !PROXY */
1382 1383 1384 1385



unsigned char *virParseUUID(char **ptr, const char *uuid) {
1386
    int rawuuid[VIR_UUID_BUFLEN];
1387
    const char *cur;
1388 1389 1390 1391 1392 1393
    unsigned char *dst_uuid = NULL;
    int i;

    if (uuid == NULL)
        goto error;

1394 1395 1396 1397 1398
    /*
     * do a liberal scan allowing '-' and ' ' anywhere between character
     * pairs as long as there is 32 of them in the end.
     */
    cur = uuid;
1399
    for (i = 0;i < VIR_UUID_BUFLEN;) {
1400 1401
        rawuuid[i] = 0;
        if (*cur == 0)
1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
            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++;
1417
        if (*cur == 0)
1418 1419 1420 1421 1422 1423 1424 1425 1426
            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;
1427
        i++;
1428
        cur++;
1429
    }
1430 1431 1432 1433

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

1434
    for (i = 0; i < VIR_UUID_BUFLEN; i++)
1435 1436
        dst_uuid[i] = rawuuid[i] & 0xFF;

1437
 error:
1438
    return(dst_uuid);
1439
}
1440

1441 1442 1443
#ifndef PROXY
/**
 * virParseXMLDevice:
1444
 * @conn: pointer to the hypervisor connection
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
 * @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 *
1458
virParseXMLDevice(virConnectPtr conn, char *xmldesc, int hvm, int xendConfigVersion)
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
{
    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")) {
1478
        if (virDomainParseXMLDiskDesc(conn, node, &buf, hvm, xendConfigVersion) != 0)
1479 1480 1481
            goto error;
    }
    else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
1482
        if (virDomainParseXMLIfDesc(conn, node, &buf, hvm) != 0)
1483 1484
            goto error;
    }
1485
 cleanup:
1486 1487 1488
    if (xml != NULL)
        xmlFreeDoc(xml);
    return buf.content;
1489
 error:
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
    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;
1515
#ifdef WITH_XEN
1516
    char *xref;
1517
#endif /* WITH_XEN */
1518
    int ret = 0;
1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531

    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) ||
1532
                (!xmlStrEqual(cur->name, BAD_CAST "target"))) continue;
1533 1534 1535
            attr = xmlGetProp(cur, BAD_CAST "dev");
            if (attr == NULL)
                goto error;
1536
            strcpy(ref, (char *)attr);
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
            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;

1549
#ifdef WITH_XEN
1550
            xref = xenStoreDomainGetNetworkID(domain->conn, domain->id,
1551 1552 1553 1554 1555 1556
                                              (char *) attr);
            if (xref != NULL) {
                strcpy(ref, xref);
                free(xref);
                goto cleanup;
            }
1557 1558 1559 1560
#else /* without xen */
            /* hack to avoid the warning that domain is unused */
            if (domain->id < 0)
	        ret = -1;
1561
#endif /* WITH_XEN */
1562

1563 1564 1565
            goto error;
        }
    }
1566
 error:
1567
    ret = -1;
1568
 cleanup:
1569 1570 1571 1572 1573 1574 1575 1576
    if (xml != NULL)
        xmlFreeDoc(xml);
    if (attr != NULL)
        xmlFree(attr);
    return ret;
}
#endif /* !PROXY */

1577 1578 1579 1580 1581 1582 1583 1584
/*
 * Local variables:
 *  indent-tabs-mode: nil
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 4
 * End:
 */