qemu_conf.c 102.9 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"
52

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

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

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

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

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

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

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

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


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

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

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

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

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

    virConfFree (conf);
    return 0;
}


138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
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) {
155
        if (!memcmp(vm->def->uuid, uuid, VIR_UUID_BUFLEN))
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            return vm;
        vm = vm->next;
    }

    return NULL;
}

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

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

    return NULL;
}

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

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

    return NULL;
}

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

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

    return NULL;
}

202

203 204 205 206
/* 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 已提交
207
    struct qemud_vm_input_def *input = def->inputs;
208 209 210 211 212 213 214 215 216 217 218

    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 已提交
219 220 221 222 223
    while (input) {
        struct qemud_vm_input_def *prev = input;
        input = input->next;
        free(prev);
    }
224
    xmlFree(def->keymap);
225
    free(def);
226 227 228 229 230 231 232 233
}

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

235

D
Daniel P. Berrange 已提交
236 237
/* The list of possible machine types for various architectures,
   as supported by QEMU - taken from 'qemu -M ?' for each arch */
238 239
static const char *const arch_info_hvm_x86_machines[] = {
    "pc", "isapc"
D
Daniel P. Berrange 已提交
240
};
241 242
static const char *const arch_info_hvm_mips_machines[] = {
    "mips"
D
Daniel P. Berrange 已提交
243
};
244 245
static const char *const arch_info_hvm_sparc_machines[] = {
    "sun4m"
D
Daniel P. Berrange 已提交
246
};
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
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 已提交
269 270
};

271
/* Feature flags for the architecture info */
J
Jim Meyering 已提交
272
static const struct qemu_feature_flags const arch_info_i686_flags [] = {
273 274
    { "pae",  1, 0 },
    { "nonpae",  1, 0 },
275 276 277 278
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
};

J
Jim Meyering 已提交
279
static const struct qemu_feature_flags const arch_info_x86_64_flags [] = {
280 281 282 283
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
};

D
Daniel P. Berrange 已提交
284
/* The archicture tables for supported QEMU archs */
285 286 287 288 289 290 291 292 293 294 295 296 297
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 已提交
298 299
};

300 301 302 303 304 305
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 已提交
306

307 308 309 310 311 312
static int
qemudCapsInitGuest(virCapsPtr caps,
                   const char *hostmachine,
                   const struct qemu_arch_info *info,
                   int hvm) {
    virCapsGuestPtr guest;
D
Daniel P. Berrange 已提交
313 314
    int i;

315 316 317 318 319 320 321 322 323
    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 已提交
324

325 326 327 328 329 330 331 332 333 334
    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 已提交
335

336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364
        /* 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 已提交
365

366 367 368 369 370 371 372
    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 已提交
373 374 375
        }
    }

376
    return 0;
D
Daniel P. Berrange 已提交
377 378
}

379 380 381 382
virCapsPtr qemudCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    int i;
D
Daniel P. Berrange 已提交
383

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    /* 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 已提交
409 410
    }

411 412 413 414 415
    return caps;

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

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

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

    *flags = 0;
    *version = 0;

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

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

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

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

    cleanup1:
        _exit(-1); /* Just in case */
    } else { /* Parent */
D
Daniel P. Berrange 已提交
453
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
454
        int got = 0, ret = -1;
455 456 457 458 459
        int major, minor, micro;

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

D
Daniel P. Berrange 已提交
460 461 462 463 464 465 466 467 468 469
        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;
470 471 472 473 474 475 476 477 478 479
        }
        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 已提交
480 481
        if (strstr(help, "-no-reboot"))
            *flags |= QEMUD_CMD_FLAG_NO_REBOOT;
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
        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;
            }
498 499 500
            qemudLog(QEMUD_ERR,
                     _("Unexpected exit status from qemu %d pid %lu"),
                     got, (unsigned long)child);
501 502 503 504 505 506
            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) {
507 508 509
            qemudLog(QEMUD_WARN,
                     _("Unexpected exit status '%d', qemu probably failed"),
                     got);
510 511 512 513 514 515
        }

        return ret;
    }
}

516
int qemudExtractVersion(virConnectPtr conn,
517 518
                        struct qemud_driver *driver) {
    const char *binary;
519
    struct stat sb;
520
    int ignored;
521

522
    if (driver->qemuVersion > 0)
523 524
        return 0;

525 526 527 528
    if ((binary = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                      "hvm",
                                                      "i686",
                                                      "qemu")) == NULL)
529 530
        return -1;

531
    if (stat(binary, &sb) < 0) {
532
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
533 534 535 536 537
                         "Cannot find QEMU binary %s: %s", binary,
                         strerror(errno));
        return -1;
    }

538
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &ignored) < 0) {
539 540 541 542 543 544 545
        return -1;
    }

    return 0;
}


D
Daniel P. Berrange 已提交
546 547 548 549 550 551 552 553
/* 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 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    xmlNodePtr cur;
    xmlChar *device = NULL;
    xmlChar *source = NULL;
    xmlChar *target = NULL;
    xmlChar *type = NULL;
    int typ = 0;

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

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

D
Daniel P. Berrange 已提交
576 577 578 579 580
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
581

D
Daniel P. Berrange 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
                if (typ == QEMUD_DISK_FILE)
                    source = xmlGetProp(cur, BAD_CAST "file");
                else
                    source = xmlGetProp(cur, BAD_CAST "dev");
            } else if ((target == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "target"))) {
                target = xmlGetProp(cur, BAD_CAST "dev");
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                disk->readonly = 1;
            }
        }
        cur = cur->next;
    }

    if (source == NULL) {
597 598 599 600 601 602 603 604
        /* 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 已提交
605
    }
606

D
Daniel P. Berrange 已提交
607
    if (target == NULL) {
608
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
609 610 611 612 613 614 615
        goto error;
    }

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

D
Daniel P. Berrange 已提交
620 621 622
    if (device &&
        !strcmp((const char *)device, "cdrom") &&
        strcmp((const char *)target, "hdc")) {
623
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid cdrom device name: %s", target);
D
Daniel P. Berrange 已提交
624 625 626 627 628 629 630 631 632 633 634 635
        goto error;
    }

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

    if ((!device || !strcmp((const char *)device, "disk")) &&
        strcmp((const char *)target, "hda") &&
        strcmp((const char *)target, "hdb") &&
        strcmp((const char *)target, "hdc") &&
        strcmp((const char *)target, "hdd")) {
636
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid harddisk device name: %s", target);
D
Daniel P. Berrange 已提交
637 638 639
        goto error;
    }

640
    strncpy(disk->src, (source ? (const char *) source : "\0"), NAME_MAX-1);
D
Daniel P. Berrange 已提交
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    disk->src[NAME_MAX-1] = '\0';

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

    if (!device)
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "disk"))
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "cdrom"))
        disk->device = QEMUD_DISK_CDROM;
    else if (!strcmp((const char *)device, "floppy"))
        disk->device = QEMUD_DISK_FLOPPY;
    else {
656
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid device type: %s", device);
D
Daniel P. Berrange 已提交
657 658 659 660 661 662 663
        goto error;
    }

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

D
Daniel P. Berrange 已提交
664
    return 0;
D
Daniel P. Berrange 已提交
665 666 667 668 669 670 671 672 673 674

 error:
    if (type)
        xmlFree(type);
    if (target)
        xmlFree(target);
    if (source)
        xmlFree(source);
    if (device)
        xmlFree(device);
D
Daniel P. Berrange 已提交
675
    return -1;
D
Daniel P. Berrange 已提交
676 677
}

678 679 680 681 682 683 684 685 686
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 已提交
687

D
Daniel P. Berrange 已提交
688 689 690 691 692 693 694 695
/* 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 已提交
696 697 698
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
699
    xmlChar *network = NULL;
700 701 702 703 704
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
D
Daniel P. Berrange 已提交
705 706 707 708 709 710 711

    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;
712 713
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
714 715 716 717 718 719
        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;
720 721
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
722 723
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
724 725 726 727 728 729 730 731 732 733 734 735
        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");
736 737 738 739
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
740 741 742
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
743
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
744 745 746 747 748 749 750 751 752 753 754 755 756
            } 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");
757 758 759 760 761
                if (STREQLEN("vnet", (const char*)ifname, 4)) {
                    /* An auto-generated target name, blank it out */
                    xmlFree(ifname);
                    ifname = NULL;
                }
762 763 764 765
            } else if ((script == NULL) &&
                       (net->type == QEMUD_NET_ETHERNET) &&
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = xmlGetProp(cur, BAD_CAST "path");
D
Daniel P. Berrange 已提交
766 767 768 769 770 771
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
772
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
773
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
774 775 776 777 778 779 780 781 782 783 784 785
               (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 已提交
786 787

        xmlFree(macaddr);
788 789 790
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
791 792
    }

793 794 795 796
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
797
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
798 799
                             "No <source> 'network' attribute specified with <interface type='network'/>");
            goto error;
800
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
801
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
802 803 804 805 806 807 808
                             "Network name '%s' too long", network);
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

809
        if (network) {
810
            xmlFree(network);
811 812 813 814 815
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
816
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
817 818 819 820 821 822 823 824 825 826 827
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.network.ifname, (char *)ifname, len);
                net->dst.network.ifname[len] = '\0';
            }
            xmlFree(ifname);
            ifname = NULL;
        }
    } else if (net->type == QEMUD_NET_ETHERNET) {
        int len;
828

829 830
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
831
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
832 833 834 835 836 837 838 839 840 841 842
                                 "TAP script path '%s' is too long", script);
                goto error;
            } else {
                strncpy(net->dst.ethernet.script, (char *)script, len);
                net->dst.ethernet.script[len] = '\0';
            }
            xmlFree(script);
            script = NULL;
        }
        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
843
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
844
                                 "TAP interface name '%s' is too long", ifname);
845 846
                goto error;
            } else {
847 848
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
849
            }
850 851 852 853 854 855
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
856
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
857 858 859
                             "No <source> 'dev' attribute specified with <interface type='bridge'/>");
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
860
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
861 862 863 864 865
                             "TAP bridge path '%s' is too long", bridge);
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
866
        }
867 868 869 870 871 872

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
873
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
874 875 876 877 878 879 880 881 882 883 884
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.bridge.ifname, (char *)ifname, len);
                net->dst.bridge.ifname[len] = '\0';
            }
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_CLIENT ||
               net->type == QEMUD_NET_SERVER ||
               net->type == QEMUD_NET_MCAST) {
885
        int len = 0;
886 887 888
        char *ret;

        if (port == NULL) {
889
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
890 891 892 893 894
                             "No <source> 'port' attribute specified with socket interface");
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
895
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
896 897 898 899 900 901 902 903 904
                             "Cannot parse <source> 'port' attribute with socket interface");
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
905
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
906 907 908 909
                                 "No <source> 'address' attribute specified with socket interface");
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
910
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
911 912 913 914 915 916 917 918 919 920
                             "IP address '%s' is too long", address);
            goto error;
        }
        if (address == NULL) {
            net->dst.socket.address[0] = '\0';
        } else {
            strncpy(net->dst.socket.address, (char*)address,len);
            net->dst.socket.address[len] = '\0';
        }
        xmlFree(address);
921 922
    }

D
Daniel P. Berrange 已提交
923
    return 0;
924 925 926 927

 error:
    if (network)
        xmlFree(network);
928 929 930 931 932 933 934 935 936 937
    if (address)
        xmlFree(address);
    if (port)
        xmlFree(port);
    if (ifname)
        xmlFree(ifname);
    if (script)
        xmlFree(script);
    if (bridge)
        xmlFree(bridge);
D
Daniel P. Berrange 已提交
938
    return -1;
D
Daniel P. Berrange 已提交
939 940 941
}


942
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
943 944 945
static int qemudParseInputXML(virConnectPtr conn,
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

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

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

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

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

D
Daniel P. Berrange 已提交
991
    return 0;
992 993 994 995 996 997 998

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

D
Daniel P. Berrange 已提交
999
    return -1;
1000 1001 1002
}


D
Daniel P. Berrange 已提交
1003 1004 1005 1006
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
1007 1008
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
1009
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
1010 1011 1012 1013 1014 1015
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
1016 1017
    struct qemud_vm_def *def;

1018
    if (!(def = calloc(1, sizeof(*def)))) {
1019
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
1020 1021
        return NULL;
    }
D
Daniel P. Berrange 已提交
1022 1023 1024 1025

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
1026
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
D
Daniel P. Berrange 已提交
1027 1028 1029 1030 1031
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1032
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
D
Daniel P. Berrange 已提交
1033 1034 1035 1036 1037 1038
        goto error;
    }


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

    if (!strcmp((char *)prop, "qemu"))
1044
        def->virtType = QEMUD_VIRT_QEMU;
D
Daniel P. Berrange 已提交
1045
    else if (!strcmp((char *)prop, "kqemu"))
1046
        def->virtType = QEMUD_VIRT_KQEMU;
D
Daniel P. Berrange 已提交
1047
    else if (!strcmp((char *)prop, "kvm"))
1048
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
1049
    else {
1050
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "invalid domain type attribute");
D
Daniel P. Berrange 已提交
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
        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)) {
1061
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
1062 1063 1064
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1065
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "domain name length too long");
D
Daniel P. Berrange 已提交
1066 1067
        goto error;
    }
1068
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1069 1070 1071 1072 1073 1074 1075
    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)) {
1076
        int err;
D
Daniel P. Berrange 已提交
1077
        if ((err = virUUIDGenerate(def->uuid))) {
1078
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1079 1080 1081
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
1082
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
1083
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
D
Daniel P. Berrange 已提交
1084 1085 1086 1087 1088 1089 1090 1091 1092
        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)) {
1093
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "missing memory element");
D
Daniel P. Berrange 已提交
1094 1095 1096
        goto error;
    } else {
        conv = NULL;
1097
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1098
        if (conv == (const char*)obj->stringval) {
1099
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
1100 1101 1102
            goto error;
        }
    }
1103
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1104 1105 1106 1107 1108 1109


    /* 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)) {
1110
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1111 1112
    } else {
        conv = NULL;
1113 1114 1115
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1116
        if (conv == (const char*)obj->stringval) {
1117
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
1118 1119 1120
            goto error;
        }
    }
1121
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1122 1123 1124 1125 1126

    /* 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)) {
1127
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1128 1129
    } else {
        conv = NULL;
1130
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1131
        if (conv == (const char*)obj->stringval) {
1132
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed vcpu information");
D
Daniel P. Berrange 已提交
1133 1134 1135
            goto error;
        }
    }
1136
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1137 1138 1139 1140 1141

    /* 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)) {
1142
        def->features |= QEMUD_FEATURE_ACPI;
D
Daniel P. Berrange 已提交
1143
    }
1144
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1145

D
Daniel P. Berrange 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

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

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    /* See if we set clock to localtime */
    obj = xmlXPathEval(BAD_CAST "string(/domain/clock/@offset)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        def->localtime = 0;
    } else {
        if (!strcmp((char*)obj->stringval, "localtime"))
            def->localtime = 1;
        else
            def->localtime = 0;
    }
1171
    xmlXPathFreeObject(obj);
1172

D
Daniel P. Berrange 已提交
1173

D
Daniel P. Berrange 已提交
1174 1175 1176 1177
    /* 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)) {
1178
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, "no OS type");
D
Daniel P. Berrange 已提交
1179 1180
        goto error;
    }
1181
    if (!virCapabilitiesSupportsGuestOSType(driver->caps, (const char*)obj->stringval)) {
1182
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, "%s", obj->stringval);
D
Daniel P. Berrange 已提交
1183 1184
        goto error;
    }
1185
    strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1186 1187 1188 1189 1190 1191
    xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1]/@arch)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1192 1193 1194 1195 1196
        const char *defaultArch = virCapabilitiesDefaultGuestArch(driver->caps, def->os.type);
        if (defaultArch == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "unsupported architecture");
            goto error;
        }
D
Daniel P. Berrange 已提交
1197
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1198
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1199 1200
            goto error;
        }
1201
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
1202 1203
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1204
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1205 1206
            goto error;
        }
1207
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1208
    }
1209
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1210 1211 1212 1213

    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)) {
1214 1215 1216 1217 1218
        const char *defaultMachine = virCapabilitiesDefaultGuestMachine(driver->caps,
                                                                        def->os.type,
                                                                        def->os.arch);
        if (defaultMachine == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "unsupported architecture");
1219 1220
            goto error;
        }
D
Daniel P. Berrange 已提交
1221
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1222
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "machine type too long");
D
Daniel P. Berrange 已提交
1223 1224
            goto error;
        }
1225
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1226 1227
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1228
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1229 1230
            goto error;
        }
1231
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1232
    }
1233
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1234 1235 1236 1237 1238 1239


    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)) {
1240
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "kernel path too long");
D
Daniel P. Berrange 已提交
1241 1242
            goto error;
        }
1243
        strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1244
    }
1245
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1246 1247 1248 1249 1250 1251


    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)) {
1252
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "initrd path too long");
D
Daniel P. Berrange 已提交
1253 1254
            goto error;
        }
1255
        strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1256
    }
1257
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1258 1259 1260 1261 1262 1263


    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)) {
1264
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "cmdline arguments too long");
D
Daniel P. Berrange 已提交
1265 1266
            goto error;
        }
1267
        strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1268
    }
1269
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1270 1271 1272 1273 1274 1275 1276


    /* 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++) {
1277 1278
            if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                continue;
D
Daniel P. Berrange 已提交
1279
            if (!strcmp((char *)prop, "hd")) {
1280
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1281
            } else if (!strcmp((char *)prop, "fd")) {
1282
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
D
Daniel P. Berrange 已提交
1283
            } else if (!strcmp((char *)prop, "cdrom")) {
1284
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
1285
            } else if (!strcmp((char *)prop, "network")) {
1286
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
D
Daniel P. Berrange 已提交
1287
            } else {
1288 1289
	        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
				 "unknown boot dev \'%s\'", (char*)prop);
D
Daniel P. Berrange 已提交
1290 1291
                goto error;
            }
1292
            xmlFree(prop);
1293
            prop = NULL;
D
Daniel P. Berrange 已提交
1294 1295 1296
        }
    }
    xmlXPathFreeObject(obj);
1297 1298 1299
    if (def->os.nBootDevs == 0) {
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1300 1301 1302 1303 1304 1305
    }


    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1306 1307 1308 1309 1310 1311 1312 1313 1314
        const char *type = (def->virtType == QEMUD_VIRT_QEMU ? "qemu" :
                            def->virtType == QEMUD_VIRT_KQEMU ? "kqemu":
                            "kvm");
        const char *emulator = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                                   def->os.type,
                                                                   def->os.arch,
                                                                   type);
        if (!emulator) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "unsupported guest type");
D
Daniel P. Berrange 已提交
1315 1316
            goto error;
        }
1317
        strcpy(def->os.binary, emulator);
D
Daniel P. Berrange 已提交
1318 1319
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1320
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "emulator path too long");
D
Daniel P. Berrange 已提交
1321 1322
            goto error;
        }
1323
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1324
    }
1325
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1326 1327 1328 1329

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1330
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1331
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
D
Daniel P. Berrange 已提交
1332
        if (!strcmp((char *)prop, "vnc")) {
1333
            xmlChar *vncport, *vnclisten;
1334
            def->graphicsType = QEMUD_GRAPHICS_VNC;
1335 1336
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
1337
                conv = NULL;
1338
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
1339
            } else {
1340
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1341
            }
1342 1343 1344 1345
            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 已提交
1346
                strcpy(def->vncListen, driver->vncListen);
1347
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
1348
            def->keymap = (char *) xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "keymap");
1349 1350
            xmlFree(vncport);
            xmlFree(vnclisten);
D
Daniel P. Berrange 已提交
1351
        } else if (!strcmp((char *)prop, "sdl")) {
1352
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1353
        } else {
1354
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Unsupported graphics type %s", prop);
D
Daniel P. Berrange 已提交
1355 1356
            goto error;
        }
1357
        xmlFree(prop);
1358
        prop = NULL;
D
Daniel P. Berrange 已提交
1359
    }
1360
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1361 1362 1363 1364 1365

    /* 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)) {
1366
        struct qemud_vm_disk_def *prev = NULL;
D
Daniel P. Berrange 已提交
1367
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1368
            struct qemud_vm_disk_def *disk = calloc(1, sizeof(*disk));
D
Daniel P. Berrange 已提交
1369 1370 1371 1372 1373 1374
            if (!disk) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "disk");
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
                free(disk);
D
Daniel P. Berrange 已提交
1375 1376
                goto error;
            }
1377
            def->ndisks++;
1378 1379 1380 1381 1382 1383 1384
            disk->next = NULL;
            if (i == 0) {
                def->disks = disk;
            } else {
                prev->next = disk;
            }
            prev = disk;
D
Daniel P. Berrange 已提交
1385 1386 1387 1388 1389 1390 1391 1392 1393
        }
    }
    xmlXPathFreeObject(obj);


    /* analysis of the network devices */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/interface", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
1394
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
1395
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1396
            struct qemud_vm_net_def *net = calloc(1, sizeof(*net));
D
Daniel P. Berrange 已提交
1397 1398 1399 1400 1401 1402
            if (!net) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "net");
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
                free(net);
D
Daniel P. Berrange 已提交
1403 1404
                goto error;
            }
1405
            def->nnets++;
1406 1407 1408 1409 1410 1411 1412
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
1413 1414 1415
        }
    }
    xmlXPathFreeObject(obj);
1416 1417 1418 1419 1420 1421 1422

    /* 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++) {
1423
            struct qemud_vm_input_def *input = calloc(1, sizeof(*input));
D
Daniel P. Berrange 已提交
1424 1425 1426 1427 1428 1429
            if (!input) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "input");
                goto error;
            }
            if (qemudParseInputXML(conn, input, obj->nodesetval->nodeTab[i]) < 0) {
                free(input);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
                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;
1440
            if (def->inputs == NULL) {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
                def->inputs = input;
            } else {
                prev->next = input;
            }
            prev = input;
        }
    }
    xmlXPathFreeObject(obj);
    obj = NULL;

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

        if (!hasPS2mouse) {
1463
            input = calloc(1, sizeof(*input));
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
            if (!input) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "input");
                goto error;
            }
            input->type = QEMU_INPUT_TYPE_MOUSE;
            input->bus = QEMU_INPUT_BUS_PS2;
            input->next = def->inputs;
            def->inputs = input;
            def->ninputs++;
        }
    }

D
Daniel P. Berrange 已提交
1476 1477
    xmlXPathFreeContext(ctxt);

1478
    return def;
D
Daniel P. Berrange 已提交
1479 1480

 error:
1481
    free(prop);
1482
    xmlXPathFreeObject(obj);
1483
    xmlXPathFreeContext(ctxt);
1484 1485
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
1486 1487 1488
}


1489
static char *
1490 1491
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
1492
                         struct qemud_vm *vm,
1493 1494
                         struct qemud_vm_net_def *net,
                         int vlan)
1495
{
1496 1497 1498
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
1499 1500 1501 1502 1503 1504
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

1505
    if (net->type == QEMUD_NET_NETWORK) {
1506
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
1507
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1508 1509 1510
                             "Network '%s' not found", net->dst.network.name);
            goto error;
        } else if (network->bridge[0] == '\0') {
1511
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1512 1513 1514 1515 1516
                             "Network '%s' not active", net->dst.network.name);
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
1517
            STREQLEN(net->dst.network.ifname, "vnet", 4) ||
1518 1519 1520 1521 1522 1523 1524
            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' ||
1525
            STREQLEN(net->dst.bridge.ifname, "vnet", 4) ||
1526 1527 1528 1529 1530
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
1531
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1532
                         "Network type %d is not supported", net->type);
1533 1534 1535
        goto error;
    }

1536
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
1537
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1538 1539 1540 1541
                         "cannot initialize bridge support: %s", strerror(err));
        goto error;
    }

1542
    if ((err = brAddTap(driver->brctl, brname,
1543
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
1544
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1545
                         "Failed to add tap interface '%s' to bridge '%s' : %s",
1546
                         ifname, brname, strerror(err));
1547 1548 1549
        goto error;
    }

1550 1551 1552
    snprintf(tapfdstr, sizeof(tapfdstr),
             "tap,fd=%d,script=,vlan=%d,ifname=%s",
             tapfd, vlan, ifname);
1553 1554 1555 1556

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

1557
    if (!(tapfds = realloc(vm->tapfds, sizeof(*tapfds) * (vm->ntapfds+2))))
1558 1559 1560 1561 1562 1563 1564 1565 1566
        goto no_memory;

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

    return retval;

 no_memory:
1567
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "tapfds");
1568
 error:
1569
    free(retval);
1570 1571 1572 1573 1574
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

D
Daniel P. Berrange 已提交
1575 1576 1577 1578
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
1579 1580
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
1581
                          struct qemud_vm *vm,
1582 1583
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
1584 1585 1586
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
1587
    struct stat sb;
1588 1589
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
1590
    struct qemud_vm_input_def *input = vm->def->inputs;
1591 1592
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
1593

1594 1595 1596 1597 1598 1599 1600 1601
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
    if (stat(vm->def->os.binary, &sb) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "Cannot find QEMU binary %s: %s", vm->def->os.binary,
                         strerror(errno));
1602
        return -1;
1603 1604 1605 1606 1607 1608 1609 1610
    }

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

1612 1613
    uname(&ut);

D
Daniel P. Berrange 已提交
1614
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
1615 1616 1617 1618
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
1619
        ut.machine[1] = '6';
1620 1621 1622 1623 1624 1625

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

1631
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
1632
        2 + /* machine type */
1633
        disableKQEMU + /* Disable kqemu */
1634 1635
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
1636 1637
        1 + /* usb */
        2 * vm->def->ninputs + /* input devices */
D
Daniel P. Berrange 已提交
1638 1639 1640 1641
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
1642
        (vm->def->localtime ? 1 : 0) + /* localtime */
1643
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1644
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
1645 1646 1647 1648 1649
        (vm->def->features & QEMUD_FEATURE_ACPI ? 0 : 1) + /* acpi */
        (vm->def->os.kernel[0] ? 2 : 0) + /* kernel */
        (vm->def->os.initrd[0] ? 2 : 0) + /* initrd */
        (vm->def->os.cmdline[0] ? 2 : 0) + /* cmdline */
        (vm->def->graphicsType == QEMUD_GRAPHICS_VNC ? 2 :
1650 1651
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)) + /* graphics */
        (vm->migrateFrom[0] ? 3 : 0); /* migrateFrom */
D
Daniel P. Berrange 已提交
1652

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

1656
    if (!(*argv = malloc(sizeof(**argv) * (len+1))))
D
Daniel P. Berrange 已提交
1657
        goto no_memory;
1658
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
1659 1660 1661
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
1662
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
1663
        goto no_memory;
1664
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
1665
        if (!((*argv)[++n] = strdup("-no-kqemu")))
1666
            goto no_memory;
D
Daniel P. Berrange 已提交
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
    }
    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;

1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
    /*
     * 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 已提交
1689 1690 1691 1692 1693
    if (!((*argv)[++n] = strdup("-monitor")))
        goto no_memory;
    if (!((*argv)[++n] = strdup("pty")))
        goto no_memory;

1694 1695 1696 1697 1698
    if (vm->def->localtime) {
        if (!((*argv)[++n] = strdup("-localtime")))
            goto no_memory;
    }

1699
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1700 1701 1702 1703 1704
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

1705
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
1706 1707
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
1708 1709
    }

1710 1711
    for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
        switch (vm->def->os.bootDevs[i]) {
D
Daniel P. Berrange 已提交
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
        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;
        }
    }
1729
    boot[vm->def->os.nBootDevs] = '\0';
D
Daniel P. Berrange 已提交
1730 1731 1732 1733 1734
    if (!((*argv)[++n] = strdup("-boot")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(boot)))
        goto no_memory;

1735
    if (vm->def->os.kernel[0]) {
D
Daniel P. Berrange 已提交
1736 1737
        if (!((*argv)[++n] = strdup("-kernel")))
            goto no_memory;
1738
        if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
D
Daniel P. Berrange 已提交
1739 1740
            goto no_memory;
    }
1741
    if (vm->def->os.initrd[0]) {
D
Daniel P. Berrange 已提交
1742 1743
        if (!((*argv)[++n] = strdup("-initrd")))
            goto no_memory;
1744
        if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
D
Daniel P. Berrange 已提交
1745 1746
            goto no_memory;
    }
1747
    if (vm->def->os.cmdline[0]) {
D
Daniel P. Berrange 已提交
1748 1749
        if (!((*argv)[++n] = strdup("-append")))
            goto no_memory;
1750
        if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
D
Daniel P. Berrange 已提交
1751 1752 1753 1754 1755 1756 1757
            goto no_memory;
    }

    while (disk) {
        char dev[NAME_MAX];
        char file[PATH_MAX];
        if (!strcmp(disk->dst, "hdc") &&
1758 1759 1760 1761 1762 1763 1764 1765 1766
            disk->device == QEMUD_DISK_CDROM) {
            if (disk->src[0])
                snprintf(dev, NAME_MAX, "-%s", "cdrom");
            else {
                /* Don't put anything on the cmdline for an empty cdrom*/
                disk = disk->next;
                continue;
            }
        } else
D
Daniel P. Berrange 已提交
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
            snprintf(dev, NAME_MAX, "-%s", disk->dst);
        snprintf(file, PATH_MAX, "%s", disk->src);

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

        disk = disk->next;
    }

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

1788 1789 1790 1791 1792 1793
            if (snprintf(nic, sizeof(nic), "nic,macaddr=%02x:%02x:%02x:%02x:%02x:%02x,vlan=%d",
                         net->mac[0], net->mac[1],
                         net->mac[2], net->mac[3],
                         net->mac[4], net->mac[5],
                         vlan) >= sizeof(nic))
                goto error;
D
Daniel P. Berrange 已提交
1794 1795 1796 1797 1798

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

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

1803 1804 1805
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
1806
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
1807
                    goto error;
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
                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;
                }
1863
            }
D
Daniel P. Berrange 已提交
1864 1865

            net = net->next;
1866
            vlan++;
D
Daniel P. Berrange 已提交
1867 1868 1869
        }
    }

1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
    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;
    }

1883
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
1884
        char vncdisplay[PATH_MAX];
1885
        int ret;
D
Daniel P. Berrange 已提交
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900

        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",
1901
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
1902 1903 1904
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
1905 1906
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
1907
        }
1908
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
1909 1910
            goto error;

D
Daniel P. Berrange 已提交
1911 1912
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
1913
        if (!((*argv)[++n] = strdup(vncdisplay)))
D
Daniel P. Berrange 已提交
1914
            goto no_memory;
1915 1916 1917 1918 1919 1920
        if (vm->def->keymap) {
            if (!((*argv)[++n] = strdup("-k")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->keymap)))
                goto no_memory;
        }
1921
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
1922
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
1923 1924 1925 1926
    } else {
        /* SDL is the default. no args needed */
    }

1927 1928 1929 1930 1931 1932 1933 1934 1935
    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 已提交
1936 1937 1938 1939 1940
    (*argv)[++n] = NULL;

    return 0;

 no_memory:
1941
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "argv");
1942 1943 1944 1945 1946 1947 1948 1949
 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 已提交
1950 1951
    if (argv) {
        for (i = 0 ; i < n ; i++)
1952 1953
            free((*argv)[i]);
        free(*argv);
D
Daniel P. Berrange 已提交
1954 1955 1956 1957 1958 1959
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
1960 1961
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
1962 1963
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
1964 1965 1966 1967
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

1968
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
1969 1970 1971 1972 1973
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1974
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1975 1976
                         "cannot create config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1977 1978 1979 1980
        goto cleanup;
    }

    towrite = strlen(xml);
1981
    if (safewrite(fd, xml, towrite) < 0) {
1982
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1983 1984
                         "cannot write config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1985 1986 1987 1988
        goto cleanup;
    }

    if (close(fd) < 0) {
1989
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1990 1991
                         "cannot save config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
        goto cleanup;
    }

    ret = 0;

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

    free(xml);

    return ret;
}

D
Daniel P. Berrange 已提交
2006 2007 2008 2009 2010 2011 2012
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
2013
    struct qemud_vm_device_def *dev = calloc(1, sizeof(*dev));
D
Daniel P. Berrange 已提交
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046

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

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

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
2047
    free(dev);
D
Daniel P. Berrange 已提交
2048 2049 2050
    return NULL;
}

2051
struct qemud_vm_def *
2052 2053
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
2054 2055
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
2056
    xmlDocPtr xml;
2057
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
2058

2059
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
2060 2061
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2062
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
2063 2064 2065
        return NULL;
    }

2066
    def = qemudParseXML(conn, driver, xml);
2067

D
Daniel P. Berrange 已提交
2068 2069
    xmlFreeDoc(xml);

2070 2071 2072 2073
    return def;
}

struct qemud_vm *
2074 2075
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
2076 2077 2078 2079
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

2080
    if ((vm = qemudFindVMByName(driver, def->name))) {
2081
        if (!qemudIsActiveVM(vm)) {
2082 2083 2084 2085 2086 2087 2088
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
2089 2090 2091
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
2092
        return vm;
D
Daniel P. Berrange 已提交
2093 2094
    }

2095
    if (!(vm = calloc(1, sizeof(*vm)))) {
2096
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "vm");
2097 2098
        return NULL;
    }
D
Daniel P. Berrange 已提交
2099

2100
    vm->stdin = -1;
2101 2102 2103 2104 2105
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
2106
    vm->state = VIR_DOMAIN_SHUTOFF;
2107
    vm->def = def;
2108
    vm->next = driver->vms;
2109

2110 2111
    driver->vms = vm;
    driver->ninactivevms++;
2112 2113 2114 2115 2116

    return vm;
}

void
2117
qemudRemoveInactiveVM(struct qemud_driver *driver,
2118 2119 2120 2121
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

2122
    curr = driver->vms;
2123 2124 2125
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
2126 2127
    }

2128 2129 2130 2131
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2132
            driver->vms = curr->next;
2133

2134
        driver->ninactivevms--;
2135 2136
    }

2137
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
2138 2139
}

2140
int
2141 2142
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
2143 2144 2145 2146 2147
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

2148
        if ((err = virFileMakePath(driver->configDir))) {
2149
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2150
                             "cannot create config directory %s: %s",
2151
                             driver->configDir, strerror(err));
2152 2153 2154
            return -1;
        }

2155 2156
        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             vm->configFile, PATH_MAX) < 0) {
2157
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2158 2159 2160
                             "cannot construct config file path");
            return -1;
        }
2161

2162 2163
        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             vm->autostartLink, PATH_MAX) < 0) {
2164
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2165 2166 2167 2168
                             "cannot construct autostart link path");
            vm->configFile[0] = '\0';
            return -1;
        }
2169 2170
    }

2171
    return qemudSaveConfig(conn, driver, vm, def);
2172
}
D
Daniel P. Berrange 已提交
2173

2174 2175
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
2176 2177
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
2178 2179 2180
    char *xml;
    int fd, ret = -1;
    int towrite;
2181
    int err;
2182

2183
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
2184 2185 2186
        return -1;
    }

2187
    if ((err = virFileMakePath(driver->networkConfigDir))) {
2188
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2189
                         "cannot create config directory %s: %s",
2190
                         driver->networkConfigDir, strerror(err));
2191 2192 2193 2194 2195 2196
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2197
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2198 2199
                         "cannot create config file %s: %s",
                         network->configFile, strerror(errno));
2200 2201 2202 2203
        goto cleanup;
    }

    towrite = strlen(xml);
2204
    if (safewrite(fd, xml, towrite) < 0) {
2205
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2206
                         "cannot write config file %s: %s",
2207
                         network->configFile, strerror(errno));
2208 2209 2210 2211
        goto cleanup;
    }

    if (close(fd) < 0) {
2212
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2213
                         "cannot save config file %s: %s",
2214
                         network->configFile, strerror(errno));
2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242
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);
}
2243

2244
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
2245
                               struct qemud_network_def *def,
2246 2247 2248 2249 2250
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
2251 2252
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
2253 2254 2255 2256 2257 2258 2259
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
2260
            def->disableSTP = 1;
2261 2262 2263 2264 2265 2266 2267
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
2268
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
2269 2270 2271 2272 2273 2274 2275
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

2276 2277
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
2278
                                   struct qemud_network_def *def,
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
                                   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;
        }

2294
        if (!(range = calloc(1, sizeof(*range)))) {
2295
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "range");
2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308
            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';

2309 2310 2311
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
        } else {
            free(range);
        }

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

        cur = cur->next;
    }

    return 1;
}
2326

2327 2328
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
2329
                             struct qemud_network_def *def,
2330 2331
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
2332
    xmlNodePtr cur;
2333 2334 2335

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
2336 2337
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
2338 2339 2340 2341 2342 2343
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
2344 2345
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
2346 2347 2348 2349
        xmlFree(netmask);
        netmask = NULL;
    }

2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364
    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);
    }

2365 2366 2367 2368
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
2369
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
2370 2371 2372 2373
            return 0;
        cur = cur->next;
    }

2374 2375 2376 2377
    return 1;
}


2378 2379
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
2380
                                                      xmlDocPtr xml) {
2381 2382
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
2383
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
2384 2385
    struct qemud_network_def *def;

2386
    if (!(def = calloc(1, sizeof(*def)))) {
2387
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network_def");
2388 2389
        return NULL;
    }
2390 2391 2392 2393

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
2394
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
2395 2396 2397 2398 2399
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
2400
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
2401 2402 2403 2404 2405 2406 2407 2408
        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)) {
2409
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
2410 2411 2412
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
2413
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "network name length too long");
2414 2415
        goto error;
    }
2416
    strcpy(def->name, (const char *)obj->stringval);
2417 2418 2419 2420 2421 2422 2423
    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)) {
2424
        int err;
D
Daniel P. Berrange 已提交
2425
        if ((err = virUUIDGenerate(def->uuid))) {
2426
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2427 2428 2429
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
2430
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
2431
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
2432 2433 2434 2435
        goto error;
    }
    xmlXPathFreeObject(obj);

2436 2437 2438 2439
    /* 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)) {
2440
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
2441 2442 2443 2444 2445 2446 2447 2448 2449
            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)) {
2450
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
2451 2452 2453 2454 2455 2456
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
2457 2458 2459
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
2460 2461
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
2462
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2463 2464 2465 2466
                             "Forwarding requested, but no IPv4 address/netmask provided");
            goto error;
        }

2467 2468 2469 2470 2471 2472
        def->forward = 1;
        tmp = xmlXPathEval(BAD_CAST "string(/network/forward[1]/@dev)", ctxt);
        if ((tmp != NULL) && (tmp->type == XPATH_STRING) &&
            (tmp->stringval != NULL) && (tmp->stringval[0] != 0)) {
            int len;
            if ((len = xmlStrlen(tmp->stringval)) >= (BR_IFNAME_MAXLEN-1)) {
2473
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
                                 "forward device name '%s' is too long",
                                 (char*)tmp->stringval);
                goto error;
            }
            strcpy(def->forwardDev, (char*)tmp->stringval);
        } else {
            def->forwardDev[0] = '\0';
        }
        xmlXPathFreeObject(tmp);
        tmp = NULL;
    } else {
        def->forward = 0;
    }
    xmlXPathFreeObject(obj);

2489 2490
    xmlXPathFreeContext(ctxt);

2491
    return def;
2492 2493 2494 2495

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
2496 2497
    xmlXPathFreeObject(obj);
    xmlXPathFreeObject(tmp);
2498
    xmlXPathFreeContext(ctxt);
2499 2500
    qemudFreeNetworkDef(def);
    return NULL;
2501 2502
}

2503
struct qemud_network_def *
2504 2505
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
2506 2507
                     const char *xmlStr,
                     const char *displayName) {
2508
    xmlDocPtr xml;
2509
    struct qemud_network_def *def;
2510

2511
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
2512 2513
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2514
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
2515 2516 2517
        return NULL;
    }

2518
    def = qemudParseNetworkXML(conn, driver, xml);
2519

2520 2521
    xmlFreeDoc(xml);

2522 2523 2524 2525
    return def;
}

struct qemud_network *
2526 2527
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
2528 2529 2530
                      struct qemud_network_def *def) {
    struct qemud_network *network;

2531
    if ((network = qemudFindNetworkByName(driver, def->name))) {
2532
        if (!qemudIsActiveNetwork(network)) {
2533 2534 2535 2536 2537 2538 2539 2540
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

2541
        return network;
2542 2543
    }

2544
    if (!(network = calloc(1, sizeof(*network)))) {
2545
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network");
2546 2547
        return NULL;
    }
2548

2549
    network->def = def;
2550
    network->next = driver->networks;
2551

2552 2553
    driver->networks = network;
    driver->ninactivenetworks++;
2554 2555 2556 2557 2558

    return network;
}

void
2559
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
2560 2561 2562 2563
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

2564
    curr = driver->networks;
2565 2566 2567
    while (curr != network) {
        prev = curr;
        curr = curr->next;
2568 2569
    }

2570 2571 2572 2573
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2574
            driver->networks = curr->next;
2575

2576
        driver->ninactivenetworks--;
2577 2578
    }

2579
    qemudFreeNetwork(network);
2580 2581
}

2582
int
2583 2584
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
2585 2586 2587 2588 2589 2590
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

2591
        if ((err = virFileMakePath(driver->networkConfigDir))) {
2592
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2593
                             "cannot create config directory %s: %s",
2594
                             driver->networkConfigDir, strerror(err));
2595 2596 2597
            return -1;
        }

2598 2599
        if (virFileBuildPath(driver->networkConfigDir, def->name, ".xml",
                             network->configFile, PATH_MAX) < 0) {
2600
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2601 2602 2603
                             "cannot construct config file path");
            return -1;
        }
2604

2605 2606
        if (virFileBuildPath(driver->networkAutostartDir, def->name, ".xml",
                             network->autostartLink, PATH_MAX) < 0) {
2607
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2608 2609 2610 2611
                             "cannot construct autostart link path");
            network->configFile[0] = '\0';
            return -1;
        }
2612 2613
    }

2614
    return qemudSaveNetworkConfig(conn, driver, network, def);
2615
}
2616

2617

2618
static struct qemud_vm *
2619
qemudLoadConfig(struct qemud_driver *driver,
2620 2621
                const char *file,
                const char *path,
2622 2623
                const char *xml,
                const char *autostartLink) {
2624 2625 2626
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

2627
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
2628
        virErrorPtr err = virGetLastError();
2629 2630 2631
        qemudLog(QEMUD_WARN, _("Error parsing QEMU guest config '%s' : %s"),
                 path, (err ? err->message :
                        _("BUG: unknown error - please report it\n")));
2632 2633 2634
        return NULL;
    }

2635
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
2636 2637 2638
        qemudLog(QEMUD_WARN,
                 _("QEMU guest config filename '%s'"
                   " does not match guest name '%s'"),
2639 2640 2641 2642 2643
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

2644
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
2645 2646 2647
        qemudLog(QEMUD_WARN,
                 _("Failed to load QEMU guest config '%s': out of memory"),
                 path);
2648 2649 2650 2651 2652 2653 2654
        qemudFreeVMDef(def);
        return NULL;
    }

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

2655 2656 2657
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

2658
    vm->autostart = virFileLinkPointsTo(vm->autostartLink, vm->configFile);
2659

2660 2661 2662 2663
    return vm;
}

static struct qemud_network *
2664
qemudLoadNetworkConfig(struct qemud_driver *driver,
2665 2666
                       const char *file,
                       const char *path,
2667 2668
                       const char *xml,
                       const char *autostartLink) {
2669 2670 2671
    struct qemud_network_def *def;
    struct qemud_network *network;

2672
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
2673
        virErrorPtr err = virGetLastError();
2674
        qemudLog(QEMUD_WARN, _("Error parsing network config '%s' : %s"),
2675
                 path, err->message);
2676 2677 2678
        return NULL;
    }

2679
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
2680 2681 2682
        qemudLog(QEMUD_WARN,
                 _("Network config filename '%s'"
                   " does not match network name '%s'"),
2683 2684 2685 2686 2687
                 path, def->name);
        qemudFreeNetworkDef(def);
        return NULL;
    }

2688
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
2689 2690
        qemudLog(QEMUD_WARN,
                 _("Failed to load network config '%s': out of memory"), path);
2691 2692 2693 2694 2695 2696 2697
        qemudFreeNetworkDef(def);
        return NULL;
    }

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

2698 2699 2700
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

2701
    network->autostart = virFileLinkPointsTo(network->autostartLink, network->configFile);
2702

2703 2704
    return network;
}
D
Daniel P. Berrange 已提交
2705

2706
static
2707
int qemudScanConfigDir(struct qemud_driver *driver,
2708
                       const char *configDir,
2709
                       const char *autostartDir,
2710
                       int isGuest) {
D
Daniel P. Berrange 已提交
2711 2712 2713
    DIR *dir;
    struct dirent *entry;

2714
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
2715 2716
        if (errno == ENOENT)
            return 0;
2717
        qemudLog(QEMUD_ERR, _("Failed to open dir '%s': %s"),
2718
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
2719 2720 2721 2722
        return -1;
    }

    while ((entry = readdir(dir))) {
2723
        char *xml;
2724
        char path[PATH_MAX];
2725
        char autostartLink[PATH_MAX];
2726

D
Daniel P. Berrange 已提交
2727 2728 2729
        if (entry->d_name[0] == '.')
            continue;

2730
        if (!virFileHasSuffix(entry->d_name, ".xml"))
2731 2732
            continue;

2733
        if (virFileBuildPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
2734
            qemudLog(QEMUD_WARN, _("Config filename '%s/%s' is too long"),
2735 2736 2737 2738
                     configDir, entry->d_name);
            continue;
        }

2739 2740 2741
        if (virFileBuildPath(autostartDir, entry->d_name, NULL,
                             autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, _("Autostart link path '%s/%s' is too long"),
2742 2743 2744 2745
                     autostartDir, entry->d_name);
            continue;
        }

2746
        if (virFileReadAll(path, QEMUD_MAX_XML_LEN, &xml) < 0)
D
Daniel P. Berrange 已提交
2747 2748
            continue;

2749
        if (isGuest)
2750
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
2751
        else
2752
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
2753 2754

        free(xml);
D
Daniel P. Berrange 已提交
2755 2756 2757
    }

    closedir(dir);
2758

D
Daniel P. Berrange 已提交
2759 2760 2761
    return 0;
}

2762
/* Scan for all guest and network config files */
2763 2764
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
2765
        return -1;
2766

2767
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
2768 2769 2770
        return -1;

    return 0;
2771
}
D
Daniel P. Berrange 已提交
2772 2773

/* Generate an XML document describing the guest's configuration */
2774 2775
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
2776 2777 2778
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
D
Daniel P. Berrange 已提交
2779
    virBufferPtr buf = 0;
D
Daniel P. Berrange 已提交
2780
    unsigned char *uuid;
2781
    char uuidstr[VIR_UUID_STRING_BUFLEN];
D
Daniel P. Berrange 已提交
2782 2783
    struct qemud_vm_disk_def *disk;
    struct qemud_vm_net_def *net;
2784
    struct qemud_vm_input_def *input;
D
Daniel P. Berrange 已提交
2785 2786 2787
    const char *type = NULL;
    int n;

D
Daniel P. Berrange 已提交
2788
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2789
    if (!buf)
2790 2791
        goto no_memory;

2792
    switch (def->virtType) {
D
Daniel P. Berrange 已提交
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
    case QEMUD_VIRT_QEMU:
        type = "qemu";
        break;
    case QEMUD_VIRT_KQEMU:
        type = "kqemu";
        break;
    case QEMUD_VIRT_KVM:
        type = "kvm";
        break;
    }
    if (!type) {
2804
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unexpected domain type %d", def->virtType);
D
Daniel P. Berrange 已提交
2805 2806 2807
        goto cleanup;
    }

2808
    if (qemudIsActiveVM(vm) && live) {
D
Daniel P. Berrange 已提交
2809
        if (virBufferVSprintf(buf, "<domain type='%s' id='%d'>\n", type, vm->id) < 0)
D
Daniel P. Berrange 已提交
2810 2811
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2812
        if (virBufferVSprintf(buf, "<domain type='%s'>\n", type) < 0)
D
Daniel P. Berrange 已提交
2813 2814 2815
            goto no_memory;
    }

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

2819
    uuid = def->uuid;
2820 2821
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
D
Daniel P. Berrange 已提交
2822
        goto no_memory;
2823
    if (virBufferVSprintf(buf, "  <memory>%lu</memory>\n", def->maxmem) < 0)
D
Daniel P. Berrange 已提交
2824
        goto no_memory;
2825
    if (virBufferVSprintf(buf, "  <currentMemory>%lu</currentMemory>\n", def->memory) < 0)
D
Daniel P. Berrange 已提交
2826
        goto no_memory;
D
Daniel P. Berrange 已提交
2827
    if (virBufferVSprintf(buf, "  <vcpu>%d</vcpu>\n", def->vcpus) < 0)
D
Daniel P. Berrange 已提交
2828 2829
        goto no_memory;

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

2833
    if (def->virtType == QEMUD_VIRT_QEMU) {
D
Daniel P. Berrange 已提交
2834
        if (virBufferVSprintf(buf, "    <type arch='%s' machine='%s'>%s</type>\n",
2835
                              def->os.arch, def->os.machine, def->os.type) < 0)
D
Daniel P. Berrange 已提交
2836 2837
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2838
        if (virBufferVSprintf(buf, "    <type>%s</type>\n", def->os.type) < 0)
D
Daniel P. Berrange 已提交
2839 2840 2841
            goto no_memory;
    }

2842
    if (def->os.kernel[0])
D
Daniel P. Berrange 已提交
2843
        if (virBufferVSprintf(buf, "    <kernel>%s</kernel>\n", def->os.kernel) < 0)
D
Daniel P. Berrange 已提交
2844
            goto no_memory;
2845
    if (def->os.initrd[0])
D
Daniel P. Berrange 已提交
2846
        if (virBufferVSprintf(buf, "    <initrd>%s</initrd>\n", def->os.initrd) < 0)
D
Daniel P. Berrange 已提交
2847
            goto no_memory;
2848
    if (def->os.cmdline[0])
D
Daniel P. Berrange 已提交
2849
        if (virBufferVSprintf(buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline) < 0)
D
Daniel P. Berrange 已提交
2850 2851
            goto no_memory;

2852
    for (n = 0 ; n < def->os.nBootDevs ; n++) {
D
Daniel P. Berrange 已提交
2853
        const char *boottype = "hd";
2854
        switch (def->os.bootDevs[n]) {
D
Daniel P. Berrange 已提交
2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
        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:
2865
            boottype = "network";
D
Daniel P. Berrange 已提交
2866 2867
            break;
        }
D
Daniel P. Berrange 已提交
2868
        if (virBufferVSprintf(buf, "    <boot dev='%s'/>\n", boottype) < 0)
D
Daniel P. Berrange 已提交
2869 2870 2871
            goto no_memory;
    }

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

2875
    if (def->features & QEMUD_FEATURE_ACPI) {
2876
        if (virBufferAddLit(buf, "  <features>\n") < 0)
2877
            goto no_memory;
2878
        if (virBufferAddLit(buf, "    <acpi/>\n") < 0)
2879
            goto no_memory;
2880
        if (virBufferAddLit(buf, "  </features>\n") < 0)
2881 2882 2883
            goto no_memory;
    }

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

2886
    if (virBufferAddLit(buf, "  <on_poweroff>destroy</on_poweroff>\n") < 0)
D
Daniel P. Berrange 已提交
2887 2888
        goto no_memory;
    if (def->noReboot) {
2889
        if (virBufferAddLit(buf, "  <on_reboot>destroy</on_reboot>\n") < 0)
D
Daniel P. Berrange 已提交
2890 2891
            goto no_memory;
    } else {
2892
        if (virBufferAddLit(buf, "  <on_reboot>restart</on_reboot>\n") < 0)
D
Daniel P. Berrange 已提交
2893 2894
            goto no_memory;
    }
2895
    if (virBufferAddLit(buf, "  <on_crash>destroy</on_crash>\n") < 0)
D
Daniel P. Berrange 已提交
2896
        goto no_memory;
2897

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

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

2904
    disk = def->disks;
D
Daniel P. Berrange 已提交
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
D
Daniel P. Berrange 已提交
2919
        if (virBufferVSprintf(buf, "    <disk type='%s' device='%s'>\n",
D
Daniel P. Berrange 已提交
2920 2921 2922
                              types[disk->type], devices[disk->device]) < 0)
            goto no_memory;

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

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

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

2935
        if (virBufferAddLit(buf, "    </disk>\n") < 0)
D
Daniel P. Berrange 已提交
2936 2937 2938 2939 2940
            goto no_memory;

        disk = disk->next;
    }

2941
    net = def->nets;
2942
    while (net) {
D
Daniel P. Berrange 已提交
2943 2944
        const char *types[] = {
            "user",
2945
            "ethernet",
D
Daniel P. Berrange 已提交
2946 2947 2948
            "server",
            "client",
            "mcast",
2949
            "network",
2950
            "bridge",
D
Daniel P. Berrange 已提交
2951
        };
D
Daniel P. Berrange 已提交
2952
        if (virBufferVSprintf(buf, "    <interface type='%s'>\n",
D
Daniel P. Berrange 已提交
2953 2954 2955
                              types[net->type]) < 0)
            goto no_memory;

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

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

2966
            if (net->dst.network.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2967
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.network.ifname) < 0)
2968 2969 2970
                    goto no_memory;
            }
            break;
2971

2972 2973
        case QEMUD_NET_ETHERNET:
            if (net->dst.ethernet.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2974
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname) < 0)
2975 2976 2977
                    goto no_memory;
            }
            if (net->dst.ethernet.script[0] != '\0') {
D
Daniel P. Berrange 已提交
2978
                if (virBufferVSprintf(buf, "      <script path='%s'/>\n", net->dst.ethernet.script) < 0)
2979 2980 2981 2982 2983
                    goto no_memory;
            }
            break;

        case QEMUD_NET_BRIDGE:
D
Daniel P. Berrange 已提交
2984
            if (virBufferVSprintf(buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname) < 0)
2985
                goto no_memory;
2986
            if (net->dst.bridge.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2987
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname) < 0)
2988 2989 2990 2991 2992 2993 2994 2995
                    goto no_memory;
            }
            break;

        case QEMUD_NET_SERVER:
        case QEMUD_NET_CLIENT:
        case QEMUD_NET_MCAST:
            if (net->dst.socket.address[0] != '\0') {
D
Daniel P. Berrange 已提交
2996
                if (virBufferVSprintf(buf, "      <source address='%s' port='%d'/>\n",
2997 2998 2999
                                      net->dst.socket.address, net->dst.socket.port) < 0)
                    goto no_memory;
            } else {
D
Daniel P. Berrange 已提交
3000
                if (virBufferVSprintf(buf, "      <source port='%d'/>\n",
3001 3002 3003
                                      net->dst.socket.port) < 0)
                    goto no_memory;
            }
3004 3005
        }

3006
        if (virBufferAddLit(buf, "    </interface>\n") < 0)
D
Daniel P. Berrange 已提交
3007 3008
            goto no_memory;

3009
        net = net->next;
D
Daniel P. Berrange 已提交
3010 3011
    }

3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
    input = def->inputs;
    while (input) {
        if (input->bus != QEMU_INPUT_BUS_PS2 &&
            virBufferVSprintf(buf, "    <input type='%s' bus='usb'/>\n",
                              input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet") < 0)
            goto no_memory;
        input = input->next;
    }
    /* If graphics is enable, add implicit mouse */
    if (def->graphicsType != QEMUD_GRAPHICS_NONE)
3022
        if (virBufferAddLit(buf, "    <input type='mouse' bus='ps2'/>\n") < 0)
3023 3024
            goto no_memory;

3025 3026
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
3027
        if (virBufferAddLit(buf, "    <graphics type='vnc'") < 0)
3028 3029 3030
            goto no_memory;

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

3035 3036 3037 3038 3039
        if (def->vncListen[0] &&
            virBufferVSprintf(buf, " listen='%s'",
                              def->vncListen) < 0)
            goto no_memory;

3040 3041 3042 3043 3044
        if (def->keymap &&
            virBufferVSprintf(buf, " keymap='%s'",
                              def->keymap) < 0)
            goto no_memory;

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

    case QEMUD_GRAPHICS_SDL:
3050
        if (virBufferAddLit(buf, "    <graphics type='sdl'/>\n") < 0)
3051 3052 3053 3054 3055 3056 3057 3058
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

3059
    if (def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
3060 3061
    }

3062
    if (virBufferAddLit(buf, "  </devices>\n") < 0)
D
Daniel P. Berrange 已提交
3063 3064 3065
        goto no_memory;


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

D
Daniel P. Berrange 已提交
3069
    return virBufferContentAndFree (buf);
D
Daniel P. Berrange 已提交
3070 3071

 no_memory:
3072
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
3073
 cleanup:
D
Daniel P. Berrange 已提交
3074
    if (buf) virBufferFree (buf);
D
Daniel P. Berrange 已提交
3075 3076 3077 3078
    return NULL;
}


3079 3080
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
3081
                              struct qemud_network *network,
3082
                              struct qemud_network_def *def) {
D
Daniel P. Berrange 已提交
3083
    virBufferPtr buf = 0;
3084
    unsigned char *uuid;
3085
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3086

D
Daniel P. Berrange 已提交
3087
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
3088
    if (!buf)
3089 3090
        goto no_memory;

3091
    if (virBufferAddLit(buf, "<network>\n") < 0)
3092 3093
        goto no_memory;

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

3097
    uuid = def->uuid;
3098 3099
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
3100 3101
        goto no_memory;

3102 3103
    if (def->forward) {
        if (def->forwardDev[0]) {
D
Daniel P. Berrange 已提交
3104
            virBufferVSprintf(buf, "  <forward dev='%s'/>\n",
3105 3106
                              def->forwardDev);
        } else {
3107
            virBufferAddLit(buf, "  <forward/>\n");
3108 3109 3110
        }
    }

3111
    virBufferAddLit(buf, "  <bridge");
3112
    if (qemudIsActiveNetwork(network)) {
D
Daniel P. Berrange 已提交
3113
        if (virBufferVSprintf(buf, " name='%s'", network->bridge) < 0)
3114 3115
            goto no_memory;
    } else if (def->bridge[0]) {
D
Daniel P. Berrange 已提交
3116
        if (virBufferVSprintf(buf, " name='%s'", def->bridge) < 0)
3117 3118
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
3119
    if (virBufferVSprintf(buf, " stp='%s' forwardDelay='%d' />\n",
3120 3121
                       def->disableSTP ? "off" : "on",
                       def->forwardDelay) < 0)
3122 3123
        goto no_memory;

3124
    if (def->ipAddress[0] || def->netmask[0]) {
3125
        if (virBufferAddLit(buf, "  <ip") < 0)
3126 3127
            goto no_memory;

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

3132
        if (def->netmask[0] &&
D
Daniel P. Berrange 已提交
3133
            virBufferVSprintf(buf, " netmask='%s'", def->netmask) < 0)
3134 3135
            goto no_memory;

3136
        if (virBufferAddLit(buf, ">\n") < 0)
3137 3138
            goto no_memory;

3139 3140
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
3141
            if (virBufferAddLit(buf, "    <dhcp>\n") < 0)
3142 3143
                goto no_memory;
            while (range) {
D
Daniel P. Berrange 已提交
3144
                if (virBufferVSprintf(buf, "      <range start='%s' end='%s' />\n",
3145 3146 3147 3148
                                      range->start, range->end) < 0)
                    goto no_memory;
                range = range->next;
            }
3149
            if (virBufferAddLit(buf, "    </dhcp>\n") < 0)
3150 3151 3152
                goto no_memory;
        }

3153
        if (virBufferAddLit(buf, "  </ip>\n") < 0)
3154
            goto no_memory;
D
Daniel P. Berrange 已提交
3155 3156
    }

3157
    if (virBufferAddLit(buf, "</network>\n") < 0)
3158 3159
        goto no_memory;

D
Daniel P. Berrange 已提交
3160
    return virBufferContentAndFree (buf);
3161 3162

 no_memory:
3163
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
3164
    if (buf) virBufferFree (buf);
3165 3166 3167 3168
    return NULL;
}


3169 3170
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
3171 3172 3173
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
3174
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "no config file for %s", name);
D
Daniel P. Berrange 已提交
3175 3176 3177
        return -1;
    }

3178
    if (unlink(configFile) < 0) {
3179
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot remove config for %s", name);
3180 3181
        return -1;
    }
3182

D
Daniel P. Berrange 已提交
3183 3184 3185
    return 0;
}

3186
#endif /* WITH_QEMU */
D
Daniel P. Berrange 已提交
3187 3188 3189 3190 3191 3192 3193 3194 3195

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