qemu_conf.c 105.5 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
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,
85
                         "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
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
        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,
120
                             "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
            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
                         _("Cannot find QEMU binary %s: %s"), binary,
534 535 536 537
                         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 617
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid floppy device name: %s"), target);
D
Daniel P. Berrange 已提交
618 619
        goto error;
    }
620

D
Daniel P. Berrange 已提交
621 622 623
    if (device &&
        !strcmp((const char *)device, "cdrom") &&
        strcmp((const char *)target, "hdc")) {
624 625
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid cdrom device name: %s"), target);
D
Daniel P. Berrange 已提交
626 627 628 629 630 631 632 633 634 635 636 637
        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")) {
638 639
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid harddisk device name: %s"), target);
D
Daniel P. Berrange 已提交
640 641 642
        goto error;
    }

643
    strncpy(disk->src, (source ? (const char *) source : "\0"), NAME_MAX-1);
D
Daniel P. Berrange 已提交
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
    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 {
659 660
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid device type: %s"), device);
D
Daniel P. Berrange 已提交
661 662 663 664 665 666 667
        goto error;
    }

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

D
Daniel P. Berrange 已提交
668
    return 0;
D
Daniel P. Berrange 已提交
669 670 671 672 673 674 675 676 677 678

 error:
    if (type)
        xmlFree(type);
    if (target)
        xmlFree(target);
    if (source)
        xmlFree(source);
    if (device)
        xmlFree(device);
D
Daniel P. Berrange 已提交
679
    return -1;
D
Daniel P. Berrange 已提交
680 681
}

682 683 684 685 686 687 688 689 690
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 已提交
691

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

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

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

        xmlFree(macaddr);
792 793 794
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
795 796
    }

797 798 799 800
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

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

813
        if (network) {
814
            xmlFree(network);
815 816 817 818 819
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
820
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
821 822
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
823 824 825 826 827 828 829 830 831 832
                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;
833

834 835
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
836
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
837
                                 _("TAP script path '%s' is too long"), script);
838 839 840 841 842 843 844 845 846 847
                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)) {
848
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
849 850
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
851 852
                goto error;
            } else {
853 854
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
855
            }
856 857 858 859 860 861
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

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

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
879
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
880
                                 _("TAP interface name '%s' is too long"), ifname);
881 882 883 884 885 886 887 888 889 890
                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) {
891
        int len = 0;
892 893 894
        char *ret;

        if (port == NULL) {
895
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
896
                             "%s", _("No <source> 'port' attribute specified with socket interface"));
897 898 899 900
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
901
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
902
                             "%s", _("Cannot parse <source> 'port' attribute with socket interface"));
903 904 905 906 907 908 909 910
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
911
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
912
                                 "%s", _("No <source> 'address' attribute specified with socket interface"));
913 914 915
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
916
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
917
                             _("IP address '%s' is too long"), address);
918 919 920 921 922 923 924 925 926
            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);
927 928
    }

D
Daniel P. Berrange 已提交
929
    return 0;
930 931 932 933

 error:
    if (network)
        xmlFree(network);
934 935 936 937 938 939 940 941 942 943
    if (address)
        xmlFree(address);
    if (port)
        xmlFree(port);
    if (ifname)
        xmlFree(ifname);
    if (script)
        xmlFree(script);
    if (bridge)
        xmlFree(bridge);
D
Daniel P. Berrange 已提交
944
    return -1;
D
Daniel P. Berrange 已提交
945 946 947
}


948
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
949 950 951
static int qemudParseInputXML(virConnectPtr conn,
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
952 953 954 955 956 957 958
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

    if (!type) {
959 960
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing input device type"));
961 962 963 964 965 966 967 968
        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 {
969 970 971
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unsupported input device type %s"),
                         (const char*)type);
972 973 974 975 976 977
        goto error;
    }

    if (bus) {
        if (!strcmp((const char*)bus, "ps2")) { /* Only allow mouse */
            if (input->type == QEMU_INPUT_TYPE_TABLET) {
978 979 980
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("ps2 bus does not support %s input device"),
                                 (const char*)type);
981 982 983 984 985 986
                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 {
987 988
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("unsupported input bus %s"), (const char*)bus);
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
            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 已提交
1003
    return 0;
1004 1005 1006 1007 1008 1009 1010

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

D
Daniel P. Berrange 已提交
1011
    return -1;
1012 1013 1014
}


D
Daniel P. Berrange 已提交
1015 1016 1017 1018
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
1019 1020
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
1021
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
1022 1023 1024 1025 1026 1027
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
1028 1029
    struct qemud_vm_def *def;

1030
    if (!(def = calloc(1, sizeof(*def)))) {
1031 1032
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
1033 1034
        return NULL;
    }
D
Daniel P. Berrange 已提交
1035 1036 1037 1038

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
1039 1040
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
D
Daniel P. Berrange 已提交
1041 1042 1043 1044 1045
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1046 1047
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
D
Daniel P. Berrange 已提交
1048 1049 1050 1051 1052 1053
        goto error;
    }


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

    if (!strcmp((char *)prop, "qemu"))
1060
        def->virtType = QEMUD_VIRT_QEMU;
D
Daniel P. Berrange 已提交
1061
    else if (!strcmp((char *)prop, "kqemu"))
1062
        def->virtType = QEMUD_VIRT_KQEMU;
D
Daniel P. Berrange 已提交
1063
    else if (!strcmp((char *)prop, "kvm"))
1064
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
1065
    else {
1066 1067
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("invalid domain type attribute"));
D
Daniel P. Berrange 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
        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)) {
1078
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
1079 1080 1081
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1082 1083
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("domain name length too long"));
D
Daniel P. Berrange 已提交
1084 1085
        goto error;
    }
1086
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1087 1088 1089 1090 1091 1092 1093
    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)) {
1094
        int err;
D
Daniel P. Berrange 已提交
1095
        if ((err = virUUIDGenerate(def->uuid))) {
1096
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1097
                             _("Failed to generate UUID: %s"), strerror(err));
1098 1099
            goto error;
        }
D
Daniel P. Berrange 已提交
1100
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
1101 1102
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
D
Daniel P. Berrange 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111
        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)) {
1112 1113
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing memory element"));
D
Daniel P. Berrange 已提交
1114 1115 1116
        goto error;
    } else {
        conv = NULL;
1117
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1118
        if (conv == (const char*)obj->stringval) {
1119 1120
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1121 1122 1123
            goto error;
        }
    }
1124
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1125 1126 1127 1128 1129 1130


    /* 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)) {
1131
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1132 1133
    } else {
        conv = NULL;
1134 1135 1136
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1137
        if (conv == (const char*)obj->stringval) {
1138 1139
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1140 1141 1142
            goto error;
        }
    }
1143
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1144 1145 1146 1147 1148

    /* 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)) {
1149
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1150 1151
    } else {
        conv = NULL;
1152
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1153
        if (conv == (const char*)obj->stringval) {
1154 1155
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed vcpu information"));
D
Daniel P. Berrange 已提交
1156 1157 1158
            goto error;
        }
    }
1159
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1160 1161 1162 1163 1164

    /* 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)) {
1165
        def->features |= QEMUD_FEATURE_ACPI;
D
Daniel P. Berrange 已提交
1166
    }
1167
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1168

D
Daniel P. Berrange 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180

    /* 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;
    }
1181
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1182

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    /* 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;
    }
1194
    xmlXPathFreeObject(obj);
1195

D
Daniel P. Berrange 已提交
1196

D
Daniel P. Berrange 已提交
1197 1198 1199 1200
    /* 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)) {
1201 1202
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
                         "%s", _("no OS type"));
D
Daniel P. Berrange 已提交
1203 1204
        goto error;
    }
1205
    if (!virCapabilitiesSupportsGuestOSType(driver->caps, (const char*)obj->stringval)) {
1206 1207
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
                         "%s", obj->stringval);
D
Daniel P. Berrange 已提交
1208 1209
        goto error;
    }
1210
    strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1211 1212 1213 1214 1215 1216
    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)) {
1217 1218
        const char *defaultArch = virCapabilitiesDefaultGuestArch(driver->caps, def->os.type);
        if (defaultArch == NULL) {
1219 1220
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1221 1222
            goto error;
        }
D
Daniel P. Berrange 已提交
1223
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1224 1225
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1226 1227
            goto error;
        }
1228
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
1229 1230
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1231 1232
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1233 1234
            goto error;
        }
1235
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1236
    }
1237
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1238 1239 1240 1241

    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)) {
1242 1243 1244 1245
        const char *defaultMachine = virCapabilitiesDefaultGuestMachine(driver->caps,
                                                                        def->os.type,
                                                                        def->os.arch);
        if (defaultMachine == NULL) {
1246 1247
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1248 1249
            goto error;
        }
D
Daniel P. Berrange 已提交
1250
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1251 1252
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("machine type too long"));
D
Daniel P. Berrange 已提交
1253 1254
            goto error;
        }
1255
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1256 1257
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1258 1259
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1260 1261
            goto error;
        }
1262
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1263
    }
1264
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1265 1266 1267 1268 1269 1270


    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)) {
1271 1272
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("kernel path too long"));
D
Daniel P. Berrange 已提交
1273 1274
            goto error;
        }
1275
        strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1276
    }
1277
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1278 1279 1280 1281 1282 1283


    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)) {
1284 1285
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("initrd path too long"));
D
Daniel P. Berrange 已提交
1286 1287
            goto error;
        }
1288
        strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1289
    }
1290
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1291 1292 1293 1294 1295 1296


    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)) {
1297 1298
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("cmdline arguments too long"));
D
Daniel P. Berrange 已提交
1299 1300
            goto error;
        }
1301
        strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1302
    }
1303
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1304 1305 1306 1307 1308 1309 1310


    /* 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++) {
1311 1312
            if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                continue;
D
Daniel P. Berrange 已提交
1313
            if (!strcmp((char *)prop, "hd")) {
1314
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1315
            } else if (!strcmp((char *)prop, "fd")) {
1316
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
D
Daniel P. Berrange 已提交
1317
            } else if (!strcmp((char *)prop, "cdrom")) {
1318
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
1319
            } else if (!strcmp((char *)prop, "network")) {
1320
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
D
Daniel P. Berrange 已提交
1321
            } else {
1322
	        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1323
                             _("unknown boot device \'%s\'"), (char*)prop);
D
Daniel P. Berrange 已提交
1324 1325
                goto error;
            }
1326
            xmlFree(prop);
1327
            prop = NULL;
D
Daniel P. Berrange 已提交
1328 1329 1330
        }
    }
    xmlXPathFreeObject(obj);
1331 1332 1333
    if (def->os.nBootDevs == 0) {
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1334 1335 1336 1337 1338 1339
    }


    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1340 1341 1342 1343 1344 1345 1346 1347
        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) {
1348 1349
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported guest type"));
D
Daniel P. Berrange 已提交
1350 1351
            goto error;
        }
1352
        strcpy(def->os.binary, emulator);
D
Daniel P. Berrange 已提交
1353 1354
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1355 1356
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("emulator path too long"));
D
Daniel P. Berrange 已提交
1357 1358
            goto error;
        }
1359
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1360
    }
1361
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1362 1363 1364 1365

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1366
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1367
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
D
Daniel P. Berrange 已提交
1368
        if (!strcmp((char *)prop, "vnc")) {
1369
            xmlChar *vncport, *vnclisten;
1370
            def->graphicsType = QEMUD_GRAPHICS_VNC;
1371 1372
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
1373
                conv = NULL;
1374
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
1375
            } else {
1376
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1377
            }
1378 1379 1380 1381
            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 已提交
1382
                strcpy(def->vncListen, driver->vncListen);
1383
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
1384
            def->keymap = (char *) xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "keymap");
1385 1386
            xmlFree(vncport);
            xmlFree(vnclisten);
D
Daniel P. Berrange 已提交
1387
        } else if (!strcmp((char *)prop, "sdl")) {
1388
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1389
        } else {
1390 1391
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Unsupported graphics type %s"), prop);
D
Daniel P. Berrange 已提交
1392 1393
            goto error;
        }
1394
        xmlFree(prop);
1395
        prop = NULL;
D
Daniel P. Berrange 已提交
1396
    }
1397
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1398 1399 1400 1401 1402

    /* 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)) {
1403
        struct qemud_vm_disk_def *prev = NULL;
D
Daniel P. Berrange 已提交
1404
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1405
            struct qemud_vm_disk_def *disk = calloc(1, sizeof(*disk));
D
Daniel P. Berrange 已提交
1406
            if (!disk) {
1407 1408
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for disk string"));
D
Daniel P. Berrange 已提交
1409 1410 1411 1412
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
                free(disk);
D
Daniel P. Berrange 已提交
1413 1414
                goto error;
            }
1415
            def->ndisks++;
1416 1417 1418 1419 1420 1421 1422
            disk->next = NULL;
            if (i == 0) {
                def->disks = disk;
            } else {
                prev->next = disk;
            }
            prev = disk;
D
Daniel P. Berrange 已提交
1423 1424 1425 1426 1427 1428 1429 1430 1431
        }
    }
    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)) {
1432
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
1433
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1434
            struct qemud_vm_net_def *net = calloc(1, sizeof(*net));
D
Daniel P. Berrange 已提交
1435
            if (!net) {
1436 1437
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for net string"));
D
Daniel P. Berrange 已提交
1438 1439 1440 1441
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
                free(net);
D
Daniel P. Berrange 已提交
1442 1443
                goto error;
            }
1444
            def->nnets++;
1445 1446 1447 1448 1449 1450 1451
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
1452 1453 1454
        }
    }
    xmlXPathFreeObject(obj);
1455 1456 1457 1458 1459 1460 1461

    /* 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++) {
1462
            struct qemud_vm_input_def *input = calloc(1, sizeof(*input));
D
Daniel P. Berrange 已提交
1463
            if (!input) {
1464 1465
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
D
Daniel P. Berrange 已提交
1466 1467 1468 1469
                goto error;
            }
            if (qemudParseInputXML(conn, input, obj->nodesetval->nodeTab[i]) < 0) {
                free(input);
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
                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;
1480
            if (def->inputs == NULL) {
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
                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) {
1503
            input = calloc(1, sizeof(*input));
1504
            if (!input) {
1505 1506
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
                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 已提交
1517 1518
    xmlXPathFreeContext(ctxt);

1519
    return def;
D
Daniel P. Berrange 已提交
1520 1521

 error:
1522
    free(prop);
1523
    xmlXPathFreeObject(obj);
1524
    xmlXPathFreeContext(ctxt);
1525 1526
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
1527 1528 1529
}


1530
static char *
1531 1532
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
1533
                         struct qemud_vm *vm,
1534 1535
                         struct qemud_vm_net_def *net,
                         int vlan)
1536
{
1537 1538 1539
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
1540 1541 1542 1543 1544 1545
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

1546
    if (net->type == QEMUD_NET_NETWORK) {
1547
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
1548
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1549 1550
                             _("Network '%s' not found"),
                             net->dst.network.name);
1551 1552
            goto error;
        } else if (network->bridge[0] == '\0') {
1553
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1554 1555
                             _("Network '%s' not active"),
                             net->dst.network.name);
1556 1557 1558 1559
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
1560
            STREQLEN(net->dst.network.ifname, "vnet", 4) ||
1561 1562 1563 1564 1565 1566 1567
            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' ||
1568
            STREQLEN(net->dst.bridge.ifname, "vnet", 4) ||
1569 1570 1571 1572 1573
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
1574
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1575
                         _("Network type %d is not supported"), net->type);
1576 1577 1578
        goto error;
    }

1579
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
1580
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1581 1582
                         _("cannot initialize bridge support: %s"),
                         strerror(err));
1583 1584 1585
        goto error;
    }

1586
    if ((err = brAddTap(driver->brctl, brname,
1587
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
1588
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1589
                     _("Failed to add tap interface '%s' to bridge '%s' : %s"),
1590
                         ifname, brname, strerror(err));
1591 1592 1593
        goto error;
    }

1594 1595 1596
    snprintf(tapfdstr, sizeof(tapfdstr),
             "tap,fd=%d,script=,vlan=%d,ifname=%s",
             tapfd, vlan, ifname);
1597 1598 1599 1600

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

1601
    if (!(tapfds = realloc(vm->tapfds, sizeof(*tapfds) * (vm->ntapfds+2))))
1602 1603 1604 1605 1606 1607 1608 1609 1610
        goto no_memory;

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

    return retval;

 no_memory:
1611 1612
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for tapfds string"));
1613
 error:
1614
    free(retval);
1615 1616 1617 1618 1619
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

D
Daniel P. Berrange 已提交
1620 1621 1622 1623
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
1624 1625
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
1626
                          struct qemud_vm *vm,
1627 1628
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
1629 1630 1631
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
1632
    struct stat sb;
1633 1634
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
1635
    struct qemud_vm_input_def *input = vm->def->inputs;
1636 1637
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
1638

1639 1640 1641 1642 1643 1644
    /* 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,
1645 1646
                         _("Cannot find QEMU binary %s: %s"),
                         vm->def->os.binary,
1647
                         strerror(errno));
1648
        return -1;
1649 1650 1651 1652 1653 1654 1655 1656
    }

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

1658 1659
    uname(&ut);

D
Daniel P. Berrange 已提交
1660
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
1661 1662 1663 1664
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
1665
        ut.machine[1] = '6';
1666 1667 1668 1669 1670 1671

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

1677
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
1678
        2 + /* machine type */
1679
        disableKQEMU + /* Disable kqemu */
1680 1681
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
1682 1683
        1 + /* usb */
        2 * vm->def->ninputs + /* input devices */
D
Daniel P. Berrange 已提交
1684 1685 1686 1687
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
1688
        (vm->def->localtime ? 1 : 0) + /* localtime */
1689
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1690
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
1691 1692 1693 1694 1695
        (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 :
1696 1697
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)) + /* graphics */
        (vm->migrateFrom[0] ? 3 : 0); /* migrateFrom */
D
Daniel P. Berrange 已提交
1698

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

1702
    if (!(*argv = malloc(sizeof(**argv) * (len+1))))
D
Daniel P. Berrange 已提交
1703
        goto no_memory;
1704
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
1705 1706 1707
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
1708
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
1709
        goto no_memory;
1710
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
1711
        if (!((*argv)[++n] = strdup("-no-kqemu")))
1712
            goto no_memory;
D
Daniel P. Berrange 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722
    }
    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;

1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
    /*
     * 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 已提交
1735 1736 1737 1738 1739
    if (!((*argv)[++n] = strdup("-monitor")))
        goto no_memory;
    if (!((*argv)[++n] = strdup("pty")))
        goto no_memory;

1740 1741 1742 1743 1744
    if (vm->def->localtime) {
        if (!((*argv)[++n] = strdup("-localtime")))
            goto no_memory;
    }

1745
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1746 1747 1748 1749 1750
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

1751
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
1752 1753
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
1754 1755
    }

1756 1757
    for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
        switch (vm->def->os.bootDevs[i]) {
D
Daniel P. Berrange 已提交
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
        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;
        }
    }
1775
    boot[vm->def->os.nBootDevs] = '\0';
D
Daniel P. Berrange 已提交
1776 1777 1778 1779 1780
    if (!((*argv)[++n] = strdup("-boot")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(boot)))
        goto no_memory;

1781
    if (vm->def->os.kernel[0]) {
D
Daniel P. Berrange 已提交
1782 1783
        if (!((*argv)[++n] = strdup("-kernel")))
            goto no_memory;
1784
        if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
D
Daniel P. Berrange 已提交
1785 1786
            goto no_memory;
    }
1787
    if (vm->def->os.initrd[0]) {
D
Daniel P. Berrange 已提交
1788 1789
        if (!((*argv)[++n] = strdup("-initrd")))
            goto no_memory;
1790
        if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
D
Daniel P. Berrange 已提交
1791 1792
            goto no_memory;
    }
1793
    if (vm->def->os.cmdline[0]) {
D
Daniel P. Berrange 已提交
1794 1795
        if (!((*argv)[++n] = strdup("-append")))
            goto no_memory;
1796
        if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
D
Daniel P. Berrange 已提交
1797 1798 1799 1800 1801 1802 1803
            goto no_memory;
    }

    while (disk) {
        char dev[NAME_MAX];
        char file[PATH_MAX];
        if (!strcmp(disk->dst, "hdc") &&
1804 1805 1806 1807 1808 1809 1810 1811 1812
            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 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
            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 {
1830
        int vlan = 0;
D
Daniel P. Berrange 已提交
1831
        while (net) {
1832
            char nic[100];
1833

1834 1835 1836 1837 1838 1839
            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 已提交
1840 1841 1842 1843 1844

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

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

1849 1850 1851
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
1852
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
1853
                    goto error;
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
                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;
                }
1909
            }
D
Daniel P. Berrange 已提交
1910 1911

            net = net->next;
1912
            vlan++;
D
Daniel P. Berrange 已提交
1913 1914 1915
        }
    }

1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
    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;
    }

1929
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
1930
        char vncdisplay[PATH_MAX];
1931
        int ret;
D
Daniel P. Berrange 已提交
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946

        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",
1947
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
1948 1949 1950
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
1951 1952
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
1953
        }
1954
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
1955 1956
            goto error;

D
Daniel P. Berrange 已提交
1957 1958
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
1959
        if (!((*argv)[++n] = strdup(vncdisplay)))
D
Daniel P. Berrange 已提交
1960
            goto no_memory;
1961 1962 1963 1964 1965 1966
        if (vm->def->keymap) {
            if (!((*argv)[++n] = strdup("-k")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->keymap)))
                goto no_memory;
        }
1967
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
1968
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
1969 1970 1971 1972
    } else {
        /* SDL is the default. no args needed */
    }

1973 1974 1975 1976 1977 1978 1979 1980 1981
    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 已提交
1982 1983 1984 1985 1986
    (*argv)[++n] = NULL;

    return 0;

 no_memory:
1987 1988
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for argv string"));
1989 1990 1991 1992 1993 1994 1995 1996
 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 已提交
1997 1998
    if (argv) {
        for (i = 0 ; i < n ; i++)
1999 2000
            free((*argv)[i]);
        free(*argv);
D
Daniel P. Berrange 已提交
2001 2002 2003 2004 2005 2006
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
2007 2008
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
2009 2010
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
2011 2012 2013 2014
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

2015
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
2016 2017 2018 2019 2020
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2021
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2022
                         _("cannot create config file %s: %s"),
2023
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2024 2025 2026 2027
        goto cleanup;
    }

    towrite = strlen(xml);
2028
    if (safewrite(fd, xml, towrite) < 0) {
2029
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2030
                         _("cannot write config file %s: %s"),
2031
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2032 2033 2034 2035
        goto cleanup;
    }

    if (close(fd) < 0) {
2036
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2037
                         _("cannot save config file %s: %s"),
2038
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
        goto cleanup;
    }

    ret = 0;

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

    free(xml);

    return ret;
}

D
Daniel P. Berrange 已提交
2053 2054 2055 2056 2057 2058 2059
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
2060
    struct qemud_vm_device_def *dev = calloc(1, sizeof(*dev));
D
Daniel P. Berrange 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070

    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) {
2071 2072
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("missing root element"));
D
Daniel P. Berrange 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084
        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 {
2085 2086
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("unknown device type"));
D
Daniel P. Berrange 已提交
2087 2088 2089 2090 2091 2092 2093 2094 2095
        goto error;
    }

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
2096
    free(dev);
D
Daniel P. Berrange 已提交
2097 2098 2099
    return NULL;
}

2100
struct qemud_vm_def *
2101 2102
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
2103 2104
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
2105
    xmlDocPtr xml;
2106
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
2107

2108
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
2109 2110
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2111
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
2112 2113 2114
        return NULL;
    }

2115
    def = qemudParseXML(conn, driver, xml);
2116

D
Daniel P. Berrange 已提交
2117 2118
    xmlFreeDoc(xml);

2119 2120 2121 2122
    return def;
}

struct qemud_vm *
2123 2124
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
2125 2126 2127 2128
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

2129
    if ((vm = qemudFindVMByName(driver, def->name))) {
2130
        if (!qemudIsActiveVM(vm)) {
2131 2132 2133 2134 2135 2136 2137
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
2138 2139 2140
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
2141
        return vm;
D
Daniel P. Berrange 已提交
2142 2143
    }

2144
    if (!(vm = calloc(1, sizeof(*vm)))) {
2145 2146
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for vm string"));
2147 2148
        return NULL;
    }
D
Daniel P. Berrange 已提交
2149

2150
    vm->stdin = -1;
2151 2152 2153 2154 2155
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
2156
    vm->state = VIR_DOMAIN_SHUTOFF;
2157
    vm->def = def;
2158
    vm->next = driver->vms;
2159

2160 2161
    driver->vms = vm;
    driver->ninactivevms++;
2162 2163 2164 2165 2166

    return vm;
}

void
2167
qemudRemoveInactiveVM(struct qemud_driver *driver,
2168 2169 2170 2171
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

2172
    curr = driver->vms;
2173 2174 2175
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
2176 2177
    }

2178 2179 2180 2181
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2182
            driver->vms = curr->next;
2183

2184
        driver->ninactivevms--;
2185 2186
    }

2187
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
2188 2189
}

2190
int
2191 2192
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
2193 2194 2195 2196 2197
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

2198
        if ((err = virFileMakePath(driver->configDir))) {
2199
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2200
                             _("cannot create config directory %s: %s"),
2201
                             driver->configDir, strerror(err));
2202 2203 2204
            return -1;
        }

2205 2206
        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             vm->configFile, PATH_MAX) < 0) {
2207
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2208
                             "%s", _("cannot construct config file path"));
2209 2210
            return -1;
        }
2211

2212 2213
        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             vm->autostartLink, PATH_MAX) < 0) {
2214
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2215
                             "%s", _("cannot construct autostart link path"));
2216 2217 2218
            vm->configFile[0] = '\0';
            return -1;
        }
2219 2220
    }

2221
    return qemudSaveConfig(conn, driver, vm, def);
2222
}
D
Daniel P. Berrange 已提交
2223

2224 2225
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
2226 2227
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
2228 2229 2230
    char *xml;
    int fd, ret = -1;
    int towrite;
2231
    int err;
2232

2233
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
2234 2235 2236
        return -1;
    }

2237
    if ((err = virFileMakePath(driver->networkConfigDir))) {
2238
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2239
                         _("cannot create config directory %s: %s"),
2240
                         driver->networkConfigDir, strerror(err));
2241 2242 2243 2244 2245 2246
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2247
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2248
                         _("cannot create config file %s: %s"),
2249
                         network->configFile, strerror(errno));
2250 2251 2252 2253
        goto cleanup;
    }

    towrite = strlen(xml);
2254
    if (safewrite(fd, xml, towrite) < 0) {
2255
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2256
                         _("cannot write config file %s: %s"),
2257
                         network->configFile, strerror(errno));
2258 2259 2260 2261
        goto cleanup;
    }

    if (close(fd) < 0) {
2262
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2263
                         _("cannot save config file %s: %s"),
2264
                         network->configFile, strerror(errno));
2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
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);
}
2293

2294
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
2295
                               struct qemud_network_def *def,
2296 2297 2298 2299 2300
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
2301 2302
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
2303 2304 2305 2306 2307 2308 2309
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
2310
            def->disableSTP = 1;
2311 2312 2313 2314 2315 2316 2317
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
2318
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
2319 2320 2321 2322 2323 2324 2325
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

2326 2327
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
2328
                                   struct qemud_network_def *def,
2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
                                   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;
        }

2344
        if (!(range = calloc(1, sizeof(*range)))) {
2345 2346
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for range string"));
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
            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';

2360 2361 2362
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
        } else {
            free(range);
        }

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

        cur = cur->next;
    }

    return 1;
}
2377

2378 2379
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
2380
                             struct qemud_network_def *def,
2381 2382
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
2383
    xmlNodePtr cur;
2384 2385 2386

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
2387 2388
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
2389 2390 2391 2392 2393 2394
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
2395 2396
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
2397 2398 2399 2400
        xmlFree(netmask);
        netmask = NULL;
    }

2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415
    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);
    }

2416 2417 2418 2419
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
2420
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
2421 2422 2423 2424
            return 0;
        cur = cur->next;
    }

2425 2426 2427 2428
    return 1;
}


2429 2430
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
2431
                                                      xmlDocPtr xml) {
2432 2433
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
2434
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
2435 2436
    struct qemud_network_def *def;

2437
    if (!(def = calloc(1, sizeof(*def)))) {
2438 2439
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                   "%s", _("failed to allocate space for network_def string"));
2440 2441
        return NULL;
    }
2442 2443 2444 2445

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
2446 2447
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
2448 2449 2450 2451 2452
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
2453 2454
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
               "%s", _("failed to allocate space for xmlXPathContext string"));
2455 2456 2457 2458 2459 2460 2461 2462
        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)) {
2463
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
2464 2465 2466
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
2467 2468
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("network name length too long"));
2469 2470
        goto error;
    }
2471
    strcpy(def->name, (const char *)obj->stringval);
2472 2473 2474 2475 2476 2477 2478
    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)) {
2479
        int err;
D
Daniel P. Berrange 已提交
2480
        if ((err = virUUIDGenerate(def->uuid))) {
2481
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2482
                             _("Failed to generate UUID: %s"), strerror(err));
2483 2484
            goto error;
        }
D
Daniel P. Berrange 已提交
2485
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
2486 2487
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
2488 2489 2490 2491
        goto error;
    }
    xmlXPathFreeObject(obj);

2492 2493 2494 2495
    /* 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)) {
2496
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
2497 2498 2499 2500 2501 2502 2503 2504 2505
            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)) {
2506
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
2507 2508 2509 2510 2511 2512
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
2513 2514 2515
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
2516 2517
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
2518
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2519
                             "%s", _("Forwarding requested, but no IPv4 address/netmask provided"));
2520 2521 2522
            goto error;
        }

2523 2524 2525 2526 2527 2528
        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)) {
2529
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2530
                                 _("forward device name '%s' is too long"),
2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544
                                 (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);

2545 2546
    xmlXPathFreeContext(ctxt);

2547
    return def;
2548 2549 2550 2551

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
2552 2553
    xmlXPathFreeObject(obj);
    xmlXPathFreeObject(tmp);
2554
    xmlXPathFreeContext(ctxt);
2555 2556
    qemudFreeNetworkDef(def);
    return NULL;
2557 2558
}

2559
struct qemud_network_def *
2560 2561
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
2562 2563
                     const char *xmlStr,
                     const char *displayName) {
2564
    xmlDocPtr xml;
2565
    struct qemud_network_def *def;
2566

2567
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
2568 2569
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2570
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
2571 2572 2573
        return NULL;
    }

2574
    def = qemudParseNetworkXML(conn, driver, xml);
2575

2576 2577
    xmlFreeDoc(xml);

2578 2579 2580 2581
    return def;
}

struct qemud_network *
2582 2583
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
2584 2585 2586
                      struct qemud_network_def *def) {
    struct qemud_network *network;

2587
    if ((network = qemudFindNetworkByName(driver, def->name))) {
2588
        if (!qemudIsActiveNetwork(network)) {
2589 2590 2591 2592 2593 2594 2595 2596
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

2597
        return network;
2598 2599
    }

2600
    if (!(network = calloc(1, sizeof(*network)))) {
2601 2602
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for network string"));
2603 2604
        return NULL;
    }
2605

2606
    network->def = def;
2607
    network->next = driver->networks;
2608

2609 2610
    driver->networks = network;
    driver->ninactivenetworks++;
2611 2612 2613 2614 2615

    return network;
}

void
2616
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
2617 2618 2619 2620
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

2621
    curr = driver->networks;
2622 2623 2624
    while (curr != network) {
        prev = curr;
        curr = curr->next;
2625 2626
    }

2627 2628 2629 2630
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2631
            driver->networks = curr->next;
2632

2633
        driver->ninactivenetworks--;
2634 2635
    }

2636
    qemudFreeNetwork(network);
2637 2638
}

2639
int
2640 2641
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
2642 2643 2644 2645 2646 2647
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

2648
        if ((err = virFileMakePath(driver->networkConfigDir))) {
2649
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2650
                             _("cannot create config directory %s: %s"),
2651
                             driver->networkConfigDir, strerror(err));
2652 2653 2654
            return -1;
        }

2655 2656
        if (virFileBuildPath(driver->networkConfigDir, def->name, ".xml",
                             network->configFile, PATH_MAX) < 0) {
2657
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2658
                             "%s", _("cannot construct config file path"));
2659 2660
            return -1;
        }
2661

2662 2663
        if (virFileBuildPath(driver->networkAutostartDir, def->name, ".xml",
                             network->autostartLink, PATH_MAX) < 0) {
2664
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2665
                             "%s", _("cannot construct autostart link path"));
2666 2667 2668
            network->configFile[0] = '\0';
            return -1;
        }
2669 2670
    }

2671
    return qemudSaveNetworkConfig(conn, driver, network, def);
2672
}
2673

2674

2675
static struct qemud_vm *
2676
qemudLoadConfig(struct qemud_driver *driver,
2677 2678
                const char *file,
                const char *path,
2679 2680
                const char *xml,
                const char *autostartLink) {
2681 2682 2683
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

2684
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
2685
        virErrorPtr err = virGetLastError();
2686 2687 2688
        qemudLog(QEMUD_WARN, _("Error parsing QEMU guest config '%s' : %s"),
                 path, (err ? err->message :
                        _("BUG: unknown error - please report it\n")));
2689 2690 2691
        return NULL;
    }

2692
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
2693 2694 2695
        qemudLog(QEMUD_WARN,
                 _("QEMU guest config filename '%s'"
                   " does not match guest name '%s'"),
2696 2697 2698 2699 2700
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

2701
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
2702 2703 2704
        qemudLog(QEMUD_WARN,
                 _("Failed to load QEMU guest config '%s': out of memory"),
                 path);
2705 2706 2707 2708 2709 2710 2711
        qemudFreeVMDef(def);
        return NULL;
    }

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

2712 2713 2714
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

2715
    vm->autostart = virFileLinkPointsTo(vm->autostartLink, vm->configFile);
2716

2717 2718 2719 2720
    return vm;
}

static struct qemud_network *
2721
qemudLoadNetworkConfig(struct qemud_driver *driver,
2722 2723
                       const char *file,
                       const char *path,
2724 2725
                       const char *xml,
                       const char *autostartLink) {
2726 2727 2728
    struct qemud_network_def *def;
    struct qemud_network *network;

2729
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
2730
        virErrorPtr err = virGetLastError();
2731
        qemudLog(QEMUD_WARN, _("Error parsing network config '%s' : %s"),
2732
                 path, err->message);
2733 2734 2735
        return NULL;
    }

2736
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
2737 2738 2739
        qemudLog(QEMUD_WARN,
                 _("Network config filename '%s'"
                   " does not match network name '%s'"),
2740 2741 2742 2743 2744
                 path, def->name);
        qemudFreeNetworkDef(def);
        return NULL;
    }

2745
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
2746 2747
        qemudLog(QEMUD_WARN,
                 _("Failed to load network config '%s': out of memory"), path);
2748 2749 2750 2751 2752 2753 2754
        qemudFreeNetworkDef(def);
        return NULL;
    }

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

2755 2756 2757
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

2758
    network->autostart = virFileLinkPointsTo(network->autostartLink, network->configFile);
2759

2760 2761
    return network;
}
D
Daniel P. Berrange 已提交
2762

2763
static
2764
int qemudScanConfigDir(struct qemud_driver *driver,
2765
                       const char *configDir,
2766
                       const char *autostartDir,
2767
                       int isGuest) {
D
Daniel P. Berrange 已提交
2768 2769 2770
    DIR *dir;
    struct dirent *entry;

2771
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
2772 2773
        if (errno == ENOENT)
            return 0;
2774
        qemudLog(QEMUD_ERR, _("Failed to open dir '%s': %s"),
2775
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
2776 2777 2778 2779
        return -1;
    }

    while ((entry = readdir(dir))) {
2780
        char *xml;
2781
        char path[PATH_MAX];
2782
        char autostartLink[PATH_MAX];
2783

D
Daniel P. Berrange 已提交
2784 2785 2786
        if (entry->d_name[0] == '.')
            continue;

2787
        if (!virFileHasSuffix(entry->d_name, ".xml"))
2788 2789
            continue;

2790
        if (virFileBuildPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
2791
            qemudLog(QEMUD_WARN, _("Config filename '%s/%s' is too long"),
2792 2793 2794 2795
                     configDir, entry->d_name);
            continue;
        }

2796 2797 2798
        if (virFileBuildPath(autostartDir, entry->d_name, NULL,
                             autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, _("Autostart link path '%s/%s' is too long"),
2799 2800 2801 2802
                     autostartDir, entry->d_name);
            continue;
        }

2803
        if (virFileReadAll(path, QEMUD_MAX_XML_LEN, &xml) < 0)
D
Daniel P. Berrange 已提交
2804 2805
            continue;

2806
        if (isGuest)
2807
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
2808
        else
2809
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
2810 2811

        free(xml);
D
Daniel P. Berrange 已提交
2812 2813 2814
    }

    closedir(dir);
2815

D
Daniel P. Berrange 已提交
2816 2817 2818
    return 0;
}

2819
/* Scan for all guest and network config files */
2820 2821
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
2822
        return -1;
2823

2824
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
2825 2826 2827
        return -1;

    return 0;
2828
}
D
Daniel P. Berrange 已提交
2829 2830

/* Generate an XML document describing the guest's configuration */
2831 2832
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
2833 2834 2835
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
D
Daniel P. Berrange 已提交
2836
    virBufferPtr buf = 0;
D
Daniel P. Berrange 已提交
2837
    unsigned char *uuid;
2838
    char uuidstr[VIR_UUID_STRING_BUFLEN];
D
Daniel P. Berrange 已提交
2839 2840
    struct qemud_vm_disk_def *disk;
    struct qemud_vm_net_def *net;
2841
    struct qemud_vm_input_def *input;
D
Daniel P. Berrange 已提交
2842 2843 2844
    const char *type = NULL;
    int n;

D
Daniel P. Berrange 已提交
2845
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2846
    if (!buf)
2847 2848
        goto no_memory;

2849
    switch (def->virtType) {
D
Daniel P. Berrange 已提交
2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
    case QEMUD_VIRT_QEMU:
        type = "qemu";
        break;
    case QEMUD_VIRT_KQEMU:
        type = "kqemu";
        break;
    case QEMUD_VIRT_KVM:
        type = "kvm";
        break;
    }
    if (!type) {
2861 2862
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unexpected domain type %d"), def->virtType);
D
Daniel P. Berrange 已提交
2863 2864 2865
        goto cleanup;
    }

2866
    if (qemudIsActiveVM(vm) && live) {
D
Daniel P. Berrange 已提交
2867
        if (virBufferVSprintf(buf, "<domain type='%s' id='%d'>\n", type, vm->id) < 0)
D
Daniel P. Berrange 已提交
2868 2869
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2870
        if (virBufferVSprintf(buf, "<domain type='%s'>\n", type) < 0)
D
Daniel P. Berrange 已提交
2871 2872 2873
            goto no_memory;
    }

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

2877
    uuid = def->uuid;
2878 2879
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
D
Daniel P. Berrange 已提交
2880
        goto no_memory;
2881
    if (virBufferVSprintf(buf, "  <memory>%lu</memory>\n", def->maxmem) < 0)
D
Daniel P. Berrange 已提交
2882
        goto no_memory;
2883
    if (virBufferVSprintf(buf, "  <currentMemory>%lu</currentMemory>\n", def->memory) < 0)
D
Daniel P. Berrange 已提交
2884
        goto no_memory;
D
Daniel P. Berrange 已提交
2885
    if (virBufferVSprintf(buf, "  <vcpu>%d</vcpu>\n", def->vcpus) < 0)
D
Daniel P. Berrange 已提交
2886 2887
        goto no_memory;

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

2891
    if (def->virtType == QEMUD_VIRT_QEMU) {
D
Daniel P. Berrange 已提交
2892
        if (virBufferVSprintf(buf, "    <type arch='%s' machine='%s'>%s</type>\n",
2893
                              def->os.arch, def->os.machine, def->os.type) < 0)
D
Daniel P. Berrange 已提交
2894 2895
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2896
        if (virBufferVSprintf(buf, "    <type>%s</type>\n", def->os.type) < 0)
D
Daniel P. Berrange 已提交
2897 2898 2899
            goto no_memory;
    }

2900
    if (def->os.kernel[0])
D
Daniel P. Berrange 已提交
2901
        if (virBufferVSprintf(buf, "    <kernel>%s</kernel>\n", def->os.kernel) < 0)
D
Daniel P. Berrange 已提交
2902
            goto no_memory;
2903
    if (def->os.initrd[0])
D
Daniel P. Berrange 已提交
2904
        if (virBufferVSprintf(buf, "    <initrd>%s</initrd>\n", def->os.initrd) < 0)
D
Daniel P. Berrange 已提交
2905
            goto no_memory;
2906
    if (def->os.cmdline[0])
D
Daniel P. Berrange 已提交
2907
        if (virBufferVSprintf(buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline) < 0)
D
Daniel P. Berrange 已提交
2908 2909
            goto no_memory;

2910
    for (n = 0 ; n < def->os.nBootDevs ; n++) {
D
Daniel P. Berrange 已提交
2911
        const char *boottype = "hd";
2912
        switch (def->os.bootDevs[n]) {
D
Daniel P. Berrange 已提交
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922
        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:
2923
            boottype = "network";
D
Daniel P. Berrange 已提交
2924 2925
            break;
        }
D
Daniel P. Berrange 已提交
2926
        if (virBufferVSprintf(buf, "    <boot dev='%s'/>\n", boottype) < 0)
D
Daniel P. Berrange 已提交
2927 2928 2929
            goto no_memory;
    }

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

2933
    if (def->features & QEMUD_FEATURE_ACPI) {
2934
        if (virBufferAddLit(buf, "  <features>\n") < 0)
2935
            goto no_memory;
2936
        if (virBufferAddLit(buf, "    <acpi/>\n") < 0)
2937
            goto no_memory;
2938
        if (virBufferAddLit(buf, "  </features>\n") < 0)
2939 2940 2941
            goto no_memory;
    }

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

2944
    if (virBufferAddLit(buf, "  <on_poweroff>destroy</on_poweroff>\n") < 0)
D
Daniel P. Berrange 已提交
2945 2946
        goto no_memory;
    if (def->noReboot) {
2947
        if (virBufferAddLit(buf, "  <on_reboot>destroy</on_reboot>\n") < 0)
D
Daniel P. Berrange 已提交
2948 2949
            goto no_memory;
    } else {
2950
        if (virBufferAddLit(buf, "  <on_reboot>restart</on_reboot>\n") < 0)
D
Daniel P. Berrange 已提交
2951 2952
            goto no_memory;
    }
2953
    if (virBufferAddLit(buf, "  <on_crash>destroy</on_crash>\n") < 0)
D
Daniel P. Berrange 已提交
2954
        goto no_memory;
2955

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

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

2962
    disk = def->disks;
D
Daniel P. Berrange 已提交
2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
D
Daniel P. Berrange 已提交
2977
        if (virBufferVSprintf(buf, "    <disk type='%s' device='%s'>\n",
D
Daniel P. Berrange 已提交
2978 2979 2980
                              types[disk->type], devices[disk->device]) < 0)
            goto no_memory;

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

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

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

2993
        if (virBufferAddLit(buf, "    </disk>\n") < 0)
D
Daniel P. Berrange 已提交
2994 2995 2996 2997 2998
            goto no_memory;

        disk = disk->next;
    }

2999
    net = def->nets;
3000
    while (net) {
D
Daniel P. Berrange 已提交
3001 3002
        const char *types[] = {
            "user",
3003
            "ethernet",
D
Daniel P. Berrange 已提交
3004 3005 3006
            "server",
            "client",
            "mcast",
3007
            "network",
3008
            "bridge",
D
Daniel P. Berrange 已提交
3009
        };
D
Daniel P. Berrange 已提交
3010
        if (virBufferVSprintf(buf, "    <interface type='%s'>\n",
D
Daniel P. Berrange 已提交
3011 3012 3013
                              types[net->type]) < 0)
            goto no_memory;

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

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

3024
            if (net->dst.network.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
3025
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.network.ifname) < 0)
3026 3027 3028
                    goto no_memory;
            }
            break;
3029

3030 3031
        case QEMUD_NET_ETHERNET:
            if (net->dst.ethernet.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
3032
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname) < 0)
3033 3034 3035
                    goto no_memory;
            }
            if (net->dst.ethernet.script[0] != '\0') {
D
Daniel P. Berrange 已提交
3036
                if (virBufferVSprintf(buf, "      <script path='%s'/>\n", net->dst.ethernet.script) < 0)
3037 3038 3039 3040 3041
                    goto no_memory;
            }
            break;

        case QEMUD_NET_BRIDGE:
D
Daniel P. Berrange 已提交
3042
            if (virBufferVSprintf(buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname) < 0)
3043
                goto no_memory;
3044
            if (net->dst.bridge.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
3045
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname) < 0)
3046 3047 3048 3049 3050 3051 3052 3053
                    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 已提交
3054
                if (virBufferVSprintf(buf, "      <source address='%s' port='%d'/>\n",
3055 3056 3057
                                      net->dst.socket.address, net->dst.socket.port) < 0)
                    goto no_memory;
            } else {
D
Daniel P. Berrange 已提交
3058
                if (virBufferVSprintf(buf, "      <source port='%d'/>\n",
3059 3060 3061
                                      net->dst.socket.port) < 0)
                    goto no_memory;
            }
3062 3063
        }

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

3067
        net = net->next;
D
Daniel P. Berrange 已提交
3068 3069
    }

3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
    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)
3080
        if (virBufferAddLit(buf, "    <input type='mouse' bus='ps2'/>\n") < 0)
3081 3082
            goto no_memory;

3083 3084
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
3085
        if (virBufferAddLit(buf, "    <graphics type='vnc'") < 0)
3086 3087 3088
            goto no_memory;

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

3093 3094 3095 3096 3097
        if (def->vncListen[0] &&
            virBufferVSprintf(buf, " listen='%s'",
                              def->vncListen) < 0)
            goto no_memory;

3098 3099 3100 3101 3102
        if (def->keymap &&
            virBufferVSprintf(buf, " keymap='%s'",
                              def->keymap) < 0)
            goto no_memory;

3103
        if (virBufferAddLit(buf, "/>\n") < 0)
3104 3105 3106 3107
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_SDL:
3108
        if (virBufferAddLit(buf, "    <graphics type='sdl'/>\n") < 0)
3109 3110 3111 3112 3113 3114 3115 3116
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

3117
    if (def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
3118 3119
    }

3120
    if (virBufferAddLit(buf, "  </devices>\n") < 0)
D
Daniel P. Berrange 已提交
3121 3122 3123
        goto no_memory;


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

D
Daniel P. Berrange 已提交
3127
    return virBufferContentAndFree (buf);
D
Daniel P. Berrange 已提交
3128 3129

 no_memory:
3130 3131
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
D
Daniel P. Berrange 已提交
3132
 cleanup:
D
Daniel P. Berrange 已提交
3133
    if (buf) virBufferFree (buf);
D
Daniel P. Berrange 已提交
3134 3135 3136 3137
    return NULL;
}


3138 3139
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
3140
                              struct qemud_network *network,
3141
                              struct qemud_network_def *def) {
D
Daniel P. Berrange 已提交
3142
    virBufferPtr buf = 0;
3143
    unsigned char *uuid;
3144
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3145

D
Daniel P. Berrange 已提交
3146
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
3147
    if (!buf)
3148 3149
        goto no_memory;

3150
    if (virBufferAddLit(buf, "<network>\n") < 0)
3151 3152
        goto no_memory;

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

3156
    uuid = def->uuid;
3157 3158
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
3159 3160
        goto no_memory;

3161 3162
    if (def->forward) {
        if (def->forwardDev[0]) {
D
Daniel P. Berrange 已提交
3163
            virBufferVSprintf(buf, "  <forward dev='%s'/>\n",
3164 3165
                              def->forwardDev);
        } else {
3166
            virBufferAddLit(buf, "  <forward/>\n");
3167 3168 3169
        }
    }

3170
    virBufferAddLit(buf, "  <bridge");
3171
    if (qemudIsActiveNetwork(network)) {
D
Daniel P. Berrange 已提交
3172
        if (virBufferVSprintf(buf, " name='%s'", network->bridge) < 0)
3173 3174
            goto no_memory;
    } else if (def->bridge[0]) {
D
Daniel P. Berrange 已提交
3175
        if (virBufferVSprintf(buf, " name='%s'", def->bridge) < 0)
3176 3177
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
3178
    if (virBufferVSprintf(buf, " stp='%s' forwardDelay='%d' />\n",
3179 3180
                       def->disableSTP ? "off" : "on",
                       def->forwardDelay) < 0)
3181 3182
        goto no_memory;

3183
    if (def->ipAddress[0] || def->netmask[0]) {
3184
        if (virBufferAddLit(buf, "  <ip") < 0)
3185 3186
            goto no_memory;

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

3191
        if (def->netmask[0] &&
D
Daniel P. Berrange 已提交
3192
            virBufferVSprintf(buf, " netmask='%s'", def->netmask) < 0)
3193 3194
            goto no_memory;

3195
        if (virBufferAddLit(buf, ">\n") < 0)
3196 3197
            goto no_memory;

3198 3199
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
3200
            if (virBufferAddLit(buf, "    <dhcp>\n") < 0)
3201 3202
                goto no_memory;
            while (range) {
D
Daniel P. Berrange 已提交
3203
                if (virBufferVSprintf(buf, "      <range start='%s' end='%s' />\n",
3204 3205 3206 3207
                                      range->start, range->end) < 0)
                    goto no_memory;
                range = range->next;
            }
3208
            if (virBufferAddLit(buf, "    </dhcp>\n") < 0)
3209 3210 3211
                goto no_memory;
        }

3212
        if (virBufferAddLit(buf, "  </ip>\n") < 0)
3213
            goto no_memory;
D
Daniel P. Berrange 已提交
3214 3215
    }

3216
    if (virBufferAddLit(buf, "</network>\n") < 0)
3217 3218
        goto no_memory;

D
Daniel P. Berrange 已提交
3219
    return virBufferContentAndFree (buf);
3220 3221

 no_memory:
3222 3223
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
D
Daniel P. Berrange 已提交
3224
    if (buf) virBufferFree (buf);
3225 3226 3227 3228
    return NULL;
}


3229 3230
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
3231 3232 3233
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
3234 3235
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("no config file for %s"), name);
D
Daniel P. Berrange 已提交
3236 3237 3238
        return -1;
    }

3239
    if (unlink(configFile) < 0) {
3240 3241
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("cannot remove config for %s"), name);
3242 3243
        return -1;
    }
3244

D
Daniel P. Berrange 已提交
3245 3246 3247
    return 0;
}

3248
#endif /* WITH_QEMU */
D
Daniel P. Berrange 已提交
3249 3250 3251 3252 3253 3254 3255 3256 3257

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