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

24 25 26
#include "config.h"

#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 45 46

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

#include <libvirt/virterror.h>

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

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

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

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

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

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

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

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


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

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

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

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

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

    virConfFree (conf);
    return 0;
}


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

198

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

    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 已提交
215 216 217 218 219
    while (input) {
        struct qemud_vm_input_def *prev = input;
        input = input->next;
        free(prev);
    }
220
    free(def);
221 222 223 224 225 226 227 228
}

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

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
/* Build up a fully qualfiied path for a config file to be
 * associated with a persistent guest or network */
static int
qemudMakeConfigPath(const char *configDir,
                    const char *name,
                    const char *ext,
                    char *buf,
                    unsigned int buflen) {
    if ((strlen(configDir) + 1 + strlen(name) + (ext ? strlen(ext) : 0) + 1) > buflen)
        return -1;

    strcpy(buf, configDir);
    strcat(buf, "/");
    strcat(buf, name);
    if (ext)
        strcat(buf, ext);
    return 0;
}

249
int
250 251 252 253 254 255
qemudEnsureDir(const char *path)
{
    struct stat st;
    char parent[PATH_MAX];
    char *p;
    int err;
256

257 258
    if (stat(path, &st) >= 0)
        return 0;
259

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
    strncpy(parent, path, PATH_MAX);
    parent[PATH_MAX - 1] = '\0';

    if (!(p = strrchr(parent, '/')))
        return EINVAL;

    if (p == parent)
        return EPERM;

    *p = '\0';

    if ((err = qemudEnsureDir(parent)))
        return err;

    if (mkdir(path, 0777) < 0 && errno != EEXIST)
        return errno;
276 277 278 279

    return 0;
}

D
Daniel P. Berrange 已提交
280 281 282
/* The list of possible machine types for various architectures,
   as supported by QEMU - taken from 'qemu -M ?' for each arch */
static const char *arch_info_x86_machines[] = {
283
    "pc", "isapc", NULL
D
Daniel P. Berrange 已提交
284 285
};
static const char *arch_info_mips_machines[] = {
286
    "mips", NULL
D
Daniel P. Berrange 已提交
287 288
};
static const char *arch_info_sparc_machines[] = {
289
    "sun4m", NULL
D
Daniel P. Berrange 已提交
290 291
};
static const char *arch_info_ppc_machines[] = {
292
    "g3bw", "mac99", "prep", NULL
D
Daniel P. Berrange 已提交
293 294
};

295 296 297 298 299 300 301 302 303 304 305 306 307 308
/* Feature flags for the architecture info */
struct qemu_feature_flags arch_info_i686_flags [] = {
    { "pae",  1, 1 },
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
    { NULL, -1, -1 }
};

struct qemu_feature_flags arch_info_x86_64_flags [] = {
    { "acpi", 1, 1 },
    { "apic", 1, 0 },
    { NULL, -1, -1 }
};

D
Daniel P. Berrange 已提交
309
/* The archicture tables for supported QEMU archs */
310 311
struct qemu_arch_info qemudArchs[] = { 
    /* i686 must be in position 0 */
312
    {  "i686", 32, arch_info_x86_machines, "qemu", arch_info_i686_flags },
313
    /* x86_64 must be in position 1 */
314 315 316 317 318 319
    {  "x86_64", 64, arch_info_x86_machines, "qemu-system-x86_64", arch_info_x86_64_flags },
    {  "mips", 32, arch_info_mips_machines, "qemu-system-mips", NULL },
    {  "mipsel", 32, arch_info_mips_machines, "qemu-system-mipsel", NULL },
    {  "sparc", 32, arch_info_sparc_machines, "qemu-system-sparc", NULL },
    {  "ppc", 32, arch_info_ppc_machines, "qemu-system-ppc", NULL },
    { NULL, -1, NULL, NULL, NULL }
D
Daniel P. Berrange 已提交
320 321 322 323
};

/* Return the default architecture if none is explicitly requested*/
static const char *qemudDefaultArch(void) {
324
    return qemudArchs[0].arch;
D
Daniel P. Berrange 已提交
325 326 327 328 329 330
}

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

331 332 333
    for (i = 0; qemudArchs[i].arch; i++) {
        if (!strcmp(qemudArchs[i].arch, arch)) {
            return qemudArchs[i].machines[0];
D
Daniel P. Berrange 已提交
334 335 336 337 338 339 340 341 342 343
        }
    }

    return NULL;
}

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

344 345 346
    for (i = 0 ; qemudArchs[i].arch; i++) {
        if (!strcmp(qemudArchs[i].arch, arch)) {
            return qemudArchs[i].binary;
D
Daniel P. Berrange 已提交
347 348 349 350 351 352 353
        }
    }

    return NULL;
}

/* Find the fully qualified path to the binary for an architecture */
354
static char *qemudLocateBinaryForArch(virConnectPtr conn,
D
Daniel P. Berrange 已提交
355 356 357 358 359 360 361 362 363 364
                                      int virtType, const char *arch) {
    const char *name;
    char *path;

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

    if (!name) {
365
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot determin binary for architecture %s", arch);
D
Daniel P. Berrange 已提交
366 367 368 369 370 371
        return NULL;
    }

    /* XXX lame. should actually use $PATH ... */
    path = malloc(strlen(name) + strlen("/usr/bin/") + 1);
    if (!path) {
372
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "path");
D
Daniel P. Berrange 已提交
373 374 375 376 377 378 379
        return NULL;
    }
    strcpy(path, "/usr/bin/");
    strcat(path, name);
    return path;
}

380 381 382 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 409 410 411 412 413 414

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 已提交
415
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
416
        int got = 0, ret = -1;
417 418 419 420 421
        int major, minor, micro;

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

D
Daniel P. Berrange 已提交
422 423 424 425 426 427 428 429 430 431
        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;
432 433 434 435 436 437 438 439 440 441
        }
        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 已提交
442 443
        if (strstr(help, "-no-reboot"))
            *flags |= QEMUD_CMD_FLAG_NO_REBOOT;
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
        if (*version >= 9000)
            *flags |= QEMUD_CMD_FLAG_VNC_COLON;
        ret = 0;

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

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

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

        return ret;
    }
}

474
int qemudExtractVersion(virConnectPtr conn,
475
                        struct qemud_driver *driver ATTRIBUTE_UNUSED) {
476
    char *binary = NULL;
477
    struct stat sb;
478
    int ignored;
479

480
    if (driver->qemuVersion > 0)
481 482
        return 0;

483
    if (!(binary = qemudLocateBinaryForArch(conn, QEMUD_VIRT_QEMU, "i686")))
484 485
        return -1;

486
    if (stat(binary, &sb) < 0) {
487
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
488 489 490 491 492 493
                         "Cannot find QEMU binary %s: %s", binary,
                         strerror(errno));
        free(binary);
        return -1;
    }

494
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &ignored) < 0) {
495 496 497 498 499 500 501 502 503
        free(binary);
        return -1;
    }

    free(binary);
    return 0;
}


D
Daniel P. Berrange 已提交
504 505 506 507 508 509 510 511
/* 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 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    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");
  
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
	
                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) {
555
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SOURCE, target ? "%s" : NULL, target);
D
Daniel P. Berrange 已提交
556 557 558
        goto error;
    }
    if (target == NULL) {
559
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
560 561 562 563 564 565 566
        goto error;
    }

    if (device &&
        !strcmp((const char *)device, "floppy") &&
        strcmp((const char *)target, "fda") &&
        strcmp((const char *)target, "fdb")) {
567
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid floppy device name: %s", target);
D
Daniel P. Berrange 已提交
568 569 570 571 572 573
        goto error;
    }
  
    if (device &&
        !strcmp((const char *)device, "cdrom") &&
        strcmp((const char *)target, "hdc")) {
574
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid cdrom device name: %s", target);
D
Daniel P. Berrange 已提交
575 576 577 578 579 580 581 582 583 584 585 586
        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")) {
587
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid harddisk device name: %s", target);
D
Daniel P. Berrange 已提交
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        goto error;
    }

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

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

    if (!device)
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "disk"))
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "cdrom"))
        disk->device = QEMUD_DISK_CDROM;
    else if (!strcmp((const char *)device, "floppy"))
        disk->device = QEMUD_DISK_FLOPPY;
    else {
607
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid device type: %s", device);
D
Daniel P. Berrange 已提交
608 609 610 611 612 613 614
        goto error;
    }

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

D
Daniel P. Berrange 已提交
615
    return 0;
D
Daniel P. Berrange 已提交
616 617 618 619 620 621 622 623 624 625

 error:
    if (type)
        xmlFree(type);
    if (target)
        xmlFree(target);
    if (source)
        xmlFree(source);
    if (device)
        xmlFree(device);
D
Daniel P. Berrange 已提交
626
    return -1;
D
Daniel P. Berrange 已提交
627 628
}

629 630 631 632 633 634 635 636 637
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 已提交
638

D
Daniel P. Berrange 已提交
639 640 641 642 643 644 645 646
/* 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 已提交
647 648 649
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
650
    xmlChar *network = NULL;
651 652 653 654 655
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
D
Daniel P. Berrange 已提交
656 657 658 659 660 661 662

    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;
663 664
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
665 666 667 668 669 670
        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;
671 672
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
673 674
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
675 676 677 678 679 680 681 682 683 684 685 686
        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");
687 688 689 690
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
691 692 693
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
694
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711
            } 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");
            } 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 已提交
712 713 714 715 716 717
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
718
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
719
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
720 721 722 723 724 725 726 727 728 729 730 731
               (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 已提交
732 733

        xmlFree(macaddr);
734 735 736
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
737 738
    }

739 740 741 742
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
743
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
744 745
                             "No <source> 'network' attribute specified with <interface type='network'/>");
            goto error;
746
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
747
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
748 749 750 751 752 753 754
                             "Network name '%s' too long", network);
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

755
        if (network) {
756
            xmlFree(network);
757 758 759 760 761
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
762
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
763 764 765 766 767 768 769 770 771 772 773
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.network.ifname, (char *)ifname, len);
                net->dst.network.ifname[len] = '\0';
            }
            xmlFree(ifname);
            ifname = NULL;
        }
    } else if (net->type == QEMUD_NET_ETHERNET) {
        int len;
774

775 776
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
777
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
778 779 780 781 782 783 784 785 786 787 788
                                 "TAP script path '%s' is too long", script);
                goto error;
            } else {
                strncpy(net->dst.ethernet.script, (char *)script, len);
                net->dst.ethernet.script[len] = '\0';
            }
            xmlFree(script);
            script = NULL;
        }
        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
789
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
790
                                 "TAP interface name '%s' is too long", ifname);
791 792
                goto error;
            } else {
793 794
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
795
            }
796 797 798 799 800 801
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
802
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
803 804 805
                             "No <source> 'dev' attribute specified with <interface type='bridge'/>");
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
806
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
807 808 809 810 811
                             "TAP bridge path '%s' is too long", bridge);
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
812
        }
813 814 815 816 817 818

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
819
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
820 821 822 823 824 825 826 827 828 829 830
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.bridge.ifname, (char *)ifname, len);
                net->dst.bridge.ifname[len] = '\0';
            }
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_CLIENT ||
               net->type == QEMUD_NET_SERVER ||
               net->type == QEMUD_NET_MCAST) {
831
        int len = 0;
832 833 834
        char *ret;

        if (port == NULL) {
835
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
836 837 838 839 840
                             "No <source> 'port' attribute specified with socket interface");
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
841
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
842 843 844 845 846 847 848 849 850
                             "Cannot parse <source> 'port' attribute with socket interface");
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
851
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
852 853 854 855
                                 "No <source> 'address' attribute specified with socket interface");
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
856
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
857 858 859 860 861 862 863 864 865 866
                             "IP address '%s' is too long", address);
            goto error;
        }
        if (address == NULL) {
            net->dst.socket.address[0] = '\0';
        } else {
            strncpy(net->dst.socket.address, (char*)address,len);
            net->dst.socket.address[len] = '\0';
        }
        xmlFree(address);
867 868
    }

D
Daniel P. Berrange 已提交
869
    return 0;
870 871 872 873

 error:
    if (network)
        xmlFree(network);
874 875 876 877 878 879 880 881 882 883
    if (address)
        xmlFree(address);
    if (port)
        xmlFree(port);
    if (ifname)
        xmlFree(ifname);
    if (script)
        xmlFree(script);
    if (bridge)
        xmlFree(bridge);
D
Daniel P. Berrange 已提交
884
    return -1;
D
Daniel P. Berrange 已提交
885 886 887
}


888
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
889 890 891
static int qemudParseInputXML(virConnectPtr conn,
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

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

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

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

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

D
Daniel P. Berrange 已提交
937
    return 0;
938 939 940 941 942 943 944

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

D
Daniel P. Berrange 已提交
945
    return -1;
946 947 948
}


D
Daniel P. Berrange 已提交
949 950 951 952
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
953 954
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
955
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
956 957 958 959 960 961
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
962 963 964
    struct qemud_vm_def *def;

    if (!(def = calloc(1, sizeof(struct qemud_vm_def)))) {
965
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
966 967
        return NULL;
    }
D
Daniel P. Berrange 已提交
968 969 970 971

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
972
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
D
Daniel P. Berrange 已提交
973 974 975 976 977
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
978
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
D
Daniel P. Berrange 已提交
979 980 981 982 983 984
        goto error;
    }


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

    if (!strcmp((char *)prop, "qemu"))
990
        def->virtType = QEMUD_VIRT_QEMU;
D
Daniel P. Berrange 已提交
991
    else if (!strcmp((char *)prop, "kqemu"))
992
        def->virtType = QEMUD_VIRT_KQEMU;
D
Daniel P. Berrange 已提交
993
    else if (!strcmp((char *)prop, "kvm"))
994
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
995
    else {
996
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "invalid domain type attribute");
D
Daniel P. Berrange 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006
        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)) {
1007
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
1008 1009 1010
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1011
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "domain name length too long");
D
Daniel P. Berrange 已提交
1012 1013
        goto error;
    }
1014
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1015 1016 1017 1018 1019 1020 1021
    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)) {
1022
        int err;
D
Daniel P. Berrange 已提交
1023
        if ((err = virUUIDGenerate(def->uuid))) {
1024
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1025 1026 1027
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
1028
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
1029
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
D
Daniel P. Berrange 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038
        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)) {
1039
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "missing memory element");
D
Daniel P. Berrange 已提交
1040 1041 1042
        goto error;
    } else {
        conv = NULL;
1043
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1044
        if (conv == (const char*)obj->stringval) {
1045
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);


    /* Extract domain memory */
    obj = xmlXPathEval(BAD_CAST "string(/domain/currentMemory[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1057
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1058 1059
    } else {
        conv = NULL;
1060 1061 1062
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1063
        if (conv == (const char*)obj->stringval) {
1064
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);

    /* Extract domain vcpu info */
    obj = xmlXPathEval(BAD_CAST "string(/domain/vcpu[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1075
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1076 1077
    } else {
        conv = NULL;
1078
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1079
        if (conv == (const char*)obj->stringval) {
1080
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed vcpu information");
D
Daniel P. Berrange 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);

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

D
Daniel P. Berrange 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

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

1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
    /* See if we set clock to localtime */
    obj = xmlXPathEval(BAD_CAST "string(/domain/clock/@offset)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        def->localtime = 0;
    } else {
        if (!strcmp((char*)obj->stringval, "localtime"))
            def->localtime = 1;
        else
            def->localtime = 0;
    }
    if (obj)
        xmlXPathFreeObject(obj);

D
Daniel P. Berrange 已提交
1124

D
Daniel P. Berrange 已提交
1125 1126 1127 1128
    /* 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)) {
1129
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, NULL);
D
Daniel P. Berrange 已提交
1130 1131 1132
        goto error;
    }
    if (strcmp((const char *)obj->stringval, "hvm")) {
1133
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, "%s", obj->stringval);
D
Daniel P. Berrange 已提交
1134 1135
        goto error;
    }
1136
    strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1137 1138 1139 1140 1141 1142 1143 1144
    xmlXPathFreeObject(obj);


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

    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1]/@machine)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1162
        const char *defaultMachine = qemudDefaultMachineForArch(def->os.arch);
1163 1164 1165 1166
        if (!defaultMachine) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unsupported arch %s", def->os.arch);
            goto error;
        }
D
Daniel P. Berrange 已提交
1167
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1168
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "machine type too long");
D
Daniel P. Berrange 已提交
1169 1170
            goto error;
        }
1171
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1172 1173
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1174
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1175 1176
            goto error;
        }
1177
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/kernel[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1187
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "kernel path too long");
D
Daniel P. Berrange 已提交
1188 1189
            goto error;
        }
1190
        strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/initrd[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1200
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "initrd path too long");
D
Daniel P. Berrange 已提交
1201 1202
            goto error;
        }
1203
        strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/cmdline[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1213
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "cmdline arguments too long");
D
Daniel P. Berrange 已提交
1214 1215
            goto error;
        }
1216
        strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    }
    if (obj)
        xmlXPathFreeObject(obj);


    /* analysis of the disk devices */
    obj = xmlXPathEval(BAD_CAST "/domain/os/boot", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        for (i = 0; i < obj->nodesetval->nodeNr && i < QEMUD_MAX_BOOT_DEVS ; i++) {
1227 1228
            if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                continue;
D
Daniel P. Berrange 已提交
1229
            if (!strcmp((char *)prop, "hd")) {
1230
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1231
            } else if (!strcmp((char *)prop, "fd")) {
1232
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
D
Daniel P. Berrange 已提交
1233
            } else if (!strcmp((char *)prop, "cdrom")) {
1234
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
1235
            } else if (!strcmp((char *)prop, "network")) {
1236
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
D
Daniel P. Berrange 已提交
1237 1238 1239
            } else {
                goto error;
            }
1240
            xmlFree(prop);
1241
            prop = NULL;
D
Daniel P. Berrange 已提交
1242 1243 1244
        }
    }
    xmlXPathFreeObject(obj);
1245 1246 1247
    if (def->os.nBootDevs == 0) {
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1248 1249 1250 1251 1252 1253
    }


    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1254
        char *tmp = qemudLocateBinaryForArch(conn, def->virtType, def->os.arch);
D
Daniel P. Berrange 已提交
1255 1256 1257
        if (!tmp) {
            goto error;
        }
1258
        strcpy(def->os.binary, tmp);
D
Daniel P. Berrange 已提交
1259 1260 1261
        free(tmp);
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1262
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "emulator path too long");
D
Daniel P. Berrange 已提交
1263 1264
            goto error;
        }
1265
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1266 1267 1268 1269 1270 1271 1272
    }
    if (obj)
        xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1273
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1274
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
D
Daniel P. Berrange 已提交
1275
        if (!strcmp((char *)prop, "vnc")) {
1276
            xmlChar *vncport, *vnclisten;
1277
            def->graphicsType = QEMUD_GRAPHICS_VNC;
1278 1279
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
1280
                conv = NULL;
1281
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
1282
            } else {
1283
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1284
            }
1285 1286 1287 1288
            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 已提交
1289
                strcpy(def->vncListen, driver->vncListen);
1290 1291 1292
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
            xmlFree(vncport);
            xmlFree(vnclisten);
D
Daniel P. Berrange 已提交
1293
        } else if (!strcmp((char *)prop, "sdl")) {
1294
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1295
        } else {
1296
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Unsupported graphics type %s", prop);
D
Daniel P. Berrange 已提交
1297 1298
            goto error;
        }
1299
        xmlFree(prop);
1300
        prop = NULL;
D
Daniel P. Berrange 已提交
1301
    }
1302
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1303 1304 1305 1306 1307

    /* 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)) {
1308
        struct qemud_vm_disk_def *prev = NULL;
D
Daniel P. Berrange 已提交
1309
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
D
Daniel P. Berrange 已提交
1310 1311 1312 1313 1314 1315 1316
            struct qemud_vm_disk_def *disk = calloc(1, sizeof(struct qemud_vm_disk_def));
            if (!disk) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "disk");
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
                free(disk);
D
Daniel P. Berrange 已提交
1317 1318
                goto error;
            }
1319
            def->ndisks++;
1320 1321 1322 1323 1324 1325 1326
            disk->next = NULL;
            if (i == 0) {
                def->disks = disk;
            } else {
                prev->next = disk;
            }
            prev = disk;
D
Daniel P. Berrange 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335
        }
    }
    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)) {
1336
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
1337
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
D
Daniel P. Berrange 已提交
1338 1339 1340 1341 1342 1343 1344
            struct qemud_vm_net_def *net = calloc(1, sizeof(struct qemud_vm_net_def));
            if (!net) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "net");
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
                free(net);
D
Daniel P. Berrange 已提交
1345 1346
                goto error;
            }
1347
            def->nnets++;
1348 1349 1350 1351 1352 1353 1354
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
1355 1356 1357
        }
    }
    xmlXPathFreeObject(obj);
1358 1359 1360 1361 1362 1363 1364

    /* 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++) {
D
Daniel P. Berrange 已提交
1365 1366 1367 1368 1369 1370 1371
            struct qemud_vm_input_def *input = calloc(1, sizeof(struct qemud_vm_input_def));
            if (!input) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "input");
                goto error;
            }
            if (qemudParseInputXML(conn, input, obj->nodesetval->nodeTab[i]) < 0) {
                free(input);
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
                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;
1382
            if (def->inputs == NULL) {
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
                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) {
            input = calloc(1, sizeof(struct qemud_vm_input_def));
            if (!input) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "input");
                goto error;
            }
            input->type = QEMU_INPUT_TYPE_MOUSE;
            input->bus = QEMU_INPUT_BUS_PS2;
            input->next = def->inputs;
            def->inputs = input;
            def->ninputs++;
        }
    }

D
Daniel P. Berrange 已提交
1418 1419
    xmlXPathFreeContext(ctxt);

1420
    return def;
D
Daniel P. Berrange 已提交
1421 1422 1423 1424 1425 1426 1427 1428

 error:
    if (prop)
        free(prop);
    if (obj)
        xmlXPathFreeObject(obj);
    if (ctxt)
        xmlXPathFreeContext(ctxt);
1429 1430
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
1431 1432 1433
}


1434
static char *
1435 1436
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
1437
                         struct qemud_vm *vm,
1438 1439
                         struct qemud_vm_net_def *net,
                         int vlan)
1440
{
1441 1442 1443
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
1444 1445 1446 1447 1448 1449
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

1450
    if (net->type == QEMUD_NET_NETWORK) {
1451
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
1452
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1453 1454 1455
                             "Network '%s' not found", net->dst.network.name);
            goto error;
        } else if (network->bridge[0] == '\0') {
1456
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
                             "Network '%s' not active", net->dst.network.name);
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
            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' ||
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
1474
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1475
                         "Network type %d is not supported", net->type);
1476 1477 1478
        goto error;
    }

1479
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
1480
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1481 1482 1483 1484
                         "cannot initialize bridge support: %s", strerror(err));
        goto error;
    }

1485
    if ((err = brAddTap(driver->brctl, brname,
1486
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
1487
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1488
                         "Failed to add tap interface '%s' to bridge '%s' : %s",
1489
                         ifname, brname, strerror(err));
1490 1491 1492
        goto error;
    }

1493
    snprintf(tapfdstr, sizeof(tapfdstr), "tap,fd=%d,script=,vlan=%d", tapfd, vlan);
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

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

    if (!(tapfds = realloc(vm->tapfds, sizeof(int) * (vm->ntapfds+2))))
        goto no_memory;

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

    return retval;

 no_memory:
1508
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "tapfds");
1509 1510 1511 1512 1513 1514 1515 1516
 error:
    if (retval)
        free(retval);
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

D
Daniel P. Berrange 已提交
1517 1518 1519 1520
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
1521 1522
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
1523
                          struct qemud_vm *vm,
1524 1525
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
1526 1527 1528
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
1529
    struct stat sb;
1530 1531
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
1532
    struct qemud_vm_input_def *input = vm->def->inputs;
1533 1534
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
1535

1536 1537 1538 1539 1540 1541 1542 1543
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
    if (stat(vm->def->os.binary, &sb) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "Cannot find QEMU binary %s: %s", vm->def->os.binary,
                         strerror(errno));
1544
        return -1;
1545 1546 1547 1548 1549 1550 1551 1552
    }

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

1554 1555
    uname(&ut);

D
Daniel P. Berrange 已提交
1556
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
1557 1558 1559 1560
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
1561
        ut.machine[1] = '6';
1562 1563 1564 1565 1566 1567

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

1573
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
1574
        2 + /* machine type */
1575
        disableKQEMU + /* Disable kqemu */
1576 1577
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
1578 1579
        1 + /* usb */
        2 * vm->def->ninputs + /* input devices */
D
Daniel P. Berrange 已提交
1580 1581 1582 1583
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
1584
        (vm->def->localtime ? 1 : 0) + /* localtime */
1585
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1586
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
1587 1588 1589 1590 1591
        (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 :
1592 1593
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)) + /* graphics */
        (vm->migrateFrom[0] ? 3 : 0); /* migrateFrom */
D
Daniel P. Berrange 已提交
1594

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

1598
    if (!(*argv = malloc(sizeof(char *) * (len+1))))
D
Daniel P. Berrange 已提交
1599
        goto no_memory;
1600
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
1601 1602 1603
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
1604
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
1605
        goto no_memory;
1606
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
1607
        if (!((*argv)[++n] = strdup("-no-kqemu")))
1608
            goto no_memory;
D
Daniel P. Berrange 已提交
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
    }
    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;

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
    /*
     * 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 已提交
1631 1632 1633 1634 1635
    if (!((*argv)[++n] = strdup("-monitor")))
        goto no_memory;
    if (!((*argv)[++n] = strdup("pty")))
        goto no_memory;

1636 1637 1638 1639 1640
    if (vm->def->localtime) {
        if (!((*argv)[++n] = strdup("-localtime")))
            goto no_memory;
    }

1641
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1642 1643 1644 1645 1646
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

1647
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
1648 1649
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
1650 1651
    }

1652 1653
    for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
        switch (vm->def->os.bootDevs[i]) {
D
Daniel P. Berrange 已提交
1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
        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;
        }
    }
1671
    boot[vm->def->os.nBootDevs] = '\0';
D
Daniel P. Berrange 已提交
1672 1673 1674 1675 1676
    if (!((*argv)[++n] = strdup("-boot")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(boot)))
        goto no_memory;

1677
    if (vm->def->os.kernel[0]) {
D
Daniel P. Berrange 已提交
1678 1679
        if (!((*argv)[++n] = strdup("-kernel")))
            goto no_memory;
1680
        if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
D
Daniel P. Berrange 已提交
1681 1682
            goto no_memory;
    }
1683
    if (vm->def->os.initrd[0]) {
D
Daniel P. Berrange 已提交
1684 1685
        if (!((*argv)[++n] = strdup("-initrd")))
            goto no_memory;
1686
        if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
D
Daniel P. Berrange 已提交
1687 1688
            goto no_memory;
    }
1689
    if (vm->def->os.cmdline[0]) {
D
Daniel P. Berrange 已提交
1690 1691
        if (!((*argv)[++n] = strdup("-append")))
            goto no_memory;
1692
        if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
D
Daniel P. Berrange 已提交
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
            goto no_memory;
    }

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

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

        disk = disk->next;
    }

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

1724 1725 1726 1727 1728 1729
            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 已提交
1730 1731 1732 1733 1734

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

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

1739 1740 1741
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
1742
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
1743
                    goto error;
1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798
                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;
                }
1799
            }
D
Daniel P. Berrange 已提交
1800 1801

            net = net->next;
1802
            vlan++;
D
Daniel P. Berrange 已提交
1803 1804 1805
        }
    }

1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
    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;
    }

1819
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
1820
        char vncdisplay[PATH_MAX];
1821
        int ret;
D
Daniel P. Berrange 已提交
1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836

        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",
1837
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
1838 1839 1840
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
1841 1842
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
1843
        }
1844
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
1845 1846
            goto error;

D
Daniel P. Berrange 已提交
1847 1848
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
1849
        if (!((*argv)[++n] = strdup(vncdisplay)))
D
Daniel P. Berrange 已提交
1850
            goto no_memory;
1851
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
1852
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
1853 1854 1855 1856
    } else {
        /* SDL is the default. no args needed */
    }

1857 1858 1859 1860 1861 1862 1863 1864 1865
    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 已提交
1866 1867 1868 1869 1870
    (*argv)[++n] = NULL;

    return 0;

 no_memory:
1871
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "argv");
1872 1873 1874 1875 1876 1877 1878 1879
 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 已提交
1880 1881
    if (argv) {
        for (i = 0 ; i < n ; i++)
1882 1883
            free((*argv)[i]);
        free(*argv);
D
Daniel P. Berrange 已提交
1884 1885 1886 1887 1888 1889
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
1890 1891
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
1892 1893
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
1894 1895 1896 1897
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

1898
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
1899 1900 1901 1902 1903
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1904
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1905 1906
                         "cannot create config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1907 1908 1909 1910 1911
        goto cleanup;
    }

    towrite = strlen(xml);
    if (write(fd, xml, towrite) != towrite) {
1912
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1913 1914
                         "cannot write config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1915 1916 1917 1918
        goto cleanup;
    }

    if (close(fd) < 0) {
1919
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1920 1921
                         "cannot save config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935
        goto cleanup;
    }

    ret = 0;

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

    free(xml);

    return ret;
}

D
Daniel P. Berrange 已提交
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
    struct qemud_vm_device_def *dev = calloc(1, sizeof(struct qemud_vm_device_def));

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

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

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
    if (dev) free(dev);
    return NULL;
}

1981
struct qemud_vm_def *
1982 1983
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
1984 1985
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
1986
    xmlDocPtr xml;
1987
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
1988

1989
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
1990 1991
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
1992
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
1993 1994 1995
        return NULL;
    }

1996
    def = qemudParseXML(conn, driver, xml);
1997

D
Daniel P. Berrange 已提交
1998 1999
    xmlFreeDoc(xml);

2000 2001 2002 2003
    return def;
}

struct qemud_vm *
2004 2005
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
2006 2007 2008 2009
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

2010
    if ((vm = qemudFindVMByName(driver, def->name))) {
2011
        if (!qemudIsActiveVM(vm)) {
2012 2013 2014 2015 2016 2017 2018
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
2019 2020 2021
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
2022
        return vm;
D
Daniel P. Berrange 已提交
2023 2024
    }

2025
    if (!(vm = calloc(1, sizeof(struct qemud_vm)))) {
2026
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "vm");
2027 2028
        return NULL;
    }
D
Daniel P. Berrange 已提交
2029

2030
    vm->stdin = -1;
2031 2032 2033 2034 2035
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
2036
    vm->state = VIR_DOMAIN_SHUTOFF;
2037
    vm->def = def;
2038
    vm->next = driver->vms;
2039

2040 2041
    driver->vms = vm;
    driver->ninactivevms++;
2042 2043 2044 2045 2046

    return vm;
}

void
2047
qemudRemoveInactiveVM(struct qemud_driver *driver,
2048 2049 2050 2051
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

2052
    curr = driver->vms;
2053 2054 2055
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
2056 2057
    }

2058 2059 2060 2061
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2062
            driver->vms = curr->next;
2063

2064
        driver->ninactivevms--;
2065 2066
    }

2067
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
2068 2069
}

2070
int
2071 2072
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
2073 2074 2075 2076 2077
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

2078
        if ((err = qemudEnsureDir(driver->configDir))) {
2079
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2080
                             "cannot create config directory %s: %s",
2081
                             driver->configDir, strerror(err));
2082 2083 2084
            return -1;
        }

2085
        if (qemudMakeConfigPath(driver->configDir, def->name, ".xml",
2086
                                vm->configFile, PATH_MAX) < 0) {
2087
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2088 2089 2090
                             "cannot construct config file path");
            return -1;
        }
2091

2092
        if (qemudMakeConfigPath(driver->autostartDir, def->name, ".xml",
2093
                                vm->autostartLink, PATH_MAX) < 0) {
2094
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2095 2096 2097 2098
                             "cannot construct autostart link path");
            vm->configFile[0] = '\0';
            return -1;
        }
2099 2100
    }

2101
    return qemudSaveConfig(conn, driver, vm, def);
2102
}
D
Daniel P. Berrange 已提交
2103

2104 2105
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
2106 2107
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
2108 2109 2110
    char *xml;
    int fd, ret = -1;
    int towrite;
2111
    int err;
2112

2113
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
2114 2115 2116
        return -1;
    }

2117
    if ((err = qemudEnsureDir(driver->networkConfigDir))) {
2118
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2119
                         "cannot create config directory %s: %s",
2120
                         driver->networkConfigDir, strerror(err));
2121 2122 2123 2124 2125 2126
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2127
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2128 2129
                         "cannot create config file %s: %s",
                         network->configFile, strerror(errno));
2130 2131 2132 2133 2134
        goto cleanup;
    }

    towrite = strlen(xml);
    if (write(fd, xml, towrite) != towrite) {
2135
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2136
                         "cannot write config file %s: %s",
2137
                         network->configFile, strerror(errno));
2138 2139 2140 2141
        goto cleanup;
    }

    if (close(fd) < 0) {
2142
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2143
                         "cannot save config file %s: %s",
2144
                         network->configFile, strerror(errno));
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
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);
}
2173

2174
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
2175
                               struct qemud_network_def *def,
2176 2177 2178 2179 2180
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
2181 2182
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
2183 2184 2185 2186 2187 2188 2189
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
2190
            def->disableSTP = 1;
2191 2192 2193 2194 2195 2196 2197
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
2198
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
2199 2200 2201 2202 2203 2204 2205
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

2206 2207
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
2208
                                   struct qemud_network_def *def,
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224
                                   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;
        }

        if (!(range = calloc(1, sizeof(struct qemud_dhcp_range_def)))) {
2225
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "range");
2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
            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';

2239 2240 2241
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
        } else {
            free(range);
        }

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

        cur = cur->next;
    }

    return 1;
}
2256

2257 2258
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
2259
                             struct qemud_network_def *def,
2260 2261
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
2262
    xmlNodePtr cur;
2263 2264 2265

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
2266 2267
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
2268 2269 2270 2271 2272 2273
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
2274 2275
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
2276 2277 2278 2279
        xmlFree(netmask);
        netmask = NULL;
    }

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

2295 2296 2297 2298
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
2299
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
2300 2301 2302 2303
            return 0;
        cur = cur->next;
    }

2304 2305 2306 2307
    return 1;
}


2308 2309
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
2310
                                                      xmlDocPtr xml) {
2311 2312
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
2313
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
2314 2315 2316
    struct qemud_network_def *def;

    if (!(def = calloc(1, sizeof(struct qemud_network_def)))) {
2317
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network_def");
2318 2319
        return NULL;
    }
2320 2321 2322 2323

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
2324
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
2325 2326 2327 2328 2329
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
2330
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
2331 2332 2333 2334 2335 2336 2337 2338
        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)) {
2339
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
2340 2341 2342
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
2343
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "network name length too long");
2344 2345
        goto error;
    }
2346
    strcpy(def->name, (const char *)obj->stringval);
2347 2348 2349 2350 2351 2352 2353
    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)) {
2354
        int err;
D
Daniel P. Berrange 已提交
2355
        if ((err = virUUIDGenerate(def->uuid))) {
2356
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2357 2358 2359
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
2360
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
2361
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
2362 2363 2364 2365
        goto error;
    }
    xmlXPathFreeObject(obj);

2366 2367 2368 2369
    /* 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)) {
2370
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
2371 2372 2373 2374 2375 2376 2377 2378 2379
            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)) {
2380
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
2381 2382 2383 2384 2385 2386
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
2387 2388 2389
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
2390 2391
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
2392
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2393 2394 2395 2396
                             "Forwarding requested, but no IPv4 address/netmask provided");
            goto error;
        }

2397 2398 2399 2400 2401 2402
        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)) {
2403
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418
                                 "forward device name '%s' is too long",
                                 (char*)tmp->stringval);
                goto error;
            }
            strcpy(def->forwardDev, (char*)tmp->stringval);
        } else {
            def->forwardDev[0] = '\0';
        }
        xmlXPathFreeObject(tmp);
        tmp = NULL;
    } else {
        def->forward = 0;
    }
    xmlXPathFreeObject(obj);

2419 2420
    xmlXPathFreeContext(ctxt);

2421
    return def;
2422 2423 2424 2425 2426 2427

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
    if (obj)
        xmlXPathFreeObject(obj);
2428 2429
    if (tmp)
        xmlXPathFreeObject(tmp);
2430 2431
    if (ctxt)
        xmlXPathFreeContext(ctxt);
2432 2433
    qemudFreeNetworkDef(def);
    return NULL;
2434 2435
}

2436
struct qemud_network_def *
2437 2438
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
2439 2440
                     const char *xmlStr,
                     const char *displayName) {
2441
    xmlDocPtr xml;
2442
    struct qemud_network_def *def;
2443

2444
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
2445 2446
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2447
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
2448 2449 2450
        return NULL;
    }

2451
    def = qemudParseNetworkXML(conn, driver, xml);
2452

2453 2454
    xmlFreeDoc(xml);

2455 2456 2457 2458
    return def;
}

struct qemud_network *
2459 2460
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
2461 2462 2463
                      struct qemud_network_def *def) {
    struct qemud_network *network;

2464
    if ((network = qemudFindNetworkByName(driver, def->name))) {
2465
        if (!qemudIsActiveNetwork(network)) {
2466 2467 2468 2469 2470 2471 2472 2473
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

2474
        return network;
2475 2476
    }

2477
    if (!(network = calloc(1, sizeof(struct qemud_network)))) {
2478
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network");
2479 2480
        return NULL;
    }
2481

2482
    network->def = def;
2483
    network->next = driver->networks;
2484

2485 2486
    driver->networks = network;
    driver->ninactivenetworks++;
2487 2488 2489 2490 2491

    return network;
}

void
2492
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
2493 2494 2495 2496
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

2497
    curr = driver->networks;
2498 2499 2500
    while (curr != network) {
        prev = curr;
        curr = curr->next;
2501 2502
    }

2503 2504 2505 2506
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2507
            driver->networks = curr->next;
2508

2509
        driver->ninactivenetworks--;
2510 2511
    }

2512
    qemudFreeNetwork(network);
2513 2514
}

2515
int
2516 2517
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
2518 2519 2520 2521 2522 2523
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

2524
        if ((err = qemudEnsureDir(driver->networkConfigDir))) {
2525
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2526
                             "cannot create config directory %s: %s",
2527
                             driver->networkConfigDir, strerror(err));
2528 2529 2530
            return -1;
        }

2531
        if (qemudMakeConfigPath(driver->networkConfigDir, def->name, ".xml",
2532
                                network->configFile, PATH_MAX) < 0) {
2533
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2534 2535 2536
                             "cannot construct config file path");
            return -1;
        }
2537

2538
        if (qemudMakeConfigPath(driver->networkAutostartDir, def->name, ".xml",
2539
                                network->autostartLink, PATH_MAX) < 0) {
2540
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2541 2542 2543 2544
                             "cannot construct autostart link path");
            network->configFile[0] = '\0';
            return -1;
        }
2545 2546
    }

2547
    return qemudSaveNetworkConfig(conn, driver, network, def);
2548
}
2549

2550 2551 2552 2553
static int
qemudReadFile(const char *path,
              char *buf,
              int maxlen) {
D
Daniel P. Berrange 已提交
2554 2555
    FILE *fh;
    struct stat st;
2556
    int ret = 0;
D
Daniel P. Berrange 已提交
2557

2558 2559 2560 2561
    if (!(fh = fopen(path, "r"))) {
        qemudLog(QEMUD_WARN, "Failed to open file '%s': %s",
                 path, strerror(errno));
        goto error;
D
Daniel P. Berrange 已提交
2562 2563 2564
    }

    if (fstat(fileno(fh), &st) < 0) {
2565 2566 2567
        qemudLog(QEMUD_WARN, "Failed to stat file '%s': %s",
                 path, strerror(errno));
        goto error;
D
Daniel P. Berrange 已提交
2568 2569
    }

2570 2571 2572
    if (S_ISDIR(st.st_mode)) {
        qemudDebug("Ignoring directory '%s' - clearly not a config file", path);
        goto error;
D
Daniel P. Berrange 已提交
2573 2574
    }

2575 2576 2577
    if (st.st_size >= maxlen) {
        qemudLog(QEMUD_WARN, "File '%s' is too large", path);
        goto error;
D
Daniel P. Berrange 已提交
2578 2579
    }

2580 2581 2582 2583
    if ((ret = fread(buf, st.st_size, 1, fh)) != 1) {
        qemudLog(QEMUD_WARN, "Failed to read config file '%s': %s",
                 path, strerror(errno));
        goto error;
D
Daniel P. Berrange 已提交
2584
    }
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610

    buf[st.st_size] = '\0';

    ret = 1;

 error:
    if (fh)
        fclose(fh);

    return ret;
}

static int
compareFileToNameSuffix(const char *file,
                        const char *name,
                        const char *suffix) {
    int filelen = strlen(file);
    int namelen = strlen(name);
    int suffixlen = strlen(suffix);

    if (filelen == (namelen + suffixlen) &&
        !strncmp(file, name, namelen) &&
        !strncmp(file + namelen, suffix, suffixlen))
        return 1;
    else
        return 0;
D
Daniel P. Berrange 已提交
2611 2612
}

2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625
static int
hasSuffix(const char *str,
          const char *suffix)
{
    int len = strlen(str);
    int suffixlen = strlen(suffix);

    if (len < suffixlen)
        return 0;

    return strcmp(str + len - suffixlen, suffix) == 0;
}

2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
static int
checkLinkPointsTo(const char *checkLink,
                  const char *checkDest)
{
    char dest[PATH_MAX];
    char real[PATH_MAX];
    char checkReal[PATH_MAX];
    int n;
    int passed = 0;

    /* read the link destination */
    if ((n = readlink(checkLink, dest, PATH_MAX)) < 0) {
        switch (errno) {
        case ENOENT:
        case ENOTDIR:
            break;

        case EINVAL:
            qemudLog(QEMUD_WARN, "Autostart file '%s' is not a symlink",
                     checkLink);
            break;

        default:
            qemudLog(QEMUD_WARN, "Failed to read autostart symlink '%s': %s",
                     checkLink, strerror(errno));
            break;
        }

        goto failed;
    } else if (n >= PATH_MAX) {
        qemudLog(QEMUD_WARN, "Symlink '%s' contents too long to fit in buffer",
                 checkLink);
        goto failed;
    }

    dest[n] = '\0';

    /* make absolute */
    if (dest[0] != '/') {
        char dir[PATH_MAX];
        char tmp[PATH_MAX];
        char *p;

        strncpy(dir, checkLink, PATH_MAX);
2670
        dir[PATH_MAX-1] = '\0';
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687

        if (!(p = strrchr(dir, '/'))) {
            qemudLog(QEMUD_WARN, "Symlink path '%s' is not absolute", checkLink);
            goto failed;
        }

        if (p == dir) /* handle unlikely root dir case */
            p++;

        *p = '\0';

        if (qemudMakeConfigPath(dir, dest, NULL, tmp, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, "Path '%s/%s' is too long", dir, dest);
            goto failed;
        }

        strncpy(dest, tmp, PATH_MAX);
2688
        dest[PATH_MAX-1] = '\0';
2689 2690 2691 2692 2693 2694 2695
    }

    /* canonicalize both paths */
    if (!realpath(dest, real)) {
        qemudLog(QEMUD_WARN, "Failed to expand path '%s' :%s",
                 dest, strerror(errno));
        strncpy(real, dest, PATH_MAX);
2696
        real[PATH_MAX-1] = '\0';
2697 2698 2699 2700 2701 2702
    }

    if (!realpath(checkDest, checkReal)) {
        qemudLog(QEMUD_WARN, "Failed to expand path '%s' :%s",
                 checkDest, strerror(errno));
        strncpy(checkReal, checkDest, PATH_MAX);
2703
        checkReal[PATH_MAX-1] = '\0';
2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
    }

    /* compare */
    if (strcmp(checkReal, real) != 0) {
        qemudLog(QEMUD_WARN, "Autostart link '%s' is not a symlink to '%s', ignoring",
                 checkLink, checkReal);
        goto failed;
    }

    passed = 1;

 failed:
    return passed;
}

2719
static struct qemud_vm *
2720
qemudLoadConfig(struct qemud_driver *driver,
2721 2722
                const char *file,
                const char *path,
2723 2724
                const char *xml,
                const char *autostartLink) {
2725 2726 2727
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

2728
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
2729
        virErrorPtr err = virGetLastError();
2730
        qemudLog(QEMUD_WARN, "Error parsing QEMU guest config '%s' : %s",
2731
                 path, err->message);
2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
        return NULL;
    }

    if (!compareFileToNameSuffix(file, def->name, ".xml")) {
        qemudLog(QEMUD_WARN, "QEMU guest config filename '%s' does not match guest name '%s'",
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

2742
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
2743 2744 2745 2746 2747 2748 2749 2750
        qemudLog(QEMUD_WARN, "Failed to load QEMU guest config '%s': out of memory", path);
        qemudFreeVMDef(def);
        return NULL;
    }

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

2751 2752 2753 2754 2755
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

    vm->autostart = checkLinkPointsTo(vm->autostartLink, vm->configFile);

2756 2757 2758 2759
    return vm;
}

static struct qemud_network *
2760
qemudLoadNetworkConfig(struct qemud_driver *driver,
2761 2762
                       const char *file,
                       const char *path,
2763 2764
                       const char *xml,
                       const char *autostartLink) {
2765 2766 2767
    struct qemud_network_def *def;
    struct qemud_network *network;

2768
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
2769
        virErrorPtr err = virGetLastError();
2770
        qemudLog(QEMUD_WARN, "Error parsing network config '%s' : %s",
2771
                 path, err->message);
2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
        return NULL;
    }

    if (!compareFileToNameSuffix(file, def->name, ".xml")) {
        qemudLog(QEMUD_WARN, "Network config filename '%s' does not match network name '%s'",
                 path, def->name);
        qemudFreeNetworkDef(def);
        return NULL;
    }

2782
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
2783 2784 2785 2786 2787 2788 2789 2790
        qemudLog(QEMUD_WARN, "Failed to load network config '%s': out of memory", path);
        qemudFreeNetworkDef(def);
        return NULL;
    }

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

2791 2792 2793 2794 2795
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

    network->autostart = checkLinkPointsTo(network->autostartLink, network->configFile);

2796 2797
    return network;
}
D
Daniel P. Berrange 已提交
2798

2799
static
2800
int qemudScanConfigDir(struct qemud_driver *driver,
2801
                       const char *configDir,
2802
                       const char *autostartDir,
2803
                       int isGuest) {
D
Daniel P. Berrange 已提交
2804 2805 2806
    DIR *dir;
    struct dirent *entry;

2807
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
2808 2809
        if (errno == ENOENT)
            return 0;
2810 2811
        qemudLog(QEMUD_ERR, "Failed to open dir '%s': %s",
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
2812 2813 2814 2815
        return -1;
    }

    while ((entry = readdir(dir))) {
2816 2817
        char xml[QEMUD_MAX_XML_LEN];
        char path[PATH_MAX];
2818
        char autostartLink[PATH_MAX];
2819

D
Daniel P. Berrange 已提交
2820 2821 2822
        if (entry->d_name[0] == '.')
            continue;

2823 2824 2825
        if (!hasSuffix(entry->d_name, ".xml"))
            continue;

2826 2827 2828 2829 2830 2831
        if (qemudMakeConfigPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, "Config filename '%s/%s' is too long",
                     configDir, entry->d_name);
            continue;
        }

2832 2833 2834 2835 2836 2837
        if (qemudMakeConfigPath(autostartDir, entry->d_name, NULL, autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, "Autostart link path '%s/%s' is too long",
                     autostartDir, entry->d_name);
            continue;
        }

2838
        if (!qemudReadFile(path, xml, QEMUD_MAX_XML_LEN))
D
Daniel P. Berrange 已提交
2839 2840
            continue;

2841
        if (isGuest)
2842
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
2843
        else
2844
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
D
Daniel P. Berrange 已提交
2845 2846 2847 2848 2849 2850 2851
    }

    closedir(dir);
 
    return 0;
}

2852
/* Scan for all guest and network config files */
2853 2854
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
2855
        return -1;
2856

2857
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
2858 2859 2860
        return -1;

    return 0;
2861
}
D
Daniel P. Berrange 已提交
2862 2863

/* Generate an XML document describing the guest's configuration */
2864 2865
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
2866 2867 2868
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
D
Daniel P. Berrange 已提交
2869
    virBufferPtr buf = 0;
D
Daniel P. Berrange 已提交
2870
    unsigned char *uuid;
2871
    char uuidstr[VIR_UUID_STRING_BUFLEN];
D
Daniel P. Berrange 已提交
2872 2873
    struct qemud_vm_disk_def *disk;
    struct qemud_vm_net_def *net;
2874
    struct qemud_vm_input_def *input;
D
Daniel P. Berrange 已提交
2875 2876 2877
    const char *type = NULL;
    int n;

D
Daniel P. Berrange 已提交
2878
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2879
    if (!buf)
2880 2881
        goto no_memory;

2882
    switch (def->virtType) {
D
Daniel P. Berrange 已提交
2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893
    case QEMUD_VIRT_QEMU:
        type = "qemu";
        break;
    case QEMUD_VIRT_KQEMU:
        type = "kqemu";
        break;
    case QEMUD_VIRT_KVM:
        type = "kvm";
        break;
    }
    if (!type) {
2894
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unexpected domain type %d", def->virtType);
D
Daniel P. Berrange 已提交
2895 2896 2897
        goto cleanup;
    }

2898
    if (qemudIsActiveVM(vm) && live) {
D
Daniel P. Berrange 已提交
2899
        if (virBufferVSprintf(buf, "<domain type='%s' id='%d'>\n", type, vm->id) < 0)
D
Daniel P. Berrange 已提交
2900 2901
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2902
        if (virBufferVSprintf(buf, "<domain type='%s'>\n", type) < 0)
D
Daniel P. Berrange 已提交
2903 2904 2905
            goto no_memory;
    }

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

2909
    uuid = def->uuid;
2910 2911
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
D
Daniel P. Berrange 已提交
2912
        goto no_memory;
D
Daniel P. Berrange 已提交
2913
    if (virBufferVSprintf(buf, "  <memory>%d</memory>\n", def->maxmem) < 0)
D
Daniel P. Berrange 已提交
2914
        goto no_memory;
D
Daniel P. Berrange 已提交
2915
    if (virBufferVSprintf(buf, "  <currentMemory>%d</currentMemory>\n", def->memory) < 0)
D
Daniel P. Berrange 已提交
2916
        goto no_memory;
D
Daniel P. Berrange 已提交
2917
    if (virBufferVSprintf(buf, "  <vcpu>%d</vcpu>\n", def->vcpus) < 0)
D
Daniel P. Berrange 已提交
2918 2919
        goto no_memory;

D
Daniel P. Berrange 已提交
2920
    if (virBufferAdd(buf, "  <os>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2921 2922
        goto no_memory;

2923
    if (def->virtType == QEMUD_VIRT_QEMU) {
D
Daniel P. Berrange 已提交
2924
        if (virBufferVSprintf(buf, "    <type arch='%s' machine='%s'>%s</type>\n",
2925
                              def->os.arch, def->os.machine, def->os.type) < 0)
D
Daniel P. Berrange 已提交
2926 2927
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2928
        if (virBufferVSprintf(buf, "    <type>%s</type>\n", def->os.type) < 0)
D
Daniel P. Berrange 已提交
2929 2930 2931
            goto no_memory;
    }

2932
    if (def->os.kernel[0])
D
Daniel P. Berrange 已提交
2933
        if (virBufferVSprintf(buf, "    <kernel>%s</kernel>\n", def->os.kernel) < 0)
D
Daniel P. Berrange 已提交
2934
            goto no_memory;
2935
    if (def->os.initrd[0])
D
Daniel P. Berrange 已提交
2936
        if (virBufferVSprintf(buf, "    <initrd>%s</initrd>\n", def->os.initrd) < 0)
D
Daniel P. Berrange 已提交
2937
            goto no_memory;
2938
    if (def->os.cmdline[0])
D
Daniel P. Berrange 已提交
2939
        if (virBufferVSprintf(buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline) < 0)
D
Daniel P. Berrange 已提交
2940 2941
            goto no_memory;

2942
    for (n = 0 ; n < def->os.nBootDevs ; n++) {
D
Daniel P. Berrange 已提交
2943
        const char *boottype = "hd";
2944
        switch (def->os.bootDevs[n]) {
D
Daniel P. Berrange 已提交
2945 2946 2947 2948 2949 2950 2951 2952 2953 2954
        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:
2955
            boottype = "network";
D
Daniel P. Berrange 已提交
2956 2957
            break;
        }
D
Daniel P. Berrange 已提交
2958
        if (virBufferVSprintf(buf, "    <boot dev='%s'/>\n", boottype) < 0)
D
Daniel P. Berrange 已提交
2959 2960 2961
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
2962
    if (virBufferAdd(buf, "  </os>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2963 2964
        goto no_memory;

2965
    if (def->features & QEMUD_FEATURE_ACPI) {
D
Daniel P. Berrange 已提交
2966
        if (virBufferAdd(buf, "  <features>\n", -1) < 0)
2967
            goto no_memory;
D
Daniel P. Berrange 已提交
2968
        if (virBufferAdd(buf, "    <acpi/>\n", -1) < 0)
2969
            goto no_memory;
D
Daniel P. Berrange 已提交
2970
        if (virBufferAdd(buf, "  </features>\n", -1) < 0)
2971 2972 2973
            goto no_memory;
    }

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

D
Daniel P. Berrange 已提交
2976
    if (virBufferAdd(buf, "  <on_poweroff>destroy</on_poweroff>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2977 2978
        goto no_memory;
    if (def->noReboot) {
D
Daniel P. Berrange 已提交
2979
        if (virBufferAdd(buf, "  <on_reboot>destroy</on_reboot>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2980 2981
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2982
        if (virBufferAdd(buf, "  <on_reboot>restart</on_reboot>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2983 2984
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
2985
    if (virBufferAdd(buf, "  <on_crash>destroy</on_crash>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2986
        goto no_memory;
2987

D
Daniel P. Berrange 已提交
2988
    if (virBufferAdd(buf, "  <devices>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2989 2990
        goto no_memory;

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

2994
    disk = def->disks;
D
Daniel P. Berrange 已提交
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
D
Daniel P. Berrange 已提交
3009
        if (virBufferVSprintf(buf, "    <disk type='%s' device='%s'>\n",
D
Daniel P. Berrange 已提交
3010 3011 3012
                              types[disk->type], devices[disk->device]) < 0)
            goto no_memory;

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

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

        if (disk->readonly)
D
Daniel P. Berrange 已提交
3020
            if (virBufferAdd(buf, "      <readonly/>\n", -1) < 0)
D
Daniel P. Berrange 已提交
3021 3022
                goto no_memory;

D
Daniel P. Berrange 已提交
3023
        if (virBufferVSprintf(buf, "    </disk>\n") < 0)
D
Daniel P. Berrange 已提交
3024 3025 3026 3027 3028
            goto no_memory;

        disk = disk->next;
    }

3029
    net = def->nets;
3030
    while (net) {
D
Daniel P. Berrange 已提交
3031 3032
        const char *types[] = {
            "user",
3033
            "ethernet",
D
Daniel P. Berrange 已提交
3034 3035 3036
            "server",
            "client",
            "mcast",
3037
            "network",
3038
            "bridge",
D
Daniel P. Berrange 已提交
3039
        };
D
Daniel P. Berrange 已提交
3040
        if (virBufferVSprintf(buf, "    <interface type='%s'>\n",
D
Daniel P. Berrange 已提交
3041 3042 3043
                              types[net->type]) < 0)
            goto no_memory;

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

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

3054
            if (net->dst.network.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
3055
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.network.ifname) < 0)
3056 3057 3058
                    goto no_memory;
            }
            break;
3059

3060 3061
        case QEMUD_NET_ETHERNET:
            if (net->dst.ethernet.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
3062
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname) < 0)
3063 3064 3065
                    goto no_memory;
            }
            if (net->dst.ethernet.script[0] != '\0') {
D
Daniel P. Berrange 已提交
3066
                if (virBufferVSprintf(buf, "      <script path='%s'/>\n", net->dst.ethernet.script) < 0)
3067 3068 3069 3070 3071
                    goto no_memory;
            }
            break;

        case QEMUD_NET_BRIDGE:
D
Daniel P. Berrange 已提交
3072
            if (virBufferVSprintf(buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname) < 0)
3073
                goto no_memory;
3074
            if (net->dst.bridge.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
3075
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname) < 0)
3076 3077 3078 3079 3080 3081 3082 3083
                    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 已提交
3084
                if (virBufferVSprintf(buf, "      <source address='%s' port='%d'/>\n",
3085 3086 3087
                                      net->dst.socket.address, net->dst.socket.port) < 0)
                    goto no_memory;
            } else {
D
Daniel P. Berrange 已提交
3088
                if (virBufferVSprintf(buf, "      <source port='%d'/>\n",
3089 3090 3091
                                      net->dst.socket.port) < 0)
                    goto no_memory;
            }
3092 3093
        }

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

3097
        net = net->next;
D
Daniel P. Berrange 已提交
3098 3099
    }

3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112
    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)
        if (virBufferAdd(buf, "    <input type='mouse' bus='ps2'/>\n", -1) < 0)
            goto no_memory;

3113 3114
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
D
Daniel P. Berrange 已提交
3115
        if (virBufferAdd(buf, "    <graphics type='vnc'", -1) < 0)
3116 3117 3118
            goto no_memory;

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

3123 3124 3125 3126 3127
        if (def->vncListen[0] &&
            virBufferVSprintf(buf, " listen='%s'",
                              def->vncListen) < 0)
            goto no_memory;

D
Daniel P. Berrange 已提交
3128
        if (virBufferAdd(buf, "/>\n", -1) < 0)
3129 3130 3131 3132
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_SDL:
D
Daniel P. Berrange 已提交
3133
        if (virBufferAdd(buf, "    <graphics type='sdl'/>\n", -1) < 0)
3134 3135 3136 3137 3138 3139 3140 3141
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

3142
    if (def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
3143 3144
    }

D
Daniel P. Berrange 已提交
3145
    if (virBufferAdd(buf, "  </devices>\n", -1) < 0)
D
Daniel P. Berrange 已提交
3146 3147 3148
        goto no_memory;


D
Daniel P. Berrange 已提交
3149
    if (virBufferAdd(buf, "</domain>\n", -1) < 0)
D
Daniel P. Berrange 已提交
3150 3151
        goto no_memory;

D
Daniel P. Berrange 已提交
3152
    return virBufferContentAndFree (buf);
D
Daniel P. Berrange 已提交
3153 3154

 no_memory:
3155
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
3156
 cleanup:
D
Daniel P. Berrange 已提交
3157
    if (buf) virBufferFree (buf);
D
Daniel P. Berrange 已提交
3158 3159 3160 3161
    return NULL;
}


3162 3163
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
3164
                              struct qemud_network *network,
3165
                              struct qemud_network_def *def) {
D
Daniel P. Berrange 已提交
3166
    virBufferPtr buf = 0;
3167
    unsigned char *uuid;
3168
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3169

D
Daniel P. Berrange 已提交
3170
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
3171
    if (!buf)
3172 3173
        goto no_memory;

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

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

3180
    uuid = def->uuid;
3181 3182
    virUUIDFormat(uuid, uuidstr);
    if (virBufferVSprintf(buf, "  <uuid>%s</uuid>\n", uuidstr) < 0)
3183 3184
        goto no_memory;

3185 3186
    if (def->forward) {
        if (def->forwardDev[0]) {
D
Daniel P. Berrange 已提交
3187
            virBufferVSprintf(buf, "  <forward dev='%s'/>\n",
3188 3189
                              def->forwardDev);
        } else {
D
Daniel P. Berrange 已提交
3190
            virBufferAdd(buf, "  <forward/>\n", -1);
3191 3192 3193
        }
    }

D
Daniel P. Berrange 已提交
3194
    virBufferAdd(buf, "  <bridge", -1);
3195
    if (qemudIsActiveNetwork(network)) {
D
Daniel P. Berrange 已提交
3196
        if (virBufferVSprintf(buf, " name='%s'", network->bridge) < 0)
3197 3198
            goto no_memory;
    } else if (def->bridge[0]) {
D
Daniel P. Berrange 已提交
3199
        if (virBufferVSprintf(buf, " name='%s'", def->bridge) < 0)
3200 3201
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
3202
    if (virBufferVSprintf(buf, " stp='%s' forwardDelay='%d' />\n",
3203 3204
                       def->disableSTP ? "off" : "on",
                       def->forwardDelay) < 0)
3205 3206
        goto no_memory;

3207
    if (def->ipAddress[0] || def->netmask[0]) {
D
Daniel P. Berrange 已提交
3208
        if (virBufferAdd(buf, "  <ip", -1) < 0)
3209 3210
            goto no_memory;

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

3215
        if (def->netmask[0] &&
D
Daniel P. Berrange 已提交
3216
            virBufferVSprintf(buf, " netmask='%s'", def->netmask) < 0)
3217 3218
            goto no_memory;

D
Daniel P. Berrange 已提交
3219
        if (virBufferAdd(buf, ">\n", -1) < 0)
3220 3221
            goto no_memory;

3222 3223
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
D
Daniel P. Berrange 已提交
3224
            if (virBufferAdd(buf, "    <dhcp>\n", -1) < 0)
3225 3226
                goto no_memory;
            while (range) {
D
Daniel P. Berrange 已提交
3227
                if (virBufferVSprintf(buf, "      <range start='%s' end='%s' />\n",
3228 3229 3230 3231
                                      range->start, range->end) < 0)
                    goto no_memory;
                range = range->next;
            }
D
Daniel P. Berrange 已提交
3232
            if (virBufferAdd(buf, "    </dhcp>\n", -1) < 0)
3233 3234 3235
                goto no_memory;
        }

D
Daniel P. Berrange 已提交
3236
        if (virBufferAdd(buf, "  </ip>\n", -1) < 0)
3237
            goto no_memory;
D
Daniel P. Berrange 已提交
3238 3239
    }

D
Daniel P. Berrange 已提交
3240
    if (virBufferAdd(buf, "</network>\n", -1) < 0)
3241 3242
        goto no_memory;

D
Daniel P. Berrange 已提交
3243
    return virBufferContentAndFree (buf);
3244 3245

 no_memory:
3246
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
3247
    if (buf) virBufferFree (buf);
3248 3249 3250 3251
    return NULL;
}


3252 3253
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
3254 3255 3256
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
3257
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "no config file for %s", name);
D
Daniel P. Berrange 已提交
3258 3259 3260
        return -1;
    }

3261
    if (unlink(configFile) < 0) {
3262
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot remove config for %s", name);
3263 3264
        return -1;
    }
3265

D
Daniel P. Berrange 已提交
3266 3267 3268
    return 0;
}

3269
#endif /* WITH_QEMU */
D
Daniel P. Berrange 已提交
3270 3271 3272 3273 3274 3275 3276 3277 3278

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