vbox_tmpl.c 423.9 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-2014 Red Hat, Inc.
12 13 14 15 16
 * 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
17
 * Foundation and shipped in the "COPYING.LESSER" file with this library.
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 * 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>

37
#include <unistd.h>
38 39 40
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
41 42 43 44

#include "internal.h"
#include "datatypes.h"
#include "domain_conf.h"
45
#include "snapshot_conf.h"
46
#include "vbox_snapshot_conf.h"
47
#include "network_conf.h"
48
#include "virerror.h"
49
#include "domain_event.h"
50
#include "storage_conf.h"
51
#include "virstoragefile.h"
52
#include "viruuid.h"
53
#include "viralloc.h"
54
#include "nodeinfo.h"
55
#include "virlog.h"
56
#include "vbox_driver.h"
57
#include "configmake.h"
E
Eric Blake 已提交
58
#include "virfile.h"
59
#include "fdstream.h"
M
Martin Kletzander 已提交
60
#include "viruri.h"
61
#include "virstring.h"
62 63
#include "virtime.h"
#include "virutil.h"
64 65

/* This one changes from version to version. */
66
#if VBOX_API_VERSION == 2002000
67
# include "vbox_CAPI_v2_2.h"
68
#elif VBOX_API_VERSION == 3000000
69
# include "vbox_CAPI_v3_0.h"
70
#elif VBOX_API_VERSION == 3001000
71
# include "vbox_CAPI_v3_1.h"
72
#elif VBOX_API_VERSION == 3002000
73
# include "vbox_CAPI_v3_2.h"
74
#elif VBOX_API_VERSION == 4000000
75
# include "vbox_CAPI_v4_0.h"
76
#elif VBOX_API_VERSION == 4001000
77
# include "vbox_CAPI_v4_1.h"
78
#elif VBOX_API_VERSION == 4002000
79
# include "vbox_CAPI_v4_2.h"
80 81 82
#elif VBOX_API_VERSION == 4002020
# include "vbox_CAPI_v4_2_20.h"
#elif VBOX_API_VERSION == 4003000
R
Ryota Ozaki 已提交
83
# include "vbox_CAPI_v4_3.h"
84 85
#elif VBOX_API_VERSION == 4003004
# include "vbox_CAPI_v4_3_4.h"
86 87
#else
# error "Unsupport VBOX_API_VERSION"
88 89
#endif

90
/* Include this *last* or we'll get the wrong vbox_CAPI_*.h. */
91
#include "vbox_glue.h"
T
Taowei 已提交
92
#include "vbox_uniformed_api.h"
93

94
#define VIR_FROM_THIS                   VIR_FROM_VBOX
95 96 97

VIR_LOG_INIT("vbox.vbox_tmpl");

T
Taowei 已提交
98 99 100
#define vboxUnsupported() \
    VIR_WARN("No %s in current vbox version %d.", __FUNCTION__, VBOX_API_VERSION);

J
John Ferlan 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
#define VBOX_UTF16_FREE(arg)                                            \
    do {                                                                \
        if (arg) {                                                      \
            data->pFuncs->pfnUtf16Free(arg);                            \
            (arg) = NULL;                                               \
        }                                                               \
    } while (0)

#define VBOX_UTF8_FREE(arg)                                             \
    do {                                                                \
        if (arg) {                                                      \
            data->pFuncs->pfnUtf8Free(arg);                             \
            (arg) = NULL;                                               \
        }                                                               \
    } while (0)

#define VBOX_COM_UNALLOC_MEM(arg)                                       \
    do {                                                                \
        if (arg) {                                                      \
            data->pFuncs->pfnComUnallocMem(arg);                        \
            (arg) = NULL;                                               \
        }                                                               \
    } while (0)

125 126 127
#define VBOX_UTF16_TO_UTF8(arg1, arg2)  data->pFuncs->pfnUtf16ToUtf8(arg1, arg2)
#define VBOX_UTF8_TO_UTF16(arg1, arg2)  data->pFuncs->pfnUtf8ToUtf16(arg1, arg2)

128 129
#define VBOX_ADDREF(arg) (arg)->vtbl->nsisupports.AddRef((nsISupports *)(arg))

130 131 132 133 134 135 136
#define VBOX_RELEASE(arg)                                                     \
    do {                                                                      \
        if (arg) {                                                            \
            (arg)->vtbl->nsisupports.Release((nsISupports *)(arg));           \
            (arg) = NULL;                                                     \
        }                                                                     \
    } while (0)
137 138 139 140

#define VBOX_OBJECT_CHECK(conn, type, value) \
vboxGlobalData *data = conn->privateData;\
type ret = value;\
141
if (!data->vboxObj) {\
142 143 144 145 146 147 148
    return ret;\
}

#define VBOX_OBJECT_HOST_CHECK(conn, type, value) \
vboxGlobalData *data = conn->privateData;\
type ret = value;\
IHost *host = NULL;\
149
if (!data->vboxObj) {\
150 151 152 153 154 155 156
    return ret;\
}\
data->vboxObj->vtbl->GetHost(data->vboxObj, &host);\
if (!host) {\
    return ret;\
}

157
#if VBOX_API_VERSION < 3001000
158

159
# define VBOX_MEDIUM_RELEASE(arg) \
160
if (arg)\
161
    (arg)->vtbl->imedium.nsisupports.Release((nsISupports *)(arg))
162
# define VBOX_MEDIUM_FUNC_ARG1(object, func, arg1) \
163
    (object)->vtbl->imedium.func((IMedium *)(object), arg1)
164
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
165 166
    (object)->vtbl->imedium.func((IMedium *)(object), arg1, arg2)

167
#else  /* VBOX_API_VERSION >= 3001000 */
168 169 170

typedef IMedium IHardDisk;
typedef IMediumAttachment IHardDiskAttachment;
171 172 173 174 175
# 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) \
176
    (object)->vtbl->func(object, arg1)
177
# define VBOX_MEDIUM_FUNC_ARG2(object, func, arg1, arg2) \
178 179
    (object)->vtbl->func(object, arg1, arg2)

180
#endif /* VBOX_API_VERSION >= 3001000 */
181

182 183 184 185 186 187
#define DEBUGPRUnichar(msg, strUtf16) \
if (strUtf16) {\
    char *strUtf8 = NULL;\
\
    g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(strUtf16, &strUtf8);\
    if (strUtf8) {\
188
        VIR_DEBUG("%s: %s", msg, strUtf8);\
189 190 191 192 193 194
        g_pVBoxGlobalData->pFuncs->pfnUtf8Free(strUtf8);\
    }\
}

#define DEBUGUUID(msg, iid) \
{\
T
Taowei 已提交
195
    VIR_DEBUG("%s: {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", msg,\
196 197 198 199 200 201 202 203 204 205 206 207 208
          (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]);\
}\

T
Taowei 已提交
209
#if VBOX_API_VERSION > 2002000
210

211 212 213 214 215 216 217 218 219 220
/* 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
 */

221
static vboxGlobalData *g_pVBoxGlobalData = NULL;
222

223
#endif /* !(VBOX_API_VERSION == 2002000) */
224

225
#if VBOX_API_VERSION < 4000000
226 227 228 229 230 231 232 233 234 235 236 237 238

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

239
#else /* VBOX_API_VERSION >= 4000000 */
240 241 242 243 244 245 246 247 248 249 250 251 252

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

253
#endif /* VBOX_API_VERSION >= 4000000 */
254

255 256
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml);
static int vboxDomainCreate(virDomainPtr dom);
257
static int vboxDomainUndefineFlags(virDomainPtr dom, unsigned int flags);
258

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

264 265
static void vboxDriverUnlock(vboxGlobalData *data)
{
266 267 268
    virMutexUnlock(&data->lock);
}

269
#if VBOX_API_VERSION == 2002000
270

271 272
static void nsIDtoChar(unsigned char *uuid, const nsID *iid)
{
273 274 275
    char uuidstrsrc[VIR_UUID_STRING_BUFLEN];
    char uuidstrdst[VIR_UUID_STRING_BUFLEN];
    unsigned char uuidinterim[VIR_UUID_BUFLEN];
276
    size_t i;
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

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

304
    for (i = 18; i < VIR_UUID_STRING_BUFLEN; i++) {
305 306 307 308
        uuidstrdst[i] = uuidstrsrc[i];
    }

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

312 313
static void nsIDFromChar(nsID *iid, const unsigned char *uuid)
{
314 315 316
    char uuidstrsrc[VIR_UUID_STRING_BUFLEN];
    char uuidstrdst[VIR_UUID_STRING_BUFLEN];
    unsigned char uuidinterim[VIR_UUID_BUFLEN];
317
    size_t i;
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

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

344
    for (i = 18; i < VIR_UUID_STRING_BUFLEN; i++) {
345 346 347 348
        uuidstrdst[i] = uuidstrsrc[i];
    }

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

353
# ifdef WIN32
354

355 356 357 358
typedef struct _vboxIID_v2_x_WIN32 vboxIID;
typedef struct _vboxIID_v2_x_WIN32 vboxIID_v2_x_WIN32;

#  define VBOX_IID_INITIALIZER { { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } } }
T
Taowei 已提交
359
#  define IID_MEMBER(name) (iidu->vboxIID_v2_x_WIN32.name)
360 361 362 363 364 365

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

T
Taowei 已提交
368 369 370 371 372 373 374
static void
_vboxIIDUnalloc(vboxGlobalData *data ATTRIBUTE_UNUSED,
                vboxIIDUnion *iid ATTRIBUTE_UNUSED)
{
    /* Nothing to free */
}

375 376 377 378 379
static void
vboxIIDToUUID_v2_x_WIN32(vboxIID_v2_x_WIN32 *iid, unsigned char *uuid)
{
    nsIDtoChar(uuid, (nsID *)&iid->value);
}
380

T
Taowei 已提交
381 382 383 384 385 386
static void
_vboxIIDToUUID(vboxGlobalData *data ATTRIBUTE_UNUSED, vboxIIDUnion *iidu, unsigned char *uuid)
{
    vboxIIDToUUID_v2_x_WIN32(&iidu->vboxIID_v2_x_WIN32, uuid);
}

387 388 389 390 391
static void
vboxIIDFromUUID_v2_x_WIN32(vboxGlobalData *data, vboxIID_v2_x_WIN32 *iid,
                           const unsigned char *uuid)
{
    vboxIIDUnalloc_v2_x_WIN32(data, iid);
392

393
    nsIDFromChar((nsID *)&iid->value, uuid);
394 395
}

T
Taowei 已提交
396 397 398 399 400 401 402
static void
_vboxIIDFromUUID(vboxGlobalData *data, vboxIIDUnion *iidu,
                 const unsigned char *uuid)
{
    vboxIIDFromUUID_v2_x_WIN32(data, &iidu->vboxIID_v2_x_WIN32, uuid);
}

403 404 405
static bool
vboxIIDIsEqual_v2_x_WIN32(vboxIID_v2_x_WIN32 *iid1, vboxIID_v2_x_WIN32 *iid2)
{
406
    return memcmp(&iid1->value, &iid2->value, sizeof(GUID)) == 0;
407
}
408

T
Taowei 已提交
409 410 411 412 413 414
static bool
_vboxIIDIsEqual(vboxGlobalData *data ATTRIBUTE_UNUSED, vboxIIDUnion *iidu1, vboxIIDUnion *iidu2)
{
    return vboxIIDIsEqual_v2_x_WIN32(&iidu1->vboxIID_v2_x_WIN32, &iidu2->vboxIID_v2_x_WIN32);
}

415 416 417 418 419 420 421 422
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);

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

T
Taowei 已提交
426 427 428 429 430 431 432
static void
_vboxIIDFromArrayItem(vboxGlobalData *data, vboxIIDUnion *iidu,
                      vboxArray *array, int idx)
{
    vboxIIDFromArrayItem_v2_x_WIN32(data, &iidu->vboxIID_v2_x_WIN32, array, idx);
}

433 434 435 436 437 438 439 440 441 442 443 444 445 446
#  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;

#  define VBOX_IID_INITIALIZER { NULL, { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } } }
T
Taowei 已提交
447
#  define IID_MEMBER(name) (iidu->vboxIID_v2_x.name)
448 449 450 451 452

static void
vboxIIDUnalloc_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid)
{
    if (iid->value == NULL) {
453 454 455
        return;
    }

456 457 458 459 460 461 462
    if (iid->value != &iid->backing) {
        data->pFuncs->pfnComUnallocMem(iid->value);
    }

    iid->value = NULL;
}

T
Taowei 已提交
463 464 465 466 467 468
static void
_vboxIIDUnalloc(vboxGlobalData *data, vboxIIDUnion *iidu)
{
    vboxIIDUnalloc_v2_x(data, &iidu->vboxIID_v2_x);
}

469 470 471 472 473 474
static void
vboxIIDToUUID_v2_x(vboxIID_v2_x *iid, unsigned char *uuid)
{
    nsIDtoChar(uuid, iid->value);
}

T
Taowei 已提交
475 476 477 478 479 480 481
static void
_vboxIIDToUUID(vboxGlobalData *data ATTRIBUTE_UNUSED,
               vboxIIDUnion *iidu, unsigned char *uuid)
{
    vboxIIDToUUID_v2_x(&iidu->vboxIID_v2_x, uuid);
}

482 483 484 485 486 487 488 489
static void
vboxIIDFromUUID_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid,
                     const unsigned char *uuid)
{
    vboxIIDUnalloc_v2_x(data, iid);

    iid->value = &iid->backing;

490
    sa_assert(iid->value);
491
    nsIDFromChar(iid->value, uuid);
492 493
}

T
Taowei 已提交
494 495 496 497 498 499 500
static void
_vboxIIDFromUUID(vboxGlobalData *data, vboxIIDUnion *iidu,
                 const unsigned char *uuid)
{
    vboxIIDFromUUID_v2_x(data, &iidu->vboxIID_v2_x, uuid);
}

501 502 503
static bool
vboxIIDIsEqual_v2_x(vboxIID_v2_x *iid1, vboxIID_v2_x *iid2)
{
504
    return memcmp(iid1->value, iid2->value, sizeof(nsID)) == 0;
505 506
}

T
Taowei 已提交
507 508 509 510 511 512 513
static bool
_vboxIIDIsEqual(vboxGlobalData *data ATTRIBUTE_UNUSED,
                vboxIIDUnion *iidu1, vboxIIDUnion *iidu2)
{
    return vboxIIDIsEqual_v2_x(&iidu1->vboxIID_v2_x, &iidu2->vboxIID_v2_x);
}

514 515 516 517 518 519 520 521
static void
vboxIIDFromArrayItem_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid,
                          vboxArray *array, int idx)
{
    vboxIIDUnalloc_v2_x(data, iid);

    iid->value = &iid->backing;

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

T
Taowei 已提交
525 526 527 528 529 530 531
static void
_vboxIIDFromArrayItem(vboxGlobalData *data, vboxIIDUnion *iidu,
                      vboxArray *array, int idx)
{
    vboxIIDFromArrayItem_v2_x(data, &iidu->vboxIID_v2_x, array, idx);
}

532 533 534 535 536 537 538 539 540 541
#  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 */

542
#else /* VBOX_API_VERSION != 2002000 */
543

544 545 546 547
typedef struct _vboxIID_v3_x vboxIID;
typedef struct _vboxIID_v3_x vboxIID_v3_x;

# define VBOX_IID_INITIALIZER { NULL, true }
T
Taowei 已提交
548
# define IID_MEMBER(name) (iidu->vboxIID_v3_x.name)
549 550 551 552 553 554 555 556 557 558

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

T
Taowei 已提交
561 562 563 564 565 566
static void
_vboxIIDUnalloc(vboxGlobalData *data, vboxIIDUnion *iidu)
{
    vboxIIDUnalloc_v3_x(data, &iidu->vboxIID_v3_x);
}

567 568 569 570 571 572 573 574
static void
vboxIIDToUUID_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                   unsigned char *uuid)
{
    char *utf8 = NULL;

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

575
    ignore_value(virUUIDParse(utf8, uuid));
576 577

    data->pFuncs->pfnUtf8Free(utf8);
578 579
}

T
Taowei 已提交
580 581 582 583 584 585 586
static void
_vboxIIDToUUID(vboxGlobalData *data, vboxIIDUnion *iidu,
               unsigned char *uuid)
{
    vboxIIDToUUID_v3_x(data, &iidu->vboxIID_v3_x, uuid);
}

587 588 589 590 591
static void
vboxIIDFromUUID_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                     const unsigned char *uuid)
{
    char utf8[VIR_UUID_STRING_BUFLEN];
592

593
    vboxIIDUnalloc_v3_x(data, iid);
594

595
    virUUIDFormat(uuid, utf8);
596

597 598
    data->pFuncs->pfnUtf8ToUtf16(utf8, &iid->value);
}
599

T
Taowei 已提交
600 601 602 603 604 605 606
static void
_vboxIIDFromUUID(vboxGlobalData *data, vboxIIDUnion *iidu,
                 const unsigned char *uuid)
{
    vboxIIDFromUUID_v3_x(data, &iidu->vboxIID_v3_x, uuid);
}

607 608 609 610 611 612
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];
613 614

    /* Note: we can't directly compare the utf8 strings here
E
Eric Blake 已提交
615
     * cause the two UUID's may have separators as space or '-'
616 617
     * or mixture of both and we don't want to fail here by
     * using direct string comparison. Here virUUIDParse() takes
618 619 620
     * care of these cases. */
    vboxIIDToUUID_v3_x(data, iid1, uuid1);
    vboxIIDToUUID_v3_x(data, iid2, uuid2);
621

622 623
    return memcmp(uuid1, uuid2, VIR_UUID_BUFLEN) == 0;
}
624

T
Taowei 已提交
625 626 627 628 629 630
static bool
_vboxIIDIsEqual(vboxGlobalData *data, vboxIIDUnion *iidu1,
                vboxIIDUnion *iidu2)
{
    return vboxIIDIsEqual_v3_x(data, &iidu1->vboxIID_v3_x, &iidu2->vboxIID_v3_x);
}
631

632 633 634 635 636
static void
vboxIIDFromArrayItem_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                          vboxArray *array, int idx)
{
    vboxIIDUnalloc_v3_x(data, iid);
637

638 639
    iid->value = array->items[idx];
    iid->owner = false;
640 641
}

T
Taowei 已提交
642 643 644 645 646 647 648
static void
_vboxIIDFromArrayItem(vboxGlobalData *data, vboxIIDUnion *iidu,
                      vboxArray *array, int idx)
{
    vboxIIDFromArrayItem_v3_x(data, &iidu->vboxIID_v3_x, array, idx);
}

649 650 651 652 653 654 655 656

# 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)
657

658
# if VBOX_API_VERSION >= 3001000
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674

/**
 * 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
 *
 */
675
static char *vboxGenerateMediumName(PRUint32  storageBus,
676 677 678 679
                                    PRInt32   deviceInst,
                                    PRInt32   devicePort,
                                    PRInt32   deviceSlot,
                                    PRUint32 *aMaxPortPerInst,
680 681
                                    PRUint32 *aMaxSlotPerPort)
{
682
    const char *prefix = NULL;
683 684 685 686 687
    char *name  = NULL;
    int   total = 0;
    PRUint32 maxPortPerInst = 0;
    PRUint32 maxSlotPerPort = 0;

688 689
    if (!aMaxPortPerInst ||
        !aMaxSlotPerPort)
690 691
        return NULL;

692 693
    if ((storageBus < StorageBus_IDE) ||
        (storageBus > StorageBus_Floppy))
694 695 696 697 698 699 700 701 702
        return NULL;

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

    if (storageBus == StorageBus_IDE) {
703
        prefix = "hd";
704 705
    } else if ((storageBus == StorageBus_SATA) ||
               (storageBus == StorageBus_SCSI)) {
706
        prefix = "sd";
707
    } else if (storageBus == StorageBus_Floppy) {
708
        prefix = "fd";
709 710
    }

711
    name = virIndexToDiskName(total, prefix);
712

713
    VIR_DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
714
          "devicePort=%d deviceSlot=%d, maxPortPerInst=%u maxSlotPerPort=%u",
715
          NULLSTR(name), total, storageBus, deviceInst, devicePort,
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
          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;

747 748 749 750 751 752
    if (!deviceName ||
        !deviceInst ||
        !devicePort ||
        !deviceSlot ||
        !aMaxPortPerInst ||
        !aMaxSlotPerPort)
753 754
        return false;

755 756
    if ((storageBus < StorageBus_IDE) ||
        (storageBus > StorageBus_Floppy))
757 758 759 760 761 762 763
        return false;

    total = virDiskNameToIndex(deviceName);

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

764 765 766
    if (!maxPortPerInst ||
        !maxSlotPerPort ||
        (total < 0))
767 768 769 770 771 772
        return false;

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

773
    VIR_DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
          "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,
794 795
                                     PRUint32 *maxSlotPerPort)
{
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    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
 */
840 841
static int PRUnicharToInt(PRUnichar *strUtf16)
{
842 843 844 845 846 847 848 849 850 851
    char *strUtf8 = NULL;
    int ret = 0;

    if (!strUtf16)
        return -1;

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

852 853 854
    if (virStrToLong_i(strUtf8, NULL, 10, &ret) < 0)
        ret = -1;

855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
    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;
}

874
# endif /* VBOX_API_VERSION >= 3001000 */
875

876
#endif /* !(VBOX_API_VERSION == 2002000) */
877

878 879 880 881 882 883
static PRUnichar *
vboxSocketFormatAddrUtf16(vboxGlobalData *data, virSocketAddrPtr addr)
{
    char *utf8 = NULL;
    PRUnichar *utf16 = NULL;

884
    utf8 = virSocketAddrFormat(addr);
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904

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

905
    if (virSocketAddrParse(addr, utf8, AF_UNSPEC) < 0) {
906 907 908 909 910
        goto cleanup;
    }

    result = 0;

911
 cleanup:
912 913 914 915 916
    VBOX_UTF8_FREE(utf8);

    return result;
}

917 918 919 920 921 922
static char *vboxConnectGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return virGetHostname();
}


923 924
static int vboxConnectIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
925 926 927 928
    /* Driver is using local, non-network based transport */
    return 1;
}

929 930
static int vboxConnectIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
931 932 933 934
    /* No encryption is needed, or used on the local transport*/
    return 0;
}

935
static int vboxConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
936 937 938 939
{
    return 1;
}

940 941 942
static int
vboxConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
{
943
    VBOX_OBJECT_CHECK(conn, int, -1);
944 945 946 947 948
    PRUint32 maxCPUCount = 0;

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

951 952 953 954
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
955 956 957 958 959 960 961 962 963
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}


964
static char *vboxConnectGetCapabilities(virConnectPtr conn) {
965
    VBOX_OBJECT_CHECK(conn, char *, NULL);
966 967 968 969 970 971 972 973

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

    return ret;
}

974 975
static int vboxConnectListDomains(virConnectPtr conn, int *ids, int nids)
{
976
    VBOX_OBJECT_CHECK(conn, int, -1);
977
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
978
    PRUint32 state;
979
    nsresult rc;
980
    size_t i, j;
981

982
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
983
    if (NS_FAILED(rc)) {
984
        virReportError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
985 986
                       _("Could not get list of Domains, rc=%08x"),
                       (unsigned)rc);
987 988
        goto cleanup;
    }
989

990 991 992
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < nids); ++i) {
        IMachine *machine = machines.items[i];
993 994 995 996 997 998

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
999 1000
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline)) {
1001 1002
                    ret++;
                    ids[j++] = i + 1;
1003 1004 1005 1006 1007
                }
            }
        }
    }

1008
 cleanup:
1009
    vboxArrayRelease(&machines);
1010 1011 1012
    return ret;
}

1013 1014
static int vboxConnectNumOfDomains(virConnectPtr conn)
{
1015
    VBOX_OBJECT_CHECK(conn, int, -1);
1016
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1017
    PRUint32 state;
1018
    nsresult rc;
1019
    size_t i;
1020

1021
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1022
    if (NS_FAILED(rc)) {
1023 1024
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get number of Domains, rc=%08x"), (unsigned)rc);
1025 1026
        goto cleanup;
    }
1027

1028 1029 1030
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1031 1032 1033 1034 1035 1036

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
1037 1038
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1039
                    ret++;
1040 1041 1042 1043
            }
        }
    }

1044
 cleanup:
1045
    vboxArrayRelease(&machines);
1046 1047 1048 1049
    return ret;
}

static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
1050 1051
                                        unsigned int flags)
{
1052 1053 1054 1055 1056 1057 1058 1059
    /* 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.
     */

1060 1061 1062 1063 1064
    virDomainPtr dom;

    virCheckFlags(0, NULL);

    dom = vboxDomainDefineXML(conn, xml);
1065 1066 1067 1068
    if (dom == NULL)
        return NULL;

    if (vboxDomainCreate(dom) < 0) {
1069
        vboxDomainUndefineFlags(dom, 0);
1070
        virObjectUnref(dom);
1071
        return NULL;
1072 1073 1074 1075 1076
    }

    return dom;
}

1077 1078
static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id)
{
1079
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1080
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1081 1082
    vboxIID iid = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
1083
    PRUint32 state;
1084
    nsresult rc;
1085

1086
    /* Internal vbox IDs start from 0, the public libvirt ID
1087
     * starts from 1, so refuse id == 0, and adjust the rest*/
1088
    if (id == 0) {
1089 1090
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), id);
1091 1092 1093 1094
        return NULL;
    }
    id = id - 1;

1095
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1096
    if (NS_FAILED(rc)) {
1097 1098
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1099 1100
        return NULL;
    }
1101

1102 1103 1104 1105
    if (id < machines.count) {
        IMachine *machine = machines.items[id];

        if (machine) {
1106
            PRBool isAccessible = PR_FALSE;
1107
            machine->vtbl->GetAccessible(machine, &isAccessible);
1108
            if (isAccessible) {
1109
                machine->vtbl->GetState(machine, &state);
1110 1111
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline)) {
1112 1113
                    PRUnichar *machineNameUtf16 = NULL;
                    char      *machineNameUtf8  = NULL;
1114

1115
                    machine->vtbl->GetName(machine, &machineNameUtf16);
1116
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1117

1118 1119 1120
                    machine->vtbl->GetId(machine, &iid.value);
                    vboxIIDToUUID(&iid, uuid);
                    vboxIIDUnalloc(&iid);
1121 1122 1123 1124 1125 1126 1127

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

1128
                    ret = virGetDomain(conn, machineNameUtf8, uuid);
1129 1130 1131 1132 1133 1134
                    if (ret)
                        ret->id = id + 1;

                    /* Cleanup all the XPCOM allocated stuff here */
                    VBOX_UTF8_FREE(machineNameUtf8);
                    VBOX_UTF16_FREE(machineNameUtf16);
1135 1136 1137 1138 1139
                }
            }
        }
    }

1140
    vboxArrayRelease(&machines);
1141 1142

    return ret;
1143 1144
}

1145 1146 1147
static virDomainPtr
vboxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
1148
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1149
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1150
    vboxIID iid = VBOX_IID_INITIALIZER;
1151
    char      *machineNameUtf8  = NULL;
1152
    PRUnichar *machineNameUtf16 = NULL;
1153
    unsigned char iid_as_uuid[VIR_UUID_BUFLEN];
1154 1155
    size_t i;
    int matched = 0;
1156
    nsresult rc;
1157

1158
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1159
    if (NS_FAILED(rc)) {
1160 1161
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1162 1163
        return NULL;
    }
1164

1165 1166
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1167
        PRBool isAccessible = PR_FALSE;
1168

1169 1170
        if (!machine)
            continue;
1171

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

1175 1176
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
1177
                continue;
1178 1179
            vboxIIDToUUID(&iid, iid_as_uuid);
            vboxIIDUnalloc(&iid);
1180

1181
            if (memcmp(uuid, iid_as_uuid, VIR_UUID_BUFLEN) == 0) {
1182

1183
                PRUint32 state;
1184

1185
                matched = 1;
1186

1187 1188
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1189

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

1192 1193 1194 1195 1196
                /* 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.
                 */
1197

1198
                ret = virGetDomain(conn, machineNameUtf8, iid_as_uuid);
1199 1200 1201
                if (ret &&
                    (state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1202
                    ret->id = i + 1;
1203 1204
            }

1205 1206
            if (matched == 1)
                break;
1207 1208 1209
        }
    }

1210 1211 1212
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1213
    vboxArrayRelease(&machines);
1214 1215

    return ret;
1216 1217
}

1218 1219 1220
static virDomainPtr
vboxDomainLookupByName(virConnectPtr conn, const char *name)
{
1221
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1222
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1223
    vboxIID iid = VBOX_IID_INITIALIZER;
1224
    char      *machineNameUtf8  = NULL;
1225
    PRUnichar *machineNameUtf16 = NULL;
1226
    unsigned char uuid[VIR_UUID_BUFLEN];
1227 1228
    size_t i;
    int matched = 0;
1229
    nsresult rc;
1230

1231
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1232
    if (NS_FAILED(rc)) {
1233 1234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1235 1236
        return NULL;
    }
1237

1238 1239
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1240
        PRBool isAccessible = PR_FALSE;
1241

1242 1243
        if (!machine)
            continue;
1244

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

1248 1249
            machine->vtbl->GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1250

1251
            if (STREQ(name, machineNameUtf8)) {
1252

1253
                PRUint32 state;
1254

1255
                matched = 1;
1256

1257 1258 1259
                machine->vtbl->GetId(machine, &iid.value);
                vboxIIDToUUID(&iid, uuid);
                vboxIIDUnalloc(&iid);
1260

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

1263 1264 1265 1266 1267
                /* 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.
                 */
1268

1269
                ret = virGetDomain(conn, machineNameUtf8, uuid);
1270 1271 1272
                if (ret &&
                    (state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1273
                    ret->id = i + 1;
1274 1275
            }

J
John Ferlan 已提交
1276 1277
            VBOX_UTF8_FREE(machineNameUtf8);
            VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1278 1279
            if (matched == 1)
                break;
1280 1281 1282
        }
    }

1283
    vboxArrayRelease(&machines);
1284 1285

    return ret;
1286 1287
}

1288

1289 1290
static int vboxDomainIsActive(virDomainPtr dom)
{
1291
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1292
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1293
    vboxIID iid = VBOX_IID_INITIALIZER;
1294 1295
    char      *machineNameUtf8  = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1296
    unsigned char uuid[VIR_UUID_BUFLEN];
1297 1298
    size_t i;
    int matched = 0;
1299
    nsresult rc;
1300

1301
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1302
    if (NS_FAILED(rc)) {
1303 1304
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1305 1306
        return ret;
    }
1307

1308 1309
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1310 1311 1312 1313 1314 1315 1316
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

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

1318 1319
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
1320
                continue;
1321 1322
            vboxIIDToUUID(&iid, uuid);
            vboxIIDUnalloc(&iid);
1323

1324
            if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {
1325

1326
                PRUint32 state;
1327

1328
                matched = 1;
1329

1330 1331
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1332

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

1335 1336
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1337 1338 1339
                    ret = 1;
                else
                    ret = 0;
1340 1341
            }

1342 1343
            if (matched == 1)
                break;
1344 1345 1346
        }
    }

1347 1348 1349
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1350
    vboxArrayRelease(&machines);
1351

1352 1353 1354 1355
    return ret;
}


1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
static int vboxDomainIsPersistent(virDomainPtr dom ATTRIBUTE_UNUSED)
{
    /* All domains are persistent.  However, we do want to check for
     * existence. */
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID iid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    nsresult rc;

    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
1368 1369
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
1370 1371 1372 1373 1374
        goto cleanup;
    }

    ret = 1;

1375
 cleanup:
1376 1377 1378
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
1379 1380 1381
}


1382 1383
static int vboxDomainIsUpdated(virDomainPtr dom ATTRIBUTE_UNUSED)
{
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
    /* VBox domains never have a persistent state that differs from
     * current state.  However, we do want to check for existence.  */
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID iid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    nsresult rc;

    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
1394 1395
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
1396 1397 1398 1399 1400
        goto cleanup;
    }

    ret = 0;

1401
 cleanup:
1402 1403 1404
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
1405 1406
}

1407 1408
static int vboxDomainSuspend(virDomainPtr dom)
{
1409
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1410
    IMachine *machine    = NULL;
1411
    vboxIID iid = VBOX_IID_INITIALIZER;
1412
    IConsole *console    = NULL;
1413
    PRBool isAccessible  = PR_FALSE;
1414
    PRUint32 state;
1415
    nsresult rc;
1416

1417
    vboxIIDFromUUID(&iid, dom->uuid);
1418
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1419
    if (NS_FAILED(rc)) {
1420 1421
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1422 1423
        goto cleanup;
    }
1424

1425 1426
    if (!machine)
        goto cleanup;
1427

1428 1429 1430
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1431

1432
        if (state == MachineState_Running) {
1433 1434
            /* set state pause */
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1435 1436 1437 1438 1439
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Pause(console);
                VBOX_RELEASE(console);
                ret = 0;
1440
            } else {
1441 1442
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("error while suspending the domain"));
1443 1444
                goto cleanup;
            }
1445
            VBOX_SESSION_CLOSE();
1446
        } else {
1447 1448
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine not in running state to suspend it"));
1449
            goto cleanup;
1450 1451 1452
        }
    }

1453
 cleanup:
1454
    VBOX_RELEASE(machine);
1455
    vboxIIDUnalloc(&iid);
1456 1457 1458
    return ret;
}

1459 1460
static int vboxDomainResume(virDomainPtr dom)
{
1461
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1462
    IMachine *machine    = NULL;
1463
    vboxIID iid = VBOX_IID_INITIALIZER;
1464 1465
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1466
    nsresult rc;
1467

1468
    PRBool isAccessible = PR_FALSE;
1469

1470
    vboxIIDFromUUID(&iid, dom->uuid);
1471
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1472
    if (NS_FAILED(rc)) {
1473 1474
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1475 1476
        goto cleanup;
    }
1477

1478 1479
    if (!machine)
        goto cleanup;
1480

1481 1482 1483 1484 1485
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);

        if (state == MachineState_Paused) {
1486 1487
            /* resume the machine here */
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1488 1489 1490 1491 1492
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Resume(console);
                VBOX_RELEASE(console);
                ret = 0;
1493
            } else {
1494 1495
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("error while resuming the domain"));
1496 1497
                goto cleanup;
            }
1498
            VBOX_SESSION_CLOSE();
1499
        } else {
1500 1501
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine not paused, so can't resume it"));
1502
            goto cleanup;
1503 1504 1505
        }
    }

1506
 cleanup:
1507
    VBOX_RELEASE(machine);
1508
    vboxIIDUnalloc(&iid);
1509 1510 1511
    return ret;
}

1512
static int vboxDomainShutdownFlags(virDomainPtr dom,
1513 1514
                                   unsigned int flags)
{
1515
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1516
    IMachine *machine    = NULL;
1517
    vboxIID iid = VBOX_IID_INITIALIZER;
1518 1519
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1520 1521
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1522

1523 1524
    virCheckFlags(0, -1);

1525
    vboxIIDFromUUID(&iid, dom->uuid);
1526
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1527
    if (NS_FAILED(rc)) {
1528 1529
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1530 1531
        goto cleanup;
    }
1532

1533 1534
    if (!machine)
        goto cleanup;
1535

1536 1537 1538
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1539

1540
        if (state == MachineState_Paused) {
1541 1542
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine paused, so can't power it down"));
1543 1544
            goto cleanup;
        } else if (state == MachineState_PoweredOff) {
1545 1546
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine already powered down"));
1547 1548
            goto cleanup;
        }
1549

1550
        VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1551 1552 1553 1554 1555
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
            console->vtbl->PowerButton(console);
            VBOX_RELEASE(console);
            ret = 0;
1556
        }
1557
        VBOX_SESSION_CLOSE();
1558 1559
    }

1560
 cleanup:
1561
    VBOX_RELEASE(machine);
1562
    vboxIIDUnalloc(&iid);
1563 1564 1565
    return ret;
}

1566 1567
static int vboxDomainShutdown(virDomainPtr dom)
{
1568 1569 1570 1571
    return vboxDomainShutdownFlags(dom, 0);
}


E
Eric Blake 已提交
1572 1573
static int vboxDomainReboot(virDomainPtr dom, unsigned int flags)
{
1574
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1575
    IMachine *machine    = NULL;
1576
    vboxIID iid = VBOX_IID_INITIALIZER;
1577 1578
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1579 1580
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1581

E
Eric Blake 已提交
1582 1583
    virCheckFlags(0, -1);

1584
    vboxIIDFromUUID(&iid, dom->uuid);
1585
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1586
    if (NS_FAILED(rc)) {
1587 1588
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1589 1590
        goto cleanup;
    }
1591

1592 1593
    if (!machine)
        goto cleanup;
1594

1595 1596 1597
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1598

1599
        if (state == MachineState_Running) {
1600
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1601 1602 1603 1604 1605
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Reset(console);
                VBOX_RELEASE(console);
                ret = 0;
1606
            }
1607
            VBOX_SESSION_CLOSE();
1608
        } else {
1609 1610
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine not running, so can't reboot it"));
1611
            goto cleanup;
1612 1613 1614
        }
    }

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

1621 1622 1623 1624
static int
vboxDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1625
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1626
    IMachine *machine    = NULL;
1627
    vboxIID iid = VBOX_IID_INITIALIZER;
1628 1629
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1630 1631
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1632

1633 1634
    virCheckFlags(0, -1);

1635
    vboxIIDFromUUID(&iid, dom->uuid);
1636
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1637
    if (NS_FAILED(rc)) {
1638 1639
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1640 1641
        goto cleanup;
    }
1642

1643 1644
    if (!machine)
        goto cleanup;
1645

1646 1647 1648
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1649

1650
        if (state == MachineState_PoweredOff) {
1651 1652
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine already powered down"));
1653 1654
            goto cleanup;
        }
1655

1656
        VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1657 1658
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
1659

1660
#if VBOX_API_VERSION == 2002000
1661
            console->vtbl->PowerDown(console);
1662
#else
1663
            IProgress *progress = NULL;
1664 1665 1666 1667
            console->vtbl->PowerDown(console, &progress);
            if (progress) {
                progress->vtbl->WaitForCompletion(progress, -1);
                VBOX_RELEASE(progress);
1668
            }
1669 1670
#endif
            VBOX_RELEASE(console);
1671
            dom->id = -1;
1672
            ret = 0;
1673
        }
1674
        VBOX_SESSION_CLOSE();
1675 1676
    }

1677
 cleanup:
1678
    VBOX_RELEASE(machine);
1679
    vboxIIDUnalloc(&iid);
1680 1681 1682
    return ret;
}

1683 1684 1685 1686 1687 1688
static int
vboxDomainDestroy(virDomainPtr dom)
{
    return vboxDomainDestroyFlags(dom, 0);
}

1689
static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
1690 1691 1692 1693 1694
    /* 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 ;)
     */
1695
    char *osType;
1696

1697
    ignore_value(VIR_STRDUP(osType, "hvm"));
1698
    return osType;
1699 1700
}

1701 1702
static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory)
{
1703
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1704
    IMachine *machine    = NULL;
1705
    vboxIID iid = VBOX_IID_INITIALIZER;
1706
    PRUint32 state       = MachineState_Null;
1707 1708
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1709

1710
    vboxIIDFromUUID(&iid, dom->uuid);
1711
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1712
    if (NS_FAILED(rc)) {
1713 1714
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1715 1716
        goto cleanup;
    }
1717

1718 1719
    if (!machine)
        goto cleanup;
1720

1721 1722 1723
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1724

1725
        if (state != MachineState_PoweredOff) {
1726 1727
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("memory size can't be changed unless domain is powered down"));
1728 1729
            goto cleanup;
        }
1730

1731
        rc = VBOX_SESSION_OPEN(iid.value, machine);
1732 1733 1734
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
1735

1736 1737
                rc = machine->vtbl->SetMemorySize(machine,
                                                  VIR_DIV_UP(memory, 1024));
1738 1739 1740 1741
                if (NS_SUCCEEDED(rc)) {
                    machine->vtbl->SaveSettings(machine);
                    ret = 0;
                } else {
1742 1743 1744 1745
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("could not set the memory size of the "
                                     "domain to: %lu Kb, rc=%08x"),
                                   memory, (unsigned)rc);
1746 1747
                }
            }
1748
            VBOX_SESSION_CLOSE();
1749 1750 1751
        }
    }

1752
 cleanup:
1753
    VBOX_RELEASE(machine);
1754
    vboxIIDUnalloc(&iid);
1755 1756 1757
    return ret;
}

1758 1759
static virDomainState vboxConvertState(enum MachineState state)
{
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    switch (state) {
        case MachineState_Running:
            return VIR_DOMAIN_RUNNING;
        case MachineState_Stuck:
            return VIR_DOMAIN_BLOCKED;
        case MachineState_Paused:
            return VIR_DOMAIN_PAUSED;
        case MachineState_Stopping:
            return VIR_DOMAIN_SHUTDOWN;
        case MachineState_PoweredOff:
R
Ryota Ozaki 已提交
1770
        case MachineState_Saved:
1771 1772 1773 1774 1775 1776 1777 1778 1779
            return VIR_DOMAIN_SHUTOFF;
        case MachineState_Aborted:
            return VIR_DOMAIN_CRASHED;
        case MachineState_Null:
        default:
            return VIR_DOMAIN_NOSTATE;
    }
}

1780 1781
static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
1782
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1783
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1784 1785
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1786
    nsresult rc;
1787
    size_t i = 0;
1788

1789
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1790
    if (NS_FAILED(rc)) {
1791 1792
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1793 1794
        goto cleanup;
    }
1795

1796
    info->nrVirtCpu = 0;
1797 1798
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1799
        PRBool isAccessible = PR_FALSE;
1800

1801 1802
        if (!machine)
            continue;
1803

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

1807 1808 1809 1810 1811 1812
            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
1813
                * for time being set max_balloon and cur_balloon to same
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
                * 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;
                }
1831 1832


1833 1834 1835 1836 1837 1838
                machine->vtbl->GetCPUCount(machine, &CPUCount);
                machine->vtbl->GetMemorySize(machine, &memorySize);
                machine->vtbl->GetState(machine, &state);

                info->cpuTime = 0;
                info->nrVirtCpu = CPUCount;
1839 1840
                info->memory = memorySize * 1024;
                info->maxMem = maxMemorySize * 1024;
1841
                info->state = vboxConvertState(state);
1842

1843
                ret = 0;
1844 1845
            }

J
John Ferlan 已提交
1846 1847
            VBOX_UTF8_FREE(machineName);
            VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1848 1849
            if (info->nrVirtCpu)
                break;
1850 1851 1852 1853
        }

    }

1854
    vboxArrayRelease(&machines);
1855

1856
 cleanup:
1857 1858 1859
    return ret;
}

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
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)) {
1877 1878
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
1879 1880 1881 1882 1883
        goto cleanup;
    }

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

1884
    *state = vboxConvertState(mstate);
1885 1886 1887 1888 1889 1890

    if (reason)
        *reason = 0;

    ret = 0;

1891
 cleanup:
1892 1893 1894 1895
    vboxIIDUnalloc(&domiid);
    return ret;
}

1896 1897 1898 1899
static int
vboxDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
{
1900
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1901
    IMachine *machine    = NULL;
1902
    vboxIID iid = VBOX_IID_INITIALIZER;
1903
    PRUint32  CPUCount   = nvcpus;
1904
    nsresult rc;
1905

1906
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
1907
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
1908 1909 1910
        return -1;
    }

1911
    vboxIIDFromUUID(&iid, dom->uuid);
1912
#if VBOX_API_VERSION >= 4000000
1913 1914 1915
    /* Get machine for the call to VBOX_SESSION_OPEN */
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
1916 1917
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
1918 1919 1920 1921 1922
        return -1;
    }
#endif

    rc = VBOX_SESSION_OPEN(iid.value, machine);
1923 1924 1925 1926 1927 1928 1929
    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;
1930
            } else {
1931 1932 1933 1934
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not set the number of cpus of the domain "
                                 "to: %u, rc=%08x"),
                               CPUCount, (unsigned)rc);
1935
            }
1936
            VBOX_RELEASE(machine);
1937
        } else {
1938 1939
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("no domain with matching id %d"), dom->id);
1940
        }
1941
    } else {
1942 1943
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("can't open session to the domain with id %d"), dom->id);
1944
    }
1945
    VBOX_SESSION_CLOSE();
1946

1947
    vboxIIDUnalloc(&iid);
1948 1949 1950
    return ret;
}

1951 1952 1953
static int
vboxDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
1954
    return vboxDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
1955 1956 1957 1958 1959
}

static int
vboxDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
1960 1961
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    ISystemProperties *systemProperties = NULL;
1962 1963
    PRUint32 maxCPUCount = 0;

1964
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
1965
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
1966 1967 1968
        return -1;
    }

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

1974 1975 1976 1977
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
1978 1979 1980 1981 1982 1983 1984 1985
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}

1986 1987 1988
static int
vboxDomainGetMaxVcpus(virDomainPtr dom)
{
1989
    return vboxDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
1990 1991 1992
                                         VIR_DOMAIN_VCPU_MAXIMUM));
}

1993 1994
static void vboxHostDeviceGetXMLDesc(vboxGlobalData *data, virDomainDefPtr def, IMachine *machine)
{
1995
#if VBOX_API_VERSION < 4003000
1996 1997
    IUSBController *USBController = NULL;
    PRBool enabled = PR_FALSE;
R
Ryota Ozaki 已提交
1998 1999 2000
#else
    IUSBDeviceFilters *USBDeviceFilters = NULL;
#endif
2001 2002 2003 2004 2005
    vboxArray deviceFilters = VBOX_ARRAY_INITIALIZER;
    size_t i;
    PRUint32 USBFilterCount = 0;

    def->nhostdevs = 0;
R
Ryota Ozaki 已提交
2006

2007
#if VBOX_API_VERSION < 4003000
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
    machine->vtbl->GetUSBController(machine, &USBController);

    if (!USBController)
        return;

    USBController->vtbl->GetEnabled(USBController, &enabled);
    if (!enabled)
        goto release_controller;

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

R
Ryota Ozaki 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029
#else
    machine->vtbl->GetUSBDeviceFilters(machine, &USBDeviceFilters);

    if (!USBDeviceFilters)
        return;

    vboxArrayGet(&deviceFilters, USBDeviceFilters,
                 USBDeviceFilters->vtbl->GetDeviceFilters);
#endif

2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
    if (deviceFilters.count <= 0)
        goto release_filters;

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

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

        deviceFilter->vtbl->GetActive(deviceFilter, &active);
        if (active) {
            def->nhostdevs++;
        }
    }

    if (def->nhostdevs == 0)
        goto release_filters;

    /* Alloc mem needed for the filters now */
    if (VIR_ALLOC_N(def->hostdevs, def->nhostdevs) < 0)
        goto release_filters;

2054 2055 2056 2057 2058 2059
    for (i = 0; i < def->nhostdevs; i++) {
        def->hostdevs[i] = virDomainHostdevDefAlloc();
        if (!def->hostdevs[i])
            goto release_hostdevs;
    }

2060
    for (i = 0; i < deviceFilters.count; i++) {
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
        PRBool active                  = PR_FALSE;
        IUSBDeviceFilter *deviceFilter = deviceFilters.items[i];
        PRUnichar *vendorIdUtf16       = NULL;
        char *vendorIdUtf8             = NULL;
        unsigned vendorId              = 0;
        PRUnichar *productIdUtf16      = NULL;
        char *productIdUtf8            = NULL;
        unsigned productId             = 0;
        char *endptr                   = NULL;

        deviceFilter->vtbl->GetActive(deviceFilter, &active);
        if (!active)
            continue;

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

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

        VBOX_UTF16_TO_UTF8(vendorIdUtf16, &vendorIdUtf8);
        VBOX_UTF16_TO_UTF8(productIdUtf16, &productIdUtf8);

2086 2087
        ignore_value(virStrToLong_ui(vendorIdUtf8, &endptr, 16, &vendorId));
        ignore_value(virStrToLong_ui(productIdUtf8, &endptr, 16, &productId));
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100

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

        VBOX_UTF16_FREE(vendorIdUtf16);
        VBOX_UTF8_FREE(vendorIdUtf8);

        VBOX_UTF16_FREE(productIdUtf16);
        VBOX_UTF8_FREE(productIdUtf8);

        USBFilterCount++;
    }

2101
 release_filters:
2102
    vboxArrayRelease(&deviceFilters);
2103
#if VBOX_API_VERSION < 4003000
2104
 release_controller:
2105
    VBOX_RELEASE(USBController);
R
Ryota Ozaki 已提交
2106 2107 2108
#else
    VBOX_RELEASE(USBDeviceFilters);
#endif
2109 2110 2111

    return;

2112
 release_hostdevs:
2113 2114 2115 2116 2117
    for (i = 0; i < def->nhostdevs; i++)
        virDomainHostdevDefFree(def->hostdevs[i]);
    VIR_FREE(def->hostdevs);

    goto release_filters;
2118 2119
}

2120
static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
2121
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
2122 2123
    virDomainDefPtr def  = NULL;
    IMachine *machine    = NULL;
2124
    vboxIID iid = VBOX_IID_INITIALIZER;
2125
    int gotAllABoutDef   = -1;
2126
    nsresult rc;
2127

2128 2129
    /* Flags checked by virDomainDefFormat */

2130
    if (VIR_ALLOC(def) < 0)
2131 2132
        goto cleanup;

2133
    vboxIIDFromUUID(&iid, dom->uuid);
2134
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
2135
    if (NS_SUCCEEDED(rc)) {
2136
        PRBool accessible = PR_FALSE;
2137

2138 2139
        machine->vtbl->GetAccessible(machine, &accessible);
        if (accessible) {
2140
            size_t i = 0;
2141 2142 2143
            PRBool PAEEnabled                   = PR_FALSE;
            PRBool ACPIEnabled                  = PR_FALSE;
            PRBool IOAPICEnabled                = PR_FALSE;
2144
            PRBool VRDxEnabled                  = PR_FALSE;
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
            PRUint32 CPUCount                   = 0;
            PRUint32 memorySize                 = 0;
            PRUint32 netAdpCnt                  = 0;
            PRUint32 netAdpIncCnt               = 0;
            PRUint32 maxMemorySize              = 4 * 1024;
            PRUint32 maxBootPosition            = 0;
            PRUint32 serialPortCount            = 0;
            PRUint32 serialPortIncCount         = 0;
            PRUint32 parallelPortCount          = 0;
            PRUint32 parallelPortIncCount       = 0;
            IBIOSSettings *bios                 = NULL;
2156
#if VBOX_API_VERSION < 3001000
2157 2158 2159 2160 2161 2162 2163 2164
            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;
2165
#else  /* VBOX_API_VERSION >= 3001000 */
2166
            vboxArray mediumAttachments         = VBOX_ARRAY_INITIALIZER;
2167 2168
#endif /* VBOX_API_VERSION >= 3001000 */
#if VBOX_API_VERSION < 4000000
2169
            IVRDPServer *VRDxServer             = NULL;
2170
#else  /* VBOX_API_VERSION >= 4000000 */
2171
            IVRDEServer *VRDxServer             = NULL;
2172
#endif /* VBOX_API_VERSION >= 4000000 */
2173
            IAudioAdapter *audioAdapter         = NULL;
2174
#if VBOX_API_VERSION >= 4001000
2175
            PRUint32 chipsetType                = ChipsetType_Null;
2176
#endif /* VBOX_API_VERSION >= 4001000 */
2177
            ISystemProperties *systemProperties = NULL;
2178 2179


2180 2181 2182
            def->virtType = VIR_DOMAIN_VIRT_VBOX;
            def->id = dom->id;
            memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
2183 2184
            if (VIR_STRDUP(def->name, dom->name) < 0)
                goto cleanup;
2185

2186
            machine->vtbl->GetMemorySize(machine, &memorySize);
2187
            def->mem.cur_balloon = memorySize * 1024;
2188

2189
#if VBOX_API_VERSION >= 4001000
2190
            machine->vtbl->GetChipsetType(machine, &chipsetType);
2191
#endif /* VBOX_API_VERSION >= 4001000 */
2192

2193 2194 2195 2196
            data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                systemProperties->vtbl->GetMaxGuestRAM(systemProperties, &maxMemorySize);
                systemProperties->vtbl->GetMaxBootPosition(systemProperties, &maxBootPosition);
2197
#if VBOX_API_VERSION < 4001000
2198
                systemProperties->vtbl->GetNetworkAdapterCount(systemProperties, &netAdpCnt);
2199
#else  /* VBOX_API_VERSION >= 4000000 */
2200
                systemProperties->vtbl->GetMaxNetworkAdapters(systemProperties, chipsetType, &netAdpCnt);
2201
#endif /* VBOX_API_VERSION >= 4000000 */
2202 2203 2204 2205 2206 2207 2208 2209 2210
                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
             */
2211 2212
            /* def->mem.max_balloon = maxMemorySize * 1024; */
            def->mem.max_balloon = memorySize * 1024;
2213 2214

            machine->vtbl->GetCPUCount(machine, &CPUCount);
E
Eric Blake 已提交
2215
            def->maxvcpus = def->vcpus = CPUCount;
2216 2217 2218

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

2219 2220
            if (VIR_STRDUP(def->os.type, "hvm") < 0)
                goto cleanup;
2221

2222
            def->os.arch = virArchFromHost();
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245

            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 */
M
Matthias Bolte 已提交
2246
                    /* Can VirtualBox really boot from a shared folder? */
2247
                }
2248
            }
2249

2250
#if VBOX_API_VERSION < 3001000
2251
            machine->vtbl->GetPAEEnabled(machine, &PAEEnabled);
2252
#elif VBOX_API_VERSION == 3001000
2253
            machine->vtbl->GetCpuProperty(machine, CpuPropertyType_PAE, &PAEEnabled);
2254
#elif VBOX_API_VERSION >= 3002000
2255 2256
            machine->vtbl->GetCPUProperty(machine, CPUPropertyType_PAE, &PAEEnabled);
#endif
2257
            if (PAEEnabled)
J
Ján Tomko 已提交
2258
                def->features[VIR_DOMAIN_FEATURE_PAE] = VIR_TRISTATE_SWITCH_ON;
2259

2260 2261 2262
            machine->vtbl->GetBIOSSettings(machine, &bios);
            if (bios) {
                bios->vtbl->GetACPIEnabled(bios, &ACPIEnabled);
2263
                if (ACPIEnabled)
J
Ján Tomko 已提交
2264
                    def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_TRISTATE_SWITCH_ON;
2265

2266
                bios->vtbl->GetIOAPICEnabled(bios, &IOAPICEnabled);
2267
                if (IOAPICEnabled)
J
Ján Tomko 已提交
2268
                    def->features[VIR_DOMAIN_FEATURE_APIC] = VIR_TRISTATE_SWITCH_ON;
2269

2270 2271 2272 2273 2274
                VBOX_RELEASE(bios);
            }

            /* Currently VirtualBox always uses locatime
             * so locatime is always true here */
2275
            def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;
2276 2277 2278 2279 2280 2281 2282 2283

            /* 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 */
2284
                        PRUint32 VRAMSize          = 8;
2285 2286 2287 2288 2289 2290 2291
                        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);
2292
#if VBOX_API_VERSION >= 3001000
2293
                        machine->vtbl->GetAccelerate2DVideoEnabled(machine, &accelerate2DEnabled);
2294
#endif /* VBOX_API_VERSION >= 3001000 */
2295 2296

                        def->videos[0]->type            = VIR_DOMAIN_VIDEO_TYPE_VBOX;
2297
                        def->videos[0]->vram            = VRAMSize * 1024;
2298 2299 2300 2301
                        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;
2302 2303 2304
                        }
                    }
                }
2305
            }
2306

2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317
            /* 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;
2318

2319
                def->ngraphics = 0;
2320

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

2325 2326 2327
                if (valueTypeUtf16) {
                    VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
                    VBOX_UTF16_FREE(valueTypeUtf16);
2328

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

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

2338 2339 2340
                        if (valueDisplayUtf16) {
                            VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                            VBOX_UTF16_FREE(valueDisplayUtf16);
2341

J
John Ferlan 已提交
2342
                            if (strlen(valueDisplayUtf8) <= 0)
2343
                                VBOX_UTF8_FREE(valueDisplayUtf8);
2344
                        }
2345

2346 2347
                        if (STREQ(valueTypeUtf8, "sdl")) {
                            sdlPresent = 1;
2348
                            if (VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) {
2349 2350 2351 2352 2353 2354
                                /* 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++;
2355
                        }
2356

2357 2358
                        if (STREQ(valueTypeUtf8, "gui")) {
                            guiPresent = 1;
2359
                            if (VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) {
2360
                                /* just don't go to cleanup yet as it is ok to have
2361 2362
                                 * guiDisplay as NULL and we check it below if it
                                 * exist and then only use it there
2363
                                 */
2364
                            }
2365 2366
                            totalPresent++;
                        }
J
John Ferlan 已提交
2367
                        VBOX_UTF8_FREE(valueDisplayUtf8);
2368 2369
                    }

2370 2371
                    if (STREQ(valueTypeUtf8, "vrdp"))
                        vrdpPresent = 1;
2372

2373 2374
                    VBOX_UTF8_FREE(valueTypeUtf8);
                }
2375

2376 2377 2378 2379 2380 2381 2382
                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++;
                    }
2383

2384 2385 2386 2387 2388 2389 2390 2391
                    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) {
2392
                        const char *tmp;
2393
                        def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP;
2394
                        tmp = virGetEnvBlockSUID("DISPLAY");
2395 2396 2397 2398
                        if (VIR_STRDUP(def->graphics[def->ngraphics]->data.desktop.display, tmp) < 0) {
                            /* just don't go to cleanup yet as it is ok to have
                             * display as NULL
                             */
2399 2400 2401 2402 2403
                        }
                        totalPresent++;
                        def->ngraphics++;
                    }
                }
2404

2405
#if VBOX_API_VERSION < 4000000
2406
                machine->vtbl->GetVRDPServer(machine, &VRDxServer);
2407
#else  /* VBOX_API_VERSION >= 4000000 */
2408
                machine->vtbl->GetVRDEServer(machine, &VRDxServer);
2409
#endif /* VBOX_API_VERSION >= 4000000 */
2410 2411 2412
                if (VRDxServer) {
                    VRDxServer->vtbl->GetEnabled(VRDxServer, &VRDxEnabled);
                    if (VRDxEnabled) {
2413 2414 2415 2416 2417 2418 2419 2420 2421

                        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;
2422
#if VBOX_API_VERSION < 3001000
2423
                            PRUint32 VRDPport = 0;
2424
                            VRDxServer->vtbl->GetPort(VRDxServer, &VRDPport);
2425 2426
                            if (VRDPport) {
                                def->graphics[def->ngraphics]->data.rdp.port = VRDPport;
2427 2428 2429
                            } else {
                                def->graphics[def->ngraphics]->data.rdp.autoport = true;
                            }
2430
#elif VBOX_API_VERSION < 4000000 /* 3001000 <= VBOX_API_VERSION < 4000000 */
2431
                            PRUnichar *VRDPport = NULL;
2432
                            VRDxServer->vtbl->GetPorts(VRDxServer, &VRDPport);
2433 2434 2435 2436
                            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);
2437 2438 2439
                            } else {
                                def->graphics[def->ngraphics]->data.rdp.autoport = true;
                            }
2440
#else /* VBOX_API_VERSION >= 4000000 */
2441 2442 2443 2444 2445 2446 2447 2448 2449
                            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);
2450
                            } else {
2451
                                def->graphics[def->ngraphics]->data.rdp.autoport = true;
2452
                            }
2453
#endif /* VBOX_API_VERSION >= 4000000 */
2454

2455
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;
2456

2457
#if VBOX_API_VERSION >= 4000000
2458 2459 2460 2461
                            PRUnichar *VRDENetAddressKey = NULL;
                            VBOX_UTF8_TO_UTF16("TCP/Address", &VRDENetAddressKey);
                            VRDxServer->vtbl->GetVRDEProperty(VRDxServer, VRDENetAddressKey, &netAddressUtf16);
                            VBOX_UTF16_FREE(VRDENetAddressKey);
2462
#else /* VBOX_API_VERSION < 4000000 */
2463
                            VRDxServer->vtbl->GetNetAddress(VRDxServer, &netAddressUtf16);
2464
#endif /* VBOX_API_VERSION < 4000000 */
2465 2466 2467
                            if (netAddressUtf16) {
                                VBOX_UTF16_TO_UTF8(netAddressUtf16, &netAddressUtf8);
                                if (STRNEQ(netAddressUtf8, ""))
2468 2469
                                    virDomainGraphicsListenSetAddress(def->graphics[def->ngraphics], 0,
                                                                      netAddressUtf8, -1, true);
2470 2471 2472
                                VBOX_UTF16_FREE(netAddressUtf16);
                                VBOX_UTF8_FREE(netAddressUtf8);
                            }
2473

2474
                            VRDxServer->vtbl->GetAllowMultiConnection(VRDxServer, &allowMultiConnection);
2475
                            if (allowMultiConnection) {
2476
                                def->graphics[def->ngraphics]->data.rdp.multiUser = true;
2477
                            }
2478

2479
                            VRDxServer->vtbl->GetReuseSingleConnection(VRDxServer, &reuseSingleConnection);
2480
                            if (reuseSingleConnection) {
2481
                                def->graphics[def->ngraphics]->data.rdp.replaceUser = true;
2482
                            }
2483

2484
                            def->ngraphics++;
2485
                        } else
2486
                            virReportOOMError();
2487
                    }
2488
                    VBOX_RELEASE(VRDxServer);
2489
                }
2490
            }
2491

2492
#if VBOX_API_VERSION < 3001000
2493 2494
            /* dump IDE hdds if present */
            VBOX_UTF8_TO_UTF16(hddBus, &hddBusUtf16);
2495

2496 2497 2498 2499
            def->ndisks = 0;
            machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 0,  &hardDiskPM);
            if (hardDiskPM)
                def->ndisks++;
2500

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

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

2509 2510 2511 2512
            VBOX_UTF16_FREE(hddBusUtf16);

            if ((def->ndisks > 0) && (VIR_ALLOC_N(def->disks, def->ndisks) >= 0)) {
                for (i = 0; i < def->ndisks; i++) {
2513
                    if ((def->disks[i] = virDomainDiskDefNew())) {
2514 2515
                        def->disks[i]->device = VIR_DOMAIN_DISK_DEVICE_DISK;
                        def->disks[i]->bus = VIR_DOMAIN_DISK_BUS_IDE;
2516
                        virDomainDiskSetType(def->disks[i],
E
Eric Blake 已提交
2517
                                             VIR_STORAGE_TYPE_FILE);
2518
                    }
2519
                }
2520
            }
2521

2522 2523 2524 2525
            if (hardDiskPM) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2526

2527 2528
                hardDiskPM->vtbl->imedium.GetLocation((IMedium *)hardDiskPM, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2529

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

2532
                if (hddType == HardDiskType_Immutable)
2533
                    def->disks[hddNum]->src->readonly = true;
2534 2535
                ignore_value(virDomainDiskSetSource(def->disks[hddNum],
                                                    hddlocation));
2536
                ignore_value(VIR_STRDUP(def->disks[hddNum]->dst, "hda"));
2537
                hddNum++;
2538

2539 2540 2541 2542
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPM);
            }
2543

2544 2545 2546 2547
            if (hardDiskPS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2548

2549 2550
                hardDiskPS->vtbl->imedium.GetLocation((IMedium *)hardDiskPS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2551

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

2554
                if (hddType == HardDiskType_Immutable)
2555
                    def->disks[hddNum]->src->readonly = true;
2556 2557
                ignore_value(virDomainDiskSetSource(def->disks[hddNum],
                                                    hddlocation));
2558
                ignore_value(VIR_STRDUP(def->disks[hddNum]->dst, "hdb"));
2559
                hddNum++;
2560

2561 2562 2563 2564
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPS);
            }
2565

2566 2567 2568 2569
            if (hardDiskSS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2570

2571 2572
                hardDiskSS->vtbl->imedium.GetLocation((IMedium *)hardDiskSS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2573

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

2576
                if (hddType == HardDiskType_Immutable)
2577
                    def->disks[hddNum]->src->readonly = true;
2578 2579
                ignore_value(virDomainDiskSetSource(def->disks[hddNum],
                                                    hddlocation));
J
Ján Tomko 已提交
2580 2581
                ignore_value(VIR_STRDUP(def->disks[hddNum]->dst, "hdd"));
                hddNum++;
2582 2583 2584 2585 2586

                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskSS);
            }
2587
#else  /* VBOX_API_VERSION >= 3001000 */
2588 2589 2590 2591 2592 2593 2594
            /* dump IDE hdds if present */

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

            /* get the number of attachments */
2598 2599
            for (i = 0; i < mediumAttachments.count; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2600 2601 2602 2603 2604 2605 2606
                if (imediumattach) {
                    IMedium *medium = NULL;

                    imediumattach->vtbl->GetMedium(imediumattach, &medium);
                    if (medium) {
                        def->ndisks++;
                        VBOX_RELEASE(medium);
2607 2608
                    }
                }
2609
            }
2610

2611 2612 2613
            /* Allocate mem, if fails return error */
            if (VIR_ALLOC_N(def->disks, def->ndisks) >= 0) {
                for (i = 0; i < def->ndisks; i++) {
2614 2615
                    virDomainDiskDefPtr disk = virDomainDiskDefNew();
                    if (!disk) {
2616 2617
                        error = true;
                        break;
2618
                    }
2619
                    def->disks[i] = disk;
2620
                }
2621 2622 2623 2624 2625 2626 2627 2628
            } else {
                error = true;
            }

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

            /* get the attachment details here */
2629 2630
            for (i = 0; i < mediumAttachments.count && diskCount < def->ndisks && !error; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663
                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;
                }
2664

2665 2666 2667
                medium->vtbl->GetLocation(medium, &mediumLocUtf16);
                VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8);
                VBOX_UTF16_FREE(mediumLocUtf16);
2668 2669
                ignore_value(virDomainDiskSetSource(def->disks[diskCount],
                                                    mediumLocUtf8));
2670 2671
                VBOX_UTF8_FREE(mediumLocUtf8);

2672
                if (!virDomainDiskGetSource(def->disks[diskCount])) {
2673 2674 2675 2676 2677
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2678

2679 2680 2681 2682 2683 2684 2685 2686 2687 2688
                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;
                }
2689

2690 2691 2692 2693 2694 2695 2696 2697 2698 2699
                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);
2700
                def->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
2701 2702 2703 2704 2705 2706
                                                                    deviceInst,
                                                                    devicePort,
                                                                    deviceSlot,
                                                                    maxPortPerInst,
                                                                    maxSlotPerPort);
                if (!def->disks[diskCount]->dst) {
2707 2708 2709 2710
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Could not generate medium name for the disk "
                                     "at: controller instance:%u, port:%d, slot:%d"),
                                   deviceInst, devicePort, deviceSlot);
2711 2712 2713 2714 2715
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2716

2717 2718
                medium->vtbl->GetReadOnly(medium, &readOnly);
                if (readOnly == PR_TRUE)
2719
                    def->disks[diskCount]->src->readonly = true;
2720

2721
                virDomainDiskSetType(def->disks[diskCount],
E
Eric Blake 已提交
2722
                                     VIR_STORAGE_TYPE_FILE);
2723

2724 2725 2726 2727
                VBOX_RELEASE(medium);
                VBOX_RELEASE(storageController);
                diskCount++;
            }
2728

2729
            vboxArrayRelease(&mediumAttachments);
2730

2731 2732 2733 2734 2735 2736 2737 2738
            /* cleanup on error */
            if (error) {
                for (i = 0; i < def->ndisks; i++) {
                    VIR_FREE(def->disks[i]);
                }
                VIR_FREE(def->disks);
                def->ndisks = 0;
            }
2739

2740
#endif /* VBOX_API_VERSION >= 3001000 */
2741

M
Matthias Bolte 已提交
2742 2743 2744 2745 2746 2747 2748 2749 2750
            /* shared folders */
            vboxArray sharedFolders = VBOX_ARRAY_INITIALIZER;

            def->nfss = 0;

            vboxArrayGet(&sharedFolders, machine,
                         machine->vtbl->GetSharedFolders);

            if (sharedFolders.count > 0) {
2751
                if (VIR_ALLOC_N(def->fss, sharedFolders.count) < 0)
M
Matthias Bolte 已提交
2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
                    goto sharedFoldersCleanup;

                for (i = 0; i < sharedFolders.count; i++) {
                    ISharedFolder *sharedFolder = sharedFolders.items[i];
                    PRUnichar *nameUtf16 = NULL;
                    char *name = NULL;
                    PRUnichar *hostPathUtf16 = NULL;
                    char *hostPath = NULL;
                    PRBool writable = PR_FALSE;

2762
                    if (VIR_ALLOC(def->fss[i]) < 0)
M
Matthias Bolte 已提交
2763 2764 2765 2766 2767 2768
                        goto sharedFoldersCleanup;

                    def->fss[i]->type = VIR_DOMAIN_FS_TYPE_MOUNT;

                    sharedFolder->vtbl->GetHostPath(sharedFolder, &hostPathUtf16);
                    VBOX_UTF16_TO_UTF8(hostPathUtf16, &hostPath);
2769 2770 2771
                    if (VIR_STRDUP(def->fss[i]->src, hostPath) < 0) {
                        VBOX_UTF8_FREE(hostPath);
                        VBOX_UTF16_FREE(hostPathUtf16);
M
Matthias Bolte 已提交
2772 2773
                        goto sharedFoldersCleanup;
                    }
2774 2775
                    VBOX_UTF8_FREE(hostPath);
                    VBOX_UTF16_FREE(hostPathUtf16);
M
Matthias Bolte 已提交
2776 2777 2778

                    sharedFolder->vtbl->GetName(sharedFolder, &nameUtf16);
                    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
2779 2780 2781
                    if (VIR_STRDUP(def->fss[i]->dst, name) < 0) {
                        VBOX_UTF8_FREE(name);
                        VBOX_UTF16_FREE(nameUtf16);
M
Matthias Bolte 已提交
2782 2783
                        goto sharedFoldersCleanup;
                    }
2784 2785
                    VBOX_UTF8_FREE(name);
                    VBOX_UTF16_FREE(nameUtf16);
M
Matthias Bolte 已提交
2786 2787 2788 2789 2790 2791 2792 2793

                    sharedFolder->vtbl->GetWritable(sharedFolder, &writable);
                    def->fss[i]->readonly = !writable;

                    ++def->nfss;
                }
            }

2794
 sharedFoldersCleanup:
M
Matthias Bolte 已提交
2795 2796
            vboxArrayRelease(&sharedFolders);

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

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

2807 2808 2809 2810
                    adapter->vtbl->GetEnabled(adapter, &enabled);
                    if (enabled) {
                        def->nnets++;
                    }
2811

2812 2813 2814
                    VBOX_RELEASE(adapter);
                }
            }
2815

2816 2817 2818
            /* 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++) {
2819
                    ignore_value(VIR_ALLOC(def->nets[i]));
2820 2821
                }
            }
2822

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

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

2831 2832 2833 2834 2835 2836 2837
                    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};
2838

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

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

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

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

2850
#if VBOX_API_VERSION < 4001000
2851
                            adapter->vtbl->GetHostInterface(adapter, &hostIntUtf16);
2852
#else /* VBOX_API_VERSION >= 4001000 */
2853
                            adapter->vtbl->GetBridgedInterface(adapter, &hostIntUtf16);
2854
#endif /* VBOX_API_VERSION >= 4001000 */
2855

2856
                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
2857
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.bridge.brname, hostInt));
2858

2859 2860
                            VBOX_UTF8_FREE(hostInt);
                            VBOX_UTF16_FREE(hostIntUtf16);
2861

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

2866 2867 2868 2869 2870
                            def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_INTERNAL;

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

                            VBOX_UTF16_TO_UTF8(intNetUtf16, &intNet);
2871
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.internal.name, intNet));
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881

                            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;

2882
#if VBOX_API_VERSION < 4001000
2883
                            adapter->vtbl->GetHostInterface(adapter, &hostIntUtf16);
2884
#else /* VBOX_API_VERSION >= 4001000 */
2885
                            adapter->vtbl->GetHostOnlyInterface(adapter, &hostIntUtf16);
2886
#endif /* VBOX_API_VERSION >= 4001000 */
2887 2888

                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
2889
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.network.name, hostInt));
2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902

                            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) {
2903
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "Am79C970A"));
2904
                        } else if (adapterType == NetworkAdapterType_Am79C973) {
2905
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "Am79C973"));
2906
                        } else if (adapterType == NetworkAdapterType_I82540EM) {
2907
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82540EM"));
2908
                        } else if (adapterType == NetworkAdapterType_I82545EM) {
2909
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82545EM"));
2910
                        } else if (adapterType == NetworkAdapterType_I82543GC) {
2911
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82543GC"));
2912
#if VBOX_API_VERSION >= 3001000
2913
                        } else if (adapterType == NetworkAdapterType_Virtio) {
2914
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "virtio"));
2915
#endif /* VBOX_API_VERSION >= 3001000 */
2916 2917
                        }

2918 2919 2920 2921 2922 2923 2924 2925 2926
                        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 ... */
2927
                        if (virMacAddrParse(macaddr, &def->nets[netAdpIncCnt]->mac) < 0)
2928 2929 2930 2931 2932 2933
                        {}

                        netAdpIncCnt++;

                        VBOX_UTF16_FREE(MACAddressUtf16);
                        VBOX_UTF8_FREE(MACAddress);
2934
                    }
2935 2936

                    VBOX_RELEASE(adapter);
2937
                }
2938
            }
2939

2940
            /* dump sound card if active */
2941

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

2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972
            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;
                        }
                    } else {
                        def->nsounds = 0;
                    }
                }
                VBOX_RELEASE(audioAdapter);
            }
2973

2974
#if VBOX_API_VERSION < 3001000
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993
            /* 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) {
2994
                            if ((def->disks[def->ndisks - 1] = virDomainDiskDefNew())) {
2995 2996
                                def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
                                def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_IDE;
2997
                                virDomainDiskSetType(def->disks[def->ndisks - 1],
E
Eric Blake 已提交
2998
                                                     VIR_STORAGE_TYPE_FILE);
2999
                                def->disks[def->ndisks - 1]->src->readonly = true;
3000
                                ignore_value(virDomainDiskSetSource(def->disks[def->ndisks - 1], location));
3001 3002
                                ignore_value(VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "hdc"));
                                def->ndisks--;
3003
                            } else {
3004
                                def->ndisks--;
3005 3006
                            }
                        } else {
3007
                            def->ndisks--;
3008
                        }
3009 3010 3011 3012

                        VBOX_UTF8_FREE(location);
                        VBOX_UTF16_FREE(locationUtf16);
                        VBOX_MEDIUM_RELEASE(dvdImage);
3013 3014
                    }
                }
3015 3016
                VBOX_RELEASE(dvdDrive);
            }
3017

3018 3019 3020 3021 3022 3023 3024
            /* 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) {
3025 3026
                    PRUint32 state = DriveState_Null;

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

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

3036 3037
                            floppyImage->vtbl->imedium.GetLocation((IMedium *)floppyImage, &locationUtf16);
                            VBOX_UTF16_TO_UTF8(locationUtf16, &location);
3038 3039 3040

                            def->ndisks++;
                            if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
3041
                                if ((def->disks[def->ndisks - 1] = virDomainDiskDefNew())) {
3042 3043
                                    def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                                    def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC;
3044
                                    virDomainDiskSetType(def->disks[def->ndisks - 1],
E
Eric Blake 已提交
3045
                                                         VIR_STORAGE_TYPE_FILE);
3046
                                    def->disks[def->ndisks - 1]->src->readonly = false;
3047
                                    ignore_value(virDomainDiskSetSource(def->disks[def->ndisks - 1], location));
3048 3049
                                    ignore_value(VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "fda"));
                                    def->ndisks--;
3050 3051 3052 3053 3054 3055 3056
                                } else {
                                    def->ndisks--;
                                }
                            } else {
                                def->ndisks--;
                            }

3057 3058 3059
                            VBOX_UTF8_FREE(location);
                            VBOX_UTF16_FREE(locationUtf16);
                            VBOX_MEDIUM_RELEASE(floppyImage);
3060 3061 3062 3063
                        }
                    }
                }

3064 3065
                VBOX_RELEASE(floppyDrive);
            }
3066 3067
#else  /* VBOX_API_VERSION >= 3001000 */
#endif /* VBOX_API_VERSION >= 3001000 */
3068 3069 3070 3071 3072 3073 3074 3075 3076

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

3079
                    serialPort->vtbl->GetEnabled(serialPort, &enabled);
3080
                    if (enabled) {
3081
                        def->nserials++;
3082 3083
                    }

3084
                    VBOX_RELEASE(serialPort);
3085
                }
3086
            }
3087

3088 3089 3090
            /* 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++) {
3091
                    ignore_value(VIR_ALLOC(def->serials[i]));
3092 3093
                }
            }
3094

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

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

3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
                    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) {
3115
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_PIPE;
3116
                        } else if (hostMode == PortMode_HostDevice) {
3117
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_DEV;
3118
#if VBOX_API_VERSION >= 3000000
3119
                        } else if (hostMode == PortMode_RawFile) {
3120
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
3121
#endif /* VBOX_API_VERSION >= 3000000 */
3122
                        } else {
3123
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_NULL;
3124
                        }
3125

3126
                        def->serials[serialPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
3127

3128 3129 3130 3131 3132 3133 3134
                        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;
                        }
3135

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

3138 3139
                        if (pathUtf16) {
                            VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3140
                            ignore_value(VIR_STRDUP(def->serials[serialPortIncCount]->source.data.file.path, path));
3141 3142
                        }

3143 3144 3145 3146
                        serialPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
3147 3148
                    }

3149 3150 3151
                    VBOX_RELEASE(serialPort);
                }
            }
3152

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

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

3163 3164 3165
                    parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                    if (enabled) {
                        def->nparallels++;
3166
                    }
3167 3168

                    VBOX_RELEASE(parallelPort);
3169
                }
3170
            }
3171

3172 3173 3174
            /* 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++) {
3175
                    ignore_value(VIR_ALLOC(def->parallels[i]));
3176
                }
3177
            }
3178

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

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

3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203
                    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;
                        }
3204

3205
                        def->parallels[parallelPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
3206
                        def->parallels[parallelPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL;
3207

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

3210
                        VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3211
                        ignore_value(VIR_STRDUP(def->parallels[parallelPortIncCount]->source.data.file.path, path));
3212

3213 3214 3215 3216
                        parallelPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
3217
                    }
3218 3219

                    VBOX_RELEASE(parallelPort);
3220
                }
3221
            }
3222

3223
            /* dump USB devices/filters if active */
3224
            vboxHostDeviceGetXMLDesc(data, def, machine);
3225 3226 3227 3228 3229

            /* all done so set gotAllABoutDef and pass def to virDomainDefFormat
             * to generate XML for it
             */
            gotAllABoutDef = 0;
3230
        }
3231 3232
        VBOX_RELEASE(machine);
        machine = NULL;
3233 3234 3235
    }

    if (gotAllABoutDef == 0)
3236
        ret = virDomainDefFormat(def, flags);
3237

3238
 cleanup:
3239
    vboxIIDUnalloc(&iid);
3240 3241 3242 3243
    virDomainDefFree(def);
    return ret;
}

3244
static int vboxConnectListDefinedDomains(virConnectPtr conn, char ** const names, int maxnames) {
3245
    VBOX_OBJECT_CHECK(conn, int, -1);
3246
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3247 3248 3249
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
3250
    nsresult rc;
3251
    size_t i, j;
3252

3253
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3254
    if (NS_FAILED(rc)) {
3255 3256 3257
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of Defined Domains, rc=%08x"),
                       (unsigned)rc);
3258 3259
        goto cleanup;
    }
3260

3261 3262
    memset(names, 0, sizeof(names[i]) * maxnames);

3263 3264 3265
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < maxnames); i++) {
        IMachine *machine = machines.items[i];
3266 3267 3268 3269 3270 3271

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
3272 3273
                if ((state < MachineState_FirstOnline) ||
                    (state > MachineState_LastOnline)) {
3274 3275
                    machine->vtbl->GetName(machine, &machineNameUtf16);
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);
3276 3277 3278
                    if (VIR_STRDUP(names[j], machineName) < 0) {
                        VBOX_UTF16_FREE(machineNameUtf16);
                        VBOX_UTF8_FREE(machineName);
3279
                        for (j = 0; j < maxnames; j++)
3280 3281 3282
                            VIR_FREE(names[j]);
                        ret = -1;
                        goto cleanup;
3283
                    }
3284 3285
                    VBOX_UTF16_FREE(machineNameUtf16);
                    VBOX_UTF8_FREE(machineName);
3286
                    j++;
3287
                    ret++;
3288 3289 3290 3291 3292
                }
            }
        }
    }

3293
 cleanup:
3294
    vboxArrayRelease(&machines);
3295 3296 3297
    return ret;
}

3298 3299
static int vboxConnectNumOfDefinedDomains(virConnectPtr conn)
{
3300
    VBOX_OBJECT_CHECK(conn, int, -1);
3301
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3302
    PRUint32 state       = MachineState_Null;
3303
    nsresult rc;
3304
    size_t i;
3305

3306
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3307
    if (NS_FAILED(rc)) {
3308 3309 3310
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get number of Defined Domains, rc=%08x"),
                       (unsigned)rc);
3311 3312
        goto cleanup;
    }
3313

3314 3315 3316
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3317 3318 3319 3320 3321 3322

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
3323 3324
                if ((state < MachineState_FirstOnline) ||
                    (state > MachineState_LastOnline)) {
3325
                    ret++;
3326 3327 3328 3329 3330
                }
            }
        }
    }

3331
 cleanup:
3332
    vboxArrayRelease(&machines);
3333 3334 3335
    return ret;
}

E
Eric Blake 已提交
3336 3337

static int
3338
vboxStartMachine(virDomainPtr dom, int maxDomID, IMachine *machine,
3339
                 vboxIID *iid ATTRIBUTE_UNUSED /* >= 4.0 */)
E
Eric Blake 已提交
3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
{
    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);

3366
        if (STREQ(valueTypeUtf8, "sdl") || STREQ(valueTypeUtf8, "gui")) {
E
Eric Blake 已提交
3367 3368 3369 3370 3371 3372 3373 3374 3375 3376

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

J
John Ferlan 已提交
3377
                if (strlen(valueDisplayUtf8) <= 0)
E
Eric Blake 已提交
3378 3379 3380 3381 3382
                    VBOX_UTF8_FREE(valueDisplayUtf8);
            }

            if (STREQ(valueTypeUtf8, "sdl")) {
                sdlPresent = 1;
3383 3384 3385 3386 3387
                if (VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) {
                    /* 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
                     */
E
Eric Blake 已提交
3388 3389 3390 3391 3392
                }
            }

            if (STREQ(valueTypeUtf8, "gui")) {
                guiPresent = 1;
3393 3394 3395 3396 3397
                if (VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) {
                    /* 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
                     */
E
Eric Blake 已提交
3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
                }
            }
        }

        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;
    }
J
John Ferlan 已提交
3418
    VBOX_UTF8_FREE(valueDisplayUtf8);
E
Eric Blake 已提交
3419 3420 3421

    if (guiPresent) {
        if (guiDisplay) {
E
Eric Blake 已提交
3422
            char *displayutf8;
3423
            if (virAsprintf(&displayutf8, "DISPLAY=%s", guiDisplay) >= 0) {
E
Eric Blake 已提交
3424 3425 3426
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3427 3428 3429 3430 3431 3432 3433 3434
            VIR_FREE(guiDisplay);
        }

        VBOX_UTF8_TO_UTF16("gui", &sessionType);
    }

    if (sdlPresent) {
        if (sdlDisplay) {
E
Eric Blake 已提交
3435
            char *displayutf8;
3436
            if (virAsprintf(&displayutf8, "DISPLAY=%s", sdlDisplay) >= 0) {
E
Eric Blake 已提交
3437 3438 3439
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
            VIR_FREE(sdlDisplay);
        }

        VBOX_UTF8_TO_UTF16("sdl", &sessionType);
    }

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

3450
#if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
3451 3452
    rc = data->vboxObj->vtbl->OpenRemoteSession(data->vboxObj,
                                                data->vboxSession,
3453
                                                iid->value,
E
Eric Blake 已提交
3454 3455
                                                sessionType,
                                                env,
3456
                                                &progress);
3457
#else /* VBOX_API_VERSION >= 4000000 */
3458 3459
    rc = machine->vtbl->LaunchVMProcess(machine, data->vboxSession,
                                        sessionType, env, &progress);
3460
#endif /* VBOX_API_VERSION >= 4000000 */
3461

E
Eric Blake 已提交
3462
    if (NS_FAILED(rc)) {
3463 3464
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("OpenRemoteSession/LaunchVMProcess failed, domain can't be started"));
E
Eric Blake 已提交
3465 3466 3467
        ret = -1;
    } else {
        PRBool completed = 0;
3468
#if VBOX_API_VERSION == 2002000
E
Eric Blake 已提交
3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
        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 */
3485
            dom->id = maxDomID + 1;
E
Eric Blake 已提交
3486 3487 3488 3489 3490 3491
            ret = 0;
        }
    }

    VBOX_RELEASE(progress);

3492
    VBOX_SESSION_CLOSE();
E
Eric Blake 已提交
3493 3494 3495 3496 3497 3498 3499

    VBOX_UTF16_FREE(env);
    VBOX_UTF16_FREE(sessionType);

    return ret;
}

3500 3501
static int vboxDomainCreateWithFlags(virDomainPtr dom, unsigned int flags)
{
3502
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
3503
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3504
    unsigned char uuid[VIR_UUID_BUFLEN] = {0};
3505
    nsresult rc;
3506
    size_t i = 0;
3507

3508 3509
    virCheckFlags(0, -1);

3510
    if (!dom->name) {
3511 3512
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Error while reading the domain name"));
3513 3514 3515
        goto cleanup;
    }

3516
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3517
    if (NS_FAILED(rc)) {
3518 3519
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
3520 3521
        goto cleanup;
    }
3522

3523 3524
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3525
        PRBool isAccessible = PR_FALSE;
3526

3527 3528
        if (!machine)
            continue;
3529

3530 3531
        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
3532
            vboxIID iid = VBOX_IID_INITIALIZER;
3533

3534 3535
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
3536
                continue;
3537
            vboxIIDToUUID(&iid, uuid);
3538

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

3543 3544 3545
                if ((state == MachineState_PoweredOff) ||
                    (state == MachineState_Saved) ||
                    (state == MachineState_Aborted)) {
3546
                    ret = vboxStartMachine(dom, i, machine, &iid);
3547
                } else {
3548
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
3549 3550 3551
                                   _("machine is not in "
                                     "poweroff|saved|aborted state, so "
                                     "couldn't start it"));
3552
                    ret = -1;
3553 3554
                }
            }
3555
            vboxIIDUnalloc(&iid);
3556 3557
            if (ret != -1)
                break;
3558 3559 3560
        }
    }

3561
    /* Do the cleanup and take care you dont leak any memory */
3562
    vboxArrayRelease(&machines);
3563

3564
 cleanup:
3565 3566 3567
    return ret;
}

3568 3569
static int vboxDomainCreate(virDomainPtr dom)
{
3570 3571 3572
    return vboxDomainCreateWithFlags(dom, 0);
}

E
Eric Blake 已提交
3573 3574 3575 3576 3577 3578
static void
vboxSetBootDeviceOrder(virDomainDefPtr def, vboxGlobalData *data,
                       IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 maxBootPosition            = 0;
3579
    size_t i = 0;
3580

3581
    VIR_DEBUG("def->os.type             %s", def->os.type);
3582
    VIR_DEBUG("def->os.arch             %s", virArchToString(def->os.arch));
3583
    VIR_DEBUG("def->os.machine          %s", def->os.machine);
3584
    VIR_DEBUG("def->os.nBootDevs        %zu", def->os.nBootDevs);
3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
    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);
3597

E
Eric Blake 已提交
3598 3599 3600 3601 3602 3603
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxBootPosition(systemProperties,
                                                   &maxBootPosition);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
3604
    }
3605

E
Eric Blake 已提交
3606 3607 3608
    /* Clear the defaults first */
    for (i = 0; i < maxBootPosition; i++) {
        machine->vtbl->SetBootOrder(machine, i+1, DeviceType_Null);
3609
    }
3610

E
Eric Blake 已提交
3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621
    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;
3622
        }
E
Eric Blake 已提交
3623
        machine->vtbl->SetBootOrder(machine, i+1, device);
3624
    }
E
Eric Blake 已提交
3625
}
3626

E
Eric Blake 已提交
3627 3628 3629
static void
vboxAttachDrives(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
3630
    size_t i;
E
Eric Blake 已提交
3631
    nsresult rc;
3632

3633
#if VBOX_API_VERSION < 3001000
E
Eric Blake 已提交
3634 3635 3636 3637
    if (def->ndisks == 0)
        return;

    for (i = 0; i < def->ndisks; i++) {
3638 3639 3640 3641 3642
        const char *src = virDomainDiskGetSource(def->disks[i]);
        int type = virDomainDiskGetType(def->disks[i]);
        int format = virDomainDiskGetFormat(def->disks[i]);

        VIR_DEBUG("disk(%zu) type:       %d", i, type);
3643 3644
        VIR_DEBUG("disk(%zu) device:     %d", i, def->disks[i]->device);
        VIR_DEBUG("disk(%zu) bus:        %d", i, def->disks[i]->bus);
3645
        VIR_DEBUG("disk(%zu) src:        %s", i, src);
3646
        VIR_DEBUG("disk(%zu) dst:        %s", i, def->disks[i]->dst);
3647 3648
        VIR_DEBUG("disk(%zu) driverName: %s", i,
                  virDomainDiskGetDriver(def->disks[i]));
3649
        VIR_DEBUG("disk(%zu) driverType: %s", i,
3650
                  virStorageFileFormatTypeToString(format));
3651
        VIR_DEBUG("disk(%zu) cachemode:  %d", i, def->disks[i]->cachemode);
3652
        VIR_DEBUG("disk(%zu) readonly:   %s", i, (def->disks[i]->src->readonly
E
Eric Blake 已提交
3653
                                             ? "True" : "False"));
3654
        VIR_DEBUG("disk(%zu) shared:     %s", i, (def->disks[i]->src->shared
E
Eric Blake 已提交
3655 3656 3657
                                             ? "True" : "False"));

        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
E
Eric Blake 已提交
3658
            if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
3659 3660 3661 3662 3663 3664 3665
                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
                 */
3666

E
Eric Blake 已提交
3667 3668 3669 3670
                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                if (dvdDrive) {
                    IDVDImage *dvdImage          = NULL;
                    PRUnichar *dvdfileUtf16      = NULL;
3671 3672
                    vboxIID dvduuid = VBOX_IID_INITIALIZER;
                    vboxIID dvdemptyuuid = VBOX_IID_INITIALIZER;
3673

3674
                    VBOX_UTF8_TO_UTF16(src, &dvdfileUtf16);
3675

E
Eric Blake 已提交
3676 3677 3678 3679 3680
                    data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                      dvdfileUtf16, &dvdImage);
                    if (!dvdImage) {
                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                          dvdfileUtf16,
3681
                                                          dvdemptyuuid.value,
E
Eric Blake 已提交
3682 3683 3684 3685
                                                          &dvdImage);
                    }
                    if (dvdImage) {
                        rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage,
3686
                                                           &dvduuid.value);
E
Eric Blake 已提交
3687
                        if (NS_FAILED(rc)) {
3688 3689 3690
                            virReportError(VIR_ERR_INTERNAL_ERROR,
                                           _("can't get the uuid of the file to "
                                             "be attached to cdrom: %s, rc=%08x"),
3691
                                           src, (unsigned)rc);
E
Eric Blake 已提交
3692
                        } else {
3693
                            rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid.value);
E
Eric Blake 已提交
3694
                            if (NS_FAILED(rc)) {
3695 3696
                                virReportError(VIR_ERR_INTERNAL_ERROR,
                                               _("could not attach the file to cdrom: %s, rc=%08x"),
3697
                                               src, (unsigned)rc);
E
Eric Blake 已提交
3698
                            } else {
3699
                                DEBUGIID("CD/DVDImage UUID:", dvduuid.value);
3700
                            }
3701
                        }
E
Eric Blake 已提交
3702 3703

                        VBOX_MEDIUM_RELEASE(dvdImage);
3704
                    }
3705
                    vboxIIDUnalloc(&dvduuid);
E
Eric Blake 已提交
3706 3707 3708
                    VBOX_UTF16_FREE(dvdfileUtf16);
                    VBOX_RELEASE(dvdDrive);
                }
E
Eric Blake 已提交
3709
            } else if (type == VIR_STORAGE_TYPE_BLOCK) {
E
Eric Blake 已提交
3710 3711
            }
        } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
E
Eric Blake 已提交
3712
            if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
3713 3714
                IHardDisk *hardDisk     = NULL;
                PRUnichar *hddfileUtf16 = NULL;
3715
                vboxIID hdduuid = VBOX_IID_INITIALIZER;
E
Eric Blake 已提交
3716 3717 3718 3719 3720 3721
                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
                 */
3722

3723
                VBOX_UTF8_TO_UTF16(src, &hddfileUtf16);
E
Eric Blake 已提交
3724
                VBOX_UTF8_TO_UTF16("", &hddEmpty);
3725

E
Eric Blake 已提交
3726 3727
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddfileUtf16,
                                                  &hardDisk);
3728

E
Eric Blake 已提交
3729
                if (!hardDisk) {
3730
# if VBOX_API_VERSION == 2002000
E
Eric Blake 已提交
3731 3732 3733 3734
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      &hardDisk);
3735
# else
E
Eric Blake 已提交
3736 3737 3738 3739 3740 3741 3742 3743
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      0,
                                                      hddEmpty,
                                                      0,
                                                      hddEmpty,
                                                      &hardDisk);
3744
# endif
E
Eric Blake 已提交
3745
                }
3746

E
Eric Blake 已提交
3747 3748
                if (hardDisk) {
                    rc = hardDisk->vtbl->imedium.GetId((IMedium *)hardDisk,
3749
                                                       &hdduuid.value);
E
Eric Blake 已提交
3750
                    if (NS_FAILED(rc)) {
3751 3752 3753
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("can't get the uuid of the file to be "
                                         "attached as harddisk: %s, rc=%08x"),
3754
                                       src, (unsigned)rc);
E
Eric Blake 已提交
3755
                    } else {
3756
                        if (def->disks[i]->src->readonly) {
E
Eric Blake 已提交
3757 3758
                            hardDisk->vtbl->SetType(hardDisk,
                                                    HardDiskType_Immutable);
3759
                            VIR_DEBUG("setting harddisk to readonly");
3760
                        } else if (!def->disks[i]->src->readonly) {
E
Eric Blake 已提交
3761 3762
                            hardDisk->vtbl->SetType(hardDisk,
                                                    HardDiskType_Normal);
3763
                            VIR_DEBUG("setting harddisk type to normal");
E
Eric Blake 已提交
3764 3765 3766
                        }
                        if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_IDE) {
                            if (STREQ(def->disks[i]->dst, "hdc")) {
3767
                                VIR_DEBUG("Not connecting harddisk to hdc as hdc"
E
Eric Blake 已提交
3768
                                       " is taken by CD/DVD Drive");
3769
                            } else {
E
Eric Blake 已提交
3770 3771 3772 3773
                                PRInt32 channel          = 0;
                                PRInt32 device           = 0;
                                PRUnichar *hddcnameUtf16 = NULL;

3774 3775
                                char *hddcname;
                                ignore_value(VIR_STRDUP(hddcname, "IDE"));
E
Eric Blake 已提交
3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787
                                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;
3788
                                }
E
Eric Blake 已提交
3789 3790

                                rc = machine->vtbl->AttachHardDisk(machine,
3791
                                                                   hdduuid.value,
E
Eric Blake 已提交
3792 3793 3794 3795 3796 3797
                                                                   hddcnameUtf16,
                                                                   channel,
                                                                   device);
                                VBOX_UTF16_FREE(hddcnameUtf16);

                                if (NS_FAILED(rc)) {
3798 3799 3800
                                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                                   _("could not attach the file as "
                                                     "harddisk: %s, rc=%08x"),
3801
                                                   src, (unsigned)rc);
E
Eric Blake 已提交
3802
                                } else {
3803
                                    DEBUGIID("Attached HDD with UUID", hdduuid.value);
3804 3805 3806
                                }
                            }
                        }
3807
                    }
E
Eric Blake 已提交
3808 3809
                    VBOX_MEDIUM_RELEASE(hardDisk);
                }
3810
                vboxIIDUnalloc(&hdduuid);
E
Eric Blake 已提交
3811 3812
                VBOX_UTF16_FREE(hddEmpty);
                VBOX_UTF16_FREE(hddfileUtf16);
E
Eric Blake 已提交
3813
            } else if (type == VIR_STORAGE_TYPE_BLOCK) {
E
Eric Blake 已提交
3814 3815
            }
        } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
E
Eric Blake 已提交
3816
            if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
3817 3818 3819 3820 3821 3822 3823
                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;
3824 3825
                        vboxIID fduuid = VBOX_IID_INITIALIZER;
                        vboxIID fdemptyuuid = VBOX_IID_INITIALIZER;
3826

3827
                        VBOX_UTF8_TO_UTF16(src, &fdfileUtf16);
E
Eric Blake 已提交
3828 3829 3830
                        rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                  fdfileUtf16,
                                                                  &floppyImage);
3831

E
Eric Blake 已提交
3832 3833 3834
                        if (!floppyImage) {
                            data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                 fdfileUtf16,
3835
                                                                 fdemptyuuid.value,
E
Eric Blake 已提交
3836 3837
                                                                 &floppyImage);
                        }
3838

E
Eric Blake 已提交
3839 3840
                        if (floppyImage) {
                            rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage,
3841
                                                                  &fduuid.value);
E
Eric Blake 已提交
3842
                            if (NS_FAILED(rc)) {
3843 3844 3845
                                virReportError(VIR_ERR_INTERNAL_ERROR,
                                               _("can't get the uuid of the file to "
                                                 "be attached to floppy drive: %s, rc=%08x"),
3846
                                               src, (unsigned)rc);
E
Eric Blake 已提交
3847 3848
                            } else {
                                rc = floppyDrive->vtbl->MountImage(floppyDrive,
3849
                                                                   fduuid.value);
E
Eric Blake 已提交
3850
                                if (NS_FAILED(rc)) {
3851 3852 3853
                                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                                   _("could not attach the file to "
                                                     "floppy drive: %s, rc=%08x"),
3854
                                                   src, (unsigned)rc);
E
Eric Blake 已提交
3855
                                } else {
3856
                                    DEBUGIID("floppyImage UUID", fduuid.value);
3857 3858
                                }
                            }
E
Eric Blake 已提交
3859
                            VBOX_MEDIUM_RELEASE(floppyImage);
3860
                        }
3861
                        vboxIIDUnalloc(&fduuid);
E
Eric Blake 已提交
3862
                        VBOX_UTF16_FREE(fdfileUtf16);
3863
                    }
E
Eric Blake 已提交
3864
                    VBOX_RELEASE(floppyDrive);
3865
                }
E
Eric Blake 已提交
3866
            } else if (type == VIR_STORAGE_TYPE_BLOCK) {
3867
            }
3868
        }
E
Eric Blake 已提交
3869
    }
3870
#else  /* VBOX_API_VERSION >= 3001000 */
E
Eric Blake 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882
    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 */
3883
    {
E
Eric Blake 已提交
3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
        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);
    }
3919

E
Eric Blake 已提交
3920
    for (i = 0; i < def->ndisks && !error; i++) {
3921 3922 3923 3924 3925
        const char *src = virDomainDiskGetSource(def->disks[i]);
        int type = virDomainDiskGetType(def->disks[i]);
        int format = virDomainDiskGetFormat(def->disks[i]);

        VIR_DEBUG("disk(%zu) type:       %d", i, type);
3926 3927
        VIR_DEBUG("disk(%zu) device:     %d", i, def->disks[i]->device);
        VIR_DEBUG("disk(%zu) bus:        %d", i, def->disks[i]->bus);
3928
        VIR_DEBUG("disk(%zu) src:        %s", i, src);
3929
        VIR_DEBUG("disk(%zu) dst:        %s", i, def->disks[i]->dst);
3930 3931
        VIR_DEBUG("disk(%zu) driverName: %s", i,
                  virDomainDiskGetDriver(def->disks[i]));
3932
        VIR_DEBUG("disk(%zu) driverType: %s", i,
3933
                  virStorageFileFormatTypeToString(format));
3934
        VIR_DEBUG("disk(%zu) cachemode:  %d", i, def->disks[i]->cachemode);
3935
        VIR_DEBUG("disk(%zu) readonly:   %s", i, (def->disks[i]->src->readonly
E
Eric Blake 已提交
3936
                                             ? "True" : "False"));
3937
        VIR_DEBUG("disk(%zu) shared:     %s", i, (def->disks[i]->src->shared
E
Eric Blake 已提交
3938 3939
                                             ? "True" : "False"));

E
Eric Blake 已提交
3940
        if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
3941 3942 3943 3944 3945
            IMedium   *medium          = NULL;
            PRUnichar *mediumUUID      = NULL;
            PRUnichar *mediumFileUtf16 = NULL;
            PRUint32   storageBus      = StorageBus_Null;
            PRUint32   deviceType      = DeviceType_Null;
3946
# if VBOX_API_VERSION >= 4000000
3947
            PRUint32   accessMode      = AccessMode_ReadOnly;
3948
# endif
E
Eric Blake 已提交
3949 3950 3951 3952
            PRInt32    deviceInst      = 0;
            PRInt32    devicePort      = 0;
            PRInt32    deviceSlot      = 0;

3953
            VBOX_UTF8_TO_UTF16(src, &mediumFileUtf16);
E
Eric Blake 已提交
3954 3955 3956

            if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                deviceType = DeviceType_HardDisk;
3957
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
3958 3959
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj,
                                                  mediumFileUtf16, &medium);
3960 3961
# else
                accessMode = AccessMode_ReadWrite;
3962
# endif
E
Eric Blake 已提交
3963 3964
            } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                deviceType = DeviceType_DVD;
3965
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
3966 3967
                data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                  mediumFileUtf16, &medium);
3968 3969
# else
                accessMode = AccessMode_ReadOnly;
3970
# endif
E
Eric Blake 已提交
3971 3972
            } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                deviceType = DeviceType_Floppy;
3973
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
3974 3975
                data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                     mediumFileUtf16, &medium);
3976 3977
# else
                accessMode = AccessMode_ReadWrite;
3978
# endif
E
Eric Blake 已提交
3979 3980 3981 3982
            } else {
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
3983

3984
# if VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
3985 3986
            data->vboxObj->vtbl->FindMedium(data->vboxObj, mediumFileUtf16,
                                            deviceType, &medium);
3987
# elif VBOX_API_VERSION >= 4002000
3988 3989
            data->vboxObj->vtbl->OpenMedium(data->vboxObj, mediumFileUtf16,
                                            deviceType, accessMode, PR_FALSE, &medium);
3990 3991
# endif

E
Eric Blake 已提交
3992 3993
            if (!medium) {
                PRUnichar *mediumEmpty = NULL;
3994

E
Eric Blake 已提交
3995
                VBOX_UTF8_TO_UTF16("", &mediumEmpty);
3996

3997
# if VBOX_API_VERSION < 4000000
3998
                if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
3999 4000 4001 4002 4003 4004 4005 4006
                    rc = data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                           mediumFileUtf16,
                                                           AccessMode_ReadWrite,
                                                           false,
                                                           mediumEmpty,
                                                           false,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
4007 4008
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_CDROM) {
4009 4010 4011 4012
                    rc = data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                           mediumFileUtf16,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
4013 4014
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
4015 4016 4017 4018 4019 4020
                    rc = data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                              mediumFileUtf16,
                                                              mediumEmpty,
                                                              &medium);
                } else {
                    rc = 0;
4021
                }
4022
# elif VBOX_API_VERSION == 4000000
4023 4024 4025 4026
                rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                     mediumFileUtf16,
                                                     deviceType, accessMode,
                                                     &medium);
4027
# elif VBOX_API_VERSION >= 4001000
4028 4029 4030 4031 4032
                rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                     mediumFileUtf16,
                                                     deviceType, accessMode,
                                                     false,
                                                     &medium);
4033
# endif /* VBOX_API_VERSION >= 4001000 */
4034

E
Eric Blake 已提交
4035 4036
                VBOX_UTF16_FREE(mediumEmpty);
            }
4037

E
Eric Blake 已提交
4038
            if (!medium) {
4039 4040 4041
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to attach the following disk/dvd/floppy "
                                 "to the machine: %s, rc=%08x"),
4042
                               src, (unsigned)rc);
E
Eric Blake 已提交
4043 4044 4045
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
4046

E
Eric Blake 已提交
4047 4048
            rc = medium->vtbl->GetId(medium, &mediumUUID);
            if (NS_FAILED(rc)) {
4049 4050 4051
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("can't get the uuid of the file to be attached "
                                 "as harddisk/dvd/floppy: %s, rc=%08x"),
4052
                               src, (unsigned)rc);
E
Eric Blake 已提交
4053 4054 4055 4056
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
4057

E
Eric Blake 已提交
4058
            if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
4059
                if (def->disks[i]->src->readonly) {
E
Eric Blake 已提交
4060
                    medium->vtbl->SetType(medium, MediumType_Immutable);
4061
                    VIR_DEBUG("setting harddisk to immutable");
4062
                } else if (!def->disks[i]->src->readonly) {
E
Eric Blake 已提交
4063
                    medium->vtbl->SetType(medium, MediumType_Normal);
4064
                    VIR_DEBUG("setting harddisk type to normal");
4065
                }
E
Eric Blake 已提交
4066
            }
4067

E
Eric Blake 已提交
4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080
            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;
            }
4081

E
Eric Blake 已提交
4082 4083 4084 4085 4086 4087 4088 4089
            /* get the device details i.e instance, port and slot */
            if (!vboxGetDeviceDetails(def->disks[i]->dst,
                                      maxPortPerInst,
                                      maxSlotPerPort,
                                      storageBus,
                                      &deviceInst,
                                      &devicePort,
                                      &deviceSlot)) {
4090
                virReportError(VIR_ERR_INTERNAL_ERROR,
4091 4092 4093
                               _("can't get the port/slot number of "
                                 "harddisk/dvd/floppy to be attached: "
                                 "%s, rc=%08x"),
4094
                               src, (unsigned)rc);
4095 4096 4097
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumUUID);
                VBOX_UTF16_FREE(mediumFileUtf16);
E
Eric Blake 已提交
4098 4099 4100 4101 4102 4103 4104 4105 4106
                continue;
            }

            /* attach the harddisk/dvd/Floppy to the storage controller */
            rc = machine->vtbl->AttachDevice(machine,
                                             storageCtlName,
                                             devicePort,
                                             deviceSlot,
                                             deviceType,
4107
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
4108
                                             mediumUUID);
4109
# else /* VBOX_API_VERSION >= 4000000 */
4110
                                             medium);
4111
# endif /* VBOX_API_VERSION >= 4000000 */
E
Eric Blake 已提交
4112 4113

            if (NS_FAILED(rc)) {
4114
                virReportError(VIR_ERR_INTERNAL_ERROR,
4115 4116
                               _("could not attach the file as "
                                 "harddisk/dvd/floppy: %s, rc=%08x"),
4117
                               src, (unsigned)rc);
E
Eric Blake 已提交
4118 4119
            } else {
                DEBUGIID("Attached HDD/DVD/Floppy with UUID", mediumUUID);
4120
            }
E
Eric Blake 已提交
4121 4122 4123 4124 4125

            VBOX_RELEASE(medium);
            VBOX_UTF16_FREE(mediumUUID);
            VBOX_UTF16_FREE(mediumFileUtf16);
            VBOX_UTF16_FREE(storageCtlName);
4126 4127
        }
    }
4128
#endif /* VBOX_API_VERSION >= 3001000 */
E
Eric Blake 已提交
4129
}
4130

E
Eric Blake 已提交
4131 4132 4133 4134
static void
vboxAttachSound(virDomainDefPtr def, IMachine *machine)
{
    nsresult rc;
4135

E
Eric Blake 已提交
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
    /* 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);
4152
                }
4153
            }
E
Eric Blake 已提交
4154
            VBOX_RELEASE(audioAdapter);
4155
        }
E
Eric Blake 已提交
4156 4157 4158 4159 4160 4161 4162
    }
}

static void
vboxAttachNetwork(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
4163
#if VBOX_API_VERSION >= 4001000
4164
    PRUint32 chipsetType                = ChipsetType_Null;
4165
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4166
    PRUint32 networkAdapterCount        = 0;
4167
    size_t i = 0;
E
Eric Blake 已提交
4168

4169
#if VBOX_API_VERSION >= 4001000
4170
    machine->vtbl->GetChipsetType(machine, &chipsetType);
4171
#endif /* VBOX_API_VERSION >= 4001000 */
4172

E
Eric Blake 已提交
4173 4174
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
4175
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4176 4177
        systemProperties->vtbl->GetNetworkAdapterCount(systemProperties,
                                                       &networkAdapterCount);
4178
#else  /* VBOX_API_VERSION >= 4000000 */
4179 4180
        systemProperties->vtbl->GetMaxNetworkAdapters(systemProperties, chipsetType,
                                                      &networkAdapterCount);
4181
#endif /* VBOX_API_VERSION >= 4000000 */
E
Eric Blake 已提交
4182 4183 4184 4185
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }

4186
    VIR_DEBUG("Number of Network Cards to be connected: %zu", def->nnets);
4187
    VIR_DEBUG("Number of Network Cards available: %d", networkAdapterCount);
E
Eric Blake 已提交
4188 4189 4190 4191 4192 4193 4194

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

4195
        virMacAddrFormat(&def->nets[i]->mac, macaddr);
E
Eric Blake 已提交
4196 4197
        snprintf(macaddrvbox, VIR_MAC_STRING_BUFLEN - 5,
                 "%02X%02X%02X%02X%02X%02X",
4198 4199 4200 4201 4202 4203
                 def->nets[i]->mac.addr[0],
                 def->nets[i]->mac.addr[1],
                 def->nets[i]->mac.addr[2],
                 def->nets[i]->mac.addr[3],
                 def->nets[i]->mac.addr[4],
                 def->nets[i]->mac.addr[5]);
E
Eric Blake 已提交
4204 4205
        macaddrvbox[VIR_MAC_STRING_BUFLEN - 6] = '\0';

4206 4207 4208 4209
        VIR_DEBUG("NIC(%zu): Type:   %d", i, def->nets[i]->type);
        VIR_DEBUG("NIC(%zu): Model:  %s", i, def->nets[i]->model);
        VIR_DEBUG("NIC(%zu): Mac:    %s", i, macaddr);
        VIR_DEBUG("NIC(%zu): ifname: %s", i, def->nets[i]->ifname);
E
Eric Blake 已提交
4210
        if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
4211
            VIR_DEBUG("NIC(%zu): name:    %s", i, def->nets[i]->data.network.name);
E
Eric Blake 已提交
4212
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
4213
            VIR_DEBUG("NIC(%zu): name:   %s", i, def->nets[i]->data.internal.name);
E
Eric Blake 已提交
4214
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
4215
            VIR_DEBUG("NIC(%zu): NAT.", i);
E
Eric Blake 已提交
4216
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
4217 4218 4219
            VIR_DEBUG("NIC(%zu): brname: %s", i, def->nets[i]->data.bridge.brname);
            VIR_DEBUG("NIC(%zu): script: %s", i, def->nets[i]->script);
            VIR_DEBUG("NIC(%zu): ipaddr: %s", i, def->nets[i]->data.bridge.ipaddr);
4220 4221
        }

E
Eric Blake 已提交
4222 4223 4224 4225 4226
        machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
        if (adapter) {
            PRUnichar *MACAddress = NULL;

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

E
Eric Blake 已提交
4228
            if (def->nets[i]->model) {
E
Eric Blake 已提交
4229
                if (STRCASEEQ(def->nets[i]->model, "Am79C970A")) {
E
Eric Blake 已提交
4230
                    adapterType = NetworkAdapterType_Am79C970A;
E
Eric Blake 已提交
4231
                } else if (STRCASEEQ(def->nets[i]->model, "Am79C973")) {
E
Eric Blake 已提交
4232
                    adapterType = NetworkAdapterType_Am79C973;
E
Eric Blake 已提交
4233
                } else if (STRCASEEQ(def->nets[i]->model, "82540EM")) {
E
Eric Blake 已提交
4234
                    adapterType = NetworkAdapterType_I82540EM;
E
Eric Blake 已提交
4235
                } else if (STRCASEEQ(def->nets[i]->model, "82545EM")) {
E
Eric Blake 已提交
4236
                    adapterType = NetworkAdapterType_I82545EM;
E
Eric Blake 已提交
4237
                } else if (STRCASEEQ(def->nets[i]->model, "82543GC")) {
E
Eric Blake 已提交
4238
                    adapterType = NetworkAdapterType_I82543GC;
4239
#if VBOX_API_VERSION >= 3001000
E
Eric Blake 已提交
4240
                } else if (STRCASEEQ(def->nets[i]->model, "virtio")) {
E
Eric Blake 已提交
4241
                    adapterType = NetworkAdapterType_Virtio;
4242
#endif /* VBOX_API_VERSION >= 3001000 */
4243
                }
E
Eric Blake 已提交
4244 4245 4246
            } else {
                adapterType = NetworkAdapterType_Am79C973;
            }
4247

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

E
Eric Blake 已提交
4250 4251 4252
            if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
                PRUnichar *hostInterface = NULL;
                /* Bridged Network */
4253

4254
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4255
                adapter->vtbl->AttachToBridgedInterface(adapter);
4256
#else /* VBOX_API_VERSION >= 4001000 */
4257
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_Bridged);
4258
#endif /* VBOX_API_VERSION >= 4001000 */
4259

E
Eric Blake 已提交
4260 4261 4262
                if (def->nets[i]->data.bridge.brname) {
                    VBOX_UTF8_TO_UTF16(def->nets[i]->data.bridge.brname,
                                       &hostInterface);
4263
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4264
                    adapter->vtbl->SetHostInterface(adapter, hostInterface);
4265
#else /* VBOX_API_VERSION >= 4001000 */
4266
                    adapter->vtbl->SetBridgedInterface(adapter, hostInterface);
4267
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4268 4269 4270 4271 4272
                    VBOX_UTF16_FREE(hostInterface);
                }
            } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
                PRUnichar *internalNetwork = NULL;
                /* Internal Network */
4273

4274
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4275
                adapter->vtbl->AttachToInternalNetwork(adapter);
4276
#else /* VBOX_API_VERSION >= 4001000 */
4277
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_Internal);
4278
#endif /* VBOX_API_VERSION >= 4001000 */
4279

E
Eric Blake 已提交
4280 4281 4282 4283 4284
                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);
4285
                }
E
Eric Blake 已提交
4286 4287 4288 4289 4290 4291
            } 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)
                 */
4292
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4293
                adapter->vtbl->AttachToHostOnlyInterface(adapter);
4294
#else /* VBOX_API_VERSION >= 4001000 */
4295
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_HostOnly);
4296
#endif /* VBOX_API_VERSION >= 4001000 */
4297

E
Eric Blake 已提交
4298 4299 4300
                if (def->nets[i]->data.network.name) {
                    VBOX_UTF8_TO_UTF16(def->nets[i]->data.network.name,
                                       &hostInterface);
4301
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4302
                    adapter->vtbl->SetHostInterface(adapter, hostInterface);
4303
#else /* VBOX_API_VERSION >= 4001000 */
4304
                    adapter->vtbl->SetHostOnlyInterface(adapter, hostInterface);
4305
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4306 4307 4308 4309
                    VBOX_UTF16_FREE(hostInterface);
                }
            } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
                /* NAT */
4310
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4311
                adapter->vtbl->AttachToNAT(adapter);
4312
#else /* VBOX_API_VERSION >= 4001000 */
4313
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_NAT);
4314
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4315 4316 4317 4318
            } else {
                /* else always default to NAT if we don't understand
                 * what option is been passed to us
                 */
4319
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4320
                adapter->vtbl->AttachToNAT(adapter);
4321
#else /* VBOX_API_VERSION >= 4001000 */
4322
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_NAT);
4323
#endif /* VBOX_API_VERSION >= 4001000 */
4324
            }
E
Eric Blake 已提交
4325 4326 4327 4328

            VBOX_UTF8_TO_UTF16(macaddrvbox, &MACAddress);
            adapter->vtbl->SetMACAddress(adapter, MACAddress);
            VBOX_UTF16_FREE(MACAddress);
4329
        }
E
Eric Blake 已提交
4330 4331 4332 4333 4334 4335 4336 4337
    }
}

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

E
Eric Blake 已提交
4340 4341 4342 4343 4344 4345 4346
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetSerialPortCount(systemProperties,
                                                   &serialPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4347

4348
    VIR_DEBUG("Number of Serial Ports to be connected: %zu", def->nserials);
4349
    VIR_DEBUG("Number of Serial Ports available: %d", serialPortCount);
E
Eric Blake 已提交
4350 4351
    for (i = 0; (i < def->nserials) && (i < serialPortCount); i++) {
        ISerialPort *serialPort = NULL;
4352

4353 4354
        VIR_DEBUG("SerialPort(%zu): Type: %d", i, def->serials[i]->source.type);
        VIR_DEBUG("SerialPort(%zu): target.port: %d", i,
E
Eric Blake 已提交
4355
              def->serials[i]->target.port);
4356

E
Eric Blake 已提交
4357 4358 4359
        machine->vtbl->GetSerialPort(machine, i, &serialPort);
        if (serialPort) {
            PRUnichar *pathUtf16 = NULL;
4360

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

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

4390
            if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_DEV) {
E
Eric Blake 已提交
4391
                serialPort->vtbl->SetHostMode(serialPort, PortMode_HostDevice);
4392
            } else if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PIPE) {
E
Eric Blake 已提交
4393
                serialPort->vtbl->SetHostMode(serialPort, PortMode_HostPipe);
4394
#if VBOX_API_VERSION >= 3000000
4395
            } else if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_FILE) {
E
Eric Blake 已提交
4396
                serialPort->vtbl->SetHostMode(serialPort, PortMode_RawFile);
4397
#endif /* VBOX_API_VERSION >= 3000000 */
E
Eric Blake 已提交
4398 4399 4400 4401
            } else {
                serialPort->vtbl->SetHostMode(serialPort,
                                              PortMode_Disconnected);
            }
4402

E
Eric Blake 已提交
4403
            VBOX_RELEASE(serialPort);
J
John Ferlan 已提交
4404
            VBOX_UTF16_FREE(pathUtf16);
4405
        }
E
Eric Blake 已提交
4406 4407
    }
}
4408

E
Eric Blake 已提交
4409 4410 4411 4412 4413
static void
vboxAttachParallel(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 parallelPortCount          = 0;
4414
    size_t i = 0;
4415

E
Eric Blake 已提交
4416 4417 4418 4419 4420 4421 4422
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetParallelPortCount(systemProperties,
                                                     &parallelPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4423

4424
    VIR_DEBUG("Number of Parallel Ports to be connected: %zu", def->nparallels);
4425
    VIR_DEBUG("Number of Parallel Ports available: %d", parallelPortCount);
E
Eric Blake 已提交
4426 4427
    for (i = 0; (i < def->nparallels) && (i < parallelPortCount); i++) {
        IParallelPort *parallelPort = NULL;
4428

4429 4430
        VIR_DEBUG("ParallelPort(%zu): Type: %d", i, def->parallels[i]->source.type);
        VIR_DEBUG("ParallelPort(%zu): target.port: %d", i,
E
Eric Blake 已提交
4431
              def->parallels[i]->target.port);
4432

E
Eric Blake 已提交
4433 4434 4435
        machine->vtbl->GetParallelPort(machine, i, &parallelPort);
        if (parallelPort) {
            PRUnichar *pathUtf16 = NULL;
4436

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

E
Eric Blake 已提交
4439 4440 4441 4442 4443
            /* 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
             */
4444 4445 4446 4447
            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 已提交
4448 4449 4450 4451
                parallelPort->vtbl->SetPath(parallelPort, pathUtf16);
                if (i == 0) {
                    parallelPort->vtbl->SetIRQ(parallelPort, 7);
                    parallelPort->vtbl->SetIOBase(parallelPort, 888);
4452
                    VIR_DEBUG(" parallePort-%zu irq: %d, iobase 0x%x, path: %s",
4453
                          i, 7, 888, def->parallels[i]->source.data.file.path);
E
Eric Blake 已提交
4454 4455 4456
                } else if (i == 1) {
                    parallelPort->vtbl->SetIRQ(parallelPort, 5);
                    parallelPort->vtbl->SetIOBase(parallelPort, 632);
4457
                    VIR_DEBUG(" parallePort-%zu irq: %d, iobase 0x%x, path: %s",
4458
                          i, 5, 632, def->parallels[i]->source.data.file.path);
4459 4460
                }
            }
E
Eric Blake 已提交
4461 4462 4463 4464 4465 4466 4467

            /* 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);
J
John Ferlan 已提交
4468
            VBOX_UTF16_FREE(pathUtf16);
4469
        }
E
Eric Blake 已提交
4470 4471 4472 4473 4474 4475 4476 4477
    }
}

static void
vboxAttachVideo(virDomainDefPtr def, IMachine *machine)
{
    if ((def->nvideos == 1) &&
        (def->videos[0]->type == VIR_DOMAIN_VIDEO_TYPE_VBOX)) {
4478 4479
        machine->vtbl->SetVRAMSize(machine,
                                   VIR_DIV_UP(def->videos[0]->vram, 1024));
E
Eric Blake 已提交
4480 4481 4482 4483
        machine->vtbl->SetMonitorCount(machine, def->videos[0]->heads);
        if (def->videos[0]->accel) {
            machine->vtbl->SetAccelerate3DEnabled(machine,
                                                  def->videos[0]->accel->support3d);
4484
#if VBOX_API_VERSION >= 3001000
E
Eric Blake 已提交
4485 4486
            machine->vtbl->SetAccelerate2DVideoEnabled(machine,
                                                       def->videos[0]->accel->support2d);
4487
#endif /* VBOX_API_VERSION >= 3001000 */
E
Eric Blake 已提交
4488 4489
        } else {
            machine->vtbl->SetAccelerate3DEnabled(machine, 0);
4490
#if VBOX_API_VERSION >= 3001000
E
Eric Blake 已提交
4491
            machine->vtbl->SetAccelerate2DVideoEnabled(machine, 0);
4492
#endif /* VBOX_API_VERSION >= 3001000 */
4493
        }
E
Eric Blake 已提交
4494 4495
    }
}
4496

E
Eric Blake 已提交
4497 4498 4499 4500 4501 4502 4503 4504
static void
vboxAttachDisplay(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    int vrdpPresent  = 0;
    int sdlPresent   = 0;
    int guiPresent   = 0;
    char *guiDisplay = NULL;
    char *sdlDisplay = NULL;
4505
    size_t i = 0;
4506

E
Eric Blake 已提交
4507
    for (i = 0; i < def->ngraphics; i++) {
4508
#if VBOX_API_VERSION < 4000000
4509
        IVRDPServer *VRDxServer = NULL;
4510
#else /* VBOX_API_VERSION >= 4000000 */
4511
        IVRDEServer *VRDxServer = NULL;
4512
#endif /* VBOX_API_VERSION >= 4000000 */
4513

E
Eric Blake 已提交
4514 4515
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) &&
            (vrdpPresent == 0)) {
4516

E
Eric Blake 已提交
4517
            vrdpPresent = 1;
4518
#if VBOX_API_VERSION < 4000000
4519
            machine->vtbl->GetVRDPServer(machine, &VRDxServer);
4520
#else /* VBOX_API_VERSION >= 4000000 */
4521
            machine->vtbl->GetVRDEServer(machine, &VRDxServer);
4522
#endif /* VBOX_API_VERSION >= 4000000 */
4523
            if (VRDxServer) {
4524 4525 4526
                const char *listenAddr
                    = virDomainGraphicsListenGetAddress(def->graphics[i], 0);

4527
                VRDxServer->vtbl->SetEnabled(VRDxServer, PR_TRUE);
4528
                VIR_DEBUG("VRDP Support turned ON.");
4529

4530
#if VBOX_API_VERSION < 3001000
E
Eric Blake 已提交
4531
                if (def->graphics[i]->data.rdp.port) {
4532
                    VRDxServer->vtbl->SetPort(VRDxServer,
E
Eric Blake 已提交
4533
                                              def->graphics[i]->data.rdp.port);
4534
                    VIR_DEBUG("VRDP Port changed to: %d",
E
Eric Blake 已提交
4535 4536 4537 4538 4539
                          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
                     */
4540
                    VRDxServer->vtbl->SetPort(VRDxServer, 0);
4541
                    VIR_DEBUG("VRDP Port changed to default, which is 3389 currently");
E
Eric Blake 已提交
4542
                }
4543
#elif VBOX_API_VERSION < 4000000 /* 3001000 <= VBOX_API_VERSION < 4000000 */
E
Eric Blake 已提交
4544 4545
                PRUnichar *portUtf16 = NULL;
                portUtf16 = PRUnicharFromInt(def->graphics[i]->data.rdp.port);
4546
                VRDxServer->vtbl->SetPorts(VRDxServer, portUtf16);
E
Eric Blake 已提交
4547
                VBOX_UTF16_FREE(portUtf16);
4548
#else /* VBOX_API_VERSION >= 4000000 */
4549 4550 4551 4552 4553 4554 4555 4556
                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);
4557
#endif /* VBOX_API_VERSION >= 4000000 */
4558

E
Eric Blake 已提交
4559
                if (def->graphics[i]->data.rdp.replaceUser) {
4560
                    VRDxServer->vtbl->SetReuseSingleConnection(VRDxServer,
E
Eric Blake 已提交
4561
                                                               PR_TRUE);
4562
                    VIR_DEBUG("VRDP set to reuse single connection");
E
Eric Blake 已提交
4563
                }
4564

E
Eric Blake 已提交
4565
                if (def->graphics[i]->data.rdp.multiUser) {
4566
                    VRDxServer->vtbl->SetAllowMultiConnection(VRDxServer,
E
Eric Blake 已提交
4567
                                                              PR_TRUE);
4568
                    VIR_DEBUG("VRDP set to allow multiple connection");
E
Eric Blake 已提交
4569
                }
4570

4571
                if (listenAddr) {
4572
#if VBOX_API_VERSION >= 4000000
4573 4574
                    PRUnichar *netAddressKey = NULL;
#endif
E
Eric Blake 已提交
4575
                    PRUnichar *netAddressUtf16 = NULL;
4576

4577
                    VBOX_UTF8_TO_UTF16(listenAddr, &netAddressUtf16);
4578
#if VBOX_API_VERSION < 4000000
4579
                    VRDxServer->vtbl->SetNetAddress(VRDxServer,
E
Eric Blake 已提交
4580
                                                    netAddressUtf16);
4581
#else /* VBOX_API_VERSION >= 4000000 */
4582 4583 4584 4585
                    VBOX_UTF8_TO_UTF16("TCP/Address", &netAddressKey);
                    VRDxServer->vtbl->SetVRDEProperty(VRDxServer, netAddressKey,
                                                      netAddressUtf16);
                    VBOX_UTF16_FREE(netAddressKey);
4586
#endif /* VBOX_API_VERSION >= 4000000 */
4587
                    VIR_DEBUG("VRDP listen address is set to: %s",
4588
                              listenAddr);
4589

E
Eric Blake 已提交
4590
                    VBOX_UTF16_FREE(netAddressUtf16);
4591
                }
E
Eric Blake 已提交
4592

4593
                VBOX_RELEASE(VRDxServer);
4594
            }
E
Eric Blake 已提交
4595
        }
4596

E
Eric Blake 已提交
4597 4598 4599
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) &&
            (guiPresent == 0)) {
            guiPresent = 1;
4600 4601 4602 4603 4604
            if (VIR_STRDUP(guiDisplay, def->graphics[i]->data.desktop.display) < 0) {
                /* 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
                 */
4605
            }
E
Eric Blake 已提交
4606
        }
4607

E
Eric Blake 已提交
4608 4609 4610
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) &&
            (sdlPresent == 0)) {
            sdlPresent = 1;
4611 4612 4613 4614 4615
            if (VIR_STRDUP(sdlDisplay, def->graphics[i]->data.sdl.display) < 0) {
                /* 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
                 */
4616
            }
4617
        }
E
Eric Blake 已提交
4618
    }
4619

E
Eric Blake 已提交
4620 4621 4622 4623
    if ((vrdpPresent == 1) && (guiPresent == 0) && (sdlPresent == 0)) {
        /* store extradata key that frontend is set to vrdp */
        PRUnichar *keyTypeUtf16   = NULL;
        PRUnichar *valueTypeUtf16 = NULL;
4624

E
Eric Blake 已提交
4625 4626
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("vrdp", &valueTypeUtf16);
4627

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

E
Eric Blake 已提交
4630 4631
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4632

E
Eric Blake 已提交
4633 4634 4635 4636 4637 4638
    } 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;
4639

E
Eric Blake 已提交
4640 4641
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("sdl", &valueTypeUtf16);
4642

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

E
Eric Blake 已提交
4645 4646
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4647

E
Eric Blake 已提交
4648 4649 4650
        if (sdlDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(sdlDisplay, &valueDisplayUtf16);
4651

E
Eric Blake 已提交
4652 4653
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4654

E
Eric Blake 已提交
4655 4656 4657
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
        }
4658

E
Eric Blake 已提交
4659 4660 4661 4662 4663 4664
    } 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;
4665

E
Eric Blake 已提交
4666 4667
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("gui", &valueTypeUtf16);
4668

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

E
Eric Blake 已提交
4671 4672
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4673

E
Eric Blake 已提交
4674 4675 4676
        if (guiDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(guiDisplay, &valueDisplayUtf16);
4677

E
Eric Blake 已提交
4678 4679
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4680

E
Eric Blake 已提交
4681 4682
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
4683
        }
E
Eric Blake 已提交
4684
    }
4685

E
Eric Blake 已提交
4686 4687 4688
    VIR_FREE(guiDisplay);
    VIR_FREE(sdlDisplay);
}
4689

E
Eric Blake 已提交
4690 4691 4692
static void
vboxAttachUSB(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
4693
#if VBOX_API_VERSION < 4003000
E
Eric Blake 已提交
4694
    IUSBController *USBController = NULL;
R
Ryota Ozaki 已提交
4695 4696 4697
#else
    IUSBDeviceFilters *USBDeviceFilters = NULL;
#endif
4698
    size_t i = 0;
E
Eric Blake 已提交
4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709
    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++) {
R
Ryota Ozaki 已提交
4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725
        if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;

        if (def->hostdevs[i]->source.subsys.type !=
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;

        if (!def->hostdevs[i]->source.subsys.u.usb.vendor &&
            !def->hostdevs[i]->source.subsys.u.usb.product)
            continue;

        VIR_DEBUG("USB Device detected, VendorId:0x%x, ProductId:0x%x",
                  def->hostdevs[i]->source.subsys.u.usb.vendor,
                  def->hostdevs[i]->source.subsys.u.usb.product);
        isUSB = true;
        break;
E
Eric Blake 已提交
4726 4727
    }

R
Ryota Ozaki 已提交
4728 4729 4730
    if (!isUSB)
        return;

4731
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
4732 4733 4734 4735 4736 4737 4738 4739 4740
    /* First Start the USB Controller and then loop
     * to attach USB Devices to it
     */
    machine->vtbl->GetUSBController(machine, &USBController);

    if (!USBController)
        return;

    USBController->vtbl->SetEnabled(USBController, 1);
4741
# if VBOX_API_VERSION < 4002000
R
Ryota Ozaki 已提交
4742
    USBController->vtbl->SetEnabledEhci(USBController, 1);
R
Ryota Ozaki 已提交
4743
# else
R
Ryota Ozaki 已提交
4744
    USBController->vtbl->SetEnabledEHCI(USBController, 1);
R
Ryota Ozaki 已提交
4745 4746 4747 4748 4749 4750
# endif
#else
    machine->vtbl->GetUSBDeviceFilters(machine, &USBDeviceFilters);

    if (!USBDeviceFilters)
        return;
4751
#endif
4752

R
Ryota Ozaki 已提交
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763
    for (i = 0; i < def->nhostdevs; i++) {
        char *filtername           = NULL;
        PRUnichar *filternameUtf16 = NULL;
        IUSBDeviceFilter *filter   = NULL;
        PRUnichar *vendorIdUtf16  = NULL;
        char vendorId[40]         = {0};
        PRUnichar *productIdUtf16 = NULL;
        char productId[40]        = {0};

        if (def->hostdevs[i]->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
4764

R
Ryota Ozaki 已提交
4765 4766 4767
        if (def->hostdevs[i]->source.subsys.type !=
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;
4768

R
Ryota Ozaki 已提交
4769 4770 4771 4772 4773 4774
        /* Zero pad for nice alignment when fewer than 9999
         * devices.
         */
        if (virAsprintf(&filtername, "filter%04zu", i) >= 0) {
            VBOX_UTF8_TO_UTF16(filtername, &filternameUtf16);
            VIR_FREE(filtername);
4775
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
4776 4777 4778
            USBController->vtbl->CreateDeviceFilter(USBController,
                                                    filternameUtf16,
                                                    &filter);
R
Ryota Ozaki 已提交
4779 4780 4781 4782 4783
#else
            USBDeviceFilters->vtbl->CreateDeviceFilter(USBDeviceFilters,
                                                       filternameUtf16,
                                                       &filter);
#endif
R
Ryota Ozaki 已提交
4784 4785
        }
        VBOX_UTF16_FREE(filternameUtf16);
E
Eric Blake 已提交
4786

R
Ryota Ozaki 已提交
4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807
        if (!filter)
            continue;

        if (!def->hostdevs[i]->source.subsys.u.usb.vendor &&
            !def->hostdevs[i]->source.subsys.u.usb.product)
            continue;

        if (def->hostdevs[i]->source.subsys.u.usb.vendor) {
            snprintf(vendorId, sizeof(vendorId), "%x",
                     def->hostdevs[i]->source.subsys.u.usb.vendor);
            VBOX_UTF8_TO_UTF16(vendorId, &vendorIdUtf16);
            filter->vtbl->SetVendorId(filter, vendorIdUtf16);
            VBOX_UTF16_FREE(vendorIdUtf16);
        }
        if (def->hostdevs[i]->source.subsys.u.usb.product) {
            snprintf(productId, sizeof(productId), "%x",
                     def->hostdevs[i]->source.subsys.u.usb.product);
            VBOX_UTF8_TO_UTF16(productId, &productIdUtf16);
            filter->vtbl->SetProductId(filter,
                                       productIdUtf16);
            VBOX_UTF16_FREE(productIdUtf16);
E
Eric Blake 已提交
4808
        }
R
Ryota Ozaki 已提交
4809
        filter->vtbl->SetActive(filter, 1);
4810
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
4811 4812 4813
        USBController->vtbl->InsertDeviceFilter(USBController,
                                                i,
                                                filter);
R
Ryota Ozaki 已提交
4814 4815 4816 4817 4818
#else
        USBDeviceFilters->vtbl->InsertDeviceFilter(USBDeviceFilters,
                                                   i,
                                                   filter);
#endif
R
Ryota Ozaki 已提交
4819
        VBOX_RELEASE(filter);
E
Eric Blake 已提交
4820
    }
R
Ryota Ozaki 已提交
4821

4822
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
4823
    VBOX_RELEASE(USBController);
R
Ryota Ozaki 已提交
4824 4825 4826
#else
    VBOX_RELEASE(USBDeviceFilters);
#endif
E
Eric Blake 已提交
4827 4828
}

M
Matthias Bolte 已提交
4829 4830 4831
static void
vboxAttachSharedFolder(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
4832
    size_t i;
M
Matthias Bolte 已提交
4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847
    PRUnichar *nameUtf16;
    PRUnichar *hostPathUtf16;
    PRBool writable;

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

    for (i = 0; i < def->nfss; i++) {
        if (def->fss[i]->type != VIR_DOMAIN_FS_TYPE_MOUNT)
            continue;

        VBOX_UTF8_TO_UTF16(def->fss[i]->dst, &nameUtf16);
        VBOX_UTF8_TO_UTF16(def->fss[i]->src, &hostPathUtf16);
        writable = !def->fss[i]->readonly;

4848
#if VBOX_API_VERSION < 4000000
M
Matthias Bolte 已提交
4849 4850
        machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                          writable);
4851
#else /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
4852 4853
        machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                          writable, PR_FALSE);
4854
#endif /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
4855 4856 4857 4858 4859 4860

        VBOX_UTF16_FREE(nameUtf16);
        VBOX_UTF16_FREE(hostPathUtf16);
    }
}

4861 4862
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml)
{
E
Eric Blake 已提交
4863 4864 4865
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
    IMachine       *machine     = NULL;
    IBIOSSettings  *bios        = NULL;
4866 4867
    vboxIID iid = VBOX_IID_INITIALIZER;
    vboxIID mchiid = VBOX_IID_INITIALIZER;
E
Eric Blake 已提交
4868 4869
    virDomainDefPtr def         = NULL;
    PRUnichar *machineNameUtf16 = NULL;
4870
#if VBOX_API_VERSION >= 3002000 && VBOX_API_VERSION < 4002000
E
Eric Blake 已提交
4871 4872 4873
    PRBool override             = PR_FALSE;
#endif
    nsresult rc;
4874
    char uuidstr[VIR_UUID_STRING_BUFLEN];
4875
#if VBOX_API_VERSION >= 4002000
4876 4877 4878 4879 4880 4881
    const char *flagsUUIDPrefix = "UUID=";
    const char *flagsForceOverwrite = "forceOverwrite=0";
    const char *flagsSeparator = ",";
    char createFlags[strlen(flagsUUIDPrefix) + VIR_UUID_STRING_BUFLEN + strlen(flagsSeparator) + strlen(flagsForceOverwrite) + 1];
    PRUnichar *createFlagsUtf16 = NULL;
#endif
E
Eric Blake 已提交
4882

4883 4884
    if (!(def = virDomainDefParseString(xml, data->caps, data->xmlopt,
                                        1 << VIR_DOMAIN_VIRT_VBOX,
E
Eric Blake 已提交
4885 4886 4887 4888 4889
                                        VIR_DOMAIN_XML_INACTIVE))) {
        goto cleanup;
    }

    VBOX_UTF8_TO_UTF16(def->name, &machineNameUtf16);
4890
    vboxIIDFromUUID(&iid, def->uuid);
4891 4892
    virUUIDFormat(def->uuid, uuidstr);

4893
#if VBOX_API_VERSION < 3002000
E
Eric Blake 已提交
4894 4895 4896 4897
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
4898
                                            iid.value,
E
Eric Blake 已提交
4899
                                            &machine);
4900
#elif VBOX_API_VERSION < 4000000 /* 3002000 <= VBOX_API_VERSION < 4000000 */
E
Eric Blake 已提交
4901 4902 4903 4904
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
4905
                                            iid.value,
E
Eric Blake 已提交
4906 4907
                                            override,
                                            &machine);
4908
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
4909 4910 4911 4912 4913 4914 4915
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            NULL,
                                            machineNameUtf16,
                                            NULL,
                                            iid.value,
                                            override,
                                            &machine);
4916
#else /* VBOX_API_VERSION >= 4002000 */
4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931
    snprintf(createFlags, sizeof(createFlags), "%s%s%s%s",
             flagsUUIDPrefix,
             uuidstr,
             flagsSeparator,
             flagsForceOverwrite
            );
    VBOX_UTF8_TO_UTF16(createFlags, &createFlagsUtf16);
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            NULL,
                                            machineNameUtf16,
                                            0,
                                            nsnull,
                                            nsnull,
                                            createFlagsUtf16,
                                            &machine);
4932
#endif /* VBOX_API_VERSION >= 4002000 */
E
Eric Blake 已提交
4933 4934 4935
    VBOX_UTF16_FREE(machineNameUtf16);

    if (NS_FAILED(rc)) {
4936 4937
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not define a domain, rc=%08x"), (unsigned)rc);
E
Eric Blake 已提交
4938 4939 4940
        goto cleanup;
    }

4941 4942
    rc = machine->vtbl->SetMemorySize(machine,
                                      VIR_DIV_UP(def->mem.cur_balloon, 1024));
E
Eric Blake 已提交
4943
    if (NS_FAILED(rc)) {
4944 4945 4946 4947
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not set the memory size of the domain to: %llu Kb, "
                         "rc=%08x"),
                       def->mem.cur_balloon, (unsigned)rc);
E
Eric Blake 已提交
4948 4949
    }

E
Eric Blake 已提交
4950
    if (def->vcpus != def->maxvcpus) {
4951 4952
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("current vcpu count must equal maximum"));
E
Eric Blake 已提交
4953 4954
    }
    rc = machine->vtbl->SetCPUCount(machine, def->maxvcpus);
E
Eric Blake 已提交
4955
    if (NS_FAILED(rc)) {
4956 4957 4958
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not set the number of virtual CPUs to: %u, rc=%08x"),
                       def->maxvcpus, (unsigned)rc);
E
Eric Blake 已提交
4959 4960
    }

4961
#if VBOX_API_VERSION < 3001000
4962 4963
    rc = machine->vtbl->SetPAEEnabled(machine,
                                      def->features[VIR_DOMAIN_FEATURE_PAE] ==
J
Ján Tomko 已提交
4964
                                      VIR_TRISTATE_SWITCH_ON);
4965
#elif VBOX_API_VERSION == 3001000
E
Eric Blake 已提交
4966
    rc = machine->vtbl->SetCpuProperty(machine, CpuPropertyType_PAE,
4967
                                       def->features[VIR_DOMAIN_FEATURE_PAE] ==
J
Ján Tomko 已提交
4968
                                       VIR_TRISTATE_SWITCH_ON);
4969
#elif VBOX_API_VERSION >= 3002000
E
Eric Blake 已提交
4970
    rc = machine->vtbl->SetCPUProperty(machine, CPUPropertyType_PAE,
4971
                                       def->features[VIR_DOMAIN_FEATURE_PAE] ==
J
Ján Tomko 已提交
4972
                                       VIR_TRISTATE_SWITCH_ON);
E
Eric Blake 已提交
4973 4974
#endif
    if (NS_FAILED(rc)) {
4975 4976
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not change PAE status to: %s, rc=%08x"),
J
Ján Tomko 已提交
4977
                       (def->features[VIR_DOMAIN_FEATURE_PAE] == VIR_TRISTATE_SWITCH_ON)
4978
                       ? _("Enabled") : _("Disabled"), (unsigned)rc);
E
Eric Blake 已提交
4979 4980 4981 4982
    }

    machine->vtbl->GetBIOSSettings(machine, &bios);
    if (bios) {
4983 4984
        rc = bios->vtbl->SetACPIEnabled(bios,
                                        def->features[VIR_DOMAIN_FEATURE_ACPI] ==
J
Ján Tomko 已提交
4985
                                        VIR_TRISTATE_SWITCH_ON);
E
Eric Blake 已提交
4986
        if (NS_FAILED(rc)) {
4987 4988
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not change ACPI status to: %s, rc=%08x"),
J
Ján Tomko 已提交
4989
                           (def->features[VIR_DOMAIN_FEATURE_ACPI] == VIR_TRISTATE_SWITCH_ON)
4990
                           ? _("Enabled") : _("Disabled"), (unsigned)rc);
E
Eric Blake 已提交
4991
        }
4992 4993
        rc = bios->vtbl->SetIOAPICEnabled(bios,
                                          def->features[VIR_DOMAIN_FEATURE_APIC] ==
J
Ján Tomko 已提交
4994
                                          VIR_TRISTATE_SWITCH_ON);
E
Eric Blake 已提交
4995
        if (NS_FAILED(rc)) {
4996 4997
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not change APIC status to: %s, rc=%08x"),
J
Ján Tomko 已提交
4998
                           (def->features[VIR_DOMAIN_FEATURE_APIC] == VIR_TRISTATE_SWITCH_ON)
4999
                           ? _("Enabled") : _("Disabled"), (unsigned)rc);
5000
        }
E
Eric Blake 已提交
5001 5002 5003 5004 5005 5006
        VBOX_RELEASE(bios);
    }

    /* Register the machine before attaching other devices to it */
    rc = data->vboxObj->vtbl->RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
5007 5008
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not define a domain, rc=%08x"), (unsigned)rc);
E
Eric Blake 已提交
5009 5010 5011 5012 5013 5014 5015
        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
     */
5016
    machine->vtbl->GetId(machine, &mchiid.value);
5017
    VBOX_SESSION_OPEN(mchiid.value, machine);
E
Eric Blake 已提交
5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028
    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);
M
Matthias Bolte 已提交
5029
    vboxAttachSharedFolder(def, data, machine);
5030

5031 5032 5033 5034
    /* Save the machine settings made till now and close the
     * session. also free up the mchiid variable used.
     */
    rc = machine->vtbl->SaveSettings(machine);
5035
    VBOX_SESSION_CLOSE();
5036
    vboxIIDUnalloc(&mchiid);
5037

5038 5039
    ret = virGetDomain(conn, def->name, def->uuid);
    VBOX_RELEASE(machine);
5040

5041
    vboxIIDUnalloc(&iid);
5042 5043
    virDomainDefFree(def);

5044
    return ret;
5045

5046
 cleanup:
5047
    VBOX_RELEASE(machine);
5048
    vboxIIDUnalloc(&iid);
5049 5050 5051 5052
    virDomainDefFree(def);
    return NULL;
}

5053
static int
5054
vboxDomainUndefineFlags(virDomainPtr dom, unsigned int flags)
5055
{
5056
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5057
    IMachine *machine    = NULL;
5058
    vboxIID iid = VBOX_IID_INITIALIZER;
5059
    nsresult rc;
5060
#if VBOX_API_VERSION >= 4000000
5061 5062
    vboxArray media = VBOX_ARRAY_INITIALIZER;
#endif
5063 5064 5065 5066
    /* No managed save, so we explicitly reject
     * VIR_DOMAIN_UNDEFINE_MANAGED_SAVE.  No snapshot metadata for
     * VBox, so we can trivially ignore that flag.  */
    virCheckFlags(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA, -1);
5067

5068
    vboxIIDFromUUID(&iid, dom->uuid);
5069

5070
#if VBOX_API_VERSION < 4000000
5071 5072 5073
    /* 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
5074 5075 5076 5077
     * 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.
5078 5079 5080
     */
    {
        PRUnichar *hddcnameUtf16 = NULL;
5081

5082 5083
        char *hddcname;
        ignore_value(VIR_STRDUP(hddcname, "IDE"));
5084 5085
        VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16);
        VIR_FREE(hddcname);
5086

5087
        /* Open a Session for the machine */
5088
        rc = VBOX_SESSION_OPEN(iid.value, machine);
5089 5090 5091 5092
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {

5093
# if VBOX_API_VERSION < 3001000
5094 5095 5096 5097
                /* 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);
5098
# else  /* VBOX_API_VERSION >= 3001000 */
5099 5100 5101
                /* get all the controller first, then the attachments and
                 * remove them all so that the machine can be undefined
                 */
5102
                vboxArray storageControllers = VBOX_ARRAY_INITIALIZER;
5103
                size_t i = 0, j = 0;
5104

5105 5106
                vboxArrayGet(&storageControllers, machine,
                             machine->vtbl->GetStorageControllers);
5107

5108 5109
                for (i = 0; i < storageControllers.count; i++) {
                    IStorageController *strCtl = storageControllers.items[i];
5110
                    PRUnichar *strCtlName = NULL;
5111
                    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
5112 5113 5114 5115 5116

                    if (!strCtl)
                        continue;

                    strCtl->vtbl->GetName(strCtl, &strCtlName);
5117 5118 5119
                    vboxArrayGetWithPtrArg(&mediumAttachments, machine,
                                           machine->vtbl->GetMediumAttachmentsOfController,
                                           strCtlName);
5120

5121 5122
                    for (j = 0; j < mediumAttachments.count; j++) {
                        IMediumAttachment *medAtt = mediumAttachments.items[j];
5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
                        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);
                        }
                    }
5139

5140 5141
                    vboxArrayRelease(&storageControllers);

5142 5143
                    machine->vtbl->RemoveStorageController(machine, strCtlName);
                    VBOX_UTF16_FREE(strCtlName);
5144
                }
5145 5146

                vboxArrayRelease(&storageControllers);
5147
# endif /* VBOX_API_VERSION >= 3001000 */
5148 5149

                machine->vtbl->SaveSettings(machine);
5150
            }
5151
            VBOX_SESSION_CLOSE();
5152
        }
5153 5154
        VBOX_UTF16_FREE(hddcnameUtf16);
    }
5155
#endif
5156

5157
#if VBOX_API_VERSION < 4000000
5158
    rc = data->vboxObj->vtbl->UnregisterMachine(data->vboxObj, iid.value, &machine);
5159
#else /* VBOX_API_VERSION >= 4000000 */
5160 5161
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
5162 5163
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
5164 5165 5166 5167 5168 5169 5170 5171 5172
        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);
5173
#endif /* VBOX_API_VERSION >= 4000000 */
5174
    DEBUGIID("UUID of machine being undefined", iid.value);
5175

5176
    if (NS_SUCCEEDED(rc)) {
5177
#if VBOX_API_VERSION < 4000000
5178
        machine->vtbl->DeleteSettings(machine);
5179
#else /* VBOX_API_VERSION >= 4000000 */
5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
        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);

5193
#  if VBOX_API_VERSION < 4003000
5194
        ((IMachine_Delete)machine->vtbl->Delete)(machine, &safeArray, &progress);
R
Ryota Ozaki 已提交
5195 5196 5197
#  else
        ((IMachine_Delete)machine->vtbl->DeleteConfig)(machine, &safeArray, &progress);
#  endif
5198
# else
5199 5200 5201
        /* XPCOM doesn't like NULL as an array, even when the array size is 0.
         * Instead pass it a dummy array to avoid passing NULL. */
        IMedium *array[] = { NULL };
5202
#  if VBOX_API_VERSION < 4003000
5203
        machine->vtbl->Delete(machine, 0, array, &progress);
R
Ryota Ozaki 已提交
5204 5205 5206
#  else
        machine->vtbl->DeleteConfig(machine, 0, array, &progress);
#  endif
5207 5208 5209 5210 5211
# endif
        if (progress != NULL) {
            progress->vtbl->WaitForCompletion(progress, -1);
            VBOX_RELEASE(progress);
        }
5212
#endif /* VBOX_API_VERSION >= 4000000 */
5213 5214
        ret = 0;
    } else {
5215 5216
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not delete the domain, rc=%08x"), (unsigned)rc);
5217 5218
    }

5219
#if VBOX_API_VERSION >= 4000000
5220 5221
    vboxArrayUnalloc(&media);
#endif
5222
    vboxIIDUnalloc(&iid);
5223
    VBOX_RELEASE(machine);
5224 5225 5226 5227

    return ret;
}

5228 5229 5230 5231 5232 5233
static int
vboxDomainUndefine(virDomainPtr dom)
{
    return vboxDomainUndefineFlags(dom, 0);
}

5234 5235
static int vboxDomainAttachDeviceImpl(virDomainPtr dom,
                                      const char *xml,
5236 5237
                                      int mediaChangeOnly ATTRIBUTE_UNUSED)
{
5238
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5239
    IMachine *machine    = NULL;
5240
    vboxIID iid = VBOX_IID_INITIALIZER;
5241 5242 5243
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5244
    nsresult rc;
5245

5246
    if (VIR_ALLOC(def) < 0)
5247 5248
        return ret;

5249
    if (VIR_STRDUP(def->os.type, "hvm") < 0)
5250 5251
        goto cleanup;

5252 5253
    dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt,
                                  VIR_DOMAIN_XML_INACTIVE);
5254
    if (dev == NULL)
5255 5256
        goto cleanup;

5257
    vboxIIDFromUUID(&iid, dom->uuid);
5258
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5259
    if (NS_FAILED(rc)) {
5260 5261
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
5262 5263
        goto cleanup;
    }
5264

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

5268 5269
        if ((state == MachineState_Running) ||
            (state == MachineState_Paused)) {
5270
            rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
5271
        } else {
5272
            rc = VBOX_SESSION_OPEN(iid.value, machine);
5273 5274 5275 5276 5277
        }
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
                if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
5278
#if VBOX_API_VERSION < 3001000
5279 5280 5281
                    const char *src = virDomainDiskGetSource(dev->data.disk);
                    int type = virDomainDiskGetType(dev->data.disk);

5282
                    if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
E
Eric Blake 已提交
5283
                        if (type == VIR_STORAGE_TYPE_FILE && src) {
5284 5285 5286 5287 5288 5289 5290 5291 5292
                            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;
5293 5294
                                vboxIID dvduuid = VBOX_IID_INITIALIZER;
                                vboxIID dvdemptyuuid = VBOX_IID_INITIALIZER;
5295

5296
                                VBOX_UTF8_TO_UTF16(src, &dvdfileUtf16);
5297

5298 5299
                                data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                if (!dvdImage) {
5300
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, dvdemptyuuid.value, &dvdImage);
5301 5302
                                }
                                if (dvdImage) {
5303
                                    rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage, &dvduuid.value);
5304
                                    if (NS_FAILED(rc)) {
5305 5306 5307
                                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                                       _("can't get the uuid of the file to "
                                                         "be attached to cdrom: %s, rc=%08x"),
5308
                                                       src, (unsigned)rc);
5309 5310 5311
                                    } else {
                                        /* unmount the previous mounted image */
                                        dvdDrive->vtbl->Unmount(dvdDrive);
5312
                                        rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid.value);
5313
                                        if (NS_FAILED(rc)) {
5314 5315
                                            virReportError(VIR_ERR_INTERNAL_ERROR,
                                                           _("could not attach the file to cdrom: %s, rc=%08x"),
5316
                                                           src, (unsigned)rc);
5317
                                        } else {
5318
                                            ret = 0;
5319
                                            DEBUGIID("CD/DVD Image UUID:", dvduuid.value);
5320 5321
                                        }
                                    }
5322 5323

                                    VBOX_MEDIUM_RELEASE(dvdImage);
5324
                                }
5325
                                vboxIIDUnalloc(&dvduuid);
5326 5327
                                VBOX_UTF16_FREE(dvdfileUtf16);
                                VBOX_RELEASE(dvdDrive);
5328
                            }
E
Eric Blake 已提交
5329
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5330 5331
                        }
                    } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
E
Eric Blake 已提交
5332
                        if (type == VIR_STORAGE_TYPE_FILE && src) {
5333 5334 5335 5336 5337 5338 5339
                            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;
5340 5341
                                    vboxIID fduuid = VBOX_IID_INITIALIZER;
                                    vboxIID fdemptyuuid = VBOX_IID_INITIALIZER;
5342
                                    VBOX_UTF8_TO_UTF16(src, &fdfileUtf16);
5343 5344 5345 5346 5347 5348 5349
                                    rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                              fdfileUtf16,
                                                                              &floppyImage);

                                    if (!floppyImage) {
                                        data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                             fdfileUtf16,
5350
                                                                             fdemptyuuid.value,
5351 5352
                                                                             &floppyImage);
                                    }
5353

5354
                                    if (floppyImage) {
5355
                                        rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage, &fduuid.value);
5356
                                        if (NS_FAILED(rc)) {
5357 5358 5359
                                            virReportError(VIR_ERR_INTERNAL_ERROR,
                                                           _("can't get the uuid of the file to be "
                                                             "attached to floppy drive: %s, rc=%08x"),
5360
                                                           src, (unsigned)rc);
5361
                                        } else {
5362
                                            rc = floppyDrive->vtbl->MountImage(floppyDrive, fduuid.value);
5363
                                            if (NS_FAILED(rc)) {
5364 5365
                                                virReportError(VIR_ERR_INTERNAL_ERROR,
                                                               _("could not attach the file to floppy drive: %s, rc=%08x"),
5366
                                                               src, (unsigned)rc);
5367
                                            } else {
5368
                                                ret = 0;
5369
                                                DEBUGIID("attached floppy, UUID:", fduuid.value);
5370 5371
                                            }
                                        }
5372
                                        VBOX_MEDIUM_RELEASE(floppyImage);
5373
                                    }
5374
                                    vboxIIDUnalloc(&fduuid);
5375
                                    VBOX_UTF16_FREE(fdfileUtf16);
5376
                                }
5377
                                VBOX_RELEASE(floppyDrive);
5378
                            }
E
Eric Blake 已提交
5379
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5380
                        }
5381
                    }
5382 5383
#else  /* VBOX_API_VERSION >= 3001000 */
#endif /* VBOX_API_VERSION >= 3001000 */
5384 5385 5386 5387
                } 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) {
5388 5389
                        }
                    }
M
Matthias Bolte 已提交
5390 5391 5392 5393 5394 5395 5396 5397 5398 5399
                } else if (dev->type == VIR_DOMAIN_DEVICE_FS &&
                           dev->data.fs->type == VIR_DOMAIN_FS_TYPE_MOUNT) {
                    PRUnichar *nameUtf16;
                    PRUnichar *hostPathUtf16;
                    PRBool writable;

                    VBOX_UTF8_TO_UTF16(dev->data.fs->dst, &nameUtf16);
                    VBOX_UTF8_TO_UTF16(dev->data.fs->src, &hostPathUtf16);
                    writable = !dev->data.fs->readonly;

5400
#if VBOX_API_VERSION < 4000000
M
Matthias Bolte 已提交
5401 5402
                    rc = machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                                           writable);
5403
#else /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
5404 5405
                    rc = machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                                           writable, PR_FALSE);
5406
#endif /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
5407 5408

                    if (NS_FAILED(rc)) {
5409 5410 5411
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("could not attach shared folder '%s', rc=%08x"),
                                       dev->data.fs->dst, (unsigned)rc);
M
Matthias Bolte 已提交
5412 5413 5414 5415 5416 5417
                    } else {
                        ret = 0;
                    }

                    VBOX_UTF16_FREE(nameUtf16);
                    VBOX_UTF16_FREE(hostPathUtf16);
5418
                }
5419 5420
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5421
            }
5422
            VBOX_SESSION_CLOSE();
5423 5424 5425
        }
    }

5426
 cleanup:
5427
    vboxIIDUnalloc(&iid);
5428 5429 5430 5431 5432
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5433 5434
static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml)
{
5435 5436 5437
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

5438 5439 5440 5441 5442 5443
static int
vboxDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

5444
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5445 5446
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
5447 5448 5449
        return -1;
    }

5450 5451 5452 5453
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

static int vboxDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
5454 5455
                                       unsigned int flags)
{
5456 5457 5458
    virCheckFlags(VIR_DOMAIN_AFFECT_CURRENT |
                  VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5459

5460
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5461 5462
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
5463 5464 5465 5466
        return -1;
    }

    return vboxDomainAttachDeviceImpl(dom, xml, 1);
5467 5468
}

5469 5470
static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml)
{
5471
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5472
    IMachine *machine    = NULL;
5473
    vboxIID iid = VBOX_IID_INITIALIZER;
5474 5475 5476
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5477
    nsresult rc;
5478

5479
    if (VIR_ALLOC(def) < 0)
5480 5481
        return ret;

5482
    if (VIR_STRDUP(def->os.type, "hvm") < 0)
5483 5484
        goto cleanup;

5485 5486
    dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt,
                                  VIR_DOMAIN_XML_INACTIVE);
5487
    if (dev == NULL)
5488 5489
        goto cleanup;

5490
    vboxIIDFromUUID(&iid, dom->uuid);
5491
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5492
    if (NS_FAILED(rc)) {
5493 5494
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
5495 5496
        goto cleanup;
    }
5497

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

5501 5502
        if ((state == MachineState_Running) ||
            (state == MachineState_Paused)) {
5503
            rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
5504
        } else {
5505
            rc = VBOX_SESSION_OPEN(iid.value, machine);
5506
        }
5507

5508 5509 5510 5511
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
                if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
5512
#if VBOX_API_VERSION < 3001000
5513 5514
                    int type = virDomainDiskGetType(dev->data.disk);

5515
                    if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
E
Eric Blake 已提交
5516
                        if (type == VIR_STORAGE_TYPE_FILE) {
5517 5518 5519 5520 5521 5522 5523 5524 5525
                            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)) {
5526 5527 5528
                                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                                   _("could not de-attach the mounted ISO, rc=%08x"),
                                                   (unsigned)rc);
5529 5530 5531 5532 5533
                                } else {
                                    ret = 0;
                                }
                                VBOX_RELEASE(dvdDrive);
                            }
E
Eric Blake 已提交
5534
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5535 5536
                        }
                    } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
E
Eric Blake 已提交
5537
                        if (type == VIR_STORAGE_TYPE_FILE) {
5538 5539 5540 5541 5542 5543 5544 5545
                            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);
5546
                                    if (NS_FAILED(rc)) {
5547 5548 5549 5550
                                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                                       _("could not attach the file "
                                                         "to floppy drive, rc=%08x"),
                                                       (unsigned)rc);
5551 5552 5553
                                    } else {
                                        ret = 0;
                                    }
5554 5555 5556 5557 5558
                                } 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;
5559
                                }
5560
                                VBOX_RELEASE(floppyDrive);
5561
                            }
E
Eric Blake 已提交
5562
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5563
                        }
5564
                    }
5565 5566
#else  /* VBOX_API_VERSION >= 3001000 */
#endif /* VBOX_API_VERSION >= 3001000 */
5567 5568 5569 5570
                } 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) {
5571 5572
                        }
                    }
M
Matthias Bolte 已提交
5573 5574 5575 5576 5577 5578 5579 5580 5581
                } else if (dev->type == VIR_DOMAIN_DEVICE_FS &&
                           dev->data.fs->type == VIR_DOMAIN_FS_TYPE_MOUNT) {
                    PRUnichar *nameUtf16;

                    VBOX_UTF8_TO_UTF16(dev->data.fs->dst, &nameUtf16);

                    rc = machine->vtbl->RemoveSharedFolder(machine, nameUtf16);

                    if (NS_FAILED(rc)) {
5582 5583 5584
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("could not detach shared folder '%s', rc=%08x"),
                                       dev->data.fs->dst, (unsigned)rc);
M
Matthias Bolte 已提交
5585 5586 5587 5588 5589
                    } else {
                        ret = 0;
                    }

                    VBOX_UTF16_FREE(nameUtf16);
5590
                }
5591 5592
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5593
            }
5594
            VBOX_SESSION_CLOSE();
5595 5596 5597
        }
    }

5598
 cleanup:
5599
    vboxIIDUnalloc(&iid);
5600 5601 5602 5603 5604
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5605 5606 5607 5608 5609 5610
static int
vboxDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

5611
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5612 5613
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
5614 5615 5616 5617 5618 5619
        return -1;
    }

    return vboxDomainDetachDevice(dom, xml);
}

J
Jiri Denemark 已提交
5620 5621 5622 5623 5624
static int
vboxDomainSnapshotGetAll(virDomainPtr dom,
                         IMachine *machine,
                         ISnapshot ***snapshots)
{
5625
    vboxIID empty = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5626 5627 5628 5629 5630 5631 5632 5633
    ISnapshot **list = NULL;
    PRUint32 count;
    nsresult rc;
    unsigned int next;
    unsigned int top;

    rc = machine->vtbl->GetSnapshotCount(machine, &count);
    if (NS_FAILED(rc)) {
5634 5635 5636
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get snapshot count for domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
5637 5638 5639 5640 5641 5642
        goto error;
    }

    if (count == 0)
        goto out;

5643
    if (VIR_ALLOC_N(list, count) < 0)
J
Jiri Denemark 已提交
5644 5645
        goto error;

5646
#if VBOX_API_VERSION < 4000000
5647
    rc = machine->vtbl->GetSnapshot(machine, empty.value, list);
5648
#else /* VBOX_API_VERSION >= 4000000 */
5649
    rc = machine->vtbl->FindSnapshot(machine, empty.value, list);
5650
#endif /* VBOX_API_VERSION >= 4000000 */
J
Jiri Denemark 已提交
5651
    if (NS_FAILED(rc) || !list[0]) {
5652 5653 5654
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get root snapshot for domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
5655 5656 5657 5658 5659 5660
        goto error;
    }

    /* BFS walk through snapshot tree */
    top = 1;
    for (next = 0; next < count; next++) {
5661
        vboxArray children = VBOX_ARRAY_INITIALIZER;
5662
        size_t i;
J
Jiri Denemark 已提交
5663 5664

        if (!list[next]) {
5665 5666
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected number of snapshots < %u"), count);
J
Jiri Denemark 已提交
5667 5668 5669
            goto error;
        }

5670 5671
        rc = vboxArrayGet(&children, list[next],
                               list[next]->vtbl->GetChildren);
J
Jiri Denemark 已提交
5672
        if (NS_FAILED(rc)) {
5673 5674
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get children snapshots"));
J
Jiri Denemark 已提交
5675 5676
            goto error;
        }
5677 5678 5679
        for (i = 0; i < children.count; i++) {
            ISnapshot *child = children.items[i];
            if (!child)
J
Jiri Denemark 已提交
5680 5681
                continue;
            if (top == count) {
5682 5683
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected number of snapshots > %u"), count);
5684
                vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5685 5686
                goto error;
            }
5687 5688
            VBOX_ADDREF(child);
            list[top++] = child;
J
Jiri Denemark 已提交
5689
        }
5690
        vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5691 5692
    }

5693
 out:
J
Jiri Denemark 已提交
5694 5695 5696
    *snapshots = list;
    return count;

5697
 error:
J
Jiri Denemark 已提交
5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716
    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;
5717
    size_t i;
J
Jiri Denemark 已提交
5718 5719 5720 5721 5722 5723 5724 5725 5726 5727

    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) {
5728 5729
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get snapshot name"));
J
Jiri Denemark 已提交
5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742
            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) {
5743 5744 5745
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("domain %s has no snapshots with name %s"),
                       dom->name, name);
J
Jiri Denemark 已提交
5746 5747 5748
        goto cleanup;
    }

5749
 cleanup:
J
Jiri Denemark 已提交
5750 5751 5752 5753 5754 5755 5756 5757 5758 5759
    if (count > 0) {
        for (i = 0; i < count; i++) {
            if (snapshots[i] != snapshot)
                VBOX_RELEASE(snapshots[i]);
        }
    }
    VIR_FREE(snapshots);
    return snapshot;
}

5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 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 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010
#if VBOX_API_VERSION >= 4002000
static int vboxCloseDisksRecursively(virDomainPtr dom, char *location)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    nsresult rc;
    size_t i = 0;
    PRUnichar *locationUtf = NULL;
    IMedium *medium = NULL;
    IMedium **children = NULL;
    PRUint32 childrenSize = 0;
    VBOX_UTF8_TO_UTF16(location, &locationUtf);
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                         locationUtf,
                                         DeviceType_HardDisk,
                                         AccessMode_ReadWrite,
                                         false,
                                         &medium);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to open HardDisk, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }
    rc = medium->vtbl->GetChildren(medium, &childrenSize, &children);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s"
                       , _("Unable to get disk children"));
        goto cleanup;
    }
    for (i = 0; i < childrenSize; i++) {
        IMedium *childMedium = children[i];
        if (childMedium) {
            PRUnichar *childLocationUtf = NULL;
            char *childLocation = NULL;
            rc = childMedium->vtbl->GetLocation(childMedium, &childLocationUtf);
            VBOX_UTF16_TO_UTF8(childLocationUtf, &childLocation);
            VBOX_UTF16_FREE(childLocationUtf);
            if (vboxCloseDisksRecursively(dom, childLocation) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s"
                               , _("Unable to close disk children"));
                goto cleanup;
            }
            VIR_FREE(childLocation);
        }
    }
    rc = medium->vtbl->Close(medium);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to close HardDisk, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VBOX_UTF16_FREE(locationUtf);
    return ret;
}

static int
vboxSnapshotRedefine(virDomainPtr dom,
                     virDomainSnapshotDefPtr def,
                     bool isCurrent)
{
    /*
     * If your snapshot has a parent,
     * it will only be redefined if you have already
     * redefined the parent.
     *
     * The general algorithm of this function is below :
     * First of all, we are going to create our vboxSnapshotXmlMachinePtr struct from
     * the machine settings path.
     * Then, if the machine current snapshot xml file is saved in the machine location,
     * it means that this snapshot was previously modified by us and has fake disks.
     * Fake disks are added when the flag VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT was not set
     * yet, in order to not corrupt read-only disks. The first thing to do is to remove those
     * disks and restore the read-write disks, if any, in the vboxSnapshotXmlMachinePtr struct.
     * We also delete the current snapshot xml file.
     *
     * After that, we are going to register the snapshot read-only disks that we want to redefine,
     * if they are not in the media registry struct.
     *
     * The next step is to unregister the machine and close all disks.
     *
     * Then, we check if the flag VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE has already been set.
     * If this flag was set, we just add read-write disks to the media registry
     * struct. Otherwise, we save the snapshot xml file into the machine location in order
     * to recover the read-write disks during the next redefine and we create differential disks
     * from the snapshot read-only disks and add them to the media registry struct.
     *
     * Finally, we register the machine with the new virtualbox description file.
     */
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID domiid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    nsresult rc;
    PRUnichar *settingsFilePath = NULL;
    char *settingsFilePath_Utf8 = NULL;
    virVBoxSnapshotConfMachinePtr snapshotMachineDesc = NULL;
    char *currentSnapshotXmlFilePath = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    char *machineName = NULL;
    char **realReadWriteDisksPath = NULL;
    int realReadWriteDisksPathSize = 0;
    char **realReadOnlyDisksPath = NULL;
    int realReadOnlyDisksPathSize = 0;
    virVBoxSnapshotConfSnapshotPtr newSnapshotPtr = NULL;
    unsigned char snapshotUuid[VIR_UUID_BUFLEN];
    int it = 0;
    int jt = 0;
    PRUint32 aMediaSize = 0;
    IMedium **aMedia = NULL;
    char *machineLocationPath = NULL;
    char *nameTmpUse = NULL;
    bool snapshotFileExists = false;
    bool needToChangeStorageController = false;

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

    rc = machine->vtbl->SaveSettings(machine);
    /*It may failed when the machine is not mutable.*/
    rc = machine->vtbl->GetSettingsFilePath(machine, &settingsFilePath);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get settings file path"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(settingsFilePath, &settingsFilePath_Utf8);

    /*Getting the machine name to retrieve the machine location path.*/
    rc = machine->vtbl->GetName(machine, &machineNameUtf16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get machine name"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);

    if (virAsprintf(&nameTmpUse, "%s.vbox", machineName) < 0)
        goto cleanup;
    machineLocationPath = virStringReplace(settingsFilePath_Utf8, nameTmpUse, "");
    if (machineLocationPath == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get the machine location path"));
        goto cleanup;
    }

    /*We create the xml struct with the settings file path.*/
    snapshotMachineDesc = virVBoxSnapshotConfLoadVboxFile(settingsFilePath_Utf8, machineLocationPath);
    if (snapshotMachineDesc == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot create a vboxSnapshotXmlPtr"));
        goto cleanup;
    }
    if (snapshotMachineDesc->currentSnapshot != NULL) {
        if (virAsprintf(&currentSnapshotXmlFilePath, "%s%s.xml", machineLocationPath,
                       snapshotMachineDesc->currentSnapshot) < 0)
            goto cleanup;
        snapshotFileExists = virFileExists(currentSnapshotXmlFilePath);
    }

    if (snapshotFileExists) {
        /*
         * We have created fake disks, so we have to remove them and replace them with
         * the read-write disks if there are any. The fake disks will be closed during
         * the machine unregistration.
         */
        if (virVBoxSnapshotConfRemoveFakeDisks(snapshotMachineDesc) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to remove Fake Disks"));
            goto cleanup;
        }
        realReadWriteDisksPathSize = virVBoxSnapshotConfGetRWDisksPathsFromLibvirtXML(currentSnapshotXmlFilePath,
                                                             &realReadWriteDisksPath);
        realReadOnlyDisksPathSize = virVBoxSnapshotConfGetRODisksPathsFromLibvirtXML(currentSnapshotXmlFilePath,
                                                                         &realReadOnlyDisksPath);
        /*The read-only disk number is necessarily greater or equal to the
         *read-write disk number*/
        if (realReadOnlyDisksPathSize < realReadWriteDisksPathSize) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("The read only disk number must be greater or equal to the "
                           " read write disk number"));
            goto cleanup;
        }
        for (it = 0; it < realReadWriteDisksPathSize; it++) {
            virVBoxSnapshotConfHardDiskPtr readWriteDisk = NULL;
            PRUnichar *locationUtf = NULL;
            IMedium *readWriteMedium = NULL;
            PRUnichar *uuidUtf = NULL;
            char *uuid = NULL;
            PRUnichar *formatUtf = NULL;
            char *format = NULL;
            const char *parentUuid = NULL;

            VBOX_UTF8_TO_UTF16(realReadWriteDisksPath[it], &locationUtf);
            rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                 locationUtf,
                                                 DeviceType_HardDisk,
                                                 AccessMode_ReadWrite,
                                                 false,
                                                 &readWriteMedium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                VBOX_UTF16_FREE(locationUtf);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf);

            rc = readWriteMedium->vtbl->GetId(readWriteMedium, &uuidUtf);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get the read write medium id"));
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(uuidUtf, &uuid);
            VBOX_UTF16_FREE(uuidUtf);

            rc = readWriteMedium->vtbl->GetFormat(readWriteMedium, &formatUtf);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get the read write medium format"));
                VIR_FREE(uuid);
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(formatUtf, &format);
            VBOX_UTF16_FREE(formatUtf);

            if (VIR_ALLOC(readWriteDisk) < 0) {
                VIR_FREE(uuid);
                VIR_FREE(formatUtf);
                goto cleanup;
            }

            readWriteDisk->format = format;
            readWriteDisk->uuid = uuid;
            readWriteDisk->location = realReadWriteDisksPath[it];
            /*
             * We get the current snapshot's read-only disk uuid in order to add the
             * read-write disk to the media registry as it's child. The read-only disk
             * is already in the media registry because it is the fake disk's parent.
             */
            parentUuid = virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
                                                      realReadOnlyDisksPath[it]);
6011 6012 6013 6014 6015
            if (parentUuid == NULL) {
                VIR_FREE(readWriteDisk);
                goto cleanup;
            }

6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 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 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716
            if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(readWriteDisk,
                                           snapshotMachineDesc->mediaRegistry,
                                           parentUuid) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to add hard disk to media Registry"));
                VIR_FREE(readWriteDisk);
                goto cleanup;
            }
            rc = readWriteMedium->vtbl->Close(readWriteMedium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
        /*
         * Now we have done this swap, we remove the snapshot xml file from the
         * current machine location.
         */
        if (unlink(currentSnapshotXmlFilePath) < 0) {
            virReportSystemError(errno,
                                 _("Unable to delete file %s"), currentSnapshotXmlFilePath);
            goto cleanup;
        }
    }
    /*
     * Before unregistering the machine, while all disks are still open, ensure that all
     * read-only disks are in the redefined snapshot's media registry (the disks need to
     * be open to query their uuid).
     */
    for (it = 0; it < def->dom->ndisks; it++) {
        int diskInMediaRegistry = 0;
        IMedium *readOnlyMedium = NULL;
        PRUnichar *locationUtf = NULL;
        PRUnichar *uuidUtf = NULL;
        char *uuid = NULL;
        PRUnichar *formatUtf = NULL;
        char *format = NULL;
        PRUnichar *parentUuidUtf = NULL;
        char *parentUuid = NULL;
        virVBoxSnapshotConfHardDiskPtr readOnlyDisk = NULL;

        diskInMediaRegistry = virVBoxSnapshotConfDiskIsInMediaRegistry(snapshotMachineDesc,
                                                        def->dom->disks[it]->src->path);
        if (diskInMediaRegistry == -1) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to know if disk is in media registry"));
            goto cleanup;
        }
        if (diskInMediaRegistry == 1) /*Nothing to do.*/
            continue;
        /*The read only disk is not in the media registry*/

        VBOX_UTF8_TO_UTF16(def->dom->disks[it]->src->path, &locationUtf);
        rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                             locationUtf,
                                             DeviceType_HardDisk,
                                             AccessMode_ReadWrite,
                                             false,
                                             &readOnlyMedium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to open HardDisk, rc=%08x"),
                           (unsigned)rc);
            VBOX_UTF16_FREE(locationUtf);
            goto cleanup;
        }
        VBOX_UTF16_FREE(locationUtf);

        rc = readOnlyMedium->vtbl->GetId(readOnlyMedium, &uuidUtf);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get hard disk id"));
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(uuidUtf, &uuid);
        VBOX_UTF16_FREE(uuidUtf);

        rc = readOnlyMedium->vtbl->GetFormat(readOnlyMedium, &formatUtf);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get hard disk format"));
            VIR_FREE(uuid);
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(formatUtf, &format);
        VBOX_UTF16_FREE(formatUtf);

        /*This disk is already in the media registry*/
        IMedium *parentReadOnlyMedium = NULL;
        rc = readOnlyMedium->vtbl->GetParent(readOnlyMedium, &parentReadOnlyMedium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get parent hard disk"));
            VIR_FREE(uuid);
            goto cleanup;
        }

        rc = parentReadOnlyMedium->vtbl->GetId(parentReadOnlyMedium, &parentUuidUtf);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to get hard disk id, rc=%08x"),
                           (unsigned)rc);
            VIR_FREE(uuid);
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(parentUuidUtf, &parentUuid);
        VBOX_UTF16_FREE(parentUuidUtf);

        rc = readOnlyMedium->vtbl->Close(readOnlyMedium);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to close HardDisk, rc=%08x"),
                           (unsigned)rc);
            VIR_FREE(uuid);
            VIR_FREE(parentUuid);
            goto cleanup;
        }

        if (VIR_ALLOC(readOnlyDisk) < 0) {
            VIR_FREE(uuid);
            VIR_FREE(parentUuid);
            goto cleanup;
        }

        readOnlyDisk->format = format;
        readOnlyDisk->uuid = uuid;
        if (VIR_STRDUP(readOnlyDisk->location, def->dom->disks[it]->src->path) < 0) {
            VIR_FREE(readOnlyDisk);
            goto cleanup;
        }

        if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(readOnlyDisk, snapshotMachineDesc->mediaRegistry,
                                       parentUuid) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to add hard disk to media registry"));
            VIR_FREE(readOnlyDisk);
            goto cleanup;
        }
    }

    /*Now, we can unregister the machine*/
    rc = machine->vtbl->Unregister(machine,
                              CleanupMode_DetachAllReturnHardDisksOnly,
                              &aMediaSize,
                              &aMedia);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to unregister machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }
    VBOX_RELEASE(machine);

    /*
     * Unregister the machine, and then close all disks returned by the unregister method.
     * Some close operations will fail because some disks that need to be closed will not
     * be returned by virtualbox. We will close them just after. We have to use this
     * solution because it is the only way to delete fake disks.
     */
    for (it = 0; it < aMediaSize; it++) {
        IMedium *medium = aMedia[it];
        if (medium) {
            PRUnichar *locationUtf16 = NULL;
            char *locationUtf8 = NULL;
            rc = medium->vtbl->GetLocation(medium, &locationUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get medium location"));
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(locationUtf16, &locationUtf8);
            VBOX_UTF16_FREE(locationUtf16);
            if (strstr(locationUtf8, "fake") != NULL) {
                /*we delete the fake disk because we don't need it anymore*/
                IProgress *progress = NULL;
                PRInt32 resultCode = -1;
                rc = medium->vtbl->DeleteStorage(medium, &progress);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to delete medium, rc=%08x"),
                                   (unsigned)rc);
                    VIR_FREE(locationUtf8);
                    goto cleanup;
                }
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_FAILED(resultCode)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Error while closing medium, rc=%08x"),
                                   (unsigned)resultCode);
                    VIR_FREE(locationUtf8);
                    goto cleanup;
                }
                VBOX_RELEASE(progress);
            } else {
                /*
                 * This a comment from vboxmanage code in the handleUnregisterVM
                 * function in VBoxManageMisc.cpp :
                 * Note that the IMachine::Unregister method will return the medium
                 * reference in a sane order, which means that closing will normally
                 * succeed, unless there is still another machine which uses the
                 * medium. No harm done if we ignore the error.
                 */
                rc = medium->vtbl->Close(medium);
            }
            VBOX_UTF8_FREE(locationUtf8);
        }
    }
    /*Close all disks that failed to close normally.*/
    for (it = 0; it < snapshotMachineDesc->mediaRegistry->ndisks; it++) {
        if (vboxCloseDisksRecursively(dom, snapshotMachineDesc->mediaRegistry->disks[it]->location) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to close recursively all disks"));
            goto cleanup;
        }
    }
    /*Here, all disks are closed or deleted*/

    /*We are now going to create and fill the Snapshot xml struct*/
    if (VIR_ALLOC(newSnapshotPtr) < 0)
        goto cleanup;

    if (virUUIDGenerate(snapshotUuid) < 0)
        goto cleanup;

    char uuidtmp[VIR_UUID_STRING_BUFLEN];
    virUUIDFormat(snapshotUuid, uuidtmp);
    if (VIR_STRDUP(newSnapshotPtr->uuid, uuidtmp) < 0)
        goto cleanup;

    VIR_DEBUG("New snapshot UUID: %s", newSnapshotPtr->uuid);
    if (VIR_STRDUP(newSnapshotPtr->name, def->name) < 0)
        goto cleanup;

    newSnapshotPtr->timeStamp = virTimeStringThen(def->creationTime * 1000);

    if (VIR_STRDUP(newSnapshotPtr->description, def->description) < 0)
        goto cleanup;

    if (VIR_STRDUP(newSnapshotPtr->hardware, snapshotMachineDesc->hardware) < 0)
        goto cleanup;

    if (VIR_STRDUP(newSnapshotPtr->storageController, snapshotMachineDesc->storageController) < 0)
        goto cleanup;

    /*We get the parent disk uuid from the parent disk location to correctly fill the storage controller.*/
    for (it = 0; it < def->dom->ndisks; it++) {
        char *location = NULL;
        const char *uuidReplacing = NULL;
        char **searchResultTab = NULL;
        ssize_t resultSize = 0;
        char *tmp = NULL;

        location = def->dom->disks[it]->src->path;
        if (!location)
            goto cleanup;
        /*Replacing the uuid*/
        uuidReplacing = virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc, location);
        if (uuidReplacing == NULL)
            goto cleanup;

        resultSize = virStringSearch(newSnapshotPtr->storageController,
                                     VBOX_UUID_REGEX,
                                     it + 1,
                                     &searchResultTab);
        if (resultSize != it + 1)
            goto cleanup;

        tmp = virStringReplace(newSnapshotPtr->storageController,
                               searchResultTab[it],
                               uuidReplacing);
        virStringFreeList(searchResultTab);
        VIR_FREE(newSnapshotPtr->storageController);
        if (!tmp)
            goto cleanup;
        if (VIR_STRDUP(newSnapshotPtr->storageController, tmp) < 0)
            goto cleanup;

        VIR_FREE(tmp);
    }
    if (virVBoxSnapshotConfAddSnapshotToXmlMachine(newSnapshotPtr, snapshotMachineDesc, def->parent) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to add the snapshot to the machine description"));
        goto cleanup;
    }
    /*
     * We change the current snapshot only if there is no current snapshot or if the
     * snapshotFile exists, otherwise, it means that the correct current snapshot is
     * already set.
     */

    if (snapshotMachineDesc->currentSnapshot == NULL || snapshotFileExists) {
        snapshotMachineDesc->currentSnapshot = newSnapshotPtr->uuid;
        needToChangeStorageController = true;
    }

    /*
     * Open the snapshot's read-write disk's full ancestry to allow opening the
     * read-write disk itself.
     */
    for (it = 0; it < def->dom->ndisks; it++) {
        char *location = NULL;
        virVBoxSnapshotConfHardDiskPtr *hardDiskToOpen = NULL;
        size_t hardDiskToOpenSize = 0;

        location = def->dom->disks[it]->src->path;
        if (!location)
            goto cleanup;

        hardDiskToOpenSize = virVBoxSnapshotConfDiskListToOpen(snapshotMachineDesc,
                                                   &hardDiskToOpen, location);
        for (jt = hardDiskToOpenSize -1; jt >= 0; jt--) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            VBOX_UTF8_TO_UTF16(hardDiskToOpen[jt]->location, &locationUtf16);

            rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                 locationUtf16,
                                                 DeviceType_HardDisk,
                                                 AccessMode_ReadWrite,
                                                 false,
                                                 &medium);
            VBOX_UTF16_FREE(locationUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
    }
    if (isCurrent || !needToChangeStorageController) {
        /* We don't create a differential hard disk because either the current snapshot
         * has already been defined or the snapshot to redefine is the current snapshot.
         * If the snapshot to redefine is the current snapshot, we add read-write disks in
         * the machine storage controllers.
         */
        for (it = 0; it < def->ndisks; it++) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            virVBoxSnapshotConfHardDiskPtr disk = NULL;
            PRUnichar *formatUtf16 = NULL;
            char *format = NULL;
            PRUnichar *uuidUtf16 = NULL;
            char *uuid = NULL;
            IMedium *parentDisk = NULL;
            PRUnichar *parentUuidUtf16 = NULL;
            char *parentUuid = NULL;

            VBOX_UTF8_TO_UTF16(def->disks[it].src->path, &locationUtf16);
            rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                 locationUtf16,
                                                 DeviceType_HardDisk,
                                                 AccessMode_ReadWrite,
                                                 false,
                                                 &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf16);

            if (VIR_ALLOC(disk) < 0)
                goto cleanup;

            rc = medium->vtbl->GetFormat(medium, &formatUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get disk format"));
                VIR_FREE(disk);
                goto cleanup;
            }

            VBOX_UTF16_TO_UTF8(formatUtf16, &format);
            disk->format = format;
            VBOX_UTF16_FREE(formatUtf16);

            if (VIR_STRDUP(disk->location, def->disks[it].src->path) < 0) {
                VIR_FREE(disk);
                goto cleanup;
            }

            rc = medium->vtbl->GetId(medium, &uuidUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get disk uuid"));
                VIR_FREE(disk);
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(uuidUtf16, &uuid);
            disk->uuid  = uuid;
            VBOX_UTF16_FREE(uuidUtf16);

            rc = medium->vtbl->GetParent(medium, &parentDisk);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get disk parent"));
                VIR_FREE(disk);
                goto cleanup;
            }

            parentDisk->vtbl->GetId(parentDisk, &parentUuidUtf16);
            VBOX_UTF16_TO_UTF8(parentUuidUtf16, &parentUuid);
            VBOX_UTF16_FREE(parentUuidUtf16);
            if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(disk,
                                           snapshotMachineDesc->mediaRegistry,
                                           parentUuid) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to add hard disk to the media registry"));
                VIR_FREE(disk);
                goto cleanup;
            }

            if (needToChangeStorageController) {
                /*We need to append this disk in the storage controller*/
                char **searchResultTab = NULL;
                ssize_t resultSize = 0;
                char *tmp = NULL;
                resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                             VBOX_UUID_REGEX,
                                             it + 1,
                                             &searchResultTab);
                if (resultSize != it + 1) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to find UUID %s"), searchResultTab[it]);
                    goto cleanup;
                }

                tmp = virStringReplace(snapshotMachineDesc->storageController,
                                       searchResultTab[it],
                                       disk->uuid);
                virStringFreeList(searchResultTab);
                VIR_FREE(snapshotMachineDesc->storageController);
                if (!tmp)
                    goto cleanup;
                if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                    goto cleanup;

                VIR_FREE(tmp);
            }
            /*Close disk*/
            rc = medium->vtbl->Close(medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
    } else {
        /*Create a "fake" disk to avoid corrupting children snapshot disks.*/
        for (it = 0; it < def->dom->ndisks; it++) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            PRUnichar *parentUuidUtf16 = NULL;
            char *parentUuid = NULL;
            IMedium *newMedium = NULL;
            PRUnichar *formatUtf16 = NULL;
            PRUnichar *newLocation = NULL;
            char *newLocationUtf8 = NULL;
            PRInt32 resultCode = -1;
            virVBoxSnapshotConfHardDiskPtr disk = NULL;
            PRUnichar *uuidUtf16 = NULL;
            char *uuid = NULL;
            char *format = NULL;
            char **searchResultTab = NULL;
            ssize_t resultSize = 0;
            char *tmp = NULL;

            VBOX_UTF8_TO_UTF16(def->dom->disks[it]->src->path, &locationUtf16);
            rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                 locationUtf16,
                                                 DeviceType_HardDisk,
                                                 AccessMode_ReadWrite,
                                                 false,
                                                 &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                VBOX_UTF16_FREE(locationUtf16);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf16);

            rc = medium->vtbl->GetId(medium, &parentUuidUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to get hardDisk Id, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(parentUuidUtf16, &parentUuid);
            VBOX_UTF16_FREE(parentUuidUtf16);
            VBOX_UTF8_TO_UTF16("VDI", &formatUtf16);

            if (virAsprintf(&newLocationUtf8, "%sfakedisk-%d.vdi", machineLocationPath, it) < 0)
                goto cleanup;
            VBOX_UTF8_TO_UTF16(newLocationUtf8, &newLocation);
            rc = data->vboxObj->vtbl->CreateHardDisk(data->vboxObj,
                                                formatUtf16,
                                                newLocation,
                                                &newMedium);
            VBOX_UTF16_FREE(newLocation);
            VBOX_UTF16_FREE(formatUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to create HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }

            IProgress *progress = NULL;
# if VBOX_API_VERSION < 4003000
            medium->vtbl->CreateDiffStorage(medium, newMedium, MediumVariant_Diff, &progress);
# else
            PRUint32 tab[1];
            tab[0] =  MediumVariant_Diff;
            medium->vtbl->CreateDiffStorage(medium, newMedium, 1, tab, &progress);
# endif

            progress->vtbl->WaitForCompletion(progress, -1);
            progress->vtbl->GetResultCode(progress, &resultCode);
            if (NS_FAILED(resultCode)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Error while creating diff storage, rc=%08x"),
                               (unsigned)resultCode);
                goto cleanup;
            }
            VBOX_RELEASE(progress);
            /*
             * The differential disk is created, we add it to the media registry and the
             * machine storage controllers.
             */

            if (VIR_ALLOC(disk) < 0)
                goto cleanup;

            rc = newMedium->vtbl->GetId(newMedium, &uuidUtf16);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to get medium uuid, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            VBOX_UTF16_TO_UTF8(uuidUtf16, &uuid);
            disk->uuid = uuid;
            VBOX_UTF16_FREE(uuidUtf16);

            if (VIR_STRDUP(disk->location, newLocationUtf8) < 0)
                goto cleanup;

            rc = newMedium->vtbl->GetFormat(newMedium, &formatUtf16);
            VBOX_UTF16_TO_UTF8(formatUtf16, &format);
            disk->format = format;
            VBOX_UTF16_FREE(formatUtf16);

            if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(disk,
                                           snapshotMachineDesc->mediaRegistry,
                                           parentUuid) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to add hard disk to the media registry"));
                goto cleanup;
            }
            /*Adding the fake disk to the machine storage controllers*/

            resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                         VBOX_UUID_REGEX,
                                         it + 1,
                                         &searchResultTab);
            if (resultSize != it + 1) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to find UUID %s"), searchResultTab[it]);
                goto cleanup;
            }

            tmp = virStringReplace(snapshotMachineDesc->storageController,
                                   searchResultTab[it],
                                   disk->uuid);
            virStringFreeList(searchResultTab);
            VIR_FREE(snapshotMachineDesc->storageController);
            if (!tmp)
                goto cleanup;
            if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                goto cleanup;

            VIR_FREE(tmp);
            /*Closing the "fake" disk*/
            rc = newMedium->vtbl->Close(newMedium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close the new medium, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
        }
        /*
         * We save the snapshot xml file to retrieve the real read-write disk during the
         * next define. This file is saved as "'machineLocation'/snapshot-'uuid'.xml"
         */
        VIR_FREE(currentSnapshotXmlFilePath);
        if (virAsprintf(&currentSnapshotXmlFilePath, "%s%s.xml", machineLocationPath, snapshotMachineDesc->currentSnapshot) < 0)
            goto cleanup;
        char *snapshotContent = virDomainSnapshotDefFormat(NULL, def, VIR_DOMAIN_XML_SECURE, 0);
        if (snapshotContent == NULL) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Unable to get snapshot content"));
            goto cleanup;
        }
        if (virFileWriteStr(currentSnapshotXmlFilePath, snapshotContent, 0644) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Unable to save new snapshot xml file"));
            goto cleanup;
        }
        VIR_FREE(snapshotContent);
    }
    /*
     * All the snapshot structure manipulation is done, we close the disks we have
     * previously opened.
     */
    for (it = 0; it < def->dom->ndisks; it++) {
        char *location = def->dom->disks[it]->src->path;
        if (!location)
            goto cleanup;

        virVBoxSnapshotConfHardDiskPtr *hardDiskToOpen = NULL;
        size_t hardDiskToOpenSize = virVBoxSnapshotConfDiskListToOpen(snapshotMachineDesc,
                                                   &hardDiskToOpen, location);
        for (jt = 0; jt < hardDiskToOpenSize; jt++) {
            IMedium *medium = NULL;
            PRUnichar *locationUtf16 = NULL;
            VBOX_UTF8_TO_UTF16(hardDiskToOpen[jt]->location, &locationUtf16);
            rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                 locationUtf16,
                                                 DeviceType_HardDisk,
                                                 AccessMode_ReadWrite,
                                                 false,
                                                 &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to open HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            rc = medium->vtbl->Close(medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to close HardDisk, rc=%08x"),
                               (unsigned)rc);
                goto cleanup;
            }
            VBOX_UTF16_FREE(locationUtf16);
        }
    }

    /*Now, we rewrite the 'machineName'.vbox file to redefine the machine.*/
    if (virVBoxSnapshotConfSaveVboxFile(snapshotMachineDesc, settingsFilePath_Utf8) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to serialize the machine description"));
        goto cleanup;
    }
    rc = data->vboxObj->vtbl->OpenMachine(data->vboxObj,
                                     settingsFilePath,
                                     &machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to open Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    rc = data->vboxObj->vtbl->RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to register Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VBOX_RELEASE(machine);
    VBOX_UTF16_FREE(settingsFilePath);
    VBOX_UTF8_FREE(settingsFilePath_Utf8);
    VIR_FREE(snapshotMachineDesc);
    VIR_FREE(currentSnapshotXmlFilePath);
    VBOX_UTF16_FREE(machineNameUtf16);
    VBOX_UTF8_FREE(machineName);
    virStringFreeList(realReadOnlyDisksPath);
    virStringFreeList(realReadWriteDisksPath);
    VIR_FREE(newSnapshotPtr);
    VIR_FREE(machineLocationPath);
    VIR_FREE(nameTmpUse);
    return ret;
}
#endif

J
Jiri Denemark 已提交
6717 6718 6719
static virDomainSnapshotPtr
vboxDomainSnapshotCreateXML(virDomainPtr dom,
                            const char *xmlDesc,
6720
                            unsigned int flags)
J
Jiri Denemark 已提交
6721 6722 6723
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    virDomainSnapshotDefPtr def = NULL;
6724
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6725 6726 6727 6728 6729 6730 6731 6732
    IMachine *machine = NULL;
    IConsole *console = NULL;
    IProgress *progress = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *name = NULL;
    PRUnichar *description = NULL;
    PRUint32 state;
    nsresult rc;
6733
#if VBOX_API_VERSION == 2002000
J
Jiri Denemark 已提交
6734 6735 6736 6737
    nsresult result;
#else
    PRInt32 result;
#endif
6738 6739 6740 6741
#if VBOX_API_VERSION >= 4002000
    bool isCurrent = false;
#endif

J
Jiri Denemark 已提交
6742

6743
    /* VBox has no snapshot metadata, so this flag is trivial.  */
6744 6745 6746
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
                  VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT, NULL);
6747

6748
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, data->caps,
6749 6750 6751
                                                data->xmlopt, -1,
                                                VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
                                                VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE)))
J
Jiri Denemark 已提交
6752 6753
        goto cleanup;

6754

6755
    vboxIIDFromUUID(&domiid, dom->uuid);
6756
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
6757
    if (NS_FAILED(rc)) {
6758 6759
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
6760 6761 6762
        goto cleanup;
    }

6763 6764 6765 6766 6767 6768 6769 6770 6771 6772
#if VBOX_API_VERSION >= 4002000
    isCurrent = flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;
    if (flags & VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE) {
        if (vboxSnapshotRedefine(dom, def, isCurrent) < 0)
            goto cleanup;
        ret = virGetDomainSnapshot(dom, def->name);
        goto cleanup;
    }
#endif

J
Jiri Denemark 已提交
6773 6774
    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
6775 6776
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
6777 6778 6779 6780 6781
        goto cleanup;
    }

    if ((state >= MachineState_FirstOnline)
        && (state <= MachineState_LastOnline)) {
6782
        rc = VBOX_SESSION_OPEN_EXISTING(domiid.value, machine);
J
Jiri Denemark 已提交
6783
    } else {
6784
        rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
6785
    }
6786

J
Jiri Denemark 已提交
6787 6788 6789
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
6790 6791 6792
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811
        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) {
6812 6813
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not take snapshot of domain %s"), dom->name);
J
Jiri Denemark 已提交
6814 6815 6816 6817 6818 6819
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
6820 6821
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not take snapshot of domain %s"), dom->name);
J
Jiri Denemark 已提交
6822 6823 6824 6825 6826
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
6827 6828
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get current snapshot of domain %s"),
J
Jiri Denemark 已提交
6829 6830 6831 6832 6833 6834
                  dom->name);
        goto cleanup;
    }

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

6835
 cleanup:
J
Jiri Denemark 已提交
6836 6837 6838 6839
    VBOX_RELEASE(progress);
    VBOX_UTF16_FREE(description);
    VBOX_UTF16_FREE(name);
    VBOX_RELEASE(console);
6840
    VBOX_SESSION_CLOSE();
J
Jiri Denemark 已提交
6841
    VBOX_RELEASE(machine);
6842
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
6843 6844 6845 6846
    virDomainSnapshotDefFree(def);
    return ret;
}

6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918
#if VBOX_API_VERSION >=4002000
static
int vboxSnapshotGetReadWriteDisks(virDomainSnapshotDefPtr def,
                                    virDomainSnapshotPtr snapshot)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID domiid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IMachine *snapMachine = NULL;
    vboxArray mediumAttachments         = VBOX_ARRAY_INITIALIZER;
    PRUint32   maxPortPerInst[StorageBus_Floppy + 1] = {};
    PRUint32   maxSlotPerPort[StorageBus_Floppy + 1] = {};
    int diskCount = 0;
    nsresult rc;
    vboxIID snapIid = VBOX_IID_INITIALIZER;
    char *snapshotUuidStr = NULL;
    size_t i = 0;

    vboxIIDFromUUID(&domiid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no domain with matching UUID"));
        goto cleanup;
    }
    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    rc = snap->vtbl->GetId(snap, &snapIid.value);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not get snapshot id"));
        goto cleanup;
    }

    VBOX_UTF16_TO_UTF8(snapIid.value, &snapshotUuidStr);
    rc = snap->vtbl->GetMachine(snap, &snapMachine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get machine"));
        goto cleanup;
    }
    def->ndisks = 0;
    rc = vboxArrayGet(&mediumAttachments, snapMachine, snapMachine->vtbl->GetMediumAttachments);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no medium attachments"));
        goto cleanup;
    }
    /* get the number of attachments */
    for (i = 0; i < mediumAttachments.count; i++) {
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        if (imediumattach) {
            IMedium *medium = NULL;

            rc = imediumattach->vtbl->GetMedium(imediumattach, &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get medium"));
                goto cleanup;
            }
            if (medium) {
                def->ndisks++;
                VBOX_RELEASE(medium);
            }
        }
    }
    /* Allocate mem, if fails return error */
    if (VIR_ALLOC_N(def->disks, def->ndisks) < 0)
        goto cleanup;
6919 6920 6921 6922
    for (i = 0; i < def->ndisks; i++) {
        if (VIR_ALLOC(def->disks[i].src) < 0)
            goto cleanup;
    }
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 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020

    if (!vboxGetMaxPortSlotValues(data->vboxObj, maxPortPerInst, maxSlotPerPort))
        goto cleanup;

    /* get the attachment details here */
    for (i = 0; i < mediumAttachments.count && diskCount < def->ndisks; i++) {
        IStorageController *storageController = NULL;
        PRUnichar *storageControllerName = NULL;
        PRUint32   deviceType     = DeviceType_Null;
        PRUint32   storageBus     = StorageBus_Null;
        IMedium   *disk         = NULL;
        PRUnichar *childLocUtf16 = NULL;
        char      *childLocUtf8  = NULL;
        PRUint32   deviceInst     = 0;
        PRInt32    devicePort     = 0;
        PRInt32    deviceSlot     = 0;
        vboxArray children = VBOX_ARRAY_INITIALIZER;
        vboxArray snapshotIids = VBOX_ARRAY_INITIALIZER;
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        size_t j = 0;
        size_t k = 0;
        if (!imediumattach)
            continue;
        rc = imediumattach->vtbl->GetMedium(imediumattach, &disk);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get medium"));
            goto cleanup;
        }
        if (!disk)
            continue;
        rc = imediumattach->vtbl->GetController(imediumattach, &storageControllerName);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get controller"));
            goto cleanup;
        }
        if (!storageControllerName) {
            VBOX_RELEASE(disk);
            continue;
        }
        rc = vboxArrayGet(&children, disk, disk->vtbl->GetChildren);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get children disk"));
            goto cleanup;
        }
        rc = vboxArrayGetWithPtrArg(&snapshotIids, disk, disk->vtbl->GetSnapshotIds, domiid.value);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get snapshot ids"));
            goto cleanup;
        }
        for (j = 0; j < children.count; ++j) {
            IMedium *child = children.items[j];
            for (k = 0; k < snapshotIids.count; ++k) {
                PRUnichar *diskSnapId = snapshotIids.items[k];
                char *diskSnapIdStr = NULL;
                VBOX_UTF16_TO_UTF8(diskSnapId, &diskSnapIdStr);
                if (STREQ(diskSnapIdStr, snapshotUuidStr)) {
                    rc = machine->vtbl->GetStorageControllerByName(machine,
                                                              storageControllerName,
                                                              &storageController);
                    VBOX_UTF16_FREE(storageControllerName);
                    if (!storageController) {
                        VBOX_RELEASE(child);
                        break;
                    }
                    rc = child->vtbl->GetLocation(child, &childLocUtf16);
                    if (NS_FAILED(rc)) {
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("cannot get disk location"));
                        goto cleanup;
                    }
                    VBOX_UTF16_TO_UTF8(childLocUtf16, &childLocUtf8);
                    VBOX_UTF16_FREE(childLocUtf16);
                    if (VIR_STRDUP(def->disks[diskCount].src->path, childLocUtf8) < 0) {
                        VBOX_RELEASE(child);
                        VBOX_RELEASE(storageController);
                        goto cleanup;
                    }
                    VBOX_UTF8_FREE(childLocUtf8);

                    rc = storageController->vtbl->GetBus(storageController, &storageBus);
                    if (NS_FAILED(rc)) {
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("cannot get storage controller bus"));
                        goto cleanup;
                    }
                    rc = imediumattach->vtbl->GetType(imediumattach, &deviceType);
                    if (NS_FAILED(rc)) {
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("cannot get medium attachment type"));
                        goto cleanup;
                    }
                    rc = imediumattach->vtbl->GetPort(imediumattach, &devicePort);
                    if (NS_FAILED(rc)) {
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
7021
                                       _("cannot get medium attachment type"));
7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049
                        goto cleanup;
                    }
                    rc = imediumattach->vtbl->GetDevice(imediumattach, &deviceSlot);
                    if (NS_FAILED(rc)) {
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                       _("cannot get medium attachment device"));
                        goto cleanup;
                    }
                    def->disks[diskCount].src->type = VIR_STORAGE_TYPE_FILE;
                    def->disks[diskCount].name = vboxGenerateMediumName(storageBus,
                                                                        deviceInst,
                                                                        devicePort,
                                                                        deviceSlot,
                                                                        maxPortPerInst,
                                                                        maxSlotPerPort);
                }
                VBOX_UTF8_FREE(diskSnapIdStr);
            }
        }
        VBOX_RELEASE(storageController);
        VBOX_RELEASE(disk);
        diskCount++;
    }
    vboxArrayRelease(&mediumAttachments);

    ret = 0;
 cleanup:
    if (ret < 0) {
7050 7051 7052 7053 7054
        for (i = 0; i < def->ndisks; i++) {
            VIR_FREE(def->disks[i].src);
        }
        VIR_FREE(def->disks);
        def->ndisks = 0;
7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127
    }
    VBOX_RELEASE(snap);
    return ret;
}

static
int vboxSnapshotGetReadOnlyDisks(virDomainSnapshotPtr snapshot,
                                    virDomainSnapshotDefPtr def)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID domiid = VBOX_IID_INITIALIZER;
    ISnapshot *snap = NULL;
    IMachine *machine = NULL;
    IMachine *snapMachine = NULL;
    IStorageController *storageController = NULL;
    IMedium   *disk         = NULL;
    nsresult rc;
    vboxIIDFromUUID(&domiid, dom->uuid);
    vboxArray mediumAttachments         = VBOX_ARRAY_INITIALIZER;
    size_t i = 0;
    PRUint32   maxPortPerInst[StorageBus_Floppy + 1] = {};
    PRUint32   maxSlotPerPort[StorageBus_Floppy + 1] = {};
    int diskCount = 0;

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

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

    rc = snap->vtbl->GetMachine(snap, &snapMachine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get machine"));
        goto cleanup;
    }
    /*
     * Get READ ONLY disks
     * In the snapshot metadata, these are the disks written inside the <domain> node
    */
    rc = vboxArrayGet(&mediumAttachments, snapMachine, snapMachine->vtbl->GetMediumAttachments);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get medium attachments"));
        goto cleanup;
    }
    /* get the number of attachments */
    for (i = 0; i < mediumAttachments.count; i++) {
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        if (imediumattach) {
            IMedium *medium = NULL;

            rc = imediumattach->vtbl->GetMedium(imediumattach, &medium);
            if (NS_FAILED(rc)) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("cannot get medium"));
                goto cleanup;
            }
            if (medium) {
                def->dom->ndisks++;
                VBOX_RELEASE(medium);
            }
        }
    }

    /* Allocate mem, if fails return error */
    if (VIR_ALLOC_N(def->dom->disks, def->dom->ndisks) >= 0) {
        for (i = 0; i < def->dom->ndisks; i++) {
7128 7129
            virDomainDiskDefPtr diskDef = virDomainDiskDefNew();
            if (!diskDef)
7130
                goto cleanup;
7131
            def->dom->disks[i] = diskDef;
7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241
        }
    } else {
        goto cleanup;
    }

    if (!vboxGetMaxPortSlotValues(data->vboxObj, maxPortPerInst, maxSlotPerPort))
        goto cleanup;

    /* get the attachment details here */
    for (i = 0; i < mediumAttachments.count && diskCount < def->dom->ndisks; i++) {
        PRUnichar *storageControllerName = NULL;
        PRUint32   deviceType     = DeviceType_Null;
        PRUint32   storageBus     = StorageBus_Null;
        PRBool     readOnly       = PR_FALSE;
        PRUnichar *mediumLocUtf16 = NULL;
        char      *mediumLocUtf8  = NULL;
        PRUint32   deviceInst     = 0;
        PRInt32    devicePort     = 0;
        PRInt32    deviceSlot     = 0;
        IMediumAttachment *imediumattach = mediumAttachments.items[i];
        if (!imediumattach)
            continue;
        rc = imediumattach->vtbl->GetMedium(imediumattach, &disk);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get medium"));
            goto cleanup;
        }
        if (!disk)
            continue;
        rc = imediumattach->vtbl->GetController(imediumattach, &storageControllerName);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get storage controller name"));
            goto cleanup;
        }
        if (!storageControllerName)
            continue;
        rc = machine->vtbl->GetStorageControllerByName(machine,
                                                  storageControllerName,
                                                  &storageController);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get storage controller"));
            goto cleanup;
        }
        VBOX_UTF16_FREE(storageControllerName);
        if (!storageController)
            continue;
        rc = disk->vtbl->GetLocation(disk, &mediumLocUtf16);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get disk location"));
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8);
        VBOX_UTF16_FREE(mediumLocUtf16);
        if (VIR_STRDUP(def->dom->disks[diskCount]->src->path, mediumLocUtf8) < 0)
            goto cleanup;

        VBOX_UTF8_FREE(mediumLocUtf8);

        rc = storageController->vtbl->GetBus(storageController, &storageBus);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get storage controller bus"));
            goto cleanup;
        }
        if (storageBus == StorageBus_IDE) {
            def->dom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_IDE;
        } else if (storageBus == StorageBus_SATA) {
            def->dom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_SATA;
        } else if (storageBus == StorageBus_SCSI) {
            def->dom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_SCSI;
        } else if (storageBus == StorageBus_Floppy) {
            def->dom->disks[diskCount]->bus = VIR_DOMAIN_DISK_BUS_FDC;
        }

        rc = imediumattach->vtbl->GetType(imediumattach, &deviceType);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get medium attachment type"));
            goto cleanup;
        }
        if (deviceType == DeviceType_HardDisk)
            def->dom->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_DISK;
        else if (deviceType == DeviceType_Floppy)
            def->dom->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
        else if (deviceType == DeviceType_DVD)
            def->dom->disks[diskCount]->device = VIR_DOMAIN_DISK_DEVICE_CDROM;

        rc = imediumattach->vtbl->GetPort(imediumattach, &devicePort);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get medium attachment port"));
            goto cleanup;
        }
        rc = imediumattach->vtbl->GetDevice(imediumattach, &deviceSlot);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get device"));
            goto cleanup;
        }
        rc = disk->vtbl->GetReadOnly(disk, &readOnly);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot get read only attribute"));
            goto cleanup;
        }
        if (readOnly == PR_TRUE)
7242
            def->dom->disks[diskCount]->src->readonly = true;
7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265
        def->dom->disks[diskCount]->src->type = VIR_STORAGE_TYPE_FILE;
        def->dom->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
                                                                 deviceInst,
                                                                 devicePort,
                                                                 deviceSlot,
                                                                 maxPortPerInst,
                                                                 maxSlotPerPort);
        if (!def->dom->disks[diskCount]->dst) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Could not generate medium name for the disk "
                             "at: controller instance:%u, port:%d, slot:%d"),
                           deviceInst, devicePort, deviceSlot);
            ret = -1;
            goto cleanup;
        }
        diskCount ++;
    }
    /* cleanup on error */

    ret = 0;
 cleanup:
    if (ret < 0) {
        for (i = 0; i < def->dom->ndisks; i++)
7266
            virDomainDiskDefFree(def->dom->disks[i]);
7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277
        VIR_FREE(def->dom->disks);
        def->dom->ndisks = 0;
    }
    VBOX_RELEASE(disk);
    VBOX_RELEASE(storageController);
    vboxArrayRelease(&mediumAttachments);
    VBOX_RELEASE(snap);
    return ret;
}
#endif

J
Jiri Denemark 已提交
7278
static char *
7279 7280
vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                             unsigned int flags)
J
Jiri Denemark 已提交
7281 7282 7283
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
7284
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7285 7286 7287 7288 7289 7290 7291 7292 7293 7294
    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];
7295 7296 7297 7298
#if VBOX_API_VERSION >=4002000
    PRUint32 memorySize                 = 0;
    PRUint32 CPUCount                 = 0;
#endif
J
Jiri Denemark 已提交
7299

7300 7301
    virCheckFlags(0, NULL);

7302
    vboxIIDFromUUID(&domiid, dom->uuid);
7303
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
7304
    if (NS_FAILED(rc)) {
7305 7306
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7307 7308 7309 7310 7311 7312
        goto cleanup;
    }

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

7313
    if (VIR_ALLOC(def) < 0 || VIR_ALLOC(def->dom) < 0)
7314
        goto cleanup;
7315 7316
    if (VIR_STRDUP(def->name, snapshot->name) < 0)
        goto cleanup;
J
Jiri Denemark 已提交
7317

7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347
#if VBOX_API_VERSION >=4002000
    /* Register def->dom properties for them to be saved inside the snapshot XMl
     * Otherwise, there is a problem while parsing the xml
     */
    def->dom->virtType = VIR_DOMAIN_VIRT_VBOX;
    def->dom->id = dom->id;
    memcpy(def->dom->uuid, dom->uuid, VIR_UUID_BUFLEN);
    if (VIR_STRDUP(def->dom->name, dom->name) < 0)
        goto cleanup;
    machine->vtbl->GetMemorySize(machine, &memorySize);
    def->dom->mem.cur_balloon = memorySize * 1024;
    /* Currently setting memory and maxMemory as same, cause
     * the notation here seems to be inconsistent while
     * reading and while dumping xml
     */
    def->dom->mem.max_balloon = memorySize * 1024;
    if (VIR_STRDUP(def->dom->os.type, "hvm") < 0)
        goto cleanup;
    def->dom->os.arch = virArchFromHost();
    machine->vtbl->GetCPUCount(machine, &CPUCount);
    def->dom->maxvcpus = def->dom->vcpus = CPUCount;
    if (vboxSnapshotGetReadWriteDisks(def, snapshot) < 0) {
        VIR_DEBUG("Could not get read write disks for snapshot");
    }

    if (vboxSnapshotGetReadOnlyDisks(snapshot, def) < 0) {
        VIR_DEBUG("Could not get Readonly disks for snapshot");
    }
#endif /* VBOX_API_VERSION >= 4002000 */

J
Jiri Denemark 已提交
7348 7349
    rc = snap->vtbl->GetDescription(snap, &str16);
    if (NS_FAILED(rc)) {
7350 7351 7352
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get description of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7353 7354 7355 7356 7357
        goto cleanup;
    }
    if (str16) {
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
7358 7359 7360 7361
        if (VIR_STRDUP(def->description, str8) < 0) {
            VBOX_UTF8_FREE(str8);
            goto cleanup;
        }
J
Jiri Denemark 已提交
7362 7363 7364 7365 7366
        VBOX_UTF8_FREE(str8);
    }

    rc = snap->vtbl->GetTimeStamp(snap, &timestamp);
    if (NS_FAILED(rc)) {
7367 7368 7369
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get creation time of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7370 7371 7372 7373 7374 7375 7376
        goto cleanup;
    }
    /* timestamp is in milliseconds while creationTime in seconds */
    def->creationTime = timestamp / 1000;

    rc = snap->vtbl->GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
7377 7378 7379
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get parent of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7380 7381 7382 7383 7384
        goto cleanup;
    }
    if (parent) {
        rc = parent->vtbl->GetName(parent, &str16);
        if (NS_FAILED(rc) || !str16) {
7385 7386 7387
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not get name of parent of snapshot %s"),
                           snapshot->name);
J
Jiri Denemark 已提交
7388 7389 7390 7391
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
7392 7393
        if (VIR_STRDUP(def->parent, str8) < 0) {
            VBOX_UTF8_FREE(str8);
7394
            goto cleanup;
7395 7396
        }
        VBOX_UTF8_FREE(str8);
J
Jiri Denemark 已提交
7397 7398 7399 7400
    }

    rc = snap->vtbl->GetOnline(snap, &online);
    if (NS_FAILED(rc)) {
7401 7402 7403
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get online state of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7404 7405 7406 7407 7408 7409 7410 7411
        goto cleanup;
    }
    if (online)
        def->state = VIR_DOMAIN_RUNNING;
    else
        def->state = VIR_DOMAIN_SHUTOFF;

    virUUIDFormat(dom->uuid, uuidstr);
7412
    memcpy(def->dom->uuid, dom->uuid, VIR_UUID_BUFLEN);
7413
    ret = virDomainSnapshotDefFormat(uuidstr, def, flags, 0);
J
Jiri Denemark 已提交
7414

7415
 cleanup:
J
Jiri Denemark 已提交
7416 7417 7418 7419
    virDomainSnapshotDefFree(def);
    VBOX_RELEASE(parent);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
7420
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
7421 7422 7423 7424 7425
    return ret;
}

static int
vboxDomainSnapshotNum(virDomainPtr dom,
7426
                      unsigned int flags)
J
Jiri Denemark 已提交
7427 7428
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7429
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7430 7431 7432 7433
    IMachine *machine = NULL;
    nsresult rc;
    PRUint32 snapshotCount;

7434 7435
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA, -1);
7436

7437
    vboxIIDFromUUID(&iid, dom->uuid);
7438
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
7439
    if (NS_FAILED(rc)) {
7440 7441
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7442 7443 7444
        goto cleanup;
    }

7445 7446 7447 7448 7449 7450
    /* VBox snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        ret = 0;
        goto cleanup;
    }

J
Jiri Denemark 已提交
7451 7452
    rc = machine->vtbl->GetSnapshotCount(machine, &snapshotCount);
    if (NS_FAILED(rc)) {
7453 7454 7455
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get snapshot count for domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
7456 7457 7458
        goto cleanup;
    }

7459 7460 7461 7462 7463
    /* VBox has at most one root snapshot.  */
    if (snapshotCount && (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS))
        ret = 1;
    else
        ret = snapshotCount;
J
Jiri Denemark 已提交
7464

7465
 cleanup:
J
Jiri Denemark 已提交
7466
    VBOX_RELEASE(machine);
7467
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7468 7469 7470 7471 7472 7473 7474
    return ret;
}

static int
vboxDomainSnapshotListNames(virDomainPtr dom,
                            char **names,
                            int nameslen,
7475
                            unsigned int flags)
J
Jiri Denemark 已提交
7476 7477
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7478
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7479 7480 7481 7482
    IMachine *machine = NULL;
    nsresult rc;
    ISnapshot **snapshots = NULL;
    int count = 0;
7483
    size_t i;
J
Jiri Denemark 已提交
7484

7485 7486
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA, -1);
7487

7488
    vboxIIDFromUUID(&iid, dom->uuid);
7489
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
7490
    if (NS_FAILED(rc)) {
7491 7492
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7493 7494 7495
        goto cleanup;
    }

7496 7497 7498 7499 7500
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        ret = 0;
        goto cleanup;
    }

7501 7502 7503
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) {
        vboxIID empty = VBOX_IID_INITIALIZER;

7504
        if (VIR_ALLOC_N(snapshots, 1) < 0)
7505
            goto cleanup;
7506
#if VBOX_API_VERSION < 4000000
7507
        rc = machine->vtbl->GetSnapshot(machine, empty.value, snapshots);
7508
#else /* VBOX_API_VERSION >= 4000000 */
7509
        rc = machine->vtbl->FindSnapshot(machine, empty.value, snapshots);
7510
#endif /* VBOX_API_VERSION >= 4000000 */
7511
        if (NS_FAILED(rc) || !snapshots[0]) {
7512 7513 7514
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not get root snapshot for domain %s"),
                           dom->name);
7515 7516 7517 7518 7519 7520 7521
            goto cleanup;
        }
        count = 1;
    } else {
        if ((count = vboxDomainSnapshotGetAll(dom, machine, &snapshots)) < 0)
            goto cleanup;
    }
J
Jiri Denemark 已提交
7522 7523 7524 7525 7526 7527 7528 7529 7530 7531

    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) {
7532 7533
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get snapshot name"));
J
Jiri Denemark 已提交
7534 7535 7536 7537
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(nameUtf16, &name);
        VBOX_UTF16_FREE(nameUtf16);
7538 7539
        if (VIR_STRDUP(names[i], name) < 0) {
            VBOX_UTF8_FREE(name);
J
Jiri Denemark 已提交
7540 7541
            goto cleanup;
        }
7542
        VBOX_UTF8_FREE(name);
J
Jiri Denemark 已提交
7543 7544 7545 7546 7547 7548 7549
    }

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

7550
 cleanup:
J
Jiri Denemark 已提交
7551 7552 7553 7554 7555 7556
    if (count > 0) {
        for (i = 0; i < count; i++)
            VBOX_RELEASE(snapshots[i]);
    }
    VIR_FREE(snapshots);
    VBOX_RELEASE(machine);
7557
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7558 7559 7560 7561 7562 7563
    return ret;
}

static virDomainSnapshotPtr
vboxDomainSnapshotLookupByName(virDomainPtr dom,
                               const char *name,
7564
                               unsigned int flags)
J
Jiri Denemark 已提交
7565 7566
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
7567
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7568 7569 7570 7571
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

7572 7573
    virCheckFlags(0, NULL);

7574
    vboxIIDFromUUID(&iid, dom->uuid);
7575
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
7576
    if (NS_FAILED(rc)) {
7577 7578
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7579 7580 7581 7582 7583 7584 7585 7586
        goto cleanup;
    }

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

    ret = virGetDomainSnapshot(dom, name);

7587
 cleanup:
J
Jiri Denemark 已提交
7588 7589
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
7590
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7591 7592 7593 7594 7595
    return ret;
}

static int
vboxDomainHasCurrentSnapshot(virDomainPtr dom,
7596
                             unsigned int flags)
J
Jiri Denemark 已提交
7597 7598
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7599
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7600 7601 7602 7603
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

7604 7605
    virCheckFlags(0, -1);

7606
    vboxIIDFromUUID(&iid, dom->uuid);
7607
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
7608
    if (NS_FAILED(rc)) {
7609 7610
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7611 7612 7613 7614 7615
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
7616 7617
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
J
Jiri Denemark 已提交
7618 7619 7620 7621 7622 7623 7624 7625
        goto cleanup;
    }

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

7626
 cleanup:
J
Jiri Denemark 已提交
7627
    VBOX_RELEASE(machine);
7628
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7629 7630 7631
    return ret;
}

7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650
static virDomainSnapshotPtr
vboxDomainSnapshotGetParent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    vboxIID iid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    ISnapshot *parent = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;

    virCheckFlags(0, NULL);

    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
7651 7652
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
7653 7654 7655 7656 7657 7658 7659 7660
        goto cleanup;
    }

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

    rc = snap->vtbl->GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
7661 7662 7663
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get parent of snapshot %s"),
                       snapshot->name);
7664 7665 7666
        goto cleanup;
    }
    if (!parent) {
7667 7668 7669
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshot->name);
7670 7671 7672 7673 7674
        goto cleanup;
    }

    rc = parent->vtbl->GetName(parent, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
7675 7676 7677
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get name of parent of snapshot %s"),
                       snapshot->name);
7678 7679 7680 7681 7682 7683 7684 7685 7686 7687
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    ret = virGetDomainSnapshot(dom, name);

7688
 cleanup:
7689 7690 7691 7692 7693 7694 7695 7696 7697
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(parent);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}

J
Jiri Denemark 已提交
7698 7699
static virDomainSnapshotPtr
vboxDomainSnapshotCurrent(virDomainPtr dom,
7700
                          unsigned int flags)
J
Jiri Denemark 已提交
7701 7702
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
7703
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7704 7705 7706 7707 7708 7709
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;

7710 7711
    virCheckFlags(0, NULL);

7712
    vboxIIDFromUUID(&iid, dom->uuid);
7713
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
7714
    if (NS_FAILED(rc)) {
7715 7716
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7717 7718 7719 7720 7721
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
7722 7723
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
J
Jiri Denemark 已提交
7724 7725 7726 7727
        goto cleanup;
    }

    if (!snapshot) {
7728 7729
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain has no snapshots"));
J
Jiri Denemark 已提交
7730 7731 7732 7733 7734
        goto cleanup;
    }

    rc = snapshot->vtbl->GetName(snapshot, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
7735 7736
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot name"));
J
Jiri Denemark 已提交
7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747
        goto cleanup;
    }

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

    ret = virGetDomainSnapshot(dom, name);

7748
 cleanup:
J
Jiri Denemark 已提交
7749 7750 7751 7752
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
7753
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7754 7755 7756
    return ret;
}

7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775
static int
vboxDomainSnapshotIsCurrent(virDomainSnapshotPtr snapshot,
                            unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID iid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    ISnapshot *current = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;

    virCheckFlags(0, -1);

    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
7776 7777
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
7778 7779 7780 7781 7782 7783 7784 7785
        goto cleanup;
    }

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

    rc = machine->vtbl->GetCurrentSnapshot(machine, &current);
    if (NS_FAILED(rc)) {
7786 7787
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
7788 7789 7790 7791 7792 7793 7794 7795 7796
        goto cleanup;
    }
    if (!current) {
        ret = 0;
        goto cleanup;
    }

    rc = current->vtbl->GetName(current, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
7797 7798
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot name"));
7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809
        goto cleanup;
    }

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

    ret = STREQ(snapshot->name, name);

7810
 cleanup:
7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(current);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}

static int
vboxDomainSnapshotHasMetadata(virDomainSnapshotPtr snapshot,
                              unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    vboxIID iid = VBOX_IID_INITIALIZER;
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    nsresult rc;

    virCheckFlags(0, -1);

    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
7836 7837
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
7838 7839 7840 7841 7842 7843 7844 7845 7846
        goto cleanup;
    }

    /* Check that snapshot exists.  If so, there is no metadata.  */
    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    ret = 0;

7847
 cleanup:
7848 7849 7850 7851 7852 7853
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}

7854
#if VBOX_API_VERSION < 3001000
J
Jiri Denemark 已提交
7855 7856 7857 7858 7859 7860
static int
vboxDomainSnapshotRestore(virDomainPtr dom,
                          IMachine *machine,
                          ISnapshot *snapshot)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7861
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7862 7863
    nsresult rc;

7864 7865
    rc = snapshot->vtbl->GetId(snapshot, &iid.value);
    if (NS_FAILED(rc)) {
7866 7867
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get snapshot UUID"));
J
Jiri Denemark 已提交
7868 7869 7870
        goto cleanup;
    }

7871
    rc = machine->vtbl->SetCurrentSnapshot(machine, iid.value);
J
Jiri Denemark 已提交
7872
    if (NS_FAILED(rc)) {
7873 7874
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not restore snapshot for domain %s"), dom->name);
J
Jiri Denemark 已提交
7875 7876 7877 7878 7879
        goto cleanup;
    }

    ret = 0;

7880
 cleanup:
7881
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895
    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;
7896
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7897

7898 7899
    rc = machine->vtbl->GetId(machine, &domiid.value);
    if (NS_FAILED(rc)) {
7900 7901
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain UUID"));
J
Jiri Denemark 已提交
7902 7903 7904 7905 7906
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
7907 7908
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
7909 7910 7911 7912 7913
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
7914 7915
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("domain %s is already running"), dom->name);
J
Jiri Denemark 已提交
7916 7917 7918
        goto cleanup;
    }

7919
    rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
7920 7921 7922
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
7923 7924 7925
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
7926 7927 7928 7929 7930 7931
        goto cleanup;
    }

    rc = console->vtbl->RestoreSnapshot(console, snapshot, &progress);
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
7932 7933
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot restore domain snapshot for running domain"));
J
Jiri Denemark 已提交
7934
        } else {
7935 7936 7937
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not restore snapshot for domain %s"),
                           dom->name);
J
Jiri Denemark 已提交
7938 7939 7940 7941 7942 7943 7944
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
7945 7946
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not restore snapshot for domain %s"), dom->name);
J
Jiri Denemark 已提交
7947 7948 7949 7950 7951
        goto cleanup;
    }

    ret = 0;

7952
 cleanup:
J
Jiri Denemark 已提交
7953 7954
    VBOX_RELEASE(progress);
    VBOX_RELEASE(console);
7955
    VBOX_SESSION_CLOSE();
7956
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
7957 7958 7959 7960 7961 7962
    return ret;
}
#endif

static int
vboxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
7963
                           unsigned int flags)
J
Jiri Denemark 已提交
7964 7965 7966
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7967
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7968 7969 7970 7971 7972 7973 7974
    IMachine *machine = NULL;
    ISnapshot *newSnapshot = NULL;
    ISnapshot *prevSnapshot = NULL;
    PRBool online = PR_FALSE;
    PRUint32 state;
    nsresult rc;

7975 7976
    virCheckFlags(0, -1);

7977
    vboxIIDFromUUID(&domiid, dom->uuid);
7978
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
7979
    if (NS_FAILED(rc)) {
7980 7981
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7982 7983 7984 7985 7986 7987 7988 7989 7990
        goto cleanup;
    }

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

    rc = newSnapshot->vtbl->GetOnline(newSnapshot, &online);
    if (NS_FAILED(rc)) {
7991 7992 7993
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get online state of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7994 7995 7996 7997 7998
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &prevSnapshot);
    if (NS_FAILED(rc)) {
7999 8000 8001
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get current snapshot of domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
8002 8003 8004 8005 8006
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
8007 8008
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
8009 8010 8011 8012 8013
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
8014 8015
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot revert snapshot of running domain"));
J
Jiri Denemark 已提交
8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028
        goto cleanup;
    }

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

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

8029
 cleanup:
J
Jiri Denemark 已提交
8030 8031
    VBOX_RELEASE(prevSnapshot);
    VBOX_RELEASE(newSnapshot);
8032
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
8033 8034 8035 8036 8037 8038 8039 8040 8041
    return ret;
}

static int
vboxDomainSnapshotDeleteSingle(vboxGlobalData *data,
                               IConsole *console,
                               ISnapshot *snapshot)
{
    IProgress *progress = NULL;
8042
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8043 8044
    int ret = -1;
    nsresult rc;
8045
#if VBOX_API_VERSION == 2002000
J
Jiri Denemark 已提交
8046 8047 8048 8049 8050
    nsresult result;
#else
    PRInt32 result;
#endif

8051 8052
    rc = snapshot->vtbl->GetId(snapshot, &iid.value);
    if (NS_FAILED(rc)) {
8053 8054
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get snapshot UUID"));
J
Jiri Denemark 已提交
8055 8056 8057
        goto cleanup;
    }

8058
#if VBOX_API_VERSION < 3001000
8059
    rc = console->vtbl->DiscardSnapshot(console, iid.value, &progress);
J
Jiri Denemark 已提交
8060
#else
8061
    rc = console->vtbl->DeleteSnapshot(console, iid.value, &progress);
J
Jiri Denemark 已提交
8062 8063 8064
#endif
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
8065 8066
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot delete domain snapshot for running domain"));
J
Jiri Denemark 已提交
8067
        } else {
8068 8069
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("could not delete snapshot"));
J
Jiri Denemark 已提交
8070 8071 8072 8073 8074 8075 8076
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
8077 8078
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not delete snapshot"));
J
Jiri Denemark 已提交
8079 8080 8081 8082 8083
        goto cleanup;
    }

    ret = 0;

8084
 cleanup:
J
Jiri Denemark 已提交
8085
    VBOX_RELEASE(progress);
8086
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
8087 8088 8089 8090 8091 8092 8093 8094
    return ret;
}

static int
vboxDomainSnapshotDeleteTree(vboxGlobalData *data,
                             IConsole *console,
                             ISnapshot *snapshot)
{
8095
    vboxArray children = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
8096 8097
    int ret = -1;
    nsresult rc;
8098
    size_t i;
J
Jiri Denemark 已提交
8099

8100
    rc = vboxArrayGet(&children, snapshot, snapshot->vtbl->GetChildren);
J
Jiri Denemark 已提交
8101
    if (NS_FAILED(rc)) {
8102 8103
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get children snapshots"));
J
Jiri Denemark 已提交
8104 8105 8106
        goto cleanup;
    }

8107 8108 8109
    for (i = 0; i < children.count; i++) {
        if (vboxDomainSnapshotDeleteTree(data, console, children.items[i]))
            goto cleanup;
J
Jiri Denemark 已提交
8110 8111 8112 8113
    }

    ret = vboxDomainSnapshotDeleteSingle(data, console, snapshot);

8114
 cleanup:
8115
    vboxArrayRelease(&children);
J
Jiri Denemark 已提交
8116 8117 8118
    return ret;
}

8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138
#if VBOX_API_VERSION >= 4002000
static int
vboxDomainSnapshotDeleteMetadataOnly(virDomainSnapshotPtr snapshot)
{
    /*
     * This function will remove the node in the vbox xml corresponding to the snapshot.
     * It is usually called by vboxDomainSnapshotDelete() with the flag
     * VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY.
     * If you want to use it anywhere else, be careful, if the snapshot you want to delete
     * has children, the result is not granted, they will probably will be deleted in the
     * xml, but you may have a problem with hard drives.
     *
     * If the snapshot which is being deleted is the current one, we will set the current
     * snapshot of the machine to the parent of this snapshot. Before writing the modified
     * xml file, we undefine the machine from vbox. After writing the file, we redefine
     * the machine with the new file.
     */

    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
8139
    virDomainSnapshotDefPtr def = NULL;
8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154
    char *defXml = NULL;
    vboxIID domiid = VBOX_IID_INITIALIZER;
    nsresult rc;
    IMachine *machine = NULL;
    PRUnichar *settingsFilePathUtf16 = NULL;
    char *settingsFilepath = NULL;
    virVBoxSnapshotConfMachinePtr snapshotMachineDesc = NULL;
    int isCurrent = -1;
    int it = 0;
    PRUnichar *machineNameUtf16 = NULL;
    char *machineName = NULL;
    char *nameTmpUse = NULL;
    char *machineLocationPath = NULL;
    PRUint32 aMediaSize = 0;
    IMedium **aMedia = NULL;
8155

8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196 8197 8198 8199 8200 8201 8202 8203 8204 8205 8206 8207 8208 8209 8210 8211 8212 8213 8214 8215 8216 8217 8218 8219 8220 8221 8222 8223 8224 8225 8226 8227 8228 8229 8230 8231 8232 8233 8234 8235 8236 8237 8238 8239 8240 8241 8242 8243 8244 8245 8246 8247 8248 8249 8250 8251 8252 8253 8254 8255 8256 8257 8258 8259 8260 8261 8262 8263 8264 8265 8266 8267 8268 8269 8270 8271 8272 8273 8274 8275 8276 8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289 8290 8291 8292 8293 8294 8295 8296 8297 8298 8299 8300 8301 8302 8303 8304 8305 8306 8307 8308 8309 8310 8311 8312 8313 8314 8315 8316 8317 8318 8319 8320 8321 8322 8323 8324 8325 8326 8327 8328 8329 8330
    defXml = vboxDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!defXml) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get XML Desc of snapshot"));
        goto cleanup;
    }
    def = virDomainSnapshotDefParseString(defXml,
                                          data->caps,
                                          data->xmlopt,
                                          -1,
                                          VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
                                          VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE);
    if (!def) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get a virDomainSnapshotDefPtr"));
        goto cleanup;
    }

    vboxIIDFromUUID(&domiid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
        goto cleanup;
    }
    rc = machine->vtbl->GetSettingsFilePath(machine, &settingsFilePathUtf16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get settings file path"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(settingsFilePathUtf16, &settingsFilepath);

    /*Getting the machine name to retrieve the machine location path.*/
    rc = machine->vtbl->GetName(machine, &machineNameUtf16);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot get machine name"));
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);
    if (virAsprintf(&nameTmpUse, "%s.vbox", machineName) < 0)
        goto cleanup;
    machineLocationPath = virStringReplace(settingsFilepath, nameTmpUse, "");
    if (machineLocationPath == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to get the machine location path"));
        goto cleanup;
    }
    snapshotMachineDesc = virVBoxSnapshotConfLoadVboxFile(settingsFilepath, machineLocationPath);
    if (!snapshotMachineDesc) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot create a vboxSnapshotXmlPtr"));
        goto cleanup;
    }

    isCurrent = virVBoxSnapshotConfIsCurrentSnapshot(snapshotMachineDesc, def->name);
    if (isCurrent < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to know if the snapshot is the current snapshot"));
        goto cleanup;
    }
    if (isCurrent) {
        /*
         * If the snapshot is the current snapshot, it means that the machine has read-write
         * disks. The first thing to do is to manipulate VirtualBox API to create
         * differential read-write disks if the parent snapshot is not null.
         */
        if (def->parent != NULL) {
            for (it = 0; it < def->dom->ndisks; it++) {
                virVBoxSnapshotConfHardDiskPtr readOnly = NULL;
                IMedium *medium = NULL;
                PRUnichar *locationUtf16 = NULL;
                PRUnichar *parentUuidUtf16 = NULL;
                char *parentUuid = NULL;
                IMedium *newMedium = NULL;
                PRUnichar *formatUtf16 = NULL;
                PRUnichar *newLocation = NULL;
                char *newLocationUtf8 = NULL;
                IProgress *progress = NULL;
                PRInt32 resultCode = -1;
                virVBoxSnapshotConfHardDiskPtr disk = NULL;
                PRUnichar *uuidUtf16 = NULL;
                char *uuid = NULL;
                char *format = NULL;
                char **searchResultTab = NULL;
                ssize_t resultSize = 0;
                char *tmp = NULL;

                readOnly = virVBoxSnapshotConfHardDiskPtrByLocation(snapshotMachineDesc,
                                                 def->dom->disks[it]->src->path);
                if (!readOnly) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Cannot get hard disk by location"));
                    goto cleanup;
                }
                if (readOnly->parent == NULL) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("The read only disk has no parent"));
                    goto cleanup;
                }

                VBOX_UTF8_TO_UTF16(readOnly->parent->location, &locationUtf16);
                rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                     locationUtf16,
                                                     DeviceType_HardDisk,
                                                     AccessMode_ReadWrite,
                                                     false,
                                                     &medium);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to open HardDisk, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }

                rc = medium->vtbl->GetId(medium, &parentUuidUtf16);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to get hardDisk Id, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
                VBOX_UTF16_TO_UTF8(parentUuidUtf16, &parentUuid);
                VBOX_UTF16_FREE(parentUuidUtf16);
                VBOX_UTF16_FREE(locationUtf16);
                VBOX_UTF8_TO_UTF16("VDI", &formatUtf16);

                if (virAsprintf(&newLocationUtf8, "%sfakedisk-%s-%d.vdi",
                                machineLocationPath, def->parent, it) < 0)
                    goto cleanup;
                VBOX_UTF8_TO_UTF16(newLocationUtf8, &newLocation);
                rc = data->vboxObj->vtbl->CreateHardDisk(data->vboxObj,
                                                         formatUtf16,
                                                         newLocation,
                                                         &newMedium);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to create HardDisk, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
                VBOX_UTF16_FREE(formatUtf16);
                VBOX_UTF16_FREE(newLocation);

# if VBOX_API_VERSION < 4003000
                medium->vtbl->CreateDiffStorage(medium, newMedium, MediumVariant_Diff, &progress);
# else
                PRUint32 tab[1];
                tab[0] =  MediumVariant_Diff;
                medium->vtbl->CreateDiffStorage(medium, newMedium, 1, tab, &progress);
# endif

                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_FAILED(resultCode)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Error while creating diff storage, rc=%08x"),
                                   (unsigned)resultCode);
                    goto cleanup;
                }
                VBOX_RELEASE(progress);
                /*
                 * The differential disk is created, we add it to the media registry and
                 * the machine storage controller.
                 */

                if (VIR_ALLOC(disk) < 0)
                    goto cleanup;

                rc = newMedium->vtbl->GetId(newMedium, &uuidUtf16);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to get medium uuid, rc=%08x"),
                                   (unsigned)rc);
8331
                    VIR_FREE(disk);
8332 8333 8334 8335 8336 8337
                    goto cleanup;
                }
                VBOX_UTF16_TO_UTF8(uuidUtf16, &uuid);
                disk->uuid = uuid;
                VBOX_UTF16_FREE(uuidUtf16);

8338 8339
                if (VIR_STRDUP(disk->location, newLocationUtf8) < 0) {
                    VIR_FREE(disk);
8340
                    goto cleanup;
8341
                }
8342 8343 8344 8345 8346 8347 8348 8349 8350 8351 8352 8353 8354 8355 8356 8357 8358 8359 8360 8361 8362 8363 8364 8365 8366 8367 8368 8369 8370 8371 8372 8373 8374 8375 8376 8377 8378 8379 8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399 8400 8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415 8416 8417 8418 8419 8420 8421 8422 8423 8424 8425 8426 8427 8428 8429 8430 8431 8432 8433 8434 8435 8436 8437 8438 8439 8440 8441 8442 8443 8444 8445 8446 8447 8448 8449 8450 8451 8452 8453 8454 8455 8456 8457 8458 8459 8460 8461 8462 8463 8464 8465 8466 8467 8468 8469 8470 8471 8472 8473 8474 8475 8476 8477 8478 8479 8480 8481 8482 8483 8484 8485 8486 8487 8488 8489 8490 8491 8492 8493 8494 8495 8496 8497 8498 8499 8500 8501 8502 8503 8504 8505 8506 8507 8508 8509 8510 8511 8512 8513 8514 8515 8516 8517 8518 8519 8520 8521 8522 8523 8524 8525 8526 8527 8528 8529 8530 8531 8532 8533 8534 8535 8536 8537 8538 8539 8540 8541 8542 8543 8544 8545 8546 8547 8548 8549 8550 8551 8552 8553 8554 8555 8556 8557 8558 8559 8560 8561 8562 8563 8564 8565 8566 8567 8568 8569 8570 8571 8572 8573

                rc = newMedium->vtbl->GetFormat(newMedium, &formatUtf16);
                VBOX_UTF16_TO_UTF8(formatUtf16, &format);
                disk->format = format;
                VBOX_UTF16_FREE(formatUtf16);

                if (virVBoxSnapshotConfAddHardDiskToMediaRegistry(disk,
                                               snapshotMachineDesc->mediaRegistry,
                                               parentUuid) < 0) {
                    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                                   _("Unable to add hard disk to the media registry"));
                    goto cleanup;
                }
                /*Adding fake disks to the machine storage controllers*/

                resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                             VBOX_UUID_REGEX,
                                             it + 1,
                                             &searchResultTab);
                if (resultSize != it + 1) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to find UUID %s"), searchResultTab[it]);
                    goto cleanup;
                }

                tmp = virStringReplace(snapshotMachineDesc->storageController,
                                       searchResultTab[it],
                                       disk->uuid);
                virStringFreeList(searchResultTab);
                VIR_FREE(snapshotMachineDesc->storageController);
                if (!tmp)
                    goto cleanup;
                if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                    goto cleanup;

                VIR_FREE(tmp);
                /*Closing the "fake" disk*/
                rc = newMedium->vtbl->Close(newMedium);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to close the new medium, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
            }
        } else {
            for (it = 0; it < def->dom->ndisks; it++) {
                const char *uuidRO = NULL;
                char **searchResultTab = NULL;
                ssize_t resultSize = 0;
                char *tmp = NULL;
                uuidRO = virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
                                                      def->dom->disks[it]->src->path);
                if (!uuidRO) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("No such disk in media registry %s"),
                                   def->dom->disks[it]->src->path);
                    goto cleanup;
                }

                resultSize = virStringSearch(snapshotMachineDesc->storageController,
                                             VBOX_UUID_REGEX,
                                             it + 1,
                                             &searchResultTab);
                if (resultSize != it + 1) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to find UUID %s"),
                                   searchResultTab[it]);
                    goto cleanup;
                }

                tmp = virStringReplace(snapshotMachineDesc->storageController,
                                       searchResultTab[it],
                                       uuidRO);
                virStringFreeList(searchResultTab);
                VIR_FREE(snapshotMachineDesc->storageController);
                if (!tmp)
                    goto cleanup;
                if (VIR_STRDUP(snapshotMachineDesc->storageController, tmp) < 0)
                    goto cleanup;

                VIR_FREE(tmp);
            }
        }
    }
    /*We remove the read write disks from the media registry*/
    for (it = 0; it < def->ndisks; it++) {
        const char *uuidRW =
            virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
                                                      def->disks[it].src->path);
        if (!uuidRW) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to find UUID for location %s"), def->disks[it].src->path);
            goto cleanup;
        }
        if (virVBoxSnapshotConfRemoveHardDisk(snapshotMachineDesc->mediaRegistry, uuidRW) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unable to remove disk from media registry. uuid = %s"), uuidRW);
            goto cleanup;
        }
    }
    /*If the parent snapshot is not NULL, we remove the-read only disks from the media registry*/
    if (def->parent != NULL) {
        for (it = 0; it < def->dom->ndisks; it++) {
            const char *uuidRO =
                virVBoxSnapshotConfHardDiskUuidByLocation(snapshotMachineDesc,
                                                          def->dom->disks[it]->src->path);
            if (!uuidRO) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to find UUID for location %s"), def->dom->disks[it]->src->path);
                goto cleanup;
            }
            if (virVBoxSnapshotConfRemoveHardDisk(snapshotMachineDesc->mediaRegistry, uuidRO) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to remove disk from media registry. uuid = %s"), uuidRO);
                goto cleanup;
            }
        }
    }
    rc = machine->vtbl->Unregister(machine,
                              CleanupMode_DetachAllReturnHardDisksOnly,
                              &aMediaSize,
                              &aMedia);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to unregister machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }
    VBOX_RELEASE(machine);
    for (it = 0; it < aMediaSize; it++) {
        IMedium *medium = aMedia[it];
        if (medium) {
            PRUnichar *locationUtf16 = NULL;
            char *locationUtf8 = NULL;
            rc = medium->vtbl->GetLocation(medium, &locationUtf16);
            VBOX_UTF16_TO_UTF8(locationUtf16, &locationUtf8);
            if (isCurrent && strstr(locationUtf8, "fake") != NULL) {
                /*we delete the fake disk because we don't need it anymore*/
                IProgress *progress = NULL;
                PRInt32 resultCode = -1;
                rc = medium->vtbl->DeleteStorage(medium, &progress);
                if (NS_FAILED(rc)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Unable to delete medium, rc=%08x"),
                                   (unsigned)rc);
                    goto cleanup;
                }
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_FAILED(resultCode)) {
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Error while closing medium, rc=%08x"),
                                   (unsigned)resultCode);
                    goto cleanup;
                }
                VBOX_RELEASE(progress);
            } else {
                /* This a comment from vboxmanage code in the handleUnregisterVM
                 * function in VBoxManageMisc.cpp :
                 * Note that the IMachine::Unregister method will return the medium
                 * reference in a sane order, which means that closing will normally
                 * succeed, unless there is still another machine which uses the
                 * medium. No harm done if we ignore the error. */
                rc = medium->vtbl->Close(medium);
            }
            VBOX_UTF16_FREE(locationUtf16);
            VBOX_UTF8_FREE(locationUtf8);
        }
    }

    /*removing the snapshot*/
    if (virVBoxSnapshotConfRemoveSnapshot(snapshotMachineDesc, def->name) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to remove snapshot %s"), def->name);
        goto cleanup;
    }

    if (isCurrent) {
        VIR_FREE(snapshotMachineDesc->currentSnapshot);
        if (def->parent != NULL) {
            virVBoxSnapshotConfSnapshotPtr snap = virVBoxSnapshotConfSnapshotByName(snapshotMachineDesc->snapshot, def->parent);
            if (!snap) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Unable to get the snapshot to remove"));
                goto cleanup;
            }
            if (VIR_STRDUP(snapshotMachineDesc->currentSnapshot, snap->uuid) < 0)
                goto cleanup;
        }
    }

    /*Registering the machine*/
    if (virVBoxSnapshotConfSaveVboxFile(snapshotMachineDesc, settingsFilepath) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to serialize the machine description"));
        goto cleanup;
    }
    rc = data->vboxObj->vtbl->OpenMachine(data->vboxObj,
                                     settingsFilePathUtf16,
                                     &machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to open Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    rc = data->vboxObj->vtbl->RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Unable to register Machine, rc=%08x"),
                       (unsigned)rc);
        goto cleanup;
    }

    ret = 0;
 cleanup:
    VIR_FREE(def);
    VIR_FREE(defXml);
    VBOX_RELEASE(machine);
    VBOX_UTF16_FREE(settingsFilePathUtf16);
    VBOX_UTF8_FREE(settingsFilepath);
    VIR_FREE(snapshotMachineDesc);
    VBOX_UTF16_FREE(machineNameUtf16);
    VBOX_UTF8_FREE(machineName);
    VIR_FREE(machineLocationPath);
    VIR_FREE(nameTmpUse);

    return ret;
}
#endif
8574

J
Jiri Denemark 已提交
8575 8576 8577 8578 8579 8580
static int
vboxDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                         unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
8581
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8582 8583 8584 8585 8586
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IConsole *console = NULL;
    PRUint32 state;
    nsresult rc;
8587
    vboxArray snapChildren = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
8588

8589 8590
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
8591

8592
    vboxIIDFromUUID(&domiid, dom->uuid);
8593
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
8594
    if (NS_FAILED(rc)) {
8595 8596
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
8597 8598 8599 8600 8601 8602 8603 8604 8605
        goto cleanup;
    }

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

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
8606 8607
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
8608 8609 8610
        goto cleanup;
    }

8611 8612 8613
    /* In case we just want to delete the metadata, we will edit the vbox file in order
     *to remove the node concerning the snapshot
    */
8614
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY) {
8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629
        rc = vboxArrayGet(&snapChildren, snap, snap->vtbl->GetChildren);
        if (NS_FAILED(rc)) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("could not get snapshot children"));
            goto cleanup;
        }
        if (snapChildren.count != 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("cannot delete metadata of a snapshot with children"));
            goto cleanup;
        } else {
#if VBOX_API_VERSION >= 4002000
            ret = vboxDomainSnapshotDeleteMetadataOnly(snapshot);
#endif
        }
8630 8631 8632
        goto cleanup;
    }

J
Jiri Denemark 已提交
8633 8634
    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
8635 8636
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot delete snapshots of running domain"));
J
Jiri Denemark 已提交
8637 8638 8639
        goto cleanup;
    }

8640
    rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
8641 8642 8643
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
8644 8645 8646
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
8647 8648 8649 8650 8651 8652 8653 8654
        goto cleanup;
    }

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

8655
 cleanup:
J
Jiri Denemark 已提交
8656 8657
    VBOX_RELEASE(console);
    VBOX_RELEASE(snap);
8658
    vboxIIDUnalloc(&domiid);
8659
    VBOX_SESSION_CLOSE();
J
Jiri Denemark 已提交
8660 8661 8662
    return ret;
}

8663
#if VBOX_API_VERSION <= 2002000 || VBOX_API_VERSION >= 4000000
8664
    /* No Callback support for VirtualBox 2.2.* series */
8665
    /* No Callback support for VirtualBox 4.* series */
8666
#else /* !(VBOX_API_VERSION == 2002000 || VBOX_API_VERSION >= 4000000) */
8667 8668

/* Functions needed for Callbacks */
8669
static nsresult PR_COM_METHOD
8670
vboxCallbackOnMachineStateChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8671 8672
                                 PRUnichar *machineId, PRUint32 state)
{
8673 8674 8675 8676 8677 8678
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

    vboxDriverLock(g_pVBoxGlobalData);

8679
    VIR_DEBUG("IVirtualBoxCallback: %p, State: %d", pThis, state);
8680 8681 8682 8683 8684 8685 8686
    DEBUGPRUnichar("machineId", machineId);

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

        g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(machineId, &machineIdUtf8);
8687
        ignore_value(virUUIDParse(machineIdUtf8, uuid));
8688 8689 8690

        dom = vboxDomainLookupByUUID(g_pVBoxGlobalData->conn, uuid);
        if (dom) {
8691
            virObjectEventPtr ev;
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

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

8722
            ev = virDomainEventLifecycleNewFromDom(dom, event, detail);
8723

8724
            if (ev)
8725
                virObjectEventStateQueue(g_pVBoxGlobalData->domainEvents, ev);
8726 8727 8728 8729 8730 8731 8732 8733
        }
    }

    vboxDriverUnlock(g_pVBoxGlobalData);

    return NS_OK;
}

8734
static nsresult PR_COM_METHOD
8735
vboxCallbackOnMachineDataChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8736 8737
                                PRUnichar *machineId)
{
8738
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
8739 8740 8741 8742 8743
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

8744
static nsresult PR_COM_METHOD
8745
vboxCallbackOnExtraDataCanChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8746 8747 8748
                                 PRUnichar *machineId, PRUnichar *key,
                                 PRUnichar *value,
                                 PRUnichar **error ATTRIBUTE_UNUSED,
8749
                                 PRBool *allowChange ATTRIBUTE_UNUSED)
8750
{
8751
    VIR_DEBUG("IVirtualBoxCallback: %p, allowChange: %s", pThis, *allowChange ? "true" : "false");
8752 8753 8754 8755 8756 8757 8758
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

8759
static nsresult PR_COM_METHOD
8760 8761
vboxCallbackOnExtraDataChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                              PRUnichar *machineId,
8762 8763
                              PRUnichar *key, PRUnichar *value)
{
8764
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
8765 8766 8767 8768 8769 8770 8771
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

8772
# if VBOX_API_VERSION < 3001000
8773
static nsresult PR_COM_METHOD
8774 8775 8776 8777
vboxCallbackOnMediaRegistered(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                              PRUnichar *mediaId,
                              PRUint32 mediaType ATTRIBUTE_UNUSED,
                              PRBool registered ATTRIBUTE_UNUSED)
8778
{
8779 8780
    VIR_DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
    VIR_DEBUG("mediaType: %d", mediaType);
8781 8782 8783 8784
    DEBUGPRUnichar("mediaId", mediaId);

    return NS_OK;
}
8785 8786
# else  /* VBOX_API_VERSION >= 3001000 */
# endif /* VBOX_API_VERSION >= 3001000 */
8787

8788
static nsresult PR_COM_METHOD
8789
vboxCallbackOnMachineRegistered(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8790 8791
                                PRUnichar *machineId, PRBool registered)
{
8792 8793 8794 8795 8796 8797
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

    vboxDriverLock(g_pVBoxGlobalData);

8798
    VIR_DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
8799 8800 8801 8802 8803 8804 8805
    DEBUGPRUnichar("machineId", machineId);

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

        g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(machineId, &machineIdUtf8);
8806
        ignore_value(virUUIDParse(machineIdUtf8, uuid));
8807 8808 8809

        dom = vboxDomainLookupByUUID(g_pVBoxGlobalData->conn, uuid);
        if (dom) {
8810
            virObjectEventPtr ev;
8811 8812

            /* CURRENT LIMITATION: we never get the VIR_DOMAIN_EVENT_UNDEFINED
J
Ján Tomko 已提交
8813
             * event because the when the machine is de-registered the call
8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825
             * 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;
            }

8826
            ev = virDomainEventLifecycleNewFromDom(dom, event, detail);
8827

8828
            if (ev)
8829
                virObjectEventStateQueue(g_pVBoxGlobalData->domainEvents, ev);
8830 8831 8832 8833 8834 8835 8836 8837
        }
    }

    vboxDriverUnlock(g_pVBoxGlobalData);

    return NS_OK;
}

8838
static nsresult PR_COM_METHOD
8839 8840 8841
vboxCallbackOnSessionStateChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                                 PRUnichar *machineId,
                                 PRUint32 state ATTRIBUTE_UNUSED)
8842
{
8843
    VIR_DEBUG("IVirtualBoxCallback: %p, state: %d", pThis, state);
8844 8845 8846 8847 8848
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

8849
static nsresult PR_COM_METHOD
8850 8851
vboxCallbackOnSnapshotTaken(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                            PRUnichar *machineId,
8852 8853
                            PRUnichar *snapshotId)
{
8854
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
8855 8856 8857 8858 8859 8860
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

8861
static nsresult PR_COM_METHOD
8862 8863
vboxCallbackOnSnapshotDiscarded(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                                PRUnichar *machineId,
8864 8865
                                PRUnichar *snapshotId)
{
8866
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
8867 8868 8869 8870 8871 8872
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

8873
static nsresult PR_COM_METHOD
8874 8875
vboxCallbackOnSnapshotChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                             PRUnichar *machineId,
8876 8877
                             PRUnichar *snapshotId)
{
8878
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
8879 8880 8881 8882 8883 8884
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

8885
static nsresult PR_COM_METHOD
8886
vboxCallbackOnGuestPropertyChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8887 8888 8889
                                  PRUnichar *machineId, PRUnichar *name,
                                  PRUnichar *value, PRUnichar *flags)
{
8890
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
8891 8892 8893 8894 8895 8896 8897 8898
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("name", name);
    DEBUGPRUnichar("value", value);
    DEBUGPRUnichar("flags", flags);

    return NS_OK;
}

8899
static nsresult PR_COM_METHOD
8900
vboxCallbackAddRef(nsISupports *pThis ATTRIBUTE_UNUSED)
8901
{
8902 8903 8904 8905
    nsresult c;

    c = ++g_pVBoxGlobalData->vboxCallBackRefCount;

8906
    VIR_DEBUG("pThis: %p, vboxCallback AddRef: %d", pThis, c);
8907 8908 8909 8910

    return c;
}

8911 8912 8913
static nsresult PR_COM_METHOD
vboxCallbackRelease(nsISupports *pThis)
{
8914 8915 8916 8917 8918 8919 8920 8921 8922
    nsresult c;

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

8923
    VIR_DEBUG("pThis: %p, vboxCallback Release: %d", pThis, c);
8924 8925 8926 8927

    return c;
}

8928 8929 8930
static nsresult PR_COM_METHOD
vboxCallbackQueryInterface(nsISupports *pThis, const nsID *iid, void **resultp)
{
8931 8932 8933 8934 8935
    IVirtualBoxCallback *that = (IVirtualBoxCallback *)pThis;
    static const nsID ivirtualboxCallbackUUID = IVIRTUALBOXCALLBACK_IID;
    static const nsID isupportIID = NS_ISUPPORTS_IID;

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

8941
        VIR_DEBUG("pThis: %p, vboxCallback QueryInterface: %d", pThis, g_pVBoxGlobalData->vboxCallBackRefCount);
8942 8943 8944 8945 8946

        return NS_OK;
    }


8947
    VIR_DEBUG("pThis: %p, vboxCallback QueryInterface didn't find a matching interface", pThis);
8948 8949 8950 8951 8952 8953
    DEBUGUUID("The UUID Callback Interface expects", iid);
    DEBUGUUID("The UUID Callback Interface got", &ivirtualboxCallbackUUID);
    return NS_NOINTERFACE;
}


8954
static IVirtualBoxCallback *vboxAllocCallbackObj(void) {
8955 8956
    IVirtualBoxCallback *vboxCallback = NULL;

8957
    /* Allocate, Initialize and return a valid
8958 8959 8960
     * IVirtualBoxCallback object here
     */
    if ((VIR_ALLOC(vboxCallback) < 0) || (VIR_ALLOC(vboxCallback->vtbl) < 0)) {
8961
        VIR_FREE(vboxCallback);
8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972
        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;
8973
# if VBOX_API_VERSION < 3001000
8974
        vboxCallback->vtbl->OnMediaRegistered           = &vboxCallbackOnMediaRegistered;
8975 8976
# else  /* VBOX_API_VERSION >= 3001000 */
# endif /* VBOX_API_VERSION >= 3001000 */
8977 8978 8979
        vboxCallback->vtbl->OnMachineRegistered         = &vboxCallbackOnMachineRegistered;
        vboxCallback->vtbl->OnSessionStateChange        = &vboxCallbackOnSessionStateChange;
        vboxCallback->vtbl->OnSnapshotTaken             = &vboxCallbackOnSnapshotTaken;
8980
# if VBOX_API_VERSION < 3002000
8981
        vboxCallback->vtbl->OnSnapshotDiscarded         = &vboxCallbackOnSnapshotDiscarded;
8982
# else /* VBOX_API_VERSION >= 3002000 */
8983
        vboxCallback->vtbl->OnSnapshotDeleted           = &vboxCallbackOnSnapshotDiscarded;
8984
# endif /* VBOX_API_VERSION >= 3002000 */
8985 8986 8987 8988 8989 8990 8991 8992 8993 8994 8995 8996
        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,
8997 8998
                             void *opaque ATTRIBUTE_UNUSED)
{
8999 9000 9001 9002 9003 9004 9005 9006 9007 9008 9009 9010
    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);
    }
}

9011 9012 9013 9014 9015 9016
static int
vboxConnectDomainEventRegister(virConnectPtr conn,
                               virConnectDomainEventCallback callback,
                               void *opaque,
                               virFreeCallback freecb)
{
9017
    VBOX_OBJECT_CHECK(conn, int, -1);
9018
    int vboxRet          = -1;
9019
    nsresult rc;
9020 9021 9022 9023 9024 9025

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

9026
    if (data->vboxCallback == NULL) {
9027
        data->vboxCallback = vboxAllocCallbackObj();
9028 9029 9030 9031
        if (data->vboxCallback != NULL) {
            rc = data->vboxObj->vtbl->RegisterCallback(data->vboxObj, data->vboxCallback);
            if (NS_SUCCEEDED(rc)) {
                vboxRet = 0;
9032 9033
            }
        }
9034 9035 9036
    } else {
        vboxRet = 0;
    }
9037

9038 9039 9040 9041 9042 9043 9044
    /* 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);
9045

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

9049 9050 9051 9052 9053
        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
             */
9054

9055
            ret = virDomainEventStateRegister(conn, data->domainEvents,
9056
                                              callback, opaque, freecb);
9057
            VIR_DEBUG("virObjectEventStateRegister (ret = %d) (conn: %p, "
9058
                      "callback: %p, opaque: %p, "
9059
                      "freecb: %p)", ret, conn, callback,
9060
                      opaque, freecb);
9061 9062 9063 9064 9065 9066
        }
    }

    vboxDriverUnlock(data);

    if (ret >= 0) {
9067
        return 0;
9068 9069 9070 9071 9072 9073 9074 9075
    } else {
        if (data->vboxObj && data->vboxCallback) {
            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        }
        return -1;
    }
}

9076 9077 9078 9079
static int
vboxConnectDomainEventDeregister(virConnectPtr conn,
                                 virConnectDomainEventCallback callback)
{
9080
    VBOX_OBJECT_CHECK(conn, int, -1);
9081
    int cnt;
9082 9083 9084 9085 9086 9087

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

9088 9089
    cnt = virDomainEventStateDeregister(conn, data->domainEvents,
                                        callback);
9090

9091 9092 9093
    if (data->vboxCallback && cnt == 0) {
        data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        VBOX_RELEASE(data->vboxCallback);
9094

9095 9096 9097
        /* Remove the Event file handle on which we are listening as well */
        virEventRemoveHandle(data->fdWatch);
        data->fdWatch = -1;
9098 9099 9100 9101
    }

    vboxDriverUnlock(data);

9102 9103 9104
    if (cnt >= 0)
        ret = 0;

9105 9106 9107
    return ret;
}

9108 9109 9110 9111 9112
static int vboxConnectDomainEventRegisterAny(virConnectPtr conn,
                                             virDomainPtr dom,
                                             int eventID,
                                             virConnectDomainEventGenericCallback callback,
                                             void *opaque,
9113 9114
                                             virFreeCallback freecb)
{
9115 9116 9117 9118 9119 9120 9121 9122 9123 9124 9125 9126 9127 9128 9129 9130 9131 9132 9133 9134 9135 9136 9137 9138 9139 9140 9141 9142 9143 9144 9145 9146 9147 9148 9149 9150 9151 9152
    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
             */

9153
            if (virDomainEventStateRegisterID(conn, data->domainEvents,
9154 9155
                                              dom, eventID,
                                              callback, opaque, freecb, &ret) < 0)
9156
                ret = -1;
9157
            VIR_DEBUG("virDomainEventStateRegisterID (ret = %d) (conn: %p, "
9158
                      "callback: %p, opaque: %p, "
9159
                      "freecb: %p)", ret, conn, callback,
9160
                      opaque, freecb);
9161 9162 9163 9164 9165 9166 9167 9168 9169 9170 9171 9172 9173 9174 9175
        }
    }

    vboxDriverUnlock(data);

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

9176 9177 9178 9179
static int
vboxConnectDomainEventDeregisterAny(virConnectPtr conn,
                                    int callbackID)
{
9180
    VBOX_OBJECT_CHECK(conn, int, -1);
9181
    int cnt;
9182 9183 9184 9185 9186 9187

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

9188
    cnt = virObjectEventStateDeregisterID(conn, data->domainEvents,
9189
                                          callbackID);
9190

9191 9192 9193
    if (data->vboxCallback && cnt == 0) {
        data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        VBOX_RELEASE(data->vboxCallback);
9194

9195 9196 9197
        /* Remove the Event file handle on which we are listening as well */
        virEventRemoveHandle(data->fdWatch);
        data->fdWatch = -1;
9198 9199 9200 9201
    }

    vboxDriverUnlock(data);

9202 9203 9204
    if (cnt >= 0)
        ret = 0;

9205 9206 9207
    return ret;
}

9208
#endif /* !(VBOX_API_VERSION == 2002000 || VBOX_API_VERSION >= 4000000) */
9209

9210 9211 9212 9213 9214
/**
 * The Network Functions here on
 */
static virDrvOpenStatus vboxNetworkOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
9215 9216
                                        unsigned int flags)
{
9217 9218
    vboxGlobalData *data = conn->privateData;

E
Eric Blake 已提交
9219 9220
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

9221 9222 9223 9224 9225 9226 9227 9228
    if (STRNEQ(conn->driver->name, "VBOX"))
        goto cleanup;

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

9229
    VIR_DEBUG("network initialized");
9230 9231 9232
    /* conn->networkPrivateData = some network specific data */
    return VIR_DRV_OPEN_SUCCESS;

9233
 cleanup:
9234 9235 9236
    return VIR_DRV_OPEN_DECLINED;
}

9237 9238
static int vboxNetworkClose(virConnectPtr conn)
{
9239
    VIR_DEBUG("network uninitialized");
9240 9241 9242 9243
    conn->networkPrivateData = NULL;
    return 0;
}

9244 9245
static int vboxConnectNumOfNetworks(virConnectPtr conn)
{
9246
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9247
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9248
    size_t i = 0;
9249

9250
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
9251

9252 9253 9254 9255
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
9256
            PRUint32 interfaceType = 0;
9257

9258
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9259 9260
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9261

9262
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9263

9264 9265
                if (status == HostNetworkInterfaceStatus_Up)
                    ret++;
9266 9267 9268 9269
            }
        }
    }

9270 9271
    vboxArrayRelease(&networkInterfaces);

9272 9273
    VBOX_RELEASE(host);

9274
    VIR_DEBUG("numActive: %d", ret);
9275
    return ret;
9276 9277
}

9278
static int vboxConnectListNetworks(virConnectPtr conn, char **const names, int nnames) {
9279
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9280
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9281
    size_t i = 0;
9282

9283 9284 9285 9286
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

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

9288
        if (networkInterface) {
9289
            PRUint32 interfaceType = 0;
9290

9291
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9292

9293 9294
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9295

9296
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9297

9298 9299 9300
                if (status == HostNetworkInterfaceStatus_Up) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
9301

9302
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
9303
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
9304

9305
                    VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8);
J
Ján Tomko 已提交
9306
                    if (VIR_STRDUP(names[ret], nameUtf8) >= 0)
9307
                        ret++;
9308

9309 9310
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
9311 9312 9313 9314 9315
                }
            }
        }
    }

9316
    vboxArrayRelease(&networkInterfaces);
9317

9318
    VBOX_RELEASE(host);
9319

9320 9321
    return ret;
}
9322

9323 9324
static int vboxConnectNumOfDefinedNetworks(virConnectPtr conn)
{
9325
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9326
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9327
    size_t i = 0;
9328

9329
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
9330

9331 9332 9333 9334
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
9335
            PRUint32 interfaceType = 0;
9336

9337
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9338 9339
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9340

9341
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9342

9343 9344
                if (status == HostNetworkInterfaceStatus_Down)
                    ret++;
9345 9346 9347 9348
            }
        }
    }

9349 9350
    vboxArrayRelease(&networkInterfaces);

9351 9352
    VBOX_RELEASE(host);

9353
    VIR_DEBUG("numActive: %d", ret);
9354
    return ret;
9355 9356
}

9357
static int vboxConnectListDefinedNetworks(virConnectPtr conn, char **const names, int nnames) {
9358
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9359
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9360
    size_t i = 0;
9361

9362 9363 9364 9365
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

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

9367
        if (networkInterface) {
9368
            PRUint32 interfaceType = 0;
9369

9370
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9371

9372 9373
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9374

9375
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9376

9377 9378 9379
                if (status == HostNetworkInterfaceStatus_Down) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
9380

9381
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
9382
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
9383

9384
                    VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8);
J
Ján Tomko 已提交
9385
                    if (VIR_STRDUP(names[ret], nameUtf8) >= 0)
9386
                        ret++;
9387

9388 9389
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
9390 9391 9392 9393 9394
                }
            }
        }
    }

9395
    vboxArrayRelease(&networkInterfaces);
9396 9397 9398 9399

    VBOX_RELEASE(host);

    return ret;
9400 9401
}

9402 9403 9404
static virNetworkPtr
vboxNetworkLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
9405
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
9406
    vboxIID iid = VBOX_IID_INITIALIZER;
9407

9408
    vboxIIDFromUUID(&iid, uuid);
9409

9410 9411 9412
    /* TODO: "internal" networks are just strings and
     * thus can't do much with them
     */
9413
    IHostNetworkInterface *networkInterface = NULL;
9414

9415
    host->vtbl->FindHostNetworkInterfaceById(host, iid.value, &networkInterface);
9416 9417
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9418

9419
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9420

9421 9422 9423
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            char *nameUtf8       = NULL;
            PRUnichar *nameUtf16 = NULL;
9424

9425 9426
            networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
            VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
9427

9428
            ret = virGetNetwork(conn, nameUtf8, uuid);
9429

9430
            VIR_DEBUG("Network Name: %s", nameUtf8);
9431
            DEBUGIID("Network UUID", iid.value);
9432

9433 9434
            VBOX_UTF8_FREE(nameUtf8);
            VBOX_UTF16_FREE(nameUtf16);
9435
        }
9436 9437

        VBOX_RELEASE(networkInterface);
9438 9439
    }

9440 9441
    VBOX_RELEASE(host);

9442
    vboxIIDUnalloc(&iid);
9443 9444 9445
    return ret;
}

9446 9447 9448
static virNetworkPtr
vboxNetworkLookupByName(virConnectPtr conn, const char *name)
{
9449 9450 9451
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *nameUtf16                    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9452

9453
    VBOX_UTF8_TO_UTF16(name, &nameUtf16);
9454

9455
    host->vtbl->FindHostNetworkInterfaceByName(host, nameUtf16, &networkInterface);
9456

9457 9458
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9459

9460
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9461

9462 9463
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            unsigned char uuid[VIR_UUID_BUFLEN];
9464
            vboxIID iid = VBOX_IID_INITIALIZER;
9465

9466 9467
            networkInterface->vtbl->GetId(networkInterface, &iid.value);
            vboxIIDToUUID(&iid, uuid);
9468
            ret = virGetNetwork(conn, name, uuid);
9469
            VIR_DEBUG("Network Name: %s", name);
9470

9471 9472
            DEBUGIID("Network UUID", iid.value);
            vboxIIDUnalloc(&iid);
9473
        }
9474 9475

        VBOX_RELEASE(networkInterface);
9476 9477
    }

9478 9479 9480
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(host);

9481 9482 9483
    return ret;
}

9484 9485 9486
static virNetworkPtr
vboxNetworkDefineCreateXML(virConnectPtr conn, const char *xml, bool start)
{
9487 9488 9489 9490
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    char      *networkInterfaceNameUtf8     = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9491
    nsresult rc;
9492

9493
    virNetworkDefPtr def = virNetworkDefParseString(xml);
9494 9495
    virNetworkIpDefPtr ipdef;
    virSocketAddr netmask;
9496

9497
    if ((!def) ||
9498
        (def->forward.type != VIR_NETWORK_FORWARD_NONE) ||
9499
        (def->nips == 0 || !def->ips))
9500 9501 9502 9503 9504 9505 9506 9507 9508 9509 9510
        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)
9511
        goto cleanup;
9512

9513 9514 9515 9516 9517 9518
    /* 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.
     */
9519

9520
#if VBOX_API_VERSION == 2002000
9521
    if (STREQ(def->name, "vboxnet0")) {
9522
        PRUint32 interfaceType = 0;
9523

9524 9525
        VBOX_UTF8_TO_UTF16(def->name, &networkInterfaceNameUtf16);
        host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
9526

9527 9528 9529 9530 9531 9532
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
        if (interfaceType != HostNetworkInterfaceType_HostOnly) {
            VBOX_RELEASE(networkInterface);
            networkInterface = NULL;
        }
    }
9533
#else /* VBOX_API_VERSION != 2002000 */
9534 9535 9536 9537
    {
        IProgress *progress = NULL;
        host->vtbl->CreateHostOnlyNetworkInterface(host, &networkInterface,
                                                   &progress);
9538

9539 9540 9541 9542
        if (progress) {
            progress->vtbl->WaitForCompletion(progress, -1);
            VBOX_RELEASE(progress);
        }
9543
    }
9544
#endif /* VBOX_API_VERSION != 2002000 */
9545

9546 9547 9548 9549
    if (networkInterface) {
        unsigned char uuid[VIR_UUID_BUFLEN];
        char      *networkNameUtf8  = NULL;
        PRUnichar *networkNameUtf16 = NULL;
9550
        vboxIID vboxnetiid = VBOX_IID_INITIALIZER;
9551 9552 9553 9554 9555 9556 9557 9558 9559 9560 9561

        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);
                goto cleanup;
            }
        }
9562

E
Eric Blake 已提交
9563
        VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
9564

9565 9566 9567
        /* Currently support only one dhcp server per network
         * with contigious address space from start to end
         */
9568
        if ((ipdef->nranges >= 1) &&
9569 9570
            VIR_SOCKET_ADDR_VALID(&ipdef->ranges[0].start) &&
            VIR_SOCKET_ADDR_VALID(&ipdef->ranges[0].end)) {
9571 9572 9573 9574 9575 9576 9577 9578 9579 9580
            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);
9581
                VIR_DEBUG("couldn't find dhcp server so creating one");
9582 9583 9584 9585 9586 9587 9588 9589
            }
            if (dhcpServer) {
                PRUnichar *ipAddressUtf16     = NULL;
                PRUnichar *networkMaskUtf16   = NULL;
                PRUnichar *fromIPAddressUtf16 = NULL;
                PRUnichar *toIPAddressUtf16   = NULL;
                PRUnichar *trunkTypeUtf16     = NULL;

9590 9591 9592 9593
                ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->address);
                networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
                fromIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].start);
                toIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].end);
9594 9595 9596 9597 9598 9599 9600 9601 9602 9603

                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;
                }
9604 9605 9606 9607 9608 9609 9610 9611 9612 9613 9614 9615 9616 9617 9618 9619 9620 9621 9622 9623 9624 9625 9626 9627 9628

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

9630
        if ((ipdef->nhosts >= 1) &&
9631
            VIR_SOCKET_ADDR_VALID(&ipdef->hosts[0].ip)) {
9632 9633
            PRUnichar *ipAddressUtf16   = NULL;
            PRUnichar *networkMaskUtf16 = NULL;
9634

9635 9636
            ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->hosts[0].ip);
            networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
9637 9638 9639 9640 9641 9642

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

9644 9645 9646 9647
            /* 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
             */
9648
#if VBOX_API_VERSION < 4002000
9649 9650 9651
            networkInterface->vtbl->EnableStaticIpConfig(networkInterface,
                                                         ipAddressUtf16,
                                                         networkMaskUtf16);
9652 9653 9654 9655 9656
#else
            networkInterface->vtbl->EnableStaticIPConfig(networkInterface,
                                                         ipAddressUtf16,
                                                         networkMaskUtf16);
#endif
9657

9658 9659 9660
            VBOX_UTF16_FREE(ipAddressUtf16);
            VBOX_UTF16_FREE(networkMaskUtf16);
        } else {
9661
#if VBOX_API_VERSION < 4002000
9662 9663
            networkInterface->vtbl->EnableDynamicIpConfig(networkInterface);
            networkInterface->vtbl->DhcpRediscover(networkInterface);
9664 9665 9666 9667
#else
            networkInterface->vtbl->EnableDynamicIPConfig(networkInterface);
            networkInterface->vtbl->DHCPRediscover(networkInterface);
#endif
9668
        }
9669

9670 9671 9672 9673 9674
        rc = networkInterface->vtbl->GetId(networkInterface, &vboxnetiid.value);
        if (NS_SUCCEEDED(rc)) {
            vboxIIDToUUID(&vboxnetiid, uuid);
            DEBUGIID("Real Network UUID", vboxnetiid.value);
            vboxIIDUnalloc(&vboxnetiid);
9675
            ret = virGetNetwork(conn, networkInterfaceNameUtf8, uuid);
9676
        }
9677 9678 9679 9680

        VIR_FREE(networkNameUtf8);
        VBOX_UTF16_FREE(networkNameUtf16);
        VBOX_RELEASE(networkInterface);
9681 9682
    }

9683 9684 9685 9686
    VBOX_UTF8_FREE(networkInterfaceNameUtf8);
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

9687
 cleanup:
9688 9689 9690 9691
    virNetworkDefFree(def);
    return ret;
}

9692 9693
static virNetworkPtr vboxNetworkCreateXML(virConnectPtr conn, const char *xml)
{
9694 9695 9696
    return vboxNetworkDefineCreateXML(conn, xml, true);
}

9697 9698
static virNetworkPtr vboxNetworkDefineXML(virConnectPtr conn, const char *xml)
{
9699 9700 9701
    return vboxNetworkDefineCreateXML(conn, xml, false);
}

9702 9703 9704
static int
vboxNetworkUndefineDestroy(virNetworkPtr network, bool removeinterface)
{
9705
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
9706
    char *networkNameUtf8 = NULL;
9707 9708
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9709 9710 9711 9712 9713 9714 9715 9716 9717

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

9718
    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0)
9719 9720
        goto cleanup;

9721
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
9722

9723
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
9724

9725 9726
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9727

9728
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9729

9730 9731 9732
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
9733

9734
#if VBOX_API_VERSION != 2002000
9735 9736 9737
            if (removeinterface) {
                PRUnichar *iidUtf16 = NULL;
                IProgress *progress = NULL;
9738

9739
                networkInterface->vtbl->GetId(networkInterface, &iidUtf16);
9740

9741
                if (iidUtf16) {
9742
# if VBOX_API_VERSION == 3000000
9743 9744 9745
                    IHostNetworkInterface *netInt = NULL;
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &netInt, &progress);
                    VBOX_RELEASE(netInt);
9746
# else  /* VBOX_API_VERSION > 3000000 */
9747
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &progress);
9748
# endif /* VBOX_API_VERSION > 3000000 */
9749 9750
                    VBOX_UTF16_FREE(iidUtf16);
                }
9751

9752 9753 9754 9755 9756
                if (progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                }
            }
9757
#endif /* VBOX_API_VERSION != 2002000 */
9758

E
Eric Blake 已提交
9759
            VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
9760 9761 9762 9763 9764 9765 9766 9767 9768 9769

            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);
9770 9771
            }

9772 9773
            VBOX_UTF16_FREE(networkNameUtf16);

9774
        }
9775
        VBOX_RELEASE(networkInterface);
9776 9777
    }

9778 9779 9780
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

9781 9782
    ret = 0;

9783
 cleanup:
9784 9785 9786 9787
    VIR_FREE(networkNameUtf8);
    return ret;
}

9788 9789
static int vboxNetworkUndefine(virNetworkPtr network)
{
9790 9791 9792
    return vboxNetworkUndefineDestroy(network, true);
}

9793 9794
static int vboxNetworkCreate(virNetworkPtr network)
{
9795
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
9796
    char *networkNameUtf8 = NULL;
9797 9798
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9799 9800 9801 9802 9803 9804 9805 9806

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

9807
    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0)
9808 9809
        goto cleanup;

9810
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
9811

9812
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
9813

9814 9815
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9816

9817
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9818

9819 9820 9821
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
9822 9823


E
Eric Blake 已提交
9824
            VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
9825

9826 9827 9828 9829 9830
            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (dhcpServer) {
                PRUnichar *trunkTypeUtf16 = NULL;
9831

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

9834
                VBOX_UTF8_TO_UTF16("netflt", &trunkTypeUtf16);
9835

9836 9837 9838 9839
                dhcpServer->vtbl->Start(dhcpServer,
                                        networkNameUtf16,
                                        networkInterfaceNameUtf16,
                                        trunkTypeUtf16);
9840

9841 9842
                VBOX_UTF16_FREE(trunkTypeUtf16);
                VBOX_RELEASE(dhcpServer);
9843 9844
            }

9845
            VBOX_UTF16_FREE(networkNameUtf16);
9846
        }
9847 9848

        VBOX_RELEASE(networkInterface);
9849 9850
    }

9851 9852 9853
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

9854 9855
    ret = 0;

9856
 cleanup:
9857 9858 9859 9860
    VIR_FREE(networkNameUtf8);
    return ret;
}

9861 9862
static int vboxNetworkDestroy(virNetworkPtr network)
{
9863
    return vboxNetworkUndefineDestroy(network, false);
9864 9865
}

9866
static char *vboxNetworkGetXMLDesc(virNetworkPtr network,
E
Eric Blake 已提交
9867 9868
                                   unsigned int flags)
{
9869
    VBOX_OBJECT_HOST_CHECK(network->conn, char *, NULL);
9870
    virNetworkDefPtr def  = NULL;
9871
    virNetworkIpDefPtr ipdef = NULL;
9872
    char *networkNameUtf8 = NULL;
9873 9874
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9875

E
Eric Blake 已提交
9876 9877
    virCheckFlags(0, NULL);

9878
    if (VIR_ALLOC(def) < 0)
9879
        goto cleanup;
9880
    if (VIR_ALLOC(ipdef) < 0)
9881 9882 9883
        goto cleanup;
    def->ips = ipdef;
    def->nips = 1;
9884

9885
    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0)
9886 9887
        goto cleanup;

9888
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
9889

9890
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
9891

9892 9893
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9894

9895
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9896

9897
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
J
Ján Tomko 已提交
9898
            if (VIR_STRDUP(def->name, network->name) >= 0) {
9899 9900
                PRUnichar *networkNameUtf16 = NULL;
                IDHCPServer *dhcpServer     = NULL;
9901
                vboxIID vboxnet0IID = VBOX_IID_INITIALIZER;
9902

9903 9904
                networkInterface->vtbl->GetId(networkInterface, &vboxnet0IID.value);
                vboxIIDToUUID(&vboxnet0IID, def->uuid);
9905

E
Eric Blake 已提交
9906
                VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
9907

9908
                def->forward.type = VIR_NETWORK_FORWARD_NONE;
9909

9910 9911 9912 9913
                data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                                 networkNameUtf16,
                                                                 &dhcpServer);
                if (dhcpServer) {
9914
                    ipdef->nranges = 1;
9915
                    if (VIR_ALLOC_N(ipdef->ranges, ipdef->nranges) >= 0) {
9916 9917 9918 9919
                        PRUnichar *ipAddressUtf16     = NULL;
                        PRUnichar *networkMaskUtf16   = NULL;
                        PRUnichar *fromIPAddressUtf16 = NULL;
                        PRUnichar *toIPAddressUtf16   = NULL;
9920
                        bool errorOccurred = false;
9921

9922 9923 9924 9925 9926 9927 9928
                        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
                         */
9929
                        if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
9930
                                                     &ipdef->address) < 0 ||
9931
                            vboxSocketParseAddrUtf16(data, networkMaskUtf16,
9932
                                                     &ipdef->netmask) < 0 ||
9933
                            vboxSocketParseAddrUtf16(data, fromIPAddressUtf16,
9934
                                                     &ipdef->ranges[0].start) < 0 ||
9935
                            vboxSocketParseAddrUtf16(data, toIPAddressUtf16,
9936
                                                     &ipdef->ranges[0].end) < 0) {
9937 9938
                            errorOccurred = true;
                        }
9939 9940 9941 9942 9943

                        VBOX_UTF16_FREE(ipAddressUtf16);
                        VBOX_UTF16_FREE(networkMaskUtf16);
                        VBOX_UTF16_FREE(fromIPAddressUtf16);
                        VBOX_UTF16_FREE(toIPAddressUtf16);
9944 9945 9946 9947

                        if (errorOccurred) {
                            goto cleanup;
                        }
9948
                    } else {
9949
                        ipdef->nranges = 0;
9950
                    }
9951

9952
                    ipdef->nhosts = 1;
9953
                    if (VIR_ALLOC_N(ipdef->hosts, ipdef->nhosts) >= 0) {
9954
                        if (VIR_STRDUP(ipdef->hosts[0].name, network->name) < 0) {
9955 9956
                            VIR_FREE(ipdef->hosts);
                            ipdef->nhosts = 0;
9957
                        } else {
9958 9959
                            PRUnichar *macAddressUtf16 = NULL;
                            PRUnichar *ipAddressUtf16  = NULL;
9960
                            bool errorOccurred = false;
9961

9962
                            networkInterface->vtbl->GetHardwareAddress(networkInterface, &macAddressUtf16);
9963 9964
                            networkInterface->vtbl->GetIPAddress(networkInterface, &ipAddressUtf16);

9965
                            VBOX_UTF16_TO_UTF8(macAddressUtf16, &ipdef->hosts[0].mac);
9966 9967

                            if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
9968
                                                         &ipdef->hosts[0].ip) < 0) {
9969 9970
                                errorOccurred = true;
                            }
9971

9972 9973
                            VBOX_UTF16_FREE(macAddressUtf16);
                            VBOX_UTF16_FREE(ipAddressUtf16);
9974 9975 9976 9977

                            if (errorOccurred) {
                                goto cleanup;
                            }
9978 9979
                        }
                    } else {
9980
                        ipdef->nhosts = 0;
9981
                    }
9982 9983 9984 9985 9986

                    VBOX_RELEASE(dhcpServer);
                } else {
                    PRUnichar *networkMaskUtf16 = NULL;
                    PRUnichar *ipAddressUtf16   = NULL;
9987
                    bool errorOccurred = false;
9988 9989 9990 9991

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

9992
                    if (vboxSocketParseAddrUtf16(data, networkMaskUtf16,
9993
                                                 &ipdef->netmask) < 0 ||
9994
                        vboxSocketParseAddrUtf16(data, ipAddressUtf16,
9995
                                                 &ipdef->address) < 0) {
9996 9997
                        errorOccurred = true;
                    }
9998 9999 10000

                    VBOX_UTF16_FREE(networkMaskUtf16);
                    VBOX_UTF16_FREE(ipAddressUtf16);
10001 10002 10003 10004

                    if (errorOccurred) {
                        goto cleanup;
                    }
10005 10006
                }

10007 10008
                DEBUGIID("Network UUID", vboxnet0IID.value);
                vboxIIDUnalloc(&vboxnet0IID);
10009
                VBOX_UTF16_FREE(networkNameUtf16);
10010 10011
            }
        }
10012 10013

        VBOX_RELEASE(networkInterface);
10014 10015
    }

10016 10017 10018
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

10019
    ret = virNetworkDefFormat(def, 0);
10020

10021
 cleanup:
10022
    virNetworkDefFree(def);
10023 10024 10025 10026
    VIR_FREE(networkNameUtf8);
    return ret;
}

10027 10028 10029 10030
/**
 * The Storage Functions here on
 */

10031 10032 10033
static virDrvOpenStatus vboxStorageOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                        unsigned int flags)
E
Eric Blake 已提交
10034
{
10035 10036
    vboxGlobalData *data = conn->privateData;

E
Eric Blake 已提交
10037 10038
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

10039
    if (STRNEQ(conn->driver->name, "VBOX"))
10040
        return VIR_DRV_OPEN_DECLINED;
10041 10042 10043 10044

    if ((data->pFuncs      == NULL) ||
        (data->vboxObj     == NULL) ||
        (data->vboxSession == NULL))
10045
        return VIR_DRV_OPEN_ERROR;
10046

10047
    VIR_DEBUG("vbox storage initialized");
10048 10049 10050 10051
    /* conn->storagePrivateData = some storage specific data */
    return VIR_DRV_OPEN_SUCCESS;
}

10052 10053
static int vboxStorageClose(virConnectPtr conn)
{
10054
    VIR_DEBUG("vbox storage uninitialized");
10055 10056 10057 10058
    conn->storagePrivateData = NULL;
    return 0;
}

10059 10060
static int vboxConnectNumOfStoragePools(virConnectPtr conn ATTRIBUTE_UNUSED)
{
10061 10062 10063 10064 10065 10066 10067 10068

    /** Currently only one pool supported, the default one
     * given by ISystemProperties::defaultHardDiskFolder()
     */

    return 1;
}

10069 10070
static int vboxConnectListStoragePools(virConnectPtr conn ATTRIBUTE_UNUSED,
                                       char **const names, int nnames) {
10071 10072
    int numActive = 0;

10073 10074 10075
    if (nnames == 1 &&
        VIR_STRDUP(names[numActive], "default-pool") > 0)
        numActive++;
10076 10077 10078
    return numActive;
}

10079 10080 10081
static virStoragePoolPtr
vboxStoragePoolLookupByName(virConnectPtr conn, const char *name)
{
10082 10083 10084 10085 10086 10087 10088 10089 10090 10091
    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";

10092
        ignore_value(virUUIDParse(uuidstr, uuid));
10093

10094
        ret = virGetStoragePool(conn, name, uuid, NULL, NULL);
10095 10096 10097 10098 10099
    }

    return ret;
}

10100 10101
static int vboxStoragePoolNumOfVolumes(virStoragePoolPtr pool)
{
10102
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
10103
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
10104 10105
    PRUint32 hardDiskAccessible = 0;
    nsresult rc;
10106
    size_t i;
10107

10108
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
10109
    if (NS_SUCCEEDED(rc)) {
10110 10111
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
10112 10113
            if (hardDisk) {
                PRUint32 hddstate;
10114

10115 10116 10117
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible)
                    hardDiskAccessible++;
10118 10119
            }
        }
10120 10121 10122 10123

        vboxArrayRelease(&hardDisks);

        ret = hardDiskAccessible;
10124
    } else {
10125
        ret = -1;
10126 10127 10128
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get number of volumes in the pool: %s, rc=%08x"),
                       pool->name, (unsigned)rc);
10129 10130
    }

10131
    return ret;
10132 10133 10134
}

static int vboxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names, int nnames) {
10135
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
10136
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
10137 10138
    PRUint32 numActive     = 0;
    nsresult rc;
10139
    size_t i;
10140

10141
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
10142
    if (NS_SUCCEEDED(rc)) {
10143 10144
        for (i = 0; i < hardDisks.count && numActive < nnames; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
10145

10146 10147 10148 10149
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
10150

10151 10152 10153
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
10154

10155 10156
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
10157

10158
                    if (nameUtf8) {
10159
                        VIR_DEBUG("nnames[%d]: %s", numActive, nameUtf8);
10160
                        if (VIR_STRDUP(names[numActive], nameUtf8) > 0)
10161 10162 10163
                            numActive++;

                        VBOX_UTF8_FREE(nameUtf8);
10164 10165 10166 10167
                    }
                }
            }
        }
10168 10169 10170 10171

        vboxArrayRelease(&hardDisks);

        ret = numActive;
10172
    } else {
10173
        ret = -1;
10174 10175 10176
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get the volume list in the pool: %s, rc=%08x"),
                       pool->name, (unsigned)rc);
10177 10178
    }

10179
    return ret;
10180 10181
}

10182 10183 10184
static virStorageVolPtr
vboxStorageVolLookupByName(virStoragePoolPtr pool, const char *name)
{
10185
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
10186
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
10187
    nsresult rc;
10188
    size_t i;
10189

10190
    if (!name)
10191
        return ret;
10192

10193
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
10194
    if (NS_SUCCEEDED(rc)) {
10195 10196
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
10197

10198 10199 10200 10201
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
10202

10203 10204 10205
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
10206

10207 10208 10209 10210
                    if (nameUtf16) {
                        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                        VBOX_UTF16_FREE(nameUtf16);
                    }
10211

10212
                    if (nameUtf8 && STREQ(nameUtf8, name)) {
10213 10214 10215
                        vboxIID hddIID = VBOX_IID_INITIALIZER;
                        unsigned char uuid[VIR_UUID_BUFLEN];
                        char key[VIR_UUID_STRING_BUFLEN] = "";
10216

10217 10218 10219 10220
                        rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
                        if (NS_SUCCEEDED(rc)) {
                            vboxIIDToUUID(&hddIID, uuid);
                            virUUIDFormat(uuid, key);
10221

10222 10223
                            ret = virGetStorageVol(pool->conn, pool->name, name, key,
                                                   NULL, NULL);
10224

10225 10226 10227 10228
                            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);
10229 10230
                        }

10231
                        vboxIIDUnalloc(&hddIID);
10232 10233
                        VBOX_UTF8_FREE(nameUtf8);
                        break;
10234
                    }
10235

J
John Ferlan 已提交
10236
                    VBOX_UTF8_FREE(nameUtf8);
10237 10238 10239
                }
            }
        }
10240

10241
        vboxArrayRelease(&hardDisks);
10242 10243 10244 10245 10246
    }

    return ret;
}

10247 10248 10249
static virStorageVolPtr
vboxStorageVolLookupByKey(virConnectPtr conn, const char *key)
{
10250
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
10251 10252
    vboxIID hddIID = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
10253 10254 10255
    IHardDisk *hardDisk  = NULL;
    nsresult rc;

10256 10257 10258
    if (!key)
        return ret;

10259
    if (virUUIDParse(key, uuid) < 0) {
10260 10261
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), key);
10262
        return NULL;
10263 10264
    }

10265
    vboxIIDFromUUID(&hddIID, uuid);
10266
#if VBOX_API_VERSION < 4000000
10267
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10268
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10269 10270
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10271 10272 10273 10274
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10275
#endif /* VBOX_API_VERSION >= 4000000 */
10276 10277
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10278

10279 10280 10281 10282
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
10283

10284 10285
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
10286

10287
            if (hddNameUtf8) {
10288
                if (vboxConnectNumOfStoragePools(conn) == 1) {
10289 10290
                    ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, key,
                                           NULL, NULL);
10291
                    VIR_DEBUG("Storage Volume Pool: %s", "default-pool");
10292 10293 10294 10295
                } else {
                    /* TODO: currently only one default pool and thus
                     * nothing here, change it when pools are supported
                     */
10296 10297
                }

10298 10299
                VIR_DEBUG("Storage Volume Name: %s", key);
                VIR_DEBUG("Storage Volume key : %s", hddNameUtf8);
10300 10301 10302

                VBOX_UTF8_FREE(hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
10303 10304
            }
        }
10305 10306

        VBOX_MEDIUM_RELEASE(hardDisk);
10307 10308
    }

10309
    vboxIIDUnalloc(&hddIID);
10310 10311 10312
    return ret;
}

10313 10314 10315
static virStorageVolPtr
vboxStorageVolLookupByPath(virConnectPtr conn, const char *path)
{
10316
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
10317 10318 10319 10320
    PRUnichar *hddPathUtf16 = NULL;
    IHardDisk *hardDisk     = NULL;
    nsresult rc;

10321 10322
    if (!path)
        return ret;
10323

10324
    VBOX_UTF8_TO_UTF16(path, &hddPathUtf16);
10325

10326 10327
    if (!hddPathUtf16)
        return ret;
10328

10329
#if VBOX_API_VERSION < 4000000
10330
    rc = data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddPathUtf16, &hardDisk);
10331
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10332 10333
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddPathUtf16,
                                         DeviceType_HardDisk, &hardDisk);
10334 10335 10336 10337
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddPathUtf16,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10338
#endif /* VBOX_API_VERSION >= 4000000 */
10339 10340
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10341

10342 10343 10344 10345
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
10346

10347
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
10348

10349 10350 10351 10352
            if (hddNameUtf16) {
                VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
            }
10353

10354 10355 10356 10357
            if (hddNameUtf8) {
                vboxIID hddIID = VBOX_IID_INITIALIZER;
                unsigned char uuid[VIR_UUID_BUFLEN];
                char key[VIR_UUID_STRING_BUFLEN] = "";
10358

10359 10360 10361 10362
                rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
                if (NS_SUCCEEDED(rc)) {
                    vboxIIDToUUID(&hddIID, uuid);
                    virUUIDFormat(uuid, key);
10363

10364 10365 10366
                    /* TODO: currently only one default pool and thus
                     * the check below, change it when pools are supported
                     */
10367
                    if (vboxConnectNumOfStoragePools(conn) == 1)
10368 10369
                        ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, key,
                                               NULL, NULL);
10370

10371 10372 10373
                    VIR_DEBUG("Storage Volume Pool: %s", "default-pool");
                    VIR_DEBUG("Storage Volume Name: %s", hddNameUtf8);
                    VIR_DEBUG("Storage Volume key : %s", key);
10374
                }
10375

10376
                vboxIIDUnalloc(&hddIID);
10377 10378
            }

J
John Ferlan 已提交
10379
            VBOX_UTF8_FREE(hddNameUtf8);
10380
        }
10381 10382

        VBOX_MEDIUM_RELEASE(hardDisk);
10383 10384
    }

10385 10386
    VBOX_UTF16_FREE(hddPathUtf16);

10387 10388 10389 10390 10391
    return ret;
}

static virStorageVolPtr vboxStorageVolCreateXML(virStoragePoolPtr pool,
                                                const char *xml,
E
Eric Blake 已提交
10392 10393
                                                unsigned int flags)
{
10394
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
10395
    virStorageVolDefPtr  def  = NULL;
10396 10397
    PRUnichar *hddFormatUtf16 = NULL;
    PRUnichar *hddNameUtf16   = NULL;
10398 10399 10400
    virStoragePoolDef poolDef;
    nsresult rc;

E
Eric Blake 已提交
10401 10402
    virCheckFlags(0, NULL);

10403 10404 10405 10406 10407 10408 10409 10410
    /* 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;

10411
    if ((def = virStorageVolDefParseString(&poolDef, xml)) == NULL)
10412 10413
        goto cleanup;

10414 10415
    if (!def->name ||
        (def->type != VIR_STORAGE_VOL_FILE))
10416
        goto cleanup;
10417

10418 10419
    /* For now only the vmdk, vpc and vdi type harddisk
     * variants can be created.  For historical reason, we default to vdi */
10420 10421 10422 10423 10424 10425 10426
    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);
    }
10427

10428
    VBOX_UTF8_TO_UTF16(def->name, &hddNameUtf16);
10429

10430 10431
    if (hddFormatUtf16 && hddNameUtf16) {
        IHardDisk *hardDisk = NULL;
10432

10433 10434 10435
        rc = data->vboxObj->vtbl->CreateHardDisk(data->vboxObj, hddFormatUtf16, hddNameUtf16, &hardDisk);
        if (NS_SUCCEEDED(rc)) {
            IProgress *progress    = NULL;
10436 10437
            PRUint64   logicalSize = VIR_DIV_UP(def->target.capacity,
                                                1024 * 1024);
10438
            PRUint32   variant     = HardDiskVariant_Standard;
10439

10440
            if (def->target.capacity == def->target.allocation)
10441
                variant = HardDiskVariant_Fixed;
10442

10443
#if VBOX_API_VERSION < 4003000
10444
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, variant, &progress);
R
Ryota Ozaki 已提交
10445 10446 10447
#else
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, 1, &variant, &progress);
#endif
10448
            if (NS_SUCCEEDED(rc) && progress) {
10449
#if VBOX_API_VERSION == 2002000
10450
                nsresult resultCode;
10451
#else
10452
                PRInt32  resultCode;
10453 10454
#endif

10455 10456
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
10457

10458
                if (NS_SUCCEEDED(resultCode)) {
10459 10460 10461
                    vboxIID hddIID = VBOX_IID_INITIALIZER;
                    unsigned char uuid[VIR_UUID_BUFLEN];
                    char key[VIR_UUID_STRING_BUFLEN] = "";
10462

10463
                    rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
10464
                    if (NS_SUCCEEDED(rc)) {
10465 10466
                        vboxIIDToUUID(&hddIID, uuid);
                        virUUIDFormat(uuid, key);
10467

10468 10469
                        ret = virGetStorageVol(pool->conn, pool->name, def->name, key,
                                               NULL, NULL);
10470
                    }
10471 10472

                    vboxIIDUnalloc(&hddIID);
10473 10474
                }

10475
                VBOX_RELEASE(progress);
10476
            }
10477
        }
10478 10479
    }

10480 10481 10482
    VBOX_UTF16_FREE(hddFormatUtf16);
    VBOX_UTF16_FREE(hddNameUtf16);

10483
 cleanup:
10484 10485 10486 10487 10488
    virStorageVolDefFree(def);
    return ret;
}

static int vboxStorageVolDelete(virStorageVolPtr vol,
E
Eric Blake 已提交
10489 10490
                                unsigned int flags)
{
10491
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
10492 10493
    vboxIID hddIID = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
10494 10495 10496
    IHardDisk *hardDisk  = NULL;
    int deregister = 0;
    nsresult rc;
10497 10498
    size_t i = 0;
    size_t j = 0;
10499

E
Eric Blake 已提交
10500 10501
    virCheckFlags(0, -1);

10502
    if (virUUIDParse(vol->key, uuid) < 0) {
10503 10504
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
10505 10506
        return -1;
    }
10507

10508
    vboxIIDFromUUID(&hddIID, uuid);
10509
#if VBOX_API_VERSION < 4000000
10510
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10511
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10512 10513
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10514 10515 10516 10517
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10518
#endif /* VBOX_API_VERSION >= 4000000 */
10519 10520
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10521

10522 10523 10524
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint32  machineIdsSize = 0;
10525 10526
            vboxArray machineIds = VBOX_ARRAY_INITIALIZER;

10527
#if VBOX_API_VERSION < 3001000
10528
            vboxArrayGet(&machineIds, hardDisk, hardDisk->vtbl->imedium.GetMachineIds);
10529
#else  /* VBOX_API_VERSION >= 3001000 */
10530
            vboxArrayGet(&machineIds, hardDisk, hardDisk->vtbl->GetMachineIds);
10531
#endif /* VBOX_API_VERSION >= 3001000 */
10532

10533
#if VBOX_API_VERSION == 2002000 && defined WIN32
10534 10535 10536 10537 10538 10539
            /* 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,
J
Ján Tomko 已提交
10540
             * we divide the size of the SafeArray by two, to compensate for
10541 10542
             * this workaround in VirtualBox */
            machineIds.count /= 2;
10543
#endif /* VBOX_API_VERSION >= 2002000 */
10544

10545
            machineIdsSize = machineIds.count;
10546

10547
            for (i = 0; i < machineIds.count; i++) {
10548
                IMachine *machine = NULL;
10549 10550 10551
                vboxIID machineId = VBOX_IID_INITIALIZER;

                vboxIIDFromArrayItem(&machineId, &machineIds, i);
10552

10553
#if VBOX_API_VERSION >= 4000000
10554 10555
                rc = VBOX_OBJECT_GET_MACHINE(machineId.value, &machine);
                if (NS_FAILED(rc)) {
10556 10557
                    virReportError(VIR_ERR_NO_DOMAIN, "%s",
                                   _("no domain with matching uuid"));
10558 10559 10560 10561 10562 10563
                    break;
                }
#endif

                rc = VBOX_SESSION_OPEN(machineId.value, machine);

10564
                if (NS_SUCCEEDED(rc)) {
10565

10566 10567
                    rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                    if (NS_SUCCEEDED(rc)) {
10568
                        vboxArray hddAttachments = VBOX_ARRAY_INITIALIZER;
10569

10570
#if VBOX_API_VERSION < 3001000
10571 10572
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetHardDiskAttachments);
10573
#else  /* VBOX_API_VERSION >= 3001000 */
10574 10575
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetMediumAttachments);
10576
#endif /* VBOX_API_VERSION >= 3001000 */
10577 10578
                        for (j = 0; j < hddAttachments.count; j++) {
                            IHardDiskAttachment *hddAttachment = hddAttachments.items[j];
10579 10580 10581 10582

                            if (hddAttachment) {
                                IHardDisk *hdd = NULL;

10583
#if VBOX_API_VERSION < 3001000
10584
                                rc = hddAttachment->vtbl->GetHardDisk(hddAttachment, &hdd);
10585
#else  /* VBOX_API_VERSION >= 3001000 */
10586
                                rc = hddAttachment->vtbl->GetMedium(hddAttachment, &hdd);
10587
#endif /* VBOX_API_VERSION >= 3001000 */
10588
                                if (NS_SUCCEEDED(rc) && hdd) {
10589
                                    vboxIID iid = VBOX_IID_INITIALIZER;
10590

10591 10592
                                    rc = VBOX_MEDIUM_FUNC_ARG1(hdd, GetId, &iid.value);
                                    if (NS_SUCCEEDED(rc)) {
10593

10594 10595
                                            DEBUGIID("HardDisk (to delete) UUID", hddIID.value);
                                            DEBUGIID("HardDisk (currently processing) UUID", iid.value);
10596

10597
                                        if (vboxIIDIsEqual(&hddIID, &iid)) {
10598 10599 10600 10601
                                            PRUnichar *controller = NULL;
                                            PRInt32    port       = 0;
                                            PRInt32    device     = 0;

10602
                                            DEBUGIID("Found HardDisk to delete, UUID", hddIID.value);
10603 10604 10605 10606 10607

                                            hddAttachment->vtbl->GetController(hddAttachment, &controller);
                                            hddAttachment->vtbl->GetPort(hddAttachment, &port);
                                            hddAttachment->vtbl->GetDevice(hddAttachment, &device);

10608
#if VBOX_API_VERSION < 3001000
10609
                                            rc = machine->vtbl->DetachHardDisk(machine, controller, port, device);
10610
#else  /* VBOX_API_VERSION >= 3001000 */
10611
                                            rc = machine->vtbl->DetachDevice(machine, controller, port, device);
10612
#endif /* VBOX_API_VERSION >= 3001000 */
10613 10614
                                            if (NS_SUCCEEDED(rc)) {
                                                rc = machine->vtbl->SaveSettings(machine);
10615
                                                VIR_DEBUG("saving machine settings");
10616
                                            }
10617

10618 10619
                                            if (NS_SUCCEEDED(rc)) {
                                                deregister++;
10620
                                                VIR_DEBUG("deregistering hdd:%d", deregister);
10621
                                            }
10622

J
John Ferlan 已提交
10623
                                            VBOX_UTF16_FREE(controller);
10624
                                        }
10625
                                        vboxIIDUnalloc(&iid);
10626
                                    }
10627
                                    VBOX_MEDIUM_RELEASE(hdd);
10628 10629 10630
                                }
                            }
                        }
10631
                        vboxArrayRelease(&hddAttachments);
10632
                        VBOX_RELEASE(machine);
10633
                    }
10634
                    VBOX_SESSION_CLOSE();
10635
                }
10636 10637

                vboxIIDUnalloc(&machineId);
10638
            }
10639

10640
            vboxArrayUnalloc(&machineIds);
10641

10642 10643 10644
            if (machineIdsSize == 0 || machineIdsSize == deregister) {
                IProgress *progress = NULL;
                rc = hardDisk->vtbl->DeleteStorage(hardDisk, &progress);
10645

10646 10647 10648
                if (NS_SUCCEEDED(rc) && progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
10649
                    DEBUGIID("HardDisk deleted, UUID", hddIID.value);
10650
                    ret = 0;
10651 10652 10653
                }
            }
        }
10654 10655

        VBOX_MEDIUM_RELEASE(hardDisk);
10656 10657
    }

10658
    vboxIIDUnalloc(&hddIID);
10659

10660 10661 10662
    return ret;
}

10663 10664 10665
static int
vboxStorageVolGetInfo(virStorageVolPtr vol, virStorageVolInfoPtr info)
{
10666
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
10667
    IHardDisk *hardDisk  = NULL;
10668 10669
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
10670 10671
    nsresult rc;

10672
    if (!info)
10673
        return ret;
10674

10675
    if (virUUIDParse(vol->key, uuid) < 0) {
10676 10677
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
10678
        return ret;
10679
    }
10680

10681
    vboxIIDFromUUID(&hddIID, uuid);
10682
#if VBOX_API_VERSION < 4000000
10683
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10684
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10685 10686
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10687 10688 10689 10690
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10691
#endif /* VBOX_API_VERSION >= 4000000 */
10692 10693
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10694

10695 10696
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
10697
#if VBOX_API_VERSION < 4000000
10698 10699
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
10700
#else /* VBOX_API_VERSION >= 4000000 */
10701 10702
            PRInt64 hddLogicalSize;
            PRInt64 hddActualSize;
10703
#endif /* VBOX_API_VERSION >= 4000000 */
10704

10705
            info->type = VIR_STORAGE_VOL_FILE;
10706

10707
            hardDisk->vtbl->GetLogicalSize(hardDisk, &hddLogicalSize);
10708
#if VBOX_API_VERSION < 4000000
10709
            info->capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
10710
#else /* VBOX_API_VERSION >= 4000000 */
10711
            info->capacity = hddLogicalSize;
10712
#endif /* VBOX_API_VERSION >= 4000000 */
10713

10714 10715
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            info->allocation = hddActualSize;
10716

10717
            ret = 0;
10718

10719 10720 10721 10722
            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);
10723
        }
10724 10725

        VBOX_MEDIUM_RELEASE(hardDisk);
10726 10727
    }

10728
    vboxIIDUnalloc(&hddIID);
10729

10730 10731 10732
    return ret;
}

E
Eric Blake 已提交
10733 10734
static char *vboxStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags)
{
10735
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
10736
    IHardDisk *hardDisk  = NULL;
10737 10738
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
10739 10740 10741 10742 10743
    virStoragePoolDef pool;
    virStorageVolDef def;
    int defOk = 0;
    nsresult rc;

E
Eric Blake 已提交
10744 10745
    virCheckFlags(0, NULL);

10746 10747 10748
    memset(&pool, 0, sizeof(pool));
    memset(&def, 0, sizeof(def));

10749
    if (virUUIDParse(vol->key, uuid) < 0) {
10750 10751
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
10752
        return ret;
10753
    }
10754

10755
    vboxIIDFromUUID(&hddIID, uuid);
10756
#if VBOX_API_VERSION < 4000000
10757
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10758
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10759 10760
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10761 10762 10763 10764
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10765
#endif /* VBOX_API_VERSION >= 4000000 */
10766 10767 10768 10769 10770 10771
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;

        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (NS_SUCCEEDED(rc) && hddstate != MediaState_Inaccessible) {
            PRUnichar *hddFormatUtf16 = NULL;
10772
#if VBOX_API_VERSION < 4000000
10773 10774
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
10775
#else /* VBOX_API_VERSION >= 4000000 */
10776 10777
            PRInt64 hddLogicalSize;
            PRInt64 hddActualSize;
10778
#endif /* VBOX_API_VERSION >= 4000000 */
10779 10780 10781 10782 10783 10784 10785 10786 10787 10788 10789

            /* 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);
10790
            if (NS_SUCCEEDED(rc) && defOk) {
10791
#if VBOX_API_VERSION < 4000000
10792
                def.target.capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
10793
#else /* VBOX_API_VERSION >= 4000000 */
10794
                def.target.capacity = hddLogicalSize;
10795
#endif /* VBOX_API_VERSION >= 4000000 */
10796
            } else
10797 10798 10799 10800
                defOk = 0;

            rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            if (NS_SUCCEEDED(rc) && defOk)
10801
                def.target.allocation = hddActualSize;
10802 10803 10804
            else
                defOk = 0;

10805
            if (VIR_STRDUP(def.name, vol->name) < 0)
10806 10807
                defOk = 0;

10808
            if (VIR_STRDUP(def.key, vol->key) < 0)
10809 10810 10811 10812 10813 10814 10815 10816 10817
                defOk = 0;

            rc = hardDisk->vtbl->GetFormat(hardDisk, &hddFormatUtf16);
            if (NS_SUCCEEDED(rc) && defOk) {
                char *hddFormatUtf8 = NULL;

                VBOX_UTF16_TO_UTF8(hddFormatUtf16, &hddFormatUtf8);
                if (hddFormatUtf8) {

10818
                    VIR_DEBUG("Storage Volume Format: %s", hddFormatUtf8);
10819 10820 10821 10822 10823

                    if (STRCASEEQ("vmdk", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VMDK;
                    else if (STRCASEEQ("vhd", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VPC;
10824 10825
                    else if (STRCASEEQ("vdi", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VDI;
10826
                    else
10827
                        def.target.format = VIR_STORAGE_FILE_RAW;
10828

10829
                    VBOX_UTF8_FREE(hddFormatUtf8);
10830 10831
                }

10832 10833 10834
                VBOX_UTF16_FREE(hddFormatUtf16);
            } else {
                defOk = 0;
10835 10836
            }
        }
10837 10838

        VBOX_MEDIUM_RELEASE(hardDisk);
10839 10840
    }

10841
    vboxIIDUnalloc(&hddIID);
10842

10843
    if (defOk)
10844
        ret = virStorageVolDefFormat(&pool, &def);
10845 10846 10847 10848 10849

    return ret;
}

static char *vboxStorageVolGetPath(virStorageVolPtr vol) {
10850
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
10851
    IHardDisk *hardDisk  = NULL;
10852 10853
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
10854 10855
    nsresult rc;

10856
    if (virUUIDParse(vol->key, uuid) < 0) {
10857 10858
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
10859
        return ret;
10860
    }
10861

10862
    vboxIIDFromUUID(&hddIID, uuid);
10863
#if VBOX_API_VERSION < 4000000
10864
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10865
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10866 10867
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10868 10869 10870 10871
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10872
#endif /* VBOX_API_VERSION >= 4000000 */
10873 10874
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10875

10876 10877 10878 10879
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddLocationUtf16 = NULL;
            char      *hddLocationUtf8  = NULL;
10880

10881
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetLocation, &hddLocationUtf16);
10882

10883 10884
            VBOX_UTF16_TO_UTF8(hddLocationUtf16, &hddLocationUtf8);
            if (hddLocationUtf8) {
10885

10886
                ignore_value(VIR_STRDUP(ret, hddLocationUtf8));
10887

10888 10889 10890
                VIR_DEBUG("Storage Volume Name: %s", vol->name);
                VIR_DEBUG("Storage Volume Path: %s", hddLocationUtf8);
                VIR_DEBUG("Storage Volume Pool: %s", vol->pool);
10891

10892
                VBOX_UTF8_FREE(hddLocationUtf8);
10893 10894
            }

10895
            VBOX_UTF16_FREE(hddLocationUtf16);
10896
        }
10897 10898

        VBOX_MEDIUM_RELEASE(hardDisk);
10899 10900
    }

10901
    vboxIIDUnalloc(&hddIID);
10902

10903 10904
    return ret;
}
10905

10906
#if VBOX_API_VERSION >= 4000000
10907 10908 10909 10910
static char *
vboxDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
10911
                     unsigned int flags)
10912 10913 10914 10915 10916 10917 10918 10919 10920 10921
{
    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 已提交
10922 10923
    virCheckFlags(0, NULL);

10924 10925 10926
    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
10927 10928
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
10929 10930 10931 10932 10933
        return NULL;
    }

    rc = machine->vtbl->GetMonitorCount(machine, &max_screen);
    if (NS_FAILED(rc)) {
10934 10935
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("unable to get monitor count"));
10936 10937 10938 10939 10940
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (screen >= max_screen) {
10941 10942 10943
        virReportError(VIR_ERR_INVALID_ARG,
                       _("screen ID higher than monitor "
                         "count (%d)"), max_screen);
10944 10945 10946 10947 10948 10949 10950 10951 10952
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (virAsprintf(&tmp, "%s/cache/libvirt/vbox.screendump.XXXXXX", LOCALSTATEDIR) < 0) {
        VBOX_RELEASE(machine);
        return NULL;
    }

10953 10954
    if ((tmp_fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
        virReportSystemError(errno, _("mkostemp(\"%s\") failed"), tmp);
10955 10956 10957 10958 10959 10960 10961 10962 10963 10964 10965 10966 10967 10968 10969 10970 10971 10972
        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;
10973
# if VBOX_API_VERSION >= 4003000
R
Ryota Ozaki 已提交
10974 10975
                PRInt32 xOrigin, yOrigin;
# endif
10976 10977 10978

                rc = display->vtbl->GetScreenResolution(display, screen,
                                                        &width, &height,
10979
# if VBOX_API_VERSION < 4003000
10980
                                                        &bitsPerPixel);
R
Ryota Ozaki 已提交
10981 10982 10983 10984
# else
                                                        &bitsPerPixel,
                                                        &xOrigin, &yOrigin);
# endif
10985 10986

                if (NS_FAILED(rc) || !width || !height) {
10987 10988
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("unable to get screen resolution"));
10989 10990 10991 10992 10993 10994 10995 10996
                    goto endjob;
                }

                rc = display->vtbl->TakeScreenShotPNGToArray(display, screen,
                                                             width, height,
                                                             &screenDataSize,
                                                             &screenData);
                if (NS_FAILED(rc)) {
10997 10998
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("failed to take screenshot"));
10999 11000 11001 11002 11003 11004 11005 11006 11007 11008 11009 11010 11011 11012 11013
                    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;
                }

11014 11015 11016
                if (VIR_STRDUP(ret, "image/png") < 0)
                    goto endjob;

E
Eric Blake 已提交
11017
                if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
11018 11019
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("unable to open stream"));
11020
                    VIR_FREE(ret);
11021
                }
11022
 endjob:
11023 11024 11025 11026 11027 11028 11029 11030 11031
                VIR_FREE(screenData);
                VBOX_RELEASE(display);
            }
            VBOX_RELEASE(console);
        }
        VBOX_SESSION_CLOSE();
    }

    VIR_FORCE_CLOSE(tmp_fd);
E
Eric Blake 已提交
11032
    unlink(tmp);
11033 11034 11035 11036 11037
    VIR_FREE(tmp);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
11038
#endif /* VBOX_API_VERSION >= 4000000 */
11039

11040 11041 11042

#define MATCH(FLAG) (flags & (FLAG))
static int
11043 11044 11045
vboxConnectListAllDomains(virConnectPtr conn,
                          virDomainPtr **domains,
                          unsigned int flags)
11046 11047 11048 11049 11050 11051 11052 11053 11054
{
    VBOX_OBJECT_CHECK(conn, int, -1);
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
    char      *machineNameUtf8  = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID iid = VBOX_IID_INITIALIZER;
    PRUint32 state;
    nsresult rc;
11055
    size_t i;
11056 11057 11058 11059 11060 11061
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    int count = 0;
    bool active;
    PRUint32 snapshotCount;

O
Osier Yang 已提交
11062
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
11063 11064 11065 11066 11067 11068 11069 11070 11071 11072 11073 11074 11075 11076

    /* filter out flag options that will produce 0 results in vbox driver:
     * - managed save: vbox guests don't have managed save images
     * - autostart: vbox doesn't support autostarting guests
     * - persistance: vbox doesn't support transient guests
     */
    if ((MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART)) ||
        (MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) &&
         !MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE))) {
        if (domains &&
            VIR_ALLOC_N(*domains, 1) < 0)
11077
            goto cleanup;
11078 11079 11080 11081 11082 11083 11084

        ret = 0;
        goto cleanup;
    }

    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
    if (NS_FAILED(rc)) {
11085 11086
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of domains, rc=%08x"), (unsigned)rc);
11087 11088 11089 11090 11091
        goto cleanup;
    }

    if (domains &&
        VIR_ALLOC_N(doms, machines.count + 1) < 0)
11092
        goto cleanup;
11093 11094 11095 11096 11097 11098 11099 11100 11101 11102 11103 11104 11105 11106 11107 11108 11109

    for (i = 0; i < machines.count; i++) {
        IMachine *machine = machines.items[i];

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

                if (state >= MachineState_FirstOnline &&
                    state <= MachineState_LastOnline)
                    active = true;
                else
                    active = false;

                /* filter by active state */
O
Osier Yang 已提交
11110
                if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
11111 11112 11113 11114 11115
                    !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) && active) ||
                      (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) && !active)))
                    continue;

                /* filter by snapshot existence */
O
Osier Yang 已提交
11116
                if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
11117 11118
                    rc = machine->vtbl->GetSnapshotCount(machine, &snapshotCount);
                    if (NS_FAILED(rc)) {
11119
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
11120
                                       _("could not get snapshot count for listed domains"));
11121 11122 11123 11124 11125 11126 11127 11128 11129 11130
                        goto cleanup;
                    }
                    if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) &&
                           snapshotCount > 0) ||
                          (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) &&
                           snapshotCount == 0)))
                        continue;
                }

                /* filter by machine state */
O
Osier Yang 已提交
11131
                if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) &&
11132 11133 11134 11135 11136 11137 11138 11139 11140 11141 11142 11143 11144 11145 11146 11147 11148 11149 11150 11151 11152 11153 11154 11155 11156 11157 11158 11159 11160 11161 11162 11163 11164 11165 11166 11167 11168 11169 11170 11171 11172 11173 11174 11175 11176 11177 11178 11179 11180 11181
                    !((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
                       state == MachineState_Running) ||
                      (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
                       state == MachineState_Paused) ||
                      (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
                       state == MachineState_PoweredOff) ||
                      (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
                       (state != MachineState_Running &&
                        state != MachineState_Paused &&
                        state != MachineState_PoweredOff))))
                    continue;

                /* just count the machines */
                if (!doms) {
                    count++;
                    continue;
                }

                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
                machine->vtbl->GetId(machine, &iid.value);
                vboxIIDToUUID(&iid, uuid);
                vboxIIDUnalloc(&iid);

                dom = virGetDomain(conn, machineNameUtf8, uuid);

                VBOX_UTF8_FREE(machineNameUtf8);
                VBOX_UTF16_FREE(machineNameUtf16);

                if (!dom)
                    goto cleanup;

                if (active)
                    dom->id = i + 1;

                doms[count++] = dom;
            }
        }
    }

    if (doms) {
        /* safe to ignore, new size will be equal or less than
         * previous allocation*/
        ignore_value(VIR_REALLOC_N(doms, count + 1));
        *domains = doms;
        doms = NULL;
    }

    ret = count;

11182
 cleanup:
11183 11184 11185 11186 11187 11188 11189 11190 11191 11192 11193 11194 11195 11196
    if (doms) {
        for (i = 0; i < count; i++) {
            if (doms[i])
                virDomainFree(doms[i]);
        }
    }
    VIR_FREE(doms);

    vboxArrayRelease(&machines);
    return ret;
}
#undef MATCH


11197 11198 11199 11200 11201 11202 11203 11204 11205 11206 11207 11208 11209 11210 11211 11212 11213 11214 11215 11216 11217
static int
vboxNodeGetInfo(virConnectPtr conn ATTRIBUTE_UNUSED,
                virNodeInfoPtr nodeinfo)
{
    return nodeGetInfo(nodeinfo);
}


static int
vboxNodeGetCellsFreeMemory(virConnectPtr conn ATTRIBUTE_UNUSED,
                           unsigned long long *freeMems,
                           int startCell,
                           int maxCells)
{
    return nodeGetCellsFreeMemory(freeMems, startCell, maxCells);
}


static unsigned long long
vboxNodeGetFreeMemory(virConnectPtr conn ATTRIBUTE_UNUSED)
{
11218 11219 11220 11221
    unsigned long long freeMem;
    if (nodeGetMemory(NULL, &freeMem) < 0)
        return 0;
    return freeMem;
11222 11223
}

11224

11225 11226 11227 11228 11229 11230 11231 11232 11233 11234 11235 11236 11237 11238
static int
vboxNodeGetFreePages(virConnectPtr conn ATTRIBUTE_UNUSED,
                     unsigned int npages,
                     unsigned int *pages,
                     int startCell,
                     unsigned int cellCount,
                     unsigned long long *counts,
                     unsigned int flags)
{
    virCheckFlags(0, -1);

    return nodeGetFreePages(npages, pages, startCell, cellCount, counts);
}

T
Taowei 已提交
11239 11240 11241 11242 11243 11244 11245 11246 11247 11248 11249 11250 11251 11252 11253 11254 11255 11256 11257 11258 11259 11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274 11275 11276 11277 11278 11279 11280 11281 11282 11283 11284 11285 11286 11287 11288 11289 11290 11291 11292 11293 11294 11295 11296 11297 11298 11299 11300 11301 11302 11303 11304 11305 11306 11307 11308 11309 11310 11311
static int _pfnInitialize(vboxGlobalData *data)
{
    data->pFuncs = g_pfnGetFunctions(VBOX_XPCOMC_VERSION);
    if (data->pFuncs == NULL)
        return -1;
#if VBOX_XPCOMC_VERSION == 0x00010000U
    data->pFuncs->pfnComInitialize(&data->vboxObj, &data->vboxSession);
#else  /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
    data->pFuncs->pfnComInitialize(IVIRTUALBOX_IID_STR, &data->vboxObj, ISESSION_IID_STR, &data->vboxSession);
#endif /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
    return 0;
}

static int
_initializeDomainEvent(vboxGlobalData *data ATTRIBUTE_UNUSED)
{
#if VBOX_API_VERSION <= 2002000 || VBOX_API_VERSION >= 4000000
    /* No event queue functionality in 2.2.* and 4.* as of now */
    vboxUnsupported();
#else /* VBOX_API_VERSION > 2002000 || VBOX_API_VERSION < 4000000 */
    /* Initialize the fWatch needed for Event Callbacks */
    data->fdWatch = -1;
    data->pFuncs->pfnGetEventQueue(&data->vboxQueue);
    if (data->vboxQueue == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("nsIEventQueue object is null"));
        return -1;
    }
#endif /* VBOX_API_VERSION > 2002000 || VBOX_API_VERSION < 4000000 */
    return 0;
}

static
void _registerGlobalData(vboxGlobalData *data ATTRIBUTE_UNUSED)
{
#if VBOX_API_VERSION == 2002000
    vboxUnsupported();
#else /* VBOX_API_VERSION != 2002000 */
    g_pVBoxGlobalData = data;
#endif /* VBOX_API_VERSION != 2002000 */
}

static void _pfnUninitialize(vboxGlobalData *data)
{
    if (data->pFuncs)
        data->pFuncs->pfnComUninitialize();
}

static void _pfnComUnallocMem(PCVBOXXPCOM pFuncs, void *pv)
{
    pFuncs->pfnComUnallocMem(pv);
}

static void _pfnUtf16Free(PCVBOXXPCOM pFuncs, PRUnichar *pwszString)
{
    pFuncs->pfnUtf16Free(pwszString);
}

static void _pfnUtf8Free(PCVBOXXPCOM pFuncs, char *pszString)
{
    pFuncs->pfnUtf8Free(pszString);
}

static int _pfnUtf16ToUtf8(PCVBOXXPCOM pFuncs, const PRUnichar *pwszString, char **ppszString)
{
    return pFuncs->pfnUtf16ToUtf8(pwszString, ppszString);
}

static int _pfnUtf8ToUtf16(PCVBOXXPCOM pFuncs, const char *pszString, PRUnichar **ppwszString)
{
    return pFuncs->pfnUtf8ToUtf16(pszString, ppwszString);
}

T
Taowei 已提交
11312 11313 11314 11315 11316 11317 11318 11319 11320 11321 11322 11323 11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337 11338 11339 11340 11341 11342 11343 11344 11345 11346 11347
#if VBOX_API_VERSION == 2002000

static void _vboxIIDInitialize(vboxIIDUnion *iidu)
{
    memset(iidu, 0, sizeof(vboxIIDUnion));
}

static void _DEBUGIID(const char *msg, vboxIIDUnion *iidu)
{
# ifdef WIN32
    DEBUGUUID(msg, (nsID *)&IID_MEMBER(value));
# else /* !WIN32 */
    DEBUGUUID(msg, IID_MEMBER(value));
# endif /* !WIN32 */
}

#else /* VBOX_API_VERSION != 2002000 */

static void _vboxIIDInitialize(vboxIIDUnion *iidu)
{
    memset(iidu, 0, sizeof(vboxIIDUnion));
    IID_MEMBER(owner) = true;
}

static void _DEBUGIID(const char *msg, vboxIIDUnion *iidu)
{
    DEBUGPRUnichar(msg, IID_MEMBER(value));
}

#endif /* VBOX_API_VERSION != 2002000 */

static nsresult _nsisupportsRelease(nsISupports *nsi)
{
    return nsi->vtbl->Release(nsi);
}

T
Taowei 已提交
11348 11349 11350 11351 11352 11353
static nsresult
_virtualboxGetVersion(IVirtualBox *vboxObj, PRUnichar **versionUtf16)
{
    return vboxObj->vtbl->GetVersion(vboxObj, versionUtf16);
}

T
Taowei 已提交
11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370 11371 11372 11373 11374 11375 11376 11377 11378 11379 11380 11381 11382 11383 11384 11385 11386 11387 11388 11389 11390 11391 11392 11393 11394 11395 11396 11397 11398 11399 11400 11401 11402 11403 11404 11405 11406 11407 11408 11409 11410 11411 11412 11413 11414 11415 11416 11417 11418 11419 11420 11421 11422 11423 11424 11425 11426 11427 11428 11429
#if VBOX_API_VERSION < 4000000

static nsresult
_virtualboxGetMachine(IVirtualBox *vboxObj, vboxIIDUnion *iidu, IMachine **machine)
{
    return vboxObj->vtbl->GetMachine(vboxObj, IID_MEMBER(value), machine);
}

#else /* VBOX_API_VERSION >= 4000000 */

static nsresult
_virtualboxGetMachine(IVirtualBox *vboxObj, vboxIIDUnion *iidu, IMachine **machine)
{
    return vboxObj->vtbl->FindMachine(vboxObj, IID_MEMBER(value), machine);
}

#endif /* VBOX_API_VERSION >= 4000000 */

#if VBOX_API_VERSION < 4000000

static nsresult
_sessionOpenExisting(vboxGlobalData *data, vboxIIDUnion *iidu, IMachine *machine ATTRIBUTE_UNUSED)
{
    return data->vboxObj->vtbl->OpenExistingSession(data->vboxObj, data->vboxSession, IID_MEMBER(value));
}

static nsresult
_sessionClose(ISession *session)
{
    return session->vtbl->Close(session);
}

#else /* VBOX_API_VERSION >= 4000000 */

static nsresult
_sessionOpenExisting(vboxGlobalData *data, vboxIIDUnion *iidu ATTRIBUTE_UNUSED, IMachine *machine)
{
    return machine->vtbl->LockMachine(machine, data->vboxSession, LockType_Shared);
}

static nsresult
_sessionClose(ISession *session)
{
    return session->vtbl->UnlockMachine(session);
}

#endif /* VBOX_API_VERSION >= 4000000 */

static nsresult
_sessionGetConsole(ISession *session, IConsole **console)
{
    return session->vtbl->GetConsole(session, console);
}

static nsresult
_consoleSaveState(IConsole *console, IProgress **progress)
{
    return console->vtbl->SaveState(console, progress);
}

static nsresult
_progressWaitForCompletion(IProgress *progress, PRInt32 timeout)
{
    return progress->vtbl->WaitForCompletion(progress, timeout);
}

static nsresult
_progressGetResultCode(IProgress *progress, resultCodeUnion *resultCode)
{
#if VBOX_API_VERSION == 2002000
    return progress->vtbl->GetResultCode(progress, &resultCode->uResultCode);
#else /* VBOX_API_VERSION != 2002000 */
    return progress->vtbl->GetResultCode(progress, &resultCode->resultCode);
#endif /* VBOX_API_VERSION != 2002000 */
}

T
Taowei 已提交
11430 11431 11432 11433 11434 11435 11436 11437 11438 11439
static vboxUniformedPFN _UPFN = {
    .Initialize = _pfnInitialize,
    .Uninitialize = _pfnUninitialize,
    .ComUnallocMem = _pfnComUnallocMem,
    .Utf16Free = _pfnUtf16Free,
    .Utf8Free = _pfnUtf8Free,
    .Utf16ToUtf8 = _pfnUtf16ToUtf8,
    .Utf8ToUtf16 = _pfnUtf8ToUtf16,
};

T
Taowei 已提交
11440 11441 11442 11443 11444 11445 11446 11447 11448 11449 11450 11451 11452 11453
static vboxUniformedIID _UIID = {
    .vboxIIDInitialize = _vboxIIDInitialize,
    .vboxIIDUnalloc = _vboxIIDUnalloc,
    .vboxIIDToUUID = _vboxIIDToUUID,
    .vboxIIDFromUUID = _vboxIIDFromUUID,
    .vboxIIDIsEqual = _vboxIIDIsEqual,
    .vboxIIDFromArrayItem = _vboxIIDFromArrayItem,
    .DEBUGIID = _DEBUGIID,
};

static vboxUniformednsISupports _nsUISupports = {
    .Release = _nsisupportsRelease,
};

T
Taowei 已提交
11454 11455
static vboxUniformedIVirtualBox _UIVirtualBox = {
    .GetVersion = _virtualboxGetVersion,
T
Taowei 已提交
11456 11457 11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471
    .GetMachine = _virtualboxGetMachine,
};

static vboxUniformedISession _UISession = {
    .OpenExisting = _sessionOpenExisting,
    .GetConsole = _sessionGetConsole,
    .Close = _sessionClose,
};

static vboxUniformedIConsole _UIConsole = {
    .SaveState = _consoleSaveState,
};

static vboxUniformedIProgress _UIProgress = {
    .WaitForCompletion = _progressWaitForCompletion,
    .GetResultCode = _progressGetResultCode,
T
Taowei 已提交
11472 11473 11474 11475 11476 11477 11478 11479 11480
};

void NAME(InstallUniformedAPI)(vboxUniformedAPI *pVBoxAPI)
{
    pVBoxAPI->APIVersion = VBOX_API_VERSION;
    pVBoxAPI->XPCOMCVersion = VBOX_XPCOMC_VERSION;
    pVBoxAPI->initializeDomainEvent = _initializeDomainEvent;
    pVBoxAPI->registerGlobalData = _registerGlobalData;
    pVBoxAPI->UPFN = _UPFN;
T
Taowei 已提交
11481 11482
    pVBoxAPI->UIID = _UIID;
    pVBoxAPI->nsUISupports = _nsUISupports;
T
Taowei 已提交
11483
    pVBoxAPI->UIVirtualBox = _UIVirtualBox;
T
Taowei 已提交
11484 11485 11486
    pVBoxAPI->UISession = _UISession;
    pVBoxAPI->UIConsole = _UIConsole;
    pVBoxAPI->UIProgress = _UIProgress;
T
Taowei 已提交
11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499

#if VBOX_API_VERSION <= 2002000 || VBOX_API_VERSION >= 4000000
    pVBoxAPI->domainEventCallbacks = 0;
#else /* VBOX_API_VERSION > 2002000 || VBOX_API_VERSION < 4000000 */
    pVBoxAPI->domainEventCallbacks = 1;
#endif /* VBOX_API_VERSION > 2002000 || VBOX_API_VERSION < 4000000 */

#if VBOX_API_VERSION == 2002000
    pVBoxAPI->hasStaticGlobalData = 0;
#else /* VBOX_API_VERSION > 2002000 */
    pVBoxAPI->hasStaticGlobalData = 1;
#endif /* VBOX_API_VERSION > 2002000 */

T
Taowei 已提交
11500 11501 11502 11503 11504 11505
#if VBOX_API_VERSION >= 4000000
    /* Get machine for the call to VBOX_SESSION_OPEN_EXISTING */
    pVBoxAPI->getMachineForSession = 1;
#else /* VBOX_API_VERSION < 4000000 */
    pVBoxAPI->getMachineForSession = 0;
#endif /* VBOX_API_VERSION < 4000000 */
T
Taowei 已提交
11506
}
11507

11508 11509 11510 11511
/**
 * Function Tables
 */

11512
virDriver NAME(Driver) = {
11513 11514
    .no = VIR_DRV_VBOX,
    .name = "VBOX",
11515 11516 11517
    .connectOpen = vboxConnectOpen, /* 0.6.3 */
    .connectClose = vboxConnectClose, /* 0.6.3 */
    .connectGetVersion = vboxConnectGetVersion, /* 0.6.3 */
11518
    .connectGetHostname = vboxConnectGetHostname, /* 0.6.3 */
11519
    .connectGetMaxVcpus = vboxConnectGetMaxVcpus, /* 0.6.3 */
11520
    .nodeGetInfo = vboxNodeGetInfo, /* 0.6.3 */
11521 11522 11523 11524
    .connectGetCapabilities = vboxConnectGetCapabilities, /* 0.6.3 */
    .connectListDomains = vboxConnectListDomains, /* 0.6.3 */
    .connectNumOfDomains = vboxConnectNumOfDomains, /* 0.6.3 */
    .connectListAllDomains = vboxConnectListAllDomains, /* 0.9.13 */
11525 11526 11527 11528 11529 11530 11531
    .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 */
11532
    .domainShutdownFlags = vboxDomainShutdownFlags, /* 0.9.10 */
11533 11534
    .domainReboot = vboxDomainReboot, /* 0.6.3 */
    .domainDestroy = vboxDomainDestroy, /* 0.6.3 */
11535
    .domainDestroyFlags = vboxDomainDestroyFlags, /* 0.9.4 */
11536 11537 11538 11539 11540 11541 11542 11543 11544 11545
    .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 */
11546 11547
    .connectListDefinedDomains = vboxConnectListDefinedDomains, /* 0.6.3 */
    .connectNumOfDefinedDomains = vboxConnectNumOfDefinedDomains, /* 0.6.3 */
11548 11549 11550 11551
    .domainCreate = vboxDomainCreate, /* 0.6.3 */
    .domainCreateWithFlags = vboxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = vboxDomainDefineXML, /* 0.6.3 */
    .domainUndefine = vboxDomainUndefine, /* 0.6.3 */
11552
    .domainUndefineFlags = vboxDomainUndefineFlags, /* 0.9.5 */
11553 11554 11555 11556 11557
    .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 */
11558 11559
    .nodeGetCellsFreeMemory = vboxNodeGetCellsFreeMemory, /* 0.6.5 */
    .nodeGetFreeMemory = vboxNodeGetFreeMemory, /* 0.6.5 */
11560
#if VBOX_API_VERSION >= 4000000
11561
    .domainScreenshot = vboxDomainScreenshot, /* 0.9.2 */
11562
#endif
11563
#if VBOX_API_VERSION > 2002000 && VBOX_API_VERSION < 4000000
11564 11565
    .connectDomainEventRegister = vboxConnectDomainEventRegister, /* 0.7.0 */
    .connectDomainEventDeregister = vboxConnectDomainEventDeregister, /* 0.7.0 */
11566
#endif
11567 11568
    .connectIsEncrypted = vboxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = vboxConnectIsSecure, /* 0.7.3 */
11569 11570 11571
    .domainIsActive = vboxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = vboxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = vboxDomainIsUpdated, /* 0.8.6 */
11572
#if VBOX_API_VERSION > 2002000 && VBOX_API_VERSION < 4000000
11573 11574
    .connectDomainEventRegisterAny = vboxConnectDomainEventRegisterAny, /* 0.8.0 */
    .connectDomainEventDeregisterAny = vboxConnectDomainEventDeregisterAny, /* 0.8.0 */
11575
#endif
11576 11577 11578 11579 11580 11581
    .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 */
11582
    .domainSnapshotGetParent = vboxDomainSnapshotGetParent, /* 0.9.7 */
11583
    .domainSnapshotCurrent = vboxDomainSnapshotCurrent, /* 0.8.0 */
11584 11585
    .domainSnapshotIsCurrent = vboxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = vboxDomainSnapshotHasMetadata, /* 0.9.13 */
11586 11587
    .domainRevertToSnapshot = vboxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = vboxDomainSnapshotDelete, /* 0.8.0 */
11588
    .connectIsAlive = vboxConnectIsAlive, /* 0.9.8 */
11589
    .nodeGetFreePages = vboxNodeGetFreePages, /* 1.2.6 */
11590
};
11591 11592 11593

virNetworkDriver NAME(NetworkDriver) = {
    "VBOX",
11594 11595
    .networkOpen = vboxNetworkOpen, /* 0.6.4 */
    .networkClose = vboxNetworkClose, /* 0.6.4 */
11596 11597 11598 11599
    .connectNumOfNetworks = vboxConnectNumOfNetworks, /* 0.6.4 */
    .connectListNetworks = vboxConnectListNetworks, /* 0.6.4 */
    .connectNumOfDefinedNetworks = vboxConnectNumOfDefinedNetworks, /* 0.6.4 */
    .connectListDefinedNetworks = vboxConnectListDefinedNetworks, /* 0.6.4 */
11600 11601 11602 11603 11604 11605 11606 11607
    .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 */
11608
};
11609 11610 11611

virStorageDriver NAME(StorageDriver) = {
    .name               = "VBOX",
11612 11613
    .storageOpen = vboxStorageOpen, /* 0.7.1 */
    .storageClose = vboxStorageClose, /* 0.7.1 */
11614 11615
    .connectNumOfStoragePools = vboxConnectNumOfStoragePools, /* 0.7.1 */
    .connectListStoragePools = vboxConnectListStoragePools, /* 0.7.1 */
11616 11617 11618 11619 11620 11621 11622 11623 11624 11625 11626 11627
    .storagePoolLookupByName = vboxStoragePoolLookupByName, /* 0.7.1 */
    .storagePoolNumOfVolumes = vboxStoragePoolNumOfVolumes, /* 0.7.1 */
    .storagePoolListVolumes = vboxStoragePoolListVolumes, /* 0.7.1 */

    .storageVolLookupByName = vboxStorageVolLookupByName, /* 0.7.1 */
    .storageVolLookupByKey = vboxStorageVolLookupByKey, /* 0.7.1 */
    .storageVolLookupByPath = vboxStorageVolLookupByPath, /* 0.7.1 */
    .storageVolCreateXML = vboxStorageVolCreateXML, /* 0.7.1 */
    .storageVolDelete = vboxStorageVolDelete, /* 0.7.1 */
    .storageVolGetInfo = vboxStorageVolGetInfo, /* 0.7.1 */
    .storageVolGetXMLDesc = vboxStorageVolGetXMLDesc, /* 0.7.1 */
    .storageVolGetPath = vboxStorageVolGetPath /* 0.7.1 */
11628
};