You need to sign in or sign up before continuing.
vbox_tmpl.c 317.8 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-2011 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 <unistd.h>
39 40 41
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
42 43 44 45

#include "internal.h"
#include "datatypes.h"
#include "domain_conf.h"
46
#include "network_conf.h"
47
#include "virterror_internal.h"
48
#include "domain_event.h"
49
#include "storage_conf.h"
50
#include "storage_file.h"
51 52 53 54 55
#include "uuid.h"
#include "memory.h"
#include "nodeinfo.h"
#include "logging.h"
#include "vbox_driver.h"
56
#include "configmake.h"
E
Eric Blake 已提交
57
#include "virfile.h"
58
#include "fdstream.h"
59 60 61 62

/* This one changes from version to version. */
#if VBOX_API_VERSION == 2002
# include "vbox_CAPI_v2_2.h"
63 64
#elif VBOX_API_VERSION == 3000
# include "vbox_CAPI_v3_0.h"
65 66
#elif VBOX_API_VERSION == 3001
# include "vbox_CAPI_v3_1.h"
67 68
#elif VBOX_API_VERSION == 3002
# include "vbox_CAPI_v3_2.h"
69 70
#elif VBOX_API_VERSION == 4000
# include "vbox_CAPI_v4_0.h"
71 72
#else
# error "Unsupport VBOX_API_VERSION"
73 74
#endif

75
/* Include this *last* or we'll get the wrong vbox_CAPI_*.h. */
76
#include "vbox_glue.h"
77 78


79 80 81 82 83 84 85
#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)

86 87
#define VBOX_ADDREF(arg) (arg)->vtbl->nsisupports.AddRef((nsISupports *)(arg))

88 89 90 91 92 93 94
#define VBOX_RELEASE(arg)                                                     \
    do {                                                                      \
        if (arg) {                                                            \
            (arg)->vtbl->nsisupports.Release((nsISupports *)(arg));           \
            (arg) = NULL;                                                     \
        }                                                                     \
    } while (0)
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

#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

117
# define VBOX_MEDIUM_RELEASE(arg) \
118 119
if(arg)\
    (arg)->vtbl->imedium.nsisupports.Release((nsISupports *)(arg))
120
# define VBOX_MEDIUM_FUNC_ARG1(object, func, arg1) \
121
    (object)->vtbl->imedium.func((IMedium *)(object), arg1)
122
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
123 124 125 126 127 128
    (object)->vtbl->imedium.func((IMedium *)(object), arg1, arg2)

#else  /* VBOX_API_VERSION >= 3001 */

typedef IMedium IHardDisk;
typedef IMediumAttachment IHardDiskAttachment;
129 130 131 132 133
# 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) \
134
    (object)->vtbl->func(object, arg1)
135
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
136 137 138
    (object)->vtbl->func(object, arg1, arg2)

#endif /* VBOX_API_VERSION >= 3001 */
139

140
#define vboxError(code, ...) \
141
        virReportErrorHelper(VIR_FROM_VBOX, code, __FILE__, \
142
                             __FUNCTION__, __LINE__, __VA_ARGS__)
143

144 145 146 147 148 149
#define DEBUGPRUnichar(msg, strUtf16) \
if (strUtf16) {\
    char *strUtf8 = NULL;\
\
    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(strUtf16, &strUtf8);\
    if (strUtf8) {\
150
        VIR_DEBUG("%s: %s", msg, strUtf8);\
151 152 153 154 155 156
        g_pVBoxGlobalData->pFuncs->pfnUtf8Free(strUtf8);\
    }\
}

#define DEBUGUUID(msg, iid) \
{\
157
    VIR_DEBUG (msg ": {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",\
158 159 160 161 162 163 164 165 166 167 168 169 170
          (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]);\
}\

171 172
typedef struct {
    virMutex lock;
173
    unsigned long version;
174 175 176 177 178

    virCapsPtr caps;

    IVirtualBox *vboxObj;
    ISession *vboxSession;
179 180 181

    /** Our version specific API table pointer. */
    PCVBOXXPCOM pFuncs;
182 183 184 185 186 187 188 189 190 191 192 193 194

#if VBOX_API_VERSION == 2002

} vboxGlobalData;

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

    /* An array of callbacks */
    virDomainEventCallbackListPtr domainEventCallbacks;

    int fdWatch;
    int domainEventDispatching;

195 196
# if VBOX_API_VERSION <= 3002
    /* IVirtualBoxCallback is used in VirtualBox 3.x only */
197
    IVirtualBoxCallback *vboxCallback;
198
# endif /* VBOX_API_VERSION <= 3002 */
199 200 201 202 203 204 205

    nsIEventQueue  *vboxQueue;
    int volatile vboxCallBackRefCount;

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

206 207
} vboxGlobalData;

208 209 210 211 212 213 214 215 216 217
/* 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
 */

218
static vboxGlobalData *g_pVBoxGlobalData = NULL;
219 220

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

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
#if VBOX_API_VERSION < 4000

# define VBOX_OBJECT_GET_MACHINE(/* in */ iid_value, /* out */ machine) \
    data->vboxObj->vtbl->GetMachine(data->vboxObj, iid_value, machine)

# define VBOX_SESSION_OPEN(/* in */ iid_value, /* unused */ machine) \
    data->vboxObj->vtbl->OpenSession(data->vboxObj, data->vboxSession, iid_value)

# define VBOX_SESSION_OPEN_EXISTING(/* in */ iid_value, /* unused */ machine) \
    data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, iid_value)

# define VBOX_SESSION_CLOSE() \
    data->vboxSession->vtbl->Close(data->vboxSession)

#else /* VBOX_API_VERSION >= 4000 */

# define VBOX_OBJECT_GET_MACHINE(/* in */ iid_value, /* out */ machine) \
    data->vboxObj->vtbl->FindMachine(data->vboxObj, iid_value, machine)

# define VBOX_SESSION_OPEN(/* unused */ iid_value, /* in */ machine) \
    machine->vtbl->LockMachine(machine, data->vboxSession, LockType_Write)

# define VBOX_SESSION_OPEN_EXISTING(/* unused */ iid_value, /* in */ machine) \
    machine->vtbl->LockMachine(machine, data->vboxSession, LockType_Shared)

# define VBOX_SESSION_CLOSE() \
    data->vboxSession->vtbl->UnlockMachine(data->vboxSession)

#endif /* VBOX_API_VERSION >= 4000 */

252 253 254 255
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml);
static int vboxDomainCreate(virDomainPtr dom);
static int vboxDomainUndefine(virDomainPtr dom);

256 257 258 259 260 261 262 263 264
static void vboxDriverLock(vboxGlobalData *data) {
    virMutexLock(&data->lock);
}

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

#if VBOX_API_VERSION == 2002
265

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

306
static void nsIDFromChar(nsID *iid, const unsigned char *uuid) {
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    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);
}

346
# ifdef WIN32
347

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
typedef struct _vboxIID_v2_x_WIN32 vboxIID;
typedef struct _vboxIID_v2_x_WIN32 vboxIID_v2_x_WIN32;

struct _vboxIID_v2_x_WIN32 {
    /* IID is represented by a GUID value. */
    GUID value;
};

#  define VBOX_IID_INITIALIZER { { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } } }

static void
vboxIIDUnalloc_v2_x_WIN32(vboxGlobalData *data ATTRIBUTE_UNUSED,
                          vboxIID_v2_x_WIN32 *iid ATTRIBUTE_UNUSED)
{
    /* Nothing to free */
363
}
364

365 366 367 368 369
static void
vboxIIDToUUID_v2_x_WIN32(vboxIID_v2_x_WIN32 *iid, unsigned char *uuid)
{
    nsIDtoChar(uuid, (nsID *)&iid->value);
}
370

371 372 373 374 375
static void
vboxIIDFromUUID_v2_x_WIN32(vboxGlobalData *data, vboxIID_v2_x_WIN32 *iid,
                           const unsigned char *uuid)
{
    vboxIIDUnalloc_v2_x_WIN32(data, iid);
376

377
    nsIDFromChar((nsID *)&iid->value, uuid);
378 379
}

380 381 382 383 384
static bool
vboxIIDIsEqual_v2_x_WIN32(vboxIID_v2_x_WIN32 *iid1, vboxIID_v2_x_WIN32 *iid2)
{
    return memcmp(&iid1->value, &iid2->value, sizeof (GUID)) == 0;
}
385

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
static void
vboxIIDFromArrayItem_v2_x_WIN32(vboxGlobalData *data, vboxIID_v2_x_WIN32 *iid,
                                vboxArray *array, int idx)
{
    GUID *items = (GUID *)array->items;

    vboxIIDUnalloc_v2_x_WIN32(data, iid);

    memcpy(&iid->value, &items[idx], sizeof (GUID));
}

#  define vboxIIDUnalloc(iid) vboxIIDUnalloc_v2_x_WIN32(data, iid)
#  define vboxIIDToUUID(iid, uuid) vboxIIDToUUID_v2_x_WIN32(iid, uuid)
#  define vboxIIDFromUUID(iid, uuid) vboxIIDFromUUID_v2_x_WIN32(data, iid, uuid)
#  define vboxIIDIsEqual(iid1, iid2) vboxIIDIsEqual_v2_x_WIN32(iid1, iid2)
#  define vboxIIDFromArrayItem(iid, array, idx) \
    vboxIIDFromArrayItem_v2_x_WIN32(data, iid, array, idx)
#  define DEBUGIID(msg, iid) DEBUGUUID(msg, (nsID *)&(iid))

# else /* !WIN32 */

typedef struct _vboxIID_v2_x vboxIID;
typedef struct _vboxIID_v2_x vboxIID_v2_x;

struct _vboxIID_v2_x {
    /* IID is represented by a pointer to a nsID. */
    nsID *value;

    /* backing is used in cases where we need to create or copy an IID.
     * We cannot allocate memory that can be freed by ComUnallocMem.
     * Therefore, we use this stack allocated nsID instead. */
    nsID backing;
};

#  define VBOX_IID_INITIALIZER { NULL, { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } } }

static void
vboxIIDUnalloc_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid)
{
    if (iid->value == NULL) {
426 427 428
        return;
    }

429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
    if (iid->value != &iid->backing) {
        data->pFuncs->pfnComUnallocMem(iid->value);
    }

    iid->value = NULL;
}

static void
vboxIIDToUUID_v2_x(vboxIID_v2_x *iid, unsigned char *uuid)
{
    nsIDtoChar(uuid, iid->value);
}

static void
vboxIIDFromUUID_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid,
                     const unsigned char *uuid)
{
    vboxIIDUnalloc_v2_x(data, iid);

    iid->value = &iid->backing;

    nsIDFromChar(iid->value, uuid);
451 452
}

453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
static bool
vboxIIDIsEqual_v2_x(vboxIID_v2_x *iid1, vboxIID_v2_x *iid2)
{
    return memcmp(iid1->value, iid2->value, sizeof (nsID)) == 0;
}

static void
vboxIIDFromArrayItem_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid,
                          vboxArray *array, int idx)
{
    vboxIIDUnalloc_v2_x(data, iid);

    iid->value = &iid->backing;

    memcpy(iid->value, array->items[idx], sizeof (nsID));
}

#  define vboxIIDUnalloc(iid) vboxIIDUnalloc_v2_x(data, iid)
#  define vboxIIDToUUID(iid, uuid) vboxIIDToUUID_v2_x(iid, uuid)
#  define vboxIIDFromUUID(iid, uuid) vboxIIDFromUUID_v2_x(data, iid, uuid)
#  define vboxIIDIsEqual(iid1, iid2) vboxIIDIsEqual_v2_x(iid1, iid2)
#  define vboxIIDFromArrayItem(iid, array, idx) \
    vboxIIDFromArrayItem_v2_x(data, iid, array, idx)
#  define DEBUGIID(msg, iid) DEBUGUUID(msg, iid)

# endif /* !WIN32 */

480
#else /* VBOX_API_VERSION != 2002 */
481

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
typedef struct _vboxIID_v3_x vboxIID;
typedef struct _vboxIID_v3_x vboxIID_v3_x;

struct _vboxIID_v3_x {
    /* IID is represented by a UTF-16 encoded UUID in string form. */
    PRUnichar *value;

    /* owner indicates if we own the value and need to free it. */
    bool owner;
};

# define VBOX_IID_INITIALIZER { NULL, true }

static void
vboxIIDUnalloc_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid)
{
    if (iid->value != NULL && iid->owner) {
        data->pFuncs->pfnUtf16Free(iid->value);
    }

    iid->value = NULL;
    iid->owner = true;
504 505
}

506 507 508 509 510 511 512 513 514 515 516
static void
vboxIIDToUUID_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                   unsigned char *uuid)
{
    char *utf8 = NULL;

    data->pFuncs->pfnUtf16ToUtf8(iid->value, &utf8);

    virUUIDParse(utf8, uuid);

    data->pFuncs->pfnUtf8Free(utf8);
517 518
}

519 520 521 522 523
static void
vboxIIDFromUUID_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                     const unsigned char *uuid)
{
    char utf8[VIR_UUID_STRING_BUFLEN];
524

525
    vboxIIDUnalloc_v3_x(data, iid);
526

527
    virUUIDFormat(uuid, utf8);
528

529 530
    data->pFuncs->pfnUtf8ToUtf16(utf8, &iid->value);
}
531

532 533 534 535 536 537
static bool
vboxIIDIsEqual_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid1,
                    vboxIID_v3_x *iid2)
{
    unsigned char uuid1[VIR_UUID_BUFLEN];
    unsigned char uuid2[VIR_UUID_BUFLEN];
538 539 540 541 542

    /* 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
543 544 545
     * care of these cases. */
    vboxIIDToUUID_v3_x(data, iid1, uuid1);
    vboxIIDToUUID_v3_x(data, iid2, uuid2);
546

547 548
    return memcmp(uuid1, uuid2, VIR_UUID_BUFLEN) == 0;
}
549 550


551 552 553 554 555
static void
vboxIIDFromArrayItem_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                          vboxArray *array, int idx)
{
    vboxIIDUnalloc_v3_x(data, iid);
556

557 558
    iid->value = array->items[idx];
    iid->owner = false;
559 560
}

561 562 563 564 565 566 567 568

# define vboxIIDUnalloc(iid) vboxIIDUnalloc_v3_x(data, iid)
# define vboxIIDToUUID(iid, uuid) vboxIIDToUUID_v3_x(data, iid, uuid)
# define vboxIIDFromUUID(iid, uuid) vboxIIDFromUUID_v3_x(data, iid, uuid)
# define vboxIIDIsEqual(iid1, iid2) vboxIIDIsEqual_v3_x(data, iid1, iid2)
# define vboxIIDFromArrayItem(iid, array, idx) \
    vboxIIDFromArrayItem_v3_x(data, iid, array, idx)
# define DEBUGIID(msg, strUtf16) DEBUGPRUnichar(msg, strUtf16)
569

570
# if VBOX_API_VERSION >= 3001
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586

/**
 * 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
 *
 */
587
static char *vboxGenerateMediumName(PRUint32  storageBus,
588 589 590 591 592
                                    PRInt32   deviceInst,
                                    PRInt32   devicePort,
                                    PRInt32   deviceSlot,
                                    PRUint32 *aMaxPortPerInst,
                                    PRUint32 *aMaxSlotPerPort) {
593
    const char *prefix = NULL;
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
    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) {
614
        prefix = "hd";
615 616
    } else if (   (storageBus == StorageBus_SATA)
               || (storageBus == StorageBus_SCSI)) {
617
        prefix = "sd";
618
    } else if (storageBus == StorageBus_Floppy) {
619
        prefix = "fd";
620 621
    }

622
    name = virIndexToDiskName(total, prefix);
623

624
    VIR_DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
625
          "devicePort=%d deviceSlot=%d, maxPortPerInst=%u maxSlotPerPort=%u",
626
          NULLSTR(name), total, storageBus, deviceInst, devicePort,
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
          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;

684
    VIR_DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
          "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;

761 762 763
    if (virStrToLong_i(strUtf8, NULL, 10, &ret) < 0)
        ret = -1;

764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
    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;
}

783
# endif /* VBOX_API_VERSION >= 3001 */
784

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

787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
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;
}

826 827 828 829 830 831 832 833 834 835 836
static virCapsPtr vboxCapsInit(void) {
    struct utsname utsname;
    virCapsPtr caps;
    virCapsGuestPtr guest;

    uname(&utsname);

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

837
    if (nodeCapsInitNUMA(caps) < 0)
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
        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;
}

866 867 868
static int
vboxInitialize(vboxGlobalData *data)
{
869 870 871
    data->pFuncs = g_pfnGetFunctions(VBOX_XPCOMC_VERSION);

    if (data->pFuncs == NULL)
872
        goto cleanup;
873 874 875

#if VBOX_XPCOMC_VERSION == 0x00010000U
    data->pFuncs->pfnComInitialize(&data->vboxObj, &data->vboxSession);
876
#else  /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
877 878
    data->pFuncs->pfnComInitialize(IVIRTUALBOX_IID_STR, &data->vboxObj,
                               ISESSION_IID_STR, &data->vboxSession);
879

880
# if VBOX_API_VERSION == 2002
881 882 883

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

884
# else  /* !(VBOX_API_VERSION == 2002) */
885 886 887 888 889 890 891

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

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

    if (data->vboxQueue == NULL) {
892 893
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("nsIEventQueue object is null"));
894 895 896
        goto cleanup;
    }

897
# endif /* !(VBOX_API_VERSION == 2002) */
898
#endif /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
899 900

    if (data->vboxObj == NULL) {
901 902
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("IVirtualBox object is null"));
903
        goto cleanup;
904 905 906
    }

    if (data->vboxSession == NULL) {
907 908
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("ISession object is null"));
909 910
        goto cleanup;
    }
911 912 913 914 915 916 917

    return 0;

cleanup:
    return -1;
}

918
static int vboxExtractVersion(vboxGlobalData *data) {
919
    int ret = -1;
920 921 922 923 924 925 926 927 928 929
    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;

930
        VBOX_UTF16_TO_UTF8(versionUtf16, &vboxVersion);
931

932
        if (virParseVersionString(vboxVersion, &data->version, false) >= 0)
933 934
            ret = 0;

935 936
        VBOX_UTF8_FREE(vboxVersion);
        VBOX_COM_UNALLOC_MEM(versionUtf16);
937 938 939
    }

    if (ret != 0)
940 941
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
                  _("Cound not extract VirtualBox version"));
942

943 944 945 946
    return ret;
}

static void vboxUninitialize(vboxGlobalData *data) {
947 948 949
    if (!data)
        return;

950 951
    if (data->pFuncs)
        data->pFuncs->pfnComUninitialize();
952 953

    virCapabilitiesFree(data->caps);
954 955 956 957 958
#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) */
959 960 961 962 963
    VIR_FREE(data);
}

static virDrvOpenStatus vboxOpen(virConnectPtr conn,
                                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
964 965
                                 unsigned int flags)
{
966
    vboxGlobalData *data = NULL;
967 968
    uid_t uid = getuid();

E
Eric Blake 已提交
969 970
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

971 972 973
    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "vbox:///session" : "vbox:///system");
        if (conn->uri == NULL) {
974
            virReportOOMError();
975 976 977 978
            return VIR_DRV_OPEN_ERROR;
        }
    }

979 980 981 982 983 984
    if (conn->uri->scheme == NULL ||
        STRNEQ (conn->uri->scheme, "vbox"))
        return VIR_DRV_OPEN_DECLINED;

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

987
    if (conn->uri->path == NULL || STREQ(conn->uri->path, "")) {
988
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
989 990 991 992
                  _("no VirtualBox driver path specified (try vbox:///session)"));
        return VIR_DRV_OPEN_ERROR;
    }

993
    if (uid != 0) {
994
        if (STRNEQ (conn->uri->path, "/session")) {
995
            vboxError(VIR_ERR_INTERNAL_ERROR,
996 997 998
                      _("unknown driver path '%s' specified (try vbox:///session)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
999 1000
    } else { /* root */
        if (STRNEQ (conn->uri->path, "/system") &&
1001
            STRNEQ (conn->uri->path, "/session")) {
1002
            vboxError(VIR_ERR_INTERNAL_ERROR,
1003 1004 1005
                      _("unknown driver path '%s' specified (try vbox:///system)"), conn->uri->path);
            return VIR_DRV_OPEN_ERROR;
        }
1006 1007 1008
    }

    if (VIR_ALLOC(data) < 0) {
1009
        virReportOOMError();
1010
        return VIR_DRV_OPEN_ERROR;
1011 1012
    }

1013
    if (!(data->caps = vboxCapsInit()) ||
1014 1015
        vboxInitialize(data) < 0 ||
        vboxExtractVersion(data) < 0) {
1016 1017 1018
        vboxUninitialize(data);
        return VIR_DRV_OPEN_ERROR;
    }
1019

1020 1021 1022 1023 1024 1025 1026
#if VBOX_API_VERSION == 2002

    /* No domainEventCallbacks in 2.2.* version */

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

    if (VIR_ALLOC(data->domainEventCallbacks) < 0) {
1027
        virReportOOMError();
1028 1029 1030 1031 1032 1033 1034 1035
        return VIR_DRV_OPEN_ERROR;
    }

    data->conn = conn;
    g_pVBoxGlobalData = data;

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

1036
    conn->privateData = data;
1037
    VIR_DEBUG("in vboxOpen");
1038 1039 1040 1041 1042 1043

    return VIR_DRV_OPEN_SUCCESS;
}

static int vboxClose(virConnectPtr conn) {
    vboxGlobalData *data = conn->privateData;
1044
    VIR_DEBUG("%s: in vboxClose",conn->driver->name);
1045 1046 1047 1048 1049 1050 1051 1052 1053

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

    return 0;
}

static int vboxGetVersion(virConnectPtr conn, unsigned long *version) {
    vboxGlobalData *data = conn->privateData;
1054
    VIR_DEBUG("%s: in vboxGetVersion",conn->driver->name);
1055 1056 1057 1058 1059 1060 1061 1062

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

    return 0;
}

1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
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;
}

1073
static int vboxGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED) {
1074
    VBOX_OBJECT_CHECK(conn, int, -1);
1075 1076 1077 1078 1079
    PRUint32 maxCPUCount = 0;

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

1082 1083 1084 1085
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}


static char *vboxGetCapabilities(virConnectPtr conn) {
1096
    VBOX_OBJECT_CHECK(conn, char *, NULL);
1097 1098 1099 1100 1101 1102 1103 1104 1105

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

    return ret;
}

static int vboxListDomains(virConnectPtr conn, int *ids, int nids) {
1106
    VBOX_OBJECT_CHECK(conn, int, -1);
1107
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1108
    PRUint32 state;
1109
    nsresult rc;
1110 1111
    int i, j;

1112
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1113
    if (NS_FAILED(rc)) {
1114 1115
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of Domains, rc=%08x"),(unsigned)rc);
1116 1117
        goto cleanup;
    }
1118

1119 1120 1121
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < nids); ++i) {
        IMachine *machine = machines.items[i];
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

        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;
1132 1133 1134 1135 1136 1137
                }
            }
        }
    }

cleanup:
1138
    vboxArrayRelease(&machines);
1139 1140 1141 1142
    return ret;
}

static int vboxNumOfDomains(virConnectPtr conn) {
1143
    VBOX_OBJECT_CHECK(conn, int, -1);
1144
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1145
    PRUint32 state;
1146
    nsresult rc;
1147 1148
    int i;

1149
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1150
    if (NS_FAILED(rc)) {
1151 1152
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get number of Domains, rc=%08x"), (unsigned)rc);
1153 1154
        goto cleanup;
    }
1155

1156 1157 1158
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1159 1160 1161 1162 1163 1164 1165 1166 1167

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

cleanup:
1173
    vboxArrayRelease(&machines);
1174 1175 1176 1177
    return ret;
}

static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
1178
                                        unsigned int flags) {
1179 1180 1181 1182 1183 1184 1185 1186
    /* 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.
     */

1187 1188 1189 1190 1191
    virDomainPtr dom;

    virCheckFlags(0, NULL);

    dom = vboxDomainDefineXML(conn, xml);
1192 1193 1194 1195 1196
    if (dom == NULL)
        return NULL;

    if (vboxDomainCreate(dom) < 0) {
        vboxDomainUndefine(dom);
1197
        virUnrefDomain(dom);
1198
        return NULL;
1199 1200 1201 1202 1203 1204
    }

    return dom;
}

static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id) {
1205
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1206
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1207 1208
    vboxIID iid = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
1209
    PRUint32 state;
1210
    nsresult rc;
1211

1212 1213 1214
    /* Internal vbox IDs start from 0, the public libvirt ID
     * starts from 1, so refuse id==0, and adjust the rest*/
    if (id == 0) {
1215
        vboxError(VIR_ERR_NO_DOMAIN,
1216 1217 1218 1219 1220
                  _("no domain with matching id %d"), id);
        return NULL;
    }
    id = id - 1;

1221
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1222
    if (NS_FAILED(rc)) {
1223 1224
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1225 1226
        return NULL;
    }
1227

1228 1229 1230 1231
    if (id < machines.count) {
        IMachine *machine = machines.items[id];

        if (machine) {
1232
            PRBool isAccessible = PR_FALSE;
1233
            machine->vtbl->GetAccessible(machine, &isAccessible);
1234
            if (isAccessible) {
1235
                machine->vtbl->GetState(machine, &state);
1236 1237 1238 1239
                if (   (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) ) {
                    PRUnichar *machineNameUtf16 = NULL;
                    char      *machineNameUtf8  = NULL;
1240

1241
                    machine->vtbl->GetName(machine, &machineNameUtf16);
1242
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1243

1244 1245 1246
                    machine->vtbl->GetId(machine, &iid.value);
                    vboxIIDToUUID(&iid, uuid);
                    vboxIIDUnalloc(&iid);
1247 1248 1249 1250 1251 1252 1253

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

1254
                    ret = virGetDomain(conn, machineNameUtf8, uuid);
1255 1256 1257 1258 1259 1260
                    if (ret)
                        ret->id = id + 1;

                    /* Cleanup all the XPCOM allocated stuff here */
                    VBOX_UTF8_FREE(machineNameUtf8);
                    VBOX_UTF16_FREE(machineNameUtf16);
1261 1262 1263 1264 1265
                }
            }
        }
    }

1266
    vboxArrayRelease(&machines);
1267 1268

    return ret;
1269 1270 1271
}

static virDomainPtr vboxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid) {
1272
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1273
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1274
    vboxIID iid = VBOX_IID_INITIALIZER;
1275
    char      *machineNameUtf8  = NULL;
1276
    PRUnichar *machineNameUtf16 = NULL;
1277
    unsigned char iid_as_uuid[VIR_UUID_BUFLEN];
1278
    int i, matched = 0;
1279
    nsresult rc;
1280

1281
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1282
    if (NS_FAILED(rc)) {
1283 1284
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1285 1286
        return NULL;
    }
1287

1288 1289
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1290
        PRBool isAccessible = PR_FALSE;
1291

1292 1293
        if (!machine)
            continue;
1294

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

1298 1299
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
1300
                continue;
1301 1302
            vboxIIDToUUID(&iid, iid_as_uuid);
            vboxIIDUnalloc(&iid);
1303

1304
            if (memcmp(uuid, iid_as_uuid, VIR_UUID_BUFLEN) == 0) {
1305

1306
                PRUint32 state;
1307

1308
                matched = 1;
1309

1310 1311
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1312

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

1315 1316 1317 1318 1319
                /* 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.
                 */
1320

1321
                ret = virGetDomain(conn, machineNameUtf8, iid_as_uuid);
1322 1323 1324 1325
                if (   ret
                    && (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret->id = i + 1;
1326 1327
            }

1328 1329
            if (matched == 1)
                break;
1330 1331 1332
        }
    }

1333 1334 1335
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1336
    vboxArrayRelease(&machines);
1337 1338

    return ret;
1339 1340 1341
}

static virDomainPtr vboxDomainLookupByName(virConnectPtr conn, const char *name) {
1342
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1343
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1344
    vboxIID iid = VBOX_IID_INITIALIZER;
1345
    char      *machineNameUtf8  = NULL;
1346
    PRUnichar *machineNameUtf16 = NULL;
1347
    unsigned char uuid[VIR_UUID_BUFLEN];
1348
    int i, matched = 0;
1349
    nsresult rc;
1350

1351
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1352
    if (NS_FAILED(rc)) {
1353 1354
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1355 1356
        return NULL;
    }
1357

1358 1359
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1360
        PRBool isAccessible = PR_FALSE;
1361

1362 1363
        if (!machine)
            continue;
1364

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

1368 1369
            machine->vtbl->GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1370

1371
            if (STREQ(name, machineNameUtf8)) {
1372

1373
                PRUint32 state;
1374

1375
                matched = 1;
1376

1377 1378 1379
                machine->vtbl->GetId(machine, &iid.value);
                vboxIIDToUUID(&iid, uuid);
                vboxIIDUnalloc(&iid);
1380

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

1383 1384 1385 1386 1387
                /* 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.
                 */
1388

1389
                ret = virGetDomain(conn, machineNameUtf8, uuid);
1390 1391 1392 1393
                if (   ret
                    && (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret->id = i + 1;
1394 1395
            }

1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
            if (machineNameUtf8) {
                VBOX_UTF8_FREE(machineNameUtf8);
                machineNameUtf8 = NULL;
            }
            if (machineNameUtf16) {
                VBOX_COM_UNALLOC_MEM(machineNameUtf16);
                machineNameUtf16 = NULL;
            }
            if (matched == 1)
                break;
1406 1407 1408
        }
    }

1409
    vboxArrayRelease(&machines);
1410 1411

    return ret;
1412 1413
}

1414 1415

static int vboxDomainIsActive(virDomainPtr dom) {
1416
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1417
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1418
    vboxIID iid = VBOX_IID_INITIALIZER;
1419 1420
    char      *machineNameUtf8  = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1421
    unsigned char uuid[VIR_UUID_BUFLEN];
1422
    int i, matched = 0;
1423
    nsresult rc;
1424

1425
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1426
    if (NS_FAILED(rc)) {
1427 1428
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1429 1430
        return ret;
    }
1431

1432 1433
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1434 1435 1436 1437 1438 1439 1440
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

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

1442 1443
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
1444
                continue;
1445 1446
            vboxIIDToUUID(&iid, uuid);
            vboxIIDUnalloc(&iid);
1447

1448
            if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {
1449

1450
                PRUint32 state;
1451

1452
                matched = 1;
1453

1454 1455
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1456

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

1459 1460 1461 1462 1463
                if (   (state >= MachineState_FirstOnline)
                    && (state <= MachineState_LastOnline) )
                    ret = 1;
                else
                    ret = 0;
1464 1465
            }

1466 1467
            if (matched == 1)
                break;
1468 1469 1470
        }
    }

1471 1472 1473
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1474
    vboxArrayRelease(&machines);
1475

1476 1477 1478 1479 1480
    return ret;
}


static int vboxDomainIsPersistent(virDomainPtr dom ATTRIBUTE_UNUSED) {
1481
    /* All domains are persistent. */
1482 1483 1484 1485
    return 1;
}


1486 1487 1488 1489
static int vboxDomainIsUpdated(virDomainPtr dom ATTRIBUTE_UNUSED) {
    return 0;
}

1490
static int vboxDomainSuspend(virDomainPtr dom) {
1491
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1492
    IMachine *machine    = NULL;
1493
    vboxIID iid = VBOX_IID_INITIALIZER;
1494
    IConsole *console    = NULL;
1495
    PRBool isAccessible  = PR_FALSE;
1496
    PRUint32 state;
1497
    nsresult rc;
1498

1499
    vboxIIDFromUUID(&iid, dom->uuid);
1500
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1501
    if (NS_FAILED(rc)) {
1502
        vboxError(VIR_ERR_NO_DOMAIN,
1503
                  _("no domain with matching id %d"), dom->id);
1504 1505
        goto cleanup;
    }
1506

1507 1508
    if (!machine)
        goto cleanup;
1509

1510 1511 1512
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1513

1514
        if (state == MachineState_Running) {
1515 1516
            /* set state pause */
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1517 1518 1519 1520 1521
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Pause(console);
                VBOX_RELEASE(console);
                ret = 0;
1522
            } else {
1523 1524
                vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                          _("error while suspending the domain"));
1525 1526
                goto cleanup;
            }
1527
            VBOX_SESSION_CLOSE();
1528
        } else {
1529 1530
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine not in running state to suspend it"));
1531
            goto cleanup;
1532 1533 1534 1535
        }
    }

cleanup:
1536
    VBOX_RELEASE(machine);
1537
    vboxIIDUnalloc(&iid);
1538 1539 1540 1541
    return ret;
}

static int vboxDomainResume(virDomainPtr dom) {
1542
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1543
    IMachine *machine    = NULL;
1544
    vboxIID iid = VBOX_IID_INITIALIZER;
1545 1546
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1547
    nsresult rc;
1548

1549
    PRBool isAccessible = PR_FALSE;
1550

1551
    vboxIIDFromUUID(&iid, dom->uuid);
1552
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1553
    if (NS_FAILED(rc)) {
1554
        vboxError(VIR_ERR_NO_DOMAIN,
1555
                  _("no domain with matching id %d"), dom->id);
1556 1557
        goto cleanup;
    }
1558

1559 1560
    if (!machine)
        goto cleanup;
1561

1562 1563 1564 1565 1566
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);

        if (state == MachineState_Paused) {
1567 1568
            /* resume the machine here */
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1569 1570 1571 1572 1573
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Resume(console);
                VBOX_RELEASE(console);
                ret = 0;
1574
            } else {
1575 1576
                vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                          _("error while resuming the domain"));
1577 1578
                goto cleanup;
            }
1579
            VBOX_SESSION_CLOSE();
1580
        } else {
1581 1582
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine not paused, so can't resume it"));
1583
            goto cleanup;
1584 1585 1586 1587
        }
    }

cleanup:
1588
    VBOX_RELEASE(machine);
1589
    vboxIIDUnalloc(&iid);
1590 1591 1592 1593
    return ret;
}

static int vboxDomainShutdown(virDomainPtr dom) {
1594
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1595
    IMachine *machine    = NULL;
1596
    vboxIID iid = VBOX_IID_INITIALIZER;
1597 1598
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1599 1600
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1601

1602
    vboxIIDFromUUID(&iid, dom->uuid);
1603
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1604
    if (NS_FAILED(rc)) {
1605
        vboxError(VIR_ERR_NO_DOMAIN,
1606
                  _("no domain with matching id %d"), dom->id);
1607 1608
        goto cleanup;
    }
1609

1610 1611
    if (!machine)
        goto cleanup;
1612

1613 1614 1615
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1616

1617
        if (state == MachineState_Paused) {
1618 1619
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine paused, so can't power it down"));
1620 1621
            goto cleanup;
        } else if (state == MachineState_PoweredOff) {
1622 1623
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine already powered down"));
1624 1625
            goto cleanup;
        }
1626

1627
        VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1628 1629 1630 1631 1632
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
            console->vtbl->PowerButton(console);
            VBOX_RELEASE(console);
            ret = 0;
1633
        }
1634
        VBOX_SESSION_CLOSE();
1635 1636 1637
    }

cleanup:
1638
    VBOX_RELEASE(machine);
1639
    vboxIIDUnalloc(&iid);
1640 1641 1642
    return ret;
}

E
Eric Blake 已提交
1643 1644
static int vboxDomainReboot(virDomainPtr dom, unsigned int flags)
{
1645
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1646
    IMachine *machine    = NULL;
1647
    vboxIID iid = VBOX_IID_INITIALIZER;
1648 1649
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1650 1651
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1652

E
Eric Blake 已提交
1653 1654
    virCheckFlags(0, -1);

1655
    vboxIIDFromUUID(&iid, dom->uuid);
1656
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1657
    if (NS_FAILED(rc)) {
1658
        vboxError(VIR_ERR_NO_DOMAIN,
1659
                  _("no domain with matching id %d"), dom->id);
1660 1661
        goto cleanup;
    }
1662

1663 1664
    if (!machine)
        goto cleanup;
1665

1666 1667 1668
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1669

1670
        if (state == MachineState_Running) {
1671
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1672 1673 1674 1675 1676
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Reset(console);
                VBOX_RELEASE(console);
                ret = 0;
1677
            }
1678
            VBOX_SESSION_CLOSE();
1679
        } else {
1680 1681
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine not running, so can't reboot it"));
1682
            goto cleanup;
1683 1684 1685 1686
        }
    }

cleanup:
1687
    VBOX_RELEASE(machine);
1688
    vboxIIDUnalloc(&iid);
1689 1690 1691
    return ret;
}

1692 1693 1694 1695
static int
vboxDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1696
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1697
    IMachine *machine    = NULL;
1698
    vboxIID iid = VBOX_IID_INITIALIZER;
1699 1700
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1701 1702
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1703

1704 1705
    virCheckFlags(0, -1);

1706
    vboxIIDFromUUID(&iid, dom->uuid);
1707
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1708
    if (NS_FAILED(rc)) {
1709
        vboxError(VIR_ERR_NO_DOMAIN,
1710
                  _("no domain with matching id %d"), dom->id);
1711 1712
        goto cleanup;
    }
1713

1714 1715
    if (!machine)
        goto cleanup;
1716

1717 1718 1719
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1720

1721
        if (state == MachineState_PoweredOff) {
1722 1723
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("machine already powered down"));
1724 1725
            goto cleanup;
        }
1726

1727
        VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1728 1729
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
1730 1731

#if VBOX_API_VERSION == 2002
1732
            console->vtbl->PowerDown(console);
1733
#else
1734
            IProgress *progress = NULL;
1735 1736 1737 1738
            console->vtbl->PowerDown(console, &progress);
            if (progress) {
                progress->vtbl->WaitForCompletion(progress, -1);
                VBOX_RELEASE(progress);
1739
            }
1740 1741
#endif
            VBOX_RELEASE(console);
1742
            dom->id = -1;
1743
            ret = 0;
1744
        }
1745
        VBOX_SESSION_CLOSE();
1746 1747 1748
    }

cleanup:
1749
    VBOX_RELEASE(machine);
1750
    vboxIIDUnalloc(&iid);
1751 1752 1753
    return ret;
}

1754 1755 1756 1757 1758 1759
static int
vboxDomainDestroy(virDomainPtr dom)
{
    return vboxDomainDestroyFlags(dom, 0);
}

1760
static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
1761 1762 1763 1764 1765
    /* 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 ;)
     */
1766 1767 1768
    char *osType = strdup("hvm");

    if (osType == NULL)
1769
        virReportOOMError();
1770 1771

    return osType;
1772 1773 1774
}

static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory) {
1775
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1776
    IMachine *machine    = NULL;
1777
    vboxIID iid = VBOX_IID_INITIALIZER;
1778
    PRUint32 state       = MachineState_Null;
1779 1780
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1781

1782
    vboxIIDFromUUID(&iid, dom->uuid);
1783
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1784
    if (NS_FAILED(rc)) {
1785
        vboxError(VIR_ERR_NO_DOMAIN,
1786
                  _("no domain with matching id %d"), dom->id);
1787 1788
        goto cleanup;
    }
1789

1790 1791
    if (!machine)
        goto cleanup;
1792

1793 1794 1795
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1796

1797
        if (state != MachineState_PoweredOff) {
1798 1799
            vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                      _("memory size can't be changed unless domain is powered down"));
1800 1801
            goto cleanup;
        }
1802

1803
        rc = VBOX_SESSION_OPEN(iid.value, machine);
1804 1805 1806
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
1807

1808 1809
                rc = machine->vtbl->SetMemorySize(machine,
                                                  VIR_DIV_UP(memory, 1024));
1810 1811 1812 1813
                if (NS_SUCCEEDED(rc)) {
                    machine->vtbl->SaveSettings(machine);
                    ret = 0;
                } else {
1814 1815 1816
                    vboxError(VIR_ERR_INTERNAL_ERROR,
                              _("could not set the memory size of the "
                                "domain to: %lu Kb, rc=%08x"),
1817
                              memory, (unsigned)rc);
1818 1819
                }
            }
1820
            VBOX_SESSION_CLOSE();
1821 1822 1823 1824
        }
    }

cleanup:
1825
    VBOX_RELEASE(machine);
1826
    vboxIIDUnalloc(&iid);
1827 1828 1829 1830
    return ret;
}

static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info) {
1831
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1832
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1833 1834
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1835 1836
    nsresult rc;
    int i = 0;
1837

1838
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1839
    if (NS_FAILED(rc)) {
1840 1841
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1842 1843
        goto cleanup;
    }
1844

1845
    info->nrVirtCpu = 0;
1846 1847
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1848
        PRBool isAccessible = PR_FALSE;
1849

1850 1851
        if (!machine)
            continue;
1852

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

1856 1857 1858 1859 1860 1861
            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
1862
                * for time being set max_balloon and cur_balloon to same
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
                * 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;
                }
1880 1881


1882 1883 1884 1885 1886 1887
                machine->vtbl->GetCPUCount(machine, &CPUCount);
                machine->vtbl->GetMemorySize(machine, &memorySize);
                machine->vtbl->GetState(machine, &state);

                info->cpuTime = 0;
                info->nrVirtCpu = CPUCount;
1888 1889
                info->memory = memorySize * 1024;
                info->maxMem = maxMemorySize * 1024;
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
                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;
1913 1914
                }

1915
                ret = 0;
1916 1917
            }

1918 1919 1920 1921 1922 1923
            if (machineName)
                VBOX_UTF8_FREE(machineName);
            if (machineNameUtf16)
                VBOX_COM_UNALLOC_MEM(machineNameUtf16);
            if (info->nrVirtCpu)
                break;
1924 1925 1926 1927
        }

    }

1928
    vboxArrayRelease(&machines);
1929 1930 1931 1932 1933

cleanup:
    return ret;
}

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
static int
vboxDomainGetState(virDomainPtr dom,
                   int *state,
                   int *reason,
                   unsigned int flags)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID domiid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    PRUint32 mstate = MachineState_Null;
    nsresult rc;

    virCheckFlags(0, -1);

    vboxIIDFromUUID(&domiid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
                  _("no domain with matching UUID"));
        goto cleanup;
    }

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

    switch (mstate) {
    case MachineState_Running:
        *state = VIR_DOMAIN_RUNNING;
        break;
    case MachineState_Stuck:
        *state = VIR_DOMAIN_BLOCKED;
        break;
    case MachineState_Paused:
        *state = VIR_DOMAIN_PAUSED;
        break;
    case MachineState_Stopping:
        *state = VIR_DOMAIN_SHUTDOWN;
        break;
    case MachineState_PoweredOff:
        *state = VIR_DOMAIN_SHUTOFF;
        break;
    case MachineState_Aborted:
        *state = VIR_DOMAIN_CRASHED;
        break;
    case MachineState_Null:
    default:
        *state = VIR_DOMAIN_NOSTATE;
        break;
    }

    if (reason)
        *reason = 0;

    ret = 0;

cleanup:
    vboxIIDUnalloc(&domiid);
    return ret;
}

1993
static int vboxDomainSave(virDomainPtr dom, const char *path ATTRIBUTE_UNUSED) {
1994
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1995
    IConsole *console    = NULL;
1996
    vboxIID iid = VBOX_IID_INITIALIZER;
1997
    IMachine *machine = NULL;
1998
    nsresult rc;
1999 2000 2001 2002 2003 2004 2005 2006

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

2007
    /* Open a Session for the machine */
2008
    vboxIIDFromUUID(&iid, dom->uuid);
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
#if VBOX_API_VERSION >= 4000
    /* Get machine for the call to VBOX_SESSION_OPEN_EXISTING */
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
                  _("no domain with matching uuid"));
        return -1;
    }
#endif

    rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
2020 2021 2022 2023
    if (NS_SUCCEEDED(rc)) {
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (NS_SUCCEEDED(rc) && console) {
            IProgress *progress = NULL;
2024

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

2027
            if (progress) {
2028
#if VBOX_API_VERSION == 2002
2029
                nsresult resultCode;
2030
#else
2031
                PRInt32 resultCode;
2032
#endif
2033

2034 2035 2036 2037
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_SUCCEEDED(resultCode)) {
                    ret = 0;
2038
                }
2039
                VBOX_RELEASE(progress);
2040
            }
2041
            VBOX_RELEASE(console);
2042
        }
2043
        VBOX_SESSION_CLOSE();
2044 2045
    }

2046
    DEBUGIID("UUID of machine being saved:", iid.value);
2047

2048
    VBOX_RELEASE(machine);
2049
    vboxIIDUnalloc(&iid);
2050 2051 2052
    return ret;
}

2053 2054 2055 2056
static int
vboxDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
{
2057
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
2058
    IMachine *machine    = NULL;
2059
    vboxIID iid = VBOX_IID_INITIALIZER;
2060
    PRUint32  CPUCount   = nvcpus;
2061
    nsresult rc;
2062

2063
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2064 2065 2066 2067
        vboxError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

2068
    vboxIIDFromUUID(&iid, dom->uuid);
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
#if VBOX_API_VERSION >= 4000
    /* Get machine for the call to VBOX_SESSION_OPEN */
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
                  _("no domain with matching uuid"));
        return -1;
    }
#endif

    rc = VBOX_SESSION_OPEN(iid.value, machine);
2080 2081 2082 2083 2084 2085 2086
    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;
2087
            } else {
2088 2089 2090
                vboxError(VIR_ERR_INTERNAL_ERROR,
                          _("could not set the number of cpus of the domain "
                            "to: %u, rc=%08x"),
2091
                          CPUCount, (unsigned)rc);
2092
            }
2093
            VBOX_RELEASE(machine);
2094
        } else {
2095
            vboxError(VIR_ERR_NO_DOMAIN,
2096
                      _("no domain with matching id %d"), dom->id);
2097
        }
2098
    } else {
2099
        vboxError(VIR_ERR_NO_DOMAIN,
2100
                  _("can't open session to the domain with id %d"), dom->id);
2101
    }
2102
    VBOX_SESSION_CLOSE();
2103

2104
    vboxIIDUnalloc(&iid);
2105 2106 2107
    return ret;
}

2108 2109 2110
static int
vboxDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
2111
    return vboxDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2112 2113 2114 2115 2116
}

static int
vboxDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
2117 2118
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    ISystemProperties *systemProperties = NULL;
2119 2120
    PRUint32 maxCPUCount = 0;

2121
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2122 2123 2124 2125
        vboxError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
        return -1;
    }

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

2131 2132 2133 2134
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
2135 2136 2137 2138 2139 2140 2141 2142
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}

2143 2144 2145
static int
vboxDomainGetMaxVcpus(virDomainPtr dom)
{
2146
    return vboxDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
2147 2148 2149
                                         VIR_DOMAIN_VCPU_MAXIMUM));
}

2150
static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
2151
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
2152 2153
    virDomainDefPtr def  = NULL;
    IMachine *machine    = NULL;
2154
    vboxIID iid = VBOX_IID_INITIALIZER;
2155
    int gotAllABoutDef   = -1;
2156
    nsresult rc;
2157
    char *tmp;
2158

2159 2160
    /* Flags checked by virDomainDefFormat */

2161
    if (VIR_ALLOC(def) < 0) {
2162
        virReportOOMError();
2163 2164 2165
        goto cleanup;
    }

2166
    vboxIIDFromUUID(&iid, dom->uuid);
2167
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
2168
    if (NS_SUCCEEDED(rc)) {
2169
        PRBool accessible = PR_FALSE;
2170

2171 2172 2173 2174 2175 2176 2177
        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;
2178
            PRBool VRDxEnabled                  = PR_FALSE;
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
            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 */
2201
            vboxArray mediumAttachments         = VBOX_ARRAY_INITIALIZER;
2202
#endif /* VBOX_API_VERSION >= 3001 */
2203 2204 2205 2206 2207
#if VBOX_API_VERSION < 4000
            IVRDPServer *VRDxServer             = NULL;
#else  /* VBOX_API_VERSION >= 4000 */
            IVRDEServer *VRDxServer             = NULL;
#endif /* VBOX_API_VERSION >= 4000 */
2208 2209 2210
            IAudioAdapter *audioAdapter         = NULL;
            IUSBController *USBController       = NULL;
            ISystemProperties *systemProperties = NULL;
2211 2212


2213 2214 2215 2216
            def->virtType = VIR_DOMAIN_VIRT_VBOX;
            def->id = dom->id;
            memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
            def->name = strdup(dom->name);
2217

2218
            machine->vtbl->GetMemorySize(machine, &memorySize);
2219
            def->mem.cur_balloon = memorySize * 1024;
2220

2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
            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
             */
2235 2236
            /* def->mem.max_balloon = maxMemorySize * 1024; */
            def->mem.max_balloon = memorySize * 1024;
2237 2238

            machine->vtbl->GetCPUCount(machine, &CPUCount);
E
Eric Blake 已提交
2239
            def->maxvcpus = def->vcpus = CPUCount;
2240 2241 2242 2243

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

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

2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
            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 */
2270
                }
2271
            }
2272

2273 2274 2275
            def->features = 0;
#if VBOX_API_VERSION < 3001
            machine->vtbl->GetPAEEnabled(machine, &PAEEnabled);
2276
#elif VBOX_API_VERSION == 3001
2277
            machine->vtbl->GetCpuProperty(machine, CpuPropertyType_PAE, &PAEEnabled);
2278 2279 2280
#elif VBOX_API_VERSION >= 3002
            machine->vtbl->GetCPUProperty(machine, CPUPropertyType_PAE, &PAEEnabled);
#endif
2281 2282 2283
            if (PAEEnabled) {
                def->features = def->features | (1 << VIR_DOMAIN_FEATURE_PAE);
            }
2284

2285 2286 2287 2288 2289 2290
            machine->vtbl->GetBIOSSettings(machine, &bios);
            if (bios) {
                bios->vtbl->GetACPIEnabled(bios, &ACPIEnabled);
                if (ACPIEnabled) {
                    def->features = def->features | (1 << VIR_DOMAIN_FEATURE_ACPI);
                }
2291

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

2297 2298 2299 2300 2301
                VBOX_RELEASE(bios);
            }

            /* Currently VirtualBox always uses locatime
             * so locatime is always true here */
2302
            def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;
2303 2304 2305 2306 2307 2308 2309 2310

            /* 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 */
2311
                        PRUint32 VRAMSize          = 8;
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323
                        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;
2324
                        def->videos[0]->vram            = VRAMSize * 1024;
2325 2326 2327 2328
                        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;
2329
                        } else
2330
                            virReportOOMError();
2331
                    } else
2332
                        virReportOOMError();
2333
                } else
2334
                    virReportOOMError();
2335
            }
2336

2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
            /* 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;
2348

2349
                def->ngraphics = 0;
2350

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

2355 2356 2357
                if (valueTypeUtf16) {
                    VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
                    VBOX_UTF16_FREE(valueTypeUtf16);
2358

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

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

2368 2369 2370
                        if (valueDisplayUtf16) {
                            VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                            VBOX_UTF16_FREE(valueDisplayUtf16);
2371

2372 2373 2374
                            if (strlen(valueDisplayUtf8) <= 0) {
                                VBOX_UTF8_FREE(valueDisplayUtf8);
                                valueDisplayUtf8 = NULL;
2375 2376
                            }
                        }
2377

2378 2379 2380 2381 2382
                        if (STREQ(valueTypeUtf8, "sdl")) {
                            sdlPresent = 1;
                            if (valueDisplayUtf8)
                                sdlDisplay = strdup(valueDisplayUtf8);
                            if (sdlDisplay == NULL) {
2383
                                virReportOOMError();
2384 2385 2386 2387 2388 2389
                                /* 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++;
2390
                        }
2391

2392 2393 2394 2395 2396
                        if (STREQ(valueTypeUtf8, "gui")) {
                            guiPresent = 1;
                            if (valueDisplayUtf8)
                                guiDisplay = strdup(valueDisplayUtf8);
                            if (guiDisplay == NULL) {
2397
                                virReportOOMError();
2398
                                /* just don't go to cleanup yet as it is ok to have
2399 2400
                                 * guiDisplay as NULL and we check it below if it
                                 * exist and then only use it there
2401
                                 */
2402
                            }
2403 2404
                            totalPresent++;
                        }
2405 2406
                        if (valueDisplayUtf8)
                            VBOX_UTF8_FREE(valueDisplayUtf8);
2407 2408
                    }

2409 2410
                    if (STREQ(valueTypeUtf8, "vrdp"))
                        vrdpPresent = 1;
2411

2412 2413
                    VBOX_UTF8_FREE(valueTypeUtf8);
                }
2414

2415 2416 2417 2418 2419 2420 2421
                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++;
                    }
2422

2423 2424 2425 2426 2427 2428 2429 2430 2431
                    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;
2432 2433 2434 2435 2436 2437 2438 2439 2440
                        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
                                 */
                            }
2441 2442 2443 2444 2445
                        }
                        totalPresent++;
                        def->ngraphics++;
                    }
                }
2446

2447 2448 2449 2450 2451 2452 2453 2454
#if VBOX_API_VERSION < 4000
                machine->vtbl->GetVRDPServer(machine, &VRDxServer);
#else  /* VBOX_API_VERSION >= 4000 */
                machine->vtbl->GetVRDEServer(machine, &VRDxServer);
#endif /* VBOX_API_VERSION >= 4000 */
                if (VRDxServer) {
                    VRDxServer->vtbl->GetEnabled(VRDxServer, &VRDxEnabled);
                    if (VRDxEnabled) {
2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465

                        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;
2466
                            VRDxServer->vtbl->GetPort(VRDxServer, &VRDPport);
2467 2468
                            if (VRDPport) {
                                def->graphics[def->ngraphics]->data.rdp.port = VRDPport;
2469
#elif VBOX_API_VERSION < 4000 /* 3001 <= VBOX_API_VERSION < 4000 */
2470
                            PRUnichar *VRDPport = NULL;
2471
                            VRDxServer->vtbl->GetPorts(VRDxServer, &VRDPport);
2472 2473 2474 2475
                            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);
2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486
#else /* VBOX_API_VERSION >= 4000 */
                            PRUnichar *VRDEPortsKey = NULL;
                            PRUnichar *VRDEPortsValue = NULL;
                            VBOX_UTF8_TO_UTF16("TCP/Ports", &VRDEPortsKey);
                            VRDxServer->vtbl->GetVRDEProperty(VRDxServer, VRDEPortsKey, &VRDEPortsValue);
                            VBOX_UTF16_FREE(VRDEPortsKey);
                            if (VRDEPortsValue) {
                                /* even if vbox supports mutilpe ports, single port for now here */
                                def->graphics[def->ngraphics]->data.rdp.port = PRUnicharToInt(VRDEPortsValue);
                                VBOX_UTF16_FREE(VRDEPortsValue);
#endif /* VBOX_API_VERSION >= 4000 */
2487 2488 2489
                            } else {
                                def->graphics[def->ngraphics]->data.rdp.autoport = 1;
                            }
2490

2491
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;
2492

2493 2494 2495 2496 2497 2498 2499 2500
#if VBOX_API_VERSION >= 4000
                            PRUnichar *VRDENetAddressKey = NULL;
                            VBOX_UTF8_TO_UTF16("TCP/Address", &VRDENetAddressKey);
                            VRDxServer->vtbl->GetVRDEProperty(VRDxServer, VRDENetAddressKey, &netAddressUtf16);
                            VBOX_UTF16_FREE(VRDENetAddressKey);
#else /* VBOX_API_VERSION < 4000 */
                            VRDxServer->vtbl->GetNetAddress(VRDxServer, &netAddressUtf16);
#endif /* VBOX_API_VERSION < 4000 */
2501 2502 2503
                            if (netAddressUtf16) {
                                VBOX_UTF16_TO_UTF8(netAddressUtf16, &netAddressUtf8);
                                if (STRNEQ(netAddressUtf8, ""))
2504 2505
                                    virDomainGraphicsListenSetAddress(def->graphics[def->ngraphics], 0,
                                                                      netAddressUtf8, -1, true);
2506 2507 2508
                                VBOX_UTF16_FREE(netAddressUtf16);
                                VBOX_UTF8_FREE(netAddressUtf8);
                            }
2509

2510
                            VRDxServer->vtbl->GetAllowMultiConnection(VRDxServer, &allowMultiConnection);
2511 2512 2513
                            if (allowMultiConnection) {
                                def->graphics[def->ngraphics]->data.rdp.multiUser = 1;
                            }
2514

2515
                            VRDxServer->vtbl->GetReuseSingleConnection(VRDxServer, &reuseSingleConnection);
2516 2517 2518
                            if (reuseSingleConnection) {
                                def->graphics[def->ngraphics]->data.rdp.replaceUser = 1;
                            }
2519

2520
                            def->ngraphics++;
2521
                        } else
2522
                            virReportOOMError();
2523
                    }
2524
                    VBOX_RELEASE(VRDxServer);
2525
                }
2526
            }
2527

2528 2529 2530
#if VBOX_API_VERSION < 3001
            /* dump IDE hdds if present */
            VBOX_UTF8_TO_UTF16(hddBus, &hddBusUtf16);
2531

2532 2533 2534 2535
            def->ndisks = 0;
            machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 0,  &hardDiskPM);
            if (hardDiskPM)
                def->ndisks++;
2536

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

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

2545 2546 2547 2548 2549 2550 2551 2552 2553
            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
2554
                        virReportOOMError();
2555
                }
2556
            }
2557

2558 2559 2560 2561
            if (hardDiskPM) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2562

2563 2564
                hardDiskPM->vtbl->imedium.GetLocation((IMedium *)hardDiskPM, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2565

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

2568 2569 2570 2571 2572
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hda");
                hddNum++;
2573

2574 2575 2576 2577
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPM);
            }
2578

2579 2580 2581 2582
            if (hardDiskPS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2583

2584 2585
                hardDiskPS->vtbl->imedium.GetLocation((IMedium *)hardDiskPS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2586

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

2589 2590 2591 2592 2593
                if (hddType == HardDiskType_Immutable)
                    def->disks[hddNum]->readonly = 1;
                def->disks[hddNum]->src = strdup(hddlocation);
                def->disks[hddNum]->dst = strdup("hdb");
                hddNum++;
2594

2595 2596 2597 2598
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPS);
            }
2599

2600 2601 2602 2603
            if (hardDiskSS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2604

2605 2606
                hardDiskSS->vtbl->imedium.GetLocation((IMedium *)hardDiskSS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2607

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

2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
                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;
2628
            vboxArrayGet(&mediumAttachments, machine, machine->vtbl->GetMediumAttachments);
2629 2630

            /* get the number of attachments */
2631 2632
            for (i = 0; i < mediumAttachments.count; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2633 2634 2635 2636 2637 2638 2639
                if (imediumattach) {
                    IMedium *medium = NULL;

                    imediumattach->vtbl->GetMedium(imediumattach, &medium);
                    if (medium) {
                        def->ndisks++;
                        VBOX_RELEASE(medium);
2640 2641
                    }
                }
2642
            }
2643

2644 2645 2646 2647
            /* 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) {
2648
                        virReportOOMError();
2649 2650
                        error = true;
                        break;
2651 2652
                    }
                }
2653
            } else {
2654
                virReportOOMError();
2655 2656 2657 2658 2659 2660 2661
                error = true;
            }

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

            /* get the attachment details here */
2662 2663
            for (i = 0; i < mediumAttachments.count && diskCount < def->ndisks && !error; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
                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;
                }
2697

2698 2699 2700 2701 2702 2703 2704 2705 2706
                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);
2707
                    virReportOOMError();
2708 2709 2710
                    error = true;
                    break;
                }
2711

2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
                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;
                }
2722

2723 2724 2725 2726 2727 2728 2729 2730 2731 2732
                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);
2733
                def->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
2734 2735 2736 2737 2738 2739
                                                                    deviceInst,
                                                                    devicePort,
                                                                    deviceSlot,
                                                                    maxPortPerInst,
                                                                    maxSlotPerPort);
                if (!def->disks[diskCount]->dst) {
2740
                    vboxError(VIR_ERR_INTERNAL_ERROR,
2741 2742
                              _("Could not generate medium name for the disk "
                                "at: controller instance:%u, port:%d, slot:%d"),
2743 2744 2745 2746 2747 2748
                              deviceInst, devicePort, deviceSlot);
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2749

2750 2751 2752
                medium->vtbl->GetReadOnly(medium, &readOnly);
                if (readOnly == PR_TRUE)
                    def->disks[diskCount]->readonly = 1;
2753

2754
                def->disks[diskCount]->type = VIR_DOMAIN_DISK_TYPE_FILE;
2755

2756 2757 2758 2759
                VBOX_RELEASE(medium);
                VBOX_RELEASE(storageController);
                diskCount++;
            }
2760

2761
            vboxArrayRelease(&mediumAttachments);
2762

2763 2764 2765 2766 2767 2768 2769 2770
            /* cleanup on error */
            if (error) {
                for (i = 0; i < def->ndisks; i++) {
                    VIR_FREE(def->disks[i]);
                }
                VIR_FREE(def->disks);
                def->ndisks = 0;
            }
2771

2772
#endif /* VBOX_API_VERSION >= 3001 */
2773

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

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

2784 2785 2786 2787
                    adapter->vtbl->GetEnabled(adapter, &enabled);
                    if (enabled) {
                        def->nnets++;
                    }
2788

2789 2790 2791
                    VBOX_RELEASE(adapter);
                }
            }
2792

2793 2794 2795 2796 2797
            /* 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
2798
                        virReportOOMError();
2799 2800
                }
            }
2801

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

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

2810 2811 2812 2813 2814 2815 2816
                    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};
2817

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

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

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

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

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

2831 2832
                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
                            def->nets[netAdpIncCnt]->data.bridge.brname = strdup(hostInt);
2833

2834 2835
                            VBOX_UTF8_FREE(hostInt);
                            VBOX_UTF16_FREE(hostIntUtf16);
2836

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

2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
                            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 */
2887 2888
                        }

2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904
                        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);
2905
                    }
2906 2907

                    VBOX_RELEASE(adapter);
2908
                }
2909
            }
2910

2911
            /* dump sound card if active */
2912

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

2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936
            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;
2937
                            virReportOOMError();
2938 2939 2940
                        }
                    } else {
                        def->nsounds = 0;
2941
                        virReportOOMError();
2942 2943 2944 2945
                    }
                }
                VBOX_RELEASE(audioAdapter);
            }
2946

2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
#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");
2974
                            } else {
2975
                                def->ndisks--;
2976
                                virReportOOMError();
2977 2978
                            }
                        } else {
2979
                            def->ndisks--;
2980
                            virReportOOMError();
2981
                        }
2982 2983 2984 2985

                        VBOX_UTF8_FREE(location);
                        VBOX_UTF16_FREE(locationUtf16);
                        VBOX_MEDIUM_RELEASE(dvdImage);
2986 2987
                    }
                }
2988 2989
                VBOX_RELEASE(dvdDrive);
            }
2990

2991 2992 2993 2994 2995 2996 2997
            /* 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) {
2998 2999
                    PRUint32 state = DriveState_Null;

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

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

3009 3010
                            floppyImage->vtbl->imedium.GetLocation((IMedium *)floppyImage, &locationUtf16);
                            VBOX_UTF16_TO_UTF8(locationUtf16, &location);
3011 3012 3013 3014

                            def->ndisks++;
                            if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
                                if (VIR_ALLOC(def->disks[def->ndisks - 1]) >= 0) {
3015 3016
                                    def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                                    def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC;
3017
                                    def->disks[def->ndisks - 1]->type = VIR_DOMAIN_DISK_TYPE_FILE;
3018
                                    def->disks[def->ndisks - 1]->readonly = 0;
3019
                                    def->disks[def->ndisks - 1]->src = strdup(location);
3020
                                    def->disks[def->ndisks - 1]->dst = strdup("fda");
3021 3022
                                } else {
                                    def->ndisks--;
3023
                                    virReportOOMError();
3024 3025 3026
                                }
                            } else {
                                def->ndisks--;
3027
                                virReportOOMError();
3028 3029
                            }

3030 3031 3032
                            VBOX_UTF8_FREE(location);
                            VBOX_UTF16_FREE(locationUtf16);
                            VBOX_MEDIUM_RELEASE(floppyImage);
3033 3034 3035 3036
                        }
                    }
                }

3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
                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) {
3050 3051
                    PRBool enabled = PR_FALSE;

3052
                    serialPort->vtbl->GetEnabled(serialPort, &enabled);
3053
                    if (enabled) {
3054
                        def->nserials++;
3055 3056
                    }

3057
                    VBOX_RELEASE(serialPort);
3058
                }
3059
            }
3060

3061 3062 3063 3064 3065
            /* 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
3066
                        virReportOOMError();
3067 3068
                }
            }
3069

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

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

3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
                    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) {
3088
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_PIPE;
3089
                        } else if (hostMode == PortMode_HostDevice) {
3090
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_DEV;
3091 3092
#if VBOX_API_VERSION >= 3000
                        } else if (hostMode == PortMode_RawFile) {
3093
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
3094 3095
#endif /* VBOX_API_VERSION >= 3000 */
                        } else {
3096
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_NULL;
3097
                        }
3098

3099
                        def->serials[serialPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
3100

3101 3102 3103 3104 3105 3106 3107
                        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;
                        }
3108

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

3111 3112
                        if (pathUtf16) {
                            VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3113
                            def->serials[serialPortIncCount]->source.data.file.path = strdup(path);
3114 3115
                        }

3116 3117 3118 3119
                        serialPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
3120 3121
                    }

3122 3123 3124
                    VBOX_RELEASE(serialPort);
                }
            }
3125

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

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

3136 3137 3138
                    parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                    if (enabled) {
                        def->nparallels++;
3139
                    }
3140 3141

                    VBOX_RELEASE(parallelPort);
3142
                }
3143
            }
3144

3145 3146 3147 3148 3149
            /* 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
3150
                        virReportOOMError();
3151
                }
3152
            }
3153

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

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

3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175
                    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;
                        }
3176

3177
                        def->parallels[parallelPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
3178
                        def->parallels[parallelPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL;
3179

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

3182
                        VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3183
                        def->parallels[parallelPortIncCount]->source.data.file.path = strdup(path);
3184

3185 3186 3187 3188
                        parallelPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
3189
                    }
3190 3191

                    VBOX_RELEASE(parallelPort);
3192
                }
3193
            }
3194

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

3201 3202
                USBController->vtbl->GetEnabled(USBController, &enabled);
                if (enabled) {
3203
                    vboxArray deviceFilters = VBOX_ARRAY_INITIALIZER;
3204

3205 3206
                    vboxArrayGet(&deviceFilters, USBController,
                                 USBController->vtbl->GetDeviceFilters);
3207

3208
                    if (deviceFilters.count > 0) {
3209

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

3214
                        for(i = 0; i < deviceFilters.count; i++) {
3215
                            PRBool active = PR_FALSE;
3216
                            IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];
3217

3218
                            deviceFilter->vtbl->GetActive(deviceFilter, &active);
3219 3220
                            if (active) {
                                def->nhostdevs++;
3221
                            }
3222
                        }
3223

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

3228
                                for(i = 0; (USBFilterCount < def->nhostdevs) || (i < deviceFilters.count); i++) {
3229
                                    PRBool active = PR_FALSE;
3230
                                    IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];
3231

3232
                                    deviceFilter->vtbl->GetActive(deviceFilter, &active);
3233 3234 3235 3236 3237 3238 3239 3240 3241
                                    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;
3242

3243 3244 3245 3246
                                            def->hostdevs[USBFilterCount]->mode =
                                                VIR_DOMAIN_HOSTDEV_MODE_SUBSYS;
                                            def->hostdevs[USBFilterCount]->source.subsys.type =
                                                VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB;
3247

3248 3249
                                            deviceFilter->vtbl->GetVendorId(deviceFilter, &vendorIdUtf16);
                                            deviceFilter->vtbl->GetProductId(deviceFilter, &productIdUtf16);
3250

3251 3252
                                            VBOX_UTF16_TO_UTF8(vendorIdUtf16, &vendorIdUtf8);
                                            VBOX_UTF16_TO_UTF8(productIdUtf16, &productIdUtf8);
3253

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

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

3260 3261
                                            VBOX_UTF16_FREE(vendorIdUtf16);
                                            VBOX_UTF8_FREE(vendorIdUtf8);
3262

3263 3264
                                            VBOX_UTF16_FREE(productIdUtf16);
                                            VBOX_UTF8_FREE(productIdUtf8);
3265

3266 3267
                                            USBFilterCount++;
                                        } else
3268
                                            virReportOOMError();
3269
                                    }
3270 3271
                                }
                            } else
3272
                                virReportOOMError();
3273 3274 3275
                        }
                    }

3276
                    /* Cleanup */
3277
                    vboxArrayRelease(&deviceFilters);
3278 3279
                }
                VBOX_RELEASE(USBController);
3280
            }
3281 3282 3283 3284 3285

            /* all done so set gotAllABoutDef and pass def to virDomainDefFormat
             * to generate XML for it
             */
            gotAllABoutDef = 0;
3286
        }
3287 3288
        VBOX_RELEASE(machine);
        machine = NULL;
3289 3290 3291
    }

    if (gotAllABoutDef == 0)
3292
        ret = virDomainDefFormat(def, flags);
3293 3294

cleanup:
3295
    vboxIIDUnalloc(&iid);
3296 3297 3298 3299 3300
    virDomainDefFree(def);
    return ret;
}

static int vboxListDefinedDomains(virConnectPtr conn, char ** const names, int maxnames) {
3301
    VBOX_OBJECT_CHECK(conn, int, -1);
3302
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3303 3304 3305
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
3306
    nsresult rc;
3307 3308
    int i, j;

3309
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3310
    if (NS_FAILED(rc)) {
3311 3312 3313
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of Defined Domains, rc=%08x"),
                  (unsigned)rc);
3314 3315
        goto cleanup;
    }
3316

3317 3318 3319
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < maxnames); i++) {
        IMachine *machine = machines.items[i];
3320 3321 3322 3323 3324 3325 3326 3327 3328 3329

        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);
3330 3331 3332 3333
                    names[j] = strdup(machineName);
                    VBOX_UTF16_FREE(machineNameUtf16);
                    VBOX_UTF8_FREE(machineName);
                    if (!names[j]) {
3334
                        virReportOOMError();
3335 3336 3337 3338
                        for ( ; j >= 0 ; j--)
                            VIR_FREE(names[j]);
                        ret = -1;
                        goto cleanup;
3339
                    }
3340
                    j++;
3341
                    ret++;
3342 3343 3344 3345 3346 3347
                }
            }
        }
    }

cleanup:
3348
    vboxArrayRelease(&machines);
3349 3350 3351 3352
    return ret;
}

static int vboxNumOfDefinedDomains(virConnectPtr conn) {
3353
    VBOX_OBJECT_CHECK(conn, int, -1);
3354
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3355
    PRUint32 state       = MachineState_Null;
3356
    nsresult rc;
3357 3358
    int i;

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

3367 3368 3369
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3370 3371 3372 3373 3374 3375 3376 3377 3378

        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++;
3379 3380 3381 3382 3383 3384
                }
            }
        }
    }

cleanup:
3385
    vboxArrayRelease(&machines);
3386 3387 3388
    return ret;
}

E
Eric Blake 已提交
3389 3390

static int
3391 3392
vboxStartMachine(virDomainPtr dom, int i, IMachine *machine,
                 vboxIID *iid ATTRIBUTE_UNUSED /* >= 4.0 */)
E
Eric Blake 已提交
3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485
{
    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 已提交
3486 3487 3488 3489 3490 3491 3492
            char *displayutf8;
            if (virAsprintf(&displayutf8, "DISPLAY=%s", guiDisplay) < 0)
                virReportOOMError();
            else {
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3493 3494 3495 3496 3497 3498 3499 3500
            VIR_FREE(guiDisplay);
        }

        VBOX_UTF8_TO_UTF16("gui", &sessionType);
    }

    if (sdlPresent) {
        if (sdlDisplay) {
E
Eric Blake 已提交
3501 3502 3503 3504 3505 3506 3507
            char *displayutf8;
            if (virAsprintf(&displayutf8, "DISPLAY=%s", sdlDisplay) < 0)
                virReportOOMError();
            else {
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3508 3509 3510 3511 3512 3513 3514 3515 3516 3517
            VIR_FREE(sdlDisplay);
        }

        VBOX_UTF8_TO_UTF16("sdl", &sessionType);
    }

    if (vrdpPresent) {
        VBOX_UTF8_TO_UTF16("vrdp", &sessionType);
    }

3518
#if VBOX_API_VERSION < 4000
E
Eric Blake 已提交
3519 3520
    rc = data->vboxObj->vtbl->OpenRemoteSession(data->vboxObj,
                                                data->vboxSession,
3521
                                                iid->value,
E
Eric Blake 已提交
3522 3523 3524
                                                sessionType,
                                                env,
                                                &progress );
3525 3526 3527 3528 3529
#else /* VBOX_API_VERSION >= 4000 */
    rc = machine->vtbl->LaunchVMProcess(machine, data->vboxSession,
                                        sessionType, env, &progress);
#endif /* VBOX_API_VERSION >= 4000 */

E
Eric Blake 已提交
3530 3531
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_OPERATION_FAILED, "%s",
3532
                  _("OpenRemoteSession/LaunchVMProcess failed, domain can't be started"));
E
Eric Blake 已提交
3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559
        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);

3560
    VBOX_SESSION_CLOSE();
E
Eric Blake 已提交
3561 3562 3563 3564 3565 3566 3567

    VBOX_UTF16_FREE(env);
    VBOX_UTF16_FREE(sessionType);

    return ret;
}

3568
static int vboxDomainCreateWithFlags(virDomainPtr dom, unsigned int flags) {
3569
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
3570
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3571
    unsigned char uuid[VIR_UUID_BUFLEN] = {0};
3572 3573
    nsresult rc;
    int i = 0;
3574

3575 3576
    virCheckFlags(0, -1);

3577
    if (!dom->name) {
3578
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
3579
                  _("Error while reading the domain name"));
3580 3581 3582
        goto cleanup;
    }

3583
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3584
    if (NS_FAILED(rc)) {
3585 3586
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("Could not get list of machines, rc=%08x"), (unsigned)rc);
3587 3588
        goto cleanup;
    }
3589

3590 3591
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3592
        PRBool isAccessible = PR_FALSE;
3593

3594 3595
        if (!machine)
            continue;
3596

3597 3598
        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
3599
            vboxIID iid = VBOX_IID_INITIALIZER;
3600

3601 3602
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
3603
                continue;
3604
            vboxIIDToUUID(&iid, uuid);
3605

3606
            if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {
3607 3608 3609 3610 3611 3612
                PRUint32 state = MachineState_Null;
                machine->vtbl->GetState(machine, &state);

                if ( (state == MachineState_PoweredOff) ||
                     (state == MachineState_Saved) ||
                     (state == MachineState_Aborted) ) {
3613
                    ret = vboxStartMachine(dom, i, machine, &iid);
3614
                } else {
3615 3616 3617
                    vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                              _("machine is not in poweroff|saved|"
                                "aborted state, so couldn't start it"));
3618
                    ret = -1;
3619 3620
                }
            }
3621
            vboxIIDUnalloc(&iid);
3622 3623
            if (ret != -1)
                break;
3624 3625 3626
        }
    }

3627
    /* Do the cleanup and take care you dont leak any memory */
3628
    vboxArrayRelease(&machines);
3629

3630 3631 3632 3633
cleanup:
    return ret;
}

3634 3635 3636 3637
static int vboxDomainCreate(virDomainPtr dom) {
    return vboxDomainCreateWithFlags(dom, 0);
}

E
Eric Blake 已提交
3638 3639 3640 3641 3642 3643 3644
static void
vboxSetBootDeviceOrder(virDomainDefPtr def, vboxGlobalData *data,
                       IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 maxBootPosition            = 0;
    int i = 0;
3645

3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661
    VIR_DEBUG("def->os.type             %s", def->os.type);
    VIR_DEBUG("def->os.arch             %s", def->os.arch);
    VIR_DEBUG("def->os.machine          %s", def->os.machine);
    VIR_DEBUG("def->os.nBootDevs        %d", def->os.nBootDevs);
    VIR_DEBUG("def->os.bootDevs[0]      %d", def->os.bootDevs[0]);
    VIR_DEBUG("def->os.bootDevs[1]      %d", def->os.bootDevs[1]);
    VIR_DEBUG("def->os.bootDevs[2]      %d", def->os.bootDevs[2]);
    VIR_DEBUG("def->os.bootDevs[3]      %d", def->os.bootDevs[3]);
    VIR_DEBUG("def->os.init             %s", def->os.init);
    VIR_DEBUG("def->os.kernel           %s", def->os.kernel);
    VIR_DEBUG("def->os.initrd           %s", def->os.initrd);
    VIR_DEBUG("def->os.cmdline          %s", def->os.cmdline);
    VIR_DEBUG("def->os.root             %s", def->os.root);
    VIR_DEBUG("def->os.loader           %s", def->os.loader);
    VIR_DEBUG("def->os.bootloader       %s", def->os.bootloader);
    VIR_DEBUG("def->os.bootloaderArgs   %s", def->os.bootloaderArgs);
3662

E
Eric Blake 已提交
3663 3664 3665 3666 3667 3668
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxBootPosition(systemProperties,
                                                   &maxBootPosition);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
3669
    }
3670

E
Eric Blake 已提交
3671 3672 3673
    /* Clear the defaults first */
    for (i = 0; i < maxBootPosition; i++) {
        machine->vtbl->SetBootOrder(machine, i+1, DeviceType_Null);
3674
    }
3675

E
Eric Blake 已提交
3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686
    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;
3687
        }
E
Eric Blake 已提交
3688
        machine->vtbl->SetBootOrder(machine, i+1, device);
3689
    }
E
Eric Blake 已提交
3690
}
3691

E
Eric Blake 已提交
3692 3693 3694 3695 3696
static void
vboxAttachDrives(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    int i;
    nsresult rc;
3697 3698

#if VBOX_API_VERSION < 3001
E
Eric Blake 已提交
3699 3700 3701 3702
    if (def->ndisks == 0)
        return;

    for (i = 0; i < def->ndisks; i++) {
3703 3704 3705 3706 3707 3708 3709 3710 3711
        VIR_DEBUG("disk(%d) type:       %d", i, def->disks[i]->type);
        VIR_DEBUG("disk(%d) device:     %d", i, def->disks[i]->device);
        VIR_DEBUG("disk(%d) bus:        %d", i, def->disks[i]->bus);
        VIR_DEBUG("disk(%d) src:        %s", i, def->disks[i]->src);
        VIR_DEBUG("disk(%d) dst:        %s", i, def->disks[i]->dst);
        VIR_DEBUG("disk(%d) driverName: %s", i, def->disks[i]->driverName);
        VIR_DEBUG("disk(%d) driverType: %s", i, def->disks[i]->driverType);
        VIR_DEBUG("disk(%d) cachemode:  %d", i, def->disks[i]->cachemode);
        VIR_DEBUG("disk(%d) readonly:   %s", i, (def->disks[i]->readonly
E
Eric Blake 已提交
3712
                                             ? "True" : "False"));
3713
        VIR_DEBUG("disk(%d) shared:     %s", i, (def->disks[i]->shared
E
Eric Blake 已提交
3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
                                             ? "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
                 */
3726

E
Eric Blake 已提交
3727 3728 3729 3730
                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                if (dvdDrive) {
                    IDVDImage *dvdImage          = NULL;
                    PRUnichar *dvdfileUtf16      = NULL;
3731 3732
                    vboxIID dvduuid = VBOX_IID_INITIALIZER;
                    vboxIID dvdemptyuuid = VBOX_IID_INITIALIZER;
3733

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

E
Eric Blake 已提交
3736 3737 3738 3739 3740
                    data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                      dvdfileUtf16, &dvdImage);
                    if (!dvdImage) {
                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                          dvdfileUtf16,
3741
                                                          dvdemptyuuid.value,
E
Eric Blake 已提交
3742 3743 3744 3745
                                                          &dvdImage);
                    }
                    if (dvdImage) {
                        rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage,
3746
                                                           &dvduuid.value);
E
Eric Blake 已提交
3747 3748 3749 3750 3751 3752
                        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 {
3753
                            rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid.value);
E
Eric Blake 已提交
3754 3755 3756 3757 3758
                            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 {
3759
                                DEBUGIID("CD/DVDImage UUID:", dvduuid.value);
3760
                            }
3761
                        }
E
Eric Blake 已提交
3762 3763

                        VBOX_MEDIUM_RELEASE(dvdImage);
3764
                    }
3765
                    vboxIIDUnalloc(&dvduuid);
E
Eric Blake 已提交
3766 3767 3768 3769 3770 3771 3772 3773 3774 3775
                    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;
3776
                vboxIID hdduuid = VBOX_IID_INITIALIZER;
E
Eric Blake 已提交
3777 3778 3779 3780 3781 3782
                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
                 */
3783

E
Eric Blake 已提交
3784 3785
                VBOX_UTF8_TO_UTF16(def->disks[i]->src, &hddfileUtf16);
                VBOX_UTF8_TO_UTF16("", &hddEmpty);
3786

E
Eric Blake 已提交
3787 3788
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddfileUtf16,
                                                  &hardDisk);
3789

E
Eric Blake 已提交
3790
                if (!hardDisk) {
3791
# if VBOX_API_VERSION == 2002
E
Eric Blake 已提交
3792 3793 3794 3795
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      &hardDisk);
3796
# else
E
Eric Blake 已提交
3797 3798 3799 3800 3801 3802 3803 3804
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      0,
                                                      hddEmpty,
                                                      0,
                                                      hddEmpty,
                                                      &hardDisk);
3805
# endif
E
Eric Blake 已提交
3806
                }
3807

E
Eric Blake 已提交
3808 3809
                if (hardDisk) {
                    rc = hardDisk->vtbl->imedium.GetId((IMedium *)hardDisk,
3810
                                                       &hdduuid.value);
E
Eric Blake 已提交
3811 3812 3813 3814 3815 3816 3817 3818 3819
                    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);
3820
                            VIR_DEBUG("setting harddisk to readonly");
E
Eric Blake 已提交
3821 3822 3823
                        } else if (!def->disks[i]->readonly) {
                            hardDisk->vtbl->SetType(hardDisk,
                                                    HardDiskType_Normal);
3824
                            VIR_DEBUG("setting harddisk type to normal");
E
Eric Blake 已提交
3825 3826 3827
                        }
                        if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_IDE) {
                            if (STREQ(def->disks[i]->dst, "hdc")) {
3828
                                VIR_DEBUG("Not connecting harddisk to hdc as hdc"
E
Eric Blake 已提交
3829
                                       " is taken by CD/DVD Drive");
3830
                            } else {
E
Eric Blake 已提交
3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
                                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;
3848
                                }
E
Eric Blake 已提交
3849 3850

                                rc = machine->vtbl->AttachHardDisk(machine,
3851
                                                                   hdduuid.value,
E
Eric Blake 已提交
3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862
                                                                   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 {
3863
                                    DEBUGIID("Attached HDD with UUID", hdduuid.value);
3864 3865 3866
                                }
                            }
                        }
3867
                    }
E
Eric Blake 已提交
3868 3869
                    VBOX_MEDIUM_RELEASE(hardDisk);
                }
3870
                vboxIIDUnalloc(&hdduuid);
E
Eric Blake 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884
                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;
3885 3886
                        vboxIID fduuid = VBOX_IID_INITIALIZER;
                        vboxIID fdemptyuuid = VBOX_IID_INITIALIZER;
3887

E
Eric Blake 已提交
3888 3889 3890 3891
                        VBOX_UTF8_TO_UTF16(def->disks[i]->src, &fdfileUtf16);
                        rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                  fdfileUtf16,
                                                                  &floppyImage);
3892

E
Eric Blake 已提交
3893 3894 3895
                        if (!floppyImage) {
                            data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                 fdfileUtf16,
3896
                                                                 fdemptyuuid.value,
E
Eric Blake 已提交
3897 3898
                                                                 &floppyImage);
                        }
3899

E
Eric Blake 已提交
3900 3901
                        if (floppyImage) {
                            rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage,
3902
                                                                  &fduuid.value);
E
Eric Blake 已提交
3903 3904 3905 3906 3907 3908 3909
                            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,
3910
                                                                   fduuid.value);
E
Eric Blake 已提交
3911 3912 3913 3914 3915 3916
                                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 {
3917
                                    DEBUGIID("floppyImage UUID", fduuid.value);
3918 3919
                                }
                            }
E
Eric Blake 已提交
3920
                            VBOX_MEDIUM_RELEASE(floppyImage);
3921
                        }
3922
                        vboxIIDUnalloc(&fduuid);
E
Eric Blake 已提交
3923
                        VBOX_UTF16_FREE(fdfileUtf16);
3924
                    }
E
Eric Blake 已提交
3925
                    VBOX_RELEASE(floppyDrive);
3926
                }
E
Eric Blake 已提交
3927
            } else if (def->disks[i]->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
3928
            }
3929
        }
E
Eric Blake 已提交
3930
    }
3931
#else  /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
    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 */
3944
    {
E
Eric Blake 已提交
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979
        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);
    }
3980

E
Eric Blake 已提交
3981
    for (i = 0; i < def->ndisks && !error; i++) {
3982 3983 3984 3985 3986 3987 3988 3989 3990
        VIR_DEBUG("disk(%d) type:       %d", i, def->disks[i]->type);
        VIR_DEBUG("disk(%d) device:     %d", i, def->disks[i]->device);
        VIR_DEBUG("disk(%d) bus:        %d", i, def->disks[i]->bus);
        VIR_DEBUG("disk(%d) src:        %s", i, def->disks[i]->src);
        VIR_DEBUG("disk(%d) dst:        %s", i, def->disks[i]->dst);
        VIR_DEBUG("disk(%d) driverName: %s", i, def->disks[i]->driverName);
        VIR_DEBUG("disk(%d) driverType: %s", i, def->disks[i]->driverType);
        VIR_DEBUG("disk(%d) cachemode:  %d", i, def->disks[i]->cachemode);
        VIR_DEBUG("disk(%d) readonly:   %s", i, (def->disks[i]->readonly
E
Eric Blake 已提交
3991
                                             ? "True" : "False"));
3992
        VIR_DEBUG("disk(%d) shared:     %s", i, (def->disks[i]->shared
E
Eric Blake 已提交
3993 3994 3995 3996 3997 3998 3999 4000 4001
                                             ? "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;
4002
# if VBOX_API_VERSION >= 4000
4003
            PRUint32   accessMode      = AccessMode_ReadOnly;
4004
# endif
E
Eric Blake 已提交
4005 4006 4007 4008 4009 4010 4011 4012
            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;
4013
# if VBOX_API_VERSION < 4000
E
Eric Blake 已提交
4014 4015
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj,
                                                  mediumFileUtf16, &medium);
4016 4017
# else
                accessMode = AccessMode_ReadWrite;
4018
# endif
E
Eric Blake 已提交
4019 4020
            } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                deviceType = DeviceType_DVD;
4021
# if VBOX_API_VERSION < 4000
E
Eric Blake 已提交
4022 4023
                data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                  mediumFileUtf16, &medium);
4024 4025
# else
                accessMode = AccessMode_ReadOnly;
4026
# endif
E
Eric Blake 已提交
4027 4028
            } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                deviceType = DeviceType_Floppy;
4029
# if VBOX_API_VERSION < 4000
E
Eric Blake 已提交
4030 4031
                data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                     mediumFileUtf16, &medium);
4032 4033
# else
                accessMode = AccessMode_ReadWrite;
4034
# endif
E
Eric Blake 已提交
4035 4036 4037 4038
            } else {
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
4039

4040 4041 4042 4043 4044
# if VBOX_API_VERSION >= 4000
            data->vboxObj->vtbl->FindMedium(data->vboxObj, mediumFileUtf16,
                                            deviceType, &medium);
# endif

E
Eric Blake 已提交
4045 4046
            if (!medium) {
                PRUnichar *mediumEmpty = NULL;
4047

E
Eric Blake 已提交
4048
                VBOX_UTF8_TO_UTF16("", &mediumEmpty);
4049

4050
# if VBOX_API_VERSION < 4000
4051
                if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
4052 4053 4054 4055 4056 4057 4058 4059
                    rc = data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                           mediumFileUtf16,
                                                           AccessMode_ReadWrite,
                                                           false,
                                                           mediumEmpty,
                                                           false,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
4060 4061
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_CDROM) {
4062 4063 4064 4065
                    rc = data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                           mediumFileUtf16,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
4066 4067
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
4068 4069 4070 4071 4072 4073
                    rc = data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                              mediumFileUtf16,
                                                              mediumEmpty,
                                                              &medium);
                } else {
                    rc = 0;
4074
                }
4075 4076 4077 4078 4079 4080
# else /* VBOX_API_VERSION >= 4000 */
                rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                     mediumFileUtf16,
                                                     deviceType, accessMode,
                                                     &medium);
# endif /* VBOX_API_VERSION >= 4000 */
4081

E
Eric Blake 已提交
4082 4083
                VBOX_UTF16_FREE(mediumEmpty);
            }
4084

E
Eric Blake 已提交
4085 4086 4087 4088 4089 4090 4091 4092
            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;
            }
4093

E
Eric Blake 已提交
4094 4095 4096 4097 4098 4099 4100 4101 4102 4103
            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;
            }
4104

E
Eric Blake 已提交
4105 4106 4107
            if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                if (def->disks[i]->readonly) {
                    medium->vtbl->SetType(medium, MediumType_Immutable);
4108
                    VIR_DEBUG("setting harddisk to immutable");
E
Eric Blake 已提交
4109 4110
                } else if (!def->disks[i]->readonly) {
                    medium->vtbl->SetType(medium, MediumType_Normal);
4111
                    VIR_DEBUG("setting harddisk type to normal");
4112
                }
E
Eric Blake 已提交
4113
            }
4114

E
Eric Blake 已提交
4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127
            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;
            }
4128

E
Eric Blake 已提交
4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140
            /* 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);
4141 4142 4143
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumUUID);
                VBOX_UTF16_FREE(mediumFileUtf16);
E
Eric Blake 已提交
4144 4145 4146 4147 4148 4149 4150 4151 4152
                continue;
            }

            /* attach the harddisk/dvd/Floppy to the storage controller */
            rc = machine->vtbl->AttachDevice(machine,
                                             storageCtlName,
                                             devicePort,
                                             deviceSlot,
                                             deviceType,
4153
# if VBOX_API_VERSION < 4000
E
Eric Blake 已提交
4154
                                             mediumUUID);
4155 4156 4157
# else /* VBOX_API_VERSION >= 4000 */
                                             medium);
# endif /* VBOX_API_VERSION >= 4000 */
E
Eric Blake 已提交
4158 4159 4160 4161 4162 4163 4164 4165

            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);
4166
            }
E
Eric Blake 已提交
4167 4168 4169 4170 4171

            VBOX_RELEASE(medium);
            VBOX_UTF16_FREE(mediumUUID);
            VBOX_UTF16_FREE(mediumFileUtf16);
            VBOX_UTF16_FREE(storageCtlName);
4172 4173 4174
        }
    }
#endif /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
4175
}
4176

E
Eric Blake 已提交
4177 4178 4179 4180
static void
vboxAttachSound(virDomainDefPtr def, IMachine *machine)
{
    nsresult rc;
4181

E
Eric Blake 已提交
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
    /* 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);
4198
                }
4199
            }
E
Eric Blake 已提交
4200
            VBOX_RELEASE(audioAdapter);
4201
        }
E
Eric Blake 已提交
4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219
    }
}

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

4220 4221
    VIR_DEBUG("Number of Network Cards to be connected: %d", def->nnets);
    VIR_DEBUG("Number of Network Cards available: %d", networkAdapterCount);
E
Eric Blake 已提交
4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239

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

4240 4241 4242 4243
        VIR_DEBUG("NIC(%d): Type:   %d", i, def->nets[i]->type);
        VIR_DEBUG("NIC(%d): Model:  %s", i, def->nets[i]->model);
        VIR_DEBUG("NIC(%d): Mac:    %s", i, macaddr);
        VIR_DEBUG("NIC(%d): ifname: %s", i, def->nets[i]->ifname);
E
Eric Blake 已提交
4244
        if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
4245
            VIR_DEBUG("NIC(%d): name:    %s", i, def->nets[i]->data.network.name);
E
Eric Blake 已提交
4246
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
4247
            VIR_DEBUG("NIC(%d): name:   %s", i, def->nets[i]->data.internal.name);
E
Eric Blake 已提交
4248
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
4249
            VIR_DEBUG("NIC(%d): NAT.", i);
E
Eric Blake 已提交
4250
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
4251 4252 4253
            VIR_DEBUG("NIC(%d): brname: %s", i, def->nets[i]->data.bridge.brname);
            VIR_DEBUG("NIC(%d): script: %s", i, def->nets[i]->data.bridge.script);
            VIR_DEBUG("NIC(%d): ipaddr: %s", i, def->nets[i]->data.bridge.ipaddr);
4254 4255
        }

E
Eric Blake 已提交
4256 4257 4258 4259 4260
        machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
        if (adapter) {
            PRUnichar *MACAddress = NULL;

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

E
Eric Blake 已提交
4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
            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;
4273
#if VBOX_API_VERSION >= 3001
E
Eric Blake 已提交
4274 4275
                } else if (STRCASEEQ(def->nets[i]->model , "virtio")) {
                    adapterType = NetworkAdapterType_Virtio;
4276 4277
#endif /* VBOX_API_VERSION >= 3001 */
                }
E
Eric Blake 已提交
4278 4279 4280
            } else {
                adapterType = NetworkAdapterType_Am79C973;
            }
4281

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

E
Eric Blake 已提交
4284 4285 4286
            if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
                PRUnichar *hostInterface = NULL;
                /* Bridged Network */
4287

E
Eric Blake 已提交
4288
                adapter->vtbl->AttachToBridgedInterface(adapter);
4289

E
Eric Blake 已提交
4290 4291 4292 4293 4294 4295 4296 4297 4298
                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 */
4299

E
Eric Blake 已提交
4300
                adapter->vtbl->AttachToInternalNetwork(adapter);
4301

E
Eric Blake 已提交
4302 4303 4304 4305 4306
                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);
4307
                }
E
Eric Blake 已提交
4308 4309 4310 4311 4312 4313 4314
            } 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);
4315

E
Eric Blake 已提交
4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329
                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);
4330
            }
E
Eric Blake 已提交
4331 4332 4333 4334

            VBOX_UTF8_TO_UTF16(macaddrvbox, &MACAddress);
            adapter->vtbl->SetMACAddress(adapter, MACAddress);
            VBOX_UTF16_FREE(MACAddress);
4335
        }
E
Eric Blake 已提交
4336 4337 4338 4339 4340 4341 4342 4343 4344
    }
}

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

E
Eric Blake 已提交
4346 4347 4348 4349 4350 4351 4352
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetSerialPortCount(systemProperties,
                                                   &serialPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4353

4354 4355
    VIR_DEBUG("Number of Serial Ports to be connected: %d", def->nserials);
    VIR_DEBUG("Number of Serial Ports available: %d", serialPortCount);
E
Eric Blake 已提交
4356 4357
    for (i = 0; (i < def->nserials) && (i < serialPortCount); i++) {
        ISerialPort *serialPort = NULL;
4358

4359 4360
        VIR_DEBUG("SerialPort(%d): Type: %d", i, def->serials[i]->source.type);
        VIR_DEBUG("SerialPort(%d): target.port: %d", i,
E
Eric Blake 已提交
4361
              def->serials[i]->target.port);
4362

E
Eric Blake 已提交
4363 4364 4365
        machine->vtbl->GetSerialPort(machine, i, &serialPort);
        if (serialPort) {
            PRUnichar *pathUtf16 = NULL;
4366

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

4369 4370 4371
            if (def->serials[i]->source.data.file.path) {
                VBOX_UTF8_TO_UTF16(def->serials[i]->source.data.file.path,
                                   &pathUtf16);
E
Eric Blake 已提交
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386
                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);
4387
                VIR_DEBUG(" serialPort-%d irq: %d, iobase 0x%x, path: %s",
4388
                      i, 4, 1016, def->serials[i]->source.data.file.path);
E
Eric Blake 已提交
4389 4390 4391
            } else if (def->serials[i]->target.port == 1) {
                serialPort->vtbl->SetIRQ(serialPort, 3);
                serialPort->vtbl->SetIOBase(serialPort, 760);
4392
                VIR_DEBUG(" serialPort-%d irq: %d, iobase 0x%x, path: %s",
4393
                      i, 3, 760, def->serials[i]->source.data.file.path);
E
Eric Blake 已提交
4394
            }
4395

4396
            if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_DEV) {
E
Eric Blake 已提交
4397
                serialPort->vtbl->SetHostMode(serialPort, PortMode_HostDevice);
4398
            } else if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PIPE) {
E
Eric Blake 已提交
4399
                serialPort->vtbl->SetHostMode(serialPort, PortMode_HostPipe);
4400
#if VBOX_API_VERSION >= 3000
4401
            } else if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_FILE) {
E
Eric Blake 已提交
4402
                serialPort->vtbl->SetHostMode(serialPort, PortMode_RawFile);
4403
#endif /* VBOX_API_VERSION >= 3000 */
E
Eric Blake 已提交
4404 4405 4406 4407
            } else {
                serialPort->vtbl->SetHostMode(serialPort,
                                              PortMode_Disconnected);
            }
4408

E
Eric Blake 已提交
4409 4410 4411 4412
            VBOX_RELEASE(serialPort);
            if (pathUtf16) {
                VBOX_UTF16_FREE(pathUtf16);
                pathUtf16 = NULL;
4413
            }
4414
        }
E
Eric Blake 已提交
4415 4416
    }
}
4417

E
Eric Blake 已提交
4418 4419 4420 4421 4422 4423
static void
vboxAttachParallel(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 parallelPortCount          = 0;
    int i = 0;
4424

E
Eric Blake 已提交
4425 4426 4427 4428 4429 4430 4431
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetParallelPortCount(systemProperties,
                                                     &parallelPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4432

4433 4434
    VIR_DEBUG("Number of Parallel Ports to be connected: %d", def->nparallels);
    VIR_DEBUG("Number of Parallel Ports available: %d", parallelPortCount);
E
Eric Blake 已提交
4435 4436
    for (i = 0; (i < def->nparallels) && (i < parallelPortCount); i++) {
        IParallelPort *parallelPort = NULL;
4437

4438 4439
        VIR_DEBUG("ParallelPort(%d): Type: %d", i, def->parallels[i]->source.type);
        VIR_DEBUG("ParallelPort(%d): target.port: %d", i,
E
Eric Blake 已提交
4440
              def->parallels[i]->target.port);
4441

E
Eric Blake 已提交
4442 4443 4444
        machine->vtbl->GetParallelPort(machine, i, &parallelPort);
        if (parallelPort) {
            PRUnichar *pathUtf16 = NULL;
4445

4446
            VBOX_UTF8_TO_UTF16(def->parallels[i]->source.data.file.path, &pathUtf16);
4447

E
Eric Blake 已提交
4448 4449 4450 4451 4452
            /* 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
             */
4453 4454 4455 4456
            if ((def->parallels[i]->source.type == VIR_DOMAIN_CHR_TYPE_DEV)  ||
                (def->parallels[i]->source.type == VIR_DOMAIN_CHR_TYPE_PTY)  ||
                (def->parallels[i]->source.type == VIR_DOMAIN_CHR_TYPE_FILE) ||
                (def->parallels[i]->source.type == VIR_DOMAIN_CHR_TYPE_PIPE)) {
E
Eric Blake 已提交
4457 4458 4459 4460
                parallelPort->vtbl->SetPath(parallelPort, pathUtf16);
                if (i == 0) {
                    parallelPort->vtbl->SetIRQ(parallelPort, 7);
                    parallelPort->vtbl->SetIOBase(parallelPort, 888);
4461
                    VIR_DEBUG(" parallePort-%d irq: %d, iobase 0x%x, path: %s",
4462
                          i, 7, 888, def->parallels[i]->source.data.file.path);
E
Eric Blake 已提交
4463 4464 4465
                } else if (i == 1) {
                    parallelPort->vtbl->SetIRQ(parallelPort, 5);
                    parallelPort->vtbl->SetIOBase(parallelPort, 632);
4466
                    VIR_DEBUG(" parallePort-%d irq: %d, iobase 0x%x, path: %s",
4467
                          i, 5, 632, def->parallels[i]->source.data.file.path);
4468 4469
                }
            }
E
Eric Blake 已提交
4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480

            /* 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;
            }
4481
        }
E
Eric Blake 已提交
4482 4483 4484 4485 4486 4487 4488 4489
    }
}

static void
vboxAttachVideo(virDomainDefPtr def, IMachine *machine)
{
    if ((def->nvideos == 1) &&
        (def->videos[0]->type == VIR_DOMAIN_VIDEO_TYPE_VBOX)) {
4490 4491
        machine->vtbl->SetVRAMSize(machine,
                                   VIR_DIV_UP(def->videos[0]->vram, 1024));
E
Eric Blake 已提交
4492 4493 4494 4495
        machine->vtbl->SetMonitorCount(machine, def->videos[0]->heads);
        if (def->videos[0]->accel) {
            machine->vtbl->SetAccelerate3DEnabled(machine,
                                                  def->videos[0]->accel->support3d);
4496
#if VBOX_API_VERSION >= 3001
E
Eric Blake 已提交
4497 4498
            machine->vtbl->SetAccelerate2DVideoEnabled(machine,
                                                       def->videos[0]->accel->support2d);
4499
#endif /* VBOX_API_VERSION >= 3001 */
E
Eric Blake 已提交
4500 4501
        } else {
            machine->vtbl->SetAccelerate3DEnabled(machine, 0);
4502
#if VBOX_API_VERSION >= 3001
E
Eric Blake 已提交
4503
            machine->vtbl->SetAccelerate2DVideoEnabled(machine, 0);
4504 4505
#endif /* VBOX_API_VERSION >= 3001 */
        }
E
Eric Blake 已提交
4506 4507
    }
}
4508

E
Eric Blake 已提交
4509 4510 4511 4512 4513 4514 4515 4516 4517
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;
4518

E
Eric Blake 已提交
4519
    for (i = 0; i < def->ngraphics; i++) {
4520 4521 4522 4523 4524
#if VBOX_API_VERSION < 4000
        IVRDPServer *VRDxServer = NULL;
#else /* VBOX_API_VERSION >= 4000 */
        IVRDEServer *VRDxServer = NULL;
#endif /* VBOX_API_VERSION >= 4000 */
4525

E
Eric Blake 已提交
4526 4527
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) &&
            (vrdpPresent == 0)) {
4528

E
Eric Blake 已提交
4529
            vrdpPresent = 1;
4530 4531 4532 4533 4534 4535
#if VBOX_API_VERSION < 4000
            machine->vtbl->GetVRDPServer(machine, &VRDxServer);
#else /* VBOX_API_VERSION >= 4000 */
            machine->vtbl->GetVRDEServer(machine, &VRDxServer);
#endif /* VBOX_API_VERSION >= 4000 */
            if (VRDxServer) {
4536 4537 4538
                const char *listenAddr
                    = virDomainGraphicsListenGetAddress(def->graphics[i], 0);

4539
                VRDxServer->vtbl->SetEnabled(VRDxServer, PR_TRUE);
4540
                VIR_DEBUG("VRDP Support turned ON.");
4541 4542

#if VBOX_API_VERSION < 3001
E
Eric Blake 已提交
4543
                if (def->graphics[i]->data.rdp.port) {
4544
                    VRDxServer->vtbl->SetPort(VRDxServer,
E
Eric Blake 已提交
4545
                                              def->graphics[i]->data.rdp.port);
4546
                    VIR_DEBUG("VRDP Port changed to: %d",
E
Eric Blake 已提交
4547 4548 4549 4550 4551
                          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
                     */
4552
                    VRDxServer->vtbl->SetPort(VRDxServer, 0);
4553
                    VIR_DEBUG("VRDP Port changed to default, which is 3389 currently");
E
Eric Blake 已提交
4554
                }
4555
#elif VBOX_API_VERSION < 4000 /* 3001 <= VBOX_API_VERSION < 4000 */
E
Eric Blake 已提交
4556 4557
                PRUnichar *portUtf16 = NULL;
                portUtf16 = PRUnicharFromInt(def->graphics[i]->data.rdp.port);
4558
                VRDxServer->vtbl->SetPorts(VRDxServer, portUtf16);
E
Eric Blake 已提交
4559
                VBOX_UTF16_FREE(portUtf16);
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569
#else /* VBOX_API_VERSION >= 4000 */
                PRUnichar *VRDEPortsKey = NULL;
                PRUnichar *VRDEPortsValue = NULL;
                VBOX_UTF8_TO_UTF16("TCP/Ports", &VRDEPortsKey);
                VRDEPortsValue = PRUnicharFromInt(def->graphics[i]->data.rdp.port);
                VRDxServer->vtbl->SetVRDEProperty(VRDxServer, VRDEPortsKey,
                                                  VRDEPortsValue);
                VBOX_UTF16_FREE(VRDEPortsKey);
                VBOX_UTF16_FREE(VRDEPortsValue);
#endif /* VBOX_API_VERSION >= 4000 */
4570

E
Eric Blake 已提交
4571
                if (def->graphics[i]->data.rdp.replaceUser) {
4572
                    VRDxServer->vtbl->SetReuseSingleConnection(VRDxServer,
E
Eric Blake 已提交
4573
                                                               PR_TRUE);
4574
                    VIR_DEBUG("VRDP set to reuse single connection");
E
Eric Blake 已提交
4575
                }
4576

E
Eric Blake 已提交
4577
                if (def->graphics[i]->data.rdp.multiUser) {
4578
                    VRDxServer->vtbl->SetAllowMultiConnection(VRDxServer,
E
Eric Blake 已提交
4579
                                                              PR_TRUE);
4580
                    VIR_DEBUG("VRDP set to allow multiple connection");
E
Eric Blake 已提交
4581
                }
4582

4583
                if (listenAddr) {
4584 4585 4586
#if VBOX_API_VERSION >= 4000
                    PRUnichar *netAddressKey = NULL;
#endif
E
Eric Blake 已提交
4587
                    PRUnichar *netAddressUtf16 = NULL;
4588

4589
                    VBOX_UTF8_TO_UTF16(listenAddr, &netAddressUtf16);
4590 4591
#if VBOX_API_VERSION < 4000
                    VRDxServer->vtbl->SetNetAddress(VRDxServer,
E
Eric Blake 已提交
4592
                                                    netAddressUtf16);
4593 4594 4595 4596 4597 4598
#else /* VBOX_API_VERSION >= 4000 */
                    VBOX_UTF8_TO_UTF16("TCP/Address", &netAddressKey);
                    VRDxServer->vtbl->SetVRDEProperty(VRDxServer, netAddressKey,
                                                      netAddressUtf16);
                    VBOX_UTF16_FREE(netAddressKey);
#endif /* VBOX_API_VERSION >= 4000 */
4599
                    VIR_DEBUG("VRDP listen address is set to: %s",
4600
                              listenAddr);
4601

E
Eric Blake 已提交
4602
                    VBOX_UTF16_FREE(netAddressUtf16);
4603
                }
E
Eric Blake 已提交
4604

4605
                VBOX_RELEASE(VRDxServer);
4606
            }
E
Eric Blake 已提交
4607
        }
4608

E
Eric Blake 已提交
4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619
        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
                     */
4620
                }
4621
            }
E
Eric Blake 已提交
4622
        }
4623

E
Eric Blake 已提交
4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634
        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
                     */
4635
                }
4636
            }
4637
        }
E
Eric Blake 已提交
4638
    }
4639

E
Eric Blake 已提交
4640 4641 4642 4643
    if ((vrdpPresent == 1) && (guiPresent == 0) && (sdlPresent == 0)) {
        /* store extradata key that frontend is set to vrdp */
        PRUnichar *keyTypeUtf16   = NULL;
        PRUnichar *valueTypeUtf16 = NULL;
4644

E
Eric Blake 已提交
4645 4646
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("vrdp", &valueTypeUtf16);
4647

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

E
Eric Blake 已提交
4650 4651
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4652

E
Eric Blake 已提交
4653 4654 4655 4656 4657 4658
    } 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;
4659

E
Eric Blake 已提交
4660 4661
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("sdl", &valueTypeUtf16);
4662

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

E
Eric Blake 已提交
4665 4666
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4667

E
Eric Blake 已提交
4668 4669 4670
        if (sdlDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(sdlDisplay, &valueDisplayUtf16);
4671

E
Eric Blake 已提交
4672 4673
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4674

E
Eric Blake 已提交
4675 4676 4677
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
        }
4678

E
Eric Blake 已提交
4679 4680 4681 4682 4683 4684
    } 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;
4685

E
Eric Blake 已提交
4686 4687
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("gui", &valueTypeUtf16);
4688

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

E
Eric Blake 已提交
4691 4692
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4693

E
Eric Blake 已提交
4694 4695 4696
        if (guiDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(guiDisplay, &valueDisplayUtf16);
4697

E
Eric Blake 已提交
4698 4699
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4700

E
Eric Blake 已提交
4701 4702
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
4703
        }
E
Eric Blake 已提交
4704
    }
4705

E
Eric Blake 已提交
4706 4707 4708
    VIR_FREE(guiDisplay);
    VIR_FREE(sdlDisplay);
}
4709

E
Eric Blake 已提交
4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731
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) {
4732
                    VIR_DEBUG("USB Device detected, VendorId:0x%x, ProductId:0x%x",
E
Eric Blake 已提交
4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749
                          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);
4750

4751 4752
            for (i = 0; i < def->nhostdevs; i++) {
                if (def->hostdevs[i]->mode ==
E
Eric Blake 已提交
4753
                    VIR_DOMAIN_HOSTDEV_MODE_SUBSYS) {
4754
                    if (def->hostdevs[i]->source.subsys.type ==
E
Eric Blake 已提交
4755
                        VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
4756

E
Eric Blake 已提交
4757
                        char *filtername           = NULL;
E
Eric Blake 已提交
4758 4759
                        PRUnichar *filternameUtf16 = NULL;
                        IUSBDeviceFilter *filter   = NULL;
4760

E
Eric Blake 已提交
4761 4762
                        /* Zero pad for nice alignment when fewer than 9999
                         * devices.
E
Eric Blake 已提交
4763
                         */
E
Eric Blake 已提交
4764 4765 4766 4767 4768 4769 4770 4771 4772
                        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 已提交
4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784
                        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 已提交
4785 4786
                                snprintf(vendorId, sizeof(vendorId), "%x",
                                         def->hostdevs[i]->source.subsys.u.usb.vendor);
E
Eric Blake 已提交
4787 4788 4789 4790 4791
                                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 已提交
4792 4793
                                snprintf(productId, sizeof(productId), "%x",
                                         def->hostdevs[i]->source.subsys.u.usb.product);
E
Eric Blake 已提交
4794 4795 4796 4797
                                VBOX_UTF8_TO_UTF16(productId, &productIdUtf16);
                                filter->vtbl->SetProductId(filter,
                                                           productIdUtf16);
                                VBOX_UTF16_FREE(productIdUtf16);
4798
                            }
E
Eric Blake 已提交
4799 4800 4801 4802 4803
                            filter->vtbl->SetActive(filter, 1);
                            USBController->vtbl->InsertDeviceFilter(USBController,
                                                                    i,
                                                                    filter);
                            VBOX_RELEASE(filter);
4804
                        }
E
Eric Blake 已提交
4805

4806 4807 4808
                    }
                }
            }
E
Eric Blake 已提交
4809 4810 4811 4812 4813 4814 4815 4816 4817
            VBOX_RELEASE(USBController);
        }
    }
}

static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml) {
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
    IMachine       *machine     = NULL;
    IBIOSSettings  *bios        = NULL;
4818 4819
    vboxIID iid = VBOX_IID_INITIALIZER;
    vboxIID mchiid = VBOX_IID_INITIALIZER;
E
Eric Blake 已提交
4820 4821 4822 4823 4824 4825 4826 4827
    virDomainDefPtr def         = NULL;
    PRUnichar *machineNameUtf16 = NULL;
#if VBOX_API_VERSION >= 3002
    PRBool override             = PR_FALSE;
#endif
    nsresult rc;

    if (!(def = virDomainDefParseString(data->caps, xml,
M
Matthias Bolte 已提交
4828
                                        1 << VIR_DOMAIN_VIRT_VBOX,
E
Eric Blake 已提交
4829 4830 4831 4832 4833
                                        VIR_DOMAIN_XML_INACTIVE))) {
        goto cleanup;
    }

    VBOX_UTF8_TO_UTF16(def->name, &machineNameUtf16);
4834
    vboxIIDFromUUID(&iid, def->uuid);
E
Eric Blake 已提交
4835 4836 4837 4838 4839
#if VBOX_API_VERSION < 3002
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
4840
                                            iid.value,
E
Eric Blake 已提交
4841
                                            &machine);
4842
#elif VBOX_API_VERSION < 4000 /* 3002 <= VBOX_API_VERSION < 4000 */
E
Eric Blake 已提交
4843 4844 4845 4846
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
4847
                                            iid.value,
E
Eric Blake 已提交
4848 4849
                                            override,
                                            &machine);
4850 4851 4852 4853 4854 4855 4856 4857 4858
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            NULL,
                                            machineNameUtf16,
                                            NULL,
                                            iid.value,
                                            override,
                                            &machine);
#endif /* VBOX_API_VERSION >= 4000 */
E
Eric Blake 已提交
4859 4860 4861 4862 4863 4864 4865 4866
    VBOX_UTF16_FREE(machineNameUtf16);

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

4867 4868
    rc = machine->vtbl->SetMemorySize(machine,
                                      VIR_DIV_UP(def->mem.cur_balloon, 1024));
E
Eric Blake 已提交
4869 4870 4871 4872
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not set the memory size of the domain to: %lu Kb, "
                    "rc=%08x"),
4873
                  def->mem.cur_balloon, (unsigned)rc);
E
Eric Blake 已提交
4874 4875
    }

E
Eric Blake 已提交
4876 4877 4878 4879 4880
    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 已提交
4881 4882
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
4883 4884
                  _("could not set the number of virtual CPUs to: %u, rc=%08x"),
                  def->maxvcpus, (unsigned)rc);
E
Eric Blake 已提交
4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922
    }

#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);
4923
        }
E
Eric Blake 已提交
4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
        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
     */
4939
    machine->vtbl->GetId(machine, &mchiid.value);
4940
    VBOX_SESSION_OPEN(mchiid.value, machine);
E
Eric Blake 已提交
4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951
    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);
4952

4953 4954 4955 4956
    /* Save the machine settings made till now and close the
     * session. also free up the mchiid variable used.
     */
    rc = machine->vtbl->SaveSettings(machine);
4957
    VBOX_SESSION_CLOSE();
4958
    vboxIIDUnalloc(&mchiid);
4959

4960 4961
    ret = virGetDomain(conn, def->name, def->uuid);
    VBOX_RELEASE(machine);
4962

4963
    vboxIIDUnalloc(&iid);
4964 4965
    virDomainDefFree(def);

4966
    return ret;
4967 4968

cleanup:
4969
    VBOX_RELEASE(machine);
4970
    vboxIIDUnalloc(&iid);
4971 4972 4973 4974
    virDomainDefFree(def);
    return NULL;
}

4975 4976 4977
static int
vboxDomainUndefine(virDomainPtr dom)
{
4978
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
4979
    IMachine *machine    = NULL;
4980
    vboxIID iid = VBOX_IID_INITIALIZER;
4981
    nsresult rc;
4982 4983 4984
#if VBOX_API_VERSION >= 4000
    vboxArray media = VBOX_ARRAY_INITIALIZER;
#endif
4985

4986
    vboxIIDFromUUID(&iid, dom->uuid);
4987

4988
#if VBOX_API_VERSION < 4000
4989 4990 4991
    /* 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
4992 4993 4994 4995
     * it is allocated to CD/DVD Drive by default.
     *
     * Only do this for VirtualBox 3.x and before. Since
     * VirtualBox 4.0 the Unregister method can do this for use.
4996 4997 4998
     */
    {
        PRUnichar *hddcnameUtf16 = NULL;
4999

5000 5001 5002
        char *hddcname = strdup("IDE");
        VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16);
        VIR_FREE(hddcname);
5003

5004
        /* Open a Session for the machine */
5005
        rc = VBOX_SESSION_OPEN(iid.value, machine);
5006 5007 5008 5009
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {

5010
# if VBOX_API_VERSION < 3001
5011 5012 5013 5014
                /* 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);
5015
# else  /* VBOX_API_VERSION >= 3001 */
5016 5017 5018
                /* get all the controller first, then the attachments and
                 * remove them all so that the machine can be undefined
                 */
5019
                vboxArray storageControllers = VBOX_ARRAY_INITIALIZER;
5020 5021
                int i = 0, j = 0;

5022 5023
                vboxArrayGet(&storageControllers, machine,
                             machine->vtbl->GetStorageControllers);
5024

5025 5026
                for (i = 0; i < storageControllers.count; i++) {
                    IStorageController *strCtl = storageControllers.items[i];
5027
                    PRUnichar *strCtlName = NULL;
5028
                    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
5029 5030 5031 5032 5033

                    if (!strCtl)
                        continue;

                    strCtl->vtbl->GetName(strCtl, &strCtlName);
5034 5035 5036
                    vboxArrayGetWithPtrArg(&mediumAttachments, machine,
                                           machine->vtbl->GetMediumAttachmentsOfController,
                                           strCtlName);
5037

5038 5039
                    for (j = 0; j < mediumAttachments.count; j++) {
                        IMediumAttachment *medAtt = mediumAttachments.items[j];
5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055
                        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);
                        }
                    }
5056

5057 5058
                    vboxArrayRelease(&storageControllers);

5059 5060
                    machine->vtbl->RemoveStorageController(machine, strCtlName);
                    VBOX_UTF16_FREE(strCtlName);
5061
                }
5062 5063

                vboxArrayRelease(&storageControllers);
5064
# endif /* VBOX_API_VERSION >= 3001 */
5065 5066

                machine->vtbl->SaveSettings(machine);
5067
            }
5068
            VBOX_SESSION_CLOSE();
5069
        }
5070 5071
        VBOX_UTF16_FREE(hddcnameUtf16);
    }
5072
#endif
5073

5074
#if VBOX_API_VERSION < 4000
5075
    rc = data->vboxObj->vtbl->UnregisterMachine(data->vboxObj, iid.value, &machine);
5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090
#else /* VBOX_API_VERSION >= 4000 */
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
                  _("no domain with matching uuid"));
        return -1;
    }

    /* We're not interested in the array returned by the Unregister method,
     * but in the side effect of unregistering the virtual machine. In order
     * to call the Unregister method correctly we need to use the vboxArray
     * wrapper here. */
    rc = vboxArrayGetWithUintArg(&media, machine, machine->vtbl->Unregister,
                                 CleanupMode_DetachAllReturnNone);
#endif /* VBOX_API_VERSION >= 4000 */
5091
    DEBUGIID("UUID of machine being undefined", iid.value);
5092

5093 5094
    if (NS_SUCCEEDED(rc)) {
#if VBOX_API_VERSION < 4000
5095
        machine->vtbl->DeleteSettings(machine);
5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118
#else /* VBOX_API_VERSION >= 4000 */
        IProgress *progress = NULL;

        /* The IMachine Delete method takes an array of IMedium items to be
         * deleted along with the virtual machine. We just want to pass an
         * empty array. But instead of adding a full vboxArraySetWithReturn to
         * the glue layer (in order to handle the required signature of the
         * Delete method) we use a local solution here. */
# ifdef WIN32
        SAFEARRAY *safeArray = NULL;
        typedef HRESULT __stdcall (*IMachine_Delete)(IMachine *self,
                                                     SAFEARRAY **media,
                                                     IProgress **progress);

        ((IMachine_Delete)machine->vtbl->Delete)(machine, &safeArray, &progress);
# else
        machine->vtbl->Delete(machine, 0, NULL, &progress);
# endif
        if (progress != NULL) {
            progress->vtbl->WaitForCompletion(progress, -1);
            VBOX_RELEASE(progress);
        }
#endif /* VBOX_API_VERSION >= 4000 */
5119 5120
        ret = 0;
    } else {
5121 5122
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not delete the domain, rc=%08x"), (unsigned)rc);
5123 5124
    }

5125 5126 5127
#if VBOX_API_VERSION >= 4000
    vboxArrayUnalloc(&media);
#endif
5128
    vboxIIDUnalloc(&iid);
5129
    VBOX_RELEASE(machine);
5130 5131 5132 5133

    return ret;
}

5134 5135 5136
static int vboxDomainAttachDeviceImpl(virDomainPtr dom,
                                      const char *xml,
                                      int mediaChangeOnly ATTRIBUTE_UNUSED) {
5137
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5138
    IMachine *machine    = NULL;
5139
    vboxIID iid = VBOX_IID_INITIALIZER;
5140 5141 5142
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5143
    nsresult rc;
5144 5145

    if (VIR_ALLOC(def) < 0) {
5146
        virReportOOMError();
5147 5148 5149 5150 5151
        return ret;
    }

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

5152
    if (def->os.type == NULL) {
5153
        virReportOOMError();
5154 5155 5156
        goto cleanup;
    }

5157
    dev = virDomainDeviceDefParse(data->caps, def, xml,
5158 5159
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
5160
        virReportOOMError();
5161 5162 5163
        goto cleanup;
    }

5164
    vboxIIDFromUUID(&iid, dom->uuid);
5165
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5166
    if (NS_FAILED(rc)) {
5167
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
5168
                  _("no domain with matching uuid"));
5169 5170
        goto cleanup;
    }
5171

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

5175 5176
        if ((state == MachineState_Running) ||
            (state == MachineState_Paused)) {
5177
            rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
5178
        } else {
5179
            rc = VBOX_SESSION_OPEN(iid.value, machine);
5180 5181 5182 5183 5184 5185 5186
        }
        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) {
5187 5188
                        if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE &&
                            dev->data.disk->src != NULL) {
5189 5190 5191 5192 5193 5194 5195 5196 5197
                            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;
5198 5199
                                vboxIID dvduuid = VBOX_IID_INITIALIZER;
                                vboxIID dvdemptyuuid = VBOX_IID_INITIALIZER;
5200

5201
                                VBOX_UTF8_TO_UTF16(dev->data.disk->src, &dvdfileUtf16);
5202

5203 5204
                                data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                if (!dvdImage) {
5205
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, dvdemptyuuid.value, &dvdImage);
5206 5207
                                }
                                if (dvdImage) {
5208
                                    rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage, &dvduuid.value);
5209
                                    if (NS_FAILED(rc)) {
5210 5211 5212
                                        vboxError(VIR_ERR_INTERNAL_ERROR,
                                                  _("can't get the uuid of the file to "
                                                    "be attached to cdrom: %s, rc=%08x"),
5213 5214 5215 5216
                                                  dev->data.disk->src, (unsigned)rc);
                                    } else {
                                        /* unmount the previous mounted image */
                                        dvdDrive->vtbl->Unmount(dvdDrive);
5217
                                        rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid.value);
5218
                                        if (NS_FAILED(rc)) {
5219 5220
                                            vboxError(VIR_ERR_INTERNAL_ERROR,
                                                      _("could not attach the file to cdrom: %s, rc=%08x"),
5221 5222
                                                      dev->data.disk->src, (unsigned)rc);
                                        } else {
5223
                                            ret = 0;
5224
                                            DEBUGIID("CD/DVD Image UUID:", dvduuid.value);
5225 5226
                                        }
                                    }
5227 5228

                                    VBOX_MEDIUM_RELEASE(dvdImage);
5229
                                }
5230
                                vboxIIDUnalloc(&dvduuid);
5231 5232
                                VBOX_UTF16_FREE(dvdfileUtf16);
                                VBOX_RELEASE(dvdDrive);
5233
                            }
5234 5235 5236
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
                        }
                    } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
5237 5238
                        if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_FILE &&
                            dev->data.disk->src != NULL) {
5239 5240 5241 5242 5243 5244 5245
                            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;
5246 5247
                                    vboxIID fduuid = VBOX_IID_INITIALIZER;
                                    vboxIID fdemptyuuid = VBOX_IID_INITIALIZER;
5248 5249 5250 5251 5252 5253 5254 5255
                                    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,
5256
                                                                             fdemptyuuid.value,
5257 5258
                                                                             &floppyImage);
                                    }
5259

5260
                                    if (floppyImage) {
5261
                                        rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage, &fduuid.value);
5262
                                        if (NS_FAILED(rc)) {
5263 5264 5265
                                            vboxError(VIR_ERR_INTERNAL_ERROR,
                                                      _("can't get the uuid of the file to be "
                                                        "attached to floppy drive: %s, rc=%08x"),
5266 5267
                                                      dev->data.disk->src, (unsigned)rc);
                                        } else {
5268
                                            rc = floppyDrive->vtbl->MountImage(floppyDrive, fduuid.value);
5269
                                            if (NS_FAILED(rc)) {
5270 5271
                                                vboxError(VIR_ERR_INTERNAL_ERROR,
                                                          _("could not attach the file to floppy drive: %s, rc=%08x"),
5272 5273
                                                          dev->data.disk->src, (unsigned)rc);
                                            } else {
5274
                                                ret = 0;
5275
                                                DEBUGIID("attached floppy, UUID:", fduuid.value);
5276 5277
                                            }
                                        }
5278
                                        VBOX_MEDIUM_RELEASE(floppyImage);
5279
                                    }
5280
                                    vboxIIDUnalloc(&fduuid);
5281
                                    VBOX_UTF16_FREE(fdfileUtf16);
5282
                                }
5283
                                VBOX_RELEASE(floppyDrive);
5284
                            }
5285
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
5286
                        }
5287 5288 5289 5290 5291 5292 5293
                    }
#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) {
5294 5295 5296
                        }
                    }
                }
5297 5298
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5299
            }
5300
            VBOX_SESSION_CLOSE();
5301 5302 5303 5304
        }
    }

cleanup:
5305
    vboxIIDUnalloc(&iid);
5306 5307 5308 5309 5310
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5311 5312 5313 5314
static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml) {
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

5315 5316 5317 5318 5319 5320
static int
vboxDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

5321
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5322
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
5323 5324 5325 5326
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

5327 5328 5329 5330 5331
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

static int vboxDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
                                       unsigned int flags) {
5332 5333 5334
    virCheckFlags(VIR_DOMAIN_AFFECT_CURRENT |
                  VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5335

5336
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5337
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
5338 5339 5340 5341 5342
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainAttachDeviceImpl(dom, xml, 1);
5343 5344
}

5345
static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml) {
5346
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5347
    IMachine *machine    = NULL;
5348
    vboxIID iid = VBOX_IID_INITIALIZER;
5349 5350 5351
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5352
    nsresult rc;
5353 5354

    if (VIR_ALLOC(def) < 0) {
5355
        virReportOOMError();
5356 5357 5358 5359 5360
        return ret;
    }

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

5361
    if (def->os.type == NULL) {
5362
        virReportOOMError();
5363 5364 5365
        goto cleanup;
    }

5366
    dev = virDomainDeviceDefParse(data->caps, def, xml,
5367 5368
                                  VIR_DOMAIN_XML_INACTIVE);
    if (dev == NULL) {
5369
        virReportOOMError();
5370 5371 5372
        goto cleanup;
    }

5373
    vboxIIDFromUUID(&iid, dom->uuid);
5374
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5375
    if (NS_FAILED(rc)) {
5376
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
5377
                  _("no domain with matching uuid"));
5378 5379
        goto cleanup;
    }
5380

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

5384 5385
        if ((state == MachineState_Running) ||
            (state == MachineState_Paused)) {
5386
            rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
5387
        } else {
5388
            rc = VBOX_SESSION_OPEN(iid.value, machine);
5389
        }
5390

5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406
        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)) {
5407 5408
                                    vboxError(VIR_ERR_INTERNAL_ERROR,
                                              _("could not de-attach the mounted ISO, rc=%08x"),
5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426
                                              (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);
5427
                                    if (NS_FAILED(rc)) {
5428 5429 5430
                                        vboxError(VIR_ERR_INTERNAL_ERROR,
                                                  _("could not attach the file "
                                                    "to floppy drive, rc=%08x"),
5431 5432 5433 5434
                                                  (unsigned)rc);
                                    } else {
                                        ret = 0;
                                    }
5435 5436 5437 5438 5439
                                } 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;
5440
                                }
5441
                                VBOX_RELEASE(floppyDrive);
5442
                            }
5443
                        } else if (dev->data.disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK) {
5444
                        }
5445 5446 5447 5448 5449 5450 5451
                    }
#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) {
5452 5453 5454
                        }
                    }
                }
5455 5456
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5457
            }
5458
            VBOX_SESSION_CLOSE();
5459 5460 5461 5462
        }
    }

cleanup:
5463
    vboxIIDUnalloc(&iid);
5464 5465 5466 5467 5468
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5469 5470 5471 5472 5473 5474
static int
vboxDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

5475
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5476
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
5477 5478 5479 5480 5481 5482 5483
                  _("cannot modify the persistent configuration of a domain"));
        return -1;
    }

    return vboxDomainDetachDevice(dom, xml);
}

J
Jiri Denemark 已提交
5484 5485 5486 5487 5488
static int
vboxDomainSnapshotGetAll(virDomainPtr dom,
                         IMachine *machine,
                         ISnapshot ***snapshots)
{
5489
    vboxIID empty = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5490 5491 5492 5493 5494 5495 5496 5497
    ISnapshot **list = NULL;
    PRUint32 count;
    nsresult rc;
    unsigned int next;
    unsigned int top;

    rc = machine->vtbl->GetSnapshotCount(machine, &count);
    if (NS_FAILED(rc)) {
5498
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511
                  _("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;
    }

5512
#if VBOX_API_VERSION < 4000
5513
    rc = machine->vtbl->GetSnapshot(machine, empty.value, list);
5514 5515 5516
#else /* VBOX_API_VERSION >= 4000 */
    rc = machine->vtbl->FindSnapshot(machine, empty.value, list);
#endif /* VBOX_API_VERSION >= 4000 */
J
Jiri Denemark 已提交
5517
    if (NS_FAILED(rc) || !list[0]) {
5518
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5519 5520 5521 5522 5523 5524 5525 5526
                  _("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++) {
5527
        vboxArray children = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
5528 5529 5530
        unsigned int i;

        if (!list[next]) {
5531
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5532 5533 5534 5535
                      _("unexpected number of snapshots < %u"), count);
            goto error;
        }

5536 5537
        rc = vboxArrayGet(&children, list[next],
                               list[next]->vtbl->GetChildren);
J
Jiri Denemark 已提交
5538
        if (NS_FAILED(rc)) {
5539
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5540 5541 5542
                      "%s", _("could not get children snapshots"));
            goto error;
        }
5543 5544 5545
        for (i = 0; i < children.count; i++) {
            ISnapshot *child = children.items[i];
            if (!child)
J
Jiri Denemark 已提交
5546 5547
                continue;
            if (top == count) {
5548
                vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5549
                          _("unexpected number of snapshots > %u"), count);
5550
                vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5551 5552
                goto error;
            }
5553 5554
            VBOX_ADDREF(child);
            list[top++] = child;
J
Jiri Denemark 已提交
5555
        }
5556
        vboxArrayRelease(&children);
J
Jiri Denemark 已提交
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 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593
    }

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) {
5594
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608
                      "%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) {
5609
        vboxError(VIR_ERR_OPERATION_INVALID,
J
Jiri Denemark 已提交
5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628
                  _("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,
5629
                            unsigned int flags)
J
Jiri Denemark 已提交
5630 5631 5632
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    virDomainSnapshotDefPtr def = NULL;
5633
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647
    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

5648 5649
    virCheckFlags(0, NULL);

J
Jiri Denemark 已提交
5650 5651 5652
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
        goto cleanup;

5653
    vboxIIDFromUUID(&domiid, dom->uuid);
5654
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
5655
    if (NS_FAILED(rc)) {
5656
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
5657 5658 5659 5660 5661 5662
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
5663
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
5664 5665 5666 5667 5668 5669
                  _("could not get domain state"));
        goto cleanup;
    }

    if ((state >= MachineState_FirstOnline)
        && (state <= MachineState_LastOnline)) {
5670
        rc = VBOX_SESSION_OPEN_EXISTING(domiid.value, machine);
J
Jiri Denemark 已提交
5671
    } else {
5672
        rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
5673
    }
5674

J
Jiri Denemark 已提交
5675 5676 5677
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
5678
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699
                  _("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) {
5700
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5701 5702 5703 5704 5705 5706 5707
                  _("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)) {
5708
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5709 5710 5711 5712 5713 5714
                  _("could not take snapshot of domain %s"), dom->name);
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
5715
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727
                  _("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);
5728
    VBOX_SESSION_CLOSE();
J
Jiri Denemark 已提交
5729
    VBOX_RELEASE(machine);
5730
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
5731 5732 5733 5734 5735
    virDomainSnapshotDefFree(def);
    return ret;
}

static char *
5736 5737
vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                             unsigned int flags)
J
Jiri Denemark 已提交
5738 5739 5740
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
5741
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752
    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];

5753 5754
    virCheckFlags(0, NULL);

5755
    vboxIIDFromUUID(&domiid, dom->uuid);
5756
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
5757
    if (NS_FAILED(rc)) {
5758
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771
                  _("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)) {
5772
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787
                  _("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)) {
5788
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5789 5790 5791 5792 5793 5794 5795 5796 5797
                  _("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)) {
5798
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5799 5800 5801 5802 5803 5804 5805
                  _("could not get parent of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }
    if (parent) {
        rc = parent->vtbl->GetName(parent, &str16);
        if (NS_FAILED(rc) || !str16) {
5806
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820
                      _("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)) {
5821
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838
                  _("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);
5839
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
5840 5841 5842 5843 5844 5845 5846 5847 5848
    return ret;

no_memory:
    virReportOOMError();
    goto cleanup;
}

static int
vboxDomainSnapshotNum(virDomainPtr dom,
5849
                      unsigned int flags)
J
Jiri Denemark 已提交
5850 5851
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5852
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5853 5854 5855 5856
    IMachine *machine = NULL;
    nsresult rc;
    PRUint32 snapshotCount;

5857 5858
    virCheckFlags(0, -1);

5859
    vboxIIDFromUUID(&iid, dom->uuid);
5860
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
5861
    if (NS_FAILED(rc)) {
5862
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
5863 5864 5865 5866 5867 5868
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetSnapshotCount(machine, &snapshotCount);
    if (NS_FAILED(rc)) {
5869
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5870 5871 5872 5873 5874 5875 5876 5877 5878
                  _("could not get snapshot count for domain %s"),
                  dom->name);
        goto cleanup;
    }

    ret = snapshotCount;

cleanup:
    VBOX_RELEASE(machine);
5879
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
5880 5881 5882 5883 5884 5885 5886
    return ret;
}

static int
vboxDomainSnapshotListNames(virDomainPtr dom,
                            char **names,
                            int nameslen,
5887
                            unsigned int flags)
J
Jiri Denemark 已提交
5888 5889
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5890
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5891 5892 5893 5894 5895 5896
    IMachine *machine = NULL;
    nsresult rc;
    ISnapshot **snapshots = NULL;
    int count = 0;
    int i;

5897 5898
    virCheckFlags(0, -1);

5899
    vboxIIDFromUUID(&iid, dom->uuid);
5900
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
5901
    if (NS_FAILED(rc)) {
5902
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918
                  _("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) {
5919
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944
                      "%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);
5945
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
5946 5947 5948 5949 5950 5951
    return ret;
}

static virDomainSnapshotPtr
vboxDomainSnapshotLookupByName(virDomainPtr dom,
                               const char *name,
5952
                               unsigned int flags)
J
Jiri Denemark 已提交
5953 5954
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
5955
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5956 5957 5958 5959
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

5960 5961
    virCheckFlags(0, NULL);

5962
    vboxIIDFromUUID(&iid, dom->uuid);
5963
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
5964
    if (NS_FAILED(rc)) {
5965
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977
                  _("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);
5978
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
5979 5980 5981 5982 5983
    return ret;
}

static int
vboxDomainHasCurrentSnapshot(virDomainPtr dom,
5984
                             unsigned int flags)
J
Jiri Denemark 已提交
5985 5986
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5987
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5988 5989 5990 5991
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

5992 5993
    virCheckFlags(0, -1);

5994
    vboxIIDFromUUID(&iid, dom->uuid);
5995
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5996
    if (NS_FAILED(rc)) {
5997
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
5998 5999 6000 6001 6002 6003
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
6004
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015
                  _("could not get current snapshot"));
        goto cleanup;
    }

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

cleanup:
    VBOX_RELEASE(machine);
6016
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
6017 6018 6019 6020 6021
    return ret;
}

static virDomainSnapshotPtr
vboxDomainSnapshotCurrent(virDomainPtr dom,
6022
                          unsigned int flags)
J
Jiri Denemark 已提交
6023 6024
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
6025
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6026 6027 6028 6029 6030 6031
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;

6032 6033
    virCheckFlags(0, NULL);

6034
    vboxIIDFromUUID(&iid, dom->uuid);
6035
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
6036
    if (NS_FAILED(rc)) {
6037
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
6038 6039 6040 6041 6042 6043
                  _("no domain with matching UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
6044
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6045 6046 6047 6048 6049
                  _("could not get current snapshot"));
        goto cleanup;
    }

    if (!snapshot) {
6050
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6051 6052 6053 6054 6055 6056
                  _("domain has no snapshots"));
        goto cleanup;
    }

    rc = snapshot->vtbl->GetName(snapshot, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
6057
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074
                  _("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);
6075
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
6076 6077 6078 6079 6080 6081 6082 6083 6084 6085
    return ret;
}

#if VBOX_API_VERSION < 3001
static int
vboxDomainSnapshotRestore(virDomainPtr dom,
                          IMachine *machine,
                          ISnapshot *snapshot)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
6086
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6087 6088
    nsresult rc;

6089 6090
    rc = snapshot->vtbl->GetId(snapshot, &iid.value);
    if (NS_FAILED(rc)) {
6091
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6092 6093 6094 6095
                  _("could not get snapshot UUID"));
        goto cleanup;
    }

6096
    rc = machine->vtbl->SetCurrentSnapshot(machine, iid.value);
J
Jiri Denemark 已提交
6097
    if (NS_FAILED(rc)) {
6098
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6099 6100 6101 6102 6103 6104 6105
                  _("could not restore snapshot for domain %s"), dom->name);
        goto cleanup;
    }

    ret = 0;

cleanup:
6106
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120
    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;
6121
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6122

6123 6124
    rc = machine->vtbl->GetId(machine, &domiid.value);
    if (NS_FAILED(rc)) {
6125
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6126 6127 6128 6129 6130 6131
                  _("could not get domain UUID"));
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
6132
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6133 6134 6135 6136 6137 6138
                  _("could not get domain state"));
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
6139
        vboxError(VIR_ERR_OPERATION_INVALID,
J
Jiri Denemark 已提交
6140 6141 6142 6143
                  _("domain %s is already running"), dom->name);
        goto cleanup;
    }

6144
    rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
6145 6146 6147
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
6148
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6149 6150 6151 6152 6153 6154 6155 6156
                  _("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) {
6157
            vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6158 6159
                      _("cannot restore domain snapshot for running domain"));
        } else {
6160
            vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6161 6162 6163 6164 6165 6166 6167 6168 6169
                      _("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)) {
6170
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6171 6172 6173 6174 6175 6176 6177 6178 6179
                  _("could not restore snapshot for domain %s"), dom->name);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VBOX_RELEASE(progress);
    VBOX_RELEASE(console);
6180
    VBOX_SESSION_CLOSE();
6181
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
6182 6183 6184 6185 6186 6187
    return ret;
}
#endif

static int
vboxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
6188
                           unsigned int flags)
J
Jiri Denemark 已提交
6189 6190 6191
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
6192
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6193 6194 6195 6196 6197 6198 6199
    IMachine *machine = NULL;
    ISnapshot *newSnapshot = NULL;
    ISnapshot *prevSnapshot = NULL;
    PRBool online = PR_FALSE;
    PRUint32 state;
    nsresult rc;

6200 6201
    virCheckFlags(0, -1);

6202
    vboxIIDFromUUID(&domiid, dom->uuid);
6203
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
6204
    if (NS_FAILED(rc)) {
6205
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
6206 6207 6208 6209 6210 6211 6212 6213 6214 6215
                  _("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)) {
6216
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6217 6218 6219 6220 6221 6222 6223
                  _("could not get online state of snapshot %s"),
                  snapshot->name);
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &prevSnapshot);
    if (NS_FAILED(rc)) {
6224
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6225 6226 6227 6228 6229 6230 6231
                  _("could not get current snapshot of domain %s"),
                  dom->name);
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
6232
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6233 6234 6235 6236 6237 6238
                  _("could not get domain state"));
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
6239
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256
                  _("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);
6257
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
6258 6259 6260 6261 6262 6263 6264 6265 6266
    return ret;
}

static int
vboxDomainSnapshotDeleteSingle(vboxGlobalData *data,
                               IConsole *console,
                               ISnapshot *snapshot)
{
    IProgress *progress = NULL;
6267
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6268 6269 6270 6271 6272 6273 6274 6275
    int ret = -1;
    nsresult rc;
#if VBOX_API_VERSION == 2002
    nsresult result;
#else
    PRInt32 result;
#endif

6276 6277
    rc = snapshot->vtbl->GetId(snapshot, &iid.value);
    if (NS_FAILED(rc)) {
6278
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6279 6280 6281 6282 6283
                  _("could not get snapshot UUID"));
        goto cleanup;
    }

#if VBOX_API_VERSION < 3001
6284
    rc = console->vtbl->DiscardSnapshot(console, iid.value, &progress);
J
Jiri Denemark 已提交
6285
#else
6286
    rc = console->vtbl->DeleteSnapshot(console, iid.value, &progress);
J
Jiri Denemark 已提交
6287 6288 6289
#endif
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
6290
            vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6291 6292
                      _("cannot delete domain snapshot for running domain"));
        } else {
6293
            vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6294 6295 6296 6297 6298 6299 6300 6301
                      _("could not delete snapshot"));
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
6302
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6303 6304 6305 6306 6307 6308 6309 6310
                  _("could not delete snapshot"));
        goto cleanup;
    }

    ret = 0;

cleanup:
    VBOX_RELEASE(progress);
6311
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
6312 6313 6314 6315 6316 6317 6318 6319
    return ret;
}

static int
vboxDomainSnapshotDeleteTree(vboxGlobalData *data,
                             IConsole *console,
                             ISnapshot *snapshot)
{
6320
    vboxArray children = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
6321 6322 6323 6324
    int ret = -1;
    nsresult rc;
    unsigned int i;

6325
    rc = vboxArrayGet(&children, snapshot, snapshot->vtbl->GetChildren);
J
Jiri Denemark 已提交
6326
    if (NS_FAILED(rc)) {
6327
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6328 6329 6330 6331
                  _("could not get children snapshots"));
        goto cleanup;
    }

6332 6333 6334
    for (i = 0; i < children.count; i++) {
        if (vboxDomainSnapshotDeleteTree(data, console, children.items[i]))
            goto cleanup;
J
Jiri Denemark 已提交
6335 6336 6337 6338 6339
    }

    ret = vboxDomainSnapshotDeleteSingle(data, console, snapshot);

cleanup:
6340
    vboxArrayRelease(&children);
J
Jiri Denemark 已提交
6341 6342 6343 6344 6345 6346 6347 6348 6349
    return ret;
}

static int
vboxDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                         unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
6350
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6351 6352 6353 6354 6355 6356
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IConsole *console = NULL;
    PRUint32 state;
    nsresult rc;

6357 6358
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);

6359
    vboxIIDFromUUID(&domiid, dom->uuid);
6360
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
6361
    if (NS_FAILED(rc)) {
6362
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
J
Jiri Denemark 已提交
6363 6364 6365 6366 6367 6368 6369 6370 6371 6372
                  _("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)) {
6373
        vboxError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
6374 6375 6376 6377 6378 6379
                  _("could not get domain state"));
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
6380
        vboxError(VIR_ERR_OPERATION_INVALID, "%s",
J
Jiri Denemark 已提交
6381 6382 6383 6384
                  _("cannot delete snapshots of running domain"));
        goto cleanup;
    }

6385
    rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
6386 6387 6388
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
6389
        vboxError(VIR_ERR_INTERNAL_ERROR,
J
Jiri Denemark 已提交
6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402
                  _("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);
6403
    vboxIIDUnalloc(&domiid);
6404
    VBOX_SESSION_CLOSE();
J
Jiri Denemark 已提交
6405 6406 6407
    return ret;
}

6408
#if VBOX_API_VERSION == 2002 || VBOX_API_VERSION == 4000
6409
    /* No Callback support for VirtualBox 2.2.* series */
6410
#else /* !(VBOX_API_VERSION == 2002) && !(VBOX_API_VERSION == 4000) */
6411 6412

/* Functions needed for Callbacks */
6413 6414 6415 6416
static nsresult PR_COM_METHOD
vboxCallbackOnMachineStateChange(IVirtualBoxCallback *pThis,
                                 PRUnichar *machineId, PRUint32 state)
{
6417 6418 6419 6420 6421 6422 6423
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

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

6424
    VIR_DEBUG("IVirtualBoxCallback: %p, State: %d", pThis, state);
6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435
    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) {
6436
            virDomainEventPtr ev;
6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466

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

6467 6468 6469 6470 6471 6472 6473 6474
            ev = virDomainEventNewFromDom(dom, event, detail);

            if (ev) {
                virDomainEventDispatch(ev,
                                       g_pVBoxGlobalData->domainEventCallbacks,
                                       virDomainEventDispatchDefaultFunc,
                                       NULL);
                virDomainEventFree(ev);
6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486
            }
        }
    }

    virDomainEventCallbackListPurgeMarked(g_pVBoxGlobalData->domainEventCallbacks);

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

    return NS_OK;
}

6487 6488 6489 6490
static nsresult PR_COM_METHOD
vboxCallbackOnMachineDataChange(IVirtualBoxCallback *pThis,
                                PRUnichar *machineId)
{
6491
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
6492 6493 6494 6495 6496
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

6497 6498 6499 6500 6501 6502 6503
static nsresult PR_COM_METHOD
vboxCallbackOnExtraDataCanChange(IVirtualBoxCallback *pThis,
                                 PRUnichar *machineId, PRUnichar *key,
                                 PRUnichar *value,
                                 PRUnichar **error ATTRIBUTE_UNUSED,
                                 PRBool *allowChange)
{
6504
    VIR_DEBUG("IVirtualBoxCallback: %p, allowChange: %s", pThis, *allowChange ? "true" : "false");
6505 6506 6507 6508 6509 6510 6511
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

6512 6513 6514 6515
static nsresult PR_COM_METHOD
vboxCallbackOnExtraDataChange(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                              PRUnichar *key, PRUnichar *value)
{
6516
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
6517 6518 6519 6520 6521 6522 6523
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

6524
# if VBOX_API_VERSION < 3001
6525 6526 6527 6528
static nsresult PR_COM_METHOD
vboxCallbackOnMediaRegistered(IVirtualBoxCallback *pThis, PRUnichar *mediaId,
                              PRUint32 mediaType, PRBool registered)
{
6529 6530
    VIR_DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
    VIR_DEBUG("mediaType: %d", mediaType);
6531 6532 6533 6534
    DEBUGPRUnichar("mediaId", mediaId);

    return NS_OK;
}
6535 6536
# else  /* VBOX_API_VERSION >= 3001 */
# endif /* VBOX_API_VERSION >= 3001 */
6537

6538 6539 6540 6541
static nsresult PR_COM_METHOD
vboxCallbackOnMachineRegistered(IVirtualBoxCallback *pThis,
                                PRUnichar *machineId, PRBool registered)
{
6542 6543 6544 6545 6546 6547 6548
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

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

6549
    VIR_DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560
    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) {
6561
            virDomainEventPtr ev;
6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576

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

6577 6578 6579 6580 6581 6582 6583 6584
            ev = virDomainEventNewFromDom(dom, event, detail);

            if (ev) {
                virDomainEventDispatch(ev,
                                       g_pVBoxGlobalData->domainEventCallbacks,
                                       virDomainEventDispatchDefaultFunc,
                                       NULL);
                virDomainEventFree(ev);
6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596
            }
        }
    }

    virDomainEventCallbackListPurgeMarked(g_pVBoxGlobalData->domainEventCallbacks);

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

    return NS_OK;
}

6597 6598 6599 6600
static nsresult PR_COM_METHOD
vboxCallbackOnSessionStateChange(IVirtualBoxCallback *pThis,
                                 PRUnichar *machineId, PRUint32 state)
{
6601
    VIR_DEBUG("IVirtualBoxCallback: %p, state: %d", pThis, state);
6602 6603 6604 6605 6606
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

6607 6608 6609 6610
static nsresult PR_COM_METHOD
vboxCallbackOnSnapshotTaken(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                            PRUnichar *snapshotId)
{
6611
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
6612 6613 6614 6615 6616 6617
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

6618 6619 6620 6621
static nsresult PR_COM_METHOD
vboxCallbackOnSnapshotDiscarded(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                                PRUnichar *snapshotId)
{
6622
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
6623 6624 6625 6626 6627 6628
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

6629 6630 6631 6632
static nsresult PR_COM_METHOD
vboxCallbackOnSnapshotChange(IVirtualBoxCallback *pThis, PRUnichar *machineId,
                             PRUnichar *snapshotId)
{
6633
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
6634 6635 6636 6637 6638 6639
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

6640 6641 6642 6643 6644
static nsresult PR_COM_METHOD
vboxCallbackOnGuestPropertyChange(IVirtualBoxCallback *pThis,
                                  PRUnichar *machineId, PRUnichar *name,
                                  PRUnichar *value, PRUnichar *flags)
{
6645
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
6646 6647 6648 6649 6650 6651 6652 6653
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("name", name);
    DEBUGPRUnichar("value", value);
    DEBUGPRUnichar("flags", flags);

    return NS_OK;
}

6654 6655 6656
static nsresult PR_COM_METHOD
vboxCallbackAddRef(nsISupports *pThis)
{
6657 6658 6659 6660
    nsresult c;

    c = ++g_pVBoxGlobalData->vboxCallBackRefCount;

6661
    VIR_DEBUG("pThis: %p, vboxCallback AddRef: %d", pThis, c);
6662 6663 6664 6665

    return c;
}

6666 6667 6668
static nsresult PR_COM_METHOD
vboxCallbackRelease(nsISupports *pThis)
{
6669 6670 6671 6672 6673 6674 6675 6676 6677
    nsresult c;

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

6678
    VIR_DEBUG("pThis: %p, vboxCallback Release: %d", pThis, c);
6679 6680 6681 6682

    return c;
}

6683 6684 6685
static nsresult PR_COM_METHOD
vboxCallbackQueryInterface(nsISupports *pThis, const nsID *iid, void **resultp)
{
6686 6687 6688 6689 6690 6691 6692 6693 6694 6695
    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;

6696
        VIR_DEBUG("pThis: %p, vboxCallback QueryInterface: %d", pThis, g_pVBoxGlobalData->vboxCallBackRefCount);
6697 6698 6699 6700 6701

        return NS_OK;
    }


6702
    VIR_DEBUG("pThis: %p, vboxCallback QueryInterface didn't find a matching interface", pThis);
6703 6704 6705 6706 6707 6708
    DEBUGUUID("The UUID Callback Interface expects", iid);
    DEBUGUUID("The UUID Callback Interface got", &ivirtualboxCallbackUUID);
    return NS_NOINTERFACE;
}


6709
static IVirtualBoxCallback *vboxAllocCallbackObj(void) {
6710 6711
    IVirtualBoxCallback *vboxCallback = NULL;

6712
    /* Allocate, Initialize and return a valid
6713 6714 6715
     * IVirtualBoxCallback object here
     */
    if ((VIR_ALLOC(vboxCallback) < 0) || (VIR_ALLOC(vboxCallback->vtbl) < 0)) {
6716
        VIR_FREE(vboxCallback);
6717
        virReportOOMError();
6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728
        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;
6729
# if VBOX_API_VERSION < 3001
6730
        vboxCallback->vtbl->OnMediaRegistered           = &vboxCallbackOnMediaRegistered;
6731 6732
# else  /* VBOX_API_VERSION >= 3001 */
# endif /* VBOX_API_VERSION >= 3001 */
6733 6734 6735
        vboxCallback->vtbl->OnMachineRegistered         = &vboxCallbackOnMachineRegistered;
        vboxCallback->vtbl->OnSessionStateChange        = &vboxCallbackOnSessionStateChange;
        vboxCallback->vtbl->OnSnapshotTaken             = &vboxCallbackOnSnapshotTaken;
6736
# if VBOX_API_VERSION < 3002
6737
        vboxCallback->vtbl->OnSnapshotDiscarded         = &vboxCallbackOnSnapshotDiscarded;
6738 6739 6740
# else /* VBOX_API_VERSION >= 3002 */
        vboxCallback->vtbl->OnSnapshotDeleted           = &vboxCallbackOnSnapshotDiscarded;
# endif /* VBOX_API_VERSION >= 3002 */
6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769
        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) {
6770
    VBOX_OBJECT_CHECK(conn, int, -1);
6771
    int vboxRet          = -1;
6772
    nsresult rc;
6773 6774 6775 6776 6777 6778

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

6779
    if (data->vboxCallback == NULL) {
6780
        data->vboxCallback = vboxAllocCallbackObj();
6781 6782 6783 6784
        if (data->vboxCallback != NULL) {
            rc = data->vboxObj->vtbl->RegisterCallback(data->vboxObj, data->vboxCallback);
            if (NS_SUCCEEDED(rc)) {
                vboxRet = 0;
6785 6786
            }
        }
6787 6788 6789
    } else {
        vboxRet = 0;
    }
6790

6791 6792 6793 6794 6795 6796 6797
    /* 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);
6798

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

6802 6803 6804 6805 6806
        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
             */
6807

6808 6809
            ret = virDomainEventCallbackListAdd(conn, data->domainEventCallbacks,
                                                callback, opaque, freecb);
6810
            VIR_DEBUG("virDomainEventCallbackListAdd (ret = %d) ( conn: %p, "
6811 6812 6813
                  "data->domainEventCallbacks: %p, callback: %p, opaque: %p, "
                  "freecb: %p )", ret, conn, data->domainEventCallbacks, callback,
                  opaque, freecb);
6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830
        }
    }

    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) {
6831
    VBOX_OBJECT_CHECK(conn, int, -1);
6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844

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

6845
    if (data->vboxCallback) {
6846 6847 6848
        /* check count here of how many times register was called
         * and only on the last de-register do the un-register call
         */
6849
        if (data->domainEventCallbacks && virDomainEventCallbackListCount(data->domainEventCallbacks) == 0) {
6850
            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
6851
            VBOX_RELEASE(data->vboxCallback);
6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863

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

    vboxDriverUnlock(data);

    return ret;
}

6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910
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);
6911
            VIR_DEBUG("virDomainEventCallbackListAddID (ret = %d) ( conn: %p, "
6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964
                  "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;
}

6965
#endif /* !(VBOX_API_VERSION == 2002) && !(VBOX_API_VERSION == 4000) */
6966

6967 6968 6969 6970 6971
/**
 * The Network Functions here on
 */
static virDrvOpenStatus vboxNetworkOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
6972 6973
                                        unsigned int flags)
{
6974 6975
    vboxGlobalData *data = conn->privateData;

E
Eric Blake 已提交
6976 6977
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

6978 6979 6980 6981 6982 6983 6984 6985
    if (STRNEQ(conn->driver->name, "VBOX"))
        goto cleanup;

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

6986
    VIR_DEBUG("network initialized");
6987 6988 6989 6990 6991 6992 6993 6994
    /* conn->networkPrivateData = some network specific data */
    return VIR_DRV_OPEN_SUCCESS;

cleanup:
    return VIR_DRV_OPEN_DECLINED;
}

static int vboxNetworkClose(virConnectPtr conn) {
6995
    VIR_DEBUG("network uninitialized");
6996 6997 6998 6999 7000
    conn->networkPrivateData = NULL;
    return 0;
}

static int vboxNumOfNetworks(virConnectPtr conn) {
7001
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
7002
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
7003
    int i = 0;
7004

7005
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
7006

7007 7008 7009 7010
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
7011
            PRUint32 interfaceType = 0;
7012

7013
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7014 7015
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
7016

7017
                networkInterface->vtbl->GetStatus(networkInterface, &status);
7018

7019 7020
                if (status == HostNetworkInterfaceStatus_Up)
                    ret++;
7021 7022 7023 7024
            }
        }
    }

7025 7026
    vboxArrayRelease(&networkInterfaces);

7027 7028
    VBOX_RELEASE(host);

7029
    VIR_DEBUG("numActive: %d", ret);
7030
    return ret;
7031 7032 7033
}

static int vboxListNetworks(virConnectPtr conn, char **const names, int nnames) {
7034
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
7035
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
7036
    int i = 0;
7037

7038 7039 7040 7041
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

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

7043
        if (networkInterface) {
7044
            PRUint32 interfaceType = 0;
7045

7046
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7047

7048 7049
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
7050

7051
                networkInterface->vtbl->GetStatus(networkInterface, &status);
7052

7053 7054 7055
                if (status == HostNetworkInterfaceStatus_Up) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
7056

7057
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
7058
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
7059

7060
                    VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8);
7061 7062
                    names[ret] = strdup(nameUtf8);
                    if (names[ret] == NULL) {
7063
                        virReportOOMError();
7064 7065
                    } else {
                        ret++;
7066 7067
                    }

7068 7069
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
7070 7071 7072 7073 7074
                }
            }
        }
    }

7075
    vboxArrayRelease(&networkInterfaces);
7076

7077
    VBOX_RELEASE(host);
7078

7079 7080
    return ret;
}
7081

7082 7083
static int vboxNumOfDefinedNetworks(virConnectPtr conn) {
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
7084
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
7085
    int i = 0;
7086

7087
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
7088

7089 7090 7091 7092
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
7093
            PRUint32 interfaceType = 0;
7094

7095
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7096 7097
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
7098

7099
                networkInterface->vtbl->GetStatus(networkInterface, &status);
7100

7101 7102
                if (status == HostNetworkInterfaceStatus_Down)
                    ret++;
7103 7104 7105 7106
            }
        }
    }

7107 7108
    vboxArrayRelease(&networkInterfaces);

7109 7110
    VBOX_RELEASE(host);

7111
    VIR_DEBUG("numActive: %d", ret);
7112
    return ret;
7113 7114 7115
}

static int vboxListDefinedNetworks(virConnectPtr conn, char **const names, int nnames) {
7116
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
7117
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
7118
    int i = 0;
7119

7120 7121 7122 7123
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

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

7125
        if (networkInterface) {
7126
            PRUint32 interfaceType = 0;
7127

7128
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7129

7130 7131
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
7132

7133
                networkInterface->vtbl->GetStatus(networkInterface, &status);
7134

7135 7136 7137
                if (status == HostNetworkInterfaceStatus_Down) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
7138

7139
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
7140
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
7141

7142
                    VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8);
7143 7144
                    names[ret] = strdup(nameUtf8);
                    if (names[ret] == NULL) {
7145
                        virReportOOMError();
7146 7147
                    } else {
                        ret++;
7148 7149
                    }

7150 7151
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
7152 7153 7154 7155 7156
                }
            }
        }
    }

7157
    vboxArrayRelease(&networkInterfaces);
7158 7159 7160 7161

    VBOX_RELEASE(host);

    return ret;
7162 7163
}

7164 7165 7166
static virNetworkPtr
vboxNetworkLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
7167
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
7168
    vboxIID iid = VBOX_IID_INITIALIZER;
7169

7170
    vboxIIDFromUUID(&iid, uuid);
7171

7172 7173 7174
    /* TODO: "internal" networks are just strings and
     * thus can't do much with them
     */
7175
    IHostNetworkInterface *networkInterface = NULL;
7176

7177
    host->vtbl->FindHostNetworkInterfaceById(host, iid.value, &networkInterface);
7178 7179
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7180

7181
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7182

7183 7184 7185
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            char *nameUtf8       = NULL;
            PRUnichar *nameUtf16 = NULL;
7186

7187 7188
            networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
            VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
7189

7190
            ret = virGetNetwork(conn, nameUtf8, uuid);
7191

7192
            VIR_DEBUG("Network Name: %s", nameUtf8);
7193
            DEBUGIID("Network UUID", iid.value);
7194

7195 7196
            VBOX_UTF8_FREE(nameUtf8);
            VBOX_UTF16_FREE(nameUtf16);
7197
        }
7198 7199

        VBOX_RELEASE(networkInterface);
7200 7201
    }

7202 7203
    VBOX_RELEASE(host);

7204
    vboxIIDUnalloc(&iid);
7205 7206 7207 7208
    return ret;
}

static virNetworkPtr vboxNetworkLookupByName(virConnectPtr conn, const char *name) {
7209 7210 7211
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *nameUtf16                    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7212

7213
    VBOX_UTF8_TO_UTF16(name, &nameUtf16);
7214

7215
    host->vtbl->FindHostNetworkInterfaceByName(host, nameUtf16, &networkInterface);
7216

7217 7218
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7219

7220
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7221

7222 7223
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            unsigned char uuid[VIR_UUID_BUFLEN];
7224
            vboxIID iid = VBOX_IID_INITIALIZER;
7225

7226 7227
            networkInterface->vtbl->GetId(networkInterface, &iid.value);
            vboxIIDToUUID(&iid, uuid);
7228
            ret = virGetNetwork(conn, name, uuid);
7229
            VIR_DEBUG("Network Name: %s", name);
7230

7231 7232
            DEBUGIID("Network UUID", iid.value);
            vboxIIDUnalloc(&iid);
7233
        }
7234 7235

        VBOX_RELEASE(networkInterface);
7236 7237
    }

7238 7239 7240
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(host);

7241 7242 7243
    return ret;
}

7244
static virNetworkPtr vboxNetworkDefineCreateXML(virConnectPtr conn, const char *xml, bool start) {
7245 7246 7247 7248
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    char      *networkInterfaceNameUtf8     = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7249
    nsresult rc;
7250

7251
    virNetworkDefPtr def = virNetworkDefParseString(xml);
7252 7253
    virNetworkIpDefPtr ipdef;
    virSocketAddr netmask;
7254

7255
    if (   (!def)
7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268
        || (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)
7269
        goto cleanup;
7270

7271 7272 7273 7274 7275 7276
    /* 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.
     */
7277

7278
#if VBOX_API_VERSION == 2002
7279
    if (STREQ(def->name, "vboxnet0")) {
7280
        PRUint32 interfaceType = 0;
7281

7282 7283
        VBOX_UTF8_TO_UTF16(def->name, &networkInterfaceNameUtf16);
        host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7284

7285 7286 7287 7288 7289 7290
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
        if (interfaceType != HostNetworkInterfaceType_HostOnly) {
            VBOX_RELEASE(networkInterface);
            networkInterface = NULL;
        }
    }
7291
#else /* VBOX_API_VERSION != 2002 */
7292 7293 7294 7295
    {
        IProgress *progress = NULL;
        host->vtbl->CreateHostOnlyNetworkInterface(host, &networkInterface,
                                                   &progress);
7296

7297 7298 7299 7300
        if (progress) {
            progress->vtbl->WaitForCompletion(progress, -1);
            VBOX_RELEASE(progress);
        }
7301
    }
7302
#endif /* VBOX_API_VERSION != 2002 */
7303

7304 7305 7306 7307
    if (networkInterface) {
        unsigned char uuid[VIR_UUID_BUFLEN];
        char      *networkNameUtf8  = NULL;
        PRUnichar *networkNameUtf16 = NULL;
7308
        vboxIID vboxnetiid = VBOX_IID_INITIALIZER;
7309 7310 7311 7312 7313 7314 7315 7316

        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);
7317
                virReportOOMError();
7318 7319 7320
                goto cleanup;
            }
        }
7321

7322
        VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
7323

7324 7325 7326
        /* Currently support only one dhcp server per network
         * with contigious address space from start to end
         */
7327 7328 7329
        if ((ipdef->nranges >= 1) &&
            VIR_SOCKET_HAS_ADDR(&ipdef->ranges[0].start) &&
            VIR_SOCKET_HAS_ADDR(&ipdef->ranges[0].end)) {
7330 7331 7332 7333 7334 7335 7336 7337 7338 7339
            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);
7340
                VIR_DEBUG("couldn't find dhcp server so creating one");
7341 7342 7343 7344 7345 7346 7347 7348
            }
            if (dhcpServer) {
                PRUnichar *ipAddressUtf16     = NULL;
                PRUnichar *networkMaskUtf16   = NULL;
                PRUnichar *fromIPAddressUtf16 = NULL;
                PRUnichar *toIPAddressUtf16   = NULL;
                PRUnichar *trunkTypeUtf16     = NULL;

7349 7350 7351 7352
                ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->address);
                networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
                fromIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].start);
                toIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].end);
7353 7354 7355 7356 7357 7358 7359 7360 7361 7362

                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;
                }
7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387

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

7389 7390
        if ((ipdef->nhosts >= 1) &&
            VIR_SOCKET_HAS_ADDR(&ipdef->hosts[0].ip)) {
7391 7392
            PRUnichar *ipAddressUtf16   = NULL;
            PRUnichar *networkMaskUtf16 = NULL;
7393

7394 7395
            ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->hosts[0].ip);
            networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
7396 7397 7398 7399 7400 7401

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

7403 7404 7405 7406 7407 7408 7409
            /* 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);
7410

7411 7412 7413 7414 7415 7416
            VBOX_UTF16_FREE(ipAddressUtf16);
            VBOX_UTF16_FREE(networkMaskUtf16);
        } else {
            networkInterface->vtbl->EnableDynamicIpConfig(networkInterface);
            networkInterface->vtbl->DhcpRediscover(networkInterface);
        }
7417

7418 7419 7420 7421 7422
        rc = networkInterface->vtbl->GetId(networkInterface, &vboxnetiid.value);
        if (NS_SUCCEEDED(rc)) {
            vboxIIDToUUID(&vboxnetiid, uuid);
            DEBUGIID("Real Network UUID", vboxnetiid.value);
            vboxIIDUnalloc(&vboxnetiid);
7423
            ret = virGetNetwork(conn, networkInterfaceNameUtf8, uuid);
7424
        }
7425 7426 7427 7428

        VIR_FREE(networkNameUtf8);
        VBOX_UTF16_FREE(networkNameUtf16);
        VBOX_RELEASE(networkInterface);
7429 7430
    }

7431 7432 7433 7434
    VBOX_UTF8_FREE(networkInterfaceNameUtf8);
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7435 7436 7437 7438 7439
cleanup:
    virNetworkDefFree(def);
    return ret;
}

7440 7441 7442 7443 7444 7445 7446 7447
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);
}

7448
static int vboxNetworkUndefineDestroy(virNetworkPtr network, bool removeinterface) {
7449
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
7450
    char *networkNameUtf8 = NULL;
7451 7452
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7453 7454 7455 7456 7457 7458 7459 7460 7461 7462

    /* 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) {
7463
        virReportOOMError();
7464 7465 7466
        goto cleanup;
    }

7467
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
7468

7469
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7470

7471 7472
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7473

7474
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7475

7476 7477 7478
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
7479

7480
#if VBOX_API_VERSION != 2002
7481 7482 7483
            if (removeinterface) {
                PRUnichar *iidUtf16 = NULL;
                IProgress *progress = NULL;
7484

7485
                networkInterface->vtbl->GetId(networkInterface, &iidUtf16);
7486

7487
                if (iidUtf16) {
7488
# if VBOX_API_VERSION == 3000
7489 7490 7491
                    IHostNetworkInterface *netInt = NULL;
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &netInt, &progress);
                    VBOX_RELEASE(netInt);
7492
# else  /* VBOX_API_VERSION > 3000 */
7493
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &progress);
7494
# endif /* VBOX_API_VERSION > 3000 */
7495 7496
                    VBOX_UTF16_FREE(iidUtf16);
                }
7497

7498 7499 7500 7501 7502
                if (progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                }
            }
7503 7504
#endif /* VBOX_API_VERSION != 2002 */

7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515
            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);
7516 7517
            }

7518 7519
            VBOX_UTF16_FREE(networkNameUtf16);

7520
        }
7521
        VBOX_RELEASE(networkInterface);
7522 7523
    }

7524 7525 7526
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7527 7528 7529 7530 7531 7532 7533
    ret = 0;

cleanup:
    VIR_FREE(networkNameUtf8);
    return ret;
}

7534 7535 7536 7537
static int vboxNetworkUndefine(virNetworkPtr network) {
    return vboxNetworkUndefineDestroy(network, true);
}

7538
static int vboxNetworkCreate(virNetworkPtr network) {
7539
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
7540
    char *networkNameUtf8 = NULL;
7541 7542
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7543 7544 7545 7546 7547 7548 7549 7550 7551

    /* 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) {
7552
        virReportOOMError();
7553 7554 7555
        goto cleanup;
    }

7556
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
7557

7558
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7559

7560 7561
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7562

7563
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7564

7565 7566 7567
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
7568 7569


7570
            VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
7571

7572 7573 7574 7575 7576
            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (dhcpServer) {
                PRUnichar *trunkTypeUtf16 = NULL;
7577

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

7580
                VBOX_UTF8_TO_UTF16("netflt", &trunkTypeUtf16);
7581

7582 7583 7584 7585
                dhcpServer->vtbl->Start(dhcpServer,
                                        networkNameUtf16,
                                        networkInterfaceNameUtf16,
                                        trunkTypeUtf16);
7586

7587 7588
                VBOX_UTF16_FREE(trunkTypeUtf16);
                VBOX_RELEASE(dhcpServer);
7589 7590
            }

7591
            VBOX_UTF16_FREE(networkNameUtf16);
7592
        }
7593 7594

        VBOX_RELEASE(networkInterface);
7595 7596
    }

7597 7598 7599
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7600 7601 7602 7603 7604 7605 7606 7607
    ret = 0;

cleanup:
    VIR_FREE(networkNameUtf8);
    return ret;
}

static int vboxNetworkDestroy(virNetworkPtr network) {
7608
    return vboxNetworkUndefineDestroy(network, false);
7609 7610
}

7611
static char *vboxNetworkGetXMLDesc(virNetworkPtr network,
E
Eric Blake 已提交
7612 7613
                                   unsigned int flags)
{
7614
    VBOX_OBJECT_HOST_CHECK(network->conn, char *, NULL);
7615
    virNetworkDefPtr def  = NULL;
7616
    virNetworkIpDefPtr ipdef = NULL;
7617
    char *networkNameUtf8 = NULL;
7618 7619
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
7620

E
Eric Blake 已提交
7621 7622
    virCheckFlags(0, NULL);

7623
    if (VIR_ALLOC(def) < 0) {
7624
        virReportOOMError();
7625 7626
        goto cleanup;
    }
7627 7628 7629 7630 7631 7632
    if (VIR_ALLOC(ipdef) < 0) {
        virReportOOMError();
        goto cleanup;
    }
    def->ips = ipdef;
    def->nips = 1;
7633 7634

    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0) {
7635
        virReportOOMError();
7636 7637 7638
        goto cleanup;
    }

7639
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
7640

7641
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
7642

7643 7644
    if (networkInterface) {
        PRUint32 interfaceType = 0;
7645

7646
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
7647

7648 7649 7650 7651 7652
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            def->name = strdup(network->name);
            if (def->name != NULL) {
                PRUnichar *networkNameUtf16 = NULL;
                IDHCPServer *dhcpServer     = NULL;
7653
                vboxIID vboxnet0IID = VBOX_IID_INITIALIZER;
7654

7655 7656
                networkInterface->vtbl->GetId(networkInterface, &vboxnet0IID.value);
                vboxIIDToUUID(&vboxnet0IID, def->uuid);
7657

7658
                VBOX_UTF8_TO_UTF16(networkNameUtf8 , &networkNameUtf16);
7659

7660
                def->forwardType = VIR_NETWORK_FORWARD_NONE;
7661

7662 7663 7664 7665
                data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                                 networkNameUtf16,
                                                                 &dhcpServer);
                if (dhcpServer) {
7666 7667
                    ipdef->nranges = 1;
                    if (VIR_ALLOC_N(ipdef->ranges, ipdef->nranges) >=0 ) {
7668 7669 7670 7671
                        PRUnichar *ipAddressUtf16     = NULL;
                        PRUnichar *networkMaskUtf16   = NULL;
                        PRUnichar *fromIPAddressUtf16 = NULL;
                        PRUnichar *toIPAddressUtf16   = NULL;
7672
                        bool errorOccurred = false;
7673

7674 7675 7676 7677 7678 7679 7680
                        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
                         */
7681
                        if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
7682
                                                     &ipdef->address) < 0 ||
7683
                            vboxSocketParseAddrUtf16(data, networkMaskUtf16,
7684
                                                     &ipdef->netmask) < 0 ||
7685
                            vboxSocketParseAddrUtf16(data, fromIPAddressUtf16,
7686
                                                     &ipdef->ranges[0].start) < 0 ||
7687
                            vboxSocketParseAddrUtf16(data, toIPAddressUtf16,
7688
                                                     &ipdef->ranges[0].end) < 0) {
7689 7690
                            errorOccurred = true;
                        }
7691 7692 7693 7694 7695

                        VBOX_UTF16_FREE(ipAddressUtf16);
                        VBOX_UTF16_FREE(networkMaskUtf16);
                        VBOX_UTF16_FREE(fromIPAddressUtf16);
                        VBOX_UTF16_FREE(toIPAddressUtf16);
7696 7697 7698 7699

                        if (errorOccurred) {
                            goto cleanup;
                        }
7700
                    } else {
7701
                        ipdef->nranges = 0;
7702
                        virReportOOMError();
7703
                    }
7704

7705 7706 7707 7708 7709 7710
                    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;
7711
                            virReportOOMError();
7712
                        } else {
7713 7714
                            PRUnichar *macAddressUtf16 = NULL;
                            PRUnichar *ipAddressUtf16  = NULL;
7715
                            bool errorOccurred = false;
7716

7717
                            networkInterface->vtbl->GetHardwareAddress(networkInterface, &macAddressUtf16);
7718 7719
                            networkInterface->vtbl->GetIPAddress(networkInterface, &ipAddressUtf16);

7720
                            VBOX_UTF16_TO_UTF8(macAddressUtf16, &ipdef->hosts[0].mac);
7721 7722

                            if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
7723
                                                         &ipdef->hosts[0].ip) < 0) {
7724 7725
                                errorOccurred = true;
                            }
7726

7727 7728
                            VBOX_UTF16_FREE(macAddressUtf16);
                            VBOX_UTF16_FREE(ipAddressUtf16);
7729 7730 7731 7732

                            if (errorOccurred) {
                                goto cleanup;
                            }
7733 7734
                        }
                    } else {
7735
                        ipdef->nhosts = 0;
7736
                    }
7737 7738 7739 7740 7741

                    VBOX_RELEASE(dhcpServer);
                } else {
                    PRUnichar *networkMaskUtf16 = NULL;
                    PRUnichar *ipAddressUtf16   = NULL;
7742
                    bool errorOccurred = false;
7743 7744 7745 7746

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

7747
                    if (vboxSocketParseAddrUtf16(data, networkMaskUtf16,
7748
                                                 &ipdef->netmask) < 0 ||
7749
                        vboxSocketParseAddrUtf16(data, ipAddressUtf16,
7750
                                                 &ipdef->address) < 0) {
7751 7752
                        errorOccurred = true;
                    }
7753 7754 7755

                    VBOX_UTF16_FREE(networkMaskUtf16);
                    VBOX_UTF16_FREE(ipAddressUtf16);
7756 7757 7758 7759

                    if (errorOccurred) {
                        goto cleanup;
                    }
7760 7761
                }

7762 7763
                DEBUGIID("Network UUID", vboxnet0IID.value);
                vboxIIDUnalloc(&vboxnet0IID);
7764 7765
                VBOX_UTF16_FREE(networkNameUtf16);
            } else {
7766
                virReportOOMError();
7767 7768
            }
        }
7769 7770

        VBOX_RELEASE(networkInterface);
7771 7772
    }

7773 7774 7775
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

7776
    ret = virNetworkDefFormat(def);
7777 7778

cleanup:
7779
    virNetworkDefFree(def);
7780 7781 7782 7783
    VIR_FREE(networkNameUtf8);
    return ret;
}

7784 7785 7786 7787 7788 7789
/**
 * The Storage Functions here on
 */

static virDrvOpenStatus vboxStorageOpen (virConnectPtr conn,
                                         virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
7790 7791
                                         unsigned int flags)
{
7792 7793
    vboxGlobalData *data = conn->privateData;

E
Eric Blake 已提交
7794 7795
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

7796
    if (STRNEQ(conn->driver->name, "VBOX"))
7797
        return VIR_DRV_OPEN_DECLINED;
7798 7799 7800 7801

    if ((data->pFuncs      == NULL) ||
        (data->vboxObj     == NULL) ||
        (data->vboxSession == NULL))
7802
        return VIR_DRV_OPEN_ERROR;
7803

7804
    VIR_DEBUG("vbox storage initialized");
7805 7806 7807 7808 7809
    /* conn->storagePrivateData = some storage specific data */
    return VIR_DRV_OPEN_SUCCESS;
}

static int vboxStorageClose (virConnectPtr conn) {
7810
    VIR_DEBUG("vbox storage uninitialized");
7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823
    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;
}

7824 7825
static int vboxStorageListPools(virConnectPtr conn ATTRIBUTE_UNUSED,
                                char **const names, int nnames) {
7826 7827 7828 7829 7830
    int numActive = 0;

    if (nnames == 1) {
        names[numActive] = strdup("default-pool");
        if (names[numActive] == NULL) {
7831
            virReportOOMError();
7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843 7844 7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858
        } 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) {
7859
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
7860
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
7861 7862 7863 7864
    PRUint32 hardDiskAccessible = 0;
    nsresult rc;
    int i;

7865
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
7866
    if (NS_SUCCEEDED(rc)) {
7867 7868
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
7869 7870
            if (hardDisk) {
                PRUint32 hddstate;
7871

7872 7873 7874
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible)
                    hardDiskAccessible++;
7875 7876
            }
        }
7877 7878 7879 7880

        vboxArrayRelease(&hardDisks);

        ret = hardDiskAccessible;
7881
    } else {
7882
        ret = -1;
7883 7884
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not get number of volumes in the pool: %s, rc=%08x"),
7885
                  pool->name, (unsigned)rc);
7886 7887
    }

7888
    return ret;
7889 7890 7891
}

static int vboxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names, int nnames) {
7892
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
7893
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
7894 7895 7896 7897
    PRUint32 numActive     = 0;
    nsresult rc;
    int i;

7898
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
7899
    if (NS_SUCCEEDED(rc)) {
7900 7901
        for (i = 0; i < hardDisks.count && numActive < nnames; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
7902

7903 7904 7905 7906
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
7907

7908 7909 7910
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
7911

7912 7913
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
7914

7915
                    if (nameUtf8) {
7916
                        VIR_DEBUG("nnames[%d]: %s", numActive, nameUtf8);
7917 7918
                        names[numActive] = strdup(nameUtf8);
                        if (names[numActive] == NULL) {
7919
                            virReportOOMError();
7920 7921
                        } else {
                            numActive++;
7922
                        }
7923 7924

                        VBOX_UTF8_FREE(nameUtf8);
7925 7926 7927 7928
                    }
                }
            }
        }
7929 7930 7931 7932

        vboxArrayRelease(&hardDisks);

        ret = numActive;
7933
    } else {
7934
        ret = -1;
7935 7936
        vboxError(VIR_ERR_INTERNAL_ERROR,
                  _("could not get the volume list in the pool: %s, rc=%08x"),
7937
                  pool->name, (unsigned)rc);
7938 7939
    }

7940
    return ret;
7941 7942 7943
}

static virStorageVolPtr vboxStorageVolLookupByName(virStoragePoolPtr pool, const char *name) {
7944
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
7945
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
7946 7947 7948
    nsresult rc;
    int i;

7949 7950
    if(!name)
        return ret;
7951

7952
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
7953
    if (NS_SUCCEEDED(rc)) {
7954 7955
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
7956

7957 7958 7959 7960
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
7961

7962 7963 7964
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
7965

7966 7967 7968 7969
                    if (nameUtf16) {
                        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                        VBOX_UTF16_FREE(nameUtf16);
                    }
7970

7971
                    if (nameUtf8 && STREQ(nameUtf8, name)) {
7972 7973 7974
                        vboxIID hddIID = VBOX_IID_INITIALIZER;
                        unsigned char uuid[VIR_UUID_BUFLEN];
                        char key[VIR_UUID_STRING_BUFLEN] = "";
7975

7976 7977 7978 7979
                        rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
                        if (NS_SUCCEEDED(rc)) {
                            vboxIIDToUUID(&hddIID, uuid);
                            virUUIDFormat(uuid, key);
7980

7981
                            ret = virGetStorageVol(pool->conn, pool->name, name, key);
7982

7983 7984 7985 7986
                            VIR_DEBUG("virStorageVolPtr: %p", ret);
                            VIR_DEBUG("Storage Volume Name: %s", name);
                            VIR_DEBUG("Storage Volume key : %s", key);
                            VIR_DEBUG("Storage Volume Pool: %s", pool->name);
7987 7988
                        }

7989
                        vboxIIDUnalloc(&hddIID);
7990 7991
                        VBOX_UTF8_FREE(nameUtf8);
                        break;
7992
                    }
7993 7994 7995

                    if (nameUtf8)
                        VBOX_UTF8_FREE(nameUtf8);
7996 7997 7998
                }
            }
        }
7999

8000
        vboxArrayRelease(&hardDisks);
8001 8002 8003 8004 8005 8006
    }

    return ret;
}

static virStorageVolPtr vboxStorageVolLookupByKey(virConnectPtr conn, const char *key) {
8007
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
8008 8009
    vboxIID hddIID = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
8010 8011 8012
    IHardDisk *hardDisk  = NULL;
    nsresult rc;

8013 8014 8015
    if (!key)
        return ret;

8016 8017 8018 8019
    if (virUUIDParse(key, uuid) < 0) {
        vboxError(VIR_ERR_INVALID_ARG,
                  _("Could not parse UUID from '%s'"), key);
        return NULL;
8020 8021
    }

8022
    vboxIIDFromUUID(&hddIID, uuid);
8023
#if VBOX_API_VERSION < 4000
8024
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
8025 8026 8027 8028
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
#endif /* VBOX_API_VERSION >= 4000 */
8029 8030
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8031

8032 8033 8034 8035
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
8036

8037 8038
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
8039

8040 8041 8042
            if (hddNameUtf8) {
                if (vboxStorageNumOfPools(conn) == 1) {
                    ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, key);
8043
                    VIR_DEBUG("Storage Volume Pool: %s", "default-pool");
8044 8045 8046 8047
                } else {
                    /* TODO: currently only one default pool and thus
                     * nothing here, change it when pools are supported
                     */
8048 8049
                }

8050 8051
                VIR_DEBUG("Storage Volume Name: %s", key);
                VIR_DEBUG("Storage Volume key : %s", hddNameUtf8);
8052 8053 8054

                VBOX_UTF8_FREE(hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
8055 8056
            }
        }
8057 8058

        VBOX_MEDIUM_RELEASE(hardDisk);
8059 8060
    }

8061
    vboxIIDUnalloc(&hddIID);
8062 8063 8064 8065
    return ret;
}

static virStorageVolPtr vboxStorageVolLookupByPath(virConnectPtr conn, const char *path) {
8066
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
8067 8068 8069 8070
    PRUnichar *hddPathUtf16 = NULL;
    IHardDisk *hardDisk     = NULL;
    nsresult rc;

8071 8072
    if (!path)
        return ret;
8073

8074
    VBOX_UTF8_TO_UTF16(path, &hddPathUtf16);
8075

8076 8077
    if (!hddPathUtf16)
        return ret;
8078

8079
#if VBOX_API_VERSION < 4000
8080
    rc = data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddPathUtf16, &hardDisk);
8081 8082 8083 8084
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddPathUtf16,
                                         DeviceType_HardDisk, &hardDisk);
#endif /* VBOX_API_VERSION >= 4000 */
8085 8086
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8087

8088 8089 8090 8091
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
8092

8093
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
8094

8095 8096 8097 8098
            if (hddNameUtf16) {
                VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
            }
8099

8100 8101 8102 8103
            if (hddNameUtf8) {
                vboxIID hddIID = VBOX_IID_INITIALIZER;
                unsigned char uuid[VIR_UUID_BUFLEN];
                char key[VIR_UUID_STRING_BUFLEN] = "";
8104

8105 8106 8107 8108
                rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
                if (NS_SUCCEEDED(rc)) {
                    vboxIIDToUUID(&hddIID, uuid);
                    virUUIDFormat(uuid, key);
8109

8110 8111 8112 8113 8114
                    /* 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, key);
8115

8116 8117 8118
                    VIR_DEBUG("Storage Volume Pool: %s", "default-pool");
                    VIR_DEBUG("Storage Volume Name: %s", hddNameUtf8);
                    VIR_DEBUG("Storage Volume key : %s", key);
8119
                }
8120

8121
                vboxIIDUnalloc(&hddIID);
8122 8123
            }

8124 8125
            if (hddNameUtf8)
                VBOX_UTF8_FREE(hddNameUtf8);
8126
        }
8127 8128

        VBOX_MEDIUM_RELEASE(hardDisk);
8129 8130
    }

8131 8132
    VBOX_UTF16_FREE(hddPathUtf16);

8133 8134 8135 8136 8137
    return ret;
}

static virStorageVolPtr vboxStorageVolCreateXML(virStoragePoolPtr pool,
                                                const char *xml,
E
Eric Blake 已提交
8138 8139
                                                unsigned int flags)
{
8140
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
8141
    virStorageVolDefPtr  def  = NULL;
8142 8143
    PRUnichar *hddFormatUtf16 = NULL;
    PRUnichar *hddNameUtf16   = NULL;
8144 8145 8146
    virStoragePoolDef poolDef;
    nsresult rc;

E
Eric Blake 已提交
8147 8148
    virCheckFlags(0, NULL);

8149 8150 8151 8152 8153 8154 8155 8156
    /* 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;

8157
    if ((def = virStorageVolDefParseString(&poolDef, xml)) == NULL)
8158 8159
        goto cleanup;

8160 8161 8162
    if (   !def->name
        || (def->type != VIR_STORAGE_VOL_FILE))
        goto cleanup;
8163

8164 8165 8166 8167 8168 8169
    /* 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
     */
8170

8171 8172 8173 8174 8175 8176 8177
    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);
    }
8178

8179
    VBOX_UTF8_TO_UTF16(def->name, &hddNameUtf16);
8180

8181 8182
    if (hddFormatUtf16 && hddNameUtf16) {
        IHardDisk *hardDisk = NULL;
8183

8184 8185 8186
        rc = data->vboxObj->vtbl->CreateHardDisk(data->vboxObj, hddFormatUtf16, hddNameUtf16, &hardDisk);
        if (NS_SUCCEEDED(rc)) {
            IProgress *progress    = NULL;
8187
            PRUint64   logicalSize = VIR_DIV_UP(def->capacity, 1024 * 1024);
8188
            PRUint32   variant     = HardDiskVariant_Standard;
8189

8190 8191
            if (def->capacity == def->allocation)
                variant = HardDiskVariant_Fixed;
8192

8193 8194
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, variant, &progress);
            if (NS_SUCCEEDED(rc) && progress) {
8195
#if VBOX_API_VERSION == 2002
8196
                nsresult resultCode;
8197
#else
8198
                PRInt32  resultCode;
8199 8200
#endif

8201 8202
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
8203

8204
                if (NS_SUCCEEDED(resultCode)) {
8205 8206 8207
                    vboxIID hddIID = VBOX_IID_INITIALIZER;
                    unsigned char uuid[VIR_UUID_BUFLEN];
                    char key[VIR_UUID_STRING_BUFLEN] = "";
8208

8209
                    rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
8210
                    if (NS_SUCCEEDED(rc)) {
8211 8212
                        vboxIIDToUUID(&hddIID, uuid);
                        virUUIDFormat(uuid, key);
8213

8214
                        ret = virGetStorageVol(pool->conn, pool->name, def->name, key);
8215
                    }
8216 8217

                    vboxIIDUnalloc(&hddIID);
8218 8219
                }

8220
                VBOX_RELEASE(progress);
8221
            }
8222
        }
8223 8224
    }

8225 8226 8227
    VBOX_UTF16_FREE(hddFormatUtf16);
    VBOX_UTF16_FREE(hddNameUtf16);

8228 8229 8230 8231 8232 8233
cleanup:
    virStorageVolDefFree(def);
    return ret;
}

static int vboxStorageVolDelete(virStorageVolPtr vol,
E
Eric Blake 已提交
8234 8235
                                unsigned int flags)
{
8236
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
8237 8238
    vboxIID hddIID = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
8239 8240 8241
    IHardDisk *hardDisk  = NULL;
    int deregister = 0;
    nsresult rc;
8242 8243
    int i = 0;
    int j = 0;
8244

E
Eric Blake 已提交
8245 8246
    virCheckFlags(0, -1);

8247 8248 8249 8250 8251
    if (virUUIDParse(vol->key, uuid) < 0) {
        vboxError(VIR_ERR_INVALID_ARG,
                  _("Could not parse UUID from '%s'"), vol->key);
        return -1;
    }
8252

8253
    vboxIIDFromUUID(&hddIID, uuid);
8254
#if VBOX_API_VERSION < 4000
8255
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
8256 8257 8258 8259
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
#endif /* VBOX_API_VERSION >= 4000 */
8260 8261
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8262

8263 8264 8265
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint32  machineIdsSize = 0;
8266 8267 8268 8269 8270 8271 8272
            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 */
8273

8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285
#if VBOX_API_VERSION == 2002 && defined WIN32
            /* VirtualBox 2.2 on Windows represents IIDs as GUIDs and the
             * machineIds array contains direct instances of the GUID struct
             * instead of pointers to the actual struct instances. But there
             * is no 128bit width simple item type for a SafeArray to fit a
             * GUID in. The largest simple type it 64bit width and VirtualBox
             * uses two of this 64bit items to represents one GUID. Therefore,
             * we devide the size of the SafeArray by two, to compensate for
             * this workaround in VirtualBox */
            machineIds.count /= 2;
#endif /* VBOX_API_VERSION >= 2002 */

8286
            machineIdsSize = machineIds.count;
8287

8288
            for (i = 0; i < machineIds.count; i++) {
8289
                IMachine *machine = NULL;
8290 8291 8292
                vboxIID machineId = VBOX_IID_INITIALIZER;

                vboxIIDFromArrayItem(&machineId, &machineIds, i);
8293

8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304
#if VBOX_API_VERSION >= 4000
                rc = VBOX_OBJECT_GET_MACHINE(machineId.value, &machine);
                if (NS_FAILED(rc)) {
                    vboxError(VIR_ERR_NO_DOMAIN, "%s",
                              _("no domain with matching uuid"));
                    break;
                }
#endif

                rc = VBOX_SESSION_OPEN(machineId.value, machine);

8305
                if (NS_SUCCEEDED(rc)) {
8306

8307 8308
                    rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                    if (NS_SUCCEEDED(rc)) {
8309
                        vboxArray hddAttachments = VBOX_ARRAY_INITIALIZER;
8310 8311

#if VBOX_API_VERSION < 3001
8312 8313
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetHardDiskAttachments);
8314
#else  /* VBOX_API_VERSION >= 3001 */
8315 8316
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetMediumAttachments);
8317
#endif /* VBOX_API_VERSION >= 3001 */
8318 8319
                        for (j = 0; j < hddAttachments.count; j++) {
                            IHardDiskAttachment *hddAttachment = hddAttachments.items[j];
8320 8321 8322 8323 8324 8325 8326 8327 8328 8329

                            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) {
8330
                                    vboxIID iid = VBOX_IID_INITIALIZER;
8331

8332 8333
                                    rc = VBOX_MEDIUM_FUNC_ARG1(hdd, GetId, &iid.value);
                                    if (NS_SUCCEEDED(rc)) {
8334

8335 8336
                                            DEBUGIID("HardDisk (to delete) UUID", hddIID.value);
                                            DEBUGIID("HardDisk (currently processing) UUID", iid.value);
8337

8338
                                        if (vboxIIDIsEqual(&hddIID, &iid)) {
8339 8340 8341 8342
                                            PRUnichar *controller = NULL;
                                            PRInt32    port       = 0;
                                            PRInt32    device     = 0;

8343
                                            DEBUGIID("Found HardDisk to delete, UUID", hddIID.value);
8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355

                                            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);
8356
                                                VIR_DEBUG("saving machine settings");
8357
                                            }
8358

8359 8360
                                            if (NS_SUCCEEDED(rc)) {
                                                deregister++;
8361
                                                VIR_DEBUG("deregistering hdd:%d", deregister);
8362
                                            }
8363 8364 8365

                                            if (controller)
                                                VBOX_UTF16_FREE(controller);
8366
                                        }
8367
                                        vboxIIDUnalloc(&iid);
8368
                                    }
8369
                                    VBOX_MEDIUM_RELEASE(hdd);
8370 8371 8372
                                }
                            }
                        }
8373
                        vboxArrayRelease(&hddAttachments);
8374
                        VBOX_RELEASE(machine);
8375
                    }
8376
                    VBOX_SESSION_CLOSE();
8377
                }
8378 8379

                vboxIIDUnalloc(&machineId);
8380
            }
8381

8382
            vboxArrayUnalloc(&machineIds);
8383

8384 8385
            if (machineIdsSize == 0 || machineIdsSize == deregister) {
                IProgress *progress = NULL;
8386

8387
                rc = hardDisk->vtbl->DeleteStorage(hardDisk, &progress);
8388

8389 8390 8391
                if (NS_SUCCEEDED(rc) && progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
8392
                    DEBUGIID("HardDisk deleted, UUID", hddIID.value);
8393
                    ret = 0;
8394 8395 8396
                }
            }
        }
8397 8398

        VBOX_MEDIUM_RELEASE(hardDisk);
8399 8400
    }

8401
    vboxIIDUnalloc(&hddIID);
8402

8403 8404 8405 8406
    return ret;
}

static int vboxStorageVolGetInfo(virStorageVolPtr vol, virStorageVolInfoPtr info) {
8407
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
8408
    IHardDisk *hardDisk  = NULL;
8409 8410
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
8411 8412
    nsresult rc;

8413
    if (!info)
8414
        return ret;
8415

8416 8417 8418
    if (virUUIDParse(vol->key, uuid) < 0) {
        vboxError(VIR_ERR_INVALID_ARG,
                  _("Could not parse UUID from '%s'"), vol->key);
8419
        return ret;
8420
    }
8421

8422
    vboxIIDFromUUID(&hddIID, uuid);
8423
#if VBOX_API_VERSION < 4000
8424
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
8425 8426 8427 8428
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
#endif /* VBOX_API_VERSION >= 4000 */
8429 8430
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8431

8432 8433
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
8434
#if VBOX_API_VERSION < 4000
8435 8436
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
8437 8438 8439 8440
#else /* VBOX_API_VERSION >= 4000 */
            PRInt64 hddLogicalSize;
            PRInt64 hddActualSize;
#endif /* VBOX_API_VERSION >= 4000 */
8441

8442
            info->type = VIR_STORAGE_VOL_FILE;
8443

8444
            hardDisk->vtbl->GetLogicalSize(hardDisk, &hddLogicalSize);
8445
#if VBOX_API_VERSION < 4000
8446
            info->capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
8447 8448 8449
#else /* VBOX_API_VERSION >= 4000 */
            info->capacity = hddLogicalSize;
#endif /* VBOX_API_VERSION >= 4000 */
8450

8451 8452
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            info->allocation = hddActualSize;
8453

8454
            ret = 0;
8455

8456 8457 8458 8459
            VIR_DEBUG("Storage Volume Name: %s", vol->name);
            VIR_DEBUG("Storage Volume Type: %s", info->type == VIR_STORAGE_VOL_BLOCK ? "Block" : "File");
            VIR_DEBUG("Storage Volume Capacity: %llu", info->capacity);
            VIR_DEBUG("Storage Volume Allocation: %llu", info->allocation);
8460
        }
8461 8462

        VBOX_MEDIUM_RELEASE(hardDisk);
8463 8464
    }

8465
    vboxIIDUnalloc(&hddIID);
8466

8467 8468 8469
    return ret;
}

E
Eric Blake 已提交
8470 8471
static char *vboxStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags)
{
8472
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
8473
    IHardDisk *hardDisk  = NULL;
8474 8475
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
8476 8477 8478 8479 8480
    virStoragePoolDef pool;
    virStorageVolDef def;
    int defOk = 0;
    nsresult rc;

E
Eric Blake 已提交
8481 8482
    virCheckFlags(0, NULL);

8483 8484 8485
    memset(&pool, 0, sizeof(pool));
    memset(&def, 0, sizeof(def));

8486 8487 8488
    if (virUUIDParse(vol->key, uuid) < 0) {
        vboxError(VIR_ERR_INVALID_ARG,
                  _("Could not parse UUID from '%s'"), vol->key);
8489
        return ret;
8490
    }
8491

8492
    vboxIIDFromUUID(&hddIID, uuid);
8493
#if VBOX_API_VERSION < 4000
8494
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
8495 8496 8497 8498
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
#endif /* VBOX_API_VERSION >= 4000 */
8499 8500 8501 8502 8503 8504
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;

        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (NS_SUCCEEDED(rc) && hddstate != MediaState_Inaccessible) {
            PRUnichar *hddFormatUtf16 = NULL;
8505
#if VBOX_API_VERSION < 4000
8506 8507
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
8508 8509 8510 8511
#else /* VBOX_API_VERSION >= 4000 */
            PRInt64 hddLogicalSize;
            PRInt64 hddActualSize;
#endif /* VBOX_API_VERSION >= 4000 */
8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522

            /* 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);
8523 8524
            if (NS_SUCCEEDED(rc) && defOk) {
#if VBOX_API_VERSION < 4000
8525
                def.capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
8526 8527 8528 8529
#else /* VBOX_API_VERSION >= 4000 */
                def.capacity = hddLogicalSize;
#endif /* VBOX_API_VERSION >= 4000 */
            } else
8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552
                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) {

8553
                    VIR_DEBUG("Storage Volume Format: %s", hddFormatUtf8);
8554 8555 8556 8557 8558

                    if (STRCASEEQ("vmdk", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VMDK;
                    else if (STRCASEEQ("vhd", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VPC;
8559
                    else
8560
                        def.target.format = VIR_STORAGE_FILE_RAW;
8561

8562 8563 8564
                    /* TODO: need to add vdi to enum virStorageFileFormat {}
                     * and then add it here
                     */
8565

8566
                    VBOX_UTF8_FREE(hddFormatUtf8);
8567 8568
                }

8569 8570 8571
                VBOX_UTF16_FREE(hddFormatUtf16);
            } else {
                defOk = 0;
8572 8573
            }
        }
8574 8575

        VBOX_MEDIUM_RELEASE(hardDisk);
8576 8577
    }

8578
    vboxIIDUnalloc(&hddIID);
8579

8580
    if (defOk)
8581
        ret = virStorageVolDefFormat(&pool, &def);
8582 8583 8584 8585 8586

    return ret;
}

static char *vboxStorageVolGetPath(virStorageVolPtr vol) {
8587
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
8588
    IHardDisk *hardDisk  = NULL;
8589 8590
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
8591 8592
    nsresult rc;

8593 8594 8595
    if (virUUIDParse(vol->key, uuid) < 0) {
        vboxError(VIR_ERR_INVALID_ARG,
                  _("Could not parse UUID from '%s'"), vol->key);
8596
        return ret;
8597
    }
8598

8599
    vboxIIDFromUUID(&hddIID, uuid);
8600
#if VBOX_API_VERSION < 4000
8601
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
8602 8603 8604 8605
#else /* VBOX_API_VERSION >= 4000 */
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
#endif /* VBOX_API_VERSION >= 4000 */
8606 8607
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
8608

8609 8610 8611 8612
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddLocationUtf16 = NULL;
            char      *hddLocationUtf8  = NULL;
8613

8614
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetLocation, &hddLocationUtf16);
8615

8616 8617
            VBOX_UTF16_TO_UTF8(hddLocationUtf16, &hddLocationUtf8);
            if (hddLocationUtf8) {
8618

8619 8620
                ret = strdup(hddLocationUtf8);
                if (!ret)
8621
                    virReportOOMError();
8622

8623 8624 8625
                VIR_DEBUG("Storage Volume Name: %s", vol->name);
                VIR_DEBUG("Storage Volume Path: %s", hddLocationUtf8);
                VIR_DEBUG("Storage Volume Pool: %s", vol->pool);
8626

8627
                VBOX_UTF8_FREE(hddLocationUtf8);
8628 8629
            }

8630
            VBOX_UTF16_FREE(hddLocationUtf16);
8631
        }
8632 8633

        VBOX_MEDIUM_RELEASE(hardDisk);
8634 8635
    }

8636
    vboxIIDUnalloc(&hddIID);
8637

8638 8639
    return ret;
}
8640

8641 8642 8643 8644 8645
#if VBOX_API_VERSION == 4000
static char *
vboxDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
8646
                     unsigned int flags)
8647 8648 8649 8650 8651 8652 8653 8654 8655 8656
{
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
    IConsole *console = NULL;
    vboxIID iid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    nsresult rc;
    char *tmp;
    int tmp_fd = -1;
    unsigned int max_screen;

E
Eric Blake 已提交
8657 8658
    virCheckFlags(0, NULL);

8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765
    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_NO_DOMAIN, "%s",
                  _("no domain with matching uuid"));
        return NULL;
    }

    rc = machine->vtbl->GetMonitorCount(machine, &max_screen);
    if (NS_FAILED(rc)) {
        vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                  _("unable to get monitor count"));
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (screen >= max_screen) {
        vboxError(VIR_ERR_INVALID_ARG, _("screen ID higher than monitor "
                  "count (%d)"), max_screen);
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (virAsprintf(&tmp, "%s/cache/libvirt/vbox.screendump.XXXXXX", LOCALSTATEDIR) < 0) {
        virReportOOMError();
        VBOX_RELEASE(machine);
        return NULL;
    }

    if ((tmp_fd = mkstemp(tmp)) == -1) {
        virReportSystemError(errno, _("mkstemp(\"%s\") failed"), tmp);
        VIR_FREE(tmp);
        VBOX_RELEASE(machine);
        return NULL;
    }


    rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
    if (NS_SUCCEEDED(rc)) {
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (NS_SUCCEEDED(rc) && console) {
            IDisplay *display = NULL;

            console->vtbl->GetDisplay(console, &display);

            if (display) {
                PRUint32 width, height, bitsPerPixel;
                PRUint32 screenDataSize;
                PRUint8 *screenData;

                rc = display->vtbl->GetScreenResolution(display, screen,
                                                        &width, &height,
                                                        &bitsPerPixel);

                if (NS_FAILED(rc) || !width || !height) {
                    vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                              _("unable to get screen resolution"));
                    goto endjob;
                }

                rc = display->vtbl->TakeScreenShotPNGToArray(display, screen,
                                                             width, height,
                                                             &screenDataSize,
                                                             &screenData);
                if (NS_FAILED(rc)) {
                    vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                              _("failed to take screenshot"));
                    goto endjob;
                }

                if (safewrite(tmp_fd, (char *) screenData,
                              screenDataSize) < 0) {
                    virReportSystemError(errno, _("unable to write data "
                                                  "to '%s'"), tmp);
                    goto endjob;
                }

                if (VIR_CLOSE(tmp_fd) < 0) {
                    virReportSystemError(errno, _("unable to close %s"), tmp);
                    goto endjob;
                }

                if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY, true) < 0) {
                    vboxError(VIR_ERR_OPERATION_FAILED, "%s",
                              _("unable to open stream"));
                    goto endjob;
                }

                ret = strdup("image/png");

endjob:
                VIR_FREE(screenData);
                VBOX_RELEASE(display);
            }
            VBOX_RELEASE(console);
        }
        VBOX_SESSION_CLOSE();
    }

    VIR_FORCE_CLOSE(tmp_fd);
    VIR_FREE(tmp);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
#endif /* VBOX_API_VERSION == 4000 */

8766 8767 8768 8769
/**
 * Function Tables
 */

8770
virDriver NAME(Driver) = {
8771 8772
    .no = VIR_DRV_VBOX,
    .name = "VBOX",
8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790
    .open = vboxOpen, /* 0.6.3 */
    .close = vboxClose, /* 0.6.3 */
    .version = vboxGetVersion, /* 0.6.3 */
    .getHostname = virGetHostname, /* 0.6.3 */
    .getMaxVcpus = vboxGetMaxVcpus, /* 0.6.3 */
    .nodeGetInfo = nodeGetInfo, /* 0.6.3 */
    .getCapabilities = vboxGetCapabilities, /* 0.6.3 */
    .listDomains = vboxListDomains, /* 0.6.3 */
    .numOfDomains = vboxNumOfDomains, /* 0.6.3 */
    .domainCreateXML = vboxDomainCreateXML, /* 0.6.3 */
    .domainLookupByID = vboxDomainLookupByID, /* 0.6.3 */
    .domainLookupByUUID = vboxDomainLookupByUUID, /* 0.6.3 */
    .domainLookupByName = vboxDomainLookupByName, /* 0.6.3 */
    .domainSuspend = vboxDomainSuspend, /* 0.6.3 */
    .domainResume = vboxDomainResume, /* 0.6.3 */
    .domainShutdown = vboxDomainShutdown, /* 0.6.3 */
    .domainReboot = vboxDomainReboot, /* 0.6.3 */
    .domainDestroy = vboxDomainDestroy, /* 0.6.3 */
8791
    .domainDestroyFlags = vboxDomainDestroyFlags, /* 0.9.4 */
8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814
    .domainGetOSType = vboxDomainGetOSType, /* 0.6.3 */
    .domainSetMemory = vboxDomainSetMemory, /* 0.6.3 */
    .domainGetInfo = vboxDomainGetInfo, /* 0.6.3 */
    .domainGetState = vboxDomainGetState, /* 0.9.2 */
    .domainSave = vboxDomainSave, /* 0.6.3 */
    .domainSetVcpus = vboxDomainSetVcpus, /* 0.7.1 */
    .domainSetVcpusFlags = vboxDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = vboxDomainGetVcpusFlags, /* 0.8.5 */
    .domainGetMaxVcpus = vboxDomainGetMaxVcpus, /* 0.7.1 */
    .domainGetXMLDesc = vboxDomainGetXMLDesc, /* 0.6.3 */
    .listDefinedDomains = vboxListDefinedDomains, /* 0.6.3 */
    .numOfDefinedDomains = vboxNumOfDefinedDomains, /* 0.6.3 */
    .domainCreate = vboxDomainCreate, /* 0.6.3 */
    .domainCreateWithFlags = vboxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = vboxDomainDefineXML, /* 0.6.3 */
    .domainUndefine = vboxDomainUndefine, /* 0.6.3 */
    .domainAttachDevice = vboxDomainAttachDevice, /* 0.6.3 */
    .domainAttachDeviceFlags = vboxDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = vboxDomainDetachDevice, /* 0.6.3 */
    .domainDetachDeviceFlags = vboxDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = vboxDomainUpdateDeviceFlags, /* 0.8.0 */
    .nodeGetCellsFreeMemory = nodeGetCellsFreeMemory, /* 0.6.5 */
    .nodeGetFreeMemory = nodeGetFreeMemory, /* 0.6.5 */
8815
#if VBOX_API_VERSION == 4000
8816
    .domainScreenshot = vboxDomainScreenshot, /* 0.9.2 */
8817
#endif
8818
#if VBOX_API_VERSION != 2002 && VBOX_API_VERSION != 4000
8819 8820
    .domainEventRegister = vboxDomainEventRegister, /* 0.7.0 */
    .domainEventDeregister = vboxDomainEventDeregister, /* 0.7.0 */
8821
#endif
8822 8823 8824 8825 8826
    .isEncrypted = vboxIsEncrypted, /* 0.7.3 */
    .isSecure = vboxIsSecure, /* 0.7.3 */
    .domainIsActive = vboxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = vboxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = vboxDomainIsUpdated, /* 0.8.6 */
8827
#if VBOX_API_VERSION != 2002 && VBOX_API_VERSION != 4000
8828 8829
    .domainEventRegisterAny = vboxDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = vboxDomainEventDeregisterAny, /* 0.8.0 */
8830
#endif
8831 8832 8833 8834 8835 8836 8837 8838 8839
    .domainSnapshotCreateXML = vboxDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = vboxDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = vboxDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = vboxDomainSnapshotListNames, /* 0.8.0 */
    .domainSnapshotLookupByName = vboxDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = vboxDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotCurrent = vboxDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = vboxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = vboxDomainSnapshotDelete, /* 0.8.0 */
8840
};
8841 8842 8843

virNetworkDriver NAME(NetworkDriver) = {
    "VBOX",
8844 8845 8846 8847 8848 8849 8850 8851 8852 8853 8854 8855 8856 8857
    .open                   = vboxNetworkOpen, /* 0.6.4 */
    .close                  = vboxNetworkClose, /* 0.6.4 */
    .numOfNetworks          = vboxNumOfNetworks, /* 0.6.4 */
    .listNetworks           = vboxListNetworks, /* 0.6.4 */
    .numOfDefinedNetworks   = vboxNumOfDefinedNetworks, /* 0.6.4 */
    .listDefinedNetworks    = vboxListDefinedNetworks, /* 0.6.4 */
    .networkLookupByUUID    = vboxNetworkLookupByUUID, /* 0.6.4 */
    .networkLookupByName    = vboxNetworkLookupByName, /* 0.6.4 */
    .networkCreateXML       = vboxNetworkCreateXML, /* 0.6.4 */
    .networkDefineXML       = vboxNetworkDefineXML, /* 0.6.4 */
    .networkUndefine        = vboxNetworkUndefine, /* 0.6.4 */
    .networkCreate          = vboxNetworkCreate, /* 0.6.4 */
    .networkDestroy         = vboxNetworkDestroy, /* 0.6.4 */
    .networkGetXMLDesc      = vboxNetworkGetXMLDesc, /* 0.6.4 */
8858
};
8859 8860 8861

virStorageDriver NAME(StorageDriver) = {
    .name               = "VBOX",
8862 8863 8864 8865 8866 8867 8868 8869 8870 8871 8872 8873 8874 8875 8876 8877
    .open               = vboxStorageOpen, /* 0.7.1 */
    .close              = vboxStorageClose, /* 0.7.1 */
    .numOfPools         = vboxStorageNumOfPools, /* 0.7.1 */
    .listPools          = vboxStorageListPools, /* 0.7.1 */
    .poolLookupByName   = vboxStoragePoolLookupByName, /* 0.7.1 */
    .poolNumOfVolumes   = vboxStoragePoolNumOfVolumes, /* 0.7.1 */
    .poolListVolumes    = vboxStoragePoolListVolumes, /* 0.7.1 */

    .volLookupByName    = vboxStorageVolLookupByName, /* 0.7.1 */
    .volLookupByKey     = vboxStorageVolLookupByKey, /* 0.7.1 */
    .volLookupByPath    = vboxStorageVolLookupByPath, /* 0.7.1 */
    .volCreateXML       = vboxStorageVolCreateXML, /* 0.7.1 */
    .volDelete          = vboxStorageVolDelete, /* 0.7.1 */
    .volGetInfo         = vboxStorageVolGetInfo, /* 0.7.1 */
    .volGetXMLDesc      = vboxStorageVolGetXMLDesc, /* 0.7.1 */
    .volGetPath         = vboxStorageVolGetPath /* 0.7.1 */
8878
};