vbox_tmpl.c 269.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/** @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.
 */

/*
11
 * Copyright (C) 2010 Red Hat, Inc.
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
 * 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>
39
#include <stdbool.h>
40 41 42 43 44

#include "internal.h"

#include "datatypes.h"
#include "domain_conf.h"
45
#include "network_conf.h"
46
#include "virterror_internal.h"
47
#include "domain_event.h"
48
#include "storage_conf.h"
49
#include "storage_file.h"
50
#include "uuid.h"
51
#include "event.h"
52 53 54 55 56 57 58 59
#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"
60 61
#elif VBOX_API_VERSION == 3000
# include "vbox_CAPI_v3_0.h"
62 63
#elif VBOX_API_VERSION == 3001
# include "vbox_CAPI_v3_1.h"
64 65
#else
# error "Unsupport VBOX_API_VERSION"
66 67
#endif

68 69 70 71
/* Include this *last* or we'll get the wrong vbox_CAPI_*.h. */
#include "vbox_XPCOMCGlue.h"


72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
#define VIR_FROM_THIS                   VIR_FROM_VBOX
#define VBOX_UTF16_FREE(arg)            data->pFuncs->pfnUtf16Free(arg)
#define VBOX_UTF8_FREE(arg)             data->pFuncs->pfnUtf8Free(arg)
#define VBOX_COM_UNALLOC_MEM(arg)       data->pFuncs->pfnComUnallocMem(arg)
#define VBOX_UTF16_TO_UTF8(arg1, arg2)  data->pFuncs->pfnUtf16ToUtf8(arg1, arg2)
#define VBOX_UTF8_TO_UTF16(arg1, arg2)  data->pFuncs->pfnUtf8ToUtf16(arg1, arg2)

#define VBOX_RELEASE(arg) \
if(arg)\
    (arg)->vtbl->nsisupports.Release((nsISupports *)(arg))

#define VBOX_OBJECT_CHECK(conn, type, value) \
vboxGlobalData *data = conn->privateData;\
type ret = value;\
if(!data->vboxObj) {\
    return ret;\
}

#define VBOX_OBJECT_HOST_CHECK(conn, type, value) \
vboxGlobalData *data = conn->privateData;\
type ret = value;\
IHost *host = NULL;\
if(!data->vboxObj) {\
    return ret;\
}\
data->vboxObj->vtbl->GetHost(data->vboxObj, &host);\
if (!host) {\
    return ret;\
}

#if VBOX_API_VERSION < 3001

104
# define VBOX_MEDIUM_RELEASE(arg) \
105 106
if(arg)\
    (arg)->vtbl->imedium.nsisupports.Release((nsISupports *)(arg))
107
# define VBOX_MEDIUM_FUNC_ARG1(object, func, arg1) \
108
    (object)->vtbl->imedium.func((IMedium *)(object), arg1)
109
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
110 111 112 113 114 115
    (object)->vtbl->imedium.func((IMedium *)(object), arg1, arg2)

#else  /* VBOX_API_VERSION >= 3001 */

typedef IMedium IHardDisk;
typedef IMediumAttachment IHardDiskAttachment;
116 117 118 119 120
# define MediaState_Inaccessible     MediumState_Inaccessible
# define HardDiskVariant_Standard    MediumVariant_Standard
# define HardDiskVariant_Fixed       MediumVariant_Fixed
# define VBOX_MEDIUM_RELEASE(arg) VBOX_RELEASE(arg)
# define VBOX_MEDIUM_FUNC_ARG1(object, func, arg1) \
121
    (object)->vtbl->func(object, arg1)
122
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
123 124 125
    (object)->vtbl->func(object, arg1, arg2)

#endif /* VBOX_API_VERSION >= 3001 */
126

127
#define vboxError(conn, code, ...) \
128
        virReportErrorHelper(conn, VIR_FROM_VBOX, code, __FILE__, \
129
                             __FUNCTION__, __LINE__, __VA_ARGS__)
130

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
#define DEBUGPRUnichar(msg, strUtf16) \
if (strUtf16) {\
    char *strUtf8 = NULL;\
\
    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(strUtf16, &strUtf8);\
    if (strUtf8) {\
        DEBUG("%s: %s", msg, strUtf8);\
        g_pVBoxGlobalData->pFuncs->pfnUtf8Free(strUtf8);\
    }\
}

#define DEBUGUUID(msg, iid) \
{\
    DEBUG (msg ": {%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]);\
}\

158 159 160 161 162 163 164 165
typedef struct {
    virMutex lock;
    int version;

    virCapsPtr caps;

    IVirtualBox *vboxObj;
    ISession *vboxSession;
166 167 168

    /** Our version specific API table pointer. */
    PCVBOXXPCOM pFuncs;
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

#if VBOX_API_VERSION == 2002

} vboxGlobalData;

#else /* !(VBOX_API_VERSION == 2002) */

    /* An array of callbacks */
    virDomainEventCallbackListPtr domainEventCallbacks;

    int fdWatch;
    int domainEventDispatching;

    IVirtualBoxCallback *vboxCallback;

    nsIEventQueue  *vboxQueue;
    int volatile vboxCallBackRefCount;

    /* pointer back to the connection */
    virConnectPtr conn;

190 191
} vboxGlobalData;

192 193 194 195 196 197 198 199 200 201
/* g_pVBoxGlobalData has to be global variable,
 * there is no other way to make the callbacks
 * work other then having g_pVBoxGlobalData as
 * global, because the functions namely AddRef,
 * Release, etc consider it as global and you
 * can't change the function definition as it
 * is XPCOM nsISupport::* function and it expects
 * them that way
 */

202
static vboxGlobalData *g_pVBoxGlobalData = NULL;
203 204

#endif /* !(VBOX_API_VERSION == 2002) */
205

206 207 208 209
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml);
static int vboxDomainCreate(virDomainPtr dom);
static int vboxDomainUndefine(virDomainPtr dom);

210 211 212 213 214 215 216 217 218
static void vboxDriverLock(vboxGlobalData *data) {
    virMutexLock(&data->lock);
}

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

#if VBOX_API_VERSION == 2002
219

220 221 222 223 224 225 226
# define vboxIIDFromUUID(uuid, iid) nsIDFromChar((iid), (uuid))
# define vboxIIDToUUID(uuid, iid) nsIDtoChar((uuid), (iid))
# define vboxIIDUnalloc(iid) data->pFuncs->pfnComUnallocMem(iid)
# define vboxIIDFree(iid) VIR_FREE(iid)
# define vboxIIDUtf8Free(iid) VIR_FREE(iid)
# define vboxIIDUtf16Free(iid) VIR_FREE(iid)
# define DEBUGIID(msg, iid) DEBUGUUID(msg, iid)
227

228
static void nsIDtoChar(unsigned char *uuid, const nsID *iid) {
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
    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);
}

268
static void nsIDFromChar(nsID *iid, const unsigned char *uuid) {
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    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);
}

308 309
typedef nsID vboxIID;

310 311 312 313 314 315
static bool vboxIIDEqual(vboxIID *firstIID, vboxIID *secondIID) {
    if (memcmp(firstIID, secondIID, sizeof(firstIID)) == 0)
        return true;
    else
        return false;
}
316

317
static void vboxIIDtoUtf8(vboxIID *iid, char **uuidstr) {
318
    unsigned char hddUUID[VIR_UUID_BUFLEN];
319

320
    if (VIR_ALLOC_N(*uuidstr, VIR_UUID_STRING_BUFLEN) < 0) {
321
        virReportOOMError();
322 323 324 325 326 327 328
        return;
    }

    vboxIIDToUUID(hddUUID, iid);
    virUUIDFormat(hddUUID, *uuidstr);
}

329
static void vboxUtf8toIID(char *uuidstr, vboxIID **iid) {
330 331 332
    unsigned char hddUUID[VIR_UUID_BUFLEN];

    if (VIR_ALLOC(*iid) < 0) {
333
        virReportOOMError();
334 335 336 337 338 339 340
        return;
    }

    virUUIDParse(uuidstr, hddUUID);
    vboxIIDFromUUID(hddUUID, *iid);
}

341
#else /* VBOX_API_VERSION != 2002 */
342

343
# define vboxIIDFromUUID(uuid, iid)\
344 345 346 347 348 349 350
{\
    char vboxIIDUtf8[VIR_UUID_STRING_BUFLEN];\
\
    virUUIDFormat((uuid), vboxIIDUtf8);\
    data->pFuncs->pfnUtf8ToUtf16(vboxIIDUtf8, (&(iid)));\
}

351
# define vboxIIDToUUID(uuid, iid)\
352 353 354 355 356 357 358
{\
    char *vboxIIDUtf8  = NULL;\
    data->pFuncs->pfnUtf16ToUtf8((iid), &vboxIIDUtf8);\
    virUUIDParse(vboxIIDUtf8, (uuid));\
    data->pFuncs->pfnUtf8Free(vboxIIDUtf8);\
}

359 360 361 362 363
# define vboxIIDFree(iid) data->pFuncs->pfnUtf16Free(iid)
# define vboxIIDUtf8Free(iid) data->pFuncs->pfnUtf8Free(iid)
# define vboxIIDUtf16Free(iid) data->pFuncs->pfnUtf16Free(iid)
# define vboxIIDUnalloc(iid) data->pFuncs->pfnUtf16Free(iid)
# define DEBUGIID(msg, strUtf16) DEBUGPRUnichar(msg, strUtf16)
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
typedef PRUnichar vboxIID;

static bool vboxIIDEqual(vboxIID *firstIID, vboxIID *secondIID) {
    unsigned char firstUUID[VIR_UUID_BUFLEN];
    unsigned char secondUUID[VIR_UUID_BUFLEN];
    char *firstIIDUtf8  = NULL;
    char *secondIIDUtf8 = NULL;

    if (!g_pVBoxGlobalData)
        return false;

    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(firstIID, &firstIIDUtf8);
    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(secondIID, &secondIIDUtf8);

    /* Note: we can't directly compare the utf8 strings here
     * cause the two UUID's may have seperators as space or '-'
     * or mixture of both and we don't want to fail here by
     * using direct string comparison. Here virUUIDParse() takes
     * care of these cases.
     */

    virUUIDParse(firstIIDUtf8, firstUUID);
    virUUIDParse(secondIIDUtf8, secondUUID);

    g_pVBoxGlobalData->pFuncs->pfnUtf8Free(firstIIDUtf8);
    g_pVBoxGlobalData->pFuncs->pfnUtf8Free(secondIIDUtf8);

    if (memcmp(firstUUID, secondUUID, sizeof(firstIID)) == 0)
        return true;
    else
        return false;
}

398
static void vboxIIDtoUtf8(vboxIID *iid, char **uuidstr) {
399 400
    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(iid, uuidstr);
    if (!(*uuidstr))
401
        virReportOOMError();
402 403
}

404
static void vboxUtf8toIID(char *uuidstr, vboxIID **iid) {
405 406
    g_pVBoxGlobalData->pFuncs->pfnUtf8ToUtf16(uuidstr, iid);
    if (!(*iid))
407
        virReportOOMError();
408 409
}

410
# if VBOX_API_VERSION >= 3001
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426

/**
 * function to generate the name for medium,
 * for e.g: hda, sda, etc
 *
 * @returns     null terminated string with device name or NULL
 *              for failures
 * @param       conn            Input Connection Pointer
 * @param       storageBus      Input storage bus type
 * @param       deviceInst      Input device instance number
 * @param       devicePort      Input port number
 * @param       deviceSlot      Input slot number
 * @param       aMaxPortPerInst Input array of max port per device instance
 * @param       aMaxSlotPerPort Input array of max slot per device port
 *
 */
427
static char *vboxGenerateMediumName(PRUint32  storageBus,
428 429 430 431 432
                                    PRInt32   deviceInst,
                                    PRInt32   devicePort,
                                    PRInt32   deviceSlot,
                                    PRUint32 *aMaxPortPerInst,
                                    PRUint32 *aMaxSlotPerPort) {
433
    const char *prefix = NULL;
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
    char *name  = NULL;
    int   total = 0;
    PRUint32 maxPortPerInst = 0;
    PRUint32 maxSlotPerPort = 0;

    if (   !aMaxPortPerInst
        || !aMaxSlotPerPort)
        return NULL;

    if (   (storageBus < StorageBus_IDE)
        || (storageBus > StorageBus_Floppy))
        return NULL;

    maxPortPerInst = aMaxPortPerInst[storageBus];
    maxSlotPerPort = aMaxSlotPerPort[storageBus];
    total =   (deviceInst * maxPortPerInst * maxSlotPerPort)
            + (devicePort * maxSlotPerPort)
            + deviceSlot;

    if (storageBus == StorageBus_IDE) {
454
        prefix = "hd";
455 456
    } else if (   (storageBus == StorageBus_SATA)
               || (storageBus == StorageBus_SCSI)) {
457
        prefix = "sd";
458
    } else if (storageBus == StorageBus_Floppy) {
459
        prefix = "fd";
460 461
    }

462
    name = virIndexToDiskName(total, prefix);
463

464
    DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
465
          "devicePort=%d deviceSlot=%d, maxPortPerInst=%u maxSlotPerPort=%u",
466
          NULLSTR(name), total, storageBus, deviceInst, devicePort,
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 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
          deviceSlot, maxPortPerInst, maxSlotPerPort);
    return name;
}

/**
 * function to get the StorageBus, Port number
 * and Device number for the given devicename
 * e.g: hda has StorageBus = IDE, port = 0,
 *      device = 0
 *
 * @returns     true on Success, false on failure.
 * @param       deviceName      Input device name
 * @param       aMaxPortPerInst Input array of max port per device instance
 * @param       aMaxSlotPerPort Input array of max slot per device port
 * @param       storageBus      Input storage bus type
 * @param       deviceInst      Output device instance number
 * @param       devicePort      Output port number
 * @param       deviceSlot      Output slot number
 *
 */
static bool vboxGetDeviceDetails(const char *deviceName,
                                 PRUint32   *aMaxPortPerInst,
                                 PRUint32   *aMaxSlotPerPort,
                                 PRUint32    storageBus,
                                 PRInt32    *deviceInst,
                                 PRInt32    *devicePort,
                                 PRInt32    *deviceSlot) {
    int total = 0;
    PRUint32 maxPortPerInst = 0;
    PRUint32 maxSlotPerPort = 0;

    if (   !deviceName
        || !deviceInst
        || !devicePort
        || !deviceSlot
        || !aMaxPortPerInst
        || !aMaxSlotPerPort)
        return false;

    if (   (storageBus < StorageBus_IDE)
        || (storageBus > StorageBus_Floppy))
        return false;

    total = virDiskNameToIndex(deviceName);

    maxPortPerInst = aMaxPortPerInst[storageBus];
    maxSlotPerPort = aMaxSlotPerPort[storageBus];

    if (   !maxPortPerInst
        || !maxSlotPerPort
        || (total < 0))
        return false;

    *deviceInst = total / (maxPortPerInst * maxSlotPerPort);
    *devicePort = (total % (maxPortPerInst * maxSlotPerPort)) / maxSlotPerPort;
    *deviceSlot = (total % (maxPortPerInst * maxSlotPerPort)) % maxSlotPerPort;

    DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
          "devicePort=%d deviceSlot=%d, maxPortPerInst=%u maxSlotPerPort=%u",
          deviceName, total, storageBus, *deviceInst, *devicePort,
          *deviceSlot, maxPortPerInst, maxSlotPerPort);

    return true;
}

/**
 * function to get the values for max port per
 * instance and max slots per port for the devices
 *
 * @returns     true on Success, false on failure.
 * @param       vbox            Input IVirtualBox pointer
 * @param       maxPortPerInst  Output array of max port per instance
 * @param       maxSlotPerPort  Output array of max slot per port
 *
 */

static bool vboxGetMaxPortSlotValues(IVirtualBox *vbox,
                                     PRUint32 *maxPortPerInst,
                                     PRUint32 *maxSlotPerPort) {
    ISystemProperties *sysProps = NULL;

    if (!vbox)
        return false;

    vbox->vtbl->GetSystemProperties(vbox, &sysProps);

    if (!sysProps)
        return false;

    sysProps->vtbl->GetMaxPortCountForStorageBus(sysProps,
                                                 StorageBus_IDE,
                                                 &maxPortPerInst[StorageBus_IDE]);
    sysProps->vtbl->GetMaxPortCountForStorageBus(sysProps,
                                                 StorageBus_SATA,
                                                 &maxPortPerInst[StorageBus_SATA]);
    sysProps->vtbl->GetMaxPortCountForStorageBus(sysProps,
                                                 StorageBus_SCSI,
                                                 &maxPortPerInst[StorageBus_SCSI]);
    sysProps->vtbl->GetMaxPortCountForStorageBus(sysProps,
                                                 StorageBus_Floppy,
                                                 &maxPortPerInst[StorageBus_Floppy]);

    sysProps->vtbl->GetMaxDevicesPerPortForStorageBus(sysProps,
                                                      StorageBus_IDE,
                                                      &maxSlotPerPort[StorageBus_IDE]);
    sysProps->vtbl->GetMaxDevicesPerPortForStorageBus(sysProps,
                                                      StorageBus_SATA,
                                                      &maxSlotPerPort[StorageBus_SATA]);
    sysProps->vtbl->GetMaxDevicesPerPortForStorageBus(sysProps,
                                                      StorageBus_SCSI,
                                                      &maxSlotPerPort[StorageBus_SCSI]);
    sysProps->vtbl->GetMaxDevicesPerPortForStorageBus(sysProps,
                                                      StorageBus_Floppy,
                                                      &maxSlotPerPort[StorageBus_Floppy]);

    VBOX_RELEASE(sysProps);

    return true;
}

/**
 * Converts Utf-16 string to int
 */
static int PRUnicharToInt(PRUnichar *strUtf16) {
    char *strUtf8 = NULL;
    int ret = 0;

    if (!strUtf16)
        return -1;

    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(strUtf16, &strUtf8);
    if (!strUtf8)
        return -1;

    ret = atoi(strUtf8);
    g_pVBoxGlobalData->pFuncs->pfnUtf8Free(strUtf8);

    return ret;
}

/**
 * Converts int to Utf-16 string
 */
static PRUnichar *PRUnicharFromInt(int n) {
    PRUnichar *strUtf16 = NULL;
    char s[24];

    snprintf(s, sizeof(s), "%d", n);

    g_pVBoxGlobalData->pFuncs->pfnUtf8ToUtf16(s, &strUtf16);

    return strUtf16;
}

621
# endif /* VBOX_API_VERSION >= 3001 */
622

623 624
#endif /* !(VBOX_API_VERSION == 2002) */

625 626 627 628 629 630 631 632 633 634 635
static virCapsPtr vboxCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

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

636
    if (nodeCapsInitNUMA(caps) < 0)
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
        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) {
P
Pritesh Kothari 已提交
666

667 668 669 670 671
    /* 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)
672
        goto cleanup;
673 674 675

#if VBOX_XPCOMC_VERSION == 0x00010000U
    data->pFuncs->pfnComInitialize(&data->vboxObj, &data->vboxSession);
676
#else  /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
677 678
    data->pFuncs->pfnComInitialize(IVIRTUALBOX_IID_STR, &data->vboxObj,
                               ISESSION_IID_STR, &data->vboxSession);
679

680
# if VBOX_API_VERSION == 2002
681 682 683

    /* No event queue functionality in 2.2.* as of now */

684
# else  /* !(VBOX_API_VERSION == 2002) */
685 686 687 688 689 690 691 692 693 694 695

    /* Initial the fWatch needed for Event Callbacks */
    data->fdWatch = -1;

    data->pFuncs->pfnGetEventQueue(&data->vboxQueue);

    if (data->vboxQueue == NULL) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR, "nsIEventQueue object is null");
        goto cleanup;
    }

696
# endif /* !(VBOX_API_VERSION == 2002) */
697
#endif /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
698 699 700

    if (data->vboxObj == NULL) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR, "IVirtualBox object is null");
701
        goto cleanup;
702 703 704 705 706 707
    }

    if (data->vboxSession == NULL) {
        vboxError(conn, VIR_ERR_INTERNAL_ERROR, "ISession object is null");
        goto cleanup;
    }
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

    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;

730
        VBOX_UTF16_TO_UTF8(versionUtf16, &vboxVersion);
731 732 733 734

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

735 736
        VBOX_UTF8_FREE(vboxVersion);
        VBOX_COM_UNALLOC_MEM(versionUtf16);
737 738 739 740 741 742 743 744 745 746 747 748 749
    } 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) {
750 751 752
    if (!data)
        return;

753 754
    if (data->pFuncs)
        data->pFuncs->pfnComUninitialize();
755 756

    virCapabilitiesFree(data->caps);
757 758 759 760 761
#if VBOX_API_VERSION == 2002
    /* No domainEventCallbacks in 2.2.* version */
#else  /* !(VBOX_API_VERSION == 2002) */
    VIR_FREE(data->domainEventCallbacks);
#endif /* !(VBOX_API_VERSION == 2002) */
762 763 764 765 766 767
    VIR_FREE(data);
}

static virDrvOpenStatus vboxOpen(virConnectPtr conn,
                                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                 int flags ATTRIBUTE_UNUSED) {
768
    vboxGlobalData *data = NULL;
769 770 771 772 773
    uid_t uid = getuid();

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "vbox:///session" : "vbox:///system");
        if (conn->uri == NULL) {
774
            virReportOOMError();
775 776 777 778
            return VIR_DRV_OPEN_ERROR;
        }
    }

779 780 781 782 783 784
    if (conn->uri->scheme == NULL ||
        STRNEQ (conn->uri->scheme, "vbox"))
        return VIR_DRV_OPEN_DECLINED;

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

787 788 789 790 791 792
    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;
    }

793
    if (uid != 0) {
794 795 796 797 798
        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;
        }
799 800
    } else { /* root */
        if (STRNEQ (conn->uri->path, "/system") &&
801 802 803 804 805
            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;
        }
806 807 808
    }

    if (VIR_ALLOC(data) < 0) {
809
        virReportOOMError();
810
        return VIR_DRV_OPEN_ERROR;
811 812
    }

813 814 815 816 817 818
    if (!(data->caps = vboxCapsInit()) ||
        vboxInitialize(conn, data) < 0 ||
        vboxExtractVersion(conn, data) < 0) {
        vboxUninitialize(data);
        return VIR_DRV_OPEN_ERROR;
    }
819

820 821 822 823 824 825 826
#if VBOX_API_VERSION == 2002

    /* No domainEventCallbacks in 2.2.* version */

#else  /* !(VBOX_API_VERSION == 2002) */

    if (VIR_ALLOC(data->domainEventCallbacks) < 0) {
827
        virReportOOMError();
828 829 830 831 832 833 834 835
        return VIR_DRV_OPEN_ERROR;
    }

    data->conn = conn;
    g_pVBoxGlobalData = data;

#endif /* !(VBOX_API_VERSION == 2002) */

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
    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;
}

863 864 865 866 867 868 869 870 871 872
static int vboxIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED) {
    /* Driver is using local, non-network based transport */
    return 1;
}

static int vboxIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED) {
    /* No encryption is needed, or used on the local transport*/
    return 0;
}

873
static int vboxGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED) {
874
    VBOX_OBJECT_CHECK(conn, int, -1);
875 876 877 878 879
    PRUint32 maxCPUCount = 0;

    /* VirtualBox Supports only hvm and thus the type passed to it
     * has no meaning, setting it to ATTRIBUTE_UNUSED
     */
880
    ISystemProperties *systemProperties = NULL;
881

882 883 884 885
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
886 887 888 889 890 891 892 893 894 895
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}


static char *vboxGetCapabilities(virConnectPtr conn) {
896
    VBOX_OBJECT_CHECK(conn, char *, NULL);
897 898 899 900 901 902 903 904 905

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

    return ret;
}

static int vboxListDomains(virConnectPtr conn, int *ids, int nids) {
906
    VBOX_OBJECT_CHECK(conn, int, -1);
907 908 909
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    PRUint32 state;
910
    nsresult rc;
911 912
    int i, j;

913 914 915 916 917 918
    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;
    }
919

920 921 922 923
    if (machineCnt == 0) {
        ret = 0;
        goto cleanup;
    }
924

925 926 927 928 929 930 931 932 933 934 935 936
    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_FirstOnline)
                    && (state <= MachineState_LastOnline) ) {
                    ret++;
                    ids[j++] = i + 1;
937 938 939 940
                }
            }
        }
    }
941
    ret++;
942 943 944

cleanup:
    for (i = 0; i < machineCnt; ++i)
945
        VBOX_RELEASE(machines[i]);
946 947 948 949
    return ret;
}

static int vboxNumOfDomains(virConnectPtr conn) {
950
    VBOX_OBJECT_CHECK(conn, int, -1);
951 952 953
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    PRUint32 state;
954
    nsresult rc;
955 956
    int i;

957 958 959 960 961 962
    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;
    }
963

964 965 966 967
    if (machineCnt == 0) {
        ret = 0;
        goto cleanup;
    }
968

969 970 971 972 973 974 975 976 977 978 979 980
    /* 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_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret++;
981 982 983
            }
        }
    }
984
    ret++;
985 986 987

cleanup:
    for (i = 0; i < machineCnt; ++i)
988
        VBOX_RELEASE(machines[i]);
989 990 991 992 993 994 995 996 997 998 999 1000 1001
    return ret;
}

static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
                                        unsigned int flags ATTRIBUTE_UNUSED) {
    /* 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.
     */

1002 1003 1004 1005 1006 1007
    virDomainPtr dom = vboxDomainDefineXML(conn, xml);
    if (dom == NULL)
        return NULL;

    if (vboxDomainCreate(dom) < 0) {
        vboxDomainUndefine(dom);
1008
        virUnrefDomain(dom);
1009
        return NULL;
1010 1011 1012 1013 1014 1015
    }

    return dom;
}

static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id) {
1016
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1017 1018
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
1019
    vboxIID *iid         = NULL;
1020 1021
    unsigned char iidl[VIR_UUID_BUFLEN];
    PRUint32 state;
1022
    nsresult rc;
1023 1024
    int i;

1025 1026 1027 1028 1029 1030 1031 1032 1033
    /* 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;

1034 1035 1036 1037 1038 1039
    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;
    }
1040

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
    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_FirstOnline)
                    && (state <= MachineState_LastOnline) ) {
                    PRUnichar *machineNameUtf16 = NULL;
                    char      *machineNameUtf8  = NULL;
1051

1052 1053
                    machines[id]->vtbl->GetName(machines[id], &machineNameUtf16);
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1054

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                    machines[id]->vtbl->GetId(machines[id], &iid);
                    vboxIIDToUUID(iidl, iid);
                    vboxIIDUnalloc(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.
                     */

                    ret = virGetDomain(conn, machineNameUtf8, iidl);
                    if (ret)
                        ret->id = id + 1;

                    /* Cleanup all the XPCOM allocated stuff here */
                    VBOX_UTF8_FREE(machineNameUtf8);
                    VBOX_UTF16_FREE(machineNameUtf16);
1072 1073 1074 1075 1076
                }
            }
        }
    }

1077 1078 1079 1080 1081
    /* Do the cleanup as required by GetMachines() */
    for (i = 0; i < machineCnt; ++i)
        VBOX_RELEASE(machines[i]);

    return ret;
1082 1083 1084
}

static virDomainPtr vboxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid) {
1085
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1086 1087
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
1088 1089
    vboxIID *iid         = NULL;
    char      *machineNameUtf8  = NULL;
1090 1091 1092
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;
1093
    nsresult rc;
1094

1095 1096 1097 1098 1099 1100
    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;
    }
1101

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

1106 1107
        if (!machine)
            continue;
1108

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

1112 1113 1114 1115 1116
            machine->vtbl->GetId(machine, &iid);
            if (!iid)
                continue;
            vboxIIDToUUID(iidl, iid);
            vboxIIDUnalloc(iid);
1117

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

1120
                PRUint32 state;
1121

1122
                matched = 1;
1123

1124 1125
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1126

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

1129 1130 1131 1132 1133
                /* 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.
                 */
1134

1135 1136 1137 1138 1139
                ret = virGetDomain(conn, machineNameUtf8, iidl);
                if (   ret
                    && (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret->id = i + 1;
1140 1141
            }

1142 1143
            if (matched == 1)
                break;
1144 1145 1146
        }
    }

1147 1148 1149 1150 1151 1152 1153
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
    for (i = 0; i < machineCnt; ++i)
        VBOX_RELEASE(machines[i]);

    return ret;
1154 1155 1156
}

static virDomainPtr vboxDomainLookupByName(virConnectPtr conn, const char *name) {
1157
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1158 1159
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
1160 1161
    vboxIID *iid         = NULL;
    char      *machineNameUtf8  = NULL;
1162 1163 1164
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;
1165
    nsresult rc;
1166

1167 1168 1169 1170 1171 1172
    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;
    }
1173

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

1178 1179
        if (!machine)
            continue;
1180

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

1184 1185
            machine->vtbl->GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1186

1187
            if (STREQ(name, machineNameUtf8)) {
1188

1189
                PRUint32 state;
1190

1191
                matched = 1;
1192

1193 1194 1195
                machine->vtbl->GetId(machine, &iid);
                vboxIIDToUUID(iidl, iid);
                vboxIIDUnalloc(iid);
1196

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

1199 1200 1201 1202 1203
                /* 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.
                 */
1204

1205 1206 1207 1208 1209
                ret = virGetDomain(conn, machineNameUtf8, iidl);
                if (   ret
                    && (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret->id = i + 1;
1210 1211
            }

1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
            if (machineNameUtf8) {
                VBOX_UTF8_FREE(machineNameUtf8);
                machineNameUtf8 = NULL;
            }
            if (machineNameUtf16) {
                VBOX_COM_UNALLOC_MEM(machineNameUtf16);
                machineNameUtf16 = NULL;
            }
            if (matched == 1)
                break;
1222 1223 1224
        }
    }

1225 1226 1227 1228 1229
    /* Do the cleanup and take care you dont leak any memory */
    for (i = 0; i < machineCnt; ++i)
        VBOX_RELEASE(machines[i]);

    return ret;
1230 1231
}

1232 1233

static int vboxDomainIsActive(virDomainPtr dom) {
1234
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1235 1236 1237 1238 1239 1240 1241
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    vboxIID *iid         = NULL;
    char      *machineNameUtf8  = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;
1242
    nsresult rc;
1243

1244 1245 1246 1247 1248 1249
    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);
        return ret;
    }
1250

1251 1252 1253 1254 1255 1256 1257 1258 1259
    for (i = 0; i < machineCnt; ++i) {
        IMachine *machine = machines[i];
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

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

1261 1262
            machine->vtbl->GetId(machine, &iid);
            if (!iid)
1263
                continue;
1264 1265
            vboxIIDToUUID(iidl, iid);
            vboxIIDUnalloc(iid);
1266

1267
            if (memcmp(dom->uuid, iidl, VIR_UUID_BUFLEN) == 0) {
1268

1269
                PRUint32 state;
1270

1271
                matched = 1;
1272

1273 1274
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1275

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

1278 1279 1280 1281 1282
                if (   (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret = 1;
                else
                    ret = 0;
1283 1284
            }

1285 1286
            if (matched == 1)
                break;
1287 1288 1289
        }
    }

1290 1291 1292 1293 1294 1295
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
    for (i = 0; i < machineCnt; ++i)
        VBOX_RELEASE(machines[i]);

1296 1297 1298 1299 1300
    return ret;
}


static int vboxDomainIsPersistent(virDomainPtr dom ATTRIBUTE_UNUSED) {
1301
    /* All domains are persistent. */
1302 1303 1304 1305
    return 1;
}


1306
static int vboxDomainSuspend(virDomainPtr dom) {
1307
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1308
    IMachine *machine    = NULL;
1309
    vboxIID  *iid        = NULL;
1310
    IConsole *console    = NULL;
1311
    PRBool isAccessible  = PR_FALSE;
1312
    PRUint32 state;
1313
    nsresult rc;
1314

1315
#if VBOX_API_VERSION == 2002
1316
    if (VIR_ALLOC(iid) < 0) {
1317
        virReportOOMError();
1318 1319
        goto cleanup;
    }
1320
#endif
1321

1322 1323 1324 1325 1326 1327 1328
    vboxIIDFromUUID(dom->uuid, iid);
    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;
    }
1329

1330 1331
    if (!machine)
        goto cleanup;
1332

1333 1334 1335
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1336

1337 1338 1339 1340 1341 1342 1343 1344
        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);
                VBOX_RELEASE(console);
                ret = 0;
1345 1346
            } else {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
1347
                          "%s", "error while suspend the domain");
1348 1349
                goto cleanup;
            }
1350 1351 1352 1353 1354
            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;
1355 1356 1357 1358
        }
    }

cleanup:
1359
    VBOX_RELEASE(machine);
1360
    vboxIIDFree(iid);
1361 1362 1363 1364
    return ret;
}

static int vboxDomainResume(virDomainPtr dom) {
1365
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1366
    IMachine *machine    = NULL;
1367
    vboxIID  *iid        = NULL;
1368 1369
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1370
    nsresult rc;
1371

1372
#if VBOX_API_VERSION == 2002
1373
    if (VIR_ALLOC(iid) < 0) {
1374
        virReportOOMError();
1375 1376
        goto cleanup;
    }
1377
#endif
1378

1379
    PRBool isAccessible = PR_FALSE;
1380

1381 1382 1383 1384 1385 1386 1387
    vboxIIDFromUUID(dom->uuid, iid);
    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;
    }
1388

1389 1390
    if (!machine)
        goto cleanup;
1391

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
    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);
                VBOX_RELEASE(console);
                ret = 0;
1404 1405
            } else {
                vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
1406
                          "%s", "error while resuming the domain");
1407 1408
                goto cleanup;
            }
1409 1410 1411 1412 1413
            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;
1414 1415 1416 1417
        }
    }

cleanup:
1418
    VBOX_RELEASE(machine);
1419
    vboxIIDFree(iid);
1420 1421 1422 1423
    return ret;
}

static int vboxDomainShutdown(virDomainPtr dom) {
1424
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1425
    IMachine *machine    = NULL;
1426
    vboxIID  *iid        = NULL;
1427 1428
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1429 1430
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1431

1432
#if VBOX_API_VERSION == 2002
1433
    if (VIR_ALLOC(iid) < 0) {
1434
        virReportOOMError();
1435 1436
        goto cleanup;
    }
1437
#endif
1438

1439 1440 1441 1442 1443 1444 1445
    vboxIIDFromUUID(dom->uuid, iid);
    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;
    }
1446

1447 1448
    if (!machine)
        goto cleanup;
1449

1450 1451 1452
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1453

1454 1455 1456 1457 1458 1459 1460 1461 1462
        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;
        }
1463

1464 1465 1466 1467 1468 1469
        data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
            console->vtbl->PowerButton(console);
            VBOX_RELEASE(console);
            ret = 0;
1470
        }
1471
        data->vboxSession->vtbl->Close(data->vboxSession);
1472 1473 1474
    }

cleanup:
1475
    VBOX_RELEASE(machine);
1476
    vboxIIDFree(iid);
1477 1478 1479 1480
    return ret;
}

static int vboxDomainReboot(virDomainPtr dom, unsigned int flags ATTRIBUTE_UNUSED) {
1481
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1482
    IMachine *machine    = NULL;
1483
    vboxIID  *iid        = NULL;
1484 1485
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1486 1487
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1488

1489
#if VBOX_API_VERSION == 2002
1490
    if (VIR_ALLOC(iid) < 0) {
1491
        virReportOOMError();
1492 1493
        goto cleanup;
    }
1494
#endif
1495

1496 1497 1498 1499 1500 1501 1502
    vboxIIDFromUUID(dom->uuid, iid);
    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;
    }
1503

1504 1505
    if (!machine)
        goto cleanup;
1506

1507 1508 1509
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1510

1511 1512 1513 1514 1515 1516 1517
        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);
                VBOX_RELEASE(console);
                ret = 0;
1518
            }
1519 1520 1521 1522 1523
            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;
1524 1525 1526 1527
        }
    }

cleanup:
1528
    VBOX_RELEASE(machine);
1529
    vboxIIDFree(iid);
1530 1531 1532 1533
    return ret;
}

static int vboxDomainDestroy(virDomainPtr dom) {
1534
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1535
    IMachine *machine    = NULL;
1536
    vboxIID  *iid        = NULL;
1537 1538
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1539 1540
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1541

1542
#if VBOX_API_VERSION == 2002
1543
    if (VIR_ALLOC(iid) < 0) {
1544
        virReportOOMError();
1545 1546
        goto cleanup;
    }
1547
#endif
1548

1549 1550 1551 1552 1553 1554 1555
    vboxIIDFromUUID(dom->uuid, iid);
    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;
    }
1556

1557 1558
    if (!machine)
        goto cleanup;
1559

1560 1561 1562
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1563

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

1570 1571 1572
        data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
1573 1574

#if VBOX_API_VERSION == 2002
1575
            console->vtbl->PowerDown(console);
1576
#else
1577 1578 1579 1580 1581
            IProgress *progress;
            console->vtbl->PowerDown(console, &progress);
            if (progress) {
                progress->vtbl->WaitForCompletion(progress, -1);
                VBOX_RELEASE(progress);
1582
            }
1583 1584 1585
#endif
            VBOX_RELEASE(console);
            ret = 0;
1586
        }
1587
        data->vboxSession->vtbl->Close(data->vboxSession);
1588 1589 1590
    }

cleanup:
1591
    VBOX_RELEASE(machine);
1592
    vboxIIDFree(iid);
1593 1594 1595
    return ret;
}

1596
static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
1597 1598 1599 1600 1601
    /* 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 ;)
     */
1602 1603 1604
    char *osType = strdup("hvm");

    if (osType == NULL)
1605
        virReportOOMError();
1606 1607

    return osType;
1608 1609 1610
}

static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory) {
1611
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1612
    IMachine *machine    = NULL;
1613
    vboxIID  *iid        = NULL;
1614
    PRUint32 state       = MachineState_Null;
1615 1616
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1617

1618
#if VBOX_API_VERSION == 2002
1619
    if (VIR_ALLOC(iid) < 0) {
1620
        virReportOOMError();
1621 1622
        goto cleanup;
    }
1623
#endif
1624

1625 1626 1627 1628 1629 1630 1631
    vboxIIDFromUUID(dom->uuid, iid);
    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;
    }
1632

1633 1634
    if (!machine)
        goto cleanup;
1635

1636 1637 1638
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1639

1640 1641 1642 1643 1644
        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;
        }
1645

1646 1647 1648 1649
        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) {
1650

1651 1652 1653 1654 1655 1656 1657 1658
                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);
1659 1660
                }
            }
1661
            data->vboxSession->vtbl->Close(data->vboxSession);
1662 1663 1664 1665
        }
    }

cleanup:
1666
    VBOX_RELEASE(machine);
1667
    vboxIIDFree(iid);
1668 1669 1670 1671
    return ret;
}

static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info) {
1672
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1673 1674 1675 1676
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1677 1678
    nsresult rc;
    int i = 0;
1679

1680 1681 1682 1683 1684 1685
    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;
    }
1686

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

1692 1693
        if (!machine)
            continue;
1694

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

1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
            machine->vtbl->GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);

            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.
                */
                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);
                    VBOX_RELEASE(systemProperties);
                    systemProperties = NULL;
                }
1722 1723


1724 1725 1726 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
                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;
1755 1756
                }

1757
                ret = 0;
1758 1759
            }

1760 1761 1762 1763 1764 1765
            if (machineName)
                VBOX_UTF8_FREE(machineName);
            if (machineNameUtf16)
                VBOX_COM_UNALLOC_MEM(machineNameUtf16);
            if (info->nrVirtCpu)
                break;
1766 1767 1768 1769
        }

    }

1770 1771 1772
    /* Do the cleanup and take care you dont leak any memory */
    for (i = 0; i < machineCnt; ++i)
        VBOX_RELEASE(machines[i]);
1773 1774 1775 1776 1777 1778

cleanup:
    return ret;
}

static int vboxDomainSave(virDomainPtr dom, const char *path ATTRIBUTE_UNUSED) {
1779
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1780
    IConsole *console    = NULL;
1781
    vboxIID  *iid        = NULL;
1782
    nsresult rc;
1783 1784 1785 1786 1787 1788 1789

    /* 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
     */
1790
#if VBOX_API_VERSION == 2002
1791
    if (VIR_ALLOC(iid) < 0) {
1792
        virReportOOMError();
1793 1794
        goto cleanup;
    }
1795
#endif
1796

1797 1798 1799 1800 1801 1802 1803
    /* Open a Session for the machine */
    vboxIIDFromUUID(dom->uuid, iid);
    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;
1804

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

1807
            if (progress) {
1808
#if VBOX_API_VERSION == 2002
1809
                nsresult resultCode;
1810
#else
1811
                PRInt32 resultCode;
1812
#endif
1813

1814 1815 1816 1817
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_SUCCEEDED(resultCode)) {
                    ret = 0;
1818
                }
1819
                VBOX_RELEASE(progress);
1820
            }
1821
            VBOX_RELEASE(console);
1822
        }
1823
        data->vboxSession->vtbl->Close(data->vboxSession);
1824 1825
    }

1826 1827
    DEBUGIID("UUID of machine being saved:", iid);

1828
#if VBOX_API_VERSION == 2002
1829
cleanup:
1830 1831
#endif
    vboxIIDFree(iid);
1832 1833 1834
    return ret;
}

1835
static int vboxDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
1836
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1837 1838 1839
    IMachine *machine    = NULL;
    vboxIID  *iid        = NULL;
    PRUint32  CPUCount   = nvcpus;
1840
    nsresult rc;
1841 1842 1843

#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
1844
        virReportOOMError();
1845 1846 1847 1848
        goto cleanup;
    }
#endif

1849
    vboxIIDFromUUID(dom->uuid, iid);
1850

1851 1852 1853 1854 1855 1856 1857 1858
    rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, iid);
    if (NS_SUCCEEDED(rc)) {
        data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
        if (machine) {
            rc = machine->vtbl->SetCPUCount(machine, CPUCount);
            if (NS_SUCCEEDED(rc)) {
                machine->vtbl->SaveSettings(machine);
                ret = 0;
1859
            } else {
1860 1861 1862
                vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR, "%s: %u, rc=%08x",
                          "could not set the number of cpus of the domain to",
                          CPUCount, (unsigned)rc);
1863
            }
1864
            VBOX_RELEASE(machine);
1865 1866
        } else {
            vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
1867
                      "no domain with matching id %d", dom->id);
1868
        }
1869 1870 1871
    } else {
        vboxError(dom->conn, VIR_ERR_INVALID_DOMAIN,
                  "can't open session to the domain with id %d", dom->id);
1872
    }
1873
    data->vboxSession->vtbl->Close(data->vboxSession);
1874 1875 1876 1877 1878 1879 1880 1881 1882

#if VBOX_API_VERSION == 2002
cleanup:
#endif
    vboxIIDFree(iid);
    return ret;
}

static int vboxDomainGetMaxVcpus(virDomainPtr dom) {
1883 1884
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    ISystemProperties *systemProperties = NULL;
1885 1886 1887 1888 1889 1890 1891
    PRUint32 maxCPUCount = 0;

    /* Currently every domain supports the same number of max cpus
     * as that supported by vbox and thus take it directly from
     * the systemproperties.
     */

1892 1893 1894 1895
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
1896 1897 1898 1899 1900 1901 1902 1903
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}

1904
static char *vboxDomainDumpXML(virDomainPtr dom, int flags) {
1905
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
1906 1907
    virDomainDefPtr def  = NULL;
    IMachine *machine    = NULL;
1908
    vboxIID  *iid        = NULL;
1909
    int gotAllABoutDef   = -1;
1910
    nsresult rc;
1911

1912
#if VBOX_API_VERSION == 2002
1913
    if (VIR_ALLOC(iid) < 0) {
1914
        virReportOOMError();
1915 1916
        goto cleanup;
    }
1917
#endif
1918 1919

    if (VIR_ALLOC(def) < 0) {
1920
        virReportOOMError();
1921 1922 1923
        goto cleanup;
    }

1924 1925 1926 1927
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_SUCCEEDED(rc) && machine) {
        PRBool accessible = PR_FALSE;
1928

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 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
        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;
            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;
#if VBOX_API_VERSION < 3001
            PRInt32       hddNum                = 0;
            IDVDDrive    *dvdDrive              = NULL;
            IHardDisk    *hardDiskPM            = NULL;
            IHardDisk    *hardDiskPS            = NULL;
            IHardDisk    *hardDiskSS            = NULL;
            const char   *hddBus                = "IDE";
            PRUnichar    *hddBusUtf16           = NULL;
            IFloppyDrive *floppyDrive           = NULL;
#else  /* VBOX_API_VERSION >= 3001 */
            PRUint32      mediumAttachSize      = 0;
            IMediumAttachment **mediumAttachments = NULL;
#endif /* VBOX_API_VERSION >= 3001 */
            IVRDPServer *VRDPServer             = NULL;
            IAudioAdapter *audioAdapter         = NULL;
            IUSBController *USBController       = NULL;
            ISystemProperties *systemProperties = NULL;
1966 1967


1968 1969 1970 1971
            def->virtType = VIR_DOMAIN_VIRT_VBOX;
            def->id = dom->id;
            memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
            def->name = strdup(dom->name);
1972

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

1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
            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);
                VBOX_RELEASE(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");
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
            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 */
2025
                }
2026
            }
2027

2028 2029 2030 2031 2032 2033 2034 2035 2036
            def->features = 0;
#if VBOX_API_VERSION < 3001
            machine->vtbl->GetPAEEnabled(machine, &PAEEnabled);
#else  /* VBOX_API_VERSION >= 3001 */
            machine->vtbl->GetCpuProperty(machine, CpuPropertyType_PAE, &PAEEnabled);
#endif /* VBOX_API_VERSION >= 3001 */
            if (PAEEnabled) {
                def->features = def->features | (1 << VIR_DOMAIN_FEATURE_PAE);
            }
2037

2038 2039 2040 2041 2042 2043
            machine->vtbl->GetBIOSSettings(machine, &bios);
            if (bios) {
                bios->vtbl->GetACPIEnabled(bios, &ACPIEnabled);
                if (ACPIEnabled) {
                    def->features = def->features | (1 << VIR_DOMAIN_FEATURE_ACPI);
                }
2044

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

2050 2051 2052 2053 2054
                VBOX_RELEASE(bios);
            }

            /* Currently VirtualBox always uses locatime
             * so locatime is always true here */
2055
            def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;
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

            /* dump video options vram/2d/3d/directx/etc. */
            {
                /* Currently supports only one graphics card */
                def->nvideos = 1;
                if (VIR_ALLOC_N(def->videos, def->nvideos) >= 0) {
                    if (VIR_ALLOC(def->videos[0]) >= 0) {
                        /* the default is: vram is 8MB, One monitor, 3dAccel Off */
                        PRUint32 VRAMSize          = 8 * 1024;
                        PRUint32 monitorCount      = 1;
                        PRBool accelerate3DEnabled = PR_FALSE;
                        PRBool accelerate2DEnabled = PR_FALSE;

                        machine->vtbl->GetVRAMSize(machine, &VRAMSize);
                        machine->vtbl->GetMonitorCount(machine, &monitorCount);
                        machine->vtbl->GetAccelerate3DEnabled(machine, &accelerate3DEnabled);
#if VBOX_API_VERSION >= 3001
                        machine->vtbl->GetAccelerate2DVideoEnabled(machine, &accelerate2DEnabled);
#endif /* VBOX_API_VERSION >= 3001 */

                        def->videos[0]->type            = VIR_DOMAIN_VIDEO_TYPE_VBOX;
                        def->videos[0]->vram            = VRAMSize;
                        def->videos[0]->heads           = monitorCount;
                        if (VIR_ALLOC(def->videos[0]->accel) >= 0) {
                            def->videos[0]->accel->support3d = accelerate3DEnabled;
                            def->videos[0]->accel->support2d = accelerate2DEnabled;
2082
                        } else
2083
                            virReportOOMError();
2084
                    } else
2085
                        virReportOOMError();
2086
                } else
2087
                    virReportOOMError();
2088
            }
2089

2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100
            /* 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;
2101

2102
                def->ngraphics = 0;
2103

2104 2105 2106
                VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
                machine->vtbl->GetExtraData(machine, keyTypeUtf16, &valueTypeUtf16);
                VBOX_UTF16_FREE(keyTypeUtf16);
2107

2108 2109 2110
                if (valueTypeUtf16) {
                    VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
                    VBOX_UTF16_FREE(valueTypeUtf16);
2111

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

2117 2118 2119
                        VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
                        machine->vtbl->GetExtraData(machine, keyDislpayUtf16, &valueDisplayUtf16);
                        VBOX_UTF16_FREE(keyDislpayUtf16);
2120

2121 2122 2123
                        if (valueDisplayUtf16) {
                            VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                            VBOX_UTF16_FREE(valueDisplayUtf16);
2124

2125 2126 2127
                            if (strlen(valueDisplayUtf8) <= 0) {
                                VBOX_UTF8_FREE(valueDisplayUtf8);
                                valueDisplayUtf8 = NULL;
2128 2129
                            }
                        }
2130

2131 2132 2133 2134 2135
                        if (STREQ(valueTypeUtf8, "sdl")) {
                            sdlPresent = 1;
                            if (valueDisplayUtf8)
                                sdlDisplay = strdup(valueDisplayUtf8);
                            if (sdlDisplay == NULL) {
2136
                                virReportOOMError();
2137 2138 2139 2140 2141 2142
                                /* 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++;
2143
                        }
2144

2145 2146 2147 2148 2149
                        if (STREQ(valueTypeUtf8, "gui")) {
                            guiPresent = 1;
                            if (valueDisplayUtf8)
                                guiDisplay = strdup(valueDisplayUtf8);
                            if (guiDisplay == NULL) {
2150
                                virReportOOMError();
2151
                                /* just don't go to cleanup yet as it is ok to have
2152 2153
                                 * guiDisplay as NULL and we check it below if it
                                 * exist and then only use it there
2154
                                 */
2155
                            }
2156 2157
                            totalPresent++;
                        }
2158 2159
                        if (valueDisplayUtf8)
                            VBOX_UTF8_FREE(valueDisplayUtf8);
2160 2161
                    }

2162 2163
                    if (STREQ(valueTypeUtf8, "vrdp"))
                        vrdpPresent = 1;
2164

2165 2166
                    VBOX_UTF8_FREE(valueTypeUtf8);
                }
2167

2168 2169 2170 2171 2172 2173 2174
                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++;
                    }
2175

2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
                    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) {
2187
                            virReportOOMError();
2188 2189 2190 2191 2192 2193 2194 2195
                            /* just don't go to cleanup yet as it is ok to have
                             * display as NULL
                             */
                        }
                        totalPresent++;
                        def->ngraphics++;
                    }
                }
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
                machine->vtbl->GetVRDPServer(machine, &VRDPServer);
                if (VRDPServer) {
                    VRDPServer->vtbl->GetEnabled(VRDPServer, &VRDPEnabled);
                    if (VRDPEnabled) {

                        totalPresent++;

                        if ((VIR_REALLOC_N(def->graphics, totalPresent) >= 0) &&
                            (VIR_ALLOC(def->graphics[def->ngraphics]) >= 0)) {
                            PRUnichar *netAddressUtf16   = NULL;
                            char      *netAddressUtf8    = NULL;
                            PRBool allowMultiConnection  = PR_FALSE;
                            PRBool reuseSingleConnection = PR_FALSE;
#if VBOX_API_VERSION < 3001
                            PRUint32 VRDPport = 0;
                            VRDPServer->vtbl->GetPort(VRDPServer, &VRDPport);
                            if (VRDPport) {
                                def->graphics[def->ngraphics]->data.rdp.port = VRDPport;
#else  /* VBOX_API_VERSION >= 3001 */
                            PRUnichar *VRDPport = NULL;
                            VRDPServer->vtbl->GetPorts(VRDPServer, &VRDPport);
                            if (VRDPport) {
                                /* even if vbox supports mutilpe ports, single port for now here */
                                def->graphics[def->ngraphics]->data.rdp.port = PRUnicharToInt(VRDPport);
                                VBOX_UTF16_FREE(VRDPport);
#endif /* VBOX_API_VERSION >= 3001 */
                            } else {
                                def->graphics[def->ngraphics]->data.rdp.autoport = 1;
                            }
2226

2227
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;
2228

2229 2230 2231 2232 2233 2234 2235 2236
                            VRDPServer->vtbl->GetNetAddress(VRDPServer, &netAddressUtf16);
                            if (netAddressUtf16) {
                                VBOX_UTF16_TO_UTF8(netAddressUtf16, &netAddressUtf8);
                                if (STRNEQ(netAddressUtf8, ""))
                                        def->graphics[def->ngraphics]->data.rdp.listenAddr = strdup(netAddressUtf8);
                                VBOX_UTF16_FREE(netAddressUtf16);
                                VBOX_UTF8_FREE(netAddressUtf8);
                            }
2237

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

2243 2244 2245 2246
                            VRDPServer->vtbl->GetReuseSingleConnection(VRDPServer, &reuseSingleConnection);
                            if (reuseSingleConnection) {
                                def->graphics[def->ngraphics]->data.rdp.replaceUser = 1;
                            }
2247

2248
                            def->ngraphics++;
2249
                        } else
2250
                            virReportOOMError();
2251
                    }
2252
                    VBOX_RELEASE(VRDPServer);
2253
                }
2254
            }
2255

2256 2257 2258
#if VBOX_API_VERSION < 3001
            /* dump IDE hdds if present */
            VBOX_UTF8_TO_UTF16(hddBus, &hddBusUtf16);
2259

2260 2261 2262 2263
            def->ndisks = 0;
            machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 0,  &hardDiskPM);
            if (hardDiskPM)
                def->ndisks++;
2264

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

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

2273 2274 2275 2276 2277 2278 2279 2280 2281
            VBOX_UTF16_FREE(hddBusUtf16);

            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;
                    } else
2282
                        virReportOOMError();
2283
                }
2284
            }
2285

2286 2287 2288 2289
            if (hardDiskPM) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2290

2291 2292
                hardDiskPM->vtbl->imedium.GetLocation((IMedium *)hardDiskPM, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2293

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

2296 2297 2298 2299 2300
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hda");
                hddNum++;
2301

2302 2303 2304 2305
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPM);
            }
2306

2307 2308 2309 2310
            if (hardDiskPS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2311

2312 2313
                hardDiskPS->vtbl->imedium.GetLocation((IMedium *)hardDiskPS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2314

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

2317 2318 2319 2320 2321
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hdb");
                hddNum++;
2322

2323 2324 2325 2326
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPS);
            }
2327

2328 2329 2330 2331
            if (hardDiskSS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2332

2333 2334
                hardDiskSS->vtbl->imedium.GetLocation((IMedium *)hardDiskSS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2335

2336
                hardDiskSS->vtbl->GetType(hardDiskSS, &hddType);
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
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hdd");
                hddNum++;

                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskSS);
            }
#else  /* VBOX_API_VERSION >= 3001 */
            /* dump IDE hdds if present */

            bool error = false;
            int diskCount = 0;
            PRUint32   maxPortPerInst[StorageBus_Floppy + 1] = {};
            PRUint32   maxSlotPerPort[StorageBus_Floppy + 1] = {};
            def->ndisks = 0;
            machine->vtbl->GetMediumAttachments(machine, &mediumAttachSize, &mediumAttachments);

            /* get the number of attachments */
            for (i = 0; i < mediumAttachSize; i++) {
                IMediumAttachment *imediumattach = mediumAttachments[i];
                if (imediumattach) {
                    IMedium *medium = NULL;

                    imediumattach->vtbl->GetMedium(imediumattach, &medium);
                    if (medium) {
                        def->ndisks++;
                        VBOX_RELEASE(medium);
2368 2369
                    }
                }
2370
            }
2371

2372 2373 2374 2375
            /* Allocate mem, if fails return error */
            if (VIR_ALLOC_N(def->disks, def->ndisks) >= 0) {
                for (i = 0; i < def->ndisks; i++) {
                    if (VIR_ALLOC(def->disks[i]) < 0) {
2376
                        virReportOOMError();
2377 2378
                        error = true;
                        break;
2379 2380
                    }
                }
2381
            } else {
2382
                virReportOOMError();
2383 2384 2385 2386 2387 2388 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
                error = true;
            }

            if (!error)
                error = !vboxGetMaxPortSlotValues(data->vboxObj, maxPortPerInst, maxSlotPerPort);

            /* get the attachment details here */
            for (i = 0; i < mediumAttachSize && diskCount < def->ndisks && !error; i++) {
                IMediumAttachment *imediumattach = mediumAttachments[i];
                IStorageController *storageController = NULL;
                PRUnichar *storageControllerName = NULL;
                PRUint32   deviceType     = DeviceType_Null;
                PRUint32   storageBus     = StorageBus_Null;
                PRBool     readOnly       = PR_FALSE;
                IMedium   *medium         = NULL;
                PRUnichar *mediumLocUtf16 = NULL;
                char      *mediumLocUtf8  = NULL;
                PRUint32   deviceInst     = 0;
                PRInt32    devicePort     = 0;
                PRInt32    deviceSlot     = 0;

                if (!imediumattach)
                    continue;

                imediumattach->vtbl->GetMedium(imediumattach, &medium);
                if (!medium)
                    continue;

                imediumattach->vtbl->GetController(imediumattach, &storageControllerName);
                if (!storageControllerName) {
                    VBOX_RELEASE(medium);
                    continue;
                }

                machine->vtbl->GetStorageControllerByName(machine,
                                                          storageControllerName,
                                                          &storageController);
                VBOX_UTF16_FREE(storageControllerName);
                if (!storageController) {
                    VBOX_RELEASE(medium);
                    continue;
                }
2425

2426 2427 2428 2429 2430 2431 2432 2433 2434
                medium->vtbl->GetLocation(medium, &mediumLocUtf16);
                VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8);
                VBOX_UTF16_FREE(mediumLocUtf16);
                def->disks[diskCount]->src = strdup(mediumLocUtf8);
                VBOX_UTF8_FREE(mediumLocUtf8);

                if (!(def->disks[diskCount]->src)) {
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
2435
                    virReportOOMError();
2436 2437 2438
                    error = true;
                    break;
                }
2439

2440 2441 2442 2443 2444 2445 2446 2447 2448 2449
                storageController->vtbl->GetBus(storageController, &storageBus);
                if (storageBus == StorageBus_IDE) {
                    def->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_IDE;
                } else if (storageBus == StorageBus_SATA) {
                    def->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_SATA;
                } else if (storageBus == StorageBus_SCSI) {
                    def->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_SCSI;
                } else if (storageBus == StorageBus_Floppy) {
                    def->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_FDC;
                }
2450

2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
                imediumattach->vtbl->GetType(imediumattach, &deviceType);
                if (deviceType == DeviceType_HardDisk)
                    def->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_DISK;
                else if (deviceType == DeviceType_Floppy)
                    def->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                else if (deviceType == DeviceType_DVD)
                    def->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_CDROM;

                imediumattach->vtbl->GetPort(imediumattach, &devicePort);
                imediumattach->vtbl->GetDevice(imediumattach, &deviceSlot);
2461
                def->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
                                                                    deviceInst,
                                                                    devicePort,
                                                                    deviceSlot,
                                                                    maxPortPerInst,
                                                                    maxSlotPerPort);
                if (!def->disks[diskCount]->dst) {
                    vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,
                              "%s: controller instance:%u, port:%d, slot:%d",
                              "Could not generate medium name for the disk at",
                              deviceInst, devicePort, deviceSlot);
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2477

2478 2479 2480
                medium->vtbl->GetReadOnly(medium, &readOnly);
                if (readOnly == PR_TRUE)
                    def->disks[diskCount]->readonly = 1;
2481

2482
                def->disks[diskCount]->type = VIR_DOMAIN_DISK_TYPE_FILE;
2483

2484 2485 2486 2487
                VBOX_RELEASE(medium);
                VBOX_RELEASE(storageController);
                diskCount++;
            }
2488

2489 2490 2491
            /* free the memory */
            for (i = 0; i < mediumAttachSize; i++)
                VBOX_RELEASE(mediumAttachments[i]);
2492

2493 2494 2495 2496 2497 2498 2499 2500
            /* cleanup on error */
            if (error) {
                for (i = 0; i < def->ndisks; i++) {
                    VIR_FREE(def->disks[i]);
                }
                VIR_FREE(def->disks);
                def->ndisks = 0;
            }
2501

2502
#endif /* VBOX_API_VERSION >= 3001 */
2503

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

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

2514 2515 2516 2517
                    adapter->vtbl->GetEnabled(adapter, &enabled);
                    if (enabled) {
                        def->nnets++;
                    }
2518

2519 2520 2521
                    VBOX_RELEASE(adapter);
                }
            }
2522

2523 2524 2525 2526 2527
            /* 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) {
                    } else
2528
                        virReportOOMError();
2529 2530
                }
            }
2531

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

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

2540 2541 2542 2543 2544 2545 2546
                    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};
2547

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

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

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

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

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

2561 2562
                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
                            def->nets[netAdpIncCnt]->data.bridge.brname = strdup(hostInt);
2563

2564 2565
                            VBOX_UTF8_FREE(hostInt);
                            VBOX_UTF16_FREE(hostIntUtf16);
2566

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

2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616
                            def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_INTERNAL;

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

                            VBOX_UTF16_TO_UTF8(intNetUtf16, &intNet);
                            def->nets[netAdpIncCnt]->data.internal.name = strdup(intNet);

                            VBOX_UTF8_FREE(intNet);
                            VBOX_UTF16_FREE(intNetUtf16);

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

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

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

                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
                            def->nets[netAdpIncCnt]->data.network.name = strdup(hostInt);

                            VBOX_UTF8_FREE(hostInt);
                            VBOX_UTF16_FREE(hostIntUtf16);

                        } 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");
#if VBOX_API_VERSION >= 3001
                        } else if (adapterType == NetworkAdapterType_Virtio) {
                            def->nets[netAdpIncCnt]->model = strdup("virtio");
#endif /* VBOX_API_VERSION >= 3001 */
2617 2618
                        }

2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
                        adapter->vtbl->GetMACAddress(adapter, &MACAddressUtf16);
                        VBOX_UTF16_TO_UTF8(MACAddressUtf16, &MACAddress);
                        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]);

                        /* XXX some real error handling here some day ... */
                        if (virParseMacAddr(macaddr, def->nets[netAdpIncCnt]->mac) < 0)
                        {}

                        netAdpIncCnt++;

                        VBOX_UTF16_FREE(MACAddressUtf16);
                        VBOX_UTF8_FREE(MACAddress);
2635
                    }
2636 2637

                    VBOX_RELEASE(adapter);
2638
                }
2639
            }
2640

2641
            /* dump sound card if active */
2642

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

2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
            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_AC97;
                            }
                        } else {
                            VIR_FREE(def->sounds);
                            def->nsounds = 0;
2667
                            virReportOOMError();
2668 2669 2670
                        }
                    } else {
                        def->nsounds = 0;
2671
                        virReportOOMError();
2672 2673 2674 2675
                    }
                }
                VBOX_RELEASE(audioAdapter);
            }
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
#if VBOX_API_VERSION < 3001
            /* 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);
                        VBOX_UTF16_TO_UTF8(locationUtf16, &location);

                        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");
2704
                            } else {
2705
                                def->ndisks--;
2706
                                virReportOOMError();
2707 2708
                            }
                        } else {
2709
                            def->ndisks--;
2710
                            virReportOOMError();
2711
                        }
2712 2713 2714 2715

                        VBOX_UTF8_FREE(location);
                        VBOX_UTF16_FREE(locationUtf16);
                        VBOX_MEDIUM_RELEASE(dvdImage);
2716 2717
                    }
                }
2718 2719
                VBOX_RELEASE(dvdDrive);
            }
2720

2721 2722 2723 2724 2725 2726 2727
            /* 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) {
2728 2729
                    PRUint32 state = DriveState_Null;

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

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

2739 2740
                            floppyImage->vtbl->imedium.GetLocation((IMedium *)floppyImage, &locationUtf16);
                            VBOX_UTF16_TO_UTF8(locationUtf16, &location);
2741 2742 2743 2744

                            def->ndisks++;
                            if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
                                if (VIR_ALLOC(def->disks[def->ndisks - 1]) >= 0) {
2745 2746
                                    def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                                    def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC;
2747
                                    def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE;
2748
                                    def->disks[def->ndisks - 1]->readonly = 0;
2749
                                    def->disks[def->ndisks - 1]->src = strdup(location);
2750
                                    def->disks[def->ndisks - 1]->dst = strdup("fda");
2751 2752
                                } else {
                                    def->ndisks--;
2753
                                    virReportOOMError();
2754 2755 2756
                                }
                            } else {
                                def->ndisks--;
2757
                                virReportOOMError();
2758 2759
                            }

2760 2761 2762
                            VBOX_UTF8_FREE(location);
                            VBOX_UTF16_FREE(locationUtf16);
                            VBOX_MEDIUM_RELEASE(floppyImage);
2763 2764 2765 2766
                        }
                    }
                }

2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
                VBOX_RELEASE(floppyDrive);
            }
#else  /* VBOX_API_VERSION >= 3001 */
#endif /* VBOX_API_VERSION >= 3001 */

            /* 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) {
2780 2781
                    PRBool enabled = PR_FALSE;

2782
                    serialPort->vtbl->GetEnabled(serialPort, &enabled);
2783
                    if (enabled) {
2784
                        def->nserials++;
2785 2786
                    }

2787
                    VBOX_RELEASE(serialPort);
2788
                }
2789
            }
2790

2791 2792 2793 2794 2795
            /* 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) {
                    } else
2796
                        virReportOOMError();
2797 2798
                }
            }
2799

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

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

2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
                    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;
#if VBOX_API_VERSION >= 3000
                        } else if (hostMode == PortMode_RawFile) {
                            def->serials[serialPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_FILE;
#endif /* VBOX_API_VERSION >= 3000 */
                        } else {
                            def->serials[serialPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_NULL;
                        }
2828

2829
                        def->serials[serialPortIncCount]->targetType = VIR_DOMAIN_CHR_TARGET_TYPE_SERIAL;
2830

2831 2832 2833 2834 2835 2836 2837
                        serialPort->vtbl->GetIRQ(serialPort, &IRQ);
                        serialPort->vtbl->GetIOBase(serialPort, &IOBase);
                        if ((IRQ == 4) && (IOBase == 1016)) {
                            def->serials[serialPortIncCount]->target.port = 0;
                        } else if ((IRQ == 3) && (IOBase == 760)) {
                            def->serials[serialPortIncCount]->target.port = 1;
                        }
2838

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

2841 2842
                        if (pathUtf16) {
                            VBOX_UTF16_TO_UTF8(pathUtf16, &path);
2843 2844 2845
                            def->serials[serialPortIncCount]->data.file.path = strdup(path);
                        }

2846 2847 2848 2849
                        serialPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
2850 2851
                    }

2852 2853 2854
                    VBOX_RELEASE(serialPort);
                }
            }
2855

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

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

2866 2867 2868
                    parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                    if (enabled) {
                        def->nparallels++;
2869
                    }
2870 2871

                    VBOX_RELEASE(parallelPort);
2872
                }
2873
            }
2874

2875 2876 2877 2878 2879
            /* 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) {
                    } else
2880
                        virReportOOMError();
2881
                }
2882
            }
2883

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

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

2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
                    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]->target.port = 0;
                        } else if ((IRQ == 5) && (IOBase == 632)) {
                            def->parallels[parallelPortIncCount]->target.port = 1;
                        }
2906

2907 2908
                        def->parallels[parallelPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_FILE;
                        def->parallels[parallelPortIncCount]->targetType = VIR_DOMAIN_CHR_TARGET_TYPE_PARALLEL;
2909

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

2912 2913
                        VBOX_UTF16_TO_UTF8(pathUtf16, &path);
                        def->parallels[parallelPortIncCount]->data.file.path = strdup(path);
2914

2915 2916 2917 2918
                        parallelPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
2919
                    }
2920 2921

                    VBOX_RELEASE(parallelPort);
2922
                }
2923
            }
2924

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

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

2936 2937 2938
                    USBController->vtbl->GetDeviceFilters(USBController,
                                                          &deviceFiltersNum,
                                                          &deviceFilters);
2939

2940
                    if (deviceFiltersNum > 0) {
2941

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

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

2949 2950 2951
                            deviceFilters[i]->vtbl->GetActive(deviceFilters[i], &active);
                            if (active) {
                                def->nhostdevs++;
2952
                            }
2953
                        }
2954

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

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

2962 2963 2964 2965 2966 2967 2968 2969 2970 2971
                                    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;
2972

2973 2974 2975 2976
                                            def->hostdevs[USBFilterCount]->mode =
                                                VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
                                            def->hostdevs[USBFilterCount]->source.subsys.type =
                                                VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB;
2977

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

2981 2982
                                            VBOX_UTF16_TO_UTF8(vendorIdUtf16, &vendorIdUtf8);
                                            VBOX_UTF16_TO_UTF8(productIdUtf16, &productIdUtf8);
2983

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

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

2990 2991
                                            VBOX_UTF16_FREE(vendorIdUtf16);
                                            VBOX_UTF8_FREE(vendorIdUtf8);
2992

2993 2994
                                            VBOX_UTF16_FREE(productIdUtf16);
                                            VBOX_UTF8_FREE(productIdUtf8);
2995

2996 2997
                                            USBFilterCount++;
                                        } else
2998
                                            virReportOOMError();
2999
                                    }
3000 3001
                                }
                            } else
3002
                                virReportOOMError();
3003 3004 3005
                        }
                    }

3006 3007 3008 3009 3010
                    /* Cleanup */
                    for(i = 0; i < deviceFiltersNum; i++)
                        VBOX_RELEASE(deviceFilters[i]);
                }
                VBOX_RELEASE(USBController);
3011
            }
3012 3013 3014 3015 3016

            /* all done so set gotAllABoutDef and pass def to virDomainDefFormat
             * to generate XML for it
             */
            gotAllABoutDef = 0;
3017
        }
3018 3019
        VBOX_RELEASE(machine);
        machine = NULL;
3020 3021 3022
    }

    if (gotAllABoutDef == 0)
3023
        ret = virDomainDefFormat(def, flags);
3024 3025

cleanup:
3026
    vboxIIDFree(iid);
3027 3028 3029 3030 3031
    virDomainDefFree(def);
    return ret;
}

static int vboxListDefinedDomains(virConnectPtr conn, char ** const names, int maxnames) {
3032
    VBOX_OBJECT_CHECK(conn, int, -1);
3033 3034 3035 3036 3037
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
3038
    nsresult rc;
3039 3040
    int i, j;

3041 3042 3043 3044 3045 3046
    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;
    }
3047

3048 3049 3050 3051
    if (machineCnt == 0) {
        ret = 0;
        goto cleanup;
    }
3052

3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
    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_FirstOnline)
                    || (state > MachineState_LastOnline) ) {
                    machine->vtbl->GetName(machine, &machineNameUtf16);
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);
                    if (!(names[j++] = strdup(machineName))) {
3066
                        virReportOOMError();
3067 3068 3069 3070
                        for ( ; j >= 0 ; j--)
                            VIR_FREE(names[j]);
                        ret = -1;
                        goto cleanup;
3071
                    }
3072
                    ret++;
3073 3074 3075 3076
                }
            }
        }
    }
3077
    ret++;
3078 3079

cleanup:
3080 3081
    VBOX_UTF8_FREE(machineName);
    VBOX_UTF16_FREE(machineNameUtf16);
3082
    for (i = 0; i < machineCnt; ++i)
3083
        VBOX_RELEASE(machines[i]);
3084 3085 3086 3087
    return ret;
}

static int vboxNumOfDefinedDomains(virConnectPtr conn) {
3088
    VBOX_OBJECT_CHECK(conn, int, -1);
3089 3090 3091
    IMachine **machines  = NULL;
    PRUint32 machineCnt  = 0;
    PRUint32 state       = MachineState_Null;
3092
    nsresult rc;
3093 3094
    int i;

3095 3096 3097 3098 3099 3100
    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;
    }
3101

3102 3103 3104 3105
    if (machineCnt == 0) {
        ret = 0;
        goto cleanup;
    }
3106

3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118
    /* 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_FirstOnline)
                    || (state > MachineState_LastOnline) ) {
                    ret++;
3119 3120 3121 3122
                }
            }
        }
    }
3123
    ret++;
3124 3125 3126

cleanup:
    for (i = 0; i < machineCnt; ++i)
3127
        VBOX_RELEASE(machines[i]);
3128 3129 3130 3131
    return ret;
}

static int vboxDomainCreate(virDomainPtr dom) {
3132
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
3133 3134 3135 3136 3137 3138 3139
    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};
3140 3141
    nsresult rc;
    int i = 0;
3142 3143 3144 3145 3146 3147 3148

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

3149 3150 3151 3152 3153 3154
    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;
    }
3155

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

3160 3161
        if (!machine)
            continue;
3162

3163 3164 3165
        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            vboxIID *iid = NULL;
3166

3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193
            machine->vtbl->GetId(machine, &iid);
            if (!iid)
                continue;
            vboxIIDToUUID(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) ) {
                    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;

                    VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
                    machine->vtbl->GetExtraData(machine, keyTypeUtf16, &valueTypeUtf16);
                    VBOX_UTF16_FREE(keyTypeUtf16);
3194

3195 3196 3197
                    if (valueTypeUtf16) {
                        VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
                        VBOX_UTF16_FREE(valueTypeUtf16);
3198

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

3201 3202 3203
                            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
                            machine->vtbl->GetExtraData(machine, keyDislpayUtf16, &valueDisplayUtf16);
                            VBOX_UTF16_FREE(keyDislpayUtf16);
3204

3205 3206 3207
                            if (valueDisplayUtf16) {
                                VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                                VBOX_UTF16_FREE(valueDisplayUtf16);
3208

3209 3210 3211
                                if (strlen(valueDisplayUtf8) <= 0) {
                                    VBOX_UTF8_FREE(valueDisplayUtf8);
                                    valueDisplayUtf8 = NULL;
3212
                                }
3213
                            }
3214

3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
                            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
                                         */
3225 3226 3227 3228
                                    }
                                }
                            }

3229
                            if (STREQ(valueTypeUtf8, "gui")) {
3230
                                guiPresent = 1;
3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
                                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
                                         */
                                    }
                                }
3241
                            }
3242
                        }
3243

3244 3245 3246
                        if (STREQ(valueTypeUtf8, "vrdp")) {
                            vrdpPresent = 1;
                        }
3247

3248 3249 3250 3251
                        if (!vrdpPresent && !sdlPresent && !guiPresent) {
                            /* if nothing is selected it means either the machine xml
                             * file is really old or some values are missing so fallback
                             */
3252 3253 3254
                            guiPresent = 1;
                        }

3255
                        VBOX_UTF8_FREE(valueTypeUtf8);
3256

3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267
                    } else {
                        guiPresent = 1;
                    }
                    if (valueDisplayUtf8)
                        VBOX_UTF8_FREE(valueDisplayUtf8);

                    if (guiPresent) {
                        if (guiDisplay) {
                            sprintf(displayutf8, "DISPLAY=%.24s", guiDisplay);
                            VBOX_UTF8_TO_UTF16(displayutf8, &env);
                            VIR_FREE(guiDisplay);
3268 3269
                        }

3270 3271
                        VBOX_UTF8_TO_UTF16("gui", &sessionType);
                    }
3272

3273 3274 3275 3276 3277
                    if (sdlPresent) {
                        if (sdlDisplay) {
                            sprintf(displayutf8, "DISPLAY=%.24s", sdlDisplay);
                            VBOX_UTF8_TO_UTF16(displayutf8, &env);
                            VIR_FREE(sdlDisplay);
3278 3279
                        }

3280 3281
                        VBOX_UTF8_TO_UTF16("sdl", &sessionType);
                    }
3282

3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
                    if (vrdpPresent) {
                        VBOX_UTF8_TO_UTF16("vrdp", &sessionType);
                    }

                    rc = 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;
3299
#if VBOX_API_VERSION == 2002
3300
                        nsresult resultCode;
3301
#else
3302
                        PRInt32  resultCode;
3303
#endif
3304 3305 3306 3307 3308
                        progress->vtbl->WaitForCompletion(progress, -1);
                        rc = progress->vtbl->GetCompleted(progress, &completed);
                        if (NS_FAILED(rc)) {
                            /* error */
                            ret = -1;
3309
                        }
3310 3311 3312 3313 3314 3315 3316 3317 3318 3319
                        progress->vtbl->GetResultCode(progress, &resultCode);
                        if (NS_FAILED(resultCode)) {
                            /* error */
                            ret = -1;
                        } else {
                            /* all ok set the domid */
                            dom->id = i + 1;
                            ret = 0;
                        }
                    }
3320

3321
                    VBOX_RELEASE(progress);
3322

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

3325 3326 3327 3328 3329
                } else {
                    vboxError(dom->conn, VIR_ERR_OPERATION_FAILED,
                              "%s", "machine is not in poweroff|saved|"
                                    "aborted state, so couldn't start it");
                    ret = -1;
3330 3331
                }
            }
3332 3333 3334
            vboxIIDUnalloc(iid);
            if (ret != -1)
                break;
3335 3336 3337
        }
    }

3338 3339 3340 3341 3342 3343
    /* Do the cleanup and take care you dont leak any memory */
    for (i = 0; i < machineCnt; ++i)
        VBOX_RELEASE(machines[i]);

    VBOX_UTF16_FREE(env);
    VBOX_UTF16_FREE(sessionType);
3344 3345 3346 3347 3348 3349

cleanup:
    return ret;
}

static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml) {
3350
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
3351 3352 3353 3354 3355
    IMachine       *machine     = NULL;
    IBIOSSettings  *bios        = NULL;
    vboxIID        *iid         = NULL;
    vboxIID        *mchiid      = NULL;
    virDomainDefPtr def         = NULL;
3356
    PRUnichar *machineNameUtf16 = NULL;
3357
    nsresult rc;
3358

3359
    if (!(def = virDomainDefParseString(data->caps, xml,
3360 3361 3362 3363
                                        VIR_DOMAIN_XML_INACTIVE))) {
        goto cleanup;
    }

3364
#if VBOX_API_VERSION == 2002
3365
    if (VIR_ALLOC(iid) < 0) {
3366
        virReportOOMError();
3367 3368
        goto cleanup;
    }
3369
#endif
3370

3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385
    VBOX_UTF8_TO_UTF16(def->name, &machineNameUtf16);
    vboxIIDFromUUID(def->uuid, iid);
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
                                            iid,
                                            &machine);
    VBOX_UTF16_FREE(machineNameUtf16);

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

3387 3388 3389 3390 3391 3392
    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);
    }
3393

3394 3395 3396 3397 3398 3399
    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);
    }
3400

3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414
#if VBOX_API_VERSION < 3001
    rc = machine->vtbl->SetPAEEnabled(machine, (def->features) &
                                      (1 << VIR_DOMAIN_FEATURE_PAE));
#else  /* VBOX_API_VERSION >= 3001 */
    rc = machine->vtbl->SetCpuProperty(machine, CpuPropertyType_PAE,
                                       (def->features) &
                                       (1 << VIR_DOMAIN_FEATURE_PAE));
#endif /* VBOX_API_VERSION >= 3001 */
    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);
    }
3415

3416 3417 3418 3419
    machine->vtbl->GetBIOSSettings(machine, &bios);
    if (bios) {
        rc = bios->vtbl->SetACPIEnabled(bios, (def->features) &
                                        (1 << VIR_DOMAIN_FEATURE_ACPI));
3420 3421
        if (NS_FAILED(rc)) {
            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
3422 3423
                      "could not change ACPI status to",
                      ((def->features) & (1 << VIR_DOMAIN_FEATURE_ACPI))
3424 3425
                      ? "Enabled" : "Disabled", (unsigned)rc);
        }
3426 3427
        rc = bios->vtbl->SetIOAPICEnabled(bios, (def->features) &
                                          (1 << VIR_DOMAIN_FEATURE_APIC));
3428
        if (NS_FAILED(rc)) {
3429 3430 3431 3432
            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);
3433
        }
3434 3435
        VBOX_RELEASE(bios);
    }
3436

3437 3438 3439 3440 3441 3442 3443
    /* 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;
    }
3444

3445 3446 3447 3448 3449 3450 3451
    /* 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);
3452

3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473
    {   /* 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);
3474

3475 3476 3477 3478 3479 3480
        data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
        if (systemProperties) {
            systemProperties->vtbl->GetMaxBootPosition(systemProperties, &maxBootPosition);
            VBOX_RELEASE(systemProperties);
            systemProperties = NULL;
        }
3481

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

3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497
        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;
3498
            }
3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529
            machine->vtbl->SetBootOrder(machine, i+1, device);
        }
    }   /* Finished:Block to set the boot device order */

#if VBOX_API_VERSION < 3001
    {   /* 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");

                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
                         */
3530

3531 3532 3533 3534 3535
                        machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                        if (dvdDrive) {
                            IDVDImage *dvdImage          = NULL;
                            PRUnichar *dvdfileUtf16      = NULL;
                            vboxIID *dvduuid             = NULL;
3536
# if VBOX_API_VERSION == 2002
3537
                            nsID dvdemptyuuid;
3538

3539
                            memset(&dvdemptyuuid, 0, sizeof(dvdemptyuuid));
3540
# else
3541
                            PRUnichar *dvdemptyuuidUtf16 = NULL;
3542
# endif
3543

3544
                            VBOX_UTF8_TO_UTF16(def->disks[i]->src, &dvdfileUtf16);
3545

3546 3547
                            data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                            if (!dvdImage) {
3548
# if VBOX_API_VERSION == 2002
3549
                                data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, &dvdemptyuuid, &dvdImage);
3550
# else
3551
                                data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, dvdemptyuuidUtf16, &dvdImage);
3552
# endif
3553 3554 3555 3556 3557 3558 3559 3560 3561
                            }
                            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);
3562 3563
                                    if (NS_FAILED(rc)) {
                                        vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
3564
                                                  "could not attach the file to cdrom",
3565 3566
                                                  def->disks[i]->src, (unsigned)rc);
                                    } else {
3567
                                        DEBUGIID("CD/DVDImage UUID:", dvduuid);
3568 3569
                                    }
                                }
3570 3571

                                VBOX_MEDIUM_RELEASE(dvdImage);
3572
                            }
3573 3574 3575
                            vboxIIDUnalloc(dvduuid);
                            VBOX_UTF16_FREE(dvdfileUtf16);
                            VBOX_RELEASE(dvdDrive);
3576
                        }
3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
                    } 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;
                        vboxIID   *hdduuid      = NULL;
                        PRUnichar *hddEmpty     = NULL;
                        /* Current Limitation: Harddisk can't be connected to
                         * Secondary Master as Secondary Master is always used
                         * for CD/DVD Drive, so don't connect the harddisk if it
                         * is requested to be connected to Secondary master
                         */
3590

3591 3592
                        VBOX_UTF8_TO_UTF16(def->disks[i]->src, &hddfileUtf16);
                        VBOX_UTF8_TO_UTF16("", &hddEmpty);
3593

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

3596
                        if (!hardDisk) {
3597
# if VBOX_API_VERSION == 2002
3598 3599 3600 3601
                            data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                              hddfileUtf16,
                                                              AccessMode_ReadWrite,
                                                              &hardDisk);
3602
# else
3603 3604 3605 3606 3607 3608 3609 3610
                            data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                              hddfileUtf16,
                                                              AccessMode_ReadWrite,
                                                              0,
                                                              hddEmpty,
                                                              0,
                                                              hddEmpty,
                                                              &hardDisk);
3611
# endif
3612
                        }
3613

3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
                        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");
                                        VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16);
                                        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;
                                        }
3651

3652 3653 3654 3655 3656 3657
                                        rc = machine->vtbl->AttachHardDisk(machine,
                                                                           hdduuid,
                                                                           hddcnameUtf16,
                                                                           channel,
                                                                           device);
                                        VBOX_UTF16_FREE(hddcnameUtf16);
3658

3659 3660 3661 3662 3663 3664
                                        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 {
                                            DEBUGIID("Attached HDD with UUID", hdduuid);
3665 3666 3667 3668
                                        }
                                    }
                                }
                            }
3669
                            VBOX_MEDIUM_RELEASE(hardDisk);
3670
                        }
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
                        vboxIIDUnalloc(hdduuid);
                        VBOX_UTF16_FREE(hddEmpty);
                        VBOX_UTF16_FREE(hddfileUtf16);
                    } 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;
                                vboxIID *fduuid             = NULL;
3686
# if VBOX_API_VERSION == 2002
3687
                                nsID fdemptyuuid;
3688

3689
                                memset(&fdemptyuuid, 0, sizeof(fdemptyuuid));
3690
# else
3691
                                PRUnichar *fdemptyuuidUtf16 = NULL;
3692
# endif
3693

3694 3695 3696 3697
                                VBOX_UTF8_TO_UTF16(def->disks[i]->src, &fdfileUtf16);
                                rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                          fdfileUtf16,
                                                                          &floppyImage);
3698

3699 3700 3701
                                if (!floppyImage) {
                                    data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                         fdfileUtf16,
3702
# if VBOX_API_VERSION == 2002
3703
                                                                         &fdemptyuuid,
3704
# else
3705
                                                                         fdemptyuuidUtf16,
3706
# endif
3707 3708
                                                                         &floppyImage);
                                }
3709

3710 3711 3712 3713 3714 3715 3716 3717
                                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);
3718 3719
                                        if (NS_FAILED(rc)) {
                                            vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
3720
                                                      "could not attach the file to floppy drive",
3721 3722
                                                      def->disks[i]->src, (unsigned)rc);
                                        } else {
3723
                                            DEBUGIID("floppyImage UUID", fduuid);
3724 3725
                                        }
                                    }
3726
                                    VBOX_MEDIUM_RELEASE(floppyImage);
3727
                                }
3728 3729
                                vboxIIDUnalloc(fduuid);
                                VBOX_UTF16_FREE(fdfileUtf16);
3730
                            }
3731
                            VBOX_RELEASE(floppyDrive);
3732
                        }
3733
                    } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
3734 3735 3736
                    }
                }
            }
3737
        }
3738

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

3741 3742 3743 3744 3745 3746 3747
#else  /* VBOX_API_VERSION >= 3001 */
    {
        PRUint32 maxPortPerInst[StorageBus_Floppy + 1] = {};
        PRUint32 maxSlotPerPort[StorageBus_Floppy + 1] = {};
        PRUnichar *storageCtlName = NULL;
        bool error = false;
        int i = 0;
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
        /* get the max port/slots/etc for the given storage bus */
        error = !vboxGetMaxPortSlotValues(data->vboxObj, maxPortPerInst, maxSlotPerPort);

        /* add a storage controller for the mediums to be attached */
        /* this needs to change when multiple controller are supported for ver > 3.1 */
        {
            IStorageController *storageCtl = NULL;
            PRUnichar *sName = NULL;

            VBOX_UTF8_TO_UTF16("IDE Controller", &sName);
            machine->vtbl->AddStorageController(machine,
                                                sName,
                                                StorageBus_IDE,
                                                &storageCtl);
            VBOX_UTF16_FREE(sName);
            VBOX_RELEASE(storageCtl);

            VBOX_UTF8_TO_UTF16("SATA Controller", &sName);
            machine->vtbl->AddStorageController(machine,
                                                sName,
                                                StorageBus_SATA,
                                                &storageCtl);
            VBOX_UTF16_FREE(sName);
            VBOX_RELEASE(storageCtl);

            VBOX_UTF8_TO_UTF16("SCSI Controller", &sName);
            machine->vtbl->AddStorageController(machine,
                                                sName,
                                                StorageBus_SCSI,
                                                &storageCtl);
            VBOX_UTF16_FREE(sName);
            VBOX_RELEASE(storageCtl);

            VBOX_UTF8_TO_UTF16("Floppy Controller", &sName);
            machine->vtbl->AddStorageController(machine,
                                                sName,
                                                StorageBus_Floppy,
                                                &storageCtl);
            VBOX_UTF16_FREE(sName);
            VBOX_RELEASE(storageCtl);
        }

        /* Started:Block to attach the CDROM/DVD Drive and HardDisks to the VM */
        for (i = 0; i < def->ndisks && !error; 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");

            if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE) {
                IMedium   *medium          = NULL;
                PRUnichar *mediumUUID      = NULL;
                PRUnichar *mediumFileUtf16 = NULL;
                PRUint32   storageBus      = StorageBus_Null;
                PRUint32   deviceType      = DeviceType_Null;
                PRInt32    deviceInst      = 0;
                PRInt32    devicePort      = 0;
                PRInt32    deviceSlot      = 0;

                VBOX_UTF8_TO_UTF16(def->disks[i]->src, &mediumFileUtf16);

                if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                    deviceType = DeviceType_HardDisk;
                    data->vboxObj->vtbl->FindHardDisk(data->vboxObj, mediumFileUtf16, &medium);
                } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                    deviceType = DeviceType_DVD;
                    data->vboxObj->vtbl->FindDVDImage(data->vboxObj, mediumFileUtf16, &medium);
                } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                    deviceType = DeviceType_Floppy;
                    data->vboxObj->vtbl->FindFloppyImage(data->vboxObj, mediumFileUtf16, &medium);
                } else {
                    VBOX_UTF16_FREE(mediumFileUtf16);
                    continue;
                }

                if (!medium) {
                    PRUnichar *mediumEmpty = NULL;

                    VBOX_UTF8_TO_UTF16("", &mediumEmpty);

                    if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                        data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                          mediumFileUtf16,
                                                          AccessMode_ReadWrite,
                                                          false,
                                                          mediumEmpty,
                                                          false,
                                                          mediumEmpty,
                                                          &medium);
                    } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                          mediumFileUtf16,
                                                          mediumEmpty,
                                                          &medium);
                    } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                        data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                             mediumFileUtf16,
                                                             mediumEmpty,
                                                             &medium);
3854
                    }
3855 3856

                    VBOX_UTF16_FREE(mediumEmpty);
3857 3858
                }

3859 3860 3861 3862 3863 3864 3865
                if (!medium) {
                    vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                              "Failed to attach the following disk/dvd/floppy to the machine",
                              def->disks[i]->src, (unsigned)rc);
                    VBOX_UTF16_FREE(mediumFileUtf16);
                    continue;
                }
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
                rc = medium->vtbl->GetId(medium, &mediumUUID);
                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/dvd/floppy",
                              def->disks[i]->src, (unsigned)rc);
                    VBOX_RELEASE(medium);
                    VBOX_UTF16_FREE(mediumFileUtf16);
                    continue;
                }

                if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                    if (def->disks[i]->readonly) {
                        medium->vtbl->SetType(medium, MediumType_Immutable);
                        DEBUG0("setting harddisk to immutable");
                    } else if (!def->disks[i]->readonly) {
                        medium->vtbl->SetType(medium, MediumType_Normal);
                        DEBUG0("setting harddisk type to normal");
                    }
                }

                if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_IDE) {
                    VBOX_UTF8_TO_UTF16("IDE Controller", &storageCtlName);
                    storageBus = StorageBus_IDE;
                } else if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_SATA) {
                    VBOX_UTF8_TO_UTF16("SATA Controller", &storageCtlName);
                    storageBus = StorageBus_SATA;
                } else if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
                    VBOX_UTF8_TO_UTF16("SCSI Controller", &storageCtlName);
                    storageBus = StorageBus_SCSI;
                } else if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_FDC) {
                    VBOX_UTF8_TO_UTF16("Floppy Controller", &storageCtlName);
                    storageBus = StorageBus_Floppy;
                }

                /* get the device details i.e instance, port and slot */
                if (!vboxGetDeviceDetails(def->disks[i]->dst,
                                          maxPortPerInst,
                                          maxSlotPerPort,
                                          storageBus,
                                          &deviceInst,
                                          &devicePort,
                                          &deviceSlot)) {
                    vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                              "can't get the port/slot number of harddisk/dvd/floppy to be attached",
                              def->disks[i]->src, (unsigned)rc);
                    VBOX_RELEASE(medium);
                    VBOX_UTF16_FREE(mediumUUID);
                    VBOX_UTF16_FREE(mediumFileUtf16);
                    continue;
                }

                /* attach the harddisk/dvd/Floppy to the storage controller */
                rc = machine->vtbl->AttachDevice(machine,
                                                 storageCtlName,
                                                 devicePort,
                                                 deviceSlot,
                                                 deviceType,
                                                 mediumUUID);

                if (NS_FAILED(rc)) {
                    vboxError(conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                              "could not attach the file as harddisk/dvd/floppy",
                              def->disks[i]->src, (unsigned)rc);
                } else {
                    DEBUGIID("Attached HDD/DVD/Floppy with UUID", mediumUUID);
                }

                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumUUID);
                VBOX_UTF16_FREE(mediumFileUtf16);
                VBOX_UTF16_FREE(storageCtlName);
3938
            }
3939 3940 3941 3942
        }
    }
    /* Finished:Block to attach the CDROM/DVD Drive and HardDisks to the VM */
#endif /* VBOX_API_VERSION >= 3001 */
3943

3944 3945 3946 3947 3948 3949
    {   /* 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;
3950

3951 3952 3953 3954 3955 3956 3957 3958 3959
            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_AC97) {
                        audioAdapter->vtbl->SetAudioController(audioAdapter, AudioControllerType_AC97);
                    }
3960
                }
3961 3962 3963 3964
                VBOX_RELEASE(audioAdapter);
            }
        }
    }   /* Finished:Block to attach the Sound Controller to the VM */
3965

3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
    {   /* 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);
            VBOX_RELEASE(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);
            if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
                DEBUG("NIC(%d): name:    %s", i, def->nets[i]->data.network.name);
            } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
                DEBUG("NIC(%d): name:   %s", i, def->nets[i]->data.internal.name);
            } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
                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;
4017

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

4020
                if (def->nets[i]->model) {
4021 4022 4023 4024 4025 4026 4027 4028 4029 4030
                    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;
4031 4032 4033 4034
#if VBOX_API_VERSION >= 3001
                    } else if (STRCASEEQ(def->nets[i]->model , "virtio")) {
                        adapterType = NetworkAdapterType_Virtio;
#endif /* VBOX_API_VERSION >= 3001 */
4035
                    }
4036 4037 4038
                } else {
                    adapterType = NetworkAdapterType_Am79C973;
                }
4039

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

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

4046
                    adapter->vtbl->AttachToBridgedInterface(adapter);
4047

4048 4049 4050 4051 4052 4053 4054 4055
                    if (def->nets[i]->data.bridge.brname) {
                        VBOX_UTF8_TO_UTF16(def->nets[i]->data.bridge.brname, &hostInterface);
                        adapter->vtbl->SetHostInterface(adapter, hostInterface);
                        VBOX_UTF16_FREE(hostInterface);
                    }
                } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
                    PRUnichar *internalNetwork = NULL;
                    /* Internal Network */
4056

4057
                    adapter->vtbl->AttachToInternalNetwork(adapter);
4058

4059 4060 4061 4062
                    if (def->nets[i]->data.internal.name) {
                        VBOX_UTF8_TO_UTF16(def->nets[i]->data.internal.name, &internalNetwork);
                        adapter->vtbl->SetInternalNetwork(adapter, internalNetwork);
                        VBOX_UTF16_FREE(internalNetwork);
4063
                    }
4064 4065 4066 4067 4068 4069 4070
                } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
                    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);
4071

4072 4073 4074 4075
                    if (def->nets[i]->data.network.name) {
                        VBOX_UTF8_TO_UTF16(def->nets[i]->data.network.name, &hostInterface);
                        adapter->vtbl->SetHostInterface(adapter, hostInterface);
                        VBOX_UTF16_FREE(hostInterface);
4076
                    }
4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087
                } 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);
                }

                VBOX_UTF8_TO_UTF16(macaddrvbox, &MACAddress);
4088
                adapter->vtbl->SetMACAddress(adapter, MACAddress);
4089
                VBOX_UTF16_FREE(MACAddress);
4090
            }
4091 4092
        }
    }   /* Finished:Block to attach the Network Card to the VM */
4093

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

4099 4100 4101 4102 4103 4104
        data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
        if (systemProperties) {
            systemProperties->vtbl->GetSerialPortCount(systemProperties, &serialPortCount);
            VBOX_RELEASE(systemProperties);
            systemProperties = NULL;
        }
4105

4106 4107 4108 4109
        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;
4110

4111 4112
            DEBUG("SerialPort(%d): Type: %d", i, def->serials[i]->type);
            DEBUG("SerialPort(%d): target.port: %d", i, def->serials[i]->target.port);
4113

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

4118
                serialPort->vtbl->SetEnabled(serialPort, 1);
4119

4120 4121 4122 4123
                if (def->serials[i]->data.file.path) {
                    VBOX_UTF8_TO_UTF16(def->serials[i]->data.file.path, &pathUtf16);
                    serialPort->vtbl->SetPath(serialPort, pathUtf16);
                }
4124

4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143
                /* 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]->target.port shows real port
                 * and not always start at 0
                 */
                if (def->serials[i]->target.port == 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]->target.port == 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);
4144 4145
                }

4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156
                if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_DEV) {
                    serialPort->vtbl->SetHostMode(serialPort, PortMode_HostDevice);
                } else if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_PIPE) {
                    serialPort->vtbl->SetHostMode(serialPort, PortMode_HostPipe);
#if VBOX_API_VERSION >= 3000
                } else if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_FILE) {
                    serialPort->vtbl->SetHostMode(serialPort, PortMode_RawFile);
#endif /* VBOX_API_VERSION >= 3000 */
                } else {
                    serialPort->vtbl->SetHostMode(serialPort, PortMode_Disconnected);
                }
4157

4158 4159 4160 4161 4162
                VBOX_RELEASE(serialPort);
                if (pathUtf16) {
                    VBOX_UTF16_FREE(pathUtf16);
                    pathUtf16 = NULL;
                }
4163
            }
4164 4165
        }
    }   /* Finished:Block to attach the Serial Port to the VM */
4166

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

4172 4173 4174 4175 4176 4177
        data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
        if (systemProperties) {
            systemProperties->vtbl->GetParallelPortCount(systemProperties, &parallelPortCount);
            VBOX_RELEASE(systemProperties);
            systemProperties = NULL;
        }
4178

4179 4180 4181 4182
        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;
4183

4184 4185
            DEBUG("ParallelPort(%d): Type: %d", i, def->parallels[i]->type);
            DEBUG("ParallelPort(%d): target.port: %d", i, def->parallels[i]->target.port);
4186

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

4191
                VBOX_UTF8_TO_UTF16(def->parallels[i]->data.file.path, &pathUtf16);
4192

4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212
                /* 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);
4213 4214 4215
                    }
                }

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

4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288
                VBOX_RELEASE(parallelPort);
                if (pathUtf16) {
                    VBOX_UTF16_FREE(pathUtf16);
                    pathUtf16 = NULL;
                }
            }
        }
    }   /* Finished:Block to attach the Parallel Port to the VM */

    {   /* Started:Block to specify video card settings */
        if ((def->nvideos == 1) && (def->videos[0]->type == VIR_DOMAIN_VIDEO_TYPE_VBOX)) {
            machine->vtbl->SetVRAMSize(machine, def->videos[0]->vram);
            machine->vtbl->SetMonitorCount(machine, def->videos[0]->heads);
            if (def->videos[0]->accel) {
                machine->vtbl->SetAccelerate3DEnabled(machine, def->videos[0]->accel->support3d);
#if VBOX_API_VERSION >= 3001
                machine->vtbl->SetAccelerate2DVideoEnabled(machine, def->videos[0]->accel->support2d);
#endif /* VBOX_API_VERSION >= 3001 */
            } else {
                machine->vtbl->SetAccelerate3DEnabled(machine, 0);
#if VBOX_API_VERSION >= 3001
                machine->vtbl->SetAccelerate2DVideoEnabled(machine, 0);
#endif /* VBOX_API_VERSION >= 3001 */
            }
        }
    }   /* Finished:Block to specify video card settings */

    {   /* Started:Block to attach the Remote Display to VM */
        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++) {
            IVRDPServer *VRDPServer = NULL;

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

                vrdpPresent = 1;
                machine->vtbl->GetVRDPServer(machine, &VRDPServer);
                if (VRDPServer) {
                    VRDPServer->vtbl->SetEnabled(VRDPServer, PR_TRUE);
                    DEBUG0("VRDP Support turned ON.");

#if VBOX_API_VERSION < 3001
                    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) {
                        /* 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");
                    }
#else  /* VBOX_API_VERSION >= 3001 */
                    PRUnichar *portUtf16 = NULL;
                    portUtf16 = PRUnicharFromInt(def->graphics[i]->data.rdp.port);
                    VRDPServer->vtbl->SetPorts(VRDPServer, portUtf16);
                    VBOX_UTF16_FREE(portUtf16);
#endif /* VBOX_API_VERSION >= 3001 */

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

4290 4291 4292 4293
                    if (def->graphics[i]->data.rdp.multiUser) {
                        VRDPServer->vtbl->SetAllowMultiConnection(VRDPServer, PR_TRUE);
                        DEBUG0("VRDP set to allow multiple connection");
                    }
4294

4295 4296
                    if (def->graphics[i]->data.rdp.listenAddr) {
                        PRUnichar *netAddressUtf16 = NULL;
4297

4298 4299 4300
                        VBOX_UTF8_TO_UTF16(def->graphics[i]->data.rdp.listenAddr, &netAddressUtf16);
                        VRDPServer->vtbl->SetNetAddress(VRDPServer, netAddressUtf16);
                        DEBUG("VRDP listen address is set to: %s", def->graphics[i]->data.rdp.listenAddr);
4301

4302
                        VBOX_UTF16_FREE(netAddressUtf16);
4303
                    }
4304 4305

                    VBOX_RELEASE(VRDPServer);
4306
                }
4307
            }
4308

4309 4310 4311 4312 4313
            if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) && (guiPresent == 0)) {
                guiPresent = 1;
                if (def->graphics[i]->data.desktop.display) {
                    guiDisplay = strdup(def->graphics[i]->data.desktop.display);
                    if (guiDisplay == NULL) {
4314
                        virReportOOMError();
4315 4316 4317 4318
                        /* 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
                         */
4319 4320
                    }
                }
4321
            }
4322

4323 4324 4325 4326 4327
            if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) && (sdlPresent == 0)) {
                sdlPresent = 1;
                if (def->graphics[i]->data.sdl.display) {
                    sdlDisplay = strdup(def->graphics[i]->data.sdl.display);
                    if (sdlDisplay == NULL) {
4328
                        virReportOOMError();
4329 4330 4331 4332
                        /* 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
                         */
4333 4334
                    }
                }
4335
            }
4336
        }
4337

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

4343 4344
            VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
            VBOX_UTF8_TO_UTF16("vrdp", &valueTypeUtf16);
4345

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

4348 4349
            VBOX_UTF16_FREE(keyTypeUtf16);
            VBOX_UTF16_FREE(valueTypeUtf16);
4350

4351 4352 4353 4354 4355 4356
        } 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;
4357

4358 4359
            VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
            VBOX_UTF8_TO_UTF16("sdl", &valueTypeUtf16);
4360

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

4363 4364
            VBOX_UTF16_FREE(keyTypeUtf16);
            VBOX_UTF16_FREE(valueTypeUtf16);
4365

4366 4367 4368
            if (sdlDisplay) {
                VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
                VBOX_UTF8_TO_UTF16(sdlDisplay, &valueDisplayUtf16);
4369

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

4372 4373 4374
                VBOX_UTF16_FREE(keyDislpayUtf16);
                VBOX_UTF16_FREE(valueDisplayUtf16);
            }
4375

4376 4377 4378 4379 4380 4381
        } 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;
4382

4383 4384
            VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
            VBOX_UTF8_TO_UTF16("gui", &valueTypeUtf16);
4385

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

4388 4389
            VBOX_UTF16_FREE(keyTypeUtf16);
            VBOX_UTF16_FREE(valueTypeUtf16);
4390

4391 4392 4393
            if (guiDisplay) {
                VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
                VBOX_UTF8_TO_UTF16(guiDisplay, &valueDisplayUtf16);
4394

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

4397 4398
                VBOX_UTF16_FREE(keyDislpayUtf16);
                VBOX_UTF16_FREE(valueDisplayUtf16);
4399
            }
4400
        }
4401

4402 4403
        VIR_FREE(guiDisplay);
        VIR_FREE(sdlDisplay);
4404

4405
    }   /* Finished:Block to attach the Remote Display to VM */
4406

4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426
    {   /* 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++;
4427 4428 4429
                        }
                    }
                }
4430
            }
4431

4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
            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) {
4446

4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487
                                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);
                                VBOX_UTF8_TO_UTF16(filtername, &filternameUtf16);

                                USBController->vtbl->CreateDeviceFilter(USBController,
                                                                        filternameUtf16,
                                                                        &filter);
                                VBOX_UTF16_FREE(filternameUtf16);

                                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);
                                        VBOX_UTF8_TO_UTF16(vendorId, &vendorIdUtf16);
                                        filter->vtbl->SetVendorId(filter, vendorIdUtf16);
                                        VBOX_UTF16_FREE(vendorIdUtf16);
                                    }
                                    if (def->hostdevs[i]->source.subsys.u.usb.product) {
                                        sprintf(productId, "%x", def->hostdevs[i]->source.subsys.u.usb.product);
                                        VBOX_UTF8_TO_UTF16(productId, &productIdUtf16);
                                        filter->vtbl->SetProductId(filter, productIdUtf16);
                                        VBOX_UTF16_FREE(productIdUtf16);
                                    }
                                    filter->vtbl->SetActive(filter, 1);
                                    USBController->vtbl->InsertDeviceFilter(USBController,
                                                                            i,
                                                                            filter);
                                    VBOX_RELEASE(filter);
4488
                                }
4489

4490 4491 4492
                            }
                        }
                    }
4493
                    VBOX_RELEASE(USBController);
4494 4495
                }
            }
4496 4497
        }
    }   /* Finished:Block to attach USB Devices to VM */
4498

4499 4500 4501 4502 4503 4504
    /* 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);
    vboxIIDUnalloc(mchiid);
4505

4506 4507 4508
    ret = virGetDomain(conn, def->name, def->uuid);
    VBOX_RELEASE(machine);
    machine = NULL;
4509

4510
    vboxIIDFree(iid);
4511 4512
    virDomainDefFree(def);

4513
    return ret;
4514 4515

cleanup:
4516
    VBOX_RELEASE(machine);
4517
    vboxIIDFree(iid);
4518 4519 4520 4521 4522
    virDomainDefFree(def);
    return NULL;
}

static int vboxDomainUndefine(virDomainPtr dom) {
4523
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
4524
    IMachine *machine    = NULL;
4525
    vboxIID  *iid        = NULL;
4526
    nsresult rc;
4527

4528
#if VBOX_API_VERSION == 2002
4529
    if (VIR_ALLOC(iid) < 0) {
4530
        virReportOOMError();
4531 4532
        goto cleanup;
    }
4533
#endif
4534

4535
    vboxIIDFromUUID(dom->uuid, iid);
4536

4537 4538 4539 4540 4541 4542 4543
    /* 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;
4544

4545 4546 4547
        char *hddcname = strdup("IDE");
        VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16);
        VIR_FREE(hddcname);
4548

4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603
        /* 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) {

#if VBOX_API_VERSION < 3001
                /* 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);
#else  /* VBOX_API_VERSION >= 3001 */
                /* get all the controller first, then the attachments and
                 * remove them all so that the machine can be undefined
                 */
                PRUint32 strCtlSize = 0;
                IStorageController **aStrCtls = NULL;
                int i = 0, j = 0;

                machine->vtbl->GetStorageControllers(machine,
                                                     &strCtlSize,
                                                     &aStrCtls);

                for (i = 0; i < strCtlSize; i++) {
                    IStorageController *strCtl = aStrCtls[i];
                    PRUnichar *strCtlName = NULL;
                    PRUint32   medAttSize = 0;
                    IMediumAttachment **aMedAtts = NULL;

                    if (!strCtl)
                        continue;

                    strCtl->vtbl->GetName(strCtl, &strCtlName);
                    machine->vtbl->GetMediumAttachmentsOfController(machine,
                                                                    strCtlName,
                                                                    &medAttSize,
                                                                    &aMedAtts);

                    for (j = 0; j < medAttSize; j++) {
                        IMediumAttachment *medAtt = aMedAtts[j];
                        PRInt32 port = ~0U;
                        PRInt32 device = ~0U;

                        if (!medAtt)
                            continue;

                        medAtt->vtbl->GetPort(medAtt, &port);
                        medAtt->vtbl->GetDevice(medAtt, &device);

                        if ((port != ~0U) && (device != ~0U)) {
                            machine->vtbl->DetachDevice(machine,
                                                        strCtlName,
                                                        port,
                                                        device);
                        }
4604

4605 4606
                        VBOX_RELEASE(medAtt);
                    }
4607

4608 4609 4610
                    VBOX_RELEASE(strCtl);
                    machine->vtbl->RemoveStorageController(machine, strCtlName);
                    VBOX_UTF16_FREE(strCtlName);
4611
                }
4612 4613 4614
#endif /* VBOX_API_VERSION >= 3001 */

                machine->vtbl->SaveSettings(machine);
4615
            }
4616
            data->vboxSession->vtbl->Close(data->vboxSession);
4617
        }
4618 4619
        VBOX_UTF16_FREE(hddcnameUtf16);
    }
4620

4621 4622
    rc = data->vboxObj->vtbl->UnregisterMachine(data->vboxObj, iid, &machine);
    DEBUGIID("UUID of machine being undefined", iid);
4623

4624 4625 4626 4627 4628 4629
    if (NS_SUCCEEDED(rc) && machine){
        machine->vtbl->DeleteSettings(machine);
        ret = 0;
    } else {
        vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
                  "could not delete the domain", (unsigned)rc);
4630 4631
    }

4632
#if VBOX_API_VERSION == 2002
4633
cleanup:
4634 4635
#endif
    vboxIIDFree(iid);
4636
    VBOX_RELEASE(machine);
4637 4638 4639 4640 4641

    return ret;
}

static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml) {
4642
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
4643
    IMachine *machine    = NULL;
4644
    vboxIID  *iid        = NULL;
4645 4646 4647
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
4648
    nsresult rc;
4649 4650

    if (VIR_ALLOC(def) < 0) {
4651
        virReportOOMError();
4652 4653 4654 4655 4656
        return ret;
    }

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

4657
    if (def->os.type == NULL) {
4658
        virReportOOMError();
4659 4660 4661
        goto cleanup;
    }

4662
    dev = virDomainDeviceDefParse(data->caps, def, xml,
4663 4664
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
4665
        virReportOOMError();
4666 4667 4668
        goto cleanup;
    }

4669
#if VBOX_API_VERSION == 2002
4670
    if (VIR_ALLOC(iid) < 0) {
4671
        virReportOOMError();
4672 4673
        goto cleanup;
    }
4674
#endif
4675

4676
    vboxIIDFromUUID(dom->uuid, iid);
4677

4678 4679 4680 4681 4682
    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");
        goto cleanup;
    }
4683

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

4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709
        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 VBOX_API_VERSION < 3001
                    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;
                                vboxIID   *dvduuid           = NULL;
4710
# if VBOX_API_VERSION == 2002
4711
                                nsID dvdemptyuuid;
4712

4713
                                memset(&dvdemptyuuid, 0, sizeof(dvdemptyuuid));
4714
# else
4715
                                PRUnichar *dvdemptyuuidUtf16 = NULL;
4716
# endif
4717

4718
                                VBOX_UTF8_TO_UTF16(dev->data.disk->src, &dvdfileUtf16);
4719

4720 4721
                                data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                if (!dvdImage) {
4722
# if VBOX_API_VERSION == 2002
4723
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, &dvdemptyuuid, &dvdImage);
4724
# else
4725
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, dvdemptyuuidUtf16, &dvdImage);
4726
# endif
4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737
                                }
                                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);
4738 4739
                                        if (NS_FAILED(rc)) {
                                            vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
4740
                                                      "could not attach the file to cdrom",
4741 4742
                                                      dev->data.disk->src, (unsigned)rc);
                                        } else {
4743 4744
                                            ret = 0;
                                            DEBUGIID("CD/DVD Image UUID:", dvduuid);
4745 4746
                                        }
                                    }
4747 4748

                                    VBOX_MEDIUM_RELEASE(dvdImage);
4749
                                }
4750 4751 4752
                                vboxIIDUnalloc(dvduuid);
                                VBOX_UTF16_FREE(dvdfileUtf16);
                                VBOX_RELEASE(dvdDrive);
4753
                            }
4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765
                        } 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;
                                    vboxIID *fduuid             = NULL;
4766
# if VBOX_API_VERSION == 2002
4767
                                    nsID fdemptyuuid;
4768

4769
                                    memset(&fdemptyuuid, 0, sizeof(fdemptyuuid));
4770
# else
4771
                                    PRUnichar *fdemptyuuidUtf16 = NULL;
4772
# endif
4773 4774 4775 4776 4777 4778 4779 4780
                                    VBOX_UTF8_TO_UTF16(dev->data.disk->src, &fdfileUtf16);
                                    rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                              fdfileUtf16,
                                                                              &floppyImage);

                                    if (!floppyImage) {
                                        data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                             fdfileUtf16,
4781
# if VBOX_API_VERSION == 2002
4782
                                                                             &fdemptyuuid,
4783
# else
4784
                                                                             fdemptyuuidUtf16,
4785
# endif
4786 4787
                                                                             &floppyImage);
                                    }
4788

4789 4790 4791 4792 4793 4794 4795 4796
                                    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);
4797 4798
                                            if (NS_FAILED(rc)) {
                                                vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
4799
                                                          "could not attach the file to floppy drive",
4800 4801
                                                          dev->data.disk->src, (unsigned)rc);
                                            } else {
4802 4803
                                                ret = 0;
                                                DEBUGIID("attached floppy, UUID:", fduuid);
4804 4805
                                            }
                                        }
4806
                                        VBOX_MEDIUM_RELEASE(floppyImage);
4807
                                    }
4808 4809
                                    vboxIIDUnalloc(fduuid);
                                    VBOX_UTF16_FREE(fdfileUtf16);
4810
                                }
4811
                                VBOX_RELEASE(floppyDrive);
4812
                            }
4813
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
4814
                        }
4815 4816 4817 4818 4819 4820 4821
                    }
#else  /* VBOX_API_VERSION >= 3001 */
#endif /* VBOX_API_VERSION >= 3001 */
                } 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) {
4822 4823 4824
                        }
                    }
                }
4825 4826
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
4827
            }
4828
            data->vboxSession->vtbl->Close(data->vboxSession);
4829 4830 4831 4832
        }
    }

cleanup:
4833
    vboxIIDFree(iid);
4834 4835 4836 4837 4838
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849
static int vboxDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        vboxError(dom->conn, VIR_ERR_OPERATION_INVALID, "%s",
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainAttachDevice(dom, xml);
}

4850
static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml) {
4851
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
4852
    IMachine *machine    = NULL;
4853
    vboxIID  *iid        = NULL;
4854 4855 4856
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
4857
    nsresult rc;
4858 4859

    if (VIR_ALLOC(def) < 0) {
4860
        virReportOOMError();
4861 4862 4863 4864 4865
        return ret;
    }

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

4866
    if (def->os.type == NULL) {
4867
        virReportOOMError();
4868 4869 4870
        goto cleanup;
    }

4871
    dev = virDomainDeviceDefParse(data->caps, def, xml,
4872 4873
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
4874
        virReportOOMError();
4875 4876 4877
        goto cleanup;
    }

4878
#if VBOX_API_VERSION == 2002
4879
    if (VIR_ALLOC(iid) < 0) {
4880
        virReportOOMError();
4881 4882
        goto cleanup;
    }
4883
#endif
4884

4885
    vboxIIDFromUUID(dom->uuid, iid);
4886

4887 4888 4889 4890 4891
    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");
        goto cleanup;
    }
4892

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

4896 4897 4898 4899 4900 4901
        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);
        }
4902

4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
        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 VBOX_API_VERSION < 3001
                    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;
                                }
                                VBOX_RELEASE(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);
4939 4940
                                    if (NS_FAILED(rc)) {
                                        vboxError(dom->conn, VIR_ERR_INTERNAL_ERROR,"%s, rc=%08x",
4941
                                                  "could not attach the file to floppy drive",
4942 4943 4944 4945
                                                  (unsigned)rc);
                                    } else {
                                        ret = 0;
                                    }
4946 4947 4948 4949 4950
                                } 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;
4951
                                }
4952
                                VBOX_RELEASE(floppyDrive);
4953
                            }
4954
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
4955
                        }
4956 4957 4958 4959 4960 4961 4962
                    }
#else  /* VBOX_API_VERSION >= 3001 */
#endif /* VBOX_API_VERSION >= 3001 */
                } 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) {
4963 4964 4965
                        }
                    }
                }
4966 4967
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
4968
            }
4969
            data->vboxSession->vtbl->Close(data->vboxSession);
4970 4971 4972 4973
        }
    }

cleanup:
4974
    vboxIIDFree(iid);
4975 4976 4977 4978 4979
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990
static int vboxDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
        vboxError(dom->conn, VIR_ERR_OPERATION_INVALID, "%s",
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainDetachDevice(dom, xml);
}

4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102
#if VBOX_API_VERSION == 2002
    /* No Callback support for VirtualBox 2.2.* series */
#else /* !(VBOX_API_VERSION == 2002) */

/* Functions needed for Callbacks */
static  nsresult vboxCallbackOnMachineStateChange (IVirtualBoxCallback *pThis,
                                                   PRUnichar * machineId,
                                                   PRUint32 state) {
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

    g_pVBoxGlobalData->domainEventDispatching = 1;
    vboxDriverLock(g_pVBoxGlobalData);

    DEBUG("IVirtualBoxCallback: %p, State: %d", pThis, state);
    DEBUGPRUnichar("machineId", machineId);

    if (machineId) {
        char *machineIdUtf8       = NULL;
        unsigned char uuid[VIR_UUID_BUFLEN];

        g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(machineId, &machineIdUtf8);
        virUUIDParse(machineIdUtf8, uuid);

        dom = vboxDomainLookupByUUID(g_pVBoxGlobalData->conn, uuid);
        if (dom) {
            int i = 0;

            if (state == MachineState_Starting) {
                event  = VIR_DOMAIN_EVENT_STARTED;
                detail = VIR_DOMAIN_EVENT_STARTED_BOOTED;
            } else if (state == MachineState_Restoring) {
                event  = VIR_DOMAIN_EVENT_STARTED;
                detail = VIR_DOMAIN_EVENT_STARTED_RESTORED;
            } else if (state == MachineState_Paused) {
                event  = VIR_DOMAIN_EVENT_SUSPENDED;
                detail = VIR_DOMAIN_EVENT_SUSPENDED_PAUSED;
            } else if (state == MachineState_Running) {
                event  = VIR_DOMAIN_EVENT_RESUMED;
                detail = VIR_DOMAIN_EVENT_RESUMED_UNPAUSED;
            } else if (state == MachineState_PoweredOff) {
                event  = VIR_DOMAIN_EVENT_STOPPED;
                detail = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
            } else if (state == MachineState_Stopping) {
                event  = VIR_DOMAIN_EVENT_STOPPED;
                detail = VIR_DOMAIN_EVENT_STOPPED_DESTROYED;
            } else if (state == MachineState_Aborted) {
                event  = VIR_DOMAIN_EVENT_STOPPED;
                detail = VIR_DOMAIN_EVENT_STOPPED_CRASHED;
            } else if (state == MachineState_Saving) {
                event  = VIR_DOMAIN_EVENT_STOPPED;
                detail = VIR_DOMAIN_EVENT_STOPPED_SAVED;
            } else {
                event  = VIR_DOMAIN_EVENT_STOPPED;
                detail = VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN;
            }

            for (i = 0; i < g_pVBoxGlobalData->domainEventCallbacks->count; i++) {
                if (g_pVBoxGlobalData->domainEventCallbacks->callbacks[i]->cb) {
                    g_pVBoxGlobalData->domainEventCallbacks->callbacks[i]->cb(g_pVBoxGlobalData->conn,
                                                                              dom,
                                                                              event,
                                                                              detail,
                                                                              NULL);
                }
            }
        }
    }

    virDomainEventCallbackListPurgeMarked(g_pVBoxGlobalData->domainEventCallbacks);

    vboxDriverUnlock(g_pVBoxGlobalData);
    g_pVBoxGlobalData->domainEventDispatching = 0;

    return NS_OK;
}

static nsresult vboxCallbackOnMachineDataChange (IVirtualBoxCallback *pThis,
                                                 PRUnichar * machineId) {
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

static nsresult vboxCallbackOnExtraDataCanChange (IVirtualBoxCallback *pThis,
                                                  PRUnichar * machineId,
                                                  PRUnichar * key,
                                                  PRUnichar * value,
                                                  PRUnichar * * error ATTRIBUTE_UNUSED,
                                                  PRBool * allowChange) {
    DEBUG("IVirtualBoxCallback: %p, allowChange: %s", pThis, *allowChange ? "true" : "false");
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

static nsresult vboxCallbackOnExtraDataChange (IVirtualBoxCallback *pThis,
                                               PRUnichar * machineId,
                                               PRUnichar * key,
                                               PRUnichar * value) {
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

5103
# if VBOX_API_VERSION < 3001
5104 5105 5106 5107 5108 5109 5110 5111 5112 5113
static nsresult vboxCallbackOnMediaRegistered (IVirtualBoxCallback *pThis,
                                               PRUnichar * mediaId,
                                               PRUint32 mediaType,
                                               PRBool registered) {
    DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
    DEBUG("mediaType: %d", mediaType);
    DEBUGPRUnichar("mediaId", mediaId);

    return NS_OK;
}
5114 5115
# else  /* VBOX_API_VERSION >= 3001 */
# endif /* VBOX_API_VERSION >= 3001 */
5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276

static nsresult vboxCallbackOnMachineRegistered (IVirtualBoxCallback *pThis,
                                                 PRUnichar * machineId,
                                                 PRBool registered) {
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

    g_pVBoxGlobalData->domainEventDispatching = 1;
    vboxDriverLock(g_pVBoxGlobalData);

    DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
    DEBUGPRUnichar("machineId", machineId);

    if (machineId) {
        char *machineIdUtf8       = NULL;
        unsigned char uuid[VIR_UUID_BUFLEN];

        g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(machineId, &machineIdUtf8);
        virUUIDParse(machineIdUtf8, uuid);

        dom = vboxDomainLookupByUUID(g_pVBoxGlobalData->conn, uuid);
        if (dom) {
            int i = 0;

            /* CURRENT LIMITATION: we never get the VIR_DOMAIN_EVENT_UNDEFINED
             * event becuase the when the machine is de-registered the call
             * to vboxDomainLookupByUUID fails and thus we don't get any
             * dom pointer which is necessary (null dom pointer doesn't work)
             * to show the VIR_DOMAIN_EVENT_UNDEFINED event
             */
            if (registered) {
                event  = VIR_DOMAIN_EVENT_DEFINED;
                detail = VIR_DOMAIN_EVENT_DEFINED_ADDED;
            } else {
                event  = VIR_DOMAIN_EVENT_UNDEFINED;
                detail = VIR_DOMAIN_EVENT_UNDEFINED_REMOVED;
            }

            for (i = 0; i < g_pVBoxGlobalData->domainEventCallbacks->count; i++) {
                if (g_pVBoxGlobalData->domainEventCallbacks->callbacks[i]->cb) {
                    g_pVBoxGlobalData->domainEventCallbacks->callbacks[i]->cb(g_pVBoxGlobalData->conn,
                                                                              dom,
                                                                              event,
                                                                              detail,
                                                                              NULL);
                }
            }
        }
    }

    virDomainEventCallbackListPurgeMarked(g_pVBoxGlobalData->domainEventCallbacks);

    vboxDriverUnlock(g_pVBoxGlobalData);
    g_pVBoxGlobalData->domainEventDispatching = 0;

    return NS_OK;
}

static nsresult vboxCallbackOnSessionStateChange (IVirtualBoxCallback *pThis,
                                                  PRUnichar * machineId,
                                                  PRUint32 state) {
    DEBUG("IVirtualBoxCallback: %p, state: %d", pThis, state);
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

static nsresult vboxCallbackOnSnapshotTaken (IVirtualBoxCallback *pThis,
                                             PRUnichar * machineId,
                                             PRUnichar * snapshotId) {
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

static nsresult vboxCallbackOnSnapshotDiscarded (IVirtualBoxCallback *pThis,
                                                 PRUnichar * machineId,
                                                 PRUnichar * snapshotId) {
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

static nsresult vboxCallbackOnSnapshotChange (IVirtualBoxCallback *pThis,
                                              PRUnichar * machineId,
                                              PRUnichar * snapshotId) {
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

static nsresult vboxCallbackOnGuestPropertyChange (IVirtualBoxCallback *pThis,
                                                   PRUnichar * machineId,
                                                   PRUnichar * name,
                                                   PRUnichar * value,
                                                   PRUnichar * flags) {
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("name", name);
    DEBUGPRUnichar("value", value);
    DEBUGPRUnichar("flags", flags);

    return NS_OK;
}

static nsresult vboxCallbackAddRef(nsISupports *pThis) {
    nsresult c;

    c = ++g_pVBoxGlobalData->vboxCallBackRefCount;

    DEBUG("pThis: %p, vboxCallback AddRef: %d", pThis, c);

    return c;
}

static nsresult vboxCallbackRelease(nsISupports *pThis) {
    nsresult c;

    c = --g_pVBoxGlobalData->vboxCallBackRefCount;
    if (c == 0) {
        /* delete object */
        VIR_FREE(pThis->vtbl);
        VIR_FREE(pThis);
    }

    DEBUG("pThis: %p, vboxCallback Release: %d", pThis, c);

    return c;
}

static nsresult vboxCallbackQueryInterface(nsISupports *pThis, const nsID *iid, void **resultp) {
    IVirtualBoxCallback *that = (IVirtualBoxCallback *)pThis;
    static const nsID ivirtualboxCallbackUUID = IVIRTUALBOXCALLBACK_IID;
    static const nsID isupportIID = NS_ISUPPORTS_IID;

    /* Match UUID for IVirtualBoxCallback class */
    if (    memcmp(iid, &ivirtualboxCallbackUUID, sizeof(nsID)) == 0
        ||  memcmp(iid, &isupportIID, sizeof(nsID)) == 0) {
        g_pVBoxGlobalData->vboxCallBackRefCount++;
        *resultp = that;

        DEBUG("pThis: %p, vboxCallback QueryInterface: %d", pThis, g_pVBoxGlobalData->vboxCallBackRefCount);

        return NS_OK;
    }


    DEBUG("pThis: %p, vboxCallback QueryInterface didn't find a matching interface", pThis);
    DEBUGUUID("The UUID Callback Interface expects", iid);
    DEBUGUUID("The UUID Callback Interface got", &ivirtualboxCallbackUUID);
    return NS_NOINTERFACE;
}


5277
static IVirtualBoxCallback *vboxAllocCallbackObj(void) {
5278 5279
    IVirtualBoxCallback *vboxCallback = NULL;

5280
    /* Allocate, Initialize and return a valid
5281 5282 5283
     * IVirtualBoxCallback object here
     */
    if ((VIR_ALLOC(vboxCallback) < 0) || (VIR_ALLOC(vboxCallback->vtbl) < 0)) {
5284
        VIR_FREE(vboxCallback);
5285
        virReportOOMError();
5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296
        return NULL;
    }

    {
        vboxCallback->vtbl->nsisupports.AddRef          = &vboxCallbackAddRef;
        vboxCallback->vtbl->nsisupports.Release         = &vboxCallbackRelease;
        vboxCallback->vtbl->nsisupports.QueryInterface  = &vboxCallbackQueryInterface;
        vboxCallback->vtbl->OnMachineStateChange        = &vboxCallbackOnMachineStateChange;
        vboxCallback->vtbl->OnMachineDataChange         = &vboxCallbackOnMachineDataChange;
        vboxCallback->vtbl->OnExtraDataCanChange        = &vboxCallbackOnExtraDataCanChange;
        vboxCallback->vtbl->OnExtraDataChange           = &vboxCallbackOnExtraDataChange;
5297
# if VBOX_API_VERSION < 3001
5298
        vboxCallback->vtbl->OnMediaRegistered           = &vboxCallbackOnMediaRegistered;
5299 5300
# else  /* VBOX_API_VERSION >= 3001 */
# endif /* VBOX_API_VERSION >= 3001 */
5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333
        vboxCallback->vtbl->OnMachineRegistered         = &vboxCallbackOnMachineRegistered;
        vboxCallback->vtbl->OnSessionStateChange        = &vboxCallbackOnSessionStateChange;
        vboxCallback->vtbl->OnSnapshotTaken             = &vboxCallbackOnSnapshotTaken;
        vboxCallback->vtbl->OnSnapshotDiscarded         = &vboxCallbackOnSnapshotDiscarded;
        vboxCallback->vtbl->OnSnapshotChange            = &vboxCallbackOnSnapshotChange;
        vboxCallback->vtbl->OnGuestPropertyChange       = &vboxCallbackOnGuestPropertyChange;
        g_pVBoxGlobalData->vboxCallBackRefCount = 1;

    }

    return vboxCallback;
}

static void vboxReadCallback(int watch ATTRIBUTE_UNUSED,
                             int fd,
                             int events ATTRIBUTE_UNUSED,
                             void *opaque ATTRIBUTE_UNUSED) {
    if (fd >= 0) {
        g_pVBoxGlobalData->vboxQueue->vtbl->ProcessPendingEvents(g_pVBoxGlobalData->vboxQueue);
    } else {
        nsresult rc;
        PLEvent *pEvent = NULL;

        rc = g_pVBoxGlobalData->vboxQueue->vtbl->WaitForEvent(g_pVBoxGlobalData->vboxQueue, &pEvent);
        if (NS_SUCCEEDED(rc))
            g_pVBoxGlobalData->vboxQueue->vtbl->HandleEvent(g_pVBoxGlobalData->vboxQueue, pEvent);
    }
}

static int vboxDomainEventRegister (virConnectPtr conn,
                                    virConnectDomainEventCallback callback,
                                    void *opaque,
                                    virFreeCallback freecb) {
5334
    VBOX_OBJECT_CHECK(conn, int, -1);
5335
    int vboxRet          = -1;
5336
    nsresult rc;
5337 5338 5339 5340 5341 5342

    /* Locking has to be there as callbacks are not
     * really fully thread safe
     */
    vboxDriverLock(data);

5343
    if (data->vboxCallback == NULL) {
5344
        data->vboxCallback = vboxAllocCallbackObj();
5345 5346 5347 5348
        if (data->vboxCallback != NULL) {
            rc = data->vboxObj->vtbl->RegisterCallback(data->vboxObj, data->vboxCallback);
            if (NS_SUCCEEDED(rc)) {
                vboxRet = 0;
5349 5350
            }
        }
5351 5352 5353
    } else {
        vboxRet = 0;
    }
5354

5355 5356 5357 5358 5359 5360 5361
    /* Get the vbox file handle and add a event handle to it
     * so that the events can be passed down to the user
     */
    if (vboxRet == 0) {
        if (data->fdWatch < 0) {
            PRInt32 vboxFileHandle;
            vboxFileHandle = data->vboxQueue->vtbl->GetEventQueueSelectFD(data->vboxQueue);
5362

5363 5364
            data->fdWatch = virEventAddHandle(vboxFileHandle, VIR_EVENT_HANDLE_READABLE, vboxReadCallback, NULL, NULL);
        }
5365

5366 5367 5368 5369 5370
        if (data->fdWatch >= 0) {
            /* Once a callback is registered with virtualbox, use a list
             * to store the callbacks registered with libvirt so that
             * later you can iterate over them
             */
5371

5372 5373 5374 5375 5376 5377
            ret = virDomainEventCallbackListAdd(conn, data->domainEventCallbacks,
                                                callback, opaque, freecb);
            DEBUG("virDomainEventCallbackListAdd (ret = %d) ( conn: %p, "
                  "data->domainEventCallbacks: %p, callback: %p, opaque: %p, "
                  "freecb: %p )", ret, conn, data->domainEventCallbacks, callback,
                  opaque, freecb);
5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394
        }
    }

    vboxDriverUnlock(data);

    if (ret >= 0) {
        return ret;
    } else {
        if (data->vboxObj && data->vboxCallback) {
            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        }
        return -1;
    }
}

static int vboxDomainEventDeregister (virConnectPtr conn,
                                      virConnectDomainEventCallback callback) {
5395
    VBOX_OBJECT_CHECK(conn, int, -1);
5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408

    /* Locking has to be there as callbacks are not
     * really fully thread safe
     */
    vboxDriverLock(data);

    if (data->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, data->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, data->domainEventCallbacks,
                                               callback);

5409
    if(data->vboxCallback) {
5410 5411 5412 5413 5414 5415 5416
        /* check count here of how many times register was called
         * and only on the last de-register do the un-register call
         */
        if (data->domainEventCallbacks && (data->domainEventCallbacks->count <= 0)) {
            int i = 0;

            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
5417
            VBOX_RELEASE(data->vboxCallback);
5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440

            /* Remove the Event file handle on which we are listening as well */
            virEventRemoveHandle(data->fdWatch);
            data->fdWatch = -1;

            /* iterate and free all the opaque objects using the
             * freecb callback provided in vboxDomainEventRegister()
             */
            for (i = 0; i < data->domainEventCallbacks->count; i++) {
                if (data->domainEventCallbacks->callbacks[i]->freecb) {
                    data->domainEventCallbacks->callbacks[i]->freecb(data->domainEventCallbacks->callbacks[i]->opaque);
                }
            }
        }
    }

    vboxDriverUnlock(data);

    return ret;
}

#endif /* !(VBOX_API_VERSION == 2002) */

5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456
/**
 * The Network Functions here on
 */
static virDrvOpenStatus vboxNetworkOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                        int flags ATTRIBUTE_UNUSED) {
    vboxGlobalData *data = conn->privateData;

    if (STRNEQ(conn->driver->name, "VBOX"))
        goto cleanup;

    if ((data->pFuncs      == NULL) ||
        (data->vboxObj     == NULL) ||
        (data->vboxSession == NULL))
        goto cleanup;

5457
    DEBUG0("network initialized");
5458 5459 5460 5461 5462 5463 5464 5465
    /* conn->networkPrivateData = some network specific data */
    return VIR_DRV_OPEN_SUCCESS;

cleanup:
    return VIR_DRV_OPEN_DECLINED;
}

static int vboxNetworkClose(virConnectPtr conn) {
5466
    DEBUG0("network uninitialized");
5467 5468 5469 5470 5471
    conn->networkPrivateData = NULL;
    return 0;
}

static int vboxNumOfNetworks(virConnectPtr conn) {
5472 5473 5474 5475
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
    PRUint32 networkInterfacesSize = 0;
    IHostNetworkInterface **networkInterfaces = NULL;
    int i = 0;
5476

5477
    host->vtbl->GetNetworkInterfaces(host, &networkInterfacesSize, &networkInterfaces);
5478

5479 5480 5481
    for (i = 0; i < networkInterfacesSize; i++) {
        if (networkInterfaces[i]) {
            PRUint32 interfaceType = 0;
5482

5483 5484 5485
            networkInterfaces[i]->vtbl->GetInterfaceType(networkInterfaces[i], &interfaceType);
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
5486

5487
                networkInterfaces[i]->vtbl->GetStatus(networkInterfaces[i], &status);
5488

5489 5490
                if (status == HostNetworkInterfaceStatus_Up)
                    ret++;
5491 5492
            }

5493
            VBOX_RELEASE(networkInterfaces[i]);
5494 5495 5496
        }
    }

5497 5498 5499 5500
    VBOX_RELEASE(host);

    DEBUG("numActive: %d", ret);
    return ret;
5501 5502 5503
}

static int vboxListNetworks(virConnectPtr conn, char **const names, int nnames) {
5504 5505 5506 5507
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
    PRUint32 networkInterfacesSize = 0;
    IHostNetworkInterface **networkInterfaces = NULL;
    int i = 0;
5508

5509
    host->vtbl->GetNetworkInterfaces(host, &networkInterfacesSize, &networkInterfaces);
5510

5511 5512 5513
    for (i = 0; (ret < nnames) && (i < networkInterfacesSize); i++) {
        if (networkInterfaces[i]) {
            PRUint32 interfaceType = 0;
5514

5515
            networkInterfaces[i]->vtbl->GetInterfaceType(networkInterfaces[i], &interfaceType);
5516

5517 5518
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
5519

5520
                networkInterfaces[i]->vtbl->GetStatus(networkInterfaces[i], &status);
5521

5522 5523 5524
                if (status == HostNetworkInterfaceStatus_Up) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
5525

5526 5527
                    networkInterfaces[i]->vtbl->GetName(networkInterfaces[i], &nameUtf16);
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
5528

5529 5530 5531 5532 5533 5534
                    DEBUG("nnames[%d]: %s", ret, nameUtf8);
                    names[ret] = strdup(nameUtf8);
                    if (names[ret] == NULL) {
                        vboxError(conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                    } else {
                        ret++;
5535 5536
                    }

5537 5538
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
5539 5540 5541 5542 5543
                }
            }
        }
    }

5544 5545
    for (i = 0; i < networkInterfacesSize; i++)
        VBOX_RELEASE(networkInterfaces[i]);
5546

5547
    VBOX_RELEASE(host);
5548

5549 5550
    return ret;
}
5551

5552 5553 5554 5555 5556
static int vboxNumOfDefinedNetworks(virConnectPtr conn) {
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
    PRUint32 networkInterfacesSize = 0;
    IHostNetworkInterface **networkInterfaces = NULL;
    int i = 0;
5557

5558
    host->vtbl->GetNetworkInterfaces(host, &networkInterfacesSize, &networkInterfaces);
5559

5560 5561 5562
    for (i = 0; i < networkInterfacesSize; i++) {
        if (networkInterfaces[i]) {
            PRUint32 interfaceType = 0;
5563

5564 5565 5566
            networkInterfaces[i]->vtbl->GetInterfaceType(networkInterfaces[i], &interfaceType);
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
5567

5568
                networkInterfaces[i]->vtbl->GetStatus(networkInterfaces[i], &status);
5569

5570 5571
                if (status == HostNetworkInterfaceStatus_Down)
                    ret++;
5572 5573
            }

5574
            VBOX_RELEASE(networkInterfaces[i]);
5575 5576 5577
        }
    }

5578 5579 5580 5581
    VBOX_RELEASE(host);

    DEBUG("numActive: %d", ret);
    return ret;
5582 5583 5584
}

static int vboxListDefinedNetworks(virConnectPtr conn, char **const names, int nnames) {
5585 5586 5587 5588
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
    PRUint32 networkInterfacesSize = 0;
    IHostNetworkInterface **networkInterfaces = NULL;
    int i = 0;
5589

5590
    host->vtbl->GetNetworkInterfaces(host, &networkInterfacesSize, &networkInterfaces);
5591

5592 5593 5594
    for (i = 0; (ret < nnames) && (i < networkInterfacesSize); i++) {
        if (networkInterfaces[i]) {
            PRUint32 interfaceType = 0;
5595

5596
            networkInterfaces[i]->vtbl->GetInterfaceType(networkInterfaces[i], &interfaceType);
5597

5598 5599
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
5600

5601
                networkInterfaces[i]->vtbl->GetStatus(networkInterfaces[i], &status);
5602

5603 5604 5605
                if (status == HostNetworkInterfaceStatus_Down) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
5606

5607 5608
                    networkInterfaces[i]->vtbl->GetName(networkInterfaces[i], &nameUtf16);
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
5609

5610 5611 5612 5613 5614 5615
                    DEBUG("nnames[%d]: %s", ret, nameUtf8);
                    names[ret] = strdup(nameUtf8);
                    if (names[ret] == NULL) {
                        vboxError(conn, VIR_ERR_SYSTEM_ERROR, "%s", "strdup failed");
                    } else {
                        ret++;
5616 5617
                    }

5618 5619
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
5620 5621 5622 5623 5624
                }
            }
        }
    }

5625 5626 5627 5628 5629 5630
    for (i = 0; i < networkInterfacesSize; i++)
        VBOX_RELEASE(networkInterfaces[i]);

    VBOX_RELEASE(host);

    return ret;
5631 5632 5633
}

static virNetworkPtr vboxNetworkLookupByUUID(virConnectPtr conn, const unsigned char *uuid) {
5634
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
5635
    vboxIID *iid         = NULL;
5636

5637
#if VBOX_API_VERSION == 2002
5638
    if (VIR_ALLOC(iid) < 0) {
5639
        virReportOOMError();
5640 5641
        goto cleanup;
    }
5642 5643 5644
#endif

    vboxIIDFromUUID(uuid, iid);
5645

5646 5647 5648
    /* TODO: "internal" networks are just strings and
     * thus can't do much with them
     */
5649
    IHostNetworkInterface *networkInterface = NULL;
5650

5651 5652 5653
    host->vtbl->FindHostNetworkInterfaceById(host, iid, &networkInterface);
    if (networkInterface) {
        PRUint32 interfaceType = 0;
5654

5655
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
5656

5657 5658 5659
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            char *nameUtf8       = NULL;
            PRUnichar *nameUtf16 = NULL;
5660

5661 5662
            networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
            VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
5663

5664
            ret = virGetNetwork(conn, nameUtf8, uuid);
5665

5666 5667
            DEBUG("Network Name: %s", nameUtf8);
            DEBUGIID("Network UUID", iid);
5668

5669 5670
            VBOX_UTF8_FREE(nameUtf8);
            VBOX_UTF16_FREE(nameUtf16);
5671
        }
5672 5673

        VBOX_RELEASE(networkInterface);
5674 5675
    }

5676 5677
    VBOX_RELEASE(host);

5678
#if VBOX_API_VERSION == 2002
5679
cleanup:
5680 5681
#endif
    vboxIIDFree(iid);
5682 5683 5684 5685
    return ret;
}

static virNetworkPtr vboxNetworkLookupByName(virConnectPtr conn, const char *name) {
5686 5687 5688
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *nameUtf16                    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
5689

5690
    VBOX_UTF8_TO_UTF16(name, &nameUtf16);
5691

5692
    host->vtbl->FindHostNetworkInterfaceByName(host, nameUtf16, &networkInterface);
5693

5694 5695
    if (networkInterface) {
        PRUint32 interfaceType = 0;
5696

5697
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
5698

5699 5700 5701
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            unsigned char uuid[VIR_UUID_BUFLEN];
            vboxIID *iid = NULL;
5702

5703 5704 5705 5706
            networkInterface->vtbl->GetId(networkInterface, &iid);
            vboxIIDToUUID(uuid, iid);
            ret = virGetNetwork(conn, name, uuid);
            DEBUG("Network Name: %s", name);
5707

5708 5709
            DEBUGIID("Network UUID", iid);
            vboxIIDUnalloc(iid);
5710
        }
5711 5712

        VBOX_RELEASE(networkInterface);
5713 5714
    }

5715 5716 5717
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(host);

5718 5719 5720
    return ret;
}

5721
static virNetworkPtr vboxNetworkDefineCreateXML(virConnectPtr conn, const char *xml, bool start) {
5722 5723 5724 5725
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    char      *networkInterfaceNameUtf8     = NULL;
    IHostNetworkInterface *networkInterface = NULL;
5726

5727
    virNetworkDefPtr def = virNetworkDefParseString(xml);
5728

5729 5730 5731
    if (   (!def)
        || (def->forwardType != VIR_NETWORK_FORWARD_NONE))
        goto cleanup;
5732

5733 5734 5735 5736 5737 5738
    /* the current limitation of hostonly network is that you can't
     * assign a name to it and it defaults to vboxnet*, for e.g:
     * vboxnet0, vboxnet1, etc. Also the UUID is assigned to it
     * automatically depending on the mac address and thus both
     * these paramters are ignored here for now.
     */
5739

5740
#if VBOX_API_VERSION == 2002
5741 5742
    if STREQ(def->name, "vboxnet0") {
        PRUint32 interfaceType = 0;
5743

5744 5745
        VBOX_UTF8_TO_UTF16(def->name, &networkInterfaceNameUtf16);
        host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
5746

5747 5748 5749 5750 5751 5752
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
        if (interfaceType != HostNetworkInterfaceType_HostOnly) {
            VBOX_RELEASE(networkInterface);
            networkInterface = NULL;
        }
    }
5753
#else /* VBOX_API_VERSION != 2002 */
5754 5755
    IProgress *progress = NULL;
    host->vtbl->CreateHostOnlyNetworkInterface(host, &networkInterface, &progress);
5756

5757 5758 5759 5760
    if (progress) {
        progress->vtbl->WaitForCompletion(progress, -1);
        VBOX_RELEASE(progress);
    }
5761
#endif /* VBOX_API_VERSION != 2002 */
5762

5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775
    if (networkInterface) {
        unsigned char uuid[VIR_UUID_BUFLEN];
        char      *networkNameUtf8  = NULL;
        PRUnichar *networkNameUtf16 = NULL;
        vboxIID   *vboxnetiid       = NULL;

        networkInterface->vtbl->GetName(networkInterface, &networkInterfaceNameUtf16);
        if (networkInterfaceNameUtf16) {
            VBOX_UTF16_TO_UTF8(networkInterfaceNameUtf16, &networkInterfaceNameUtf8);

            if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", networkInterfaceNameUtf8) < 0) {
                VBOX_RELEASE(host);
                VBOX_RELEASE(networkInterface);
5776
                virReportOOMError();
5777 5778 5779
                goto cleanup;
            }
        }
5780

5781
        VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
5782

5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836
        /* Currently support only one dhcp server per network
         * with contigious address space from start to end
         */
        if ((def->nranges >= 1) &&
            (def->ranges[0].start) &&
            (def->ranges[0].end)) {
            IDHCPServer *dhcpServer = NULL;

            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (!dhcpServer) {
                /* create a dhcp server */
                data->vboxObj->vtbl->CreateDHCPServer(data->vboxObj,
                                                      networkNameUtf16,
                                                      &dhcpServer);
                DEBUG0("couldn't find dhcp server so creating one");
            }
            if (dhcpServer) {
                PRUnichar *ipAddressUtf16     = NULL;
                PRUnichar *networkMaskUtf16   = NULL;
                PRUnichar *fromIPAddressUtf16 = NULL;
                PRUnichar *toIPAddressUtf16   = NULL;
                PRUnichar *trunkTypeUtf16     = NULL;


                VBOX_UTF8_TO_UTF16(def->ipAddress, &ipAddressUtf16);
                VBOX_UTF8_TO_UTF16(def->netmask, &networkMaskUtf16);
                VBOX_UTF8_TO_UTF16(def->ranges[0].start, &fromIPAddressUtf16);
                VBOX_UTF8_TO_UTF16(def->ranges[0].end, &toIPAddressUtf16);
                VBOX_UTF8_TO_UTF16("netflt", &trunkTypeUtf16);

                dhcpServer->vtbl->SetEnabled(dhcpServer, PR_TRUE);

                dhcpServer->vtbl->SetConfiguration(dhcpServer,
                                                   ipAddressUtf16,
                                                   networkMaskUtf16,
                                                   fromIPAddressUtf16,
                                                   toIPAddressUtf16);

                if (start)
                    dhcpServer->vtbl->Start(dhcpServer,
                                            networkNameUtf16,
                                            networkInterfaceNameUtf16,
                                            trunkTypeUtf16);

                VBOX_UTF16_FREE(ipAddressUtf16);
                VBOX_UTF16_FREE(networkMaskUtf16);
                VBOX_UTF16_FREE(fromIPAddressUtf16);
                VBOX_UTF16_FREE(toIPAddressUtf16);
                VBOX_UTF16_FREE(trunkTypeUtf16);
                VBOX_RELEASE(dhcpServer);
            }
        }
5837

5838 5839 5840 5841
        if ((def->nhosts >= 1) &&
            (def->hosts[0].ip)) {
            PRUnichar *ipAddressUtf16   = NULL;
            PRUnichar *networkMaskUtf16 = NULL;
5842

5843 5844
            VBOX_UTF8_TO_UTF16(def->netmask, &networkMaskUtf16);
            VBOX_UTF8_TO_UTF16(def->hosts[0].ip, &ipAddressUtf16);
5845

5846 5847 5848 5849 5850 5851 5852
            /* Current drawback is that since EnableStaticIpConfig() sets
             * IP and enables the interface so even if the dhcpserver is not
             * started the interface is still up and running
             */
            networkInterface->vtbl->EnableStaticIpConfig(networkInterface,
                                                         ipAddressUtf16,
                                                         networkMaskUtf16);
5853

5854 5855 5856 5857 5858 5859
            VBOX_UTF16_FREE(ipAddressUtf16);
            VBOX_UTF16_FREE(networkMaskUtf16);
        } else {
            networkInterface->vtbl->EnableDynamicIpConfig(networkInterface);
            networkInterface->vtbl->DhcpRediscover(networkInterface);
        }
5860

5861 5862 5863 5864 5865 5866
        networkInterface->vtbl->GetId(networkInterface, &vboxnetiid);
        if (vboxnetiid) {
            vboxIIDToUUID(uuid, vboxnetiid);
            DEBUGIID("Real Network UUID", vboxnetiid);
            vboxIIDUnalloc(vboxnetiid);
            ret = virGetNetwork(conn, networkInterfaceNameUtf8, uuid);
5867
        }
5868 5869 5870 5871

        VIR_FREE(networkNameUtf8);
        VBOX_UTF16_FREE(networkNameUtf16);
        VBOX_RELEASE(networkInterface);
5872 5873
    }

5874 5875 5876 5877
    VBOX_UTF8_FREE(networkInterfaceNameUtf8);
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

5878 5879 5880 5881 5882
cleanup:
    virNetworkDefFree(def);
    return ret;
}

5883 5884 5885 5886 5887 5888 5889 5890
static virNetworkPtr vboxNetworkCreateXML(virConnectPtr conn, const char *xml) {
    return vboxNetworkDefineCreateXML(conn, xml, true);
}

static virNetworkPtr vboxNetworkDefineXML(virConnectPtr conn, const char *xml) {
    return vboxNetworkDefineCreateXML(conn, xml, false);
}

5891
static int vboxNetworkUndefineDestroy(virNetworkPtr network, bool removeinterface) {
5892
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903
    char *networkNameUtf8 = NULL;

    /* Current limitation of the function for VirtualBox 2.2.* is
     * that you can't delete the default hostonly adaptor namely:
     * vboxnet0 and thus all this functions does is remove the
     * dhcp server configuration, but the network can still be used
     * by giving the machine static IP and also it will still
     * show up in the net-list in virsh
     */

    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0) {
5904
        virReportOOMError();
5905 5906 5907
        goto cleanup;
    }

5908 5909
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
5910

5911
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
5912

5913
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
5914

5915 5916
    if (networkInterface) {
        PRUint32 interfaceType = 0;
5917

5918
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
5919

5920 5921 5922
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
5923

5924
#if VBOX_API_VERSION != 2002
5925 5926 5927
            if (removeinterface) {
                PRUnichar *iidUtf16 = NULL;
                IProgress *progress = NULL;
5928

5929
                networkInterface->vtbl->GetId(networkInterface, &iidUtf16);
5930

5931
                if (iidUtf16) {
5932
# if VBOX_API_VERSION == 3000
5933 5934 5935
                    IHostNetworkInterface *netInt = NULL;
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &netInt, &progress);
                    VBOX_RELEASE(netInt);
5936
# else  /* VBOX_API_VERSION > 3000 */
5937
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &progress);
5938
# endif /* VBOX_API_VERSION > 3000 */
5939 5940
                    VBOX_UTF16_FREE(iidUtf16);
                }
5941

5942 5943 5944 5945 5946
                if (progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                }
            }
5947 5948
#endif /* VBOX_API_VERSION != 2002 */

5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959
            VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);

            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (dhcpServer) {
                dhcpServer->vtbl->SetEnabled(dhcpServer, PR_FALSE);
                dhcpServer->vtbl->Stop(dhcpServer);
                if (removeinterface)
                    data->vboxObj->vtbl->RemoveDHCPServer(data->vboxObj, dhcpServer);
                VBOX_RELEASE(dhcpServer);
5960 5961
            }

5962 5963
            VBOX_UTF16_FREE(networkNameUtf16);

5964
        }
5965
        VBOX_RELEASE(networkInterface);
5966 5967
    }

5968 5969 5970
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

5971 5972 5973 5974 5975 5976 5977
    ret = 0;

cleanup:
    VIR_FREE(networkNameUtf8);
    return ret;
}

5978 5979 5980 5981
static int vboxNetworkUndefine(virNetworkPtr network) {
    return vboxNetworkUndefineDestroy(network, true);
}

5982
static int vboxNetworkCreate(virNetworkPtr network) {
5983
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
5984 5985 5986 5987 5988 5989 5990 5991 5992 5993
    char *networkNameUtf8 = NULL;

    /* Current limitation of the function for VirtualBox 2.2.* is
     * that the default hostonly network "vboxnet0" is always active
     * and thus all this functions does is start the dhcp server,
     * but the network can still be used without starting the dhcp
     * server by giving the machine static IP
     */

    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0) {
5994
        virReportOOMError();
5995 5996 5997
        goto cleanup;
    }

5998 5999
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
6000

6001
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
6002

6003
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
6004

6005 6006
    if (networkInterface) {
        PRUint32 interfaceType = 0;
6007

6008
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6009

6010 6011 6012
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
6013 6014


6015
            VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
6016

6017 6018 6019 6020 6021
            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (dhcpServer) {
                PRUnichar *trunkTypeUtf16 = NULL;
6022

6023
                dhcpServer->vtbl->SetEnabled(dhcpServer, PR_TRUE);
6024

6025
                VBOX_UTF8_TO_UTF16("netflt", &trunkTypeUtf16);
6026

6027 6028 6029 6030
                dhcpServer->vtbl->Start(dhcpServer,
                                        networkNameUtf16,
                                        networkInterfaceNameUtf16,
                                        trunkTypeUtf16);
6031

6032 6033
                VBOX_UTF16_FREE(trunkTypeUtf16);
                VBOX_RELEASE(dhcpServer);
6034 6035
            }

6036
            VBOX_UTF16_FREE(networkNameUtf16);
6037
        }
6038 6039

        VBOX_RELEASE(networkInterface);
6040 6041
    }

6042 6043 6044
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

6045 6046 6047 6048 6049 6050 6051 6052
    ret = 0;

cleanup:
    VIR_FREE(networkNameUtf8);
    return ret;
}

static int vboxNetworkDestroy(virNetworkPtr network) {
6053
    return vboxNetworkUndefineDestroy(network, false);
6054 6055 6056
}

static char *vboxNetworkDumpXML(virNetworkPtr network, int flags ATTRIBUTE_UNUSED) {
6057
    VBOX_OBJECT_HOST_CHECK(network->conn, char *, NULL);
6058 6059 6060 6061
    virNetworkDefPtr def  = NULL;
    char *networkNameUtf8 = NULL;

    if (VIR_ALLOC(def) < 0) {
6062
        virReportOOMError();
6063 6064 6065 6066
        goto cleanup;
    }

    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0) {
6067
        virReportOOMError();
6068 6069 6070
        goto cleanup;
    }

6071 6072
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
6073

6074
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
6075

6076
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
6077

6078 6079
    if (networkInterface) {
        PRUint32 interfaceType = 0;
6080

6081
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6082

6083 6084 6085 6086 6087 6088
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            def->name = strdup(network->name);
            if (def->name != NULL) {
                PRUnichar *networkNameUtf16 = NULL;
                IDHCPServer *dhcpServer     = NULL;
                vboxIID *vboxnet0IID        = NULL;
6089

6090 6091
                networkInterface->vtbl->GetId(networkInterface, &vboxnet0IID);
                vboxIIDToUUID(def->uuid, vboxnet0IID);
6092

6093
                VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
6094

6095
                def->forwardType = VIR_NETWORK_FORWARD_NONE;
6096

6097 6098 6099 6100 6101 6102 6103 6104 6105 6106
                data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                                 networkNameUtf16,
                                                                 &dhcpServer);
                if (dhcpServer) {
                    def->nranges = 1;
                    if (VIR_ALLOC_N(def->ranges, def->nranges) >=0 ) {
                        PRUnichar *ipAddressUtf16     = NULL;
                        PRUnichar *networkMaskUtf16   = NULL;
                        PRUnichar *fromIPAddressUtf16 = NULL;
                        PRUnichar *toIPAddressUtf16   = NULL;
6107

6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125
                        dhcpServer->vtbl->GetIPAddress(dhcpServer, &ipAddressUtf16);
                        dhcpServer->vtbl->GetNetworkMask(dhcpServer, &networkMaskUtf16);
                        dhcpServer->vtbl->GetLowerIP(dhcpServer, &fromIPAddressUtf16);
                        dhcpServer->vtbl->GetUpperIP(dhcpServer, &toIPAddressUtf16);
                        /* Currently virtualbox supports only one dhcp server per network
                         * with contigious address space from start to end
                         */
                        VBOX_UTF16_TO_UTF8(ipAddressUtf16, &def->ipAddress);
                        VBOX_UTF16_TO_UTF8(networkMaskUtf16, &def->netmask);
                        VBOX_UTF16_TO_UTF8(fromIPAddressUtf16, &def->ranges[0].start);
                        VBOX_UTF16_TO_UTF8(toIPAddressUtf16, &def->ranges[0].end);

                        VBOX_UTF16_FREE(ipAddressUtf16);
                        VBOX_UTF16_FREE(networkMaskUtf16);
                        VBOX_UTF16_FREE(fromIPAddressUtf16);
                        VBOX_UTF16_FREE(toIPAddressUtf16);
                    } else {
                        def->nranges = 0;
6126
                        virReportOOMError();
6127
                    }
6128

6129 6130 6131 6132 6133 6134 6135 6136 6137
                    def->nhosts = 1;
                    if (VIR_ALLOC_N(def->hosts, def->nhosts) >=0 ) {
                        def->hosts[0].name = strdup(network->name);
                        if (def->hosts[0].name == NULL) {
                            VIR_FREE(def->hosts);
                            def->nhosts = 0;
                            vboxError(network->conn,
                                      VIR_ERR_SYSTEM_ERROR,
                                      "%s", "strdup failed");
6138
                        } else {
6139 6140
                            PRUnichar *macAddressUtf16 = NULL;
                            PRUnichar *ipAddressUtf16  = NULL;
6141

6142
                            networkInterface->vtbl->GetHardwareAddress(networkInterface, &macAddressUtf16);
6143 6144
                            networkInterface->vtbl->GetIPAddress(networkInterface, &ipAddressUtf16);

6145 6146
                            VBOX_UTF16_TO_UTF8(macAddressUtf16, &def->hosts[0].mac);
                            VBOX_UTF16_TO_UTF8(ipAddressUtf16, &def->hosts[0].ip);
6147

6148 6149
                            VBOX_UTF16_FREE(macAddressUtf16);
                            VBOX_UTF16_FREE(ipAddressUtf16);
6150 6151
                        }
                    } else {
6152
                        def->nhosts = 0;
6153
                    }
6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167

                    VBOX_RELEASE(dhcpServer);
                } else {
                    PRUnichar *networkMaskUtf16 = NULL;
                    PRUnichar *ipAddressUtf16   = NULL;

                    networkInterface->vtbl->GetNetworkMask(networkInterface, &networkMaskUtf16);
                    networkInterface->vtbl->GetIPAddress(networkInterface, &ipAddressUtf16);

                    VBOX_UTF16_TO_UTF8(networkMaskUtf16, &def->netmask);
                    VBOX_UTF16_TO_UTF8(ipAddressUtf16, &def->ipAddress);

                    VBOX_UTF16_FREE(networkMaskUtf16);
                    VBOX_UTF16_FREE(ipAddressUtf16);
6168 6169
                }

6170 6171 6172 6173 6174 6175
                DEBUGIID("Network UUID", vboxnet0IID);
                vboxIIDUnalloc(vboxnet0IID);
                VBOX_UTF16_FREE(networkNameUtf16);
            } else {
                vboxError(network->conn, VIR_ERR_SYSTEM_ERROR,
                           "%s", "strdup failed");
6176 6177
            }
        }
6178 6179

        VBOX_RELEASE(networkInterface);
6180 6181
    }

6182 6183 6184
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

6185
    ret = virNetworkDefFormat(def);
6186 6187

cleanup:
6188
    virNetworkDefFree(def);
6189 6190 6191 6192
    VIR_FREE(networkNameUtf8);
    return ret;
}

6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209
/**
 * The Storage Functions here on
 */

static virDrvOpenStatus vboxStorageOpen (virConnectPtr conn,
                                         virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                         int flags ATTRIBUTE_UNUSED) {
    vboxGlobalData *data = conn->privateData;

    if (STRNEQ(conn->driver->name, "VBOX"))
        goto cleanup;

    if ((data->pFuncs      == NULL) ||
        (data->vboxObj     == NULL) ||
        (data->vboxSession == NULL))
        goto cleanup;

6210
    DEBUG0("vbox storage initialized");
6211 6212 6213 6214 6215 6216 6217 6218
    /* conn->storagePrivateData = some storage specific data */
    return VIR_DRV_OPEN_SUCCESS;

cleanup:
    return VIR_DRV_OPEN_DECLINED;
}

static int vboxStorageClose (virConnectPtr conn) {
6219
    DEBUG0("vbox storage uninitialized");
6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232
    conn->storagePrivateData = NULL;
    return 0;
}

static int vboxStorageNumOfPools(virConnectPtr conn ATTRIBUTE_UNUSED) {

    /** Currently only one pool supported, the default one
     * given by ISystemProperties::defaultHardDiskFolder()
     */

    return 1;
}

6233 6234
static int vboxStorageListPools(virConnectPtr conn ATTRIBUTE_UNUSED,
                                char **const names, int nnames) {
6235 6236 6237 6238 6239
    int numActive = 0;

    if (nnames == 1) {
        names[numActive] = strdup("default-pool");
        if (names[numActive] == NULL) {
6240
            virReportOOMError();
6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267
        } else {
            numActive++;
        }
    }
    return numActive;
}

static virStoragePoolPtr vboxStoragePoolLookupByName(virConnectPtr conn, const char *name) {
    virStoragePoolPtr ret = NULL;

    /** Current limitation of the function: since
     * the default pool doesn't have UUID just assign
     * one till vbox can handle pools
     */
    if (STREQ("default-pool", name)) {
        unsigned char uuid[VIR_UUID_BUFLEN];
        const char *uuidstr = "1deff1ff-1481-464f-967f-a50fe8936cc4";

        virUUIDParse(uuidstr, uuid);

        ret = virGetStoragePool(conn, name, uuid);
    }

    return ret;
}

static int vboxStoragePoolNumOfVolumes(virStoragePoolPtr pool) {
6268
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
6269 6270 6271 6272 6273 6274
    IHardDisk **hardDisks       = NULL;
    PRUint32 hardDiskCount      = 0;
    PRUint32 hardDiskAccessible = 0;
    nsresult rc;
    int i;

6275 6276 6277 6278 6279 6280
    rc = data->vboxObj->vtbl->GetHardDisks(data->vboxObj, &hardDiskCount, &hardDisks);
    if (NS_SUCCEEDED(rc)) {
        for (i = 0; i < hardDiskCount; ++i) {
            IHardDisk *hardDisk = hardDisks[i];
            if (hardDisk) {
                PRUint32 hddstate;
6281

6282 6283 6284
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible)
                    hardDiskAccessible++;
6285

6286
                VBOX_MEDIUM_RELEASE(hardDisk);
6287 6288
            }
        }
6289 6290 6291 6292 6293 6294
        hardDiskCount = 0;
    } else {
        hardDiskCount = -1;
        vboxError(pool->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                  "could not get number of volumes in the pool",
                  pool->name, (unsigned)rc);
6295 6296 6297
    }

    if (hardDiskAccessible)
6298
        ret = hardDiskAccessible;
6299
    else
6300 6301 6302
        ret = hardDiskCount;

    return ret;
6303 6304 6305
}

static int vboxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names, int nnames) {
6306
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
6307 6308 6309 6310 6311 6312
    IHardDisk **hardDisks  = NULL;
    PRUint32 hardDiskCount = 0;
    PRUint32 numActive     = 0;
    nsresult rc;
    int i;

6313 6314 6315 6316
    rc = data->vboxObj->vtbl->GetHardDisks(data->vboxObj, &hardDiskCount, &hardDisks);
    if (NS_SUCCEEDED(rc)) {
        for (i = 0; i < hardDiskCount && numActive < nnames; ++i) {
            IHardDisk *hardDisk = hardDisks[i];
6317

6318 6319 6320 6321
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
6322

6323 6324 6325
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
6326

6327 6328
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
6329

6330 6331 6332 6333
                    if (nameUtf8) {
                        DEBUG("nnames[%d]: %s", numActive, nameUtf8);
                        names[numActive] = strdup(nameUtf8);
                        if (names[numActive] == NULL) {
6334
                            virReportOOMError();
6335 6336
                        } else {
                            numActive++;
6337
                        }
6338 6339

                        VBOX_UTF8_FREE(nameUtf8);
6340 6341
                    }
                }
6342
                VBOX_MEDIUM_RELEASE(hardDisk);
6343 6344
            }
        }
6345 6346 6347 6348 6349 6350
        hardDiskCount = 0;
    } else {
        hardDiskCount = -1;
        vboxError(pool->conn, VIR_ERR_INTERNAL_ERROR,"%s:%s, rc=%08x",
                  "could not get the volume list in the pool",
                  pool->name, (unsigned)rc);
6351 6352 6353
    }

    if (numActive)
6354
        ret = numActive;
6355
    else
6356 6357 6358
        ret = hardDiskCount;

    return ret;
6359 6360 6361
}

static virStorageVolPtr vboxStorageVolLookupByName(virStoragePoolPtr pool, const char *name) {
6362
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
6363 6364 6365 6366 6367
    IHardDisk **hardDisks        = NULL;
    PRUint32 hardDiskCount       = 0;
    nsresult rc;
    int i;

6368 6369
    if(!name)
        return ret;
6370

6371 6372 6373 6374
    rc = data->vboxObj->vtbl->GetHardDisks(data->vboxObj, &hardDiskCount, &hardDisks);
    if (NS_SUCCEEDED(rc)) {
        for (i = 0; i < hardDiskCount; ++i) {
            IHardDisk *hardDisk = hardDisks[i];
6375

6376 6377 6378 6379
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
6380

6381 6382 6383
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
6384

6385 6386 6387 6388
                    if (nameUtf16) {
                        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                        VBOX_UTF16_FREE(nameUtf16);
                    }
6389

6390 6391 6392
                    if (nameUtf8 && STREQ(nameUtf8, name)) {
                        vboxIID *hddIID     = NULL;
                        char    *hddIIDUtf8 = NULL;
6393

6394
                        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID);
6395

6396
                        if (hddIID) {
6397
                            vboxIIDtoUtf8(hddIID, &hddIIDUtf8);
6398 6399
                            vboxIIDUnalloc(hddIID);
                        }
6400

6401
                        if (hddIIDUtf8) {
6402

6403
                            ret = virGetStorageVol(pool->conn, pool->name, name, hddIIDUtf8);
6404

6405 6406 6407 6408
                            DEBUG("virStorageVolPtr: %p", ret);
                            DEBUG("Storage Volume Name: %s", name);
                            DEBUG("Storage Volume key : %s", hddIIDUtf8);
                            DEBUG("Storage Volume Pool: %s", pool->name);
6409

6410
                            vboxIIDUtf8Free(hddIIDUtf8);
6411 6412
                        }

6413 6414
                        VBOX_UTF8_FREE(nameUtf8);
                        break;
6415
                    }
6416 6417 6418

                    if (nameUtf8)
                        VBOX_UTF8_FREE(nameUtf8);
6419 6420 6421
                }
            }
        }
6422 6423 6424

        for (i = 0; i < hardDiskCount; ++i)
            VBOX_MEDIUM_RELEASE(hardDisks[i]);
6425 6426 6427 6428 6429 6430
    }

    return ret;
}

static virStorageVolPtr vboxStorageVolLookupByKey(virConnectPtr conn, const char *key) {
6431
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
6432 6433 6434 6435
    vboxIID   *hddIID    = NULL;
    IHardDisk *hardDisk  = NULL;
    nsresult rc;

6436 6437 6438
    if (!key)
        return ret;

6439
#if VBOX_API_VERSION == 2002
6440

6441
    if (VIR_ALLOC(hddIID) < 0) {
6442
        virReportOOMError();
6443 6444 6445
        goto cleanup;
    }

6446 6447 6448 6449
    unsigned char hddUUID[VIR_UUID_BUFLEN];

    virUUIDParse(key, hddUUID);
    vboxIIDFromUUID(hddUUID, hddIID);
6450 6451 6452

#else  /* VBOX_API_VERSION != 2002 */

6453 6454 6455
    VBOX_UTF8_TO_UTF16(key, &hddIID);
    if (!hddIID)
        return ret;
6456

6457
#endif /* VBOX_API_VERSION != 2002 */
6458

6459 6460 6461
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
6462

6463 6464 6465 6466
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
6467

6468 6469
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
6470

6471 6472 6473 6474 6475 6476 6477 6478
            if (hddNameUtf8) {
                if (vboxStorageNumOfPools(conn) == 1) {
                    ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, key);
                    DEBUG("Storage Volume Pool: %s", "default-pool");
                } else {
                    /* TODO: currently only one default pool and thus
                     * nothing here, change it when pools are supported
                     */
6479 6480
                }

6481 6482 6483 6484 6485
                DEBUG("Storage Volume Name: %s", key);
                DEBUG("Storage Volume key : %s", hddNameUtf8);

                VBOX_UTF8_FREE(hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
6486 6487
            }
        }
6488 6489

        VBOX_MEDIUM_RELEASE(hardDisk);
6490 6491 6492 6493
    }

#if VBOX_API_VERSION == 2002
cleanup:
6494
#endif  /* VBOX_API_VERSION == 2002 */
6495 6496 6497 6498 6499
    vboxIIDFree(hddIID);
    return ret;
}

static virStorageVolPtr vboxStorageVolLookupByPath(virConnectPtr conn, const char *path) {
6500
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
6501 6502 6503 6504
    PRUnichar *hddPathUtf16 = NULL;
    IHardDisk *hardDisk     = NULL;
    nsresult rc;

6505 6506
    if (!path)
        return ret;
6507

6508
    VBOX_UTF8_TO_UTF16(path, &hddPathUtf16);
6509

6510 6511
    if (!hddPathUtf16)
        return ret;
6512

6513 6514 6515
    rc = data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddPathUtf16, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
6516

6517 6518 6519 6520 6521 6522
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
            vboxIID   *hddIID       = NULL;
            char      *hddIIDUtf8   = NULL;
6523

6524 6525
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID);
6526

6527 6528 6529 6530
            if (hddNameUtf16) {
                VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
            }
6531

6532
            if (hddIID) {
6533
                vboxIIDtoUtf8(hddIID, &hddIIDUtf8);
6534 6535
                vboxIIDUnalloc(hddIID);
            }
6536

6537
            if (hddIIDUtf8 && hddNameUtf8) {
6538

6539 6540 6541 6542 6543
                /* TODO: currently only one default pool and thus
                 * the check below, change it when pools are supported
                 */
                if (vboxStorageNumOfPools(conn) == 1)
                    ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, hddIIDUtf8);
6544

6545 6546 6547
                DEBUG("Storage Volume Pool: %s", "default-pool");
                DEBUG("Storage Volume Name: %s", hddNameUtf8);
                DEBUG("Storage Volume key : %s", hddIIDUtf8);
6548 6549 6550

            }

6551 6552 6553 6554 6555
            if (hddNameUtf8)
                VBOX_UTF8_FREE(hddNameUtf8);

            if (hddIIDUtf8)
                vboxIIDUtf8Free(hddIIDUtf8);
6556
        }
6557 6558

        VBOX_MEDIUM_RELEASE(hardDisk);
6559 6560
    }

6561 6562
    VBOX_UTF16_FREE(hddPathUtf16);

6563 6564 6565 6566 6567 6568
    return ret;
}

static virStorageVolPtr vboxStorageVolCreateXML(virStoragePoolPtr pool,
                                                const char *xml,
                                                unsigned int flags ATTRIBUTE_UNUSED) {
6569
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
6570
    virStorageVolDefPtr  def  = NULL;
6571 6572
    PRUnichar *hddFormatUtf16 = NULL;
    PRUnichar *hddNameUtf16   = NULL;
6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583
    virStoragePoolDef poolDef;
    nsresult rc;

    /* since there is currently one default pool now
     * and virStorageVolDefFormat() just checks it type
     * so just assign it for now, change the behaviour
     * when vbox supports pools.
     */
    memset(&poolDef, 0, sizeof(poolDef));
    poolDef.type = VIR_STORAGE_POOL_DIR;

6584
    if ((def = virStorageVolDefParseString(&poolDef, xml)) == NULL)
6585 6586
        goto cleanup;

6587 6588 6589
    if (   !def->name
        || (def->type != VIR_STORAGE_VOL_FILE))
        goto cleanup;
6590

6591 6592 6593 6594 6595 6596
    /* TODO: for now only the vmdk, vpc and vdi type harddisk
     * variants can be created, also since there is no vdi
     * type in enum virStorageFileFormat {} the default
     * will be to create vdi if nothing is specified in
     * def->target.format
     */
6597

6598 6599 6600 6601 6602 6603 6604
    if (def->target.format == VIR_STORAGE_FILE_VMDK) {
        VBOX_UTF8_TO_UTF16("VMDK", &hddFormatUtf16);
    } else if (def->target.format == VIR_STORAGE_FILE_VPC) {
        VBOX_UTF8_TO_UTF16("VHD", &hddFormatUtf16);
    } else {
        VBOX_UTF8_TO_UTF16("VDI", &hddFormatUtf16);
    }
6605

6606
    VBOX_UTF8_TO_UTF16(def->name, &hddNameUtf16);
6607

6608 6609
    if (hddFormatUtf16 && hddNameUtf16) {
        IHardDisk *hardDisk = NULL;
6610

6611 6612 6613 6614 6615
        rc = data->vboxObj->vtbl->CreateHardDisk(data->vboxObj, hddFormatUtf16, hddNameUtf16, &hardDisk);
        if (NS_SUCCEEDED(rc)) {
            IProgress *progress    = NULL;
            PRUint64   logicalSize = def->capacity / 1024 / 1024;
            PRUint32   variant     = HardDiskVariant_Standard;
6616

6617 6618
            if (def->capacity == def->allocation)
                variant = HardDiskVariant_Fixed;
6619

6620 6621 6622
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, variant, &progress);
            if (NS_SUCCEEDED(rc) && progress) {
                vboxIID *hddIID = NULL;
6623
#if VBOX_API_VERSION == 2002
6624
                nsresult resultCode;
6625
#else
6626
                PRInt32  resultCode;
6627 6628
#endif

6629 6630
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
6631

6632
                if (NS_SUCCEEDED(resultCode)) {
6633

6634 6635 6636
                    rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID);
                    if (NS_SUCCEEDED(rc)) {
                        char *hddKey = NULL;
6637

6638
                        vboxIIDtoUtf8(hddIID, &hddKey);
6639

6640 6641
                        if (hddKey)
                            ret = virGetStorageVol(pool->conn, pool->name, def->name, hddKey);
6642

6643 6644
                        vboxIIDUtf8Free(hddKey);
                        vboxIIDUnalloc(hddIID);
6645 6646 6647
                    }
                }

6648
                VBOX_RELEASE(progress);
6649 6650
            }

6651
        }
6652 6653
    }

6654 6655 6656
    VBOX_UTF16_FREE(hddFormatUtf16);
    VBOX_UTF16_FREE(hddNameUtf16);

6657 6658 6659 6660 6661 6662 6663
cleanup:
    virStorageVolDefFree(def);
    return ret;
}

static int vboxStorageVolDelete(virStorageVolPtr vol,
                                unsigned int flags ATTRIBUTE_UNUSED) {
6664
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
6665 6666 6667 6668
    vboxIID   *hddIID    = NULL;
    IHardDisk *hardDisk  = NULL;
    int deregister = 0;
    nsresult rc;
6669 6670
    int i = 0;
    int j = 0;
6671

6672
    vboxUtf8toIID(vol->key, &hddIID);
6673 6674
    if (!hddIID)
        return ret;
6675

6676 6677 6678
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
6679

6680 6681 6682 6683
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint32  machineIdsSize = 0;
            vboxIID **machineIds     = NULL;
6684

6685
            VBOX_MEDIUM_FUNC_ARG2(hardDisk, GetMachineIds, &machineIdsSize, &machineIds);
6686

6687 6688
            for (i = 0; i < machineIdsSize; i++) {
                IMachine *machine = NULL;
6689

6690 6691
                rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, machineIds[i]);
                if (NS_SUCCEEDED(rc)) {
6692

6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742
                    rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                    if (NS_SUCCEEDED(rc)) {
                        PRUint32 hddAttachSize = 0;
                        IHardDiskAttachment **hddAttachments = NULL;

#if VBOX_API_VERSION < 3001
                        machine->vtbl->GetHardDiskAttachments(machine, &hddAttachSize, &hddAttachments);
#else  /* VBOX_API_VERSION >= 3001 */
                        machine->vtbl->GetMediumAttachments(machine, &hddAttachSize, &hddAttachments);
#endif /* VBOX_API_VERSION >= 3001 */
                        for (j = 0; j < hddAttachSize; j++) {
                            IHardDiskAttachment *hddAttachment = hddAttachments[j];

                            if (hddAttachment) {
                                IHardDisk *hdd = NULL;

#if VBOX_API_VERSION < 3001
                                rc = hddAttachment->vtbl->GetHardDisk(hddAttachment, &hdd);
#else  /* VBOX_API_VERSION >= 3001 */
                                rc = hddAttachment->vtbl->GetMedium(hddAttachment, &hdd);
#endif /* VBOX_API_VERSION >= 3001 */
                                if (NS_SUCCEEDED(rc) && hdd) {
                                    vboxIID *iid = NULL;

                                    VBOX_MEDIUM_FUNC_ARG1(hdd, GetId, &iid);
                                    if (iid) {

                                            DEBUGIID("HardDisk (to delete) UUID", hddIID);
                                            DEBUGIID("HardDisk (currently processing) UUID", iid);

                                        if (vboxIIDEqual(hddIID, iid)) {
                                            PRUnichar *controller = NULL;
                                            PRInt32    port       = 0;
                                            PRInt32    device     = 0;

                                            DEBUGIID("Found HardDisk to delete, UUID", hddIID);

                                            hddAttachment->vtbl->GetController(hddAttachment, &controller);
                                            hddAttachment->vtbl->GetPort(hddAttachment, &port);
                                            hddAttachment->vtbl->GetDevice(hddAttachment, &device);

#if VBOX_API_VERSION < 3001
                                            rc = machine->vtbl->DetachHardDisk(machine, controller, port, device);
#else  /* VBOX_API_VERSION >= 3001 */
                                            rc = machine->vtbl->DetachDevice(machine, controller, port, device);
#endif /* VBOX_API_VERSION >= 3001 */
                                            if (NS_SUCCEEDED(rc)) {
                                                rc = machine->vtbl->SaveSettings(machine);
                                                DEBUG0("saving machine settings");
                                            }
6743

6744 6745 6746
                                            if (NS_SUCCEEDED(rc)) {
                                                deregister++;
                                                DEBUG("deregistering hdd:%d", deregister);
6747
                                            }
6748 6749 6750

                                            if (controller)
                                                VBOX_UTF16_FREE(controller);
6751
                                        }
6752
                                        vboxIIDUnalloc(iid);
6753
                                    }
6754
                                    VBOX_MEDIUM_RELEASE(hdd);
6755
                                }
6756
                                VBOX_RELEASE(hddAttachment);
6757 6758
                            }
                        }
6759
                        VBOX_RELEASE(machine);
6760
                    }
6761 6762 6763
                    data->vboxSession->vtbl->Close(data->vboxSession);
                }
            }
6764

6765 6766 6767
            for (i = 0; i < machineIdsSize; i++)
                if (machineIds[i])
                    vboxIIDUnalloc(machineIds[i]);
6768

6769 6770
            if (machineIdsSize == 0 || machineIdsSize == deregister) {
                IProgress *progress = NULL;
6771

6772
                rc = hardDisk->vtbl->DeleteStorage(hardDisk, &progress);
6773

6774 6775 6776 6777 6778
                if (NS_SUCCEEDED(rc) && progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                    DEBUGIID("HardDisk deleted, UUID", hddIID);
                    ret = 0;
6779 6780 6781 6782
                }
            }

        }
6783 6784

        VBOX_MEDIUM_RELEASE(hardDisk);
6785 6786
    }

6787 6788
    vboxIIDUtf16Free(hddIID);

6789 6790 6791 6792
    return ret;
}

static int vboxStorageVolGetInfo(virStorageVolPtr vol, virStorageVolInfoPtr info) {
6793
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
6794 6795 6796 6797
    IHardDisk *hardDisk  = NULL;
    vboxIID   *hddIID    = NULL;
    nsresult rc;

6798
    if (!info)
6799
        return ret;
6800

6801
    vboxUtf8toIID(vol->key, &hddIID);
6802 6803
    if (!hddIID)
        return ret;
6804

6805 6806 6807
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
6808

6809 6810 6811 6812
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
6813

6814
            info->type = VIR_STORAGE_VOL_FILE;
6815

6816 6817
            hardDisk->vtbl->GetLogicalSize(hardDisk, &hddLogicalSize);
            info->capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
6818

6819 6820
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            info->allocation = hddActualSize;
6821

6822
            ret = 0;
6823

6824 6825 6826 6827
            DEBUG("Storage Volume Name: %s", vol->name);
            DEBUG("Storage Volume Type: %s", info->type == VIR_STORAGE_VOL_BLOCK ? "Block" : "File");
            DEBUG("Storage Volume Capacity: %llu", info->capacity);
            DEBUG("Storage Volume Allocation: %llu", info->allocation);
6828
        }
6829 6830

        VBOX_MEDIUM_RELEASE(hardDisk);
6831 6832
    }

6833 6834
    vboxIIDUtf16Free(hddIID);

6835 6836 6837 6838
    return ret;
}

static char *vboxStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags ATTRIBUTE_UNUSED) {
6839
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
6840 6841 6842 6843 6844 6845 6846 6847 6848 6849
    IHardDisk *hardDisk  = NULL;
    vboxIID   *hddIID    = NULL;
    virStoragePoolDef pool;
    virStorageVolDef def;
    int defOk = 0;
    nsresult rc;

    memset(&pool, 0, sizeof(pool));
    memset(&def, 0, sizeof(def));

6850
    vboxUtf8toIID(vol->key, &hddIID);
6851 6852
    if (!hddIID)
        return ret;
6853

6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;

        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (NS_SUCCEEDED(rc) && hddstate != MediaState_Inaccessible) {
            PRUnichar *hddFormatUtf16 = NULL;
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;

            /* since there is currently one default pool now
             * and virStorageVolDefFormat() just checks it type
             * so just assign it for now, change the behaviour
             * when vbox supports pools.
             */
            pool.type = VIR_STORAGE_POOL_DIR;
            def.type = VIR_STORAGE_VOL_FILE;
            defOk = 1;

            rc = hardDisk->vtbl->GetLogicalSize(hardDisk, &hddLogicalSize);
            if (NS_SUCCEEDED(rc) && defOk)
                def.capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
            else
                defOk = 0;

            rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            if (NS_SUCCEEDED(rc) && defOk)
                def.allocation = hddActualSize;
            else
                defOk = 0;

            def.name = strdup(vol->name);
            if (!(def.name && defOk))
                defOk = 0;

            def.key = strdup(vol->key);
            if (!(def.key && defOk))
                defOk = 0;

            rc = hardDisk->vtbl->GetFormat(hardDisk, &hddFormatUtf16);
            if (NS_SUCCEEDED(rc) && defOk) {
                char *hddFormatUtf8 = NULL;

                VBOX_UTF16_TO_UTF8(hddFormatUtf16, &hddFormatUtf8);
                if (hddFormatUtf8) {

                    DEBUG("Storage Volume Format: %s", hddFormatUtf8);

                    if (STRCASEEQ("vmdk", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VMDK;
                    else if (STRCASEEQ("vhd", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VPC;
6906
                    else
6907
                        def.target.format = VIR_STORAGE_FILE_RAW;
6908

6909 6910 6911
                    /* TODO: need to add vdi to enum virStorageFileFormat {}
                     * and then add it here
                     */
6912

6913
                    VBOX_UTF8_FREE(hddFormatUtf8);
6914 6915
                }

6916 6917 6918
                VBOX_UTF16_FREE(hddFormatUtf16);
            } else {
                defOk = 0;
6919 6920
            }
        }
6921 6922

        VBOX_MEDIUM_RELEASE(hardDisk);
6923 6924
    }

6925 6926
    vboxIIDUtf16Free(hddIID);

6927
    if (defOk)
6928
        ret = virStorageVolDefFormat(&pool, &def);
6929 6930 6931 6932 6933

    return ret;
}

static char *vboxStorageVolGetPath(virStorageVolPtr vol) {
6934
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
6935 6936 6937 6938
    IHardDisk *hardDisk  = NULL;
    vboxIID   *hddIID    = NULL;
    nsresult rc;

6939
    vboxUtf8toIID(vol->key, &hddIID);
6940 6941
    if (!hddIID)
        return ret;
6942

6943 6944 6945
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
6946

6947 6948 6949 6950
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddLocationUtf16 = NULL;
            char      *hddLocationUtf8  = NULL;
6951

6952
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetLocation, &hddLocationUtf16);
6953

6954 6955
            VBOX_UTF16_TO_UTF8(hddLocationUtf16, &hddLocationUtf8);
            if (hddLocationUtf8) {
6956

6957 6958
                ret = strdup(hddLocationUtf8);
                if (!ret)
6959
                    virReportOOMError();
6960

6961 6962 6963
                DEBUG("Storage Volume Name: %s", vol->name);
                DEBUG("Storage Volume Path: %s", hddLocationUtf8);
                DEBUG("Storage Volume Pool: %s", vol->pool);
6964

6965
                VBOX_UTF8_FREE(hddLocationUtf8);
6966 6967
            }

6968
            VBOX_UTF16_FREE(hddLocationUtf16);
6969
        }
6970 6971

        VBOX_MEDIUM_RELEASE(hardDisk);
6972 6973
    }

6974 6975
    vboxIIDUtf16Free(hddIID);

6976 6977
    return ret;
}
6978 6979 6980 6981 6982

/**
 * Function Tables
 */

6983 6984 6985
virDriver NAME(Driver) = {
    VIR_DRV_VBOX,
    "VBOX",
6986 6987 6988 6989 6990
    vboxOpen, /* open */
    vboxClose, /* close */
    NULL, /* supports_feature */
    NULL, /* type */
    vboxGetVersion, /* version */
6991
    NULL, /* libvirtVersion (impl. in libvirt.c) */
6992
    virGetHostname, /* getHostname */
6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014
    vboxGetMaxVcpus, /* getMaxVcpus */
    nodeGetInfo, /* nodeGetInfo */
    vboxGetCapabilities, /* getCapabilities */
    vboxListDomains, /* listDomains */
    vboxNumOfDomains, /* numOfDomains */
    vboxDomainCreateXML, /* domainCreateXML */
    vboxDomainLookupByID, /* domainLookupByID */
    vboxDomainLookupByUUID, /* domainLookupByUUID */
    vboxDomainLookupByName, /* domainLookupByName */
    vboxDomainSuspend, /* domainSuspend */
    vboxDomainResume, /* domainResume */
    vboxDomainShutdown, /* domainShutdown */
    vboxDomainReboot, /* domainReboot */
    vboxDomainDestroy, /* domainDestroy */
    vboxDomainGetOSType, /* domainGetOSType */
    NULL, /* domainGetMaxMemory */
    NULL, /* domainSetMaxMemory */
    vboxDomainSetMemory, /* domainSetMemory */
    vboxDomainGetInfo, /* domainGetInfo */
    vboxDomainSave, /* domainSave */
    NULL, /* domainRestore */
    NULL, /* domainCoreDump */
7015
    vboxDomainSetVcpus, /* domainSetVcpus */
7016 7017
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
7018
    vboxDomainGetMaxVcpus, /* domainGetMaxVcpus */
7019 7020 7021
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
    vboxDomainDumpXML, /* domainDumpXML */
7022 7023
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
7024 7025 7026 7027 7028 7029
    vboxListDefinedDomains, /* listDefinedDomains */
    vboxNumOfDefinedDomains, /* numOfDefinedDomains */
    vboxDomainCreate, /* domainCreate */
    vboxDomainDefineXML, /* domainDefineXML */
    vboxDomainUndefine, /* domainUndefine */
    vboxDomainAttachDevice, /* domainAttachDevice */
7030
    vboxDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
7031
    vboxDomainDetachDevice, /* domainDetachDevice */
7032
    vboxDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
7033 7034 7035 7036 7037 7038 7039 7040 7041 7042
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
7043
    NULL, /* domainMemoryStats */
7044 7045
    NULL, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
7046 7047
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
7048
#if VBOX_API_VERSION == 2002
7049 7050
    NULL, /* domainEventRegister */
    NULL, /* domainEventDeregister */
7051 7052 7053 7054
#else
    vboxDomainEventRegister, /* domainEventRegister */
    vboxDomainEventDeregister, /* domainEventDeregister */
#endif
7055 7056 7057 7058 7059
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
    NULL, /* nodeDeviceDettach */
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
C
Chris Lalancette 已提交
7060
    NULL, /* domainMigratePrepareTunnel */
7061 7062 7063 7064
    vboxIsEncrypted,
    vboxIsSecure,
    vboxDomainIsActive,
    vboxDomainIsPersistent,
J
Jiri Denemark 已提交
7065
    NULL, /* cpuCompare */
7066
    NULL, /* cpuBaseline */
7067
    NULL, /* domainGetJobInfo */
7068
    NULL, /* domainAbortJob */
7069
};
7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090

virNetworkDriver NAME(NetworkDriver) = {
    "VBOX",
    .open                   = vboxNetworkOpen,
    .close                  = vboxNetworkClose,
    .numOfNetworks          = vboxNumOfNetworks,
    .listNetworks           = vboxListNetworks,
    .numOfDefinedNetworks   = vboxNumOfDefinedNetworks,
    .listDefinedNetworks    = vboxListDefinedNetworks,
    .networkLookupByUUID    = vboxNetworkLookupByUUID,
    .networkLookupByName    = vboxNetworkLookupByName,
    .networkCreateXML       = vboxNetworkCreateXML,
    .networkDefineXML       = vboxNetworkDefineXML,
    .networkUndefine        = vboxNetworkUndefine,
    .networkCreate          = vboxNetworkCreate,
    .networkDestroy         = vboxNetworkDestroy,
    .networkDumpXML         = vboxNetworkDumpXML,
    .networkGetBridgeName   = NULL,
    .networkGetAutostart    = NULL,
    .networkSetAutostart    = NULL
};
7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126

virStorageDriver NAME(StorageDriver) = {
    .name               = "VBOX",
    .open               = vboxStorageOpen,
    .close              = vboxStorageClose,
    .numOfPools         = vboxStorageNumOfPools,
    .listPools          = vboxStorageListPools,
    .numOfDefinedPools  = NULL,
    .listDefinedPools   = NULL,
    .findPoolSources    = NULL,
    .poolLookupByName   = vboxStoragePoolLookupByName,
    .poolLookupByUUID   = NULL,
    .poolLookupByVolume = NULL,
    .poolCreateXML      = NULL,
    .poolDefineXML      = NULL,
    .poolBuild          = NULL,
    .poolUndefine       = NULL,
    .poolCreate         = NULL,
    .poolDestroy        = NULL,
    .poolDelete         = NULL,
    .poolRefresh        = NULL,
    .poolGetInfo        = NULL,
    .poolGetXMLDesc     = NULL,
    .poolGetAutostart   = NULL,
    .poolSetAutostart   = NULL,
    .poolNumOfVolumes   = vboxStoragePoolNumOfVolumes,
    .poolListVolumes    = vboxStoragePoolListVolumes,

    .volLookupByName    = vboxStorageVolLookupByName,
    .volLookupByKey     = vboxStorageVolLookupByKey,
    .volLookupByPath    = vboxStorageVolLookupByPath,
    .volCreateXML       = vboxStorageVolCreateXML,
    .volCreateXMLFrom   = NULL,
    .volDelete          = vboxStorageVolDelete,
    .volGetInfo         = vboxStorageVolGetInfo,
    .volGetXMLDesc      = vboxStorageVolGetXMLDesc,
7127
    .volGetPath         = vboxStorageVolGetPath
7128
};