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

24
#include <config.h>
25 26

#ifdef WITH_QEMU
27

D
Daniel P. Berrange 已提交
28 29 30 31 32 33 34 35
#include <dirent.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
36
#include <sys/wait.h>
37
#include <arpa/inet.h>
38
#include <sys/utsname.h>
D
Daniel P. Berrange 已提交
39 40 41 42 43 44

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

45
#include "libvirt/virterror.h"
D
Daniel P. Berrange 已提交
46

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

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

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

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

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

D
Daniel P. Berrange 已提交
76 77 78 79 80 81 82 83 84
int qemudLoadDriverConfig(struct qemud_driver *driver,
                          const char *filename) {
    virConfPtr conf;
    virConfValuePtr p;

    /* Setup 2 critical defaults */
    strcpy(driver->vncListen, "127.0.0.1");
    if (!(driver->vncTLSx509certdir = strdup(SYSCONF_DIR "/pki/libvirt-vnc"))) {
        qemudReportError(NULL, NULL, NULL, VIR_ERR_NO_MEMORY,
85
                         "%s", _("failed to allocate vncTLSx509certdir"));
D
Daniel P. Berrange 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
        return -1;
    }

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

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


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

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

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

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

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

    virConfFree (conf);
    return 0;
}


138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
struct qemud_vm *qemudFindVMByID(const struct qemud_driver *driver, int id) {
    struct qemud_vm *vm = driver->vms;

    while (vm) {
        if (qemudIsActiveVM(vm) && vm->id == id)
            return vm;
        vm = vm->next;
    }

    return NULL;
}

struct qemud_vm *qemudFindVMByUUID(const struct qemud_driver *driver,
                                   const unsigned char *uuid) {
    struct qemud_vm *vm = driver->vms;

    while (vm) {
155
        if (!memcmp(vm->def->uuid, uuid, VIR_UUID_BUFLEN))
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            return vm;
        vm = vm->next;
    }

    return NULL;
}

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

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

    return NULL;
}

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

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

    return NULL;
}

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

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

    return NULL;
}

202

203 204 205 206
/* Free all memory associated with a struct qemud_vm object */
void qemudFreeVMDef(struct qemud_vm_def *def) {
    struct qemud_vm_disk_def *disk = def->disks;
    struct qemud_vm_net_def *net = def->nets;
D
Daniel P. Berrange 已提交
207
    struct qemud_vm_input_def *input = def->inputs;
208 209
    struct qemud_vm_chr_def *serial = def->serials;
    struct qemud_vm_chr_def *parallel = def->parallels;
210 211 212 213 214 215 216 217 218 219 220

    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 已提交
221 222 223 224 225
    while (input) {
        struct qemud_vm_input_def *prev = input;
        input = input->next;
        free(prev);
    }
226 227 228 229 230 231 232 233 234 235
    while (serial) {
        struct qemud_vm_chr_def *prev = serial;
        serial = serial->next;
        free(prev);
    }
    while (parallel) {
        struct qemud_vm_chr_def *prev = parallel;
        parallel = parallel->next;
        free(prev);
    }
236
    xmlFree(def->keymap);
237
    free(def);
238 239 240 241 242 243 244 245
}

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

247

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

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

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

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

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

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

D
Daniel P. Berrange 已提交
296
/* The archicture tables for supported QEMU archs */
297 298 299 300 301 302 303 304 305 306 307 308 309
static const struct qemu_arch_info const arch_info_hvm[] = {
    {  "i686", 32, arch_info_hvm_x86_machines, 2,
       "/usr/bin/qemu", arch_info_i686_flags, 4 },
    {  "x86_64", 64, arch_info_hvm_x86_machines, 2,
       "/usr/bin/qemu-system-x86_64", arch_info_x86_64_flags, 2 },
    {  "mips", 32, arch_info_hvm_mips_machines, 1,
       "/usr/bin/qemu-system-mips", NULL, 0 },
    {  "mipsel", 32, arch_info_hvm_mips_machines, 1,
       "/usr/bin/qemu-system-mipsel", NULL, 0 },
    {  "sparc", 32, arch_info_hvm_sparc_machines, 1,
       "/usr/bin/qemu-system-sparc", NULL, 0 },
    {  "ppc", 32, arch_info_hvm_ppc_machines, 3,
       "/usr/bin/qemu-system-ppc", NULL, 0 },
D
Daniel P. Berrange 已提交
310 311
};

312 313 314 315 316 317
static const struct qemu_arch_info const arch_info_xen[] = {
    {  "i686", 32, arch_info_xen_x86_machines, 1,
       "/usr/bin/xenner", arch_info_i686_flags, 4 },
    {  "x86_64", 64, arch_info_xen_x86_machines, 1,
       "/usr/bin/xenner", arch_info_x86_64_flags, 2 },
};
D
Daniel P. Berrange 已提交
318

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

327 328 329 330 331 332 333 334 335
    if ((guest = virCapabilitiesAddGuest(caps,
                                         hvm ? "hvm" : "xen",
                                         info->arch,
                                         info->wordsize,
                                         info->binary,
                                         NULL,
                                         info->nmachines,
                                         info->machines)) == NULL)
        return -1;
D
Daniel P. Berrange 已提交
336

337 338 339 340 341 342 343 344 345 346
    if (hvm) {
        /* Check for existance of base emulator */
        if (access(info->binary, X_OK) == 0 &&
            virCapabilitiesAddGuestDomain(guest,
                                          "qemu",
                                          NULL,
                                          NULL,
                                          0,
                                          NULL) == NULL)
            return -1;
D
Daniel P. Berrange 已提交
347

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
        /* If guest & host match, then we can accelerate */
        if (STREQ(info->arch, hostmachine)) {
            if (access("/dev/kqemu", F_OK) == 0 &&
                virCapabilitiesAddGuestDomain(guest,
                                              "kqemu",
                                              NULL,
                                              NULL,
                                              0,
                                              NULL) == NULL)
                return -1;

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

378 379 380 381 382 383 384
    if (info->nflags) {
        for (i = 0 ; i < info->nflags ; i++) {
            if (virCapabilitiesAddGuestFeature(guest,
                                               info->flags[i].name,
                                               info->flags[i].default_on,
                                               info->flags[i].toggle) == NULL)
                return -1;
D
Daniel P. Berrange 已提交
385 386 387
        }
    }

388
    return 0;
D
Daniel P. Berrange 已提交
389 390
}

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

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

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

    for (i = 0 ; i < (sizeof(arch_info_hvm)/sizeof(arch_info_hvm[0])) ; i++)
        if (qemudCapsInitGuest(caps,
                               utsname.machine,
                               &arch_info_hvm[i], 1) < 0)
            goto no_memory;

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

423 424 425 426 427
    return caps;

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

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

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 已提交
465
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
466
        int got = 0, ret = -1;
467 468 469 470 471
        int major, minor, micro;

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

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

        return ret;
    }
}

528
int qemudExtractVersion(virConnectPtr conn,
529 530
                        struct qemud_driver *driver) {
    const char *binary;
531
    struct stat sb;
532
    int ignored;
533

534
    if (driver->qemuVersion > 0)
535 536
        return 0;

537 538 539 540
    if ((binary = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                      "hvm",
                                                      "i686",
                                                      "qemu")) == NULL)
541 542
        return -1;

543
    if (stat(binary, &sb) < 0) {
544
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
545
                         _("Cannot find QEMU binary %s: %s"), binary,
546 547 548 549
                         strerror(errno));
        return -1;
    }

550
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &ignored) < 0) {
551 552 553 554 555 556
        return -1;
    }

    return 0;
}

557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
/* Converts def->virtType to applicable string type
 * @param type integer virt type
 * @return string type on success, NULL on fail
 */
const char * qemudVirtTypeToString(int type) {
    switch (type) {
        case QEMUD_VIRT_QEMU:
            return "qemu";
        case QEMUD_VIRT_KQEMU:
            return "kqemu";
        case QEMUD_VIRT_KVM:
            return "kvm";
    }
    return NULL;
}
572

D
Daniel P. Berrange 已提交
573 574 575 576 577 578 579 580
/* 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 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    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");
602

D
Daniel P. Berrange 已提交
603 604 605 606 607
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
608

D
Daniel P. Berrange 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
                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) {
624 625 626 627 628 629 630 631
        /* There is a case without the source
         * to the CD-ROM device
         */
        if (!device || STRNEQ((const char *) device, "cdrom")) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SOURCE,
                             target ? "%s" : NULL, target);
            goto error;
        }
D
Daniel P. Berrange 已提交
632
    }
633

D
Daniel P. Berrange 已提交
634
    if (target == NULL) {
635
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
636 637 638 639 640 641 642
        goto error;
    }

    if (device &&
        !strcmp((const char *)device, "floppy") &&
        strcmp((const char *)target, "fda") &&
        strcmp((const char *)target, "fdb")) {
643 644
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid floppy device name: %s"), target);
D
Daniel P. Berrange 已提交
645 646
        goto error;
    }
647

D
Daniel P. Berrange 已提交
648 649 650
    if (device &&
        !strcmp((const char *)device, "cdrom") &&
        strcmp((const char *)target, "hdc")) {
651 652
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid cdrom device name: %s"), target);
D
Daniel P. Berrange 已提交
653 654 655 656 657 658 659 660 661 662 663 664
        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")) {
665 666
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid harddisk device name: %s"), target);
D
Daniel P. Berrange 已提交
667 668 669
        goto error;
    }

670
    strncpy(disk->src, (source ? (const char *) source : "\0"), NAME_MAX-1);
D
Daniel P. Berrange 已提交
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
    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 {
686 687
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Invalid device type: %s"), device);
D
Daniel P. Berrange 已提交
688 689 690 691 692 693 694
        goto error;
    }

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

D
Daniel P. Berrange 已提交
695
    return 0;
D
Daniel P. Berrange 已提交
696 697

 error:
698 699 700 701
    xmlFree(type);
    xmlFree(target);
    xmlFree(source);
    xmlFree(device);
D
Daniel P. Berrange 已提交
702
    return -1;
D
Daniel P. Berrange 已提交
703 704
}

705 706 707 708 709 710 711 712 713
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 已提交
714

D
Daniel P. Berrange 已提交
715 716 717 718 719 720 721 722
/* 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 已提交
723 724 725
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
726
    xmlChar *network = NULL;
727 728 729 730 731
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
732
    xmlChar *model = NULL;
D
Daniel P. Berrange 已提交
733 734 735 736 737 738 739

    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;
740 741
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
742 743 744 745 746 747
        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;
748 749
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
750 751
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
752 753 754 755 756 757 758 759 760 761 762 763
        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");
764 765 766 767
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
768 769 770
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
771
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
772 773 774 775 776 777 778 779 780 781 782 783 784
            } 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");
785 786 787 788 789
                if (STREQLEN("vnet", (const char*)ifname, 4)) {
                    /* An auto-generated target name, blank it out */
                    xmlFree(ifname);
                    ifname = NULL;
                }
790 791 792 793
            } else if ((script == NULL) &&
                       (net->type == QEMUD_NET_ETHERNET) &&
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = xmlGetProp(cur, BAD_CAST "path");
794 795
            } else if (xmlStrEqual (cur->name, BAD_CAST "model")) {
                model = xmlGetProp (cur, BAD_CAST "type");
D
Daniel P. Berrange 已提交
796 797 798 799 800 801
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
802
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
803
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
804 805 806 807 808 809 810 811 812 813 814 815
               (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 已提交
816 817

        xmlFree(macaddr);
818 819 820
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
821 822
    }

823 824 825 826
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
827
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
828
                             "%s", _("No <source> 'network' attribute specified with <interface type='network'/>"));
829
            goto error;
830
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
831
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
832
                             _("Network name '%s' too long"), network);
833 834 835 836 837 838
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

839
        if (network) {
840
            xmlFree(network);
841 842 843 844 845
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
846
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
847 848
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
849 850 851 852 853 854 855 856 857 858
                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;
859

860 861
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
862
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
863
                                 _("TAP script path '%s' is too long"), script);
864 865 866 867 868 869 870 871 872 873
                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)) {
874
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
875 876
                                 _("TAP interface name '%s' is too long"),
                                 ifname);
877 878
                goto error;
            } else {
879 880
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
881
            }
882 883 884 885 886 887
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
888
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
889
                             "%s", _("No <source> 'dev' attribute specified with <interface type='bridge'/>"));
890 891
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
892
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
893
                             _("TAP bridge path '%s' is too long"), bridge);
894 895 896 897
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
898
        }
899 900 901 902 903 904

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
905
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
906
                                 _("TAP interface name '%s' is too long"), ifname);
907 908 909 910 911 912 913 914 915 916
                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) {
917
        int len = 0;
918 919 920
        char *ret;

        if (port == NULL) {
921
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
922
                             "%s", _("No <source> 'port' attribute specified with socket interface"));
923 924 925 926
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
927
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
928
                             "%s", _("Cannot parse <source> 'port' attribute with socket interface"));
929 930 931 932 933 934 935 936
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
937
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
938
                                 "%s", _("No <source> 'address' attribute specified with socket interface"));
939 940 941
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
942
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
943
                             _("IP address '%s' is too long"), address);
944 945 946 947 948 949 950 951 952
            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);
953 954
    }

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    /* NIC model (see -net nic,model=?).  We only check that it looks
     * reasonable, not that it is a supported NIC type.  FWIW kvm
     * supports these types as of April 2008:
     * i82551 i82557b i82559er ne2k_pci pcnet rtl8139 e1000 virtio
     */
    if (model != NULL) {
        int i, len, char_ok;

        len = xmlStrlen (model);
        if (len >= QEMUD_MODEL_MAX_LEN) {
            qemudReportError (conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                              _("Model name '%s' is too long"), model);
            goto error;
        }
        for (i = 0; i < len; ++i) {
            char_ok =
                (model[i] >= '0' && model[i] <= '9') ||
                (model[i] >= 'a' && model[i] <= 'z') ||
                (model[i] >= 'A' && model[i] <= 'Z') || model[i] == '_';
            if (!char_ok) {
                qemudReportError (conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                                  _("Model name contains invalid characters"));
                goto error;
            }
        }
        strncpy (net->model, (const char*) model, len);
        net->model[len] = '\0';

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

D
Daniel P. Berrange 已提交
988
    return 0;
989 990

 error:
991 992 993 994 995 996
    xmlFree(network);
    xmlFree(address);
    xmlFree(port);
    xmlFree(ifname);
    xmlFree(script);
    xmlFree(bridge);
997
    xmlFree(model);
D
Daniel P. Berrange 已提交
998
    return -1;
D
Daniel P. Berrange 已提交
999 1000 1001
}


1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
/* Parse the XML definition for a character device
 * @param net pre-allocated & zero'd net record
 * @param node XML nodeset to parse for net definition
 * @return 0 on success, -1 on failure
 *
 * The XML we're dealing with looks like
 *
 * <serial type="pty">
 *   <source path="/dev/pts/3"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="dev">
 *   <source path="/dev/ttyS0"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="tcp">
 *   <source mode="connect" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="tcp">
 *   <source mode="bind" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="udp">
 *   <source mode="bind" host="0.0.0.0" service="2445"/>
 *   <source mode="connect" host="0.0.0.0" service="2445"/>
 *   <target port="1"/>
 * </serial>
 *
 * <serial type="unix">
 *   <source mode="bind" path="/tmp/foo"/>
 *   <target port="1"/>
 * </serial>
 *
 */
static int qemudParseCharXML(virConnectPtr conn,
                             struct qemud_vm_chr_def *chr,
                             int portNum,
                             xmlNodePtr node) {
    xmlNodePtr cur;
    xmlChar *type = NULL;
    xmlChar *bindHost = NULL;
    xmlChar *bindService = NULL;
    xmlChar *connectHost = NULL;
    xmlChar *connectService = NULL;
    xmlChar *path = NULL;
    xmlChar *mode = NULL;
    xmlChar *protocol = NULL;
    int ret = -1;

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

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

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

                    break;

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

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

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


    chr->dstPort = portNum;

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

    case QEMUD_CHR_SRC_TYPE_VC:
        break;

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

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

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

    case QEMUD_CHR_SRC_TYPE_STDIO:
        /* Nada */
        break;

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

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

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

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

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

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

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

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

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

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

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

    ret = 0;

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

    return ret;
}


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

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

        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
            struct qemud_vm_chr_def *chr = calloc(1, sizeof(*chr));
            if (!chr) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                                 "%s",
                                 _("failed to allocate space for char device"));
                goto cleanup;
            }

            if (qemudParseCharXML(conn, chr, i, obj->nodesetval->nodeTab[i]) < 0) {
                free(chr);
                goto cleanup;
            }
            if (ndevs)
                (*ndevs)++;
            chr->next = NULL;
            if (i == 0) {
                *devs = chr;
            } else {
                prev->next = chr;
            }
            prev = chr;
        }
    }

    ret = 0;

cleanup:
    xmlXPathFreeObject(obj);
    return ret;
}


1329
/* Parse the XML definition for a network interface */
D
Daniel P. Berrange 已提交
1330 1331 1332
static int qemudParseInputXML(virConnectPtr conn,
                              struct qemud_vm_input_def *input,
                              xmlNodePtr node) {
1333 1334 1335 1336 1337 1338 1339
    xmlChar *type = NULL;
    xmlChar *bus = NULL;

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

    if (!type) {
1340 1341
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing input device type"));
1342 1343 1344 1345 1346 1347 1348 1349
        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 {
1350 1351 1352
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unsupported input device type %s"),
                         (const char*)type);
1353 1354 1355 1356 1357 1358
        goto error;
    }

    if (bus) {
        if (!strcmp((const char*)bus, "ps2")) { /* Only allow mouse */
            if (input->type == QEMU_INPUT_TYPE_TABLET) {
1359 1360 1361
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("ps2 bus does not support %s input device"),
                                 (const char*)type);
1362 1363 1364 1365 1366 1367
                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 {
1368 1369
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("unsupported input bus %s"), (const char*)bus);
1370 1371 1372 1373 1374 1375 1376 1377 1378
            goto error;
        }
    } else {
        if (input->type == QEMU_INPUT_TYPE_MOUSE)
            input->bus = QEMU_INPUT_BUS_PS2;
        else
            input->bus = QEMU_INPUT_BUS_USB;
    }

1379 1380
    xmlFree(type);
    xmlFree(bus);
1381

D
Daniel P. Berrange 已提交
1382
    return 0;
1383 1384

 error:
1385 1386
    xmlFree(type);
    xmlFree(bus);
1387

D
Daniel P. Berrange 已提交
1388
    return -1;
1389 1390
}

D
Daniel Veillard 已提交
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
/* Sound device helper functions */
static int qemudSoundModelFromString(const char *model) {
    if (STREQ(model, "sb16")) {
        return QEMU_SOUND_SB16;
    } else if (STREQ(model, "es1370")) {
        return QEMU_SOUND_ES1370;
    } else if (STREQ(model, "pcspk")) {
        return QEMU_SOUND_PCSPK;
    }

    return -1;
}

static const char *qemudSoundModelToString(const int model) {

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

    return NULL;
}


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

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

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

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

1443

D
Daniel P. Berrange 已提交
1444 1445 1446 1447
/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
1448 1449
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
1450
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
1451 1452 1453 1454 1455 1456
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
1457 1458
    struct qemud_vm_def *def;

1459
    if (!(def = calloc(1, sizeof(*def)))) {
1460 1461
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
1462 1463
        return NULL;
    }
D
Daniel P. Berrange 已提交
1464 1465 1466 1467

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
1468 1469
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
D
Daniel P. Berrange 已提交
1470 1471 1472 1473 1474
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1475 1476
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for xmlXPathContext"));
D
Daniel P. Berrange 已提交
1477 1478 1479 1480 1481 1482
        goto error;
    }


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

    if (!strcmp((char *)prop, "qemu"))
1489
        def->virtType = QEMUD_VIRT_QEMU;
D
Daniel P. Berrange 已提交
1490
    else if (!strcmp((char *)prop, "kqemu"))
1491
        def->virtType = QEMUD_VIRT_KQEMU;
D
Daniel P. Berrange 已提交
1492
    else if (!strcmp((char *)prop, "kvm"))
1493
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
1494
    else {
1495 1496
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("invalid domain type attribute"));
D
Daniel P. Berrange 已提交
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
        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)) {
1507
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
1508 1509 1510
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1511 1512
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("domain name length too long"));
D
Daniel P. Berrange 已提交
1513 1514
        goto error;
    }
1515
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1516 1517 1518 1519 1520 1521 1522
    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)) {
1523
        int err;
D
Daniel P. Berrange 已提交
1524
        if ((err = virUUIDGenerate(def->uuid))) {
1525
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1526
                             _("Failed to generate UUID: %s"), strerror(err));
1527 1528
            goto error;
        }
D
Daniel P. Berrange 已提交
1529
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
1530 1531
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
D
Daniel P. Berrange 已提交
1532 1533 1534 1535 1536 1537 1538 1539 1540
        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)) {
1541 1542
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("missing memory element"));
D
Daniel P. Berrange 已提交
1543 1544 1545
        goto error;
    } else {
        conv = NULL;
1546
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1547
        if (conv == (const char*)obj->stringval) {
1548 1549
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1550 1551 1552
            goto error;
        }
    }
1553
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1554 1555 1556 1557 1558 1559


    /* 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)) {
1560
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1561 1562
    } else {
        conv = NULL;
1563 1564 1565
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
1566
        if (conv == (const char*)obj->stringval) {
1567 1568
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed memory information"));
D
Daniel P. Berrange 已提交
1569 1570 1571
            goto error;
        }
    }
1572
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1573 1574 1575 1576 1577

    /* 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)) {
1578
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
1579 1580
    } else {
        conv = NULL;
1581
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
1582
        if (conv == (const char*)obj->stringval) {
1583 1584
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("malformed vcpu information"));
D
Daniel P. Berrange 已提交
1585 1586 1587
            goto error;
        }
    }
1588
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1589 1590 1591 1592 1593

    /* 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)) {
1594
        def->features |= QEMUD_FEATURE_ACPI;
D
Daniel P. Berrange 已提交
1595
    }
1596
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1597

D
Daniel P. Berrange 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609

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

1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    /* 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;
    }
1623
    xmlXPathFreeObject(obj);
1624

D
Daniel P. Berrange 已提交
1625

D
Daniel P. Berrange 已提交
1626 1627 1628 1629
    /* 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)) {
1630 1631
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
                         "%s", _("no OS type"));
D
Daniel P. Berrange 已提交
1632 1633
        goto error;
    }
1634
    if (!virCapabilitiesSupportsGuestOSType(driver->caps, (const char*)obj->stringval)) {
1635 1636
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE,
                         "%s", obj->stringval);
D
Daniel P. Berrange 已提交
1637 1638
        goto error;
    }
1639
    strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1640 1641 1642 1643 1644 1645
    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)) {
1646 1647
        const char *defaultArch = virCapabilitiesDefaultGuestArch(driver->caps, def->os.type);
        if (defaultArch == NULL) {
1648 1649
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1650 1651
            goto error;
        }
D
Daniel P. Berrange 已提交
1652
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1653 1654
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1655 1656
            goto error;
        }
1657
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
1658 1659
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
1660 1661
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1662 1663
            goto error;
        }
1664
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1665
    }
1666
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1667 1668 1669 1670

    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)) {
1671 1672 1673 1674
        const char *defaultMachine = virCapabilitiesDefaultGuestMachine(driver->caps,
                                                                        def->os.type,
                                                                        def->os.arch);
        if (defaultMachine == NULL) {
1675 1676
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported architecture"));
1677 1678
            goto error;
        }
D
Daniel P. Berrange 已提交
1679
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1680 1681
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("machine type too long"));
D
Daniel P. Berrange 已提交
1682 1683
            goto error;
        }
1684
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1685 1686
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1687 1688
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("architecture type too long"));
D
Daniel P. Berrange 已提交
1689 1690
            goto error;
        }
1691
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1692
    }
1693
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1694 1695 1696 1697 1698 1699


    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)) {
1700 1701
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("kernel path too long"));
D
Daniel P. Berrange 已提交
1702 1703
            goto error;
        }
1704
        strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1705
    }
1706
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1707 1708 1709 1710 1711 1712


    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)) {
1713 1714
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("initrd path too long"));
D
Daniel P. Berrange 已提交
1715 1716
            goto error;
        }
1717
        strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1718
    }
1719
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1720 1721 1722 1723 1724 1725


    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)) {
1726 1727
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("cmdline arguments too long"));
D
Daniel P. Berrange 已提交
1728 1729
            goto error;
        }
1730
        strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1731
    }
1732
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1733 1734 1735 1736 1737 1738 1739


    /* 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++) {
1740 1741
            if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                continue;
D
Daniel P. Berrange 已提交
1742
            if (!strcmp((char *)prop, "hd")) {
1743
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1744
            } else if (!strcmp((char *)prop, "fd")) {
1745
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
D
Daniel P. Berrange 已提交
1746
            } else if (!strcmp((char *)prop, "cdrom")) {
1747
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
1748
            } else if (!strcmp((char *)prop, "network")) {
1749
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
D
Daniel P. Berrange 已提交
1750
            } else {
1751
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1752
                             _("unknown boot device \'%s\'"), (char*)prop);
D
Daniel P. Berrange 已提交
1753 1754
                goto error;
            }
1755
            xmlFree(prop);
1756
            prop = NULL;
D
Daniel P. Berrange 已提交
1757 1758 1759
        }
    }
    xmlXPathFreeObject(obj);
1760 1761 1762
    if (def->os.nBootDevs == 0) {
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1763 1764 1765 1766 1767 1768
    }


    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1769 1770 1771 1772 1773 1774
        const char *type = qemudVirtTypeToString(def->virtType);
        if (!type) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unknown virt type"));
            goto error;
        }
1775 1776 1777 1778 1779
        const char *emulator = virCapabilitiesDefaultGuestEmulator(driver->caps,
                                                                   def->os.type,
                                                                   def->os.arch,
                                                                   type);
        if (!emulator) {
1780 1781
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("unsupported guest type"));
D
Daniel P. Berrange 已提交
1782 1783
            goto error;
        }
1784
        strcpy(def->os.binary, emulator);
D
Daniel P. Berrange 已提交
1785 1786
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1787 1788
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("emulator path too long"));
D
Daniel P. Berrange 已提交
1789 1790
            goto error;
        }
1791
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1792
    }
1793
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1794 1795 1796 1797

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1798
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1799
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
D
Daniel P. Berrange 已提交
1800
        if (!strcmp((char *)prop, "vnc")) {
1801
            xmlChar *vncport, *vnclisten;
1802
            def->graphicsType = QEMUD_GRAPHICS_VNC;
1803 1804
            vncport = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (vncport) {
D
Daniel P. Berrange 已提交
1805
                conv = NULL;
1806
                def->vncPort = strtoll((const char*)vncport, &conv, 10);
D
Daniel P. Berrange 已提交
1807
            } else {
1808
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1809
            }
1810 1811 1812 1813
            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 已提交
1814
                strcpy(def->vncListen, driver->vncListen);
1815
            def->vncListen[BR_INET_ADDR_MAXLEN-1] = '\0';
1816
            def->keymap = (char *) xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "keymap");
1817 1818
            xmlFree(vncport);
            xmlFree(vnclisten);
D
Daniel P. Berrange 已提交
1819
        } else if (!strcmp((char *)prop, "sdl")) {
1820
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1821
        } else {
1822 1823
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Unsupported graphics type %s"), prop);
D
Daniel P. Berrange 已提交
1824 1825
            goto error;
        }
1826
        xmlFree(prop);
1827
        prop = NULL;
D
Daniel P. Berrange 已提交
1828
    }
1829
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1830 1831 1832 1833 1834

    /* 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)) {
1835
        struct qemud_vm_disk_def *prev = NULL;
D
Daniel P. Berrange 已提交
1836
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1837
            struct qemud_vm_disk_def *disk = calloc(1, sizeof(*disk));
D
Daniel P. Berrange 已提交
1838
            if (!disk) {
1839 1840
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for disk string"));
D
Daniel P. Berrange 已提交
1841 1842 1843 1844
                goto error;
            }
            if (qemudParseDiskXML(conn, disk, obj->nodesetval->nodeTab[i]) < 0) {
                free(disk);
D
Daniel P. Berrange 已提交
1845 1846
                goto error;
            }
1847
            def->ndisks++;
1848 1849 1850 1851 1852 1853 1854
            disk->next = NULL;
            if (i == 0) {
                def->disks = disk;
            } else {
                prev->next = disk;
            }
            prev = disk;
D
Daniel P. Berrange 已提交
1855 1856 1857
        }
    }
    xmlXPathFreeObject(obj);
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896
    obj = NULL;

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

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

            if (qemudParseCharXML(conn, chr, 0, obj->nodesetval->nodeTab[0]) < 0) {
                free(chr);
                goto error;
            }
            def->nserials = 1;
            def->serials = chr;
        }
        xmlXPathFreeObject(obj);
    }
D
Daniel P. Berrange 已提交
1897 1898 1899 1900 1901 1902


    /* 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)) {
1903
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
1904
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
1905
            struct qemud_vm_net_def *net = calloc(1, sizeof(*net));
D
Daniel P. Berrange 已提交
1906
            if (!net) {
1907 1908
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                           "%s", _("failed to allocate space for net string"));
D
Daniel P. Berrange 已提交
1909 1910 1911 1912
                goto error;
            }
            if (qemudParseInterfaceXML(conn, net, obj->nodesetval->nodeTab[i]) < 0) {
                free(net);
D
Daniel P. Berrange 已提交
1913 1914
                goto error;
            }
1915
            def->nnets++;
1916 1917 1918 1919 1920 1921 1922
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
1923 1924 1925
        }
    }
    xmlXPathFreeObject(obj);
1926 1927 1928 1929 1930 1931 1932

    /* 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++) {
1933
            struct qemud_vm_input_def *input = calloc(1, sizeof(*input));
D
Daniel P. Berrange 已提交
1934
            if (!input) {
1935 1936
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
D
Daniel P. Berrange 已提交
1937 1938 1939 1940
                goto error;
            }
            if (qemudParseInputXML(conn, input, obj->nodesetval->nodeTab[i]) < 0) {
                free(input);
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
                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;
1951
            if (def->inputs == NULL) {
1952 1953 1954 1955 1956 1957 1958 1959
                def->inputs = input;
            } else {
                prev->next = input;
            }
            prev = input;
        }
    }
    xmlXPathFreeObject(obj);
D
Daniel Veillard 已提交
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003

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

            struct qemud_vm_sound_def *sound = calloc(1, sizeof(*sound));
            struct qemud_vm_sound_def *check = def->sounds;
            int collision = 0;
            if (!sound) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for sound dev"));
                goto error;
            }
            if (qemudParseSoundXML(conn, sound,
                                   obj->nodesetval->nodeTab[i]) < 0) {
                free(sound);
                goto error;
            }

            // Check that model type isn't already present in sound dev list
            while(check) {
                if (check->model == sound->model) {
                    collision = 1;
                    break;
                }
                check = check->next;
            }
            if (collision)
                continue;

            def->nsounds++;
            sound->next = NULL;
            if (def->sounds == NULL) {
                def->sounds = sound;
            } else {
                prev->next = sound;
            }
            prev = sound;
        }
    }
    xmlXPathFreeObject(obj);
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
    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) {
2018
            input = calloc(1, sizeof(*input));
2019
            if (!input) {
2020 2021
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for input string"));
2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
                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 已提交
2032 2033
    xmlXPathFreeContext(ctxt);

2034
    return def;
D
Daniel P. Berrange 已提交
2035 2036

 error:
2037
    free(prop);
2038
    xmlXPathFreeObject(obj);
2039
    xmlXPathFreeContext(ctxt);
2040 2041
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
2042 2043 2044
}


2045
static char *
2046 2047
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
2048
                         struct qemud_vm *vm,
2049 2050
                         struct qemud_vm_net_def *net,
                         int vlan)
2051
{
2052 2053 2054
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
2055 2056 2057 2058 2059 2060
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

2061
    if (net->type == QEMUD_NET_NETWORK) {
2062
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
2063
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2064 2065
                             _("Network '%s' not found"),
                             net->dst.network.name);
2066 2067
            goto error;
        } else if (network->bridge[0] == '\0') {
2068
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2069 2070
                             _("Network '%s' not active"),
                             net->dst.network.name);
2071 2072 2073 2074
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
2075
            STREQLEN(net->dst.network.ifname, "vnet", 4) ||
2076 2077 2078 2079 2080 2081 2082
            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' ||
2083
            STREQLEN(net->dst.bridge.ifname, "vnet", 4) ||
2084 2085 2086 2087 2088
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
2089
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2090
                         _("Network type %d is not supported"), net->type);
2091 2092 2093
        goto error;
    }

2094
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
2095
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2096 2097
                         _("cannot initialize bridge support: %s"),
                         strerror(err));
2098 2099 2100
        goto error;
    }

2101
    if ((err = brAddTap(driver->brctl, brname,
2102
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
2103
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2104
                     _("Failed to add tap interface '%s' to bridge '%s' : %s"),
2105
                         ifname, brname, strerror(err));
2106 2107 2108
        goto error;
    }

2109 2110 2111
    snprintf(tapfdstr, sizeof(tapfdstr),
             "tap,fd=%d,script=,vlan=%d,ifname=%s",
             tapfd, vlan, ifname);
2112 2113 2114 2115

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

2116
    if (!(tapfds = realloc(vm->tapfds, sizeof(*tapfds) * (vm->ntapfds+2))))
2117 2118 2119 2120 2121 2122 2123 2124 2125
        goto no_memory;

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

    return retval;

 no_memory:
2126 2127
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for tapfds string"));
2128
 error:
2129
    free(retval);
2130 2131 2132 2133 2134
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
static int qemudBuildCommandLineChrDevStr(struct qemud_vm_chr_def *dev,
                                          char *buf,
                                          int buflen)
{
    switch (dev->srcType) {
    case QEMUD_CHR_SRC_TYPE_NULL:
        strncpy(buf, "null", buflen);
        buf[buflen-1] = '\0';
        break;

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

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

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

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

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

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

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

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

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

    return 0;
}

D
Daniel P. Berrange 已提交
2207 2208 2209 2210
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
2211 2212
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
2213
                          struct qemud_vm *vm,
2214 2215
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
2216 2217 2218
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
2219
    struct stat sb;
2220 2221
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
2222
    struct qemud_vm_input_def *input = vm->def->inputs;
D
Daniel Veillard 已提交
2223
    struct qemud_vm_sound_def *sound = vm->def->sounds;
2224 2225
    struct qemud_vm_chr_def *serial = vm->def->serials;
    struct qemud_vm_chr_def *parallel = vm->def->parallels;
2226 2227
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
2228

2229 2230 2231 2232 2233 2234
    /* 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,
2235 2236
                         _("Cannot find QEMU binary %s: %s"),
                         vm->def->os.binary,
2237
                         strerror(errno));
2238
        return -1;
2239 2240 2241 2242 2243 2244 2245 2246
    }

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

2248 2249
    uname(&ut);

D
Daniel P. Berrange 已提交
2250
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
2251 2252 2253 2254
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
2255
        ut.machine[1] = '6';
2256 2257 2258 2259 2260 2261

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

2267
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
2268
        2 + /* machine type */
2269
        disableKQEMU + /* Disable kqemu */
2270 2271
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
2272 2273
        1 + /* usb */
        2 * vm->def->ninputs + /* input devices */
D
Daniel Veillard 已提交
2274
        ((vm->def->nsounds > 0) ? 2 : 0) + /* sound */
2275 2276
        (vm->def->nserials > 0 ? (2 * vm->def->nserials) : 2) + /* character devices */
        (vm->def->nparallels > 0 ? (2 * vm->def->nparallels) : 2) + /* character devices */
D
Daniel P. Berrange 已提交
2277 2278 2279 2280
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
2281
        (vm->def->localtime ? 1 : 0) + /* localtime */
2282
        (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
2283
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
2284 2285 2286 2287 2288
        (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 :
2289 2290
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)) + /* graphics */
        (vm->migrateFrom[0] ? 3 : 0); /* migrateFrom */
D
Daniel P. Berrange 已提交
2291

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

2295
    if (!(*argv = malloc(sizeof(**argv) * (len+1))))
D
Daniel P. Berrange 已提交
2296
        goto no_memory;
2297
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
2298 2299 2300
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
2301
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
2302
        goto no_memory;
2303
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
2304
        if (!((*argv)[++n] = strdup("-no-kqemu")))
2305
            goto no_memory;
D
Daniel P. Berrange 已提交
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
    }
    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;

2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
    /*
     * 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 已提交
2328 2329 2330 2331 2332
    if (!((*argv)[++n] = strdup("-monitor")))
        goto no_memory;
    if (!((*argv)[++n] = strdup("pty")))
        goto no_memory;

2333 2334 2335 2336 2337
    if (vm->def->localtime) {
        if (!((*argv)[++n] = strdup("-localtime")))
            goto no_memory;
    }

2338
    if (vm->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
2339 2340 2341 2342 2343
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

2344
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
2345 2346
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
2347 2348
    }

2349 2350
    for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
        switch (vm->def->os.bootDevs[i]) {
D
Daniel P. Berrange 已提交
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
        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;
        }
    }
2368
    boot[vm->def->os.nBootDevs] = '\0';
D
Daniel P. Berrange 已提交
2369 2370 2371 2372 2373
    if (!((*argv)[++n] = strdup("-boot")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(boot)))
        goto no_memory;

2374
    if (vm->def->os.kernel[0]) {
D
Daniel P. Berrange 已提交
2375 2376
        if (!((*argv)[++n] = strdup("-kernel")))
            goto no_memory;
2377
        if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
D
Daniel P. Berrange 已提交
2378 2379
            goto no_memory;
    }
2380
    if (vm->def->os.initrd[0]) {
D
Daniel P. Berrange 已提交
2381 2382
        if (!((*argv)[++n] = strdup("-initrd")))
            goto no_memory;
2383
        if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
D
Daniel P. Berrange 已提交
2384 2385
            goto no_memory;
    }
2386
    if (vm->def->os.cmdline[0]) {
D
Daniel P. Berrange 已提交
2387 2388
        if (!((*argv)[++n] = strdup("-append")))
            goto no_memory;
2389
        if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
D
Daniel P. Berrange 已提交
2390 2391 2392 2393 2394 2395 2396
            goto no_memory;
    }

    while (disk) {
        char dev[NAME_MAX];
        char file[PATH_MAX];
        if (!strcmp(disk->dst, "hdc") &&
2397 2398 2399 2400 2401 2402 2403 2404 2405
            disk->device == QEMUD_DISK_CDROM) {
            if (disk->src[0])
                snprintf(dev, NAME_MAX, "-%s", "cdrom");
            else {
                /* Don't put anything on the cmdline for an empty cdrom*/
                disk = disk->next;
                continue;
            }
        } else
D
Daniel P. Berrange 已提交
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
            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 {
2423
        int vlan = 0;
D
Daniel P. Berrange 已提交
2424
        while (net) {
2425
            char nic[100];
2426

2427 2428
            if (snprintf(nic, sizeof(nic),
                         "nic,macaddr=%02x:%02x:%02x:%02x:%02x:%02x,vlan=%d%s%s",
2429 2430 2431
                         net->mac[0], net->mac[1],
                         net->mac[2], net->mac[3],
                         net->mac[4], net->mac[5],
2432 2433
                         vlan,
                         (net->model[0] ? ",model=" : ""), net->model) >= sizeof(nic))
2434
                goto error;
D
Daniel P. Berrange 已提交
2435 2436 2437 2438 2439

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

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

2444 2445 2446
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
2447
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
2448
                    goto error;
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503
                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;
                }
2504
            }
D
Daniel P. Berrange 已提交
2505 2506

            net = net->next;
2507
            vlan++;
D
Daniel P. Berrange 已提交
2508 2509 2510
        }
    }

2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
    if (!serial) {
        if (!((*argv)[++n] = strdup("-serial")))
            goto no_memory;
        if (!((*argv)[++n] = strdup("none")))
            goto no_memory;
    } else {
        while (serial) {
            char buf[4096];

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

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

            serial = serial->next;
        }
    }

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

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

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

            parallel = parallel->next;
        }
    }

2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565
    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;
    }

2566
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
2567
        char vncdisplay[PATH_MAX];
2568
        int ret;
D
Daniel P. Berrange 已提交
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583

        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",
2584
                           vm->def->vncListen,
D
Daniel P. Berrange 已提交
2585 2586 2587
                           vm->def->vncActivePort - 5900,
                           options);
        } else {
2588 2589
            ret = snprintf(vncdisplay, sizeof(vncdisplay), "%d",
                           vm->def->vncActivePort - 5900);
D
Daniel P. Berrange 已提交
2590
        }
2591
        if (ret < 0 || ret >= (int)sizeof(vncdisplay))
2592 2593
            goto error;

D
Daniel P. Berrange 已提交
2594 2595
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
2596
        if (!((*argv)[++n] = strdup(vncdisplay)))
D
Daniel P. Berrange 已提交
2597
            goto no_memory;
2598 2599 2600 2601 2602 2603
        if (vm->def->keymap) {
            if (!((*argv)[++n] = strdup("-k")))
                goto no_memory;
            if (!((*argv)[++n] = strdup(vm->def->keymap)))
                goto no_memory;
        }
2604
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
2605
        /* Nada - we added -nographic earlier in this function */
D
Daniel P. Berrange 已提交
2606 2607 2608 2609
    } else {
        /* SDL is the default. no args needed */
    }

D
Daniel Veillard 已提交
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635
    /* Add sound hardware */
    if (sound) {
        int size = 100;
        char *modstr = calloc(1, size+1);
        if (!modstr)
            goto no_memory;
        if (!((*argv)[++n] = strdup("-soundhw")))
            goto no_memory;

        while(sound && size > 0) {
            const char *model = qemudSoundModelToString(sound->model);
            if (!model) {
               qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                _("invalid sound model"));
               goto error;
            }
            strncat(modstr, model, size);
            size -= strlen(model);
            sound = sound->next;
            if (sound)
               strncat(modstr, ",", size--);
        }
        if (!((*argv)[++n] = modstr))
            goto no_memory;
    }

2636 2637 2638 2639 2640 2641 2642 2643 2644
    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 已提交
2645 2646 2647 2648 2649
    (*argv)[++n] = NULL;

    return 0;

 no_memory:
2650 2651
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to allocate space for argv string"));
2652 2653 2654 2655 2656 2657 2658 2659
 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 已提交
2660 2661
    if (argv) {
        for (i = 0 ; i < n ; i++)
2662 2663
            free((*argv)[i]);
        free(*argv);
D
Daniel P. Berrange 已提交
2664 2665 2666 2667 2668 2669
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
2670 2671
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
2672 2673
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
2674 2675 2676 2677
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

2678
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
2679 2680 2681 2682 2683
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
2684
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2685
                         _("cannot create config file %s: %s"),
2686
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2687 2688 2689 2690
        goto cleanup;
    }

    towrite = strlen(xml);
2691
    if (safewrite(fd, xml, towrite) < 0) {
2692
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2693
                         _("cannot write config file %s: %s"),
2694
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2695 2696 2697 2698
        goto cleanup;
    }

    if (close(fd) < 0) {
2699
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2700
                         _("cannot save config file %s: %s"),
2701
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715
        goto cleanup;
    }

    ret = 0;

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

    free(xml);

    return ret;
}

D
Daniel P. Berrange 已提交
2716 2717 2718 2719 2720 2721 2722
struct qemud_vm_device_def *
qemudParseVMDeviceDef(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
                      const char *xmlStr)
{
    xmlDocPtr xml;
    xmlNodePtr node;
2723
    struct qemud_vm_device_def *dev = calloc(1, sizeof(*dev));
D
Daniel P. Berrange 已提交
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733

    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) {
2734 2735
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("missing root element"));
D
Daniel P. Berrange 已提交
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746
        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);
D
Daniel Veillard 已提交
2747 2748 2749
    } else if (xmlStrEqual(node->name, BAD_CAST "sound")) {
        dev->type = QEMUD_DEVICE_SOUND;
        qemudParseSoundXML(conn, &(dev->data.sound), node);
D
Daniel P. Berrange 已提交
2750
    } else {
2751 2752
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR,
                         "%s", _("unknown device type"));
D
Daniel P. Berrange 已提交
2753 2754 2755 2756 2757 2758 2759 2760 2761
        goto error;
    }

    xmlFreeDoc(xml);

    return dev;

  error:
    if (xml) xmlFreeDoc(xml);
2762
    free(dev);
D
Daniel P. Berrange 已提交
2763 2764 2765
    return NULL;
}

2766
struct qemud_vm_def *
2767 2768
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
2769 2770
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
2771
    xmlDocPtr xml;
2772
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
2773

2774
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
2775 2776
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2777
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
2778 2779 2780
        return NULL;
    }

2781
    def = qemudParseXML(conn, driver, xml);
2782

D
Daniel P. Berrange 已提交
2783 2784
    xmlFreeDoc(xml);

2785 2786 2787 2788
    return def;
}

struct qemud_vm *
2789 2790
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
2791 2792 2793 2794
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

2795
    if ((vm = qemudFindVMByName(driver, def->name))) {
2796
        if (!qemudIsActiveVM(vm)) {
2797 2798 2799 2800 2801 2802 2803
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
2804 2805 2806
        /* Reset version, because the emulator path might have changed */
        vm->qemuVersion = 0;
        vm->qemuCmdFlags = 0;
2807
        return vm;
D
Daniel P. Berrange 已提交
2808 2809
    }

2810
    if (!(vm = calloc(1, sizeof(*vm)))) {
2811 2812
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for vm string"));
2813 2814
        return NULL;
    }
D
Daniel P. Berrange 已提交
2815

2816
    vm->stdin = -1;
2817 2818 2819 2820 2821
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
2822
    vm->state = VIR_DOMAIN_SHUTOFF;
2823
    vm->def = def;
2824
    vm->next = driver->vms;
2825

2826 2827
    driver->vms = vm;
    driver->ninactivevms++;
2828 2829 2830 2831 2832

    return vm;
}

void
2833
qemudRemoveInactiveVM(struct qemud_driver *driver,
2834 2835 2836 2837
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

2838
    curr = driver->vms;
2839 2840 2841
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
2842 2843
    }

2844 2845 2846 2847
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2848
            driver->vms = curr->next;
2849

2850
        driver->ninactivevms--;
2851 2852
    }

2853
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
2854 2855
}

2856
int
2857 2858
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
2859 2860 2861 2862 2863
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

2864
        if ((err = virFileMakePath(driver->configDir))) {
2865
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2866
                             _("cannot create config directory %s: %s"),
2867
                             driver->configDir, strerror(err));
2868 2869 2870
            return -1;
        }

2871 2872
        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             vm->configFile, PATH_MAX) < 0) {
2873
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2874
                             "%s", _("cannot construct config file path"));
2875 2876
            return -1;
        }
2877

2878 2879
        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             vm->autostartLink, PATH_MAX) < 0) {
2880
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2881
                             "%s", _("cannot construct autostart link path"));
2882 2883 2884
            vm->configFile[0] = '\0';
            return -1;
        }
2885 2886
    }

2887
    return qemudSaveConfig(conn, driver, vm, def);
2888
}
D
Daniel P. Berrange 已提交
2889

2890 2891
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
2892 2893
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
2894 2895 2896
    char *xml;
    int fd, ret = -1;
    int towrite;
2897
    int err;
2898

2899
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
2900 2901 2902
        return -1;
    }

2903
    if ((err = virFileMakePath(driver->networkConfigDir))) {
2904
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2905
                         _("cannot create config directory %s: %s"),
2906
                         driver->networkConfigDir, strerror(err));
2907 2908 2909 2910 2911 2912
        goto cleanup;
    }

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

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

    if (close(fd) < 0) {
2928
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2929
                         _("cannot save config file %s: %s"),
2930
                         network->configFile, strerror(errno));
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
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);
}
2959

2960
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
2961
                               struct qemud_network_def *def,
2962 2963 2964 2965 2966
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
2967 2968
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
2969 2970 2971 2972 2973 2974 2975
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
2976
            def->disableSTP = 1;
2977 2978 2979 2980 2981 2982 2983
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
2984
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
2985 2986 2987 2988 2989 2990 2991
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

2992 2993
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
2994
                                   struct qemud_network_def *def,
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
                                   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;
        }

3010
        if (!(range = calloc(1, sizeof(*range)))) {
3011 3012
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for range string"));
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025
            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';

3026 3027 3028
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
3029 3030 3031 3032
        } else {
            free(range);
        }

3033 3034
        xmlFree(start);
        xmlFree(end);
3035 3036 3037 3038 3039 3040

        cur = cur->next;
    }

    return 1;
}
3041

3042 3043
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
3044
                             struct qemud_network_def *def,
3045 3046
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
3047
    xmlNodePtr cur;
3048 3049 3050

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
3051 3052
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
3053 3054 3055 3056 3057 3058
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
3059 3060
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
3061 3062 3063 3064
        xmlFree(netmask);
        netmask = NULL;
    }

3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
    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);
    }

3080 3081 3082 3083
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
3084
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
3085 3086 3087 3088
            return 0;
        cur = cur->next;
    }

3089 3090 3091 3092
    return 1;
}


3093 3094
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
3095
                                                      xmlDocPtr xml) {
3096 3097
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
3098
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
3099 3100
    struct qemud_network_def *def;

3101
    if (!(def = calloc(1, sizeof(*def)))) {
3102 3103
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                   "%s", _("failed to allocate space for network_def string"));
3104 3105
        return NULL;
    }
3106 3107 3108 3109

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
3110 3111
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("incorrect root element"));
3112 3113 3114 3115 3116
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
3117 3118
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
               "%s", _("failed to allocate space for xmlXPathContext string"));
3119 3120 3121 3122 3123 3124 3125 3126
        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)) {
3127
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
3128 3129 3130
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
3131 3132
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("network name length too long"));
3133 3134
        goto error;
    }
3135
    strcpy(def->name, (const char *)obj->stringval);
3136 3137 3138 3139 3140 3141 3142
    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)) {
3143
        int err;
D
Daniel P. Berrange 已提交
3144
        if ((err = virUUIDGenerate(def->uuid))) {
3145
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3146
                             _("Failed to generate UUID: %s"), strerror(err));
3147 3148
            goto error;
        }
D
Daniel P. Berrange 已提交
3149
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
3150 3151
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("malformed uuid element"));
3152 3153 3154 3155
        goto error;
    }
    xmlXPathFreeObject(obj);

3156 3157 3158 3159
    /* 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)) {
3160
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
3161 3162 3163 3164 3165 3166 3167 3168 3169
            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)) {
3170
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
3171 3172 3173 3174 3175 3176
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
3177 3178 3179
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
3180 3181
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
3182
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3183
                             "%s", _("Forwarding requested, but no IPv4 address/netmask provided"));
3184 3185 3186
            goto error;
        }

3187
        def->forward = 1;
3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198

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

3199 3200 3201 3202 3203
        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)) {
3204
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3205
                                 _("forward device name '%s' is too long"),
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219
                                 (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);

3220 3221
    xmlXPathFreeContext(ctxt);

3222
    return def;
3223 3224 3225 3226

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
3227 3228
    xmlXPathFreeObject(obj);
    xmlXPathFreeObject(tmp);
3229
    xmlXPathFreeContext(ctxt);
3230 3231
    qemudFreeNetworkDef(def);
    return NULL;
3232 3233
}

3234
struct qemud_network_def *
3235 3236
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
3237 3238
                     const char *xmlStr,
                     const char *displayName) {
3239
    xmlDocPtr xml;
3240
    struct qemud_network_def *def;
3241

3242
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
3243 3244
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
3245
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
3246 3247 3248
        return NULL;
    }

3249
    def = qemudParseNetworkXML(conn, driver, xml);
3250

3251 3252
    xmlFreeDoc(xml);

3253 3254 3255 3256
    return def;
}

struct qemud_network *
3257 3258
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
3259 3260 3261
                      struct qemud_network_def *def) {
    struct qemud_network *network;

3262
    if ((network = qemudFindNetworkByName(driver, def->name))) {
3263
        if (!qemudIsActiveNetwork(network)) {
3264 3265 3266 3267 3268 3269 3270 3271
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

3272
        return network;
3273 3274
    }

3275
    if (!(network = calloc(1, sizeof(*network)))) {
3276 3277
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for network string"));
3278 3279
        return NULL;
    }
3280

3281
    network->def = def;
3282
    network->next = driver->networks;
3283

3284 3285
    driver->networks = network;
    driver->ninactivenetworks++;
3286 3287 3288 3289 3290

    return network;
}

void
3291
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
3292 3293 3294 3295
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

3296
    curr = driver->networks;
3297 3298 3299
    while (curr != network) {
        prev = curr;
        curr = curr->next;
3300 3301
    }

3302 3303 3304 3305
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
3306
            driver->networks = curr->next;
3307

3308
        driver->ninactivenetworks--;
3309 3310
    }

3311
    qemudFreeNetwork(network);
3312 3313
}

3314
int
3315 3316
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
3317 3318 3319 3320 3321 3322
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

3323
        if ((err = virFileMakePath(driver->networkConfigDir))) {
3324
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3325
                             _("cannot create config directory %s: %s"),
3326
                             driver->networkConfigDir, strerror(err));
3327 3328 3329
            return -1;
        }

3330 3331
        if (virFileBuildPath(driver->networkConfigDir, def->name, ".xml",
                             network->configFile, PATH_MAX) < 0) {
3332
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3333
                             "%s", _("cannot construct config file path"));
3334 3335
            return -1;
        }
3336

3337 3338
        if (virFileBuildPath(driver->networkAutostartDir, def->name, ".xml",
                             network->autostartLink, PATH_MAX) < 0) {
3339
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3340
                             "%s", _("cannot construct autostart link path"));
3341 3342 3343
            network->configFile[0] = '\0';
            return -1;
        }
3344 3345
    }

3346
    return qemudSaveNetworkConfig(conn, driver, network, def);
3347
}
3348

3349

3350
static struct qemud_vm *
3351
qemudLoadConfig(struct qemud_driver *driver,
3352 3353
                const char *file,
                const char *path,
3354 3355
                const char *xml,
                const char *autostartLink) {
3356 3357 3358
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

3359
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
3360
        virErrorPtr err = virGetLastError();
3361 3362 3363
        qemudLog(QEMUD_WARN, _("Error parsing QEMU guest config '%s' : %s"),
                 path, (err ? err->message :
                        _("BUG: unknown error - please report it\n")));
3364 3365 3366
        return NULL;
    }

3367
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
3368 3369 3370
        qemudLog(QEMUD_WARN,
                 _("QEMU guest config filename '%s'"
                   " does not match guest name '%s'"),
3371 3372 3373 3374 3375
                 path, def->name);
        qemudFreeVMDef(def);
        return NULL;
    }

3376
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
3377 3378 3379
        qemudLog(QEMUD_WARN,
                 _("Failed to load QEMU guest config '%s': out of memory"),
                 path);
3380 3381 3382 3383 3384 3385 3386
        qemudFreeVMDef(def);
        return NULL;
    }

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

3387 3388 3389
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

3390
    vm->autostart = virFileLinkPointsTo(vm->autostartLink, vm->configFile);
3391

3392 3393 3394 3395
    return vm;
}

static struct qemud_network *
3396
qemudLoadNetworkConfig(struct qemud_driver *driver,
3397 3398
                       const char *file,
                       const char *path,
3399 3400
                       const char *xml,
                       const char *autostartLink) {
3401 3402 3403
    struct qemud_network_def *def;
    struct qemud_network *network;

3404
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
3405
        virErrorPtr err = virGetLastError();
3406
        qemudLog(QEMUD_WARN, _("Error parsing network config '%s' : %s"),
3407
                 path, err->message);
3408 3409 3410
        return NULL;
    }

3411
    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
3412 3413 3414
        qemudLog(QEMUD_WARN,
                 _("Network config filename '%s'"
                   " does not match network name '%s'"),
3415 3416 3417 3418 3419
                 path, def->name);
        qemudFreeNetworkDef(def);
        return NULL;
    }

3420
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
3421 3422
        qemudLog(QEMUD_WARN,
                 _("Failed to load network config '%s': out of memory"), path);
3423 3424 3425 3426 3427 3428 3429
        qemudFreeNetworkDef(def);
        return NULL;
    }

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

3430 3431 3432
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

3433
    network->autostart = virFileLinkPointsTo(network->autostartLink, network->configFile);
3434

3435 3436
    return network;
}
D
Daniel P. Berrange 已提交
3437

3438
static
3439
int qemudScanConfigDir(struct qemud_driver *driver,
3440
                       const char *configDir,
3441
                       const char *autostartDir,
3442
                       int isGuest) {
D
Daniel P. Berrange 已提交
3443 3444 3445
    DIR *dir;
    struct dirent *entry;

3446
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
3447 3448
        if (errno == ENOENT)
            return 0;
3449
        qemudLog(QEMUD_ERR, _("Failed to open dir '%s': %s"),
3450
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
3451 3452 3453 3454
        return -1;
    }

    while ((entry = readdir(dir))) {
3455
        char *xml;
3456
        char path[PATH_MAX];
3457
        char autostartLink[PATH_MAX];
3458

D
Daniel P. Berrange 已提交
3459 3460 3461
        if (entry->d_name[0] == '.')
            continue;

3462
        if (!virFileHasSuffix(entry->d_name, ".xml"))
3463 3464
            continue;

3465
        if (virFileBuildPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
3466
            qemudLog(QEMUD_WARN, _("Config filename '%s/%s' is too long"),
3467 3468 3469 3470
                     configDir, entry->d_name);
            continue;
        }

3471 3472 3473
        if (virFileBuildPath(autostartDir, entry->d_name, NULL,
                             autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, _("Autostart link path '%s/%s' is too long"),
3474 3475 3476 3477
                     autostartDir, entry->d_name);
            continue;
        }

3478
        if (virFileReadAll(path, QEMUD_MAX_XML_LEN, &xml) < 0)
D
Daniel P. Berrange 已提交
3479 3480
            continue;

3481
        if (isGuest)
3482
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
3483
        else
3484
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
3485 3486

        free(xml);
D
Daniel P. Berrange 已提交
3487 3488 3489
    }

    closedir(dir);
3490

D
Daniel P. Berrange 已提交
3491 3492 3493
    return 0;
}

3494
/* Scan for all guest and network config files */
3495 3496
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
3497
        return -1;
3498

3499
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
3500 3501 3502
        return -1;

    return 0;
3503
}
D
Daniel P. Berrange 已提交
3504

3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529
static int qemudGenerateXMLChar(virBufferPtr buf,
                                const struct qemud_vm_chr_def *dev,
                                const char *type)
{
    const char *const types[] = {
        "null",
        "vc",
        "pty",
        "dev",
        "file",
        "pipe",
        "stdio",
        "udp",
        "tcp",
        "unix"
    };
    /*verify(ARRAY_CARDINALITY(types) == QEMUD_CHR_SRC_TYPE_LAST);*/

    if (dev->srcType < 0 || dev->srcType >= QEMUD_CHR_SRC_TYPE_LAST)
        return -1;

    /* Compat with legacy  <console tty='/dev/pts/5'/> syntax */
    if (STREQ(type, "console") &&
        dev->srcType == QEMUD_CHR_SRC_TYPE_PTY &&
        dev->srcData.file.path[0] != '\0') {
3530 3531 3532
        virBufferVSprintf(buf, "    <%s type='%s' tty='%s'>\n",
                          type, types[dev->srcType],
                          dev->srcData.file.path);
3533
    } else {
3534 3535
        virBufferVSprintf(buf, "    <%s type='%s'>\n",
                          type, types[dev->srcType]);
3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550
    }

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

    case QEMUD_CHR_SRC_TYPE_PTY:
    case QEMUD_CHR_SRC_TYPE_DEV:
    case QEMUD_CHR_SRC_TYPE_FILE:
    case QEMUD_CHR_SRC_TYPE_PIPE:
        if (dev->srcType != QEMUD_CHR_SRC_TYPE_PTY ||
            dev->srcData.file.path[0]) {
3551 3552
            virBufferVSprintf(buf, "      <source path='%s'/>\n",
                              dev->srcData.file.path);
3553 3554 3555 3556 3557 3558
        }
        break;

    case QEMUD_CHR_SRC_TYPE_UDP:
        if (dev->srcData.udp.bindService[0] != '\0' &&
            dev->srcData.udp.bindHost[0] != '\0') {
3559 3560 3561
            virBufferVSprintf(buf, "      <source mode='bind' host='%s' service='%s'/>\n",
                              dev->srcData.udp.bindHost,
                              dev->srcData.udp.bindService);
3562
        } else if (dev->srcData.udp.bindHost[0] !='\0') {
3563 3564
            virBufferVSprintf(buf, "      <source mode='bind' host='%s'/>\n",
                              dev->srcData.udp.bindHost);
3565
        } else if (dev->srcData.udp.bindService[0] != '\0') {
3566 3567
            virBufferVSprintf(buf, "      <source mode='bind' service='%s'/>\n",
                              dev->srcData.udp.bindService);
3568 3569 3570 3571
        }

        if (dev->srcData.udp.connectService[0] != '\0' &&
            dev->srcData.udp.connectHost[0] != '\0') {
3572 3573 3574
            virBufferVSprintf(buf, "      <source mode='connect' host='%s' service='%s'/>\n",
                              dev->srcData.udp.connectHost,
                              dev->srcData.udp.connectService);
3575
        } else if (dev->srcData.udp.connectHost[0] != '\0') {
3576 3577
            virBufferVSprintf(buf, "      <source mode='connect' host='%s'/>\n",
                              dev->srcData.udp.connectHost);
3578
        } else if (dev->srcData.udp.connectService[0] != '\0') {
3579 3580
            virBufferVSprintf(buf, "      <source mode='connect' service='%s'/>\n",
                              dev->srcData.udp.connectService);
3581 3582 3583 3584
        }
        break;

    case QEMUD_CHR_SRC_TYPE_TCP:
3585 3586 3587 3588 3589 3590 3591
        virBufferVSprintf(buf, "      <source mode='%s' host='%s' service='%s'/>\n",
                          dev->srcData.tcp.listen ? "bind" : "connect",
                          dev->srcData.tcp.host,
                          dev->srcData.tcp.service);
        virBufferVSprintf(buf, "      <protocol type='%s'/>\n",
                          dev->srcData.tcp.protocol == QEMUD_CHR_SRC_TCP_PROTOCOL_TELNET
                          ? "telnet" : "raw");
3592 3593 3594
        break;

    case QEMUD_CHR_SRC_TYPE_UNIX:
3595 3596 3597
        virBufferVSprintf(buf, "      <source mode='%s' path='%s'/>\n",
                          dev->srcData.nix.listen ? "bind" : "connect",
                          dev->srcData.nix.path);
3598 3599 3600
        break;
    }

3601 3602
    virBufferVSprintf(buf, "      <target port='%d'/>\n",
                      dev->dstPort);
3603

3604 3605
    virBufferVSprintf(buf, "    </%s>\n",
                      type);
3606 3607 3608 3609 3610

    return 0;
}


D
Daniel P. Berrange 已提交
3611
/* Generate an XML document describing the guest's configuration */
3612 3613
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
3614 3615 3616
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
3617
    virBuffer buf = VIR_BUFFER_INITIALIZER;
D
Daniel P. Berrange 已提交
3618
    unsigned char *uuid;
3619
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3620 3621 3622
    const struct qemud_vm_disk_def *disk;
    const struct qemud_vm_net_def *net;
    const struct qemud_vm_input_def *input;
D
Daniel Veillard 已提交
3623
    const struct qemud_vm_sound_def *sound;
3624
    const struct qemud_vm_chr_def *chr;
D
Daniel P. Berrange 已提交
3625 3626 3627
    const char *type = NULL;
    int n;

3628
    if (!(type = qemudVirtTypeToString(def->virtType))) {
3629 3630
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unexpected domain type %d"), def->virtType);
D
Daniel P. Berrange 已提交
3631 3632 3633
        goto cleanup;
    }

3634 3635 3636 3637
    if (qemudIsActiveVM(vm) && live)
        virBufferVSprintf(&buf, "<domain type='%s' id='%d'>\n", type, vm->id);
    else
        virBufferVSprintf(&buf, "<domain type='%s'>\n", type);
D
Daniel P. Berrange 已提交
3638

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

3641
    uuid = def->uuid;
3642
    virUUIDFormat(uuid, uuidstr);
3643
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
D
Daniel P. Berrange 已提交
3644

3645 3646 3647 3648
    virBufferVSprintf(&buf, "  <memory>%lu</memory>\n", def->maxmem);
    virBufferVSprintf(&buf, "  <currentMemory>%lu</currentMemory>\n", def->memory);
    virBufferVSprintf(&buf, "  <vcpu>%d</vcpu>\n", def->vcpus);
    virBufferAddLit(&buf, "  <os>\n");
D
Daniel P. Berrange 已提交
3649

3650 3651 3652 3653 3654
    if (def->virtType == QEMUD_VIRT_QEMU)
        virBufferVSprintf(&buf, "    <type arch='%s' machine='%s'>%s</type>\n",
                          def->os.arch, def->os.machine, def->os.type);
    else
        virBufferVSprintf(&buf, "    <type>%s</type>\n", def->os.type);
D
Daniel P. Berrange 已提交
3655

3656
    if (def->os.kernel[0])
3657
        virBufferVSprintf(&buf, "    <kernel>%s</kernel>\n", def->os.kernel);
3658
    if (def->os.initrd[0])
3659
        virBufferVSprintf(&buf, "    <initrd>%s</initrd>\n", def->os.initrd);
3660
    if (def->os.cmdline[0])
3661
        virBufferVSprintf(&buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline);
D
Daniel P. Berrange 已提交
3662

3663
    for (n = 0 ; n < def->os.nBootDevs ; n++) {
D
Daniel P. Berrange 已提交
3664
        const char *boottype = "hd";
3665
        switch (def->os.bootDevs[n]) {
D
Daniel P. Berrange 已提交
3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
        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:
3676
            boottype = "network";
D
Daniel P. Berrange 已提交
3677 3678
            break;
        }
3679
        virBufferVSprintf(&buf, "    <boot dev='%s'/>\n", boottype);
D
Daniel P. Berrange 已提交
3680 3681
    }

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

3684
    if (def->features & QEMUD_FEATURE_ACPI) {
3685 3686 3687
        virBufferAddLit(&buf, "  <features>\n");
        virBufferAddLit(&buf, "    <acpi/>\n");
        virBufferAddLit(&buf, "  </features>\n");
3688 3689
    }

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

3692 3693 3694 3695 3696
    virBufferAddLit(&buf, "  <on_poweroff>destroy</on_poweroff>\n");
    if (def->noReboot)
        virBufferAddLit(&buf, "  <on_reboot>destroy</on_reboot>\n");
    else
        virBufferAddLit(&buf, "  <on_reboot>restart</on_reboot>\n");
3697

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

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

3703
    disk = def->disks;
D
Daniel P. Berrange 已提交
3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
3718 3719
        virBufferVSprintf(&buf, "    <disk type='%s' device='%s'>\n",
                          types[disk->type], devices[disk->device]);
D
Daniel P. Berrange 已提交
3720

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

3725
        virBufferVSprintf(&buf, "      <target dev='%s'/>\n", disk->dst);
D
Daniel P. Berrange 已提交
3726 3727

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

3730
        virBufferAddLit(&buf, "    </disk>\n");
D
Daniel P. Berrange 已提交
3731 3732 3733 3734

        disk = disk->next;
    }

3735
    net = def->nets;
3736
    while (net) {
D
Daniel P. Berrange 已提交
3737 3738
        const char *types[] = {
            "user",
3739
            "ethernet",
D
Daniel P. Berrange 已提交
3740 3741 3742
            "server",
            "client",
            "mcast",
3743
            "network",
3744
            "bridge",
D
Daniel P. Berrange 已提交
3745
        };
3746 3747
        virBufferVSprintf(&buf, "    <interface type='%s'>\n",
                          types[net->type]);
D
Daniel P. Berrange 已提交
3748

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

3753 3754
        switch (net->type) {
        case QEMUD_NET_NETWORK:
3755
            virBufferVSprintf(&buf, "      <source network='%s'/>\n", net->dst.network.name);
3756

3757 3758
            if (net->dst.network.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.network.ifname);
3759
            break;
3760

3761
        case QEMUD_NET_ETHERNET:
3762 3763 3764 3765
            if (net->dst.ethernet.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname);
            if (net->dst.ethernet.script[0] != '\0')
                virBufferVSprintf(&buf, "      <script path='%s'/>\n", net->dst.ethernet.script);
3766 3767 3768
            break;

        case QEMUD_NET_BRIDGE:
3769 3770 3771
            virBufferVSprintf(&buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname);
            if (net->dst.bridge.ifname[0] != '\0')
                virBufferVSprintf(&buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname);
3772 3773 3774 3775 3776
            break;

        case QEMUD_NET_SERVER:
        case QEMUD_NET_CLIENT:
        case QEMUD_NET_MCAST:
3777 3778 3779 3780 3781 3782
            if (net->dst.socket.address[0] != '\0')
                virBufferVSprintf(&buf, "      <source address='%s' port='%d'/>\n",
                                  net->dst.socket.address, net->dst.socket.port);
            else
                virBufferVSprintf(&buf, "      <source port='%d'/>\n",
                                  net->dst.socket.port);
3783 3784
        }

3785 3786 3787 3788 3789
        if (net->model && net->model[0] != '\0') {
            virBufferVSprintf(&buf, "      <model type='%s'/>\n",
                              net->model);
        }

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

3792
        net = net->next;
D
Daniel P. Berrange 已提交
3793 3794
    }

3795 3796
    chr = def->serials;
    while (chr) {
3797
        if (qemudGenerateXMLChar(&buf, chr, "serial") < 0)
3798 3799 3800 3801 3802 3803 3804
            goto no_memory;

        chr = chr->next;
    }

    chr = def->parallels;
    while (chr) {
3805
        if (qemudGenerateXMLChar(&buf, chr, "parallel") < 0)
3806 3807 3808 3809 3810 3811 3812
            goto no_memory;

        chr = chr->next;
    }

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

3816 3817
    input = def->inputs;
    while (input) {
3818 3819 3820
        if (input->bus != QEMU_INPUT_BUS_PS2)
            virBufferVSprintf(&buf, "    <input type='%s' bus='usb'/>\n",
                              input->type == QEMU_INPUT_TYPE_MOUSE ? "mouse" : "tablet");
3821 3822 3823 3824
        input = input->next;
    }
    /* If graphics is enable, add implicit mouse */
    if (def->graphicsType != QEMUD_GRAPHICS_NONE)
3825
        virBufferAddLit(&buf, "    <input type='mouse' bus='ps2'/>\n");
3826

3827 3828
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
3829
        virBufferAddLit(&buf, "    <graphics type='vnc'");
3830

3831 3832 3833
        if (def->vncPort)
            virBufferVSprintf(&buf, " port='%d'",
                              qemudIsActiveVM(vm) && live ? def->vncActivePort : def->vncPort);
3834

3835 3836 3837
        if (def->vncListen[0])
            virBufferVSprintf(&buf, " listen='%s'",
                              def->vncListen);
3838

3839 3840 3841
        if (def->keymap)
            virBufferVSprintf(&buf, " keymap='%s'",
                              def->keymap);
3842

3843
        virBufferAddLit(&buf, "/>\n");
3844 3845 3846
        break;

    case QEMUD_GRAPHICS_SDL:
3847
        virBufferAddLit(&buf, "    <graphics type='sdl'/>\n");
3848 3849 3850 3851 3852 3853 3854
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

D
Daniel Veillard 已提交
3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866
    sound = def->sounds;
    while(sound) {
        const char *model = qemudSoundModelToString(sound->model);
        if (!model) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("invalid sound model"));
            goto cleanup;
        }
        virBufferVSprintf(&buf, "    <sound model='%s'/>\n", model);
        sound = sound->next;
    }

3867 3868
    virBufferAddLit(&buf, "  </devices>\n");
    virBufferAddLit(&buf, "</domain>\n");
D
Daniel P. Berrange 已提交
3869

3870
    if (virBufferError(&buf))
D
Daniel P. Berrange 已提交
3871 3872
        goto no_memory;

3873
    return virBufferContentAndReset(&buf);
D
Daniel P. Berrange 已提交
3874 3875

 no_memory:
3876 3877
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
D
Daniel P. Berrange 已提交
3878
 cleanup:
3879
    free(virBufferContentAndReset(&buf));
D
Daniel P. Berrange 已提交
3880 3881 3882 3883
    return NULL;
}


3884 3885
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
3886
                              struct qemud_network *network,
3887
                              struct qemud_network_def *def) {
3888
    virBuffer buf = VIR_BUFFER_INITIALIZER;
3889
    unsigned char *uuid;
3890
    char uuidstr[VIR_UUID_STRING_BUFLEN];
3891

3892
    virBufferAddLit(&buf, "<network>\n");
3893

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

3896
    uuid = def->uuid;
3897
    virUUIDFormat(uuid, uuidstr);
3898
    virBufferVSprintf(&buf, "  <uuid>%s</uuid>\n", uuidstr);
3899

3900 3901
    if (def->forward) {
        if (def->forwardDev[0]) {
3902
            virBufferVSprintf(&buf, "  <forward dev='%s' mode='%s'/>\n",
3903
                              def->forwardDev, (def->forwardMode == QEMUD_NET_FORWARD_ROUTE ? "route" : "nat"));
3904
        } else {
3905
            virBufferVSprintf(&buf, "  <forward mode='%s'/>\n", (def->forwardMode == QEMUD_NET_FORWARD_ROUTE ? "route" : "nat"));
3906 3907 3908
        }
    }

3909
    virBufferAddLit(&buf, "  <bridge");
3910
    if (qemudIsActiveNetwork(network)) {
3911
        virBufferVSprintf(&buf, " name='%s'", network->bridge);
3912
    } else if (def->bridge[0]) {
3913
        virBufferVSprintf(&buf, " name='%s'", def->bridge);
3914
    }
3915 3916 3917
    virBufferVSprintf(&buf, " stp='%s' forwardDelay='%d' />\n",
                      def->disableSTP ? "off" : "on",
                      def->forwardDelay);
3918

3919
    if (def->ipAddress[0] || def->netmask[0]) {
3920
        virBufferAddLit(&buf, "  <ip");
3921

3922 3923
        if (def->ipAddress[0])
            virBufferVSprintf(&buf, " address='%s'", def->ipAddress);
3924

3925 3926
        if (def->netmask[0])
            virBufferVSprintf(&buf, " netmask='%s'", def->netmask);
3927

3928
        virBufferAddLit(&buf, ">\n");
3929

3930 3931
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
3932
            virBufferAddLit(&buf, "    <dhcp>\n");
3933
            while (range) {
3934 3935
                virBufferVSprintf(&buf, "      <range start='%s' end='%s' />\n",
                                  range->start, range->end);
3936 3937
                range = range->next;
            }
3938
            virBufferAddLit(&buf, "    </dhcp>\n");
3939 3940
        }

3941
        virBufferAddLit(&buf, "  </ip>\n");
D
Daniel P. Berrange 已提交
3942 3943
    }

3944 3945 3946
    virBufferAddLit(&buf, "</network>\n");

    if (virBufferError(&buf))
3947 3948
        goto no_memory;

3949
    return virBufferContentAndReset(&buf);
3950 3951

 no_memory:
3952 3953
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                     "%s", _("failed to generate XML: out of memory"));
3954
    free(virBufferContentAndReset(&buf));
3955 3956 3957 3958
    return NULL;
}


3959 3960
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
3961 3962 3963
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
3964 3965
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("no config file for %s"), name);
D
Daniel P. Berrange 已提交
3966 3967 3968
        return -1;
    }

3969
    if (unlink(configFile) < 0) {
3970 3971
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("cannot remove config for %s"), name);
3972 3973
        return -1;
    }
3974

D
Daniel P. Berrange 已提交
3975 3976 3977
    return 0;
}

3978
#endif /* WITH_QEMU */