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

24 25
#include <config.h>

D
Daniel P. Berrange 已提交
26 27 28 29 30 31 32 33
#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>
34
#include <sys/wait.h>
35
#include <arpa/inet.h>
36
#include <sys/utsname.h>
D
Daniel P. Berrange 已提交
37 38 39 40 41 42 43 44

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

#include <libvirt/virterror.h>

45
#include "qemu_conf.h"
46
#include "uuid.h"
47
#include "buf.h"
48

49 50
#define qemudLog(level, msg...) fprintf(stderr, msg)

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

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

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
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) {
        if (!memcmp(vm->def->uuid, uuid, QEMUD_UUID_RAW_LEN))
            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) {
        if (!memcmp(network->def->uuid, uuid, QEMUD_UUID_RAW_LEN))
            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;
}

133

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
/* 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;

    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);
    }
149
    free(def);
150 151 152 153 154 155 156 157
}

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

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
/* Build up a fully qualfiied path for a config file to be
 * associated with a persistent guest or network */
static int
qemudMakeConfigPath(const char *configDir,
                    const char *name,
                    const char *ext,
                    char *buf,
                    unsigned int buflen) {
    if ((strlen(configDir) + 1 + strlen(name) + (ext ? strlen(ext) : 0) + 1) > buflen)
        return -1;

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

178
int
179 180 181 182 183 184
qemudEnsureDir(const char *path)
{
    struct stat st;
    char parent[PATH_MAX];
    char *p;
    int err;
185

186 187
    if (stat(path, &st) >= 0)
        return 0;
188

189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    strncpy(parent, path, PATH_MAX);
    parent[PATH_MAX - 1] = '\0';

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

    if (p == parent)
        return EPERM;

    *p = '\0';

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

    if (mkdir(path, 0777) < 0 && errno != EEXIST)
        return errno;
205 206 207 208

    return 0;
}

D
Daniel P. Berrange 已提交
209 210 211
/* The list of possible machine types for various architectures,
   as supported by QEMU - taken from 'qemu -M ?' for each arch */
static const char *arch_info_x86_machines[] = {
212
    "pc", "isapc", NULL
D
Daniel P. Berrange 已提交
213 214
};
static const char *arch_info_mips_machines[] = {
215
    "mips", NULL
D
Daniel P. Berrange 已提交
216 217
};
static const char *arch_info_sparc_machines[] = {
218
    "sun4m", NULL
D
Daniel P. Berrange 已提交
219 220
};
static const char *arch_info_ppc_machines[] = {
221
    "g3bw", "mac99", "prep", NULL
D
Daniel P. Berrange 已提交
222 223 224
};

/* The archicture tables for supported QEMU archs */
225 226 227 228 229 230 231 232 233 234
struct qemu_arch_info qemudArchs[] = { 
    /* i686 must be in position 0 */
    {  "i686", 32, arch_info_x86_machines, "qemu" },
    /* x86_64 must be in position 1 */
    {  "x86_64", 64, arch_info_x86_machines, "qemu-system-x86_64" },
    {  "mips", 32, arch_info_mips_machines, "qemu-system-mips" },
    {  "mipsel", 32, arch_info_mips_machines, "qemu-system-mipsel" },
    {  "sparc", 32, arch_info_sparc_machines, "qemu-system-sparc" },
    {  "ppc", 32, arch_info_ppc_machines, "qemu-system-ppc" },
    { NULL, -1, NULL, NULL }
D
Daniel P. Berrange 已提交
235 236 237 238
};

/* Return the default architecture if none is explicitly requested*/
static const char *qemudDefaultArch(void) {
239
    return qemudArchs[0].arch;
D
Daniel P. Berrange 已提交
240 241 242 243 244 245
}

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

246 247 248
    for (i = 0; qemudArchs[i].arch; i++) {
        if (!strcmp(qemudArchs[i].arch, arch)) {
            return qemudArchs[i].machines[0];
D
Daniel P. Berrange 已提交
249 250 251 252 253 254 255 256 257 258
        }
    }

    return NULL;
}

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

259 260 261
    for (i = 0 ; qemudArchs[i].arch; i++) {
        if (!strcmp(qemudArchs[i].arch, arch)) {
            return qemudArchs[i].binary;
D
Daniel P. Berrange 已提交
262 263 264 265 266 267 268
        }
    }

    return NULL;
}

/* Find the fully qualified path to the binary for an architecture */
269 270
static char *qemudLocateBinaryForArch(virConnectPtr conn,
                                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
D
Daniel P. Berrange 已提交
271 272 273 274 275 276 277 278 279 280
                                      int virtType, const char *arch) {
    const char *name;
    char *path;

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

    if (!name) {
281
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot determin binary for architecture %s", arch);
D
Daniel P. Berrange 已提交
282 283 284 285 286 287
        return NULL;
    }

    /* XXX lame. should actually use $PATH ... */
    path = malloc(strlen(name) + strlen("/usr/bin/") + 1);
    if (!path) {
288
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "path");
D
Daniel P. Berrange 已提交
289 290 291 292 293 294 295
        return NULL;
    }
    strcpy(path, "/usr/bin/");
    strcat(path, name);
    return path;
}

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330

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 已提交
331
        char help[8192]; /* Ought to be enough to hold QEMU help screen */
332
        int got = 0, ret = -1;
333 334 335 336 337
        int major, minor, micro;

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

D
Daniel P. Berrange 已提交
338 339 340 341 342 343 344 345 346 347
        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;
348 349 350 351 352 353 354 355 356 357
        }
        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 已提交
358 359
        if (strstr(help, "-no-reboot"))
            *flags |= QEMUD_CMD_FLAG_NO_REBOOT;
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        if (*version >= 9000)
            *flags |= QEMUD_CMD_FLAG_VNC_COLON;
        ret = 0;

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

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

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

        return ret;
    }
}

390 391
int qemudExtractVersion(virConnectPtr conn,
                        struct qemud_driver *driver) {
392
    char *binary = NULL;
393
    struct stat sb;
394

395
    if (driver->qemuVersion > 0)
396 397
        return 0;

398
    if (!(binary = qemudLocateBinaryForArch(conn, driver, QEMUD_VIRT_QEMU, "i686")))
399 400
        return -1;

401
    if (stat(binary, &sb) < 0) {
402
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
403 404 405 406 407 408
                         "Cannot find QEMU binary %s: %s", binary,
                         strerror(errno));
        free(binary);
        return -1;
    }

409
    if (qemudExtractVersionInfo(binary, &driver->qemuVersion, &driver->qemuCmdFlags) < 0) {
410 411 412 413 414 415 416 417 418
        free(binary);
        return -1;
    }

    free(binary);
    return 0;
}


D
Daniel P. Berrange 已提交
419
/* Parse the XML definition for a disk */
420 421
static struct qemud_vm_disk_def *qemudParseDiskXML(virConnectPtr conn,
                                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
D
Daniel P. Berrange 已提交
422 423 424 425 426 427 428 429 430 431
                                                   xmlNodePtr node) {
    struct qemud_vm_disk_def *disk = calloc(1, sizeof(struct qemud_vm_disk_def));
    xmlNodePtr cur;
    xmlChar *device = NULL;
    xmlChar *source = NULL;
    xmlChar *target = NULL;
    xmlChar *type = NULL;
    int typ = 0;

    if (!disk) {
432
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "disk");
D
Daniel P. Berrange 已提交
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 465 466 467 468 469 470 471
        return NULL;
    }

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

    device = xmlGetProp(node, BAD_CAST "device");
  
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE) {
            if ((source == NULL) &&
                (xmlStrEqual(cur->name, BAD_CAST "source"))) {
	
                if (typ == QEMUD_DISK_FILE)
                    source = xmlGetProp(cur, BAD_CAST "file");
                else
                    source = xmlGetProp(cur, BAD_CAST "dev");
            } else if ((target == NULL) &&
                       (xmlStrEqual(cur->name, BAD_CAST "target"))) {
                target = xmlGetProp(cur, BAD_CAST "dev");
            } else if (xmlStrEqual(cur->name, BAD_CAST "readonly")) {
                disk->readonly = 1;
            }
        }
        cur = cur->next;
    }

    if (source == NULL) {
472
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SOURCE, target ? "%s" : NULL, target);
D
Daniel P. Berrange 已提交
473 474 475
        goto error;
    }
    if (target == NULL) {
476
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_TARGET, source ? "%s" : NULL, source);
D
Daniel P. Berrange 已提交
477 478 479 480 481 482 483
        goto error;
    }

    if (device &&
        !strcmp((const char *)device, "floppy") &&
        strcmp((const char *)target, "fda") &&
        strcmp((const char *)target, "fdb")) {
484
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid floppy device name: %s", target);
D
Daniel P. Berrange 已提交
485 486 487 488 489 490
        goto error;
    }
  
    if (device &&
        !strcmp((const char *)device, "cdrom") &&
        strcmp((const char *)target, "hdc")) {
491
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid cdrom device name: %s", target);
D
Daniel P. Berrange 已提交
492 493 494 495 496 497 498 499 500 501 502 503
        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")) {
504
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid harddisk device name: %s", target);
D
Daniel P. Berrange 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        goto error;
    }

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

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

    if (!device)
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "disk"))
        disk->device = QEMUD_DISK_DISK;
    else if (!strcmp((const char *)device, "cdrom"))
        disk->device = QEMUD_DISK_CDROM;
    else if (!strcmp((const char *)device, "floppy"))
        disk->device = QEMUD_DISK_FLOPPY;
    else {
524
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Invalid device type: %s", device);
D
Daniel P. Berrange 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
        goto error;
    }

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

    return disk;

 error:
    if (type)
        xmlFree(type);
    if (target)
        xmlFree(target);
    if (source)
        xmlFree(source);
    if (device)
        xmlFree(device);
    free(disk);
    return NULL;
}

547 548 549 550 551 552 553 554 555
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 已提交
556 557

/* Parse the XML definition for a network interface */
558 559
static struct qemud_vm_net_def *qemudParseInterfaceXML(virConnectPtr conn,
                                                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
D
Daniel P. Berrange 已提交
560 561 562 563 564
                                                       xmlNodePtr node) {
    struct qemud_vm_net_def *net = calloc(1, sizeof(struct qemud_vm_net_def));
    xmlNodePtr cur;
    xmlChar *macaddr = NULL;
    xmlChar *type = NULL;
565
    xmlChar *network = NULL;
566 567 568 569 570
    xmlChar *bridge = NULL;
    xmlChar *ifname = NULL;
    xmlChar *script = NULL;
    xmlChar *address = NULL;
    xmlChar *port = NULL;
D
Daniel P. Berrange 已提交
571 572

    if (!net) {
573
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "net");
D
Daniel P. Berrange 已提交
574 575 576 577 578 579 580 581 582
        return NULL;
    }

    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;
583 584
        else if (xmlStrEqual(type, BAD_CAST "ethernet"))
            net->type = QEMUD_NET_ETHERNET;
D
Daniel P. Berrange 已提交
585 586 587 588 589 590
        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;
591 592
        else if (xmlStrEqual(type, BAD_CAST "network"))
            net->type = QEMUD_NET_NETWORK;
593 594
        else if (xmlStrEqual(type, BAD_CAST "bridge"))
            net->type = QEMUD_NET_BRIDGE;
D
Daniel P. Berrange 已提交
595 596 597 598 599 600 601 602 603 604 605 606
        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");
607 608 609 610
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_NETWORK) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                network = xmlGetProp(cur, BAD_CAST "network");
611 612 613
            } else if ((network == NULL) &&
                       (net->type == QEMUD_NET_BRIDGE) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
614
                bridge = xmlGetProp(cur, BAD_CAST "bridge");
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
            } else if ((network == NULL) &&
                       ((net->type == QEMUD_NET_SERVER) ||
                        (net->type == QEMUD_NET_CLIENT) ||
                        (net->type == QEMUD_NET_MCAST)) &&
                       (xmlStrEqual(cur->name, BAD_CAST "source"))) {
                address = xmlGetProp(cur, BAD_CAST "address");
                port = xmlGetProp(cur, BAD_CAST "port");
            } else if ((ifname == NULL) &&
                       ((net->type == QEMUD_NET_NETWORK) ||
                        (net->type == QEMUD_NET_ETHERNET) ||
                        (net->type == QEMUD_NET_BRIDGE)) &&
                       xmlStrEqual(cur->name, BAD_CAST "target")) {
                ifname = xmlGetProp(cur, BAD_CAST "dev");
            } else if ((script == NULL) &&
                       (net->type == QEMUD_NET_ETHERNET) &&
                       xmlStrEqual(cur->name, BAD_CAST "script")) {
                script = xmlGetProp(cur, BAD_CAST "path");
D
Daniel P. Berrange 已提交
632 633 634 635 636 637
            }
        }
        cur = cur->next;
    }

    if (macaddr) {
638
        unsigned int mac[6];
D
Daniel P. Berrange 已提交
639
        sscanf((const char *)macaddr, "%02x:%02x:%02x:%02x:%02x:%02x",
640 641 642 643 644 645 646 647 648 649 650 651
               (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 已提交
652 653

        xmlFree(macaddr);
654 655 656
        macaddr = NULL;
    } else {
        qemudRandomMAC(net);
D
Daniel P. Berrange 已提交
657 658
    }

659 660 661 662
    if (net->type == QEMUD_NET_NETWORK) {
        int len;

        if (network == NULL) {
663
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
664 665
                             "No <source> 'network' attribute specified with <interface type='network'/>");
            goto error;
666
        } else if ((len = xmlStrlen(network)) >= (QEMUD_MAX_NAME_LEN-1)) {
667
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
668 669 670 671 672 673 674
                             "Network name '%s' too long", network);
            goto error;
        } else {
            strncpy(net->dst.network.name, (char *)network, len);
            net->dst.network.name[len] = '\0';
        }

675
        if (network) {
676
            xmlFree(network);
677 678 679 680 681
            network = NULL;
        }

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
682
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
683 684 685 686 687 688 689 690 691 692 693
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.network.ifname, (char *)ifname, len);
                net->dst.network.ifname[len] = '\0';
            }
            xmlFree(ifname);
            ifname = NULL;
        }
    } else if (net->type == QEMUD_NET_ETHERNET) {
        int len;
694

695 696
        if (script != NULL) {
            if ((len = xmlStrlen(script)) >= (PATH_MAX-1)) {
697
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
698 699 700 701 702 703 704 705 706 707 708
                                 "TAP script path '%s' is too long", script);
                goto error;
            } else {
                strncpy(net->dst.ethernet.script, (char *)script, len);
                net->dst.ethernet.script[len] = '\0';
            }
            xmlFree(script);
            script = NULL;
        }
        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
709
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
710
                                 "TAP interface name '%s' is too long", ifname);
711 712
                goto error;
            } else {
713 714
                strncpy(net->dst.ethernet.ifname, (char *)ifname, len);
                net->dst.ethernet.ifname[len] = '\0';
715
            }
716 717 718 719 720 721
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_BRIDGE) {
        int len;

        if (bridge == NULL) {
722
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
723 724 725
                             "No <source> 'dev' attribute specified with <interface type='bridge'/>");
            goto error;
        } else if ((len = xmlStrlen(bridge)) >= (BR_IFNAME_MAXLEN-1)) {
726
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
727 728 729 730 731
                             "TAP bridge path '%s' is too long", bridge);
            goto error;
        } else {
            strncpy(net->dst.bridge.brname, (char *)bridge, len);
            net->dst.bridge.brname[len] = '\0';
732
        }
733 734 735 736 737 738

        xmlFree(bridge);
        bridge = NULL;

        if (ifname != NULL) {
            if ((len = xmlStrlen(ifname)) >= (BR_IFNAME_MAXLEN-1)) {
739
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
                                 "TAP interface name '%s' is too long", ifname);
                goto error;
            } else {
                strncpy(net->dst.bridge.ifname, (char *)ifname, len);
                net->dst.bridge.ifname[len] = '\0';
            }
            xmlFree(ifname);
        }
    } else if (net->type == QEMUD_NET_CLIENT ||
               net->type == QEMUD_NET_SERVER ||
               net->type == QEMUD_NET_MCAST) {
        int len;
        char *ret;

        if (port == NULL) {
755
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
756 757 758 759 760
                             "No <source> 'port' attribute specified with socket interface");
            goto error;
        }
        if (!(net->dst.socket.port = strtol((char*)port, &ret, 10)) &&
            ret == (char*)port) {
761
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
762 763 764 765 766 767 768 769 770
                             "Cannot parse <source> 'port' attribute with socket interface");
            goto error;
        }
        xmlFree(port);
        port = NULL;

        if (address == NULL) {
            if (net->type == QEMUD_NET_CLIENT ||
                net->type == QEMUD_NET_MCAST) {
771
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
772 773 774 775
                                 "No <source> 'address' attribute specified with socket interface");
                goto error;
            }
        } else if ((len = xmlStrlen(address)) >= (BR_INET_ADDR_MAXLEN)) {
776
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
777 778 779 780 781 782 783 784 785 786
                             "IP address '%s' is too long", address);
            goto error;
        }
        if (address == NULL) {
            net->dst.socket.address[0] = '\0';
        } else {
            strncpy(net->dst.socket.address, (char*)address,len);
            net->dst.socket.address[len] = '\0';
        }
        xmlFree(address);
787 788
    }

D
Daniel P. Berrange 已提交
789
    return net;
790 791 792 793

 error:
    if (network)
        xmlFree(network);
794 795 796 797 798 799 800 801 802 803
    if (address)
        xmlFree(address);
    if (port)
        xmlFree(port);
    if (ifname)
        xmlFree(ifname);
    if (script)
        xmlFree(script);
    if (bridge)
        xmlFree(bridge);
804 805
    free(net);
    return NULL;
D
Daniel P. Berrange 已提交
806 807 808 809 810 811 812
}


/*
 * Parses a libvirt XML definition of a guest, and populates the
 * the qemud_vm struct with matching data about the guests config
 */
813 814
static struct qemud_vm_def *qemudParseXML(virConnectPtr conn,
                                          struct qemud_driver *driver,
815
                                          xmlDocPtr xml) {
D
Daniel P. Berrange 已提交
816 817 818 819 820 821
    xmlNodePtr root = NULL;
    xmlChar *prop = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    char *conv = NULL;
    int i;
822 823 824
    struct qemud_vm_def *def;

    if (!(def = calloc(1, sizeof(struct qemud_vm_def)))) {
825
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
826 827
        return NULL;
    }
D
Daniel P. Berrange 已提交
828 829 830 831

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "domain"))) {
832
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
D
Daniel P. Berrange 已提交
833 834 835 836 837
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
838
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
D
Daniel P. Berrange 已提交
839 840 841 842 843 844
        goto error;
    }


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

    if (!strcmp((char *)prop, "qemu"))
850
        def->virtType = QEMUD_VIRT_QEMU;
D
Daniel P. Berrange 已提交
851
    else if (!strcmp((char *)prop, "kqemu"))
852
        def->virtType = QEMUD_VIRT_KQEMU;
D
Daniel P. Berrange 已提交
853
    else if (!strcmp((char *)prop, "kvm"))
854
        def->virtType = QEMUD_VIRT_KVM;
D
Daniel P. Berrange 已提交
855
    else {
856
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "invalid domain type attribute");
D
Daniel P. Berrange 已提交
857 858 859 860 861 862 863 864 865 866
        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)) {
867
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
D
Daniel P. Berrange 已提交
868 869 870
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
871
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "domain name length too long");
D
Daniel P. Berrange 已提交
872 873
        goto error;
    }
874
    strcpy(def->name, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
875 876 877 878 879 880 881
    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)) {
882
        int err;
D
Daniel P. Berrange 已提交
883
        if ((err = virUUIDGenerate(def->uuid))) {
884
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
885 886 887
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
888
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
889
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
D
Daniel P. Berrange 已提交
890 891 892 893 894 895 896 897 898
        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)) {
899
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "missing memory element");
D
Daniel P. Berrange 已提交
900 901 902
        goto error;
    } else {
        conv = NULL;
903
        def->maxmem = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
904
        if (conv == (const char*)obj->stringval) {
905
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
906 907 908 909 910 911 912 913 914 915 916
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);


    /* Extract domain memory */
    obj = xmlXPathEval(BAD_CAST "string(/domain/currentMemory[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
917
        def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
918 919
    } else {
        conv = NULL;
920 921 922
        def->memory = strtoll((const char*)obj->stringval, &conv, 10);
        if (def->memory > def->maxmem)
            def->memory = def->maxmem;
D
Daniel P. Berrange 已提交
923
        if (conv == (const char*)obj->stringval) {
924
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed memory information");
D
Daniel P. Berrange 已提交
925 926 927 928 929 930 931 932 933 934
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);

    /* Extract domain vcpu info */
    obj = xmlXPathEval(BAD_CAST "string(/domain/vcpu[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
935
        def->vcpus = 1;
D
Daniel P. Berrange 已提交
936 937
    } else {
        conv = NULL;
938
        def->vcpus = strtoll((const char*)obj->stringval, &conv, 10);
D
Daniel P. Berrange 已提交
939
        if (conv == (const char*)obj->stringval) {
940
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed vcpu information");
D
Daniel P. Berrange 已提交
941 942 943 944 945 946 947 948 949 950
            goto error;
        }
    }
    if (obj)
        xmlXPathFreeObject(obj);

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

D
Daniel P. Berrange 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

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


D
Daniel P. Berrange 已提交
971 972 973 974
    /* 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)) {
975
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, NULL);
D
Daniel P. Berrange 已提交
976 977 978
        goto error;
    }
    if (strcmp((const char *)obj->stringval, "hvm")) {
979
        qemudReportError(conn, NULL, NULL, VIR_ERR_OS_TYPE, "%s", obj->stringval);
D
Daniel P. Berrange 已提交
980 981
        goto error;
    }
982
    strcpy(def->os.type, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
983 984 985 986 987 988 989 990
    xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1]/@arch)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
        const char *defaultArch = qemudDefaultArch();
        if (strlen(defaultArch) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
991
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
992 993
            goto error;
        }
994
        strcpy(def->os.arch, defaultArch);
D
Daniel P. Berrange 已提交
995 996
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_TYPE_MAX_LEN-1)) {
997
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
998 999
            goto error;
        }
1000
        strcpy(def->os.arch, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1001 1002 1003 1004 1005 1006 1007
    }
    if (obj)
        xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "string(/domain/os/type[1]/@machine)", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1008
        const char *defaultMachine = qemudDefaultMachineForArch(def->os.arch);
D
Daniel P. Berrange 已提交
1009
        if (strlen(defaultMachine) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1010
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "machine type too long");
D
Daniel P. Berrange 已提交
1011 1012
            goto error;
        }
1013
        strcpy(def->os.machine, defaultMachine);
D
Daniel P. Berrange 已提交
1014 1015
    } else {
        if (strlen((const char *)obj->stringval) >= (QEMUD_OS_MACHINE_MAX_LEN-1)) {
1016
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "architecture type too long");
D
Daniel P. Berrange 已提交
1017 1018
            goto error;
        }
1019
        strcpy(def->os.machine, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/kernel[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1029
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "kernel path too long");
D
Daniel P. Berrange 已提交
1030 1031
            goto error;
        }
1032
        strcpy(def->os.kernel, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1033 1034 1035 1036 1037 1038 1039 1040 1041
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/initrd[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1042
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "initrd path too long");
D
Daniel P. Berrange 已提交
1043 1044
            goto error;
        }
1045
        strcpy(def->os.initrd, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1046 1047 1048 1049 1050 1051 1052 1053 1054
    }
    if (obj)
        xmlXPathFreeObject(obj);


    obj = xmlXPathEval(BAD_CAST "string(/domain/os/cmdline[1])", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_STRING) &&
        (obj->stringval != NULL) && (obj->stringval[0] != 0)) {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1055
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "cmdline arguments too long");
D
Daniel P. Berrange 已提交
1056 1057
            goto error;
        }
1058
        strcpy(def->os.cmdline, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    }
    if (obj)
        xmlXPathFreeObject(obj);


    /* analysis of the disk devices */
    obj = xmlXPathEval(BAD_CAST "/domain/os/boot", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
        for (i = 0; i < obj->nodesetval->nodeNr && i < QEMUD_MAX_BOOT_DEVS ; i++) {
1069 1070
            if (!(prop = xmlGetProp(obj->nodesetval->nodeTab[i], BAD_CAST "dev")))
                continue;
D
Daniel P. Berrange 已提交
1071
            if (!strcmp((char *)prop, "hd")) {
1072
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1073
            } else if (!strcmp((char *)prop, "fd")) {
1074
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_FLOPPY;
D
Daniel P. Berrange 已提交
1075
            } else if (!strcmp((char *)prop, "cdrom")) {
1076
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_CDROM;
D
Daniel P. Berrange 已提交
1077
            } else if (!strcmp((char *)prop, "net")) {
1078
                def->os.bootDevs[def->os.nBootDevs++] = QEMUD_BOOT_NET;
D
Daniel P. Berrange 已提交
1079
            } else {
1080
                xmlFree(prop);
D
Daniel P. Berrange 已提交
1081 1082
                goto error;
            }
1083
            xmlFree(prop);
1084
            prop = NULL;
D
Daniel P. Berrange 已提交
1085 1086 1087
        }
    }
    xmlXPathFreeObject(obj);
1088 1089 1090
    if (def->os.nBootDevs == 0) {
        def->os.nBootDevs = 1;
        def->os.bootDevs[0] = QEMUD_BOOT_DISK;
D
Daniel P. Berrange 已提交
1091 1092 1093 1094 1095 1096
    }


    obj = xmlXPathEval(BAD_CAST "string(/domain/devices/emulator[1])", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_STRING) ||
        (obj->stringval == NULL) || (obj->stringval[0] == 0)) {
1097
        char *tmp = qemudLocateBinaryForArch(conn, driver, def->virtType, def->os.arch);
D
Daniel P. Berrange 已提交
1098 1099 1100
        if (!tmp) {
            goto error;
        }
1101
        strcpy(def->os.binary, tmp);
D
Daniel P. Berrange 已提交
1102 1103 1104
        free(tmp);
    } else {
        if (strlen((const char *)obj->stringval) >= (PATH_MAX-1)) {
1105
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "emulator path too long");
D
Daniel P. Berrange 已提交
1106 1107
            goto error;
        }
1108
        strcpy(def->os.binary, (const char *)obj->stringval);
D
Daniel P. Berrange 已提交
1109 1110 1111 1112 1113 1114 1115
    }
    if (obj)
        xmlXPathFreeObject(obj);

    obj = xmlXPathEval(BAD_CAST "/domain/devices/graphics", ctxt);
    if ((obj == NULL) || (obj->type != XPATH_NODESET) ||
        (obj->nodesetval == NULL) || (obj->nodesetval->nodeNr == 0)) {
1116
        def->graphicsType = QEMUD_GRAPHICS_NONE;
1117
    } else if ((prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "type"))) {
D
Daniel P. Berrange 已提交
1118
        if (!strcmp((char *)prop, "vnc")) {
1119
            def->graphicsType = QEMUD_GRAPHICS_VNC;
D
Daniel P. Berrange 已提交
1120 1121 1122
            prop = xmlGetProp(obj->nodesetval->nodeTab[0], BAD_CAST "port");
            if (prop) {
                conv = NULL;
1123
                def->vncPort = strtoll((const char*)prop, &conv, 10);
D
Daniel P. Berrange 已提交
1124
            } else {
1125
                def->vncPort = -1;
D
Daniel P. Berrange 已提交
1126 1127
            }
        } else if (!strcmp((char *)prop, "sdl")) {
1128
            def->graphicsType = QEMUD_GRAPHICS_SDL;
D
Daniel P. Berrange 已提交
1129
        } else {
1130
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "Unsupported graphics type %s", prop);
D
Daniel P. Berrange 已提交
1131 1132
            goto error;
        }
1133
        xmlFree(prop);
1134
        prop = NULL;
D
Daniel P. Berrange 已提交
1135
    }
1136
    xmlXPathFreeObject(obj);
D
Daniel P. Berrange 已提交
1137 1138 1139 1140 1141

    /* 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)) {
1142
        struct qemud_vm_disk_def *prev = NULL;
D
Daniel P. Berrange 已提交
1143 1144
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
            struct qemud_vm_disk_def *disk;
1145
            if (!(disk = qemudParseDiskXML(conn, driver, obj->nodesetval->nodeTab[i]))) {
D
Daniel P. Berrange 已提交
1146 1147
                goto error;
            }
1148
            def->ndisks++;
1149 1150 1151 1152 1153 1154 1155
            disk->next = NULL;
            if (i == 0) {
                def->disks = disk;
            } else {
                prev->next = disk;
            }
            prev = disk;
D
Daniel P. Berrange 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164
        }
    }
    xmlXPathFreeObject(obj);


    /* analysis of the network devices */
    obj = xmlXPathEval(BAD_CAST "/domain/devices/interface", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_NODESET) &&
        (obj->nodesetval != NULL) && (obj->nodesetval->nodeNr >= 0)) {
1165
        struct qemud_vm_net_def *prev = NULL;
D
Daniel P. Berrange 已提交
1166 1167
        for (i = 0; i < obj->nodesetval->nodeNr; i++) {
            struct qemud_vm_net_def *net;
1168
            if (!(net = qemudParseInterfaceXML(conn, driver, obj->nodesetval->nodeTab[i]))) {
D
Daniel P. Berrange 已提交
1169 1170
                goto error;
            }
1171
            def->nnets++;
1172 1173 1174 1175 1176 1177 1178
            net->next = NULL;
            if (i == 0) {
                def->nets = net;
            } else {
                prev->next = net;
            }
            prev = net;
D
Daniel P. Berrange 已提交
1179 1180 1181 1182 1183
        }
    }
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);

1184
    return def;
D
Daniel P. Berrange 已提交
1185 1186 1187 1188 1189 1190 1191 1192

 error:
    if (prop)
        free(prop);
    if (obj)
        xmlXPathFreeObject(obj);
    if (ctxt)
        xmlXPathFreeContext(ctxt);
1193 1194
    qemudFreeVMDef(def);
    return NULL;
D
Daniel P. Berrange 已提交
1195 1196 1197
}


1198
static char *
1199 1200
qemudNetworkIfaceConnect(virConnectPtr conn,
                         struct qemud_driver *driver,
1201
                         struct qemud_vm *vm,
1202 1203
                         struct qemud_vm_net_def *net,
                         int vlan)
1204
{
1205 1206 1207
    struct qemud_network *network = NULL;
    char *brname;
    char *ifname;
1208 1209 1210 1211 1212 1213
    char tapfdstr[4+3+32+7];
    char *retval = NULL;
    int err;
    int tapfd = -1;
    int *tapfds;

1214
    if (net->type == QEMUD_NET_NETWORK) {
1215
        if (!(network = qemudFindNetworkByName(driver, net->dst.network.name))) {
1216
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1217 1218 1219
                             "Network '%s' not found", net->dst.network.name);
            goto error;
        } else if (network->bridge[0] == '\0') {
1220
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
                             "Network '%s' not active", net->dst.network.name);
            goto error;
        }
        brname = network->bridge;
        if (net->dst.network.ifname[0] == '\0' ||
            strchr(net->dst.network.ifname, '%')) {
            strcpy(net->dst.network.ifname, "vnet%d");
        }
        ifname = net->dst.network.ifname;
    } else if (net->type == QEMUD_NET_BRIDGE) {
        brname = net->dst.bridge.brname;
        if (net->dst.bridge.ifname[0] == '\0' ||
            strchr(net->dst.bridge.ifname, '%')) {
            strcpy(net->dst.bridge.ifname, "vnet%d");
        }
        ifname = net->dst.bridge.ifname;
    } else {
1238
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1239
                         "Network type %d is not supported", net->type);
1240 1241 1242
        goto error;
    }

1243
    if (!driver->brctl && (err = brInit(&driver->brctl))) {
1244
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1245 1246 1247 1248
                         "cannot initialize bridge support: %s", strerror(err));
        goto error;
    }

1249
    if ((err = brAddTap(driver->brctl, brname,
1250
                        ifname, BR_IFNAME_MAXLEN, &tapfd))) {
1251
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1252
                         "Failed to add tap interface '%s' to bridge '%s' : %s",
1253
                         ifname, brname, strerror(err));
1254 1255 1256
        goto error;
    }

1257
    snprintf(tapfdstr, sizeof(tapfdstr), "tap,fd=%d,script=,vlan=%d", tapfd, vlan);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271

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

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

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

    return retval;

 no_memory:
1272
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "tapfds");
1273 1274 1275 1276 1277 1278 1279 1280
 error:
    if (retval)
        free(retval);
    if (tapfd != -1)
        close(tapfd);
    return NULL;
}

D
Daniel P. Berrange 已提交
1281 1282 1283 1284
/*
 * Constructs a argv suitable for launching qemu with config defined
 * for a given virtual machine.
 */
1285 1286
int qemudBuildCommandLine(virConnectPtr conn,
                          struct qemud_driver *driver,
D
Daniel P. Berrange 已提交
1287
                          struct qemud_vm *vm,
1288 1289
                          char ***argv) {
    int len, n = -1, i;
D
Daniel P. Berrange 已提交
1290 1291 1292
    char memory[50];
    char vcpus[50];
    char boot[QEMUD_MAX_BOOT_DEVS+1];
1293
    struct stat sb;
1294 1295
    struct qemud_vm_disk_def *disk = vm->def->disks;
    struct qemud_vm_net_def *net = vm->def->nets;
1296 1297
    struct utsname ut;
    int disableKQEMU = 0;
D
Daniel P. Berrange 已提交
1298

1299
    if (qemudExtractVersion(conn, driver) < 0)
1300 1301
        return -1;

1302 1303
    uname(&ut);

D
Daniel P. Berrange 已提交
1304
    /* Nasty hack make i?86 look like i686 to simplify next comparison */
1305 1306 1307 1308
    if (ut.machine[0] == 'i' &&
        ut.machine[2] == '8' &&
        ut.machine[3] == '6' &&
        !ut.machine[4])
D
Daniel P. Berrange 已提交
1309
        ut.machine[1] = '6';
1310 1311 1312 1313 1314 1315

    /* Need to explicitly disable KQEMU if
     * 1. Arch matches host arch
     * 2. Guest is 'qemu'
     * 3. The qemu binary has the -no-kqemu flag
     */
1316
    if ((driver->qemuCmdFlags & QEMUD_CMD_FLAG_KQEMU) &&
1317 1318 1319 1320 1321 1322 1323 1324 1325
        !strcmp(ut.machine, vm->def->os.arch) &&
        vm->def->virtType == QEMUD_VIRT_QEMU)
        disableKQEMU = 1;

    /* 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) {
1326
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1327 1328 1329 1330 1331
                         "Cannot find QEMU binary %s: %s", vm->def->os.binary,
                         strerror(errno));
        return -1;
    }

1332
    len = 1 + /* qemu */
D
Daniel P. Berrange 已提交
1333
        2 + /* machine type */
1334
        disableKQEMU + /* Disable kqemu */
1335 1336
        2 * vm->def->ndisks + /* disks*/
        (vm->def->nnets > 0 ? (4 * vm->def->nnets) : 2) + /* networks */
D
Daniel P. Berrange 已提交
1337 1338 1339 1340
        2 + /* memory*/
        2 + /* cpus */
        2 + /* boot device */
        2 + /* monitor */
1341
        (driver->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1342
         vm->def->noReboot ? 1 : 0) + /* no-reboot */
1343 1344 1345 1346 1347 1348
        (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 :
         (vm->def->graphicsType == QEMUD_GRAPHICS_SDL ? 0 : 1)); /* graphics */
D
Daniel P. Berrange 已提交
1349

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

1353
    if (!(*argv = malloc(sizeof(char *) * (len+1))))
D
Daniel P. Berrange 已提交
1354
        goto no_memory;
1355
    if (!((*argv)[++n] = strdup(vm->def->os.binary)))
D
Daniel P. Berrange 已提交
1356 1357 1358
        goto no_memory;
    if (!((*argv)[++n] = strdup("-M")))
        goto no_memory;
1359
    if (!((*argv)[++n] = strdup(vm->def->os.machine)))
D
Daniel P. Berrange 已提交
1360
        goto no_memory;
1361
    if (disableKQEMU) {
D
Daniel P. Berrange 已提交
1362
        if (!((*argv)[++n] = strdup("-no-kqemu")))
1363
            goto no_memory;
D
Daniel P. Berrange 已提交
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    }
    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;

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

1379
    if (driver->qemuCmdFlags & QEMUD_CMD_FLAG_NO_REBOOT &&
D
Daniel P. Berrange 已提交
1380 1381 1382 1383 1384
        vm->def->noReboot) {
        if (!((*argv)[++n] = strdup("-no-reboot")))
            goto no_memory;
    }

1385
    if (!(vm->def->features & QEMUD_FEATURE_ACPI)) {
1386 1387
        if (!((*argv)[++n] = strdup("-no-acpi")))
            goto no_memory;
D
Daniel P. Berrange 已提交
1388 1389
    }

1390 1391
    for (i = 0 ; i < vm->def->os.nBootDevs ; i++) {
        switch (vm->def->os.bootDevs[i]) {
D
Daniel P. Berrange 已提交
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
        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;
        }
    }
1409
    boot[vm->def->os.nBootDevs] = '\0';
D
Daniel P. Berrange 已提交
1410 1411 1412 1413 1414
    if (!((*argv)[++n] = strdup("-boot")))
        goto no_memory;
    if (!((*argv)[++n] = strdup(boot)))
        goto no_memory;

1415
    if (vm->def->os.kernel[0]) {
D
Daniel P. Berrange 已提交
1416 1417
        if (!((*argv)[++n] = strdup("-kernel")))
            goto no_memory;
1418
        if (!((*argv)[++n] = strdup(vm->def->os.kernel)))
D
Daniel P. Berrange 已提交
1419 1420
            goto no_memory;
    }
1421
    if (vm->def->os.initrd[0]) {
D
Daniel P. Berrange 已提交
1422 1423
        if (!((*argv)[++n] = strdup("-initrd")))
            goto no_memory;
1424
        if (!((*argv)[++n] = strdup(vm->def->os.initrd)))
D
Daniel P. Berrange 已提交
1425 1426
            goto no_memory;
    }
1427
    if (vm->def->os.cmdline[0]) {
D
Daniel P. Berrange 已提交
1428 1429
        if (!((*argv)[++n] = strdup("-append")))
            goto no_memory;
1430
        if (!((*argv)[++n] = strdup(vm->def->os.cmdline)))
D
Daniel P. Berrange 已提交
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
            goto no_memory;
    }

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

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

        disk = disk->next;
    }

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

1462 1463 1464 1465 1466 1467
            if (snprintf(nic, sizeof(nic), "nic,macaddr=%02x:%02x:%02x:%02x:%02x:%02x,vlan=%d",
                         net->mac[0], net->mac[1],
                         net->mac[2], net->mac[3],
                         net->mac[4], net->mac[5],
                         vlan) >= sizeof(nic))
                goto error;
D
Daniel P. Berrange 已提交
1468 1469 1470 1471 1472

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

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

1477 1478 1479
            switch (net->type) {
            case QEMUD_NET_NETWORK:
            case QEMUD_NET_BRIDGE:
1480
                if (!((*argv)[++n] = qemudNetworkIfaceConnect(conn, driver, vm, net, vlan)))
1481
                    goto error;
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536
                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;
                }
1537
            }
D
Daniel P. Berrange 已提交
1538 1539

            net = net->next;
1540
            vlan++;
D
Daniel P. Berrange 已提交
1541 1542 1543
        }
    }

1544
    if (vm->def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
1545
        char port[10];
1546 1547
        int ret;
        ret = snprintf(port, sizeof(port),
1548
                       ((driver->qemuCmdFlags & QEMUD_CMD_FLAG_VNC_COLON) ?
1549 1550 1551 1552 1553
                        ":%d" : "%d"),
                       vm->def->vncActivePort - 5900);
        if (ret < 0 || ret >= (int)sizeof(port))
            goto error;

D
Daniel P. Berrange 已提交
1554 1555 1556 1557
        if (!((*argv)[++n] = strdup("-vnc")))
            goto no_memory;
        if (!((*argv)[++n] = strdup(port)))
            goto no_memory;
1558
    } else if (vm->def->graphicsType == QEMUD_GRAPHICS_NONE) {
D
Daniel P. Berrange 已提交
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
        if (!((*argv)[++n] = strdup("-nographic")))
            goto no_memory;
    } else {
        /* SDL is the default. no args needed */
    }

    (*argv)[++n] = NULL;

    return 0;

 no_memory:
1570
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "argv");
1571 1572 1573 1574 1575 1576 1577 1578
 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 已提交
1579 1580
    if (argv) {
        for (i = 0 ; i < n ; i++)
1581 1582
            free((*argv)[i]);
        free(*argv);
D
Daniel P. Berrange 已提交
1583 1584 1585 1586 1587 1588
    }
    return -1;
}


/* Save a guest's config data into a persistent file */
1589 1590
static int qemudSaveConfig(virConnectPtr conn,
                           struct qemud_driver *driver,
1591 1592
                           struct qemud_vm *vm,
                           struct qemud_vm_def *def) {
D
Daniel P. Berrange 已提交
1593 1594 1595 1596
    char *xml;
    int fd = -1, ret = -1;
    int towrite;

1597
    if (!(xml = qemudGenerateXML(conn, driver, vm, def, 0)))
D
Daniel P. Berrange 已提交
1598 1599 1600 1601 1602
        return -1;

    if ((fd = open(vm->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1603
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1604 1605
                         "cannot create config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1606 1607 1608 1609 1610
        goto cleanup;
    }

    towrite = strlen(xml);
    if (write(fd, xml, towrite) != towrite) {
1611
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1612 1613
                         "cannot write config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1614 1615 1616 1617
        goto cleanup;
    }

    if (close(fd) < 0) {
1618
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1619 1620
                         "cannot save config file %s: %s",
                         vm->configFile, strerror(errno));
D
Daniel P. Berrange 已提交
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
        goto cleanup;
    }

    ret = 0;

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

    free(xml);

    return ret;
}

1635
struct qemud_vm_def *
1636 1637
qemudParseVMDef(virConnectPtr conn,
                struct qemud_driver *driver,
1638 1639
                const char *xmlStr,
                const char *displayName) {
D
Daniel P. Berrange 已提交
1640
    xmlDocPtr xml;
1641
    struct qemud_vm_def *def = NULL;
D
Daniel P. Berrange 已提交
1642

1643
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "domain.xml", NULL,
D
Daniel P. Berrange 已提交
1644 1645
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
1646
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
D
Daniel P. Berrange 已提交
1647 1648 1649
        return NULL;
    }

1650
    def = qemudParseXML(conn, driver, xml);
1651

D
Daniel P. Berrange 已提交
1652 1653
    xmlFreeDoc(xml);

1654 1655 1656 1657
    return def;
}

struct qemud_vm *
1658 1659
qemudAssignVMDef(virConnectPtr conn,
                 struct qemud_driver *driver,
1660 1661 1662 1663
                 struct qemud_vm_def *def)
{
    struct qemud_vm *vm = NULL;

1664
    if ((vm = qemudFindVMByName(driver, def->name))) {
1665
        if (!qemudIsActiveVM(vm)) {
1666 1667 1668 1669 1670 1671 1672
            qemudFreeVMDef(vm->def);
            vm->def = def;
        } else {
            if (vm->newDef)
                qemudFreeVMDef(vm->newDef);
            vm->newDef = def;
        }
D
Daniel P. Berrange 已提交
1673

1674
        return vm;
D
Daniel P. Berrange 已提交
1675 1676
    }

1677
    if (!(vm = calloc(1, sizeof(struct qemud_vm)))) {
1678
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "vm");
1679 1680
        return NULL;
    }
D
Daniel P. Berrange 已提交
1681

1682 1683 1684 1685 1686
    vm->stdout = -1;
    vm->stderr = -1;
    vm->monitor = -1;
    vm->pid = -1;
    vm->id = -1;
1687
    vm->state = VIR_DOMAIN_SHUTOFF;
1688
    vm->def = def;
1689
    vm->next = driver->vms;
1690

1691 1692
    driver->vms = vm;
    driver->ninactivevms++;
1693 1694 1695 1696 1697

    return vm;
}

void
1698
qemudRemoveInactiveVM(struct qemud_driver *driver,
1699 1700 1701 1702
                      struct qemud_vm *vm)
{
    struct qemud_vm *prev = NULL, *curr;

1703
    curr = driver->vms;
1704 1705 1706
    while (curr != vm) {
        prev = curr;
        curr = curr->next;
D
Daniel P. Berrange 已提交
1707 1708
    }

1709 1710 1711 1712
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
1713
            driver->vms = curr->next;
1714

1715
        driver->ninactivevms--;
1716 1717
    }

1718
    qemudFreeVM(vm);
D
Daniel P. Berrange 已提交
1719 1720
}

1721
int
1722 1723
qemudSaveVMDef(virConnectPtr conn,
               struct qemud_driver *driver,
1724 1725 1726 1727 1728
               struct qemud_vm *vm,
               struct qemud_vm_def *def) {
    if (vm->configFile[0] == '\0') {
        int err;

1729
        if ((err = qemudEnsureDir(driver->configDir))) {
1730
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1731
                             "cannot create config directory %s: %s",
1732
                             driver->configDir, strerror(err));
1733 1734 1735
            return -1;
        }

1736
        if (qemudMakeConfigPath(driver->configDir, def->name, ".xml",
1737
                                vm->configFile, PATH_MAX) < 0) {
1738
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1739 1740 1741
                             "cannot construct config file path");
            return -1;
        }
1742

1743
        if (qemudMakeConfigPath(driver->autostartDir, def->name, ".xml",
1744
                                vm->autostartLink, PATH_MAX) < 0) {
1745
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1746 1747 1748 1749
                             "cannot construct autostart link path");
            vm->configFile[0] = '\0';
            return -1;
        }
1750 1751
    }

1752
    return qemudSaveConfig(conn, driver, vm, def);
1753
}
D
Daniel P. Berrange 已提交
1754

1755 1756
static int qemudSaveNetworkConfig(virConnectPtr conn,
                                  struct qemud_driver *driver,
1757 1758
                                  struct qemud_network *network,
                                  struct qemud_network_def *def) {
1759 1760 1761
    char *xml;
    int fd, ret = -1;
    int towrite;
1762
    int err;
1763

1764
    if (!(xml = qemudGenerateNetworkXML(conn, driver, network, def))) {
1765 1766 1767
        return -1;
    }

1768
    if ((err = qemudEnsureDir(driver->networkConfigDir))) {
1769
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1770
                         "cannot create config directory %s: %s",
1771
                         driver->networkConfigDir, strerror(err));
1772 1773 1774 1775 1776 1777
        goto cleanup;
    }

    if ((fd = open(network->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1778
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1779 1780
                         "cannot create config file %s: %s",
                         network->configFile, strerror(errno));
1781 1782 1783 1784 1785
        goto cleanup;
    }

    towrite = strlen(xml);
    if (write(fd, xml, towrite) != towrite) {
1786
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1787
                         "cannot write config file %s: %s",
1788
                         network->configFile, strerror(errno));
1789 1790 1791 1792
        goto cleanup;
    }

    if (close(fd) < 0) {
1793
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1794
                         "cannot save config file %s: %s",
1795
                         network->configFile, strerror(errno));
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807
        goto cleanup;
    }

    ret = 0;

 cleanup:

    free(xml);

    return ret;
}

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
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);
}
1824

1825
static int qemudParseBridgeXML(struct qemud_driver *driver ATTRIBUTE_UNUSED,
1826
                               struct qemud_network_def *def,
1827 1828 1829 1830 1831
                               xmlNodePtr node) {
    xmlChar *name, *stp, *delay;

    name = xmlGetProp(node, BAD_CAST "name");
    if (name != NULL) {
1832 1833
        strncpy(def->bridge, (const char *)name, IF_NAMESIZE-1);
        def->bridge[IF_NAMESIZE-1] = '\0';
1834 1835 1836 1837 1838 1839 1840
        xmlFree(name);
        name = NULL;
    }

    stp = xmlGetProp(node, BAD_CAST "stp");
    if (stp != NULL) {
        if (xmlStrEqual(stp, BAD_CAST "off")) {
1841
            def->disableSTP = 1;
1842 1843 1844 1845 1846 1847 1848
        }
        xmlFree(stp);
        stp = NULL;
    }

    delay = xmlGetProp(node, BAD_CAST "delay");
    if (delay != NULL) {
1849
        def->forwardDelay = strtol((const char *)delay, NULL, 10);
1850 1851 1852 1853 1854 1855 1856
        xmlFree(delay);
        delay = NULL;
    }

    return 1;
}

1857 1858
static int qemudParseDhcpRangesXML(virConnectPtr conn,
                                   struct qemud_driver *driver ATTRIBUTE_UNUSED,
1859
                                   struct qemud_network_def *def,
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875
                                   xmlNodePtr node) {

    xmlNodePtr cur;

    cur = node->children;
    while (cur != NULL) {
        struct qemud_dhcp_range_def *range;
        xmlChar *start, *end;

        if (cur->type != XML_ELEMENT_NODE ||
            !xmlStrEqual(cur->name, BAD_CAST "range")) {
            cur = cur->next;
            continue;
        }

        if (!(range = calloc(1, sizeof(struct qemud_dhcp_range_def)))) {
1876
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "range");
1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
            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';

1890 1891 1892
            range->next = def->ranges;
            def->ranges = range;
            def->nranges++;
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
        } else {
            free(range);
        }

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

        cur = cur->next;
    }

    return 1;
}
1907

1908 1909
static int qemudParseInetXML(virConnectPtr conn,
                             struct qemud_driver *driver ATTRIBUTE_UNUSED,
1910
                             struct qemud_network_def *def,
1911 1912
                             xmlNodePtr node) {
    xmlChar *address, *netmask;
1913
    xmlNodePtr cur;
1914 1915 1916

    address = xmlGetProp(node, BAD_CAST "address");
    if (address != NULL) {
1917 1918
        strncpy(def->ipAddress, (const char *)address, BR_INET_ADDR_MAXLEN-1);
        def->ipAddress[BR_INET_ADDR_MAXLEN-1] = '\0';
1919 1920 1921 1922 1923 1924
        xmlFree(address);
        address = NULL;
    }

    netmask = xmlGetProp(node, BAD_CAST "netmask");
    if (netmask != NULL) {
1925 1926
        strncpy(def->netmask, (const char *)netmask, BR_INET_ADDR_MAXLEN-1);
        def->netmask[BR_INET_ADDR_MAXLEN-1] = '\0';
1927 1928 1929 1930
        xmlFree(netmask);
        netmask = NULL;
    }

1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    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);
    }

1946 1947 1948 1949
    cur = node->children;
    while (cur != NULL) {
        if (cur->type == XML_ELEMENT_NODE &&
            xmlStrEqual(cur->name, BAD_CAST "dhcp") &&
1950
            !qemudParseDhcpRangesXML(conn, driver, def, cur))
1951 1952 1953 1954
            return 0;
        cur = cur->next;
    }

1955 1956 1957 1958
    return 1;
}


1959 1960
static struct qemud_network_def *qemudParseNetworkXML(virConnectPtr conn,
                                                      struct qemud_driver *driver,
1961
                                                      xmlDocPtr xml) {
1962 1963
    xmlNodePtr root = NULL;
    xmlXPathContextPtr ctxt = NULL;
1964
    xmlXPathObjectPtr obj = NULL, tmp = NULL;
1965 1966 1967
    struct qemud_network_def *def;

    if (!(def = calloc(1, sizeof(struct qemud_network_def)))) {
1968
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network_def");
1969 1970
        return NULL;
    }
1971 1972 1973 1974

    /* Prepare parser / xpath context */
    root = xmlDocGetRootElement(xml);
    if ((root == NULL) || (!xmlStrEqual(root->name, BAD_CAST "network"))) {
1975
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "incorrect root element");
1976 1977 1978 1979 1980
        goto error;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1981
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xmlXPathContext");
1982 1983 1984 1985 1986 1987 1988 1989
        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)) {
1990
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_NAME, NULL);
1991 1992 1993
        goto error;
    }
    if (strlen((const char *)obj->stringval) >= (QEMUD_MAX_NAME_LEN-1)) {
1994
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "network name length too long");
1995 1996
        goto error;
    }
1997
    strcpy(def->name, (const char *)obj->stringval);
1998 1999 2000 2001 2002 2003 2004
    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)) {
2005
        int err;
D
Daniel P. Berrange 已提交
2006
        if ((err = virUUIDGenerate(def->uuid))) {
2007
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2008 2009 2010
                             "Failed to generate UUID: %s", strerror(err));
            goto error;
        }
D
Daniel P. Berrange 已提交
2011
    } else if (virUUIDParse((const char *)obj->stringval, def->uuid) < 0) {
2012
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s", "malformed uuid element");
2013 2014 2015 2016
        goto error;
    }
    xmlXPathFreeObject(obj);

2017 2018 2019 2020
    /* 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)) {
2021
        if (!qemudParseBridgeXML(driver, def, obj->nodesetval->nodeTab[0])) {
2022 2023 2024 2025 2026 2027 2028 2029 2030
            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)) {
2031
        if (!qemudParseInetXML(conn, driver, def, obj->nodesetval->nodeTab[0])) {
2032 2033 2034 2035 2036 2037
            goto error;
        }
    }
    xmlXPathFreeObject(obj);

    /* IPv4 forwarding setup */
2038 2039 2040
    obj = xmlXPathEval(BAD_CAST "count(/network/forward) > 0", ctxt);
    if ((obj != NULL) && (obj->type == XPATH_BOOLEAN) &&
        obj->boolval) {
2041 2042
        if (!def->ipAddress[0] ||
            !def->netmask[0]) {
2043
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2044 2045 2046 2047
                             "Forwarding requested, but no IPv4 address/netmask provided");
            goto error;
        }

2048 2049 2050 2051 2052 2053
        def->forward = 1;
        tmp = xmlXPathEval(BAD_CAST "string(/network/forward[1]/@dev)", ctxt);
        if ((tmp != NULL) && (tmp->type == XPATH_STRING) &&
            (tmp->stringval != NULL) && (tmp->stringval[0] != 0)) {
            int len;
            if ((len = xmlStrlen(tmp->stringval)) >= (BR_IFNAME_MAXLEN-1)) {
2054
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
                                 "forward device name '%s' is too long",
                                 (char*)tmp->stringval);
                goto error;
            }
            strcpy(def->forwardDev, (char*)tmp->stringval);
        } else {
            def->forwardDev[0] = '\0';
        }
        xmlXPathFreeObject(tmp);
        tmp = NULL;
    } else {
        def->forward = 0;
    }
    xmlXPathFreeObject(obj);

2070 2071
    xmlXPathFreeContext(ctxt);

2072
    return def;
2073 2074 2075 2076 2077 2078

 error:
    /* XXX free all the stuff in the qemud_network struct, or leave it upto
       the caller ? */
    if (obj)
        xmlXPathFreeObject(obj);
2079 2080
    if (tmp)
        xmlXPathFreeObject(tmp);
2081 2082
    if (ctxt)
        xmlXPathFreeContext(ctxt);
2083 2084
    qemudFreeNetworkDef(def);
    return NULL;
2085 2086
}

2087
struct qemud_network_def *
2088 2089
qemudParseNetworkDef(virConnectPtr conn,
                     struct qemud_driver *driver,
2090 2091
                     const char *xmlStr,
                     const char *displayName) {
2092
    xmlDocPtr xml;
2093
    struct qemud_network_def *def;
2094

2095
    if (!(xml = xmlReadDoc(BAD_CAST xmlStr, displayName ? displayName : "network.xml", NULL,
2096 2097
                           XML_PARSE_NOENT | XML_PARSE_NONET |
                           XML_PARSE_NOERROR | XML_PARSE_NOWARNING))) {
2098
        qemudReportError(conn, NULL, NULL, VIR_ERR_XML_ERROR, NULL);
2099 2100 2101
        return NULL;
    }

2102
    def = qemudParseNetworkXML(conn, driver, xml);
2103

2104 2105
    xmlFreeDoc(xml);

2106 2107 2108 2109
    return def;
}

struct qemud_network *
2110 2111
qemudAssignNetworkDef(virConnectPtr conn,
                      struct qemud_driver *driver,
2112 2113 2114
                      struct qemud_network_def *def) {
    struct qemud_network *network;

2115
    if ((network = qemudFindNetworkByName(driver, def->name))) {
2116
        if (!qemudIsActiveNetwork(network)) {
2117 2118 2119 2120 2121 2122 2123 2124
            qemudFreeNetworkDef(network->def);
            network->def = def;
        } else {
            if (network->newDef)
                qemudFreeNetworkDef(network->newDef);
            network->newDef = def;
        }

2125
        return network;
2126 2127
    }

2128
    if (!(network = calloc(1, sizeof(struct qemud_network)))) {
2129
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "network");
2130 2131
        return NULL;
    }
2132

2133
    network->def = def;
2134
    network->next = driver->networks;
2135

2136 2137
    driver->networks = network;
    driver->ninactivenetworks++;
2138 2139 2140 2141 2142

    return network;
}

void
2143
qemudRemoveInactiveNetwork(struct qemud_driver *driver,
2144 2145 2146 2147
                           struct qemud_network *network)
{
    struct qemud_network *prev = NULL, *curr;

2148
    curr = driver->networks;
2149 2150 2151
    while (curr != network) {
        prev = curr;
        curr = curr->next;
2152 2153
    }

2154 2155 2156 2157
    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
2158
            driver->networks = curr->next;
2159

2160
        driver->ninactivenetworks--;
2161 2162
    }

2163
    qemudFreeNetwork(network);
2164 2165
}

2166
int
2167 2168
qemudSaveNetworkDef(virConnectPtr conn,
                    struct qemud_driver *driver,
2169 2170 2171 2172 2173 2174
                    struct qemud_network *network,
                    struct qemud_network_def *def) {

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

2175
        if ((err = qemudEnsureDir(driver->networkConfigDir))) {
2176
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2177
                             "cannot create config directory %s: %s",
2178
                             driver->networkConfigDir, strerror(err));
2179 2180 2181
            return -1;
        }

2182
        if (qemudMakeConfigPath(driver->networkConfigDir, def->name, ".xml",
2183
                                network->configFile, PATH_MAX) < 0) {
2184
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2185 2186 2187
                             "cannot construct config file path");
            return -1;
        }
2188

2189
        if (qemudMakeConfigPath(driver->networkAutostartDir, def->name, ".xml",
2190
                                network->autostartLink, PATH_MAX) < 0) {
2191
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2192 2193 2194 2195
                             "cannot construct autostart link path");
            network->configFile[0] = '\0';
            return -1;
        }
2196 2197
    }

2198
    return qemudSaveNetworkConfig(conn, driver, network, def);
2199
}
2200

2201 2202 2203 2204
static int
qemudReadFile(const char *path,
              char *buf,
              int maxlen) {
D
Daniel P. Berrange 已提交
2205 2206
    FILE *fh;
    struct stat st;
2207
    int ret = 0;
D
Daniel P. Berrange 已提交
2208

2209 2210 2211 2212
    if (!(fh = fopen(path, "r"))) {
        qemudLog(QEMUD_WARN, "Failed to open file '%s': %s",
                 path, strerror(errno));
        goto error;
D
Daniel P. Berrange 已提交
2213 2214 2215
    }

    if (fstat(fileno(fh), &st) < 0) {
2216 2217 2218
        qemudLog(QEMUD_WARN, "Failed to stat file '%s': %s",
                 path, strerror(errno));
        goto error;
D
Daniel P. Berrange 已提交
2219 2220
    }

2221 2222 2223
    if (S_ISDIR(st.st_mode)) {
        qemudDebug("Ignoring directory '%s' - clearly not a config file", path);
        goto error;
D
Daniel P. Berrange 已提交
2224 2225
    }

2226 2227 2228
    if (st.st_size >= maxlen) {
        qemudLog(QEMUD_WARN, "File '%s' is too large", path);
        goto error;
D
Daniel P. Berrange 已提交
2229 2230
    }

2231 2232 2233 2234
    if ((ret = fread(buf, st.st_size, 1, fh)) != 1) {
        qemudLog(QEMUD_WARN, "Failed to read config file '%s': %s",
                 path, strerror(errno));
        goto error;
D
Daniel P. Berrange 已提交
2235
    }
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261

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

    ret = 1;

 error:
    if (fh)
        fclose(fh);

    return ret;
}

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

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

2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
static int
hasSuffix(const char *str,
          const char *suffix)
{
    int len = strlen(str);
    int suffixlen = strlen(suffix);

    if (len < suffixlen)
        return 0;

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

2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369
static int
checkLinkPointsTo(const char *checkLink,
                  const char *checkDest)
{
    char dest[PATH_MAX];
    char real[PATH_MAX];
    char checkReal[PATH_MAX];
    int n;
    int passed = 0;

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

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

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

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

    dest[n] = '\0';

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

        strncpy(dir, checkLink, PATH_MAX);
        dir[PATH_MAX] = '\0';

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

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

        *p = '\0';

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

        strncpy(dest, tmp, PATH_MAX);
        dest[PATH_MAX] = '\0';
    }

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

    if (!realpath(checkDest, checkReal)) {
        qemudLog(QEMUD_WARN, "Failed to expand path '%s' :%s",
                 checkDest, strerror(errno));
        strncpy(checkReal, checkDest, PATH_MAX);
        checkReal[PATH_MAX] = '\0';
    }

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

    passed = 1;

 failed:
    return passed;
}

2370
static struct qemud_vm *
2371
qemudLoadConfig(struct qemud_driver *driver,
2372 2373
                const char *file,
                const char *path,
2374 2375
                const char *xml,
                const char *autostartLink) {
2376 2377 2378
    struct qemud_vm_def *def;
    struct qemud_vm *vm;

2379
    if (!(def = qemudParseVMDef(NULL, driver, xml, file))) {
2380
        virErrorPtr err = virGetLastError();
2381
        qemudLog(QEMUD_WARN, "Error parsing QEMU guest config '%s' : %s",
2382
                 path, err->message);
2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
        return NULL;
    }

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

2393
    if (!(vm = qemudAssignVMDef(NULL, driver, def))) {
2394 2395 2396 2397 2398 2399 2400 2401
        qemudLog(QEMUD_WARN, "Failed to load QEMU guest config '%s': out of memory", path);
        qemudFreeVMDef(def);
        return NULL;
    }

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

2402 2403 2404 2405 2406
    strncpy(vm->autostartLink, autostartLink, PATH_MAX);
    vm->autostartLink[PATH_MAX-1] = '\0';

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

2407 2408 2409 2410
    return vm;
}

static struct qemud_network *
2411
qemudLoadNetworkConfig(struct qemud_driver *driver,
2412 2413
                       const char *file,
                       const char *path,
2414 2415
                       const char *xml,
                       const char *autostartLink) {
2416 2417 2418
    struct qemud_network_def *def;
    struct qemud_network *network;

2419
    if (!(def = qemudParseNetworkDef(NULL, driver, xml, file))) {
2420
        virErrorPtr err = virGetLastError();
2421
        qemudLog(QEMUD_WARN, "Error parsing network config '%s' : %s",
2422
                 path, err->message);
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
        return NULL;
    }

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

2433
    if (!(network = qemudAssignNetworkDef(NULL, driver, def))) {
2434 2435 2436 2437 2438 2439 2440 2441
        qemudLog(QEMUD_WARN, "Failed to load network config '%s': out of memory", path);
        qemudFreeNetworkDef(def);
        return NULL;
    }

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

2442 2443 2444 2445 2446
    strncpy(network->autostartLink, autostartLink, PATH_MAX);
    network->autostartLink[PATH_MAX-1] = '\0';

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

2447 2448
    return network;
}
D
Daniel P. Berrange 已提交
2449

2450
static
2451
int qemudScanConfigDir(struct qemud_driver *driver,
2452
                       const char *configDir,
2453
                       const char *autostartDir,
2454
                       int isGuest) {
D
Daniel P. Berrange 已提交
2455 2456 2457
    DIR *dir;
    struct dirent *entry;

2458
    if (!(dir = opendir(configDir))) {
D
Daniel P. Berrange 已提交
2459 2460
        if (errno == ENOENT)
            return 0;
2461 2462
        qemudLog(QEMUD_ERR, "Failed to open dir '%s': %s",
                 configDir, strerror(errno));
D
Daniel P. Berrange 已提交
2463 2464 2465 2466
        return -1;
    }

    while ((entry = readdir(dir))) {
2467 2468
        char xml[QEMUD_MAX_XML_LEN];
        char path[PATH_MAX];
2469
        char autostartLink[PATH_MAX];
2470

D
Daniel P. Berrange 已提交
2471 2472 2473
        if (entry->d_name[0] == '.')
            continue;

2474 2475 2476
        if (!hasSuffix(entry->d_name, ".xml"))
            continue;

2477 2478 2479 2480 2481 2482
        if (qemudMakeConfigPath(configDir, entry->d_name, NULL, path, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, "Config filename '%s/%s' is too long",
                     configDir, entry->d_name);
            continue;
        }

2483 2484 2485 2486 2487 2488
        if (qemudMakeConfigPath(autostartDir, entry->d_name, NULL, autostartLink, PATH_MAX) < 0) {
            qemudLog(QEMUD_WARN, "Autostart link path '%s/%s' is too long",
                     autostartDir, entry->d_name);
            continue;
        }

2489
        if (!qemudReadFile(path, xml, QEMUD_MAX_XML_LEN))
D
Daniel P. Berrange 已提交
2490 2491
            continue;

2492
        if (isGuest)
2493
            qemudLoadConfig(driver, entry->d_name, path, xml, autostartLink);
2494
        else
2495
            qemudLoadNetworkConfig(driver, entry->d_name, path, xml, autostartLink);
D
Daniel P. Berrange 已提交
2496 2497 2498 2499 2500 2501 2502
    }

    closedir(dir);
 
    return 0;
}

2503
/* Scan for all guest and network config files */
2504 2505
int qemudScanConfigs(struct qemud_driver *driver) {
    if (qemudScanConfigDir(driver, driver->configDir, driver->autostartDir, 1) < 0)
2506
        return -1;
2507

2508
    if (qemudScanConfigDir(driver, driver->networkConfigDir, driver->networkAutostartDir, 0) < 0)
2509 2510 2511
        return -1;

    return 0;
2512
}
D
Daniel P. Berrange 已提交
2513 2514

/* Generate an XML document describing the guest's configuration */
2515 2516
char *qemudGenerateXML(virConnectPtr conn,
                       struct qemud_driver *driver ATTRIBUTE_UNUSED,
2517 2518 2519
                       struct qemud_vm *vm,
                       struct qemud_vm_def *def,
                       int live) {
D
Daniel P. Berrange 已提交
2520
    virBufferPtr buf = 0;
D
Daniel P. Berrange 已提交
2521 2522 2523 2524 2525 2526
    unsigned char *uuid;
    struct qemud_vm_disk_def *disk;
    struct qemud_vm_net_def *net;
    const char *type = NULL;
    int n;

D
Daniel P. Berrange 已提交
2527
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2528
    if (!buf)
2529 2530
        goto no_memory;

2531
    switch (def->virtType) {
D
Daniel P. Berrange 已提交
2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542
    case QEMUD_VIRT_QEMU:
        type = "qemu";
        break;
    case QEMUD_VIRT_KQEMU:
        type = "kqemu";
        break;
    case QEMUD_VIRT_KVM:
        type = "kvm";
        break;
    }
    if (!type) {
2543
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "unexpected domain type %d", def->virtType);
D
Daniel P. Berrange 已提交
2544 2545 2546
        goto cleanup;
    }

2547
    if (qemudIsActiveVM(vm) && live) {
D
Daniel P. Berrange 已提交
2548
        if (virBufferVSprintf(buf, "<domain type='%s' id='%d'>\n", type, vm->id) < 0)
D
Daniel P. Berrange 已提交
2549 2550
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2551
        if (virBufferVSprintf(buf, "<domain type='%s'>\n", type) < 0)
D
Daniel P. Berrange 已提交
2552 2553 2554
            goto no_memory;
    }

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

2558
    uuid = def->uuid;
D
Daniel P. Berrange 已提交
2559
    if (virBufferVSprintf(buf, "  <uuid>%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x</uuid>\n",
D
Daniel P. Berrange 已提交
2560 2561 2562 2563 2564
                          uuid[0], uuid[1], uuid[2], uuid[3],
                          uuid[4], uuid[5], uuid[6], uuid[7],
                          uuid[8], uuid[9], uuid[10], uuid[11],
                          uuid[12], uuid[13], uuid[14], uuid[15]) < 0)
        goto no_memory;
D
Daniel P. Berrange 已提交
2565
    if (virBufferVSprintf(buf, "  <memory>%d</memory>\n", def->maxmem) < 0)
D
Daniel P. Berrange 已提交
2566
        goto no_memory;
D
Daniel P. Berrange 已提交
2567
    if (virBufferVSprintf(buf, "  <currentMemory>%d</currentMemory>\n", def->memory) < 0)
D
Daniel P. Berrange 已提交
2568
        goto no_memory;
D
Daniel P. Berrange 已提交
2569
    if (virBufferVSprintf(buf, "  <vcpu>%d</vcpu>\n", def->vcpus) < 0)
D
Daniel P. Berrange 已提交
2570 2571
        goto no_memory;

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

2575
    if (def->virtType == QEMUD_VIRT_QEMU) {
D
Daniel P. Berrange 已提交
2576
        if (virBufferVSprintf(buf, "    <type arch='%s' machine='%s'>%s</type>\n",
2577
                              def->os.arch, def->os.machine, def->os.type) < 0)
D
Daniel P. Berrange 已提交
2578 2579
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2580
        if (virBufferVSprintf(buf, "    <type>%s</type>\n", def->os.type) < 0)
D
Daniel P. Berrange 已提交
2581 2582 2583
            goto no_memory;
    }

2584
    if (def->os.kernel[0])
D
Daniel P. Berrange 已提交
2585
        if (virBufferVSprintf(buf, "    <kernel>%s</kernel>\n", def->os.kernel) < 0)
D
Daniel P. Berrange 已提交
2586
            goto no_memory;
2587
    if (def->os.initrd[0])
D
Daniel P. Berrange 已提交
2588
        if (virBufferVSprintf(buf, "    <initrd>%s</initrd>\n", def->os.initrd) < 0)
D
Daniel P. Berrange 已提交
2589
            goto no_memory;
2590
    if (def->os.cmdline[0])
D
Daniel P. Berrange 已提交
2591
        if (virBufferVSprintf(buf, "    <cmdline>%s</cmdline>\n", def->os.cmdline) < 0)
D
Daniel P. Berrange 已提交
2592 2593
            goto no_memory;

2594
    for (n = 0 ; n < def->os.nBootDevs ; n++) {
D
Daniel P. Berrange 已提交
2595
        const char *boottype = "hd";
2596
        switch (def->os.bootDevs[n]) {
D
Daniel P. Berrange 已提交
2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609
        case QEMUD_BOOT_FLOPPY:
            boottype = "fd";
            break;
        case QEMUD_BOOT_DISK:
            boottype = "hd";
            break;
        case QEMUD_BOOT_CDROM:
            boottype = "cdrom";
            break;
        case QEMUD_BOOT_NET:
            boottype = "net";
            break;
        }
D
Daniel P. Berrange 已提交
2610
        if (virBufferVSprintf(buf, "    <boot dev='%s'/>\n", boottype) < 0)
D
Daniel P. Berrange 已提交
2611 2612 2613
            goto no_memory;
    }

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

2617
    if (def->features & QEMUD_FEATURE_ACPI) {
D
Daniel P. Berrange 已提交
2618
        if (virBufferAdd(buf, "  <features>\n", -1) < 0)
2619
            goto no_memory;
D
Daniel P. Berrange 已提交
2620
        if (virBufferAdd(buf, "    <acpi/>\n", -1) < 0)
2621
            goto no_memory;
D
Daniel P. Berrange 已提交
2622
        if (virBufferAdd(buf, "  </features>\n", -1) < 0)
2623 2624 2625
            goto no_memory;
    }

D
Daniel P. Berrange 已提交
2626
    if (virBufferAdd(buf, "  <on_poweroff>destroy</on_poweroff>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2627 2628
        goto no_memory;
    if (def->noReboot) {
D
Daniel P. Berrange 已提交
2629
        if (virBufferAdd(buf, "  <on_reboot>destroy</on_reboot>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2630 2631
            goto no_memory;
    } else {
D
Daniel P. Berrange 已提交
2632
        if (virBufferAdd(buf, "  <on_reboot>restart</on_reboot>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2633 2634
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
2635
    if (virBufferAdd(buf, "  <on_crash>destroy</on_crash>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2636
        goto no_memory;
2637

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

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

2644
    disk = def->disks;
D
Daniel P. Berrange 已提交
2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658
    while (disk) {
        const char *types[] = {
            "block",
            "file",
        };
        const char *typeAttrs[] = {
            "dev",
            "file",
        };
        const char *devices[] = {
            "disk",
            "cdrom",
            "floppy",
        };
D
Daniel P. Berrange 已提交
2659
        if (virBufferVSprintf(buf, "    <disk type='%s' device='%s'>\n",
D
Daniel P. Berrange 已提交
2660 2661 2662
                              types[disk->type], devices[disk->device]) < 0)
            goto no_memory;

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

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

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

D
Daniel P. Berrange 已提交
2673
        if (virBufferVSprintf(buf, "    </disk>\n") < 0)
D
Daniel P. Berrange 已提交
2674 2675 2676 2677 2678
            goto no_memory;

        disk = disk->next;
    }

2679
    net = def->nets;
2680
    while (net) {
D
Daniel P. Berrange 已提交
2681 2682
        const char *types[] = {
            "user",
2683
            "ethernet",
D
Daniel P. Berrange 已提交
2684 2685 2686
            "server",
            "client",
            "mcast",
2687
            "network",
2688
            "bridge",
D
Daniel P. Berrange 已提交
2689
        };
D
Daniel P. Berrange 已提交
2690
        if (virBufferVSprintf(buf, "    <interface type='%s'>\n",
D
Daniel P. Berrange 已提交
2691 2692 2693
                              types[net->type]) < 0)
            goto no_memory;

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

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

2704
            if (net->dst.network.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2705
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.network.ifname) < 0)
2706 2707 2708
                    goto no_memory;
            }
            break;
2709

2710 2711
        case QEMUD_NET_ETHERNET:
            if (net->dst.ethernet.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2712
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.ethernet.ifname) < 0)
2713 2714 2715
                    goto no_memory;
            }
            if (net->dst.ethernet.script[0] != '\0') {
D
Daniel P. Berrange 已提交
2716
                if (virBufferVSprintf(buf, "      <script path='%s'/>\n", net->dst.ethernet.script) < 0)
2717 2718 2719 2720 2721
                    goto no_memory;
            }
            break;

        case QEMUD_NET_BRIDGE:
D
Daniel P. Berrange 已提交
2722
            if (virBufferVSprintf(buf, "      <source bridge='%s'/>\n", net->dst.bridge.brname) < 0)
2723
                goto no_memory;
2724
            if (net->dst.bridge.ifname[0] != '\0') {
D
Daniel P. Berrange 已提交
2725
                if (virBufferVSprintf(buf, "      <target dev='%s'/>\n", net->dst.bridge.ifname) < 0)
2726 2727 2728 2729 2730 2731 2732 2733
                    goto no_memory;
            }
            break;

        case QEMUD_NET_SERVER:
        case QEMUD_NET_CLIENT:
        case QEMUD_NET_MCAST:
            if (net->dst.socket.address[0] != '\0') {
D
Daniel P. Berrange 已提交
2734
                if (virBufferVSprintf(buf, "      <source address='%s' port='%d'/>\n",
2735 2736 2737
                                      net->dst.socket.address, net->dst.socket.port) < 0)
                    goto no_memory;
            } else {
D
Daniel P. Berrange 已提交
2738
                if (virBufferVSprintf(buf, "      <source port='%d'/>\n",
2739 2740 2741
                                      net->dst.socket.port) < 0)
                    goto no_memory;
            }
2742 2743
        }

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

2747
        net = net->next;
D
Daniel P. Berrange 已提交
2748 2749
    }

2750 2751
    switch (def->graphicsType) {
    case QEMUD_GRAPHICS_VNC:
D
Daniel P. Berrange 已提交
2752
        if (virBufferAdd(buf, "    <graphics type='vnc'", -1) < 0)
2753 2754 2755
            goto no_memory;

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

D
Daniel P. Berrange 已提交
2760
        if (virBufferAdd(buf, "/>\n", -1) < 0)
2761 2762 2763 2764
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_SDL:
D
Daniel P. Berrange 已提交
2765
        if (virBufferAdd(buf, "    <graphics type='sdl'/>\n", -1) < 0)
2766 2767 2768 2769 2770 2771 2772 2773
            goto no_memory;
        break;

    case QEMUD_GRAPHICS_NONE:
    default:
        break;
    }

2774
    if (def->graphicsType == QEMUD_GRAPHICS_VNC) {
D
Daniel P. Berrange 已提交
2775 2776
    }

D
Daniel P. Berrange 已提交
2777
    if (virBufferAdd(buf, "  </devices>\n", -1) < 0)
D
Daniel P. Berrange 已提交
2778 2779 2780
        goto no_memory;


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

D
Daniel P. Berrange 已提交
2784
    return virBufferContentAndFree (buf);
D
Daniel P. Berrange 已提交
2785 2786

 no_memory:
2787
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
2788
 cleanup:
D
Daniel P. Berrange 已提交
2789
    if (buf) virBufferFree (buf);
D
Daniel P. Berrange 已提交
2790 2791 2792 2793
    return NULL;
}


2794 2795
char *qemudGenerateNetworkXML(virConnectPtr conn,
                              struct qemud_driver *driver ATTRIBUTE_UNUSED,
2796
                              struct qemud_network *network,
2797
                              struct qemud_network_def *def) {
D
Daniel P. Berrange 已提交
2798
    virBufferPtr buf = 0;
2799 2800
    unsigned char *uuid;

D
Daniel P. Berrange 已提交
2801
    buf = virBufferNew (QEMUD_MAX_XML_LEN);
2802
    if (!buf)
2803 2804
        goto no_memory;

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

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

2811
    uuid = def->uuid;
D
Daniel P. Berrange 已提交
2812
    if (virBufferVSprintf(buf, "  <uuid>%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x</uuid>\n",
2813 2814 2815 2816 2817 2818
                          uuid[0], uuid[1], uuid[2], uuid[3],
                          uuid[4], uuid[5], uuid[6], uuid[7],
                          uuid[8], uuid[9], uuid[10], uuid[11],
                          uuid[12], uuid[13], uuid[14], uuid[15]) < 0)
        goto no_memory;

2819 2820
    if (def->forward) {
        if (def->forwardDev[0]) {
D
Daniel P. Berrange 已提交
2821
            virBufferVSprintf(buf, "  <forward dev='%s'/>\n",
2822 2823
                              def->forwardDev);
        } else {
D
Daniel P. Berrange 已提交
2824
            virBufferAdd(buf, "  <forward/>\n", -1);
2825 2826 2827
        }
    }

D
Daniel P. Berrange 已提交
2828
    virBufferAdd(buf, "  <bridge", -1);
2829
    if (qemudIsActiveNetwork(network)) {
D
Daniel P. Berrange 已提交
2830
        if (virBufferVSprintf(buf, " name='%s'", network->bridge) < 0)
2831 2832
            goto no_memory;
    } else if (def->bridge[0]) {
D
Daniel P. Berrange 已提交
2833
        if (virBufferVSprintf(buf, " name='%s'", def->bridge) < 0)
2834 2835
            goto no_memory;
    }
D
Daniel P. Berrange 已提交
2836
    if (virBufferVSprintf(buf, " stp='%s' forwardDelay='%d' />\n",
2837 2838
                       def->disableSTP ? "off" : "on",
                       def->forwardDelay) < 0)
2839 2840
        goto no_memory;

2841
    if (def->ipAddress[0] || def->netmask[0]) {
D
Daniel P. Berrange 已提交
2842
        if (virBufferAdd(buf, "  <ip", -1) < 0)
2843 2844
            goto no_memory;

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

2849
        if (def->netmask[0] &&
D
Daniel P. Berrange 已提交
2850
            virBufferVSprintf(buf, " netmask='%s'", def->netmask) < 0)
2851 2852
            goto no_memory;

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

2856 2857
        if (def->ranges) {
            struct qemud_dhcp_range_def *range = def->ranges;
D
Daniel P. Berrange 已提交
2858
            if (virBufferAdd(buf, "    <dhcp>\n", -1) < 0)
2859 2860
                goto no_memory;
            while (range) {
D
Daniel P. Berrange 已提交
2861
                if (virBufferVSprintf(buf, "      <range start='%s' end='%s' />\n",
2862 2863 2864 2865
                                      range->start, range->end) < 0)
                    goto no_memory;
                range = range->next;
            }
D
Daniel P. Berrange 已提交
2866
            if (virBufferAdd(buf, "    </dhcp>\n", -1) < 0)
2867 2868 2869
                goto no_memory;
        }

D
Daniel P. Berrange 已提交
2870
        if (virBufferAdd(buf, "  </ip>\n", -1) < 0)
2871
            goto no_memory;
D
Daniel P. Berrange 已提交
2872 2873
    }

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

D
Daniel P. Berrange 已提交
2877
    return virBufferContentAndFree (buf);
2878 2879

 no_memory:
2880
    qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, "xml");
D
Daniel P. Berrange 已提交
2881
    if (buf) virBufferFree (buf);
2882 2883 2884 2885
    return NULL;
}


2886 2887
int qemudDeleteConfig(virConnectPtr conn,
                      struct qemud_driver *driver ATTRIBUTE_UNUSED,
2888 2889 2890
                      const char *configFile,
                      const char *name) {
    if (!configFile[0]) {
2891
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "no config file for %s", name);
D
Daniel P. Berrange 已提交
2892 2893 2894
        return -1;
    }

2895
    if (unlink(configFile) < 0) {
2896
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "cannot remove config for %s", name);
2897 2898
        return -1;
    }
2899

D
Daniel P. Berrange 已提交
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911
    return 0;
}


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