qemu_conf.c 137.8 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
#include "libvirt/virterror.h"
D
Daniel P. Berrange 已提交
46

47
#include "qemu_conf.h"
48
#include "uuid.h"
49
#include "buf.h"
D
Daniel P. Berrange 已提交
50
#include "conf.h"
51
#include "util.h"
J
Jim Meyering 已提交
52 53
#include "verify.h"
#include "c-ctype.h"
54

55 56
#define qemudLog(level, msg...) fprintf(stderr, msg)

57 58 59 60 61 62
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 已提交
63
    const char *virerr;
64 65 66 67 68 69 70 71

    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 已提交
72

73
    virerr = __virErrorMsg(code, (errorMessage[0] ? errorMessage : NULL));
74
    __virRaiseError(conn, dom, net, VIR_FROM_QEMU, code, VIR_ERR_ERROR,
D
Daniel Veillard 已提交
75
                    virerr, errorMessage, NULL, -1, -1, virerr, errorMessage);
76 77
}

D
Daniel P. Berrange 已提交
78 79 80 81 82 83 84 85 86
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,
87
                         "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
        return -1;
    }

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

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


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

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

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

    p = virConfGetValue (conf, "vnc_tls_x509_cert_dir");
    CHECK_TYPE ("vnc_tls_x509_cert_dir", VIR_CONF_STRING);
    if (p && p->str) {
        free(driver->vncTLSx509certdir);
        if (!(driver->vncTLSx509certdir = strdup(p->str))) {
            qemudReportError(NULL, NULL, NULL, VIR_ERR_NO_MEMORY,
122
                             "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
            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;
}


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

    return NULL;
}

204

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

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

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

249

D
Daniel P. Berrange 已提交
250 251
/* The list of possible machine types for various architectures,
   as supported by QEMU - taken from 'qemu -M ?' for each arch */
252 253
static const char *const arch_info_hvm_x86_machines[] = {
    "pc", "isapc"
D
Daniel P. Berrange 已提交
254
};
255 256
static const char *const arch_info_hvm_mips_machines[] = {
    "mips"
D
Daniel P. Berrange 已提交
257
};
258 259
static const char *const arch_info_hvm_sparc_machines[] = {
    "sun4m"
D
Daniel P. Berrange 已提交
260
};
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
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 已提交
283 284
};

285
/* Feature flags for the architecture info */
J
Jim Meyering 已提交
286
static const struct qemu_feature_flags const arch_info_i686_flags [] = {
287 288
    { "pae",  1, 0 },
    { "nonpae",  1, 0 },
289 290 291 292
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
};

J
Jim Meyering 已提交
293
static const struct qemu_feature_flags const arch_info_x86_64_flags [] = {
294 295 296 297
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
};

D
Daniel P. Berrange 已提交
298
/* The archicture tables for supported QEMU archs */
299 300 301 302 303 304 305 306 307 308 309 310 311
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 已提交
312 313
};

314 315 316 317 318 319
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 已提交
320

321 322 323 324 325 326
static int
qemudCapsInitGuest(virCapsPtr caps,
                   const char *hostmachine,
                   const struct qemu_arch_info *info,
                   int hvm) {
    virCapsGuestPtr guest;
D
Daniel P. Berrange 已提交
327 328
    int i;

329 330 331 332 333 334 335 336 337
    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 已提交
338

339 340 341 342 343 344 345 346 347 348
    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 已提交
349

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
        /* 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 已提交
379

380 381 382 383 384 385 386
    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 已提交
387 388 389
        }
    }

390
    return 0;
D
Daniel P. Berrange 已提交
391 392
}

393 394 395 396
virCapsPtr qemudCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    int i;
D
Daniel P. Berrange 已提交
397

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422
    /* Really, this never fails - look at the man-page. */
    uname (&utsname);

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

    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 已提交
423 424
    }

425 426 427 428 429
    return caps;

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

432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

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

454 455 456 457 458 459 460 461 462
        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;

463 464 465
        /* Passing -help, rather than relying on no-args which doesn't
           always work */
        execle(qemu, qemu, "-help", (char*)NULL, qemuenv);
466 467 468 469

    cleanup1:
        _exit(-1); /* Just in case */
    } else { /* Parent */
D
Daniel P. Berrange 已提交
470
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
471
        int got = 0, ret = -1;
472 473 474 475 476
        int major, minor, micro;

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

D
Daniel P. Berrange 已提交
477 478 479 480 481 482 483 484 485 486
        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;
487 488 489 490 491 492 493 494 495 496
        }
        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 已提交
497 498
        if (strstr(help, "-no-reboot"))
            *flags |= QEMUD_CMD_FLAG_NO_REBOOT;
499 500 501 502
        if (strstr(help, "-name"))
            *flags |= QEMUD_CMD_FLAG_NAME;
        if (strstr(help, "-drive"))
            *flags |= QEMUD_CMD_FLAG_DRIVE;
503
        if (strstr(help, "boot=on"))
504
            *flags |= QEMUD_CMD_FLAG_DRIVE_BOOT;
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
        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;
            }
521 522 523
            qemudLog(QEMUD_ERR,
                     _("Unexpected exit status from qemu %d pid %lu"),
                     got, (unsigned long)child);
524 525 526 527 528 529
            ret = -1;
        }
        /* Check & log unexpected exit status, but don't fail,
         * as there's really no need to throw an error if we did
         * actually read a valid version number above */
        if (WEXITSTATUS(got) != 1) {
530 531 532
            qemudLog(QEMUD_WARN,
                     _("Unexpected exit status '%d', qemu probably failed"),
                     got);
533 534 535 536 537 538
        }

        return ret;
    }
}

539
int qemudExtractVersion(virConnectPtr conn,
540 541
                        struct qemud_driver *driver) {
    const char *binary;
542
    struct stat sb;
543
    int ignored;
544

545
    if (driver->qemuVersion > 0)
546 547
        return 0;

548 549 550 551
    if ((binary = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                      "hvm",
                                                      "i686",
                                                      "qemu")) == NULL)
552 553
        return -1;

554
    if (stat(binary, &sb) < 0) {
555
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
556
                         _("Cannot find QEMU binary %s: %s"), binary,
557 558 559 560
                         strerror(errno));
        return -1;
    }

561
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &ignored) < 0) {
562 563 564 565 566 567
        return -1;
    }

    return 0;
}

568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
/* 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;
}
583

D
Daniel P. Berrange 已提交
584 585 586 587 588 589 590 591
/* 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 已提交
592 593 594 595 596
    xmlNodePtr cur;
    xmlChar *device = NULL;
    xmlChar *source = NULL;
    xmlChar *target = NULL;
    xmlChar *type = NULL;
597
    xmlChar *bus = NULL;
D
Daniel P. Berrange 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    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");
614

D
Daniel P. Berrange 已提交
615 616 617 618 619
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
620

D
Daniel P. Berrange 已提交
621 622 623 624 625 626 627
                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");
628
                bus = xmlGetProp(cur, BAD_CAST "bus");
D
Daniel P. Berrange 已提交
629 630 631 632 633 634 635 636
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                disk->readonly = 1;
            }
        }
        cur = cur->next;
    }

    if (source == NULL) {
637 638 639 640 641 642 643 644
        /* 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 已提交
645
    }
646

D
Daniel P. Berrange 已提交
647
    if (target == NULL) {
648
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
649 650 651 652
        goto error;
    }

    if (device &&
653 654 655
        STREQ((const char *)device, "floppy") &&
        STRNEQ((const char *)target, "fda") &&
        STRNEQ((const char *)target, "fdb")) {
656 657
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid floppy device name: %s"), target);
D
Daniel P. Berrange 已提交
658 659
        goto error;
    }
660

D
Daniel P. Berrange 已提交
661
    if (device &&
662 663
        STREQ((const char *)device, "cdrom") &&
        STRNEQ((const char *)target, "hdc")) {
664 665
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid cdrom device name: %s"), target);
D
Daniel P. Berrange 已提交
666 667 668 669
        goto error;
    }

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

673 674 675
    if ((!device || STREQ((const char *)device, "disk")) &&
        !STRPREFIX((const char *)target, "hd") &&
        !STRPREFIX((const char *)target, "sd") &&
676 677
        !STRPREFIX((const char *)target, "vd") &&
        !STRPREFIX((const char *)target, "xvd")) {
678 679
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid harddisk device name: %s"), target);
D
Daniel P. Berrange 已提交
680 681 682
        goto error;
    }

683
    strncpy(disk->src, (source ? (const char *) source : "\0"), NAME_MAX-1);
D
Daniel P. Berrange 已提交
684 685 686 687 688 689 690 691
    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;
692
    else if (STREQ((const char *)device, "disk"))
D
Daniel P. Berrange 已提交
693
        disk->device = QEMUD_DISK_DISK;
694
    else if (STREQ((const char *)device, "cdrom"))
D
Daniel P. Berrange 已提交
695
        disk->device = QEMUD_DISK_CDROM;
696
    else if (STREQ((const char *)device, "floppy"))
D
Daniel P. Berrange 已提交
697 698
        disk->device = QEMUD_DISK_FLOPPY;
    else {
699 700
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid device type: %s"), device);
D
Daniel P. Berrange 已提交
701 702 703
        goto error;
    }

704
    if (!bus) {
705
        if (disk->device == QEMUD_DISK_FLOPPY) {
706
            disk->bus = QEMUD_DISK_BUS_FDC;
707 708 709 710 711 712 713 714 715 716 717 718
        } 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;
        }
719 720 721 722 723 724 725 726
    } 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;
727 728
    else if (STREQ((const char *)bus, "xen"))
        disk->bus = QEMUD_DISK_BUS_XEN;
729 730 731 732 733 734 735 736 737 738 739 740 741
    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 已提交
742 743 744
    xmlFree(device);
    xmlFree(target);
    xmlFree(source);
745
    xmlFree(bus);
D
Daniel P. Berrange 已提交
746

D
Daniel P. Berrange 已提交
747
    return 0;
D
Daniel P. Berrange 已提交
748 749

 error:
750
    xmlFree(bus);
751 752 753 754
    xmlFree(type);
    xmlFree(target);
    xmlFree(source);
    xmlFree(device);
D
Daniel P. Berrange 已提交
755
    return -1;
D
Daniel P. Berrange 已提交
756 757
}

758 759 760 761 762 763 764 765 766
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 已提交
767

D
Daniel P. Berrange 已提交
768 769 770 771 772 773 774 775
/* 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 已提交
776 777 778
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
779
    xmlChar *network = NULL;
780 781 782 783 784
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
785
    xmlChar *model = NULL;
D
Daniel P. Berrange 已提交
786 787 788 789 790 791 792

    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;
793 794
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
795 796 797 798 799 800
        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;
801 802
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
803 804
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
805 806 807 808 809 810 811 812 813 814 815 816
        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");
817 818 819 820
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
821 822 823
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
824
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
825 826 827 828 829 830 831 832 833 834 835 836 837
            } 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");
838
                if (STRPREFIX((const char*)ifname, "vnet")) {
839 840 841 842
                    /* An auto-generated target name, blank it out */
                    xmlFree(ifname);
                    ifname = NULL;
                }
843 844 845 846
            } else if ((script == NULL) &&
                       (net->type == QEMUD_NET_ETHERNET) &&
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = xmlGetProp(cur, BAD_CAST "path");
847 848
            } else if (xmlStrEqual (cur->name, BAD_CAST "model")) {
                model = xmlGetProp (cur, BAD_CAST "type");
D
Daniel P. Berrange 已提交
849 850 851 852 853 854
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
855
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
856
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
857 858 859 860 861 862 863 864 865 866 867 868
               (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 已提交
869 870

        xmlFree(macaddr);
871 872 873
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
874 875
    }

876 877 878 879
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
880
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
881
                             "%s", _("No <source> 'network' attribute specified with <interface type='network'/>"));
882
            goto error;
883
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
884
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
885
                             _("Network name '%s' too long"), network);
886 887 888 889 890 891
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

892
        if (network) {
893
            xmlFree(network);
894 895 896 897 898
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
899
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
900 901
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
902 903 904 905 906 907 908 909 910 911
                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;
912

913 914
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
915
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
916
                                 _("TAP script path '%s' is too long"), script);
917 918 919 920 921 922 923 924 925 926
                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)) {
927
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
928 929
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
930 931
                goto error;
            } else {
932 933
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
934
            }
935 936 937 938 939 940
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
941
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
942
                             "%s", _("No <source> 'dev' attribute specified with <interface type='bridge'/>"));
943 944
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
945
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
946
                             _("TAP bridge path '%s' is too long"), bridge);
947 948 949 950
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
951
        }
952 953 954 955 956 957

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
958
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
959
                                 _("TAP interface name '%s' is too long"), ifname);
960 961 962 963 964 965 966 967 968 969
                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) {
970
        int len = 0;
971 972 973
        char *ret;

        if (port == NULL) {
974
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
975
                             "%s", _("No <source> 'port' attribute specified with socket interface"));
976 977 978 979
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
980
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
981
                             "%s", _("Cannot parse <source> 'port' attribute with socket interface"));
982 983 984 985 986 987 988 989
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
990
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
991
                                 "%s", _("No <source> 'address' attribute specified with socket interface"));
992 993 994
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
995
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
996
                             _("IP address '%s' is too long"), address);
997 998 999 1000 1001 1002 1003 1004 1005
            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);
1006 1007
    }

1008 1009 1010 1011 1012 1013
    /* 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 已提交
1014
        int i, len;
1015 1016 1017 1018 1019 1020 1021 1022

        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 已提交
1023
            int char_ok = c_isalnum(model[i]) || model[i] == '_';
1024
            if (!char_ok) {
1025
                qemudReportError (conn, NULL, NULL, VIR_ERR_INVALID_ARG, "%s",
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
                                  _("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 已提交
1038
    return 0;
1039 1040

 error:
1041 1042 1043 1044 1045 1046
    xmlFree(network);
    xmlFree(address);
    xmlFree(port);
    xmlFree(ifname);
    xmlFree(script);
    xmlFree(bridge);
1047
    xmlFree(model);
D
Daniel P. Berrange 已提交
1048
    return -1;
D
Daniel P. Berrange 已提交
1049 1050 1051
}


1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 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
/* 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++) {
            struct qemud_vm_chr_def *chr = calloc(1, sizeof(*chr));
            if (!chr) {
                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) {
                free(chr);
                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;
}


1379
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
1380
static int qemudParseInputXML(virConnectPtr conn,
1381
                              const struct qemud_vm_def *vm,
D
Daniel P. Berrange 已提交
1382 1383
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
1384 1385 1386 1387 1388 1389 1390
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

    if (!type) {
1391 1392
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing input device type"));
1393 1394 1395
        goto error;
    }

1396
    if (STREQ((const char *)type, "mouse")) {
1397
        input->type = QEMU_INPUT_TYPE_MOUSE;
1398
    } else if (STREQ((const char *)type, "tablet")) {
1399 1400
        input->type = QEMU_INPUT_TYPE_TABLET;
    } else {
1401 1402 1403
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unsupported input device type %s"),
                         (const char*)type);
1404 1405 1406 1407
        goto error;
    }

    if (bus) {
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
        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 {
1420
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1421
                                 _("unsupported input bus %s"), (const char*)bus);
1422 1423 1424
                goto error;
            }
        } else {
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437
            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;
            }
1438 1439
        }
    } else {
D
Daniel P. Berrange 已提交
1440
        if (STREQ(vm->os.type, "hvm")) {
1441 1442 1443 1444 1445 1446 1447
            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;
        }
1448 1449
    }

1450 1451
    xmlFree(type);
    xmlFree(bus);
1452

D
Daniel P. Berrange 已提交
1453
    return 0;
1454 1455

 error:
1456 1457
    xmlFree(type);
    xmlFree(bus);
1458

D
Daniel P. Berrange 已提交
1459
    return -1;
1460 1461
}

1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
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",
1475 1476
                               "virtio",
                               "xen"};
1477 1478 1479 1480 1481
    verify_true(ARRAY_CARDINALITY(busnames) == QEMUD_DISK_BUS_LAST);

    return busnames[busId];
}

D
Daniel Veillard 已提交
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
/* 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 已提交
1534 1535 1536 1537
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
1538 1539
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
1540
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
1541 1542 1543 1544 1545 1546
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
1547 1548
    struct qemud_vm_def *def;

1549
    if (!(def = calloc(1, sizeof(*def)))) {
1550 1551
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
1552 1553
        return NULL;
    }
D
Daniel P. Berrange 已提交
1554 1555 1556 1557

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
1558 1559
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
D
Daniel P. Berrange 已提交
1560 1561 1562 1563 1564
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1565 1566
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
D
Daniel P. Berrange 已提交
1567 1568 1569 1570 1571 1572
        goto error;
    }


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

1578
    if (STREQ((char *)prop, "qemu"))
1579
        def->virtType = QEMUD_VIRT_QEMU;
1580
    else if (STREQ((char *)prop, "kqemu"))
1581
        def->virtType = QEMUD_VIRT_KQEMU;
1582
    else if (STREQ((char *)prop, "kvm"))
1583
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
1584
    else {
1585 1586
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("invalid domain type attribute"));
D
Daniel P. Berrange 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
        goto error;
    }
    free(prop);
    prop = NULL;


    /* Extract domain name */
    obj = xmlXPathEval(BAD_CAST "string(/domain/name[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1597
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
1598 1599 1600
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1601 1602
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("domain name length too long"));
D
Daniel P. Berrange 已提交
1603 1604
        goto error;
    }
1605
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1606 1607 1608 1609 1610 1611 1612
    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)) {
1613
        int err;
D
Daniel P. Berrange 已提交
1614
        if ((err = virUUIDGenerate(def->uuid))) {
1615
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1616
                             _("Failed to generate UUID: %s"), strerror(err));
1617 1618
            goto error;
        }
D
Daniel P. Berrange 已提交
1619
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
1620 1621
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
D
Daniel P. Berrange 已提交
1622 1623 1624 1625 1626 1627 1628 1629 1630
        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)) {
1631 1632
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing memory element"));
D
Daniel P. Berrange 已提交
1633 1634 1635
        goto error;
    } else {
        conv = NULL;
1636
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1637
        if (conv == (const char*)obj->stringval) {
1638 1639
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1640 1641 1642
            goto error;
        }
    }
1643
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1644 1645 1646 1647 1648 1649


    /* 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)) {
1650
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1651 1652
    } else {
        conv = NULL;
1653 1654 1655
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1656
        if (conv == (const char*)obj->stringval) {
1657 1658
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1659 1660 1661
            goto error;
        }
    }
1662
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1663 1664 1665 1666 1667

    /* 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)) {
1668
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1669 1670
    } else {
        conv = NULL;
1671
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1672
        if (conv == (const char*)obj->stringval) {
1673 1674
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed vcpu information"));
D
Daniel P. Berrange 已提交
1675 1676 1677
            goto error;
        }
    }
1678
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1679 1680 1681 1682 1683

    /* 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)) {
1684
        def->features |= QEMUD_FEATURE_ACPI;
D
Daniel P. Berrange 已提交
1685
    }
1686
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1687

D
Daniel P. Berrange 已提交
1688 1689 1690 1691 1692 1693 1694

    /* 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 {
1695
        if (STREQ((char*)obj->stringval, "destroy"))
D
Daniel P. Berrange 已提交
1696 1697 1698 1699
            def->noReboot = 1;
        else
            def->noReboot = 0;
    }
1700
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1701

1702 1703 1704 1705 1706 1707
    /* 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 {
1708
        if (STREQ((char*)obj->stringval, "localtime"))
1709 1710 1711 1712
            def->localtime = 1;
        else
            def->localtime = 0;
    }
1713
    xmlXPathFreeObject(obj);
1714

D
Daniel P. Berrange 已提交
1715

D
Daniel P. Berrange 已提交
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
    /* 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 已提交
1726
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1727

D
Daniel P. Berrange 已提交
1728 1729 1730 1731
    /* 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 已提交
1732 1733 1734 1735 1736 1737 1738
        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 已提交
1739
    }
J
Jim Meyering 已提交
1740 1741
    xmlXPathFreeObject(obj);
    obj = NULL;
D
Daniel P. Berrange 已提交
1742 1743

    if (!virCapabilitiesSupportsGuestOSType(driver->caps, def->os.type)) {
1744
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
D
Daniel P. Berrange 已提交
1745
                         "%s", def->os.type);
D
Daniel P. Berrange 已提交
1746 1747 1748 1749 1750 1751
        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)) {
1752 1753
        const char *defaultArch = virCapabilitiesDefaultGuestArch(driver->caps, def->os.type);
        if (defaultArch == NULL) {
1754 1755
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1756 1757
            goto error;
        }
D
Daniel P. Berrange 已提交
1758
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1759 1760
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1761 1762
            goto error;
        }
1763
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
1764 1765
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1766 1767
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1768 1769
            goto error;
        }
1770
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1771
    }
1772
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1773 1774 1775 1776

    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)) {
1777 1778 1779 1780
        const char *defaultMachine = virCapabilitiesDefaultGuestMachine(driver->caps,
                                                                        def->os.type,
                                                                        def->os.arch);
        if (defaultMachine == NULL) {
1781 1782
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1783 1784
            goto error;
        }
D
Daniel P. Berrange 已提交
1785
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1786 1787
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("machine type too long"));
D
Daniel P. Berrange 已提交
1788 1789
            goto error;
        }
1790
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1791 1792
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1793 1794
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1795 1796
            goto error;
        }
1797
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1798
    }
1799
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1800 1801


D
Daniel P. Berrange 已提交
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
    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 已提交
1812
        }
D
Daniel P. Berrange 已提交
1813
        xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1814 1815


D
Daniel P. Berrange 已提交
1816 1817 1818 1819 1820 1821 1822 1823 1824
        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 已提交
1825
        }
D
Daniel P. Berrange 已提交
1826
        xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1827 1828


D
Daniel P. Berrange 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837
        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 已提交
1838
        }
D
Daniel P. Berrange 已提交
1839
        xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1840 1841


D
Daniel P. Berrange 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
        /* 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 已提交
1864 1865
            }
        }
D
Daniel P. Berrange 已提交
1866 1867 1868 1869 1870
        xmlXPathFreeObject(obj);
        if (def->os.nBootDevs == 0) {
            def->os.nBootDevs = 1;
            def->os.bootDevs[0] = QEMUD_BOOT_DISK;
        }
D
Daniel P. Berrange 已提交
1871 1872 1873 1874 1875
    }

    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1876 1877 1878 1879 1880 1881
        const char *type = qemudVirtTypeToString(def->virtType);
        if (!type) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unknown virt type"));
            goto error;
        }
1882 1883 1884 1885 1886
        const char *emulator = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                                   def->os.type,
                                                                   def->os.arch,
                                                                   type);
        if (!emulator) {
1887 1888
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported guest type"));
D
Daniel P. Berrange 已提交
1889 1890
            goto error;
        }
1891
        strcpy(def->os.binary, emulator);
D
Daniel P. Berrange 已提交
1892 1893
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1894 1895
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("emulator path too long"));
D
Daniel P. Berrange 已提交
1896 1897
            goto error;
        }
1898
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1899
    }
1900
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1901 1902 1903 1904

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1905
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1906
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
1907
        if (STREQ((char *)prop, "vnc")) {
1908
            xmlChar *vncport, *vnclisten;
1909
            def->graphicsType = QEMUD_GRAPHICS_VNC;
1910 1911
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
1912
                conv = NULL;
1913
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
1914
            } else {
1915
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1916
            }
1917 1918 1919 1920
            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 已提交
1921
                strcpy(def->vncListen, driver->vncListen);
1922
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
1923
            def->keymap = (char *) xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "keymap");
1924 1925
            xmlFree(vncport);
            xmlFree(vnclisten);
1926
        } else if (STREQ((char *)prop, "sdl")) {
1927
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1928
        } else {
1929 1930
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Unsupported graphics type %s"), prop);
D
Daniel P. Berrange 已提交
1931 1932
            goto error;
        }
1933
        xmlFree(prop);
1934
        prop = NULL;
D
Daniel P. Berrange 已提交
1935
    }
1936
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1937 1938 1939 1940 1941 1942

    /* 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++) {
1943
            struct qemud_vm_disk_def *disk = calloc(1, sizeof(*disk));
D
Daniel P. Berrange 已提交
1944
            if (!disk) {
1945 1946
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for disk string"));
D
Daniel P. Berrange 已提交
1947 1948 1949 1950
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
                free(disk);
D
Daniel P. Berrange 已提交
1951 1952
                goto error;
            }
1953
            def->ndisks++;
1954
            if (i == 0) {
1955
                disk->next = NULL;
1956 1957
                def->disks = disk;
            } else {
1958 1959 1960 1961 1962 1963 1964 1965 1966
                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;
                }
1967
            }
D
Daniel P. Berrange 已提交
1968 1969 1970
        }
    }
    xmlXPathFreeObject(obj);
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    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)) {
            struct qemud_vm_chr_def *chr = calloc(1, sizeof(*chr));
            if (!chr) {
                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) {
                free(chr);
                goto error;
            }
            def->nserials = 1;
            def->serials = chr;
        }
        xmlXPathFreeObject(obj);
    }
D
Daniel P. Berrange 已提交
2010 2011 2012 2013 2014 2015


    /* 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)) {
2016
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
2017
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
2018
            struct qemud_vm_net_def *net = calloc(1, sizeof(*net));
D
Daniel P. Berrange 已提交
2019
            if (!net) {
2020 2021
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for net string"));
D
Daniel P. Berrange 已提交
2022 2023 2024 2025
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
                free(net);
D
Daniel P. Berrange 已提交
2026 2027
                goto error;
            }
2028
            def->nnets++;
2029 2030 2031 2032 2033 2034 2035
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
2036 2037 2038
        }
    }
    xmlXPathFreeObject(obj);
2039 2040 2041 2042 2043 2044 2045

    /* 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++) {
2046
            struct qemud_vm_input_def *input = calloc(1, sizeof(*input));
D
Daniel P. Berrange 已提交
2047
            if (!input) {
2048 2049
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
D
Daniel P. Berrange 已提交
2050 2051
                goto error;
            }
2052
            if (qemudParseInputXML(conn, def, input, obj->nodesetval->nodeTab[i]) < 0) {
D
Daniel P. Berrange 已提交
2053
                free(input);
2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
                goto error;
            }
            /* Mouse + PS/2 is implicit with graphics, so don't store it */
            if (input->bus == QEMU_INPUT_BUS_PS2 &&
                input->type == QEMU_INPUT_TYPE_MOUSE) {
                free(input);
                continue;
            }
            def->ninputs++;
            input->next = NULL;
2064
            if (def->inputs == NULL) {
2065 2066 2067 2068 2069 2070 2071 2072
                def->inputs = input;
            } else {
                prev->next = input;
            }
            prev = input;
        }
    }
    xmlXPathFreeObject(obj);
D
Daniel Veillard 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116

    /* 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++) {

            struct qemud_vm_sound_def *sound = calloc(1, sizeof(*sound));
            struct qemud_vm_sound_def *check = def->sounds;
            int collision = 0;
            if (!sound) {
                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) {
                free(sound);
                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;
            }
            if (collision)
                continue;

            def->nsounds++;
            sound->next = NULL;
            if (def->sounds == NULL) {
                def->sounds = sound;
            } else {
                prev->next = sound;
            }
            prev = sound;
        }
    }
    xmlXPathFreeObject(obj);
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130
    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) {
2131
            input = calloc(1, sizeof(*input));
2132
            if (!input) {
2133 2134
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
                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 已提交
2145 2146
    xmlXPathFreeContext(ctxt);

2147
    return def;
D
Daniel P. Berrange 已提交
2148 2149

 error:
2150
    free(prop);
2151
    xmlXPathFreeObject(obj);
2152
    xmlXPathFreeContext(ctxt);
2153 2154
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
2155 2156 2157
}


2158
static char *
2159 2160
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
2161
                         struct qemud_vm *vm,
2162 2163
                         struct qemud_vm_net_def *net,
                         int vlan)
2164
{
2165 2166 2167
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
2168 2169 2170 2171 2172 2173
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

2174
    if (net->type == QEMUD_NET_NETWORK) {
2175
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
2176
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2177 2178
                             _("Network '%s' not found"),
                             net->dst.network.name);
2179 2180
            goto error;
        } else if (network->bridge[0] == '\0') {
2181
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2182 2183
                             _("Network '%s' not active"),
                             net->dst.network.name);
2184 2185 2186 2187
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
2188
            STRPREFIX(net->dst.network.ifname, "vnet") ||
2189 2190 2191 2192 2193 2194 2195
            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' ||
2196
            STRPREFIX(net->dst.bridge.ifname, "vnet") ||
2197 2198 2199 2200 2201
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
2202
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2203
                         _("Network type %d is not supported"), net->type);
2204 2205 2206
        goto error;
    }

2207
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
2208
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2209 2210
                         _("cannot initialize bridge support: %s"),
                         strerror(err));
2211 2212 2213
        goto error;
    }

2214
    if ((err = brAddTap(driver->brctl, brname,
2215
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
2216
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2217
                     _("Failed to add tap interface '%s' to bridge '%s' : %s"),
2218
                         ifname, brname, strerror(err));
2219 2220 2221
        goto error;
    }

2222 2223 2224
    snprintf(tapfdstr, sizeof(tapfdstr),
             "tap,fd=%d,script=,vlan=%d,ifname=%s",
             tapfd, vlan, ifname);
2225 2226 2227 2228

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

2229
    if (!(tapfds = realloc(vm->tapfds, sizeof(*tapfds) * (vm->ntapfds+2))))
2230 2231 2232 2233 2234 2235 2236 2237 2238
        goto no_memory;

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

    return retval;

 no_memory:
2239 2240
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for tapfds string"));
2241
 error:
2242
    free(retval);
2243 2244 2245 2246 2247
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
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 已提交
2320 2321 2322 2323
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
2324 2325
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
2326
                          struct qemud_vm *vm,
2327 2328
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
2329 2330 2331
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
2332 2333
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
2334
    struct qemud_vm_input_def *input = vm->def->inputs;
D
Daniel Veillard 已提交
2335
    struct qemud_vm_sound_def *sound = vm->def->sounds;
2336 2337
    struct qemud_vm_chr_def *serial = vm->def->serials;
    struct qemud_vm_chr_def *parallel = vm->def->parallels;
2338 2339
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
2340

2341 2342 2343 2344 2345 2346
    if (vm->qemuVersion == 0) {
        if (qemudExtractVersionInfo(vm->def->os.binary,
                                    &(vm->qemuVersion),
                                    &(vm->qemuCmdFlags)) < 0)
            return -1;
    }
2347

2348 2349
    uname(&ut);

D
Daniel P. Berrange 已提交
2350
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
2351 2352 2353 2354
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
2355
        ut.machine[1] = '6';
2356 2357 2358 2359 2360 2361

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

2367
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
2368
        2 + /* machine type */
2369
        disableKQEMU + /* Disable kqemu */
2370
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NAME ? 2 : 0) + /* -name XXX */
2371 2372
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
2373 2374
        1 + /* usb */
        2 * vm->def->ninputs + /* input devices */
D
Daniel Veillard 已提交
2375
        ((vm->def->nsounds > 0) ? 2 : 0) + /* sound */
2376 2377
        (vm->def->nserials > 0 ? (2 * vm->def->nserials) : 2) + /* character devices */
        (vm->def->nparallels > 0 ? (2 * vm->def->nparallels) : 2) + /* character devices */
D
Daniel P. Berrange 已提交
2378 2379 2380 2381
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
2382
        (vm->def->localtime ? 1 : 0) + /* localtime */
2383
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
2384
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
2385 2386 2387 2388
        (vm->def->features & QEMUD_FEATURE_ACPI ? 0 : 1) + /* acpi */
        (vm->def->os.kernel[0] ? 2 : 0) + /* kernel */
        (vm->def->os.initrd[0] ? 2 : 0) + /* initrd */
        (vm->def->os.cmdline[0] ? 2 : 0) + /* cmdline */
D
Daniel P. Berrange 已提交
2389
        (vm->def->os.bootloader[0] ? 2 : 0) + /* bootloader */
2390
        (vm->def->graphicsType == QEMUD_GRAPHICS_VNC ? 2 :
2391 2392
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)) + /* graphics */
        (vm->migrateFrom[0] ? 3 : 0); /* migrateFrom */
D
Daniel P. Berrange 已提交
2393

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

2397
    if (!(*argv = calloc(len+1, sizeof(**argv))))
D
Daniel P. Berrange 已提交
2398
        goto no_memory;
2399
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
2400 2401 2402
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
2403
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
2404
        goto no_memory;
2405
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
2406
        if (!((*argv)[++n] = strdup("-no-kqemu")))
2407
            goto no_memory;
D
Daniel P. Berrange 已提交
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
    }
    if (!((*argv)[++n] = strdup("-m")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(memory)))
        goto no_memory;
    if (!((*argv)[++n] = strdup("-smp")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(vcpus)))
        goto no_memory;

2418 2419 2420 2421 2422 2423
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NAME) {
        if (!((*argv)[++n] = strdup("-name")))
            goto no_memory;
        if (!((*argv)[++n] = strdup(vm->def->name)))
            goto no_memory;
    }
2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
    /*
     * NB, -nographic *MUST* come before any serial, or monitor
     * or parallel port flags due to QEMU craziness, where it
     * decides to change the serial port & monitor to be on stdout
     * if you ask for nographic. So we have to make sure we override
     * these defaults ourselves...
     */
    if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
        if (!((*argv)[++n] = strdup("-nographic")))
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
2436 2437 2438 2439 2440
    if (!((*argv)[++n] = strdup("-monitor")))
        goto no_memory;
    if (!((*argv)[++n] = strdup("pty")))
        goto no_memory;

2441 2442 2443 2444 2445
    if (vm->def->localtime) {
        if (!((*argv)[++n] = strdup("-localtime")))
            goto no_memory;
    }

2446
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
2447 2448 2449 2450 2451
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

2452
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
2453 2454
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
2455 2456
    }

D
Daniel P. Berrange 已提交
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
    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';
        if (!((*argv)[++n] = strdup("-boot")))
D
Daniel P. Berrange 已提交
2479
            goto no_memory;
D
Daniel P. Berrange 已提交
2480
        if (!((*argv)[++n] = strdup(boot)))
D
Daniel P. Berrange 已提交
2481
            goto no_memory;
D
Daniel P. Berrange 已提交
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502

        if (vm->def->os.kernel[0]) {
            if (!((*argv)[++n] = strdup("-kernel")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
                goto no_memory;
        }
        if (vm->def->os.initrd[0]) {
            if (!((*argv)[++n] = strdup("-initrd")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
                goto no_memory;
        }
        if (vm->def->os.cmdline[0]) {
            if (!((*argv)[++n] = strdup("-append")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
                goto no_memory;
        }
    } else {
        if (!((*argv)[++n] = strdup("-bootloader")))
D
Daniel P. Berrange 已提交
2503
            goto no_memory;
D
Daniel P. Berrange 已提交
2504
        if (!((*argv)[++n] = strdup(vm->def->os.bootloader)))
D
Daniel P. Berrange 已提交
2505 2506 2507
            goto no_memory;
    }

2508
    /* If QEMU supports -drive param instead of old -hda, -hdb, -cdrom .. */
2509
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
2510 2511 2512
        int bootCD = 0, bootFloppy = 0, bootDisk = 0;

        /* If QEMU supports boot=on for -drive param... */
2513
        if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE_BOOT) {
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
            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;
                }
2526
            }
2527
        }
D
Daniel P. Berrange 已提交
2528

2529 2530 2531 2532 2533 2534 2535
        while (disk) {
            char opt[PATH_MAX];
            const char *media = NULL;
            int bootable = 0;
            int idx = virDiskNameToIndex(disk->dst);
            if (!((*argv)[++n] = strdup("-drive")))
                goto no_memory;
D
Daniel P. Berrange 已提交
2536

2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603
            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" : "");

            if (!((*argv)[++n] = strdup(opt)))
                goto no_memory;
            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);

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

            disk = disk->next;
        }
D
Daniel P. Berrange 已提交
2604 2605 2606 2607 2608 2609 2610 2611
    }

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

2616 2617
            if (snprintf(nic, sizeof(nic),
                         "nic,macaddr=%02x:%02x:%02x:%02x:%02x:%02x,vlan=%d%s%s",
2618 2619 2620
                         net->mac[0], net->mac[1],
                         net->mac[2], net->mac[3],
                         net->mac[4], net->mac[5],
2621 2622
                         vlan,
                         (net->model[0] ? ",model=" : ""), net->model) >= sizeof(nic))
2623
                goto error;
D
Daniel P. Berrange 已提交
2624 2625 2626 2627 2628

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

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

2633 2634 2635
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
2636
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
2637
                    goto error;
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
                break;

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

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

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

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

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

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

            net = net->next;
2696
            vlan++;
D
Daniel P. Berrange 已提交
2697 2698 2699
        }
    }

2700 2701 2702 2703 2704 2705 2706 2707 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 2735 2736 2737 2738 2739 2740 2741
    if (!serial) {
        if (!((*argv)[++n] = strdup("-serial")))
            goto no_memory;
        if (!((*argv)[++n] = strdup("none")))
            goto no_memory;
    } else {
        while (serial) {
            char buf[4096];

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

            if (!((*argv)[++n] = strdup("-serial")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(buf)))
                goto no_memory;

            serial = serial->next;
        }
    }

    if (!parallel) {
        if (!((*argv)[++n] = strdup("-parallel")))
            goto no_memory;
        if (!((*argv)[++n] = strdup("none")))
            goto no_memory;
    } else {
        while (parallel) {
            char buf[4096];

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

            if (!((*argv)[++n] = strdup("-parallel")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(buf)))
                goto no_memory;

            parallel = parallel->next;
        }
    }

2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754
    if (!((*argv)[++n] = strdup("-usb")))
        goto no_memory;
    while (input) {
        if (input->bus == QEMU_INPUT_BUS_USB) {
            if (!((*argv)[++n] = strdup("-usbdevice")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet")))
                goto no_memory;
        }

        input = input->next;
    }

2755
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
2756
        char vncdisplay[PATH_MAX];
2757
        int ret;
D
Daniel P. Berrange 已提交
2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772

        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",
2773
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
2774 2775 2776
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
2777 2778
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
2779
        }
2780
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
2781 2782
            goto error;

D
Daniel P. Berrange 已提交
2783 2784
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
2785
        if (!((*argv)[++n] = strdup(vncdisplay)))
D
Daniel P. Berrange 已提交
2786
            goto no_memory;
2787 2788 2789 2790 2791 2792
        if (vm->def->keymap) {
            if (!((*argv)[++n] = strdup("-k")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->keymap)))
                goto no_memory;
        }
2793
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
2794
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
2795 2796 2797 2798
    } else {
        /* SDL is the default. no args needed */
    }

D
Daniel Veillard 已提交
2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
    /* Add sound hardware */
    if (sound) {
        int size = 100;
        char *modstr = calloc(1, size+1);
        if (!modstr)
            goto no_memory;
        if (!((*argv)[++n] = strdup("-soundhw")))
            goto no_memory;

        while(sound && size > 0) {
            const char *model = qemudSoundModelToString(sound->model);
            if (!model) {
2811 2812 2813
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 "%s", _("invalid sound model"));
                goto error;
D
Daniel Veillard 已提交
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824
            }
            strncat(modstr, model, size);
            size -= strlen(model);
            sound = sound->next;
            if (sound)
               strncat(modstr, ",", size--);
        }
        if (!((*argv)[++n] = modstr))
            goto no_memory;
    }

2825 2826 2827 2828 2829 2830 2831 2832 2833
    if (vm->migrateFrom[0]) {
        if (!((*argv)[++n] = strdup("-S")))
            goto no_memory;
        if (!((*argv)[++n] = strdup("-incoming")))
            goto no_memory;
        if (!((*argv)[++n] = strdup(vm->migrateFrom)))
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
2834 2835 2836 2837 2838
    (*argv)[++n] = NULL;

    return 0;

 no_memory:
2839 2840
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for argv string"));
2841 2842 2843 2844 2845 2846 2847 2848
 error:
    if (vm->tapfds) {
        for (i = 0; vm->tapfds[i] != -1; i++)
            close(vm->tapfds[i]);
        free(vm->tapfds);
        vm->tapfds = NULL;
        vm->ntapfds = 0;
    }
D
Daniel P. Berrange 已提交
2849 2850
    if (argv) {
        for (i = 0 ; i < n ; i++)
2851 2852
            free((*argv)[i]);
        free(*argv);
2853
        *argv = NULL;
D
Daniel P. Berrange 已提交
2854 2855 2856 2857 2858 2859
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
2860 2861
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
2862 2863
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
2864 2865 2866 2867
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

2868
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
2869 2870 2871 2872 2873
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2874
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2875
                         _("cannot create config file %s: %s"),
2876
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2877 2878 2879 2880
        goto cleanup;
    }

    towrite = strlen(xml);
2881
    if (safewrite(fd, xml, towrite) < 0) {
2882
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2883
                         _("cannot write config file %s: %s"),
2884
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2885 2886 2887 2888
        goto cleanup;
    }

    if (close(fd) < 0) {
2889
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2890
                         _("cannot save config file %s: %s"),
2891
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
        goto cleanup;
    }

    ret = 0;

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

    free(xml);

    return ret;
}

D
Daniel P. Berrange 已提交
2906 2907
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
2908
                      const struct qemud_vm_def *def,
D
Daniel P. Berrange 已提交
2909 2910 2911 2912
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
2913
    struct qemud_vm_device_def *dev = calloc(1, sizeof(*dev));
D
Daniel P. Berrange 已提交
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923

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

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
2924 2925
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("missing root element"));
D
Daniel P. Berrange 已提交
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935
        goto error;
    }
    if (xmlStrEqual(node->name, BAD_CAST "disk")) {
        dev->type = QEMUD_DEVICE_DISK;
        qemudParseDiskXML(conn, &(dev->data.disk), node);
    } else if (xmlStrEqual(node->name, BAD_CAST "net")) {
        dev->type = QEMUD_DEVICE_NET;
        qemudParseInterfaceXML(conn, &(dev->data.net), node);
    } else if (xmlStrEqual(node->name, BAD_CAST "input")) {
        dev->type = QEMUD_DEVICE_DISK;
2936
        qemudParseInputXML(conn, def, &(dev->data.input), node);
D
Daniel Veillard 已提交
2937 2938 2939
    } else if (xmlStrEqual(node->name, BAD_CAST "sound")) {
        dev->type = QEMUD_DEVICE_SOUND;
        qemudParseSoundXML(conn, &(dev->data.sound), node);
D
Daniel P. Berrange 已提交
2940
    } else {
2941 2942
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("unknown device type"));
D
Daniel P. Berrange 已提交
2943 2944 2945 2946 2947 2948 2949 2950 2951
        goto error;
    }

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
2952
    free(dev);
D
Daniel P. Berrange 已提交
2953 2954 2955
    return NULL;
}

2956
struct qemud_vm_def *
2957 2958
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
2959 2960
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
2961
    xmlDocPtr xml;
2962
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
2963

2964
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
2965 2966
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2967
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
2968 2969 2970
        return NULL;
    }

2971
    def = qemudParseXML(conn, driver, xml);
2972

D
Daniel P. Berrange 已提交
2973 2974
    xmlFreeDoc(xml);

2975 2976 2977 2978
    return def;
}

struct qemud_vm *
2979 2980
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
2981 2982 2983 2984
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

2985
    if ((vm = qemudFindVMByName(driver, def->name))) {
2986
        if (!qemudIsActiveVM(vm)) {
2987 2988 2989 2990 2991 2992 2993
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
2994 2995 2996
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
2997
        return vm;
D
Daniel P. Berrange 已提交
2998 2999
    }

3000
    if (!(vm = calloc(1, sizeof(*vm)))) {
3001 3002
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for vm string"));
3003 3004
        return NULL;
    }
D
Daniel P. Berrange 已提交
3005

3006
    vm->stdin = -1;
3007 3008 3009 3010 3011
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
3012
    vm->state = VIR_DOMAIN_SHUTOFF;
3013
    vm->def = def;
3014
    vm->next = driver->vms;
3015

3016 3017
    driver->vms = vm;
    driver->ninactivevms++;
3018 3019 3020 3021 3022

    return vm;
}

void
3023
qemudRemoveInactiveVM(struct qemud_driver *driver,
3024 3025 3026 3027
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

3028
    curr = driver->vms;
3029 3030 3031
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
3032 3033
    }

3034 3035 3036 3037
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
3038
            driver->vms = curr->next;
3039

3040
        driver->ninactivevms--;
3041 3042
    }

3043
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
3044 3045
}

3046
int
3047 3048
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
3049 3050 3051 3052 3053
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

3054
        if ((err = virFileMakePath(driver->configDir))) {
3055
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3056
                             _("cannot create config directory %s: %s"),
3057
                             driver->configDir, strerror(err));
3058 3059 3060
            return -1;
        }

3061 3062
        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             vm->configFile, PATH_MAX) < 0) {
3063
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3064
                             "%s", _("cannot construct config file path"));
3065 3066
            return -1;
        }
3067

3068 3069
        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             vm->autostartLink, PATH_MAX) < 0) {
3070
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3071
                             "%s", _("cannot construct autostart link path"));
3072 3073 3074
            vm->configFile[0] = '\0';
            return -1;
        }
3075 3076
    }

3077
    return qemudSaveConfig(conn, driver, vm, def);
3078
}
D
Daniel P. Berrange 已提交
3079

3080 3081
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
3082 3083
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
3084 3085 3086
    char *xml;
    int fd, ret = -1;
    int towrite;
3087
    int err;
3088

3089
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
3090 3091 3092
        return -1;
    }

3093
    if ((err = virFileMakePath(driver->networkConfigDir))) {
3094
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3095
                         _("cannot create config directory %s: %s"),
3096
                         driver->networkConfigDir, strerror(err));
3097 3098 3099 3100 3101 3102
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
3103
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3104
                         _("cannot create config file %s: %s"),
3105
                         network->configFile, strerror(errno));
3106 3107 3108 3109
        goto cleanup;
    }

    towrite = strlen(xml);
3110
    if (safewrite(fd, xml, towrite) < 0) {
3111
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3112
                         _("cannot write config file %s: %s"),
3113
                         network->configFile, strerror(errno));
3114 3115 3116 3117
        goto cleanup;
    }

    if (close(fd) < 0) {
3118
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3119
                         _("cannot save config file %s: %s"),
3120
                         network->configFile, strerror(errno));
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148
void qemudFreeNetworkDef(struct qemud_network_def *def) {
    struct qemud_dhcp_range_def *range = def->ranges;
    while (range) {
        struct qemud_dhcp_range_def *next = range->next;
        free(range);
        range = next;
    }
    free(def);
}

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

3150
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
3151
                               struct qemud_network_def *def,
3152 3153 3154 3155 3156
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
3157 3158
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
3159 3160 3161 3162 3163 3164 3165
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
3166
            def->disableSTP = 1;
3167 3168 3169 3170 3171 3172 3173
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
3174
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
3175 3176 3177 3178 3179 3180 3181
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

3182 3183
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
3184
                                   struct qemud_network_def *def,
3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
                                   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;
        }

3200
        if (!(range = calloc(1, sizeof(*range)))) {
3201 3202
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for range string"));
3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215
            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';

3216 3217 3218
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
3219 3220 3221 3222
        } else {
            free(range);
        }

3223 3224
        xmlFree(start);
        xmlFree(end);
3225 3226 3227 3228 3229 3230

        cur = cur->next;
    }

    return 1;
}
3231

3232 3233
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
3234
                             struct qemud_network_def *def,
3235 3236
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
3237
    xmlNodePtr cur;
3238 3239 3240

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
3241 3242
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
3243 3244 3245 3246 3247 3248
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
3249 3250
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
3251 3252 3253 3254
        xmlFree(netmask);
        netmask = NULL;
    }

3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
    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);
    }

3270 3271 3272 3273
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
3274
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
3275 3276 3277 3278
            return 0;
        cur = cur->next;
    }

3279 3280 3281 3282
    return 1;
}


3283 3284
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
3285
                                                      xmlDocPtr xml) {
3286 3287
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
3288
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
3289 3290
    struct qemud_network_def *def;

3291
    if (!(def = calloc(1, sizeof(*def)))) {
3292 3293
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                   "%s", _("failed to allocate space for network_def string"));
3294 3295
        return NULL;
    }
3296 3297 3298 3299

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
3300 3301
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
3302 3303 3304 3305 3306
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
3307 3308
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
               "%s", _("failed to allocate space for xmlXPathContext string"));
3309 3310 3311 3312 3313 3314 3315 3316
        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)) {
3317
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
3318 3319 3320
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
3321 3322
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("network name length too long"));
3323 3324
        goto error;
    }
3325
    strcpy(def->name, (const char *)obj->stringval);
3326 3327 3328 3329 3330 3331 3332
    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)) {
3333
        int err;
D
Daniel P. Berrange 已提交
3334
        if ((err = virUUIDGenerate(def->uuid))) {
3335
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3336
                             _("Failed to generate UUID: %s"), strerror(err));
3337 3338
            goto error;
        }
D
Daniel P. Berrange 已提交
3339
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
3340 3341
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
3342 3343 3344 3345
        goto error;
    }
    xmlXPathFreeObject(obj);

3346 3347 3348 3349
    /* 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)) {
3350
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
3351 3352 3353 3354 3355 3356 3357 3358 3359
            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)) {
3360
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
3361 3362 3363 3364 3365 3366
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
3367 3368 3369
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
3370 3371
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
3372
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3373
                             "%s", _("Forwarding requested, but no IPv4 address/netmask provided"));
3374 3375 3376
            goto error;
        }

3377
        def->forward = 1;
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388

        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;

3389 3390 3391 3392 3393
        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)) {
3394
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3395
                                 _("forward device name '%s' is too long"),
3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409
                                 (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);

3410 3411
    xmlXPathFreeContext(ctxt);

3412
    return def;
3413 3414 3415 3416

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
3417 3418
    xmlXPathFreeObject(obj);
    xmlXPathFreeObject(tmp);
3419
    xmlXPathFreeContext(ctxt);
3420 3421
    qemudFreeNetworkDef(def);
    return NULL;
3422 3423
}

3424
struct qemud_network_def *
3425 3426
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
3427 3428
                     const char *xmlStr,
                     const char *displayName) {
3429
    xmlDocPtr xml;
3430
    struct qemud_network_def *def;
3431

3432
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
3433 3434
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
3435
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
3436 3437 3438
        return NULL;
    }

3439
    def = qemudParseNetworkXML(conn, driver, xml);
3440

3441 3442
    xmlFreeDoc(xml);

3443 3444 3445 3446
    return def;
}

struct qemud_network *
3447 3448
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
3449 3450 3451
                      struct qemud_network_def *def) {
    struct qemud_network *network;

3452
    if ((network = qemudFindNetworkByName(driver, def->name))) {
3453
        if (!qemudIsActiveNetwork(network)) {
3454 3455 3456 3457 3458 3459 3460 3461
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

3462
        return network;
3463 3464
    }

3465
    if (!(network = calloc(1, sizeof(*network)))) {
3466 3467
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for network string"));
3468 3469
        return NULL;
    }
3470

3471
    network->def = def;
3472
    network->next = driver->networks;
3473

3474 3475
    driver->networks = network;
    driver->ninactivenetworks++;
3476 3477 3478 3479 3480

    return network;
}

void
3481
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
3482 3483 3484 3485
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

3486
    curr = driver->networks;
3487 3488 3489
    while (curr != network) {
        prev = curr;
        curr = curr->next;
3490 3491
    }

3492 3493 3494 3495
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
3496
            driver->networks = curr->next;
3497

3498
        driver->ninactivenetworks--;
3499 3500
    }

3501
    qemudFreeNetwork(network);
3502 3503
}

3504
int
3505 3506
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
3507 3508 3509 3510 3511 3512
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

3513
        if ((err = virFileMakePath(driver->networkConfigDir))) {
3514
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3515
                             _("cannot create config directory %s: %s"),
3516
                             driver->networkConfigDir, strerror(err));
3517 3518 3519
            return -1;
        }

3520 3521
        if (virFileBuildPath(driver->networkConfigDir, def->name, ".xml",
                             network->configFile, PATH_MAX) < 0) {
3522
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3523
                             "%s", _("cannot construct config file path"));
3524 3525
            return -1;
        }
3526

3527 3528
        if (virFileBuildPath(driver->networkAutostartDir, def->name, ".xml",
                             network->autostartLink, PATH_MAX) < 0) {
3529
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3530
                             "%s", _("cannot construct autostart link path"));
3531 3532 3533
            network->configFile[0] = '\0';
            return -1;
        }
3534 3535
    }

3536
    return qemudSaveNetworkConfig(conn, driver, network, def);
3537
}
3538

3539

3540
static struct qemud_vm *
3541
qemudLoadConfig(struct qemud_driver *driver,
3542 3543
                const char *file,
                const char *path,
3544 3545
                const char *xml,
                const char *autostartLink) {
3546 3547 3548
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

3549
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
3550
        virErrorPtr err = virGetLastError();
3551 3552 3553
        qemudLog(QEMUD_WARN, _("Error parsing QEMU guest config '%s' : %s"),
                 path, (err ? err->message :
                        _("BUG: unknown error - please report it\n")));
3554 3555 3556
        return NULL;
    }

3557
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
3558 3559 3560
        qemudLog(QEMUD_WARN,
                 _("QEMU guest config filename '%s'"
                   " does not match guest name '%s'"),
3561 3562 3563 3564 3565
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

3566
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
3567 3568 3569
        qemudLog(QEMUD_WARN,
                 _("Failed to load QEMU guest config '%s': out of memory"),
                 path);
3570 3571 3572 3573 3574 3575 3576
        qemudFreeVMDef(def);
        return NULL;
    }

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

3577 3578 3579
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

3580
    vm->autostart = virFileLinkPointsTo(vm->autostartLink, vm->configFile);
3581

3582 3583 3584 3585
    return vm;
}

static struct qemud_network *
3586
qemudLoadNetworkConfig(struct qemud_driver *driver,
3587 3588
                       const char *file,
                       const char *path,
3589 3590
                       const char *xml,
                       const char *autostartLink) {
3591 3592 3593
    struct qemud_network_def *def;
    struct qemud_network *network;

3594
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
3595
        virErrorPtr err = virGetLastError();
3596
        qemudLog(QEMUD_WARN, _("Error parsing network config '%s' : %s"),
3597
                 path, err->message);
3598 3599 3600
        return NULL;
    }

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

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

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

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

3623
    network->autostart = virFileLinkPointsTo(network->autostartLink, network->configFile);
3624

3625 3626
    return network;
}
D
Daniel P. Berrange 已提交
3627

3628
static
3629
int qemudScanConfigDir(struct qemud_driver *driver,
3630
                       const char *configDir,
3631
                       const char *autostartDir,
3632
                       int isGuest) {
D
Daniel P. Berrange 已提交
3633 3634 3635
    DIR *dir;
    struct dirent *entry;

3636
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
3637 3638
        if (errno == ENOENT)
            return 0;
3639
        qemudLog(QEMUD_ERR, _("Failed to open dir '%s': %s"),
3640
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
3641 3642 3643 3644
        return -1;
    }

    while ((entry = readdir(dir))) {
3645
        char *xml;
3646
        char path[PATH_MAX];
3647
        char autostartLink[PATH_MAX];
3648

D
Daniel P. Berrange 已提交
3649 3650 3651
        if (entry->d_name[0] == '.')
            continue;

3652
        if (!virFileHasSuffix(entry->d_name, ".xml"))
3653 3654
            continue;

3655
        if (virFileBuildPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
3656
            qemudLog(QEMUD_WARN, _("Config filename '%s/%s' is too long"),
3657 3658 3659 3660
                     configDir, entry->d_name);
            continue;
        }

3661 3662 3663
        if (virFileBuildPath(autostartDir, entry->d_name, NULL,
                             autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, _("Autostart link path '%s/%s' is too long"),
3664 3665 3666 3667
                     autostartDir, entry->d_name);
            continue;
        }

3668
        if (virFileReadAll(path, QEMUD_MAX_XML_LEN, &xml) < 0)
D
Daniel P. Berrange 已提交
3669 3670
            continue;

3671
        if (isGuest)
3672
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
3673
        else
3674
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
3675 3676

        free(xml);
D
Daniel P. Berrange 已提交
3677 3678 3679
    }

    closedir(dir);
3680

D
Daniel P. Berrange 已提交
3681 3682 3683
    return 0;
}

3684
/* Scan for all guest and network config files */
3685 3686
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
3687
        return -1;
3688

3689
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
3690 3691 3692
        return -1;

    return 0;
3693
}
D
Daniel P. Berrange 已提交
3694

3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
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"
    };
3711
    verify_true(ARRAY_CARDINALITY(types) == QEMUD_CHR_SRC_TYPE_LAST);
3712 3713 3714 3715 3716

    /* 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') {
3717 3718 3719
        virBufferVSprintf(buf, "    <%s type='%s' tty='%s'>\n",
                          type, types[dev->srcType],
                          dev->srcData.file.path);
3720
    } else {
3721 3722
        virBufferVSprintf(buf, "    <%s type='%s'>\n",
                          type, types[dev->srcType]);
3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
    }

    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]) {
3738 3739
            virBufferVSprintf(buf, "      <source path='%s'/>\n",
                              dev->srcData.file.path);
3740 3741 3742 3743 3744 3745
        }
        break;

    case QEMUD_CHR_SRC_TYPE_UDP:
        if (dev->srcData.udp.bindService[0] != '\0' &&
            dev->srcData.udp.bindHost[0] != '\0') {
3746 3747 3748
            virBufferVSprintf(buf, "      <source mode='bind' host='%s' service='%s'/>\n",
                              dev->srcData.udp.bindHost,
                              dev->srcData.udp.bindService);
3749
        } else if (dev->srcData.udp.bindHost[0] !='\0') {
3750 3751
            virBufferVSprintf(buf, "      <source mode='bind' host='%s'/>\n",
                              dev->srcData.udp.bindHost);
3752
        } else if (dev->srcData.udp.bindService[0] != '\0') {
3753 3754
            virBufferVSprintf(buf, "      <source mode='bind' service='%s'/>\n",
                              dev->srcData.udp.bindService);
3755 3756 3757 3758
        }

        if (dev->srcData.udp.connectService[0] != '\0' &&
            dev->srcData.udp.connectHost[0] != '\0') {
3759 3760 3761
            virBufferVSprintf(buf, "      <source mode='connect' host='%s' service='%s'/>\n",
                              dev->srcData.udp.connectHost,
                              dev->srcData.udp.connectService);
3762
        } else if (dev->srcData.udp.connectHost[0] != '\0') {
3763 3764
            virBufferVSprintf(buf, "      <source mode='connect' host='%s'/>\n",
                              dev->srcData.udp.connectHost);
3765
        } else if (dev->srcData.udp.connectService[0] != '\0') {
3766 3767
            virBufferVSprintf(buf, "      <source mode='connect' service='%s'/>\n",
                              dev->srcData.udp.connectService);
3768 3769 3770 3771
        }
        break;

    case QEMUD_CHR_SRC_TYPE_TCP:
3772 3773 3774 3775 3776 3777 3778
        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");
3779 3780 3781
        break;

    case QEMUD_CHR_SRC_TYPE_UNIX:
3782 3783 3784
        virBufferVSprintf(buf, "      <source mode='%s' path='%s'/>\n",
                          dev->srcData.nix.listen ? "bind" : "connect",
                          dev->srcData.nix.path);
3785 3786 3787
        break;
    }

3788 3789
    virBufferVSprintf(buf, "      <target port='%d'/>\n",
                      dev->dstPort);
3790

3791 3792
    virBufferVSprintf(buf, "    </%s>\n",
                      type);
3793 3794 3795 3796 3797

    return 0;
}


D
Daniel P. Berrange 已提交
3798
/* Generate an XML document describing the guest's configuration */
3799 3800
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
3801 3802 3803
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
3804
    virBuffer buf = VIR_BUFFER_INITIALIZER;
D
Daniel P. Berrange 已提交
3805
    unsigned char *uuid;
3806
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3807 3808 3809
    const struct qemud_vm_disk_def *disk;
    const struct qemud_vm_net_def *net;
    const struct qemud_vm_input_def *input;
D
Daniel Veillard 已提交
3810
    const struct qemud_vm_sound_def *sound;
3811
    const struct qemud_vm_chr_def *chr;
D
Daniel P. Berrange 已提交
3812 3813 3814
    const char *type = NULL;
    int n;

3815
    if (!(type = qemudVirtTypeToString(def->virtType))) {
3816 3817
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unexpected domain type %d"), def->virtType);
D
Daniel P. Berrange 已提交
3818 3819 3820
        goto cleanup;
    }

3821 3822 3823 3824
    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 已提交
3825

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

3828
    uuid = def->uuid;
3829
    virUUIDFormat(uuid, uuidstr);
3830
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
D
Daniel P. Berrange 已提交
3831

3832 3833 3834
    virBufferVSprintf(&buf, "  <memory>%lu</memory>\n", def->maxmem);
    virBufferVSprintf(&buf, "  <currentMemory>%lu</currentMemory>\n", def->memory);
    virBufferVSprintf(&buf, "  <vcpu>%d</vcpu>\n", def->vcpus);
D
Daniel P. Berrange 已提交
3835 3836
    if (def->os.bootloader[0])
        virBufferVSprintf(&buf, "  <bootloader>%s</bootloader>\n", def->os.bootloader);
3837
    virBufferAddLit(&buf, "  <os>\n");
D
Daniel P. Berrange 已提交
3838

3839 3840 3841 3842 3843
    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 已提交
3844

D
Daniel P. Berrange 已提交
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870
    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 已提交
3871 3872
    }

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

3875
    if (def->features & QEMUD_FEATURE_ACPI) {
3876 3877 3878
        virBufferAddLit(&buf, "  <features>\n");
        virBufferAddLit(&buf, "    <acpi/>\n");
        virBufferAddLit(&buf, "  </features>\n");
3879 3880
    }

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

3883 3884 3885 3886 3887
    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");
3888

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

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

3894
    disk = def->disks;
D
Daniel P. Berrange 已提交
3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
3909 3910
        virBufferVSprintf(&buf, "    <disk type='%s' device='%s'>\n",
                          types[disk->type], devices[disk->device]);
D
Daniel P. Berrange 已提交
3911

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

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

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

3922
        virBufferAddLit(&buf, "    </disk>\n");
D
Daniel P. Berrange 已提交
3923 3924 3925 3926

        disk = disk->next;
    }

3927
    net = def->nets;
3928
    while (net) {
D
Daniel P. Berrange 已提交
3929 3930
        const char *types[] = {
            "user",
3931
            "ethernet",
D
Daniel P. Berrange 已提交
3932 3933 3934
            "server",
            "client",
            "mcast",
3935
            "network",
3936
            "bridge",
D
Daniel P. Berrange 已提交
3937
        };
3938 3939
        virBufferVSprintf(&buf, "    <interface type='%s'>\n",
                          types[net->type]);
D
Daniel P. Berrange 已提交
3940

3941 3942 3943
        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 已提交
3944

3945 3946
        switch (net->type) {
        case QEMUD_NET_NETWORK:
3947
            virBufferVSprintf(&buf, "      <source network='%s'/>\n", net->dst.network.name);
3948

3949 3950
            if (net->dst.network.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.network.ifname);
3951
            break;
3952

3953
        case QEMUD_NET_ETHERNET:
3954 3955 3956 3957
            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);
3958 3959 3960
            break;

        case QEMUD_NET_BRIDGE:
3961 3962 3963
            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);
3964 3965 3966 3967 3968
            break;

        case QEMUD_NET_SERVER:
        case QEMUD_NET_CLIENT:
        case QEMUD_NET_MCAST:
3969 3970 3971 3972 3973 3974
            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);
3975 3976
        }

3977 3978 3979 3980 3981
        if (net->model && net->model[0] != '\0') {
            virBufferVSprintf(&buf, "      <model type='%s'/>\n",
                              net->model);
        }

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

3984
        net = net->next;
D
Daniel P. Berrange 已提交
3985 3986
    }

3987 3988
    chr = def->serials;
    while (chr) {
3989
        if (qemudGenerateXMLChar(&buf, chr, "serial") < 0)
3990 3991 3992 3993 3994 3995 3996
            goto no_memory;

        chr = chr->next;
    }

    chr = def->parallels;
    while (chr) {
3997
        if (qemudGenerateXMLChar(&buf, chr, "parallel") < 0)
3998 3999 4000 4001 4002 4003 4004
            goto no_memory;

        chr = chr->next;
    }

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

4008 4009
    input = def->inputs;
    while (input) {
4010
        if (input->bus == QEMU_INPUT_BUS_USB)
4011 4012
            virBufferVSprintf(&buf, "    <input type='%s' bus='usb'/>\n",
                              input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet");
4013 4014 4015 4016
        input = input->next;
    }
    /* If graphics is enable, add implicit mouse */
    if (def->graphicsType != QEMUD_GRAPHICS_NONE)
4017 4018
        virBufferVSprintf(&buf, "    <input type='mouse' bus='%s'/>\n",
                          STREQ(def->os.type, "hvm") ? "ps2" : "xen");
4019

4020 4021
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
4022
        virBufferAddLit(&buf, "    <graphics type='vnc'");
4023

4024 4025 4026
        if (def->vncPort)
            virBufferVSprintf(&buf, " port='%d'",
                              qemudIsActiveVM(vm) && live ? def->vncActivePort : def->vncPort);
4027

4028 4029 4030
        if (def->vncListen[0])
            virBufferVSprintf(&buf, " listen='%s'",
                              def->vncListen);
4031

4032 4033 4034
        if (def->keymap)
            virBufferVSprintf(&buf, " keymap='%s'",
                              def->keymap);
4035

4036
        virBufferAddLit(&buf, "/>\n");
4037 4038 4039
        break;

    case QEMUD_GRAPHICS_SDL:
4040
        virBufferAddLit(&buf, "    <graphics type='sdl'/>\n");
4041 4042 4043 4044 4045 4046 4047
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

D
Daniel Veillard 已提交
4048 4049 4050 4051 4052
    sound = def->sounds;
    while(sound) {
        const char *model = qemudSoundModelToString(sound->model);
        if (!model) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
4053
                             "%s", _("invalid sound model"));
D
Daniel Veillard 已提交
4054 4055 4056 4057 4058 4059
            goto cleanup;
        }
        virBufferVSprintf(&buf, "    <sound model='%s'/>\n", model);
        sound = sound->next;
    }

4060 4061
    virBufferAddLit(&buf, "  </devices>\n");
    virBufferAddLit(&buf, "</domain>\n");
D
Daniel P. Berrange 已提交
4062

4063
    if (virBufferError(&buf))
D
Daniel P. Berrange 已提交
4064 4065
        goto no_memory;

4066
    return virBufferContentAndReset(&buf);
D
Daniel P. Berrange 已提交
4067 4068

 no_memory:
4069 4070
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
D
Daniel P. Berrange 已提交
4071
 cleanup:
4072
    free(virBufferContentAndReset(&buf));
D
Daniel P. Berrange 已提交
4073 4074 4075 4076
    return NULL;
}


4077 4078
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
4079
                              struct qemud_network *network,
4080
                              struct qemud_network_def *def) {
4081
    virBuffer buf = VIR_BUFFER_INITIALIZER;
4082
    unsigned char *uuid;
4083
    char uuidstr[VIR_UUID_STRING_BUFLEN];
4084

4085
    virBufferAddLit(&buf, "<network>\n");
4086

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

4089
    uuid = def->uuid;
4090
    virUUIDFormat(uuid, uuidstr);
4091
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
4092

4093 4094
    if (def->forward) {
        if (def->forwardDev[0]) {
4095
            virBufferVSprintf(&buf, "  <forward dev='%s' mode='%s'/>\n",
4096
                              def->forwardDev, (def->forwardMode == QEMUD_NET_FORWARD_ROUTE ? "route" : "nat"));
4097
        } else {
4098
            virBufferVSprintf(&buf, "  <forward mode='%s'/>\n", (def->forwardMode == QEMUD_NET_FORWARD_ROUTE ? "route" : "nat"));
4099 4100 4101
        }
    }

4102
    virBufferAddLit(&buf, "  <bridge");
4103
    if (qemudIsActiveNetwork(network)) {
4104
        virBufferVSprintf(&buf, " name='%s'", network->bridge);
4105
    } else if (def->bridge[0]) {
4106
        virBufferVSprintf(&buf, " name='%s'", def->bridge);
4107
    }
4108 4109 4110
    virBufferVSprintf(&buf, " stp='%s' forwardDelay='%d' />\n",
                      def->disableSTP ? "off" : "on",
                      def->forwardDelay);
4111

4112
    if (def->ipAddress[0] || def->netmask[0]) {
4113
        virBufferAddLit(&buf, "  <ip");
4114

4115 4116
        if (def->ipAddress[0])
            virBufferVSprintf(&buf, " address='%s'", def->ipAddress);
4117

4118 4119
        if (def->netmask[0])
            virBufferVSprintf(&buf, " netmask='%s'", def->netmask);
4120

4121
        virBufferAddLit(&buf, ">\n");
4122

4123 4124
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
4125
            virBufferAddLit(&buf, "    <dhcp>\n");
4126
            while (range) {
4127 4128
                virBufferVSprintf(&buf, "      <range start='%s' end='%s' />\n",
                                  range->start, range->end);
4129 4130
                range = range->next;
            }
4131
            virBufferAddLit(&buf, "    </dhcp>\n");
4132 4133
        }

4134
        virBufferAddLit(&buf, "  </ip>\n");
D
Daniel P. Berrange 已提交
4135 4136
    }

4137 4138 4139
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
4140 4141
        goto no_memory;

4142
    return virBufferContentAndReset(&buf);
4143 4144

 no_memory:
4145 4146
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
4147
    free(virBufferContentAndReset(&buf));
4148 4149 4150 4151
    return NULL;
}


4152 4153
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
4154 4155 4156
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
4157 4158
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("no config file for %s"), name);
D
Daniel P. Berrange 已提交
4159 4160 4161
        return -1;
    }

4162
    if (unlink(configFile) < 0) {
4163 4164
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("cannot remove config for %s"), name);
4165 4166
        return -1;
    }
4167

D
Daniel P. Berrange 已提交
4168 4169 4170
    return 0;
}

4171
#endif /* WITH_QEMU */