qemu_conf.c 138.6 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * config.c: VM configuration management
 *
4
 * Copyright (C) 2006, 2007, 2008 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * 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 46 47 48
#if HAVE_NUMACTL
#include <numa.h>
#endif

49
#include "internal.h"
50
#include "qemu_conf.h"
51
#include "uuid.h"
52
#include "buf.h"
D
Daniel P. Berrange 已提交
53
#include "conf.h"
54
#include "util.h"
55
#include "memory.h"
J
Jim Meyering 已提交
56 57
#include "verify.h"
#include "c-ctype.h"
58
#include "xml.h"
59

60 61
#define qemudLog(level, msg...) fprintf(stderr, msg)

62 63 64 65 66 67
void qemudReportError(virConnectPtr conn,
                      virDomainPtr dom,
                      virNetworkPtr net,
                      int code, const char *fmt, ...) {
    va_list args;
    char errorMessage[QEMUD_MAX_ERROR_LEN];
D
Daniel Veillard 已提交
68
    const char *virerr;
69 70 71 72 73 74 75 76

    if (fmt) {
        va_start(args, fmt);
        vsnprintf(errorMessage, QEMUD_MAX_ERROR_LEN-1, fmt, args);
        va_end(args);
    } else {
        errorMessage[0] = '\0';
    }
D
Daniel Veillard 已提交
77

78
    virerr = __virErrorMsg(code, (errorMessage[0] ? errorMessage : NULL));
79
    __virRaiseError(conn, dom, net, VIR_FROM_QEMU, code, VIR_ERR_ERROR,
D
Daniel Veillard 已提交
80
                    virerr, errorMessage, NULL, -1, -1, virerr, errorMessage);
81 82
}

D
Daniel P. Berrange 已提交
83 84 85 86 87 88 89 90 91
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,
92
                         "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
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
        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) {
124
        VIR_FREE(driver->vncTLSx509certdir);
D
Daniel P. Berrange 已提交
125 126
        if (!(driver->vncTLSx509certdir = strdup(p->str))) {
            qemudReportError(NULL, NULL, NULL, VIR_ERR_NO_MEMORY,
127
                             "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
            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;
}


145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
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) {
162
        if (!memcmp(vm->def->uuid, uuid, VIR_UUID_BUFLEN))
163 164 165 166 167 168 169 170 171 172 173 174
            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) {
175
        if (STREQ(vm->def->name, name))
176 177 178 179 180 181 182 183 184 185 186 187
            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) {
188
        if (!memcmp(network->def->uuid, uuid, VIR_UUID_BUFLEN))
189 190 191 192 193 194 195 196 197 198 199 200
            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) {
201
        if (STREQ(network->def->name, name))
202 203 204 205 206 207 208
            return network;
        network = network->next;
    }

    return NULL;
}

209

210 211 212 213
/* 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 已提交
214
    struct qemud_vm_input_def *input = def->inputs;
215 216
    struct qemud_vm_chr_def *serial = def->serials;
    struct qemud_vm_chr_def *parallel = def->parallels;
217
    struct qemud_vm_sound_def *sound = def->sounds;
218 219 220 221

    while (disk) {
        struct qemud_vm_disk_def *prev = disk;
        disk = disk->next;
222
        VIR_FREE(prev);
223 224 225 226
    }
    while (net) {
        struct qemud_vm_net_def *prev = net;
        net = net->next;
227
        VIR_FREE(prev);
228
    }
D
Daniel P. Berrange 已提交
229 230 231
    while (input) {
        struct qemud_vm_input_def *prev = input;
        input = input->next;
232
        VIR_FREE(prev);
D
Daniel P. Berrange 已提交
233
    }
234 235 236
    while (serial) {
        struct qemud_vm_chr_def *prev = serial;
        serial = serial->next;
237
        VIR_FREE(prev);
238 239 240 241
    }
    while (parallel) {
        struct qemud_vm_chr_def *prev = parallel;
        parallel = parallel->next;
242
        VIR_FREE(prev);
243
    }
244 245 246
    while (sound) {
        struct qemud_vm_sound_def *prev = sound;
        sound = sound->next;
247
        VIR_FREE(prev);
248
    }
249
    xmlFree(def->keymap);
250
    VIR_FREE(def);
251 252 253 254 255 256
}

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

260

D
Daniel P. Berrange 已提交
261 262
/* The list of possible machine types for various architectures,
   as supported by QEMU - taken from 'qemu -M ?' for each arch */
263 264
static const char *const arch_info_hvm_x86_machines[] = {
    "pc", "isapc"
D
Daniel P. Berrange 已提交
265
};
266 267
static const char *const arch_info_hvm_mips_machines[] = {
    "mips"
D
Daniel P. Berrange 已提交
268
};
269 270
static const char *const arch_info_hvm_sparc_machines[] = {
    "sun4m"
D
Daniel P. Berrange 已提交
271
};
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
static const char *const arch_info_hvm_ppc_machines[] = {
    "g3bw", "mac99", "prep"
};

static const char *const arch_info_xen_x86_machines[] = {
    "xenner"
};

struct qemu_feature_flags {
    const char *name;
    const int default_on;
    const int toggle;
};

struct qemu_arch_info {
    const char *arch;
    int wordsize;
    const char *const *machines;
    int nmachines;
    const char *binary;
    const struct qemu_feature_flags *flags;
    int nflags;
D
Daniel P. Berrange 已提交
294 295
};

296
/* Feature flags for the architecture info */
J
Jim Meyering 已提交
297
static const struct qemu_feature_flags const arch_info_i686_flags [] = {
298 299
    { "pae",  1, 0 },
    { "nonpae",  1, 0 },
300 301 302 303
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
};

J
Jim Meyering 已提交
304
static const struct qemu_feature_flags const arch_info_x86_64_flags [] = {
305 306 307 308
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
};

D
Daniel P. Berrange 已提交
309
/* The archicture tables for supported QEMU archs */
310 311 312 313 314 315 316 317 318 319 320 321 322
static const struct qemu_arch_info const arch_info_hvm[] = {
    {  "i686", 32, arch_info_hvm_x86_machines, 2,
       "/usr/bin/qemu", arch_info_i686_flags, 4 },
    {  "x86_64", 64, arch_info_hvm_x86_machines, 2,
       "/usr/bin/qemu-system-x86_64", arch_info_x86_64_flags, 2 },
    {  "mips", 32, arch_info_hvm_mips_machines, 1,
       "/usr/bin/qemu-system-mips", NULL, 0 },
    {  "mipsel", 32, arch_info_hvm_mips_machines, 1,
       "/usr/bin/qemu-system-mipsel", NULL, 0 },
    {  "sparc", 32, arch_info_hvm_sparc_machines, 1,
       "/usr/bin/qemu-system-sparc", NULL, 0 },
    {  "ppc", 32, arch_info_hvm_ppc_machines, 3,
       "/usr/bin/qemu-system-ppc", NULL, 0 },
D
Daniel P. Berrange 已提交
323 324
};

325 326 327 328 329 330
static const struct qemu_arch_info const arch_info_xen[] = {
    {  "i686", 32, arch_info_xen_x86_machines, 1,
       "/usr/bin/xenner", arch_info_i686_flags, 4 },
    {  "x86_64", 64, arch_info_xen_x86_machines, 1,
       "/usr/bin/xenner", arch_info_x86_64_flags, 2 },
};
D
Daniel P. Berrange 已提交
331

332 333 334 335 336 337
static int
qemudCapsInitGuest(virCapsPtr caps,
                   const char *hostmachine,
                   const struct qemu_arch_info *info,
                   int hvm) {
    virCapsGuestPtr guest;
D
Daniel P. Berrange 已提交
338 339
    int i;

340 341 342 343 344 345 346 347 348
    if ((guest = virCapabilitiesAddGuest(caps,
                                         hvm ? "hvm" : "xen",
                                         info->arch,
                                         info->wordsize,
                                         info->binary,
                                         NULL,
                                         info->nmachines,
                                         info->machines)) == NULL)
        return -1;
D
Daniel P. Berrange 已提交
349

350 351 352 353 354 355 356 357 358 359
    if (hvm) {
        /* Check for existance of base emulator */
        if (access(info->binary, X_OK) == 0 &&
            virCapabilitiesAddGuestDomain(guest,
                                          "qemu",
                                          NULL,
                                          NULL,
                                          0,
                                          NULL) == NULL)
            return -1;
D
Daniel P. Berrange 已提交
360

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        /* If guest & host match, then we can accelerate */
        if (STREQ(info->arch, hostmachine)) {
            if (access("/dev/kqemu", F_OK) == 0 &&
                virCapabilitiesAddGuestDomain(guest,
                                              "kqemu",
                                              NULL,
                                              NULL,
                                              0,
                                              NULL) == NULL)
                return -1;

            if (access("/dev/kvm", F_OK) == 0 &&
                virCapabilitiesAddGuestDomain(guest,
                                              "kvm",
                                              "/usr/bin/qemu-kvm",
                                              NULL,
                                              0,
                                              NULL) == NULL)
                return -1;
        }
    } else {
        if (virCapabilitiesAddGuestDomain(guest,
                                          "kvm",
                                          NULL,
                                          NULL,
                                          0,
                                          NULL) == NULL)
            return -1;
    }
D
Daniel P. Berrange 已提交
390

391 392 393 394 395 396 397
    if (info->nflags) {
        for (i = 0 ; i < info->nflags ; i++) {
            if (virCapabilitiesAddGuestFeature(guest,
                                               info->flags[i].name,
                                               info->flags[i].default_on,
                                               info->flags[i].toggle) == NULL)
                return -1;
D
Daniel P. Berrange 已提交
398 399 400
        }
    }

401
    return 0;
D
Daniel P. Berrange 已提交
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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
#if HAVE_NUMACTL
#define MAX_CPUS 4096
#define MAX_CPUS_MASK_SIZE (sizeof(unsigned long))
#define MAX_CPUS_MASK_LEN (MAX_CPUS / MAX_CPUS_MASK_SIZE)
#define MAX_CPUS_MASK_BYTES (MAX_CPUS / 8)

#define MASK_CPU_ISSET(mask, cpu) \
    (((mask)[((cpu) / MAX_CPUS_MASK_SIZE)] >> ((cpu) % MAX_CPUS_MASK_SIZE)) & 1)

static int
qemudCapsInitNUMA(virCapsPtr caps)
{
    int n, i;
    unsigned long *mask = NULL;
    int ncpus;
    int *cpus = NULL;
    int ret = -1;

    if (numa_available() < 0)
        return 0;

    if (VIR_ALLOC_N(mask, MAX_CPUS_MASK_LEN) < 0)
        goto cleanup;

    for (n = 0 ; n <= numa_max_node() ; n++) {
        if (numa_node_to_cpus(n, mask, MAX_CPUS_MASK_BYTES) < 0)
            goto cleanup;

        for (ncpus = 0, i = 0 ; i < MAX_CPUS ; i++)
            if (MASK_CPU_ISSET(mask, i))
                ncpus++;

        if (VIR_ALLOC_N(cpus, ncpus) < 0)
            goto cleanup;

        for (ncpus = 0, i = 0 ; i < MAX_CPUS ; i++)
            if (MASK_CPU_ISSET(mask, i))
                cpus[ncpus++] = i;

        if (virCapabilitiesAddHostNUMACell(caps,
                                           n,
                                           ncpus,
                                           cpus) < 0)
            goto cleanup;

        VIR_FREE(cpus);
    }

    ret = 0;

cleanup:
    VIR_FREE(cpus);
    VIR_FREE(mask);
    return ret;
}
#else
static int qemudCapsInitNUMA(virCapsPtr caps ATTRIBUTE_UNUSED) { return 0; }
#endif

463 464 465 466
virCapsPtr qemudCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    int i;
D
Daniel P. Berrange 已提交
467

468 469 470 471 472 473 474
    /* Really, this never fails - look at the man-page. */
    uname (&utsname);

    if ((caps = virCapabilitiesNew(utsname.machine,
                                   0, 0)) == NULL)
        goto no_memory;

475 476 477
    if (qemudCapsInitNUMA(caps) < 0)
        goto no_memory;

478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
    for (i = 0 ; i < (sizeof(arch_info_hvm)/sizeof(arch_info_hvm[0])) ; i++)
        if (qemudCapsInitGuest(caps,
                               utsname.machine,
                               &arch_info_hvm[i], 1) < 0)
            goto no_memory;

    if (access("/usr/bin/xenner", X_OK) == 0 &&
        access("/dev/kvm", F_OK) == 0) {
        for (i = 0 ; i < (sizeof(arch_info_xen)/sizeof(arch_info_xen[0])) ; i++)
            /* Allow Xen 32-on-32, 32-on-64 and 64-on-64 */
            if (STREQ(arch_info_xen[i].arch, utsname.machine) ||
                (STREQ(utsname.machine, "x86_64") &&
                 STREQ(arch_info_xen[i].arch, "i686"))) {
                if (qemudCapsInitGuest(caps,
                                       utsname.machine,
                                       &arch_info_xen[i], 0) < 0)
                    goto no_memory;
            }
D
Daniel P. Berrange 已提交
496 497
    }

498 499 500 501 502
    return caps;

 no_memory:
    virCapabilitiesFree(caps);
    return NULL;
D
Daniel P. Berrange 已提交
503 504
}

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523

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 */
524 525 526
        /* Just in case QEMU is translated someday we force to C locale.. */
        const char *const qemuenv[] = { "LANG=C", NULL };

527 528 529 530 531 532 533 534 535
        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;

536 537 538
        /* Passing -help, rather than relying on no-args which doesn't
           always work */
        execle(qemu, qemu, "-help", (char*)NULL, qemuenv);
539 540 541 542

    cleanup1:
        _exit(-1); /* Just in case */
    } else { /* Parent */
D
Daniel P. Berrange 已提交
543
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
544
        int got = 0, ret = -1;
545 546 547 548 549
        int major, minor, micro;

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

D
Daniel P. Berrange 已提交
550 551 552 553 554 555 556 557 558 559
        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;
560 561 562 563 564 565 566 567 568 569
        }
        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 已提交
570 571
        if (strstr(help, "-no-reboot"))
            *flags |= QEMUD_CMD_FLAG_NO_REBOOT;
572 573 574 575
        if (strstr(help, "-name"))
            *flags |= QEMUD_CMD_FLAG_NAME;
        if (strstr(help, "-drive"))
            *flags |= QEMUD_CMD_FLAG_DRIVE;
576
        if (strstr(help, "boot=on"))
577
            *flags |= QEMUD_CMD_FLAG_DRIVE_BOOT;
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
        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;
            }
594 595 596
            qemudLog(QEMUD_ERR,
                     _("Unexpected exit status from qemu %d pid %lu"),
                     got, (unsigned long)child);
597 598 599 600 601
            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 */
602
        if (WEXITSTATUS(got) != 0) {
603 604 605
            qemudLog(QEMUD_WARN,
                     _("Unexpected exit status '%d', qemu probably failed"),
                     got);
606 607 608 609 610 611
        }

        return ret;
    }
}

612
int qemudExtractVersion(virConnectPtr conn,
613 614
                        struct qemud_driver *driver) {
    const char *binary;
615
    struct stat sb;
616
    int ignored;
617

618
    if (driver->qemuVersion > 0)
619 620
        return 0;

621 622 623 624
    if ((binary = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                      "hvm",
                                                      "i686",
                                                      "qemu")) == NULL)
625 626
        return -1;

627
    if (stat(binary, &sb) < 0) {
628
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
629
                         _("Cannot find QEMU binary %s: %s"), binary,
630 631 632 633
                         strerror(errno));
        return -1;
    }

634
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &ignored) < 0) {
635 636 637 638 639 640
        return -1;
    }

    return 0;
}

641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
/* Converts def->virtType to applicable string type
 * @param type integer virt type
 * @return string type on success, NULL on fail
 */
const char * qemudVirtTypeToString(int type) {
    switch (type) {
        case QEMUD_VIRT_QEMU:
            return "qemu";
        case QEMUD_VIRT_KQEMU:
            return "kqemu";
        case QEMUD_VIRT_KVM:
            return "kvm";
    }
    return NULL;
}
656

D
Daniel P. Berrange 已提交
657 658 659 660 661 662 663 664
/* 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 已提交
665 666 667 668 669
    xmlNodePtr cur;
    xmlChar *device = NULL;
    xmlChar *source = NULL;
    xmlChar *target = NULL;
    xmlChar *type = NULL;
670
    xmlChar *bus = NULL;
D
Daniel P. Berrange 已提交
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
    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");
687

D
Daniel P. Berrange 已提交
688 689 690 691 692
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
693

D
Daniel P. Berrange 已提交
694 695 696 697 698 699 700
                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");
701
                bus = xmlGetProp(cur, BAD_CAST "bus");
D
Daniel P. Berrange 已提交
702 703 704 705 706 707 708 709
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                disk->readonly = 1;
            }
        }
        cur = cur->next;
    }

    if (source == NULL) {
710 711 712 713 714 715 716 717
        /* There is a case without the source
         * to the CD-ROM device
         */
        if (!device || STRNEQ((const char *) device, "cdrom")) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SOURCE,
                             target ? "%s" : NULL, target);
            goto error;
        }
D
Daniel P. Berrange 已提交
718
    }
719

D
Daniel P. Berrange 已提交
720
    if (target == NULL) {
721
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
722 723 724 725
        goto error;
    }

    if (device &&
726 727 728
        STREQ((const char *)device, "floppy") &&
        STRNEQ((const char *)target, "fda") &&
        STRNEQ((const char *)target, "fdb")) {
729 730
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid floppy device name: %s"), target);
D
Daniel P. Berrange 已提交
731 732
        goto error;
    }
733

D
Daniel P. Berrange 已提交
734
    if (device &&
735 736
        STREQ((const char *)device, "cdrom") &&
        STRNEQ((const char *)target, "hdc")) {
737 738
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid cdrom device name: %s"), target);
D
Daniel P. Berrange 已提交
739 740 741 742
        goto error;
    }

    if (device &&
743
        STREQ((const char *)device, "cdrom"))
D
Daniel P. Berrange 已提交
744 745
        disk->readonly = 1;

746 747 748
    if ((!device || STREQ((const char *)device, "disk")) &&
        !STRPREFIX((const char *)target, "hd") &&
        !STRPREFIX((const char *)target, "sd") &&
749 750
        !STRPREFIX((const char *)target, "vd") &&
        !STRPREFIX((const char *)target, "xvd")) {
751 752
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid harddisk device name: %s"), target);
D
Daniel P. Berrange 已提交
753 754 755
        goto error;
    }

756
    strncpy(disk->src, (source ? (const char *) source : "\0"), NAME_MAX-1);
D
Daniel P. Berrange 已提交
757 758 759 760 761 762 763 764
    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;
765
    else if (STREQ((const char *)device, "disk"))
D
Daniel P. Berrange 已提交
766
        disk->device = QEMUD_DISK_DISK;
767
    else if (STREQ((const char *)device, "cdrom"))
D
Daniel P. Berrange 已提交
768
        disk->device = QEMUD_DISK_CDROM;
769
    else if (STREQ((const char *)device, "floppy"))
D
Daniel P. Berrange 已提交
770 771
        disk->device = QEMUD_DISK_FLOPPY;
    else {
772 773
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid device type: %s"), device);
D
Daniel P. Berrange 已提交
774 775 776
        goto error;
    }

777
    if (!bus) {
778
        if (disk->device == QEMUD_DISK_FLOPPY) {
779
            disk->bus = QEMUD_DISK_BUS_FDC;
780 781 782 783 784 785 786 787 788 789 790 791
        } else {
            if (STRPREFIX((const char *)target, "hd"))
                disk->bus = QEMUD_DISK_BUS_IDE;
            else if (STRPREFIX((const char *)target, "sd"))
                disk->bus = QEMUD_DISK_BUS_SCSI;
            else if (STRPREFIX((const char *)target, "vd"))
                disk->bus = QEMUD_DISK_BUS_VIRTIO;
            else if (STRPREFIX((const char *)target, "xvd"))
                disk->bus = QEMUD_DISK_BUS_XEN;
            else
                disk->bus = QEMUD_DISK_BUS_IDE;
        }
792 793 794 795 796 797 798 799
    } else if (STREQ((const char *)bus, "ide"))
        disk->bus = QEMUD_DISK_BUS_IDE;
    else if (STREQ((const char *)bus, "fdc"))
        disk->bus = QEMUD_DISK_BUS_FDC;
    else if (STREQ((const char *)bus, "scsi"))
        disk->bus = QEMUD_DISK_BUS_SCSI;
    else if (STREQ((const char *)bus, "virtio"))
        disk->bus = QEMUD_DISK_BUS_VIRTIO;
800 801
    else if (STREQ((const char *)bus, "xen"))
        disk->bus = QEMUD_DISK_BUS_XEN;
802 803 804 805 806 807 808 809 810 811 812 813 814
    else {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid bus type: %s"), bus);
        goto error;
    }

    if (disk->device == QEMUD_DISK_FLOPPY &&
        disk->bus != QEMUD_DISK_BUS_FDC) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid bus type '%s' for floppy disk"), bus);
        goto error;
    }

D
Daniel P. Berrange 已提交
815 816 817
    xmlFree(device);
    xmlFree(target);
    xmlFree(source);
818
    xmlFree(bus);
D
Daniel P. Berrange 已提交
819

D
Daniel P. Berrange 已提交
820
    return 0;
D
Daniel P. Berrange 已提交
821 822

 error:
823
    xmlFree(bus);
824 825 826 827
    xmlFree(type);
    xmlFree(target);
    xmlFree(source);
    xmlFree(device);
D
Daniel P. Berrange 已提交
828
    return -1;
D
Daniel P. Berrange 已提交
829 830
}

831 832 833 834 835 836 837 838 839
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 已提交
840

D
Daniel P. Berrange 已提交
841 842 843 844 845 846 847 848
/* 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 已提交
849 850 851
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
852
    xmlChar *network = NULL;
853 854 855 856 857
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
858
    xmlChar *model = NULL;
D
Daniel P. Berrange 已提交
859 860 861 862 863 864 865

    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;
866 867
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
868 869 870 871 872 873
        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;
874 875
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
876 877
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
878 879 880 881 882 883 884 885 886 887 888 889
        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");
890 891 892 893
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
894 895 896
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
897
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
898 899 900 901 902 903 904 905 906 907 908 909 910
            } 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");
911
                if (STRPREFIX((const char*)ifname, "vnet")) {
912 913 914 915
                    /* An auto-generated target name, blank it out */
                    xmlFree(ifname);
                    ifname = NULL;
                }
916 917 918 919
            } else if ((script == NULL) &&
                       (net->type == QEMUD_NET_ETHERNET) &&
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = xmlGetProp(cur, BAD_CAST "path");
920 921
            } else if (xmlStrEqual (cur->name, BAD_CAST "model")) {
                model = xmlGetProp (cur, BAD_CAST "type");
D
Daniel P. Berrange 已提交
922 923 924 925 926 927
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
928
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
929
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
930 931 932 933 934 935 936 937 938 939 940 941
               (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 已提交
942 943

        xmlFree(macaddr);
944 945 946
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
947 948
    }

949 950 951 952
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
953
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
954
                             "%s", _("No <source> 'network' attribute specified with <interface type='network'/>"));
955
            goto error;
956
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
957
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
958
                             _("Network name '%s' too long"), network);
959 960 961 962 963 964
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

965
        if (network) {
966
            xmlFree(network);
967 968 969 970 971
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
972
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
973 974
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
975 976 977 978 979 980 981 982 983 984
                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;
985

986 987
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
988
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
989
                                 _("TAP script path '%s' is too long"), script);
990 991 992 993 994 995 996 997 998 999
                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)) {
1000
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1001 1002
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
1003 1004
                goto error;
            } else {
1005 1006
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
1007
            }
1008 1009 1010 1011 1012 1013
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
1014
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1015
                             "%s", _("No <source> 'dev' attribute specified with <interface type='bridge'/>"));
1016 1017
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
1018
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1019
                             _("TAP bridge path '%s' is too long"), bridge);
1020 1021 1022 1023
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
1024
        }
1025 1026 1027 1028 1029 1030

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
1031
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1032
                                 _("TAP interface name '%s' is too long"), ifname);
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
                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) {
1043
        int len = 0;
1044 1045 1046
        char *ret;

        if (port == NULL) {
1047
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1048
                             "%s", _("No <source> 'port' attribute specified with socket interface"));
1049 1050 1051 1052
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
1053
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1054
                             "%s", _("Cannot parse <source> 'port' attribute with socket interface"));
1055 1056 1057 1058 1059 1060 1061 1062
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
1063
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1064
                                 "%s", _("No <source> 'address' attribute specified with socket interface"));
1065 1066 1067
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
1068
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1069
                             _("IP address '%s' is too long"), address);
1070 1071 1072 1073 1074 1075 1076 1077 1078
            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);
1079 1080
    }

1081 1082 1083 1084 1085 1086
    /* NIC model (see -net nic,model=?).  We only check that it looks
     * reasonable, not that it is a supported NIC type.  FWIW kvm
     * supports these types as of April 2008:
     * i82551 i82557b i82559er ne2k_pci pcnet rtl8139 e1000 virtio
     */
    if (model != NULL) {
J
Jim Meyering 已提交
1087
        int i, len;
1088 1089 1090 1091 1092 1093 1094 1095

        len = xmlStrlen (model);
        if (len >= QEMUD_MODEL_MAX_LEN) {
            qemudReportError (conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                              _("Model name '%s' is too long"), model);
            goto error;
        }
        for (i = 0; i < len; ++i) {
J
Jim Meyering 已提交
1096
            int char_ok = c_isalnum(model[i]) || model[i] == '_';
1097
            if (!char_ok) {
1098
                qemudReportError (conn, NULL, NULL, VIR_ERR_INVALID_ARG, "%s",
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                                  _("Model name contains invalid characters"));
                goto error;
            }
        }
        strncpy (net->model, (const char*) model, len);
        net->model[len] = '\0';

        xmlFree (model);
        model = NULL;
    } else
        net->model[0] = '\0';

D
Daniel P. Berrange 已提交
1111
    return 0;
1112 1113

 error:
1114 1115 1116 1117 1118 1119
    xmlFree(network);
    xmlFree(address);
    xmlFree(port);
    xmlFree(ifname);
    xmlFree(script);
    xmlFree(bridge);
1120
    xmlFree(model);
D
Daniel P. Berrange 已提交
1121
    return -1;
D
Daniel P. Berrange 已提交
1122 1123 1124
}


1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
/* Parse the XML definition for a character device
 * @param net pre-allocated & zero'd net record
 * @param node XML nodeset to parse for net definition
 * @return 0 on success, -1 on failure
 *
 * The XML we're dealing with looks like
 *
 * <serial type="pty">
 *   <source path="/dev/pts/3"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="dev">
 *   <source path="/dev/ttyS0"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="tcp">
 *   <source mode="connect" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="tcp">
 *   <source mode="bind" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="udp">
 *   <source mode="bind" host="0.0.0.0" service="2445"/>
 *   <source mode="connect" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="unix">
 *   <source mode="bind" path="/tmp/foo"/>
 *   <target port="1"/>
 * </serial>
 *
 */
static int qemudParseCharXML(virConnectPtr conn,
                             struct qemud_vm_chr_def *chr,
                             int portNum,
                             xmlNodePtr node) {
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *bindHost = NULL;
    xmlChar *bindService = NULL;
    xmlChar *connectHost = NULL;
    xmlChar *connectService = NULL;
    xmlChar *path = NULL;
    xmlChar *mode = NULL;
    xmlChar *protocol = NULL;
    int ret = -1;

    chr->srcType = QEMUD_CHR_SRC_TYPE_PTY;
    type = xmlGetProp(node, BAD_CAST "type");
    if (type != NULL) {
        if (xmlStrEqual(type, BAD_CAST "null"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_NULL;
        else if (xmlStrEqual(type, BAD_CAST "vc"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_VC;
        else if (xmlStrEqual(type, BAD_CAST "pty"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_PTY;
        else if (xmlStrEqual(type, BAD_CAST "dev"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_DEV;
        else if (xmlStrEqual(type, BAD_CAST "file"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_FILE;
        else if (xmlStrEqual(type, BAD_CAST "pipe"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_PIPE;
        else if (xmlStrEqual(type, BAD_CAST "stdio"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_STDIO;
        else if (xmlStrEqual(type, BAD_CAST "udp"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_UDP;
        else if (xmlStrEqual(type, BAD_CAST "tcp"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_TCP;
        else if (xmlStrEqual(type, BAD_CAST "unix"))
            chr->srcType = QEMUD_CHR_SRC_TYPE_UNIX;
        else
            chr->srcType = QEMUD_CHR_SRC_TYPE_NULL;
    }

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

                switch (chr->srcType) {
                case QEMUD_CHR_SRC_TYPE_PTY:
                case QEMUD_CHR_SRC_TYPE_DEV:
                case QEMUD_CHR_SRC_TYPE_FILE:
                case QEMUD_CHR_SRC_TYPE_PIPE:
                case QEMUD_CHR_SRC_TYPE_UNIX:
                    if (path == NULL)
                        path = xmlGetProp(cur, BAD_CAST "path");

                    break;

                case QEMUD_CHR_SRC_TYPE_UDP:
                case QEMUD_CHR_SRC_TYPE_TCP:
                    if (mode == NULL ||
                        STREQ((const char *)mode, "connect")) {

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

                    if (chr->srcType == QEMUD_CHR_SRC_TYPE_UDP) {
                        xmlFree(mode);
                        mode = NULL;
                    }
                }
            } else if (xmlStrEqual(cur->name, BAD_CAST "protocol")) {
                if (protocol == NULL)
                    protocol = xmlGetProp(cur, BAD_CAST "type");
            }
        }
        cur = cur->next;
    }


    chr->dstPort = portNum;

    switch (chr->srcType) {
    case QEMUD_CHR_SRC_TYPE_NULL:
        /* Nada */
        break;

    case QEMUD_CHR_SRC_TYPE_VC:
        break;

    case QEMUD_CHR_SRC_TYPE_PTY:
        /* @path attribute is an output only property - pty is auto-allocted */
        break;

    case QEMUD_CHR_SRC_TYPE_DEV:
    case QEMUD_CHR_SRC_TYPE_FILE:
    case QEMUD_CHR_SRC_TYPE_PIPE:
        if (path == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Missing source path attribute for char device"));
            goto cleanup;
        }

        strncpy(chr->srcData.file.path, (const char *)path,
                sizeof(chr->srcData.file.path));
        NUL_TERMINATE(chr->srcData.file.path);
        break;

    case QEMUD_CHR_SRC_TYPE_STDIO:
        /* Nada */
        break;

    case QEMUD_CHR_SRC_TYPE_TCP:
        if (mode == NULL ||
            STREQ((const char *)mode, "connect")) {
            if (connectHost == NULL) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("Missing source host attribute for char device"));
                goto cleanup;
            }
            if (connectService == NULL) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("Missing source service attribute for char device"));
                goto cleanup;
            }

            strncpy(chr->srcData.tcp.host, (const char *)connectHost,
                    sizeof(chr->srcData.tcp.host));
            NUL_TERMINATE(chr->srcData.tcp.host);
            strncpy(chr->srcData.tcp.service, (const char *)connectService,
                    sizeof(chr->srcData.tcp.service));
            NUL_TERMINATE(chr->srcData.tcp.service);

            chr->srcData.tcp.listen = 0;
        } else {
            if (bindHost == NULL) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("Missing source host attribute for char device"));
                goto cleanup;
            }
            if (bindService == NULL) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("Missing source service attribute for char device"));
                goto cleanup;
            }

            strncpy(chr->srcData.tcp.host, (const char *)bindHost,
                    sizeof(chr->srcData.tcp.host));
            NUL_TERMINATE(chr->srcData.tcp.host);
            strncpy(chr->srcData.tcp.service, (const char *)bindService,
                    sizeof(chr->srcData.tcp.service));
            NUL_TERMINATE(chr->srcData.tcp.service);

            chr->srcData.tcp.listen = 1;
        }
        if (protocol != NULL &&
            STREQ((const char *)protocol, "telnet"))
            chr->srcData.tcp.protocol = QEMUD_CHR_SRC_TCP_PROTOCOL_TELNET;
        else
            chr->srcData.tcp.protocol = QEMUD_CHR_SRC_TCP_PROTOCOL_RAW;
        break;

    case QEMUD_CHR_SRC_TYPE_UDP:
        if (connectService == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Missing source service attribute for char device"));
            goto cleanup;
        }

        if (connectHost != NULL) {
            strncpy(chr->srcData.udp.connectHost, (const char *)connectHost,
                    sizeof(chr->srcData.udp.connectHost));
            NUL_TERMINATE(chr->srcData.udp.connectHost);
        }
        strncpy(chr->srcData.udp.connectService, (const char *)connectService,
                sizeof(chr->srcData.udp.connectService));
        NUL_TERMINATE(chr->srcData.udp.connectService);

        if (bindHost != NULL) {
            strncpy(chr->srcData.udp.bindHost, (const char *)bindHost,
                    sizeof(chr->srcData.udp.bindHost));
            NUL_TERMINATE(chr->srcData.udp.bindHost);
        }
        if (bindService != NULL) {
            strncpy(chr->srcData.udp.bindService, (const char *)bindService,
                    sizeof(chr->srcData.udp.bindService));
            NUL_TERMINATE(chr->srcData.udp.bindService);
        }
        break;

    case QEMUD_CHR_SRC_TYPE_UNIX:
        if (path == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Missing source path attribute for char device"));
            goto cleanup;
        }

        if (mode != NULL &&
            STRNEQ((const char *)mode, "connect"))
            chr->srcData.nix.listen = 1;
        else
            chr->srcData.nix.listen = 0;

        strncpy(chr->srcData.nix.path, (const char *)path,
                sizeof(chr->srcData.nix.path));
        NUL_TERMINATE(chr->srcData.nix.path);
        break;
    }

    ret = 0;

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

    return ret;
}


static int qemudParseCharXMLDevices(virConnectPtr conn,
                                    xmlXPathContextPtr ctxt,
                                    const char *xpath,
                                    unsigned int *ndevs,
                                    struct qemud_vm_chr_def **devs)
{
    xmlXPathObjectPtr obj;
    int i, ret = -1;

    obj = xmlXPathEval(BAD_CAST xpath, ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        struct qemud_vm_chr_def *prev = *devs;
        if (ndevs == NULL &&
            obj->nodesetval->nodeNr > 1) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("too many character devices"));
            goto cleanup;
        }

        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1420 1421
            struct qemud_vm_chr_def *chr;
            if (VIR_ALLOC(chr) < 0) {
1422 1423 1424 1425 1426 1427 1428
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                                 "%s",
                                 _("failed to allocate space for char device"));
                goto cleanup;
            }

            if (qemudParseCharXML(conn, chr, i, obj->nodesetval->nodeTab[i]) < 0) {
1429
                VIR_FREE(chr);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
                goto cleanup;
            }
            if (ndevs)
                (*ndevs)++;
            chr->next = NULL;
            if (i == 0) {
                *devs = chr;
            } else {
                prev->next = chr;
            }
            prev = chr;
        }
    }

    ret = 0;

cleanup:
    xmlXPathFreeObject(obj);
    return ret;
}


1452
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
1453
static int qemudParseInputXML(virConnectPtr conn,
1454
                              const struct qemud_vm_def *vm,
D
Daniel P. Berrange 已提交
1455 1456
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
1457 1458 1459 1460 1461 1462 1463
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

    if (!type) {
1464 1465
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing input device type"));
1466 1467 1468
        goto error;
    }

1469
    if (STREQ((const char *)type, "mouse")) {
1470
        input->type = QEMU_INPUT_TYPE_MOUSE;
1471
    } else if (STREQ((const char *)type, "tablet")) {
1472 1473
        input->type = QEMU_INPUT_TYPE_TABLET;
    } else {
1474 1475 1476
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unsupported input device type %s"),
                         (const char*)type);
1477 1478 1479 1480
        goto error;
    }

    if (bus) {
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
        if (STREQ(vm->os.type, "hvm")) {
            if (STREQ((const char*)bus, "ps2")) { /* Only allow mouse */
                if (input->type != QEMU_INPUT_TYPE_MOUSE) {
                    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 (STREQ((const char *)bus, "usb")) { /* Allow mouse & tablet */
                input->bus = QEMU_INPUT_BUS_USB;
            } else {
1493
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1494
                                 _("unsupported input bus %s"), (const char*)bus);
1495 1496 1497
                goto error;
            }
        } else {
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
            if (STREQ((const char *)bus, "xen")) { /* Allow mouse only */
                input->bus = QEMU_INPUT_BUS_XEN;
                if (input->type != QEMU_INPUT_TYPE_MOUSE) {
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                     _("xen bus does not support %s input device"),
                                     (const char*)type);
                    goto error;
                }
            } else {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("unsupported input bus %s"), (const char*)bus);
                goto error;
            }
1511 1512
        }
    } else {
D
Daniel P. Berrange 已提交
1513
        if (STREQ(vm->os.type, "hvm")) {
1514 1515 1516 1517 1518 1519 1520
            if (input->type == QEMU_INPUT_TYPE_MOUSE)
                input->bus = QEMU_INPUT_BUS_PS2;
            else
                input->bus = QEMU_INPUT_BUS_USB;
        } else {
            input->bus = QEMU_INPUT_BUS_XEN;
        }
1521 1522
    }

1523 1524
    xmlFree(type);
    xmlFree(bus);
1525

D
Daniel P. Berrange 已提交
1526
    return 0;
1527 1528

 error:
1529 1530
    xmlFree(type);
    xmlFree(bus);
1531

D
Daniel P. Berrange 已提交
1532
    return -1;
1533 1534
}

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
static int qemudDiskCompare(const void *aptr, const void *bptr) {
    struct qemud_vm_disk_def *a = (struct qemud_vm_disk_def *) aptr;
    struct qemud_vm_disk_def *b = (struct qemud_vm_disk_def *) bptr;
    if (a->bus == b->bus)
        return virDiskNameToIndex(a->dst) - virDiskNameToIndex(b->dst);
    else
        return a->bus - b->bus;
}

static const char *qemudBusIdToName(int busId, int qemuIF) {
    const char *busnames[] = { "ide",
                               (qemuIF ? "floppy" : "fdc"),
                               "scsi",
1548 1549
                               "virtio",
                               "xen"};
1550 1551 1552 1553 1554
    verify_true(ARRAY_CARDINALITY(busnames) == QEMUD_DISK_BUS_LAST);

    return busnames[busId];
}

D
Daniel Veillard 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
/* Sound device helper functions */
static int qemudSoundModelFromString(const char *model) {
    if (STREQ(model, "sb16")) {
        return QEMU_SOUND_SB16;
    } else if (STREQ(model, "es1370")) {
        return QEMU_SOUND_ES1370;
    } else if (STREQ(model, "pcspk")) {
        return QEMU_SOUND_PCSPK;
    }

    return -1;
}

static const char *qemudSoundModelToString(const int model) {

    if (model == QEMU_SOUND_SB16) {
        return "sb16";
    } else if (model == QEMU_SOUND_ES1370) {
        return "es1370";
    } else if (model == QEMU_SOUND_PCSPK) {
        return "pcspk";
    }

    return NULL;
}


static int qemudParseSoundXML(virConnectPtr conn,
                              struct qemud_vm_sound_def *sound,
                              const xmlNodePtr node) {

    int err = -1;
    xmlChar *model = NULL;
    model = xmlGetProp(node, BAD_CAST "model");

    if (!model) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing sound model"));
        goto error;
    }
    if ((sound->model = qemudSoundModelFromString((char *) model)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("invalid sound model '%s'"), (char *) model);
        goto error;
    }

    err = 0;
 error:
    xmlFree(model);
    return err;
}

D
Daniel P. Berrange 已提交
1607 1608 1609 1610
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
1611 1612
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
1613
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
1614 1615 1616 1617 1618 1619
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
1620 1621
    struct qemud_vm_def *def;

1622
    if (VIR_ALLOC(def) < 0) {
1623 1624
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
1625 1626
        return NULL;
    }
D
Daniel P. Berrange 已提交
1627 1628 1629 1630

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
1631 1632
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
D
Daniel P. Berrange 已提交
1633 1634 1635 1636 1637
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1638 1639
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
D
Daniel P. Berrange 已提交
1640 1641 1642 1643 1644 1645
        goto error;
    }


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

1651
    if (STREQ((char *)prop, "qemu"))
1652
        def->virtType = QEMUD_VIRT_QEMU;
1653
    else if (STREQ((char *)prop, "kqemu"))
1654
        def->virtType = QEMUD_VIRT_KQEMU;
1655
    else if (STREQ((char *)prop, "kvm"))
1656
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
1657
    else {
1658 1659
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("invalid domain type attribute"));
D
Daniel P. Berrange 已提交
1660 1661
        goto error;
    }
1662
    VIR_FREE(prop);
D
Daniel P. Berrange 已提交
1663 1664 1665 1666 1667 1668


    /* 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)) {
1669
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
1670 1671 1672
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1673 1674
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("domain name length too long"));
D
Daniel P. Berrange 已提交
1675 1676
        goto error;
    }
1677
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1678 1679 1680 1681 1682 1683 1684
    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)) {
1685
        int err;
D
Daniel P. Berrange 已提交
1686
        if ((err = virUUIDGenerate(def->uuid))) {
1687
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1688
                             _("Failed to generate UUID: %s"), strerror(err));
1689 1690
            goto error;
        }
D
Daniel P. Berrange 已提交
1691
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
1692 1693
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
D
Daniel P. Berrange 已提交
1694 1695 1696 1697 1698 1699 1700 1701 1702
        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)) {
1703 1704
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing memory element"));
D
Daniel P. Berrange 已提交
1705 1706 1707
        goto error;
    } else {
        conv = NULL;
1708
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1709
        if (conv == (const char*)obj->stringval) {
1710 1711
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1712 1713 1714
            goto error;
        }
    }
1715
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1716 1717 1718 1719 1720 1721


    /* 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)) {
1722
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1723 1724
    } else {
        conv = NULL;
1725 1726 1727
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1728
        if (conv == (const char*)obj->stringval) {
1729 1730
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1731 1732 1733
            goto error;
        }
    }
1734
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1735 1736 1737 1738 1739

    /* 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)) {
1740
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1741 1742
    } else {
        conv = NULL;
1743
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1744
        if (conv == (const char*)obj->stringval) {
1745 1746
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed vcpu information"));
D
Daniel P. Berrange 已提交
1747 1748 1749
            goto error;
        }
    }
1750
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1751

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
    /* Extract domain vcpu info */
    obj = xmlXPathEval(BAD_CAST "string(/domain/vcpu[1]/@cpuset)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        /* Allow use on all CPUS */
        memset(def->cpumask, 1, QEMUD_CPUMASK_LEN);
    } else {
        char *set = (char *)obj->stringval;
        memset(def->cpumask, 0, QEMUD_CPUMASK_LEN);
        if (virParseCpuSet(conn, (const char **)&set,
                           0, def->cpumask,
                           QEMUD_CPUMASK_LEN) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed vcpu mask information"));
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

D
Daniel P. Berrange 已提交
1771 1772 1773 1774
    /* 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)) {
1775
        def->features |= QEMUD_FEATURE_ACPI;
D
Daniel P. Berrange 已提交
1776
    }
1777
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1778

D
Daniel P. Berrange 已提交
1779 1780 1781 1782 1783 1784 1785

    /* 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 {
1786
        if (STREQ((char*)obj->stringval, "destroy"))
D
Daniel P. Berrange 已提交
1787 1788 1789 1790
            def->noReboot = 1;
        else
            def->noReboot = 0;
    }
1791
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1792

1793 1794 1795 1796 1797 1798
    /* 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 {
1799
        if (STREQ((char*)obj->stringval, "localtime"))
1800 1801 1802 1803
            def->localtime = 1;
        else
            def->localtime = 0;
    }
1804
    xmlXPathFreeObject(obj);
1805

D
Daniel P. Berrange 已提交
1806

D
Daniel P. Berrange 已提交
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
    /* Extract bootloader */
    obj = xmlXPathEval(BAD_CAST "string(/domain/bootloader)", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        strncpy(def->os.bootloader, (const char*)obj->stringval, sizeof(def->os.bootloader));
        NUL_TERMINATE(def->os.bootloader);

        /* Set a default OS type, since <type> is optional with bootloader */
        strcpy(def->os.type, "xen");
    }
J
Jim Meyering 已提交
1817
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1818

D
Daniel P. Berrange 已提交
1819 1820 1821 1822
    /* 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)) {
D
Daniel P. Berrange 已提交
1823 1824 1825 1826 1827 1828 1829
        if (!def->os.type[0]) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
                             "%s", _("no OS type"));
            goto error;
        }
    } else {
        strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1830
    }
J
Jim Meyering 已提交
1831 1832
    xmlXPathFreeObject(obj);
    obj = NULL;
D
Daniel P. Berrange 已提交
1833 1834

    if (!virCapabilitiesSupportsGuestOSType(driver->caps, def->os.type)) {
1835
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
D
Daniel P. Berrange 已提交
1836
                         "%s", def->os.type);
D
Daniel P. Berrange 已提交
1837 1838 1839 1840 1841 1842
        goto error;
    }

    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)) {
1843 1844
        const char *defaultArch = virCapabilitiesDefaultGuestArch(driver->caps, def->os.type);
        if (defaultArch == NULL) {
1845 1846
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1847 1848
            goto error;
        }
D
Daniel P. Berrange 已提交
1849
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1850 1851
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1852 1853
            goto error;
        }
1854
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
1855 1856
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1857 1858
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1859 1860
            goto error;
        }
1861
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1862
    }
1863
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1864 1865 1866 1867

    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)) {
1868 1869 1870 1871
        const char *defaultMachine = virCapabilitiesDefaultGuestMachine(driver->caps,
                                                                        def->os.type,
                                                                        def->os.arch);
        if (defaultMachine == NULL) {
1872 1873
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1874 1875
            goto error;
        }
D
Daniel P. Berrange 已提交
1876
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1877 1878
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("machine type too long"));
D
Daniel P. Berrange 已提交
1879 1880
            goto error;
        }
1881
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1882 1883
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1884 1885
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1886 1887
            goto error;
        }
1888
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1889
    }
1890
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1891 1892


D
Daniel P. Berrange 已提交
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
    if (!def->os.bootloader[0]) {
        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)) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("kernel path too long"));
                goto error;
            }
            strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1903
        }
D
Daniel P. Berrange 已提交
1904
        xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1905 1906


D
Daniel P. Berrange 已提交
1907 1908 1909 1910 1911 1912 1913 1914 1915
        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)) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("initrd path too long"));
                goto error;
            }
            strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1916
        }
D
Daniel P. Berrange 已提交
1917
        xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1918 1919


D
Daniel P. Berrange 已提交
1920 1921 1922 1923 1924 1925 1926 1927 1928
        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)) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("cmdline arguments too long"));
                goto error;
            }
            strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1929
        }
D
Daniel P. Berrange 已提交
1930
        xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1931 1932


D
Daniel P. Berrange 已提交
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
        /* 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++) {
                if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                    continue;
                if (STREQ((char *)prop, "hd")) {
                    def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
                } else if (STREQ((char *)prop, "fd")) {
                    def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
                } else if (STREQ((char *)prop, "cdrom")) {
                    def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
                } else if (STREQ((char *)prop, "network")) {
                    def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
                } else {
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                     _("unknown boot device \'%s\'"), (char*)prop);
                    goto error;
                }
                xmlFree(prop);
                prop = NULL;
D
Daniel P. Berrange 已提交
1955 1956
            }
        }
D
Daniel P. Berrange 已提交
1957 1958 1959 1960 1961
        xmlXPathFreeObject(obj);
        if (def->os.nBootDevs == 0) {
            def->os.nBootDevs = 1;
            def->os.bootDevs[0] = QEMUD_BOOT_DISK;
        }
D
Daniel P. Berrange 已提交
1962 1963 1964 1965 1966
    }

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1967 1968 1969 1970 1971 1972
        const char *type = qemudVirtTypeToString(def->virtType);
        if (!type) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unknown virt type"));
            goto error;
        }
1973 1974 1975 1976 1977
        const char *emulator = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                                   def->os.type,
                                                                   def->os.arch,
                                                                   type);
        if (!emulator) {
1978 1979
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported guest type"));
D
Daniel P. Berrange 已提交
1980 1981
            goto error;
        }
1982
        strcpy(def->os.binary, emulator);
D
Daniel P. Berrange 已提交
1983 1984
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1985 1986
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("emulator path too long"));
D
Daniel P. Berrange 已提交
1987 1988
            goto error;
        }
1989
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1990
    }
1991
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1992 1993 1994 1995

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1996
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1997
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
1998
        if (STREQ((char *)prop, "vnc")) {
1999
            xmlChar *vncport, *vnclisten;
2000
            def->graphicsType = QEMUD_GRAPHICS_VNC;
2001 2002
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
2003
                conv = NULL;
2004
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
2005
            } else {
2006
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
2007
            }
2008 2009 2010 2011
            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 已提交
2012
                strcpy(def->vncListen, driver->vncListen);
2013
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
2014
            def->keymap = (char *) xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "keymap");
2015 2016
            xmlFree(vncport);
            xmlFree(vnclisten);
2017
        } else if (STREQ((char *)prop, "sdl")) {
2018
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
2019
        } else {
2020 2021
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Unsupported graphics type %s"), prop);
D
Daniel P. Berrange 已提交
2022 2023
            goto error;
        }
2024
        xmlFree(prop);
2025
        prop = NULL;
D
Daniel P. Berrange 已提交
2026
    }
2027
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
2028 2029 2030 2031 2032 2033

    /* 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)) {
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
2034 2035
            struct qemud_vm_disk_def *disk;
            if (VIR_ALLOC(disk) < 0) {
2036 2037
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for disk string"));
D
Daniel P. Berrange 已提交
2038 2039 2040
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
2041
                VIR_FREE(disk);
D
Daniel P. Berrange 已提交
2042 2043
                goto error;
            }
2044
            def->ndisks++;
2045
            if (i == 0) {
2046
                disk->next = NULL;
2047 2048
                def->disks = disk;
            } else {
2049 2050 2051 2052 2053 2054 2055 2056 2057
                struct qemud_vm_disk_def *ptr = def->disks;
                while (ptr) {
                    if (!ptr->next || qemudDiskCompare(disk, ptr->next) < 0) {
                        disk->next = ptr->next;
                        ptr->next = disk;
                        break;
                    }
                    ptr = ptr->next;
                }
2058
            }
D
Daniel P. Berrange 已提交
2059 2060 2061
        }
    }
    xmlXPathFreeObject(obj);
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083
    obj = NULL;

    /* analysis of the character devices */
    if (qemudParseCharXMLDevices(conn, ctxt,
                                 "/domain/devices/parallel",
                                 &def->nparallels,
                                 &def->parallels) < 0)
        goto error;
    if (qemudParseCharXMLDevices(conn, ctxt,
                                 "/domain/devices/serial",
                                 &def->nserials,
                                 &def->serials) < 0)
        goto error;

    /*
     * If no serial devices were listed, then look for console
     * devices which is the legacy syntax for the same thing
     */
    if (def->nserials == 0) {
        obj = xmlXPathEval(BAD_CAST "/domain/devices/console", ctxt);
        if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
            (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr == 1)) {
2084 2085
            struct qemud_vm_chr_def *chr;
            if (VIR_ALLOC(chr) < 0) {
2086 2087 2088 2089 2090 2091 2092
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                                 "%s",
                                 _("failed to allocate space for char device"));
                goto error;
            }

            if (qemudParseCharXML(conn, chr, 0, obj->nodesetval->nodeTab[0]) < 0) {
2093
                VIR_FREE(chr);
2094 2095 2096 2097 2098 2099 2100
                goto error;
            }
            def->nserials = 1;
            def->serials = chr;
        }
        xmlXPathFreeObject(obj);
    }
D
Daniel P. Berrange 已提交
2101 2102 2103 2104 2105 2106


    /* 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)) {
2107
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
2108
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
2109 2110
            struct qemud_vm_net_def *net;
            if (VIR_ALLOC(net) < 0) {
2111 2112
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for net string"));
D
Daniel P. Berrange 已提交
2113 2114 2115
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
2116
                VIR_FREE(net);
D
Daniel P. Berrange 已提交
2117 2118
                goto error;
            }
2119
            def->nnets++;
2120 2121 2122 2123 2124 2125 2126
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
2127 2128 2129
        }
    }
    xmlXPathFreeObject(obj);
2130 2131 2132 2133 2134 2135 2136

    /* 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++) {
2137 2138
            struct qemud_vm_input_def *input;
            if (VIR_ALLOC(input) < 0) {
2139 2140
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
D
Daniel P. Berrange 已提交
2141 2142
                goto error;
            }
2143
            if (qemudParseInputXML(conn, def, input, obj->nodesetval->nodeTab[i]) < 0) {
2144
                VIR_FREE(input);
2145 2146 2147 2148 2149
                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) {
2150
                VIR_FREE(input);
2151 2152 2153 2154
                continue;
            }
            def->ninputs++;
            input->next = NULL;
2155
            if (def->inputs == NULL) {
2156 2157 2158 2159 2160 2161 2162 2163
                def->inputs = input;
            } else {
                prev->next = input;
            }
            prev = input;
        }
    }
    xmlXPathFreeObject(obj);
D
Daniel Veillard 已提交
2164 2165 2166 2167 2168 2169 2170 2171

    /* Parse sound driver xml */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/sound", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        struct qemud_vm_sound_def *prev = NULL;
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {

2172
            struct qemud_vm_sound_def *sound;
D
Daniel Veillard 已提交
2173 2174
            struct qemud_vm_sound_def *check = def->sounds;
            int collision = 0;
2175
            if (VIR_ALLOC(sound) < 0) {
D
Daniel Veillard 已提交
2176 2177 2178 2179 2180 2181
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for sound dev"));
                goto error;
            }
            if (qemudParseSoundXML(conn, sound,
                                   obj->nodesetval->nodeTab[i]) < 0) {
2182
                VIR_FREE(sound);
D
Daniel Veillard 已提交
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
                goto error;
            }

            // Check that model type isn't already present in sound dev list
            while(check) {
                if (check->model == sound->model) {
                    collision = 1;
                    break;
                }
                check = check->next;
            }
2194
            if (collision) {
2195
                VIR_FREE(sound);
D
Daniel Veillard 已提交
2196
                continue;
2197
            }
D
Daniel Veillard 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209

            def->nsounds++;
            sound->next = NULL;
            if (def->sounds == NULL) {
                def->sounds = sound;
            } else {
                prev->next = sound;
            }
            prev = sound;
        }
    }
    xmlXPathFreeObject(obj);
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
    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) {
2224
            if (VIR_ALLOC(input) < 0) {
2225 2226
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
                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 已提交
2237 2238
    xmlXPathFreeContext(ctxt);

2239
    return def;
D
Daniel P. Berrange 已提交
2240 2241

 error:
2242
    VIR_FREE(prop);
2243
    xmlXPathFreeObject(obj);
2244
    xmlXPathFreeContext(ctxt);
2245 2246
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
2247 2248 2249
}


2250
static char *
2251 2252
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
2253
                         struct qemud_vm *vm,
2254 2255
                         struct qemud_vm_net_def *net,
                         int vlan)
2256
{
2257 2258 2259
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
2260 2261 2262 2263 2264
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;

2265
    if (net->type == QEMUD_NET_NETWORK) {
2266
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
2267
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2268 2269
                             _("Network '%s' not found"),
                             net->dst.network.name);
2270 2271
            goto error;
        } else if (network->bridge[0] == '\0') {
2272
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2273 2274
                             _("Network '%s' not active"),
                             net->dst.network.name);
2275 2276 2277 2278
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
2279
            STRPREFIX(net->dst.network.ifname, "vnet") ||
2280 2281 2282 2283 2284 2285 2286
            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' ||
2287
            STRPREFIX(net->dst.bridge.ifname, "vnet") ||
2288 2289 2290 2291 2292
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
2293
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2294
                         _("Network type %d is not supported"), net->type);
2295 2296 2297
        goto error;
    }

2298
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
2299
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2300 2301
                         _("cannot initialize bridge support: %s"),
                         strerror(err));
2302 2303 2304
        goto error;
    }

2305
    if ((err = brAddTap(driver->brctl, brname,
2306
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
        if (errno == ENOTSUP) {
            /* In this particular case, give a better diagnostic. */
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Failed to add tap interface to bridge. "
                               "%s is not a bridge device"), brname);
        } else {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Failed to add tap interface '%s' "
                               "to bridge '%s' : %s"),
                             ifname, brname, strerror(err));
        }
2318 2319 2320
        goto error;
    }

2321 2322 2323
    snprintf(tapfdstr, sizeof(tapfdstr),
             "tap,fd=%d,script=,vlan=%d,ifname=%s",
             tapfd, vlan, ifname);
2324 2325 2326 2327

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

2328
    if (VIR_REALLOC_N(vm->tapfds, vm->ntapfds+2) < 0)
2329 2330 2331 2332 2333 2334 2335 2336
        goto no_memory;

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

    return retval;

 no_memory:
2337 2338
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for tapfds string"));
2339
 error:
2340
    VIR_FREE(retval);
2341 2342 2343 2344 2345
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
static int qemudBuildCommandLineChrDevStr(struct qemud_vm_chr_def *dev,
                                          char *buf,
                                          int buflen)
{
    switch (dev->srcType) {
    case QEMUD_CHR_SRC_TYPE_NULL:
        strncpy(buf, "null", buflen);
        buf[buflen-1] = '\0';
        break;

    case QEMUD_CHR_SRC_TYPE_VC:
        strncpy(buf, "vc", buflen);
        buf[buflen-1] = '\0';
        break;

    case QEMUD_CHR_SRC_TYPE_PTY:
        strncpy(buf, "pty", buflen);
        buf[buflen-1] = '\0';
        break;

    case QEMUD_CHR_SRC_TYPE_DEV:
        if (snprintf(buf, buflen, "%s",
                     dev->srcData.file.path) >= buflen)
            return -1;
        break;

    case QEMUD_CHR_SRC_TYPE_FILE:
        if (snprintf(buf, buflen, "file:%s",
                     dev->srcData.file.path) >= buflen)
            return -1;
        break;

    case QEMUD_CHR_SRC_TYPE_PIPE:
        if (snprintf(buf, buflen, "pipe:%s",
                     dev->srcData.file.path) >= buflen)
            return -1;
        break;

    case QEMUD_CHR_SRC_TYPE_STDIO:
        strncpy(buf, "stdio", buflen);
        buf[buflen-1] = '\0';
        break;

    case QEMUD_CHR_SRC_TYPE_UDP:
        if (snprintf(buf, buflen, "udp:%s:%s@%s:%s",
                     dev->srcData.udp.connectHost,
                     dev->srcData.udp.connectService,
                     dev->srcData.udp.bindHost,
                     dev->srcData.udp.bindService) >= buflen)
            return -1;
        break;

    case QEMUD_CHR_SRC_TYPE_TCP:
        if (snprintf(buf, buflen, "%s:%s:%s%s",
                     dev->srcData.tcp.protocol == QEMUD_CHR_SRC_TCP_PROTOCOL_TELNET ? "telnet" : "tcp",
                     dev->srcData.tcp.host,
                     dev->srcData.tcp.service,
                     dev->srcData.tcp.listen ? ",listen" : "") >= buflen)
            return -1;
        break;

    case QEMUD_CHR_SRC_TYPE_UNIX:
        if (snprintf(buf, buflen, "unix:%s%s",
                     dev->srcData.nix.path,
                     dev->srcData.nix.listen ? ",listen" : "") >= buflen)
            return -1;
        break;
    }

    return 0;
}

D
Daniel P. Berrange 已提交
2418 2419 2420 2421
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
2422 2423
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
2424
                          struct qemud_vm *vm,
2425 2426
                          char ***retargv) {
    int i;
D
Daniel P. Berrange 已提交
2427 2428 2429
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
2430 2431
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
2432
    struct qemud_vm_input_def *input = vm->def->inputs;
D
Daniel Veillard 已提交
2433
    struct qemud_vm_sound_def *sound = vm->def->sounds;
2434 2435
    struct qemud_vm_chr_def *serial = vm->def->serials;
    struct qemud_vm_chr_def *parallel = vm->def->parallels;
2436 2437
    struct utsname ut;
    int disableKQEMU = 0;
2438 2439
    int qargc = 0, qarga = 0;
    char **qargv = NULL;
D
Daniel P. Berrange 已提交
2440

2441 2442 2443 2444 2445 2446
    if (vm->qemuVersion == 0) {
        if (qemudExtractVersionInfo(vm->def->os.binary,
                                    &(vm->qemuVersion),
                                    &(vm->qemuCmdFlags)) < 0)
            return -1;
    }
2447

2448 2449
    uname(&ut);

D
Daniel P. Berrange 已提交
2450
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
2451 2452 2453 2454
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
2455
        ut.machine[1] = '6';
2456 2457 2458 2459 2460 2461

    /* Need to explicitly disable KQEMU if
     * 1. Arch matches host arch
     * 2. Guest is 'qemu'
     * 3. The qemu binary has the -no-kqemu flag
     */
2462
    if ((vm->qemuCmdFlags & QEMUD_CMD_FLAG_KQEMU) &&
2463
        STREQ(ut.machine, vm->def->os.arch) &&
2464 2465 2466
        vm->def->virtType == QEMUD_VIRT_QEMU)
        disableKQEMU = 1;

2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
#define ADD_ARG_SPACE                                                   \
    do { \
        if (qargc == qarga) {                                           \
            qarga += 10;                                                \
            if (VIR_REALLOC_N(qargv, qarga) < 0)                        \
                goto no_memory;                                         \
        }                                                               \
    } while (0)

#define ADD_ARG(thisarg)                                                \
    do {                                                                \
        ADD_ARG_SPACE;                                                  \
        qargv[qargc++] = thisarg;                                       \
    } while (0)

#define ADD_ARG_LIT(thisarg)                                            \
    do {                                                                \
        ADD_ARG_SPACE;                                                  \
        if ((qargv[qargc++] = strdup(thisarg)) == NULL)                 \
            goto no_memory;                                             \
    } while (0)
D
Daniel P. Berrange 已提交
2488

2489
    snprintf(memory, sizeof(memory), "%lu", vm->def->memory/1024);
2490
    snprintf(vcpus, sizeof(vcpus), "%d", vm->def->vcpus);
D
Daniel P. Berrange 已提交
2491

2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502

    ADD_ARG_LIT(vm->def->os.binary);
    ADD_ARG_LIT("-S");
    ADD_ARG_LIT("-M");
    ADD_ARG_LIT(vm->def->os.machine);
    if (disableKQEMU)
        ADD_ARG_LIT("-no-kqemu");
    ADD_ARG_LIT("-m");
    ADD_ARG_LIT(memory);
    ADD_ARG_LIT("-smp");
    ADD_ARG_LIT(vcpus);
D
Daniel P. Berrange 已提交
2503

2504
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NAME) {
2505 2506
        ADD_ARG_LIT("-name");
        ADD_ARG_LIT(vm->def->name);
2507
    }
2508 2509 2510 2511 2512 2513 2514
    /*
     * 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...
     */
2515 2516
    if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE)
        ADD_ARG_LIT("-nographic");
2517

2518 2519
    ADD_ARG_LIT("-monitor");
    ADD_ARG_LIT("pty");
D
Daniel P. Berrange 已提交
2520

2521 2522
    if (vm->def->localtime)
        ADD_ARG_LIT("-localtime");
2523

2524 2525 2526
    if ((vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT) &&
        vm->def->noReboot)
        ADD_ARG_LIT("-no-reboot");
D
Daniel P. Berrange 已提交
2527

2528 2529
    if (!(vm->def->features & QEMUD_FEATURE_ACPI))
        ADD_ARG_LIT("-no-acpi");
D
Daniel P. Berrange 已提交
2530

D
Daniel P. Berrange 已提交
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551
    if (!vm->def->os.bootloader[0]) {
        for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
            switch (vm->def->os.bootDevs[i]) {
            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;
            }
        }
        boot[vm->def->os.nBootDevs] = '\0';
2552 2553
        ADD_ARG_LIT("-boot");
        ADD_ARG_LIT(boot);
D
Daniel P. Berrange 已提交
2554 2555

        if (vm->def->os.kernel[0]) {
2556 2557
            ADD_ARG_LIT("-kernel");
            ADD_ARG_LIT(vm->def->os.kernel);
D
Daniel P. Berrange 已提交
2558 2559
        }
        if (vm->def->os.initrd[0]) {
2560 2561
            ADD_ARG_LIT("-initrd");
            ADD_ARG_LIT(vm->def->os.initrd);
D
Daniel P. Berrange 已提交
2562 2563
        }
        if (vm->def->os.cmdline[0]) {
2564 2565
            ADD_ARG_LIT("-append");
            ADD_ARG_LIT(vm->def->os.cmdline);
D
Daniel P. Berrange 已提交
2566 2567
        }
    } else {
2568 2569
        ADD_ARG_LIT("-bootloader");
        ADD_ARG_LIT(vm->def->os.bootloader);
D
Daniel P. Berrange 已提交
2570 2571
    }

2572
    /* If QEMU supports -drive param instead of old -hda, -hdb, -cdrom .. */
2573
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
2574 2575 2576
        int bootCD = 0, bootFloppy = 0, bootDisk = 0;

        /* If QEMU supports boot=on for -drive param... */
2577
        if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE_BOOT) {
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
            for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
                switch (vm->def->os.bootDevs[i]) {
                case QEMUD_BOOT_CDROM:
                    bootCD = 1;
                    break;
                case QEMUD_BOOT_FLOPPY:
                    bootFloppy = 1;
                    break;
                case QEMUD_BOOT_DISK:
                    bootDisk = 1;
                    break;
                }
2590
            }
2591
        }
D
Daniel P. Berrange 已提交
2592

2593 2594 2595 2596 2597
        while (disk) {
            char opt[PATH_MAX];
            const char *media = NULL;
            int bootable = 0;
            int idx = virDiskNameToIndex(disk->dst);
D
Daniel P. Berrange 已提交
2598

2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628
            if (idx < 0) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("unsupported disk type '%s'"), disk->dst);
                goto error;
            }

            if (disk->device == QEMUD_DISK_CDROM)
                media = "media=cdrom,";

            switch (disk->device) {
            case QEMUD_DISK_CDROM:
                bootable = bootCD;
                bootCD = 0;
                break;
            case QEMUD_DISK_FLOPPY:
                bootable = bootFloppy;
                bootFloppy = 0;
                break;
            case QEMUD_DISK_DISK:
                bootable = bootDisk;
                bootDisk = 0;
                break;
            }

            snprintf(opt, PATH_MAX, "file=%s,if=%s,%sindex=%d%s",
                     disk->src, qemudBusIdToName(disk->bus, 1),
                     media ? media : "",
                     idx,
                     bootable ? ",boot=on" : "");

2629 2630
            ADD_ARG_LIT("-drive");
            ADD_ARG_LIT(opt);
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
            disk = disk->next;
        }
    } else {
        while (disk) {
            char dev[NAME_MAX];
            char file[PATH_MAX];

            if (STREQ(disk->dst, "hdc") &&
                disk->device == QEMUD_DISK_CDROM) {
                if (disk->src[0]) {
                    snprintf(dev, NAME_MAX, "-%s", "cdrom");
                } else {
                    disk = disk->next;
                    continue;
                }
            } else {
                if (STRPREFIX(disk->dst, "hd") ||
                    STRPREFIX(disk->dst, "fd")) {
                    snprintf(dev, NAME_MAX, "-%s", disk->dst);
                } else {
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                     _("unsupported disk type '%s'"), disk->dst);
                    goto error;
                }
            }

            snprintf(file, PATH_MAX, "%s", disk->src);

2659 2660
            ADD_ARG_LIT(dev);
            ADD_ARG_LIT(file);
2661 2662 2663

            disk = disk->next;
        }
D
Daniel P. Berrange 已提交
2664 2665 2666
    }

    if (!net) {
2667 2668
        ADD_ARG_LIT("-net");
        ADD_ARG_LIT("none");
D
Daniel P. Berrange 已提交
2669
    } else {
2670
        int vlan = 0;
D
Daniel P. Berrange 已提交
2671
        while (net) {
2672
            char nic[100];
2673

2674 2675
            if (snprintf(nic, sizeof(nic),
                         "nic,macaddr=%02x:%02x:%02x:%02x:%02x:%02x,vlan=%d%s%s",
2676 2677 2678
                         net->mac[0], net->mac[1],
                         net->mac[2], net->mac[3],
                         net->mac[4], net->mac[5],
2679 2680
                         vlan,
                         (net->model[0] ? ",model=" : ""), net->model) >= sizeof(nic))
2681
                goto error;
D
Daniel P. Berrange 已提交
2682

2683 2684 2685
            ADD_ARG_LIT("-net");
            ADD_ARG_LIT(nic);
            ADD_ARG_LIT("-net");
2686

2687 2688 2689
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
2690 2691 2692 2693 2694 2695 2696
                {
                    char *tap = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan);
                    if (tap == NULL)
                        goto error;
                    ADD_ARG(tap);
                    break;
                }
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706

            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;

2707
                    ADD_ARG_LIT(arg);
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
                }
                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;

2735
                    ADD_ARG_LIT(arg);
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
                }
                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;

2746
                    ADD_ARG_LIT(arg);
2747
                }
2748
            }
D
Daniel P. Berrange 已提交
2749 2750

            net = net->next;
2751
            vlan++;
D
Daniel P. Berrange 已提交
2752 2753 2754
        }
    }

2755
    if (!serial) {
2756 2757
        ADD_ARG_LIT("-serial");
        ADD_ARG_LIT("none");
2758 2759 2760 2761 2762 2763 2764
    } else {
        while (serial) {
            char buf[4096];

            if (qemudBuildCommandLineChrDevStr(serial, buf, sizeof(buf)) < 0)
                goto error;

2765 2766
            ADD_ARG_LIT("-serial");
            ADD_ARG_LIT(buf);
2767 2768 2769 2770 2771 2772

            serial = serial->next;
        }
    }

    if (!parallel) {
2773 2774
        ADD_ARG_LIT("-parallel");
        ADD_ARG_LIT("none");
2775 2776 2777 2778 2779 2780 2781
    } else {
        while (parallel) {
            char buf[4096];

            if (qemudBuildCommandLineChrDevStr(parallel, buf, sizeof(buf)) < 0)
                goto error;

2782 2783
            ADD_ARG_LIT("-parallel");
            ADD_ARG_LIT(buf);
2784 2785 2786 2787 2788

            parallel = parallel->next;
        }
    }

2789
    ADD_ARG_LIT("-usb");
2790 2791
    while (input) {
        if (input->bus == QEMU_INPUT_BUS_USB) {
2792 2793
            ADD_ARG_LIT("-usbdevice");
            ADD_ARG_LIT(input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet");
2794 2795 2796 2797 2798
        }

        input = input->next;
    }

2799
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
2800
        char vncdisplay[PATH_MAX];
2801
        int ret;
D
Daniel P. Berrange 已提交
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816

        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",
2817
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
2818 2819 2820
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
2821 2822
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
2823
        }
2824
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
2825 2826
            goto error;

2827 2828
        ADD_ARG_LIT("-vnc");
        ADD_ARG_LIT(vncdisplay);
2829
        if (vm->def->keymap) {
2830 2831
            ADD_ARG_LIT("-k");
            ADD_ARG_LIT(vm->def->keymap);
2832
        }
2833
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
2834
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
2835 2836 2837 2838
    } else {
        /* SDL is the default. no args needed */
    }

D
Daniel Veillard 已提交
2839 2840 2841
    /* Add sound hardware */
    if (sound) {
        int size = 100;
2842 2843
        char *modstr;
        if (VIR_ALLOC_N(modstr, size+1) < 0)
D
Daniel Veillard 已提交
2844 2845 2846 2847 2848
            goto no_memory;

        while(sound && size > 0) {
            const char *model = qemudSoundModelToString(sound->model);
            if (!model) {
2849
                VIR_FREE(modstr);
2850 2851 2852
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("invalid sound model"));
                goto error;
D
Daniel Veillard 已提交
2853 2854 2855 2856 2857 2858 2859
            }
            strncat(modstr, model, size);
            size -= strlen(model);
            sound = sound->next;
            if (sound)
               strncat(modstr, ",", size--);
        }
2860 2861
        ADD_ARG_LIT("-soundhw");
        ADD_ARG(modstr);
D
Daniel Veillard 已提交
2862 2863
    }

2864
    if (vm->migrateFrom[0]) {
2865 2866
        ADD_ARG_LIT("-incoming");
        ADD_ARG_LIT(vm->migrateFrom);
2867 2868
    }

2869
    ADD_ARG(NULL);
D
Daniel P. Berrange 已提交
2870

2871
    *retargv = qargv;
D
Daniel P. Berrange 已提交
2872 2873 2874
    return 0;

 no_memory:
2875 2876
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for argv string"));
2877 2878 2879 2880
 error:
    if (vm->tapfds) {
        for (i = 0; vm->tapfds[i] != -1; i++)
            close(vm->tapfds[i]);
2881
        VIR_FREE(vm->tapfds);
2882 2883 2884
        vm->tapfds = NULL;
        vm->ntapfds = 0;
    }
2885 2886
    if (qargv) {
        for (i = 0 ; i < qargc ; i++)
2887 2888
            VIR_FREE((qargv)[i]);
        VIR_FREE(qargv);
D
Daniel P. Berrange 已提交
2889 2890
    }
    return -1;
2891 2892 2893 2894

#undef ADD_ARG
#undef ADD_ARG_LIT
#undef ADD_ARG_SPACE
D
Daniel P. Berrange 已提交
2895 2896 2897 2898
}


/* Save a guest's config data into a persistent file */
2899 2900
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
2901 2902
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
2903 2904 2905 2906
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

2907
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
2908 2909 2910 2911 2912
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2913
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2914
                         _("cannot create config file %s: %s"),
2915
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2916 2917 2918 2919
        goto cleanup;
    }

    towrite = strlen(xml);
2920
    if (safewrite(fd, xml, towrite) < 0) {
2921
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2922
                         _("cannot write config file %s: %s"),
2923
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2924 2925 2926 2927
        goto cleanup;
    }

    if (close(fd) < 0) {
2928
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2929
                         _("cannot save config file %s: %s"),
2930
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2931 2932 2933 2934 2935 2936 2937 2938 2939
        goto cleanup;
    }

    ret = 0;

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

2940
    VIR_FREE(xml);
D
Daniel P. Berrange 已提交
2941 2942 2943 2944

    return ret;
}

D
Daniel P. Berrange 已提交
2945 2946
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
2947
                      const struct qemud_vm_def *def,
D
Daniel P. Berrange 已提交
2948 2949 2950 2951
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
2952 2953 2954 2955 2956 2957
    struct qemud_vm_device_def *dev;

    if (VIR_ALLOC(dev) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return NULL;
    }
D
Daniel P. Berrange 已提交
2958 2959 2960 2961 2962

    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);
2963
        goto error;
D
Daniel P. Berrange 已提交
2964 2965 2966 2967
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
2968 2969
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("missing root element"));
D
Daniel P. Berrange 已提交
2970 2971 2972 2973 2974
        goto error;
    }
    if (xmlStrEqual(node->name, BAD_CAST "disk")) {
        dev->type = QEMUD_DEVICE_DISK;
        qemudParseDiskXML(conn, &(dev->data.disk), node);
2975
    } else if (xmlStrEqual(node->name, BAD_CAST "interface")) {
D
Daniel P. Berrange 已提交
2976 2977 2978 2979
        dev->type = QEMUD_DEVICE_NET;
        qemudParseInterfaceXML(conn, &(dev->data.net), node);
    } else if (xmlStrEqual(node->name, BAD_CAST "input")) {
        dev->type = QEMUD_DEVICE_DISK;
2980
        qemudParseInputXML(conn, def, &(dev->data.input), node);
D
Daniel Veillard 已提交
2981 2982 2983
    } else if (xmlStrEqual(node->name, BAD_CAST "sound")) {
        dev->type = QEMUD_DEVICE_SOUND;
        qemudParseSoundXML(conn, &(dev->data.sound), node);
D
Daniel P. Berrange 已提交
2984
    } else {
2985 2986
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("unknown device type"));
D
Daniel P. Berrange 已提交
2987 2988 2989 2990 2991 2992 2993 2994 2995
        goto error;
    }

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
2996
    VIR_FREE(dev);
D
Daniel P. Berrange 已提交
2997 2998 2999
    return NULL;
}

3000
struct qemud_vm_def *
3001 3002
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
3003 3004
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
3005
    xmlDocPtr xml;
3006
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
3007

3008
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
3009 3010
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
3011
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
3012 3013 3014
        return NULL;
    }

3015
    def = qemudParseXML(conn, driver, xml);
3016

D
Daniel P. Berrange 已提交
3017 3018
    xmlFreeDoc(xml);

3019 3020 3021 3022
    return def;
}

struct qemud_vm *
3023 3024
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
3025 3026 3027 3028
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

3029
    if ((vm = qemudFindVMByName(driver, def->name))) {
3030
        if (!qemudIsActiveVM(vm)) {
3031 3032 3033 3034 3035 3036 3037
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
3038 3039 3040
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
3041
        return vm;
D
Daniel P. Berrange 已提交
3042 3043
    }

3044
    if (VIR_ALLOC(vm) < 0) {
3045 3046
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for vm string"));
3047 3048
        return NULL;
    }
D
Daniel P. Berrange 已提交
3049

3050
    vm->stdin = -1;
3051 3052 3053 3054 3055
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
3056
    vm->state = VIR_DOMAIN_SHUTOFF;
3057
    vm->def = def;
3058
    vm->next = driver->vms;
3059

3060 3061
    driver->vms = vm;
    driver->ninactivevms++;
3062 3063 3064 3065 3066

    return vm;
}

void
3067
qemudRemoveInactiveVM(struct qemud_driver *driver,
3068 3069 3070 3071
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

3072
    curr = driver->vms;
3073 3074 3075
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
3076 3077
    }

3078 3079 3080 3081
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
3082
            driver->vms = curr->next;
3083

3084
        driver->ninactivevms--;
3085 3086
    }

3087
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
3088 3089
}

3090
int
3091 3092
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
3093 3094 3095 3096 3097
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

3098
        if ((err = virFileMakePath(driver->configDir))) {
3099
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3100
                             _("cannot create config directory %s: %s"),
3101
                             driver->configDir, strerror(err));
3102 3103 3104
            return -1;
        }

3105 3106
        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             vm->configFile, PATH_MAX) < 0) {
3107
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3108
                             "%s", _("cannot construct config file path"));
3109 3110
            return -1;
        }
3111

3112 3113
        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             vm->autostartLink, PATH_MAX) < 0) {
3114
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3115
                             "%s", _("cannot construct autostart link path"));
3116 3117 3118
            vm->configFile[0] = '\0';
            return -1;
        }
3119 3120
    }

3121
    return qemudSaveConfig(conn, driver, vm, def);
3122
}
D
Daniel P. Berrange 已提交
3123

3124 3125
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
3126 3127
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
3128 3129 3130
    char *xml;
    int fd, ret = -1;
    int towrite;
3131
    int err;
3132

3133
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
3134 3135 3136
        return -1;
    }

3137
    if ((err = virFileMakePath(driver->networkConfigDir))) {
3138
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3139
                         _("cannot create config directory %s: %s"),
3140
                         driver->networkConfigDir, strerror(err));
3141 3142 3143 3144 3145 3146
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
3147
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3148
                         _("cannot create config file %s: %s"),
3149
                         network->configFile, strerror(errno));
3150 3151 3152 3153
        goto cleanup;
    }

    towrite = strlen(xml);
3154
    if (safewrite(fd, xml, towrite) < 0) {
3155
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3156
                         _("cannot write config file %s: %s"),
3157
                         network->configFile, strerror(errno));
3158 3159 3160 3161
        goto cleanup;
    }

    if (close(fd) < 0) {
3162
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3163
                         _("cannot save config file %s: %s"),
3164
                         network->configFile, strerror(errno));
3165 3166 3167 3168 3169 3170 3171
        goto cleanup;
    }

    ret = 0;

 cleanup:

3172
    VIR_FREE(xml);
3173 3174 3175 3176

    return ret;
}

3177 3178 3179 3180
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;
3181
        VIR_FREE(range);
3182 3183
        range = next;
    }
3184
    VIR_FREE(def);
3185 3186 3187 3188 3189 3190
}

void qemudFreeNetwork(struct qemud_network *network) {
    qemudFreeNetworkDef(network->def);
    if (network->newDef)
        qemudFreeNetworkDef(network->newDef);
3191
    VIR_FREE(network);
3192
}
3193

3194
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
3195
                               struct qemud_network_def *def,
3196 3197 3198 3199 3200
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
3201 3202
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
3203 3204 3205 3206 3207 3208 3209
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
3210
            def->disableSTP = 1;
3211 3212 3213 3214 3215 3216 3217
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
3218
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
3219 3220 3221 3222 3223 3224 3225
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

3226 3227
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
3228
                                   struct qemud_network_def *def,
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243
                                   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;
        }

3244
        if (VIR_ALLOC(range) < 0) {
3245 3246
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for range string"));
3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259
            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';

3260 3261 3262
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
3263
        } else {
3264
            VIR_FREE(range);
3265 3266
        }

3267 3268
        xmlFree(start);
        xmlFree(end);
3269 3270 3271 3272 3273 3274

        cur = cur->next;
    }

    return 1;
}
3275

3276 3277
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
3278
                             struct qemud_network_def *def,
3279 3280
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
3281
    xmlNodePtr cur;
3282 3283 3284

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
3285 3286
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
3287 3288 3289 3290 3291 3292
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
3293 3294
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
3295 3296 3297 3298
        xmlFree(netmask);
        netmask = NULL;
    }

3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
    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);
    }

3314 3315 3316 3317
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
3318
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
3319 3320 3321 3322
            return 0;
        cur = cur->next;
    }

3323 3324 3325 3326
    return 1;
}


3327 3328
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
3329
                                                      xmlDocPtr xml) {
3330 3331
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
3332
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
3333 3334
    struct qemud_network_def *def;

3335
    if (VIR_ALLOC(def) < 0) {
3336 3337
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                   "%s", _("failed to allocate space for network_def string"));
3338 3339
        return NULL;
    }
3340 3341 3342 3343

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
3344 3345
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
3346 3347 3348 3349 3350
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
3351 3352
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
               "%s", _("failed to allocate space for xmlXPathContext string"));
3353 3354 3355 3356 3357 3358 3359 3360
        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)) {
3361
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
3362 3363 3364
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
3365 3366
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("network name length too long"));
3367 3368
        goto error;
    }
3369
    strcpy(def->name, (const char *)obj->stringval);
3370 3371 3372 3373 3374 3375 3376
    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)) {
3377
        int err;
D
Daniel P. Berrange 已提交
3378
        if ((err = virUUIDGenerate(def->uuid))) {
3379
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3380
                             _("Failed to generate UUID: %s"), strerror(err));
3381 3382
            goto error;
        }
D
Daniel P. Berrange 已提交
3383
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
3384 3385
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
3386 3387 3388 3389
        goto error;
    }
    xmlXPathFreeObject(obj);

3390 3391 3392 3393
    /* 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)) {
3394
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
3395 3396 3397 3398 3399 3400 3401 3402 3403
            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)) {
3404
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
3405 3406 3407 3408 3409 3410
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
3411 3412 3413
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
3414 3415
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
3416
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3417
                             "%s", _("Forwarding requested, but no IPv4 address/netmask provided"));
3418 3419 3420
            goto error;
        }

3421
        def->forward = 1;
3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432

        tmp = xmlXPathEval(BAD_CAST "string(/network/forward[1]/@mode)", ctxt);
        if ((tmp != NULL) && (tmp->type == XPATH_STRING) &&
            (tmp->stringval != NULL) && (xmlStrEqual(tmp->stringval, BAD_CAST "route"))) {
            def->forwardMode = QEMUD_NET_FORWARD_ROUTE;
        } else {
            def->forwardMode = QEMUD_NET_FORWARD_NAT;
        }
        xmlXPathFreeObject(tmp);
        tmp = NULL;

3433 3434 3435 3436 3437
        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)) {
3438
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3439
                                 _("forward device name '%s' is too long"),
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453
                                 (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);

3454 3455
    xmlXPathFreeContext(ctxt);

3456
    return def;
3457 3458 3459 3460

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
3461 3462
    xmlXPathFreeObject(obj);
    xmlXPathFreeObject(tmp);
3463
    xmlXPathFreeContext(ctxt);
3464 3465
    qemudFreeNetworkDef(def);
    return NULL;
3466 3467
}

3468
struct qemud_network_def *
3469 3470
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
3471 3472
                     const char *xmlStr,
                     const char *displayName) {
3473
    xmlDocPtr xml;
3474
    struct qemud_network_def *def;
3475

3476
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
3477 3478
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
3479
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
3480 3481 3482
        return NULL;
    }

3483
    def = qemudParseNetworkXML(conn, driver, xml);
3484

3485 3486
    xmlFreeDoc(xml);

3487 3488 3489 3490
    return def;
}

struct qemud_network *
3491 3492
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
3493 3494 3495
                      struct qemud_network_def *def) {
    struct qemud_network *network;

3496
    if ((network = qemudFindNetworkByName(driver, def->name))) {
3497
        if (!qemudIsActiveNetwork(network)) {
3498 3499 3500 3501 3502 3503 3504 3505
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

3506
        return network;
3507 3508
    }

3509
    if (VIR_ALLOC(network) < 0) {
3510 3511
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for network string"));
3512 3513
        return NULL;
    }
3514

3515
    network->def = def;
3516
    network->next = driver->networks;
3517

3518 3519
    driver->networks = network;
    driver->ninactivenetworks++;
3520 3521 3522 3523 3524

    return network;
}

void
3525
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
3526 3527 3528 3529
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

3530
    curr = driver->networks;
3531 3532 3533
    while (curr != network) {
        prev = curr;
        curr = curr->next;
3534 3535
    }

3536 3537 3538 3539
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
3540
            driver->networks = curr->next;
3541

3542
        driver->ninactivenetworks--;
3543 3544
    }

3545
    qemudFreeNetwork(network);
3546 3547
}

3548
int
3549 3550
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
3551 3552 3553 3554 3555 3556
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

3557
        if ((err = virFileMakePath(driver->networkConfigDir))) {
3558
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3559
                             _("cannot create config directory %s: %s"),
3560
                             driver->networkConfigDir, strerror(err));
3561 3562 3563
            return -1;
        }

3564 3565
        if (virFileBuildPath(driver->networkConfigDir, def->name, ".xml",
                             network->configFile, PATH_MAX) < 0) {
3566
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3567
                             "%s", _("cannot construct config file path"));
3568 3569
            return -1;
        }
3570

3571 3572
        if (virFileBuildPath(driver->networkAutostartDir, def->name, ".xml",
                             network->autostartLink, PATH_MAX) < 0) {
3573
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3574
                             "%s", _("cannot construct autostart link path"));
3575 3576 3577
            network->configFile[0] = '\0';
            return -1;
        }
3578 3579
    }

3580
    return qemudSaveNetworkConfig(conn, driver, network, def);
3581
}
3582

3583

3584
static struct qemud_vm *
3585
qemudLoadConfig(struct qemud_driver *driver,
3586 3587
                const char *file,
                const char *path,
3588 3589
                const char *xml,
                const char *autostartLink) {
3590 3591 3592
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

3593
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
3594
        virErrorPtr err = virGetLastError();
3595 3596 3597
        qemudLog(QEMUD_WARN, _("Error parsing QEMU guest config '%s' : %s"),
                 path, (err ? err->message :
                        _("BUG: unknown error - please report it\n")));
3598 3599 3600
        return NULL;
    }

3601
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
3602 3603 3604
        qemudLog(QEMUD_WARN,
                 _("QEMU guest config filename '%s'"
                   " does not match guest name '%s'"),
3605 3606 3607 3608 3609
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

3610
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
3611 3612 3613
        qemudLog(QEMUD_WARN,
                 _("Failed to load QEMU guest config '%s': out of memory"),
                 path);
3614 3615 3616 3617 3618 3619 3620
        qemudFreeVMDef(def);
        return NULL;
    }

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

3621 3622 3623
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

3624
    vm->autostart = virFileLinkPointsTo(vm->autostartLink, vm->configFile);
3625

3626 3627 3628 3629
    return vm;
}

static struct qemud_network *
3630
qemudLoadNetworkConfig(struct qemud_driver *driver,
3631 3632
                       const char *file,
                       const char *path,
3633 3634
                       const char *xml,
                       const char *autostartLink) {
3635 3636 3637
    struct qemud_network_def *def;
    struct qemud_network *network;

3638
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
3639
        virErrorPtr err = virGetLastError();
3640
        qemudLog(QEMUD_WARN, _("Error parsing network config '%s' : %s"),
3641
                 path, err->message);
3642 3643 3644
        return NULL;
    }

3645
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
3646 3647 3648
        qemudLog(QEMUD_WARN,
                 _("Network config filename '%s'"
                   " does not match network name '%s'"),
3649 3650 3651 3652 3653
                 path, def->name);
        qemudFreeNetworkDef(def);
        return NULL;
    }

3654
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
3655 3656
        qemudLog(QEMUD_WARN,
                 _("Failed to load network config '%s': out of memory"), path);
3657 3658 3659 3660 3661 3662 3663
        qemudFreeNetworkDef(def);
        return NULL;
    }

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

3664 3665 3666
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

3667
    network->autostart = virFileLinkPointsTo(network->autostartLink, network->configFile);
3668

3669 3670
    return network;
}
D
Daniel P. Berrange 已提交
3671

3672
static
3673
int qemudScanConfigDir(struct qemud_driver *driver,
3674
                       const char *configDir,
3675
                       const char *autostartDir,
3676
                       int isGuest) {
D
Daniel P. Berrange 已提交
3677 3678 3679
    DIR *dir;
    struct dirent *entry;

3680
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
3681 3682
        if (errno == ENOENT)
            return 0;
3683
        qemudLog(QEMUD_ERR, _("Failed to open dir '%s': %s"),
3684
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
3685 3686 3687 3688
        return -1;
    }

    while ((entry = readdir(dir))) {
3689
        char *xml;
3690
        char path[PATH_MAX];
3691
        char autostartLink[PATH_MAX];
3692

D
Daniel P. Berrange 已提交
3693 3694 3695
        if (entry->d_name[0] == '.')
            continue;

3696
        if (!virFileHasSuffix(entry->d_name, ".xml"))
3697 3698
            continue;

3699
        if (virFileBuildPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
3700
            qemudLog(QEMUD_WARN, _("Config filename '%s/%s' is too long"),
3701 3702 3703 3704
                     configDir, entry->d_name);
            continue;
        }

3705 3706 3707
        if (virFileBuildPath(autostartDir, entry->d_name, NULL,
                             autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, _("Autostart link path '%s/%s' is too long"),
3708 3709 3710 3711
                     autostartDir, entry->d_name);
            continue;
        }

3712
        if (virFileReadAll(path, QEMUD_MAX_XML_LEN, &xml) < 0)
D
Daniel P. Berrange 已提交
3713 3714
            continue;

3715
        if (isGuest)
3716
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
3717
        else
3718
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
3719

3720
        VIR_FREE(xml);
D
Daniel P. Berrange 已提交
3721 3722 3723
    }

    closedir(dir);
3724

D
Daniel P. Berrange 已提交
3725 3726 3727
    return 0;
}

3728
/* Scan for all guest and network config files */
3729 3730
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
3731
        return -1;
3732

3733
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
3734 3735 3736
        return -1;

    return 0;
3737
}
D
Daniel P. Berrange 已提交
3738

3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
static int qemudGenerateXMLChar(virBufferPtr buf,
                                const struct qemud_vm_chr_def *dev,
                                const char *type)
{
    const char *const types[] = {
        "null",
        "vc",
        "pty",
        "dev",
        "file",
        "pipe",
        "stdio",
        "udp",
        "tcp",
        "unix"
    };
3755
    verify_true(ARRAY_CARDINALITY(types) == QEMUD_CHR_SRC_TYPE_LAST);
3756 3757 3758 3759 3760

    /* Compat with legacy  <console tty='/dev/pts/5'/> syntax */
    if (STREQ(type, "console") &&
        dev->srcType == QEMUD_CHR_SRC_TYPE_PTY &&
        dev->srcData.file.path[0] != '\0') {
3761 3762 3763
        virBufferVSprintf(buf, "    <%s type='%s' tty='%s'>\n",
                          type, types[dev->srcType],
                          dev->srcData.file.path);
3764
    } else {
3765 3766
        virBufferVSprintf(buf, "    <%s type='%s'>\n",
                          type, types[dev->srcType]);
3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
    }

    switch (dev->srcType) {
    case QEMUD_CHR_SRC_TYPE_NULL:
    case QEMUD_CHR_SRC_TYPE_VC:
    case QEMUD_CHR_SRC_TYPE_STDIO:
        /* nada */
        break;

    case QEMUD_CHR_SRC_TYPE_PTY:
    case QEMUD_CHR_SRC_TYPE_DEV:
    case QEMUD_CHR_SRC_TYPE_FILE:
    case QEMUD_CHR_SRC_TYPE_PIPE:
        if (dev->srcType != QEMUD_CHR_SRC_TYPE_PTY ||
            dev->srcData.file.path[0]) {
3782 3783
            virBufferVSprintf(buf, "      <source path='%s'/>\n",
                              dev->srcData.file.path);
3784 3785 3786 3787 3788 3789
        }
        break;

    case QEMUD_CHR_SRC_TYPE_UDP:
        if (dev->srcData.udp.bindService[0] != '\0' &&
            dev->srcData.udp.bindHost[0] != '\0') {
3790 3791 3792
            virBufferVSprintf(buf, "      <source mode='bind' host='%s' service='%s'/>\n",
                              dev->srcData.udp.bindHost,
                              dev->srcData.udp.bindService);
3793
        } else if (dev->srcData.udp.bindHost[0] !='\0') {
3794 3795
            virBufferVSprintf(buf, "      <source mode='bind' host='%s'/>\n",
                              dev->srcData.udp.bindHost);
3796
        } else if (dev->srcData.udp.bindService[0] != '\0') {
3797 3798
            virBufferVSprintf(buf, "      <source mode='bind' service='%s'/>\n",
                              dev->srcData.udp.bindService);
3799 3800 3801 3802
        }

        if (dev->srcData.udp.connectService[0] != '\0' &&
            dev->srcData.udp.connectHost[0] != '\0') {
3803 3804 3805
            virBufferVSprintf(buf, "      <source mode='connect' host='%s' service='%s'/>\n",
                              dev->srcData.udp.connectHost,
                              dev->srcData.udp.connectService);
3806
        } else if (dev->srcData.udp.connectHost[0] != '\0') {
3807 3808
            virBufferVSprintf(buf, "      <source mode='connect' host='%s'/>\n",
                              dev->srcData.udp.connectHost);
3809
        } else if (dev->srcData.udp.connectService[0] != '\0') {
3810 3811
            virBufferVSprintf(buf, "      <source mode='connect' service='%s'/>\n",
                              dev->srcData.udp.connectService);
3812 3813 3814 3815
        }
        break;

    case QEMUD_CHR_SRC_TYPE_TCP:
3816 3817 3818 3819 3820 3821 3822
        virBufferVSprintf(buf, "      <source mode='%s' host='%s' service='%s'/>\n",
                          dev->srcData.tcp.listen ? "bind" : "connect",
                          dev->srcData.tcp.host,
                          dev->srcData.tcp.service);
        virBufferVSprintf(buf, "      <protocol type='%s'/>\n",
                          dev->srcData.tcp.protocol == QEMUD_CHR_SRC_TCP_PROTOCOL_TELNET
                          ? "telnet" : "raw");
3823 3824 3825
        break;

    case QEMUD_CHR_SRC_TYPE_UNIX:
3826 3827 3828
        virBufferVSprintf(buf, "      <source mode='%s' path='%s'/>\n",
                          dev->srcData.nix.listen ? "bind" : "connect",
                          dev->srcData.nix.path);
3829 3830 3831
        break;
    }

3832 3833
    virBufferVSprintf(buf, "      <target port='%d'/>\n",
                      dev->dstPort);
3834

3835 3836
    virBufferVSprintf(buf, "    </%s>\n",
                      type);
3837 3838 3839 3840 3841

    return 0;
}


D
Daniel P. Berrange 已提交
3842
/* Generate an XML document describing the guest's configuration */
3843 3844
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
3845 3846 3847
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
3848
    virBuffer buf = VIR_BUFFER_INITIALIZER;
D
Daniel P. Berrange 已提交
3849
    unsigned char *uuid;
3850
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3851 3852 3853
    const struct qemud_vm_disk_def *disk;
    const struct qemud_vm_net_def *net;
    const struct qemud_vm_input_def *input;
D
Daniel Veillard 已提交
3854
    const struct qemud_vm_sound_def *sound;
3855
    const struct qemud_vm_chr_def *chr;
3856
    const char *type = NULL, *tmp;
3857
    int n, allones = 1;
D
Daniel P. Berrange 已提交
3858

3859
    if (!(type = qemudVirtTypeToString(def->virtType))) {
3860 3861
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unexpected domain type %d"), def->virtType);
D
Daniel P. Berrange 已提交
3862 3863 3864
        goto cleanup;
    }

3865 3866 3867 3868
    if (qemudIsActiveVM(vm) && live)
        virBufferVSprintf(&buf, "<domain type='%s' id='%d'>\n", type, vm->id);
    else
        virBufferVSprintf(&buf, "<domain type='%s'>\n", type);
D
Daniel P. Berrange 已提交
3869

3870
    virBufferVSprintf(&buf, "  <name>%s</name>\n", def->name);
D
Daniel P. Berrange 已提交
3871

3872
    uuid = def->uuid;
3873
    virUUIDFormat(uuid, uuidstr);
3874
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
D
Daniel P. Berrange 已提交
3875

3876 3877
    virBufferVSprintf(&buf, "  <memory>%lu</memory>\n", def->maxmem);
    virBufferVSprintf(&buf, "  <currentMemory>%lu</currentMemory>\n", def->memory);
3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892

    for (n = 0 ; n < QEMUD_CPUMASK_LEN ; n++)
        if (def->cpumask[n] != 1)
            allones = 0;

    if (allones) {
        virBufferVSprintf(&buf, "  <vcpu>%d</vcpu>\n", def->vcpus);
    } else {
        char *cpumask = NULL;
        if ((cpumask = virSaveCpuSet(conn, def->cpumask, QEMUD_CPUMASK_LEN)) == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                             "%s", _("allocating cpu mask"));
            goto cleanup;
        }
        virBufferVSprintf(&buf, "  <vcpu cpuset='%s'>%d</vcpu>\n", cpumask, def->vcpus);
3893
        VIR_FREE(cpumask);
3894 3895
    }

D
Daniel P. Berrange 已提交
3896 3897
    if (def->os.bootloader[0])
        virBufferVSprintf(&buf, "  <bootloader>%s</bootloader>\n", def->os.bootloader);
3898
    virBufferAddLit(&buf, "  <os>\n");
D
Daniel P. Berrange 已提交
3899

3900 3901 3902 3903 3904
    if (def->virtType == QEMUD_VIRT_QEMU)
        virBufferVSprintf(&buf, "    <type arch='%s' machine='%s'>%s</type>\n",
                          def->os.arch, def->os.machine, def->os.type);
    else
        virBufferVSprintf(&buf, "    <type>%s</type>\n", def->os.type);
D
Daniel P. Berrange 已提交
3905

D
Daniel P. Berrange 已提交
3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931
    if (!def->os.bootloader[0]) {
        if (def->os.kernel[0])
            virBufferVSprintf(&buf, "    <kernel>%s</kernel>\n", def->os.kernel);
        if (def->os.initrd[0])
            virBufferVSprintf(&buf, "    <initrd>%s</initrd>\n", def->os.initrd);
        if (def->os.cmdline[0])
            virBufferVSprintf(&buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline);

        for (n = 0 ; n < def->os.nBootDevs ; n++) {
            const char *boottype = "hd";
            switch (def->os.bootDevs[n]) {
            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:
                boottype = "network";
                break;
            }
            virBufferVSprintf(&buf, "    <boot dev='%s'/>\n", boottype);
        }
D
Daniel P. Berrange 已提交
3932 3933
    }

3934
    virBufferAddLit(&buf, "  </os>\n");
D
Daniel P. Berrange 已提交
3935

3936
    if (def->features & QEMUD_FEATURE_ACPI) {
3937 3938 3939
        virBufferAddLit(&buf, "  <features>\n");
        virBufferAddLit(&buf, "    <acpi/>\n");
        virBufferAddLit(&buf, "  </features>\n");
3940 3941
    }

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

3944 3945 3946 3947 3948
    virBufferAddLit(&buf, "  <on_poweroff>destroy</on_poweroff>\n");
    if (def->noReboot)
        virBufferAddLit(&buf, "  <on_reboot>destroy</on_reboot>\n");
    else
        virBufferAddLit(&buf, "  <on_reboot>restart</on_reboot>\n");
3949

3950 3951
    virBufferAddLit(&buf, "  <on_crash>destroy</on_crash>\n");
    virBufferAddLit(&buf, "  <devices>\n");
D
Daniel P. Berrange 已提交
3952

3953
    virBufferVSprintf(&buf, "    <emulator>%s</emulator>\n", def->os.binary);
D
Daniel P. Berrange 已提交
3954

3955
    disk = def->disks;
D
Daniel P. Berrange 已提交
3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
3970 3971
        virBufferVSprintf(&buf, "    <disk type='%s' device='%s'>\n",
                          types[disk->type], devices[disk->device]);
D
Daniel P. Berrange 已提交
3972

3973
        if (disk->src[0])
3974 3975
            virBufferVSprintf(&buf, "      <source %s='%s'/>\n",
                              typeAttrs[disk->type], disk->src);
D
Daniel P. Berrange 已提交
3976

3977 3978
        virBufferVSprintf(&buf, "      <target dev='%s' bus='%s'/>\n",
                          disk->dst, qemudBusIdToName(disk->bus, 0));
D
Daniel P. Berrange 已提交
3979 3980

        if (disk->readonly)
3981
            virBufferAddLit(&buf, "      <readonly/>\n");
D
Daniel P. Berrange 已提交
3982

3983
        virBufferAddLit(&buf, "    </disk>\n");
D
Daniel P. Berrange 已提交
3984 3985 3986 3987

        disk = disk->next;
    }

3988
    net = def->nets;
3989
    while (net) {
D
Daniel P. Berrange 已提交
3990 3991
        const char *types[] = {
            "user",
3992
            "ethernet",
D
Daniel P. Berrange 已提交
3993 3994 3995
            "server",
            "client",
            "mcast",
3996
            "network",
3997
            "bridge",
D
Daniel P. Berrange 已提交
3998
        };
3999 4000
        virBufferVSprintf(&buf, "    <interface type='%s'>\n",
                          types[net->type]);
D
Daniel P. Berrange 已提交
4001

4002 4003 4004
        virBufferVSprintf(&buf, "      <mac address='%02x:%02x:%02x:%02x:%02x:%02x'/>\n",
                          net->mac[0], net->mac[1], net->mac[2],
                          net->mac[3], net->mac[4], net->mac[5]);
D
Daniel P. Berrange 已提交
4005

4006 4007
        switch (net->type) {
        case QEMUD_NET_NETWORK:
4008
            virBufferVSprintf(&buf, "      <source network='%s'/>\n", net->dst.network.name);
4009

4010 4011
            if (net->dst.network.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.network.ifname);
4012
            break;
4013

4014
        case QEMUD_NET_ETHERNET:
4015 4016 4017 4018
            if (net->dst.ethernet.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname);
            if (net->dst.ethernet.script[0] != '\0')
                virBufferVSprintf(&buf, "      <script path='%s'/>\n", net->dst.ethernet.script);
4019 4020 4021
            break;

        case QEMUD_NET_BRIDGE:
4022 4023 4024
            virBufferVSprintf(&buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname);
            if (net->dst.bridge.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname);
4025 4026 4027 4028 4029
            break;

        case QEMUD_NET_SERVER:
        case QEMUD_NET_CLIENT:
        case QEMUD_NET_MCAST:
4030 4031 4032 4033 4034 4035
            if (net->dst.socket.address[0] != '\0')
                virBufferVSprintf(&buf, "      <source address='%s' port='%d'/>\n",
                                  net->dst.socket.address, net->dst.socket.port);
            else
                virBufferVSprintf(&buf, "      <source port='%d'/>\n",
                                  net->dst.socket.port);
4036 4037
        }

4038 4039 4040 4041 4042
        if (net->model && net->model[0] != '\0') {
            virBufferVSprintf(&buf, "      <model type='%s'/>\n",
                              net->model);
        }

4043
        virBufferAddLit(&buf, "    </interface>\n");
D
Daniel P. Berrange 已提交
4044

4045
        net = net->next;
D
Daniel P. Berrange 已提交
4046 4047
    }

4048 4049
    chr = def->serials;
    while (chr) {
4050
        if (qemudGenerateXMLChar(&buf, chr, "serial") < 0)
4051 4052 4053 4054 4055 4056 4057
            goto no_memory;

        chr = chr->next;
    }

    chr = def->parallels;
    while (chr) {
4058
        if (qemudGenerateXMLChar(&buf, chr, "parallel") < 0)
4059 4060 4061 4062 4063 4064 4065
            goto no_memory;

        chr = chr->next;
    }

    /* First serial device is the primary console */
    if (def->nserials > 0 &&
4066
        qemudGenerateXMLChar(&buf, def->serials, "console") < 0)
4067 4068
        goto no_memory;

4069 4070
    input = def->inputs;
    while (input) {
4071
        if (input->bus == QEMU_INPUT_BUS_USB)
4072 4073
            virBufferVSprintf(&buf, "    <input type='%s' bus='usb'/>\n",
                              input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet");
4074 4075 4076 4077
        input = input->next;
    }
    /* If graphics is enable, add implicit mouse */
    if (def->graphicsType != QEMUD_GRAPHICS_NONE)
4078 4079
        virBufferVSprintf(&buf, "    <input type='mouse' bus='%s'/>\n",
                          STREQ(def->os.type, "hvm") ? "ps2" : "xen");
4080

4081 4082
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
4083
        virBufferAddLit(&buf, "    <graphics type='vnc'");
4084

4085 4086 4087
        if (def->vncPort)
            virBufferVSprintf(&buf, " port='%d'",
                              qemudIsActiveVM(vm) && live ? def->vncActivePort : def->vncPort);
4088

4089 4090 4091
        if (def->vncListen[0])
            virBufferVSprintf(&buf, " listen='%s'",
                              def->vncListen);
4092

4093 4094 4095
        if (def->keymap)
            virBufferVSprintf(&buf, " keymap='%s'",
                              def->keymap);
4096

4097
        virBufferAddLit(&buf, "/>\n");
4098 4099 4100
        break;

    case QEMUD_GRAPHICS_SDL:
4101
        virBufferAddLit(&buf, "    <graphics type='sdl'/>\n");
4102 4103 4104 4105 4106 4107 4108
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

D
Daniel Veillard 已提交
4109 4110 4111 4112 4113
    sound = def->sounds;
    while(sound) {
        const char *model = qemudSoundModelToString(sound->model);
        if (!model) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
4114
                             "%s", _("invalid sound model"));
D
Daniel Veillard 已提交
4115 4116 4117 4118 4119 4120
            goto cleanup;
        }
        virBufferVSprintf(&buf, "    <sound model='%s'/>\n", model);
        sound = sound->next;
    }

4121 4122
    virBufferAddLit(&buf, "  </devices>\n");
    virBufferAddLit(&buf, "</domain>\n");
D
Daniel P. Berrange 已提交
4123

4124
    if (virBufferError(&buf))
D
Daniel P. Berrange 已提交
4125 4126
        goto no_memory;

4127
    return virBufferContentAndReset(&buf);
D
Daniel P. Berrange 已提交
4128 4129

 no_memory:
4130 4131
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
D
Daniel P. Berrange 已提交
4132
 cleanup:
4133 4134
    tmp = virBufferContentAndReset(&buf);
    VIR_FREE(tmp);
D
Daniel P. Berrange 已提交
4135 4136 4137 4138
    return NULL;
}


4139 4140
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
4141
                              struct qemud_network *network,
4142
                              struct qemud_network_def *def) {
4143
    virBuffer buf = VIR_BUFFER_INITIALIZER;
4144
    unsigned char *uuid;
4145
    char *tmp;
4146
    char uuidstr[VIR_UUID_STRING_BUFLEN];
4147

4148
    virBufferAddLit(&buf, "<network>\n");
4149

4150
    virBufferVSprintf(&buf, "  <name>%s</name>\n", def->name);
4151

4152
    uuid = def->uuid;
4153
    virUUIDFormat(uuid, uuidstr);
4154
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
4155

4156 4157
    if (def->forward) {
        if (def->forwardDev[0]) {
4158
            virBufferVSprintf(&buf, "  <forward dev='%s' mode='%s'/>\n",
4159
                              def->forwardDev, (def->forwardMode == QEMUD_NET_FORWARD_ROUTE ? "route" : "nat"));
4160
        } else {
4161
            virBufferVSprintf(&buf, "  <forward mode='%s'/>\n", (def->forwardMode == QEMUD_NET_FORWARD_ROUTE ? "route" : "nat"));
4162 4163 4164
        }
    }

4165
    virBufferAddLit(&buf, "  <bridge");
4166
    if (qemudIsActiveNetwork(network)) {
4167
        virBufferVSprintf(&buf, " name='%s'", network->bridge);
4168
    } else if (def->bridge[0]) {
4169
        virBufferVSprintf(&buf, " name='%s'", def->bridge);
4170
    }
4171 4172 4173
    virBufferVSprintf(&buf, " stp='%s' forwardDelay='%d' />\n",
                      def->disableSTP ? "off" : "on",
                      def->forwardDelay);
4174

4175
    if (def->ipAddress[0] || def->netmask[0]) {
4176
        virBufferAddLit(&buf, "  <ip");
4177

4178 4179
        if (def->ipAddress[0])
            virBufferVSprintf(&buf, " address='%s'", def->ipAddress);
4180

4181 4182
        if (def->netmask[0])
            virBufferVSprintf(&buf, " netmask='%s'", def->netmask);
4183

4184
        virBufferAddLit(&buf, ">\n");
4185

4186 4187
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
4188
            virBufferAddLit(&buf, "    <dhcp>\n");
4189
            while (range) {
4190 4191
                virBufferVSprintf(&buf, "      <range start='%s' end='%s' />\n",
                                  range->start, range->end);
4192 4193
                range = range->next;
            }
4194
            virBufferAddLit(&buf, "    </dhcp>\n");
4195 4196
        }

4197
        virBufferAddLit(&buf, "  </ip>\n");
D
Daniel P. Berrange 已提交
4198 4199
    }

4200 4201 4202
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
4203 4204
        goto no_memory;

4205
    return virBufferContentAndReset(&buf);
4206 4207

 no_memory:
4208 4209
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
4210 4211
    tmp = virBufferContentAndReset(&buf);
    VIR_FREE(tmp);
4212 4213 4214 4215
    return NULL;
}


4216 4217
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
4218 4219 4220
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
4221 4222
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("no config file for %s"), name);
D
Daniel P. Berrange 已提交
4223 4224 4225
        return -1;
    }

4226
    if (unlink(configFile) < 0) {
4227 4228
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("cannot remove config for %s"), name);
4229 4230
        return -1;
    }
4231

D
Daniel P. Berrange 已提交
4232 4233 4234
    return 0;
}

4235
#endif /* WITH_QEMU */