qemu_conf.c 98.1 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * config.c: VM configuration management
 *
 * Copyright (C) 2006, 2007 Red Hat, Inc.
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

24
#include <config.h>
25 26

#ifdef WITH_QEMU
27

D
Daniel P. Berrange 已提交
28 29 30 31 32 33 34 35
#include <dirent.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
36
#include <sys/wait.h>
37
#include <arpa/inet.h>
38
#include <sys/utsname.h>
D
Daniel P. Berrange 已提交
39 40 41 42 43 44

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/uri.h>

45
#include "libvirt/virterror.h"
D
Daniel P. Berrange 已提交
46

47
#include "qemu_conf.h"
48
#include "uuid.h"
49
#include "buf.h"
D
Daniel P. Berrange 已提交
50
#include "conf.h"
51
#include "util.h"
52

53 54
#define qemudLog(level, msg...) fprintf(stderr, msg)

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
void qemudReportError(virConnectPtr conn,
                      virDomainPtr dom,
                      virNetworkPtr net,
                      int code, const char *fmt, ...) {
    va_list args;
    char errorMessage[QEMUD_MAX_ERROR_LEN];

    if (fmt) {
        va_start(args, fmt);
        vsnprintf(errorMessage, QEMUD_MAX_ERROR_LEN-1, fmt, args);
        va_end(args);
    } else {
        errorMessage[0] = '\0';
    }
    __virRaiseError(conn, dom, net, VIR_FROM_QEMU, code, VIR_ERR_ERROR,
70
                    NULL, NULL, NULL, -1, -1, "%s", errorMessage);
71 72
}

D
Daniel P. Berrange 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
int qemudLoadDriverConfig(struct qemud_driver *driver,
                          const char *filename) {
    virConfPtr conf;
    virConfValuePtr p;

    /* Setup 2 critical defaults */
    strcpy(driver->vncListen, "127.0.0.1");
    if (!(driver->vncTLSx509certdir = strdup(SYSCONF_DIR "/pki/libvirt-vnc"))) {
        qemudReportError(NULL, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "vncTLSx509certdir");
        return -1;
    }

    /* Just check the file is readable before opening it, otherwise
     * libvirt emits an error.
     */
    if (access (filename, R_OK) == -1) return 0;

    conf = virConfReadFile (filename);
    if (!conf) return 0;


#define CHECK_TYPE(name,typ) if (p && p->type != (typ)) {               \
        qemudReportError(NULL, NULL, NULL, VIR_ERR_INTERNAL_ERROR,      \
                         "remoteReadConfigFile: %s: %s: expected type " #typ "\n", \
                         filename, (name));                             \
        virConfFree(conf);                                              \
        return -1;                                                      \
    }

    p = virConfGetValue (conf, "vnc_tls");
    CHECK_TYPE ("vnc_tls", VIR_CONF_LONG);
    if (p) driver->vncTLS = p->l;

    p = virConfGetValue (conf, "vnc_tls_x509_verify");
    CHECK_TYPE ("vnc_tls_x509_verify", VIR_CONF_LONG);
    if (p) driver->vncTLSx509verify = p->l;

    p = virConfGetValue (conf, "vnc_tls_x509_cert_dir");
    CHECK_TYPE ("vnc_tls_x509_cert_dir", VIR_CONF_STRING);
    if (p && p->str) {
        free(driver->vncTLSx509certdir);
        if (!(driver->vncTLSx509certdir = strdup(p->str))) {
            qemudReportError(NULL, NULL, NULL, VIR_ERR_NO_MEMORY,
                             "vncTLSx509certdir");
            virConfFree(conf);
            return -1;
        }
    }

    p = virConfGetValue (conf, "vnc_listen");
    CHECK_TYPE ("vnc_listen", VIR_CONF_STRING);
    if (p && p->str) {
        strncpy(driver->vncListen, p->str, sizeof(driver->vncListen));
        driver->vncListen[sizeof(driver->vncListen)-1] = '\0';
    }

    virConfFree (conf);
    return 0;
}


135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
struct qemud_vm *qemudFindVMByID(const struct qemud_driver *driver, int id) {
    struct qemud_vm *vm = driver->vms;

    while (vm) {
        if (qemudIsActiveVM(vm) && vm->id == id)
            return vm;
        vm = vm->next;
    }

    return NULL;
}

struct qemud_vm *qemudFindVMByUUID(const struct qemud_driver *driver,
                                   const unsigned char *uuid) {
    struct qemud_vm *vm = driver->vms;

    while (vm) {
152
        if (!memcmp(vm->def->uuid, uuid, VIR_UUID_BUFLEN))
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
            return vm;
        vm = vm->next;
    }

    return NULL;
}

struct qemud_vm *qemudFindVMByName(const struct qemud_driver *driver,
                                   const char *name) {
    struct qemud_vm *vm = driver->vms;

    while (vm) {
        if (!strcmp(vm->def->name, name))
            return vm;
        vm = vm->next;
    }

    return NULL;
}

struct qemud_network *qemudFindNetworkByUUID(const struct qemud_driver *driver,
                                             const unsigned char *uuid) {
    struct qemud_network *network = driver->networks;

    while (network) {
178
        if (!memcmp(network->def->uuid, uuid, VIR_UUID_BUFLEN))
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
            return network;
        network = network->next;
    }

    return NULL;
}

struct qemud_network *qemudFindNetworkByName(const struct qemud_driver *driver,
                                             const char *name) {
    struct qemud_network *network = driver->networks;

    while (network) {
        if (!strcmp(network->def->name, name))
            return network;
        network = network->next;
    }

    return NULL;
}

199

200 201 202 203
/* Free all memory associated with a struct qemud_vm object */
void qemudFreeVMDef(struct qemud_vm_def *def) {
    struct qemud_vm_disk_def *disk = def->disks;
    struct qemud_vm_net_def *net = def->nets;
D
Daniel P. Berrange 已提交
204
    struct qemud_vm_input_def *input = def->inputs;
205 206 207 208 209 210 211 212 213 214 215

    while (disk) {
        struct qemud_vm_disk_def *prev = disk;
        disk = disk->next;
        free(prev);
    }
    while (net) {
        struct qemud_vm_net_def *prev = net;
        net = net->next;
        free(prev);
    }
D
Daniel P. Berrange 已提交
216 217 218 219 220
    while (input) {
        struct qemud_vm_input_def *prev = input;
        input = input->next;
        free(prev);
    }
221
    xmlFree(def->keymap);
222
    free(def);
223 224 225 226 227 228 229 230
}

void qemudFreeVM(struct qemud_vm *vm) {
    qemudFreeVMDef(vm->def);
    if (vm->newDef)
        qemudFreeVMDef(vm->newDef);
    free(vm);
}
D
Daniel P. Berrange 已提交
231

232

D
Daniel P. Berrange 已提交
233 234
/* The list of possible machine types for various architectures,
   as supported by QEMU - taken from 'qemu -M ?' for each arch */
J
Jim Meyering 已提交
235
static const char *const arch_info_x86_machines[] = {
236
    "pc", "isapc", NULL
D
Daniel P. Berrange 已提交
237
};
J
Jim Meyering 已提交
238
static const char *const arch_info_mips_machines[] = {
239
    "mips", NULL
D
Daniel P. Berrange 已提交
240
};
J
Jim Meyering 已提交
241
static const char *const arch_info_sparc_machines[] = {
242
    "sun4m", NULL
D
Daniel P. Berrange 已提交
243
};
J
Jim Meyering 已提交
244
static const char *const arch_info_ppc_machines[] = {
245
    "g3bw", "mac99", "prep", NULL
D
Daniel P. Berrange 已提交
246 247
};

248
/* Feature flags for the architecture info */
J
Jim Meyering 已提交
249
static const struct qemu_feature_flags const arch_info_i686_flags [] = {
250 251 252 253 254 255
    { "pae",  1, 1 },
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
    { NULL, -1, -1 }
};

J
Jim Meyering 已提交
256
static const struct qemu_feature_flags const arch_info_x86_64_flags [] = {
257 258 259 260 261
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
    { NULL, -1, -1 }
};

D
Daniel P. Berrange 已提交
262
/* The archicture tables for supported QEMU archs */
263
const struct qemu_arch_info const qemudArchs[] = {
264
    /* i686 must be in position 0 */
265
    {  "i686", 32, arch_info_x86_machines, "qemu", arch_info_i686_flags },
266
    /* x86_64 must be in position 1 */
267 268 269 270 271 272
    {  "x86_64", 64, arch_info_x86_machines, "qemu-system-x86_64", arch_info_x86_64_flags },
    {  "mips", 32, arch_info_mips_machines, "qemu-system-mips", NULL },
    {  "mipsel", 32, arch_info_mips_machines, "qemu-system-mipsel", NULL },
    {  "sparc", 32, arch_info_sparc_machines, "qemu-system-sparc", NULL },
    {  "ppc", 32, arch_info_ppc_machines, "qemu-system-ppc", NULL },
    { NULL, -1, NULL, NULL, NULL }
D
Daniel P. Berrange 已提交
273 274 275 276
};

/* Return the default architecture if none is explicitly requested*/
static const char *qemudDefaultArch(void) {
277
    return qemudArchs[0].arch;
D
Daniel P. Berrange 已提交
278 279 280 281 282 283
}

/* Return the default machine type for a given architecture */
static const char *qemudDefaultMachineForArch(const char *arch) {
    int i;

284 285 286
    for (i = 0; qemudArchs[i].arch; i++) {
        if (!strcmp(qemudArchs[i].arch, arch)) {
            return qemudArchs[i].machines[0];
D
Daniel P. Berrange 已提交
287 288 289 290 291 292 293 294 295 296
        }
    }

    return NULL;
}

/* Return the default binary name for a particular architecture */
static const char *qemudDefaultBinaryForArch(const char *arch) {
    int i;

297 298 299
    for (i = 0 ; qemudArchs[i].arch; i++) {
        if (!strcmp(qemudArchs[i].arch, arch)) {
            return qemudArchs[i].binary;
D
Daniel P. Berrange 已提交
300 301 302 303 304 305 306
        }
    }

    return NULL;
}

/* Find the fully qualified path to the binary for an architecture */
307
static char *qemudLocateBinaryForArch(virConnectPtr conn,
D
Daniel P. Berrange 已提交
308 309 310 311 312 313 314 315 316 317
                                      int virtType, const char *arch) {
    const char *name;
    char *path;

    if (virtType == QEMUD_VIRT_KVM)
        name = "qemu-kvm";
    else
        name = qemudDefaultBinaryForArch(arch);

    if (!name) {
318
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot determin binary for architecture %s", arch);
D
Daniel P. Berrange 已提交
319 320 321 322 323 324
        return NULL;
    }

    /* XXX lame. should actually use $PATH ... */
    path = malloc(strlen(name) + strlen("/usr/bin/") + 1);
    if (!path) {
325
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "path");
D
Daniel P. Berrange 已提交
326 327 328 329 330 331 332
        return NULL;
    }
    strcpy(path, "/usr/bin/");
    strcat(path, name);
    return path;
}

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367

static int qemudExtractVersionInfo(const char *qemu, int *version, int *flags) {
    pid_t child;
    int newstdout[2];

    *flags = 0;
    *version = 0;

    if (pipe(newstdout) < 0) {
        return -1;
    }

    if ((child = fork()) < 0) {
        close(newstdout[0]);
        close(newstdout[1]);
        return -1;
    }

    if (child == 0) { /* Kid */
        if (close(STDIN_FILENO) < 0)
            goto cleanup1;
        if (close(STDERR_FILENO) < 0)
            goto cleanup1;
        if (close(newstdout[0]) < 0)
            goto cleanup1;
        if (dup2(newstdout[1], STDOUT_FILENO) < 0)
            goto cleanup1;

        /* Just in case QEMU is translated someday.. */
        setenv("LANG", "C", 1);
        execl(qemu, qemu, (char*)NULL);

    cleanup1:
        _exit(-1); /* Just in case */
    } else { /* Parent */
D
Daniel P. Berrange 已提交
368
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
369
        int got = 0, ret = -1;
370 371 372 373 374
        int major, minor, micro;

        if (close(newstdout[1]) < 0)
            goto cleanup2;

D
Daniel P. Berrange 已提交
375 376 377 378 379 380 381 382 383 384
        while (got < (sizeof(help)-1)) {
            int len;
            if ((len = read(newstdout[0], help+got, sizeof(help)-got-1)) <= 0) {
                if (!len)
                    break;
                if (errno == EINTR)
                    continue;
                goto cleanup2;
            }
            got += len;
385 386 387 388 389 390 391 392 393 394
        }
        help[got] = '\0';

        if (sscanf(help, "QEMU PC emulator version %d.%d.%d", &major,&minor, &micro) != 3) {
            goto cleanup2;
        }

        *version = (major * 1000 * 1000) + (minor * 1000) + micro;
        if (strstr(help, "-no-kqemu"))
            *flags |= QEMUD_CMD_FLAG_KQEMU;
D
Daniel P. Berrange 已提交
395 396
        if (strstr(help, "-no-reboot"))
            *flags |= QEMUD_CMD_FLAG_NO_REBOOT;
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
        if (*version >= 9000)
            *flags |= QEMUD_CMD_FLAG_VNC_COLON;
        ret = 0;

        qemudDebug("Version %d %d %d  Cooked version: %d, with flags ? %d",
                   major, minor, micro, *version, *flags);

    cleanup2:
        if (close(newstdout[0]) < 0)
            ret = -1;

    rewait:
        if (waitpid(child, &got, 0) != child) {
            if (errno == EINTR) {
                goto rewait;
            }
            qemudLog(QEMUD_ERR, "Unexpected exit status from qemu %d pid %lu", got, (unsigned long)child);
            ret = -1;
        }
        /* Check & log unexpected exit status, but don't fail,
         * as there's really no need to throw an error if we did
         * actually read a valid version number above */
        if (WEXITSTATUS(got) != 1) {
            qemudLog(QEMUD_WARN, "Unexpected exit status '%d', qemu probably failed", got);
        }

        return ret;
    }
}

427
int qemudExtractVersion(virConnectPtr conn,
428
                        struct qemud_driver *driver ATTRIBUTE_UNUSED) {
429
    char *binary = NULL;
430
    struct stat sb;
431
    int ignored;
432

433
    if (driver->qemuVersion > 0)
434 435
        return 0;

436
    if (!(binary = qemudLocateBinaryForArch(conn, QEMUD_VIRT_QEMU, "i686")))
437 438
        return -1;

439
    if (stat(binary, &sb) < 0) {
440
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
441 442 443 444 445 446
                         "Cannot find QEMU binary %s: %s", binary,
                         strerror(errno));
        free(binary);
        return -1;
    }

447
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &ignored) < 0) {
448 449 450 451 452 453 454 455 456
        free(binary);
        return -1;
    }

    free(binary);
    return 0;
}


D
Daniel P. Berrange 已提交
457 458 459 460 461 462 463 464
/* Parse the XML definition for a disk
 * @param disk pre-allocated & zero'd disk record
 * @param node XML nodeset to parse for disk definition
 * @return 0 on success, -1 on failure
 */
static int qemudParseDiskXML(virConnectPtr conn,
                             struct qemud_vm_disk_def *disk,
                             xmlNodePtr node) {
D
Daniel P. Berrange 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
    xmlNodePtr cur;
    xmlChar *device = NULL;
    xmlChar *source = NULL;
    xmlChar *target = NULL;
    xmlChar *type = NULL;
    int typ = 0;

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
        if (xmlStrEqual(type, BAD_CAST "file"))
            typ = QEMUD_DISK_FILE;
        else if (xmlStrEqual(type, BAD_CAST "block"))
            typ = QEMUD_DISK_BLOCK;
        else {
            typ = QEMUD_DISK_FILE;
        }
        xmlFree(type);
        type = NULL;
    }

    device = xmlGetProp(node, BAD_CAST "device");
486

D
Daniel P. Berrange 已提交
487 488 489 490 491
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
492

D
Daniel P. Berrange 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
                if (typ == QEMUD_DISK_FILE)
                    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");
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                disk->readonly = 1;
            }
        }
        cur = cur->next;
    }

    if (source == NULL) {
508
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SOURCE, target ? "%s" : NULL, target);
D
Daniel P. Berrange 已提交
509 510 511
        goto error;
    }
    if (target == NULL) {
512
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
513 514 515 516 517 518 519
        goto error;
    }

    if (device &&
        !strcmp((const char *)device, "floppy") &&
        strcmp((const char *)target, "fda") &&
        strcmp((const char *)target, "fdb")) {
520
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid floppy device name: %s", target);
D
Daniel P. Berrange 已提交
521 522
        goto error;
    }
523

D
Daniel P. Berrange 已提交
524 525 526
    if (device &&
        !strcmp((const char *)device, "cdrom") &&
        strcmp((const char *)target, "hdc")) {
527
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid cdrom device name: %s", target);
D
Daniel P. Berrange 已提交
528 529 530 531 532 533 534 535 536 537 538 539
        goto error;
    }

    if (device &&
        !strcmp((const char *)device, "cdrom"))
        disk->readonly = 1;

    if ((!device || !strcmp((const char *)device, "disk")) &&
        strcmp((const char *)target, "hda") &&
        strcmp((const char *)target, "hdb") &&
        strcmp((const char *)target, "hdc") &&
        strcmp((const char *)target, "hdd")) {
540
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid harddisk device name: %s", target);
D
Daniel P. Berrange 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        goto error;
    }

    strncpy(disk->src, (const char *)source, NAME_MAX-1);
    disk->src[NAME_MAX-1] = '\0';

    strncpy(disk->dst, (const char *)target, NAME_MAX-1);
    disk->dst[NAME_MAX-1] = '\0';
    disk->type = typ;

    if (!device)
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "disk"))
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "cdrom"))
        disk->device = QEMUD_DISK_CDROM;
    else if (!strcmp((const char *)device, "floppy"))
        disk->device = QEMUD_DISK_FLOPPY;
    else {
560
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid device type: %s", device);
D
Daniel P. Berrange 已提交
561 562 563 564 565 566 567
        goto error;
    }

    xmlFree(device);
    xmlFree(target);
    xmlFree(source);

D
Daniel P. Berrange 已提交
568
    return 0;
D
Daniel P. Berrange 已提交
569 570 571 572 573 574 575 576 577 578

 error:
    if (type)
        xmlFree(type);
    if (target)
        xmlFree(target);
    if (source)
        xmlFree(source);
    if (device)
        xmlFree(device);
D
Daniel P. Berrange 已提交
579
    return -1;
D
Daniel P. Berrange 已提交
580 581
}

582 583 584 585 586 587 588 589 590
static void qemudRandomMAC(struct qemud_vm_net_def *net) {
    net->mac[0] = 0x52;
    net->mac[1] = 0x54;
    net->mac[2] = 0x00;
    net->mac[3] = 1 + (int)(256*(rand()/(RAND_MAX+1.0)));
    net->mac[4] = 1 + (int)(256*(rand()/(RAND_MAX+1.0)));
    net->mac[5] = 1 + (int)(256*(rand()/(RAND_MAX+1.0)));
}

D
Daniel P. Berrange 已提交
591

D
Daniel P. Berrange 已提交
592 593 594 595 596 597 598 599
/* Parse the XML definition for a network interface
 * @param net pre-allocated & zero'd net record
 * @param node XML nodeset to parse for net definition
 * @return 0 on success, -1 on failure
 */
static int qemudParseInterfaceXML(virConnectPtr conn,
                                  struct qemud_vm_net_def *net,
                                  xmlNodePtr node) {
D
Daniel P. Berrange 已提交
600 601 602
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
603
    xmlChar *network = NULL;
604 605 606 607 608
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
D
Daniel P. Berrange 已提交
609 610 611 612 613 614 615

    net->type = QEMUD_NET_USER;

    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
        if (xmlStrEqual(type, BAD_CAST "user"))
            net->type = QEMUD_NET_USER;
616 617
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
618 619 620 621 622 623
        else if (xmlStrEqual(type, BAD_CAST "server"))
            net->type = QEMUD_NET_SERVER;
        else if (xmlStrEqual(type, BAD_CAST "client"))
            net->type = QEMUD_NET_CLIENT;
        else if (xmlStrEqual(type, BAD_CAST "mcast"))
            net->type = QEMUD_NET_MCAST;
624 625
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
626 627
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
628 629 630 631 632 633 634 635 636 637 638 639
        else
            net->type = QEMUD_NET_USER;
        xmlFree(type);
        type = NULL;
    }

    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((macaddr == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "mac"))) {
                macaddr = xmlGetProp(cur, BAD_CAST "address");
640 641 642 643
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
644 645 646
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
647
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
648 649 650 651 652 653 654 655 656 657 658 659 660
            } else if ((network == NULL) &&
                       ((net->type == QEMUD_NET_SERVER) ||
                        (net->type == QEMUD_NET_CLIENT) ||
                        (net->type == QEMUD_NET_MCAST)) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                address = xmlGetProp(cur, BAD_CAST "address");
                port = xmlGetProp(cur, BAD_CAST "port");
            } else if ((ifname == NULL) &&
                       ((net->type == QEMUD_NET_NETWORK) ||
                        (net->type == QEMUD_NET_ETHERNET) ||
                        (net->type == QEMUD_NET_BRIDGE)) &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
                ifname = xmlGetProp(cur, BAD_CAST "dev");
661 662 663 664 665
                if (STREQLEN("vnet", (const char*)ifname, 4)) {
                    /* An auto-generated target name, blank it out */
                    xmlFree(ifname);
                    ifname = NULL;
                }
666 667 668 669
            } else if ((script == NULL) &&
                       (net->type == QEMUD_NET_ETHERNET) &&
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = xmlGetProp(cur, BAD_CAST "path");
D
Daniel P. Berrange 已提交
670 671 672 673 674 675
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
676
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
677
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
678 679 680 681 682 683 684 685 686 687 688 689
               (unsigned int*)&mac[0],
               (unsigned int*)&mac[1],
               (unsigned int*)&mac[2],
               (unsigned int*)&mac[3],
               (unsigned int*)&mac[4],
               (unsigned int*)&mac[5]);
        net->mac[0] = mac[0];
        net->mac[1] = mac[1];
        net->mac[2] = mac[2];
        net->mac[3] = mac[3];
        net->mac[4] = mac[4];
        net->mac[5] = mac[5];
D
Daniel P. Berrange 已提交
690 691

        xmlFree(macaddr);
692 693 694
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
695 696
    }

697 698 699 700
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
701
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
702 703
                             "No <source> 'network' attribute specified with <interface type='network'/>");
            goto error;
704
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
705
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
706 707 708 709 710 711 712
                             "Network name '%s' too long", network);
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

713
        if (network) {
714
            xmlFree(network);
715 716 717 718 719
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
720
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
721 722 723 724 725 726 727 728 729 730 731
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.network.ifname, (char *)ifname, len);
                net->dst.network.ifname[len] = '\0';
            }
            xmlFree(ifname);
            ifname = NULL;
        }
    } else if (net->type == QEMUD_NET_ETHERNET) {
        int len;
732

733 734
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
735
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
736 737 738 739 740 741 742 743 744 745 746
                                 "TAP script path '%s' is too long", script);
                goto error;
            } else {
                strncpy(net->dst.ethernet.script, (char *)script, len);
                net->dst.ethernet.script[len] = '\0';
            }
            xmlFree(script);
            script = NULL;
        }
        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
747
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
748
                                 "TAP interface name '%s' is too long", ifname);
749 750
                goto error;
            } else {
751 752
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
753
            }
754 755 756 757 758 759
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
760
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
761 762 763
                             "No <source> 'dev' attribute specified with <interface type='bridge'/>");
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
764
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
765 766 767 768 769
                             "TAP bridge path '%s' is too long", bridge);
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
770
        }
771 772 773 774 775 776

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
777
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
778 779 780 781 782 783 784 785 786 787 788
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.bridge.ifname, (char *)ifname, len);
                net->dst.bridge.ifname[len] = '\0';
            }
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_CLIENT ||
               net->type == QEMUD_NET_SERVER ||
               net->type == QEMUD_NET_MCAST) {
789
        int len = 0;
790 791 792
        char *ret;

        if (port == NULL) {
793
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
794 795 796 797 798
                             "No <source> 'port' attribute specified with socket interface");
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
799
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
800 801 802 803 804 805 806 807 808
                             "Cannot parse <source> 'port' attribute with socket interface");
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
809
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
810 811 812 813
                                 "No <source> 'address' attribute specified with socket interface");
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
814
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
815 816 817 818 819 820 821 822 823 824
                             "IP address '%s' is too long", address);
            goto error;
        }
        if (address == NULL) {
            net->dst.socket.address[0] = '\0';
        } else {
            strncpy(net->dst.socket.address, (char*)address,len);
            net->dst.socket.address[len] = '\0';
        }
        xmlFree(address);
825 826
    }

D
Daniel P. Berrange 已提交
827
    return 0;
828 829 830 831

 error:
    if (network)
        xmlFree(network);
832 833 834 835 836 837 838 839 840 841
    if (address)
        xmlFree(address);
    if (port)
        xmlFree(port);
    if (ifname)
        xmlFree(ifname);
    if (script)
        xmlFree(script);
    if (bridge)
        xmlFree(bridge);
D
Daniel P. Berrange 已提交
842
    return -1;
D
Daniel P. Berrange 已提交
843 844 845
}


846
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
847 848 849
static int qemudParseInputXML(virConnectPtr conn,
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

    if (!type) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "no type provide for input device");
        goto error;
    }

    if (!strcmp((const char *)type, "mouse")) {
        input->type = QEMU_INPUT_TYPE_MOUSE;
    } else if (!strcmp((const char *)type, "tablet")) {
        input->type = QEMU_INPUT_TYPE_TABLET;
    } else {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unsupported input device type %s", (const char*)type);
        goto error;
    }

    if (bus) {
        if (!strcmp((const char*)bus, "ps2")) { /* Only allow mouse */
            if (input->type == QEMU_INPUT_TYPE_TABLET) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "ps2 bus does not support %s input device", (const char*)type);
                goto error;
            }
            input->bus = QEMU_INPUT_BUS_PS2;
        } else if (!strcmp((const char *)bus, "usb")) { /* Allow mouse & keyboard */
            input->bus = QEMU_INPUT_BUS_USB;
        } else {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unsupported input bus %s", (const char*)bus);
            goto error;
        }
    } else {
        if (input->type == QEMU_INPUT_TYPE_MOUSE)
            input->bus = QEMU_INPUT_BUS_PS2;
        else
            input->bus = QEMU_INPUT_BUS_USB;
    }

    if (type)
        xmlFree(type);
    if (bus)
        xmlFree(bus);

D
Daniel P. Berrange 已提交
895
    return 0;
896 897 898 899 900 901 902

 error:
    if (type)
        xmlFree(type);
    if (bus)
        xmlFree(bus);

D
Daniel P. Berrange 已提交
903
    return -1;
904 905 906
}


D
Daniel P. Berrange 已提交
907 908 909 910
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
911 912
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
913
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
914 915 916 917 918 919
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
920 921
    struct qemud_vm_def *def;

922
    if (!(def = calloc(1, sizeof(*def)))) {
923
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
924 925
        return NULL;
    }
D
Daniel P. Berrange 已提交
926 927 928 929

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
930
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
D
Daniel P. Berrange 已提交
931 932 933 934 935
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
936
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
D
Daniel P. Berrange 已提交
937 938 939 940 941 942
        goto error;
    }


    /* Find out what type of QEMU virtualization to use */
    if (!(prop = xmlGetProp(root, BAD_CAST "type"))) {
943
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "missing domain type attribute");
D
Daniel P. Berrange 已提交
944 945 946 947
        goto error;
    }

    if (!strcmp((char *)prop, "qemu"))
948
        def->virtType = QEMUD_VIRT_QEMU;
D
Daniel P. Berrange 已提交
949
    else if (!strcmp((char *)prop, "kqemu"))
950
        def->virtType = QEMUD_VIRT_KQEMU;
D
Daniel P. Berrange 已提交
951
    else if (!strcmp((char *)prop, "kvm"))
952
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
953
    else {
954
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "invalid domain type attribute");
D
Daniel P. Berrange 已提交
955 956 957 958 959 960 961 962 963 964
        goto error;
    }
    free(prop);
    prop = NULL;


    /* Extract domain name */
    obj = xmlXPathEval(BAD_CAST "string(/domain/name[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
965
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
966 967 968
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
969
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "domain name length too long");
D
Daniel P. Berrange 已提交
970 971
        goto error;
    }
972
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
973 974 975 976 977 978 979
    xmlXPathFreeObject(obj);


    /* Extract domain uuid */
    obj = xmlXPathEval(BAD_CAST "string(/domain/uuid[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
980
        int err;
D
Daniel P. Berrange 已提交
981
        if ((err = virUUIDGenerate(def->uuid))) {
982
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
983 984 985
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
986
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
987
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
D
Daniel P. Berrange 已提交
988 989 990 991 992 993 994 995 996
        goto error;
    }
    xmlXPathFreeObject(obj);


    /* Extract domain memory */
    obj = xmlXPathEval(BAD_CAST "string(/domain/memory[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
997
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "missing memory element");
D
Daniel P. Berrange 已提交
998 999 1000
        goto error;
    } else {
        conv = NULL;
1001
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1002
        if (conv == (const char*)obj->stringval) {
1003
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);


    /* Extract domain memory */
    obj = xmlXPathEval(BAD_CAST "string(/domain/currentMemory[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1015
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1016 1017
    } else {
        conv = NULL;
1018 1019 1020
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1021
        if (conv == (const char*)obj->stringval) {
1022
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);

    /* Extract domain vcpu info */
    obj = xmlXPathEval(BAD_CAST "string(/domain/vcpu[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1033
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1034 1035
    } else {
        conv = NULL;
1036
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1037
        if (conv == (const char*)obj->stringval) {
1038
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed vcpu information");
D
Daniel P. Berrange 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);

    /* See if ACPI feature is requested */
    obj = xmlXPathEval(BAD_CAST "/domain/features/acpi", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr == 1)) {
1049
        def->features |= QEMUD_FEATURE_ACPI;
D
Daniel P. Berrange 已提交
1050
    }
1051
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1052

D
Daniel P. Berrange 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

    /* See if we disable reboots */
    obj = xmlXPathEval(BAD_CAST "string(/domain/on_reboot)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        def->noReboot = 0;
    } else {
        if (!strcmp((char*)obj->stringval, "destroy"))
            def->noReboot = 1;
        else
            def->noReboot = 0;
    }
    if (obj)
        xmlXPathFreeObject(obj);

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    /* See if we set clock to localtime */
    obj = xmlXPathEval(BAD_CAST "string(/domain/clock/@offset)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        def->localtime = 0;
    } else {
        if (!strcmp((char*)obj->stringval, "localtime"))
            def->localtime = 1;
        else
            def->localtime = 0;
    }
    if (obj)
        xmlXPathFreeObject(obj);

D
Daniel P. Berrange 已提交
1082

D
Daniel P. Berrange 已提交
1083 1084 1085 1086
    /* Extract OS type info */
    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1087
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, NULL);
D
Daniel P. Berrange 已提交
1088 1089 1090
        goto error;
    }
    if (strcmp((const char *)obj->stringval, "hvm")) {
1091
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, "%s", obj->stringval);
D
Daniel P. Berrange 已提交
1092 1093
        goto error;
    }
1094
    strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1095 1096 1097 1098 1099 1100 1101 1102
    xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1]/@arch)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        const char *defaultArch = qemudDefaultArch();
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1103
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1104 1105
            goto error;
        }
1106
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
1107 1108
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1109
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1110 1111
            goto error;
        }
1112
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1113 1114 1115 1116 1117 1118 1119
    }
    if (obj)
        xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1]/@machine)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1120
        const char *defaultMachine = qemudDefaultMachineForArch(def->os.arch);
1121 1122 1123 1124
        if (!defaultMachine) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unsupported arch %s", def->os.arch);
            goto error;
        }
D
Daniel P. Berrange 已提交
1125
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1126
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "machine type too long");
D
Daniel P. Berrange 已提交
1127 1128
            goto error;
        }
1129
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1130 1131
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1132
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1133 1134
            goto error;
        }
1135
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/kernel[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1145
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "kernel path too long");
D
Daniel P. Berrange 已提交
1146 1147
            goto error;
        }
1148
        strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1149 1150 1151 1152 1153 1154 1155 1156 1157
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/initrd[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1158
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "initrd path too long");
D
Daniel P. Berrange 已提交
1159 1160
            goto error;
        }
1161
        strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/cmdline[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1171
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "cmdline arguments too long");
D
Daniel P. Berrange 已提交
1172 1173
            goto error;
        }
1174
        strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
    }
    if (obj)
        xmlXPathFreeObject(obj);


    /* analysis of the disk devices */
    obj = xmlXPathEval(BAD_CAST "/domain/os/boot", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        for (i = 0; i < obj->nodesetval->nodeNr && i < QEMUD_MAX_BOOT_DEVS ; i++) {
1185 1186
            if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                continue;
D
Daniel P. Berrange 已提交
1187
            if (!strcmp((char *)prop, "hd")) {
1188
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1189
            } else if (!strcmp((char *)prop, "fd")) {
1190
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
D
Daniel P. Berrange 已提交
1191
            } else if (!strcmp((char *)prop, "cdrom")) {
1192
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
1193
            } else if (!strcmp((char *)prop, "network")) {
1194
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
D
Daniel P. Berrange 已提交
1195
            } else {
1196 1197
	        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
				 "unknown boot dev \'%s\'", (char*)prop);
D
Daniel P. Berrange 已提交
1198 1199
                goto error;
            }
1200
            xmlFree(prop);
1201
            prop = NULL;
D
Daniel P. Berrange 已提交
1202 1203 1204
        }
    }
    xmlXPathFreeObject(obj);
1205 1206 1207
    if (def->os.nBootDevs == 0) {
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1208 1209 1210 1211 1212 1213
    }


    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1214
        char *tmp = qemudLocateBinaryForArch(conn, def->virtType, def->os.arch);
D
Daniel P. Berrange 已提交
1215 1216 1217
        if (!tmp) {
            goto error;
        }
1218
        strcpy(def->os.binary, tmp);
D
Daniel P. Berrange 已提交
1219 1220 1221
        free(tmp);
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1222
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "emulator path too long");
D
Daniel P. Berrange 已提交
1223 1224
            goto error;
        }
1225
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1226 1227 1228 1229 1230 1231 1232
    }
    if (obj)
        xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1233
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1234
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
D
Daniel P. Berrange 已提交
1235
        if (!strcmp((char *)prop, "vnc")) {
1236
            xmlChar *vncport, *vnclisten;
1237
            def->graphicsType = QEMUD_GRAPHICS_VNC;
1238 1239
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
1240
                conv = NULL;
1241
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
1242
            } else {
1243
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1244
            }
1245 1246 1247 1248
            vnclisten = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "listen");
            if (vnclisten && *vnclisten)
                strncpy(def->vncListen, (char *)vnclisten, BR_INET_ADDR_MAXLEN-1);
            else
D
Daniel P. Berrange 已提交
1249
                strcpy(def->vncListen, driver->vncListen);
1250
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
1251
            def->keymap = (char *) xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "keymap");
1252 1253
            xmlFree(vncport);
            xmlFree(vnclisten);
D
Daniel P. Berrange 已提交
1254
        } else if (!strcmp((char *)prop, "sdl")) {
1255
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1256
        } else {
1257
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Unsupported graphics type %s", prop);
D
Daniel P. Berrange 已提交
1258 1259
            goto error;
        }
1260
        xmlFree(prop);
1261
        prop = NULL;
D
Daniel P. Berrange 已提交
1262
    }
1263
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1264 1265 1266 1267 1268

    /* analysis of the disk devices */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/disk", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
1269
        struct qemud_vm_disk_def *prev = NULL;
D
Daniel P. Berrange 已提交
1270
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1271
            struct qemud_vm_disk_def *disk = calloc(1, sizeof(*disk));
D
Daniel P. Berrange 已提交
1272 1273 1274 1275 1276 1277
            if (!disk) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "disk");
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
                free(disk);
D
Daniel P. Berrange 已提交
1278 1279
                goto error;
            }
1280
            def->ndisks++;
1281 1282 1283 1284 1285 1286 1287
            disk->next = NULL;
            if (i == 0) {
                def->disks = disk;
            } else {
                prev->next = disk;
            }
            prev = disk;
D
Daniel P. Berrange 已提交
1288 1289 1290 1291 1292 1293 1294 1295 1296
        }
    }
    xmlXPathFreeObject(obj);


    /* analysis of the network devices */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/interface", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
1297
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
1298
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1299
            struct qemud_vm_net_def *net = calloc(1, sizeof(*net));
D
Daniel P. Berrange 已提交
1300 1301 1302 1303 1304 1305
            if (!net) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "net");
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
                free(net);
D
Daniel P. Berrange 已提交
1306 1307
                goto error;
            }
1308
            def->nnets++;
1309 1310 1311 1312 1313 1314 1315
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
1316 1317 1318
        }
    }
    xmlXPathFreeObject(obj);
1319 1320 1321 1322 1323 1324 1325

    /* analysis of the input devices */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/input", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        struct qemud_vm_input_def *prev = NULL;
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1326
            struct qemud_vm_input_def *input = calloc(1, sizeof(*input));
D
Daniel P. Berrange 已提交
1327 1328 1329 1330 1331 1332
            if (!input) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "input");
                goto error;
            }
            if (qemudParseInputXML(conn, input, obj->nodesetval->nodeTab[i]) < 0) {
                free(input);
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
                goto error;
            }
            /* Mouse + PS/2 is implicit with graphics, so don't store it */
            if (input->bus == QEMU_INPUT_BUS_PS2 &&
                input->type == QEMU_INPUT_TYPE_MOUSE) {
                free(input);
                continue;
            }
            def->ninputs++;
            input->next = NULL;
1343
            if (def->inputs == NULL) {
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
                def->inputs = input;
            } else {
                prev->next = input;
            }
            prev = input;
        }
    }
    xmlXPathFreeObject(obj);
    obj = NULL;

    /* If graphics are enabled, there's an implicit PS2 mouse */
    if (def->graphicsType != QEMUD_GRAPHICS_NONE) {
        int hasPS2mouse = 0;
        struct qemud_vm_input_def *input = def->inputs;
        while (input) {
            if (input->type == QEMU_INPUT_TYPE_MOUSE &&
                input->bus == QEMU_INPUT_BUS_PS2)
                hasPS2mouse = 1;
            input = input->next;
        }

        if (!hasPS2mouse) {
1366
            input = calloc(1, sizeof(*input));
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
            if (!input) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "input");
                goto error;
            }
            input->type = QEMU_INPUT_TYPE_MOUSE;
            input->bus = QEMU_INPUT_BUS_PS2;
            input->next = def->inputs;
            def->inputs = input;
            def->ninputs++;
        }
    }

D
Daniel P. Berrange 已提交
1379 1380
    xmlXPathFreeContext(ctxt);

1381
    return def;
D
Daniel P. Berrange 已提交
1382 1383

 error:
1384
    free(prop);
D
Daniel P. Berrange 已提交
1385 1386
    if (obj)
        xmlXPathFreeObject(obj);
1387
    xmlXPathFreeContext(ctxt);
1388 1389
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
1390 1391 1392
}


1393
static char *
1394 1395
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
1396
                         struct qemud_vm *vm,
1397 1398
                         struct qemud_vm_net_def *net,
                         int vlan)
1399
{
1400 1401 1402
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
1403 1404 1405 1406 1407 1408
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

1409
    if (net->type == QEMUD_NET_NETWORK) {
1410
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
1411
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1412 1413 1414
                             "Network '%s' not found", net->dst.network.name);
            goto error;
        } else if (network->bridge[0] == '\0') {
1415
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1416 1417 1418 1419 1420
                             "Network '%s' not active", net->dst.network.name);
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
1421
            STREQLEN(net->dst.network.ifname, "vnet", 4) ||
1422 1423 1424 1425 1426 1427 1428
            strchr(net->dst.network.ifname, '%')) {
            strcpy(net->dst.network.ifname, "vnet%d");
        }
        ifname = net->dst.network.ifname;
    } else if (net->type == QEMUD_NET_BRIDGE) {
        brname = net->dst.bridge.brname;
        if (net->dst.bridge.ifname[0] == '\0' ||
1429
            STREQLEN(net->dst.bridge.ifname, "vnet", 4) ||
1430 1431 1432 1433 1434
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
1435
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1436
                         "Network type %d is not supported", net->type);
1437 1438 1439
        goto error;
    }

1440
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
1441
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1442 1443 1444 1445
                         "cannot initialize bridge support: %s", strerror(err));
        goto error;
    }

1446
    if ((err = brAddTap(driver->brctl, brname,
1447
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
1448
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1449
                         "Failed to add tap interface '%s' to bridge '%s' : %s",
1450
                         ifname, brname, strerror(err));
1451 1452 1453
        goto error;
    }

1454
    snprintf(tapfdstr, sizeof(tapfdstr), "tap,fd=%d,script=,vlan=%d", tapfd, vlan);
1455 1456 1457 1458

    if (!(retval = strdup(tapfdstr)))
        goto no_memory;

1459
    if (!(tapfds = realloc(vm->tapfds, sizeof(*tapfds) * (vm->ntapfds+2))))
1460 1461 1462 1463 1464 1465 1466 1467 1468
        goto no_memory;

    vm->tapfds = tapfds;
    vm->tapfds[vm->ntapfds++] = tapfd;
    vm->tapfds[vm->ntapfds]   = -1;

    return retval;

 no_memory:
1469
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "tapfds");
1470
 error:
1471
    free(retval);
1472 1473 1474 1475 1476
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

D
Daniel P. Berrange 已提交
1477 1478 1479 1480
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
1481 1482
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
1483
                          struct qemud_vm *vm,
1484 1485
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
1486 1487 1488
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
1489
    struct stat sb;
1490 1491
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
1492
    struct qemud_vm_input_def *input = vm->def->inputs;
1493 1494
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
1495

1496 1497 1498 1499 1500 1501 1502 1503
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
    if (stat(vm->def->os.binary, &sb) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "Cannot find QEMU binary %s: %s", vm->def->os.binary,
                         strerror(errno));
1504
        return -1;
1505 1506 1507 1508 1509 1510 1511 1512
    }

    if (vm->qemuVersion == 0) {
        if (qemudExtractVersionInfo(vm->def->os.binary,
                                    &(vm->qemuVersion),
                                    &(vm->qemuCmdFlags)) < 0)
            return -1;
    }
1513

1514 1515
    uname(&ut);

D
Daniel P. Berrange 已提交
1516
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
1517 1518 1519 1520
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
1521
        ut.machine[1] = '6';
1522 1523 1524 1525 1526 1527

    /* Need to explicitly disable KQEMU if
     * 1. Arch matches host arch
     * 2. Guest is 'qemu'
     * 3. The qemu binary has the -no-kqemu flag
     */
1528
    if ((vm->qemuCmdFlags & QEMUD_CMD_FLAG_KQEMU) &&
1529 1530 1531 1532
        !strcmp(ut.machine, vm->def->os.arch) &&
        vm->def->virtType == QEMUD_VIRT_QEMU)
        disableKQEMU = 1;

1533
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
1534
        2 + /* machine type */
1535
        disableKQEMU + /* Disable kqemu */
1536 1537
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
1538 1539
        1 + /* usb */
        2 * vm->def->ninputs + /* input devices */
D
Daniel P. Berrange 已提交
1540 1541 1542 1543
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
1544
        (vm->def->localtime ? 1 : 0) + /* localtime */
1545
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1546
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
1547 1548 1549 1550 1551
        (vm->def->features & QEMUD_FEATURE_ACPI ? 0 : 1) + /* acpi */
        (vm->def->os.kernel[0] ? 2 : 0) + /* kernel */
        (vm->def->os.initrd[0] ? 2 : 0) + /* initrd */
        (vm->def->os.cmdline[0] ? 2 : 0) + /* cmdline */
        (vm->def->graphicsType == QEMUD_GRAPHICS_VNC ? 2 :
1552 1553
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)) + /* graphics */
        (vm->migrateFrom[0] ? 3 : 0); /* migrateFrom */
D
Daniel P. Berrange 已提交
1554

1555 1556
    snprintf(memory, sizeof(memory), "%d", vm->def->memory/1024);
    snprintf(vcpus, sizeof(vcpus), "%d", vm->def->vcpus);
D
Daniel P. Berrange 已提交
1557

1558
    if (!(*argv = malloc(sizeof(**argv) * (len+1))))
D
Daniel P. Berrange 已提交
1559
        goto no_memory;
1560
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
1561 1562 1563
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
1564
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
1565
        goto no_memory;
1566
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
1567
        if (!((*argv)[++n] = strdup("-no-kqemu")))
1568
            goto no_memory;
D
Daniel P. Berrange 已提交
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
    }
    if (!((*argv)[++n] = strdup("-m")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(memory)))
        goto no_memory;
    if (!((*argv)[++n] = strdup("-smp")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(vcpus)))
        goto no_memory;

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
    /*
     * NB, -nographic *MUST* come before any serial, or monitor
     * or parallel port flags due to QEMU craziness, where it
     * decides to change the serial port & monitor to be on stdout
     * if you ask for nographic. So we have to make sure we override
     * these defaults ourselves...
     */
    if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
        if (!((*argv)[++n] = strdup("-nographic")))
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
1591 1592 1593 1594 1595
    if (!((*argv)[++n] = strdup("-monitor")))
        goto no_memory;
    if (!((*argv)[++n] = strdup("pty")))
        goto no_memory;

1596 1597 1598 1599 1600
    if (vm->def->localtime) {
        if (!((*argv)[++n] = strdup("-localtime")))
            goto no_memory;
    }

1601
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1602 1603 1604 1605 1606
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

1607
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
1608 1609
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
1610 1611
    }

1612 1613
    for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
        switch (vm->def->os.bootDevs[i]) {
D
Daniel P. Berrange 已提交
1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
        case QEMUD_BOOT_CDROM:
            boot[i] = 'd';
            break;
        case QEMUD_BOOT_FLOPPY:
            boot[i] = 'a';
            break;
        case QEMUD_BOOT_DISK:
            boot[i] = 'c';
            break;
        case QEMUD_BOOT_NET:
            boot[i] = 'n';
            break;
        default:
            boot[i] = 'c';
            break;
        }
    }
1631
    boot[vm->def->os.nBootDevs] = '\0';
D
Daniel P. Berrange 已提交
1632 1633 1634 1635 1636
    if (!((*argv)[++n] = strdup("-boot")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(boot)))
        goto no_memory;

1637
    if (vm->def->os.kernel[0]) {
D
Daniel P. Berrange 已提交
1638 1639
        if (!((*argv)[++n] = strdup("-kernel")))
            goto no_memory;
1640
        if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
D
Daniel P. Berrange 已提交
1641 1642
            goto no_memory;
    }
1643
    if (vm->def->os.initrd[0]) {
D
Daniel P. Berrange 已提交
1644 1645
        if (!((*argv)[++n] = strdup("-initrd")))
            goto no_memory;
1646
        if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
D
Daniel P. Berrange 已提交
1647 1648
            goto no_memory;
    }
1649
    if (vm->def->os.cmdline[0]) {
D
Daniel P. Berrange 已提交
1650 1651
        if (!((*argv)[++n] = strdup("-append")))
            goto no_memory;
1652
        if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
D
Daniel P. Berrange 已提交
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
            goto no_memory;
    }

    while (disk) {
        char dev[NAME_MAX];
        char file[PATH_MAX];
        if (!strcmp(disk->dst, "hdc") &&
            disk->device == QEMUD_DISK_CDROM)
            snprintf(dev, NAME_MAX, "-%s", "cdrom");
        else
            snprintf(dev, NAME_MAX, "-%s", disk->dst);
        snprintf(file, PATH_MAX, "%s", disk->src);

        if (!((*argv)[++n] = strdup(dev)))
            goto no_memory;
        if (!((*argv)[++n] = strdup(file)))
            goto no_memory;

        disk = disk->next;
    }

    if (!net) {
        if (!((*argv)[++n] = strdup("-net")))
            goto no_memory;
        if (!((*argv)[++n] = strdup("none")))
            goto no_memory;
    } else {
1680
        int vlan = 0;
D
Daniel P. Berrange 已提交
1681
        while (net) {
1682
            char nic[100];
1683

1684 1685 1686 1687 1688 1689
            if (snprintf(nic, sizeof(nic), "nic,macaddr=%02x:%02x:%02x:%02x:%02x:%02x,vlan=%d",
                         net->mac[0], net->mac[1],
                         net->mac[2], net->mac[3],
                         net->mac[4], net->mac[5],
                         vlan) >= sizeof(nic))
                goto error;
D
Daniel P. Berrange 已提交
1690 1691 1692 1693 1694

            if (!((*argv)[++n] = strdup("-net")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(nic)))
                goto no_memory;
1695

D
Daniel P. Berrange 已提交
1696 1697
            if (!((*argv)[++n] = strdup("-net")))
                goto no_memory;
1698

1699 1700 1701
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
1702
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
1703
                    goto error;
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758
                break;

            case QEMUD_NET_ETHERNET:
                {
                    char arg[PATH_MAX];
                    if (snprintf(arg, PATH_MAX-1, "tap,ifname=%s,script=%s,vlan=%d",
                                 net->dst.ethernet.ifname,
                                 net->dst.ethernet.script,
                                 vlan) >= (PATH_MAX-1))
                        goto error;

                    if (!((*argv)[++n] = strdup(arg)))
                        goto no_memory;
                }
                break;

            case QEMUD_NET_CLIENT:
            case QEMUD_NET_SERVER:
            case QEMUD_NET_MCAST:
                {
                    char arg[PATH_MAX];
                    const char *mode = NULL;
                    switch (net->type) {
                    case QEMUD_NET_CLIENT:
                        mode = "connect";
                        break;
                    case QEMUD_NET_SERVER:
                        mode = "listen";
                        break;
                    case QEMUD_NET_MCAST:
                        mode = "mcast";
                        break;
                    }
                    if (snprintf(arg, PATH_MAX-1, "socket,%s=%s:%d,vlan=%d",
                                 mode,
                                 net->dst.socket.address,
                                 net->dst.socket.port,
                                 vlan) >= (PATH_MAX-1))
                        goto error;

                    if (!((*argv)[++n] = strdup(arg)))
                        goto no_memory;
                }
                break;

            case QEMUD_NET_USER:
            default:
                {
                    char arg[PATH_MAX];
                    if (snprintf(arg, PATH_MAX-1, "user,vlan=%d", vlan) >= (PATH_MAX-1))
                        goto error;

                    if (!((*argv)[++n] = strdup(arg)))
                        goto no_memory;
                }
1759
            }
D
Daniel P. Berrange 已提交
1760 1761

            net = net->next;
1762
            vlan++;
D
Daniel P. Berrange 已提交
1763 1764 1765
        }
    }

1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778
    if (!((*argv)[++n] = strdup("-usb")))
        goto no_memory;
    while (input) {
        if (input->bus == QEMU_INPUT_BUS_USB) {
            if (!((*argv)[++n] = strdup("-usbdevice")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet")))
                goto no_memory;
        }

        input = input->next;
    }

1779
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
1780
        char vncdisplay[PATH_MAX];
1781
        int ret;
D
Daniel P. Berrange 已提交
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796

        if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_VNC_COLON) {
            char options[PATH_MAX] = "";
            if (driver->vncTLS) {
                strcat(options, ",tls");
                if (driver->vncTLSx509verify) {
                    strcat(options, ",x509verify=");
                } else {
                    strcat(options, ",x509=");
                }
                strncat(options, driver->vncTLSx509certdir,
                        sizeof(options) - (strlen(driver->vncTLSx509certdir)-1));
                options[sizeof(options)-1] = '\0';
            }
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%s:%d%s",
1797
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
1798 1799 1800
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
1801 1802
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
1803
        }
1804
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
1805 1806
            goto error;

D
Daniel P. Berrange 已提交
1807 1808
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
1809
        if (!((*argv)[++n] = strdup(vncdisplay)))
D
Daniel P. Berrange 已提交
1810
            goto no_memory;
1811 1812 1813 1814 1815 1816
        if (vm->def->keymap) {
            if (!((*argv)[++n] = strdup("-k")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->keymap)))
                goto no_memory;
        }
1817
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
1818
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
1819 1820 1821 1822
    } else {
        /* SDL is the default. no args needed */
    }

1823 1824 1825 1826 1827 1828 1829 1830 1831
    if (vm->migrateFrom[0]) {
        if (!((*argv)[++n] = strdup("-S")))
            goto no_memory;
        if (!((*argv)[++n] = strdup("-incoming")))
            goto no_memory;
        if (!((*argv)[++n] = strdup(vm->migrateFrom)))
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
1832 1833 1834 1835 1836
    (*argv)[++n] = NULL;

    return 0;

 no_memory:
1837
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "argv");
1838 1839 1840 1841 1842 1843 1844 1845
 error:
    if (vm->tapfds) {
        for (i = 0; vm->tapfds[i] != -1; i++)
            close(vm->tapfds[i]);
        free(vm->tapfds);
        vm->tapfds = NULL;
        vm->ntapfds = 0;
    }
D
Daniel P. Berrange 已提交
1846 1847
    if (argv) {
        for (i = 0 ; i < n ; i++)
1848 1849
            free((*argv)[i]);
        free(*argv);
D
Daniel P. Berrange 已提交
1850 1851 1852 1853 1854 1855
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
1856 1857
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
1858 1859
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
1860 1861 1862 1863
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

1864
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
1865 1866 1867 1868 1869
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1870
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1871 1872
                         "cannot create config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1873 1874 1875 1876 1877
        goto cleanup;
    }

    towrite = strlen(xml);
    if (write(fd, xml, towrite) != towrite) {
1878
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1879 1880
                         "cannot write config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1881 1882 1883 1884
        goto cleanup;
    }

    if (close(fd) < 0) {
1885
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1886 1887
                         "cannot save config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901
        goto cleanup;
    }

    ret = 0;

 cleanup:
    if (fd != -1)
        close(fd);

    free(xml);

    return ret;
}

D
Daniel P. Berrange 已提交
1902 1903 1904 1905 1906 1907 1908
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
1909
    struct qemud_vm_device_def *dev = calloc(1, sizeof(*dev));
D
Daniel P. Berrange 已提交
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942

    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, "device.xml", NULL,
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
        return NULL;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, "missing root element");
        goto error;
    }
    if (xmlStrEqual(node->name, BAD_CAST "disk")) {
        dev->type = QEMUD_DEVICE_DISK;
        qemudParseDiskXML(conn, &(dev->data.disk), node);
    } else if (xmlStrEqual(node->name, BAD_CAST "net")) {
        dev->type = QEMUD_DEVICE_NET;
        qemudParseInterfaceXML(conn, &(dev->data.net), node);
    } else if (xmlStrEqual(node->name, BAD_CAST "input")) {
        dev->type = QEMUD_DEVICE_DISK;
        qemudParseInputXML(conn, &(dev->data.input), node);
    } else {
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, "unknown device type");
        goto error;
    }

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
1943
    free(dev);
D
Daniel P. Berrange 已提交
1944 1945 1946
    return NULL;
}

1947
struct qemud_vm_def *
1948 1949
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
1950 1951
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
1952
    xmlDocPtr xml;
1953
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
1954

1955
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
1956 1957
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
1958
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
1959 1960 1961
        return NULL;
    }

1962
    def = qemudParseXML(conn, driver, xml);
1963

D
Daniel P. Berrange 已提交
1964 1965
    xmlFreeDoc(xml);

1966 1967 1968 1969
    return def;
}

struct qemud_vm *
1970 1971
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
1972 1973 1974 1975
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

1976
    if ((vm = qemudFindVMByName(driver, def->name))) {
1977
        if (!qemudIsActiveVM(vm)) {
1978 1979 1980 1981 1982 1983 1984
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
1985 1986 1987
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
1988
        return vm;
D
Daniel P. Berrange 已提交
1989 1990
    }

1991
    if (!(vm = calloc(1, sizeof(*vm)))) {
1992
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "vm");
1993 1994
        return NULL;
    }
D
Daniel P. Berrange 已提交
1995

1996
    vm->stdin = -1;
1997 1998 1999 2000 2001
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
2002
    vm->state = VIR_DOMAIN_SHUTOFF;
2003
    vm->def = def;
2004
    vm->next = driver->vms;
2005

2006 2007
    driver->vms = vm;
    driver->ninactivevms++;
2008 2009 2010 2011 2012

    return vm;
}

void
2013
qemudRemoveInactiveVM(struct qemud_driver *driver,
2014 2015 2016 2017
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

2018
    curr = driver->vms;
2019 2020 2021
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
2022 2023
    }

2024 2025 2026 2027
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2028
            driver->vms = curr->next;
2029

2030
        driver->ninactivevms--;
2031 2032
    }

2033
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
2034 2035
}

2036
int
2037 2038
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
2039 2040 2041 2042 2043
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

2044
        if ((err = virFileMakePath(driver->configDir))) {
2045
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2046
                             "cannot create config directory %s: %s",
2047
                             driver->configDir, strerror(err));
2048 2049 2050
            return -1;
        }

2051 2052
        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             vm->configFile, PATH_MAX) < 0) {
2053
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2054 2055 2056
                             "cannot construct config file path");
            return -1;
        }
2057

2058 2059
        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             vm->autostartLink, PATH_MAX) < 0) {
2060
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2061 2062 2063 2064
                             "cannot construct autostart link path");
            vm->configFile[0] = '\0';
            return -1;
        }
2065 2066
    }

2067
    return qemudSaveConfig(conn, driver, vm, def);
2068
}
D
Daniel P. Berrange 已提交
2069

2070 2071
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
2072 2073
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
2074 2075 2076
    char *xml;
    int fd, ret = -1;
    int towrite;
2077
    int err;
2078

2079
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
2080 2081 2082
        return -1;
    }

2083
    if ((err = virFileMakePath(driver->networkConfigDir))) {
2084
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2085
                         "cannot create config directory %s: %s",
2086
                         driver->networkConfigDir, strerror(err));
2087 2088 2089 2090 2091 2092
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2093
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2094 2095
                         "cannot create config file %s: %s",
                         network->configFile, strerror(errno));
2096 2097 2098 2099 2100
        goto cleanup;
    }

    towrite = strlen(xml);
    if (write(fd, xml, towrite) != towrite) {
2101
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2102
                         "cannot write config file %s: %s",
2103
                         network->configFile, strerror(errno));
2104 2105 2106 2107
        goto cleanup;
    }

    if (close(fd) < 0) {
2108
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2109
                         "cannot save config file %s: %s",
2110
                         network->configFile, strerror(errno));
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138
void qemudFreeNetworkDef(struct qemud_network_def *def) {
    struct qemud_dhcp_range_def *range = def->ranges;
    while (range) {
        struct qemud_dhcp_range_def *next = range->next;
        free(range);
        range = next;
    }
    free(def);
}

void qemudFreeNetwork(struct qemud_network *network) {
    qemudFreeNetworkDef(network->def);
    if (network->newDef)
        qemudFreeNetworkDef(network->newDef);
    free(network);
}
2139

2140
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
2141
                               struct qemud_network_def *def,
2142 2143 2144 2145 2146
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
2147 2148
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
2149 2150 2151 2152 2153 2154 2155
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
2156
            def->disableSTP = 1;
2157 2158 2159 2160 2161 2162 2163
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
2164
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
2165 2166 2167 2168 2169 2170 2171
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

2172 2173
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
2174
                                   struct qemud_network_def *def,
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
                                   xmlNodePtr node) {

    xmlNodePtr cur;

    cur = node->children;
    while (cur != NULL) {
        struct qemud_dhcp_range_def *range;
        xmlChar *start, *end;

        if (cur->type != XML_ELEMENT_NODE ||
            !xmlStrEqual(cur->name, BAD_CAST "range")) {
            cur = cur->next;
            continue;
        }

2190
        if (!(range = calloc(1, sizeof(*range)))) {
2191
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "range");
2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
            return 0;
        }

        start = xmlGetProp(cur, BAD_CAST "start");
        end = xmlGetProp(cur, BAD_CAST "end");

        if (start && start[0] && end && end[0]) {
            strncpy(range->start, (const char *)start, BR_INET_ADDR_MAXLEN-1);
            range->start[BR_INET_ADDR_MAXLEN-1] = '\0';

            strncpy(range->end, (const char *)end, BR_INET_ADDR_MAXLEN-1);
            range->end[BR_INET_ADDR_MAXLEN-1] = '\0';

2205 2206 2207
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
        } else {
            free(range);
        }

        if (start)
            xmlFree(start);
        if (end)
            xmlFree(end);

        cur = cur->next;
    }

    return 1;
}
2222

2223 2224
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
2225
                             struct qemud_network_def *def,
2226 2227
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
2228
    xmlNodePtr cur;
2229 2230 2231

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
2232 2233
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
2234 2235 2236 2237 2238 2239
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
2240 2241
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
2242 2243 2244 2245
        xmlFree(netmask);
        netmask = NULL;
    }

2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
    if (def->ipAddress[0] && def->netmask[0]) {
        struct in_addr inaddress, innetmask;
        char *netaddr;

        inet_aton((const char*)def->ipAddress, &inaddress);
        inet_aton((const char*)def->netmask, &innetmask);

        inaddress.s_addr &= innetmask.s_addr;

        netaddr = inet_ntoa(inaddress);

        snprintf(def->network,sizeof(def->network)-1,
                 "%s/%s", netaddr, (const char *)def->netmask);
    }

2261 2262 2263 2264
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
2265
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
2266 2267 2268 2269
            return 0;
        cur = cur->next;
    }

2270 2271 2272 2273
    return 1;
}


2274 2275
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
2276
                                                      xmlDocPtr xml) {
2277 2278
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
2279
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
2280 2281
    struct qemud_network_def *def;

2282
    if (!(def = calloc(1, sizeof(*def)))) {
2283
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network_def");
2284 2285
        return NULL;
    }
2286 2287 2288 2289

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
2290
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
2291 2292 2293 2294 2295
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
2296
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
2297 2298 2299 2300 2301 2302 2303 2304
        goto error;
    }


    /* Extract network name */
    obj = xmlXPathEval(BAD_CAST "string(/network/name[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
2305
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
2306 2307 2308
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
2309
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "network name length too long");
2310 2311
        goto error;
    }
2312
    strcpy(def->name, (const char *)obj->stringval);
2313 2314 2315 2316 2317 2318 2319
    xmlXPathFreeObject(obj);


    /* Extract network uuid */
    obj = xmlXPathEval(BAD_CAST "string(/network/uuid[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
2320
        int err;
D
Daniel P. Berrange 已提交
2321
        if ((err = virUUIDGenerate(def->uuid))) {
2322
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2323 2324 2325
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
2326
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
2327
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
2328 2329 2330 2331
        goto error;
    }
    xmlXPathFreeObject(obj);

2332 2333 2334 2335
    /* Parse bridge information */
    obj = xmlXPathEval(BAD_CAST "/network/bridge[1]", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr > 0)) {
2336
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
2337 2338 2339 2340 2341 2342 2343 2344 2345
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* Parse IP information */
    obj = xmlXPathEval(BAD_CAST "/network/ip[1]", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr > 0)) {
2346
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
2347 2348 2349 2350 2351 2352
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
2353 2354 2355
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
2356 2357
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
2358
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2359 2360 2361 2362
                             "Forwarding requested, but no IPv4 address/netmask provided");
            goto error;
        }

2363 2364 2365 2366 2367 2368
        def->forward = 1;
        tmp = xmlXPathEval(BAD_CAST "string(/network/forward[1]/@dev)", ctxt);
        if ((tmp != NULL) && (tmp->type == XPATH_STRING) &&
            (tmp->stringval != NULL) && (tmp->stringval[0] != 0)) {
            int len;
            if ((len = xmlStrlen(tmp->stringval)) >= (BR_IFNAME_MAXLEN-1)) {
2369
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
                                 "forward device name '%s' is too long",
                                 (char*)tmp->stringval);
                goto error;
            }
            strcpy(def->forwardDev, (char*)tmp->stringval);
        } else {
            def->forwardDev[0] = '\0';
        }
        xmlXPathFreeObject(tmp);
        tmp = NULL;
    } else {
        def->forward = 0;
    }
    xmlXPathFreeObject(obj);

2385 2386
    xmlXPathFreeContext(ctxt);

2387
    return def;
2388 2389 2390 2391 2392 2393

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
    if (obj)
        xmlXPathFreeObject(obj);
2394 2395
    if (tmp)
        xmlXPathFreeObject(tmp);
2396
    xmlXPathFreeContext(ctxt);
2397 2398
    qemudFreeNetworkDef(def);
    return NULL;
2399 2400
}

2401
struct qemud_network_def *
2402 2403
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
2404 2405
                     const char *xmlStr,
                     const char *displayName) {
2406
    xmlDocPtr xml;
2407
    struct qemud_network_def *def;
2408

2409
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
2410 2411
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2412
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
2413 2414 2415
        return NULL;
    }

2416
    def = qemudParseNetworkXML(conn, driver, xml);
2417

2418 2419
    xmlFreeDoc(xml);

2420 2421 2422 2423
    return def;
}

struct qemud_network *
2424 2425
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
2426 2427 2428
                      struct qemud_network_def *def) {
    struct qemud_network *network;

2429
    if ((network = qemudFindNetworkByName(driver, def->name))) {
2430
        if (!qemudIsActiveNetwork(network)) {
2431 2432 2433 2434 2435 2436 2437 2438
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

2439
        return network;
2440 2441
    }

2442
    if (!(network = calloc(1, sizeof(*network)))) {
2443
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network");
2444 2445
        return NULL;
    }
2446

2447
    network->def = def;
2448
    network->next = driver->networks;
2449

2450 2451
    driver->networks = network;
    driver->ninactivenetworks++;
2452 2453 2454 2455 2456

    return network;
}

void
2457
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
2458 2459 2460 2461
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

2462
    curr = driver->networks;
2463 2464 2465
    while (curr != network) {
        prev = curr;
        curr = curr->next;
2466 2467
    }

2468 2469 2470 2471
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2472
            driver->networks = curr->next;
2473

2474
        driver->ninactivenetworks--;
2475 2476
    }

2477
    qemudFreeNetwork(network);
2478 2479
}

2480
int
2481 2482
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
2483 2484 2485 2486 2487 2488
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

    if (network->configFile[0] == '\0') {
        int err;

2489
        if ((err = virFileMakePath(driver->networkConfigDir))) {
2490
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2491
                             "cannot create config directory %s: %s",
2492
                             driver->networkConfigDir, strerror(err));
2493 2494 2495
            return -1;
        }

2496 2497
        if (virFileBuildPath(driver->networkConfigDir, def->name, ".xml",
                             network->configFile, PATH_MAX) < 0) {
2498
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2499 2500 2501
                             "cannot construct config file path");
            return -1;
        }
2502

2503 2504
        if (virFileBuildPath(driver->networkAutostartDir, def->name, ".xml",
                             network->autostartLink, PATH_MAX) < 0) {
2505
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2506 2507 2508 2509
                             "cannot construct autostart link path");
            network->configFile[0] = '\0';
            return -1;
        }
2510 2511
    }

2512
    return qemudSaveNetworkConfig(conn, driver, network, def);
2513
}
2514

2515

2516
static struct qemud_vm *
2517
qemudLoadConfig(struct qemud_driver *driver,
2518 2519
                const char *file,
                const char *path,
2520 2521
                const char *xml,
                const char *autostartLink) {
2522 2523 2524
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

2525
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
2526
        virErrorPtr err = virGetLastError();
2527
        qemudLog(QEMUD_WARN, "Error parsing QEMU guest config '%s' : %s",
2528 2529
                 path, err ? err->message :
		             "BUG: unknown error - please report it\n");
2530 2531 2532
        return NULL;
    }

2533
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
2534 2535 2536 2537 2538 2539
        qemudLog(QEMUD_WARN, "QEMU guest config filename '%s' does not match guest name '%s'",
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

2540
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
2541 2542 2543 2544 2545 2546 2547 2548
        qemudLog(QEMUD_WARN, "Failed to load QEMU guest config '%s': out of memory", path);
        qemudFreeVMDef(def);
        return NULL;
    }

    strncpy(vm->configFile, path, PATH_MAX);
    vm->configFile[PATH_MAX-1] = '\0';

2549 2550 2551
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

2552
    vm->autostart = virFileLinkPointsTo(vm->autostartLink, vm->configFile);
2553

2554 2555 2556 2557
    return vm;
}

static struct qemud_network *
2558
qemudLoadNetworkConfig(struct qemud_driver *driver,
2559 2560
                       const char *file,
                       const char *path,
2561 2562
                       const char *xml,
                       const char *autostartLink) {
2563 2564 2565
    struct qemud_network_def *def;
    struct qemud_network *network;

2566
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
2567
        virErrorPtr err = virGetLastError();
2568
        qemudLog(QEMUD_WARN, "Error parsing network config '%s' : %s",
2569
                 path, err->message);
2570 2571 2572
        return NULL;
    }

2573
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
2574 2575 2576 2577 2578 2579
        qemudLog(QEMUD_WARN, "Network config filename '%s' does not match network name '%s'",
                 path, def->name);
        qemudFreeNetworkDef(def);
        return NULL;
    }

2580
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
2581 2582 2583 2584 2585 2586 2587 2588
        qemudLog(QEMUD_WARN, "Failed to load network config '%s': out of memory", path);
        qemudFreeNetworkDef(def);
        return NULL;
    }

    strncpy(network->configFile, path, PATH_MAX);
    network->configFile[PATH_MAX-1] = '\0';

2589 2590 2591
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

2592
    network->autostart = virFileLinkPointsTo(network->autostartLink, network->configFile);
2593

2594 2595
    return network;
}
D
Daniel P. Berrange 已提交
2596

2597
static
2598
int qemudScanConfigDir(struct qemud_driver *driver,
2599
                       const char *configDir,
2600
                       const char *autostartDir,
2601
                       int isGuest) {
D
Daniel P. Berrange 已提交
2602 2603 2604
    DIR *dir;
    struct dirent *entry;

2605
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
2606 2607
        if (errno == ENOENT)
            return 0;
2608 2609
        qemudLog(QEMUD_ERR, "Failed to open dir '%s': %s",
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
2610 2611 2612 2613
        return -1;
    }

    while ((entry = readdir(dir))) {
2614
        char *xml;
2615
        char path[PATH_MAX];
2616
        char autostartLink[PATH_MAX];
2617

D
Daniel P. Berrange 已提交
2618 2619 2620
        if (entry->d_name[0] == '.')
            continue;

2621
        if (!virFileHasSuffix(entry->d_name, ".xml"))
2622 2623
            continue;

2624
        if (virFileBuildPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
2625 2626 2627 2628 2629
            qemudLog(QEMUD_WARN, "Config filename '%s/%s' is too long",
                     configDir, entry->d_name);
            continue;
        }

2630
        if (virFileBuildPath(autostartDir, entry->d_name, NULL, autostartLink, PATH_MAX) < 0) {
2631 2632 2633 2634 2635
            qemudLog(QEMUD_WARN, "Autostart link path '%s/%s' is too long",
                     autostartDir, entry->d_name);
            continue;
        }

2636
        if (virFileReadAll(path, QEMUD_MAX_XML_LEN, &xml) < 0)
D
Daniel P. Berrange 已提交
2637 2638
            continue;

2639
        if (isGuest)
2640
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
2641
        else
2642
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
2643 2644

        free(xml);
D
Daniel P. Berrange 已提交
2645 2646 2647
    }

    closedir(dir);
2648

D
Daniel P. Berrange 已提交
2649 2650 2651
    return 0;
}

2652
/* Scan for all guest and network config files */
2653 2654
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
2655
        return -1;
2656

2657
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
2658 2659 2660
        return -1;

    return 0;
2661
}
D
Daniel P. Berrange 已提交
2662 2663

/* Generate an XML document describing the guest's configuration */
2664 2665
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
2666 2667 2668
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
D
Daniel P. Berrange 已提交
2669
    virBufferPtr buf = 0;
D
Daniel P. Berrange 已提交
2670
    unsigned char *uuid;
2671
    char uuidstr[VIR_UUID_STRING_BUFLEN];
D
Daniel P. Berrange 已提交
2672 2673
    struct qemud_vm_disk_def *disk;
    struct qemud_vm_net_def *net;
2674
    struct qemud_vm_input_def *input;
D
Daniel P. Berrange 已提交
2675 2676 2677
    const char *type = NULL;
    int n;

D
Daniel P. Berrange 已提交
2678
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2679
    if (!buf)
2680 2681
        goto no_memory;

2682
    switch (def->virtType) {
D
Daniel P. Berrange 已提交
2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693
    case QEMUD_VIRT_QEMU:
        type = "qemu";
        break;
    case QEMUD_VIRT_KQEMU:
        type = "kqemu";
        break;
    case QEMUD_VIRT_KVM:
        type = "kvm";
        break;
    }
    if (!type) {
2694
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unexpected domain type %d", def->virtType);
D
Daniel P. Berrange 已提交
2695 2696 2697
        goto cleanup;
    }

2698
    if (qemudIsActiveVM(vm) && live) {
D
Daniel P. Berrange 已提交
2699
        if (virBufferVSprintf(buf, "<domain type='%s' id='%d'>\n", type, vm->id) < 0)
D
Daniel P. Berrange 已提交
2700 2701
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2702
        if (virBufferVSprintf(buf, "<domain type='%s'>\n", type) < 0)
D
Daniel P. Berrange 已提交
2703 2704 2705
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
2706
    if (virBufferVSprintf(buf, "  <name>%s</name>\n", def->name) < 0)
D
Daniel P. Berrange 已提交
2707 2708
        goto no_memory;

2709
    uuid = def->uuid;
2710 2711
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
D
Daniel P. Berrange 已提交
2712
        goto no_memory;
D
Daniel P. Berrange 已提交
2713
    if (virBufferVSprintf(buf, "  <memory>%d</memory>\n", def->maxmem) < 0)
D
Daniel P. Berrange 已提交
2714
        goto no_memory;
D
Daniel P. Berrange 已提交
2715
    if (virBufferVSprintf(buf, "  <currentMemory>%d</currentMemory>\n", def->memory) < 0)
D
Daniel P. Berrange 已提交
2716
        goto no_memory;
D
Daniel P. Berrange 已提交
2717
    if (virBufferVSprintf(buf, "  <vcpu>%d</vcpu>\n", def->vcpus) < 0)
D
Daniel P. Berrange 已提交
2718 2719
        goto no_memory;

2720
    if (virBufferAddLit(buf, "  <os>\n") < 0)
D
Daniel P. Berrange 已提交
2721 2722
        goto no_memory;

2723
    if (def->virtType == QEMUD_VIRT_QEMU) {
D
Daniel P. Berrange 已提交
2724
        if (virBufferVSprintf(buf, "    <type arch='%s' machine='%s'>%s</type>\n",
2725
                              def->os.arch, def->os.machine, def->os.type) < 0)
D
Daniel P. Berrange 已提交
2726 2727
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2728
        if (virBufferVSprintf(buf, "    <type>%s</type>\n", def->os.type) < 0)
D
Daniel P. Berrange 已提交
2729 2730 2731
            goto no_memory;
    }

2732
    if (def->os.kernel[0])
D
Daniel P. Berrange 已提交
2733
        if (virBufferVSprintf(buf, "    <kernel>%s</kernel>\n", def->os.kernel) < 0)
D
Daniel P. Berrange 已提交
2734
            goto no_memory;
2735
    if (def->os.initrd[0])
D
Daniel P. Berrange 已提交
2736
        if (virBufferVSprintf(buf, "    <initrd>%s</initrd>\n", def->os.initrd) < 0)
D
Daniel P. Berrange 已提交
2737
            goto no_memory;
2738
    if (def->os.cmdline[0])
D
Daniel P. Berrange 已提交
2739
        if (virBufferVSprintf(buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline) < 0)
D
Daniel P. Berrange 已提交
2740 2741
            goto no_memory;

2742
    for (n = 0 ; n < def->os.nBootDevs ; n++) {
D
Daniel P. Berrange 已提交
2743
        const char *boottype = "hd";
2744
        switch (def->os.bootDevs[n]) {
D
Daniel P. Berrange 已提交
2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
        case QEMUD_BOOT_FLOPPY:
            boottype = "fd";
            break;
        case QEMUD_BOOT_DISK:
            boottype = "hd";
            break;
        case QEMUD_BOOT_CDROM:
            boottype = "cdrom";
            break;
        case QEMUD_BOOT_NET:
2755
            boottype = "network";
D
Daniel P. Berrange 已提交
2756 2757
            break;
        }
D
Daniel P. Berrange 已提交
2758
        if (virBufferVSprintf(buf, "    <boot dev='%s'/>\n", boottype) < 0)
D
Daniel P. Berrange 已提交
2759 2760 2761
            goto no_memory;
    }

2762
    if (virBufferAddLit(buf, "  </os>\n") < 0)
D
Daniel P. Berrange 已提交
2763 2764
        goto no_memory;

2765
    if (def->features & QEMUD_FEATURE_ACPI) {
2766
        if (virBufferAddLit(buf, "  <features>\n") < 0)
2767
            goto no_memory;
2768
        if (virBufferAddLit(buf, "    <acpi/>\n") < 0)
2769
            goto no_memory;
2770
        if (virBufferAddLit(buf, "  </features>\n") < 0)
2771 2772 2773
            goto no_memory;
    }

2774 2775
    virBufferVSprintf(buf, "  <clock offset='%s'/>\n", def->localtime ? "localtime" : "utc");

2776
    if (virBufferAddLit(buf, "  <on_poweroff>destroy</on_poweroff>\n") < 0)
D
Daniel P. Berrange 已提交
2777 2778
        goto no_memory;
    if (def->noReboot) {
2779
        if (virBufferAddLit(buf, "  <on_reboot>destroy</on_reboot>\n") < 0)
D
Daniel P. Berrange 已提交
2780 2781
            goto no_memory;
    } else {
2782
        if (virBufferAddLit(buf, "  <on_reboot>restart</on_reboot>\n") < 0)
D
Daniel P. Berrange 已提交
2783 2784
            goto no_memory;
    }
2785
    if (virBufferAddLit(buf, "  <on_crash>destroy</on_crash>\n") < 0)
D
Daniel P. Berrange 已提交
2786
        goto no_memory;
2787

2788
    if (virBufferAddLit(buf, "  <devices>\n") < 0)
D
Daniel P. Berrange 已提交
2789 2790
        goto no_memory;

D
Daniel P. Berrange 已提交
2791
    if (virBufferVSprintf(buf, "    <emulator>%s</emulator>\n", def->os.binary) < 0)
D
Daniel P. Berrange 已提交
2792 2793
        goto no_memory;

2794
    disk = def->disks;
D
Daniel P. Berrange 已提交
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
D
Daniel P. Berrange 已提交
2809
        if (virBufferVSprintf(buf, "    <disk type='%s' device='%s'>\n",
D
Daniel P. Berrange 已提交
2810 2811 2812
                              types[disk->type], devices[disk->device]) < 0)
            goto no_memory;

D
Daniel P. Berrange 已提交
2813
        if (virBufferVSprintf(buf, "      <source %s='%s'/>\n", typeAttrs[disk->type], disk->src) < 0)
D
Daniel P. Berrange 已提交
2814 2815
            goto no_memory;

D
Daniel P. Berrange 已提交
2816
        if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", disk->dst) < 0)
D
Daniel P. Berrange 已提交
2817 2818 2819
            goto no_memory;

        if (disk->readonly)
2820
            if (virBufferAddLit(buf, "      <readonly/>\n") < 0)
D
Daniel P. Berrange 已提交
2821 2822
                goto no_memory;

D
Daniel P. Berrange 已提交
2823
        if (virBufferVSprintf(buf, "    </disk>\n") < 0)
D
Daniel P. Berrange 已提交
2824 2825 2826 2827 2828
            goto no_memory;

        disk = disk->next;
    }

2829
    net = def->nets;
2830
    while (net) {
D
Daniel P. Berrange 已提交
2831 2832
        const char *types[] = {
            "user",
2833
            "ethernet",
D
Daniel P. Berrange 已提交
2834 2835 2836
            "server",
            "client",
            "mcast",
2837
            "network",
2838
            "bridge",
D
Daniel P. Berrange 已提交
2839
        };
D
Daniel P. Berrange 已提交
2840
        if (virBufferVSprintf(buf, "    <interface type='%s'>\n",
D
Daniel P. Berrange 已提交
2841 2842 2843
                              types[net->type]) < 0)
            goto no_memory;

D
Daniel P. Berrange 已提交
2844
        if (virBufferVSprintf(buf, "      <mac address='%02x:%02x:%02x:%02x:%02x:%02x'/>\n",
D
Daniel P. Berrange 已提交
2845 2846 2847 2848
                              net->mac[0], net->mac[1], net->mac[2],
                              net->mac[3], net->mac[4], net->mac[5]) < 0)
            goto no_memory;

2849 2850
        switch (net->type) {
        case QEMUD_NET_NETWORK:
D
Daniel P. Berrange 已提交
2851
            if (virBufferVSprintf(buf, "      <source network='%s'/>\n", net->dst.network.name) < 0)
2852 2853
                goto no_memory;

2854
            if (net->dst.network.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2855
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.network.ifname) < 0)
2856 2857 2858
                    goto no_memory;
            }
            break;
2859

2860 2861
        case QEMUD_NET_ETHERNET:
            if (net->dst.ethernet.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2862
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname) < 0)
2863 2864 2865
                    goto no_memory;
            }
            if (net->dst.ethernet.script[0] != '\0') {
D
Daniel P. Berrange 已提交
2866
                if (virBufferVSprintf(buf, "      <script path='%s'/>\n", net->dst.ethernet.script) < 0)
2867 2868 2869 2870 2871
                    goto no_memory;
            }
            break;

        case QEMUD_NET_BRIDGE:
D
Daniel P. Berrange 已提交
2872
            if (virBufferVSprintf(buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname) < 0)
2873
                goto no_memory;
2874
            if (net->dst.bridge.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2875
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname) < 0)
2876 2877 2878 2879 2880 2881 2882 2883
                    goto no_memory;
            }
            break;

        case QEMUD_NET_SERVER:
        case QEMUD_NET_CLIENT:
        case QEMUD_NET_MCAST:
            if (net->dst.socket.address[0] != '\0') {
D
Daniel P. Berrange 已提交
2884
                if (virBufferVSprintf(buf, "      <source address='%s' port='%d'/>\n",
2885 2886 2887
                                      net->dst.socket.address, net->dst.socket.port) < 0)
                    goto no_memory;
            } else {
D
Daniel P. Berrange 已提交
2888
                if (virBufferVSprintf(buf, "      <source port='%d'/>\n",
2889 2890 2891
                                      net->dst.socket.port) < 0)
                    goto no_memory;
            }
2892 2893
        }

D
Daniel P. Berrange 已提交
2894
        if (virBufferVSprintf(buf, "    </interface>\n") < 0)
D
Daniel P. Berrange 已提交
2895 2896
            goto no_memory;

2897
        net = net->next;
D
Daniel P. Berrange 已提交
2898 2899
    }

2900 2901 2902 2903 2904 2905 2906 2907 2908 2909
    input = def->inputs;
    while (input) {
        if (input->bus != QEMU_INPUT_BUS_PS2 &&
            virBufferVSprintf(buf, "    <input type='%s' bus='usb'/>\n",
                              input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet") < 0)
            goto no_memory;
        input = input->next;
    }
    /* If graphics is enable, add implicit mouse */
    if (def->graphicsType != QEMUD_GRAPHICS_NONE)
2910
        if (virBufferAddLit(buf, "    <input type='mouse' bus='ps2'/>\n") < 0)
2911 2912
            goto no_memory;

2913 2914
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
2915
        if (virBufferAddLit(buf, "    <graphics type='vnc'") < 0)
2916 2917 2918
            goto no_memory;

        if (def->vncPort &&
D
Daniel P. Berrange 已提交
2919
            virBufferVSprintf(buf, " port='%d'",
2920
                              qemudIsActiveVM(vm) && live ? def->vncActivePort : def->vncPort) < 0)
2921 2922
            goto no_memory;

2923 2924 2925 2926 2927
        if (def->vncListen[0] &&
            virBufferVSprintf(buf, " listen='%s'",
                              def->vncListen) < 0)
            goto no_memory;

2928 2929 2930 2931 2932
        if (def->keymap &&
            virBufferVSprintf(buf, " keymap='%s'",
                              def->keymap) < 0)
            goto no_memory;

2933
        if (virBufferAddLit(buf, "/>\n") < 0)
2934 2935 2936 2937
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_SDL:
2938
        if (virBufferAddLit(buf, "    <graphics type='sdl'/>\n") < 0)
2939 2940 2941 2942 2943 2944 2945 2946
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

2947
    if (def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
2948 2949
    }

2950
    if (virBufferAddLit(buf, "  </devices>\n") < 0)
D
Daniel P. Berrange 已提交
2951 2952 2953
        goto no_memory;


2954
    if (virBufferAddLit(buf, "</domain>\n") < 0)
D
Daniel P. Berrange 已提交
2955 2956
        goto no_memory;

D
Daniel P. Berrange 已提交
2957
    return virBufferContentAndFree (buf);
D
Daniel P. Berrange 已提交
2958 2959

 no_memory:
2960
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
2961
 cleanup:
D
Daniel P. Berrange 已提交
2962
    if (buf) virBufferFree (buf);
D
Daniel P. Berrange 已提交
2963 2964 2965 2966
    return NULL;
}


2967 2968
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
2969
                              struct qemud_network *network,
2970
                              struct qemud_network_def *def) {
D
Daniel P. Berrange 已提交
2971
    virBufferPtr buf = 0;
2972
    unsigned char *uuid;
2973
    char uuidstr[VIR_UUID_STRING_BUFLEN];
2974

D
Daniel P. Berrange 已提交
2975
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2976
    if (!buf)
2977 2978
        goto no_memory;

D
Daniel P. Berrange 已提交
2979
    if (virBufferVSprintf(buf, "<network>\n") < 0)
2980 2981
        goto no_memory;

D
Daniel P. Berrange 已提交
2982
    if (virBufferVSprintf(buf, "  <name>%s</name>\n", def->name) < 0)
2983 2984
        goto no_memory;

2985
    uuid = def->uuid;
2986 2987
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
2988 2989
        goto no_memory;

2990 2991
    if (def->forward) {
        if (def->forwardDev[0]) {
D
Daniel P. Berrange 已提交
2992
            virBufferVSprintf(buf, "  <forward dev='%s'/>\n",
2993 2994
                              def->forwardDev);
        } else {
2995
            virBufferAddLit(buf, "  <forward/>\n");
2996 2997 2998
        }
    }

2999
    virBufferAddLit(buf, "  <bridge");
3000
    if (qemudIsActiveNetwork(network)) {
D
Daniel P. Berrange 已提交
3001
        if (virBufferVSprintf(buf, " name='%s'", network->bridge) < 0)
3002 3003
            goto no_memory;
    } else if (def->bridge[0]) {
D
Daniel P. Berrange 已提交
3004
        if (virBufferVSprintf(buf, " name='%s'", def->bridge) < 0)
3005 3006
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
3007
    if (virBufferVSprintf(buf, " stp='%s' forwardDelay='%d' />\n",
3008 3009
                       def->disableSTP ? "off" : "on",
                       def->forwardDelay) < 0)
3010 3011
        goto no_memory;

3012
    if (def->ipAddress[0] || def->netmask[0]) {
3013
        if (virBufferAddLit(buf, "  <ip") < 0)
3014 3015
            goto no_memory;

3016
        if (def->ipAddress[0] &&
D
Daniel P. Berrange 已提交
3017
            virBufferVSprintf(buf, " address='%s'", def->ipAddress) < 0)
3018 3019
            goto no_memory;

3020
        if (def->netmask[0] &&
D
Daniel P. Berrange 已提交
3021
            virBufferVSprintf(buf, " netmask='%s'", def->netmask) < 0)
3022 3023
            goto no_memory;

3024
        if (virBufferAddLit(buf, ">\n") < 0)
3025 3026
            goto no_memory;

3027 3028
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
3029
            if (virBufferAddLit(buf, "    <dhcp>\n") < 0)
3030 3031
                goto no_memory;
            while (range) {
D
Daniel P. Berrange 已提交
3032
                if (virBufferVSprintf(buf, "      <range start='%s' end='%s' />\n",
3033 3034 3035 3036
                                      range->start, range->end) < 0)
                    goto no_memory;
                range = range->next;
            }
3037
            if (virBufferAddLit(buf, "    </dhcp>\n") < 0)
3038 3039 3040
                goto no_memory;
        }

3041
        if (virBufferAddLit(buf, "  </ip>\n") < 0)
3042
            goto no_memory;
D
Daniel P. Berrange 已提交
3043 3044
    }

3045
    if (virBufferAddLit(buf, "</network>\n") < 0)
3046 3047
        goto no_memory;

D
Daniel P. Berrange 已提交
3048
    return virBufferContentAndFree (buf);
3049 3050

 no_memory:
3051
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
3052
    if (buf) virBufferFree (buf);
3053 3054 3055 3056
    return NULL;
}


3057 3058
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
3059 3060 3061
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
3062
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "no config file for %s", name);
D
Daniel P. Berrange 已提交
3063 3064 3065
        return -1;
    }

3066
    if (unlink(configFile) < 0) {
3067
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot remove config for %s", name);
3068 3069
        return -1;
    }
3070

D
Daniel P. Berrange 已提交
3071 3072 3073
    return 0;
}

3074
#endif /* WITH_QEMU */
D
Daniel P. Berrange 已提交
3075 3076 3077 3078 3079 3080 3081 3082 3083

/*
 * Local variables:
 *  indent-tabs-mode: nil
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  tab-width: 4
 * End:
 */