vbox_tmpl.c 170.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/** @file vbox_tmpl.c
 * Template File to support multiple versions of VirtualBox
 * at runtime :).
 *
 * IMPORTANT:
 * Please dont include this file in the src/Makefile.am, it
 * is automatically include by other files.
 */

/*
 * Copyright (C) 2008-2009 Sun Microsystems, Inc.
 *
 * This file is part of a free software library; you can redistribute
 * it and/or modify it under the terms of the GNU Lesser General
 * Public License version 2.1 as published by the Free Software
 * Foundation and shipped in the "COPYING" file with this library.
 * The library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY of any kind.
 *
 * Sun LGPL Disclaimer: For the avoidance of doubt, except that if
 * any license choice other than GPL or LGPL is available it will
 * apply instead, Sun elects to use only the Lesser General Public
 * License version 2.1 (LGPLv2) at this time for any software where
 * a choice of LGPL license versions is made available with the
 * language indicating that LGPLv2 or any later version may be used,
 * or where a choice of which version of the LGPL is applied is
 * otherwise unspecified.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
 * Clara, CA 95054 USA or visit http://www.sun.com if you need
 * additional information or have any questions.
 */

#include <config.h>

#include <dlfcn.h>
#include <sys/utsname.h>

#include "internal.h"

#include "datatypes.h"
#include "domain_conf.h"
43
#include "network_conf.h"
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#include "virterror_internal.h"
#include "uuid.h"
#include "memory.h"
#include "nodeinfo.h"
#include "logging.h"
#include "vbox_driver.h"

/* This one changes from version to version. */
#if VBOX_API_VERSION == 2002
# include "vbox_CAPI_v2_2.h"
/* Commented for now, v2.5 is far far away */
/*
#elif VBOX_API_VERSION == 2005
# include "VBoxCAPI_v2_5.h"
*/
#endif

61 62 63 64
/* Include this *last* or we'll get the wrong vbox_CAPI_*.h. */
#include "vbox_XPCOMCGlue.h"


65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
#define VIR_FROM_THIS VIR_FROM_VBOX

#define vboxError(conn, code, fmt...) \
        virReportErrorHelper(conn, VIR_FROM_VBOX, code, __FILE__, \
                            __FUNCTION__, __LINE__, fmt)

typedef struct {
    virMutex lock;
    int version;

    virDomainObjList domains;
    virCapsPtr caps;

    IVirtualBox *vboxObj;
    ISession *vboxSession;
80 81 82

    /** Our version specific API table pointer. */
    PCVBOXXPCOM pFuncs;
83 84
} vboxGlobalData;

85

86 87 88 89
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml);
static int vboxDomainCreate(virDomainPtr dom);
static int vboxDomainUndefine(virDomainPtr dom);

90
static void nsIDtoChar(unsigned char *uuid, const nsID *iid) {
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    char uuidstrsrc[VIR_UUID_STRING_BUFLEN];
    char uuidstrdst[VIR_UUID_STRING_BUFLEN];
    unsigned char uuidinterim[VIR_UUID_BUFLEN];
    int i;

    memcpy(uuidinterim, iid, VIR_UUID_BUFLEN);
    virUUIDFormat(uuidinterim, uuidstrsrc);

    uuidstrdst[0]  = uuidstrsrc[6];
    uuidstrdst[1]  = uuidstrsrc[7];
    uuidstrdst[2]  = uuidstrsrc[4];
    uuidstrdst[3]  = uuidstrsrc[5];
    uuidstrdst[4]  = uuidstrsrc[2];
    uuidstrdst[5]  = uuidstrsrc[3];
    uuidstrdst[6]  = uuidstrsrc[0];
    uuidstrdst[7]  = uuidstrsrc[1];

    uuidstrdst[8]  = uuidstrsrc[8];

    uuidstrdst[9]  = uuidstrsrc[11];
    uuidstrdst[10] = uuidstrsrc[12];
    uuidstrdst[11] = uuidstrsrc[9];
    uuidstrdst[12] = uuidstrsrc[10];

    uuidstrdst[13] = uuidstrsrc[13];

    uuidstrdst[14] = uuidstrsrc[16];
    uuidstrdst[15] = uuidstrsrc[17];
    uuidstrdst[16] = uuidstrsrc[14];
    uuidstrdst[17] = uuidstrsrc[15];

    for(i = 18; i < VIR_UUID_STRING_BUFLEN; i++) {
        uuidstrdst[i] = uuidstrsrc[i];
    }

    uuidstrdst[VIR_UUID_STRING_BUFLEN-1] = '\0';
    virUUIDParse(uuidstrdst, uuid);
}

static void vboxDriverLock(vboxGlobalData *data) {
    virMutexLock(&data->lock);
}

static void vboxDriverUnlock(vboxGlobalData *data) {
    virMutexUnlock(&data->lock);
}

138
static void nsIDFromChar(nsID *iid, const unsigned char *uuid) {
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    char uuidstrsrc[VIR_UUID_STRING_BUFLEN];
    char uuidstrdst[VIR_UUID_STRING_BUFLEN];
    unsigned char uuidinterim[VIR_UUID_BUFLEN];
    int i;

    virUUIDFormat(uuid, uuidstrsrc);

    uuidstrdst[0]  = uuidstrsrc[6];
    uuidstrdst[1]  = uuidstrsrc[7];
    uuidstrdst[2]  = uuidstrsrc[4];
    uuidstrdst[3]  = uuidstrsrc[5];
    uuidstrdst[4]  = uuidstrsrc[2];
    uuidstrdst[5]  = uuidstrsrc[3];
    uuidstrdst[6]  = uuidstrsrc[0];
    uuidstrdst[7]  = uuidstrsrc[1];

    uuidstrdst[8]  = uuidstrsrc[8];

    uuidstrdst[9]  = uuidstrsrc[11];
    uuidstrdst[10] = uuidstrsrc[12];
    uuidstrdst[11] = uuidstrsrc[9];
    uuidstrdst[12] = uuidstrsrc[10];

    uuidstrdst[13] = uuidstrsrc[13];

    uuidstrdst[14] = uuidstrsrc[16];
    uuidstrdst[15] = uuidstrsrc[17];
    uuidstrdst[16] = uuidstrsrc[14];
    uuidstrdst[17] = uuidstrsrc[15];

    for(i = 18; i < VIR_UUID_STRING_BUFLEN; i++) {
        uuidstrdst[i] = uuidstrsrc[i];
    }

    uuidstrdst[VIR_UUID_STRING_BUFLEN-1] = '\0';
    virUUIDParse(uuidstrdst, uuidinterim);
    memcpy(iid, uuidinterim, VIR_UUID_BUFLEN);
}

static virCapsPtr vboxCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

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

    if (virCapsInitNUMA(caps) < 0)
        goto no_memory;

    virCapabilitiesSetMacPrefix(caps, (unsigned char[]){ 0x08, 0x00, 0x27 });

    if ((guest = virCapabilitiesAddGuest(caps,
                                         "hvm",
                                         utsname.machine,
                                         sizeof(void *) * CHAR_BIT,
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

    if (virCapabilitiesAddGuestDomain(guest,
                                      "vbox",
                                      NULL,
                                      NULL,
                                      0,
                                      NULL) == NULL)
        goto no_memory;
    return caps;

no_memory:
    virCapabilitiesFree(caps);
    return NULL;
}

static int vboxInitialize(virConnectPtr conn, vboxGlobalData *data) {
219 220 221 222 223
    /* Get the API table for out version, g_pVBoxFuncs is for the oldest
       version of the API that we support so we cannot use that. */
    data->pFuncs = g_pfnGetFunctions(VBOX_XPCOMC_VERSION);

    if (data->pFuncs == NULL)
224
        goto cleanup;
225 226 227 228 229 230 231 232 233 234

#if VBOX_XPCOMC_VERSION == 0x00010000U
    data->pFuncs->pfnComInitialize(&data->vboxObj, &data->vboxSession);
#else
    data->pFuncs->pfnComInitialize(IVIRTUALBOX_IID_STR, &data->vboxObj,
                               ISESSION_IID_STR, &data->vboxSession);
#endif

    if (data->vboxObj == NULL) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR, "IVirtualBox object is null");
235
        goto cleanup;
236 237 238 239 240 241
    }

    if (data->vboxSession == NULL) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR, "ISession object is null");
        goto cleanup;
    }
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

    return 0;

cleanup:
    return -1;
}

static int vboxExtractVersion(virConnectPtr conn, vboxGlobalData *data) {
    unsigned int major      = 0;
    unsigned int minor      = 0;
    unsigned int micro      = 0;
    int          ret        = -1;
    PRUnichar *versionUtf16 = NULL;
    nsresult rc;

    if (data->version > 0)
        return 0;

    rc = data->vboxObj->vtbl->GetVersion(data->vboxObj, &versionUtf16);
    if (NS_SUCCEEDED(rc)) {
        char *vboxVersion = NULL;

264
        data->pFuncs->pfnUtf16ToUtf8(versionUtf16, &vboxVersion);
265 266 267 268

        if (sscanf(vboxVersion, "%u.%u.%u", &major, &minor, &micro) == 3)
            ret = 0;

269 270
        data->pFuncs->pfnUtf8Free(vboxVersion);
        data->pFuncs->pfnComUnallocMem(versionUtf16);
271 272 273 274 275 276 277 278 279 280 281 282 283
    } else {
        ret = -1;
    }

    data->version = (major * 1000 * 1000) + (minor * 1000) + micro;

    if (ret != 0)
        vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s",
                  "Cound not extract VirtualBox version");
    return ret;
}

static void vboxUninitialize(vboxGlobalData *data) {
284 285 286
    if (!data)
        return;

287 288
    if (data->pFuncs)
        data->pFuncs->pfnComUninitialize();
289 290 291 292 293 294 295 296 297 298
    VBoxCGlueTerm();

    virDomainObjListFree(&data->domains);
    virCapabilitiesFree(data->caps);
    VIR_FREE(data);
}

static virDrvOpenStatus vboxOpen(virConnectPtr conn,
                                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                 int flags ATTRIBUTE_UNUSED) {
299
    vboxGlobalData *data = NULL;
300 301 302 303 304
    uid_t uid = getuid();

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "vbox:///session" : "vbox:///system");
        if (conn->uri == NULL) {
305
            virReportOOMError(conn);
306 307 308 309
            return VIR_DRV_OPEN_ERROR;
        }
    }

310 311 312 313 314 315
    if (conn->uri->scheme == NULL ||
        STRNEQ (conn->uri->scheme, "vbox"))
        return VIR_DRV_OPEN_DECLINED;

    /* Leave for remote driver */
    if (conn->uri->server != NULL)
316 317
        return VIR_DRV_OPEN_DECLINED;

318 319 320 321 322 323
    if (conn->uri->path == NULL || STREQ(conn->uri->path, "")) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR, "%s",
                  _("no VirtualBox driver path specified (try vbox:///session)"));
        return VIR_DRV_OPEN_ERROR;
    }

324
    if (uid != 0) {
325 326 327 328 329
        if (STRNEQ (conn->uri->path, "/session")) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,
                      _("unknown driver path '%s' specified (try vbox:///session)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
330 331
    } else { /* root */
        if (STRNEQ (conn->uri->path, "/system") &&
332 333 334 335 336
            STRNEQ (conn->uri->path, "/session")) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,
                      _("unknown driver path '%s' specified (try vbox:///system)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
337 338 339 340
    }

    if (VIR_ALLOC(data) < 0) {
        virReportOOMError(conn);
341
        return VIR_DRV_OPEN_ERROR;
342 343
    }

344 345 346 347 348 349
    if (!(data->caps = vboxCapsInit()) ||
        vboxInitialize(conn, data) < 0 ||
        vboxExtractVersion(conn, data) < 0) {
        vboxUninitialize(data);
        return VIR_DRV_OPEN_ERROR;
    }
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463

    conn->privateData = data;
    DEBUG0("in vboxOpen");

    return VIR_DRV_OPEN_SUCCESS;
}

static int vboxClose(virConnectPtr conn) {
    vboxGlobalData *data = conn->privateData;
    DEBUG("%s: in vboxClose",conn->driver->name);

    vboxUninitialize(data);
    conn->privateData = NULL;

    return 0;
}

static int vboxGetVersion(virConnectPtr conn, unsigned long *version) {
    vboxGlobalData *data = conn->privateData;
    DEBUG("%s: in vboxGetVersion",conn->driver->name);

    vboxDriverLock(data);
    *version = data->version;
    vboxDriverUnlock(data);

    return 0;
}

static char *vboxGetHostname(virConnectPtr conn) {
    char *hostname;

    /* the return string should be freed by caller */
    hostname = virGetHostname();
    if (hostname == NULL) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s",
                  "failed to determine host name");
        return NULL;
    }

    return hostname;
}

static int vboxGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED) {
    vboxGlobalData *data = conn->privateData;
    PRUint32 maxCPUCount = 0;
    int ret = -1;

    /* VirtualBox Supports only hvm and thus the type passed to it
     * has no meaning, setting it to ATTRIBUTE_UNUSED
     */
    if(data->vboxObj) {
        ISystemProperties *systemProperties = NULL;

        data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
        if (systemProperties) {
            systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
            systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
        }
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}

static int vboxNodeGetInfo(virConnectPtr conn, virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
}

static char *vboxGetCapabilities(virConnectPtr conn) {
    vboxGlobalData *data = conn->privateData;
    char *ret;

    vboxDriverLock(data);
    ret = virCapabilitiesFormatXML(data->caps);
    vboxDriverUnlock(data);

    return ret;
}

static int vboxListDomains(virConnectPtr conn, int *ids, int nids) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    PRUint32 state;
    int ret = -1;
    int i, j;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of Domains",(unsigned)rc);
            goto cleanup;
        }

        if (machineCnt == 0) {
            ret = 0;
            goto cleanup;
        }

        for (i = 0,j = 0; (i < machineCnt) && (j < nids); ++i) {
            IMachine *machine = machines[i];

            if (machine) {
                PRBool isAccessible = PR_FALSE;
                machine->vtbl->GetAccessible(machine, &isAccessible);
                if (isAccessible) {
                    machine->vtbl->GetState(machine, &state);
                    if ((state == MachineState_Running) ||
                        (state == MachineState_Paused) ) {
                        ret++;
464
                        ids[j++] = i + 1;
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
                    }
                }
            }
        }
        ret++;
    }

cleanup:
    for (i = 0; i < machineCnt; ++i)
        if (machines[i])
            machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
    return ret;
}

static int vboxNumOfDomains(virConnectPtr conn) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    PRUint32 state;
    int ret = -1;
    int i;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get number of Domains",(unsigned)rc);
            goto cleanup;
        }

        if (machineCnt == 0) {
            ret = 0;
            goto cleanup;
        }

        /* Do the cleanup as required by GetMachines() */
        for (i = 0; i < machineCnt; ++i) {
            IMachine *machine = machines[i];

            if (machine) {
                PRBool isAccessible = PR_FALSE;
                machine->vtbl->GetAccessible(machine, &isAccessible);
                if (isAccessible) {
                    machine->vtbl->GetState(machine, &state);
                    if ((state == MachineState_Running) ||
                        (state == MachineState_Paused) ) {
                        ret++;
                    }
                }
            }
        }
        ret++;
    }

cleanup:
    for (i = 0; i < machineCnt; ++i)
        if (machines[i])
            machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
    return ret;
}

static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
                                        unsigned int flags ATTRIBUTE_UNUSED) {
    virDomainPtr dom = NULL;

    /* VirtualBox currently doesn't have support for running
     * virtual machines without actually defining them and thus
     * for time being just define new machine and start it.
     *
     * TODO: After the appropriate API's are added in VirtualBox
     * change this behaviour to the expected one.
     */

    dom = vboxDomainDefineXML(conn, xml);
    if (dom) {
        if (vboxDomainCreate(dom) < 0)
            goto cleanup;
    } else {
        goto cleanup;
    }

    return dom;

cleanup:
    vboxDomainUndefine(dom);
    return NULL;
}

static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    virDomainPtr dom     = NULL;
    nsID  *iid           = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    PRUint32 state;
    int i;

565 566 567 568 569 570 571 572 573
    /* Internal vbox IDs start from 0, the public libvirt ID
     * starts from 1, so refuse id==0, and adjust the rest*/
    if (id == 0) {
        vboxError(conn, VIR_ERR_NO_DOMAIN,
                  _("no domain with matching id %d"), id);
        return NULL;
    }
    id = id - 1;

574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of machines",(unsigned)rc);
            return NULL;
        }

        if (id < machineCnt) {
            if (machines[id]) {
                PRBool isAccessible = PR_FALSE;
                machines[id]->vtbl->GetAccessible(machines[id], &isAccessible);
                if (isAccessible) {
                    machines[id]->vtbl->GetState(machines[id], &state);
                    if ((state == MachineState_Running) ||
                        (state == MachineState_Paused) ) {
                        PRUnichar *machineNameUtf16 = NULL;
                        char *machineName;

                        machines[id]->vtbl->GetName(machines[id], &machineNameUtf16);
594
                        data->pFuncs->pfnUtf16ToUtf8(machineNameUtf16, &machineName);
595 596 597 598 599 600 601 602 603 604 605 606

                        machines[id]->vtbl->GetId(machines[id], &iid);
                        nsIDtoChar(iidl, iid);

                        /* get a new domain pointer from virGetDomain, if it fails
                         * then no need to assign the id, else assign the id, cause
                         * it is -1 by default. rest is taken care by virGetDomain
                         * itself, so need not worry.
                         */

                        dom = virGetDomain(conn, machineName, iidl);
                        if (dom)
607
                            dom->id = id + 1;
608 609

                        /* Cleanup all the XPCOM allocated stuff here */
610 611 612
                        data->pFuncs->pfnComUnallocMem(iid);
                        data->pFuncs->pfnUtf8Free(machineName);
                        data->pFuncs->pfnComUnallocMem(machineNameUtf16);
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
                    }
                }
            }
        }

        /* Do the cleanup as required by GetMachines() */
        for (i = 0; i < machineCnt; ++i) {
            if (machines[i])
                machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
        }
    }

    return dom;
}

static virDomainPtr vboxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    virDomainPtr dom     = NULL;
    nsID  *iid           = NULL;
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of machines",(unsigned)rc);
            return NULL;
        }

        for (i = 0; i < machineCnt; ++i) {
            IMachine *machine = machines[i];
            PRBool isAccessible = PR_FALSE;

            if (!machine)
                continue;

            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {

                machine->vtbl->GetId(machine, &iid);
                if (!iid)
                    continue;
                nsIDtoChar(iidl, iid);

                if (memcmp(uuid, iidl, VIR_UUID_BUFLEN) == 0) {

                    PRUint32 state;

                    matched = 1;

                    machine->vtbl->GetName(machine, &machineNameUtf16);
670
                    data->pFuncs->pfnUtf16ToUtf8(machineNameUtf16, &machineName);
671 672 673 674 675 676 677 678 679 680 681 682 683

                    machine->vtbl->GetState(machine, &state);

                    /* get a new domain pointer from virGetDomain, if it fails
                     * then no need to assign the id, else assign the id, cause
                     * it is -1 by default. rest is taken care by virGetDomain
                     * itself, so need not worry.
                     */

                    dom = virGetDomain(conn, machineName, iidl);
                    if (dom)
                        if ((state == MachineState_Running) ||
                            (state == MachineState_Paused) )
684
                            dom->id = i + 1;
685 686 687
                }

                if (iid) {
688
                    data->pFuncs->pfnComUnallocMem(iid);
689 690 691 692 693 694 695 696 697
                    iid = NULL;
                }
                if (matched == 1)
                    break;
            }
        }

        /* Do the cleanup and take care you dont leak any memory */
        if (machineName)
698
            data->pFuncs->pfnUtf8Free(machineName);
699
        if (machineNameUtf16)
700
            data->pFuncs->pfnComUnallocMem(machineNameUtf16);
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
        for (i = 0; i < machineCnt; ++i) {
            if (machines[i])
                machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
        }
    }

    return dom;
}

static virDomainPtr vboxDomainLookupByName(virConnectPtr conn, const char *name) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    virDomainPtr dom     = NULL;
    nsID  *iid           = NULL;
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of machines",(unsigned)rc);
            return NULL;
        }

        for (i = 0; i < machineCnt; ++i) {
            IMachine *machine = machines[i];
            PRBool isAccessible = PR_FALSE;

            if (!machine)
                continue;

            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {

                machine->vtbl->GetName(machine, &machineNameUtf16);
741
                data->pFuncs->pfnUtf16ToUtf8(machineNameUtf16, &machineName);
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

                if (machineName && (STREQ(name, machineName))) {

                    PRUint32 state;

                    matched = 1;

                    machine->vtbl->GetId(machine, &iid);
                    nsIDtoChar(iidl, iid);

                    machine->vtbl->GetState(machine, &state);

                    /* get a new domain pointer from virGetDomain, if it fails
                     * then no need to assign the id, else assign the id, cause
                     * it is -1 by default. rest is taken care by virGetDomain
                     * itself, so need not worry.
                     */

                    dom = virGetDomain(conn, machineName, iidl);
                    if (dom)
                        if ((state == MachineState_Running) ||
                            (state == MachineState_Paused) )
764
                            dom->id = i + 1;
765 766 767
                }

                if (machineName) {
768
                    data->pFuncs->pfnUtf8Free(machineName);
769 770 771
                    machineName = NULL;
                }
                if (machineNameUtf16) {
772
                    data->pFuncs->pfnComUnallocMem(machineNameUtf16);
773 774 775 776 777 778 779 780 781
                    machineNameUtf16 = NULL;
                }
                if (matched == 1)
                    break;
            }
        }

        /* Do the cleanup and take care you dont leak any memory */
        if (iid)
782
            data->pFuncs->pfnComUnallocMem(iid);
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
        for (i = 0; i < machineCnt; ++i) {
            if (machines[i])
                machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
        }
    }

    return dom;
}

static int vboxDomainSuspend(virDomainPtr dom) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID  *iid           = NULL;
    IConsole *console    = NULL;
    PRUint32 state;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if (data->vboxObj) {
        PRBool isAccessible = PR_FALSE;

        nsIDFromChar(iid, dom->uuid);
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                            "no domain with matching id %d", dom->id);
            goto cleanup;
        }

        if (!machine)
            goto cleanup;

        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            machine->vtbl->GetState(machine, &state);

            if (state == MachineState_Running) {
                 /* set state pause */
                data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
                data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
                if (console) {
                    console->vtbl->Pause(console);
                    console->vtbl->nsisupports.Release((nsISupports *)console);
                    ret = 0;
                } else {
                    vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                              "%s", "error while suspend the domain");
                    goto cleanup;
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            } else {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "machine not in running state to suspend it");
                goto cleanup;
            }
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static int vboxDomainResume(virDomainPtr dom) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID  *iid           = NULL;
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if (data->vboxObj) {
        PRBool isAccessible = PR_FALSE;

        nsIDFromChar(iid, dom->uuid);
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                            "no domain with matching id %d", dom->id);
            goto cleanup;
        }

        if (!machine)
            goto cleanup;

        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            machine->vtbl->GetState(machine, &state);

            if (state == MachineState_Paused) {
                 /* resume the machine here */
                data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
                data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
                if (console) {
                    console->vtbl->Resume(console);
                    console->vtbl->nsisupports.Release((nsISupports *)console);
                    ret = 0;
                } else {
                    vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                              "%s", "error while resuming the domain");
                    goto cleanup;
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            } else {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "machine not paused, so can't resume it");
                goto cleanup;
            }
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static int vboxDomainShutdown(virDomainPtr dom) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID  *iid           = NULL;
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        PRBool isAccessible = PR_FALSE;

        nsIDFromChar(iid, dom->uuid);
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                            "no domain with matching id %d", dom->id);
            goto cleanup;
        }

        if (!machine)
            goto cleanup;

        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            machine->vtbl->GetState(machine, &state);

            if (state == MachineState_Paused) {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "machine paused, so can't power it down");
                goto cleanup;
            } else if (state == MachineState_PoweredOff) {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "machine already powered down");
                goto cleanup;
            }

            data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->PowerButton(console);
                console->vtbl->nsisupports.Release((nsISupports *)console);
                ret = 0;
            }
            data->vboxSession->vtbl->Close(data->vboxSession);
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static int vboxDomainReboot(virDomainPtr dom, unsigned int flags ATTRIBUTE_UNUSED) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID  *iid           = NULL;
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        PRBool isAccessible = PR_FALSE;

        nsIDFromChar(iid, dom->uuid);
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                            "no domain with matching id %d", dom->id);
            goto cleanup;
        }

        if (!machine)
            goto cleanup;

        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            machine->vtbl->GetState(machine, &state);

            if (state == MachineState_Running) {
                data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
                data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
                if (console) {
                    console->vtbl->Reset(console);
                    console->vtbl->nsisupports.Release((nsISupports *)console);
                    ret = 0;
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            } else {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "machine not running, so can't reboot it");
                goto cleanup;
            }
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static int vboxDomainDestroy(virDomainPtr dom) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID  *iid           = NULL;
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        PRBool isAccessible = PR_FALSE;

        nsIDFromChar(iid, dom->uuid);
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                            "no domain with matching id %d", dom->id);
            goto cleanup;
        }

        if (!machine)
            goto cleanup;

        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            machine->vtbl->GetState(machine, &state);

            if (state == MachineState_PoweredOff) {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "machine already powered down");
                goto cleanup;
            }

            data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->PowerDown(console);
                console->vtbl->nsisupports.Release((nsISupports *)console);
                ret = 0;
            }
            data->vboxSession->vtbl->Close(data->vboxSession);
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
    /* Returning "hvm" always as suggested on list, cause
     * this functions seems to be badly named and it
     * is supposed to pass the ABI name and not the domain
     * operating system driver as I had imagined ;)
     */
    return strdup("hvm");
}

static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID  *iid           = NULL;
    PRUint32 state       = MachineState_Null;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        PRBool isAccessible = PR_FALSE;

        nsIDFromChar(iid, dom->uuid);
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                            "no domain with matching id %d", dom->id);
            goto cleanup;
        }

        if (!machine)
            goto cleanup;

        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            machine->vtbl->GetState(machine, &state);

            if (state != MachineState_PoweredOff) {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                          "%s", "memory size can't be changed unless domain is powered down");
                goto cleanup;
            }

            rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, iid);
            if (NS_SUCCEEDED(rc)) {
                rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                if (NS_SUCCEEDED(rc) && machine) {

                    rc = machine->vtbl->SetMemorySize(machine, memory / 1024);
                    if (NS_SUCCEEDED(rc)) {
                        machine->vtbl->SaveSettings(machine);
                        ret = 0;
                    } else {
                        vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%lu Kb, rc=%08x",
                                  "could not set the memory size of the domain to",
                                  memory, (unsigned)rc);
                    }
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            }
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    int i, ret = -1;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(NULL, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of machines",(unsigned)rc);
            goto cleanup;
        }

        info->nrVirtCpu = 0;
        for (i = 0; i < machineCnt; ++i) {
            IMachine *machine = machines[i];
            PRBool isAccessible = PR_FALSE;

            if (!machine)
                continue;

            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {

                machine->vtbl->GetName(machine, &machineNameUtf16);
1194
                data->pFuncs->pfnUtf16ToUtf8(machineNameUtf16, &machineName);
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254

                if (STREQ(dom->name, machineName)) {
                    /* Get the Machine State (also match it with
                    * virDomainState). Get the Machine memory and
                    * for time being set maxmem and memory to same
                    * Also since there is no direct way of checking
                    * the cputime required (one condition being the
                    * VM is remote), return zero for cputime. Get the
                    * number of CPU (This is 1 for current
                    * VirtualBox builds).
                    */
                    PRUint32 CPUCount   = 0;
                    PRUint32 memorySize = 0;
                    PRUint32 state      = MachineState_Null;
                    PRUint32 maxMemorySize = 4 * 1024;
                    ISystemProperties *systemProperties = NULL;

                    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
                    if (systemProperties) {
                        systemProperties->vtbl->GetMaxGuestRAM(systemProperties, &maxMemorySize);
                        systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
                        systemProperties = NULL;
                    }


                    machine->vtbl->GetCPUCount(machine, &CPUCount);
                    machine->vtbl->GetMemorySize(machine, &memorySize);
                    machine->vtbl->GetState(machine, &state);

                    info->cpuTime = 0;
                    info->nrVirtCpu = CPUCount;
                    info->memory = memorySize * 1024;
                    info->maxMem = maxMemorySize * 1024;
                    switch(state) {
                        case MachineState_Running:
                            info->state = VIR_DOMAIN_RUNNING;
                            break;
                        case MachineState_Stuck:
                            info->state = VIR_DOMAIN_BLOCKED;
                            break;
                        case MachineState_Paused:
                            info->state = VIR_DOMAIN_PAUSED;
                            break;
                        case MachineState_Stopping:
                            info->state = VIR_DOMAIN_SHUTDOWN;
                            break;
                        case MachineState_PoweredOff:
                            info->state = VIR_DOMAIN_SHUTOFF;
                            break;
                        case MachineState_Aborted:
                            info->state = VIR_DOMAIN_CRASHED;
                            break;
                        case MachineState_Null:
                        default:
                            info->state = VIR_DOMAIN_NOSTATE;
                            break;
                    }
                }

                if (machineName)
1255
                    data->pFuncs->pfnUtf8Free(machineName);
1256
                if (machineNameUtf16)
1257
                    data->pFuncs->pfnComUnallocMem(machineNameUtf16);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
                if (info->nrVirtCpu)
                    break;
            }

        }

        /* Do the cleanup and take care you dont leak any memory */
        for (i = 0; i < machineCnt; ++i) {
            if (machines[i])
                machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
        }
    }

    ret = 0;

cleanup:
    return ret;
}

static int vboxDomainSave(virDomainPtr dom, const char *path ATTRIBUTE_UNUSED) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IConsole *console    = NULL;
    nsID *iid            = NULL;
    int ret = -1;

    /* VirtualBox currently doesn't support saving to a file
     * at a location other then the machine folder and thus
     * setting path to ATTRIBUTE_UNUSED for now, will change
     * this behaviour once get the VirtualBox API in right
     * shape to do this
     */
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        nsIDFromChar(iid, dom->uuid);

        /* Open a Session for the machine */
        rc = data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (NS_SUCCEEDED(rc) && console) {
                IProgress *progress = NULL;

                console->vtbl->SaveState(console, &progress);

                if (progress) {
                    nsresult resultCode;

                    progress->vtbl->WaitForCompletion(progress, -1);
                    progress->vtbl->GetResultCode(progress, &resultCode);
                    if (NS_SUCCEEDED(rc)) {
                        ret = 0;
                    }
                    progress->vtbl->nsisupports.Release((nsISupports *)progress);
                }
                console->vtbl->nsisupports.Release((nsISupports *)console);
            }
            data->vboxSession->vtbl->Close(data->vboxSession);
        }

        DEBUG("UUID of machine being saved:"
              "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
              (unsigned)iid->m0,    (unsigned)iid->m1, (unsigned)iid->m2,
              (unsigned)iid->m3[0], (unsigned)iid->m3[1],
              (unsigned)iid->m3[2], (unsigned)iid->m3[3],
              (unsigned)iid->m3[4], (unsigned)iid->m3[5],
              (unsigned)iid->m3[6], (unsigned)iid->m3[7]);
    }

cleanup:
    VIR_FREE(iid);
    return ret;
}

static char *vboxDomainDumpXML(virDomainPtr dom, int flags) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    virDomainDefPtr def  = NULL;
    IMachine *machine    = NULL;
    nsID *iid            = NULL;
    char *ret            = NULL;
    int gotAllABoutDef   = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if (VIR_ALLOC(def) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        nsIDFromChar(iid, dom->uuid);

        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_SUCCEEDED(rc) && machine) {
            PRBool accessible = PR_FALSE;

            machine->vtbl->GetAccessible(machine, &accessible);
            if (accessible) {
                int i = 0;
                struct utsname utsname;
                PRBool PAEEnabled                   = PR_FALSE;
                PRBool ACPIEnabled                  = PR_FALSE;
                PRBool IOAPICEnabled                = PR_FALSE;
                PRBool VRDPEnabled                  = PR_FALSE;
                PRInt32 hddNum                      = 0;
                PRUint32 CPUCount                   = 0;
                PRUint32 memorySize                 = 0;
                PRUint32 netAdpCnt                  = 0;
                PRUint32 netAdpIncCnt               = 0;
                PRUint32 maxMemorySize              = 4 * 1024;
                PRUint32 USBFilterCount             = 0;
                PRUint32 maxBootPosition            = 0;
                PRUint32 serialPortCount            = 0;
                PRUint32 serialPortIncCount         = 0;
                PRUint32 parallelPortCount          = 0;
                PRUint32 parallelPortIncCount       = 0;
                IBIOSSettings *bios                 = NULL;
                IDVDDrive *dvdDrive                 = NULL;
                IHardDisk *hardDiskPM               = NULL;
                IHardDisk *hardDiskPS               = NULL;
                IHardDisk *hardDiskSS               = NULL;
                PRUnichar *hddBusUtf16              = NULL;
                IVRDPServer *VRDPServer             = NULL;
                IFloppyDrive *floppyDrive           = NULL;
                IAudioAdapter *audioAdapter         = NULL;
                IUSBController *USBController       = NULL;
                ISystemProperties *systemProperties = NULL;
                char *hddBus = strdup("IDE");


                def->virtType = VIR_DOMAIN_VIRT_VBOX;
                def->id = dom->id;
                memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
                def->name = strdup(dom->name);

                machine->vtbl->GetMemorySize(machine, &memorySize);
                def->memory = memorySize * 1024;

                data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
                if (systemProperties) {
                    systemProperties->vtbl->GetMaxGuestRAM(systemProperties, &maxMemorySize);
                    systemProperties->vtbl->GetMaxBootPosition(systemProperties, &maxBootPosition);
                    systemProperties->vtbl->GetNetworkAdapterCount(systemProperties, &netAdpCnt);
                    systemProperties->vtbl->GetSerialPortCount(systemProperties, &serialPortCount);
                    systemProperties->vtbl->GetParallelPortCount(systemProperties, &parallelPortCount);
                    systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
                    systemProperties = NULL;
                }
                /* Currently setting memory and maxMemory as same, cause
                 * the notation here seems to be inconsistent while
                 * reading and while dumping xml
                 */
                /* def->maxmem = maxMemorySize * 1024; */
                def->maxmem = memorySize * 1024;

                machine->vtbl->GetCPUCount(machine, &CPUCount);
                def->vcpus = CPUCount;

                /* Skip cpumasklen, cpumask, onReboot, onPoweroff, onCrash */

                def->os.type = strdup("hvm");

                uname(&utsname);
                def->os.arch = strdup(utsname.machine);

                def->os.nBootDevs = 0;
                for (i = 0; (i < VIR_DOMAIN_BOOT_LAST) && (i < maxBootPosition); i++) {
                    PRUint32 device = DeviceType_Null;

                    machine->vtbl->GetBootOrder(machine, i+1, &device);

                    if (device == DeviceType_Floppy) {
                        def->os.bootDevs[i] = VIR_DOMAIN_BOOT_FLOPPY;
                        def->os.nBootDevs++;
                    } else if (device == DeviceType_DVD) {
                        def->os.bootDevs[i] = VIR_DOMAIN_BOOT_CDROM;
                        def->os.nBootDevs++;
                    } else if (device == DeviceType_HardDisk) {
                        def->os.bootDevs[i] = VIR_DOMAIN_BOOT_DISK;
                        def->os.nBootDevs++;
                    } else if (device == DeviceType_Network) {
                        def->os.bootDevs[i] = VIR_DOMAIN_BOOT_NET;
                        def->os.nBootDevs++;
                    } else if (device == DeviceType_USB) {
                        /* Not supported by libvirt yet */
                    } else if (device == DeviceType_SharedFolder) {
                        /* Not supported by libvirt yet */
                    }
                }

                def->features = 0;
                machine->vtbl->GetPAEEnabled(machine, &PAEEnabled);
                if (PAEEnabled) {
                    def->features = def->features | (1 << VIR_DOMAIN_FEATURE_PAE);
                }

                machine->vtbl->GetBIOSSettings(machine, &bios);
                if (bios) {
                    bios->vtbl->GetACPIEnabled(bios, &ACPIEnabled);
                    if (ACPIEnabled) {
                        def->features = def->features | (1 << VIR_DOMAIN_FEATURE_ACPI);
                    }

                    bios->vtbl->GetIOAPICEnabled(bios, &IOAPICEnabled);
                    if (IOAPICEnabled) {
                        def->features = def->features | (1 << VIR_DOMAIN_FEATURE_APIC);
                    }

                    bios->vtbl->nsisupports.Release((nsISupports *)bios);
                }

                /* Currently VirtualBox always uses locatime
                 * so locatime is always true here */
                def->localtime = 1;

1481 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
                /* dump display options vrdp/gui/sdl */
                {
                    int vrdpPresent           = 0;
                    int sdlPresent            = 0;
                    int guiPresent            = 0;
                    int totalPresent          = 0;
                    char *guiDisplay          = NULL;
                    char *sdlDisplay          = NULL;
                    PRUnichar *keyTypeUtf16   = NULL;
                    PRUnichar *valueTypeUtf16 = NULL;
                    char      *valueTypeUtf8  = NULL;

                    def->ngraphics = 0;

                    data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Type", &keyTypeUtf16);
                    machine->vtbl->GetExtraData(machine, keyTypeUtf16, &valueTypeUtf16);
                    data->pFuncs->pfnUtf16Free(keyTypeUtf16);

                    if (valueTypeUtf16) {
                        data->pFuncs->pfnUtf16ToUtf8(valueTypeUtf16, &valueTypeUtf8);
                        data->pFuncs->pfnUtf16Free(valueTypeUtf16);

                        if ( STREQ(valueTypeUtf8, "sdl") || STREQ(valueTypeUtf8, "gui") ) {
                            PRUnichar *keyDislpayUtf16   = NULL;
                            PRUnichar *valueDisplayUtf16 = NULL;
                            char      *valueDisplayUtf8  = NULL;

                            data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Display", &keyDislpayUtf16);
                            machine->vtbl->GetExtraData(machine, keyDislpayUtf16, &valueDisplayUtf16);
                            data->pFuncs->pfnUtf16Free(keyDislpayUtf16);

                            if (valueDisplayUtf16) {
                                data->pFuncs->pfnUtf16ToUtf8(valueDisplayUtf16, &valueDisplayUtf8);
                                data->pFuncs->pfnUtf16Free(valueDisplayUtf16);

                                if (strlen(valueDisplayUtf8) <= 0) {
                                    data->pFuncs->pfnUtf8Free(valueDisplayUtf8);
                                    valueDisplayUtf8 = NULL;
                                }
1520 1521
                            }

1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
                            if (STREQ(valueTypeUtf8, "sdl")) {
                                sdlPresent = 1;
                                if (valueDisplayUtf8)
                                    sdlDisplay = strdup(valueDisplayUtf8);
                                if (sdlDisplay == NULL) {
                                    vboxError(dom->conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                                    /* just don't go to cleanup yet as it is ok to have
                                     * sdlDisplay as NULL and we check it below if it
                                     * exist and then only use it there
                                     */
                                }
                                totalPresent++;
1534 1535
                            }

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
                            if (STREQ(valueTypeUtf8, "gui")) {
                                guiPresent = 1;
                                if (valueDisplayUtf8)
                                    guiDisplay = strdup(valueDisplayUtf8);
                                if (guiDisplay == NULL) {
                                    vboxError(dom->conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                                    /* just don't go to cleanup yet as it is ok to have
                                     * guiDisplay as NULL and we check it below if it
                                     * exist and then only use it there
                                     */
                                }
                                totalPresent++;
                            }
                            if (valueDisplayUtf8)
                                data->pFuncs->pfnUtf8Free(valueDisplayUtf8);
                        }
1552

1553 1554
                        if (STREQ(valueTypeUtf8, "vrdp"))
                            vrdpPresent = 1;
1555

1556 1557
                        data->pFuncs->pfnUtf8Free(valueTypeUtf8);
                    }
1558

1559 1560 1561 1562 1563 1564 1565
                    if ((totalPresent > 0) && (VIR_ALLOC_N(def->graphics, totalPresent) >= 0)) {
                        if ((guiPresent) && (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0)) {
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP;
                            if (guiDisplay)
                                def->graphics[def->ngraphics]->data.desktop.display = guiDisplay;
                            def->ngraphics++;
                        }
1566

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
                        if ((sdlPresent) && (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0)) {
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_SDL;
                            if (sdlDisplay)
                                def->graphics[def->ngraphics]->data.sdl.display = sdlDisplay;
                            def->ngraphics++;
                        }
                    } else if ((vrdpPresent != 1) && (totalPresent == 0) && (VIR_ALLOC_N(def->graphics, 1) >= 0)) {
                        if (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0) {
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP;
                            def->graphics[def->ngraphics]->data.desktop.display = strdup(getenv("DISPLAY"));
                            if (def->graphics[def->ngraphics]->data.desktop.display == NULL) {
                                vboxError(dom->conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                                /* just don't go to cleanup yet as it is ok to have
                                 * display as NULL
                                 */
1582
                            }
1583 1584 1585 1586 1587 1588 1589 1590 1591
                            totalPresent++;
                            def->ngraphics++;
                        }
                    }

                    machine->vtbl->GetVRDPServer(machine, &VRDPServer);
                    if (VRDPServer) {
                        VRDPServer->vtbl->GetEnabled(VRDPServer, &VRDPEnabled);
                        if (VRDPEnabled) {
1592

1593
                            totalPresent++;
1594

1595 1596 1597 1598 1599 1600 1601
                            if ((VIR_REALLOC_N(def->graphics, totalPresent) >= 0) &&
                                (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0)) {
                                PRUint32 VRDPport            = 0;
                                PRUnichar *netAddressUtf16   = NULL;
                                char      *netAddressUtf8    = NULL;
                                PRBool allowMultiConnection  = PR_FALSE;
                                PRBool reuseSingleConnection = PR_FALSE;
1602

1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
                                def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;

                                VRDPServer->vtbl->GetPort(VRDPServer, &VRDPport);
                                if (VRDPport) {
                                    def->graphics[def->ngraphics]->data.rdp.port = VRDPport;
                                } else {
                                    def->graphics[def->ngraphics]->data.rdp.autoport = 1;
                                }

                                VRDPServer->vtbl->GetNetAddress(VRDPServer, &netAddressUtf16);
                                if (netAddressUtf16) {
                                    data->pFuncs->pfnUtf16ToUtf8(netAddressUtf16, &netAddressUtf8);
                                    if (STRNEQ(netAddressUtf8, ""))
                                            def->graphics[def->ngraphics]->data.rdp.listenAddr = strdup(netAddressUtf8);
                                    data->pFuncs->pfnUtf16Free(netAddressUtf16);
                                    data->pFuncs->pfnUtf8Free(netAddressUtf8);
                                }

                                VRDPServer->vtbl->GetAllowMultiConnection(VRDPServer, &allowMultiConnection);
                                if (allowMultiConnection) {
                                    def->graphics[def->ngraphics]->data.rdp.multiUser = 1;
                                }
1625

1626 1627 1628
                                VRDPServer->vtbl->GetReuseSingleConnection(VRDPServer, &reuseSingleConnection);
                                if (reuseSingleConnection) {
                                    def->graphics[def->ngraphics]->data.rdp.replaceUser = 1;
1629
                                }
1630 1631

                                def->ngraphics++;
1632 1633
                            }
                        }
1634
                        VRDPServer->vtbl->nsisupports.Release((nsISupports *)VRDPServer);
1635 1636 1637 1638
                    }
                }

                /* dump IDE hdds if present */
1639
                data->pFuncs->pfnUtf8ToUtf16(hddBus, &hddBusUtf16);
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
                VIR_FREE(hddBus);

                def->ndisks = 0;
                machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 0,  &hardDiskPM);
                if (hardDiskPM)
                    def->ndisks++;

                machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 1,  &hardDiskPS);
                if (hardDiskPS)
                    def->ndisks++;

                machine->vtbl->GetHardDisk(machine, hddBusUtf16, 1, 1,  &hardDiskSS);
                if (hardDiskSS)
                    def->ndisks++;

1655
                data->pFuncs->pfnUtf16Free(hddBusUtf16);
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672

                if ((def->ndisks > 0) && (VIR_ALLOC_N(def->disks, def->ndisks) >= 0)) {
                    for (i = 0; i < def->ndisks; i++) {
                        if (VIR_ALLOC(def->disks[i]) >= 0) {
                            def->disks[i]->device = VIR_DOMAIN_DISK_DEVICE_DISK;
                            def->disks[i]->bus = VIR_DOMAIN_DISK_BUS_IDE;
                            def->disks[i]->type = VIR_DOMAIN_DISK_TYPE_FILE;
                        }
                    }
                }

                if (hardDiskPM) {
                    PRUnichar *hddlocationUtf16 = NULL;
                    char *hddlocation           = NULL;
                    PRUint32 hddType            = HardDiskType_Normal;

                    hardDiskPM->vtbl->imedium.GetLocation((IMedium *)hardDiskPM, &hddlocationUtf16);
1673
                    data->pFuncs->pfnUtf16ToUtf8(hddlocationUtf16, &hddlocation);
1674 1675 1676 1677 1678 1679 1680 1681 1682

                    hardDiskPM->vtbl->GetType(hardDiskPM, &hddType);

                    if (hddType == HardDiskType_Immutable)
                        def->disks[hddNum]->readonly = 1;
                    def->disks[hddNum]->src = strdup(hddlocation);
                    def->disks[hddNum]->dst = strdup("hda");
                    hddNum++;

1683 1684
                    data->pFuncs->pfnUtf8Free(hddlocation);
                    data->pFuncs->pfnUtf16Free(hddlocationUtf16);
1685 1686 1687 1688 1689 1690 1691 1692 1693
                    hardDiskPM->vtbl->imedium.nsisupports.Release((nsISupports *)hardDiskPM);
                }

                if (hardDiskPS) {
                    PRUnichar *hddlocationUtf16 = NULL;
                    char *hddlocation           = NULL;
                    PRUint32 hddType            = HardDiskType_Normal;

                    hardDiskPS->vtbl->imedium.GetLocation((IMedium *)hardDiskPS, &hddlocationUtf16);
1694
                    data->pFuncs->pfnUtf16ToUtf8(hddlocationUtf16, &hddlocation);
1695 1696 1697 1698 1699 1700 1701 1702 1703

                    hardDiskPS->vtbl->GetType(hardDiskPS, &hddType);

                    if (hddType == HardDiskType_Immutable)
                        def->disks[hddNum]->readonly = 1;
                    def->disks[hddNum]->src = strdup(hddlocation);
                    def->disks[hddNum]->dst = strdup("hdb");
                    hddNum++;

1704 1705
                    data->pFuncs->pfnUtf8Free(hddlocation);
                    data->pFuncs->pfnUtf16Free(hddlocationUtf16);
1706 1707 1708 1709 1710 1711 1712 1713 1714
                    hardDiskPS->vtbl->imedium.nsisupports.Release((nsISupports *)hardDiskPS);
                }

                if (hardDiskSS) {
                    PRUnichar *hddlocationUtf16 = NULL;
                    char *hddlocation           = NULL;
                    PRUint32 hddType            = HardDiskType_Normal;

                    hardDiskSS->vtbl->imedium.GetLocation((IMedium *)hardDiskSS, &hddlocationUtf16);
1715
                    data->pFuncs->pfnUtf16ToUtf8(hddlocationUtf16, &hddlocation);
1716 1717 1718 1719 1720 1721 1722 1723 1724

                    hardDiskSS->vtbl->GetType(hardDiskSS, &hddType);

                    if (hddType == HardDiskType_Immutable)
                        def->disks[hddNum]->readonly = 1;
                    def->disks[hddNum]->src = strdup(hddlocation);
                    def->disks[hddNum]->dst = strdup("hdd");
                    hddNum++;

1725 1726
                    data->pFuncs->pfnUtf8Free(hddlocation);
                    data->pFuncs->pfnUtf16Free(hddlocationUtf16);
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
                    hardDiskSS->vtbl->imedium.nsisupports.Release((nsISupports *)hardDiskSS);
                }

                /* dump network cards if present */
                def->nnets = 0;
                /* Get which network cards are enabled */
                for (i = 0; i < netAdpCnt; i++) {
                    INetworkAdapter *adapter = NULL;

                    machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
                    if (adapter) {
                        PRBool enabled = PR_FALSE;

                        adapter->vtbl->GetEnabled(adapter, &enabled);
                        if (enabled) {
                            def->nnets++;
                        }

                        adapter->vtbl->nsisupports.Release((nsISupports *)adapter);
                    }
                }

                /* Allocate memory for the networkcards which are enabled */
                if ((def->nnets > 0) && (VIR_ALLOC_N(def->nets, def->nnets) >= 0)) {
                    for (i = 0; i < def->nnets; i++) {
                        if (VIR_ALLOC(def->nets[i]) >= 0) {
                        }
                    }
                }

                /* Now get the details about the network cards here */
                for (i = 0;(netAdpIncCnt < def->nnets) && (i < netAdpCnt); i++) {
                    INetworkAdapter *adapter = NULL;

                    machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
                    if (adapter) {
                        PRBool enabled = PR_FALSE;

                        adapter->vtbl->GetEnabled(adapter, &enabled);
                        if (enabled) {
                            PRUint32 attachmentType    = NetworkAttachmentType_Null;
                            PRUint32 adapterType       = NetworkAdapterType_Null;
                            PRUnichar *MACAddressUtf16 = NULL;
                            char *MACAddress           = NULL;
                            char macaddr[VIR_MAC_STRING_BUFLEN] = {0};

                            adapter->vtbl->GetAttachmentType(adapter, &attachmentType);
                            if (attachmentType == NetworkAttachmentType_NAT) {

                                def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_USER;

                            } else if (attachmentType == NetworkAttachmentType_Bridged) {
                                PRUnichar *hostIntUtf16 = NULL;
                                char *hostInt           = NULL;

                                def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_BRIDGE;

                                adapter->vtbl->GetHostInterface(adapter, &hostIntUtf16);

1786
                                data->pFuncs->pfnUtf16ToUtf8(hostIntUtf16, &hostInt);
1787 1788
                                def->nets[netAdpIncCnt]->data.bridge.brname = strdup(hostInt);

1789 1790
                                data->pFuncs->pfnUtf8Free(hostInt);
                                data->pFuncs->pfnUtf16Free(hostIntUtf16);
1791 1792 1793 1794 1795 1796 1797 1798 1799

                            } else if (attachmentType == NetworkAttachmentType_Internal) {
                                PRUnichar *intNetUtf16 = NULL;
                                char *intNet           = NULL;

                                def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_INTERNAL;

                                adapter->vtbl->GetInternalNetwork(adapter, &intNetUtf16);

1800
                                data->pFuncs->pfnUtf16ToUtf8(intNetUtf16, &intNet);
1801 1802
                                def->nets[netAdpIncCnt]->data.internal.name = strdup(intNet);

1803 1804
                                data->pFuncs->pfnUtf8Free(intNet);
                                data->pFuncs->pfnUtf16Free(intNetUtf16);
1805 1806 1807 1808 1809

                            } else if (attachmentType == NetworkAttachmentType_HostOnly) {
                                PRUnichar *hostIntUtf16 = NULL;
                                char *hostInt           = NULL;

1810
                                def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_NETWORK;
1811 1812 1813

                                adapter->vtbl->GetHostInterface(adapter, &hostIntUtf16);

1814
                                data->pFuncs->pfnUtf16ToUtf8(hostIntUtf16, &hostInt);
1815
                                def->nets[netAdpIncCnt]->data.network.name = strdup(hostInt);
1816

1817 1818
                                data->pFuncs->pfnUtf8Free(hostInt);
                                data->pFuncs->pfnUtf16Free(hostIntUtf16);
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840

                            } else {
                                /* default to user type i.e. NAT in VirtualBox if this
                                 * dump is ever used to create a machine.
                                 */
                                def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_USER;
                            }

                            adapter->vtbl->GetAdapterType(adapter, &adapterType);
                            if (adapterType == NetworkAdapterType_Am79C970A) {
                                def->nets[netAdpIncCnt]->model = strdup("Am79C970A");
                            } else if (adapterType == NetworkAdapterType_Am79C973) {
                                def->nets[netAdpIncCnt]->model = strdup("Am79C973");
                            } else if (adapterType == NetworkAdapterType_I82540EM) {
                                def->nets[netAdpIncCnt]->model = strdup("82540EM");
                            } else if (adapterType == NetworkAdapterType_I82545EM) {
                                def->nets[netAdpIncCnt]->model = strdup("82545EM");
                            } else if (adapterType == NetworkAdapterType_I82543GC) {
                                def->nets[netAdpIncCnt]->model = strdup("82543GC");
                            }

                            adapter->vtbl->GetMACAddress(adapter, &MACAddressUtf16);
1841
                            data->pFuncs->pfnUtf16ToUtf8(MACAddressUtf16, &MACAddress);
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
                            snprintf(macaddr, VIR_MAC_STRING_BUFLEN,
                                     "%c%c:%c%c:%c%c:%c%c:%c%c:%c%c",
                                     MACAddress[0], MACAddress[1], MACAddress[2], MACAddress[3],
                                     MACAddress[4], MACAddress[5], MACAddress[6], MACAddress[7],
                                     MACAddress[8], MACAddress[9], MACAddress[10], MACAddress[11]);

                            virParseMacAddr(macaddr, def->nets[netAdpIncCnt]->mac);

                            netAdpIncCnt++;

1852 1853
                            data->pFuncs->pfnUtf16Free(MACAddressUtf16);
                            data->pFuncs->pfnUtf8Free(MACAddress);
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
                        }

                        adapter->vtbl->nsisupports.Release((nsISupports *)adapter);
                    }
                }

                /* dump sound card if active */

                /* Set def->nsounds to one as VirtualBox currently supports
                 * only one sound card
                 */

                machine->vtbl->GetAudioAdapter(machine, &audioAdapter);
                if (audioAdapter) {
                    PRBool enabled = PR_FALSE;

                    audioAdapter->vtbl->GetEnabled(audioAdapter, &enabled);
                    if (enabled) {
                        PRUint32 audioController = AudioControllerType_AC97;

                        def->nsounds = 1;
                        if (VIR_ALLOC_N(def->sounds, def->nsounds) >= 0) {
                            if (VIR_ALLOC(def->sounds[0]) >= 0) {
                                audioAdapter->vtbl->GetAudioController(audioAdapter, &audioController);
                                if (audioController == AudioControllerType_SB16) {
                                    def->sounds[0]->model = VIR_DOMAIN_SOUND_MODEL_SB16;
                                } else if (audioController == AudioControllerType_AC97) {
                                    def->sounds[0]->model = VIR_DOMAIN_SOUND_MODEL_ES97;
                                }
                            } else {
                                VIR_FREE(def->sounds);
                                def->nsounds = 0;
                            }
                        } else {
                            def->nsounds = 0;
                        }
                    }
                    audioAdapter->vtbl->nsisupports.Release((nsISupports *)audioAdapter);
                }

                /* dump CDROM/DVD if the drive is attached and has DVD/CD in it */
                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                if (dvdDrive) {
                    PRUint32 state = DriveState_Null;

                    dvdDrive->vtbl->GetState(dvdDrive, &state);
                    if (state == DriveState_ImageMounted) {
                        IDVDImage *dvdImage = NULL;

                        dvdDrive->vtbl->GetImage(dvdDrive, &dvdImage);
                        if (dvdImage) {
                            PRUnichar *locationUtf16 = NULL;
                            char *location           = NULL;

                            dvdImage->vtbl->imedium.GetLocation((IMedium *)dvdImage, &locationUtf16);
1909
                            data->pFuncs->pfnUtf16ToUtf8(locationUtf16, &location);
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926

                            def->ndisks++;
                            if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
                                if (VIR_ALLOC(def->disks[def->ndisks - 1]) >= 0) {
                                    def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
                                    def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_IDE;
                                    def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE;
                                    def->disks[def->ndisks - 1]->readonly = 1;
                                    def->disks[def->ndisks - 1]->src = strdup(location);
                                    def->disks[def->ndisks - 1]->dst = strdup("hdc");
                                } else {
                                    def->ndisks--;
                                }
                            } else {
                                def->ndisks--;
                            }

1927 1928
                            data->pFuncs->pfnUtf8Free(location);
                            data->pFuncs->pfnUtf16Free(locationUtf16);
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
                            dvdImage->vtbl->imedium.nsisupports.Release((nsISupports *)dvdImage);
                        }
                    }
                    dvdDrive->vtbl->nsisupports.Release((nsISupports *)dvdDrive);
                }

                /* dump Floppy if the drive is attached and has floppy in it */
                machine->vtbl->GetFloppyDrive(machine, &floppyDrive);
                if (floppyDrive) {
                    PRBool enabled = PR_FALSE;

                    floppyDrive->vtbl->GetEnabled(floppyDrive, &enabled);
                    if (enabled) {
                        PRUint32 state = DriveState_Null;

                        floppyDrive->vtbl->GetState(floppyDrive, &state);
                        if (state == DriveState_ImageMounted) {
                            IFloppyImage *floppyImage = NULL;

                            floppyDrive->vtbl->GetImage(floppyDrive, &floppyImage);
                            if (floppyImage) {
                                PRUnichar *locationUtf16 = NULL;
                                char *location           = NULL;

                                floppyImage->vtbl->imedium.GetLocation((IMedium *)floppyImage, &locationUtf16);
1954
                                data->pFuncs->pfnUtf16ToUtf8(locationUtf16, &location);
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971

                                def->ndisks++;
                                if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
                                    if (VIR_ALLOC(def->disks[def->ndisks - 1]) >= 0) {
                                        def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                                        def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC;
                                        def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE;
                                        def->disks[def->ndisks - 1]->readonly = 0;
                                        def->disks[def->ndisks - 1]->src = strdup(location);
                                        def->disks[def->ndisks - 1]->dst = strdup("fda");
                                    } else {
                                        def->ndisks--;
                                    }
                                } else {
                                    def->ndisks--;
                                }

1972 1973
                                data->pFuncs->pfnUtf8Free(location);
                                data->pFuncs->pfnUtf16Free(locationUtf16);
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
                                floppyImage->vtbl->imedium.nsisupports.Release((nsISupports *)floppyImage);
                            }
                        }
                    }

                    floppyDrive->vtbl->nsisupports.Release((nsISupports *)floppyDrive);
                }

                /* dump serial port if active */
                def->nserials = 0;
                /* Get which serial ports are enabled/active */
                for (i = 0; i < serialPortCount; i++) {
                    ISerialPort *serialPort = NULL;

                    machine->vtbl->GetSerialPort(machine, i, &serialPort);
                    if (serialPort) {
                        PRBool enabled = PR_FALSE;

                        serialPort->vtbl->GetEnabled(serialPort, &enabled);
                        if (enabled) {
                            def->nserials++;
                        }

                        serialPort->vtbl->nsisupports.Release((nsISupports *)serialPort);
                    }
                }

                /* Allocate memory for the serial ports which are enabled */
                if ((def->nserials > 0) && (VIR_ALLOC_N(def->serials, def->nserials) >= 0)) {
                    for (i = 0; i < def->nserials; i++) {
                        if (VIR_ALLOC(def->serials[i]) >= 0) {
                        }
                    }
                }

                /* Now get the details about the serial ports here */
                for (i = 0;(serialPortIncCount < def->nserials) && (i < serialPortCount); i++) {
                    ISerialPort *serialPort = NULL;

                    machine->vtbl->GetSerialPort(machine, i, &serialPort);
                    if (serialPort) {
                        PRBool enabled = PR_FALSE;

                        serialPort->vtbl->GetEnabled(serialPort, &enabled);
                        if (enabled) {
                            PRUint32 hostMode    = PortMode_Disconnected;
                            PRUint32 IOBase      = 0;
                            PRUint32 IRQ         = 0;
                            PRUnichar *pathUtf16 = NULL;
                            char *path           = NULL;

                            serialPort->vtbl->GetHostMode(serialPort, &hostMode);
                            if (hostMode == PortMode_HostPipe) {
                                def->serials[serialPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_PIPE;
                            } else if (hostMode == PortMode_HostDevice) {
                                def->serials[serialPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_DEV;
                            } else {
                                def->serials[serialPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_NULL;
                            }

                            serialPort->vtbl->GetIRQ(serialPort, &IRQ);
                            serialPort->vtbl->GetIOBase(serialPort, &IOBase);
                            if ((IRQ == 4) && (IOBase == 1016)) {
                                def->serials[serialPortIncCount]->dstPort = 0;
                            } else if ((IRQ == 3) && (IOBase == 760)) {
                                def->serials[serialPortIncCount]->dstPort = 1;
                            }

                            serialPort->vtbl->GetPath(serialPort, &pathUtf16);

2044
                            data->pFuncs->pfnUtf16ToUtf8(pathUtf16, &path);
2045 2046 2047 2048
                            def->serials[serialPortIncCount]->data.file.path = strdup(path);

                            serialPortIncCount++;

2049 2050
                            data->pFuncs->pfnUtf16Free(pathUtf16);
                            data->pFuncs->pfnUtf8Free(path);
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110
                        }

                        serialPort->vtbl->nsisupports.Release((nsISupports *)serialPort);
                    }
                }

                /* dump parallel ports if active */
                def->nparallels = 0;
                /* Get which parallel ports are enabled/active */
                for (i = 0; i < parallelPortCount; i++) {
                    IParallelPort *parallelPort = NULL;

                    machine->vtbl->GetParallelPort(machine, i, &parallelPort);
                    if (parallelPort) {
                        PRBool enabled = PR_FALSE;

                        parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                        if (enabled) {
                            def->nparallels++;
                        }

                        parallelPort->vtbl->nsisupports.Release((nsISupports *)parallelPort);
                    }
                }

                /* Allocate memory for the parallel ports which are enabled */
                if ((def->nparallels > 0) && (VIR_ALLOC_N(def->parallels, def->nparallels) >= 0)) {
                    for (i = 0; i < def->nparallels; i++) {
                        if (VIR_ALLOC(def->parallels[i]) >= 0) {
                        }
                    }
                }

                /* Now get the details about the parallel ports here */
                for (i = 0;(parallelPortIncCount < def->nparallels) && (i < parallelPortCount); i++) {
                    IParallelPort *parallelPort = NULL;

                    machine->vtbl->GetParallelPort(machine, i, &parallelPort);
                    if (parallelPort) {
                        PRBool enabled = PR_FALSE;

                        parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                        if (enabled) {
                            PRUint32 IOBase      = 0;
                            PRUint32 IRQ         = 0;
                            PRUnichar *pathUtf16 = NULL;
                            char *path           = NULL;

                            parallelPort->vtbl->GetIRQ(parallelPort, &IRQ);
                            parallelPort->vtbl->GetIOBase(parallelPort, &IOBase);
                            if ((IRQ == 7) && (IOBase == 888)) {
                                def->parallels[parallelPortIncCount]->dstPort = 0;
                            } else if ((IRQ == 5) && (IOBase == 632)) {
                                def->parallels[parallelPortIncCount]->dstPort = 1;
                            }

                            def->parallels[parallelPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_FILE;

                            parallelPort->vtbl->GetPath(parallelPort, &pathUtf16);

2111
                            data->pFuncs->pfnUtf16ToUtf8(pathUtf16, &path);
2112 2113 2114 2115
                            def->parallels[parallelPortIncCount]->data.file.path = strdup(path);

                            parallelPortIncCount++;

2116 2117
                            data->pFuncs->pfnUtf16Free(pathUtf16);
                            data->pFuncs->pfnUtf8Free(path);
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
                        }

                        parallelPort->vtbl->nsisupports.Release((nsISupports *)parallelPort);
                    }
                }

                /* dump USB devices/filters if active */
                def->nhostdevs = 0;
                machine->vtbl->GetUSBController(machine, &USBController);
                if (USBController) {
                    PRBool enabled = PR_FALSE;

                    USBController->vtbl->GetEnabled(USBController, &enabled);
                    if (enabled) {
                        PRUint32 deviceFiltersNum        = 0;
                        IUSBDeviceFilter **deviceFilters = NULL;

                        USBController->vtbl->GetDeviceFilters(USBController,
                                                              &deviceFiltersNum,
                                                              &deviceFilters);

                        if (deviceFiltersNum > 0) {

                            /* check if the filters are active and then only
                             * alloc mem and set def->nhostdevs
                             */

                            for(i = 0; i < deviceFiltersNum; i++) {
                                PRBool active = PR_FALSE;

                                deviceFilters[i]->vtbl->GetActive(deviceFilters[i], &active);
                                if (active) {
                                    def->nhostdevs++;
                                }
                            }

                            if (def->nhostdevs > 0) {
                                /* Alloc mem needed for the filters now */
                                if (VIR_ALLOC_N(def->hostdevs, def->nhostdevs) >= 0) {

                                    for(i = 0; (USBFilterCount < def->nhostdevs) || (i < deviceFiltersNum); i++) {
                                        PRBool active = PR_FALSE;

                                        deviceFilters[i]->vtbl->GetActive(deviceFilters[i], &active);
                                        if (active) {
                                            if (VIR_ALLOC(def->hostdevs[USBFilterCount]) >= 0) {
                                                PRUnichar *vendorIdUtf16  = NULL;
                                                char *vendorIdUtf8        = NULL;
                                                unsigned vendorId         = 0;
                                                PRUnichar *productIdUtf16 = NULL;
                                                char *productIdUtf8       = NULL;
                                                unsigned productId        = 0;
                                                char *endptr              = NULL;

                                                def->hostdevs[USBFilterCount]->mode =
                                                    VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
                                                def->hostdevs[USBFilterCount]->source.subsys.type =
                                                    VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB;

                                                deviceFilters[i]->vtbl->GetVendorId(deviceFilters[i], &vendorIdUtf16);
                                                deviceFilters[i]->vtbl->GetProductId(deviceFilters[i], &productIdUtf16);

2180 2181
                                                data->pFuncs->pfnUtf16ToUtf8(vendorIdUtf16, &vendorIdUtf8);
                                                data->pFuncs->pfnUtf16ToUtf8(productIdUtf16, &productIdUtf8);
2182 2183 2184 2185 2186 2187 2188

                                                vendorId  = strtol(vendorIdUtf8, &endptr, 16);
                                                productId = strtol(productIdUtf8, &endptr, 16);

                                                def->hostdevs[USBFilterCount]->source.subsys.u.usb.vendor  = vendorId;
                                                def->hostdevs[USBFilterCount]->source.subsys.u.usb.product = productId;

2189 2190
                                                data->pFuncs->pfnUtf16Free(vendorIdUtf16);
                                                data->pFuncs->pfnUtf8Free(vendorIdUtf8);
2191

2192 2193
                                                data->pFuncs->pfnUtf16Free(productIdUtf16);
                                                data->pFuncs->pfnUtf8Free(productIdUtf8);
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 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 2262 2263 2264 2265

                                                USBFilterCount++;
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        /* Cleanup */
                        for(i = 0; i < deviceFiltersNum; i++) {
                            if (deviceFilters[i])
                                deviceFilters[i]->vtbl->nsisupports.Release((nsISupports *)deviceFilters[i]);
                        }
                    }
                    USBController->vtbl->nsisupports.Release((nsISupports *)USBController);
                }

                /* all done so set gotAllABoutDef and pass def to virDomainDefFormat
                 * to generate XML for it
                 */
                gotAllABoutDef = 0;
            }
            machine->vtbl->nsisupports.Release((nsISupports *)machine);
            machine = NULL;
        }
    }

    if (gotAllABoutDef == 0)
        ret = virDomainDefFormat(dom->conn, def, flags);

cleanup:
    VIR_FREE(iid);
    virDomainDefFree(def);
    return ret;
}

static int vboxListDefinedDomains(virConnectPtr conn, char ** const names, int maxnames) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
    int ret = -1;
    int i, j;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of Defined Domains",(unsigned)rc);
            goto cleanup;
        }

        if (machineCnt == 0) {
            ret = 0;
            goto cleanup;
        }

        for (i = 0,j = 0; (i < machineCnt) && (j < maxnames); i++) {
            IMachine *machine = machines[i];

            if (machine) {
                PRBool isAccessible = PR_FALSE;
                machine->vtbl->GetAccessible(machine, &isAccessible);
                if (isAccessible) {
                    machine->vtbl->GetState(machine, &state);
                    if ((state != MachineState_Running) &&
                        (state != MachineState_Paused) ) {
                        machine->vtbl->GetName(machine, &machineNameUtf16);
2266
                        data->pFuncs->pfnUtf16ToUtf8(machineNameUtf16, &machineName);
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
                        if (!(names[j++] = strdup(machineName))) {
                            virReportOOMError(conn);
                            for ( ; j >= 0 ; j--)
                                VIR_FREE(names[j]);
                            ret = -1;
                            goto cleanup;
                        }
                        ret++;
                    }
                }
            }
        }
        ret++;
    }

cleanup:
2283 2284
    data->pFuncs->pfnUtf8Free(machineName);
    data->pFuncs->pfnUtf16Free(machineNameUtf16);
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 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
    for (i = 0; i < machineCnt; ++i)
        if (machines[i])
            machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
    return ret;
}

static int vboxNumOfDefinedDomains(virConnectPtr conn) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    PRUint32 state       = MachineState_Null;
    int ret = -1;
    int i;

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get number of Defined Domains",(unsigned)rc);
            goto cleanup;
        }

        if (machineCnt == 0) {
            ret = 0;
            goto cleanup;
        }

        /* Do the cleanup as required by GetMachines() */
        for (i = 0; i < machineCnt; ++i) {
            IMachine *machine = machines[i];

            if (machine) {
                PRBool isAccessible = PR_FALSE;
                machine->vtbl->GetAccessible(machine, &isAccessible);
                if (isAccessible) {
                    machine->vtbl->GetState(machine, &state);
                    if ((state != MachineState_Running) &&
                        (state != MachineState_Paused) ) {
                        ret++;
                    }
                }
            }
        }
        ret++;
    }

cleanup:
    for (i = 0; i < machineCnt; ++i)
        if (machines[i])
            machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
    return ret;
}

static int vboxDomainCreate(virDomainPtr dom) {
    nsresult rc;
    vboxGlobalData *data   = dom->conn->privateData;
    IMachine **machines    = NULL;
    IProgress *progress    = NULL;
    PRUint32 machineCnt    = 0;
    PRUnichar *env         = NULL;
    PRUnichar *sessionType = NULL;
    char displayutf8[32]   = {0};
    unsigned char iidl[VIR_UUID_BUFLEN] = {0};
    int i, ret = -1;


    if (!dom->name) {
        vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s",
                  "Error while reading the domain name");
        goto cleanup;
    }

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachines(data->vboxObj, &machineCnt, &machines);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "Could not get list of machines",(unsigned)rc);
            goto cleanup;
        }

        for (i = 0; i < machineCnt; ++i) {
            IMachine *machine = machines[i];
            PRBool isAccessible = PR_FALSE;

            if (!machine)
                continue;

            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                nsID *iid = NULL;

                machine->vtbl->GetId(machine, &iid);
                if (!iid)
                    continue;
                nsIDtoChar(iidl, iid);

                if (memcmp(dom->uuid, iidl, VIR_UUID_BUFLEN) == 0) {
                    PRUint32 state = MachineState_Null;
                    machine->vtbl->GetState(machine, &state);

                    if ( (state == MachineState_PoweredOff) ||
                         (state == MachineState_Saved) ||
                         (state == MachineState_Aborted) ) {
2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488
                        int vrdpPresent              = 0;
                        int sdlPresent               = 0;
                        int guiPresent               = 0;
                        char *guiDisplay             = NULL;
                        char *sdlDisplay             = NULL;
                        PRUnichar *keyTypeUtf16      = NULL;
                        PRUnichar *valueTypeUtf16    = NULL;
                        char      *valueTypeUtf8     = NULL;
                        PRUnichar *keyDislpayUtf16   = NULL;
                        PRUnichar *valueDisplayUtf16 = NULL;
                        char      *valueDisplayUtf8  = NULL;

                        data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Type", &keyTypeUtf16);
                        machine->vtbl->GetExtraData(machine, keyTypeUtf16, &valueTypeUtf16);
                        data->pFuncs->pfnUtf16Free(keyTypeUtf16);

                        if (valueTypeUtf16) {
                            data->pFuncs->pfnUtf16ToUtf8(valueTypeUtf16, &valueTypeUtf8);
                            data->pFuncs->pfnUtf16Free(valueTypeUtf16);

                            if ( STREQ(valueTypeUtf8, "sdl") || STREQ(valueTypeUtf8, "gui") ) {

                                data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Display", &keyDislpayUtf16);
                                machine->vtbl->GetExtraData(machine, keyDislpayUtf16, &valueDisplayUtf16);
                                data->pFuncs->pfnUtf16Free(keyDislpayUtf16);

                                if (valueDisplayUtf16) {
                                    data->pFuncs->pfnUtf16ToUtf8(valueDisplayUtf16, &valueDisplayUtf8);
                                    data->pFuncs->pfnUtf16Free(valueDisplayUtf16);

                                    if (strlen(valueDisplayUtf8) <= 0) {
                                        data->pFuncs->pfnUtf8Free(valueDisplayUtf8);
                                        valueDisplayUtf8 = NULL;
                                    }
                                }

                                if (STREQ(valueTypeUtf8, "sdl")) {
                                    sdlPresent = 1;
                                    if (valueDisplayUtf8) {
                                        sdlDisplay = strdup(valueDisplayUtf8);
                                        if (sdlDisplay == NULL) {
                                            vboxError(dom->conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                                            /* just don't go to cleanup yet as it is ok to have
                                             * sdlDisplay as NULL and we check it below if it
                                             * exist and then only use it there
                                             */
                                        }
                                    }
                                }

                                if (STREQ(valueTypeUtf8, "gui")) {
                                    guiPresent = 1;
                                    if (valueDisplayUtf8) {
                                        guiDisplay = strdup(valueDisplayUtf8);
                                        if (guiDisplay == NULL) {
                                            vboxError(dom->conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                                            /* just don't go to cleanup yet as it is ok to have
                                             * guiDisplay as NULL and we check it below if it
                                             * exist and then only use it there
                                             */
                                        }
                                    }
                                }
                            }

                            if (STREQ(valueTypeUtf8, "vrdp")) {
                                vrdpPresent = 1;
                            }

                            data->pFuncs->pfnUtf8Free(valueTypeUtf8);

                        } else {
                            guiPresent = 1;
                        }
                        if (valueDisplayUtf8)
                            data->pFuncs->pfnUtf8Free(valueDisplayUtf8);

                        if (guiPresent) {
                            if (guiDisplay) {
                                sprintf(displayutf8, "DISPLAY=%.24s", guiDisplay);
                                data->pFuncs->pfnUtf8ToUtf16(displayutf8, &env);
                                VIR_FREE(guiDisplay);
                            }

                            data->pFuncs->pfnUtf8ToUtf16("gui", &sessionType);
                        }

                        if (sdlPresent) {
                            if (sdlDisplay) {
                                sprintf(displayutf8, "DISPLAY=%.24s", sdlDisplay);
                                data->pFuncs->pfnUtf8ToUtf16(displayutf8, &env);
                                VIR_FREE(sdlDisplay);
                            }

                            data->pFuncs->pfnUtf8ToUtf16("sdl", &sessionType);
                        }

                        if (vrdpPresent) {
                            data->pFuncs->pfnUtf8ToUtf16("vrdp", &sessionType);
                        }
2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514

                        data->vboxObj->vtbl->OpenRemoteSession(data->vboxObj,
                                                               data->vboxSession,
                                                               iid,
                                                               sessionType,
                                                               env,
                                                               &progress );
                        if (NS_FAILED(rc)) {
                            vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                                      "%s", "openremotesession failed, domain can't be started");
                            ret = -1;
                        } else {
                            PRBool completed = 0;
                            nsresult resultCode;
                            progress->vtbl->WaitForCompletion(progress, -1);
                            rc = progress->vtbl->GetCompleted(progress, &completed);
                            if (NS_FAILED(rc)) {
                                /* error */
                                ret = -1;
                            }
                            progress->vtbl->GetResultCode(progress, &resultCode);
                            if (NS_FAILED(resultCode)) {
                                /* error */
                                ret = -1;
                            } else {
                                /* all ok set the domid */
2515
                                dom->id = i + 1;
2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
                                ret = 0;
                            }
                        }

                        if (progress)
                            progress->vtbl->nsisupports.Release((nsISupports *)progress);

                        data->vboxSession->vtbl->Close(data->vboxSession);

                    } else {
                        vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                                  "%s", "machine is not in poweroff|saved|"
                                        "aborted state, so couldn't start it");
                        ret = -1;
                    }
                }

                if (iid)
2534
                    data->pFuncs->pfnComUnallocMem(iid);
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546
                if (ret != -1)
                    break;
            }
        }

        /* Do the cleanup and take care you dont leak any memory */
        for (i = 0; i < machineCnt; ++i) {
            if (machines[i])
                machines[i]->vtbl->nsisupports.Release((nsISupports *)machines[i]);
        }
    }

2547 2548
    data->pFuncs->pfnUtf16Free(env);
    data->pFuncs->pfnUtf16Free(sessionType);
2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575

cleanup:
    return ret;
}

static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml) {
    nsresult rc;
    vboxGlobalData *data = conn->privateData;
    IMachine *machine   = NULL;
    IBIOSSettings *bios = NULL;
    virDomainPtr dom    = NULL;
    nsID *iid           = NULL;
    nsID *mchiid        = NULL;
    virDomainDefPtr def = NULL;
    PRUnichar *machineNameUtf16 = NULL;

    if (!(def = virDomainDefParseString(conn, data->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
        goto cleanup;
    }

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(conn);
        goto cleanup;
    }

    if (data->vboxObj) {
2576
        data->pFuncs->pfnUtf8ToUtf16(def->name, &machineNameUtf16);
2577 2578 2579 2580 2581 2582 2583
        nsIDFromChar(iid, def->uuid);
        rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                                machineNameUtf16,
                                                NULL,
                                                NULL,
                                                iid,
                                                &machine);
2584
        data->pFuncs->pfnUtf16Free(machineNameUtf16);
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738

        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "could not define a domain",(unsigned)rc);
            goto cleanup;
        }

        rc = machine->vtbl->SetMemorySize(machine, def->memory / 1024);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%lu Kb, rc=%08x",
                      "could not set the memory size of the domain to",
                      def->memory, (unsigned)rc);
        }

        rc = machine->vtbl->SetCPUCount(machine, def->vcpus);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%lu, rc=%08x",
                      "could not set the number of virtual CPUs to",
                      def->vcpus, (unsigned)rc);
        }

        rc = machine->vtbl->SetPAEEnabled(machine, (def->features) &
                                          (1 << VIR_DOMAIN_FEATURE_PAE));
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                      "could not change PAE status to",
                      ((def->features) & (1 << VIR_DOMAIN_FEATURE_PAE))
                      ? "Enabled" : "Disabled", (unsigned)rc);
        }

        machine->vtbl->GetBIOSSettings(machine, &bios);
        if (bios) {
            rc = bios->vtbl->SetACPIEnabled(bios, (def->features) &
                                            (1 << VIR_DOMAIN_FEATURE_ACPI));
            if (NS_FAILED(rc)) {
                vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                          "could not change ACPI status to",
                          ((def->features) & (1 << VIR_DOMAIN_FEATURE_ACPI))
                          ? "Enabled" : "Disabled", (unsigned)rc);
            }
            rc = bios->vtbl->SetIOAPICEnabled(bios, (def->features) &
                                              (1 << VIR_DOMAIN_FEATURE_APIC));
            if (NS_FAILED(rc)) {
                vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                          "could not change APIC status to",
                          ((def->features) & (1 << VIR_DOMAIN_FEATURE_APIC))
                          ? "Enabled" : "Disabled", (unsigned)rc);
            }
            bios->vtbl->nsisupports.Release((nsISupports *)bios);
        }

        /* Register the machine before attaching other devices to it */
        rc = data->vboxObj->vtbl->RegisterMachine(data->vboxObj, machine);
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                      "could not define a domain",(unsigned)rc);
            goto cleanup;
        }

        /* Get the uuid of the machine, currently it is immutable
         * object so open a session to it and get it back, so that
         * you can make changes to the machine setting
         */
        machine->vtbl->GetId(machine, &mchiid);
        data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, mchiid);
        data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);

        {   /* Started:Block to set the boot device order */
            ISystemProperties *systemProperties = NULL;
            PRUint32 maxBootPosition            = 0;
            int i = 0;

            DEBUG("def->os.type             %s", def->os.type);
            DEBUG("def->os.arch             %s", def->os.arch);
            DEBUG("def->os.machine          %s", def->os.machine);
            DEBUG("def->os.nBootDevs        %d", def->os.nBootDevs);
            DEBUG("def->os.bootDevs[0]      %d", def->os.bootDevs[0]);
            DEBUG("def->os.bootDevs[1]      %d", def->os.bootDevs[1]);
            DEBUG("def->os.bootDevs[2]      %d", def->os.bootDevs[2]);
            DEBUG("def->os.bootDevs[3]      %d", def->os.bootDevs[3]);
            DEBUG("def->os.init             %s", def->os.init);
            DEBUG("def->os.kernel           %s", def->os.kernel);
            DEBUG("def->os.initrd           %s", def->os.initrd);
            DEBUG("def->os.cmdline          %s", def->os.cmdline);
            DEBUG("def->os.root             %s", def->os.root);
            DEBUG("def->os.loader           %s", def->os.loader);
            DEBUG("def->os.bootloader       %s", def->os.bootloader);
            DEBUG("def->os.bootloaderArgs   %s", def->os.bootloaderArgs);

            data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                systemProperties->vtbl->GetMaxBootPosition(systemProperties, &maxBootPosition);
                systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
                systemProperties = NULL;
            }

            /* Clear the defaults first */
            for (i = 0; i < maxBootPosition; i++) {
                machine->vtbl->SetBootOrder(machine, i+1, DeviceType_Null);
            }

            for (i = 0; (i < def->os.nBootDevs) && (i < maxBootPosition); i++) {
                PRUint32 device = DeviceType_Null;

                if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_FLOPPY) {
                    device = DeviceType_Floppy;
                } else if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_CDROM) {
                    device = DeviceType_DVD;
                } else if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_DISK) {
                    device = DeviceType_HardDisk;
                } else if (def->os.bootDevs[i] == VIR_DOMAIN_BOOT_NET) {
                    device = DeviceType_Network;
                }
                machine->vtbl->SetBootOrder(machine, i+1, device);
            }
        }   /* Finished:Block to set the boot device order */

        {   /* Started:Block to attach the CDROM/DVD Drive and HardDisks to the VM */

            if (def->ndisks > 0) {
                int i;

                for (i = 0; i < def->ndisks; i++) {
                    DEBUG("disk(%d) type:       %d", i, def->disks[i]->type);
                    DEBUG("disk(%d) device:     %d", i, def->disks[i]->device);
                    DEBUG("disk(%d) bus:        %d", i, def->disks[i]->bus);
                    DEBUG("disk(%d) src:        %s", i, def->disks[i]->src);
                    DEBUG("disk(%d) dst:        %s", i, def->disks[i]->dst);
                    DEBUG("disk(%d) driverName: %s", i, def->disks[i]->driverName);
                    DEBUG("disk(%d) driverType: %s", i, def->disks[i]->driverType);
                    DEBUG("disk(%d) cachemode:  %d", i, def->disks[i]->cachemode);
                    DEBUG("disk(%d) readonly:   %s", i, def->disks[i]->readonly ? "True" : "False");
                    DEBUG("disk(%d) shared:     %s", i, def->disks[i]->shared ? "True" : "False");
                    DEBUG("disk(%d) slotnum:    %d", i, def->disks[i]->slotnum);

                    if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                        if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                            IDVDDrive *dvdDrive = NULL;
                            /* Currently CDROM/DVD Drive is always IDE
                             * Secondary Master so neglecting the following
                             * parameters:
                             *      def->disks[i]->bus
                             *      def->disks[i]->dst
                             */

                            machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                            if (dvdDrive) {
                                IDVDImage *dvdImage     = NULL;
                                PRUnichar *dvdfileUtf16 = NULL;
                                nsID *dvduuid           = NULL;
                                nsID dvdemptyuuid;

                                memset(&dvdemptyuuid, 0, sizeof(dvdemptyuuid));

2739
                                data->pFuncs->pfnUtf8ToUtf16(def->disks[i]->src, &dvdfileUtf16);
2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764

                                data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                if (!dvdImage) {
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, &dvdemptyuuid, &dvdImage);
                                }
                                if (dvdImage) {
                                    rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage, &dvduuid);
                                    if (NS_FAILED(rc)) {
                                        vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                  "can't get the uuid of the file to be attached to cdrom",
                                                  def->disks[i]->src, (unsigned)rc);
                                    } else {
                                        rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid);
                                        if (NS_FAILED(rc)) {
                                            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                      "could not attach the file to cdrom",
                                                      def->disks[i]->src, (unsigned)rc);
                                        } else {
                                            DEBUG("CD/DVDImage UUID:{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                                            (unsigned)dvduuid->m0,    (unsigned)dvduuid->m1, (unsigned)dvduuid->m2,
                                            (unsigned)dvduuid->m3[0], (unsigned)dvduuid->m3[1],
                                            (unsigned)dvduuid->m3[2], (unsigned)dvduuid->m3[3],
                                            (unsigned)dvduuid->m3[4], (unsigned)dvduuid->m3[5],
                                            (unsigned)dvduuid->m3[6], (unsigned)dvduuid->m3[7]);
                                        }
2765
                                        data->pFuncs->pfnComUnallocMem(dvduuid);
2766 2767 2768 2769
                                    }

                                    dvdImage->vtbl->imedium.nsisupports.Release((nsISupports *)dvdImage);
                                }
2770
                                data->pFuncs->pfnUtf16Free(dvdfileUtf16);
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785
                                dvdDrive->vtbl->nsisupports.Release((nsISupports *)dvdDrive);
                            }
                        } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                        }
                    } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                        if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                            IHardDisk *hardDisk     = NULL;
                            PRUnichar *hddfileUtf16 = NULL;
                            nsID *hdduuid           = NULL;
                            /* Current Limitation: Harddisk can't be connected to
                             * Secondary Master as Secondary Master is always used
                             * for CD/DVD Drive, so not connect the harddisk if it
                             * is requested to be connected to Secondary master
                             */

2786
                            data->pFuncs->pfnUtf8ToUtf16(def->disks[i]->src, &hddfileUtf16);
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820

                            data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddfileUtf16, &hardDisk);

                            if (!hardDisk) {
                                data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                                  hddfileUtf16,
                                                                  AccessMode_ReadWrite,
                                                                  &hardDisk);
                            }

                            if (hardDisk) {
                                rc = hardDisk->vtbl->imedium.GetId((IMedium *)hardDisk, &hdduuid);
                                if (NS_FAILED(rc)) {
                                    vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                              "can't get the uuid of the file to be attached as harddisk",
                                              def->disks[i]->src, (unsigned)rc);
                                } else {
                                    if (def->disks[i]->readonly) {
                                        hardDisk->vtbl->SetType(hardDisk, HardDiskType_Immutable);
                                        DEBUG0("setting harddisk to readonly");
                                    } else if (!def->disks[i]->readonly) {
                                        hardDisk->vtbl->SetType(hardDisk, HardDiskType_Normal);
                                        DEBUG0("setting harddisk type to normal");
                                    }
                                    if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_IDE) {
                                        if (STREQ(def->disks[i]->dst, "hdc")) {
                                            DEBUG0("Not connecting harddisk to hdc as hdc"
                                                   " is taken by CD/DVD Drive");
                                        } else {
                                            PRInt32 channel          = 0;
                                            PRInt32 device           = 0;
                                            PRUnichar *hddcnameUtf16 = NULL;

                                            char *hddcname = strdup("IDE");
2821
                                            data->pFuncs->pfnUtf8ToUtf16(hddcname, &hddcnameUtf16);
2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837
                                            VIR_FREE(hddcname);

                                            if (STREQ(def->disks[i]->dst, "hda")) {
                                                channel = 0;
                                                device  = 0;
                                            } else if (STREQ(def->disks[i]->dst, "hdb")) {
                                                channel = 0;
                                                device  = 1;
                                            } else if (STREQ(def->disks[i]->dst, "hdd")) {
                                                channel = 1;
                                                device  = 1;
                                            }

                                            rc = machine->vtbl->AttachHardDisk(machine, hdduuid,
                                                                               hddcnameUtf16,
                                                                               channel, device);
2838
                                            data->pFuncs->pfnUtf16Free(hddcnameUtf16);
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855

                                            if (NS_FAILED(rc)) {
                                                vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                          "could not attach the file as harddisk",
                                                          def->disks[i]->src, (unsigned)rc);
                                            } else {
                                                DEBUG("Attached HDD with UUID:"
                                                      "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                                                (unsigned)hdduuid->m0,    (unsigned)hdduuid->m1,
                                                (unsigned)hdduuid->m2,
                                                (unsigned)hdduuid->m3[0], (unsigned)hdduuid->m3[1],
                                                (unsigned)hdduuid->m3[2], (unsigned)hdduuid->m3[3],
                                                (unsigned)hdduuid->m3[4], (unsigned)hdduuid->m3[5],
                                                (unsigned)hdduuid->m3[6], (unsigned)hdduuid->m3[7]);
                                            }
                                        }
                                    }
2856
                                    data->pFuncs->pfnComUnallocMem(hdduuid);
2857 2858 2859
                                }
                                hardDisk->vtbl->imedium.nsisupports.Release((nsISupports *)hardDisk);
                            }
2860
                            data->pFuncs->pfnUtf16Free(hddfileUtf16);
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
                        } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                        }
                    } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                        if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                            IFloppyDrive *floppyDrive;
                            machine->vtbl->GetFloppyDrive(machine, &floppyDrive);
                            if (floppyDrive) {
                                rc = floppyDrive->vtbl->SetEnabled(floppyDrive, 1);
                                if (NS_SUCCEEDED(rc)) {
                                    IFloppyImage *floppyImage = NULL;
                                    PRUnichar *fdfileUtf16    = NULL;
                                    nsID *fduuid              = NULL;
                                    nsID fdemptyuuid;

                                    memset(&fdemptyuuid, 0, sizeof(fdemptyuuid));

2877
                                    data->pFuncs->pfnUtf8ToUtf16(def->disks[i]->src, &fdfileUtf16);
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907
                                    rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj, fdfileUtf16,
                                                                              &floppyImage);

                                    if (!floppyImage) {
                                        data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj, fdfileUtf16,
                                                                             &fdemptyuuid, &floppyImage);
                                    }

                                    if (floppyImage) {
                                        rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage, &fduuid);
                                        if (NS_FAILED(rc)) {
                                            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                      "can't get the uuid of the file to be attached to floppy drive",
                                                      def->disks[i]->src, (unsigned)rc);
                                        } else {
                                            rc = floppyDrive->vtbl->MountImage(floppyDrive, fduuid);
                                            if (NS_FAILED(rc)) {
                                                vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                          "could not attach the file to floppy drive",
                                                          def->disks[i]->src, (unsigned)rc);
                                            } else {
                                                DEBUG("floppyImage UUID:"
                                                      "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                                                (unsigned)fduuid->m0,    (unsigned)fduuid->m1,
                                                (unsigned)fduuid->m2,
                                                (unsigned)fduuid->m3[0], (unsigned)fduuid->m3[1],
                                                (unsigned)fduuid->m3[2], (unsigned)fduuid->m3[3],
                                                (unsigned)fduuid->m3[4], (unsigned)fduuid->m3[5],
                                                (unsigned)fduuid->m3[6], (unsigned)fduuid->m3[7]);
                                            }
2908
                                            data->pFuncs->pfnComUnallocMem(fduuid);
2909 2910 2911
                                        }
                                        floppyImage->vtbl->imedium.nsisupports.Release((nsISupports *)floppyImage);
                                    }
2912
                                    data->pFuncs->pfnUtf16Free(fdfileUtf16);
2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
                                }
                                floppyDrive->vtbl->nsisupports.Release((nsISupports *)floppyDrive);
                            }
                        } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                        }
                    }
                }
            }

        }   /* Finished:Block to attach the CDROM/DVD Drive and HardDisks to the VM */

        {   /* Started:Block to attach the Sound Controller to the VM */
            /* Check if def->nsounds is one as VirtualBox currently supports
             * only one sound card
             */
            if (def->nsounds == 1) {
                IAudioAdapter *audioAdapter = NULL;

                machine->vtbl->GetAudioAdapter(machine, &audioAdapter);
                if (audioAdapter) {
                    rc = audioAdapter->vtbl->SetEnabled(audioAdapter, 1);
                    if (NS_SUCCEEDED(rc)) {
                        if (def->sounds[0]->model == VIR_DOMAIN_SOUND_MODEL_SB16) {
                            audioAdapter->vtbl->SetAudioController(audioAdapter, AudioControllerType_SB16);
                        } else if (def->sounds[0]->model == VIR_DOMAIN_SOUND_MODEL_ES97) {
                            audioAdapter->vtbl->SetAudioController(audioAdapter, AudioControllerType_AC97);
                        }
                    }
                    audioAdapter->vtbl->nsisupports.Release((nsISupports *)audioAdapter);
                }
            }
        }   /* Finished:Block to attach the Sound Controller to the VM */

        {   /* Started:Block to attach the Network Card to the VM */
            ISystemProperties *systemProperties = NULL;
            PRUint32 networkAdapterCount        = 0;
            int i = 0;

            data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                systemProperties->vtbl->GetNetworkAdapterCount(systemProperties, &networkAdapterCount);
                systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
                systemProperties = NULL;
            }

            DEBUG("Number of Network Cards to be connected: %d", def->nnets);
            DEBUG("Number of Network Cards available: %d", networkAdapterCount);

            for (i = 0; (i < def->nnets) && (i < networkAdapterCount); i++) {
                INetworkAdapter *adapter = NULL;
                PRUint32 adapterType     = NetworkAdapterType_Null;
                char macaddr[VIR_MAC_STRING_BUFLEN] = {0};
                char macaddrvbox[VIR_MAC_STRING_BUFLEN - 5] = {0};

                virFormatMacAddr(def->nets[i]->mac, macaddr);
                snprintf(macaddrvbox, VIR_MAC_STRING_BUFLEN - 5,
                         "%02X%02X%02X%02X%02X%02X",
                         def->nets[i]->mac[0],
                         def->nets[i]->mac[1],
                         def->nets[i]->mac[2],
                         def->nets[i]->mac[3],
                         def->nets[i]->mac[4],
                         def->nets[i]->mac[5]);
                macaddrvbox[VIR_MAC_STRING_BUFLEN - 6] = '\0';

                DEBUG("NIC(%d): Type:   %d", i, def->nets[i]->type);
                DEBUG("NIC(%d): Model:  %s", i, def->nets[i]->model);
                DEBUG("NIC(%d): Mac:    %s", i, macaddr);
                DEBUG("NIC(%d): ifname: %s", i, def->nets[i]->ifname);
2982 2983
                if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
                    DEBUG("NIC(%d): name:    %s", i, def->nets[i]->data.network.name);
2984 2985
                } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
                    DEBUG("NIC(%d): name:   %s", i, def->nets[i]->data.internal.name);
2986
                } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020
                    DEBUG("NIC(%d): NAT.", i);
                } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
                    DEBUG("NIC(%d): brname: %s", i, def->nets[i]->data.bridge.brname);
                    DEBUG("NIC(%d): script: %s", i, def->nets[i]->data.bridge.script);
                    DEBUG("NIC(%d): ipaddr: %s", i, def->nets[i]->data.bridge.ipaddr);
                }

                machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
                if (adapter) {
                    PRUnichar *MACAddress      = NULL;

                    adapter->vtbl->SetEnabled(adapter, 1);

                    if (STRCASEEQ(def->nets[i]->model , "Am79C970A")) {
                        adapterType = NetworkAdapterType_Am79C970A;
                    } else if (STRCASEEQ(def->nets[i]->model , "Am79C973")) {
                        adapterType = NetworkAdapterType_Am79C973;
                    } else if (STRCASEEQ(def->nets[i]->model , "82540EM")) {
                        adapterType = NetworkAdapterType_I82540EM;
                    } else if (STRCASEEQ(def->nets[i]->model , "82545EM")) {
                        adapterType = NetworkAdapterType_I82545EM;
                    } else if (STRCASEEQ(def->nets[i]->model , "82543GC")) {
                        adapterType = NetworkAdapterType_I82543GC;
                    }

                    adapter->vtbl->SetAdapterType(adapter, adapterType);

                    if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
                        PRUnichar *hostInterface = NULL;
                        /* Bridged Network */

                        adapter->vtbl->AttachToBridgedInterface(adapter);

                        if (def->nets[i]->data.bridge.brname) {
3021
                            data->pFuncs->pfnUtf8ToUtf16(def->nets[i]->data.bridge.brname, &hostInterface);
3022
                            adapter->vtbl->SetHostInterface(adapter, hostInterface);
3023
                            data->pFuncs->pfnUtf16Free(hostInterface);
3024 3025 3026 3027 3028 3029 3030
                        }
                    } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
                        PRUnichar *internalNetwork = NULL;
                        /* Internal Network */

                        adapter->vtbl->AttachToInternalNetwork(adapter);

3031 3032
                        if (def->nets[i]->data.internal.name) {
                            data->pFuncs->pfnUtf8ToUtf16(def->nets[i]->data.internal.name, &internalNetwork);
3033
                            adapter->vtbl->SetInternalNetwork(adapter, internalNetwork);
3034
                            data->pFuncs->pfnUtf16Free(internalNetwork);
3035
                        }
3036
                    } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
3037 3038 3039 3040 3041 3042 3043
                        PRUnichar *hostInterface = NULL;
                        /* Host Only Networking (currently only vboxnet0 available
                         * on *nix and mac, on windows you can create and configure
                         * as many as you want)
                         */
                        adapter->vtbl->AttachToHostOnlyInterface(adapter);

3044 3045
                        if (def->nets[i]->data.network.name) {
                            g_pVBoxFuncs->pfnUtf8ToUtf16(def->nets[i]->data.network.name, &hostInterface);
3046
                            adapter->vtbl->SetHostInterface(adapter, hostInterface);
3047
                            data->pFuncs->pfnUtf16Free(hostInterface);
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
                        }
                    } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
                        /* NAT */
                        adapter->vtbl->AttachToNAT(adapter);
                    } else {
                        /* else always default to NAT if we don't understand
                         * what option is been passed to us
                         */
                        adapter->vtbl->AttachToNAT(adapter);
                    }

3059
                    data->pFuncs->pfnUtf8ToUtf16(macaddrvbox, &MACAddress);
3060 3061 3062
                    if (def->nets[i]->mac) {
                        adapter->vtbl->SetMACAddress(adapter, MACAddress);
                    }
3063
                    data->pFuncs->pfnUtf16Free(MACAddress);
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092
                }
            }
        }   /* Finished:Block to attach the Network Card to the VM */

        {   /* Started:Block to attach the Serial Port to the VM */
            ISystemProperties *systemProperties = NULL;
            PRUint32 serialPortCount            = 0;
            int i = 0;

            data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                systemProperties->vtbl->GetSerialPortCount(systemProperties, &serialPortCount);
                systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
                systemProperties = NULL;
            }

            DEBUG("Number of Serial Ports to be connected: %d", def->nserials);
            DEBUG("Number of Serial Ports available: %d", serialPortCount);
            for (i = 0; (i < def->nserials) && (i < serialPortCount); i++) {
                ISerialPort *serialPort = NULL;

                DEBUG("SerialPort(%d): Type: %d", i, def->serials[i]->type);
                DEBUG("SerialPort(%d): dstPort: %d", i, def->serials[i]->dstPort);

                machine->vtbl->GetSerialPort(machine, i, &serialPort);
                if (serialPort) {
                    PRUnichar *pathUtf16 = NULL;

                    serialPort->vtbl->SetEnabled(serialPort, 1);
3093
                    data->pFuncs->pfnUtf8ToUtf16(def->serials[i]->data.file.path, &pathUtf16);
3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140

                    /* For now hard code the serial ports to COM1 and COM2,
                     * COM1 (Base Addr: 0x3F8 (decimal: 1016), IRQ: 4)
                     * COM2 (Base Addr: 0x2F8 (decimal:  760), IRQ: 3)
                     * TODO: make this more flexible
                     */
                    /* TODO: to improve the libvirt XMl handling so
                     * that def->serials[i]->dstPort shows real port
                     * and not always start at 0
                     */
                    if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_DEV) {
                        serialPort->vtbl->SetPath(serialPort, pathUtf16);
                        if (def->serials[i]->dstPort == 0) {
                            serialPort->vtbl->SetIRQ(serialPort, 4);
                            serialPort->vtbl->SetIOBase(serialPort, 1016);
                            DEBUG(" serialPort-%d irq: %d, iobase 0x%x, path: %s",
                                  i, 4, 1016, def->serials[i]->data.file.path);
                        } else if (def->serials[i]->dstPort == 1) {
                            serialPort->vtbl->SetIRQ(serialPort, 3);
                            serialPort->vtbl->SetIOBase(serialPort, 760);
                            DEBUG(" serialPort-%d irq: %d, iobase 0x%x, path: %s",
                                  i, 3, 760, def->serials[i]->data.file.path);
                        }
                        serialPort->vtbl->SetHostMode(serialPort, PortMode_HostDevice);
                    } else if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_PIPE) {
                        serialPort->vtbl->SetPath(serialPort, pathUtf16);
                        if (def->serials[i]->dstPort == 0) {
                            serialPort->vtbl->SetIRQ(serialPort, 4);
                            serialPort->vtbl->SetIOBase(serialPort, 1016);
                            DEBUG(" serialPort-%d irq: %d, iobase 0x%x, path: %s",
                                  i, 4, 1016, def->serials[i]->data.file.path);
                        } else if (def->serials[i]->dstPort == 1) {
                            serialPort->vtbl->SetIRQ(serialPort, 3);
                            serialPort->vtbl->SetIOBase(serialPort, 760);
                            DEBUG(" serialPort-%d irq: %d, iobase 0x%x, path: %s",
                                  i, 3, 760, def->serials[i]->data.file.path);
                        }
                        if (!virFileExists(def->serials[i]->data.file.path)) {
                            serialPort->vtbl->SetServer(serialPort, 1);
                        }
                        serialPort->vtbl->SetHostMode(serialPort, PortMode_HostPipe);
                    } else if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_NULL) {
                        serialPort->vtbl->SetHostMode(serialPort, PortMode_Disconnected);
                    }

                    serialPort->vtbl->nsisupports.Release((nsISupports *)serialPort);
                    if (pathUtf16) {
3141
                        data->pFuncs->pfnUtf16Free(pathUtf16);
3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
                        pathUtf16 = NULL;
                    }
                }
            }
        }   /* Finished:Block to attach the Serial Port to the VM */

        {   /* Started:Block to attach the Parallel Port to the VM */
            ISystemProperties *systemProperties = NULL;
            PRUint32 parallelPortCount          = 0;
            int i = 0;

            data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                systemProperties->vtbl->GetParallelPortCount(systemProperties, &parallelPortCount);
                systemProperties->vtbl->nsisupports.Release((nsISupports *)systemProperties);
                systemProperties = NULL;
            }

            DEBUG("Number of Parallel Ports to be connected: %d", def->nparallels);
            DEBUG("Number of Parallel Ports available: %d", parallelPortCount);
            for (i = 0; (i < def->nparallels) && (i < parallelPortCount); i++) {
                IParallelPort *parallelPort = NULL;

                DEBUG("ParallelPort(%d): Type: %d", i, def->parallels[i]->type);
                DEBUG("ParallelPort(%d): dstPort: %d", i, def->parallels[i]->dstPort);

                machine->vtbl->GetParallelPort(machine, i, &parallelPort);
                if (parallelPort) {
                    PRUnichar *pathUtf16 = NULL;

3172
                    data->pFuncs->pfnUtf8ToUtf16(def->parallels[i]->data.file.path, &pathUtf16);
3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203

                    /* For now hard code the parallel ports to
                     * LPT1 (Base Addr: 0x378 (decimal: 888), IRQ: 7)
                     * LPT2 (Base Addr: 0x278 (decimal: 632), IRQ: 5)
                     * TODO: make this more flexible
                     */
                    if ((def->parallels[i]->type == VIR_DOMAIN_CHR_TYPE_DEV)  ||
                        (def->parallels[i]->type == VIR_DOMAIN_CHR_TYPE_PTY)  ||
                        (def->parallels[i]->type == VIR_DOMAIN_CHR_TYPE_FILE) ||
                        (def->parallels[i]->type == VIR_DOMAIN_CHR_TYPE_PIPE)) {
                        parallelPort->vtbl->SetPath(parallelPort, pathUtf16);
                        if (i == 0) {
                            parallelPort->vtbl->SetIRQ(parallelPort, 7);
                            parallelPort->vtbl->SetIOBase(parallelPort, 888);
                            DEBUG(" parallePort-%d irq: %d, iobase 0x%x, path: %s",
                                  i, 7, 888, def->parallels[i]->data.file.path);
                        } else if (i == 1) {
                            parallelPort->vtbl->SetIRQ(parallelPort, 5);
                            parallelPort->vtbl->SetIOBase(parallelPort, 632);
                            DEBUG(" parallePort-%d irq: %d, iobase 0x%x, path: %s",
                                  i, 5, 632, def->parallels[i]->data.file.path);
                        }
                    }

                    /* like serial port, parallel port can't be enabled unless
                     * correct IRQ and IOBase values are specified.
                     */
                    parallelPort->vtbl->SetEnabled(parallelPort, 1);

                    parallelPort->vtbl->nsisupports.Release((nsISupports *)parallelPort);
                    if (pathUtf16) {
3204
                        data->pFuncs->pfnUtf16Free(pathUtf16);
3205 3206 3207 3208 3209 3210 3211
                        pathUtf16 = NULL;
                    }
                }
            }
        }   /* Finished:Block to attach the Parallel Port to the VM */

        {   /* Started:Block to attach the Remote Display to VM */
3212 3213 3214 3215 3216 3217 3218 3219
            int vrdpPresent  = 0;
            int sdlPresent   = 0;
            int guiPresent   = 0;
            char *guiDisplay = NULL;
            char *sdlDisplay = NULL;
            int i = 0;

            for (i = 0; i < def->ngraphics; i++) {
3220 3221
                IVRDPServer *VRDPServer = NULL;

3222
                if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) && (vrdpPresent == 0)) {
3223

3224
                    vrdpPresent = 1;
3225 3226 3227 3228 3229
                    machine->vtbl->GetVRDPServer(machine, &VRDPServer);
                    if (VRDPServer) {
                        VRDPServer->vtbl->SetEnabled(VRDPServer, PR_TRUE);
                        DEBUG0("VRDP Support turned ON on port: 3389");

3230 3231 3232 3233
                        if (def->graphics[i]->data.rdp.port) {
                            VRDPServer->vtbl->SetPort(VRDPServer, def->graphics[i]->data.rdp.port);
                            DEBUG("VRDP Port changed to: %d", def->graphics[i]->data.rdp.port);
                        } else if (def->graphics[i]->data.rdp.autoport) {
3234 3235 3236 3237 3238 3239 3240
                            /* Setting the port to 0 will reset its value to
                             * the default one which is 3389 currently
                             */
                            VRDPServer->vtbl->SetPort(VRDPServer, 0);
                            DEBUG0("VRDP Port changed to default, which is 3389 currently");
                        }

3241
                        if (def->graphics[i]->data.rdp.replaceUser) {
3242 3243 3244 3245
                            VRDPServer->vtbl->SetReuseSingleConnection(VRDPServer, PR_TRUE);
                            DEBUG0("VRDP set to reuse single connection");
                        }

3246
                        if (def->graphics[i]->data.rdp.multiUser) {
3247 3248 3249 3250
                            VRDPServer->vtbl->SetAllowMultiConnection(VRDPServer, PR_TRUE);
                            DEBUG0("VRDP set to allow multiple connection");
                        }

3251
                        if (def->graphics[i]->data.rdp.listenAddr) {
3252 3253
                            PRUnichar *netAddressUtf16 = NULL;

3254
                            data->pFuncs->pfnUtf8ToUtf16(def->graphics[i]->data.rdp.listenAddr, &netAddressUtf16);
3255
                            VRDPServer->vtbl->SetNetAddress(VRDPServer, netAddressUtf16);
3256
                            DEBUG("VRDP listen address is set to: %s", def->graphics[i]->data.rdp.listenAddr);
3257

3258
                            data->pFuncs->pfnUtf16Free(netAddressUtf16);
3259 3260 3261 3262 3263
                        }

                        VRDPServer->vtbl->nsisupports.Release((nsISupports *)VRDPServer);
                    }
                }
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287

                if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) && (guiPresent == 0)) {
                    guiPresent = 1;
                    guiDisplay = strdup(def->graphics[i]->data.desktop.display);
                    if (guiDisplay == NULL) {
                        vboxError(conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                        /* just don't go to cleanup yet as it is ok to have
                         * guiDisplay as NULL and we check it below if it
                         * exist and then only use it there
                         */
                    }
                }

                if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) && (sdlPresent == 0)) {
                    sdlPresent = 1;
                    sdlDisplay = strdup(def->graphics[i]->data.sdl.display);
                    if (sdlDisplay == NULL) {
                        vboxError(conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                        /* just don't go to cleanup yet as it is ok to have
                         * sdlDisplay as NULL and we check it below if it
                         * exist and then only use it there
                         */
                    }
                }
3288
            }
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356

            if ((vrdpPresent == 1) && (guiPresent == 0) && (sdlPresent == 0)) {
                /* store extradata key that frontend is set to vrdp */
                PRUnichar *keyTypeUtf16   = NULL;
                PRUnichar *valueTypeUtf16 = NULL;

                data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Type", &keyTypeUtf16);
                data->pFuncs->pfnUtf8ToUtf16("vrdp", &valueTypeUtf16);

                machine->vtbl->SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);

                data->pFuncs->pfnUtf16Free(keyTypeUtf16);
                data->pFuncs->pfnUtf16Free(valueTypeUtf16);

            } else if ((guiPresent == 0) && (sdlPresent == 1)) {
                /* store extradata key that frontend is set to sdl */
                PRUnichar *keyTypeUtf16      = NULL;
                PRUnichar *valueTypeUtf16    = NULL;
                PRUnichar *keyDislpayUtf16   = NULL;
                PRUnichar *valueDisplayUtf16 = NULL;

                data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Type", &keyTypeUtf16);
                data->pFuncs->pfnUtf8ToUtf16("sdl", &valueTypeUtf16);

                machine->vtbl->SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);

                data->pFuncs->pfnUtf16Free(keyTypeUtf16);
                data->pFuncs->pfnUtf16Free(valueTypeUtf16);

                if (sdlDisplay) {
                    data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Display", &keyDislpayUtf16);
                    data->pFuncs->pfnUtf8ToUtf16(sdlDisplay, &valueDisplayUtf16);

                    machine->vtbl->SetExtraData(machine, keyDislpayUtf16, valueDisplayUtf16);

                    data->pFuncs->pfnUtf16Free(keyDislpayUtf16);
                    data->pFuncs->pfnUtf16Free(valueDisplayUtf16);
                }

            } else {
                /* if all are set then default is gui, with vrdp turned on */
                PRUnichar *keyTypeUtf16      = NULL;
                PRUnichar *valueTypeUtf16    = NULL;
                PRUnichar *keyDislpayUtf16   = NULL;
                PRUnichar *valueDisplayUtf16 = NULL;

                data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Type", &keyTypeUtf16);
                data->pFuncs->pfnUtf8ToUtf16("gui", &valueTypeUtf16);

                machine->vtbl->SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);

                data->pFuncs->pfnUtf16Free(keyTypeUtf16);
                data->pFuncs->pfnUtf16Free(valueTypeUtf16);

                if (guiDisplay) {
                    data->pFuncs->pfnUtf8ToUtf16("FRONTEND/Display", &keyDislpayUtf16);
                    data->pFuncs->pfnUtf8ToUtf16(guiDisplay, &valueDisplayUtf16);

                    machine->vtbl->SetExtraData(machine, keyDislpayUtf16, valueDisplayUtf16);

                    data->pFuncs->pfnUtf16Free(keyDislpayUtf16);
                    data->pFuncs->pfnUtf16Free(valueDisplayUtf16);
                }
            }

            VIR_FREE(guiDisplay);
            VIR_FREE(sdlDisplay);

3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
        }   /* Finished:Block to attach the Remote Display to VM */

        {   /* Started:Block to attach USB Devices to VM */
            if (def->nhostdevs > 0) {
                IUSBController *USBController = NULL;
                int i = 0, isUSB = 0;
                /* Loop through the devices first and see if you
                 * have a USB Device, only if you have one then
                 * start the USB controller else just proceed as
                 * usual
                 */
                for (i = 0; i < def->nhostdevs; i++) {
                    if (def->hostdevs[i]->mode ==
                            VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
                        if (def->hostdevs[i]->source.subsys.type ==
                                VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
                            if (def->hostdevs[i]->source.subsys.u.usb.vendor ||
                                def->hostdevs[i]->source.subsys.u.usb.product) {
                                DEBUG("USB Device detected, VendorId:0x%x, ProductId:0x%x",
                                      def->hostdevs[i]->source.subsys.u.usb.vendor,
                                      def->hostdevs[i]->source.subsys.u.usb.product);
                                isUSB++;
                            }
                        }
                    }
                }

                if (isUSB > 0) {
                    /* First Start the USB Controller and then loop
                     * to attach USB Devices to it
                     */
                    machine->vtbl->GetUSBController(machine, &USBController);
                    if (USBController) {
                        USBController->vtbl->SetEnabled(USBController, 1);
                        USBController->vtbl->SetEnabledEhci(USBController, 1);

                        for (i = 0; i < def->nhostdevs; i++) {
                            if (def->hostdevs[i]->mode ==
                                    VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
                                if (def->hostdevs[i]->source.subsys.type ==
                                        VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {

                                    char filtername[11]        = {0};
                                    PRUnichar *filternameUtf16 = NULL;
                                    IUSBDeviceFilter *filter   = NULL;

                                    /* Assuming can't have more then 9999 devices so
                                     * restricting to %04d
                                     */
                                    sprintf(filtername, "filter%04d", i);
3407
                                    data->pFuncs->pfnUtf8ToUtf16(filtername, &filternameUtf16);
3408 3409 3410 3411

                                    USBController->vtbl->CreateDeviceFilter(USBController,
                                                                            filternameUtf16,
                                                                            &filter);
3412
                                    data->pFuncs->pfnUtf16Free(filternameUtf16);
3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424

                                    if (filter &&
                                        (def->hostdevs[i]->source.subsys.u.usb.vendor ||
                                        def->hostdevs[i]->source.subsys.u.usb.product)) {

                                        PRUnichar *vendorIdUtf16  = NULL;
                                        char vendorId[40]         = {0};
                                        PRUnichar *productIdUtf16 = NULL;
                                        char productId[40]        = {0};

                                        if (def->hostdevs[i]->source.subsys.u.usb.vendor) {
                                            sprintf(vendorId, "%x", def->hostdevs[i]->source.subsys.u.usb.vendor);
3425
                                            data->pFuncs->pfnUtf8ToUtf16(vendorId, &vendorIdUtf16);
3426
                                            filter->vtbl->SetVendorId(filter, vendorIdUtf16);
3427
                                            data->pFuncs->pfnUtf16Free(vendorIdUtf16);
3428 3429 3430
                                        }
                                        if (def->hostdevs[i]->source.subsys.u.usb.product) {
                                            sprintf(productId, "%x", def->hostdevs[i]->source.subsys.u.usb.product);
3431
                                            data->pFuncs->pfnUtf8ToUtf16(productId, &productIdUtf16);
3432
                                            filter->vtbl->SetProductId(filter, productIdUtf16);
3433
                                            data->pFuncs->pfnUtf16Free(productIdUtf16);
3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
                                        }
                                        filter->vtbl->SetActive(filter, 1);
                                        USBController->vtbl->InsertDeviceFilter(USBController,
                                                                                i,
                                                                                filter);
                                        filter->vtbl->nsisupports.Release((nsISupports *)filter);
                                    }

                                }
                            }
                        }
                        USBController->vtbl->nsisupports.Release((nsISupports *)USBController);
                    }
                }
            }
        }   /* Finished:Block to attach USB Devices to VM */

        /* Save the machine settings made till now and close the
         * session. also free up the mchiid variable used.
         */
        rc = machine->vtbl->SaveSettings(machine);
        data->vboxSession->vtbl->Close(data->vboxSession);
3456
        data->pFuncs->pfnComUnallocMem(mchiid);
3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501

        dom = virGetDomain(conn, def->name, def->uuid);
        if(machine) {
            machine->vtbl->nsisupports.Release((nsISupports *)machine);
            machine = NULL;
        }
    }

    VIR_FREE(iid);
    virDomainDefFree(def);

    return dom;

cleanup:
    if(machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);
    VIR_FREE(iid);
    virDomainDefFree(def);
    return NULL;
}

static int vboxDomainUndefine(virDomainPtr dom) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID *iid            = NULL;
    int ret = -1;

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if(data->vboxObj) {
        nsIDFromChar(iid, dom->uuid);

        /* Block for checking if HDD's are attched to VM.
         * considering just IDE bus for now. Also skipped
         * chanel=1 and device=0 (Secondary Master) as currenlty
         * it is allocated to CD/DVD Drive bt default
         */
        {
            PRUnichar *hddcnameUtf16 = NULL;

            char *hddcname = strdup("IDE");
3502
            data->pFuncs->pfnUtf8ToUtf16(hddcname, &hddcnameUtf16);
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519
            VIR_FREE(hddcname);

            /* Open a Session for the machine */
            rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, iid);
            if (NS_SUCCEEDED(rc)) {
                rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                if (NS_SUCCEEDED(rc) && machine) {

                    /* Disconnect all the drives if present */
                    machine->vtbl->DetachHardDisk(machine, hddcnameUtf16, 0, 0);
                    machine->vtbl->DetachHardDisk(machine, hddcnameUtf16, 0, 1);
                    machine->vtbl->DetachHardDisk(machine, hddcnameUtf16, 1, 1);

                    machine->vtbl->SaveSettings(machine);
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            }
3520
            data->pFuncs->pfnUtf16Free(hddcnameUtf16);
3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
        }

        rc = data->vboxObj->vtbl->UnregisterMachine(data->vboxObj, iid, &machine);
        DEBUG("UUID of machine being undefined:{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
        (unsigned)iid->m0,    (unsigned)iid->m1, (unsigned)iid->m2,
        (unsigned)iid->m3[0], (unsigned)iid->m3[1],
        (unsigned)iid->m3[2], (unsigned)iid->m3[3],
        (unsigned)iid->m3[4], (unsigned)iid->m3[5],
        (unsigned)iid->m3[6], (unsigned)iid->m3[7]);

        if (NS_SUCCEEDED(rc) && machine){
            machine->vtbl->DeleteSettings(machine);
            ret = 0;
        }
    }

cleanup:
    if (machine)
        machine->vtbl->nsisupports.Release((nsISupports *)machine);

    VIR_FREE(iid);
    return ret;
}

static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID *iid            = NULL;
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
    int ret = -1;

    if (VIR_ALLOC(def) < 0) {
        virReportOOMError(dom->conn);
        return ret;
    }

    def->os.type = strdup("hvm");

    dev = virDomainDeviceDefParse(dom->conn, data->caps, def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    nsIDFromChar(iid, dom->uuid);
    DEBUG("machine uuid:{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
          (unsigned)iid->m0,    (unsigned)iid->m1,
          (unsigned)iid->m2,    (unsigned)iid->m3[0],
          (unsigned)iid->m3[1], (unsigned)iid->m3[2],
          (unsigned)iid->m3[3], (unsigned)iid->m3[4],
          (unsigned)iid->m3[5], (unsigned)iid->m3[6],
          (unsigned)iid->m3[7]);

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                      "no domain with matching uuid:"
                      "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                      (unsigned)iid->m0,    (unsigned)iid->m1,
                      (unsigned)iid->m2,    (unsigned)iid->m3[0],
                      (unsigned)iid->m3[1], (unsigned)iid->m3[2],
                      (unsigned)iid->m3[3], (unsigned)iid->m3[4],
                      (unsigned)iid->m3[5], (unsigned)iid->m3[6],
                      (unsigned)iid->m3[7]);
            goto cleanup;
        }

        if (machine) {
            machine->vtbl->GetState(machine, &state);

            if ((state == MachineState_Running) ||
                (state == MachineState_Paused)) {
                rc = data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
            } else {
                rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, iid);
            }
            if (NS_SUCCEEDED(rc)) {
                rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                if (NS_SUCCEEDED(rc) && machine) {
                    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
                        if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                            if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                                IDVDDrive *dvdDrive = NULL;
                                /* Currently CDROM/DVD Drive is always IDE
                                 * Secondary Master so neglecting the following
                                 * parameter dev->data.disk->bus
                                 */
                                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                                if (dvdDrive) {
                                    IDVDImage *dvdImage     = NULL;
                                    PRUnichar *dvdfileUtf16 = NULL;
                                    nsID *dvduuid           = NULL;
                                    nsID dvdemptyuuid;

                                    memset(&dvdemptyuuid, 0, sizeof(dvdemptyuuid));

3627
                                    data->pFuncs->pfnUtf8ToUtf16(dev->data.disk->src, &dvdfileUtf16);
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657

                                    data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                    if (!dvdImage) {
                                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, &dvdemptyuuid, &dvdImage);
                                    }
                                    if (dvdImage) {
                                        rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage, &dvduuid);
                                        if (NS_FAILED(rc)) {
                                            vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                      "can't get the uuid of the file to be attached to cdrom",
                                                      dev->data.disk->src, (unsigned)rc);
                                        } else {
                                            /* unmount the previous mounted image */
                                            dvdDrive->vtbl->Unmount(dvdDrive);
                                            rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid);
                                            if (NS_FAILED(rc)) {
                                                vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                          "could not attach the file to cdrom",
                                                          dev->data.disk->src, (unsigned)rc);
                                            } else {
                                                ret = 0;
                                                DEBUG("CD/DVD Image UUID:"
                                                      "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                                                      (unsigned)dvduuid->m0,    (unsigned)dvduuid->m1,
                                                      (unsigned)dvduuid->m2,    (unsigned)dvduuid->m3[0],
                                                      (unsigned)dvduuid->m3[1], (unsigned)dvduuid->m3[2],
                                                      (unsigned)dvduuid->m3[3], (unsigned)dvduuid->m3[4],
                                                      (unsigned)dvduuid->m3[5], (unsigned)dvduuid->m3[6],
                                                      (unsigned)dvduuid->m3[7]);
                                            }
3658
                                            data->pFuncs->pfnComUnallocMem(dvduuid);
3659 3660 3661 3662
                                        }

                                        dvdImage->vtbl->imedium.nsisupports.Release((nsISupports *)dvdImage);
                                    }
3663
                                    data->pFuncs->pfnUtf16Free(dvdfileUtf16);
3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681
                                    dvdDrive->vtbl->nsisupports.Release((nsISupports *)dvdDrive);
                                }
                            } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                            }
                        } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                            if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                                IFloppyDrive *floppyDrive;
                                machine->vtbl->GetFloppyDrive(machine, &floppyDrive);
                                if (floppyDrive) {
                                    rc = floppyDrive->vtbl->SetEnabled(floppyDrive, 1);
                                    if (NS_SUCCEEDED(rc)) {
                                        IFloppyImage *floppyImage = NULL;
                                        PRUnichar *fdfileUtf16    = NULL;
                                        nsID *fduuid              = NULL;
                                        nsID fdemptyuuid;

                                        memset(&fdemptyuuid, 0, sizeof(fdemptyuuid));

3682
                                        data->pFuncs->pfnUtf8ToUtf16(dev->data.disk->src, &fdfileUtf16);
3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
                                        rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj, fdfileUtf16,
                                                                                  &floppyImage);

                                        if (!floppyImage) {
                                            data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj, fdfileUtf16,
                                                                                 &fdemptyuuid, &floppyImage);
                                        }

                                        if (floppyImage) {
                                            rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage, &fduuid);
                                            if (NS_FAILED(rc)) {
                                                vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                          "can't get the uuid of the file to be attached to floppy drive",
                                                          dev->data.disk->src, (unsigned)rc);
                                            } else {
                                                rc = floppyDrive->vtbl->MountImage(floppyDrive, fduuid);
                                                if (NS_FAILED(rc)) {
                                                    vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                                                              "could not attach the file to floppy drive",
                                                              dev->data.disk->src, (unsigned)rc);
                                                } else {
                                                    ret = 0;
                                                    DEBUG("attached floppy, UUID:"
                                                          "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                                                          (unsigned)fduuid->m0,    (unsigned)fduuid->m1,
                                                          (unsigned)fduuid->m2,
                                                          (unsigned)fduuid->m3[0], (unsigned)fduuid->m3[1],
                                                          (unsigned)fduuid->m3[2], (unsigned)fduuid->m3[3],
                                                          (unsigned)fduuid->m3[4], (unsigned)fduuid->m3[5],
                                                          (unsigned)fduuid->m3[6], (unsigned)fduuid->m3[7]);
                                                }
3714
                                                data->pFuncs->pfnComUnallocMem(fduuid);
3715 3716 3717
                                            }
                                            floppyImage->vtbl->imedium.nsisupports.Release((nsISupports *)floppyImage);
                                        }
3718
                                        data->pFuncs->pfnUtf16Free(fdfileUtf16);
3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945
                                    }
                                    floppyDrive->vtbl->nsisupports.Release((nsISupports *)floppyDrive);
                                }
                            } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                            }
                        }
                    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
                    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
                        if (dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
                            if (dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
                            }
                        }
                    }
                    machine->vtbl->SaveSettings(machine);
                    machine->vtbl->nsisupports.Release((nsISupports *)machine);
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            }
        }
    }

cleanup:
    VIR_FREE(iid);
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml) {
    nsresult rc;
    vboxGlobalData *data = dom->conn->privateData;
    IMachine *machine    = NULL;
    nsID *iid            = NULL;
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
    int ret = -1;

    if (VIR_ALLOC(def) < 0) {
        virReportOOMError(dom->conn);
        return ret;
    }

    def->os.type = strdup("hvm");

    dev = virDomainDeviceDefParse(dom->conn, data->caps, def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError(dom->conn);
        goto cleanup;
    }

    nsIDFromChar(iid, dom->uuid);
    DEBUG("machine uuid:{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
          (unsigned)iid->m0,    (unsigned)iid->m1,
          (unsigned)iid->m2,    (unsigned)iid->m3[0],
          (unsigned)iid->m3[1], (unsigned)iid->m3[2],
          (unsigned)iid->m3[3], (unsigned)iid->m3[4],
          (unsigned)iid->m3[5], (unsigned)iid->m3[6],
          (unsigned)iid->m3[7]);

    if(data->vboxObj) {
        rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
        if (NS_FAILED(rc)) {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                      "no domain with matching uuid:"
                      "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
                      (unsigned)iid->m0,    (unsigned)iid->m1,
                      (unsigned)iid->m2,    (unsigned)iid->m3[0],
                      (unsigned)iid->m3[1], (unsigned)iid->m3[2],
                      (unsigned)iid->m3[3], (unsigned)iid->m3[4],
                      (unsigned)iid->m3[5], (unsigned)iid->m3[6],
                      (unsigned)iid->m3[7]);
            goto cleanup;
        }

        if (machine) {
            machine->vtbl->GetState(machine, &state);

            if ((state == MachineState_Running) ||
                (state == MachineState_Paused)) {
                rc = data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
            } else {
                rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, iid);
            }
            if (NS_SUCCEEDED(rc)) {
                rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                if (NS_SUCCEEDED(rc) && machine) {
                    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
                        if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                            if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                                IDVDDrive *dvdDrive = NULL;
                                /* Currently CDROM/DVD Drive is always IDE
                                 * Secondary Master so neglecting the following
                                 * parameter dev->data.disk->bus
                                 */
                                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                                if (dvdDrive) {
                                    rc = dvdDrive->vtbl->Unmount(dvdDrive);
                                    if (NS_FAILED(rc)) {
                                        vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                                                  "could not de-attach the mounted ISO",
                                                  (unsigned)rc);
                                    } else {
                                        ret = 0;
                                    }
                                    dvdDrive->vtbl->nsisupports.Release((nsISupports *)dvdDrive);
                                }
                            } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                            }
                        } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                            if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                                IFloppyDrive *floppyDrive;
                                machine->vtbl->GetFloppyDrive(machine, &floppyDrive);
                                if (floppyDrive) {
                                    PRBool enabled = PR_FALSE;

                                    floppyDrive->vtbl->GetEnabled(floppyDrive, &enabled);
                                    if (enabled) {
                                        rc = floppyDrive->vtbl->Unmount(floppyDrive);
                                        if (NS_FAILED(rc)) {
                                            vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                                                      "could not attach the file to floppy drive",
                                                      (unsigned)rc);
                                        } else {
                                            ret = 0;
                                        }
                                    } else {
                                        /* If you are here means floppy drive is already unmounted
                                         * so don't flag error, just say everything is fine and quit
                                         */
                                        ret = 0;
                                    }
                                    floppyDrive->vtbl->nsisupports.Release((nsISupports *)floppyDrive);
                                }
                            } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                            }
                        }
                    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
                    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
                        if (dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
                            if (dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
                            }
                        }
                    }
                    machine->vtbl->SaveSettings(machine);
                    machine->vtbl->nsisupports.Release((nsISupports *)machine);
                }
                data->vboxSession->vtbl->Close(data->vboxSession);
            }
        }
    }

cleanup:
    VIR_FREE(iid);
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

virDriver NAME(Driver) = {
    VIR_DRV_VBOX,
    "VBOX",
    .open                          = vboxOpen,
    .close                         = vboxClose,
    .supports_feature              = NULL,
    .type                          = NULL,
    .version                       = vboxGetVersion,
    .getHostname                   = vboxGetHostname,
    .getMaxVcpus                   = vboxGetMaxVcpus,
    .nodeGetInfo                   = vboxNodeGetInfo,
    .getCapabilities               = vboxGetCapabilities,
    .listDomains                   = vboxListDomains,
    .numOfDomains                  = vboxNumOfDomains,
    .domainCreateXML               = vboxDomainCreateXML,
    .domainLookupByID              = vboxDomainLookupByID,
    .domainLookupByUUID            = vboxDomainLookupByUUID,
    .domainLookupByName            = vboxDomainLookupByName,
    .domainSuspend                 = vboxDomainSuspend,
    .domainResume                  = vboxDomainResume,
    .domainShutdown                = vboxDomainShutdown,
    .domainReboot                  = vboxDomainReboot,
    .domainDestroy                 = vboxDomainDestroy,
    .domainGetOSType               = vboxDomainGetOSType,
    .domainGetMaxMemory            = NULL,
    .domainSetMaxMemory            = NULL,
    .domainSetMemory               = vboxDomainSetMemory,
    .domainGetInfo                 = vboxDomainGetInfo,
    .domainSave                    = vboxDomainSave,
    .domainRestore                 = NULL,
    .domainCoreDump                = NULL,
    .domainSetVcpus                = NULL,
    .domainPinVcpu                 = NULL,
    .domainGetVcpus                = NULL,
    .domainGetMaxVcpus             = NULL,
    .domainDumpXML                 = vboxDomainDumpXML,
    .listDefinedDomains            = vboxListDefinedDomains,
    .numOfDefinedDomains           = vboxNumOfDefinedDomains,
    .domainCreate                  = vboxDomainCreate,
    .domainDefineXML               = vboxDomainDefineXML,
    .domainUndefine                = vboxDomainUndefine,
    .domainAttachDevice            = vboxDomainAttachDevice,
    .domainDetachDevice            = vboxDomainDetachDevice,
    .domainGetAutostart            = NULL,
    .domainSetAutostart            = NULL,
    .domainGetSchedulerType        = NULL,
    .domainGetSchedulerParameters  = NULL,
    .domainSetSchedulerParameters  = NULL,
    .domainMigratePrepare          = NULL,
    .domainMigratePerform          = NULL,
    .domainMigrateFinish           = NULL,
    .domainBlockStats              = NULL,
    .domainInterfaceStats          = NULL,
    .domainBlockPeek               = NULL,
    .domainMemoryPeek              = NULL,
    .nodeGetCellsFreeMemory        = NULL,
    .getFreeMemory                 = NULL,
    .domainEventRegister           = NULL,
    .domainEventDeregister         = NULL,
    .domainMigratePrepare2         = NULL,
    .domainMigrateFinish2          = NULL,
};