vbox_tmpl.c 301.2 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
 * 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 <sys/utsname.h>
38
#include <stdbool.h>
39
#include <unistd.h>
40 41 42 43

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

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


73 74 75 76 77 78 79
#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)

80 81
#define VBOX_ADDREF(arg) (arg)->vtbl->nsisupports.AddRef((nsISupports *)(arg))

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
#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

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

#else  /* VBOX_API_VERSION >= 3001 */

typedef IMedium IHardDisk;
typedef IMediumAttachment IHardDiskAttachment;
119 120 121 122 123
# 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) \
124
    (object)->vtbl->func(object, arg1)
125
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
126 127 128
    (object)->vtbl->func(object, arg1, arg2)

#endif /* VBOX_API_VERSION >= 3001 */
129

130 131
#define vboxError(code, ...) \
        virReportErrorHelper(NULL, VIR_FROM_VBOX, code, __FILE__, \
132
                             __FUNCTION__, __LINE__, __VA_ARGS__)
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 158 159 160
#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]);\
}\

161 162
typedef struct {
    virMutex lock;
163
    unsigned long version;
164 165 166 167 168

    virCapsPtr caps;

    IVirtualBox *vboxObj;
    ISession *vboxSession;
169 170 171

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

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

193 194
} vboxGlobalData;

195 196 197 198 199 200 201 202 203 204
/* 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
 */

205
static vboxGlobalData *g_pVBoxGlobalData = NULL;
206 207

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

209 210 211 212
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml);
static int vboxDomainCreate(virDomainPtr dom);
static int vboxDomainUndefine(virDomainPtr dom);

213 214 215 216 217 218 219 220 221
static void vboxDriverLock(vboxGlobalData *data) {
    virMutexLock(&data->lock);
}

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

#if VBOX_API_VERSION == 2002
222

223 224 225 226 227 228 229
# 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)
230

231
static void nsIDtoChar(unsigned char *uuid, const nsID *iid) {
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 268 269 270
    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);
}

271
static void nsIDFromChar(nsID *iid, const unsigned char *uuid) {
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 308 309 310
    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);
}

311 312
typedef nsID vboxIID;

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

320
static void vboxIIDtoUtf8(vboxIID *iid, char **uuidstr) {
321
    unsigned char hddUUID[VIR_UUID_BUFLEN];
322

323
    if (VIR_ALLOC_N(*uuidstr, VIR_UUID_STRING_BUFLEN) < 0) {
324
        virReportOOMError();
325 326 327 328 329 330 331
        return;
    }

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

332
static void vboxUtf8toIID(char *uuidstr, vboxIID **iid) {
333 334 335
    unsigned char hddUUID[VIR_UUID_BUFLEN];

    if (VIR_ALLOC(*iid) < 0) {
336
        virReportOOMError();
337 338 339 340 341 342 343
        return;
    }

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

344
#else /* VBOX_API_VERSION != 2002 */
345

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

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

362 363 364 365 366
# 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)
367

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
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;
}

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

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

413
# if VBOX_API_VERSION >= 3001
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

/**
 * 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
 *
 */
430
static char *vboxGenerateMediumName(PRUint32  storageBus,
431 432 433 434 435
                                    PRInt32   deviceInst,
                                    PRInt32   devicePort,
                                    PRInt32   deviceSlot,
                                    PRUint32 *aMaxPortPerInst,
                                    PRUint32 *aMaxSlotPerPort) {
436
    const char *prefix = NULL;
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    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) {
457
        prefix = "hd";
458 459
    } else if (   (storageBus == StorageBus_SATA)
               || (storageBus == StorageBus_SCSI)) {
460
        prefix = "sd";
461
    } else if (storageBus == StorageBus_Floppy) {
462
        prefix = "fd";
463 464
    }

465
    name = virIndexToDiskName(total, prefix);
466

467
    DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
468
          "devicePort=%d deviceSlot=%d, maxPortPerInst=%u maxSlotPerPort=%u",
469
          NULLSTR(name), total, storageBus, deviceInst, devicePort,
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
          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;

604 605 606
    if (virStrToLong_i(strUtf8, NULL, 10, &ret) < 0)
        ret = -1;

607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
    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;
}

626
# endif /* VBOX_API_VERSION >= 3001 */
627

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

630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
static PRUnichar *
vboxSocketFormatAddrUtf16(vboxGlobalData *data, virSocketAddrPtr addr)
{
    char *utf8 = NULL;
    PRUnichar *utf16 = NULL;

    utf8 = virSocketFormatAddr(addr);

    if (utf8 == NULL) {
        return NULL;
    }

    VBOX_UTF8_TO_UTF16(utf8, &utf16);
    VIR_FREE(utf8);

    return utf16;
}

static int
vboxSocketParseAddrUtf16(vboxGlobalData *data, const PRUnichar *utf16,
                         virSocketAddrPtr addr)
{
    int result = -1;
    char *utf8 = NULL;

    VBOX_UTF16_TO_UTF8(utf16, &utf8);

    if (virSocketParseAddr(utf8, addr, AF_UNSPEC) < 0) {
        goto cleanup;
    }

    result = 0;

cleanup:
    VBOX_UTF8_FREE(utf8);

    return result;
}

669 670 671 672 673 674 675 676 677 678 679
static virCapsPtr vboxCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

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

680
    if (nodeCapsInitNUMA(caps) < 0)
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708
        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;
}

709 710 711
static int
vboxInitialize(vboxGlobalData *data)
{
712 713 714
    data->pFuncs = g_pfnGetFunctions(VBOX_XPCOMC_VERSION);

    if (data->pFuncs == NULL)
715
        goto cleanup;
716 717 718

#if VBOX_XPCOMC_VERSION == 0x00010000U
    data->pFuncs->pfnComInitialize(&data->vboxObj, &data->vboxSession);
719
#else  /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
720 721
    data->pFuncs->pfnComInitialize(IVIRTUALBOX_IID_STR, &data->vboxObj,
                               ISESSION_IID_STR, &data->vboxSession);
722

723
# if VBOX_API_VERSION == 2002
724 725 726

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

727
# else  /* !(VBOX_API_VERSION == 2002) */
728 729 730 731 732 733 734

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

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

    if (data->vboxQueue == NULL) {
735 736
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("nsIEventQueue object is null"));
737 738 739
        goto cleanup;
    }

740
# endif /* !(VBOX_API_VERSION == 2002) */
741
#endif /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
742 743

    if (data->vboxObj == NULL) {
744 745
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("IVirtualBox object is null"));
746
        goto cleanup;
747 748 749
    }

    if (data->vboxSession == NULL) {
750 751
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("ISession object is null"));
752 753
        goto cleanup;
    }
754 755 756 757 758 759 760

    return 0;

cleanup:
    return -1;
}

761
static int vboxExtractVersion(vboxGlobalData *data) {
762
    int ret = -1;
763 764 765 766 767 768 769 770 771 772
    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;

773
        VBOX_UTF16_TO_UTF8(versionUtf16, &vboxVersion);
774

775
        if (virParseVersionString(vboxVersion, &data->version) >= 0)
776 777
            ret = 0;

778 779
        VBOX_UTF8_FREE(vboxVersion);
        VBOX_COM_UNALLOC_MEM(versionUtf16);
780 781 782
    }

    if (ret != 0)
783 784
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Cound not extract VirtualBox version"));
785

786 787 788 789
    return ret;
}

static void vboxUninitialize(vboxGlobalData *data) {
790 791 792
    if (!data)
        return;

793 794
    if (data->pFuncs)
        data->pFuncs->pfnComUninitialize();
795 796

    virCapabilitiesFree(data->caps);
797 798 799 800 801
#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) */
802 803 804 805 806 807
    VIR_FREE(data);
}

static virDrvOpenStatus vboxOpen(virConnectPtr conn,
                                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                 int flags ATTRIBUTE_UNUSED) {
808
    vboxGlobalData *data = NULL;
809 810 811 812 813
    uid_t uid = getuid();

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "vbox:///session" : "vbox:///system");
        if (conn->uri == NULL) {
814
            virReportOOMError();
815 816 817 818
            return VIR_DRV_OPEN_ERROR;
        }
    }

819 820 821 822 823 824
    if (conn->uri->scheme == NULL ||
        STRNEQ (conn->uri->scheme, "vbox"))
        return VIR_DRV_OPEN_DECLINED;

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

827
    if (conn->uri->path == NULL || STREQ(conn->uri->path, "")) {
828
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
829 830 831 832
                  _("no VirtualBox driver path specified (try vbox:///session)"));
        return VIR_DRV_OPEN_ERROR;
    }

833
    if (uid != 0) {
834
        if (STRNEQ (conn->uri->path, "/session")) {
835
            vboxError(VIR_ERR_INTERNAL_ERROR,
836 837 838
                      _("unknown driver path '%s' specified (try vbox:///session)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
839 840
    } else { /* root */
        if (STRNEQ (conn->uri->path, "/system") &&
841
            STRNEQ (conn->uri->path, "/session")) {
842
            vboxError(VIR_ERR_INTERNAL_ERROR,
843 844 845
                      _("unknown driver path '%s' specified (try vbox:///system)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
846 847 848
    }

    if (VIR_ALLOC(data) < 0) {
849
        virReportOOMError();
850
        return VIR_DRV_OPEN_ERROR;
851 852
    }

853
    if (!(data->caps = vboxCapsInit()) ||
854 855
        vboxInitialize(data) < 0 ||
        vboxExtractVersion(data) < 0) {
856 857 858
        vboxUninitialize(data);
        return VIR_DRV_OPEN_ERROR;
    }
859

860 861 862 863 864 865 866
#if VBOX_API_VERSION == 2002

    /* No domainEventCallbacks in 2.2.* version */

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

    if (VIR_ALLOC(data->domainEventCallbacks) < 0) {
867
        virReportOOMError();
868 869 870 871 872 873 874 875
        return VIR_DRV_OPEN_ERROR;
    }

    data->conn = conn;
    g_pVBoxGlobalData = data;

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

876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    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;
}

903 904 905 906 907 908 909 910 911 912
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;
}

913
static int vboxGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED) {
914
    VBOX_OBJECT_CHECK(conn, int, -1);
915 916 917 918 919
    PRUint32 maxCPUCount = 0;

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

922 923 924 925
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
926 927 928 929 930 931 932 933 934 935
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}


static char *vboxGetCapabilities(virConnectPtr conn) {
936
    VBOX_OBJECT_CHECK(conn, char *, NULL);
937 938 939 940 941 942 943 944 945

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

    return ret;
}

static int vboxListDomains(virConnectPtr conn, int *ids, int nids) {
946
    VBOX_OBJECT_CHECK(conn, int, -1);
947
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
948
    PRUint32 state;
949
    nsresult rc;
950 951
    int i, j;

952
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
953
    if (NS_FAILED(rc)) {
954 955
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of Domains, rc=%08x"),(unsigned)rc);
956 957
        goto cleanup;
    }
958

959 960 961
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < nids); ++i) {
        IMachine *machine = machines.items[i];
962 963 964 965 966 967 968 969 970 971

        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;
972 973 974 975 976 977
                }
            }
        }
    }

cleanup:
978
    vboxArrayRelease(&machines);
979 980 981 982
    return ret;
}

static int vboxNumOfDomains(virConnectPtr conn) {
983
    VBOX_OBJECT_CHECK(conn, int, -1);
984
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
985
    PRUint32 state;
986
    nsresult rc;
987 988
    int i;

989
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
990
    if (NS_FAILED(rc)) {
991 992
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get number of Domains, rc=%08x"), (unsigned)rc);
993 994
        goto cleanup;
    }
995

996 997 998
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
999 1000 1001 1002 1003 1004 1005 1006 1007

        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++;
1008 1009 1010 1011 1012
            }
        }
    }

cleanup:
1013
    vboxArrayRelease(&machines);
1014 1015 1016 1017
    return ret;
}

static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
1018
                                        unsigned int flags) {
1019 1020 1021 1022 1023 1024 1025 1026
    /* 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.
     */

1027 1028 1029 1030 1031
    virDomainPtr dom;

    virCheckFlags(0, NULL);

    dom = vboxDomainDefineXML(conn, xml);
1032 1033 1034 1035 1036
    if (dom == NULL)
        return NULL;

    if (vboxDomainCreate(dom) < 0) {
        vboxDomainUndefine(dom);
1037
        virUnrefDomain(dom);
1038
        return NULL;
1039 1040 1041 1042 1043 1044
    }

    return dom;
}

static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id) {
1045
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1046
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1047
    vboxIID *iid         = NULL;
1048 1049
    unsigned char iidl[VIR_UUID_BUFLEN];
    PRUint32 state;
1050
    nsresult rc;
1051

1052 1053 1054
    /* Internal vbox IDs start from 0, the public libvirt ID
     * starts from 1, so refuse id==0, and adjust the rest*/
    if (id == 0) {
1055
        vboxError(VIR_ERR_NO_DOMAIN,
1056 1057 1058 1059 1060
                  _("no domain with matching id %d"), id);
        return NULL;
    }
    id = id - 1;

1061
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1062
    if (NS_FAILED(rc)) {
1063 1064
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1065 1066
        return NULL;
    }
1067

1068 1069 1070 1071
    if (id < machines.count) {
        IMachine *machine = machines.items[id];

        if (machine) {
1072
            PRBool isAccessible = PR_FALSE;
1073
            machine->vtbl->GetAccessible(machine, &isAccessible);
1074
            if (isAccessible) {
1075
                machine->vtbl->GetState(machine, &state);
1076 1077 1078 1079
                if (   (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) ) {
                    PRUnichar *machineNameUtf16 = NULL;
                    char      *machineNameUtf8  = NULL;
1080

1081
                    machine->vtbl->GetName(machine, &machineNameUtf16);
1082
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1083

1084
                    machine->vtbl->GetId(machine, &iid);
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
                    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);
1101 1102 1103 1104 1105
                }
            }
        }
    }

1106
    vboxArrayRelease(&machines);
1107 1108

    return ret;
1109 1110 1111
}

static virDomainPtr vboxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid) {
1112
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1113
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1114 1115
    vboxIID *iid         = NULL;
    char      *machineNameUtf8  = NULL;
1116 1117 1118
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;
1119
    nsresult rc;
1120

1121
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1122
    if (NS_FAILED(rc)) {
1123 1124
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1125 1126
        return NULL;
    }
1127

1128 1129
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1130
        PRBool isAccessible = PR_FALSE;
1131

1132 1133
        if (!machine)
            continue;
1134

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

1138 1139 1140 1141 1142
            machine->vtbl->GetId(machine, &iid);
            if (!iid)
                continue;
            vboxIIDToUUID(iidl, iid);
            vboxIIDUnalloc(iid);
1143

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

1146
                PRUint32 state;
1147

1148
                matched = 1;
1149

1150 1151
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1152

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

1155 1156 1157 1158 1159
                /* 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.
                 */
1160

1161 1162 1163 1164 1165
                ret = virGetDomain(conn, machineNameUtf8, iidl);
                if (   ret
                    && (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret->id = i + 1;
1166 1167
            }

1168 1169
            if (matched == 1)
                break;
1170 1171 1172
        }
    }

1173 1174 1175
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1176
    vboxArrayRelease(&machines);
1177 1178

    return ret;
1179 1180 1181
}

static virDomainPtr vboxDomainLookupByName(virConnectPtr conn, const char *name) {
1182
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1183
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1184 1185
    vboxIID *iid         = NULL;
    char      *machineNameUtf8  = NULL;
1186 1187 1188
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;
1189
    nsresult rc;
1190

1191
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1192
    if (NS_FAILED(rc)) {
1193 1194
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1195 1196
        return NULL;
    }
1197

1198 1199
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1200
        PRBool isAccessible = PR_FALSE;
1201

1202 1203
        if (!machine)
            continue;
1204

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

1208 1209
            machine->vtbl->GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1210

1211
            if (STREQ(name, machineNameUtf8)) {
1212

1213
                PRUint32 state;
1214

1215
                matched = 1;
1216

1217 1218 1219
                machine->vtbl->GetId(machine, &iid);
                vboxIIDToUUID(iidl, iid);
                vboxIIDUnalloc(iid);
1220

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

1223 1224 1225 1226 1227
                /* 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.
                 */
1228

1229 1230 1231 1232 1233
                ret = virGetDomain(conn, machineNameUtf8, iidl);
                if (   ret
                    && (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret->id = i + 1;
1234 1235
            }

1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
            if (machineNameUtf8) {
                VBOX_UTF8_FREE(machineNameUtf8);
                machineNameUtf8 = NULL;
            }
            if (machineNameUtf16) {
                VBOX_COM_UNALLOC_MEM(machineNameUtf16);
                machineNameUtf16 = NULL;
            }
            if (matched == 1)
                break;
1246 1247 1248
        }
    }

1249
    vboxArrayRelease(&machines);
1250 1251

    return ret;
1252 1253
}

1254 1255

static int vboxDomainIsActive(virDomainPtr dom) {
1256
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1257
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1258 1259 1260 1261 1262
    vboxIID *iid         = NULL;
    char      *machineNameUtf8  = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char iidl[VIR_UUID_BUFLEN];
    int i, matched = 0;
1263
    nsresult rc;
1264

1265
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1266
    if (NS_FAILED(rc)) {
1267 1268
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1269 1270
        return ret;
    }
1271

1272 1273
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1274 1275 1276 1277 1278 1279 1280
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

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

1282 1283
            machine->vtbl->GetId(machine, &iid);
            if (!iid)
1284
                continue;
1285 1286
            vboxIIDToUUID(iidl, iid);
            vboxIIDUnalloc(iid);
1287

1288
            if (memcmp(dom->uuid, iidl, VIR_UUID_BUFLEN) == 0) {
1289

1290
                PRUint32 state;
1291

1292
                matched = 1;
1293

1294 1295
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1296

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

1299 1300 1301 1302 1303
                if (   (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret = 1;
                else
                    ret = 0;
1304 1305
            }

1306 1307
            if (matched == 1)
                break;
1308 1309 1310
        }
    }

1311 1312 1313
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1314
    vboxArrayRelease(&machines);
1315

1316 1317 1318 1319 1320
    return ret;
}


static int vboxDomainIsPersistent(virDomainPtr dom ATTRIBUTE_UNUSED) {
1321
    /* All domains are persistent. */
1322 1323 1324 1325
    return 1;
}


1326 1327 1328 1329
static int vboxDomainIsUpdated(virDomainPtr dom ATTRIBUTE_UNUSED) {
    return 0;
}

1330
static int vboxDomainSuspend(virDomainPtr dom) {
1331
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1332
    IMachine *machine    = NULL;
1333
    vboxIID  *iid        = NULL;
1334
    IConsole *console    = NULL;
1335
    PRBool isAccessible  = PR_FALSE;
1336
    PRUint32 state;
1337
    nsresult rc;
1338

1339
#if VBOX_API_VERSION == 2002
1340
    if (VIR_ALLOC(iid) < 0) {
1341
        virReportOOMError();
1342 1343
        goto cleanup;
    }
1344
#endif
1345

1346 1347 1348
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
1349
        vboxError(VIR_ERR_INVALID_DOMAIN,
1350
                  _("no domain with matching id %d"), dom->id);
1351 1352
        goto cleanup;
    }
1353

1354 1355
    if (!machine)
        goto cleanup;
1356

1357 1358 1359
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1360

1361 1362 1363 1364 1365 1366 1367 1368
        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;
1369
            } else {
1370 1371
                vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                          _("error while suspending the domain"));
1372 1373
                goto cleanup;
            }
1374 1375
            data->vboxSession->vtbl->Close(data->vboxSession);
        } else {
1376 1377
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine not in running state to suspend it"));
1378
            goto cleanup;
1379 1380 1381 1382
        }
    }

cleanup:
1383
    VBOX_RELEASE(machine);
1384
    vboxIIDFree(iid);
1385 1386 1387 1388
    return ret;
}

static int vboxDomainResume(virDomainPtr dom) {
1389
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1390
    IMachine *machine    = NULL;
1391
    vboxIID  *iid        = NULL;
1392 1393
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1394
    nsresult rc;
1395

1396
#if VBOX_API_VERSION == 2002
1397
    if (VIR_ALLOC(iid) < 0) {
1398
        virReportOOMError();
1399 1400
        goto cleanup;
    }
1401
#endif
1402

1403
    PRBool isAccessible = PR_FALSE;
1404

1405 1406 1407
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
1408
        vboxError(VIR_ERR_INVALID_DOMAIN,
1409
                  _("no domain with matching id %d"), dom->id);
1410 1411
        goto cleanup;
    }
1412

1413 1414
    if (!machine)
        goto cleanup;
1415

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    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;
1428
            } else {
1429 1430
                vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                          _("error while resuming the domain"));
1431 1432
                goto cleanup;
            }
1433 1434
            data->vboxSession->vtbl->Close(data->vboxSession);
        } else {
1435 1436
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine not paused, so can't resume it"));
1437
            goto cleanup;
1438 1439 1440 1441
        }
    }

cleanup:
1442
    VBOX_RELEASE(machine);
1443
    vboxIIDFree(iid);
1444 1445 1446 1447
    return ret;
}

static int vboxDomainShutdown(virDomainPtr dom) {
1448
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1449
    IMachine *machine    = NULL;
1450
    vboxIID  *iid        = NULL;
1451 1452
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1453 1454
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1455

1456
#if VBOX_API_VERSION == 2002
1457
    if (VIR_ALLOC(iid) < 0) {
1458
        virReportOOMError();
1459 1460
        goto cleanup;
    }
1461
#endif
1462

1463 1464 1465
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
1466
        vboxError(VIR_ERR_INVALID_DOMAIN,
1467
                  _("no domain with matching id %d"), dom->id);
1468 1469
        goto cleanup;
    }
1470

1471 1472
    if (!machine)
        goto cleanup;
1473

1474 1475 1476
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1477

1478
        if (state == MachineState_Paused) {
1479 1480
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine paused, so can't power it down"));
1481 1482
            goto cleanup;
        } else if (state == MachineState_PoweredOff) {
1483 1484
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine already powered down"));
1485 1486
            goto cleanup;
        }
1487

1488 1489 1490 1491 1492 1493
        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;
1494
        }
1495
        data->vboxSession->vtbl->Close(data->vboxSession);
1496 1497 1498
    }

cleanup:
1499
    VBOX_RELEASE(machine);
1500
    vboxIIDFree(iid);
1501 1502 1503 1504
    return ret;
}

static int vboxDomainReboot(virDomainPtr dom, unsigned int flags ATTRIBUTE_UNUSED) {
1505
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1506
    IMachine *machine    = NULL;
1507
    vboxIID  *iid        = NULL;
1508 1509
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1510 1511
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1512

1513
#if VBOX_API_VERSION == 2002
1514
    if (VIR_ALLOC(iid) < 0) {
1515
        virReportOOMError();
1516 1517
        goto cleanup;
    }
1518
#endif
1519

1520 1521 1522
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
1523
        vboxError(VIR_ERR_INVALID_DOMAIN,
1524
                  _("no domain with matching id %d"), dom->id);
1525 1526
        goto cleanup;
    }
1527

1528 1529
    if (!machine)
        goto cleanup;
1530

1531 1532 1533
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1534

1535 1536 1537 1538 1539 1540 1541
        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;
1542
            }
1543 1544
            data->vboxSession->vtbl->Close(data->vboxSession);
        } else {
1545 1546
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine not running, so can't reboot it"));
1547
            goto cleanup;
1548 1549 1550 1551
        }
    }

cleanup:
1552
    VBOX_RELEASE(machine);
1553
    vboxIIDFree(iid);
1554 1555 1556 1557
    return ret;
}

static int vboxDomainDestroy(virDomainPtr dom) {
1558
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1559
    IMachine *machine    = NULL;
1560
    vboxIID  *iid        = NULL;
1561 1562
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1563 1564
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1565

1566
#if VBOX_API_VERSION == 2002
1567
    if (VIR_ALLOC(iid) < 0) {
1568
        virReportOOMError();
1569 1570
        goto cleanup;
    }
1571
#endif
1572

1573 1574 1575
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
1576
        vboxError(VIR_ERR_INVALID_DOMAIN,
1577
                  _("no domain with matching id %d"), dom->id);
1578 1579
        goto cleanup;
    }
1580

1581 1582
    if (!machine)
        goto cleanup;
1583

1584 1585 1586
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1587

1588
        if (state == MachineState_PoweredOff) {
1589 1590
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine already powered down"));
1591 1592
            goto cleanup;
        }
1593

1594 1595 1596
        data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid);
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
1597 1598

#if VBOX_API_VERSION == 2002
1599
            console->vtbl->PowerDown(console);
1600
#else
1601
            IProgress *progress = NULL;
1602 1603 1604 1605
            console->vtbl->PowerDown(console, &progress);
            if (progress) {
                progress->vtbl->WaitForCompletion(progress, -1);
                VBOX_RELEASE(progress);
1606
            }
1607 1608
#endif
            VBOX_RELEASE(console);
1609
            dom->id = -1;
1610
            ret = 0;
1611
        }
1612
        data->vboxSession->vtbl->Close(data->vboxSession);
1613 1614 1615
    }

cleanup:
1616
    VBOX_RELEASE(machine);
1617
    vboxIIDFree(iid);
1618 1619 1620
    return ret;
}

1621
static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
1622 1623 1624 1625 1626
    /* 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 ;)
     */
1627 1628 1629
    char *osType = strdup("hvm");

    if (osType == NULL)
1630
        virReportOOMError();
1631 1632

    return osType;
1633 1634 1635
}

static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory) {
1636
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1637
    IMachine *machine    = NULL;
1638
    vboxIID  *iid        = NULL;
1639
    PRUint32 state       = MachineState_Null;
1640 1641
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1642

1643
#if VBOX_API_VERSION == 2002
1644
    if (VIR_ALLOC(iid) < 0) {
1645
        virReportOOMError();
1646 1647
        goto cleanup;
    }
1648
#endif
1649

1650 1651 1652
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
1653
        vboxError(VIR_ERR_INVALID_DOMAIN,
1654
                  _("no domain with matching id %d"), dom->id);
1655 1656
        goto cleanup;
    }
1657

1658 1659
    if (!machine)
        goto cleanup;
1660

1661 1662 1663
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1664

1665
        if (state != MachineState_PoweredOff) {
1666 1667
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("memory size can't be changed unless domain is powered down"));
1668 1669
            goto cleanup;
        }
1670

1671 1672 1673 1674
        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) {
1675

1676 1677 1678 1679 1680
                rc = machine->vtbl->SetMemorySize(machine, memory / 1024);
                if (NS_SUCCEEDED(rc)) {
                    machine->vtbl->SaveSettings(machine);
                    ret = 0;
                } else {
1681 1682 1683
                    vboxError(VIR_ERR_INTERNAL_ERROR,
                              _("could not set the memory size of the "
                                "domain to: %lu Kb, rc=%08x"),
1684
                              memory, (unsigned)rc);
1685 1686
                }
            }
1687
            data->vboxSession->vtbl->Close(data->vboxSession);
1688 1689 1690 1691
        }
    }

cleanup:
1692
    VBOX_RELEASE(machine);
1693
    vboxIIDFree(iid);
1694 1695 1696 1697
    return ret;
}

static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info) {
1698
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1699
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1700 1701
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1702 1703
    nsresult rc;
    int i = 0;
1704

1705
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1706
    if (NS_FAILED(rc)) {
1707 1708
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1709 1710
        goto cleanup;
    }
1711

1712
    info->nrVirtCpu = 0;
1713 1714
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1715
        PRBool isAccessible = PR_FALSE;
1716

1717 1718
        if (!machine)
            continue;
1719

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

1723 1724 1725 1726 1727 1728
            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
1729
                * for time being set max_balloon and cur_balloon to same
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
                * 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;
                }
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;
1755 1756
                info->memory = memorySize * 1024;
                info->maxMem = maxMemorySize * 1024;
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
                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;
1780 1781
                }

1782
                ret = 0;
1783 1784
            }

1785 1786 1787 1788 1789 1790
            if (machineName)
                VBOX_UTF8_FREE(machineName);
            if (machineNameUtf16)
                VBOX_COM_UNALLOC_MEM(machineNameUtf16);
            if (info->nrVirtCpu)
                break;
1791 1792 1793 1794
        }

    }

1795
    vboxArrayRelease(&machines);
1796 1797 1798 1799 1800 1801

cleanup:
    return ret;
}

static int vboxDomainSave(virDomainPtr dom, const char *path ATTRIBUTE_UNUSED) {
1802
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1803
    IConsole *console    = NULL;
1804
    vboxIID  *iid        = NULL;
1805
    nsresult rc;
1806 1807 1808 1809 1810 1811 1812

    /* 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
     */
1813
#if VBOX_API_VERSION == 2002
1814
    if (VIR_ALLOC(iid) < 0) {
1815
        virReportOOMError();
1816 1817
        goto cleanup;
    }
1818
#endif
1819

1820 1821 1822 1823 1824 1825 1826
    /* 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;
1827

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

1830
            if (progress) {
1831
#if VBOX_API_VERSION == 2002
1832
                nsresult resultCode;
1833
#else
1834
                PRInt32 resultCode;
1835
#endif
1836

1837 1838 1839 1840
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_SUCCEEDED(resultCode)) {
                    ret = 0;
1841
                }
1842
                VBOX_RELEASE(progress);
1843
            }
1844
            VBOX_RELEASE(console);
1845
        }
1846
        data->vboxSession->vtbl->Close(data->vboxSession);
1847 1848
    }

1849 1850
    DEBUGIID("UUID of machine being saved:", iid);

1851
#if VBOX_API_VERSION == 2002
1852
cleanup:
1853 1854
#endif
    vboxIIDFree(iid);
1855 1856 1857
    return ret;
}

1858 1859 1860 1861
static int
vboxDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
{
1862
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1863 1864 1865
    IMachine *machine    = NULL;
    vboxIID  *iid        = NULL;
    PRUint32  CPUCount   = nvcpus;
1866
    nsresult rc;
1867

1868 1869 1870 1871 1872
    if (flags != VIR_DOMAIN_VCPU_LIVE) {
        vboxError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

1873 1874
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
1875
        virReportOOMError();
1876 1877 1878 1879
        goto cleanup;
    }
#endif

1880
    vboxIIDFromUUID(dom->uuid, iid);
1881

1882 1883 1884 1885 1886 1887 1888 1889
    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;
1890
            } else {
1891 1892 1893
                vboxError(VIR_ERR_INTERNAL_ERROR,
                          _("could not set the number of cpus of the domain "
                            "to: %u, rc=%08x"),
1894
                          CPUCount, (unsigned)rc);
1895
            }
1896
            VBOX_RELEASE(machine);
1897
        } else {
1898
            vboxError(VIR_ERR_INVALID_DOMAIN,
1899
                      _("no domain with matching id %d"), dom->id);
1900
        }
1901
    } else {
1902
        vboxError(VIR_ERR_INVALID_DOMAIN,
1903
                  _("can't open session to the domain with id %d"), dom->id);
1904
    }
1905
    data->vboxSession->vtbl->Close(data->vboxSession);
1906 1907 1908 1909 1910 1911 1912 1913

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

1914 1915 1916 1917 1918 1919 1920 1921 1922
static int
vboxDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
    return vboxDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
}

static int
vboxDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
1923 1924
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    ISystemProperties *systemProperties = NULL;
1925 1926
    PRUint32 maxCPUCount = 0;

1927 1928 1929 1930 1931
    if (flags != (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
        vboxError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

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

1937 1938 1939 1940
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
1941 1942 1943 1944 1945 1946 1947 1948
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}

1949 1950 1951 1952 1953 1954 1955
static int
vboxDomainGetMaxVcpus(virDomainPtr dom)
{
    return vboxDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
                                         VIR_DOMAIN_VCPU_MAXIMUM));
}

1956
static char *vboxDomainDumpXML(virDomainPtr dom, int flags) {
1957
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
1958 1959
    virDomainDefPtr def  = NULL;
    IMachine *machine    = NULL;
1960
    vboxIID  *iid        = NULL;
1961
    int gotAllABoutDef   = -1;
1962
    nsresult rc;
1963
    char *tmp;
1964

1965
#if VBOX_API_VERSION == 2002
1966
    if (VIR_ALLOC(iid) < 0) {
1967
        virReportOOMError();
1968 1969
        goto cleanup;
    }
1970
#endif
1971 1972

    if (VIR_ALLOC(def) < 0) {
1973
        virReportOOMError();
1974 1975 1976
        goto cleanup;
    }

1977 1978 1979 1980
    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_SUCCEEDED(rc) && machine) {
        PRBool accessible = PR_FALSE;
1981

1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
        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 */
2012
            vboxArray mediumAttachments         = VBOX_ARRAY_INITIALIZER;
2013 2014 2015 2016 2017
#endif /* VBOX_API_VERSION >= 3001 */
            IVRDPServer *VRDPServer             = NULL;
            IAudioAdapter *audioAdapter         = NULL;
            IUSBController *USBController       = NULL;
            ISystemProperties *systemProperties = NULL;
2018 2019


2020 2021 2022 2023
            def->virtType = VIR_DOMAIN_VIRT_VBOX;
            def->id = dom->id;
            memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
            def->name = strdup(dom->name);
2024

2025
            machine->vtbl->GetMemorySize(machine, &memorySize);
2026
            def->mem.cur_balloon = memorySize * 1024;
2027

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041
            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
             */
2042 2043
            /* def->mem.max_balloon = maxMemorySize * 1024; */
            def->mem.max_balloon = memorySize * 1024;
2044 2045

            machine->vtbl->GetCPUCount(machine, &CPUCount);
E
Eric Blake 已提交
2046
            def->maxvcpus = def->vcpus = CPUCount;
2047 2048 2049 2050

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

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

2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
            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 */
2077
                }
2078
            }
2079

2080 2081 2082
            def->features = 0;
#if VBOX_API_VERSION < 3001
            machine->vtbl->GetPAEEnabled(machine, &PAEEnabled);
2083
#elif VBOX_API_VERSION == 3001
2084
            machine->vtbl->GetCpuProperty(machine, CpuPropertyType_PAE, &PAEEnabled);
2085 2086 2087
#elif VBOX_API_VERSION >= 3002
            machine->vtbl->GetCPUProperty(machine, CPUPropertyType_PAE, &PAEEnabled);
#endif
2088 2089 2090
            if (PAEEnabled) {
                def->features = def->features | (1 << VIR_DOMAIN_FEATURE_PAE);
            }
2091

2092 2093 2094 2095 2096 2097
            machine->vtbl->GetBIOSSettings(machine, &bios);
            if (bios) {
                bios->vtbl->GetACPIEnabled(bios, &ACPIEnabled);
                if (ACPIEnabled) {
                    def->features = def->features | (1 << VIR_DOMAIN_FEATURE_ACPI);
                }
2098

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

2104 2105 2106 2107 2108
                VBOX_RELEASE(bios);
            }

            /* Currently VirtualBox always uses locatime
             * so locatime is always true here */
2109
            def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135

            /* 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;
2136
                        } else
2137
                            virReportOOMError();
2138
                    } else
2139
                        virReportOOMError();
2140
                } else
2141
                    virReportOOMError();
2142
            }
2143

2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154
            /* 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;
2155

2156
                def->ngraphics = 0;
2157

2158 2159 2160
                VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
                machine->vtbl->GetExtraData(machine, keyTypeUtf16, &valueTypeUtf16);
                VBOX_UTF16_FREE(keyTypeUtf16);
2161

2162 2163 2164
                if (valueTypeUtf16) {
                    VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
                    VBOX_UTF16_FREE(valueTypeUtf16);
2165

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

2171 2172 2173
                        VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
                        machine->vtbl->GetExtraData(machine, keyDislpayUtf16, &valueDisplayUtf16);
                        VBOX_UTF16_FREE(keyDislpayUtf16);
2174

2175 2176 2177
                        if (valueDisplayUtf16) {
                            VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                            VBOX_UTF16_FREE(valueDisplayUtf16);
2178

2179 2180 2181
                            if (strlen(valueDisplayUtf8) <= 0) {
                                VBOX_UTF8_FREE(valueDisplayUtf8);
                                valueDisplayUtf8 = NULL;
2182 2183
                            }
                        }
2184

2185 2186 2187 2188 2189
                        if (STREQ(valueTypeUtf8, "sdl")) {
                            sdlPresent = 1;
                            if (valueDisplayUtf8)
                                sdlDisplay = strdup(valueDisplayUtf8);
                            if (sdlDisplay == NULL) {
2190
                                virReportOOMError();
2191 2192 2193 2194 2195 2196
                                /* 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++;
2197
                        }
2198

2199 2200 2201 2202 2203
                        if (STREQ(valueTypeUtf8, "gui")) {
                            guiPresent = 1;
                            if (valueDisplayUtf8)
                                guiDisplay = strdup(valueDisplayUtf8);
                            if (guiDisplay == NULL) {
2204
                                virReportOOMError();
2205
                                /* just don't go to cleanup yet as it is ok to have
2206 2207
                                 * guiDisplay as NULL and we check it below if it
                                 * exist and then only use it there
2208
                                 */
2209
                            }
2210 2211
                            totalPresent++;
                        }
2212 2213
                        if (valueDisplayUtf8)
                            VBOX_UTF8_FREE(valueDisplayUtf8);
2214 2215
                    }

2216 2217
                    if (STREQ(valueTypeUtf8, "vrdp"))
                        vrdpPresent = 1;
2218

2219 2220
                    VBOX_UTF8_FREE(valueTypeUtf8);
                }
2221

2222 2223 2224 2225 2226 2227 2228
                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++;
                    }
2229

2230 2231 2232 2233 2234 2235 2236 2237 2238
                    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;
2239 2240 2241 2242 2243 2244 2245 2246 2247
                        tmp = getenv("DISPLAY");
                        if (tmp != NULL) {
                            def->graphics[def->ngraphics]->data.desktop.display = strdup(tmp);
                            if (def->graphics[def->ngraphics]->data.desktop.display == NULL) {
                                virReportOOMError();
                                /* just don't go to cleanup yet as it is ok to have
                                 * display as NULL
                                 */
                            }
2248 2249 2250 2251 2252
                        }
                        totalPresent++;
                        def->ngraphics++;
                    }
                }
2253

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282
                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;
                            }
2283

2284
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;
2285

2286 2287 2288 2289 2290 2291 2292 2293
                            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);
                            }
2294

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

2300 2301 2302 2303
                            VRDPServer->vtbl->GetReuseSingleConnection(VRDPServer, &reuseSingleConnection);
                            if (reuseSingleConnection) {
                                def->graphics[def->ngraphics]->data.rdp.replaceUser = 1;
                            }
2304

2305
                            def->ngraphics++;
2306
                        } else
2307
                            virReportOOMError();
2308
                    }
2309
                    VBOX_RELEASE(VRDPServer);
2310
                }
2311
            }
2312

2313 2314 2315
#if VBOX_API_VERSION < 3001
            /* dump IDE hdds if present */
            VBOX_UTF8_TO_UTF16(hddBus, &hddBusUtf16);
2316

2317 2318 2319 2320
            def->ndisks = 0;
            machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 0,  &hardDiskPM);
            if (hardDiskPM)
                def->ndisks++;
2321

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

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

2330 2331 2332 2333 2334 2335 2336 2337 2338
            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
2339
                        virReportOOMError();
2340
                }
2341
            }
2342

2343 2344 2345 2346
            if (hardDiskPM) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2347

2348 2349
                hardDiskPM->vtbl->imedium.GetLocation((IMedium *)hardDiskPM, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2350

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

2353 2354 2355 2356 2357
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hda");
                hddNum++;
2358

2359 2360 2361 2362
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPM);
            }
2363

2364 2365 2366 2367
            if (hardDiskPS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2368

2369 2370
                hardDiskPS->vtbl->imedium.GetLocation((IMedium *)hardDiskPS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2371

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

2374 2375 2376 2377 2378
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hdb");
                hddNum++;
2379

2380 2381 2382 2383
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPS);
            }
2384

2385 2386 2387 2388
            if (hardDiskSS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2389

2390 2391
                hardDiskSS->vtbl->imedium.GetLocation((IMedium *)hardDiskSS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2392

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

2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
                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;
2413
            vboxArrayGet(&mediumAttachments, machine, machine->vtbl->GetMediumAttachments);
2414 2415

            /* get the number of attachments */
2416 2417
            for (i = 0; i < mediumAttachments.count; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2418 2419 2420 2421 2422 2423 2424
                if (imediumattach) {
                    IMedium *medium = NULL;

                    imediumattach->vtbl->GetMedium(imediumattach, &medium);
                    if (medium) {
                        def->ndisks++;
                        VBOX_RELEASE(medium);
2425 2426
                    }
                }
2427
            }
2428

2429 2430 2431 2432
            /* 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) {
2433
                        virReportOOMError();
2434 2435
                        error = true;
                        break;
2436 2437
                    }
                }
2438
            } else {
2439
                virReportOOMError();
2440 2441 2442 2443 2444 2445 2446
                error = true;
            }

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

            /* get the attachment details here */
2447 2448
            for (i = 0; i < mediumAttachments.count && diskCount < def->ndisks && !error; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
                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;
                }
2482

2483 2484 2485 2486 2487 2488 2489 2490 2491
                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);
2492
                    virReportOOMError();
2493 2494 2495
                    error = true;
                    break;
                }
2496

2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
                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;
                }
2507

2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
                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);
2518
                def->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
2519 2520 2521 2522 2523 2524
                                                                    deviceInst,
                                                                    devicePort,
                                                                    deviceSlot,
                                                                    maxPortPerInst,
                                                                    maxSlotPerPort);
                if (!def->disks[diskCount]->dst) {
2525
                    vboxError(VIR_ERR_INTERNAL_ERROR,
2526 2527
                              _("Could not generate medium name for the disk "
                                "at: controller instance:%u, port:%d, slot:%d"),
2528 2529 2530 2531 2532 2533
                              deviceInst, devicePort, deviceSlot);
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2534

2535 2536 2537
                medium->vtbl->GetReadOnly(medium, &readOnly);
                if (readOnly == PR_TRUE)
                    def->disks[diskCount]->readonly = 1;
2538

2539
                def->disks[diskCount]->type = VIR_DOMAIN_DISK_TYPE_FILE;
2540

2541 2542 2543 2544
                VBOX_RELEASE(medium);
                VBOX_RELEASE(storageController);
                diskCount++;
            }
2545

2546
            vboxArrayRelease(&mediumAttachments);
2547

2548 2549 2550 2551 2552 2553 2554 2555
            /* cleanup on error */
            if (error) {
                for (i = 0; i < def->ndisks; i++) {
                    VIR_FREE(def->disks[i]);
                }
                VIR_FREE(def->disks);
                def->ndisks = 0;
            }
2556

2557
#endif /* VBOX_API_VERSION >= 3001 */
2558

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

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

2569 2570 2571 2572
                    adapter->vtbl->GetEnabled(adapter, &enabled);
                    if (enabled) {
                        def->nnets++;
                    }
2573

2574 2575 2576
                    VBOX_RELEASE(adapter);
                }
            }
2577

2578 2579 2580 2581 2582
            /* 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
2583
                        virReportOOMError();
2584 2585
                }
            }
2586

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

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

2595 2596 2597 2598 2599 2600 2601
                    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};
2602

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

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

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

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

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

2616 2617
                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
                            def->nets[netAdpIncCnt]->data.bridge.brname = strdup(hostInt);
2618

2619 2620
                            VBOX_UTF8_FREE(hostInt);
                            VBOX_UTF16_FREE(hostIntUtf16);
2621

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

2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
                            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 */
2672 2673
                        }

2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
                        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);
2690
                    }
2691 2692

                    VBOX_RELEASE(adapter);
2693
                }
2694
            }
2695

2696
            /* dump sound card if active */
2697

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

2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
            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;
2722
                            virReportOOMError();
2723 2724 2725
                        }
                    } else {
                        def->nsounds = 0;
2726
                        virReportOOMError();
2727 2728 2729 2730
                    }
                }
                VBOX_RELEASE(audioAdapter);
            }
2731

2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
#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");
2759
                            } else {
2760
                                def->ndisks--;
2761
                                virReportOOMError();
2762 2763
                            }
                        } else {
2764
                            def->ndisks--;
2765
                            virReportOOMError();
2766
                        }
2767 2768 2769 2770

                        VBOX_UTF8_FREE(location);
                        VBOX_UTF16_FREE(locationUtf16);
                        VBOX_MEDIUM_RELEASE(dvdImage);
2771 2772
                    }
                }
2773 2774
                VBOX_RELEASE(dvdDrive);
            }
2775

2776 2777 2778 2779 2780 2781 2782
            /* 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) {
2783 2784
                    PRUint32 state = DriveState_Null;

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

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

2794 2795
                            floppyImage->vtbl->imedium.GetLocation((IMedium *)floppyImage, &locationUtf16);
                            VBOX_UTF16_TO_UTF8(locationUtf16, &location);
2796 2797 2798 2799

                            def->ndisks++;
                            if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
                                if (VIR_ALLOC(def->disks[def->ndisks - 1]) >= 0) {
2800 2801
                                    def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                                    def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC;
2802
                                    def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE;
2803
                                    def->disks[def->ndisks - 1]->readonly = 0;
2804
                                    def->disks[def->ndisks - 1]->src = strdup(location);
2805
                                    def->disks[def->ndisks - 1]->dst = strdup("fda");
2806 2807
                                } else {
                                    def->ndisks--;
2808
                                    virReportOOMError();
2809 2810 2811
                                }
                            } else {
                                def->ndisks--;
2812
                                virReportOOMError();
2813 2814
                            }

2815 2816 2817
                            VBOX_UTF8_FREE(location);
                            VBOX_UTF16_FREE(locationUtf16);
                            VBOX_MEDIUM_RELEASE(floppyImage);
2818 2819 2820 2821
                        }
                    }
                }

2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
                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) {
2835 2836
                    PRBool enabled = PR_FALSE;

2837
                    serialPort->vtbl->GetEnabled(serialPort, &enabled);
2838
                    if (enabled) {
2839
                        def->nserials++;
2840 2841
                    }

2842
                    VBOX_RELEASE(serialPort);
2843
                }
2844
            }
2845

2846 2847 2848 2849 2850
            /* 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
2851
                        virReportOOMError();
2852 2853
                }
            }
2854

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

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

2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
                    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;
                        }
2883

2884
                        def->serials[serialPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
2885

2886 2887 2888 2889 2890 2891 2892
                        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;
                        }
2893

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

2896 2897
                        if (pathUtf16) {
                            VBOX_UTF16_TO_UTF8(pathUtf16, &path);
2898 2899 2900
                            def->serials[serialPortIncCount]->data.file.path = strdup(path);
                        }

2901 2902 2903 2904
                        serialPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
2905 2906
                    }

2907 2908 2909
                    VBOX_RELEASE(serialPort);
                }
            }
2910

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

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

2921 2922 2923
                    parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                    if (enabled) {
                        def->nparallels++;
2924
                    }
2925 2926

                    VBOX_RELEASE(parallelPort);
2927
                }
2928
            }
2929

2930 2931 2932 2933 2934
            /* 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
2935
                        virReportOOMError();
2936
                }
2937
            }
2938

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

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

2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
                    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;
                        }
2961

2962
                        def->parallels[parallelPortIncCount]->type = VIR_DOMAIN_CHR_TYPE_FILE;
2963
                        def->parallels[parallelPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL;
2964

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

2967 2968
                        VBOX_UTF16_TO_UTF8(pathUtf16, &path);
                        def->parallels[parallelPortIncCount]->data.file.path = strdup(path);
2969

2970 2971 2972 2973
                        parallelPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
2974
                    }
2975 2976

                    VBOX_RELEASE(parallelPort);
2977
                }
2978
            }
2979

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

2986 2987
                USBController->vtbl->GetEnabled(USBController, &enabled);
                if (enabled) {
2988
                    vboxArray deviceFilters = VBOX_ARRAY_INITIALIZER;
2989

2990 2991
                    vboxArrayGet(&deviceFilters, USBController,
                                 USBController->vtbl->GetDeviceFilters);
2992

2993
                    if (deviceFilters.count > 0) {
2994

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

2999
                        for(i = 0; i < deviceFilters.count; i++) {
3000
                            PRBool active = PR_FALSE;
3001
                            IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];
3002

3003
                            deviceFilter->vtbl->GetActive(deviceFilter, &active);
3004 3005
                            if (active) {
                                def->nhostdevs++;
3006
                            }
3007
                        }
3008

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

3013
                                for(i = 0; (USBFilterCount < def->nhostdevs) || (i < deviceFilters.count); i++) {
3014
                                    PRBool active = PR_FALSE;
3015
                                    IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];
3016

3017
                                    deviceFilter->vtbl->GetActive(deviceFilter, &active);
3018 3019 3020 3021 3022 3023 3024 3025 3026
                                    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;
3027

3028 3029 3030 3031
                                            def->hostdevs[USBFilterCount]->mode =
                                                VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
                                            def->hostdevs[USBFilterCount]->source.subsys.type =
                                                VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB;
3032

3033 3034
                                            deviceFilter->vtbl->GetVendorId(deviceFilter, &vendorIdUtf16);
                                            deviceFilter->vtbl->GetProductId(deviceFilter, &productIdUtf16);
3035

3036 3037
                                            VBOX_UTF16_TO_UTF8(vendorIdUtf16, &vendorIdUtf8);
                                            VBOX_UTF16_TO_UTF8(productIdUtf16, &productIdUtf8);
3038

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

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

3045 3046
                                            VBOX_UTF16_FREE(vendorIdUtf16);
                                            VBOX_UTF8_FREE(vendorIdUtf8);
3047

3048 3049
                                            VBOX_UTF16_FREE(productIdUtf16);
                                            VBOX_UTF8_FREE(productIdUtf8);
3050

3051 3052
                                            USBFilterCount++;
                                        } else
3053
                                            virReportOOMError();
3054
                                    }
3055 3056
                                }
                            } else
3057
                                virReportOOMError();
3058 3059 3060
                        }
                    }

3061
                    /* Cleanup */
3062
                    vboxArrayRelease(&deviceFilters);
3063 3064
                }
                VBOX_RELEASE(USBController);
3065
            }
3066 3067 3068 3069 3070

            /* all done so set gotAllABoutDef and pass def to virDomainDefFormat
             * to generate XML for it
             */
            gotAllABoutDef = 0;
3071
        }
3072 3073
        VBOX_RELEASE(machine);
        machine = NULL;
3074 3075 3076
    }

    if (gotAllABoutDef == 0)
3077
        ret = virDomainDefFormat(def, flags);
3078 3079

cleanup:
3080
    vboxIIDFree(iid);
3081 3082 3083 3084 3085
    virDomainDefFree(def);
    return ret;
}

static int vboxListDefinedDomains(virConnectPtr conn, char ** const names, int maxnames) {
3086
    VBOX_OBJECT_CHECK(conn, int, -1);
3087
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3088 3089 3090
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
3091
    nsresult rc;
3092 3093
    int i, j;

3094
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3095
    if (NS_FAILED(rc)) {
3096 3097 3098
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of Defined Domains, rc=%08x"),
                  (unsigned)rc);
3099 3100
        goto cleanup;
    }
3101

3102 3103 3104
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < maxnames); i++) {
        IMachine *machine = machines.items[i];
3105 3106 3107 3108 3109 3110 3111 3112 3113 3114

        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);
3115 3116 3117 3118
                    names[j] = strdup(machineName);
                    VBOX_UTF16_FREE(machineNameUtf16);
                    VBOX_UTF8_FREE(machineName);
                    if (!names[j]) {
3119
                        virReportOOMError();
3120 3121 3122 3123
                        for ( ; j >= 0 ; j--)
                            VIR_FREE(names[j]);
                        ret = -1;
                        goto cleanup;
3124
                    }
3125
                    j++;
3126
                    ret++;
3127 3128 3129 3130 3131 3132
                }
            }
        }
    }

cleanup:
3133
    vboxArrayRelease(&machines);
3134 3135 3136 3137
    return ret;
}

static int vboxNumOfDefinedDomains(virConnectPtr conn) {
3138
    VBOX_OBJECT_CHECK(conn, int, -1);
3139
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3140
    PRUint32 state       = MachineState_Null;
3141
    nsresult rc;
3142 3143
    int i;

3144
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3145
    if (NS_FAILED(rc)) {
3146 3147 3148
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get number of Defined Domains, rc=%08x"),
                  (unsigned)rc);
3149 3150
        goto cleanup;
    }
3151

3152 3153 3154
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3155 3156 3157 3158 3159 3160 3161 3162 3163

        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++;
3164 3165 3166 3167 3168 3169
                }
            }
        }
    }

cleanup:
3170
    vboxArrayRelease(&machines);
3171 3172 3173
    return ret;
}

E
Eric Blake 已提交
3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269

static int
vboxStartMachine(virDomainPtr dom, int i, IMachine *machine, vboxIID *iid)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    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;
    IProgress *progress          = NULL;
    PRUnichar *env               = NULL;
    PRUnichar *sessionType       = NULL;
    nsresult rc;

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

    if (valueTypeUtf16) {
        VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
        VBOX_UTF16_FREE(valueTypeUtf16);

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

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

            if (valueDisplayUtf16) {
                VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                VBOX_UTF16_FREE(valueDisplayUtf16);

                if (strlen(valueDisplayUtf8) <= 0) {
                    VBOX_UTF8_FREE(valueDisplayUtf8);
                    valueDisplayUtf8 = NULL;
                }
            }

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

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

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

        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
             */
            guiPresent = 1;
        }

        VBOX_UTF8_FREE(valueTypeUtf8);

    } else {
        guiPresent = 1;
    }
    if (valueDisplayUtf8)
        VBOX_UTF8_FREE(valueDisplayUtf8);

    if (guiPresent) {
        if (guiDisplay) {
E
Eric Blake 已提交
3270 3271 3272 3273 3274 3275 3276
            char *displayutf8;
            if (virAsprintf(&displayutf8, "DISPLAY=%s", guiDisplay) < 0)
                virReportOOMError();
            else {
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3277 3278 3279 3280 3281 3282 3283 3284
            VIR_FREE(guiDisplay);
        }

        VBOX_UTF8_TO_UTF16("gui", &sessionType);
    }

    if (sdlPresent) {
        if (sdlDisplay) {
E
Eric Blake 已提交
3285 3286 3287 3288 3289 3290 3291
            char *displayutf8;
            if (virAsprintf(&displayutf8, "DISPLAY=%s", sdlDisplay) < 0)
                virReportOOMError();
            else {
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
            VIR_FREE(sdlDisplay);
        }

        VBOX_UTF8_TO_UTF16("sdl", &sessionType);
    }

    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(VIR_ERR_OPERATION_FAILED, "%s",
                  _("openremotesession failed, domain can't be started"));
        ret = -1;
    } else {
        PRBool completed = 0;
#if VBOX_API_VERSION == 2002
        nsresult resultCode;
#else
        PRInt32  resultCode;
#endif
        progress->vtbl->WaitForCompletion(progress, -1);
        rc = progress->vtbl->GetCompleted(progress, &completed);
        if (NS_FAILED(rc)) {
            /* error */
            ret = -1;
        }
        progress->vtbl->GetResultCode(progress, &resultCode);
        if (NS_FAILED(resultCode)) {
            /* error */
            ret = -1;
        } else {
            /* all ok set the domid */
            dom->id = i + 1;
            ret = 0;
        }
    }

    VBOX_RELEASE(progress);

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

    VBOX_UTF16_FREE(env);
    VBOX_UTF16_FREE(sessionType);

    return ret;
}

3346
static int vboxDomainCreateWithFlags(virDomainPtr dom, unsigned int flags) {
3347
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
3348
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3349
    unsigned char iidl[VIR_UUID_BUFLEN] = {0};
3350 3351
    nsresult rc;
    int i = 0;
3352

3353 3354
    virCheckFlags(0, -1);

3355
    if (!dom->name) {
3356
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
3357
                  _("Error while reading the domain name"));
3358 3359 3360
        goto cleanup;
    }

3361
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3362
    if (NS_FAILED(rc)) {
3363 3364
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
3365 3366
        goto cleanup;
    }
3367

3368 3369
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3370
        PRBool isAccessible = PR_FALSE;
3371

3372 3373
        if (!machine)
            continue;
3374

3375 3376 3377
        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
            vboxIID *iid = NULL;
3378

3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390
            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) ) {
E
Eric Blake 已提交
3391
                    ret = vboxStartMachine(dom, i, machine, iid);
3392
                } else {
3393 3394 3395
                    vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                              _("machine is not in poweroff|saved|"
                                "aborted state, so couldn't start it"));
3396
                    ret = -1;
3397 3398
                }
            }
3399 3400 3401
            vboxIIDUnalloc(iid);
            if (ret != -1)
                break;
3402 3403 3404
        }
    }

3405
    /* Do the cleanup and take care you dont leak any memory */
3406
    vboxArrayRelease(&machines);
3407

3408 3409 3410 3411
cleanup:
    return ret;
}

3412 3413 3414 3415
static int vboxDomainCreate(virDomainPtr dom) {
    return vboxDomainCreateWithFlags(dom, 0);
}

E
Eric Blake 已提交
3416 3417 3418 3419 3420 3421 3422
static void
vboxSetBootDeviceOrder(virDomainDefPtr def, vboxGlobalData *data,
                       IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 maxBootPosition            = 0;
    int i = 0;
3423

E
Eric Blake 已提交
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439
    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);
3440

E
Eric Blake 已提交
3441 3442 3443 3444 3445 3446
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxBootPosition(systemProperties,
                                                   &maxBootPosition);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
3447
    }
3448

E
Eric Blake 已提交
3449 3450 3451
    /* Clear the defaults first */
    for (i = 0; i < maxBootPosition; i++) {
        machine->vtbl->SetBootOrder(machine, i+1, DeviceType_Null);
3452
    }
3453

E
Eric Blake 已提交
3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
    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;
3465
        }
E
Eric Blake 已提交
3466
        machine->vtbl->SetBootOrder(machine, i+1, device);
3467
    }
E
Eric Blake 已提交
3468
}
3469

E
Eric Blake 已提交
3470 3471 3472 3473 3474
static void
vboxAttachDrives(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    int i;
    nsresult rc;
3475 3476

#if VBOX_API_VERSION < 3001
E
Eric Blake 已提交
3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
    if (def->ndisks == 0)
        return;

    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 &&
                def->disks[i]->src != NULL) {
                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
                 */
3504

E
Eric Blake 已提交
3505 3506 3507 3508 3509
                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                if (dvdDrive) {
                    IDVDImage *dvdImage          = NULL;
                    PRUnichar *dvdfileUtf16      = NULL;
                    vboxIID *dvduuid             = NULL;
3510
# if VBOX_API_VERSION == 2002
E
Eric Blake 已提交
3511
                    nsID dvdemptyuuid;
3512

E
Eric Blake 已提交
3513
                    memset(&dvdemptyuuid, 0, sizeof(dvdemptyuuid));
3514
# else
E
Eric Blake 已提交
3515
                    PRUnichar *dvdemptyuuidUtf16 = NULL;
3516
# endif
3517

E
Eric Blake 已提交
3518
                    VBOX_UTF8_TO_UTF16(def->disks[i]->src, &dvdfileUtf16);
3519

E
Eric Blake 已提交
3520 3521 3522
                    data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                      dvdfileUtf16, &dvdImage);
                    if (!dvdImage) {
3523
# if VBOX_API_VERSION == 2002
E
Eric Blake 已提交
3524 3525 3526 3527
                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                          dvdfileUtf16,
                                                          &dvdemptyuuid,
                                                          &dvdImage);
3528
# else
E
Eric Blake 已提交
3529 3530 3531 3532
                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                          dvdfileUtf16,
                                                          dvdemptyuuidUtf16,
                                                          &dvdImage);
3533
# endif
E
Eric Blake 已提交
3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550
                    }
                    if (dvdImage) {
                        rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage,
                                                           &dvduuid);
                        if (NS_FAILED(rc)) {
                            vboxError(VIR_ERR_INTERNAL_ERROR,
                                      _("can't get the uuid of the file to "
                                        "be attached to cdrom: %s, rc=%08x"),
                                      def->disks[i]->src, (unsigned)rc);
                        } else {
                            rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid);
                            if (NS_FAILED(rc)) {
                                vboxError(VIR_ERR_INTERNAL_ERROR,
                                          _("could not attach the file to cdrom: %s, rc=%08x"),
                                          def->disks[i]->src, (unsigned)rc);
                            } else {
                                DEBUGIID("CD/DVDImage UUID:", dvduuid);
3551
                            }
3552
                        }
E
Eric Blake 已提交
3553 3554

                        VBOX_MEDIUM_RELEASE(dvdImage);
3555
                    }
E
Eric Blake 已提交
3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573
                    vboxIIDUnalloc(dvduuid);
                    VBOX_UTF16_FREE(dvdfileUtf16);
                    VBOX_RELEASE(dvdDrive);
                }
            } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
            }
        } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
            if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_FILE &&
                def->disks[i]->src != NULL) {
                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
                 */
3574

E
Eric Blake 已提交
3575 3576
                VBOX_UTF8_TO_UTF16(def->disks[i]->src, &hddfileUtf16);
                VBOX_UTF8_TO_UTF16("", &hddEmpty);
3577

E
Eric Blake 已提交
3578 3579
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddfileUtf16,
                                                  &hardDisk);
3580

E
Eric Blake 已提交
3581
                if (!hardDisk) {
3582
# if VBOX_API_VERSION == 2002
E
Eric Blake 已提交
3583 3584 3585 3586
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      &hardDisk);
3587
# else
E
Eric Blake 已提交
3588 3589 3590 3591 3592 3593 3594 3595
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      0,
                                                      hddEmpty,
                                                      0,
                                                      hddEmpty,
                                                      &hardDisk);
3596
# endif
E
Eric Blake 已提交
3597
                }
3598

E
Eric Blake 已提交
3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
                if (hardDisk) {
                    rc = hardDisk->vtbl->imedium.GetId((IMedium *)hardDisk,
                                                       &hdduuid);
                    if (NS_FAILED(rc)) {
                        vboxError(VIR_ERR_INTERNAL_ERROR,
                                  _("can't get the uuid of the file to be "
                                    "attached as harddisk: %s, rc=%08x"),
                                  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");
3621
                            } else {
E
Eric Blake 已提交
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638
                                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;
3639
                                }
E
Eric Blake 已提交
3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654

                                rc = machine->vtbl->AttachHardDisk(machine,
                                                                   hdduuid,
                                                                   hddcnameUtf16,
                                                                   channel,
                                                                   device);
                                VBOX_UTF16_FREE(hddcnameUtf16);

                                if (NS_FAILED(rc)) {
                                    vboxError(VIR_ERR_INTERNAL_ERROR,
                                              _("could not attach the file as "
                                                "harddisk: %s, rc=%08x"),
                                              def->disks[i]->src, (unsigned)rc);
                                } else {
                                    DEBUGIID("Attached HDD with UUID", hdduuid);
3655 3656 3657
                                }
                            }
                        }
3658
                    }
E
Eric Blake 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676
                    VBOX_MEDIUM_RELEASE(hardDisk);
                }
                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 &&
                def->disks[i]->src != NULL) {
                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;
3677
# if VBOX_API_VERSION == 2002
E
Eric Blake 已提交
3678
                        nsID fdemptyuuid;
3679

E
Eric Blake 已提交
3680
                        memset(&fdemptyuuid, 0, sizeof(fdemptyuuid));
3681
# else
E
Eric Blake 已提交
3682
                        PRUnichar *fdemptyuuidUtf16 = NULL;
3683
# endif
3684

E
Eric Blake 已提交
3685 3686 3687 3688
                        VBOX_UTF8_TO_UTF16(def->disks[i]->src, &fdfileUtf16);
                        rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                  fdfileUtf16,
                                                                  &floppyImage);
3689

E
Eric Blake 已提交
3690 3691 3692
                        if (!floppyImage) {
                            data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                 fdfileUtf16,
3693
# if VBOX_API_VERSION == 2002
E
Eric Blake 已提交
3694
                                                                 &fdemptyuuid,
3695
# else
E
Eric Blake 已提交
3696
                                                                 fdemptyuuidUtf16,
3697
# endif
E
Eric Blake 已提交
3698 3699
                                                                 &floppyImage);
                        }
3700

E
Eric Blake 已提交
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718
                        if (floppyImage) {
                            rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage,
                                                                  &fduuid);
                            if (NS_FAILED(rc)) {
                                vboxError(VIR_ERR_INTERNAL_ERROR,
                                          _("can't get the uuid of the file to "
                                            "be attached to floppy drive: %s, rc=%08x"),
                                          def->disks[i]->src, (unsigned)rc);
                            } else {
                                rc = floppyDrive->vtbl->MountImage(floppyDrive,
                                                                   fduuid);
                                if (NS_FAILED(rc)) {
                                    vboxError(VIR_ERR_INTERNAL_ERROR,
                                              _("could not attach the file to "
                                                "floppy drive: %s, rc=%08x"),
                                              def->disks[i]->src, (unsigned)rc);
                                } else {
                                    DEBUGIID("floppyImage UUID", fduuid);
3719 3720
                                }
                            }
E
Eric Blake 已提交
3721
                            VBOX_MEDIUM_RELEASE(floppyImage);
3722
                        }
E
Eric Blake 已提交
3723 3724
                        vboxIIDUnalloc(fduuid);
                        VBOX_UTF16_FREE(fdfileUtf16);
3725
                    }
E
Eric Blake 已提交
3726
                    VBOX_RELEASE(floppyDrive);
3727
                }
E
Eric Blake 已提交
3728
            } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
3729
            }
3730
        }
E
Eric Blake 已提交
3731
    }
3732
#else  /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
    PRUint32 maxPortPerInst[StorageBus_Floppy + 1] = {};
    PRUint32 maxSlotPerPort[StorageBus_Floppy + 1] = {};
    PRUnichar *storageCtlName = NULL;
    bool error = false;

    /* 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 */
3745
    {
E
Eric Blake 已提交
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780
        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);
    }
3781

E
Eric Blake 已提交
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
    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 &&
            def->disks[i]->src != NULL) {
            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;
            }
3825

E
Eric Blake 已提交
3826 3827
            if (!medium) {
                PRUnichar *mediumEmpty = NULL;
3828

E
Eric Blake 已提交
3829
                VBOX_UTF8_TO_UTF16("", &mediumEmpty);
3830 3831

                if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
3832 3833 3834 3835 3836 3837 3838 3839
                    rc = data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                           mediumFileUtf16,
                                                           AccessMode_ReadWrite,
                                                           false,
                                                           mediumEmpty,
                                                           false,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
3840 3841
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_CDROM) {
3842 3843 3844 3845
                    rc = data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                           mediumFileUtf16,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
3846 3847
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
3848 3849 3850 3851 3852 3853
                    rc = data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                              mediumFileUtf16,
                                                              mediumEmpty,
                                                              &medium);
                } else {
                    rc = 0;
3854 3855
                }

E
Eric Blake 已提交
3856 3857
                VBOX_UTF16_FREE(mediumEmpty);
            }
3858

E
Eric Blake 已提交
3859 3860 3861 3862 3863 3864 3865 3866
            if (!medium) {
                vboxError(VIR_ERR_INTERNAL_ERROR,
                          _("Failed to attach the following disk/dvd/floppy "
                            "to the machine: %s, rc=%08x"),
                          def->disks[i]->src, (unsigned)rc);
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
3867

E
Eric Blake 已提交
3868 3869 3870 3871 3872 3873 3874 3875 3876 3877
            rc = medium->vtbl->GetId(medium, &mediumUUID);
            if (NS_FAILED(rc)) {
                vboxError(VIR_ERR_INTERNAL_ERROR,
                          _("can't get the uuid of the file to be attached "
                            "as harddisk/dvd/floppy: %s, rc=%08x"),
                          def->disks[i]->src, (unsigned)rc);
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
3878

E
Eric Blake 已提交
3879 3880 3881 3882 3883 3884 3885
            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");
3886
                }
E
Eric Blake 已提交
3887
            }
3888

E
Eric Blake 已提交
3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
            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;
            }
3902

E
Eric Blake 已提交
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914
            /* get the device details i.e instance, port and slot */
            if (!vboxGetDeviceDetails(def->disks[i]->dst,
                                      maxPortPerInst,
                                      maxSlotPerPort,
                                      storageBus,
                                      &deviceInst,
                                      &devicePort,
                                      &deviceSlot)) {
                vboxError(VIR_ERR_INTERNAL_ERROR,
                          _("can't get the port/slot number of harddisk/"
                            "dvd/floppy to be attached: %s, rc=%08x"),
                          def->disks[i]->src, (unsigned)rc);
3915 3916 3917
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumUUID);
                VBOX_UTF16_FREE(mediumFileUtf16);
E
Eric Blake 已提交
3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935
                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(VIR_ERR_INTERNAL_ERROR,
                          _("could not attach the file as harddisk/"
                            "dvd/floppy: %s, rc=%08x"),
                          def->disks[i]->src, (unsigned)rc);
            } else {
                DEBUGIID("Attached HDD/DVD/Floppy with UUID", mediumUUID);
3936
            }
E
Eric Blake 已提交
3937 3938 3939 3940 3941

            VBOX_RELEASE(medium);
            VBOX_UTF16_FREE(mediumUUID);
            VBOX_UTF16_FREE(mediumFileUtf16);
            VBOX_UTF16_FREE(storageCtlName);
3942 3943 3944
        }
    }
#endif /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
3945
}
3946

E
Eric Blake 已提交
3947 3948 3949 3950
static void
vboxAttachSound(virDomainDefPtr def, IMachine *machine)
{
    nsresult rc;
3951

E
Eric Blake 已提交
3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967
    /* Check if def->nsounds is one as VirtualBox currently supports
     * only one sound card
     */
    if (def->nsounds == 1) {
        IAudioAdapter *audioAdapter = NULL;

        machine->vtbl->GetAudioAdapter(machine, &audioAdapter);
        if (audioAdapter) {
            rc = audioAdapter->vtbl->SetEnabled(audioAdapter, 1);
            if (NS_SUCCEEDED(rc)) {
                if (def->sounds[0]->model == VIR_DOMAIN_SOUND_MODEL_SB16) {
                    audioAdapter->vtbl->SetAudioController(audioAdapter,
                                                           AudioControllerType_SB16);
                } else if (def->sounds[0]->model == VIR_DOMAIN_SOUND_MODEL_AC97) {
                    audioAdapter->vtbl->SetAudioController(audioAdapter,
                                                           AudioControllerType_AC97);
3968
                }
3969
            }
E
Eric Blake 已提交
3970
            VBOX_RELEASE(audioAdapter);
3971
        }
E
Eric Blake 已提交
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 4017 4018 4019 4020 4021 4022 4023
    }
}

static void
vboxAttachNetwork(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    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);
4024 4025
        }

E
Eric Blake 已提交
4026 4027 4028 4029 4030
        machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
        if (adapter) {
            PRUnichar *MACAddress = NULL;

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

E
Eric Blake 已提交
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042
            if (def->nets[i]->model) {
                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;
4043
#if VBOX_API_VERSION >= 3001
E
Eric Blake 已提交
4044 4045
                } else if (STRCASEEQ(def->nets[i]->model , "virtio")) {
                    adapterType = NetworkAdapterType_Virtio;
4046 4047
#endif /* VBOX_API_VERSION >= 3001 */
                }
E
Eric Blake 已提交
4048 4049 4050
            } else {
                adapterType = NetworkAdapterType_Am79C973;
            }
4051

E
Eric Blake 已提交
4052
            adapter->vtbl->SetAdapterType(adapter, adapterType);
4053

E
Eric Blake 已提交
4054 4055 4056
            if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
                PRUnichar *hostInterface = NULL;
                /* Bridged Network */
4057

E
Eric Blake 已提交
4058
                adapter->vtbl->AttachToBridgedInterface(adapter);
4059

E
Eric Blake 已提交
4060 4061 4062 4063 4064 4065 4066 4067 4068
                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 */
4069

E
Eric Blake 已提交
4070
                adapter->vtbl->AttachToInternalNetwork(adapter);
4071

E
Eric Blake 已提交
4072 4073 4074 4075 4076
                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);
4077
                }
E
Eric Blake 已提交
4078 4079 4080 4081 4082 4083 4084
            } 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);
4085

E
Eric Blake 已提交
4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099
                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);
                }
            } 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);
4100
            }
E
Eric Blake 已提交
4101 4102 4103 4104

            VBOX_UTF8_TO_UTF16(macaddrvbox, &MACAddress);
            adapter->vtbl->SetMACAddress(adapter, MACAddress);
            VBOX_UTF16_FREE(MACAddress);
4105
        }
E
Eric Blake 已提交
4106 4107 4108 4109 4110 4111 4112 4113 4114
    }
}

static void
vboxAttachSerial(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 serialPortCount            = 0;
    int i = 0;
4115

E
Eric Blake 已提交
4116 4117 4118 4119 4120 4121 4122
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetSerialPortCount(systemProperties,
                                                   &serialPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4123

E
Eric Blake 已提交
4124 4125 4126 4127
    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;
4128

E
Eric Blake 已提交
4129 4130 4131
        DEBUG("SerialPort(%d): Type: %d", i, def->serials[i]->type);
        DEBUG("SerialPort(%d): target.port: %d", i,
              def->serials[i]->target.port);
4132

E
Eric Blake 已提交
4133 4134 4135
        machine->vtbl->GetSerialPort(machine, i, &serialPort);
        if (serialPort) {
            PRUnichar *pathUtf16 = NULL;
4136

E
Eric Blake 已提交
4137
            serialPort->vtbl->SetEnabled(serialPort, 1);
4138

E
Eric Blake 已提交
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163
            if (def->serials[i]->data.file.path) {
                VBOX_UTF8_TO_UTF16(def->serials[i]->data.file.path, &pathUtf16);
                serialPort->vtbl->SetPath(serialPort, pathUtf16);
            }

            /* 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);
            }
4164

E
Eric Blake 已提交
4165 4166 4167 4168
            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);
4169
#if VBOX_API_VERSION >= 3000
E
Eric Blake 已提交
4170 4171
            } else if (def->serials[i]->type == VIR_DOMAIN_CHR_TYPE_FILE) {
                serialPort->vtbl->SetHostMode(serialPort, PortMode_RawFile);
4172
#endif /* VBOX_API_VERSION >= 3000 */
E
Eric Blake 已提交
4173 4174 4175 4176
            } else {
                serialPort->vtbl->SetHostMode(serialPort,
                                              PortMode_Disconnected);
            }
4177

E
Eric Blake 已提交
4178 4179 4180 4181
            VBOX_RELEASE(serialPort);
            if (pathUtf16) {
                VBOX_UTF16_FREE(pathUtf16);
                pathUtf16 = NULL;
4182
            }
4183
        }
E
Eric Blake 已提交
4184 4185
    }
}
4186

E
Eric Blake 已提交
4187 4188 4189 4190 4191 4192
static void
vboxAttachParallel(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 parallelPortCount          = 0;
    int i = 0;
4193

E
Eric Blake 已提交
4194 4195 4196 4197 4198 4199 4200
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetParallelPortCount(systemProperties,
                                                     &parallelPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4201

E
Eric Blake 已提交
4202 4203 4204 4205
    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;
4206

E
Eric Blake 已提交
4207 4208 4209
        DEBUG("ParallelPort(%d): Type: %d", i, def->parallels[i]->type);
        DEBUG("ParallelPort(%d): target.port: %d", i,
              def->parallels[i]->target.port);
4210

E
Eric Blake 已提交
4211 4212 4213
        machine->vtbl->GetParallelPort(machine, i, &parallelPort);
        if (parallelPort) {
            PRUnichar *pathUtf16 = NULL;
4214

E
Eric Blake 已提交
4215
            VBOX_UTF8_TO_UTF16(def->parallels[i]->data.file.path, &pathUtf16);
4216

E
Eric Blake 已提交
4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236
            /* 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);
4237 4238
                }
            }
E
Eric Blake 已提交
4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249

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

            VBOX_RELEASE(parallelPort);
            if (pathUtf16) {
                VBOX_UTF16_FREE(pathUtf16);
                pathUtf16 = NULL;
            }
4250
        }
E
Eric Blake 已提交
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263
    }
}

static void
vboxAttachVideo(virDomainDefPtr def, IMachine *machine)
{
    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);
4264
#if VBOX_API_VERSION >= 3001
E
Eric Blake 已提交
4265 4266
            machine->vtbl->SetAccelerate2DVideoEnabled(machine,
                                                       def->videos[0]->accel->support2d);
4267
#endif /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
4268 4269
        } else {
            machine->vtbl->SetAccelerate3DEnabled(machine, 0);
4270
#if VBOX_API_VERSION >= 3001
E
Eric Blake 已提交
4271
            machine->vtbl->SetAccelerate2DVideoEnabled(machine, 0);
4272 4273
#endif /* VBOX_API_VERSION >= 3001 */
        }
E
Eric Blake 已提交
4274 4275
    }
}
4276

E
Eric Blake 已提交
4277 4278 4279 4280 4281 4282 4283 4284 4285
static void
vboxAttachDisplay(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    int vrdpPresent  = 0;
    int sdlPresent   = 0;
    int guiPresent   = 0;
    char *guiDisplay = NULL;
    char *sdlDisplay = NULL;
    int i = 0;
4286

E
Eric Blake 已提交
4287 4288
    for (i = 0; i < def->ngraphics; i++) {
        IVRDPServer *VRDPServer = NULL;
4289

E
Eric Blake 已提交
4290 4291
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) &&
            (vrdpPresent == 0)) {
4292

E
Eric Blake 已提交
4293 4294 4295 4296 4297
            vrdpPresent = 1;
            machine->vtbl->GetVRDPServer(machine, &VRDPServer);
            if (VRDPServer) {
                VRDPServer->vtbl->SetEnabled(VRDPServer, PR_TRUE);
                DEBUG0("VRDP Support turned ON.");
4298 4299

#if VBOX_API_VERSION < 3001
E
Eric Blake 已提交
4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311
                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");
                }
4312
#else  /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
4313 4314 4315 4316
                PRUnichar *portUtf16 = NULL;
                portUtf16 = PRUnicharFromInt(def->graphics[i]->data.rdp.port);
                VRDPServer->vtbl->SetPorts(VRDPServer, portUtf16);
                VBOX_UTF16_FREE(portUtf16);
4317 4318
#endif /* VBOX_API_VERSION >= 3001 */

E
Eric Blake 已提交
4319 4320 4321 4322 4323
                if (def->graphics[i]->data.rdp.replaceUser) {
                    VRDPServer->vtbl->SetReuseSingleConnection(VRDPServer,
                                                               PR_TRUE);
                    DEBUG0("VRDP set to reuse single connection");
                }
4324

E
Eric Blake 已提交
4325 4326 4327 4328 4329
                if (def->graphics[i]->data.rdp.multiUser) {
                    VRDPServer->vtbl->SetAllowMultiConnection(VRDPServer,
                                                              PR_TRUE);
                    DEBUG0("VRDP set to allow multiple connection");
                }
4330

E
Eric Blake 已提交
4331 4332
                if (def->graphics[i]->data.rdp.listenAddr) {
                    PRUnichar *netAddressUtf16 = NULL;
4333

E
Eric Blake 已提交
4334 4335 4336 4337 4338 4339
                    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);
4340

E
Eric Blake 已提交
4341
                    VBOX_UTF16_FREE(netAddressUtf16);
4342
                }
E
Eric Blake 已提交
4343 4344

                VBOX_RELEASE(VRDPServer);
4345
            }
E
Eric Blake 已提交
4346
        }
4347

E
Eric Blake 已提交
4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358
        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) {
                    virReportOOMError();
                    /* 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
                     */
4359
                }
4360
            }
E
Eric Blake 已提交
4361
        }
4362

E
Eric Blake 已提交
4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373
        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) {
                    virReportOOMError();
                    /* 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
                     */
4374
                }
4375
            }
4376
        }
E
Eric Blake 已提交
4377
    }
4378

E
Eric Blake 已提交
4379 4380 4381 4382
    if ((vrdpPresent == 1) && (guiPresent == 0) && (sdlPresent == 0)) {
        /* store extradata key that frontend is set to vrdp */
        PRUnichar *keyTypeUtf16   = NULL;
        PRUnichar *valueTypeUtf16 = NULL;
4383

E
Eric Blake 已提交
4384 4385
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("vrdp", &valueTypeUtf16);
4386

E
Eric Blake 已提交
4387
        machine->vtbl->SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);
4388

E
Eric Blake 已提交
4389 4390
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4391

E
Eric Blake 已提交
4392 4393 4394 4395 4396 4397
    } 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;
4398

E
Eric Blake 已提交
4399 4400
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("sdl", &valueTypeUtf16);
4401

E
Eric Blake 已提交
4402
        machine->vtbl->SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);
4403

E
Eric Blake 已提交
4404 4405
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4406

E
Eric Blake 已提交
4407 4408 4409
        if (sdlDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(sdlDisplay, &valueDisplayUtf16);
4410

E
Eric Blake 已提交
4411 4412
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4413

E
Eric Blake 已提交
4414 4415 4416
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
        }
4417

E
Eric Blake 已提交
4418 4419 4420 4421 4422 4423
    } 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;
4424

E
Eric Blake 已提交
4425 4426
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("gui", &valueTypeUtf16);
4427

E
Eric Blake 已提交
4428
        machine->vtbl->SetExtraData(machine, keyTypeUtf16, valueTypeUtf16);
4429

E
Eric Blake 已提交
4430 4431
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4432

E
Eric Blake 已提交
4433 4434 4435
        if (guiDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(guiDisplay, &valueDisplayUtf16);
4436

E
Eric Blake 已提交
4437 4438
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4439

E
Eric Blake 已提交
4440 4441
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
4442
        }
E
Eric Blake 已提交
4443
    }
4444

E
Eric Blake 已提交
4445 4446 4447
    VIR_FREE(guiDisplay);
    VIR_FREE(sdlDisplay);
}
4448

E
Eric Blake 已提交
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 4488
static void
vboxAttachUSB(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    IUSBController *USBController = NULL;
    int i = 0;
    bool isUSB = false;

    if (def->nhostdevs == 0)
        return;

    /* 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 = true;
                    break;
                }
            }
        }
    }

    if (isUSB) {
        /* 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);
4489

4490 4491
            for (i = 0; i < def->nhostdevs; i++) {
                if (def->hostdevs[i]->mode ==
E
Eric Blake 已提交
4492
                    VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
4493
                    if (def->hostdevs[i]->source.subsys.type ==
E
Eric Blake 已提交
4494
                        VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
4495

E
Eric Blake 已提交
4496
                        char *filtername           = NULL;
E
Eric Blake 已提交
4497 4498
                        PRUnichar *filternameUtf16 = NULL;
                        IUSBDeviceFilter *filter   = NULL;
4499

E
Eric Blake 已提交
4500 4501
                        /* Zero pad for nice alignment when fewer than 9999
                         * devices.
E
Eric Blake 已提交
4502
                         */
E
Eric Blake 已提交
4503 4504 4505 4506 4507 4508 4509 4510 4511
                        if (virAsprintf(&filtername, "filter%04d", i) < 0) {
                            virReportOOMError();
                        } else {
                            VBOX_UTF8_TO_UTF16(filtername, &filternameUtf16);
                            VIR_FREE(filtername);
                            USBController->vtbl->CreateDeviceFilter(USBController,
                                                                    filternameUtf16,
                                                                    &filter);
                        }
E
Eric Blake 已提交
4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523
                        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) {
E
Eric Blake 已提交
4524 4525
                                snprintf(vendorId, sizeof(vendorId), "%x",
                                         def->hostdevs[i]->source.subsys.u.usb.vendor);
E
Eric Blake 已提交
4526 4527 4528 4529 4530
                                VBOX_UTF8_TO_UTF16(vendorId, &vendorIdUtf16);
                                filter->vtbl->SetVendorId(filter, vendorIdUtf16);
                                VBOX_UTF16_FREE(vendorIdUtf16);
                            }
                            if (def->hostdevs[i]->source.subsys.u.usb.product) {
E
Eric Blake 已提交
4531 4532
                                snprintf(productId, sizeof(productId), "%x",
                                         def->hostdevs[i]->source.subsys.u.usb.product);
E
Eric Blake 已提交
4533 4534 4535 4536
                                VBOX_UTF8_TO_UTF16(productId, &productIdUtf16);
                                filter->vtbl->SetProductId(filter,
                                                           productIdUtf16);
                                VBOX_UTF16_FREE(productIdUtf16);
4537
                            }
E
Eric Blake 已提交
4538 4539 4540 4541 4542
                            filter->vtbl->SetActive(filter, 1);
                            USBController->vtbl->InsertDeviceFilter(USBController,
                                                                    i,
                                                                    filter);
                            VBOX_RELEASE(filter);
4543
                        }
E
Eric Blake 已提交
4544

4545 4546 4547
                    }
                }
            }
E
Eric Blake 已提交
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
            VBOX_RELEASE(USBController);
        }
    }
}

static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml) {
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
    IMachine       *machine     = NULL;
    IBIOSSettings  *bios        = NULL;
    vboxIID        *iid         = NULL;
    vboxIID        *mchiid      = NULL;
    virDomainDefPtr def         = NULL;
    PRUnichar *machineNameUtf16 = NULL;
#if VBOX_API_VERSION >= 3002
    PRBool override             = PR_FALSE;
#endif
    nsresult rc;

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

#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    VBOX_UTF8_TO_UTF16(def->name, &machineNameUtf16);
    vboxIIDFromUUID(def->uuid, iid);
#if VBOX_API_VERSION < 3002
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
                                            iid,
                                            &machine);
#else /* VBOX_API_VERSION >= 3002 */
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
                                            iid,
                                            override,
                                            &machine);
#endif /* VBOX_API_VERSION >= 3002 */
    VBOX_UTF16_FREE(machineNameUtf16);

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

4604
    rc = machine->vtbl->SetMemorySize(machine, def->mem.cur_balloon / 1024);
E
Eric Blake 已提交
4605 4606 4607 4608
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not set the memory size of the domain to: %lu Kb, "
                    "rc=%08x"),
4609
                  def->mem.cur_balloon, (unsigned)rc);
E
Eric Blake 已提交
4610 4611
    }

E
Eric Blake 已提交
4612 4613 4614 4615 4616
    if (def->vcpus != def->maxvcpus) {
        vboxError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                    _("current vcpu count must equal maximum"));
    }
    rc = machine->vtbl->SetCPUCount(machine, def->maxvcpus);
E
Eric Blake 已提交
4617 4618
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
4619 4620
                  _("could not set the number of virtual CPUs to: %u, rc=%08x"),
                  def->maxvcpus, (unsigned)rc);
E
Eric Blake 已提交
4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658
    }

#if VBOX_API_VERSION < 3001
    rc = machine->vtbl->SetPAEEnabled(machine, (def->features) &
                                      (1 << VIR_DOMAIN_FEATURE_PAE));
#elif VBOX_API_VERSION == 3001
    rc = machine->vtbl->SetCpuProperty(machine, CpuPropertyType_PAE,
                                       (def->features) &
                                       (1 << VIR_DOMAIN_FEATURE_PAE));
#elif VBOX_API_VERSION >= 3002
    rc = machine->vtbl->SetCPUProperty(machine, CPUPropertyType_PAE,
                                       (def->features) &
                                       (1 << VIR_DOMAIN_FEATURE_PAE));
#endif
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not change PAE status to: %s, rc=%08x"),
                  ((def->features) & (1 << VIR_DOMAIN_FEATURE_PAE))
                  ? _("Enabled") : _("Disabled"), (unsigned)rc);
    }

    machine->vtbl->GetBIOSSettings(machine, &bios);
    if (bios) {
        rc = bios->vtbl->SetACPIEnabled(bios, (def->features) &
                                        (1 << VIR_DOMAIN_FEATURE_ACPI));
        if (NS_FAILED(rc)) {
            vboxError(VIR_ERR_INTERNAL_ERROR,
                      _("could not change ACPI status to: %s, rc=%08x"),
                      ((def->features) & (1 << VIR_DOMAIN_FEATURE_ACPI))
                      ? _("Enabled") : _("Disabled"), (unsigned)rc);
        }
        rc = bios->vtbl->SetIOAPICEnabled(bios, (def->features) &
                                          (1 << VIR_DOMAIN_FEATURE_APIC));
        if (NS_FAILED(rc)) {
            vboxError(VIR_ERR_INTERNAL_ERROR,
                      _("could not change APIC status to: %s, rc=%08x"),
                      ((def->features) & (1 << VIR_DOMAIN_FEATURE_APIC))
                      ? _("Enabled") : _("Disabled"), (unsigned)rc);
4659
        }
E
Eric Blake 已提交
4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687
        VBOX_RELEASE(bios);
    }

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

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

    vboxSetBootDeviceOrder(def, data, machine);
    vboxAttachDrives(def, data, machine);
    vboxAttachSound(def, machine);
    vboxAttachNetwork(def, data, machine);
    vboxAttachSerial(def, data, machine);
    vboxAttachParallel(def, data, machine);
    vboxAttachVideo(def, machine);
    vboxAttachDisplay(def, data, machine);
    vboxAttachUSB(def, data, machine);
4688

4689 4690 4691 4692 4693 4694
    /* 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);
4695

4696 4697 4698
    ret = virGetDomain(conn, def->name, def->uuid);
    VBOX_RELEASE(machine);
    machine = NULL;
4699

4700
    vboxIIDFree(iid);
4701 4702
    virDomainDefFree(def);

4703
    return ret;
4704 4705

cleanup:
4706
    VBOX_RELEASE(machine);
4707
    vboxIIDFree(iid);
4708 4709 4710 4711 4712
    virDomainDefFree(def);
    return NULL;
}

static int vboxDomainUndefine(virDomainPtr dom) {
4713
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
4714
    IMachine *machine    = NULL;
4715
    vboxIID  *iid        = NULL;
4716
    nsresult rc;
4717

4718
#if VBOX_API_VERSION == 2002
4719
    if (VIR_ALLOC(iid) < 0) {
4720
        virReportOOMError();
4721 4722
        goto cleanup;
    }
4723
#endif
4724

4725
    vboxIIDFromUUID(dom->uuid, iid);
4726

4727 4728 4729 4730 4731 4732 4733
    /* 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;
4734

4735 4736 4737
        char *hddcname = strdup("IDE");
        VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16);
        VIR_FREE(hddcname);
4738

4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753
        /* 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
                 */
4754
                vboxArray storageControllers = VBOX_ARRAY_INITIALIZER;
4755 4756
                int i = 0, j = 0;

4757 4758
                vboxArrayGet(&storageControllers, machine,
                             machine->vtbl->GetStorageControllers);
4759

4760 4761
                for (i = 0; i < storageControllers.count; i++) {
                    IStorageController *strCtl = storageControllers.items[i];
4762
                    PRUnichar *strCtlName = NULL;
4763
                    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
4764 4765 4766 4767 4768

                    if (!strCtl)
                        continue;

                    strCtl->vtbl->GetName(strCtl, &strCtlName);
4769 4770 4771
                    vboxArrayGetWithArg(&mediumAttachments, machine,
                                        machine->vtbl->GetMediumAttachmentsOfController,
                                        strCtlName);
4772

4773 4774
                    for (j = 0; j < mediumAttachments.count; j++) {
                        IMediumAttachment *medAtt = mediumAttachments.items[j];
4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790
                        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);
                        }
                    }
4791

4792 4793
                    vboxArrayRelease(&storageControllers);

4794 4795
                    machine->vtbl->RemoveStorageController(machine, strCtlName);
                    VBOX_UTF16_FREE(strCtlName);
4796
                }
4797 4798

                vboxArrayRelease(&storageControllers);
4799 4800 4801
#endif /* VBOX_API_VERSION >= 3001 */

                machine->vtbl->SaveSettings(machine);
4802
            }
4803
            data->vboxSession->vtbl->Close(data->vboxSession);
4804
        }
4805 4806
        VBOX_UTF16_FREE(hddcnameUtf16);
    }
4807

4808 4809
    rc = data->vboxObj->vtbl->UnregisterMachine(data->vboxObj, iid, &machine);
    DEBUGIID("UUID of machine being undefined", iid);
4810

4811 4812 4813 4814
    if (NS_SUCCEEDED(rc) && machine){
        machine->vtbl->DeleteSettings(machine);
        ret = 0;
    } else {
4815 4816
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not delete the domain, rc=%08x"), (unsigned)rc);
4817 4818
    }

4819
#if VBOX_API_VERSION == 2002
4820
cleanup:
4821 4822
#endif
    vboxIIDFree(iid);
4823
    VBOX_RELEASE(machine);
4824 4825 4826 4827

    return ret;
}

4828 4829 4830
static int vboxDomainAttachDeviceImpl(virDomainPtr dom,
                                      const char *xml,
                                      int mediaChangeOnly ATTRIBUTE_UNUSED) {
4831
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
4832
    IMachine *machine    = NULL;
4833
    vboxIID  *iid        = NULL;
4834 4835 4836
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
4837
    nsresult rc;
4838 4839

    if (VIR_ALLOC(def) < 0) {
4840
        virReportOOMError();
4841 4842 4843 4844 4845
        return ret;
    }

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

4846
    if (def->os.type == NULL) {
4847
        virReportOOMError();
4848 4849 4850
        goto cleanup;
    }

4851
    dev = virDomainDeviceDefParse(data->caps, def, xml,
4852 4853
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
4854
        virReportOOMError();
4855 4856 4857
        goto cleanup;
    }

4858
#if VBOX_API_VERSION == 2002
4859
    if (VIR_ALLOC(iid) < 0) {
4860
        virReportOOMError();
4861 4862
        goto cleanup;
    }
4863
#endif
4864

4865
    vboxIIDFromUUID(dom->uuid, iid);
4866

4867 4868
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
4869 4870
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
                  _("no domain with matching uuid"));
4871 4872
        goto cleanup;
    }
4873

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

4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
        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) {
4889 4890
                        if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE &&
                            dev->data.disk->src != NULL) {
4891 4892 4893 4894 4895 4896 4897 4898 4899 4900
                            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;
4901
# if VBOX_API_VERSION == 2002
4902
                                nsID dvdemptyuuid;
4903

4904
                                memset(&dvdemptyuuid, 0, sizeof(dvdemptyuuid));
4905
# else
4906
                                PRUnichar *dvdemptyuuidUtf16 = NULL;
4907
# endif
4908

4909
                                VBOX_UTF8_TO_UTF16(dev->data.disk->src, &dvdfileUtf16);
4910

4911 4912
                                data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                if (!dvdImage) {
4913
# if VBOX_API_VERSION == 2002
4914
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, &dvdemptyuuid, &dvdImage);
4915
# else
4916
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, dvdemptyuuidUtf16, &dvdImage);
4917
# endif
4918 4919 4920 4921
                                }
                                if (dvdImage) {
                                    rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage, &dvduuid);
                                    if (NS_FAILED(rc)) {
4922 4923 4924
                                        vboxError(VIR_ERR_INTERNAL_ERROR,
                                                  _("can't get the uuid of the file to "
                                                    "be attached to cdrom: %s, rc=%08x"),
4925 4926 4927 4928 4929
                                                  dev->data.disk->src, (unsigned)rc);
                                    } else {
                                        /* unmount the previous mounted image */
                                        dvdDrive->vtbl->Unmount(dvdDrive);
                                        rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid);
4930
                                        if (NS_FAILED(rc)) {
4931 4932
                                            vboxError(VIR_ERR_INTERNAL_ERROR,
                                                      _("could not attach the file to cdrom: %s, rc=%08x"),
4933 4934
                                                      dev->data.disk->src, (unsigned)rc);
                                        } else {
4935 4936
                                            ret = 0;
                                            DEBUGIID("CD/DVD Image UUID:", dvduuid);
4937 4938
                                        }
                                    }
4939 4940

                                    VBOX_MEDIUM_RELEASE(dvdImage);
4941
                                }
4942 4943 4944
                                vboxIIDUnalloc(dvduuid);
                                VBOX_UTF16_FREE(dvdfileUtf16);
                                VBOX_RELEASE(dvdDrive);
4945
                            }
4946 4947 4948
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                        }
                    } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
4949 4950
                        if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE &&
                            dev->data.disk->src != NULL) {
4951 4952 4953 4954 4955 4956 4957 4958
                            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;
4959
# if VBOX_API_VERSION == 2002
4960
                                    nsID fdemptyuuid;
4961

4962
                                    memset(&fdemptyuuid, 0, sizeof(fdemptyuuid));
4963
# else
4964
                                    PRUnichar *fdemptyuuidUtf16 = NULL;
4965
# endif
4966 4967 4968 4969 4970 4971 4972 4973
                                    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,
4974
# if VBOX_API_VERSION == 2002
4975
                                                                             &fdemptyuuid,
4976
# else
4977
                                                                             fdemptyuuidUtf16,
4978
# endif
4979 4980
                                                                             &floppyImage);
                                    }
4981

4982 4983 4984
                                    if (floppyImage) {
                                        rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage, &fduuid);
                                        if (NS_FAILED(rc)) {
4985 4986 4987
                                            vboxError(VIR_ERR_INTERNAL_ERROR,
                                                      _("can't get the uuid of the file to be "
                                                        "attached to floppy drive: %s, rc=%08x"),
4988 4989 4990
                                                      dev->data.disk->src, (unsigned)rc);
                                        } else {
                                            rc = floppyDrive->vtbl->MountImage(floppyDrive, fduuid);
4991
                                            if (NS_FAILED(rc)) {
4992 4993
                                                vboxError(VIR_ERR_INTERNAL_ERROR,
                                                          _("could not attach the file to floppy drive: %s, rc=%08x"),
4994 4995
                                                          dev->data.disk->src, (unsigned)rc);
                                            } else {
4996 4997
                                                ret = 0;
                                                DEBUGIID("attached floppy, UUID:", fduuid);
4998 4999
                                            }
                                        }
5000
                                        VBOX_MEDIUM_RELEASE(floppyImage);
5001
                                    }
5002 5003
                                    vboxIIDUnalloc(fduuid);
                                    VBOX_UTF16_FREE(fdfileUtf16);
5004
                                }
5005
                                VBOX_RELEASE(floppyDrive);
5006
                            }
5007
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
5008
                        }
5009 5010 5011 5012 5013 5014 5015
                    }
#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) {
5016 5017 5018
                        }
                    }
                }
5019 5020
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5021
            }
5022
            data->vboxSession->vtbl->Close(data->vboxSession);
5023 5024 5025 5026
        }
    }

cleanup:
5027
    vboxIIDFree(iid);
5028 5029 5030 5031 5032
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5033 5034 5035 5036
static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml) {
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

5037 5038 5039
static int vboxDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
5040
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
5041 5042 5043 5044
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

5045 5046 5047 5048 5049
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

static int vboxDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags) {
5050 5051 5052 5053
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_CURRENT |
                  VIR_DOMAIN_DEVICE_MODIFY_LIVE |
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG, -1);

5054
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
5055
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
5056 5057 5058 5059 5060
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainAttachDeviceImpl(dom, xml, 1);
5061 5062
}

5063
static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml) {
5064
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5065
    IMachine *machine    = NULL;
5066
    vboxIID  *iid        = NULL;
5067 5068 5069
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5070
    nsresult rc;
5071 5072

    if (VIR_ALLOC(def) < 0) {
5073
        virReportOOMError();
5074 5075 5076 5077 5078
        return ret;
    }

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

5079
    if (def->os.type == NULL) {
5080
        virReportOOMError();
5081 5082 5083
        goto cleanup;
    }

5084
    dev = virDomainDeviceDefParse(data->caps, def, xml,
5085 5086
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
5087
        virReportOOMError();
5088 5089 5090
        goto cleanup;
    }

5091
#if VBOX_API_VERSION == 2002
5092
    if (VIR_ALLOC(iid) < 0) {
5093
        virReportOOMError();
5094 5095
        goto cleanup;
    }
5096
#endif
5097

5098
    vboxIIDFromUUID(dom->uuid, iid);
5099

5100 5101
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
5102 5103
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
                  _("no domain with matching uuid"));
5104 5105
        goto cleanup;
    }
5106

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

5110 5111 5112 5113 5114 5115
        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);
        }
5116

5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132
        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)) {
5133 5134
                                    vboxError(VIR_ERR_INTERNAL_ERROR,
                                              _("could not de-attach the mounted ISO, rc=%08x"),
5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152
                                              (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);
5153
                                    if (NS_FAILED(rc)) {
5154 5155 5156
                                        vboxError(VIR_ERR_INTERNAL_ERROR,
                                                  _("could not attach the file "
                                                    "to floppy drive, rc=%08x"),
5157 5158 5159 5160
                                                  (unsigned)rc);
                                    } else {
                                        ret = 0;
                                    }
5161 5162 5163 5164 5165
                                } 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;
5166
                                }
5167
                                VBOX_RELEASE(floppyDrive);
5168
                            }
5169
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
5170
                        }
5171 5172 5173 5174 5175 5176 5177
                    }
#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) {
5178 5179 5180
                        }
                    }
                }
5181 5182
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5183
            }
5184
            data->vboxSession->vtbl->Close(data->vboxSession);
5185 5186 5187 5188
        }
    }

cleanup:
5189
    vboxIIDFree(iid);
5190 5191 5192 5193 5194
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5195 5196 5197
static int vboxDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags) {
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
5198
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
5199 5200 5201 5202 5203 5204 5205
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainDetachDevice(dom, xml);
}

J
Jiri Denemark 已提交
5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218
static int
vboxDomainSnapshotGetAll(virDomainPtr dom,
                         IMachine *machine,
                         ISnapshot ***snapshots)
{
    ISnapshot **list = NULL;
    PRUint32 count;
    nsresult rc;
    unsigned int next;
    unsigned int top;

    rc = machine->vtbl->GetSnapshotCount(machine, &count);
    if (NS_FAILED(rc)) {
5219
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234
                  _("could not get snapshot count for domain %s"),
                  dom->name);
        goto error;
    }

    if (count == 0)
        goto out;

    if (VIR_ALLOC_N(list, count) < 0) {
        virReportOOMError();
        goto error;
    }

    rc = machine->vtbl->GetSnapshot(machine, NULL, list);
    if (NS_FAILED(rc) || !list[0]) {
5235
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5236 5237 5238 5239 5240 5241 5242 5243
                  _("could not get root snapshot for domain %s"),
                  dom->name);
        goto error;
    }

    /* BFS walk through snapshot tree */
    top = 1;
    for (next = 0; next < count; next++) {
5244
        vboxArray children = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
5245 5246 5247
        unsigned int i;

        if (!list[next]) {
5248
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5249 5250 5251 5252
                      _("unexpected number of snapshots < %u"), count);
            goto error;
        }

5253 5254
        rc = vboxArrayGet(&children, list[next],
                               list[next]->vtbl->GetChildren);
J
Jiri Denemark 已提交
5255
        if (NS_FAILED(rc)) {
5256
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5257 5258 5259
                      "%s", _("could not get children snapshots"));
            goto error;
        }
5260 5261 5262
        for (i = 0; i < children.count; i++) {
            ISnapshot *child = children.items[i];
            if (!child)
J
Jiri Denemark 已提交
5263 5264
                continue;
            if (top == count) {
5265
                vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5266
                          _("unexpected number of snapshots > %u"), count);
5267
                vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5268 5269
                goto error;
            }
5270 5271
            VBOX_ADDREF(child);
            list[top++] = child;
J
Jiri Denemark 已提交
5272
        }
5273
        vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310
    }

out:
    *snapshots = list;
    return count;

error:
    if (list) {
        for (next = 0; next < count; next++)
            VBOX_RELEASE(list[next]);
    }
    VIR_FREE(list);

    return -1;
}

static ISnapshot *
vboxDomainSnapshotGet(vboxGlobalData *data,
                      virDomainPtr dom,
                      IMachine *machine,
                      const char *name)
{
    ISnapshot **snapshots = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;
    int count = 0;
    int i;

    if ((count = vboxDomainSnapshotGetAll(dom, machine, &snapshots)) < 0)
        goto cleanup;

    for (i = 0; i < count; i++) {
        PRUnichar *nameUtf16;
        char *nameUtf8;

        rc = snapshots[i]->vtbl->GetName(snapshots[i], &nameUtf16);
        if (NS_FAILED(rc) || !nameUtf16) {
5311
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325
                      "%s", _("could not get snapshot name"));
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
        VBOX_UTF16_FREE(nameUtf16);
        if (STREQ(name, nameUtf8))
            snapshot = snapshots[i];
        VBOX_UTF8_FREE(nameUtf8);

        if (snapshot)
            break;
    }

    if (!snapshot) {
5326
        vboxError(VIR_ERR_OPERATION_INVALID,
J
Jiri Denemark 已提交
5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345
                  _("domain %s has no snapshots with name %s"),
                  dom->name, name);
        goto cleanup;
    }

cleanup:
    if (count > 0) {
        for (i = 0; i < count; i++) {
            if (snapshots[i] != snapshot)
                VBOX_RELEASE(snapshots[i]);
        }
    }
    VIR_FREE(snapshots);
    return snapshot;
}

static virDomainSnapshotPtr
vboxDomainSnapshotCreateXML(virDomainPtr dom,
                            const char *xmlDesc,
5346
                            unsigned int flags)
J
Jiri Denemark 已提交
5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    virDomainSnapshotDefPtr def = NULL;
    vboxIID *domiid = NULL;
    IMachine *machine = NULL;
    IConsole *console = NULL;
    IProgress *progress = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *name = NULL;
    PRUnichar *description = NULL;
    PRUint32 state;
    nsresult rc;
#if VBOX_API_VERSION == 2002
    nsresult result;
#else
    PRInt32 result;
#endif

5365 5366
    virCheckFlags(0, NULL);

J
Jiri Denemark 已提交
5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
        goto cleanup;

#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(domiid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, domiid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, domiid, &machine);
    if (NS_FAILED(rc) || !machine) {
5380
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5381 5382 5383 5384 5385 5386
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
5387
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404
                  _("could not get domain state"));
        goto cleanup;
    }

    if ((state >= MachineState_FirstOnline)
        && (state <= MachineState_LastOnline)) {
        rc = data->vboxObj->vtbl->OpenExistingSession(data->vboxObj,
                                                      data->vboxSession,
                                                      domiid);
    } else {
        rc = data->vboxObj->vtbl->OpenSession(data->vboxObj,
                                              data->vboxSession,
                                              domiid);
    }
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
5405
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426
                  _("could not open VirtualBox session with domain %s"),
                  dom->name);
        goto cleanup;
    }

    VBOX_UTF8_TO_UTF16(def->name, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    if (def->description) {
        VBOX_UTF8_TO_UTF16(def->description, &description);
        if (!description) {
            virReportOOMError();
            goto cleanup;
        }
    }

    rc = console->vtbl->TakeSnapshot(console, name, description, &progress);
    if (NS_FAILED(rc) || !progress) {
5427
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5428 5429 5430 5431 5432 5433 5434
                  _("could not take snapshot of domain %s"), dom->name);
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
5435
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5436 5437 5438 5439 5440 5441
                  _("could not take snapshot of domain %s"), dom->name);
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
5442
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463
                  _("could not get current snapshot of domain %s"),
                  dom->name);
        goto cleanup;
    }

    ret = virGetDomainSnapshot(dom, def->name);

cleanup:
    VBOX_RELEASE(progress);
    VBOX_UTF16_FREE(description);
    VBOX_UTF16_FREE(name);
    VBOX_RELEASE(console);
    data->vboxSession->vtbl->Close(data->vboxSession);
    VBOX_RELEASE(machine);
    vboxIIDFree(domiid);
    virDomainSnapshotDefFree(def);
    return ret;
}

static char *
vboxDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
5464
                          unsigned int flags)
J
Jiri Denemark 已提交
5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
    vboxIID *domiid = NULL;
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    ISnapshot *parent = NULL;
    nsresult rc;
    virDomainSnapshotDefPtr def = NULL;
    PRUnichar *str16;
    char *str8;
    PRInt64 timestamp;
    PRBool online = PR_FALSE;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

5480 5481
    virCheckFlags(0, NULL);

J
Jiri Denemark 已提交
5482 5483 5484 5485 5486 5487 5488 5489 5490 5491
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(domiid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, domiid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, domiid, &machine);
    if (NS_FAILED(rc)) {
5492
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    if (VIR_ALLOC(def) < 0
        || !(def->name = strdup(snapshot->name)))
        goto no_memory;

    rc = snap->vtbl->GetDescription(snap, &str16);
    if (NS_FAILED(rc)) {
5506
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521
                  _("could not get description of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }
    if (str16) {
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
        def->description = strdup(str8);
        VBOX_UTF8_FREE(str8);
        if (!def->description)
            goto no_memory;
    }

    rc = snap->vtbl->GetTimeStamp(snap, &timestamp);
    if (NS_FAILED(rc)) {
5522
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5523 5524 5525 5526 5527 5528 5529 5530 5531
                  _("could not get creation time of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }
    /* timestamp is in milliseconds while creationTime in seconds */
    def->creationTime = timestamp / 1000;

    rc = snap->vtbl->GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
5532
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5533 5534 5535 5536 5537 5538 5539
                  _("could not get parent of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }
    if (parent) {
        rc = parent->vtbl->GetName(parent, &str16);
        if (NS_FAILED(rc) || !str16) {
5540
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554
                      _("could not get name of parent of snapshot %s"),
                      snapshot->name);
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
        def->parent = strdup(str8);
        VBOX_UTF8_FREE(str8);
        if (!def->parent)
            goto no_memory;
    }

    rc = snap->vtbl->GetOnline(snap, &online);
    if (NS_FAILED(rc)) {
5555
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582
                  _("could not get online state of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }
    if (online)
        def->state = VIR_DOMAIN_RUNNING;
    else
        def->state = VIR_DOMAIN_SHUTOFF;

    virUUIDFormat(dom->uuid, uuidstr);
    ret = virDomainSnapshotDefFormat(uuidstr, def, 0);

cleanup:
    virDomainSnapshotDefFree(def);
    VBOX_RELEASE(parent);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
    vboxIIDFree(domiid);
    return ret;

no_memory:
    virReportOOMError();
    goto cleanup;
}

static int
vboxDomainSnapshotNum(virDomainPtr dom,
5583
                      unsigned int flags)
J
Jiri Denemark 已提交
5584 5585 5586 5587 5588 5589 5590
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID *iid = NULL;
    IMachine *machine = NULL;
    nsresult rc;
    PRUint32 snapshotCount;

5591 5592
    virCheckFlags(0, -1);

J
Jiri Denemark 已提交
5593 5594 5595 5596 5597 5598 5599 5600 5601 5602
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
5603
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5604 5605 5606 5607 5608 5609
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetSnapshotCount(machine, &snapshotCount);
    if (NS_FAILED(rc)) {
5610
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627
                  _("could not get snapshot count for domain %s"),
                  dom->name);
        goto cleanup;
    }

    ret = snapshotCount;

cleanup:
    VBOX_RELEASE(machine);
    vboxIIDFree(iid);
    return ret;
}

static int
vboxDomainSnapshotListNames(virDomainPtr dom,
                            char **names,
                            int nameslen,
5628
                            unsigned int flags)
J
Jiri Denemark 已提交
5629 5630 5631 5632 5633 5634 5635 5636 5637
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID *iid = NULL;
    IMachine *machine = NULL;
    nsresult rc;
    ISnapshot **snapshots = NULL;
    int count = 0;
    int i;

5638 5639
    virCheckFlags(0, -1);

J
Jiri Denemark 已提交
5640 5641 5642 5643 5644 5645 5646 5647 5648 5649
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
5650
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    if ((count = vboxDomainSnapshotGetAll(dom, machine, &snapshots)) < 0)
        goto cleanup;

    for (i = 0; i < nameslen; i++) {
        PRUnichar *nameUtf16;
        char *name;

        if (i >= count)
            break;

        rc = snapshots[i]->vtbl->GetName(snapshots[i], &nameUtf16);
        if (NS_FAILED(rc) || !nameUtf16) {
5667
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699
                      "%s", _("could not get snapshot name"));
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(nameUtf16, &name);
        VBOX_UTF16_FREE(nameUtf16);
        names[i] = strdup(name);
        VBOX_UTF8_FREE(name);
        if (!names[i]) {
            virReportOOMError();
            goto cleanup;
        }
    }

    if (count <= nameslen)
        ret = count;
    else
        ret = nameslen;

cleanup:
    if (count > 0) {
        for (i = 0; i < count; i++)
            VBOX_RELEASE(snapshots[i]);
    }
    VIR_FREE(snapshots);
    VBOX_RELEASE(machine);
    vboxIIDFree(iid);
    return ret;
}

static virDomainSnapshotPtr
vboxDomainSnapshotLookupByName(virDomainPtr dom,
                               const char *name,
5700
                               unsigned int flags)
J
Jiri Denemark 已提交
5701 5702 5703 5704 5705 5706 5707
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    vboxIID *iid = NULL;
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

5708 5709
    virCheckFlags(0, NULL);

J
Jiri Denemark 已提交
5710 5711 5712 5713 5714 5715 5716 5717 5718 5719
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc)) {
5720
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    if (!(snapshot = vboxDomainSnapshotGet(data, dom, machine, name)))
        goto cleanup;

    ret = virGetDomainSnapshot(dom, name);

cleanup:
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
    vboxIIDFree(iid);
    return ret;
}

static int
vboxDomainHasCurrentSnapshot(virDomainPtr dom,
5739
                             unsigned int flags)
J
Jiri Denemark 已提交
5740 5741 5742 5743 5744 5745 5746
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID *iid = NULL;
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

5747 5748
    virCheckFlags(0, -1);

J
Jiri Denemark 已提交
5749 5750 5751 5752 5753 5754 5755 5756 5757 5758
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc) || !machine) {
5759
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5760 5761 5762 5763 5764 5765
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
5766
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783
                  _("could not get current snapshot"));
        goto cleanup;
    }

    if (snapshot)
        ret = 1;
    else
        ret = 0;

cleanup:
    VBOX_RELEASE(machine);
    vboxIIDFree(iid);
    return ret;
}

static virDomainSnapshotPtr
vboxDomainSnapshotCurrent(virDomainPtr dom,
5784
                          unsigned int flags)
J
Jiri Denemark 已提交
5785 5786 5787 5788 5789 5790 5791 5792 5793
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    vboxIID *iid = NULL;
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;

5794 5795
    virCheckFlags(0, NULL);

J
Jiri Denemark 已提交
5796 5797 5798 5799 5800 5801 5802 5803 5804 5805
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(iid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, iid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, iid, &machine);
    if (NS_FAILED(rc) || !machine) {
5806
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5807 5808 5809 5810 5811 5812
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
5813
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5814 5815 5816 5817 5818
                  _("could not get current snapshot"));
        goto cleanup;
    }

    if (!snapshot) {
5819
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
5820 5821 5822 5823 5824 5825
                  _("domain has no snapshots"));
        goto cleanup;
    }

    rc = snapshot->vtbl->GetName(snapshot, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
5826
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859
                  _("could not get current snapshot name"));
        goto cleanup;
    }

    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    ret = virGetDomainSnapshot(dom, name);

cleanup:
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
    vboxIIDFree(iid);
    return ret;
}

#if VBOX_API_VERSION < 3001
static int
vboxDomainSnapshotRestore(virDomainPtr dom,
                          IMachine *machine,
                          ISnapshot *snapshot)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID *iid = NULL;
    nsresult rc;

    rc = snapshot->vtbl->GetId(snapshot, &iid);
    if (NS_FAILED(rc) || !iid) {
5860
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5861 5862 5863 5864 5865 5866
                  _("could not get snapshot UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->SetCurrentSnapshot(machine, iid);
    if (NS_FAILED(rc)) {
5867
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893
                  _("could not restore snapshot for domain %s"), dom->name);
        goto cleanup;
    }

    ret = 0;

cleanup:
    vboxIIDUnalloc(iid);
    return ret;
}
#else
static int
vboxDomainSnapshotRestore(virDomainPtr dom,
                          IMachine *machine,
                          ISnapshot *snapshot)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    IConsole *console = NULL;
    IProgress *progress = NULL;
    PRUint32 state;
    nsresult rc;
    PRInt32 result;
    vboxIID *domiid;

    rc = machine->vtbl->GetId(machine, &domiid);
    if (NS_FAILED(rc) || !domiid) {
5894
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5895 5896 5897 5898 5899 5900
                  _("could not get domain UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
5901
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5902 5903 5904 5905 5906 5907
                  _("could not get domain state"));
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
5908
        vboxError(VIR_ERR_OPERATION_INVALID,
J
Jiri Denemark 已提交
5909 5910 5911 5912 5913 5914 5915 5916 5917
                  _("domain %s is already running"), dom->name);
        goto cleanup;
    }

    rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession,
                                          domiid);
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
5918
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5919 5920 5921 5922 5923 5924 5925 5926
                  _("could not open VirtualBox session with domain %s"),
                  dom->name);
        goto cleanup;
    }

    rc = console->vtbl->RestoreSnapshot(console, snapshot, &progress);
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
5927
            vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
5928 5929
                      _("cannot restore domain snapshot for running domain"));
        } else {
5930
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5931 5932 5933 5934 5935 5936 5937 5938 5939
                      _("could not restore snapshot for domain %s"),
                      dom->name);
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
5940
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956
                  _("could not restore snapshot for domain %s"), dom->name);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VBOX_RELEASE(progress);
    VBOX_RELEASE(console);
    data->vboxSession->vtbl->Close(data->vboxSession);
    return ret;
}
#endif

static int
vboxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
5957
                           unsigned int flags)
J
Jiri Denemark 已提交
5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID *domiid = NULL;
    IMachine *machine = NULL;
    ISnapshot *newSnapshot = NULL;
    ISnapshot *prevSnapshot = NULL;
    PRBool online = PR_FALSE;
    PRUint32 state;
    nsresult rc;

5969 5970
    virCheckFlags(0, -1);

J
Jiri Denemark 已提交
5971 5972 5973 5974 5975 5976 5977 5978 5979 5980
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(domiid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, domiid);
    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, domiid, &machine);
    if (NS_FAILED(rc)) {
5981
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
5982 5983 5984 5985 5986 5987 5988 5989 5990 5991
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    newSnapshot = vboxDomainSnapshotGet(data, dom, machine, snapshot->name);
    if (!newSnapshot)
        goto cleanup;

    rc = newSnapshot->vtbl->GetOnline(newSnapshot, &online);
    if (NS_FAILED(rc)) {
5992
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5993 5994 5995 5996 5997 5998 5999
                  _("could not get online state of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &prevSnapshot);
    if (NS_FAILED(rc)) {
6000
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6001 6002 6003 6004 6005 6006 6007
                  _("could not get current snapshot of domain %s"),
                  dom->name);
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
6008
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6009 6010 6011 6012 6013 6014
                  _("could not get domain state"));
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
6015
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053
                  _("cannot revert snapshot of running domain"));
        goto cleanup;
    }

    if (vboxDomainSnapshotRestore(dom, machine, newSnapshot))
        goto cleanup;

    if (online) {
        ret = vboxDomainCreate(dom);
        if (!ret)
            vboxDomainSnapshotRestore(dom, machine, prevSnapshot);
    } else
        ret = 0;

cleanup:
    VBOX_RELEASE(prevSnapshot);
    VBOX_RELEASE(newSnapshot);
    vboxIIDUnalloc(domiid);
    return ret;
}

static int
vboxDomainSnapshotDeleteSingle(vboxGlobalData *data,
                               IConsole *console,
                               ISnapshot *snapshot)
{
    IProgress *progress = NULL;
    vboxIID *iid = NULL;
    int ret = -1;
    nsresult rc;
#if VBOX_API_VERSION == 2002
    nsresult result;
#else
    PRInt32 result;
#endif

    rc = snapshot->vtbl->GetId(snapshot, &iid);
    if (NS_FAILED(rc) || !iid) {
6054
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065
                  _("could not get snapshot UUID"));
        goto cleanup;
    }

#if VBOX_API_VERSION < 3001
    rc = console->vtbl->DiscardSnapshot(console, iid, &progress);
#else
    rc = console->vtbl->DeleteSnapshot(console, iid, &progress);
#endif
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
6066
            vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6067 6068
                      _("cannot delete domain snapshot for running domain"));
        } else {
6069
            vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6070 6071 6072 6073 6074 6075 6076 6077
                      _("could not delete snapshot"));
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
6078
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095
                  _("could not delete snapshot"));
        goto cleanup;
    }

    ret = 0;

cleanup:
    VBOX_RELEASE(progress);
    vboxIIDUnalloc(iid);
    return ret;
}

static int
vboxDomainSnapshotDeleteTree(vboxGlobalData *data,
                             IConsole *console,
                             ISnapshot *snapshot)
{
6096
    vboxArray children = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
6097 6098 6099 6100
    int ret = -1;
    nsresult rc;
    unsigned int i;

6101
    rc = vboxArrayGet(&children, snapshot, snapshot->vtbl->GetChildren);
J
Jiri Denemark 已提交
6102
    if (NS_FAILED(rc)) {
6103
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6104 6105 6106 6107
                  _("could not get children snapshots"));
        goto cleanup;
    }

6108 6109 6110
    for (i = 0; i < children.count; i++) {
        if (vboxDomainSnapshotDeleteTree(data, console, children.items[i]))
            goto cleanup;
J
Jiri Denemark 已提交
6111 6112 6113 6114 6115
    }

    ret = vboxDomainSnapshotDeleteSingle(data, console, snapshot);

cleanup:
6116
    vboxArrayRelease(&children);
J
Jiri Denemark 已提交
6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132
    return ret;
}

static int
vboxDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                         unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID *domiid = NULL;
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IConsole *console = NULL;
    PRUint32 state;
    nsresult rc;

6133 6134
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

J
Jiri Denemark 已提交
6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145
#if VBOX_API_VERSION == 2002
    if (VIR_ALLOC(domiid) < 0) {
        virReportOOMError();
        goto cleanup;
    }
#endif

    vboxIIDFromUUID(dom->uuid, domiid);

    rc = data->vboxObj->vtbl->GetMachine(data->vboxObj, domiid, &machine);
    if (NS_FAILED(rc)) {
6146
        vboxError(VIR_ERR_INVALID_DOMAIN, "%s",
J
Jiri Denemark 已提交
6147 6148 6149 6150 6151 6152 6153 6154 6155 6156
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name);
    if (!snap)
        goto cleanup;

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
6157
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6158 6159 6160 6161 6162 6163
                  _("could not get domain state"));
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
6164
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6165 6166 6167 6168 6169 6170 6171 6172 6173
                  _("cannot delete snapshots of running domain"));
        goto cleanup;
    }

    rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession,
                                          domiid);
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
6174
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192
                  _("could not open VirtualBox session with domain %s"),
                  dom->name);
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN)
        ret = vboxDomainSnapshotDeleteTree(data, console, snap);
    else
        ret = vboxDomainSnapshotDeleteSingle(data, console, snap);

cleanup:
    VBOX_RELEASE(console);
    VBOX_RELEASE(snap);
    vboxIIDUnalloc(domiid);
    data->vboxSession->vtbl->Close(data->vboxSession);
    return ret;
}

6193 6194 6195 6196 6197
#if VBOX_API_VERSION == 2002
    /* No Callback support for VirtualBox 2.2.* series */
#else /* !(VBOX_API_VERSION == 2002) */

/* Functions needed for Callbacks */
6198 6199 6200 6201
static nsresult PR_COM_METHOD
vboxCallbackOnMachineStateChange(IVirtualBoxCallback *pThis,
                                 PRUnichar *machineId, PRUint32 state)
{
6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220
    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) {
6221
            virDomainEventPtr ev;
6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251

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

6252 6253 6254 6255 6256 6257 6258 6259
            ev = virDomainEventNewFromDom(dom, event, detail);

            if (ev) {
                virDomainEventDispatch(ev,
                                       g_pVBoxGlobalData->domainEventCallbacks,
                                       virDomainEventDispatchDefaultFunc,
                                       NULL);
                virDomainEventFree(ev);
6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271
            }
        }
    }

    virDomainEventCallbackListPurgeMarked(g_pVBoxGlobalData->domainEventCallbacks);

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

    return NS_OK;
}

6272 6273 6274 6275
static nsresult PR_COM_METHOD
vboxCallbackOnMachineDataChange(IVirtualBoxCallback *pThis,
                                PRUnichar *machineId)
{
6276 6277 6278 6279 6280 6281
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

6282 6283 6284 6285 6286 6287 6288
static nsresult PR_COM_METHOD
vboxCallbackOnExtraDataCanChange(IVirtualBoxCallback *pThis,
                                 PRUnichar *machineId, PRUnichar *key,
                                 PRUnichar *value,
                                 PRUnichar **error ATTRIBUTE_UNUSED,
                                 PRBool *allowChange)
{
6289 6290 6291 6292 6293 6294 6295 6296
    DEBUG("IVirtualBoxCallback: %p, allowChange: %s", pThis, *allowChange ? "true" : "false");
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

6297 6298 6299 6300
static nsresult PR_COM_METHOD
vboxCallbackOnExtraDataChange(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                              PRUnichar *key, PRUnichar *value)
{
6301 6302 6303 6304 6305 6306 6307 6308
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

6309
# if VBOX_API_VERSION < 3001
6310 6311 6312 6313
static nsresult PR_COM_METHOD
vboxCallbackOnMediaRegistered(IVirtualBoxCallback *pThis, PRUnichar *mediaId,
                              PRUint32 mediaType, PRBool registered)
{
6314 6315 6316 6317 6318 6319
    DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
    DEBUG("mediaType: %d", mediaType);
    DEBUGPRUnichar("mediaId", mediaId);

    return NS_OK;
}
6320 6321
# else  /* VBOX_API_VERSION >= 3001 */
# endif /* VBOX_API_VERSION >= 3001 */
6322

6323 6324 6325 6326
static nsresult PR_COM_METHOD
vboxCallbackOnMachineRegistered(IVirtualBoxCallback *pThis,
                                PRUnichar *machineId, PRBool registered)
{
6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345
    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) {
6346
            virDomainEventPtr ev;
6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361

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

6362 6363 6364 6365 6366 6367 6368 6369
            ev = virDomainEventNewFromDom(dom, event, detail);

            if (ev) {
                virDomainEventDispatch(ev,
                                       g_pVBoxGlobalData->domainEventCallbacks,
                                       virDomainEventDispatchDefaultFunc,
                                       NULL);
                virDomainEventFree(ev);
6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381
            }
        }
    }

    virDomainEventCallbackListPurgeMarked(g_pVBoxGlobalData->domainEventCallbacks);

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

    return NS_OK;
}

6382 6383 6384 6385
static nsresult PR_COM_METHOD
vboxCallbackOnSessionStateChange(IVirtualBoxCallback *pThis,
                                 PRUnichar *machineId, PRUint32 state)
{
6386 6387 6388 6389 6390 6391
    DEBUG("IVirtualBoxCallback: %p, state: %d", pThis, state);
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

6392 6393 6394 6395
static nsresult PR_COM_METHOD
vboxCallbackOnSnapshotTaken(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                            PRUnichar *snapshotId)
{
6396 6397 6398 6399 6400 6401 6402
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

6403 6404 6405 6406
static nsresult PR_COM_METHOD
vboxCallbackOnSnapshotDiscarded(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                                PRUnichar *snapshotId)
{
6407 6408 6409 6410 6411 6412 6413
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

6414 6415 6416 6417
static nsresult PR_COM_METHOD
vboxCallbackOnSnapshotChange(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                             PRUnichar *snapshotId)
{
6418 6419 6420 6421 6422 6423 6424
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

6425 6426 6427 6428 6429
static nsresult PR_COM_METHOD
vboxCallbackOnGuestPropertyChange(IVirtualBoxCallback *pThis,
                                  PRUnichar *machineId, PRUnichar *name,
                                  PRUnichar *value, PRUnichar *flags)
{
6430 6431 6432 6433 6434 6435 6436 6437 6438
    DEBUG("IVirtualBoxCallback: %p", pThis);
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("name", name);
    DEBUGPRUnichar("value", value);
    DEBUGPRUnichar("flags", flags);

    return NS_OK;
}

6439 6440 6441
static nsresult PR_COM_METHOD
vboxCallbackAddRef(nsISupports *pThis)
{
6442 6443 6444 6445 6446 6447 6448 6449 6450
    nsresult c;

    c = ++g_pVBoxGlobalData->vboxCallBackRefCount;

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

    return c;
}

6451 6452 6453
static nsresult PR_COM_METHOD
vboxCallbackRelease(nsISupports *pThis)
{
6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467
    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;
}

6468 6469 6470
static nsresult PR_COM_METHOD
vboxCallbackQueryInterface(nsISupports *pThis, const nsID *iid, void **resultp)
{
6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493
    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;
}


6494
static IVirtualBoxCallback *vboxAllocCallbackObj(void) {
6495 6496
    IVirtualBoxCallback *vboxCallback = NULL;

6497
    /* Allocate, Initialize and return a valid
6498 6499 6500
     * IVirtualBoxCallback object here
     */
    if ((VIR_ALLOC(vboxCallback) < 0) || (VIR_ALLOC(vboxCallback->vtbl) < 0)) {
6501
        VIR_FREE(vboxCallback);
6502
        virReportOOMError();
6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513
        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;
6514
# if VBOX_API_VERSION < 3001
6515
        vboxCallback->vtbl->OnMediaRegistered           = &vboxCallbackOnMediaRegistered;
6516 6517
# else  /* VBOX_API_VERSION >= 3001 */
# endif /* VBOX_API_VERSION >= 3001 */
6518 6519 6520
        vboxCallback->vtbl->OnMachineRegistered         = &vboxCallbackOnMachineRegistered;
        vboxCallback->vtbl->OnSessionStateChange        = &vboxCallbackOnSessionStateChange;
        vboxCallback->vtbl->OnSnapshotTaken             = &vboxCallbackOnSnapshotTaken;
6521
# if VBOX_API_VERSION < 3002
6522
        vboxCallback->vtbl->OnSnapshotDiscarded         = &vboxCallbackOnSnapshotDiscarded;
6523 6524 6525
# else /* VBOX_API_VERSION >= 3002 */
        vboxCallback->vtbl->OnSnapshotDeleted           = &vboxCallbackOnSnapshotDiscarded;
# endif /* VBOX_API_VERSION >= 3002 */
6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554
        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) {
6555
    VBOX_OBJECT_CHECK(conn, int, -1);
6556
    int vboxRet          = -1;
6557
    nsresult rc;
6558 6559 6560 6561 6562 6563

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

6564
    if (data->vboxCallback == NULL) {
6565
        data->vboxCallback = vboxAllocCallbackObj();
6566 6567 6568 6569
        if (data->vboxCallback != NULL) {
            rc = data->vboxObj->vtbl->RegisterCallback(data->vboxObj, data->vboxCallback);
            if (NS_SUCCEEDED(rc)) {
                vboxRet = 0;
6570 6571
            }
        }
6572 6573 6574
    } else {
        vboxRet = 0;
    }
6575

6576 6577 6578 6579 6580 6581 6582
    /* 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);
6583

6584 6585
            data->fdWatch = virEventAddHandle(vboxFileHandle, VIR_EVENT_HANDLE_READABLE, vboxReadCallback, NULL, NULL);
        }
6586

6587 6588 6589 6590 6591
        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
             */
6592

6593 6594 6595 6596 6597 6598
            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);
6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615
        }
    }

    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) {
6616
    VBOX_OBJECT_CHECK(conn, int, -1);
6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629

    /* 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);

6630
    if (data->vboxCallback) {
6631 6632 6633
        /* check count here of how many times register was called
         * and only on the last de-register do the un-register call
         */
6634
        if (data->domainEventCallbacks && virDomainEventCallbackListCount(data->domainEventCallbacks) == 0) {
6635
            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
6636
            VBOX_RELEASE(data->vboxCallback);
6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648

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

    vboxDriverUnlock(data);

    return ret;
}

6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 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 6743 6744 6745 6746 6747 6748 6749
static int vboxDomainEventRegisterAny(virConnectPtr conn,
                                      virDomainPtr dom,
                                      int eventID,
                                      virConnectDomainEventGenericCallback callback,
                                      void *opaque,
                                      virFreeCallback freecb) {
    VBOX_OBJECT_CHECK(conn, int, -1);
    int vboxRet          = -1;
    nsresult rc;

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

    if (data->vboxCallback == NULL) {
        data->vboxCallback = vboxAllocCallbackObj();
        if (data->vboxCallback != NULL) {
            rc = data->vboxObj->vtbl->RegisterCallback(data->vboxObj, data->vboxCallback);
            if (NS_SUCCEEDED(rc)) {
                vboxRet = 0;
            }
        }
    } else {
        vboxRet = 0;
    }

    /* 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);

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

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

            ret = virDomainEventCallbackListAddID(conn, data->domainEventCallbacks,
                                                  dom, eventID,
                                                  callback, opaque, freecb);
            DEBUG("virDomainEventCallbackListAddID (ret = %d) ( conn: %p, "
                  "data->domainEventCallbacks: %p, callback: %p, opaque: %p, "
                  "freecb: %p )", ret, conn, data->domainEventCallbacks, callback,
                  opaque, freecb);
        }
    }

    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 vboxDomainEventDeregisterAny(virConnectPtr conn,
                                        int callbackID) {
    VBOX_OBJECT_CHECK(conn, int, -1);

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

    if (data->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDeleteID(conn, data->domainEventCallbacks,
                                                     callbackID);
    else
        ret = virDomainEventCallbackListRemoveID(conn, data->domainEventCallbacks,
                                                 callbackID);

    if (data->vboxCallback) {
        /* 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 && virDomainEventCallbackListCount(data->domainEventCallbacks) == 0) {
            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
            VBOX_RELEASE(data->vboxCallback);

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

    vboxDriverUnlock(data);

    return ret;
}

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

6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767
/**
 * 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;

6768
    DEBUG0("network initialized");
6769 6770 6771 6772 6773 6774 6775 6776
    /* conn->networkPrivateData = some network specific data */
    return VIR_DRV_OPEN_SUCCESS;

cleanup:
    return VIR_DRV_OPEN_DECLINED;
}

static int vboxNetworkClose(virConnectPtr conn) {
6777
    DEBUG0("network uninitialized");
6778 6779 6780 6781 6782
    conn->networkPrivateData = NULL;
    return 0;
}

static int vboxNumOfNetworks(virConnectPtr conn) {
6783
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
6784
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
6785
    int i = 0;
6786

6787
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
6788

6789 6790 6791 6792
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
6793
            PRUint32 interfaceType = 0;
6794

6795
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6796 6797
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
6798

6799
                networkInterface->vtbl->GetStatus(networkInterface, &status);
6800

6801 6802
                if (status == HostNetworkInterfaceStatus_Up)
                    ret++;
6803 6804 6805 6806
            }
        }
    }

6807 6808
    vboxArrayRelease(&networkInterfaces);

6809 6810 6811 6812
    VBOX_RELEASE(host);

    DEBUG("numActive: %d", ret);
    return ret;
6813 6814 6815
}

static int vboxListNetworks(virConnectPtr conn, char **const names, int nnames) {
6816
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
6817
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
6818
    int i = 0;
6819

6820 6821 6822 6823
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

    for (i = 0; (ret < nnames) && (i < networkInterfaces.count); i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];
6824

6825
        if (networkInterface) {
6826
            PRUint32 interfaceType = 0;
6827

6828
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6829

6830 6831
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
6832

6833
                networkInterface->vtbl->GetStatus(networkInterface, &status);
6834

6835 6836 6837
                if (status == HostNetworkInterfaceStatus_Up) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
6838

6839
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
6840
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
6841

6842 6843 6844
                    DEBUG("nnames[%d]: %s", ret, nameUtf8);
                    names[ret] = strdup(nameUtf8);
                    if (names[ret] == NULL) {
6845
                        virReportOOMError();
6846 6847
                    } else {
                        ret++;
6848 6849
                    }

6850 6851
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
6852 6853 6854 6855 6856
                }
            }
        }
    }

6857
    vboxArrayRelease(&networkInterfaces);
6858

6859
    VBOX_RELEASE(host);
6860

6861 6862
    return ret;
}
6863

6864 6865
static int vboxNumOfDefinedNetworks(virConnectPtr conn) {
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
6866
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
6867
    int i = 0;
6868

6869
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
6870

6871 6872 6873 6874
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
6875
            PRUint32 interfaceType = 0;
6876

6877
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6878 6879
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
6880

6881
                networkInterface->vtbl->GetStatus(networkInterface, &status);
6882

6883 6884
                if (status == HostNetworkInterfaceStatus_Down)
                    ret++;
6885 6886 6887 6888
            }
        }
    }

6889 6890
    vboxArrayRelease(&networkInterfaces);

6891 6892 6893 6894
    VBOX_RELEASE(host);

    DEBUG("numActive: %d", ret);
    return ret;
6895 6896 6897
}

static int vboxListDefinedNetworks(virConnectPtr conn, char **const names, int nnames) {
6898
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
6899
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
6900
    int i = 0;
6901

6902 6903 6904 6905
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

    for (i = 0; (ret < nnames) && (i < networkInterfaces.count); i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];
6906

6907
        if (networkInterface) {
6908
            PRUint32 interfaceType = 0;
6909

6910
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6911

6912 6913
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
6914

6915
                networkInterface->vtbl->GetStatus(networkInterface, &status);
6916

6917 6918 6919
                if (status == HostNetworkInterfaceStatus_Down) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
6920

6921
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
6922
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
6923

6924 6925 6926
                    DEBUG("nnames[%d]: %s", ret, nameUtf8);
                    names[ret] = strdup(nameUtf8);
                    if (names[ret] == NULL) {
6927
                        virReportOOMError();
6928 6929
                    } else {
                        ret++;
6930 6931
                    }

6932 6933
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
6934 6935 6936 6937 6938
                }
            }
        }
    }

6939
    vboxArrayRelease(&networkInterfaces);
6940 6941 6942 6943

    VBOX_RELEASE(host);

    return ret;
6944 6945 6946
}

static virNetworkPtr vboxNetworkLookupByUUID(virConnectPtr conn, const unsigned char *uuid) {
6947
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
6948
    vboxIID *iid         = NULL;
6949

6950
#if VBOX_API_VERSION == 2002
6951
    if (VIR_ALLOC(iid) < 0) {
6952
        virReportOOMError();
6953 6954
        goto cleanup;
    }
6955 6956 6957
#endif

    vboxIIDFromUUID(uuid, iid);
6958

6959 6960 6961
    /* TODO: "internal" networks are just strings and
     * thus can't do much with them
     */
6962
    IHostNetworkInterface *networkInterface = NULL;
6963

6964 6965 6966
    host->vtbl->FindHostNetworkInterfaceById(host, iid, &networkInterface);
    if (networkInterface) {
        PRUint32 interfaceType = 0;
6967

6968
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
6969

6970 6971 6972
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            char *nameUtf8       = NULL;
            PRUnichar *nameUtf16 = NULL;
6973

6974 6975
            networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
            VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
6976

6977
            ret = virGetNetwork(conn, nameUtf8, uuid);
6978

6979 6980
            DEBUG("Network Name: %s", nameUtf8);
            DEBUGIID("Network UUID", iid);
6981

6982 6983
            VBOX_UTF8_FREE(nameUtf8);
            VBOX_UTF16_FREE(nameUtf16);
6984
        }
6985 6986

        VBOX_RELEASE(networkInterface);
6987 6988
    }

6989 6990
    VBOX_RELEASE(host);

6991
#if VBOX_API_VERSION == 2002
6992
cleanup:
6993 6994
#endif
    vboxIIDFree(iid);
6995 6996 6997 6998
    return ret;
}

static virNetworkPtr vboxNetworkLookupByName(virConnectPtr conn, const char *name) {
6999 7000 7001
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *nameUtf16                    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7002

7003
    VBOX_UTF8_TO_UTF16(name, &nameUtf16);
7004

7005
    host->vtbl->FindHostNetworkInterfaceByName(host, nameUtf16, &networkInterface);
7006

7007 7008
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7009

7010
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7011

7012 7013 7014
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            unsigned char uuid[VIR_UUID_BUFLEN];
            vboxIID *iid = NULL;
7015

7016 7017 7018 7019
            networkInterface->vtbl->GetId(networkInterface, &iid);
            vboxIIDToUUID(uuid, iid);
            ret = virGetNetwork(conn, name, uuid);
            DEBUG("Network Name: %s", name);
7020

7021 7022
            DEBUGIID("Network UUID", iid);
            vboxIIDUnalloc(iid);
7023
        }
7024 7025

        VBOX_RELEASE(networkInterface);
7026 7027
    }

7028 7029 7030
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(host);

7031 7032 7033
    return ret;
}

7034
static virNetworkPtr vboxNetworkDefineCreateXML(virConnectPtr conn, const char *xml, bool start) {
7035 7036 7037 7038
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    char      *networkInterfaceNameUtf8     = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7039

7040
    virNetworkDefPtr def = virNetworkDefParseString(xml);
7041 7042
    virNetworkIpDefPtr ipdef;
    virSocketAddr netmask;
7043

7044
    if (   (!def)
7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057
        || (def->forwardType != VIR_NETWORK_FORWARD_NONE)
        || (def->nips == 0 || !def->ips))
        goto cleanup;

    /* Look for the first IPv4 IP address definition and use that.
     * If there weren't any IPv4 addresses, ignore the network (since it's
     * required below to have an IPv4 address)
    */
    ipdef = virNetworkDefGetIpByIndex(def, AF_INET, 0);
    if (!ipdef)
        goto cleanup;

    if (virNetworkIpDefNetmask(ipdef, &netmask) < 0)
7058
        goto cleanup;
7059

7060 7061 7062 7063 7064 7065
    /* 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.
     */
7066

7067
#if VBOX_API_VERSION == 2002
7068 7069
    if STREQ(def->name, "vboxnet0") {
        PRUint32 interfaceType = 0;
7070

7071 7072
        VBOX_UTF8_TO_UTF16(def->name, &networkInterfaceNameUtf16);
        host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7073

7074 7075 7076 7077 7078 7079
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
        if (interfaceType != HostNetworkInterfaceType_HostOnly) {
            VBOX_RELEASE(networkInterface);
            networkInterface = NULL;
        }
    }
7080
#else /* VBOX_API_VERSION != 2002 */
7081 7082
    IProgress *progress = NULL;
    host->vtbl->CreateHostOnlyNetworkInterface(host, &networkInterface, &progress);
7083

7084 7085 7086 7087
    if (progress) {
        progress->vtbl->WaitForCompletion(progress, -1);
        VBOX_RELEASE(progress);
    }
7088
#endif /* VBOX_API_VERSION != 2002 */
7089

7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102
    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);
7103
                virReportOOMError();
7104 7105 7106
                goto cleanup;
            }
        }
7107

7108
        VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
7109

7110 7111 7112
        /* Currently support only one dhcp server per network
         * with contigious address space from start to end
         */
7113 7114 7115
        if ((ipdef->nranges >= 1) &&
            VIR_SOCKET_HAS_ADDR(&ipdef->ranges[0].start) &&
            VIR_SOCKET_HAS_ADDR(&ipdef->ranges[0].end)) {
7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134
            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;

7135 7136 7137 7138
                ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->address);
                networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
                fromIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].start);
                toIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].end);
7139 7140 7141 7142 7143 7144 7145 7146 7147 7148

                if (ipAddressUtf16 == NULL || networkMaskUtf16 == NULL ||
                    fromIPAddressUtf16 == NULL || toIPAddressUtf16 == NULL) {
                    VBOX_UTF16_FREE(ipAddressUtf16);
                    VBOX_UTF16_FREE(networkMaskUtf16);
                    VBOX_UTF16_FREE(fromIPAddressUtf16);
                    VBOX_UTF16_FREE(toIPAddressUtf16);
                    VBOX_RELEASE(dhcpServer);
                    goto cleanup;
                }
7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173

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

7175 7176
        if ((ipdef->nhosts >= 1) &&
            VIR_SOCKET_HAS_ADDR(&ipdef->hosts[0].ip)) {
7177 7178
            PRUnichar *ipAddressUtf16   = NULL;
            PRUnichar *networkMaskUtf16 = NULL;
7179

7180 7181
            ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->hosts[0].ip);
            networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
7182 7183 7184 7185 7186 7187

            if (ipAddressUtf16 == NULL || networkMaskUtf16 == NULL) {
                VBOX_UTF16_FREE(ipAddressUtf16);
                VBOX_UTF16_FREE(networkMaskUtf16);
                goto cleanup;
            }
7188

7189 7190 7191 7192 7193 7194 7195
            /* 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);
7196

7197 7198 7199 7200 7201 7202
            VBOX_UTF16_FREE(ipAddressUtf16);
            VBOX_UTF16_FREE(networkMaskUtf16);
        } else {
            networkInterface->vtbl->EnableDynamicIpConfig(networkInterface);
            networkInterface->vtbl->DhcpRediscover(networkInterface);
        }
7203

7204 7205 7206 7207 7208 7209
        networkInterface->vtbl->GetId(networkInterface, &vboxnetiid);
        if (vboxnetiid) {
            vboxIIDToUUID(uuid, vboxnetiid);
            DEBUGIID("Real Network UUID", vboxnetiid);
            vboxIIDUnalloc(vboxnetiid);
            ret = virGetNetwork(conn, networkInterfaceNameUtf8, uuid);
7210
        }
7211 7212 7213 7214

        VIR_FREE(networkNameUtf8);
        VBOX_UTF16_FREE(networkNameUtf16);
        VBOX_RELEASE(networkInterface);
7215 7216
    }

7217 7218 7219 7220
    VBOX_UTF8_FREE(networkInterfaceNameUtf8);
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7221 7222 7223 7224 7225
cleanup:
    virNetworkDefFree(def);
    return ret;
}

7226 7227 7228 7229 7230 7231 7232 7233
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);
}

7234
static int vboxNetworkUndefineDestroy(virNetworkPtr network, bool removeinterface) {
7235
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246
    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) {
7247
        virReportOOMError();
7248 7249 7250
        goto cleanup;
    }

7251 7252
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7253

7254
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
7255

7256
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7257

7258 7259
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7260

7261
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7262

7263 7264 7265
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
7266

7267
#if VBOX_API_VERSION != 2002
7268 7269 7270
            if (removeinterface) {
                PRUnichar *iidUtf16 = NULL;
                IProgress *progress = NULL;
7271

7272
                networkInterface->vtbl->GetId(networkInterface, &iidUtf16);
7273

7274
                if (iidUtf16) {
7275
# if VBOX_API_VERSION == 3000
7276 7277 7278
                    IHostNetworkInterface *netInt = NULL;
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &netInt, &progress);
                    VBOX_RELEASE(netInt);
7279
# else  /* VBOX_API_VERSION > 3000 */
7280
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &progress);
7281
# endif /* VBOX_API_VERSION > 3000 */
7282 7283
                    VBOX_UTF16_FREE(iidUtf16);
                }
7284

7285 7286 7287 7288 7289
                if (progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                }
            }
7290 7291
#endif /* VBOX_API_VERSION != 2002 */

7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302
            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);
7303 7304
            }

7305 7306
            VBOX_UTF16_FREE(networkNameUtf16);

7307
        }
7308
        VBOX_RELEASE(networkInterface);
7309 7310
    }

7311 7312 7313
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7314 7315 7316 7317 7318 7319 7320
    ret = 0;

cleanup:
    VIR_FREE(networkNameUtf8);
    return ret;
}

7321 7322 7323 7324
static int vboxNetworkUndefine(virNetworkPtr network) {
    return vboxNetworkUndefineDestroy(network, true);
}

7325
static int vboxNetworkCreate(virNetworkPtr network) {
7326
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
7327 7328 7329 7330 7331 7332 7333 7334 7335 7336
    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) {
7337
        virReportOOMError();
7338 7339 7340
        goto cleanup;
    }

7341 7342
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7343

7344
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
7345

7346
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7347

7348 7349
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7350

7351
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7352

7353 7354 7355
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
7356 7357


7358
            VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
7359

7360 7361 7362 7363 7364
            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (dhcpServer) {
                PRUnichar *trunkTypeUtf16 = NULL;
7365

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

7368
                VBOX_UTF8_TO_UTF16("netflt", &trunkTypeUtf16);
7369

7370 7371 7372 7373
                dhcpServer->vtbl->Start(dhcpServer,
                                        networkNameUtf16,
                                        networkInterfaceNameUtf16,
                                        trunkTypeUtf16);
7374

7375 7376
                VBOX_UTF16_FREE(trunkTypeUtf16);
                VBOX_RELEASE(dhcpServer);
7377 7378
            }

7379
            VBOX_UTF16_FREE(networkNameUtf16);
7380
        }
7381 7382

        VBOX_RELEASE(networkInterface);
7383 7384
    }

7385 7386 7387
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7388 7389 7390 7391 7392 7393 7394 7395
    ret = 0;

cleanup:
    VIR_FREE(networkNameUtf8);
    return ret;
}

static int vboxNetworkDestroy(virNetworkPtr network) {
7396
    return vboxNetworkUndefineDestroy(network, false);
7397 7398 7399
}

static char *vboxNetworkDumpXML(virNetworkPtr network, int flags ATTRIBUTE_UNUSED) {
7400
    VBOX_OBJECT_HOST_CHECK(network->conn, char *, NULL);
7401
    virNetworkDefPtr def  = NULL;
7402
    virNetworkIpDefPtr ipdef = NULL;
7403 7404 7405
    char *networkNameUtf8 = NULL;

    if (VIR_ALLOC(def) < 0) {
7406
        virReportOOMError();
7407 7408
        goto cleanup;
    }
7409 7410 7411 7412 7413 7414
    if (VIR_ALLOC(ipdef) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    def->ips = ipdef;
    def->nips = 1;
7415 7416

    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0) {
7417
        virReportOOMError();
7418 7419 7420
        goto cleanup;
    }

7421 7422
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7423

7424
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
7425

7426
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7427

7428 7429
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7430

7431
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7432

7433 7434 7435 7436 7437 7438
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            def->name = strdup(network->name);
            if (def->name != NULL) {
                PRUnichar *networkNameUtf16 = NULL;
                IDHCPServer *dhcpServer     = NULL;
                vboxIID *vboxnet0IID        = NULL;
7439

7440 7441
                networkInterface->vtbl->GetId(networkInterface, &vboxnet0IID);
                vboxIIDToUUID(def->uuid, vboxnet0IID);
7442

7443
                VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
7444

7445
                def->forwardType = VIR_NETWORK_FORWARD_NONE;
7446

7447 7448 7449 7450
                data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                                 networkNameUtf16,
                                                                 &dhcpServer);
                if (dhcpServer) {
7451 7452
                    ipdef->nranges = 1;
                    if (VIR_ALLOC_N(ipdef->ranges, ipdef->nranges) >=0 ) {
7453 7454 7455 7456
                        PRUnichar *ipAddressUtf16     = NULL;
                        PRUnichar *networkMaskUtf16   = NULL;
                        PRUnichar *fromIPAddressUtf16 = NULL;
                        PRUnichar *toIPAddressUtf16   = NULL;
7457
                        bool errorOccurred = false;
7458

7459 7460 7461 7462 7463 7464 7465
                        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
                         */
7466
                        if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
7467
                                                     &ipdef->address) < 0 ||
7468
                            vboxSocketParseAddrUtf16(data, networkMaskUtf16,
7469
                                                     &ipdef->netmask) < 0 ||
7470
                            vboxSocketParseAddrUtf16(data, fromIPAddressUtf16,
7471
                                                     &ipdef->ranges[0].start) < 0 ||
7472
                            vboxSocketParseAddrUtf16(data, toIPAddressUtf16,
7473
                                                     &ipdef->ranges[0].end) < 0) {
7474 7475
                            errorOccurred = true;
                        }
7476 7477 7478 7479 7480

                        VBOX_UTF16_FREE(ipAddressUtf16);
                        VBOX_UTF16_FREE(networkMaskUtf16);
                        VBOX_UTF16_FREE(fromIPAddressUtf16);
                        VBOX_UTF16_FREE(toIPAddressUtf16);
7481 7482 7483 7484

                        if (errorOccurred) {
                            goto cleanup;
                        }
7485
                    } else {
7486
                        ipdef->nranges = 0;
7487
                        virReportOOMError();
7488
                    }
7489

7490 7491 7492 7493 7494 7495
                    ipdef->nhosts = 1;
                    if (VIR_ALLOC_N(ipdef->hosts, ipdef->nhosts) >=0 ) {
                        ipdef->hosts[0].name = strdup(network->name);
                        if (ipdef->hosts[0].name == NULL) {
                            VIR_FREE(ipdef->hosts);
                            ipdef->nhosts = 0;
7496
                            virReportOOMError();
7497
                        } else {
7498 7499
                            PRUnichar *macAddressUtf16 = NULL;
                            PRUnichar *ipAddressUtf16  = NULL;
7500
                            bool errorOccurred = false;
7501

7502
                            networkInterface->vtbl->GetHardwareAddress(networkInterface, &macAddressUtf16);
7503 7504
                            networkInterface->vtbl->GetIPAddress(networkInterface, &ipAddressUtf16);

7505
                            VBOX_UTF16_TO_UTF8(macAddressUtf16, &ipdef->hosts[0].mac);
7506 7507

                            if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
7508
                                                         &ipdef->hosts[0].ip) < 0) {
7509 7510
                                errorOccurred = true;
                            }
7511

7512 7513
                            VBOX_UTF16_FREE(macAddressUtf16);
                            VBOX_UTF16_FREE(ipAddressUtf16);
7514 7515 7516 7517

                            if (errorOccurred) {
                                goto cleanup;
                            }
7518 7519
                        }
                    } else {
7520
                        ipdef->nhosts = 0;
7521
                    }
7522 7523 7524 7525 7526

                    VBOX_RELEASE(dhcpServer);
                } else {
                    PRUnichar *networkMaskUtf16 = NULL;
                    PRUnichar *ipAddressUtf16   = NULL;
7527
                    bool errorOccurred = false;
7528 7529 7530 7531

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

7532
                    if (vboxSocketParseAddrUtf16(data, networkMaskUtf16,
7533
                                                 &ipdef->netmask) < 0 ||
7534
                        vboxSocketParseAddrUtf16(data, ipAddressUtf16,
7535
                                                 &ipdef->address) < 0) {
7536 7537
                        errorOccurred = true;
                    }
7538 7539 7540

                    VBOX_UTF16_FREE(networkMaskUtf16);
                    VBOX_UTF16_FREE(ipAddressUtf16);
7541 7542 7543 7544

                    if (errorOccurred) {
                        goto cleanup;
                    }
7545 7546
                }

7547 7548 7549 7550
                DEBUGIID("Network UUID", vboxnet0IID);
                vboxIIDUnalloc(vboxnet0IID);
                VBOX_UTF16_FREE(networkNameUtf16);
            } else {
7551
                virReportOOMError();
7552 7553
            }
        }
7554 7555

        VBOX_RELEASE(networkInterface);
7556 7557
    }

7558 7559 7560
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7561
    ret = virNetworkDefFormat(def);
7562 7563

cleanup:
7564
    virNetworkDefFree(def);
7565 7566 7567 7568
    VIR_FREE(networkNameUtf8);
    return ret;
}

7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579 7580 7581 7582 7583 7584 7585
/**
 * 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;

7586
    DEBUG0("vbox storage initialized");
7587 7588 7589 7590 7591 7592 7593 7594
    /* conn->storagePrivateData = some storage specific data */
    return VIR_DRV_OPEN_SUCCESS;

cleanup:
    return VIR_DRV_OPEN_DECLINED;
}

static int vboxStorageClose (virConnectPtr conn) {
7595
    DEBUG0("vbox storage uninitialized");
7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608
    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;
}

7609 7610
static int vboxStorageListPools(virConnectPtr conn ATTRIBUTE_UNUSED,
                                char **const names, int nnames) {
7611 7612 7613 7614 7615
    int numActive = 0;

    if (nnames == 1) {
        names[numActive] = strdup("default-pool");
        if (names[numActive] == NULL) {
7616
            virReportOOMError();
7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643
        } 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) {
7644
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
7645
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
7646 7647 7648 7649
    PRUint32 hardDiskAccessible = 0;
    nsresult rc;
    int i;

7650
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
7651
    if (NS_SUCCEEDED(rc)) {
7652 7653
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
7654 7655
            if (hardDisk) {
                PRUint32 hddstate;
7656

7657 7658 7659
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible)
                    hardDiskAccessible++;
7660 7661
            }
        }
7662 7663 7664 7665

        vboxArrayRelease(&hardDisks);

        ret = hardDiskAccessible;
7666
    } else {
7667
        ret = -1;
7668 7669
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not get number of volumes in the pool: %s, rc=%08x"),
7670
                  pool->name, (unsigned)rc);
7671 7672
    }

7673
    return ret;
7674 7675 7676
}

static int vboxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names, int nnames) {
7677
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
7678
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
7679 7680 7681 7682
    PRUint32 numActive     = 0;
    nsresult rc;
    int i;

7683
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
7684
    if (NS_SUCCEEDED(rc)) {
7685 7686
        for (i = 0; i < hardDisks.count && numActive < nnames; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
7687

7688 7689 7690 7691
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
7692

7693 7694 7695
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
7696

7697 7698
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
7699

7700 7701 7702 7703
                    if (nameUtf8) {
                        DEBUG("nnames[%d]: %s", numActive, nameUtf8);
                        names[numActive] = strdup(nameUtf8);
                        if (names[numActive] == NULL) {
7704
                            virReportOOMError();
7705 7706
                        } else {
                            numActive++;
7707
                        }
7708 7709

                        VBOX_UTF8_FREE(nameUtf8);
7710 7711 7712 7713
                    }
                }
            }
        }
7714 7715 7716 7717

        vboxArrayRelease(&hardDisks);

        ret = numActive;
7718
    } else {
7719
        ret = -1;
7720 7721
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not get the volume list in the pool: %s, rc=%08x"),
7722
                  pool->name, (unsigned)rc);
7723 7724
    }

7725
    return ret;
7726 7727 7728
}

static virStorageVolPtr vboxStorageVolLookupByName(virStoragePoolPtr pool, const char *name) {
7729
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
7730
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
7731 7732 7733
    nsresult rc;
    int i;

7734 7735
    if(!name)
        return ret;
7736

7737
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
7738
    if (NS_SUCCEEDED(rc)) {
7739 7740
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
7741

7742 7743 7744 7745
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
7746

7747 7748 7749
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
7750

7751 7752 7753 7754
                    if (nameUtf16) {
                        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                        VBOX_UTF16_FREE(nameUtf16);
                    }
7755

7756 7757 7758
                    if (nameUtf8 && STREQ(nameUtf8, name)) {
                        vboxIID *hddIID     = NULL;
                        char    *hddIIDUtf8 = NULL;
7759

7760
                        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID);
7761

7762
                        if (hddIID) {
7763
                            vboxIIDtoUtf8(hddIID, &hddIIDUtf8);
7764 7765
                            vboxIIDUnalloc(hddIID);
                        }
7766

7767
                        if (hddIIDUtf8) {
7768

7769
                            ret = virGetStorageVol(pool->conn, pool->name, name, hddIIDUtf8);
7770

7771 7772 7773 7774
                            DEBUG("virStorageVolPtr: %p", ret);
                            DEBUG("Storage Volume Name: %s", name);
                            DEBUG("Storage Volume key : %s", hddIIDUtf8);
                            DEBUG("Storage Volume Pool: %s", pool->name);
7775

7776
                            vboxIIDUtf8Free(hddIIDUtf8);
7777 7778
                        }

7779 7780
                        VBOX_UTF8_FREE(nameUtf8);
                        break;
7781
                    }
7782 7783 7784

                    if (nameUtf8)
                        VBOX_UTF8_FREE(nameUtf8);
7785 7786 7787
                }
            }
        }
7788

7789
        vboxArrayRelease(&hardDisks);
7790 7791 7792 7793 7794 7795
    }

    return ret;
}

static virStorageVolPtr vboxStorageVolLookupByKey(virConnectPtr conn, const char *key) {
7796
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
7797 7798 7799 7800
    vboxIID   *hddIID    = NULL;
    IHardDisk *hardDisk  = NULL;
    nsresult rc;

7801 7802 7803
    if (!key)
        return ret;

7804
#if VBOX_API_VERSION == 2002
7805

7806
    if (VIR_ALLOC(hddIID) < 0) {
7807
        virReportOOMError();
7808 7809 7810
        goto cleanup;
    }

7811 7812 7813 7814
    unsigned char hddUUID[VIR_UUID_BUFLEN];

    virUUIDParse(key, hddUUID);
    vboxIIDFromUUID(hddUUID, hddIID);
7815 7816 7817

#else  /* VBOX_API_VERSION != 2002 */

7818 7819 7820
    VBOX_UTF8_TO_UTF16(key, &hddIID);
    if (!hddIID)
        return ret;
7821

7822
#endif /* VBOX_API_VERSION != 2002 */
7823

7824 7825 7826
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
7827

7828 7829 7830 7831
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
7832

7833 7834
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
7835

7836 7837 7838 7839 7840 7841 7842 7843
            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
                     */
7844 7845
                }

7846 7847 7848 7849 7850
                DEBUG("Storage Volume Name: %s", key);
                DEBUG("Storage Volume key : %s", hddNameUtf8);

                VBOX_UTF8_FREE(hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
7851 7852
            }
        }
7853 7854

        VBOX_MEDIUM_RELEASE(hardDisk);
7855 7856 7857 7858
    }

#if VBOX_API_VERSION == 2002
cleanup:
7859
#endif  /* VBOX_API_VERSION == 2002 */
7860 7861 7862 7863 7864
    vboxIIDFree(hddIID);
    return ret;
}

static virStorageVolPtr vboxStorageVolLookupByPath(virConnectPtr conn, const char *path) {
7865
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
7866 7867 7868 7869
    PRUnichar *hddPathUtf16 = NULL;
    IHardDisk *hardDisk     = NULL;
    nsresult rc;

7870 7871
    if (!path)
        return ret;
7872

7873
    VBOX_UTF8_TO_UTF16(path, &hddPathUtf16);
7874

7875 7876
    if (!hddPathUtf16)
        return ret;
7877

7878 7879 7880
    rc = data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddPathUtf16, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
7881

7882 7883 7884 7885 7886 7887
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
            vboxIID   *hddIID       = NULL;
            char      *hddIIDUtf8   = NULL;
7888

7889 7890
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID);
7891

7892 7893 7894 7895
            if (hddNameUtf16) {
                VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
            }
7896

7897
            if (hddIID) {
7898
                vboxIIDtoUtf8(hddIID, &hddIIDUtf8);
7899 7900
                vboxIIDUnalloc(hddIID);
            }
7901

7902
            if (hddIIDUtf8 && hddNameUtf8) {
7903

7904 7905 7906 7907 7908
                /* 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);
7909

7910 7911 7912
                DEBUG("Storage Volume Pool: %s", "default-pool");
                DEBUG("Storage Volume Name: %s", hddNameUtf8);
                DEBUG("Storage Volume key : %s", hddIIDUtf8);
7913 7914 7915

            }

7916 7917 7918 7919 7920
            if (hddNameUtf8)
                VBOX_UTF8_FREE(hddNameUtf8);

            if (hddIIDUtf8)
                vboxIIDUtf8Free(hddIIDUtf8);
7921
        }
7922 7923

        VBOX_MEDIUM_RELEASE(hardDisk);
7924 7925
    }

7926 7927
    VBOX_UTF16_FREE(hddPathUtf16);

7928 7929 7930 7931 7932 7933
    return ret;
}

static virStorageVolPtr vboxStorageVolCreateXML(virStoragePoolPtr pool,
                                                const char *xml,
                                                unsigned int flags ATTRIBUTE_UNUSED) {
7934
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
7935
    virStorageVolDefPtr  def  = NULL;
7936 7937
    PRUnichar *hddFormatUtf16 = NULL;
    PRUnichar *hddNameUtf16   = NULL;
7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948
    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;

7949
    if ((def = virStorageVolDefParseString(&poolDef, xml)) == NULL)
7950 7951
        goto cleanup;

7952 7953 7954
    if (   !def->name
        || (def->type != VIR_STORAGE_VOL_FILE))
        goto cleanup;
7955

7956 7957 7958 7959 7960 7961
    /* 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
     */
7962

7963 7964 7965 7966 7967 7968 7969
    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);
    }
7970

7971
    VBOX_UTF8_TO_UTF16(def->name, &hddNameUtf16);
7972

7973 7974
    if (hddFormatUtf16 && hddNameUtf16) {
        IHardDisk *hardDisk = NULL;
7975

7976 7977 7978 7979 7980
        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;
7981

7982 7983
            if (def->capacity == def->allocation)
                variant = HardDiskVariant_Fixed;
7984

7985 7986 7987
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, variant, &progress);
            if (NS_SUCCEEDED(rc) && progress) {
                vboxIID *hddIID = NULL;
7988
#if VBOX_API_VERSION == 2002
7989
                nsresult resultCode;
7990
#else
7991
                PRInt32  resultCode;
7992 7993
#endif

7994 7995
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
7996

7997
                if (NS_SUCCEEDED(resultCode)) {
7998

7999 8000 8001
                    rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID);
                    if (NS_SUCCEEDED(rc)) {
                        char *hddKey = NULL;
8002

8003
                        vboxIIDtoUtf8(hddIID, &hddKey);
8004

8005 8006
                        if (hddKey)
                            ret = virGetStorageVol(pool->conn, pool->name, def->name, hddKey);
8007

8008 8009
                        vboxIIDUtf8Free(hddKey);
                        vboxIIDUnalloc(hddIID);
8010 8011 8012
                    }
                }

8013
                VBOX_RELEASE(progress);
8014 8015
            }

8016
        }
8017 8018
    }

8019 8020 8021
    VBOX_UTF16_FREE(hddFormatUtf16);
    VBOX_UTF16_FREE(hddNameUtf16);

8022 8023 8024 8025 8026 8027 8028
cleanup:
    virStorageVolDefFree(def);
    return ret;
}

static int vboxStorageVolDelete(virStorageVolPtr vol,
                                unsigned int flags ATTRIBUTE_UNUSED) {
8029
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
8030 8031 8032 8033
    vboxIID   *hddIID    = NULL;
    IHardDisk *hardDisk  = NULL;
    int deregister = 0;
    nsresult rc;
8034 8035
    int i = 0;
    int j = 0;
8036

8037
    vboxUtf8toIID(vol->key, &hddIID);
8038 8039
    if (!hddIID)
        return ret;
8040

8041 8042 8043
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8044

8045 8046 8047
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint32  machineIdsSize = 0;
8048 8049 8050 8051 8052 8053 8054
            vboxArray machineIds = VBOX_ARRAY_INITIALIZER;

#if VBOX_API_VERSION < 3001
            vboxArrayGet(&machineIds, hardDisk, hardDisk->vtbl->imedium.GetMachineIds);
#else  /* VBOX_API_VERSION >= 3001 */
            vboxArrayGet(&machineIds, hardDisk, hardDisk->vtbl->GetMachineIds);
#endif /* VBOX_API_VERSION >= 3001 */
8055

8056
            machineIdsSize = machineIds.count;
8057

8058
            for (i = 0; i < machineIds.count; i++) {
8059
                IMachine *machine = NULL;
8060
                vboxIID *machineId = machineIds.items[i];
8061

8062
                rc = data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, machineId);
8063
                if (NS_SUCCEEDED(rc)) {
8064

8065 8066
                    rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                    if (NS_SUCCEEDED(rc)) {
8067
                        vboxArray hddAttachments = VBOX_ARRAY_INITIALIZER;
8068 8069

#if VBOX_API_VERSION < 3001
8070 8071
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetHardDiskAttachments);
8072
#else  /* VBOX_API_VERSION >= 3001 */
8073 8074
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetMediumAttachments);
8075
#endif /* VBOX_API_VERSION >= 3001 */
8076 8077
                        for (j = 0; j < hddAttachments.count; j++) {
                            IHardDiskAttachment *hddAttachment = hddAttachments.items[j];
8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115

                            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");
                                            }
8116

8117 8118 8119
                                            if (NS_SUCCEEDED(rc)) {
                                                deregister++;
                                                DEBUG("deregistering hdd:%d", deregister);
8120
                                            }
8121 8122 8123

                                            if (controller)
                                                VBOX_UTF16_FREE(controller);
8124
                                        }
8125
                                        vboxIIDUnalloc(iid);
8126
                                    }
8127
                                    VBOX_MEDIUM_RELEASE(hdd);
8128 8129 8130
                                }
                            }
                        }
8131
                        vboxArrayRelease(&hddAttachments);
8132
                        VBOX_RELEASE(machine);
8133
                    }
8134 8135 8136
                    data->vboxSession->vtbl->Close(data->vboxSession);
                }
            }
8137

8138
            vboxArrayUnalloc(&machineIds);
8139

8140 8141
            if (machineIdsSize == 0 || machineIdsSize == deregister) {
                IProgress *progress = NULL;
8142

8143
                rc = hardDisk->vtbl->DeleteStorage(hardDisk, &progress);
8144

8145 8146 8147 8148 8149
                if (NS_SUCCEEDED(rc) && progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                    DEBUGIID("HardDisk deleted, UUID", hddIID);
                    ret = 0;
8150 8151 8152 8153
                }
            }

        }
8154 8155

        VBOX_MEDIUM_RELEASE(hardDisk);
8156 8157
    }

8158 8159
    vboxIIDUtf16Free(hddIID);

8160 8161 8162 8163
    return ret;
}

static int vboxStorageVolGetInfo(virStorageVolPtr vol, virStorageVolInfoPtr info) {
8164
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
8165 8166 8167 8168
    IHardDisk *hardDisk  = NULL;
    vboxIID   *hddIID    = NULL;
    nsresult rc;

8169
    if (!info)
8170
        return ret;
8171

8172
    vboxUtf8toIID(vol->key, &hddIID);
8173 8174
    if (!hddIID)
        return ret;
8175

8176 8177 8178
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8179

8180 8181 8182 8183
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
8184

8185
            info->type = VIR_STORAGE_VOL_FILE;
8186

8187 8188
            hardDisk->vtbl->GetLogicalSize(hardDisk, &hddLogicalSize);
            info->capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
8189

8190 8191
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            info->allocation = hddActualSize;
8192

8193
            ret = 0;
8194

8195 8196 8197 8198
            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);
8199
        }
8200 8201

        VBOX_MEDIUM_RELEASE(hardDisk);
8202 8203
    }

8204 8205
    vboxIIDUtf16Free(hddIID);

8206 8207 8208 8209
    return ret;
}

static char *vboxStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags ATTRIBUTE_UNUSED) {
8210
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
8211 8212 8213 8214 8215 8216 8217 8218 8219 8220
    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));

8221
    vboxUtf8toIID(vol->key, &hddIID);
8222 8223
    if (!hddIID)
        return ret;
8224

8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276
    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;
8277
                    else
8278
                        def.target.format = VIR_STORAGE_FILE_RAW;
8279

8280 8281 8282
                    /* TODO: need to add vdi to enum virStorageFileFormat {}
                     * and then add it here
                     */
8283

8284
                    VBOX_UTF8_FREE(hddFormatUtf8);
8285 8286
                }

8287 8288 8289
                VBOX_UTF16_FREE(hddFormatUtf16);
            } else {
                defOk = 0;
8290 8291
            }
        }
8292 8293

        VBOX_MEDIUM_RELEASE(hardDisk);
8294 8295
    }

8296 8297
    vboxIIDUtf16Free(hddIID);

8298
    if (defOk)
8299
        ret = virStorageVolDefFormat(&pool, &def);
8300 8301 8302 8303 8304

    return ret;
}

static char *vboxStorageVolGetPath(virStorageVolPtr vol) {
8305
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
8306 8307 8308 8309
    IHardDisk *hardDisk  = NULL;
    vboxIID   *hddIID    = NULL;
    nsresult rc;

8310
    vboxUtf8toIID(vol->key, &hddIID);
8311 8312
    if (!hddIID)
        return ret;
8313

8314 8315 8316
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID, &hardDisk);
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8317

8318 8319 8320 8321
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddLocationUtf16 = NULL;
            char      *hddLocationUtf8  = NULL;
8322

8323
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetLocation, &hddLocationUtf16);
8324

8325 8326
            VBOX_UTF16_TO_UTF8(hddLocationUtf16, &hddLocationUtf8);
            if (hddLocationUtf8) {
8327

8328 8329
                ret = strdup(hddLocationUtf8);
                if (!ret)
8330
                    virReportOOMError();
8331

8332 8333 8334
                DEBUG("Storage Volume Name: %s", vol->name);
                DEBUG("Storage Volume Path: %s", hddLocationUtf8);
                DEBUG("Storage Volume Pool: %s", vol->pool);
8335

8336
                VBOX_UTF8_FREE(hddLocationUtf8);
8337 8338
            }

8339
            VBOX_UTF16_FREE(hddLocationUtf16);
8340
        }
8341 8342

        VBOX_MEDIUM_RELEASE(hardDisk);
8343 8344
    }

8345 8346
    vboxIIDUtf16Free(hddIID);

8347 8348
    return ret;
}
8349 8350 8351 8352 8353

/**
 * Function Tables
 */

8354 8355 8356
virDriver NAME(Driver) = {
    VIR_DRV_VBOX,
    "VBOX",
8357 8358 8359 8360 8361
    vboxOpen, /* open */
    vboxClose, /* close */
    NULL, /* supports_feature */
    NULL, /* type */
    vboxGetVersion, /* version */
8362
    NULL, /* libvirtVersion (impl. in libvirt.c) */
8363
    virGetHostname, /* getHostname */
8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385
    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 */
8386
    vboxDomainSetVcpus, /* domainSetVcpus */
8387 8388
    vboxDomainSetVcpusFlags, /* domainSetVcpusFlags */
    vboxDomainGetVcpusFlags, /* domainGetVcpusFlags */
8389 8390
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
8391
    vboxDomainGetMaxVcpus, /* domainGetMaxVcpus */
8392 8393 8394
    NULL, /* domainGetSecurityLabel */
    NULL, /* nodeGetSecurityModel */
    vboxDomainDumpXML, /* domainDumpXML */
8395 8396
    NULL, /* domainXMLFromNative */
    NULL, /* domainXMLToNative */
8397 8398 8399
    vboxListDefinedDomains, /* listDefinedDomains */
    vboxNumOfDefinedDomains, /* numOfDefinedDomains */
    vboxDomainCreate, /* domainCreate */
8400
    vboxDomainCreateWithFlags, /* domainCreateWithFlags */
8401 8402 8403
    vboxDomainDefineXML, /* domainDefineXML */
    vboxDomainUndefine, /* domainUndefine */
    vboxDomainAttachDevice, /* domainAttachDevice */
8404
    vboxDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
8405
    vboxDomainDetachDevice, /* domainDetachDevice */
8406
    vboxDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
8407
    vboxDomainUpdateDeviceFlags, /* domainUpdateDeviceFlags */
8408 8409 8410 8411 8412 8413 8414 8415 8416 8417
    NULL, /* domainGetAutostart */
    NULL, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
    NULL, /* domainBlockStats */
    NULL, /* domainInterfaceStats */
8418
    NULL, /* domainMemoryStats */
8419 8420
    NULL, /* domainBlockPeek */
    NULL, /* domainMemoryPeek */
8421
    NULL, /* domainGetBlockInfo */
8422 8423
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
8424
#if VBOX_API_VERSION == 2002
8425 8426
    NULL, /* domainEventRegister */
    NULL, /* domainEventDeregister */
8427 8428 8429 8430
#else
    vboxDomainEventRegister, /* domainEventRegister */
    vboxDomainEventDeregister, /* domainEventDeregister */
#endif
8431 8432 8433 8434 8435
    NULL, /* domainMigratePrepare2 */
    NULL, /* domainMigrateFinish2 */
    NULL, /* nodeDeviceDettach */
    NULL, /* nodeDeviceReAttach */
    NULL, /* nodeDeviceReset */
C
Chris Lalancette 已提交
8436
    NULL, /* domainMigratePrepareTunnel */
8437 8438 8439 8440
    vboxIsEncrypted, /* isEncrypted */
    vboxIsSecure, /* isSecure */
    vboxDomainIsActive, /* domainIsActive */
    vboxDomainIsPersistent, /* domainIsPersistent */
8441
    vboxDomainIsUpdated, /* domainIsUpdated */
J
Jiri Denemark 已提交
8442
    NULL, /* cpuCompare */
8443
    NULL, /* cpuBaseline */
8444
    NULL, /* domainGetJobInfo */
8445
    NULL, /* domainAbortJob */
8446
    NULL, /* domainMigrateSetMaxDowntime */
8447
#if VBOX_API_VERSION == 2002
8448 8449
    NULL, /* domainEventRegisterAny */
    NULL, /* domainEventDeregisterAny */
8450 8451 8452 8453
#else
    vboxDomainEventRegisterAny, /* domainEventRegisterAny */
    vboxDomainEventDeregisterAny, /* domainEventDeregisterAny */
#endif
8454 8455 8456
    NULL, /* domainManagedSave */
    NULL, /* domainHasManagedSaveImage */
    NULL, /* domainManagedSaveRemove */
J
Jiri Denemark 已提交
8457 8458 8459 8460 8461 8462 8463 8464 8465
    vboxDomainSnapshotCreateXML, /* domainSnapshotCreateXML */
    vboxDomainSnapshotDumpXML, /* domainSnapshotDumpXML */
    vboxDomainSnapshotNum, /* domainSnapshotNum */
    vboxDomainSnapshotListNames, /* domainSnapshotListNames */
    vboxDomainSnapshotLookupByName, /* domainSnapshotLookupByName */
    vboxDomainHasCurrentSnapshot, /* domainHasCurrentSnapshot */
    vboxDomainSnapshotCurrent, /* domainSnapshotCurrent */
    vboxDomainRevertToSnapshot, /* domainRevertToSnapshot */
    vboxDomainSnapshotDelete, /* domainSnapshotDelete */
C
Chris Lalancette 已提交
8466
    NULL, /* qemuDomainMonitorCommand */
8467 8468
    NULL, /* domainSetMemoryParameters */
    NULL, /* domainGetMemoryParameters */
8469
    NULL, /* domainOpenConsole */
8470
};
8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491

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
};
8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527

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,
8528
    .volGetPath         = vboxStorageVolGetPath
8529
};