vbox_tmpl.c 423.3 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"
92 93


94
#define VIR_FROM_THIS                   VIR_FROM_VBOX
95 96 97

VIR_LOG_INIT("vbox.vbox_tmpl");

J
John Ferlan 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
#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)

122 123 124
#define VBOX_UTF16_TO_UTF8(arg1, arg2)  data->pFuncs->pfnUtf16ToUtf8(arg1, arg2)
#define VBOX_UTF8_TO_UTF16(arg1, arg2)  data->pFuncs->pfnUtf8ToUtf16(arg1, arg2)

125 126
#define VBOX_ADDREF(arg) (arg)->vtbl->nsisupports.AddRef((nsISupports *)(arg))

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

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

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

154
#if VBOX_API_VERSION < 3001000
155

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

164
#else  /* VBOX_API_VERSION >= 3001000 */
165 166 167

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

177
#endif /* VBOX_API_VERSION >= 3001000 */
178

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

#define DEBUGUUID(msg, iid) \
{\
192
    VIR_DEBUG(msg ": {%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",\
193 194 195 196 197 198 199 200 201 202 203 204 205
          (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]);\
}\

206 207
typedef struct {
    virMutex lock;
208
    unsigned long version;
209 210

    virCapsPtr caps;
211
    virDomainXMLOptionPtr xmlopt;
212 213 214

    IVirtualBox *vboxObj;
    ISession *vboxSession;
215 216 217

    /** Our version specific API table pointer. */
    PCVBOXXPCOM pFuncs;
218

219
#if VBOX_API_VERSION == 2002000
220 221 222

} vboxGlobalData;

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

225
    /* Async event handling */
226
    virObjectEventStatePtr domainEvents;
227 228
    int fdWatch;

229
# if VBOX_API_VERSION <= 3002000
230
    /* IVirtualBoxCallback is used in VirtualBox 3.x only */
231
    IVirtualBoxCallback *vboxCallback;
232
# endif /* VBOX_API_VERSION <= 3002000 */
233 234 235 236 237 238 239

    nsIEventQueue  *vboxQueue;
    int volatile vboxCallBackRefCount;

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

240 241
} vboxGlobalData;

242 243 244 245 246 247 248 249 250 251
/* 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
 */

252
static vboxGlobalData *g_pVBoxGlobalData = NULL;
253

254
#endif /* !(VBOX_API_VERSION == 2002000) */
255

256
#if VBOX_API_VERSION < 4000000
257 258 259 260 261 262 263 264 265 266 267 268 269

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

270
#else /* VBOX_API_VERSION >= 4000000 */
271 272 273 274 275 276 277 278 279 280 281 282 283

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

284
#endif /* VBOX_API_VERSION >= 4000000 */
285

286 287
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml);
static int vboxDomainCreate(virDomainPtr dom);
288
static int vboxDomainUndefineFlags(virDomainPtr dom, unsigned int flags);
289

290 291
static void vboxDriverLock(vboxGlobalData *data)
{
292 293 294
    virMutexLock(&data->lock);
}

295 296
static void vboxDriverUnlock(vboxGlobalData *data)
{
297 298 299
    virMutexUnlock(&data->lock);
}

300
#if VBOX_API_VERSION == 2002000
301

302 303
static void nsIDtoChar(unsigned char *uuid, const nsID *iid)
{
304 305 306
    char uuidstrsrc[VIR_UUID_STRING_BUFLEN];
    char uuidstrdst[VIR_UUID_STRING_BUFLEN];
    unsigned char uuidinterim[VIR_UUID_BUFLEN];
307
    size_t i;
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334

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

335
    for (i = 18; i < VIR_UUID_STRING_BUFLEN; i++) {
336 337 338 339
        uuidstrdst[i] = uuidstrsrc[i];
    }

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

343 344
static void nsIDFromChar(nsID *iid, const unsigned char *uuid)
{
345 346 347
    char uuidstrsrc[VIR_UUID_STRING_BUFLEN];
    char uuidstrdst[VIR_UUID_STRING_BUFLEN];
    unsigned char uuidinterim[VIR_UUID_BUFLEN];
348
    size_t i;
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374

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

375
    for (i = 18; i < VIR_UUID_STRING_BUFLEN; i++) {
376 377 378 379
        uuidstrdst[i] = uuidstrsrc[i];
    }

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

384
# ifdef WIN32
385

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
typedef struct _vboxIID_v2_x_WIN32 vboxIID;
typedef struct _vboxIID_v2_x_WIN32 vboxIID_v2_x_WIN32;

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

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

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

403 404 405 406 407
static void
vboxIIDToUUID_v2_x_WIN32(vboxIID_v2_x_WIN32 *iid, unsigned char *uuid)
{
    nsIDtoChar(uuid, (nsID *)&iid->value);
}
408

409 410 411 412 413
static void
vboxIIDFromUUID_v2_x_WIN32(vboxGlobalData *data, vboxIID_v2_x_WIN32 *iid,
                           const unsigned char *uuid)
{
    vboxIIDUnalloc_v2_x_WIN32(data, iid);
414

415
    nsIDFromChar((nsID *)&iid->value, uuid);
416 417
}

418 419 420
static bool
vboxIIDIsEqual_v2_x_WIN32(vboxIID_v2_x_WIN32 *iid1, vboxIID_v2_x_WIN32 *iid2)
{
421
    return memcmp(&iid1->value, &iid2->value, sizeof(GUID)) == 0;
422
}
423

424 425 426 427 428 429 430 431
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);

432
    memcpy(&iid->value, &items[idx], sizeof(GUID));
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
}

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

# else /* !WIN32 */

typedef struct _vboxIID_v2_x vboxIID;
typedef struct _vboxIID_v2_x vboxIID_v2_x;

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

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

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

static void
vboxIIDUnalloc_v2_x(vboxGlobalData *data, vboxIID_v2_x *iid)
{
    if (iid->value == NULL) {
464 465 466
        return;
    }

467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
    if (iid->value != &iid->backing) {
        data->pFuncs->pfnComUnallocMem(iid->value);
    }

    iid->value = NULL;
}

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

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

    iid->value = &iid->backing;

488
    sa_assert(iid->value);
489
    nsIDFromChar(iid->value, uuid);
490 491
}

492 493 494
static bool
vboxIIDIsEqual_v2_x(vboxIID_v2_x *iid1, vboxIID_v2_x *iid2)
{
495
    return memcmp(iid1->value, iid2->value, sizeof(nsID)) == 0;
496 497 498 499 500 501 502 503 504 505
}

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

    iid->value = &iid->backing;

506
    memcpy(iid->value, array->items[idx], sizeof(nsID));
507 508 509 510 511 512 513 514 515 516 517 518
}

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

519
#else /* VBOX_API_VERSION != 2002000 */
520

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
typedef struct _vboxIID_v3_x vboxIID;
typedef struct _vboxIID_v3_x vboxIID_v3_x;

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

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

# define VBOX_IID_INITIALIZER { NULL, true }

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

    iid->value = NULL;
    iid->owner = true;
543 544
}

545 546 547 548 549 550 551 552
static void
vboxIIDToUUID_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                   unsigned char *uuid)
{
    char *utf8 = NULL;

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

553
    ignore_value(virUUIDParse(utf8, uuid));
554 555

    data->pFuncs->pfnUtf8Free(utf8);
556 557
}

558 559 560 561 562
static void
vboxIIDFromUUID_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                     const unsigned char *uuid)
{
    char utf8[VIR_UUID_STRING_BUFLEN];
563

564
    vboxIIDUnalloc_v3_x(data, iid);
565

566
    virUUIDFormat(uuid, utf8);
567

568 569
    data->pFuncs->pfnUtf8ToUtf16(utf8, &iid->value);
}
570

571 572 573 574 575 576
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];
577 578

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

586 587
    return memcmp(uuid1, uuid2, VIR_UUID_BUFLEN) == 0;
}
588 589


590 591 592 593 594
static void
vboxIIDFromArrayItem_v3_x(vboxGlobalData *data, vboxIID_v3_x *iid,
                          vboxArray *array, int idx)
{
    vboxIIDUnalloc_v3_x(data, iid);
595

596 597
    iid->value = array->items[idx];
    iid->owner = false;
598 599
}

600 601 602 603 604 605 606 607

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

609
# if VBOX_API_VERSION >= 3001000
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625

/**
 * 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
 *
 */
626
static char *vboxGenerateMediumName(PRUint32  storageBus,
627 628 629 630
                                    PRInt32   deviceInst,
                                    PRInt32   devicePort,
                                    PRInt32   deviceSlot,
                                    PRUint32 *aMaxPortPerInst,
631 632
                                    PRUint32 *aMaxSlotPerPort)
{
633
    const char *prefix = NULL;
634 635 636 637 638
    char *name  = NULL;
    int   total = 0;
    PRUint32 maxPortPerInst = 0;
    PRUint32 maxSlotPerPort = 0;

639 640
    if (!aMaxPortPerInst ||
        !aMaxSlotPerPort)
641 642
        return NULL;

643 644
    if ((storageBus < StorageBus_IDE) ||
        (storageBus > StorageBus_Floppy))
645 646 647 648 649 650 651 652 653
        return NULL;

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

    if (storageBus == StorageBus_IDE) {
654
        prefix = "hd";
655 656
    } else if ((storageBus == StorageBus_SATA) ||
               (storageBus == StorageBus_SCSI)) {
657
        prefix = "sd";
658
    } else if (storageBus == StorageBus_Floppy) {
659
        prefix = "fd";
660 661
    }

662
    name = virIndexToDiskName(total, prefix);
663

664
    VIR_DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
665
          "devicePort=%d deviceSlot=%d, maxPortPerInst=%u maxSlotPerPort=%u",
666
          NULLSTR(name), total, storageBus, deviceInst, devicePort,
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
          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;

698 699 700 701 702 703
    if (!deviceName ||
        !deviceInst ||
        !devicePort ||
        !deviceSlot ||
        !aMaxPortPerInst ||
        !aMaxSlotPerPort)
704 705
        return false;

706 707
    if ((storageBus < StorageBus_IDE) ||
        (storageBus > StorageBus_Floppy))
708 709 710 711 712 713 714
        return false;

    total = virDiskNameToIndex(deviceName);

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

715 716 717
    if (!maxPortPerInst ||
        !maxSlotPerPort ||
        (total < 0))
718 719 720 721 722 723
        return false;

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

724
    VIR_DEBUG("name=%s, total=%d, storageBus=%u, deviceInst=%d, "
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
          "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,
745 746
                                     PRUint32 *maxSlotPerPort)
{
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    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
 */
791 792
static int PRUnicharToInt(PRUnichar *strUtf16)
{
793 794 795 796 797 798 799 800 801 802
    char *strUtf8 = NULL;
    int ret = 0;

    if (!strUtf16)
        return -1;

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

803 804 805
    if (virStrToLong_i(strUtf8, NULL, 10, &ret) < 0)
        ret = -1;

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
    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;
}

825
# endif /* VBOX_API_VERSION >= 3001000 */
826

827
#endif /* !(VBOX_API_VERSION == 2002000) */
828

829 830 831 832 833 834
static PRUnichar *
vboxSocketFormatAddrUtf16(vboxGlobalData *data, virSocketAddrPtr addr)
{
    char *utf8 = NULL;
    PRUnichar *utf16 = NULL;

835
    utf8 = virSocketAddrFormat(addr);
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855

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

856
    if (virSocketAddrParse(addr, utf8, AF_UNSPEC) < 0) {
857 858 859 860 861
        goto cleanup;
    }

    result = 0;

862
 cleanup:
863 864 865 866 867
    VBOX_UTF8_FREE(utf8);

    return result;
}

868

869 870 871 872 873
static virDomainDefParserConfig vboxDomainDefParserConfig = {
    .macPrefix = { 0x08, 0x00, 0x27 },
};


874
static virDomainXMLOptionPtr
875 876
vboxXMLConfInit(void)
{
877 878
    return virDomainXMLOptionNew(&vboxDomainDefParserConfig,
                                 NULL, NULL);
879 880 881
}


882 883
static virCapsPtr vboxCapsInit(void)
{
884 885 886
    virCapsPtr caps;
    virCapsGuestPtr guest;

887
    if ((caps = virCapabilitiesNew(virArchFromHost(),
888
                                   false, false)) == NULL)
889 890
        goto no_memory;

891
    if (nodeCapsInitNUMA(caps) < 0)
892 893 894 895
        goto no_memory;

    if ((guest = virCapabilitiesAddGuest(caps,
                                         "hvm",
896
                                         caps->host.arch,
897 898 899 900 901 902 903 904 905 906 907 908 909
                                         NULL,
                                         NULL,
                                         0,
                                         NULL)) == NULL)
        goto no_memory;

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

911 912
    return caps;

913
 no_memory:
914
    virObjectUnref(caps);
915 916 917
    return NULL;
}

918 919 920
static int
vboxInitialize(vboxGlobalData *data)
{
921 922 923
    data->pFuncs = g_pfnGetFunctions(VBOX_XPCOMC_VERSION);

    if (data->pFuncs == NULL)
924
        goto cleanup;
925 926 927

#if VBOX_XPCOMC_VERSION == 0x00010000U
    data->pFuncs->pfnComInitialize(&data->vboxObj, &data->vboxSession);
928
#else  /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
929 930
    data->pFuncs->pfnComInitialize(IVIRTUALBOX_IID_STR, &data->vboxObj,
                               ISESSION_IID_STR, &data->vboxSession);
931

932
# if VBOX_API_VERSION == 2002000
933 934 935

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

936
# else  /* !(VBOX_API_VERSION == 2002000) */
937 938 939 940 941 942 943

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

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

    if (data->vboxQueue == NULL) {
944 945
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("nsIEventQueue object is null"));
946 947 948
        goto cleanup;
    }

949
# endif /* !(VBOX_API_VERSION == 2002000) */
950
#endif /* !(VBOX_XPCOMC_VERSION == 0x00010000U) */
951 952

    if (data->vboxObj == NULL) {
953 954
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("IVirtualBox object is null"));
955
        goto cleanup;
956 957 958
    }

    if (data->vboxSession == NULL) {
959 960
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("ISession object is null"));
961 962
        goto cleanup;
    }
963 964 965

    return 0;

966
 cleanup:
967 968 969
    return -1;
}

970 971
static int vboxExtractVersion(vboxGlobalData *data)
{
972
    int ret = -1;
973 974 975 976 977 978 979 980 981 982
    PRUnichar *versionUtf16 = NULL;
    nsresult rc;

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

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

983
        VBOX_UTF16_TO_UTF8(versionUtf16, &vboxVersion);
984

985
        if (virParseVersionString(vboxVersion, &data->version, false) >= 0)
986 987
            ret = 0;

988 989
        VBOX_UTF8_FREE(vboxVersion);
        VBOX_COM_UNALLOC_MEM(versionUtf16);
990 991 992
    }

    if (ret != 0)
993 994
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not extract VirtualBox version"));
995

996 997 998
    return ret;
}

999 1000
static void vboxUninitialize(vboxGlobalData *data)
{
1001 1002 1003
    if (!data)
        return;

1004 1005
    if (data->pFuncs)
        data->pFuncs->pfnComUninitialize();
1006

1007
    virObjectUnref(data->caps);
1008
    virObjectUnref(data->xmlopt);
1009
#if VBOX_API_VERSION == 2002000
1010
    /* No domainEventCallbacks in 2.2.* version */
1011
#else  /* !(VBOX_API_VERSION == 2002000) */
1012
    virObjectEventStateFree(data->domainEvents);
1013
#endif /* !(VBOX_API_VERSION == 2002000) */
1014 1015 1016
    VIR_FREE(data);
}

1017

1018 1019 1020
static virDrvOpenStatus vboxConnectOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                        unsigned int flags)
E
Eric Blake 已提交
1021
{
1022
    vboxGlobalData *data = NULL;
1023
    uid_t uid = geteuid();
1024

E
Eric Blake 已提交
1025 1026
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

1027 1028 1029
    if (conn->uri == NULL &&
        !(conn->uri = virURIParse(uid ? "vbox:///session" : "vbox:///system")))
        return VIR_DRV_OPEN_ERROR;
1030

1031
    if (conn->uri->scheme == NULL ||
1032
        STRNEQ(conn->uri->scheme, "vbox"))
1033 1034 1035 1036
        return VIR_DRV_OPEN_DECLINED;

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

1039
    if (conn->uri->path == NULL || STREQ(conn->uri->path, "")) {
1040 1041
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no VirtualBox driver path specified (try vbox:///session)"));
1042 1043 1044
        return VIR_DRV_OPEN_ERROR;
    }

1045
    if (uid != 0) {
1046
        if (STRNEQ(conn->uri->path, "/session")) {
1047 1048
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown driver path '%s' specified (try vbox:///session)"), conn->uri->path);
1049 1050
            return VIR_DRV_OPEN_ERROR;
        }
1051
    } else { /* root */
1052 1053
        if (STRNEQ(conn->uri->path, "/system") &&
            STRNEQ(conn->uri->path, "/session")) {
1054 1055
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown driver path '%s' specified (try vbox:///system)"), conn->uri->path);
1056 1057
            return VIR_DRV_OPEN_ERROR;
        }
1058 1059
    }

1060
    if (VIR_ALLOC(data) < 0)
1061
        return VIR_DRV_OPEN_ERROR;
1062

1063
    if (!(data->caps = vboxCapsInit()) ||
1064
        vboxInitialize(data) < 0 ||
1065
        vboxExtractVersion(data) < 0 ||
1066
        !(data->xmlopt = vboxXMLConfInit())) {
1067 1068 1069
        vboxUninitialize(data);
        return VIR_DRV_OPEN_ERROR;
    }
1070

1071
#if VBOX_API_VERSION == 2002000
1072 1073 1074

    /* No domainEventCallbacks in 2.2.* version */

1075
#else  /* !(VBOX_API_VERSION == 2002000) */
1076

1077
    if (!(data->domainEvents = virObjectEventStateNew())) {
1078
        vboxUninitialize(data);
1079 1080 1081 1082 1083 1084
        return VIR_DRV_OPEN_ERROR;
    }

    data->conn = conn;
    g_pVBoxGlobalData = data;

1085
#endif /* !(VBOX_API_VERSION == 2002000) */
1086

1087
    conn->privateData = data;
1088
    VIR_DEBUG("in vboxOpen");
1089 1090 1091 1092

    return VIR_DRV_OPEN_SUCCESS;
}

1093 1094
static int vboxConnectClose(virConnectPtr conn)
{
1095
    vboxGlobalData *data = conn->privateData;
E
Eric Blake 已提交
1096
    VIR_DEBUG("%s: in vboxClose", conn->driver->name);
1097 1098 1099 1100 1101 1102 1103

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

    return 0;
}

1104 1105
static int vboxConnectGetVersion(virConnectPtr conn, unsigned long *version)
{
1106
    vboxGlobalData *data = conn->privateData;
E
Eric Blake 已提交
1107
    VIR_DEBUG("%s: in vboxGetVersion", conn->driver->name);
1108 1109 1110 1111 1112 1113 1114 1115

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

    return 0;
}

1116 1117 1118 1119 1120 1121 1122

static char *vboxConnectGetHostname(virConnectPtr conn ATTRIBUTE_UNUSED)
{
    return virGetHostname();
}


1123 1124
static int vboxConnectIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
{
1125 1126 1127 1128
    /* Driver is using local, non-network based transport */
    return 1;
}

1129 1130
static int vboxConnectIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
{
1131 1132 1133 1134
    /* No encryption is needed, or used on the local transport*/
    return 0;
}

1135
static int vboxConnectIsAlive(virConnectPtr conn ATTRIBUTE_UNUSED)
1136 1137 1138 1139
{
    return 1;
}

1140 1141 1142
static int
vboxConnectGetMaxVcpus(virConnectPtr conn, const char *type ATTRIBUTE_UNUSED)
{
1143
    VBOX_OBJECT_CHECK(conn, int, -1);
1144 1145 1146 1147 1148
    PRUint32 maxCPUCount = 0;

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

1151 1152 1153 1154
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
1155 1156 1157 1158 1159 1160 1161 1162 1163
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}


1164
static char *vboxConnectGetCapabilities(virConnectPtr conn) {
1165
    VBOX_OBJECT_CHECK(conn, char *, NULL);
1166 1167 1168 1169 1170 1171 1172 1173

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

    return ret;
}

1174 1175
static int vboxConnectListDomains(virConnectPtr conn, int *ids, int nids)
{
1176
    VBOX_OBJECT_CHECK(conn, int, -1);
1177
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1178
    PRUint32 state;
1179
    nsresult rc;
1180
    size_t i, j;
1181

1182
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1183
    if (NS_FAILED(rc)) {
1184
        virReportError(VIR_ERR_INTERNAL_ERROR,
E
Eric Blake 已提交
1185 1186
                       _("Could not get list of Domains, rc=%08x"),
                       (unsigned)rc);
1187 1188
        goto cleanup;
    }
1189

1190 1191 1192
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < nids); ++i) {
        IMachine *machine = machines.items[i];
1193 1194 1195 1196 1197 1198

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
1199 1200
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline)) {
1201 1202
                    ret++;
                    ids[j++] = i + 1;
1203 1204 1205 1206 1207
                }
            }
        }
    }

1208
 cleanup:
1209
    vboxArrayRelease(&machines);
1210 1211 1212
    return ret;
}

1213 1214
static int vboxConnectNumOfDomains(virConnectPtr conn)
{
1215
    VBOX_OBJECT_CHECK(conn, int, -1);
1216
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1217
    PRUint32 state;
1218
    nsresult rc;
1219
    size_t i;
1220

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

1228 1229 1230
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1231 1232 1233 1234 1235 1236

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
1237 1238
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1239
                    ret++;
1240 1241 1242 1243
            }
        }
    }

1244
 cleanup:
1245
    vboxArrayRelease(&machines);
1246 1247 1248 1249
    return ret;
}

static virDomainPtr vboxDomainCreateXML(virConnectPtr conn, const char *xml,
1250 1251
                                        unsigned int flags)
{
1252 1253 1254 1255 1256 1257 1258 1259
    /* 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.
     */

1260 1261 1262 1263 1264
    virDomainPtr dom;

    virCheckFlags(0, NULL);

    dom = vboxDomainDefineXML(conn, xml);
1265 1266 1267 1268
    if (dom == NULL)
        return NULL;

    if (vboxDomainCreate(dom) < 0) {
1269
        vboxDomainUndefineFlags(dom, 0);
1270
        virObjectUnref(dom);
1271
        return NULL;
1272 1273 1274 1275 1276
    }

    return dom;
}

1277 1278
static virDomainPtr vboxDomainLookupByID(virConnectPtr conn, int id)
{
1279
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1280
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1281 1282
    vboxIID iid = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
1283
    PRUint32 state;
1284
    nsresult rc;
1285

1286
    /* Internal vbox IDs start from 0, the public libvirt ID
1287
     * starts from 1, so refuse id == 0, and adjust the rest*/
1288
    if (id == 0) {
1289 1290
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), id);
1291 1292 1293 1294
        return NULL;
    }
    id = id - 1;

1295
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1296
    if (NS_FAILED(rc)) {
1297 1298
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1299 1300
        return NULL;
    }
1301

1302 1303 1304 1305
    if (id < machines.count) {
        IMachine *machine = machines.items[id];

        if (machine) {
1306
            PRBool isAccessible = PR_FALSE;
1307
            machine->vtbl->GetAccessible(machine, &isAccessible);
1308
            if (isAccessible) {
1309
                machine->vtbl->GetState(machine, &state);
1310 1311
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline)) {
1312 1313
                    PRUnichar *machineNameUtf16 = NULL;
                    char      *machineNameUtf8  = NULL;
1314

1315
                    machine->vtbl->GetName(machine, &machineNameUtf16);
1316
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1317

1318 1319 1320
                    machine->vtbl->GetId(machine, &iid.value);
                    vboxIIDToUUID(&iid, uuid);
                    vboxIIDUnalloc(&iid);
1321 1322 1323 1324 1325 1326 1327

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

1328
                    ret = virGetDomain(conn, machineNameUtf8, uuid);
1329 1330 1331 1332 1333 1334
                    if (ret)
                        ret->id = id + 1;

                    /* Cleanup all the XPCOM allocated stuff here */
                    VBOX_UTF8_FREE(machineNameUtf8);
                    VBOX_UTF16_FREE(machineNameUtf16);
1335 1336 1337 1338 1339
                }
            }
        }
    }

1340
    vboxArrayRelease(&machines);
1341 1342

    return ret;
1343 1344
}

1345 1346 1347
static virDomainPtr
vboxDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
1348
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1349
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1350
    vboxIID iid = VBOX_IID_INITIALIZER;
1351
    char      *machineNameUtf8  = NULL;
1352
    PRUnichar *machineNameUtf16 = NULL;
1353
    unsigned char iid_as_uuid[VIR_UUID_BUFLEN];
1354 1355
    size_t i;
    int matched = 0;
1356
    nsresult rc;
1357

1358
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1359
    if (NS_FAILED(rc)) {
1360 1361
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1362 1363
        return NULL;
    }
1364

1365 1366
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1367
        PRBool isAccessible = PR_FALSE;
1368

1369 1370
        if (!machine)
            continue;
1371

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

1375 1376
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
1377
                continue;
1378 1379
            vboxIIDToUUID(&iid, iid_as_uuid);
            vboxIIDUnalloc(&iid);
1380

1381
            if (memcmp(uuid, iid_as_uuid, VIR_UUID_BUFLEN) == 0) {
1382

1383
                PRUint32 state;
1384

1385
                matched = 1;
1386

1387 1388
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1389

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

1392 1393 1394 1395 1396
                /* 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.
                 */
1397

1398
                ret = virGetDomain(conn, machineNameUtf8, iid_as_uuid);
1399 1400 1401
                if (ret &&
                    (state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1402
                    ret->id = i + 1;
1403 1404
            }

1405 1406
            if (matched == 1)
                break;
1407 1408 1409
        }
    }

1410 1411 1412
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1413
    vboxArrayRelease(&machines);
1414 1415

    return ret;
1416 1417
}

1418 1419 1420
static virDomainPtr
vboxDomainLookupByName(virConnectPtr conn, const char *name)
{
1421
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
1422
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1423
    vboxIID iid = VBOX_IID_INITIALIZER;
1424
    char      *machineNameUtf8  = NULL;
1425
    PRUnichar *machineNameUtf16 = NULL;
1426
    unsigned char uuid[VIR_UUID_BUFLEN];
1427 1428
    size_t i;
    int matched = 0;
1429
    nsresult rc;
1430

1431
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1432
    if (NS_FAILED(rc)) {
1433 1434
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1435 1436
        return NULL;
    }
1437

1438 1439
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1440
        PRBool isAccessible = PR_FALSE;
1441

1442 1443
        if (!machine)
            continue;
1444

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

1448 1449
            machine->vtbl->GetName(machine, &machineNameUtf16);
            VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1450

1451
            if (STREQ(name, machineNameUtf8)) {
1452

1453
                PRUint32 state;
1454

1455
                matched = 1;
1456

1457 1458 1459
                machine->vtbl->GetId(machine, &iid.value);
                vboxIIDToUUID(&iid, uuid);
                vboxIIDUnalloc(&iid);
1460

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

1463 1464 1465 1466 1467
                /* 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.
                 */
1468

1469
                ret = virGetDomain(conn, machineNameUtf8, uuid);
1470 1471 1472
                if (ret &&
                    (state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1473
                    ret->id = i + 1;
1474 1475
            }

J
John Ferlan 已提交
1476 1477
            VBOX_UTF8_FREE(machineNameUtf8);
            VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1478 1479
            if (matched == 1)
                break;
1480 1481 1482
        }
    }

1483
    vboxArrayRelease(&machines);
1484 1485

    return ret;
1486 1487
}

1488

1489 1490
static int vboxDomainIsActive(virDomainPtr dom)
{
1491
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1492
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1493
    vboxIID iid = VBOX_IID_INITIALIZER;
1494 1495
    char      *machineNameUtf8  = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1496
    unsigned char uuid[VIR_UUID_BUFLEN];
1497 1498
    size_t i;
    int matched = 0;
1499
    nsresult rc;
1500

1501
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1502
    if (NS_FAILED(rc)) {
1503 1504
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1505 1506
        return ret;
    }
1507

1508 1509
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1510 1511 1512 1513 1514 1515 1516
        PRBool isAccessible = PR_FALSE;

        if (!machine)
            continue;

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

1518 1519
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
1520
                continue;
1521 1522
            vboxIIDToUUID(&iid, uuid);
            vboxIIDUnalloc(&iid);
1523

1524
            if (memcmp(dom->uuid, uuid, VIR_UUID_BUFLEN) == 0) {
1525

1526
                PRUint32 state;
1527

1528
                matched = 1;
1529

1530 1531
                machine->vtbl->GetName(machine, &machineNameUtf16);
                VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineNameUtf8);
1532

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

1535 1536
                if ((state >= MachineState_FirstOnline) &&
                    (state <= MachineState_LastOnline))
1537 1538 1539
                    ret = 1;
                else
                    ret = 0;
1540 1541
            }

1542 1543
            if (matched == 1)
                break;
1544 1545 1546
        }
    }

1547 1548 1549
    /* Do the cleanup and take care you dont leak any memory */
    VBOX_UTF8_FREE(machineNameUtf8);
    VBOX_COM_UNALLOC_MEM(machineNameUtf16);
1550
    vboxArrayRelease(&machines);
1551

1552 1553 1554 1555
    return ret;
}


1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
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)) {
1568 1569
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
1570 1571 1572 1573 1574
        goto cleanup;
    }

    ret = 1;

1575
 cleanup:
1576 1577 1578
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
1579 1580 1581
}


1582 1583
static int vboxDomainIsUpdated(virDomainPtr dom ATTRIBUTE_UNUSED)
{
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
    /* 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)) {
1594 1595
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
1596 1597 1598 1599 1600
        goto cleanup;
    }

    ret = 0;

1601
 cleanup:
1602 1603 1604
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
1605 1606
}

1607 1608
static int vboxDomainSuspend(virDomainPtr dom)
{
1609
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1610
    IMachine *machine    = NULL;
1611
    vboxIID iid = VBOX_IID_INITIALIZER;
1612
    IConsole *console    = NULL;
1613
    PRBool isAccessible  = PR_FALSE;
1614
    PRUint32 state;
1615
    nsresult rc;
1616

1617
    vboxIIDFromUUID(&iid, dom->uuid);
1618
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1619
    if (NS_FAILED(rc)) {
1620 1621
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1622 1623
        goto cleanup;
    }
1624

1625 1626
    if (!machine)
        goto cleanup;
1627

1628 1629 1630
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1631

1632
        if (state == MachineState_Running) {
1633 1634
            /* set state pause */
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1635 1636 1637 1638 1639
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Pause(console);
                VBOX_RELEASE(console);
                ret = 0;
1640
            } else {
1641 1642
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("error while suspending the domain"));
1643 1644
                goto cleanup;
            }
1645
            VBOX_SESSION_CLOSE();
1646
        } else {
1647 1648
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine not in running state to suspend it"));
1649
            goto cleanup;
1650 1651 1652
        }
    }

1653
 cleanup:
1654
    VBOX_RELEASE(machine);
1655
    vboxIIDUnalloc(&iid);
1656 1657 1658
    return ret;
}

1659 1660
static int vboxDomainResume(virDomainPtr dom)
{
1661
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1662
    IMachine *machine    = NULL;
1663
    vboxIID iid = VBOX_IID_INITIALIZER;
1664 1665
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1666
    nsresult rc;
1667

1668
    PRBool isAccessible = PR_FALSE;
1669

1670
    vboxIIDFromUUID(&iid, dom->uuid);
1671
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1672
    if (NS_FAILED(rc)) {
1673 1674
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1675 1676
        goto cleanup;
    }
1677

1678 1679
    if (!machine)
        goto cleanup;
1680

1681 1682 1683 1684 1685
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);

        if (state == MachineState_Paused) {
1686 1687
            /* resume the machine here */
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1688 1689 1690 1691 1692
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Resume(console);
                VBOX_RELEASE(console);
                ret = 0;
1693
            } else {
1694 1695
                virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                               _("error while resuming the domain"));
1696 1697
                goto cleanup;
            }
1698
            VBOX_SESSION_CLOSE();
1699
        } else {
1700 1701
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine not paused, so can't resume it"));
1702
            goto cleanup;
1703 1704 1705
        }
    }

1706
 cleanup:
1707
    VBOX_RELEASE(machine);
1708
    vboxIIDUnalloc(&iid);
1709 1710 1711
    return ret;
}

1712
static int vboxDomainShutdownFlags(virDomainPtr dom,
1713 1714
                                   unsigned int flags)
{
1715
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1716
    IMachine *machine    = NULL;
1717
    vboxIID iid = VBOX_IID_INITIALIZER;
1718 1719
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1720 1721
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1722

1723 1724
    virCheckFlags(0, -1);

1725
    vboxIIDFromUUID(&iid, dom->uuid);
1726
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1727
    if (NS_FAILED(rc)) {
1728 1729
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1730 1731
        goto cleanup;
    }
1732

1733 1734
    if (!machine)
        goto cleanup;
1735

1736 1737 1738
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1739

1740
        if (state == MachineState_Paused) {
1741 1742
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine paused, so can't power it down"));
1743 1744
            goto cleanup;
        } else if (state == MachineState_PoweredOff) {
1745 1746
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine already powered down"));
1747 1748
            goto cleanup;
        }
1749

1750
        VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1751 1752 1753 1754 1755
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
            console->vtbl->PowerButton(console);
            VBOX_RELEASE(console);
            ret = 0;
1756
        }
1757
        VBOX_SESSION_CLOSE();
1758 1759
    }

1760
 cleanup:
1761
    VBOX_RELEASE(machine);
1762
    vboxIIDUnalloc(&iid);
1763 1764 1765
    return ret;
}

1766 1767
static int vboxDomainShutdown(virDomainPtr dom)
{
1768 1769 1770 1771
    return vboxDomainShutdownFlags(dom, 0);
}


E
Eric Blake 已提交
1772 1773
static int vboxDomainReboot(virDomainPtr dom, unsigned int flags)
{
1774
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1775
    IMachine *machine    = NULL;
1776
    vboxIID iid = VBOX_IID_INITIALIZER;
1777 1778
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1779 1780
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1781

E
Eric Blake 已提交
1782 1783
    virCheckFlags(0, -1);

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

1792 1793
    if (!machine)
        goto cleanup;
1794

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

1799
        if (state == MachineState_Running) {
1800
            VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1801 1802 1803 1804 1805
            data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
            if (console) {
                console->vtbl->Reset(console);
                VBOX_RELEASE(console);
                ret = 0;
1806
            }
1807
            VBOX_SESSION_CLOSE();
1808
        } else {
1809 1810
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine not running, so can't reboot it"));
1811
            goto cleanup;
1812 1813 1814
        }
    }

1815
 cleanup:
1816
    VBOX_RELEASE(machine);
1817
    vboxIIDUnalloc(&iid);
1818 1819 1820
    return ret;
}

1821 1822 1823 1824
static int
vboxDomainDestroyFlags(virDomainPtr dom,
                       unsigned int flags)
{
1825
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1826
    IMachine *machine    = NULL;
1827
    vboxIID iid = VBOX_IID_INITIALIZER;
1828 1829
    IConsole *console    = NULL;
    PRUint32 state       = MachineState_Null;
1830 1831
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1832

1833 1834
    virCheckFlags(0, -1);

1835
    vboxIIDFromUUID(&iid, dom->uuid);
1836
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1837
    if (NS_FAILED(rc)) {
1838 1839
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1840 1841
        goto cleanup;
    }
1842

1843 1844
    if (!machine)
        goto cleanup;
1845

1846 1847 1848
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1849

1850
        if (state == MachineState_PoweredOff) {
1851 1852
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("machine already powered down"));
1853 1854
            goto cleanup;
        }
1855

1856
        VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
1857 1858
        data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (console) {
1859

1860
#if VBOX_API_VERSION == 2002000
1861
            console->vtbl->PowerDown(console);
1862
#else
1863
            IProgress *progress = NULL;
1864 1865 1866 1867
            console->vtbl->PowerDown(console, &progress);
            if (progress) {
                progress->vtbl->WaitForCompletion(progress, -1);
                VBOX_RELEASE(progress);
1868
            }
1869 1870
#endif
            VBOX_RELEASE(console);
1871
            dom->id = -1;
1872
            ret = 0;
1873
        }
1874
        VBOX_SESSION_CLOSE();
1875 1876
    }

1877
 cleanup:
1878
    VBOX_RELEASE(machine);
1879
    vboxIIDUnalloc(&iid);
1880 1881 1882
    return ret;
}

1883 1884 1885 1886 1887 1888
static int
vboxDomainDestroy(virDomainPtr dom)
{
    return vboxDomainDestroyFlags(dom, 0);
}

1889
static char *vboxDomainGetOSType(virDomainPtr dom ATTRIBUTE_UNUSED) {
1890 1891 1892 1893 1894
    /* 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 ;)
     */
1895
    char *osType;
1896

1897
    ignore_value(VIR_STRDUP(osType, "hvm"));
1898
    return osType;
1899 1900
}

1901 1902
static int vboxDomainSetMemory(virDomainPtr dom, unsigned long memory)
{
1903
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1904
    IMachine *machine    = NULL;
1905
    vboxIID iid = VBOX_IID_INITIALIZER;
1906
    PRUint32 state       = MachineState_Null;
1907 1908
    PRBool isAccessible  = PR_FALSE;
    nsresult rc;
1909

1910
    vboxIIDFromUUID(&iid, dom->uuid);
1911
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
1912
    if (NS_FAILED(rc)) {
1913 1914
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("no domain with matching id %d"), dom->id);
1915 1916
        goto cleanup;
    }
1917

1918 1919
    if (!machine)
        goto cleanup;
1920

1921 1922 1923
    machine->vtbl->GetAccessible(machine, &isAccessible);
    if (isAccessible) {
        machine->vtbl->GetState(machine, &state);
1924

1925
        if (state != MachineState_PoweredOff) {
1926 1927
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("memory size can't be changed unless domain is powered down"));
1928 1929
            goto cleanup;
        }
1930

1931
        rc = VBOX_SESSION_OPEN(iid.value, machine);
1932 1933 1934
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
1935

1936 1937
                rc = machine->vtbl->SetMemorySize(machine,
                                                  VIR_DIV_UP(memory, 1024));
1938 1939 1940 1941
                if (NS_SUCCEEDED(rc)) {
                    machine->vtbl->SaveSettings(machine);
                    ret = 0;
                } else {
1942 1943 1944 1945
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("could not set the memory size of the "
                                     "domain to: %lu Kb, rc=%08x"),
                                   memory, (unsigned)rc);
1946 1947
                }
            }
1948
            VBOX_SESSION_CLOSE();
1949 1950 1951
        }
    }

1952
 cleanup:
1953
    VBOX_RELEASE(machine);
1954
    vboxIIDUnalloc(&iid);
1955 1956 1957
    return ret;
}

1958 1959
static virDomainState vboxConvertState(enum MachineState state)
{
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
    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 已提交
1970
        case MachineState_Saved:
1971 1972 1973 1974 1975 1976 1977 1978 1979
            return VIR_DOMAIN_SHUTOFF;
        case MachineState_Aborted:
            return VIR_DOMAIN_CRASHED;
        case MachineState_Null:
        default:
            return VIR_DOMAIN_NOSTATE;
    }
}

1980 1981
static int vboxDomainGetInfo(virDomainPtr dom, virDomainInfoPtr info)
{
1982
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
1983
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
1984 1985
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
1986
    nsresult rc;
1987
    size_t i = 0;
1988

1989
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
1990
    if (NS_FAILED(rc)) {
1991 1992
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
1993 1994
        goto cleanup;
    }
1995

1996
    info->nrVirtCpu = 0;
1997 1998
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
1999
        PRBool isAccessible = PR_FALSE;
2000

2001 2002
        if (!machine)
            continue;
2003

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

2007 2008 2009 2010 2011 2012
            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
2013
                * for time being set max_balloon and cur_balloon to same
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
                * 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;
                }
2031 2032


2033 2034 2035 2036 2037 2038
                machine->vtbl->GetCPUCount(machine, &CPUCount);
                machine->vtbl->GetMemorySize(machine, &memorySize);
                machine->vtbl->GetState(machine, &state);

                info->cpuTime = 0;
                info->nrVirtCpu = CPUCount;
2039 2040
                info->memory = memorySize * 1024;
                info->maxMem = maxMemorySize * 1024;
2041
                info->state = vboxConvertState(state);
2042

2043
                ret = 0;
2044 2045
            }

J
John Ferlan 已提交
2046 2047
            VBOX_UTF8_FREE(machineName);
            VBOX_COM_UNALLOC_MEM(machineNameUtf16);
2048 2049
            if (info->nrVirtCpu)
                break;
2050 2051 2052 2053
        }

    }

2054
    vboxArrayRelease(&machines);
2055

2056
 cleanup:
2057 2058 2059
    return ret;
}

2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
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)) {
2077 2078
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
2079 2080 2081 2082 2083
        goto cleanup;
    }

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

2084
    *state = vboxConvertState(mstate);
2085 2086 2087 2088 2089 2090

    if (reason)
        *reason = 0;

    ret = 0;

2091
 cleanup:
2092 2093 2094 2095
    vboxIIDUnalloc(&domiid);
    return ret;
}

2096 2097
static int vboxDomainSave(virDomainPtr dom, const char *path ATTRIBUTE_UNUSED)
{
2098
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
2099
    IConsole *console    = NULL;
2100
    vboxIID iid = VBOX_IID_INITIALIZER;
2101
    IMachine *machine = NULL;
2102
    nsresult rc;
2103 2104 2105 2106 2107 2108 2109 2110

    /* VirtualBox currently doesn't support saving to a file
     * at a location other then the machine folder and thus
     * setting path to ATTRIBUTE_UNUSED for now, will change
     * this behaviour once get the VirtualBox API in right
     * shape to do this
     */

2111
    /* Open a Session for the machine */
2112
    vboxIIDFromUUID(&iid, dom->uuid);
2113
#if VBOX_API_VERSION >= 4000000
2114 2115 2116
    /* Get machine for the call to VBOX_SESSION_OPEN_EXISTING */
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
2117 2118
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
2119 2120 2121 2122 2123
        return -1;
    }
#endif

    rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
2124 2125 2126 2127
    if (NS_SUCCEEDED(rc)) {
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
        if (NS_SUCCEEDED(rc) && console) {
            IProgress *progress = NULL;
2128

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

2131
            if (progress) {
2132
#if VBOX_API_VERSION == 2002000
2133
                nsresult resultCode;
2134
#else
2135
                PRInt32 resultCode;
2136
#endif
2137

2138 2139 2140 2141
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
                if (NS_SUCCEEDED(resultCode)) {
                    ret = 0;
2142
                }
2143
                VBOX_RELEASE(progress);
2144
            }
2145
            VBOX_RELEASE(console);
2146
        }
2147
        VBOX_SESSION_CLOSE();
2148 2149
    }

2150
    DEBUGIID("UUID of machine being saved:", iid.value);
2151

2152
    VBOX_RELEASE(machine);
2153
    vboxIIDUnalloc(&iid);
2154 2155 2156
    return ret;
}

2157 2158 2159 2160
static int
vboxDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
                        unsigned int flags)
{
2161
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
2162
    IMachine *machine    = NULL;
2163
    vboxIID iid = VBOX_IID_INITIALIZER;
2164
    PRUint32  CPUCount   = nvcpus;
2165
    nsresult rc;
2166

2167
    if (flags != VIR_DOMAIN_AFFECT_LIVE) {
2168
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2169 2170 2171
        return -1;
    }

2172
    vboxIIDFromUUID(&iid, dom->uuid);
2173
#if VBOX_API_VERSION >= 4000000
2174 2175 2176
    /* Get machine for the call to VBOX_SESSION_OPEN */
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
2177 2178
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
2179 2180 2181 2182 2183
        return -1;
    }
#endif

    rc = VBOX_SESSION_OPEN(iid.value, machine);
2184 2185 2186 2187 2188 2189 2190
    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;
2191
            } else {
2192 2193 2194 2195
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("could not set the number of cpus of the domain "
                                 "to: %u, rc=%08x"),
                               CPUCount, (unsigned)rc);
2196
            }
2197
            VBOX_RELEASE(machine);
2198
        } else {
2199 2200
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("no domain with matching id %d"), dom->id);
2201
        }
2202
    } else {
2203 2204
        virReportError(VIR_ERR_NO_DOMAIN,
                       _("can't open session to the domain with id %d"), dom->id);
2205
    }
2206
    VBOX_SESSION_CLOSE();
2207

2208
    vboxIIDUnalloc(&iid);
2209 2210 2211
    return ret;
}

2212 2213 2214
static int
vboxDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
{
2215
    return vboxDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_AFFECT_LIVE);
2216 2217 2218 2219 2220
}

static int
vboxDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
{
2221 2222
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
    ISystemProperties *systemProperties = NULL;
2223 2224
    PRUint32 maxCPUCount = 0;

2225
    if (flags != (VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_VCPU_MAXIMUM)) {
2226
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported flags: (0x%x)"), flags);
2227 2228 2229
        return -1;
    }

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

2235 2236 2237 2238
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxGuestCPUCount(systemProperties, &maxCPUCount);
        VBOX_RELEASE(systemProperties);
2239 2240 2241 2242 2243 2244 2245 2246
    }

    if (maxCPUCount > 0)
        ret = maxCPUCount;

    return ret;
}

2247 2248 2249
static int
vboxDomainGetMaxVcpus(virDomainPtr dom)
{
2250
    return vboxDomainGetVcpusFlags(dom, (VIR_DOMAIN_AFFECT_LIVE |
2251 2252 2253
                                         VIR_DOMAIN_VCPU_MAXIMUM));
}

2254 2255
static void vboxHostDeviceGetXMLDesc(vboxGlobalData *data, virDomainDefPtr def, IMachine *machine)
{
2256
#if VBOX_API_VERSION < 4003000
2257 2258
    IUSBController *USBController = NULL;
    PRBool enabled = PR_FALSE;
R
Ryota Ozaki 已提交
2259 2260 2261
#else
    IUSBDeviceFilters *USBDeviceFilters = NULL;
#endif
2262 2263 2264 2265 2266
    vboxArray deviceFilters = VBOX_ARRAY_INITIALIZER;
    size_t i;
    PRUint32 USBFilterCount = 0;

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

2268
#if VBOX_API_VERSION < 4003000
2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    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 已提交
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
#else
    machine->vtbl->GetUSBDeviceFilters(machine, &USBDeviceFilters);

    if (!USBDeviceFilters)
        return;

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

2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
    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;

2315 2316 2317 2318 2319 2320
    for (i = 0; i < def->nhostdevs; i++) {
        def->hostdevs[i] = virDomainHostdevDefAlloc();
        if (!def->hostdevs[i])
            goto release_hostdevs;
    }

2321
    for (i = 0; i < deviceFilters.count; i++) {
2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
        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);

2347 2348
        ignore_value(virStrToLong_ui(vendorIdUtf8, &endptr, 16, &vendorId));
        ignore_value(virStrToLong_ui(productIdUtf8, &endptr, 16, &productId));
2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361

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

2362
 release_filters:
2363
    vboxArrayRelease(&deviceFilters);
2364
#if VBOX_API_VERSION < 4003000
2365
 release_controller:
2366
    VBOX_RELEASE(USBController);
R
Ryota Ozaki 已提交
2367 2368 2369
#else
    VBOX_RELEASE(USBDeviceFilters);
#endif
2370 2371 2372

    return;

2373
 release_hostdevs:
2374 2375 2376 2377 2378
    for (i = 0; i < def->nhostdevs; i++)
        virDomainHostdevDefFree(def->hostdevs[i]);
    VIR_FREE(def->hostdevs);

    goto release_filters;
2379 2380
}

2381
static char *vboxDomainGetXMLDesc(virDomainPtr dom, unsigned int flags) {
2382
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
2383 2384
    virDomainDefPtr def  = NULL;
    IMachine *machine    = NULL;
2385
    vboxIID iid = VBOX_IID_INITIALIZER;
2386
    int gotAllABoutDef   = -1;
2387
    nsresult rc;
2388

2389 2390
    /* Flags checked by virDomainDefFormat */

2391
    if (VIR_ALLOC(def) < 0)
2392 2393
        goto cleanup;

2394
    vboxIIDFromUUID(&iid, dom->uuid);
2395
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
2396
    if (NS_SUCCEEDED(rc)) {
2397
        PRBool accessible = PR_FALSE;
2398

2399 2400
        machine->vtbl->GetAccessible(machine, &accessible);
        if (accessible) {
2401
            size_t i = 0;
2402 2403 2404
            PRBool PAEEnabled                   = PR_FALSE;
            PRBool ACPIEnabled                  = PR_FALSE;
            PRBool IOAPICEnabled                = PR_FALSE;
2405
            PRBool VRDxEnabled                  = PR_FALSE;
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
            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;
2417
#if VBOX_API_VERSION < 3001000
2418 2419 2420 2421 2422 2423 2424 2425
            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;
2426
#else  /* VBOX_API_VERSION >= 3001000 */
2427
            vboxArray mediumAttachments         = VBOX_ARRAY_INITIALIZER;
2428 2429
#endif /* VBOX_API_VERSION >= 3001000 */
#if VBOX_API_VERSION < 4000000
2430
            IVRDPServer *VRDxServer             = NULL;
2431
#else  /* VBOX_API_VERSION >= 4000000 */
2432
            IVRDEServer *VRDxServer             = NULL;
2433
#endif /* VBOX_API_VERSION >= 4000000 */
2434
            IAudioAdapter *audioAdapter         = NULL;
2435
#if VBOX_API_VERSION >= 4001000
2436
            PRUint32 chipsetType                = ChipsetType_Null;
2437
#endif /* VBOX_API_VERSION >= 4001000 */
2438
            ISystemProperties *systemProperties = NULL;
2439 2440


2441 2442 2443
            def->virtType = VIR_DOMAIN_VIRT_VBOX;
            def->id = dom->id;
            memcpy(def->uuid, dom->uuid, VIR_UUID_BUFLEN);
2444 2445
            if (VIR_STRDUP(def->name, dom->name) < 0)
                goto cleanup;
2446

2447
            machine->vtbl->GetMemorySize(machine, &memorySize);
2448
            def->mem.cur_balloon = memorySize * 1024;
2449

2450
#if VBOX_API_VERSION >= 4001000
2451
            machine->vtbl->GetChipsetType(machine, &chipsetType);
2452
#endif /* VBOX_API_VERSION >= 4001000 */
2453

2454 2455 2456 2457
            data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
            if (systemProperties) {
                systemProperties->vtbl->GetMaxGuestRAM(systemProperties, &maxMemorySize);
                systemProperties->vtbl->GetMaxBootPosition(systemProperties, &maxBootPosition);
2458
#if VBOX_API_VERSION < 4001000
2459
                systemProperties->vtbl->GetNetworkAdapterCount(systemProperties, &netAdpCnt);
2460
#else  /* VBOX_API_VERSION >= 4000000 */
2461
                systemProperties->vtbl->GetMaxNetworkAdapters(systemProperties, chipsetType, &netAdpCnt);
2462
#endif /* VBOX_API_VERSION >= 4000000 */
2463 2464 2465 2466 2467 2468 2469 2470 2471
                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
             */
2472 2473
            /* def->mem.max_balloon = maxMemorySize * 1024; */
            def->mem.max_balloon = memorySize * 1024;
2474 2475

            machine->vtbl->GetCPUCount(machine, &CPUCount);
E
Eric Blake 已提交
2476
            def->maxvcpus = def->vcpus = CPUCount;
2477 2478 2479

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

2480 2481
            if (VIR_STRDUP(def->os.type, "hvm") < 0)
                goto cleanup;
2482

2483
            def->os.arch = virArchFromHost();
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506

            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 已提交
2507
                    /* Can VirtualBox really boot from a shared folder? */
2508
                }
2509
            }
2510

2511
#if VBOX_API_VERSION < 3001000
2512
            machine->vtbl->GetPAEEnabled(machine, &PAEEnabled);
2513
#elif VBOX_API_VERSION == 3001000
2514
            machine->vtbl->GetCpuProperty(machine, CpuPropertyType_PAE, &PAEEnabled);
2515
#elif VBOX_API_VERSION >= 3002000
2516 2517
            machine->vtbl->GetCPUProperty(machine, CPUPropertyType_PAE, &PAEEnabled);
#endif
2518
            if (PAEEnabled)
J
Ján Tomko 已提交
2519
                def->features[VIR_DOMAIN_FEATURE_PAE] = VIR_TRISTATE_SWITCH_ON;
2520

2521 2522 2523
            machine->vtbl->GetBIOSSettings(machine, &bios);
            if (bios) {
                bios->vtbl->GetACPIEnabled(bios, &ACPIEnabled);
2524
                if (ACPIEnabled)
J
Ján Tomko 已提交
2525
                    def->features[VIR_DOMAIN_FEATURE_ACPI] = VIR_TRISTATE_SWITCH_ON;
2526

2527
                bios->vtbl->GetIOAPICEnabled(bios, &IOAPICEnabled);
2528
                if (IOAPICEnabled)
J
Ján Tomko 已提交
2529
                    def->features[VIR_DOMAIN_FEATURE_APIC] = VIR_TRISTATE_SWITCH_ON;
2530

2531 2532 2533 2534 2535
                VBOX_RELEASE(bios);
            }

            /* Currently VirtualBox always uses locatime
             * so locatime is always true here */
2536
            def->clock.offset = VIR_DOMAIN_CLOCK_OFFSET_LOCALTIME;
2537 2538 2539 2540 2541 2542 2543 2544

            /* 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 */
2545
                        PRUint32 VRAMSize          = 8;
2546 2547 2548 2549 2550 2551 2552
                        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);
2553
#if VBOX_API_VERSION >= 3001000
2554
                        machine->vtbl->GetAccelerate2DVideoEnabled(machine, &accelerate2DEnabled);
2555
#endif /* VBOX_API_VERSION >= 3001000 */
2556 2557

                        def->videos[0]->type            = VIR_DOMAIN_VIDEO_TYPE_VBOX;
2558
                        def->videos[0]->vram            = VRAMSize * 1024;
2559 2560 2561 2562
                        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;
2563 2564 2565
                        }
                    }
                }
2566
            }
2567

2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
            /* 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;
2579

2580
                def->ngraphics = 0;
2581

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

2586 2587 2588
                if (valueTypeUtf16) {
                    VBOX_UTF16_TO_UTF8(valueTypeUtf16, &valueTypeUtf8);
                    VBOX_UTF16_FREE(valueTypeUtf16);
2589

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

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

2599 2600 2601
                        if (valueDisplayUtf16) {
                            VBOX_UTF16_TO_UTF8(valueDisplayUtf16, &valueDisplayUtf8);
                            VBOX_UTF16_FREE(valueDisplayUtf16);
2602

J
John Ferlan 已提交
2603
                            if (strlen(valueDisplayUtf8) <= 0)
2604
                                VBOX_UTF8_FREE(valueDisplayUtf8);
2605
                        }
2606

2607 2608
                        if (STREQ(valueTypeUtf8, "sdl")) {
                            sdlPresent = 1;
2609
                            if (VIR_STRDUP(sdlDisplay, valueDisplayUtf8) < 0) {
2610 2611 2612 2613 2614 2615
                                /* 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++;
2616
                        }
2617

2618 2619
                        if (STREQ(valueTypeUtf8, "gui")) {
                            guiPresent = 1;
2620
                            if (VIR_STRDUP(guiDisplay, valueDisplayUtf8) < 0) {
2621
                                /* just don't go to cleanup yet as it is ok to have
2622 2623
                                 * guiDisplay as NULL and we check it below if it
                                 * exist and then only use it there
2624
                                 */
2625
                            }
2626 2627
                            totalPresent++;
                        }
J
John Ferlan 已提交
2628
                        VBOX_UTF8_FREE(valueDisplayUtf8);
2629 2630
                    }

2631 2632
                    if (STREQ(valueTypeUtf8, "vrdp"))
                        vrdpPresent = 1;
2633

2634 2635
                    VBOX_UTF8_FREE(valueTypeUtf8);
                }
2636

2637 2638 2639 2640 2641 2642 2643
                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++;
                    }
2644

2645 2646 2647 2648 2649 2650 2651 2652
                    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) {
2653
                        const char *tmp;
2654
                        def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP;
2655
                        tmp = virGetEnvBlockSUID("DISPLAY");
2656 2657 2658 2659
                        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
                             */
2660 2661 2662 2663 2664
                        }
                        totalPresent++;
                        def->ngraphics++;
                    }
                }
2665

2666
#if VBOX_API_VERSION < 4000000
2667
                machine->vtbl->GetVRDPServer(machine, &VRDxServer);
2668
#else  /* VBOX_API_VERSION >= 4000000 */
2669
                machine->vtbl->GetVRDEServer(machine, &VRDxServer);
2670
#endif /* VBOX_API_VERSION >= 4000000 */
2671 2672 2673
                if (VRDxServer) {
                    VRDxServer->vtbl->GetEnabled(VRDxServer, &VRDxEnabled);
                    if (VRDxEnabled) {
2674 2675 2676 2677 2678 2679 2680 2681 2682

                        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;
2683
#if VBOX_API_VERSION < 3001000
2684
                            PRUint32 VRDPport = 0;
2685
                            VRDxServer->vtbl->GetPort(VRDxServer, &VRDPport);
2686 2687
                            if (VRDPport) {
                                def->graphics[def->ngraphics]->data.rdp.port = VRDPport;
2688 2689 2690
                            } else {
                                def->graphics[def->ngraphics]->data.rdp.autoport = true;
                            }
2691
#elif VBOX_API_VERSION < 4000000 /* 3001000 <= VBOX_API_VERSION < 4000000 */
2692
                            PRUnichar *VRDPport = NULL;
2693
                            VRDxServer->vtbl->GetPorts(VRDxServer, &VRDPport);
2694 2695 2696 2697
                            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);
2698 2699 2700
                            } else {
                                def->graphics[def->ngraphics]->data.rdp.autoport = true;
                            }
2701
#else /* VBOX_API_VERSION >= 4000000 */
2702 2703 2704 2705 2706 2707 2708 2709 2710
                            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);
2711
                            } else {
2712
                                def->graphics[def->ngraphics]->data.rdp.autoport = true;
2713
                            }
2714
#endif /* VBOX_API_VERSION >= 4000000 */
2715

2716
                            def->graphics[def->ngraphics]->type = VIR_DOMAIN_GRAPHICS_TYPE_RDP;
2717

2718
#if VBOX_API_VERSION >= 4000000
2719 2720 2721 2722
                            PRUnichar *VRDENetAddressKey = NULL;
                            VBOX_UTF8_TO_UTF16("TCP/Address", &VRDENetAddressKey);
                            VRDxServer->vtbl->GetVRDEProperty(VRDxServer, VRDENetAddressKey, &netAddressUtf16);
                            VBOX_UTF16_FREE(VRDENetAddressKey);
2723
#else /* VBOX_API_VERSION < 4000000 */
2724
                            VRDxServer->vtbl->GetNetAddress(VRDxServer, &netAddressUtf16);
2725
#endif /* VBOX_API_VERSION < 4000000 */
2726 2727 2728
                            if (netAddressUtf16) {
                                VBOX_UTF16_TO_UTF8(netAddressUtf16, &netAddressUtf8);
                                if (STRNEQ(netAddressUtf8, ""))
2729 2730
                                    virDomainGraphicsListenSetAddress(def->graphics[def->ngraphics], 0,
                                                                      netAddressUtf8, -1, true);
2731 2732 2733
                                VBOX_UTF16_FREE(netAddressUtf16);
                                VBOX_UTF8_FREE(netAddressUtf8);
                            }
2734

2735
                            VRDxServer->vtbl->GetAllowMultiConnection(VRDxServer, &allowMultiConnection);
2736
                            if (allowMultiConnection) {
2737
                                def->graphics[def->ngraphics]->data.rdp.multiUser = true;
2738
                            }
2739

2740
                            VRDxServer->vtbl->GetReuseSingleConnection(VRDxServer, &reuseSingleConnection);
2741
                            if (reuseSingleConnection) {
2742
                                def->graphics[def->ngraphics]->data.rdp.replaceUser = true;
2743
                            }
2744

2745
                            def->ngraphics++;
2746
                        } else
2747
                            virReportOOMError();
2748
                    }
2749
                    VBOX_RELEASE(VRDxServer);
2750
                }
2751
            }
2752

2753
#if VBOX_API_VERSION < 3001000
2754 2755
            /* dump IDE hdds if present */
            VBOX_UTF8_TO_UTF16(hddBus, &hddBusUtf16);
2756

2757 2758 2759 2760
            def->ndisks = 0;
            machine->vtbl->GetHardDisk(machine, hddBusUtf16, 0, 0,  &hardDiskPM);
            if (hardDiskPM)
                def->ndisks++;
2761

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

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

2770 2771 2772 2773
            VBOX_UTF16_FREE(hddBusUtf16);

            if ((def->ndisks > 0) && (VIR_ALLOC_N(def->disks, def->ndisks) >= 0)) {
                for (i = 0; i < def->ndisks; i++) {
2774
                    if ((def->disks[i] = virDomainDiskDefNew())) {
2775 2776
                        def->disks[i]->device = VIR_DOMAIN_DISK_DEVICE_DISK;
                        def->disks[i]->bus = VIR_DOMAIN_DISK_BUS_IDE;
2777
                        virDomainDiskSetType(def->disks[i],
E
Eric Blake 已提交
2778
                                             VIR_STORAGE_TYPE_FILE);
2779
                    }
2780
                }
2781
            }
2782

2783 2784 2785 2786
            if (hardDiskPM) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2787

2788 2789
                hardDiskPM->vtbl->imedium.GetLocation((IMedium *)hardDiskPM, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2790

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

2793
                if (hddType == HardDiskType_Immutable)
2794
                    def->disks[hddNum]->src->readonly = true;
2795 2796
                ignore_value(virDomainDiskSetSource(def->disks[hddNum],
                                                    hddlocation));
2797
                ignore_value(VIR_STRDUP(def->disks[hddNum]->dst, "hda"));
2798
                hddNum++;
2799

2800 2801 2802 2803
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPM);
            }
2804

2805 2806 2807 2808
            if (hardDiskPS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2809

2810 2811
                hardDiskPS->vtbl->imedium.GetLocation((IMedium *)hardDiskPS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2812

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

2815
                if (hddType == HardDiskType_Immutable)
2816
                    def->disks[hddNum]->src->readonly = true;
2817 2818
                ignore_value(virDomainDiskSetSource(def->disks[hddNum],
                                                    hddlocation));
2819
                ignore_value(VIR_STRDUP(def->disks[hddNum]->dst, "hdb"));
2820
                hddNum++;
2821

2822 2823 2824 2825
                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskPS);
            }
2826

2827 2828 2829 2830
            if (hardDiskSS) {
                PRUnichar *hddlocationUtf16 = NULL;
                char *hddlocation           = NULL;
                PRUint32 hddType            = HardDiskType_Normal;
2831

2832 2833
                hardDiskSS->vtbl->imedium.GetLocation((IMedium *)hardDiskSS, &hddlocationUtf16);
                VBOX_UTF16_TO_UTF8(hddlocationUtf16, &hddlocation);
2834

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

2837
                if (hddType == HardDiskType_Immutable)
2838
                    def->disks[hddNum]->src->readonly = true;
2839 2840
                ignore_value(virDomainDiskSetSource(def->disks[hddNum],
                                                    hddlocation));
J
Ján Tomko 已提交
2841 2842
                ignore_value(VIR_STRDUP(def->disks[hddNum]->dst, "hdd"));
                hddNum++;
2843 2844 2845 2846 2847

                VBOX_UTF8_FREE(hddlocation);
                VBOX_UTF16_FREE(hddlocationUtf16);
                VBOX_MEDIUM_RELEASE(hardDiskSS);
            }
2848
#else  /* VBOX_API_VERSION >= 3001000 */
2849 2850 2851 2852 2853 2854 2855
            /* dump IDE hdds if present */

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

            /* get the number of attachments */
2859 2860
            for (i = 0; i < mediumAttachments.count; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2861 2862 2863 2864 2865 2866 2867
                if (imediumattach) {
                    IMedium *medium = NULL;

                    imediumattach->vtbl->GetMedium(imediumattach, &medium);
                    if (medium) {
                        def->ndisks++;
                        VBOX_RELEASE(medium);
2868 2869
                    }
                }
2870
            }
2871

2872 2873 2874
            /* Allocate mem, if fails return error */
            if (VIR_ALLOC_N(def->disks, def->ndisks) >= 0) {
                for (i = 0; i < def->ndisks; i++) {
2875 2876
                    virDomainDiskDefPtr disk = virDomainDiskDefNew();
                    if (!disk) {
2877 2878
                        error = true;
                        break;
2879
                    }
2880
                    def->disks[i] = disk;
2881
                }
2882 2883 2884 2885 2886 2887 2888 2889
            } else {
                error = true;
            }

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

            /* get the attachment details here */
2890 2891
            for (i = 0; i < mediumAttachments.count && diskCount < def->ndisks && !error; i++) {
                IMediumAttachment *imediumattach = mediumAttachments.items[i];
2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
                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;
                }
2925

2926 2927 2928
                medium->vtbl->GetLocation(medium, &mediumLocUtf16);
                VBOX_UTF16_TO_UTF8(mediumLocUtf16, &mediumLocUtf8);
                VBOX_UTF16_FREE(mediumLocUtf16);
2929 2930
                ignore_value(virDomainDiskSetSource(def->disks[diskCount],
                                                    mediumLocUtf8));
2931 2932
                VBOX_UTF8_FREE(mediumLocUtf8);

2933
                if (!virDomainDiskGetSource(def->disks[diskCount])) {
2934 2935 2936 2937 2938
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2939

2940 2941 2942 2943 2944 2945 2946 2947 2948 2949
                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;
                }
2950

2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
                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);
2961
                def->disks[diskCount]->dst = vboxGenerateMediumName(storageBus,
2962 2963 2964 2965 2966 2967
                                                                    deviceInst,
                                                                    devicePort,
                                                                    deviceSlot,
                                                                    maxPortPerInst,
                                                                    maxSlotPerPort);
                if (!def->disks[diskCount]->dst) {
2968 2969 2970 2971
                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                   _("Could not generate medium name for the disk "
                                     "at: controller instance:%u, port:%d, slot:%d"),
                                   deviceInst, devicePort, deviceSlot);
2972 2973 2974 2975 2976
                    VBOX_RELEASE(medium);
                    VBOX_RELEASE(storageController);
                    error = true;
                    break;
                }
2977

2978 2979
                medium->vtbl->GetReadOnly(medium, &readOnly);
                if (readOnly == PR_TRUE)
2980
                    def->disks[diskCount]->src->readonly = true;
2981

2982
                virDomainDiskSetType(def->disks[diskCount],
E
Eric Blake 已提交
2983
                                     VIR_STORAGE_TYPE_FILE);
2984

2985 2986 2987 2988
                VBOX_RELEASE(medium);
                VBOX_RELEASE(storageController);
                diskCount++;
            }
2989

2990
            vboxArrayRelease(&mediumAttachments);
2991

2992 2993 2994 2995 2996 2997 2998 2999
            /* cleanup on error */
            if (error) {
                for (i = 0; i < def->ndisks; i++) {
                    VIR_FREE(def->disks[i]);
                }
                VIR_FREE(def->disks);
                def->ndisks = 0;
            }
3000

3001
#endif /* VBOX_API_VERSION >= 3001000 */
3002

M
Matthias Bolte 已提交
3003 3004 3005 3006 3007 3008 3009 3010 3011
            /* shared folders */
            vboxArray sharedFolders = VBOX_ARRAY_INITIALIZER;

            def->nfss = 0;

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

            if (sharedFolders.count > 0) {
3012
                if (VIR_ALLOC_N(def->fss, sharedFolders.count) < 0)
M
Matthias Bolte 已提交
3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
                    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;

3023
                    if (VIR_ALLOC(def->fss[i]) < 0)
M
Matthias Bolte 已提交
3024 3025 3026 3027 3028 3029
                        goto sharedFoldersCleanup;

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

                    sharedFolder->vtbl->GetHostPath(sharedFolder, &hostPathUtf16);
                    VBOX_UTF16_TO_UTF8(hostPathUtf16, &hostPath);
3030 3031 3032
                    if (VIR_STRDUP(def->fss[i]->src, hostPath) < 0) {
                        VBOX_UTF8_FREE(hostPath);
                        VBOX_UTF16_FREE(hostPathUtf16);
M
Matthias Bolte 已提交
3033 3034
                        goto sharedFoldersCleanup;
                    }
3035 3036
                    VBOX_UTF8_FREE(hostPath);
                    VBOX_UTF16_FREE(hostPathUtf16);
M
Matthias Bolte 已提交
3037 3038 3039

                    sharedFolder->vtbl->GetName(sharedFolder, &nameUtf16);
                    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
3040 3041 3042
                    if (VIR_STRDUP(def->fss[i]->dst, name) < 0) {
                        VBOX_UTF8_FREE(name);
                        VBOX_UTF16_FREE(nameUtf16);
M
Matthias Bolte 已提交
3043 3044
                        goto sharedFoldersCleanup;
                    }
3045 3046
                    VBOX_UTF8_FREE(name);
                    VBOX_UTF16_FREE(nameUtf16);
M
Matthias Bolte 已提交
3047 3048 3049 3050 3051 3052 3053 3054

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

                    ++def->nfss;
                }
            }

3055
 sharedFoldersCleanup:
M
Matthias Bolte 已提交
3056 3057
            vboxArrayRelease(&sharedFolders);

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

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

3068 3069 3070 3071
                    adapter->vtbl->GetEnabled(adapter, &enabled);
                    if (enabled) {
                        def->nnets++;
                    }
3072

3073 3074 3075
                    VBOX_RELEASE(adapter);
                }
            }
3076

3077 3078 3079
            /* 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++) {
3080
                    ignore_value(VIR_ALLOC(def->nets[i]));
3081 3082
                }
            }
3083

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

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

3092 3093 3094 3095 3096 3097 3098
                    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};
3099

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

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

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

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

3111
#if VBOX_API_VERSION < 4001000
3112
                            adapter->vtbl->GetHostInterface(adapter, &hostIntUtf16);
3113
#else /* VBOX_API_VERSION >= 4001000 */
3114
                            adapter->vtbl->GetBridgedInterface(adapter, &hostIntUtf16);
3115
#endif /* VBOX_API_VERSION >= 4001000 */
3116

3117
                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
3118
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.bridge.brname, hostInt));
3119

3120 3121
                            VBOX_UTF8_FREE(hostInt);
                            VBOX_UTF16_FREE(hostIntUtf16);
3122

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

3127 3128 3129 3130 3131
                            def->nets[netAdpIncCnt]->type = VIR_DOMAIN_NET_TYPE_INTERNAL;

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

                            VBOX_UTF16_TO_UTF8(intNetUtf16, &intNet);
3132
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.internal.name, intNet));
3133 3134 3135 3136 3137 3138 3139 3140 3141 3142

                            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;

3143
#if VBOX_API_VERSION < 4001000
3144
                            adapter->vtbl->GetHostInterface(adapter, &hostIntUtf16);
3145
#else /* VBOX_API_VERSION >= 4001000 */
3146
                            adapter->vtbl->GetHostOnlyInterface(adapter, &hostIntUtf16);
3147
#endif /* VBOX_API_VERSION >= 4001000 */
3148 3149

                            VBOX_UTF16_TO_UTF8(hostIntUtf16, &hostInt);
3150
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->data.network.name, hostInt));
3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163

                            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) {
3164
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "Am79C970A"));
3165
                        } else if (adapterType == NetworkAdapterType_Am79C973) {
3166
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "Am79C973"));
3167
                        } else if (adapterType == NetworkAdapterType_I82540EM) {
3168
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82540EM"));
3169
                        } else if (adapterType == NetworkAdapterType_I82545EM) {
3170
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82545EM"));
3171
                        } else if (adapterType == NetworkAdapterType_I82543GC) {
3172
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "82543GC"));
3173
#if VBOX_API_VERSION >= 3001000
3174
                        } else if (adapterType == NetworkAdapterType_Virtio) {
3175
                            ignore_value(VIR_STRDUP(def->nets[netAdpIncCnt]->model, "virtio"));
3176
#endif /* VBOX_API_VERSION >= 3001000 */
3177 3178
                        }

3179 3180 3181 3182 3183 3184 3185 3186 3187
                        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 ... */
3188
                        if (virMacAddrParse(macaddr, &def->nets[netAdpIncCnt]->mac) < 0)
3189 3190 3191 3192 3193 3194
                        {}

                        netAdpIncCnt++;

                        VBOX_UTF16_FREE(MACAddressUtf16);
                        VBOX_UTF8_FREE(MACAddress);
3195
                    }
3196 3197

                    VBOX_RELEASE(adapter);
3198
                }
3199
            }
3200

3201
            /* dump sound card if active */
3202

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

3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233
            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);
            }
3234

3235
#if VBOX_API_VERSION < 3001000
3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
            /* 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) {
3255
                            if ((def->disks[def->ndisks - 1] = virDomainDiskDefNew())) {
3256 3257
                                def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_CDROM;
                                def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_IDE;
3258
                                virDomainDiskSetType(def->disks[def->ndisks - 1],
E
Eric Blake 已提交
3259
                                                     VIR_STORAGE_TYPE_FILE);
3260
                                def->disks[def->ndisks - 1]->src->readonly = true;
3261
                                ignore_value(virDomainDiskSetSource(def->disks[def->ndisks - 1], location));
3262 3263
                                ignore_value(VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "hdc"));
                                def->ndisks--;
3264
                            } else {
3265
                                def->ndisks--;
3266 3267
                            }
                        } else {
3268
                            def->ndisks--;
3269
                        }
3270 3271 3272 3273

                        VBOX_UTF8_FREE(location);
                        VBOX_UTF16_FREE(locationUtf16);
                        VBOX_MEDIUM_RELEASE(dvdImage);
3274 3275
                    }
                }
3276 3277
                VBOX_RELEASE(dvdDrive);
            }
3278

3279 3280 3281 3282 3283 3284 3285
            /* 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) {
3286 3287
                    PRUint32 state = DriveState_Null;

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

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

3297 3298
                            floppyImage->vtbl->imedium.GetLocation((IMedium *)floppyImage, &locationUtf16);
                            VBOX_UTF16_TO_UTF8(locationUtf16, &location);
3299 3300 3301

                            def->ndisks++;
                            if (VIR_REALLOC_N(def->disks, def->ndisks) >= 0) {
3302
                                if ((def->disks[def->ndisks - 1] = virDomainDiskDefNew())) {
3303 3304
                                    def->disks[def->ndisks - 1]->device = VIR_DOMAIN_DISK_DEVICE_FLOPPY;
                                    def->disks[def->ndisks - 1]->bus = VIR_DOMAIN_DISK_BUS_FDC;
3305
                                    virDomainDiskSetType(def->disks[def->ndisks - 1],
E
Eric Blake 已提交
3306
                                                         VIR_STORAGE_TYPE_FILE);
3307
                                    def->disks[def->ndisks - 1]->src->readonly = false;
3308
                                    ignore_value(virDomainDiskSetSource(def->disks[def->ndisks - 1], location));
3309 3310
                                    ignore_value(VIR_STRDUP(def->disks[def->ndisks - 1]->dst, "fda"));
                                    def->ndisks--;
3311 3312 3313 3314 3315 3316 3317
                                } else {
                                    def->ndisks--;
                                }
                            } else {
                                def->ndisks--;
                            }

3318 3319 3320
                            VBOX_UTF8_FREE(location);
                            VBOX_UTF16_FREE(locationUtf16);
                            VBOX_MEDIUM_RELEASE(floppyImage);
3321 3322 3323 3324
                        }
                    }
                }

3325 3326
                VBOX_RELEASE(floppyDrive);
            }
3327 3328
#else  /* VBOX_API_VERSION >= 3001000 */
#endif /* VBOX_API_VERSION >= 3001000 */
3329 3330 3331 3332 3333 3334 3335 3336 3337

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

3340
                    serialPort->vtbl->GetEnabled(serialPort, &enabled);
3341
                    if (enabled) {
3342
                        def->nserials++;
3343 3344
                    }

3345
                    VBOX_RELEASE(serialPort);
3346
                }
3347
            }
3348

3349 3350 3351
            /* 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++) {
3352
                    ignore_value(VIR_ALLOC(def->serials[i]));
3353 3354
                }
            }
3355

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

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

3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
                    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) {
3376
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_PIPE;
3377
                        } else if (hostMode == PortMode_HostDevice) {
3378
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_DEV;
3379
#if VBOX_API_VERSION >= 3000000
3380
                        } else if (hostMode == PortMode_RawFile) {
3381
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
3382
#endif /* VBOX_API_VERSION >= 3000000 */
3383
                        } else {
3384
                            def->serials[serialPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_NULL;
3385
                        }
3386

3387
                        def->serials[serialPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_SERIAL;
3388

3389 3390 3391 3392 3393 3394 3395
                        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;
                        }
3396

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

3399 3400
                        if (pathUtf16) {
                            VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3401
                            ignore_value(VIR_STRDUP(def->serials[serialPortIncCount]->source.data.file.path, path));
3402 3403
                        }

3404 3405 3406 3407
                        serialPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
3408 3409
                    }

3410 3411 3412
                    VBOX_RELEASE(serialPort);
                }
            }
3413

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

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

3424 3425 3426
                    parallelPort->vtbl->GetEnabled(parallelPort, &enabled);
                    if (enabled) {
                        def->nparallels++;
3427
                    }
3428 3429

                    VBOX_RELEASE(parallelPort);
3430
                }
3431
            }
3432

3433 3434 3435
            /* 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++) {
3436
                    ignore_value(VIR_ALLOC(def->parallels[i]));
3437
                }
3438
            }
3439

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

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

3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
                    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;
                        }
3465

3466
                        def->parallels[parallelPortIncCount]->source.type = VIR_DOMAIN_CHR_TYPE_FILE;
3467
                        def->parallels[parallelPortIncCount]->deviceType = VIR_DOMAIN_CHR_DEVICE_TYPE_PARALLEL;
3468

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

3471
                        VBOX_UTF16_TO_UTF8(pathUtf16, &path);
3472
                        ignore_value(VIR_STRDUP(def->parallels[parallelPortIncCount]->source.data.file.path, path));
3473

3474 3475 3476 3477
                        parallelPortIncCount++;

                        VBOX_UTF16_FREE(pathUtf16);
                        VBOX_UTF8_FREE(path);
3478
                    }
3479 3480

                    VBOX_RELEASE(parallelPort);
3481
                }
3482
            }
3483

3484
            /* dump USB devices/filters if active */
3485
            vboxHostDeviceGetXMLDesc(data, def, machine);
3486 3487 3488 3489 3490

            /* all done so set gotAllABoutDef and pass def to virDomainDefFormat
             * to generate XML for it
             */
            gotAllABoutDef = 0;
3491
        }
3492 3493
        VBOX_RELEASE(machine);
        machine = NULL;
3494 3495 3496
    }

    if (gotAllABoutDef == 0)
3497
        ret = virDomainDefFormat(def, flags);
3498

3499
 cleanup:
3500
    vboxIIDUnalloc(&iid);
3501 3502 3503 3504
    virDomainDefFree(def);
    return ret;
}

3505
static int vboxConnectListDefinedDomains(virConnectPtr conn, char ** const names, int maxnames) {
3506
    VBOX_OBJECT_CHECK(conn, int, -1);
3507
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3508 3509 3510
    char *machineName    = NULL;
    PRUnichar *machineNameUtf16 = NULL;
    PRUint32 state;
3511
    nsresult rc;
3512
    size_t i, j;
3513

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

3522 3523
    memset(names, 0, sizeof(names[i]) * maxnames);

3524 3525 3526
    ret = 0;
    for (i = 0, j = 0; (i < machines.count) && (j < maxnames); i++) {
        IMachine *machine = machines.items[i];
3527 3528 3529 3530 3531 3532

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
3533 3534
                if ((state < MachineState_FirstOnline) ||
                    (state > MachineState_LastOnline)) {
3535 3536
                    machine->vtbl->GetName(machine, &machineNameUtf16);
                    VBOX_UTF16_TO_UTF8(machineNameUtf16, &machineName);
3537 3538 3539
                    if (VIR_STRDUP(names[j], machineName) < 0) {
                        VBOX_UTF16_FREE(machineNameUtf16);
                        VBOX_UTF8_FREE(machineName);
3540
                        for (j = 0; j < maxnames; j++)
3541 3542 3543
                            VIR_FREE(names[j]);
                        ret = -1;
                        goto cleanup;
3544
                    }
3545 3546
                    VBOX_UTF16_FREE(machineNameUtf16);
                    VBOX_UTF8_FREE(machineName);
3547
                    j++;
3548
                    ret++;
3549 3550 3551 3552 3553
                }
            }
        }
    }

3554
 cleanup:
3555
    vboxArrayRelease(&machines);
3556 3557 3558
    return ret;
}

3559 3560
static int vboxConnectNumOfDefinedDomains(virConnectPtr conn)
{
3561
    VBOX_OBJECT_CHECK(conn, int, -1);
3562
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3563
    PRUint32 state       = MachineState_Null;
3564
    nsresult rc;
3565
    size_t i;
3566

3567
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3568
    if (NS_FAILED(rc)) {
3569 3570 3571
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get number of Defined Domains, rc=%08x"),
                       (unsigned)rc);
3572 3573
        goto cleanup;
    }
3574

3575 3576 3577
    ret = 0;
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3578 3579 3580 3581 3582 3583

        if (machine) {
            PRBool isAccessible = PR_FALSE;
            machine->vtbl->GetAccessible(machine, &isAccessible);
            if (isAccessible) {
                machine->vtbl->GetState(machine, &state);
3584 3585
                if ((state < MachineState_FirstOnline) ||
                    (state > MachineState_LastOnline)) {
3586
                    ret++;
3587 3588 3589 3590 3591
                }
            }
        }
    }

3592
 cleanup:
3593
    vboxArrayRelease(&machines);
3594 3595 3596
    return ret;
}

E
Eric Blake 已提交
3597 3598

static int
3599
vboxStartMachine(virDomainPtr dom, int maxDomID, IMachine *machine,
3600
                 vboxIID *iid ATTRIBUTE_UNUSED /* >= 4.0 */)
E
Eric Blake 已提交
3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626
{
    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);

3627
        if (STREQ(valueTypeUtf8, "sdl") || STREQ(valueTypeUtf8, "gui")) {
E
Eric Blake 已提交
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637

            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 已提交
3638
                if (strlen(valueDisplayUtf8) <= 0)
E
Eric Blake 已提交
3639 3640 3641 3642 3643
                    VBOX_UTF8_FREE(valueDisplayUtf8);
            }

            if (STREQ(valueTypeUtf8, "sdl")) {
                sdlPresent = 1;
3644 3645 3646 3647 3648
                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 已提交
3649 3650 3651 3652 3653
                }
            }

            if (STREQ(valueTypeUtf8, "gui")) {
                guiPresent = 1;
3654 3655 3656 3657 3658
                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 已提交
3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
                }
            }
        }

        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 已提交
3679
    VBOX_UTF8_FREE(valueDisplayUtf8);
E
Eric Blake 已提交
3680 3681 3682

    if (guiPresent) {
        if (guiDisplay) {
E
Eric Blake 已提交
3683
            char *displayutf8;
3684
            if (virAsprintf(&displayutf8, "DISPLAY=%s", guiDisplay) >= 0) {
E
Eric Blake 已提交
3685 3686 3687
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3688 3689 3690 3691 3692 3693 3694 3695
            VIR_FREE(guiDisplay);
        }

        VBOX_UTF8_TO_UTF16("gui", &sessionType);
    }

    if (sdlPresent) {
        if (sdlDisplay) {
E
Eric Blake 已提交
3696
            char *displayutf8;
3697
            if (virAsprintf(&displayutf8, "DISPLAY=%s", sdlDisplay) >= 0) {
E
Eric Blake 已提交
3698 3699 3700
                VBOX_UTF8_TO_UTF16(displayutf8, &env);
                VIR_FREE(displayutf8);
            }
E
Eric Blake 已提交
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
            VIR_FREE(sdlDisplay);
        }

        VBOX_UTF8_TO_UTF16("sdl", &sessionType);
    }

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

3711
#if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
3712 3713
    rc = data->vboxObj->vtbl->OpenRemoteSession(data->vboxObj,
                                                data->vboxSession,
3714
                                                iid->value,
E
Eric Blake 已提交
3715 3716
                                                sessionType,
                                                env,
3717
                                                &progress);
3718
#else /* VBOX_API_VERSION >= 4000000 */
3719 3720
    rc = machine->vtbl->LaunchVMProcess(machine, data->vboxSession,
                                        sessionType, env, &progress);
3721
#endif /* VBOX_API_VERSION >= 4000000 */
3722

E
Eric Blake 已提交
3723
    if (NS_FAILED(rc)) {
3724 3725
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("OpenRemoteSession/LaunchVMProcess failed, domain can't be started"));
E
Eric Blake 已提交
3726 3727 3728
        ret = -1;
    } else {
        PRBool completed = 0;
3729
#if VBOX_API_VERSION == 2002000
E
Eric Blake 已提交
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
        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 */
3746
            dom->id = maxDomID + 1;
E
Eric Blake 已提交
3747 3748 3749 3750 3751 3752
            ret = 0;
        }
    }

    VBOX_RELEASE(progress);

3753
    VBOX_SESSION_CLOSE();
E
Eric Blake 已提交
3754 3755 3756 3757 3758 3759 3760

    VBOX_UTF16_FREE(env);
    VBOX_UTF16_FREE(sessionType);

    return ret;
}

3761 3762
static int vboxDomainCreateWithFlags(virDomainPtr dom, unsigned int flags)
{
3763
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
3764
    vboxArray machines = VBOX_ARRAY_INITIALIZER;
3765
    unsigned char uuid[VIR_UUID_BUFLEN] = {0};
3766
    nsresult rc;
3767
    size_t i = 0;
3768

3769 3770
    virCheckFlags(0, -1);

3771
    if (!dom->name) {
3772 3773
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Error while reading the domain name"));
3774 3775 3776
        goto cleanup;
    }

3777
    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
3778
    if (NS_FAILED(rc)) {
3779 3780
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of machines, rc=%08x"), (unsigned)rc);
3781 3782
        goto cleanup;
    }
3783

3784 3785
    for (i = 0; i < machines.count; ++i) {
        IMachine *machine = machines.items[i];
3786
        PRBool isAccessible = PR_FALSE;
3787

3788 3789
        if (!machine)
            continue;
3790

3791 3792
        machine->vtbl->GetAccessible(machine, &isAccessible);
        if (isAccessible) {
3793
            vboxIID iid = VBOX_IID_INITIALIZER;
3794

3795 3796
            rc = machine->vtbl->GetId(machine, &iid.value);
            if (NS_FAILED(rc))
3797
                continue;
3798
            vboxIIDToUUID(&iid, uuid);
3799

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

3804 3805 3806
                if ((state == MachineState_PoweredOff) ||
                    (state == MachineState_Saved) ||
                    (state == MachineState_Aborted)) {
3807
                    ret = vboxStartMachine(dom, i, machine, &iid);
3808
                } else {
3809
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
3810 3811 3812
                                   _("machine is not in "
                                     "poweroff|saved|aborted state, so "
                                     "couldn't start it"));
3813
                    ret = -1;
3814 3815
                }
            }
3816
            vboxIIDUnalloc(&iid);
3817 3818
            if (ret != -1)
                break;
3819 3820 3821
        }
    }

3822
    /* Do the cleanup and take care you dont leak any memory */
3823
    vboxArrayRelease(&machines);
3824

3825
 cleanup:
3826 3827 3828
    return ret;
}

3829 3830
static int vboxDomainCreate(virDomainPtr dom)
{
3831 3832 3833
    return vboxDomainCreateWithFlags(dom, 0);
}

E
Eric Blake 已提交
3834 3835 3836 3837 3838 3839
static void
vboxSetBootDeviceOrder(virDomainDefPtr def, vboxGlobalData *data,
                       IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 maxBootPosition            = 0;
3840
    size_t i = 0;
3841

3842
    VIR_DEBUG("def->os.type             %s", def->os.type);
3843
    VIR_DEBUG("def->os.arch             %s", virArchToString(def->os.arch));
3844
    VIR_DEBUG("def->os.machine          %s", def->os.machine);
3845
    VIR_DEBUG("def->os.nBootDevs        %zu", def->os.nBootDevs);
3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
    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);
3858

E
Eric Blake 已提交
3859 3860 3861 3862 3863 3864
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetMaxBootPosition(systemProperties,
                                                   &maxBootPosition);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
3865
    }
3866

E
Eric Blake 已提交
3867 3868 3869
    /* Clear the defaults first */
    for (i = 0; i < maxBootPosition; i++) {
        machine->vtbl->SetBootOrder(machine, i+1, DeviceType_Null);
3870
    }
3871

E
Eric Blake 已提交
3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882
    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;
3883
        }
E
Eric Blake 已提交
3884
        machine->vtbl->SetBootOrder(machine, i+1, device);
3885
    }
E
Eric Blake 已提交
3886
}
3887

E
Eric Blake 已提交
3888 3889 3890
static void
vboxAttachDrives(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
3891
    size_t i;
E
Eric Blake 已提交
3892
    nsresult rc;
3893

3894
#if VBOX_API_VERSION < 3001000
E
Eric Blake 已提交
3895 3896 3897 3898
    if (def->ndisks == 0)
        return;

    for (i = 0; i < def->ndisks; i++) {
3899 3900 3901 3902 3903
        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);
3904 3905
        VIR_DEBUG("disk(%zu) device:     %d", i, def->disks[i]->device);
        VIR_DEBUG("disk(%zu) bus:        %d", i, def->disks[i]->bus);
3906
        VIR_DEBUG("disk(%zu) src:        %s", i, src);
3907
        VIR_DEBUG("disk(%zu) dst:        %s", i, def->disks[i]->dst);
3908 3909
        VIR_DEBUG("disk(%zu) driverName: %s", i,
                  virDomainDiskGetDriver(def->disks[i]));
3910
        VIR_DEBUG("disk(%zu) driverType: %s", i,
3911
                  virStorageFileFormatTypeToString(format));
3912
        VIR_DEBUG("disk(%zu) cachemode:  %d", i, def->disks[i]->cachemode);
3913
        VIR_DEBUG("disk(%zu) readonly:   %s", i, (def->disks[i]->src->readonly
E
Eric Blake 已提交
3914
                                             ? "True" : "False"));
3915
        VIR_DEBUG("disk(%zu) shared:     %s", i, (def->disks[i]->src->shared
E
Eric Blake 已提交
3916 3917 3918
                                             ? "True" : "False"));

        if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
E
Eric Blake 已提交
3919
            if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
3920 3921 3922 3923 3924 3925 3926
                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
                 */
3927

E
Eric Blake 已提交
3928 3929 3930 3931
                machine->vtbl->GetDVDDrive(machine, &dvdDrive);
                if (dvdDrive) {
                    IDVDImage *dvdImage          = NULL;
                    PRUnichar *dvdfileUtf16      = NULL;
3932 3933
                    vboxIID dvduuid = VBOX_IID_INITIALIZER;
                    vboxIID dvdemptyuuid = VBOX_IID_INITIALIZER;
3934

3935
                    VBOX_UTF8_TO_UTF16(src, &dvdfileUtf16);
3936

E
Eric Blake 已提交
3937 3938 3939 3940 3941
                    data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                      dvdfileUtf16, &dvdImage);
                    if (!dvdImage) {
                        data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                          dvdfileUtf16,
3942
                                                          dvdemptyuuid.value,
E
Eric Blake 已提交
3943 3944 3945 3946
                                                          &dvdImage);
                    }
                    if (dvdImage) {
                        rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage,
3947
                                                           &dvduuid.value);
E
Eric Blake 已提交
3948
                        if (NS_FAILED(rc)) {
3949 3950 3951
                            virReportError(VIR_ERR_INTERNAL_ERROR,
                                           _("can't get the uuid of the file to "
                                             "be attached to cdrom: %s, rc=%08x"),
3952
                                           src, (unsigned)rc);
E
Eric Blake 已提交
3953
                        } else {
3954
                            rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid.value);
E
Eric Blake 已提交
3955
                            if (NS_FAILED(rc)) {
3956 3957
                                virReportError(VIR_ERR_INTERNAL_ERROR,
                                               _("could not attach the file to cdrom: %s, rc=%08x"),
3958
                                               src, (unsigned)rc);
E
Eric Blake 已提交
3959
                            } else {
3960
                                DEBUGIID("CD/DVDImage UUID:", dvduuid.value);
3961
                            }
3962
                        }
E
Eric Blake 已提交
3963 3964

                        VBOX_MEDIUM_RELEASE(dvdImage);
3965
                    }
3966
                    vboxIIDUnalloc(&dvduuid);
E
Eric Blake 已提交
3967 3968 3969
                    VBOX_UTF16_FREE(dvdfileUtf16);
                    VBOX_RELEASE(dvdDrive);
                }
E
Eric Blake 已提交
3970
            } else if (type == VIR_STORAGE_TYPE_BLOCK) {
E
Eric Blake 已提交
3971 3972
            }
        } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
E
Eric Blake 已提交
3973
            if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
3974 3975
                IHardDisk *hardDisk     = NULL;
                PRUnichar *hddfileUtf16 = NULL;
3976
                vboxIID hdduuid = VBOX_IID_INITIALIZER;
E
Eric Blake 已提交
3977 3978 3979 3980 3981 3982
                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
                 */
3983

3984
                VBOX_UTF8_TO_UTF16(src, &hddfileUtf16);
E
Eric Blake 已提交
3985
                VBOX_UTF8_TO_UTF16("", &hddEmpty);
3986

E
Eric Blake 已提交
3987 3988
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddfileUtf16,
                                                  &hardDisk);
3989

E
Eric Blake 已提交
3990
                if (!hardDisk) {
3991
# if VBOX_API_VERSION == 2002000
E
Eric Blake 已提交
3992 3993 3994 3995
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      &hardDisk);
3996
# else
E
Eric Blake 已提交
3997 3998 3999 4000 4001 4002 4003 4004
                    data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                      hddfileUtf16,
                                                      AccessMode_ReadWrite,
                                                      0,
                                                      hddEmpty,
                                                      0,
                                                      hddEmpty,
                                                      &hardDisk);
4005
# endif
E
Eric Blake 已提交
4006
                }
4007

E
Eric Blake 已提交
4008 4009
                if (hardDisk) {
                    rc = hardDisk->vtbl->imedium.GetId((IMedium *)hardDisk,
4010
                                                       &hdduuid.value);
E
Eric Blake 已提交
4011
                    if (NS_FAILED(rc)) {
4012 4013 4014
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("can't get the uuid of the file to be "
                                         "attached as harddisk: %s, rc=%08x"),
4015
                                       src, (unsigned)rc);
E
Eric Blake 已提交
4016
                    } else {
4017
                        if (def->disks[i]->src->readonly) {
E
Eric Blake 已提交
4018 4019
                            hardDisk->vtbl->SetType(hardDisk,
                                                    HardDiskType_Immutable);
4020
                            VIR_DEBUG("setting harddisk to readonly");
4021
                        } else if (!def->disks[i]->src->readonly) {
E
Eric Blake 已提交
4022 4023
                            hardDisk->vtbl->SetType(hardDisk,
                                                    HardDiskType_Normal);
4024
                            VIR_DEBUG("setting harddisk type to normal");
E
Eric Blake 已提交
4025 4026 4027
                        }
                        if (def->disks[i]->bus == VIR_DOMAIN_DISK_BUS_IDE) {
                            if (STREQ(def->disks[i]->dst, "hdc")) {
4028
                                VIR_DEBUG("Not connecting harddisk to hdc as hdc"
E
Eric Blake 已提交
4029
                                       " is taken by CD/DVD Drive");
4030
                            } else {
E
Eric Blake 已提交
4031 4032 4033 4034
                                PRInt32 channel          = 0;
                                PRInt32 device           = 0;
                                PRUnichar *hddcnameUtf16 = NULL;

4035 4036
                                char *hddcname;
                                ignore_value(VIR_STRDUP(hddcname, "IDE"));
E
Eric Blake 已提交
4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048
                                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;
4049
                                }
E
Eric Blake 已提交
4050 4051

                                rc = machine->vtbl->AttachHardDisk(machine,
4052
                                                                   hdduuid.value,
E
Eric Blake 已提交
4053 4054 4055 4056 4057 4058
                                                                   hddcnameUtf16,
                                                                   channel,
                                                                   device);
                                VBOX_UTF16_FREE(hddcnameUtf16);

                                if (NS_FAILED(rc)) {
4059 4060 4061
                                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                                   _("could not attach the file as "
                                                     "harddisk: %s, rc=%08x"),
4062
                                                   src, (unsigned)rc);
E
Eric Blake 已提交
4063
                                } else {
4064
                                    DEBUGIID("Attached HDD with UUID", hdduuid.value);
4065 4066 4067
                                }
                            }
                        }
4068
                    }
E
Eric Blake 已提交
4069 4070
                    VBOX_MEDIUM_RELEASE(hardDisk);
                }
4071
                vboxIIDUnalloc(&hdduuid);
E
Eric Blake 已提交
4072 4073
                VBOX_UTF16_FREE(hddEmpty);
                VBOX_UTF16_FREE(hddfileUtf16);
E
Eric Blake 已提交
4074
            } else if (type == VIR_STORAGE_TYPE_BLOCK) {
E
Eric Blake 已提交
4075 4076
            }
        } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
E
Eric Blake 已提交
4077
            if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
4078 4079 4080 4081 4082 4083 4084
                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;
4085 4086
                        vboxIID fduuid = VBOX_IID_INITIALIZER;
                        vboxIID fdemptyuuid = VBOX_IID_INITIALIZER;
4087

4088
                        VBOX_UTF8_TO_UTF16(src, &fdfileUtf16);
E
Eric Blake 已提交
4089 4090 4091
                        rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                  fdfileUtf16,
                                                                  &floppyImage);
4092

E
Eric Blake 已提交
4093 4094 4095
                        if (!floppyImage) {
                            data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                 fdfileUtf16,
4096
                                                                 fdemptyuuid.value,
E
Eric Blake 已提交
4097 4098
                                                                 &floppyImage);
                        }
4099

E
Eric Blake 已提交
4100 4101
                        if (floppyImage) {
                            rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage,
4102
                                                                  &fduuid.value);
E
Eric Blake 已提交
4103
                            if (NS_FAILED(rc)) {
4104 4105 4106
                                virReportError(VIR_ERR_INTERNAL_ERROR,
                                               _("can't get the uuid of the file to "
                                                 "be attached to floppy drive: %s, rc=%08x"),
4107
                                               src, (unsigned)rc);
E
Eric Blake 已提交
4108 4109
                            } else {
                                rc = floppyDrive->vtbl->MountImage(floppyDrive,
4110
                                                                   fduuid.value);
E
Eric Blake 已提交
4111
                                if (NS_FAILED(rc)) {
4112 4113 4114
                                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                                   _("could not attach the file to "
                                                     "floppy drive: %s, rc=%08x"),
4115
                                                   src, (unsigned)rc);
E
Eric Blake 已提交
4116
                                } else {
4117
                                    DEBUGIID("floppyImage UUID", fduuid.value);
4118 4119
                                }
                            }
E
Eric Blake 已提交
4120
                            VBOX_MEDIUM_RELEASE(floppyImage);
4121
                        }
4122
                        vboxIIDUnalloc(&fduuid);
E
Eric Blake 已提交
4123
                        VBOX_UTF16_FREE(fdfileUtf16);
4124
                    }
E
Eric Blake 已提交
4125
                    VBOX_RELEASE(floppyDrive);
4126
                }
E
Eric Blake 已提交
4127
            } else if (type == VIR_STORAGE_TYPE_BLOCK) {
4128
            }
4129
        }
E
Eric Blake 已提交
4130
    }
4131
#else  /* VBOX_API_VERSION >= 3001000 */
E
Eric Blake 已提交
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143
    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 */
4144
    {
E
Eric Blake 已提交
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179
        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);
    }
4180

E
Eric Blake 已提交
4181
    for (i = 0; i < def->ndisks && !error; i++) {
4182 4183 4184 4185 4186
        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);
4187 4188
        VIR_DEBUG("disk(%zu) device:     %d", i, def->disks[i]->device);
        VIR_DEBUG("disk(%zu) bus:        %d", i, def->disks[i]->bus);
4189
        VIR_DEBUG("disk(%zu) src:        %s", i, src);
4190
        VIR_DEBUG("disk(%zu) dst:        %s", i, def->disks[i]->dst);
4191 4192
        VIR_DEBUG("disk(%zu) driverName: %s", i,
                  virDomainDiskGetDriver(def->disks[i]));
4193
        VIR_DEBUG("disk(%zu) driverType: %s", i,
4194
                  virStorageFileFormatTypeToString(format));
4195
        VIR_DEBUG("disk(%zu) cachemode:  %d", i, def->disks[i]->cachemode);
4196
        VIR_DEBUG("disk(%zu) readonly:   %s", i, (def->disks[i]->src->readonly
E
Eric Blake 已提交
4197
                                             ? "True" : "False"));
4198
        VIR_DEBUG("disk(%zu) shared:     %s", i, (def->disks[i]->src->shared
E
Eric Blake 已提交
4199 4200
                                             ? "True" : "False"));

E
Eric Blake 已提交
4201
        if (type == VIR_STORAGE_TYPE_FILE && src) {
E
Eric Blake 已提交
4202 4203 4204 4205 4206
            IMedium   *medium          = NULL;
            PRUnichar *mediumUUID      = NULL;
            PRUnichar *mediumFileUtf16 = NULL;
            PRUint32   storageBus      = StorageBus_Null;
            PRUint32   deviceType      = DeviceType_Null;
4207
# if VBOX_API_VERSION >= 4000000
4208
            PRUint32   accessMode      = AccessMode_ReadOnly;
4209
# endif
E
Eric Blake 已提交
4210 4211 4212 4213
            PRInt32    deviceInst      = 0;
            PRInt32    devicePort      = 0;
            PRInt32    deviceSlot      = 0;

4214
            VBOX_UTF8_TO_UTF16(src, &mediumFileUtf16);
E
Eric Blake 已提交
4215 4216 4217

            if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
                deviceType = DeviceType_HardDisk;
4218
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
4219 4220
                data->vboxObj->vtbl->FindHardDisk(data->vboxObj,
                                                  mediumFileUtf16, &medium);
4221 4222
# else
                accessMode = AccessMode_ReadWrite;
4223
# endif
E
Eric Blake 已提交
4224 4225
            } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
                deviceType = DeviceType_DVD;
4226
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
4227 4228
                data->vboxObj->vtbl->FindDVDImage(data->vboxObj,
                                                  mediumFileUtf16, &medium);
4229 4230
# else
                accessMode = AccessMode_ReadOnly;
4231
# endif
E
Eric Blake 已提交
4232 4233
            } else if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
                deviceType = DeviceType_Floppy;
4234
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
4235 4236
                data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                     mediumFileUtf16, &medium);
4237 4238
# else
                accessMode = AccessMode_ReadWrite;
4239
# endif
E
Eric Blake 已提交
4240 4241 4242 4243
            } else {
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
4244

4245
# if VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
4246 4247
            data->vboxObj->vtbl->FindMedium(data->vboxObj, mediumFileUtf16,
                                            deviceType, &medium);
4248
# elif VBOX_API_VERSION >= 4002000
4249 4250
            data->vboxObj->vtbl->OpenMedium(data->vboxObj, mediumFileUtf16,
                                            deviceType, accessMode, PR_FALSE, &medium);
4251 4252
# endif

E
Eric Blake 已提交
4253 4254
            if (!medium) {
                PRUnichar *mediumEmpty = NULL;
4255

E
Eric Blake 已提交
4256
                VBOX_UTF8_TO_UTF16("", &mediumEmpty);
4257

4258
# if VBOX_API_VERSION < 4000000
4259
                if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
4260 4261 4262 4263 4264 4265 4266 4267
                    rc = data->vboxObj->vtbl->OpenHardDisk(data->vboxObj,
                                                           mediumFileUtf16,
                                                           AccessMode_ReadWrite,
                                                           false,
                                                           mediumEmpty,
                                                           false,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
4268 4269
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_CDROM) {
4270 4271 4272 4273
                    rc = data->vboxObj->vtbl->OpenDVDImage(data->vboxObj,
                                                           mediumFileUtf16,
                                                           mediumEmpty,
                                                           &medium);
E
Eric Blake 已提交
4274 4275
                } else if (def->disks[i]->device ==
                           VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
4276 4277 4278 4279 4280 4281
                    rc = data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                              mediumFileUtf16,
                                                              mediumEmpty,
                                                              &medium);
                } else {
                    rc = 0;
4282
                }
4283
# elif VBOX_API_VERSION == 4000000
4284 4285 4286 4287
                rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                     mediumFileUtf16,
                                                     deviceType, accessMode,
                                                     &medium);
4288
# elif VBOX_API_VERSION >= 4001000
4289 4290 4291 4292 4293
                rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj,
                                                     mediumFileUtf16,
                                                     deviceType, accessMode,
                                                     false,
                                                     &medium);
4294
# endif /* VBOX_API_VERSION >= 4001000 */
4295

E
Eric Blake 已提交
4296 4297
                VBOX_UTF16_FREE(mediumEmpty);
            }
4298

E
Eric Blake 已提交
4299
            if (!medium) {
4300 4301 4302
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Failed to attach the following disk/dvd/floppy "
                                 "to the machine: %s, rc=%08x"),
4303
                               src, (unsigned)rc);
E
Eric Blake 已提交
4304 4305 4306
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
4307

E
Eric Blake 已提交
4308 4309
            rc = medium->vtbl->GetId(medium, &mediumUUID);
            if (NS_FAILED(rc)) {
4310 4311 4312
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("can't get the uuid of the file to be attached "
                                 "as harddisk/dvd/floppy: %s, rc=%08x"),
4313
                               src, (unsigned)rc);
E
Eric Blake 已提交
4314 4315 4316 4317
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumFileUtf16);
                continue;
            }
4318

E
Eric Blake 已提交
4319
            if (def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
4320
                if (def->disks[i]->src->readonly) {
E
Eric Blake 已提交
4321
                    medium->vtbl->SetType(medium, MediumType_Immutable);
4322
                    VIR_DEBUG("setting harddisk to immutable");
4323
                } else if (!def->disks[i]->src->readonly) {
E
Eric Blake 已提交
4324
                    medium->vtbl->SetType(medium, MediumType_Normal);
4325
                    VIR_DEBUG("setting harddisk type to normal");
4326
                }
E
Eric Blake 已提交
4327
            }
4328

E
Eric Blake 已提交
4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341
            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;
            }
4342

E
Eric Blake 已提交
4343 4344 4345 4346 4347 4348 4349 4350
            /* get the device details i.e instance, port and slot */
            if (!vboxGetDeviceDetails(def->disks[i]->dst,
                                      maxPortPerInst,
                                      maxSlotPerPort,
                                      storageBus,
                                      &deviceInst,
                                      &devicePort,
                                      &deviceSlot)) {
4351
                virReportError(VIR_ERR_INTERNAL_ERROR,
4352 4353 4354
                               _("can't get the port/slot number of "
                                 "harddisk/dvd/floppy to be attached: "
                                 "%s, rc=%08x"),
4355
                               src, (unsigned)rc);
4356 4357 4358
                VBOX_RELEASE(medium);
                VBOX_UTF16_FREE(mediumUUID);
                VBOX_UTF16_FREE(mediumFileUtf16);
E
Eric Blake 已提交
4359 4360 4361 4362 4363 4364 4365 4366 4367
                continue;
            }

            /* attach the harddisk/dvd/Floppy to the storage controller */
            rc = machine->vtbl->AttachDevice(machine,
                                             storageCtlName,
                                             devicePort,
                                             deviceSlot,
                                             deviceType,
4368
# if VBOX_API_VERSION < 4000000
E
Eric Blake 已提交
4369
                                             mediumUUID);
4370
# else /* VBOX_API_VERSION >= 4000000 */
4371
                                             medium);
4372
# endif /* VBOX_API_VERSION >= 4000000 */
E
Eric Blake 已提交
4373 4374

            if (NS_FAILED(rc)) {
4375
                virReportError(VIR_ERR_INTERNAL_ERROR,
4376 4377
                               _("could not attach the file as "
                                 "harddisk/dvd/floppy: %s, rc=%08x"),
4378
                               src, (unsigned)rc);
E
Eric Blake 已提交
4379 4380
            } else {
                DEBUGIID("Attached HDD/DVD/Floppy with UUID", mediumUUID);
4381
            }
E
Eric Blake 已提交
4382 4383 4384 4385 4386

            VBOX_RELEASE(medium);
            VBOX_UTF16_FREE(mediumUUID);
            VBOX_UTF16_FREE(mediumFileUtf16);
            VBOX_UTF16_FREE(storageCtlName);
4387 4388
        }
    }
4389
#endif /* VBOX_API_VERSION >= 3001000 */
E
Eric Blake 已提交
4390
}
4391

E
Eric Blake 已提交
4392 4393 4394 4395
static void
vboxAttachSound(virDomainDefPtr def, IMachine *machine)
{
    nsresult rc;
4396

E
Eric Blake 已提交
4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412
    /* 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);
4413
                }
4414
            }
E
Eric Blake 已提交
4415
            VBOX_RELEASE(audioAdapter);
4416
        }
E
Eric Blake 已提交
4417 4418 4419 4420 4421 4422 4423
    }
}

static void
vboxAttachNetwork(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
4424
#if VBOX_API_VERSION >= 4001000
4425
    PRUint32 chipsetType                = ChipsetType_Null;
4426
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4427
    PRUint32 networkAdapterCount        = 0;
4428
    size_t i = 0;
E
Eric Blake 已提交
4429

4430
#if VBOX_API_VERSION >= 4001000
4431
    machine->vtbl->GetChipsetType(machine, &chipsetType);
4432
#endif /* VBOX_API_VERSION >= 4001000 */
4433

E
Eric Blake 已提交
4434 4435
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
4436
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4437 4438
        systemProperties->vtbl->GetNetworkAdapterCount(systemProperties,
                                                       &networkAdapterCount);
4439
#else  /* VBOX_API_VERSION >= 4000000 */
4440 4441
        systemProperties->vtbl->GetMaxNetworkAdapters(systemProperties, chipsetType,
                                                      &networkAdapterCount);
4442
#endif /* VBOX_API_VERSION >= 4000000 */
E
Eric Blake 已提交
4443 4444 4445 4446
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }

4447
    VIR_DEBUG("Number of Network Cards to be connected: %zu", def->nnets);
4448
    VIR_DEBUG("Number of Network Cards available: %d", networkAdapterCount);
E
Eric Blake 已提交
4449 4450 4451 4452 4453 4454 4455

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

4456
        virMacAddrFormat(&def->nets[i]->mac, macaddr);
E
Eric Blake 已提交
4457 4458
        snprintf(macaddrvbox, VIR_MAC_STRING_BUFLEN - 5,
                 "%02X%02X%02X%02X%02X%02X",
4459 4460 4461 4462 4463 4464
                 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 已提交
4465 4466
        macaddrvbox[VIR_MAC_STRING_BUFLEN - 6] = '\0';

4467 4468 4469 4470
        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 已提交
4471
        if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
4472
            VIR_DEBUG("NIC(%zu): name:    %s", i, def->nets[i]->data.network.name);
E
Eric Blake 已提交
4473
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
4474
            VIR_DEBUG("NIC(%zu): name:   %s", i, def->nets[i]->data.internal.name);
E
Eric Blake 已提交
4475
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
4476
            VIR_DEBUG("NIC(%zu): NAT.", i);
E
Eric Blake 已提交
4477
        } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
4478 4479 4480
            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);
4481 4482
        }

E
Eric Blake 已提交
4483 4484 4485 4486 4487
        machine->vtbl->GetNetworkAdapter(machine, i, &adapter);
        if (adapter) {
            PRUnichar *MACAddress = NULL;

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

E
Eric Blake 已提交
4489
            if (def->nets[i]->model) {
E
Eric Blake 已提交
4490
                if (STRCASEEQ(def->nets[i]->model, "Am79C970A")) {
E
Eric Blake 已提交
4491
                    adapterType = NetworkAdapterType_Am79C970A;
E
Eric Blake 已提交
4492
                } else if (STRCASEEQ(def->nets[i]->model, "Am79C973")) {
E
Eric Blake 已提交
4493
                    adapterType = NetworkAdapterType_Am79C973;
E
Eric Blake 已提交
4494
                } else if (STRCASEEQ(def->nets[i]->model, "82540EM")) {
E
Eric Blake 已提交
4495
                    adapterType = NetworkAdapterType_I82540EM;
E
Eric Blake 已提交
4496
                } else if (STRCASEEQ(def->nets[i]->model, "82545EM")) {
E
Eric Blake 已提交
4497
                    adapterType = NetworkAdapterType_I82545EM;
E
Eric Blake 已提交
4498
                } else if (STRCASEEQ(def->nets[i]->model, "82543GC")) {
E
Eric Blake 已提交
4499
                    adapterType = NetworkAdapterType_I82543GC;
4500
#if VBOX_API_VERSION >= 3001000
E
Eric Blake 已提交
4501
                } else if (STRCASEEQ(def->nets[i]->model, "virtio")) {
E
Eric Blake 已提交
4502
                    adapterType = NetworkAdapterType_Virtio;
4503
#endif /* VBOX_API_VERSION >= 3001000 */
4504
                }
E
Eric Blake 已提交
4505 4506 4507
            } else {
                adapterType = NetworkAdapterType_Am79C973;
            }
4508

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

E
Eric Blake 已提交
4511 4512 4513
            if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
                PRUnichar *hostInterface = NULL;
                /* Bridged Network */
4514

4515
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4516
                adapter->vtbl->AttachToBridgedInterface(adapter);
4517
#else /* VBOX_API_VERSION >= 4001000 */
4518
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_Bridged);
4519
#endif /* VBOX_API_VERSION >= 4001000 */
4520

E
Eric Blake 已提交
4521 4522 4523
                if (def->nets[i]->data.bridge.brname) {
                    VBOX_UTF8_TO_UTF16(def->nets[i]->data.bridge.brname,
                                       &hostInterface);
4524
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4525
                    adapter->vtbl->SetHostInterface(adapter, hostInterface);
4526
#else /* VBOX_API_VERSION >= 4001000 */
4527
                    adapter->vtbl->SetBridgedInterface(adapter, hostInterface);
4528
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4529 4530 4531 4532 4533
                    VBOX_UTF16_FREE(hostInterface);
                }
            } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_INTERNAL) {
                PRUnichar *internalNetwork = NULL;
                /* Internal Network */
4534

4535
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4536
                adapter->vtbl->AttachToInternalNetwork(adapter);
4537
#else /* VBOX_API_VERSION >= 4001000 */
4538
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_Internal);
4539
#endif /* VBOX_API_VERSION >= 4001000 */
4540

E
Eric Blake 已提交
4541 4542 4543 4544 4545
                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);
4546
                }
E
Eric Blake 已提交
4547 4548 4549 4550 4551 4552
            } 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)
                 */
4553
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4554
                adapter->vtbl->AttachToHostOnlyInterface(adapter);
4555
#else /* VBOX_API_VERSION >= 4001000 */
4556
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_HostOnly);
4557
#endif /* VBOX_API_VERSION >= 4001000 */
4558

E
Eric Blake 已提交
4559 4560 4561
                if (def->nets[i]->data.network.name) {
                    VBOX_UTF8_TO_UTF16(def->nets[i]->data.network.name,
                                       &hostInterface);
4562
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4563
                    adapter->vtbl->SetHostInterface(adapter, hostInterface);
4564
#else /* VBOX_API_VERSION >= 4001000 */
4565
                    adapter->vtbl->SetHostOnlyInterface(adapter, hostInterface);
4566
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4567 4568 4569 4570
                    VBOX_UTF16_FREE(hostInterface);
                }
            } else if (def->nets[i]->type == VIR_DOMAIN_NET_TYPE_USER) {
                /* NAT */
4571
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4572
                adapter->vtbl->AttachToNAT(adapter);
4573
#else /* VBOX_API_VERSION >= 4001000 */
4574
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_NAT);
4575
#endif /* VBOX_API_VERSION >= 4001000 */
E
Eric Blake 已提交
4576 4577 4578 4579
            } else {
                /* else always default to NAT if we don't understand
                 * what option is been passed to us
                 */
4580
#if VBOX_API_VERSION < 4001000
E
Eric Blake 已提交
4581
                adapter->vtbl->AttachToNAT(adapter);
4582
#else /* VBOX_API_VERSION >= 4001000 */
4583
                adapter->vtbl->SetAttachmentType(adapter, NetworkAttachmentType_NAT);
4584
#endif /* VBOX_API_VERSION >= 4001000 */
4585
            }
E
Eric Blake 已提交
4586 4587 4588 4589

            VBOX_UTF8_TO_UTF16(macaddrvbox, &MACAddress);
            adapter->vtbl->SetMACAddress(adapter, MACAddress);
            VBOX_UTF16_FREE(MACAddress);
4590
        }
E
Eric Blake 已提交
4591 4592 4593 4594 4595 4596 4597 4598
    }
}

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

E
Eric Blake 已提交
4601 4602 4603 4604 4605 4606 4607
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetSerialPortCount(systemProperties,
                                                   &serialPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4608

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

4614 4615
        VIR_DEBUG("SerialPort(%zu): Type: %d", i, def->serials[i]->source.type);
        VIR_DEBUG("SerialPort(%zu): target.port: %d", i,
E
Eric Blake 已提交
4616
              def->serials[i]->target.port);
4617

E
Eric Blake 已提交
4618 4619 4620
        machine->vtbl->GetSerialPort(machine, i, &serialPort);
        if (serialPort) {
            PRUnichar *pathUtf16 = NULL;
4621

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

4624 4625 4626
            if (def->serials[i]->source.data.file.path) {
                VBOX_UTF8_TO_UTF16(def->serials[i]->source.data.file.path,
                                   &pathUtf16);
E
Eric Blake 已提交
4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
                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);
4642
                VIR_DEBUG(" serialPort-%zu irq: %d, iobase 0x%x, path: %s",
4643
                      i, 4, 1016, def->serials[i]->source.data.file.path);
E
Eric Blake 已提交
4644 4645 4646
            } else if (def->serials[i]->target.port == 1) {
                serialPort->vtbl->SetIRQ(serialPort, 3);
                serialPort->vtbl->SetIOBase(serialPort, 760);
4647
                VIR_DEBUG(" serialPort-%zu irq: %d, iobase 0x%x, path: %s",
4648
                      i, 3, 760, def->serials[i]->source.data.file.path);
E
Eric Blake 已提交
4649
            }
4650

4651
            if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_DEV) {
E
Eric Blake 已提交
4652
                serialPort->vtbl->SetHostMode(serialPort, PortMode_HostDevice);
4653
            } else if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_PIPE) {
E
Eric Blake 已提交
4654
                serialPort->vtbl->SetHostMode(serialPort, PortMode_HostPipe);
4655
#if VBOX_API_VERSION >= 3000000
4656
            } else if (def->serials[i]->source.type == VIR_DOMAIN_CHR_TYPE_FILE) {
E
Eric Blake 已提交
4657
                serialPort->vtbl->SetHostMode(serialPort, PortMode_RawFile);
4658
#endif /* VBOX_API_VERSION >= 3000000 */
E
Eric Blake 已提交
4659 4660 4661 4662
            } else {
                serialPort->vtbl->SetHostMode(serialPort,
                                              PortMode_Disconnected);
            }
4663

E
Eric Blake 已提交
4664
            VBOX_RELEASE(serialPort);
J
John Ferlan 已提交
4665
            VBOX_UTF16_FREE(pathUtf16);
4666
        }
E
Eric Blake 已提交
4667 4668
    }
}
4669

E
Eric Blake 已提交
4670 4671 4672 4673 4674
static void
vboxAttachParallel(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    ISystemProperties *systemProperties = NULL;
    PRUint32 parallelPortCount          = 0;
4675
    size_t i = 0;
4676

E
Eric Blake 已提交
4677 4678 4679 4680 4681 4682 4683
    data->vboxObj->vtbl->GetSystemProperties(data->vboxObj, &systemProperties);
    if (systemProperties) {
        systemProperties->vtbl->GetParallelPortCount(systemProperties,
                                                     &parallelPortCount);
        VBOX_RELEASE(systemProperties);
        systemProperties = NULL;
    }
4684

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

4690 4691
        VIR_DEBUG("ParallelPort(%zu): Type: %d", i, def->parallels[i]->source.type);
        VIR_DEBUG("ParallelPort(%zu): target.port: %d", i,
E
Eric Blake 已提交
4692
              def->parallels[i]->target.port);
4693

E
Eric Blake 已提交
4694 4695 4696
        machine->vtbl->GetParallelPort(machine, i, &parallelPort);
        if (parallelPort) {
            PRUnichar *pathUtf16 = NULL;
4697

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

E
Eric Blake 已提交
4700 4701 4702 4703 4704
            /* 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
             */
4705 4706 4707 4708
            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 已提交
4709 4710 4711 4712
                parallelPort->vtbl->SetPath(parallelPort, pathUtf16);
                if (i == 0) {
                    parallelPort->vtbl->SetIRQ(parallelPort, 7);
                    parallelPort->vtbl->SetIOBase(parallelPort, 888);
4713
                    VIR_DEBUG(" parallePort-%zu irq: %d, iobase 0x%x, path: %s",
4714
                          i, 7, 888, def->parallels[i]->source.data.file.path);
E
Eric Blake 已提交
4715 4716 4717
                } else if (i == 1) {
                    parallelPort->vtbl->SetIRQ(parallelPort, 5);
                    parallelPort->vtbl->SetIOBase(parallelPort, 632);
4718
                    VIR_DEBUG(" parallePort-%zu irq: %d, iobase 0x%x, path: %s",
4719
                          i, 5, 632, def->parallels[i]->source.data.file.path);
4720 4721
                }
            }
E
Eric Blake 已提交
4722 4723 4724 4725 4726 4727 4728

            /* 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 已提交
4729
            VBOX_UTF16_FREE(pathUtf16);
4730
        }
E
Eric Blake 已提交
4731 4732 4733 4734 4735 4736 4737 4738
    }
}

static void
vboxAttachVideo(virDomainDefPtr def, IMachine *machine)
{
    if ((def->nvideos == 1) &&
        (def->videos[0]->type == VIR_DOMAIN_VIDEO_TYPE_VBOX)) {
4739 4740
        machine->vtbl->SetVRAMSize(machine,
                                   VIR_DIV_UP(def->videos[0]->vram, 1024));
E
Eric Blake 已提交
4741 4742 4743 4744
        machine->vtbl->SetMonitorCount(machine, def->videos[0]->heads);
        if (def->videos[0]->accel) {
            machine->vtbl->SetAccelerate3DEnabled(machine,
                                                  def->videos[0]->accel->support3d);
4745
#if VBOX_API_VERSION >= 3001000
E
Eric Blake 已提交
4746 4747
            machine->vtbl->SetAccelerate2DVideoEnabled(machine,
                                                       def->videos[0]->accel->support2d);
4748
#endif /* VBOX_API_VERSION >= 3001000 */
E
Eric Blake 已提交
4749 4750
        } else {
            machine->vtbl->SetAccelerate3DEnabled(machine, 0);
4751
#if VBOX_API_VERSION >= 3001000
E
Eric Blake 已提交
4752
            machine->vtbl->SetAccelerate2DVideoEnabled(machine, 0);
4753
#endif /* VBOX_API_VERSION >= 3001000 */
4754
        }
E
Eric Blake 已提交
4755 4756
    }
}
4757

E
Eric Blake 已提交
4758 4759 4760 4761 4762 4763 4764 4765
static void
vboxAttachDisplay(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
    int vrdpPresent  = 0;
    int sdlPresent   = 0;
    int guiPresent   = 0;
    char *guiDisplay = NULL;
    char *sdlDisplay = NULL;
4766
    size_t i = 0;
4767

E
Eric Blake 已提交
4768
    for (i = 0; i < def->ngraphics; i++) {
4769
#if VBOX_API_VERSION < 4000000
4770
        IVRDPServer *VRDxServer = NULL;
4771
#else /* VBOX_API_VERSION >= 4000000 */
4772
        IVRDEServer *VRDxServer = NULL;
4773
#endif /* VBOX_API_VERSION >= 4000000 */
4774

E
Eric Blake 已提交
4775 4776
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_RDP) &&
            (vrdpPresent == 0)) {
4777

E
Eric Blake 已提交
4778
            vrdpPresent = 1;
4779
#if VBOX_API_VERSION < 4000000
4780
            machine->vtbl->GetVRDPServer(machine, &VRDxServer);
4781
#else /* VBOX_API_VERSION >= 4000000 */
4782
            machine->vtbl->GetVRDEServer(machine, &VRDxServer);
4783
#endif /* VBOX_API_VERSION >= 4000000 */
4784
            if (VRDxServer) {
4785 4786 4787
                const char *listenAddr
                    = virDomainGraphicsListenGetAddress(def->graphics[i], 0);

4788
                VRDxServer->vtbl->SetEnabled(VRDxServer, PR_TRUE);
4789
                VIR_DEBUG("VRDP Support turned ON.");
4790

4791
#if VBOX_API_VERSION < 3001000
E
Eric Blake 已提交
4792
                if (def->graphics[i]->data.rdp.port) {
4793
                    VRDxServer->vtbl->SetPort(VRDxServer,
E
Eric Blake 已提交
4794
                                              def->graphics[i]->data.rdp.port);
4795
                    VIR_DEBUG("VRDP Port changed to: %d",
E
Eric Blake 已提交
4796 4797 4798 4799 4800
                          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
                     */
4801
                    VRDxServer->vtbl->SetPort(VRDxServer, 0);
4802
                    VIR_DEBUG("VRDP Port changed to default, which is 3389 currently");
E
Eric Blake 已提交
4803
                }
4804
#elif VBOX_API_VERSION < 4000000 /* 3001000 <= VBOX_API_VERSION < 4000000 */
E
Eric Blake 已提交
4805 4806
                PRUnichar *portUtf16 = NULL;
                portUtf16 = PRUnicharFromInt(def->graphics[i]->data.rdp.port);
4807
                VRDxServer->vtbl->SetPorts(VRDxServer, portUtf16);
E
Eric Blake 已提交
4808
                VBOX_UTF16_FREE(portUtf16);
4809
#else /* VBOX_API_VERSION >= 4000000 */
4810 4811 4812 4813 4814 4815 4816 4817
                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);
4818
#endif /* VBOX_API_VERSION >= 4000000 */
4819

E
Eric Blake 已提交
4820
                if (def->graphics[i]->data.rdp.replaceUser) {
4821
                    VRDxServer->vtbl->SetReuseSingleConnection(VRDxServer,
E
Eric Blake 已提交
4822
                                                               PR_TRUE);
4823
                    VIR_DEBUG("VRDP set to reuse single connection");
E
Eric Blake 已提交
4824
                }
4825

E
Eric Blake 已提交
4826
                if (def->graphics[i]->data.rdp.multiUser) {
4827
                    VRDxServer->vtbl->SetAllowMultiConnection(VRDxServer,
E
Eric Blake 已提交
4828
                                                              PR_TRUE);
4829
                    VIR_DEBUG("VRDP set to allow multiple connection");
E
Eric Blake 已提交
4830
                }
4831

4832
                if (listenAddr) {
4833
#if VBOX_API_VERSION >= 4000000
4834 4835
                    PRUnichar *netAddressKey = NULL;
#endif
E
Eric Blake 已提交
4836
                    PRUnichar *netAddressUtf16 = NULL;
4837

4838
                    VBOX_UTF8_TO_UTF16(listenAddr, &netAddressUtf16);
4839
#if VBOX_API_VERSION < 4000000
4840
                    VRDxServer->vtbl->SetNetAddress(VRDxServer,
E
Eric Blake 已提交
4841
                                                    netAddressUtf16);
4842
#else /* VBOX_API_VERSION >= 4000000 */
4843 4844 4845 4846
                    VBOX_UTF8_TO_UTF16("TCP/Address", &netAddressKey);
                    VRDxServer->vtbl->SetVRDEProperty(VRDxServer, netAddressKey,
                                                      netAddressUtf16);
                    VBOX_UTF16_FREE(netAddressKey);
4847
#endif /* VBOX_API_VERSION >= 4000000 */
4848
                    VIR_DEBUG("VRDP listen address is set to: %s",
4849
                              listenAddr);
4850

E
Eric Blake 已提交
4851
                    VBOX_UTF16_FREE(netAddressUtf16);
4852
                }
E
Eric Blake 已提交
4853

4854
                VBOX_RELEASE(VRDxServer);
4855
            }
E
Eric Blake 已提交
4856
        }
4857

E
Eric Blake 已提交
4858 4859 4860
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_DESKTOP) &&
            (guiPresent == 0)) {
            guiPresent = 1;
4861 4862 4863 4864 4865
            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
                 */
4866
            }
E
Eric Blake 已提交
4867
        }
4868

E
Eric Blake 已提交
4869 4870 4871
        if ((def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SDL) &&
            (sdlPresent == 0)) {
            sdlPresent = 1;
4872 4873 4874 4875 4876
            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
                 */
4877
            }
4878
        }
E
Eric Blake 已提交
4879
    }
4880

E
Eric Blake 已提交
4881 4882 4883 4884
    if ((vrdpPresent == 1) && (guiPresent == 0) && (sdlPresent == 0)) {
        /* store extradata key that frontend is set to vrdp */
        PRUnichar *keyTypeUtf16   = NULL;
        PRUnichar *valueTypeUtf16 = NULL;
4885

E
Eric Blake 已提交
4886 4887
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("vrdp", &valueTypeUtf16);
4888

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

E
Eric Blake 已提交
4891 4892
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4893

E
Eric Blake 已提交
4894 4895 4896 4897 4898 4899
    } 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;
4900

E
Eric Blake 已提交
4901 4902
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("sdl", &valueTypeUtf16);
4903

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

E
Eric Blake 已提交
4906 4907
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4908

E
Eric Blake 已提交
4909 4910 4911
        if (sdlDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(sdlDisplay, &valueDisplayUtf16);
4912

E
Eric Blake 已提交
4913 4914
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4915

E
Eric Blake 已提交
4916 4917 4918
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
        }
4919

E
Eric Blake 已提交
4920 4921 4922 4923 4924 4925
    } 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;
4926

E
Eric Blake 已提交
4927 4928
        VBOX_UTF8_TO_UTF16("FRONTEND/Type", &keyTypeUtf16);
        VBOX_UTF8_TO_UTF16("gui", &valueTypeUtf16);
4929

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

E
Eric Blake 已提交
4932 4933
        VBOX_UTF16_FREE(keyTypeUtf16);
        VBOX_UTF16_FREE(valueTypeUtf16);
4934

E
Eric Blake 已提交
4935 4936 4937
        if (guiDisplay) {
            VBOX_UTF8_TO_UTF16("FRONTEND/Display", &keyDislpayUtf16);
            VBOX_UTF8_TO_UTF16(guiDisplay, &valueDisplayUtf16);
4938

E
Eric Blake 已提交
4939 4940
            machine->vtbl->SetExtraData(machine, keyDislpayUtf16,
                                        valueDisplayUtf16);
4941

E
Eric Blake 已提交
4942 4943
            VBOX_UTF16_FREE(keyDislpayUtf16);
            VBOX_UTF16_FREE(valueDisplayUtf16);
4944
        }
E
Eric Blake 已提交
4945
    }
4946

E
Eric Blake 已提交
4947 4948 4949
    VIR_FREE(guiDisplay);
    VIR_FREE(sdlDisplay);
}
4950

E
Eric Blake 已提交
4951 4952 4953
static void
vboxAttachUSB(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
4954
#if VBOX_API_VERSION < 4003000
E
Eric Blake 已提交
4955
    IUSBController *USBController = NULL;
R
Ryota Ozaki 已提交
4956 4957 4958
#else
    IUSBDeviceFilters *USBDeviceFilters = NULL;
#endif
4959
    size_t i = 0;
E
Eric Blake 已提交
4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970
    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 已提交
4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986
        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 已提交
4987 4988
    }

R
Ryota Ozaki 已提交
4989 4990 4991
    if (!isUSB)
        return;

4992
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
4993 4994 4995 4996 4997 4998 4999 5000 5001
    /* 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);
5002
# if VBOX_API_VERSION < 4002000
R
Ryota Ozaki 已提交
5003
    USBController->vtbl->SetEnabledEhci(USBController, 1);
R
Ryota Ozaki 已提交
5004
# else
R
Ryota Ozaki 已提交
5005
    USBController->vtbl->SetEnabledEHCI(USBController, 1);
R
Ryota Ozaki 已提交
5006 5007 5008 5009 5010 5011
# endif
#else
    machine->vtbl->GetUSBDeviceFilters(machine, &USBDeviceFilters);

    if (!USBDeviceFilters)
        return;
5012
#endif
5013

R
Ryota Ozaki 已提交
5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024
    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;
5025

R
Ryota Ozaki 已提交
5026 5027 5028
        if (def->hostdevs[i]->source.subsys.type !=
            VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB)
            continue;
5029

R
Ryota Ozaki 已提交
5030 5031 5032 5033 5034 5035
        /* 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);
5036
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
5037 5038 5039
            USBController->vtbl->CreateDeviceFilter(USBController,
                                                    filternameUtf16,
                                                    &filter);
R
Ryota Ozaki 已提交
5040 5041 5042 5043 5044
#else
            USBDeviceFilters->vtbl->CreateDeviceFilter(USBDeviceFilters,
                                                       filternameUtf16,
                                                       &filter);
#endif
R
Ryota Ozaki 已提交
5045 5046
        }
        VBOX_UTF16_FREE(filternameUtf16);
E
Eric Blake 已提交
5047

R
Ryota Ozaki 已提交
5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068
        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 已提交
5069
        }
R
Ryota Ozaki 已提交
5070
        filter->vtbl->SetActive(filter, 1);
5071
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
5072 5073 5074
        USBController->vtbl->InsertDeviceFilter(USBController,
                                                i,
                                                filter);
R
Ryota Ozaki 已提交
5075 5076 5077 5078 5079
#else
        USBDeviceFilters->vtbl->InsertDeviceFilter(USBDeviceFilters,
                                                   i,
                                                   filter);
#endif
R
Ryota Ozaki 已提交
5080
        VBOX_RELEASE(filter);
E
Eric Blake 已提交
5081
    }
R
Ryota Ozaki 已提交
5082

5083
#if VBOX_API_VERSION < 4003000
R
Ryota Ozaki 已提交
5084
    VBOX_RELEASE(USBController);
R
Ryota Ozaki 已提交
5085 5086 5087
#else
    VBOX_RELEASE(USBDeviceFilters);
#endif
E
Eric Blake 已提交
5088 5089
}

M
Matthias Bolte 已提交
5090 5091 5092
static void
vboxAttachSharedFolder(virDomainDefPtr def, vboxGlobalData *data, IMachine *machine)
{
5093
    size_t i;
M
Matthias Bolte 已提交
5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108
    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;

5109
#if VBOX_API_VERSION < 4000000
M
Matthias Bolte 已提交
5110 5111
        machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                          writable);
5112
#else /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
5113 5114
        machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                          writable, PR_FALSE);
5115
#endif /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
5116 5117 5118 5119 5120 5121

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

5122 5123
static virDomainPtr vboxDomainDefineXML(virConnectPtr conn, const char *xml)
{
E
Eric Blake 已提交
5124 5125 5126
    VBOX_OBJECT_CHECK(conn, virDomainPtr, NULL);
    IMachine       *machine     = NULL;
    IBIOSSettings  *bios        = NULL;
5127 5128
    vboxIID iid = VBOX_IID_INITIALIZER;
    vboxIID mchiid = VBOX_IID_INITIALIZER;
E
Eric Blake 已提交
5129 5130
    virDomainDefPtr def         = NULL;
    PRUnichar *machineNameUtf16 = NULL;
5131
#if VBOX_API_VERSION >= 3002000 && VBOX_API_VERSION < 4002000
E
Eric Blake 已提交
5132 5133 5134
    PRBool override             = PR_FALSE;
#endif
    nsresult rc;
5135
    char uuidstr[VIR_UUID_STRING_BUFLEN];
5136
#if VBOX_API_VERSION >= 4002000
5137 5138 5139 5140 5141 5142
    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 已提交
5143

5144 5145
    if (!(def = virDomainDefParseString(xml, data->caps, data->xmlopt,
                                        1 << VIR_DOMAIN_VIRT_VBOX,
E
Eric Blake 已提交
5146 5147 5148 5149 5150
                                        VIR_DOMAIN_XML_INACTIVE))) {
        goto cleanup;
    }

    VBOX_UTF8_TO_UTF16(def->name, &machineNameUtf16);
5151
    vboxIIDFromUUID(&iid, def->uuid);
5152 5153
    virUUIDFormat(def->uuid, uuidstr);

5154
#if VBOX_API_VERSION < 3002000
E
Eric Blake 已提交
5155 5156 5157 5158
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
5159
                                            iid.value,
E
Eric Blake 已提交
5160
                                            &machine);
5161
#elif VBOX_API_VERSION < 4000000 /* 3002000 <= VBOX_API_VERSION < 4000000 */
E
Eric Blake 已提交
5162 5163 5164 5165
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            machineNameUtf16,
                                            NULL,
                                            NULL,
5166
                                            iid.value,
E
Eric Blake 已提交
5167 5168
                                            override,
                                            &machine);
5169
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
5170 5171 5172 5173 5174 5175 5176
    rc = data->vboxObj->vtbl->CreateMachine(data->vboxObj,
                                            NULL,
                                            machineNameUtf16,
                                            NULL,
                                            iid.value,
                                            override,
                                            &machine);
5177
#else /* VBOX_API_VERSION >= 4002000 */
5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
    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);
5193
#endif /* VBOX_API_VERSION >= 4002000 */
E
Eric Blake 已提交
5194 5195 5196
    VBOX_UTF16_FREE(machineNameUtf16);

    if (NS_FAILED(rc)) {
5197 5198
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not define a domain, rc=%08x"), (unsigned)rc);
E
Eric Blake 已提交
5199 5200 5201
        goto cleanup;
    }

5202 5203
    rc = machine->vtbl->SetMemorySize(machine,
                                      VIR_DIV_UP(def->mem.cur_balloon, 1024));
E
Eric Blake 已提交
5204
    if (NS_FAILED(rc)) {
5205 5206 5207 5208
        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 已提交
5209 5210
    }

E
Eric Blake 已提交
5211
    if (def->vcpus != def->maxvcpus) {
5212 5213
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("current vcpu count must equal maximum"));
E
Eric Blake 已提交
5214 5215
    }
    rc = machine->vtbl->SetCPUCount(machine, def->maxvcpus);
E
Eric Blake 已提交
5216
    if (NS_FAILED(rc)) {
5217 5218 5219
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not set the number of virtual CPUs to: %u, rc=%08x"),
                       def->maxvcpus, (unsigned)rc);
E
Eric Blake 已提交
5220 5221
    }

5222
#if VBOX_API_VERSION < 3001000
5223 5224
    rc = machine->vtbl->SetPAEEnabled(machine,
                                      def->features[VIR_DOMAIN_FEATURE_PAE] ==
J
Ján Tomko 已提交
5225
                                      VIR_TRISTATE_SWITCH_ON);
5226
#elif VBOX_API_VERSION == 3001000
E
Eric Blake 已提交
5227
    rc = machine->vtbl->SetCpuProperty(machine, CpuPropertyType_PAE,
5228
                                       def->features[VIR_DOMAIN_FEATURE_PAE] ==
J
Ján Tomko 已提交
5229
                                       VIR_TRISTATE_SWITCH_ON);
5230
#elif VBOX_API_VERSION >= 3002000
E
Eric Blake 已提交
5231
    rc = machine->vtbl->SetCPUProperty(machine, CPUPropertyType_PAE,
5232
                                       def->features[VIR_DOMAIN_FEATURE_PAE] ==
J
Ján Tomko 已提交
5233
                                       VIR_TRISTATE_SWITCH_ON);
E
Eric Blake 已提交
5234 5235
#endif
    if (NS_FAILED(rc)) {
5236 5237
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not change PAE status to: %s, rc=%08x"),
J
Ján Tomko 已提交
5238
                       (def->features[VIR_DOMAIN_FEATURE_PAE] == VIR_TRISTATE_SWITCH_ON)
5239
                       ? _("Enabled") : _("Disabled"), (unsigned)rc);
E
Eric Blake 已提交
5240 5241 5242 5243
    }

    machine->vtbl->GetBIOSSettings(machine, &bios);
    if (bios) {
5244 5245
        rc = bios->vtbl->SetACPIEnabled(bios,
                                        def->features[VIR_DOMAIN_FEATURE_ACPI] ==
J
Ján Tomko 已提交
5246
                                        VIR_TRISTATE_SWITCH_ON);
E
Eric Blake 已提交
5247
        if (NS_FAILED(rc)) {
5248 5249
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not change ACPI status to: %s, rc=%08x"),
J
Ján Tomko 已提交
5250
                           (def->features[VIR_DOMAIN_FEATURE_ACPI] == VIR_TRISTATE_SWITCH_ON)
5251
                           ? _("Enabled") : _("Disabled"), (unsigned)rc);
E
Eric Blake 已提交
5252
        }
5253 5254
        rc = bios->vtbl->SetIOAPICEnabled(bios,
                                          def->features[VIR_DOMAIN_FEATURE_APIC] ==
J
Ján Tomko 已提交
5255
                                          VIR_TRISTATE_SWITCH_ON);
E
Eric Blake 已提交
5256
        if (NS_FAILED(rc)) {
5257 5258
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not change APIC status to: %s, rc=%08x"),
J
Ján Tomko 已提交
5259
                           (def->features[VIR_DOMAIN_FEATURE_APIC] == VIR_TRISTATE_SWITCH_ON)
5260
                           ? _("Enabled") : _("Disabled"), (unsigned)rc);
5261
        }
E
Eric Blake 已提交
5262 5263 5264 5265 5266 5267
        VBOX_RELEASE(bios);
    }

    /* Register the machine before attaching other devices to it */
    rc = data->vboxObj->vtbl->RegisterMachine(data->vboxObj, machine);
    if (NS_FAILED(rc)) {
5268 5269
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not define a domain, rc=%08x"), (unsigned)rc);
E
Eric Blake 已提交
5270 5271 5272 5273 5274 5275 5276
        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
     */
5277
    machine->vtbl->GetId(machine, &mchiid.value);
5278
    VBOX_SESSION_OPEN(mchiid.value, machine);
E
Eric Blake 已提交
5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289
    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 已提交
5290
    vboxAttachSharedFolder(def, data, machine);
5291

5292 5293 5294 5295
    /* Save the machine settings made till now and close the
     * session. also free up the mchiid variable used.
     */
    rc = machine->vtbl->SaveSettings(machine);
5296
    VBOX_SESSION_CLOSE();
5297
    vboxIIDUnalloc(&mchiid);
5298

5299 5300
    ret = virGetDomain(conn, def->name, def->uuid);
    VBOX_RELEASE(machine);
5301

5302
    vboxIIDUnalloc(&iid);
5303 5304
    virDomainDefFree(def);

5305
    return ret;
5306

5307
 cleanup:
5308
    VBOX_RELEASE(machine);
5309
    vboxIIDUnalloc(&iid);
5310 5311 5312 5313
    virDomainDefFree(def);
    return NULL;
}

5314
static int
5315
vboxDomainUndefineFlags(virDomainPtr dom, unsigned int flags)
5316
{
5317
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5318
    IMachine *machine    = NULL;
5319
    vboxIID iid = VBOX_IID_INITIALIZER;
5320
    nsresult rc;
5321
#if VBOX_API_VERSION >= 4000000
5322 5323
    vboxArray media = VBOX_ARRAY_INITIALIZER;
#endif
5324 5325 5326 5327
    /* 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);
5328

5329
    vboxIIDFromUUID(&iid, dom->uuid);
5330

5331
#if VBOX_API_VERSION < 4000000
5332 5333 5334
    /* 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
5335 5336 5337 5338
     * 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.
5339 5340 5341
     */
    {
        PRUnichar *hddcnameUtf16 = NULL;
5342

5343 5344
        char *hddcname;
        ignore_value(VIR_STRDUP(hddcname, "IDE"));
5345 5346
        VBOX_UTF8_TO_UTF16(hddcname, &hddcnameUtf16);
        VIR_FREE(hddcname);
5347

5348
        /* Open a Session for the machine */
5349
        rc = VBOX_SESSION_OPEN(iid.value, machine);
5350 5351 5352 5353
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {

5354
# if VBOX_API_VERSION < 3001000
5355 5356 5357 5358
                /* 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);
5359
# else  /* VBOX_API_VERSION >= 3001000 */
5360 5361 5362
                /* get all the controller first, then the attachments and
                 * remove them all so that the machine can be undefined
                 */
5363
                vboxArray storageControllers = VBOX_ARRAY_INITIALIZER;
5364
                size_t i = 0, j = 0;
5365

5366 5367
                vboxArrayGet(&storageControllers, machine,
                             machine->vtbl->GetStorageControllers);
5368

5369 5370
                for (i = 0; i < storageControllers.count; i++) {
                    IStorageController *strCtl = storageControllers.items[i];
5371
                    PRUnichar *strCtlName = NULL;
5372
                    vboxArray mediumAttachments = VBOX_ARRAY_INITIALIZER;
5373 5374 5375 5376 5377

                    if (!strCtl)
                        continue;

                    strCtl->vtbl->GetName(strCtl, &strCtlName);
5378 5379 5380
                    vboxArrayGetWithPtrArg(&mediumAttachments, machine,
                                           machine->vtbl->GetMediumAttachmentsOfController,
                                           strCtlName);
5381

5382 5383
                    for (j = 0; j < mediumAttachments.count; j++) {
                        IMediumAttachment *medAtt = mediumAttachments.items[j];
5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399
                        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);
                        }
                    }
5400

5401 5402
                    vboxArrayRelease(&storageControllers);

5403 5404
                    machine->vtbl->RemoveStorageController(machine, strCtlName);
                    VBOX_UTF16_FREE(strCtlName);
5405
                }
5406 5407

                vboxArrayRelease(&storageControllers);
5408
# endif /* VBOX_API_VERSION >= 3001000 */
5409 5410

                machine->vtbl->SaveSettings(machine);
5411
            }
5412
            VBOX_SESSION_CLOSE();
5413
        }
5414 5415
        VBOX_UTF16_FREE(hddcnameUtf16);
    }
5416
#endif
5417

5418
#if VBOX_API_VERSION < 4000000
5419
    rc = data->vboxObj->vtbl->UnregisterMachine(data->vboxObj, iid.value, &machine);
5420
#else /* VBOX_API_VERSION >= 4000000 */
5421 5422
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
5423 5424
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
5425 5426 5427 5428 5429 5430 5431 5432 5433
        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);
5434
#endif /* VBOX_API_VERSION >= 4000000 */
5435
    DEBUGIID("UUID of machine being undefined", iid.value);
5436

5437
    if (NS_SUCCEEDED(rc)) {
5438
#if VBOX_API_VERSION < 4000000
5439
        machine->vtbl->DeleteSettings(machine);
5440
#else /* VBOX_API_VERSION >= 4000000 */
5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453
        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);

5454
#  if VBOX_API_VERSION < 4003000
5455
        ((IMachine_Delete)machine->vtbl->Delete)(machine, &safeArray, &progress);
R
Ryota Ozaki 已提交
5456 5457 5458
#  else
        ((IMachine_Delete)machine->vtbl->DeleteConfig)(machine, &safeArray, &progress);
#  endif
5459
# else
5460 5461 5462
        /* 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 };
5463
#  if VBOX_API_VERSION < 4003000
5464
        machine->vtbl->Delete(machine, 0, array, &progress);
R
Ryota Ozaki 已提交
5465 5466 5467
#  else
        machine->vtbl->DeleteConfig(machine, 0, array, &progress);
#  endif
5468 5469 5470 5471 5472
# endif
        if (progress != NULL) {
            progress->vtbl->WaitForCompletion(progress, -1);
            VBOX_RELEASE(progress);
        }
5473
#endif /* VBOX_API_VERSION >= 4000000 */
5474 5475
        ret = 0;
    } else {
5476 5477
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not delete the domain, rc=%08x"), (unsigned)rc);
5478 5479
    }

5480
#if VBOX_API_VERSION >= 4000000
5481 5482
    vboxArrayUnalloc(&media);
#endif
5483
    vboxIIDUnalloc(&iid);
5484
    VBOX_RELEASE(machine);
5485 5486 5487 5488

    return ret;
}

5489 5490 5491 5492 5493 5494
static int
vboxDomainUndefine(virDomainPtr dom)
{
    return vboxDomainUndefineFlags(dom, 0);
}

5495 5496
static int vboxDomainAttachDeviceImpl(virDomainPtr dom,
                                      const char *xml,
5497 5498
                                      int mediaChangeOnly ATTRIBUTE_UNUSED)
{
5499
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5500
    IMachine *machine    = NULL;
5501
    vboxIID iid = VBOX_IID_INITIALIZER;
5502 5503 5504
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5505
    nsresult rc;
5506

5507
    if (VIR_ALLOC(def) < 0)
5508 5509
        return ret;

5510
    if (VIR_STRDUP(def->os.type, "hvm") < 0)
5511 5512
        goto cleanup;

5513 5514
    dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt,
                                  VIR_DOMAIN_XML_INACTIVE);
5515
    if (dev == NULL)
5516 5517
        goto cleanup;

5518
    vboxIIDFromUUID(&iid, dom->uuid);
5519
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5520
    if (NS_FAILED(rc)) {
5521 5522
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
5523 5524
        goto cleanup;
    }
5525

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

5529 5530
        if ((state == MachineState_Running) ||
            (state == MachineState_Paused)) {
5531
            rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
5532
        } else {
5533
            rc = VBOX_SESSION_OPEN(iid.value, machine);
5534 5535 5536 5537 5538
        }
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
                if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
5539
#if VBOX_API_VERSION < 3001000
5540 5541 5542
                    const char *src = virDomainDiskGetSource(dev->data.disk);
                    int type = virDomainDiskGetType(dev->data.disk);

5543
                    if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
E
Eric Blake 已提交
5544
                        if (type == VIR_STORAGE_TYPE_FILE && src) {
5545 5546 5547 5548 5549 5550 5551 5552 5553
                            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;
5554 5555
                                vboxIID dvduuid = VBOX_IID_INITIALIZER;
                                vboxIID dvdemptyuuid = VBOX_IID_INITIALIZER;
5556

5557
                                VBOX_UTF8_TO_UTF16(src, &dvdfileUtf16);
5558

5559 5560
                                data->vboxObj->vtbl->FindDVDImage(data->vboxObj, dvdfileUtf16, &dvdImage);
                                if (!dvdImage) {
5561
                                    data->vboxObj->vtbl->OpenDVDImage(data->vboxObj, dvdfileUtf16, dvdemptyuuid.value, &dvdImage);
5562 5563
                                }
                                if (dvdImage) {
5564
                                    rc = dvdImage->vtbl->imedium.GetId((IMedium *)dvdImage, &dvduuid.value);
5565
                                    if (NS_FAILED(rc)) {
5566 5567 5568
                                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                                       _("can't get the uuid of the file to "
                                                         "be attached to cdrom: %s, rc=%08x"),
5569
                                                       src, (unsigned)rc);
5570 5571 5572
                                    } else {
                                        /* unmount the previous mounted image */
                                        dvdDrive->vtbl->Unmount(dvdDrive);
5573
                                        rc = dvdDrive->vtbl->MountImage(dvdDrive, dvduuid.value);
5574
                                        if (NS_FAILED(rc)) {
5575 5576
                                            virReportError(VIR_ERR_INTERNAL_ERROR,
                                                           _("could not attach the file to cdrom: %s, rc=%08x"),
5577
                                                           src, (unsigned)rc);
5578
                                        } else {
5579
                                            ret = 0;
5580
                                            DEBUGIID("CD/DVD Image UUID:", dvduuid.value);
5581 5582
                                        }
                                    }
5583 5584

                                    VBOX_MEDIUM_RELEASE(dvdImage);
5585
                                }
5586
                                vboxIIDUnalloc(&dvduuid);
5587 5588
                                VBOX_UTF16_FREE(dvdfileUtf16);
                                VBOX_RELEASE(dvdDrive);
5589
                            }
E
Eric Blake 已提交
5590
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5591 5592
                        }
                    } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
E
Eric Blake 已提交
5593
                        if (type == VIR_STORAGE_TYPE_FILE && src) {
5594 5595 5596 5597 5598 5599 5600
                            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;
5601 5602
                                    vboxIID fduuid = VBOX_IID_INITIALIZER;
                                    vboxIID fdemptyuuid = VBOX_IID_INITIALIZER;
5603
                                    VBOX_UTF8_TO_UTF16(src, &fdfileUtf16);
5604 5605 5606 5607 5608 5609 5610
                                    rc = data->vboxObj->vtbl->FindFloppyImage(data->vboxObj,
                                                                              fdfileUtf16,
                                                                              &floppyImage);

                                    if (!floppyImage) {
                                        data->vboxObj->vtbl->OpenFloppyImage(data->vboxObj,
                                                                             fdfileUtf16,
5611
                                                                             fdemptyuuid.value,
5612 5613
                                                                             &floppyImage);
                                    }
5614

5615
                                    if (floppyImage) {
5616
                                        rc = floppyImage->vtbl->imedium.GetId((IMedium *)floppyImage, &fduuid.value);
5617
                                        if (NS_FAILED(rc)) {
5618 5619 5620
                                            virReportError(VIR_ERR_INTERNAL_ERROR,
                                                           _("can't get the uuid of the file to be "
                                                             "attached to floppy drive: %s, rc=%08x"),
5621
                                                           src, (unsigned)rc);
5622
                                        } else {
5623
                                            rc = floppyDrive->vtbl->MountImage(floppyDrive, fduuid.value);
5624
                                            if (NS_FAILED(rc)) {
5625 5626
                                                virReportError(VIR_ERR_INTERNAL_ERROR,
                                                               _("could not attach the file to floppy drive: %s, rc=%08x"),
5627
                                                               src, (unsigned)rc);
5628
                                            } else {
5629
                                                ret = 0;
5630
                                                DEBUGIID("attached floppy, UUID:", fduuid.value);
5631 5632
                                            }
                                        }
5633
                                        VBOX_MEDIUM_RELEASE(floppyImage);
5634
                                    }
5635
                                    vboxIIDUnalloc(&fduuid);
5636
                                    VBOX_UTF16_FREE(fdfileUtf16);
5637
                                }
5638
                                VBOX_RELEASE(floppyDrive);
5639
                            }
E
Eric Blake 已提交
5640
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5641
                        }
5642
                    }
5643 5644
#else  /* VBOX_API_VERSION >= 3001000 */
#endif /* VBOX_API_VERSION >= 3001000 */
5645 5646 5647 5648
                } 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) {
5649 5650
                        }
                    }
M
Matthias Bolte 已提交
5651 5652 5653 5654 5655 5656 5657 5658 5659 5660
                } 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;

5661
#if VBOX_API_VERSION < 4000000
M
Matthias Bolte 已提交
5662 5663
                    rc = machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                                           writable);
5664
#else /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
5665 5666
                    rc = machine->vtbl->CreateSharedFolder(machine, nameUtf16, hostPathUtf16,
                                                           writable, PR_FALSE);
5667
#endif /* VBOX_API_VERSION >= 4000000 */
M
Matthias Bolte 已提交
5668 5669

                    if (NS_FAILED(rc)) {
5670 5671 5672
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("could not attach shared folder '%s', rc=%08x"),
                                       dev->data.fs->dst, (unsigned)rc);
M
Matthias Bolte 已提交
5673 5674 5675 5676 5677 5678
                    } else {
                        ret = 0;
                    }

                    VBOX_UTF16_FREE(nameUtf16);
                    VBOX_UTF16_FREE(hostPathUtf16);
5679
                }
5680 5681
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5682
            }
5683
            VBOX_SESSION_CLOSE();
5684 5685 5686
        }
    }

5687
 cleanup:
5688
    vboxIIDUnalloc(&iid);
5689 5690 5691 5692 5693
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5694 5695
static int vboxDomainAttachDevice(virDomainPtr dom, const char *xml)
{
5696 5697 5698
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

5699 5700 5701 5702 5703 5704
static int
vboxDomainAttachDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

5705
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5706 5707
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
5708 5709 5710
        return -1;
    }

5711 5712 5713 5714
    return vboxDomainAttachDeviceImpl(dom, xml, 0);
}

static int vboxDomainUpdateDeviceFlags(virDomainPtr dom, const char *xml,
5715 5716
                                       unsigned int flags)
{
5717 5718 5719
    virCheckFlags(VIR_DOMAIN_AFFECT_CURRENT |
                  VIR_DOMAIN_AFFECT_LIVE |
                  VIR_DOMAIN_AFFECT_CONFIG, -1);
5720

5721
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5722 5723
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
5724 5725 5726 5727
        return -1;
    }

    return vboxDomainAttachDeviceImpl(dom, xml, 1);
5728 5729
}

5730 5731
static int vboxDomainDetachDevice(virDomainPtr dom, const char *xml)
{
5732
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
5733
    IMachine *machine    = NULL;
5734
    vboxIID iid = VBOX_IID_INITIALIZER;
5735 5736 5737
    PRUint32 state       = MachineState_Null;
    virDomainDefPtr def  = NULL;
    virDomainDeviceDefPtr dev  = NULL;
5738
    nsresult rc;
5739

5740
    if (VIR_ALLOC(def) < 0)
5741 5742
        return ret;

5743
    if (VIR_STRDUP(def->os.type, "hvm") < 0)
5744 5745
        goto cleanup;

5746 5747
    dev = virDomainDeviceDefParse(xml, def, data->caps, data->xmlopt,
                                  VIR_DOMAIN_XML_INACTIVE);
5748
    if (dev == NULL)
5749 5750
        goto cleanup;

5751
    vboxIIDFromUUID(&iid, dom->uuid);
5752
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
5753
    if (NS_FAILED(rc)) {
5754 5755
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
5756 5757
        goto cleanup;
    }
5758

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

5762 5763
        if ((state == MachineState_Running) ||
            (state == MachineState_Paused)) {
5764
            rc = VBOX_SESSION_OPEN_EXISTING(iid.value, machine);
5765
        } else {
5766
            rc = VBOX_SESSION_OPEN(iid.value, machine);
5767
        }
5768

5769 5770 5771 5772
        if (NS_SUCCEEDED(rc)) {
            rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
            if (NS_SUCCEEDED(rc) && machine) {
                if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
5773
#if VBOX_API_VERSION < 3001000
5774 5775
                    int type = virDomainDiskGetType(dev->data.disk);

5776
                    if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM) {
E
Eric Blake 已提交
5777
                        if (type == VIR_STORAGE_TYPE_FILE) {
5778 5779 5780 5781 5782 5783 5784 5785 5786
                            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)) {
5787 5788 5789
                                    virReportError(VIR_ERR_INTERNAL_ERROR,
                                                   _("could not de-attach the mounted ISO, rc=%08x"),
                                                   (unsigned)rc);
5790 5791 5792 5793 5794
                                } else {
                                    ret = 0;
                                }
                                VBOX_RELEASE(dvdDrive);
                            }
E
Eric Blake 已提交
5795
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5796 5797
                        }
                    } else if (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY) {
E
Eric Blake 已提交
5798
                        if (type == VIR_STORAGE_TYPE_FILE) {
5799 5800 5801 5802 5803 5804 5805 5806
                            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);
5807
                                    if (NS_FAILED(rc)) {
5808 5809 5810 5811
                                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                                       _("could not attach the file "
                                                         "to floppy drive, rc=%08x"),
                                                       (unsigned)rc);
5812 5813 5814
                                    } else {
                                        ret = 0;
                                    }
5815 5816 5817 5818 5819
                                } 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;
5820
                                }
5821
                                VBOX_RELEASE(floppyDrive);
5822
                            }
E
Eric Blake 已提交
5823
                        } else if (type == VIR_STORAGE_TYPE_BLOCK) {
5824
                        }
5825
                    }
5826 5827
#else  /* VBOX_API_VERSION >= 3001000 */
#endif /* VBOX_API_VERSION >= 3001000 */
5828 5829 5830 5831
                } 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) {
5832 5833
                        }
                    }
M
Matthias Bolte 已提交
5834 5835 5836 5837 5838 5839 5840 5841 5842
                } 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)) {
5843 5844 5845
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("could not detach shared folder '%s', rc=%08x"),
                                       dev->data.fs->dst, (unsigned)rc);
M
Matthias Bolte 已提交
5846 5847 5848 5849 5850
                    } else {
                        ret = 0;
                    }

                    VBOX_UTF16_FREE(nameUtf16);
5851
                }
5852 5853
                machine->vtbl->SaveSettings(machine);
                VBOX_RELEASE(machine);
5854
            }
5855
            VBOX_SESSION_CLOSE();
5856 5857 5858
        }
    }

5859
 cleanup:
5860
    vboxIIDUnalloc(&iid);
5861 5862 5863 5864 5865
    virDomainDefFree(def);
    virDomainDeviceDefFree(dev);
    return ret;
}

5866 5867 5868 5869 5870 5871
static int
vboxDomainDetachDeviceFlags(virDomainPtr dom, const char *xml,
                            unsigned int flags)
{
    virCheckFlags(VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG, -1);

5872
    if (flags & VIR_DOMAIN_AFFECT_CONFIG) {
5873 5874
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot modify the persistent configuration of a domain"));
5875 5876 5877 5878 5879 5880
        return -1;
    }

    return vboxDomainDetachDevice(dom, xml);
}

J
Jiri Denemark 已提交
5881 5882 5883 5884 5885
static int
vboxDomainSnapshotGetAll(virDomainPtr dom,
                         IMachine *machine,
                         ISnapshot ***snapshots)
{
5886
    vboxIID empty = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
5887 5888 5889 5890 5891 5892 5893 5894
    ISnapshot **list = NULL;
    PRUint32 count;
    nsresult rc;
    unsigned int next;
    unsigned int top;

    rc = machine->vtbl->GetSnapshotCount(machine, &count);
    if (NS_FAILED(rc)) {
5895 5896 5897
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get snapshot count for domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
5898 5899 5900 5901 5902 5903
        goto error;
    }

    if (count == 0)
        goto out;

5904
    if (VIR_ALLOC_N(list, count) < 0)
J
Jiri Denemark 已提交
5905 5906
        goto error;

5907
#if VBOX_API_VERSION < 4000000
5908
    rc = machine->vtbl->GetSnapshot(machine, empty.value, list);
5909
#else /* VBOX_API_VERSION >= 4000000 */
5910
    rc = machine->vtbl->FindSnapshot(machine, empty.value, list);
5911
#endif /* VBOX_API_VERSION >= 4000000 */
J
Jiri Denemark 已提交
5912
    if (NS_FAILED(rc) || !list[0]) {
5913 5914 5915
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get root snapshot for domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
5916 5917 5918 5919 5920 5921
        goto error;
    }

    /* BFS walk through snapshot tree */
    top = 1;
    for (next = 0; next < count; next++) {
5922
        vboxArray children = VBOX_ARRAY_INITIALIZER;
5923
        size_t i;
J
Jiri Denemark 已提交
5924 5925

        if (!list[next]) {
5926 5927
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected number of snapshots < %u"), count);
J
Jiri Denemark 已提交
5928 5929 5930
            goto error;
        }

5931 5932
        rc = vboxArrayGet(&children, list[next],
                               list[next]->vtbl->GetChildren);
J
Jiri Denemark 已提交
5933
        if (NS_FAILED(rc)) {
5934 5935
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get children snapshots"));
J
Jiri Denemark 已提交
5936 5937
            goto error;
        }
5938 5939 5940
        for (i = 0; i < children.count; i++) {
            ISnapshot *child = children.items[i];
            if (!child)
J
Jiri Denemark 已提交
5941 5942
                continue;
            if (top == count) {
5943 5944
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("unexpected number of snapshots > %u"), count);
5945
                vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5946 5947
                goto error;
            }
5948 5949
            VBOX_ADDREF(child);
            list[top++] = child;
J
Jiri Denemark 已提交
5950
        }
5951
        vboxArrayRelease(&children);
J
Jiri Denemark 已提交
5952 5953
    }

5954
 out:
J
Jiri Denemark 已提交
5955 5956 5957
    *snapshots = list;
    return count;

5958
 error:
J
Jiri Denemark 已提交
5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977
    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;
5978
    size_t i;
J
Jiri Denemark 已提交
5979 5980 5981 5982 5983 5984 5985 5986 5987 5988

    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) {
5989 5990
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get snapshot name"));
J
Jiri Denemark 已提交
5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003
            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) {
6004 6005 6006
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("domain %s has no snapshots with name %s"),
                       dom->name, name);
J
Jiri Denemark 已提交
6007 6008 6009
        goto cleanup;
    }

6010
 cleanup:
J
Jiri Denemark 已提交
6011 6012 6013 6014 6015 6016 6017 6018 6019 6020
    if (count > 0) {
        for (i = 0; i < count; i++) {
            if (snapshots[i] != snapshot)
                VBOX_RELEASE(snapshots[i]);
        }
    }
    VIR_FREE(snapshots);
    return snapshot;
}

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
#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]);
6272 6273 6274 6275 6276
            if (parentUuid == NULL) {
                VIR_FREE(readWriteDisk);
                goto cleanup;
            }

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 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 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 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977
            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 已提交
6978 6979 6980
static virDomainSnapshotPtr
vboxDomainSnapshotCreateXML(virDomainPtr dom,
                            const char *xmlDesc,
6981
                            unsigned int flags)
J
Jiri Denemark 已提交
6982 6983 6984
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
    virDomainSnapshotDefPtr def = NULL;
6985
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
6986 6987 6988 6989 6990 6991 6992 6993
    IMachine *machine = NULL;
    IConsole *console = NULL;
    IProgress *progress = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *name = NULL;
    PRUnichar *description = NULL;
    PRUint32 state;
    nsresult rc;
6994
#if VBOX_API_VERSION == 2002000
J
Jiri Denemark 已提交
6995 6996 6997 6998
    nsresult result;
#else
    PRInt32 result;
#endif
6999 7000 7001 7002
#if VBOX_API_VERSION >= 4002000
    bool isCurrent = false;
#endif

J
Jiri Denemark 已提交
7003

7004
    /* VBox has no snapshot metadata, so this flag is trivial.  */
7005 7006 7007
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA |
                  VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                  VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT, NULL);
7008

7009
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, data->caps,
7010 7011 7012
                                                data->xmlopt, -1,
                                                VIR_DOMAIN_SNAPSHOT_PARSE_DISKS |
                                                VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE)))
J
Jiri Denemark 已提交
7013 7014
        goto cleanup;

7015

7016
    vboxIIDFromUUID(&domiid, dom->uuid);
7017
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
7018
    if (NS_FAILED(rc)) {
7019 7020
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7021 7022 7023
        goto cleanup;
    }

7024 7025 7026 7027 7028 7029 7030 7031 7032 7033
#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 已提交
7034 7035
    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
7036 7037
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
7038 7039 7040 7041 7042
        goto cleanup;
    }

    if ((state >= MachineState_FirstOnline)
        && (state <= MachineState_LastOnline)) {
7043
        rc = VBOX_SESSION_OPEN_EXISTING(domiid.value, machine);
J
Jiri Denemark 已提交
7044
    } else {
7045
        rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
7046
    }
7047

J
Jiri Denemark 已提交
7048 7049 7050
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
7051 7052 7053
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072
        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) {
7073 7074
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not take snapshot of domain %s"), dom->name);
J
Jiri Denemark 已提交
7075 7076 7077 7078 7079 7080
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
7081 7082
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not take snapshot of domain %s"), dom->name);
J
Jiri Denemark 已提交
7083 7084 7085 7086 7087
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
7088 7089
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get current snapshot of domain %s"),
J
Jiri Denemark 已提交
7090 7091 7092 7093 7094 7095
                  dom->name);
        goto cleanup;
    }

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

7096
 cleanup:
J
Jiri Denemark 已提交
7097 7098 7099 7100
    VBOX_RELEASE(progress);
    VBOX_UTF16_FREE(description);
    VBOX_UTF16_FREE(name);
    VBOX_RELEASE(console);
7101
    VBOX_SESSION_CLOSE();
J
Jiri Denemark 已提交
7102
    VBOX_RELEASE(machine);
7103
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
7104 7105 7106 7107
    virDomainSnapshotDefFree(def);
    return ret;
}

7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 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
#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;
7180 7181 7182 7183
    for (i = 0; i < def->ndisks; i++) {
        if (VIR_ALLOC(def->disks[i].src) < 0)
            goto cleanup;
    }
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 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281

    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",
7282
                                       _("cannot get medium attachment type"));
7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310
                        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) {
7311 7312 7313 7314 7315
        for (i = 0; i < def->ndisks; i++) {
            VIR_FREE(def->disks[i].src);
        }
        VIR_FREE(def->disks);
        def->ndisks = 0;
7316 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 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388
    }
    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++) {
7389 7390
            virDomainDiskDefPtr diskDef = virDomainDiskDefNew();
            if (!diskDef)
7391
                goto cleanup;
7392
            def->dom->disks[i] = diskDef;
7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
        }
    } 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)
7503
            def->dom->disks[diskCount]->src->readonly = true;
7504 7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524 7525 7526
        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++)
7527
            virDomainDiskDefFree(def->dom->disks[i]);
7528 7529 7530 7531 7532 7533 7534 7535 7536 7537 7538
        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 已提交
7539
static char *
7540 7541
vboxDomainSnapshotGetXMLDesc(virDomainSnapshotPtr snapshot,
                             unsigned int flags)
J
Jiri Denemark 已提交
7542 7543 7544
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, char *, NULL);
7545
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7546 7547 7548 7549 7550 7551 7552 7553 7554 7555
    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];
7556 7557 7558 7559
#if VBOX_API_VERSION >=4002000
    PRUint32 memorySize                 = 0;
    PRUint32 CPUCount                 = 0;
#endif
J
Jiri Denemark 已提交
7560

7561 7562
    virCheckFlags(0, NULL);

7563
    vboxIIDFromUUID(&domiid, dom->uuid);
7564
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
7565
    if (NS_FAILED(rc)) {
7566 7567
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7568 7569 7570 7571 7572 7573
        goto cleanup;
    }

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

7574
    if (VIR_ALLOC(def) < 0 || VIR_ALLOC(def->dom) < 0)
7575
        goto cleanup;
7576 7577
    if (VIR_STRDUP(def->name, snapshot->name) < 0)
        goto cleanup;
J
Jiri Denemark 已提交
7578

7579 7580 7581 7582 7583 7584 7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608
#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 已提交
7609 7610
    rc = snap->vtbl->GetDescription(snap, &str16);
    if (NS_FAILED(rc)) {
7611 7612 7613
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get description of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7614 7615 7616 7617 7618
        goto cleanup;
    }
    if (str16) {
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
7619 7620 7621 7622
        if (VIR_STRDUP(def->description, str8) < 0) {
            VBOX_UTF8_FREE(str8);
            goto cleanup;
        }
J
Jiri Denemark 已提交
7623 7624 7625 7626 7627
        VBOX_UTF8_FREE(str8);
    }

    rc = snap->vtbl->GetTimeStamp(snap, &timestamp);
    if (NS_FAILED(rc)) {
7628 7629 7630
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get creation time of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7631 7632 7633 7634 7635 7636 7637
        goto cleanup;
    }
    /* timestamp is in milliseconds while creationTime in seconds */
    def->creationTime = timestamp / 1000;

    rc = snap->vtbl->GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
7638 7639 7640
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get parent of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7641 7642 7643 7644 7645
        goto cleanup;
    }
    if (parent) {
        rc = parent->vtbl->GetName(parent, &str16);
        if (NS_FAILED(rc) || !str16) {
7646 7647 7648
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not get name of parent of snapshot %s"),
                           snapshot->name);
J
Jiri Denemark 已提交
7649 7650 7651 7652
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(str16, &str8);
        VBOX_UTF16_FREE(str16);
7653 7654
        if (VIR_STRDUP(def->parent, str8) < 0) {
            VBOX_UTF8_FREE(str8);
7655
            goto cleanup;
7656 7657
        }
        VBOX_UTF8_FREE(str8);
J
Jiri Denemark 已提交
7658 7659 7660 7661
    }

    rc = snap->vtbl->GetOnline(snap, &online);
    if (NS_FAILED(rc)) {
7662 7663 7664
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get online state of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
7665 7666 7667 7668 7669 7670 7671 7672
        goto cleanup;
    }
    if (online)
        def->state = VIR_DOMAIN_RUNNING;
    else
        def->state = VIR_DOMAIN_SHUTOFF;

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

7676
 cleanup:
J
Jiri Denemark 已提交
7677 7678 7679 7680
    virDomainSnapshotDefFree(def);
    VBOX_RELEASE(parent);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
7681
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
7682 7683 7684 7685 7686
    return ret;
}

static int
vboxDomainSnapshotNum(virDomainPtr dom,
7687
                      unsigned int flags)
J
Jiri Denemark 已提交
7688 7689
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7690
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7691 7692 7693 7694
    IMachine *machine = NULL;
    nsresult rc;
    PRUint32 snapshotCount;

7695 7696
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA, -1);
7697

7698
    vboxIIDFromUUID(&iid, dom->uuid);
7699
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
7700
    if (NS_FAILED(rc)) {
7701 7702
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7703 7704 7705
        goto cleanup;
    }

7706 7707 7708 7709 7710 7711
    /* VBox snapshots do not require libvirt to maintain any metadata.  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        ret = 0;
        goto cleanup;
    }

J
Jiri Denemark 已提交
7712 7713
    rc = machine->vtbl->GetSnapshotCount(machine, &snapshotCount);
    if (NS_FAILED(rc)) {
7714 7715 7716
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get snapshot count for domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
7717 7718 7719
        goto cleanup;
    }

7720 7721 7722 7723 7724
    /* VBox has at most one root snapshot.  */
    if (snapshotCount && (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS))
        ret = 1;
    else
        ret = snapshotCount;
J
Jiri Denemark 已提交
7725

7726
 cleanup:
J
Jiri Denemark 已提交
7727
    VBOX_RELEASE(machine);
7728
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7729 7730 7731 7732 7733 7734 7735
    return ret;
}

static int
vboxDomainSnapshotListNames(virDomainPtr dom,
                            char **names,
                            int nameslen,
7736
                            unsigned int flags)
J
Jiri Denemark 已提交
7737 7738
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7739
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7740 7741 7742 7743
    IMachine *machine = NULL;
    nsresult rc;
    ISnapshot **snapshots = NULL;
    int count = 0;
7744
    size_t i;
J
Jiri Denemark 已提交
7745

7746 7747
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_LIST_ROOTS |
                  VIR_DOMAIN_SNAPSHOT_LIST_METADATA, -1);
7748

7749
    vboxIIDFromUUID(&iid, dom->uuid);
7750
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
7751
    if (NS_FAILED(rc)) {
7752 7753
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7754 7755 7756
        goto cleanup;
    }

7757 7758 7759 7760 7761
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA) {
        ret = 0;
        goto cleanup;
    }

7762 7763 7764
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS) {
        vboxIID empty = VBOX_IID_INITIALIZER;

7765
        if (VIR_ALLOC_N(snapshots, 1) < 0)
7766
            goto cleanup;
7767
#if VBOX_API_VERSION < 4000000
7768
        rc = machine->vtbl->GetSnapshot(machine, empty.value, snapshots);
7769
#else /* VBOX_API_VERSION >= 4000000 */
7770
        rc = machine->vtbl->FindSnapshot(machine, empty.value, snapshots);
7771
#endif /* VBOX_API_VERSION >= 4000000 */
7772
        if (NS_FAILED(rc) || !snapshots[0]) {
7773 7774 7775
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not get root snapshot for domain %s"),
                           dom->name);
7776 7777 7778 7779 7780 7781 7782
            goto cleanup;
        }
        count = 1;
    } else {
        if ((count = vboxDomainSnapshotGetAll(dom, machine, &snapshots)) < 0)
            goto cleanup;
    }
J
Jiri Denemark 已提交
7783 7784 7785 7786 7787 7788 7789 7790 7791 7792

    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) {
7793 7794
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("could not get snapshot name"));
J
Jiri Denemark 已提交
7795 7796 7797 7798
            goto cleanup;
        }
        VBOX_UTF16_TO_UTF8(nameUtf16, &name);
        VBOX_UTF16_FREE(nameUtf16);
7799 7800
        if (VIR_STRDUP(names[i], name) < 0) {
            VBOX_UTF8_FREE(name);
J
Jiri Denemark 已提交
7801 7802
            goto cleanup;
        }
7803
        VBOX_UTF8_FREE(name);
J
Jiri Denemark 已提交
7804 7805 7806 7807 7808 7809 7810
    }

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

7811
 cleanup:
J
Jiri Denemark 已提交
7812 7813 7814 7815 7816 7817
    if (count > 0) {
        for (i = 0; i < count; i++)
            VBOX_RELEASE(snapshots[i]);
    }
    VIR_FREE(snapshots);
    VBOX_RELEASE(machine);
7818
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7819 7820 7821 7822 7823 7824
    return ret;
}

static virDomainSnapshotPtr
vboxDomainSnapshotLookupByName(virDomainPtr dom,
                               const char *name,
7825
                               unsigned int flags)
J
Jiri Denemark 已提交
7826 7827
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
7828
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7829 7830 7831 7832
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

7833 7834
    virCheckFlags(0, NULL);

7835
    vboxIIDFromUUID(&iid, dom->uuid);
7836
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
J
Jiri Denemark 已提交
7837
    if (NS_FAILED(rc)) {
7838 7839
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7840 7841 7842 7843 7844 7845 7846 7847
        goto cleanup;
    }

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

    ret = virGetDomainSnapshot(dom, name);

7848
 cleanup:
J
Jiri Denemark 已提交
7849 7850
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
7851
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7852 7853 7854 7855 7856
    return ret;
}

static int
vboxDomainHasCurrentSnapshot(virDomainPtr dom,
7857
                             unsigned int flags)
J
Jiri Denemark 已提交
7858 7859
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
7860
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7861 7862 7863 7864
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    nsresult rc;

7865 7866
    virCheckFlags(0, -1);

7867
    vboxIIDFromUUID(&iid, dom->uuid);
7868
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
7869
    if (NS_FAILED(rc)) {
7870 7871
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7872 7873 7874 7875 7876
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
7877 7878
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
J
Jiri Denemark 已提交
7879 7880 7881 7882 7883 7884 7885 7886
        goto cleanup;
    }

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

7887
 cleanup:
J
Jiri Denemark 已提交
7888
    VBOX_RELEASE(machine);
7889
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
7890 7891 7892
    return ret;
}

7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907 7908 7909 7910 7911
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)) {
7912 7913
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
7914 7915 7916 7917 7918 7919 7920 7921
        goto cleanup;
    }

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

    rc = snap->vtbl->GetParent(snap, &parent);
    if (NS_FAILED(rc)) {
7922 7923 7924
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get parent of snapshot %s"),
                       snapshot->name);
7925 7926 7927
        goto cleanup;
    }
    if (!parent) {
7928 7929 7930
        virReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
                       _("snapshot '%s' does not have a parent"),
                       snapshot->name);
7931 7932 7933 7934 7935
        goto cleanup;
    }

    rc = parent->vtbl->GetName(parent, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
7936 7937 7938
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get name of parent of snapshot %s"),
                       snapshot->name);
7939 7940 7941 7942 7943 7944 7945 7946 7947 7948
        goto cleanup;
    }
    VBOX_UTF16_TO_UTF8(nameUtf16, &name);
    if (!name) {
        virReportOOMError();
        goto cleanup;
    }

    ret = virGetDomainSnapshot(dom, name);

7949
 cleanup:
7950 7951 7952 7953 7954 7955 7956 7957 7958
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snap);
    VBOX_RELEASE(parent);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}

J
Jiri Denemark 已提交
7959 7960
static virDomainSnapshotPtr
vboxDomainSnapshotCurrent(virDomainPtr dom,
7961
                          unsigned int flags)
J
Jiri Denemark 已提交
7962 7963
{
    VBOX_OBJECT_CHECK(dom->conn, virDomainSnapshotPtr, NULL);
7964
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
7965 7966 7967 7968 7969 7970
    IMachine *machine = NULL;
    ISnapshot *snapshot = NULL;
    PRUnichar *nameUtf16 = NULL;
    char *name = NULL;
    nsresult rc;

7971 7972
    virCheckFlags(0, NULL);

7973
    vboxIIDFromUUID(&iid, dom->uuid);
7974
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
7975
    if (NS_FAILED(rc)) {
7976 7977
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
7978 7979 7980 7981 7982
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &snapshot);
    if (NS_FAILED(rc)) {
7983 7984
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
J
Jiri Denemark 已提交
7985 7986 7987 7988
        goto cleanup;
    }

    if (!snapshot) {
7989 7990
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain has no snapshots"));
J
Jiri Denemark 已提交
7991 7992 7993 7994 7995
        goto cleanup;
    }

    rc = snapshot->vtbl->GetName(snapshot, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
7996 7997
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot name"));
J
Jiri Denemark 已提交
7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008
        goto cleanup;
    }

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

    ret = virGetDomainSnapshot(dom, name);

8009
 cleanup:
J
Jiri Denemark 已提交
8010 8011 8012 8013
    VBOX_UTF8_FREE(name);
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(snapshot);
    VBOX_RELEASE(machine);
8014
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
8015 8016 8017
    return ret;
}

8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036
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)) {
8037 8038
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
8039 8040 8041 8042 8043 8044 8045 8046
        goto cleanup;
    }

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

    rc = machine->vtbl->GetCurrentSnapshot(machine, &current);
    if (NS_FAILED(rc)) {
8047 8048
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot"));
8049 8050 8051 8052 8053 8054 8055 8056 8057
        goto cleanup;
    }
    if (!current) {
        ret = 0;
        goto cleanup;
    }

    rc = current->vtbl->GetName(current, &nameUtf16);
    if (NS_FAILED(rc) || !nameUtf16) {
8058 8059
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get current snapshot name"));
8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070
        goto cleanup;
    }

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

    ret = STREQ(snapshot->name, name);

8071
 cleanup:
8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096
    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)) {
8097 8098
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
8099 8100 8101 8102 8103 8104 8105 8106 8107
        goto cleanup;
    }

    /* Check that snapshot exists.  If so, there is no metadata.  */
    if (!(snap = vboxDomainSnapshotGet(data, dom, machine, snapshot->name)))
        goto cleanup;

    ret = 0;

8108
 cleanup:
8109 8110 8111 8112 8113 8114
    VBOX_RELEASE(snap);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}

8115
#if VBOX_API_VERSION < 3001000
J
Jiri Denemark 已提交
8116 8117 8118 8119 8120 8121
static int
vboxDomainSnapshotRestore(virDomainPtr dom,
                          IMachine *machine,
                          ISnapshot *snapshot)
{
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
8122
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8123 8124
    nsresult rc;

8125 8126
    rc = snapshot->vtbl->GetId(snapshot, &iid.value);
    if (NS_FAILED(rc)) {
8127 8128
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get snapshot UUID"));
J
Jiri Denemark 已提交
8129 8130 8131
        goto cleanup;
    }

8132
    rc = machine->vtbl->SetCurrentSnapshot(machine, iid.value);
J
Jiri Denemark 已提交
8133
    if (NS_FAILED(rc)) {
8134 8135
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not restore snapshot for domain %s"), dom->name);
J
Jiri Denemark 已提交
8136 8137 8138 8139 8140
        goto cleanup;
    }

    ret = 0;

8141
 cleanup:
8142
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
8143 8144 8145 8146 8147 8148 8149 8150 8151 8152 8153 8154 8155 8156
    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;
8157
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8158

8159 8160
    rc = machine->vtbl->GetId(machine, &domiid.value);
    if (NS_FAILED(rc)) {
8161 8162
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain UUID"));
J
Jiri Denemark 已提交
8163 8164 8165 8166 8167
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
8168 8169
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
8170 8171 8172 8173 8174
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
8175 8176
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("domain %s is already running"), dom->name);
J
Jiri Denemark 已提交
8177 8178 8179
        goto cleanup;
    }

8180
    rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
8181 8182 8183
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
8184 8185 8186
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
8187 8188 8189 8190 8191 8192
        goto cleanup;
    }

    rc = console->vtbl->RestoreSnapshot(console, snapshot, &progress);
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
8193 8194
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot restore domain snapshot for running domain"));
J
Jiri Denemark 已提交
8195
        } else {
8196 8197 8198
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("could not restore snapshot for domain %s"),
                           dom->name);
J
Jiri Denemark 已提交
8199 8200 8201 8202 8203 8204 8205
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
8206 8207
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not restore snapshot for domain %s"), dom->name);
J
Jiri Denemark 已提交
8208 8209 8210 8211 8212
        goto cleanup;
    }

    ret = 0;

8213
 cleanup:
J
Jiri Denemark 已提交
8214 8215
    VBOX_RELEASE(progress);
    VBOX_RELEASE(console);
8216
    VBOX_SESSION_CLOSE();
8217
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
8218 8219 8220 8221 8222 8223
    return ret;
}
#endif

static int
vboxDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
8224
                           unsigned int flags)
J
Jiri Denemark 已提交
8225 8226 8227
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
8228
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8229 8230 8231 8232 8233 8234 8235
    IMachine *machine = NULL;
    ISnapshot *newSnapshot = NULL;
    ISnapshot *prevSnapshot = NULL;
    PRBool online = PR_FALSE;
    PRUint32 state;
    nsresult rc;

8236 8237
    virCheckFlags(0, -1);

8238
    vboxIIDFromUUID(&domiid, dom->uuid);
8239
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
8240
    if (NS_FAILED(rc)) {
8241 8242
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
8243 8244 8245 8246 8247 8248 8249 8250 8251
        goto cleanup;
    }

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

    rc = newSnapshot->vtbl->GetOnline(newSnapshot, &online);
    if (NS_FAILED(rc)) {
8252 8253 8254
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get online state of snapshot %s"),
                       snapshot->name);
J
Jiri Denemark 已提交
8255 8256 8257 8258 8259
        goto cleanup;
    }

    rc = machine->vtbl->GetCurrentSnapshot(machine, &prevSnapshot);
    if (NS_FAILED(rc)) {
8260 8261 8262
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get current snapshot of domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
8263 8264 8265 8266 8267
        goto cleanup;
    }

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
8268 8269
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
8270 8271 8272 8273 8274
        goto cleanup;
    }

    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
8275 8276
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot revert snapshot of running domain"));
J
Jiri Denemark 已提交
8277 8278 8279 8280 8281 8282 8283 8284 8285 8286 8287 8288 8289
        goto cleanup;
    }

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

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

8290
 cleanup:
J
Jiri Denemark 已提交
8291 8292
    VBOX_RELEASE(prevSnapshot);
    VBOX_RELEASE(newSnapshot);
8293
    vboxIIDUnalloc(&domiid);
J
Jiri Denemark 已提交
8294 8295 8296 8297 8298 8299 8300 8301 8302
    return ret;
}

static int
vboxDomainSnapshotDeleteSingle(vboxGlobalData *data,
                               IConsole *console,
                               ISnapshot *snapshot)
{
    IProgress *progress = NULL;
8303
    vboxIID iid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8304 8305
    int ret = -1;
    nsresult rc;
8306
#if VBOX_API_VERSION == 2002000
J
Jiri Denemark 已提交
8307 8308 8309 8310 8311
    nsresult result;
#else
    PRInt32 result;
#endif

8312 8313
    rc = snapshot->vtbl->GetId(snapshot, &iid.value);
    if (NS_FAILED(rc)) {
8314 8315
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get snapshot UUID"));
J
Jiri Denemark 已提交
8316 8317 8318
        goto cleanup;
    }

8319
#if VBOX_API_VERSION < 3001000
8320
    rc = console->vtbl->DiscardSnapshot(console, iid.value, &progress);
J
Jiri Denemark 已提交
8321
#else
8322
    rc = console->vtbl->DeleteSnapshot(console, iid.value, &progress);
J
Jiri Denemark 已提交
8323 8324 8325
#endif
    if (NS_FAILED(rc) || !progress) {
        if (rc == VBOX_E_INVALID_VM_STATE) {
8326 8327
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot delete domain snapshot for running domain"));
J
Jiri Denemark 已提交
8328
        } else {
8329 8330
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("could not delete snapshot"));
J
Jiri Denemark 已提交
8331 8332 8333 8334 8335 8336 8337
        }
        goto cleanup;
    }

    progress->vtbl->WaitForCompletion(progress, -1);
    progress->vtbl->GetResultCode(progress, &result);
    if (NS_FAILED(result)) {
8338 8339
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not delete snapshot"));
J
Jiri Denemark 已提交
8340 8341 8342 8343 8344
        goto cleanup;
    }

    ret = 0;

8345
 cleanup:
J
Jiri Denemark 已提交
8346
    VBOX_RELEASE(progress);
8347
    vboxIIDUnalloc(&iid);
J
Jiri Denemark 已提交
8348 8349 8350 8351 8352 8353 8354 8355
    return ret;
}

static int
vboxDomainSnapshotDeleteTree(vboxGlobalData *data,
                             IConsole *console,
                             ISnapshot *snapshot)
{
8356
    vboxArray children = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
8357 8358
    int ret = -1;
    nsresult rc;
8359
    size_t i;
J
Jiri Denemark 已提交
8360

8361
    rc = vboxArrayGet(&children, snapshot, snapshot->vtbl->GetChildren);
J
Jiri Denemark 已提交
8362
    if (NS_FAILED(rc)) {
8363 8364
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get children snapshots"));
J
Jiri Denemark 已提交
8365 8366 8367
        goto cleanup;
    }

8368 8369 8370
    for (i = 0; i < children.count; i++) {
        if (vboxDomainSnapshotDeleteTree(data, console, children.items[i]))
            goto cleanup;
J
Jiri Denemark 已提交
8371 8372 8373 8374
    }

    ret = vboxDomainSnapshotDeleteSingle(data, console, snapshot);

8375
 cleanup:
8376
    vboxArrayRelease(&children);
J
Jiri Denemark 已提交
8377 8378 8379
    return ret;
}

8380 8381 8382 8383 8384 8385 8386 8387 8388 8389 8390 8391 8392 8393 8394 8395 8396 8397 8398 8399
#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);
8400
    virDomainSnapshotDefPtr def = NULL;
8401 8402 8403 8404 8405 8406 8407 8408 8409 8410 8411 8412 8413 8414 8415
    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;
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 8574 8575 8576 8577 8578 8579 8580 8581 8582 8583 8584 8585 8586 8587 8588 8589 8590 8591
    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);
8592
                    VIR_FREE(disk);
8593 8594 8595 8596 8597 8598
                    goto cleanup;
                }
                VBOX_UTF16_TO_UTF8(uuidUtf16, &uuid);
                disk->uuid = uuid;
                VBOX_UTF16_FREE(uuidUtf16);

8599 8600
                if (VIR_STRDUP(disk->location, newLocationUtf8) < 0) {
                    VIR_FREE(disk);
8601
                    goto cleanup;
8602
                }
8603 8604 8605 8606 8607 8608 8609 8610 8611 8612 8613 8614 8615 8616 8617 8618 8619 8620 8621 8622 8623 8624 8625 8626 8627 8628 8629 8630 8631 8632 8633 8634 8635 8636 8637 8638 8639 8640 8641 8642 8643 8644 8645 8646 8647 8648 8649 8650 8651 8652 8653 8654 8655 8656 8657 8658 8659 8660 8661 8662 8663 8664 8665 8666 8667 8668 8669 8670 8671 8672 8673 8674 8675 8676 8677 8678 8679 8680 8681 8682 8683 8684 8685 8686 8687 8688 8689 8690 8691 8692 8693 8694 8695 8696 8697 8698 8699 8700 8701 8702 8703 8704 8705 8706 8707 8708 8709 8710 8711 8712 8713 8714 8715 8716 8717 8718 8719 8720 8721 8722 8723 8724 8725 8726 8727 8728 8729 8730 8731 8732 8733 8734 8735 8736 8737 8738 8739 8740 8741 8742 8743 8744 8745 8746 8747 8748 8749 8750 8751 8752 8753 8754 8755 8756 8757 8758 8759 8760 8761 8762 8763 8764 8765 8766 8767 8768 8769 8770 8771 8772 8773 8774 8775 8776 8777 8778 8779 8780 8781 8782 8783 8784 8785 8786 8787 8788 8789 8790 8791 8792 8793 8794 8795 8796 8797 8798 8799 8800 8801 8802 8803 8804 8805 8806 8807 8808 8809 8810 8811 8812 8813 8814 8815 8816 8817 8818 8819 8820 8821 8822 8823 8824 8825 8826 8827 8828 8829 8830 8831 8832 8833 8834

                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
8835

J
Jiri Denemark 已提交
8836 8837 8838 8839 8840 8841
static int
vboxDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
                         unsigned int flags)
{
    virDomainPtr dom = snapshot->domain;
    VBOX_OBJECT_CHECK(dom->conn, int, -1);
8842
    vboxIID domiid = VBOX_IID_INITIALIZER;
J
Jiri Denemark 已提交
8843 8844 8845 8846 8847
    IMachine *machine = NULL;
    ISnapshot *snap = NULL;
    IConsole *console = NULL;
    PRUint32 state;
    nsresult rc;
8848
    vboxArray snapChildren = VBOX_ARRAY_INITIALIZER;
J
Jiri Denemark 已提交
8849

8850 8851
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN |
                  VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY, -1);
8852

8853
    vboxIIDFromUUID(&domiid, dom->uuid);
8854
    rc = VBOX_OBJECT_GET_MACHINE(domiid.value, &machine);
J
Jiri Denemark 已提交
8855
    if (NS_FAILED(rc)) {
8856 8857
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching UUID"));
J
Jiri Denemark 已提交
8858 8859 8860 8861 8862 8863 8864 8865 8866
        goto cleanup;
    }

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

    rc = machine->vtbl->GetState(machine, &state);
    if (NS_FAILED(rc)) {
8867 8868
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not get domain state"));
J
Jiri Denemark 已提交
8869 8870 8871
        goto cleanup;
    }

8872 8873 8874
    /* In case we just want to delete the metadata, we will edit the vbox file in order
     *to remove the node concerning the snapshot
    */
8875
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY) {
8876 8877 8878 8879 8880 8881 8882 8883 8884 8885 8886 8887 8888 8889 8890
        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
        }
8891 8892 8893
        goto cleanup;
    }

J
Jiri Denemark 已提交
8894 8895
    if (state >= MachineState_FirstOnline
        && state <= MachineState_LastOnline) {
8896 8897
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot delete snapshots of running domain"));
J
Jiri Denemark 已提交
8898 8899 8900
        goto cleanup;
    }

8901
    rc = VBOX_SESSION_OPEN(domiid.value, machine);
J
Jiri Denemark 已提交
8902 8903 8904
    if (NS_SUCCEEDED(rc))
        rc = data->vboxSession->vtbl->GetConsole(data->vboxSession, &console);
    if (NS_FAILED(rc)) {
8905 8906 8907
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not open VirtualBox session with domain %s"),
                       dom->name);
J
Jiri Denemark 已提交
8908 8909 8910 8911 8912 8913 8914 8915
        goto cleanup;
    }

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

8916
 cleanup:
J
Jiri Denemark 已提交
8917 8918
    VBOX_RELEASE(console);
    VBOX_RELEASE(snap);
8919
    vboxIIDUnalloc(&domiid);
8920
    VBOX_SESSION_CLOSE();
J
Jiri Denemark 已提交
8921 8922 8923
    return ret;
}

8924
#if VBOX_API_VERSION <= 2002000 || VBOX_API_VERSION >= 4000000
8925
    /* No Callback support for VirtualBox 2.2.* series */
8926
    /* No Callback support for VirtualBox 4.* series */
8927
#else /* !(VBOX_API_VERSION == 2002000 || VBOX_API_VERSION >= 4000000) */
8928 8929

/* Functions needed for Callbacks */
8930
static nsresult PR_COM_METHOD
8931
vboxCallbackOnMachineStateChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8932 8933
                                 PRUnichar *machineId, PRUint32 state)
{
8934 8935 8936 8937 8938 8939
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

    vboxDriverLock(g_pVBoxGlobalData);

8940
    VIR_DEBUG("IVirtualBoxCallback: %p, State: %d", pThis, state);
8941 8942 8943 8944 8945 8946 8947
    DEBUGPRUnichar("machineId", machineId);

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

        g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(machineId, &machineIdUtf8);
8948
        ignore_value(virUUIDParse(machineIdUtf8, uuid));
8949 8950 8951

        dom = vboxDomainLookupByUUID(g_pVBoxGlobalData->conn, uuid);
        if (dom) {
8952
            virObjectEventPtr ev;
8953 8954 8955 8956 8957 8958 8959 8960 8961 8962 8963 8964 8965 8966 8967 8968 8969 8970 8971 8972 8973 8974 8975 8976 8977 8978 8979 8980 8981 8982

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

8983
            ev = virDomainEventLifecycleNewFromDom(dom, event, detail);
8984

8985
            if (ev)
8986
                virObjectEventStateQueue(g_pVBoxGlobalData->domainEvents, ev);
8987 8988 8989 8990 8991 8992 8993 8994
        }
    }

    vboxDriverUnlock(g_pVBoxGlobalData);

    return NS_OK;
}

8995
static nsresult PR_COM_METHOD
8996
vboxCallbackOnMachineDataChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
8997 8998
                                PRUnichar *machineId)
{
8999
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
9000 9001 9002 9003 9004
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

9005
static nsresult PR_COM_METHOD
9006
vboxCallbackOnExtraDataCanChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
9007 9008 9009
                                 PRUnichar *machineId, PRUnichar *key,
                                 PRUnichar *value,
                                 PRUnichar **error ATTRIBUTE_UNUSED,
9010
                                 PRBool *allowChange ATTRIBUTE_UNUSED)
9011
{
9012
    VIR_DEBUG("IVirtualBoxCallback: %p, allowChange: %s", pThis, *allowChange ? "true" : "false");
9013 9014 9015 9016 9017 9018 9019
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

9020
static nsresult PR_COM_METHOD
9021 9022
vboxCallbackOnExtraDataChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                              PRUnichar *machineId,
9023 9024
                              PRUnichar *key, PRUnichar *value)
{
9025
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
9026 9027 9028 9029 9030 9031 9032
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("key", key);
    DEBUGPRUnichar("value", value);

    return NS_OK;
}

9033
# if VBOX_API_VERSION < 3001000
9034
static nsresult PR_COM_METHOD
9035 9036 9037 9038
vboxCallbackOnMediaRegistered(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                              PRUnichar *mediaId,
                              PRUint32 mediaType ATTRIBUTE_UNUSED,
                              PRBool registered ATTRIBUTE_UNUSED)
9039
{
9040 9041
    VIR_DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
    VIR_DEBUG("mediaType: %d", mediaType);
9042 9043 9044 9045
    DEBUGPRUnichar("mediaId", mediaId);

    return NS_OK;
}
9046 9047
# else  /* VBOX_API_VERSION >= 3001000 */
# endif /* VBOX_API_VERSION >= 3001000 */
9048

9049
static nsresult PR_COM_METHOD
9050
vboxCallbackOnMachineRegistered(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
9051 9052
                                PRUnichar *machineId, PRBool registered)
{
9053 9054 9055 9056 9057 9058
    virDomainPtr dom = NULL;
    int event        = 0;
    int detail       = 0;

    vboxDriverLock(g_pVBoxGlobalData);

9059
    VIR_DEBUG("IVirtualBoxCallback: %p, registered: %s", pThis, registered ? "true" : "false");
9060 9061 9062 9063 9064 9065 9066
    DEBUGPRUnichar("machineId", machineId);

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

        g_pVBoxGlobalData->pFuncs->pfnUtf16ToUtf8(machineId, &machineIdUtf8);
9067
        ignore_value(virUUIDParse(machineIdUtf8, uuid));
9068 9069 9070

        dom = vboxDomainLookupByUUID(g_pVBoxGlobalData->conn, uuid);
        if (dom) {
9071
            virObjectEventPtr ev;
9072 9073

            /* CURRENT LIMITATION: we never get the VIR_DOMAIN_EVENT_UNDEFINED
J
Ján Tomko 已提交
9074
             * event because the when the machine is de-registered the call
9075 9076 9077 9078 9079 9080 9081 9082 9083 9084 9085 9086
             * 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;
            }

9087
            ev = virDomainEventLifecycleNewFromDom(dom, event, detail);
9088

9089
            if (ev)
9090
                virObjectEventStateQueue(g_pVBoxGlobalData->domainEvents, ev);
9091 9092 9093 9094 9095 9096 9097 9098
        }
    }

    vboxDriverUnlock(g_pVBoxGlobalData);

    return NS_OK;
}

9099
static nsresult PR_COM_METHOD
9100 9101 9102
vboxCallbackOnSessionStateChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                                 PRUnichar *machineId,
                                 PRUint32 state ATTRIBUTE_UNUSED)
9103
{
9104
    VIR_DEBUG("IVirtualBoxCallback: %p, state: %d", pThis, state);
9105 9106 9107 9108 9109
    DEBUGPRUnichar("machineId", machineId);

    return NS_OK;
}

9110
static nsresult PR_COM_METHOD
9111 9112
vboxCallbackOnSnapshotTaken(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                            PRUnichar *machineId,
9113 9114
                            PRUnichar *snapshotId)
{
9115
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
9116 9117 9118 9119 9120 9121
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

9122
static nsresult PR_COM_METHOD
9123 9124
vboxCallbackOnSnapshotDiscarded(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                                PRUnichar *machineId,
9125 9126
                                PRUnichar *snapshotId)
{
9127
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
9128 9129 9130 9131 9132 9133
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

9134
static nsresult PR_COM_METHOD
9135 9136
vboxCallbackOnSnapshotChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
                             PRUnichar *machineId,
9137 9138
                             PRUnichar *snapshotId)
{
9139
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
9140 9141 9142 9143 9144 9145
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("snapshotId", snapshotId);

    return NS_OK;
}

9146
static nsresult PR_COM_METHOD
9147
vboxCallbackOnGuestPropertyChange(IVirtualBoxCallback *pThis ATTRIBUTE_UNUSED,
9148 9149 9150
                                  PRUnichar *machineId, PRUnichar *name,
                                  PRUnichar *value, PRUnichar *flags)
{
9151
    VIR_DEBUG("IVirtualBoxCallback: %p", pThis);
9152 9153 9154 9155 9156 9157 9158 9159
    DEBUGPRUnichar("machineId", machineId);
    DEBUGPRUnichar("name", name);
    DEBUGPRUnichar("value", value);
    DEBUGPRUnichar("flags", flags);

    return NS_OK;
}

9160
static nsresult PR_COM_METHOD
9161
vboxCallbackAddRef(nsISupports *pThis ATTRIBUTE_UNUSED)
9162
{
9163 9164 9165 9166
    nsresult c;

    c = ++g_pVBoxGlobalData->vboxCallBackRefCount;

9167
    VIR_DEBUG("pThis: %p, vboxCallback AddRef: %d", pThis, c);
9168 9169 9170 9171

    return c;
}

9172 9173 9174
static nsresult PR_COM_METHOD
vboxCallbackRelease(nsISupports *pThis)
{
9175 9176 9177 9178 9179 9180 9181 9182 9183
    nsresult c;

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

9184
    VIR_DEBUG("pThis: %p, vboxCallback Release: %d", pThis, c);
9185 9186 9187 9188

    return c;
}

9189 9190 9191
static nsresult PR_COM_METHOD
vboxCallbackQueryInterface(nsISupports *pThis, const nsID *iid, void **resultp)
{
9192 9193 9194 9195 9196
    IVirtualBoxCallback *that = (IVirtualBoxCallback *)pThis;
    static const nsID ivirtualboxCallbackUUID = IVIRTUALBOXCALLBACK_IID;
    static const nsID isupportIID = NS_ISUPPORTS_IID;

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

9202
        VIR_DEBUG("pThis: %p, vboxCallback QueryInterface: %d", pThis, g_pVBoxGlobalData->vboxCallBackRefCount);
9203 9204 9205 9206 9207

        return NS_OK;
    }


9208
    VIR_DEBUG("pThis: %p, vboxCallback QueryInterface didn't find a matching interface", pThis);
9209 9210 9211 9212 9213 9214
    DEBUGUUID("The UUID Callback Interface expects", iid);
    DEBUGUUID("The UUID Callback Interface got", &ivirtualboxCallbackUUID);
    return NS_NOINTERFACE;
}


9215
static IVirtualBoxCallback *vboxAllocCallbackObj(void) {
9216 9217
    IVirtualBoxCallback *vboxCallback = NULL;

9218
    /* Allocate, Initialize and return a valid
9219 9220 9221
     * IVirtualBoxCallback object here
     */
    if ((VIR_ALLOC(vboxCallback) < 0) || (VIR_ALLOC(vboxCallback->vtbl) < 0)) {
9222
        VIR_FREE(vboxCallback);
9223 9224 9225 9226 9227 9228 9229 9230 9231 9232 9233
        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;
9234
# if VBOX_API_VERSION < 3001000
9235
        vboxCallback->vtbl->OnMediaRegistered           = &vboxCallbackOnMediaRegistered;
9236 9237
# else  /* VBOX_API_VERSION >= 3001000 */
# endif /* VBOX_API_VERSION >= 3001000 */
9238 9239 9240
        vboxCallback->vtbl->OnMachineRegistered         = &vboxCallbackOnMachineRegistered;
        vboxCallback->vtbl->OnSessionStateChange        = &vboxCallbackOnSessionStateChange;
        vboxCallback->vtbl->OnSnapshotTaken             = &vboxCallbackOnSnapshotTaken;
9241
# if VBOX_API_VERSION < 3002000
9242
        vboxCallback->vtbl->OnSnapshotDiscarded         = &vboxCallbackOnSnapshotDiscarded;
9243
# else /* VBOX_API_VERSION >= 3002000 */
9244
        vboxCallback->vtbl->OnSnapshotDeleted           = &vboxCallbackOnSnapshotDiscarded;
9245
# endif /* VBOX_API_VERSION >= 3002000 */
9246 9247 9248 9249 9250 9251 9252 9253 9254 9255 9256 9257
        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,
9258 9259
                             void *opaque ATTRIBUTE_UNUSED)
{
9260 9261 9262 9263 9264 9265 9266 9267 9268 9269 9270 9271
    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);
    }
}

9272 9273 9274 9275 9276 9277
static int
vboxConnectDomainEventRegister(virConnectPtr conn,
                               virConnectDomainEventCallback callback,
                               void *opaque,
                               virFreeCallback freecb)
{
9278
    VBOX_OBJECT_CHECK(conn, int, -1);
9279
    int vboxRet          = -1;
9280
    nsresult rc;
9281 9282 9283 9284 9285 9286

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

9287
    if (data->vboxCallback == NULL) {
9288
        data->vboxCallback = vboxAllocCallbackObj();
9289 9290 9291 9292
        if (data->vboxCallback != NULL) {
            rc = data->vboxObj->vtbl->RegisterCallback(data->vboxObj, data->vboxCallback);
            if (NS_SUCCEEDED(rc)) {
                vboxRet = 0;
9293 9294
            }
        }
9295 9296 9297
    } else {
        vboxRet = 0;
    }
9298

9299 9300 9301 9302 9303 9304 9305
    /* 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);
9306

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

9310 9311 9312 9313 9314
        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
             */
9315

9316
            ret = virDomainEventStateRegister(conn, data->domainEvents,
9317
                                              callback, opaque, freecb);
9318
            VIR_DEBUG("virObjectEventStateRegister (ret = %d) (conn: %p, "
9319
                      "callback: %p, opaque: %p, "
9320
                      "freecb: %p)", ret, conn, callback,
9321
                      opaque, freecb);
9322 9323 9324 9325 9326 9327
        }
    }

    vboxDriverUnlock(data);

    if (ret >= 0) {
9328
        return 0;
9329 9330 9331 9332 9333 9334 9335 9336
    } else {
        if (data->vboxObj && data->vboxCallback) {
            data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        }
        return -1;
    }
}

9337 9338 9339 9340
static int
vboxConnectDomainEventDeregister(virConnectPtr conn,
                                 virConnectDomainEventCallback callback)
{
9341
    VBOX_OBJECT_CHECK(conn, int, -1);
9342
    int cnt;
9343 9344 9345 9346 9347 9348

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

9349 9350
    cnt = virDomainEventStateDeregister(conn, data->domainEvents,
                                        callback);
9351

9352 9353 9354
    if (data->vboxCallback && cnt == 0) {
        data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        VBOX_RELEASE(data->vboxCallback);
9355

9356 9357 9358
        /* Remove the Event file handle on which we are listening as well */
        virEventRemoveHandle(data->fdWatch);
        data->fdWatch = -1;
9359 9360 9361 9362
    }

    vboxDriverUnlock(data);

9363 9364 9365
    if (cnt >= 0)
        ret = 0;

9366 9367 9368
    return ret;
}

9369 9370 9371 9372 9373
static int vboxConnectDomainEventRegisterAny(virConnectPtr conn,
                                             virDomainPtr dom,
                                             int eventID,
                                             virConnectDomainEventGenericCallback callback,
                                             void *opaque,
9374 9375
                                             virFreeCallback freecb)
{
9376 9377 9378 9379 9380 9381 9382 9383 9384 9385 9386 9387 9388 9389 9390 9391 9392 9393 9394 9395 9396 9397 9398 9399 9400 9401 9402 9403 9404 9405 9406 9407 9408 9409 9410 9411 9412 9413
    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
             */

9414
            if (virDomainEventStateRegisterID(conn, data->domainEvents,
9415 9416
                                              dom, eventID,
                                              callback, opaque, freecb, &ret) < 0)
9417
                ret = -1;
9418
            VIR_DEBUG("virDomainEventStateRegisterID (ret = %d) (conn: %p, "
9419
                      "callback: %p, opaque: %p, "
9420
                      "freecb: %p)", ret, conn, callback,
9421
                      opaque, freecb);
9422 9423 9424 9425 9426 9427 9428 9429 9430 9431 9432 9433 9434 9435 9436
        }
    }

    vboxDriverUnlock(data);

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

9437 9438 9439 9440
static int
vboxConnectDomainEventDeregisterAny(virConnectPtr conn,
                                    int callbackID)
{
9441
    VBOX_OBJECT_CHECK(conn, int, -1);
9442
    int cnt;
9443 9444 9445 9446 9447 9448

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

9449
    cnt = virObjectEventStateDeregisterID(conn, data->domainEvents,
9450
                                          callbackID);
9451

9452 9453 9454
    if (data->vboxCallback && cnt == 0) {
        data->vboxObj->vtbl->UnregisterCallback(data->vboxObj, data->vboxCallback);
        VBOX_RELEASE(data->vboxCallback);
9455

9456 9457 9458
        /* Remove the Event file handle on which we are listening as well */
        virEventRemoveHandle(data->fdWatch);
        data->fdWatch = -1;
9459 9460 9461 9462
    }

    vboxDriverUnlock(data);

9463 9464 9465
    if (cnt >= 0)
        ret = 0;

9466 9467 9468
    return ret;
}

9469
#endif /* !(VBOX_API_VERSION == 2002000 || VBOX_API_VERSION >= 4000000) */
9470

9471 9472 9473 9474 9475
/**
 * The Network Functions here on
 */
static virDrvOpenStatus vboxNetworkOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
9476 9477
                                        unsigned int flags)
{
9478 9479
    vboxGlobalData *data = conn->privateData;

E
Eric Blake 已提交
9480 9481
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

9482 9483 9484 9485 9486 9487 9488 9489
    if (STRNEQ(conn->driver->name, "VBOX"))
        goto cleanup;

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

9490
    VIR_DEBUG("network initialized");
9491 9492 9493
    /* conn->networkPrivateData = some network specific data */
    return VIR_DRV_OPEN_SUCCESS;

9494
 cleanup:
9495 9496 9497
    return VIR_DRV_OPEN_DECLINED;
}

9498 9499
static int vboxNetworkClose(virConnectPtr conn)
{
9500
    VIR_DEBUG("network uninitialized");
9501 9502 9503 9504
    conn->networkPrivateData = NULL;
    return 0;
}

9505 9506
static int vboxConnectNumOfNetworks(virConnectPtr conn)
{
9507
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9508
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9509
    size_t i = 0;
9510

9511
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
9512

9513 9514 9515 9516
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
9517
            PRUint32 interfaceType = 0;
9518

9519
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9520 9521
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9522

9523
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9524

9525 9526
                if (status == HostNetworkInterfaceStatus_Up)
                    ret++;
9527 9528 9529 9530
            }
        }
    }

9531 9532
    vboxArrayRelease(&networkInterfaces);

9533 9534
    VBOX_RELEASE(host);

9535
    VIR_DEBUG("numActive: %d", ret);
9536
    return ret;
9537 9538
}

9539
static int vboxConnectListNetworks(virConnectPtr conn, char **const names, int nnames) {
9540
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9541
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9542
    size_t i = 0;
9543

9544 9545 9546 9547
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

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

9549
        if (networkInterface) {
9550
            PRUint32 interfaceType = 0;
9551

9552
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9553

9554 9555
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9556

9557
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9558

9559 9560 9561
                if (status == HostNetworkInterfaceStatus_Up) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
9562

9563
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
9564
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
9565

9566
                    VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8);
J
Ján Tomko 已提交
9567
                    if (VIR_STRDUP(names[ret], nameUtf8) >= 0)
9568
                        ret++;
9569

9570 9571
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
9572 9573 9574 9575 9576
                }
            }
        }
    }

9577
    vboxArrayRelease(&networkInterfaces);
9578

9579
    VBOX_RELEASE(host);
9580

9581 9582
    return ret;
}
9583

9584 9585
static int vboxConnectNumOfDefinedNetworks(virConnectPtr conn)
{
9586
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9587
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9588
    size_t i = 0;
9589

9590
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);
9591

9592 9593 9594 9595
    for (i = 0; i < networkInterfaces.count; i++) {
        IHostNetworkInterface *networkInterface = networkInterfaces.items[i];

        if (networkInterface) {
9596
            PRUint32 interfaceType = 0;
9597

9598
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9599 9600
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9601

9602
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9603

9604 9605
                if (status == HostNetworkInterfaceStatus_Down)
                    ret++;
9606 9607 9608 9609
            }
        }
    }

9610 9611
    vboxArrayRelease(&networkInterfaces);

9612 9613
    VBOX_RELEASE(host);

9614
    VIR_DEBUG("numActive: %d", ret);
9615
    return ret;
9616 9617
}

9618
static int vboxConnectListDefinedNetworks(virConnectPtr conn, char **const names, int nnames) {
9619
    VBOX_OBJECT_HOST_CHECK(conn, int, 0);
9620
    vboxArray networkInterfaces = VBOX_ARRAY_INITIALIZER;
9621
    size_t i = 0;
9622

9623 9624 9625 9626
    vboxArrayGet(&networkInterfaces, host, host->vtbl->GetNetworkInterfaces);

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

9628
        if (networkInterface) {
9629
            PRUint32 interfaceType = 0;
9630

9631
            networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9632

9633 9634
            if (interfaceType == HostNetworkInterfaceType_HostOnly) {
                PRUint32 status = HostNetworkInterfaceStatus_Unknown;
9635

9636
                networkInterface->vtbl->GetStatus(networkInterface, &status);
9637

9638 9639 9640
                if (status == HostNetworkInterfaceStatus_Down) {
                    char *nameUtf8       = NULL;
                    PRUnichar *nameUtf16 = NULL;
9641

9642
                    networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
9643
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
9644

9645
                    VIR_DEBUG("nnames[%d]: %s", ret, nameUtf8);
J
Ján Tomko 已提交
9646
                    if (VIR_STRDUP(names[ret], nameUtf8) >= 0)
9647
                        ret++;
9648

9649 9650
                    VBOX_UTF8_FREE(nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
9651 9652 9653 9654 9655
                }
            }
        }
    }

9656
    vboxArrayRelease(&networkInterfaces);
9657 9658 9659 9660

    VBOX_RELEASE(host);

    return ret;
9661 9662
}

9663 9664 9665
static virNetworkPtr
vboxNetworkLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
{
9666
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
9667
    vboxIID iid = VBOX_IID_INITIALIZER;
9668

9669
    vboxIIDFromUUID(&iid, uuid);
9670

9671 9672 9673
    /* TODO: "internal" networks are just strings and
     * thus can't do much with them
     */
9674
    IHostNetworkInterface *networkInterface = NULL;
9675

9676
    host->vtbl->FindHostNetworkInterfaceById(host, iid.value, &networkInterface);
9677 9678
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9679

9680
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9681

9682 9683 9684
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            char *nameUtf8       = NULL;
            PRUnichar *nameUtf16 = NULL;
9685

9686 9687
            networkInterface->vtbl->GetName(networkInterface, &nameUtf16);
            VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
9688

9689
            ret = virGetNetwork(conn, nameUtf8, uuid);
9690

9691
            VIR_DEBUG("Network Name: %s", nameUtf8);
9692
            DEBUGIID("Network UUID", iid.value);
9693

9694 9695
            VBOX_UTF8_FREE(nameUtf8);
            VBOX_UTF16_FREE(nameUtf16);
9696
        }
9697 9698

        VBOX_RELEASE(networkInterface);
9699 9700
    }

9701 9702
    VBOX_RELEASE(host);

9703
    vboxIIDUnalloc(&iid);
9704 9705 9706
    return ret;
}

9707 9708 9709
static virNetworkPtr
vboxNetworkLookupByName(virConnectPtr conn, const char *name)
{
9710 9711 9712
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *nameUtf16                    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9713

9714
    VBOX_UTF8_TO_UTF16(name, &nameUtf16);
9715

9716
    host->vtbl->FindHostNetworkInterfaceByName(host, nameUtf16, &networkInterface);
9717

9718 9719
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9720

9721
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9722

9723 9724
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            unsigned char uuid[VIR_UUID_BUFLEN];
9725
            vboxIID iid = VBOX_IID_INITIALIZER;
9726

9727 9728
            networkInterface->vtbl->GetId(networkInterface, &iid.value);
            vboxIIDToUUID(&iid, uuid);
9729
            ret = virGetNetwork(conn, name, uuid);
9730
            VIR_DEBUG("Network Name: %s", name);
9731

9732 9733
            DEBUGIID("Network UUID", iid.value);
            vboxIIDUnalloc(&iid);
9734
        }
9735 9736

        VBOX_RELEASE(networkInterface);
9737 9738
    }

9739 9740 9741
    VBOX_UTF16_FREE(nameUtf16);
    VBOX_RELEASE(host);

9742 9743 9744
    return ret;
}

9745 9746 9747
static virNetworkPtr
vboxNetworkDefineCreateXML(virConnectPtr conn, const char *xml, bool start)
{
9748 9749 9750 9751
    VBOX_OBJECT_HOST_CHECK(conn, virNetworkPtr, NULL);
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    char      *networkInterfaceNameUtf8     = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9752
    nsresult rc;
9753

9754
    virNetworkDefPtr def = virNetworkDefParseString(xml);
9755 9756
    virNetworkIpDefPtr ipdef;
    virSocketAddr netmask;
9757

9758
    if ((!def) ||
9759
        (def->forward.type != VIR_NETWORK_FORWARD_NONE) ||
9760
        (def->nips == 0 || !def->ips))
9761 9762 9763 9764 9765 9766 9767 9768 9769 9770 9771
        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)
9772
        goto cleanup;
9773

9774 9775 9776 9777 9778 9779
    /* 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.
     */
9780

9781
#if VBOX_API_VERSION == 2002000
9782
    if (STREQ(def->name, "vboxnet0")) {
9783
        PRUint32 interfaceType = 0;
9784

9785 9786
        VBOX_UTF8_TO_UTF16(def->name, &networkInterfaceNameUtf16);
        host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
9787

9788 9789 9790 9791 9792 9793
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
        if (interfaceType != HostNetworkInterfaceType_HostOnly) {
            VBOX_RELEASE(networkInterface);
            networkInterface = NULL;
        }
    }
9794
#else /* VBOX_API_VERSION != 2002000 */
9795 9796 9797 9798
    {
        IProgress *progress = NULL;
        host->vtbl->CreateHostOnlyNetworkInterface(host, &networkInterface,
                                                   &progress);
9799

9800 9801 9802 9803
        if (progress) {
            progress->vtbl->WaitForCompletion(progress, -1);
            VBOX_RELEASE(progress);
        }
9804
    }
9805
#endif /* VBOX_API_VERSION != 2002000 */
9806

9807 9808 9809 9810
    if (networkInterface) {
        unsigned char uuid[VIR_UUID_BUFLEN];
        char      *networkNameUtf8  = NULL;
        PRUnichar *networkNameUtf16 = NULL;
9811
        vboxIID vboxnetiid = VBOX_IID_INITIALIZER;
9812 9813 9814 9815 9816 9817 9818 9819 9820 9821 9822

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

E
Eric Blake 已提交
9824
        VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
9825

9826 9827 9828
        /* Currently support only one dhcp server per network
         * with contigious address space from start to end
         */
9829
        if ((ipdef->nranges >= 1) &&
9830 9831
            VIR_SOCKET_ADDR_VALID(&ipdef->ranges[0].start) &&
            VIR_SOCKET_ADDR_VALID(&ipdef->ranges[0].end)) {
9832 9833 9834 9835 9836 9837 9838 9839 9840 9841
            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);
9842
                VIR_DEBUG("couldn't find dhcp server so creating one");
9843 9844 9845 9846 9847 9848 9849 9850
            }
            if (dhcpServer) {
                PRUnichar *ipAddressUtf16     = NULL;
                PRUnichar *networkMaskUtf16   = NULL;
                PRUnichar *fromIPAddressUtf16 = NULL;
                PRUnichar *toIPAddressUtf16   = NULL;
                PRUnichar *trunkTypeUtf16     = NULL;

9851 9852 9853 9854
                ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->address);
                networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
                fromIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].start);
                toIPAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->ranges[0].end);
9855 9856 9857 9858 9859 9860 9861 9862 9863 9864

                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;
                }
9865 9866 9867 9868 9869 9870 9871 9872 9873 9874 9875 9876 9877 9878 9879 9880 9881 9882 9883 9884 9885 9886 9887 9888 9889

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

9891
        if ((ipdef->nhosts >= 1) &&
9892
            VIR_SOCKET_ADDR_VALID(&ipdef->hosts[0].ip)) {
9893 9894
            PRUnichar *ipAddressUtf16   = NULL;
            PRUnichar *networkMaskUtf16 = NULL;
9895

9896 9897
            ipAddressUtf16 = vboxSocketFormatAddrUtf16(data, &ipdef->hosts[0].ip);
            networkMaskUtf16 = vboxSocketFormatAddrUtf16(data, &netmask);
9898 9899 9900 9901 9902 9903

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

9905 9906 9907 9908
            /* 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
             */
9909
#if VBOX_API_VERSION < 4002000
9910 9911 9912
            networkInterface->vtbl->EnableStaticIpConfig(networkInterface,
                                                         ipAddressUtf16,
                                                         networkMaskUtf16);
9913 9914 9915 9916 9917
#else
            networkInterface->vtbl->EnableStaticIPConfig(networkInterface,
                                                         ipAddressUtf16,
                                                         networkMaskUtf16);
#endif
9918

9919 9920 9921
            VBOX_UTF16_FREE(ipAddressUtf16);
            VBOX_UTF16_FREE(networkMaskUtf16);
        } else {
9922
#if VBOX_API_VERSION < 4002000
9923 9924
            networkInterface->vtbl->EnableDynamicIpConfig(networkInterface);
            networkInterface->vtbl->DhcpRediscover(networkInterface);
9925 9926 9927 9928
#else
            networkInterface->vtbl->EnableDynamicIPConfig(networkInterface);
            networkInterface->vtbl->DHCPRediscover(networkInterface);
#endif
9929
        }
9930

9931 9932 9933 9934 9935
        rc = networkInterface->vtbl->GetId(networkInterface, &vboxnetiid.value);
        if (NS_SUCCEEDED(rc)) {
            vboxIIDToUUID(&vboxnetiid, uuid);
            DEBUGIID("Real Network UUID", vboxnetiid.value);
            vboxIIDUnalloc(&vboxnetiid);
9936
            ret = virGetNetwork(conn, networkInterfaceNameUtf8, uuid);
9937
        }
9938 9939 9940 9941

        VIR_FREE(networkNameUtf8);
        VBOX_UTF16_FREE(networkNameUtf16);
        VBOX_RELEASE(networkInterface);
9942 9943
    }

9944 9945 9946 9947
    VBOX_UTF8_FREE(networkInterfaceNameUtf8);
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

9948
 cleanup:
9949 9950 9951 9952
    virNetworkDefFree(def);
    return ret;
}

9953 9954
static virNetworkPtr vboxNetworkCreateXML(virConnectPtr conn, const char *xml)
{
9955 9956 9957
    return vboxNetworkDefineCreateXML(conn, xml, true);
}

9958 9959
static virNetworkPtr vboxNetworkDefineXML(virConnectPtr conn, const char *xml)
{
9960 9961 9962
    return vboxNetworkDefineCreateXML(conn, xml, false);
}

9963 9964 9965
static int
vboxNetworkUndefineDestroy(virNetworkPtr network, bool removeinterface)
{
9966
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
9967
    char *networkNameUtf8 = NULL;
9968 9969
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
9970 9971 9972 9973 9974 9975 9976 9977 9978

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

9979
    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0)
9980 9981
        goto cleanup;

9982
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
9983

9984
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
9985

9986 9987
    if (networkInterface) {
        PRUint32 interfaceType = 0;
9988

9989
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
9990

9991 9992 9993
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
9994

9995
#if VBOX_API_VERSION != 2002000
9996 9997 9998
            if (removeinterface) {
                PRUnichar *iidUtf16 = NULL;
                IProgress *progress = NULL;
9999

10000
                networkInterface->vtbl->GetId(networkInterface, &iidUtf16);
10001

10002
                if (iidUtf16) {
10003
# if VBOX_API_VERSION == 3000000
10004 10005 10006
                    IHostNetworkInterface *netInt = NULL;
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &netInt, &progress);
                    VBOX_RELEASE(netInt);
10007
# else  /* VBOX_API_VERSION > 3000000 */
10008
                    host->vtbl->RemoveHostOnlyNetworkInterface(host, iidUtf16, &progress);
10009
# endif /* VBOX_API_VERSION > 3000000 */
10010 10011
                    VBOX_UTF16_FREE(iidUtf16);
                }
10012

10013 10014 10015 10016 10017
                if (progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
                }
            }
10018
#endif /* VBOX_API_VERSION != 2002000 */
10019

E
Eric Blake 已提交
10020
            VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
10021 10022 10023 10024 10025 10026 10027 10028 10029 10030

            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);
10031 10032
            }

10033 10034
            VBOX_UTF16_FREE(networkNameUtf16);

10035
        }
10036
        VBOX_RELEASE(networkInterface);
10037 10038
    }

10039 10040 10041
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

10042 10043
    ret = 0;

10044
 cleanup:
10045 10046 10047 10048
    VIR_FREE(networkNameUtf8);
    return ret;
}

10049 10050
static int vboxNetworkUndefine(virNetworkPtr network)
{
10051 10052 10053
    return vboxNetworkUndefineDestroy(network, true);
}

10054 10055
static int vboxNetworkCreate(virNetworkPtr network)
{
10056
    VBOX_OBJECT_HOST_CHECK(network->conn, int, -1);
10057
    char *networkNameUtf8 = NULL;
10058 10059
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
10060 10061 10062 10063 10064 10065 10066 10067

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

10068
    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0)
10069 10070
        goto cleanup;

10071
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
10072

10073
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
10074

10075 10076
    if (networkInterface) {
        PRUint32 interfaceType = 0;
10077

10078
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
10079

10080 10081 10082
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
            PRUnichar *networkNameUtf16 = NULL;
            IDHCPServer *dhcpServer     = NULL;
10083 10084


E
Eric Blake 已提交
10085
            VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
10086

10087 10088 10089 10090 10091
            data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                             networkNameUtf16,
                                                             &dhcpServer);
            if (dhcpServer) {
                PRUnichar *trunkTypeUtf16 = NULL;
10092

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

10095
                VBOX_UTF8_TO_UTF16("netflt", &trunkTypeUtf16);
10096

10097 10098 10099 10100
                dhcpServer->vtbl->Start(dhcpServer,
                                        networkNameUtf16,
                                        networkInterfaceNameUtf16,
                                        trunkTypeUtf16);
10101

10102 10103
                VBOX_UTF16_FREE(trunkTypeUtf16);
                VBOX_RELEASE(dhcpServer);
10104 10105
            }

10106
            VBOX_UTF16_FREE(networkNameUtf16);
10107
        }
10108 10109

        VBOX_RELEASE(networkInterface);
10110 10111
    }

10112 10113 10114
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

10115 10116
    ret = 0;

10117
 cleanup:
10118 10119 10120 10121
    VIR_FREE(networkNameUtf8);
    return ret;
}

10122 10123
static int vboxNetworkDestroy(virNetworkPtr network)
{
10124
    return vboxNetworkUndefineDestroy(network, false);
10125 10126
}

10127
static char *vboxNetworkGetXMLDesc(virNetworkPtr network,
E
Eric Blake 已提交
10128 10129
                                   unsigned int flags)
{
10130
    VBOX_OBJECT_HOST_CHECK(network->conn, char *, NULL);
10131
    virNetworkDefPtr def  = NULL;
10132
    virNetworkIpDefPtr ipdef = NULL;
10133
    char *networkNameUtf8 = NULL;
10134 10135
    PRUnichar *networkInterfaceNameUtf16    = NULL;
    IHostNetworkInterface *networkInterface = NULL;
10136

E
Eric Blake 已提交
10137 10138
    virCheckFlags(0, NULL);

10139
    if (VIR_ALLOC(def) < 0)
10140
        goto cleanup;
10141
    if (VIR_ALLOC(ipdef) < 0)
10142 10143 10144
        goto cleanup;
    def->ips = ipdef;
    def->nips = 1;
10145

10146
    if (virAsprintf(&networkNameUtf8, "HostInterfaceNetworking-%s", network->name) < 0)
10147 10148
        goto cleanup;

10149
    VBOX_UTF8_TO_UTF16(network->name, &networkInterfaceNameUtf16);
10150

10151
    host->vtbl->FindHostNetworkInterfaceByName(host, networkInterfaceNameUtf16, &networkInterface);
10152

10153 10154
    if (networkInterface) {
        PRUint32 interfaceType = 0;
10155

10156
        networkInterface->vtbl->GetInterfaceType(networkInterface, &interfaceType);
10157

10158
        if (interfaceType == HostNetworkInterfaceType_HostOnly) {
J
Ján Tomko 已提交
10159
            if (VIR_STRDUP(def->name, network->name) >= 0) {
10160 10161
                PRUnichar *networkNameUtf16 = NULL;
                IDHCPServer *dhcpServer     = NULL;
10162
                vboxIID vboxnet0IID = VBOX_IID_INITIALIZER;
10163

10164 10165
                networkInterface->vtbl->GetId(networkInterface, &vboxnet0IID.value);
                vboxIIDToUUID(&vboxnet0IID, def->uuid);
10166

E
Eric Blake 已提交
10167
                VBOX_UTF8_TO_UTF16(networkNameUtf8, &networkNameUtf16);
10168

10169
                def->forward.type = VIR_NETWORK_FORWARD_NONE;
10170

10171 10172 10173 10174
                data->vboxObj->vtbl->FindDHCPServerByNetworkName(data->vboxObj,
                                                                 networkNameUtf16,
                                                                 &dhcpServer);
                if (dhcpServer) {
10175
                    ipdef->nranges = 1;
10176
                    if (VIR_ALLOC_N(ipdef->ranges, ipdef->nranges) >= 0) {
10177 10178 10179 10180
                        PRUnichar *ipAddressUtf16     = NULL;
                        PRUnichar *networkMaskUtf16   = NULL;
                        PRUnichar *fromIPAddressUtf16 = NULL;
                        PRUnichar *toIPAddressUtf16   = NULL;
10181
                        bool errorOccurred = false;
10182

10183 10184 10185 10186 10187 10188 10189
                        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
                         */
10190
                        if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
10191
                                                     &ipdef->address) < 0 ||
10192
                            vboxSocketParseAddrUtf16(data, networkMaskUtf16,
10193
                                                     &ipdef->netmask) < 0 ||
10194
                            vboxSocketParseAddrUtf16(data, fromIPAddressUtf16,
10195
                                                     &ipdef->ranges[0].start) < 0 ||
10196
                            vboxSocketParseAddrUtf16(data, toIPAddressUtf16,
10197
                                                     &ipdef->ranges[0].end) < 0) {
10198 10199
                            errorOccurred = true;
                        }
10200 10201 10202 10203 10204

                        VBOX_UTF16_FREE(ipAddressUtf16);
                        VBOX_UTF16_FREE(networkMaskUtf16);
                        VBOX_UTF16_FREE(fromIPAddressUtf16);
                        VBOX_UTF16_FREE(toIPAddressUtf16);
10205 10206 10207 10208

                        if (errorOccurred) {
                            goto cleanup;
                        }
10209
                    } else {
10210
                        ipdef->nranges = 0;
10211
                    }
10212

10213
                    ipdef->nhosts = 1;
10214
                    if (VIR_ALLOC_N(ipdef->hosts, ipdef->nhosts) >= 0) {
10215
                        if (VIR_STRDUP(ipdef->hosts[0].name, network->name) < 0) {
10216 10217
                            VIR_FREE(ipdef->hosts);
                            ipdef->nhosts = 0;
10218
                        } else {
10219 10220
                            PRUnichar *macAddressUtf16 = NULL;
                            PRUnichar *ipAddressUtf16  = NULL;
10221
                            bool errorOccurred = false;
10222

10223
                            networkInterface->vtbl->GetHardwareAddress(networkInterface, &macAddressUtf16);
10224 10225
                            networkInterface->vtbl->GetIPAddress(networkInterface, &ipAddressUtf16);

10226
                            VBOX_UTF16_TO_UTF8(macAddressUtf16, &ipdef->hosts[0].mac);
10227 10228

                            if (vboxSocketParseAddrUtf16(data, ipAddressUtf16,
10229
                                                         &ipdef->hosts[0].ip) < 0) {
10230 10231
                                errorOccurred = true;
                            }
10232

10233 10234
                            VBOX_UTF16_FREE(macAddressUtf16);
                            VBOX_UTF16_FREE(ipAddressUtf16);
10235 10236 10237 10238

                            if (errorOccurred) {
                                goto cleanup;
                            }
10239 10240
                        }
                    } else {
10241
                        ipdef->nhosts = 0;
10242
                    }
10243 10244 10245 10246 10247

                    VBOX_RELEASE(dhcpServer);
                } else {
                    PRUnichar *networkMaskUtf16 = NULL;
                    PRUnichar *ipAddressUtf16   = NULL;
10248
                    bool errorOccurred = false;
10249 10250 10251 10252

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

10253
                    if (vboxSocketParseAddrUtf16(data, networkMaskUtf16,
10254
                                                 &ipdef->netmask) < 0 ||
10255
                        vboxSocketParseAddrUtf16(data, ipAddressUtf16,
10256
                                                 &ipdef->address) < 0) {
10257 10258
                        errorOccurred = true;
                    }
10259 10260 10261

                    VBOX_UTF16_FREE(networkMaskUtf16);
                    VBOX_UTF16_FREE(ipAddressUtf16);
10262 10263 10264 10265

                    if (errorOccurred) {
                        goto cleanup;
                    }
10266 10267
                }

10268 10269
                DEBUGIID("Network UUID", vboxnet0IID.value);
                vboxIIDUnalloc(&vboxnet0IID);
10270
                VBOX_UTF16_FREE(networkNameUtf16);
10271 10272
            }
        }
10273 10274

        VBOX_RELEASE(networkInterface);
10275 10276
    }

10277 10278 10279
    VBOX_UTF16_FREE(networkInterfaceNameUtf16);
    VBOX_RELEASE(host);

10280
    ret = virNetworkDefFormat(def, 0);
10281

10282
 cleanup:
10283
    virNetworkDefFree(def);
10284 10285 10286 10287
    VIR_FREE(networkNameUtf8);
    return ret;
}

10288 10289 10290 10291
/**
 * The Storage Functions here on
 */

10292 10293 10294
static virDrvOpenStatus vboxStorageOpen(virConnectPtr conn,
                                        virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                                        unsigned int flags)
E
Eric Blake 已提交
10295
{
10296 10297
    vboxGlobalData *data = conn->privateData;

E
Eric Blake 已提交
10298 10299
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

10300
    if (STRNEQ(conn->driver->name, "VBOX"))
10301
        return VIR_DRV_OPEN_DECLINED;
10302 10303 10304 10305

    if ((data->pFuncs      == NULL) ||
        (data->vboxObj     == NULL) ||
        (data->vboxSession == NULL))
10306
        return VIR_DRV_OPEN_ERROR;
10307

10308
    VIR_DEBUG("vbox storage initialized");
10309 10310 10311 10312
    /* conn->storagePrivateData = some storage specific data */
    return VIR_DRV_OPEN_SUCCESS;
}

10313 10314
static int vboxStorageClose(virConnectPtr conn)
{
10315
    VIR_DEBUG("vbox storage uninitialized");
10316 10317 10318 10319
    conn->storagePrivateData = NULL;
    return 0;
}

10320 10321
static int vboxConnectNumOfStoragePools(virConnectPtr conn ATTRIBUTE_UNUSED)
{
10322 10323 10324 10325 10326 10327 10328 10329

    /** Currently only one pool supported, the default one
     * given by ISystemProperties::defaultHardDiskFolder()
     */

    return 1;
}

10330 10331
static int vboxConnectListStoragePools(virConnectPtr conn ATTRIBUTE_UNUSED,
                                       char **const names, int nnames) {
10332 10333
    int numActive = 0;

10334 10335 10336
    if (nnames == 1 &&
        VIR_STRDUP(names[numActive], "default-pool") > 0)
        numActive++;
10337 10338 10339
    return numActive;
}

10340 10341 10342
static virStoragePoolPtr
vboxStoragePoolLookupByName(virConnectPtr conn, const char *name)
{
10343 10344 10345 10346 10347 10348 10349 10350 10351 10352
    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";

10353
        ignore_value(virUUIDParse(uuidstr, uuid));
10354

10355
        ret = virGetStoragePool(conn, name, uuid, NULL, NULL);
10356 10357 10358 10359 10360
    }

    return ret;
}

10361 10362
static int vboxStoragePoolNumOfVolumes(virStoragePoolPtr pool)
{
10363
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
10364
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
10365 10366
    PRUint32 hardDiskAccessible = 0;
    nsresult rc;
10367
    size_t i;
10368

10369
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
10370
    if (NS_SUCCEEDED(rc)) {
10371 10372
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
10373 10374
            if (hardDisk) {
                PRUint32 hddstate;
10375

10376 10377 10378
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible)
                    hardDiskAccessible++;
10379 10380
            }
        }
10381 10382 10383 10384

        vboxArrayRelease(&hardDisks);

        ret = hardDiskAccessible;
10385
    } else {
10386
        ret = -1;
10387 10388 10389
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get number of volumes in the pool: %s, rc=%08x"),
                       pool->name, (unsigned)rc);
10390 10391
    }

10392
    return ret;
10393 10394 10395
}

static int vboxStoragePoolListVolumes(virStoragePoolPtr pool, char **const names, int nnames) {
10396
    VBOX_OBJECT_CHECK(pool->conn, int, -1);
10397
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
10398 10399
    PRUint32 numActive     = 0;
    nsresult rc;
10400
    size_t i;
10401

10402
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
10403
    if (NS_SUCCEEDED(rc)) {
10404 10405
        for (i = 0; i < hardDisks.count && numActive < nnames; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
10406

10407 10408 10409 10410
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
10411

10412 10413 10414
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
10415

10416 10417
                    VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                    VBOX_UTF16_FREE(nameUtf16);
10418

10419
                    if (nameUtf8) {
10420
                        VIR_DEBUG("nnames[%d]: %s", numActive, nameUtf8);
10421
                        if (VIR_STRDUP(names[numActive], nameUtf8) > 0)
10422 10423 10424
                            numActive++;

                        VBOX_UTF8_FREE(nameUtf8);
10425 10426 10427 10428
                    }
                }
            }
        }
10429 10430 10431 10432

        vboxArrayRelease(&hardDisks);

        ret = numActive;
10433
    } else {
10434
        ret = -1;
10435 10436 10437
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("could not get the volume list in the pool: %s, rc=%08x"),
                       pool->name, (unsigned)rc);
10438 10439
    }

10440
    return ret;
10441 10442
}

10443 10444 10445
static virStorageVolPtr
vboxStorageVolLookupByName(virStoragePoolPtr pool, const char *name)
{
10446
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
10447
    vboxArray hardDisks = VBOX_ARRAY_INITIALIZER;
10448
    nsresult rc;
10449
    size_t i;
10450

10451
    if (!name)
10452
        return ret;
10453

10454
    rc = vboxArrayGet(&hardDisks, data->vboxObj, data->vboxObj->vtbl->GetHardDisks);
10455
    if (NS_SUCCEEDED(rc)) {
10456 10457
        for (i = 0; i < hardDisks.count; ++i) {
            IHardDisk *hardDisk = hardDisks.items[i];
10458

10459 10460 10461 10462
            if (hardDisk) {
                PRUint32 hddstate;
                char      *nameUtf8  = NULL;
                PRUnichar *nameUtf16 = NULL;
10463

10464 10465 10466
                VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
                if (hddstate != MediaState_Inaccessible) {
                    VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &nameUtf16);
10467

10468 10469 10470 10471
                    if (nameUtf16) {
                        VBOX_UTF16_TO_UTF8(nameUtf16, &nameUtf8);
                        VBOX_UTF16_FREE(nameUtf16);
                    }
10472

10473
                    if (nameUtf8 && STREQ(nameUtf8, name)) {
10474 10475 10476
                        vboxIID hddIID = VBOX_IID_INITIALIZER;
                        unsigned char uuid[VIR_UUID_BUFLEN];
                        char key[VIR_UUID_STRING_BUFLEN] = "";
10477

10478 10479 10480 10481
                        rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
                        if (NS_SUCCEEDED(rc)) {
                            vboxIIDToUUID(&hddIID, uuid);
                            virUUIDFormat(uuid, key);
10482

10483 10484
                            ret = virGetStorageVol(pool->conn, pool->name, name, key,
                                                   NULL, NULL);
10485

10486 10487 10488 10489
                            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);
10490 10491
                        }

10492
                        vboxIIDUnalloc(&hddIID);
10493 10494
                        VBOX_UTF8_FREE(nameUtf8);
                        break;
10495
                    }
10496

J
John Ferlan 已提交
10497
                    VBOX_UTF8_FREE(nameUtf8);
10498 10499 10500
                }
            }
        }
10501

10502
        vboxArrayRelease(&hardDisks);
10503 10504 10505 10506 10507
    }

    return ret;
}

10508 10509 10510
static virStorageVolPtr
vboxStorageVolLookupByKey(virConnectPtr conn, const char *key)
{
10511
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
10512 10513
    vboxIID hddIID = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
10514 10515 10516
    IHardDisk *hardDisk  = NULL;
    nsresult rc;

10517 10518 10519
    if (!key)
        return ret;

10520
    if (virUUIDParse(key, uuid) < 0) {
10521 10522
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), key);
10523
        return NULL;
10524 10525
    }

10526
    vboxIIDFromUUID(&hddIID, uuid);
10527
#if VBOX_API_VERSION < 4000000
10528
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10529
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10530 10531
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10532 10533 10534 10535
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10536
#endif /* VBOX_API_VERSION >= 4000000 */
10537 10538
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10539

10540 10541 10542 10543
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
10544

10545 10546
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
            VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
10547

10548
            if (hddNameUtf8) {
10549
                if (vboxConnectNumOfStoragePools(conn) == 1) {
10550 10551
                    ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, key,
                                           NULL, NULL);
10552
                    VIR_DEBUG("Storage Volume Pool: %s", "default-pool");
10553 10554 10555 10556
                } else {
                    /* TODO: currently only one default pool and thus
                     * nothing here, change it when pools are supported
                     */
10557 10558
                }

10559 10560
                VIR_DEBUG("Storage Volume Name: %s", key);
                VIR_DEBUG("Storage Volume key : %s", hddNameUtf8);
10561 10562 10563

                VBOX_UTF8_FREE(hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
10564 10565
            }
        }
10566 10567

        VBOX_MEDIUM_RELEASE(hardDisk);
10568 10569
    }

10570
    vboxIIDUnalloc(&hddIID);
10571 10572 10573
    return ret;
}

10574 10575 10576
static virStorageVolPtr
vboxStorageVolLookupByPath(virConnectPtr conn, const char *path)
{
10577
    VBOX_OBJECT_CHECK(conn, virStorageVolPtr, NULL);
10578 10579 10580 10581
    PRUnichar *hddPathUtf16 = NULL;
    IHardDisk *hardDisk     = NULL;
    nsresult rc;

10582 10583
    if (!path)
        return ret;
10584

10585
    VBOX_UTF8_TO_UTF16(path, &hddPathUtf16);
10586

10587 10588
    if (!hddPathUtf16)
        return ret;
10589

10590
#if VBOX_API_VERSION < 4000000
10591
    rc = data->vboxObj->vtbl->FindHardDisk(data->vboxObj, hddPathUtf16, &hardDisk);
10592
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10593 10594
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddPathUtf16,
                                         DeviceType_HardDisk, &hardDisk);
10595 10596 10597 10598
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddPathUtf16,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10599
#endif /* VBOX_API_VERSION >= 4000000 */
10600 10601
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10602

10603 10604 10605 10606
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddNameUtf16 = NULL;
            char      *hddNameUtf8  = NULL;
10607

10608
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetName, &hddNameUtf16);
10609

10610 10611 10612 10613
            if (hddNameUtf16) {
                VBOX_UTF16_TO_UTF8(hddNameUtf16, &hddNameUtf8);
                VBOX_UTF16_FREE(hddNameUtf16);
            }
10614

10615 10616 10617 10618
            if (hddNameUtf8) {
                vboxIID hddIID = VBOX_IID_INITIALIZER;
                unsigned char uuid[VIR_UUID_BUFLEN];
                char key[VIR_UUID_STRING_BUFLEN] = "";
10619

10620 10621 10622 10623
                rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
                if (NS_SUCCEEDED(rc)) {
                    vboxIIDToUUID(&hddIID, uuid);
                    virUUIDFormat(uuid, key);
10624

10625 10626 10627
                    /* TODO: currently only one default pool and thus
                     * the check below, change it when pools are supported
                     */
10628
                    if (vboxConnectNumOfStoragePools(conn) == 1)
10629 10630
                        ret = virGetStorageVol(conn, "default-pool", hddNameUtf8, key,
                                               NULL, NULL);
10631

10632 10633 10634
                    VIR_DEBUG("Storage Volume Pool: %s", "default-pool");
                    VIR_DEBUG("Storage Volume Name: %s", hddNameUtf8);
                    VIR_DEBUG("Storage Volume key : %s", key);
10635
                }
10636

10637
                vboxIIDUnalloc(&hddIID);
10638 10639
            }

J
John Ferlan 已提交
10640
            VBOX_UTF8_FREE(hddNameUtf8);
10641
        }
10642 10643

        VBOX_MEDIUM_RELEASE(hardDisk);
10644 10645
    }

10646 10647
    VBOX_UTF16_FREE(hddPathUtf16);

10648 10649 10650 10651 10652
    return ret;
}

static virStorageVolPtr vboxStorageVolCreateXML(virStoragePoolPtr pool,
                                                const char *xml,
E
Eric Blake 已提交
10653 10654
                                                unsigned int flags)
{
10655
    VBOX_OBJECT_CHECK(pool->conn, virStorageVolPtr, NULL);
10656
    virStorageVolDefPtr  def  = NULL;
10657 10658
    PRUnichar *hddFormatUtf16 = NULL;
    PRUnichar *hddNameUtf16   = NULL;
10659 10660 10661
    virStoragePoolDef poolDef;
    nsresult rc;

E
Eric Blake 已提交
10662 10663
    virCheckFlags(0, NULL);

10664 10665 10666 10667 10668 10669 10670 10671
    /* 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;

10672
    if ((def = virStorageVolDefParseString(&poolDef, xml)) == NULL)
10673 10674
        goto cleanup;

10675 10676
    if (!def->name ||
        (def->type != VIR_STORAGE_VOL_FILE))
10677
        goto cleanup;
10678

10679 10680
    /* For now only the vmdk, vpc and vdi type harddisk
     * variants can be created.  For historical reason, we default to vdi */
10681 10682 10683 10684 10685 10686 10687
    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);
    }
10688

10689
    VBOX_UTF8_TO_UTF16(def->name, &hddNameUtf16);
10690

10691 10692
    if (hddFormatUtf16 && hddNameUtf16) {
        IHardDisk *hardDisk = NULL;
10693

10694 10695 10696
        rc = data->vboxObj->vtbl->CreateHardDisk(data->vboxObj, hddFormatUtf16, hddNameUtf16, &hardDisk);
        if (NS_SUCCEEDED(rc)) {
            IProgress *progress    = NULL;
10697 10698
            PRUint64   logicalSize = VIR_DIV_UP(def->target.capacity,
                                                1024 * 1024);
10699
            PRUint32   variant     = HardDiskVariant_Standard;
10700

10701
            if (def->target.capacity == def->target.allocation)
10702
                variant = HardDiskVariant_Fixed;
10703

10704
#if VBOX_API_VERSION < 4003000
10705
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, variant, &progress);
R
Ryota Ozaki 已提交
10706 10707 10708
#else
            rc = hardDisk->vtbl->CreateBaseStorage(hardDisk, logicalSize, 1, &variant, &progress);
#endif
10709
            if (NS_SUCCEEDED(rc) && progress) {
10710
#if VBOX_API_VERSION == 2002000
10711
                nsresult resultCode;
10712
#else
10713
                PRInt32  resultCode;
10714 10715
#endif

10716 10717
                progress->vtbl->WaitForCompletion(progress, -1);
                progress->vtbl->GetResultCode(progress, &resultCode);
10718

10719
                if (NS_SUCCEEDED(resultCode)) {
10720 10721 10722
                    vboxIID hddIID = VBOX_IID_INITIALIZER;
                    unsigned char uuid[VIR_UUID_BUFLEN];
                    char key[VIR_UUID_STRING_BUFLEN] = "";
10723

10724
                    rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetId, &hddIID.value);
10725
                    if (NS_SUCCEEDED(rc)) {
10726 10727
                        vboxIIDToUUID(&hddIID, uuid);
                        virUUIDFormat(uuid, key);
10728

10729 10730
                        ret = virGetStorageVol(pool->conn, pool->name, def->name, key,
                                               NULL, NULL);
10731
                    }
10732 10733

                    vboxIIDUnalloc(&hddIID);
10734 10735
                }

10736
                VBOX_RELEASE(progress);
10737
            }
10738
        }
10739 10740
    }

10741 10742 10743
    VBOX_UTF16_FREE(hddFormatUtf16);
    VBOX_UTF16_FREE(hddNameUtf16);

10744
 cleanup:
10745 10746 10747 10748 10749
    virStorageVolDefFree(def);
    return ret;
}

static int vboxStorageVolDelete(virStorageVolPtr vol,
E
Eric Blake 已提交
10750 10751
                                unsigned int flags)
{
10752
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
10753 10754
    vboxIID hddIID = VBOX_IID_INITIALIZER;
    unsigned char uuid[VIR_UUID_BUFLEN];
10755 10756 10757
    IHardDisk *hardDisk  = NULL;
    int deregister = 0;
    nsresult rc;
10758 10759
    size_t i = 0;
    size_t j = 0;
10760

E
Eric Blake 已提交
10761 10762
    virCheckFlags(0, -1);

10763
    if (virUUIDParse(vol->key, uuid) < 0) {
10764 10765
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
10766 10767
        return -1;
    }
10768

10769
    vboxIIDFromUUID(&hddIID, uuid);
10770
#if VBOX_API_VERSION < 4000000
10771
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10772
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10773 10774
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10775 10776 10777 10778
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10779
#endif /* VBOX_API_VERSION >= 4000000 */
10780 10781
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10782

10783 10784 10785
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUint32  machineIdsSize = 0;
10786 10787
            vboxArray machineIds = VBOX_ARRAY_INITIALIZER;

10788
#if VBOX_API_VERSION < 3001000
10789
            vboxArrayGet(&machineIds, hardDisk, hardDisk->vtbl->imedium.GetMachineIds);
10790
#else  /* VBOX_API_VERSION >= 3001000 */
10791
            vboxArrayGet(&machineIds, hardDisk, hardDisk->vtbl->GetMachineIds);
10792
#endif /* VBOX_API_VERSION >= 3001000 */
10793

10794
#if VBOX_API_VERSION == 2002000 && defined WIN32
10795 10796 10797 10798 10799 10800
            /* 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 已提交
10801
             * we divide the size of the SafeArray by two, to compensate for
10802 10803
             * this workaround in VirtualBox */
            machineIds.count /= 2;
10804
#endif /* VBOX_API_VERSION >= 2002000 */
10805

10806
            machineIdsSize = machineIds.count;
10807

10808
            for (i = 0; i < machineIds.count; i++) {
10809
                IMachine *machine = NULL;
10810 10811 10812
                vboxIID machineId = VBOX_IID_INITIALIZER;

                vboxIIDFromArrayItem(&machineId, &machineIds, i);
10813

10814
#if VBOX_API_VERSION >= 4000000
10815 10816
                rc = VBOX_OBJECT_GET_MACHINE(machineId.value, &machine);
                if (NS_FAILED(rc)) {
10817 10818
                    virReportError(VIR_ERR_NO_DOMAIN, "%s",
                                   _("no domain with matching uuid"));
10819 10820 10821 10822 10823 10824
                    break;
                }
#endif

                rc = VBOX_SESSION_OPEN(machineId.value, machine);

10825
                if (NS_SUCCEEDED(rc)) {
10826

10827 10828
                    rc = data->vboxSession->vtbl->GetMachine(data->vboxSession, &machine);
                    if (NS_SUCCEEDED(rc)) {
10829
                        vboxArray hddAttachments = VBOX_ARRAY_INITIALIZER;
10830

10831
#if VBOX_API_VERSION < 3001000
10832 10833
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetHardDiskAttachments);
10834
#else  /* VBOX_API_VERSION >= 3001000 */
10835 10836
                        vboxArrayGet(&hddAttachments, machine,
                                     machine->vtbl->GetMediumAttachments);
10837
#endif /* VBOX_API_VERSION >= 3001000 */
10838 10839
                        for (j = 0; j < hddAttachments.count; j++) {
                            IHardDiskAttachment *hddAttachment = hddAttachments.items[j];
10840 10841 10842 10843

                            if (hddAttachment) {
                                IHardDisk *hdd = NULL;

10844
#if VBOX_API_VERSION < 3001000
10845
                                rc = hddAttachment->vtbl->GetHardDisk(hddAttachment, &hdd);
10846
#else  /* VBOX_API_VERSION >= 3001000 */
10847
                                rc = hddAttachment->vtbl->GetMedium(hddAttachment, &hdd);
10848
#endif /* VBOX_API_VERSION >= 3001000 */
10849
                                if (NS_SUCCEEDED(rc) && hdd) {
10850
                                    vboxIID iid = VBOX_IID_INITIALIZER;
10851

10852 10853
                                    rc = VBOX_MEDIUM_FUNC_ARG1(hdd, GetId, &iid.value);
                                    if (NS_SUCCEEDED(rc)) {
10854

10855 10856
                                            DEBUGIID("HardDisk (to delete) UUID", hddIID.value);
                                            DEBUGIID("HardDisk (currently processing) UUID", iid.value);
10857

10858
                                        if (vboxIIDIsEqual(&hddIID, &iid)) {
10859 10860 10861 10862
                                            PRUnichar *controller = NULL;
                                            PRInt32    port       = 0;
                                            PRInt32    device     = 0;

10863
                                            DEBUGIID("Found HardDisk to delete, UUID", hddIID.value);
10864 10865 10866 10867 10868

                                            hddAttachment->vtbl->GetController(hddAttachment, &controller);
                                            hddAttachment->vtbl->GetPort(hddAttachment, &port);
                                            hddAttachment->vtbl->GetDevice(hddAttachment, &device);

10869
#if VBOX_API_VERSION < 3001000
10870
                                            rc = machine->vtbl->DetachHardDisk(machine, controller, port, device);
10871
#else  /* VBOX_API_VERSION >= 3001000 */
10872
                                            rc = machine->vtbl->DetachDevice(machine, controller, port, device);
10873
#endif /* VBOX_API_VERSION >= 3001000 */
10874 10875
                                            if (NS_SUCCEEDED(rc)) {
                                                rc = machine->vtbl->SaveSettings(machine);
10876
                                                VIR_DEBUG("saving machine settings");
10877
                                            }
10878

10879 10880
                                            if (NS_SUCCEEDED(rc)) {
                                                deregister++;
10881
                                                VIR_DEBUG("deregistering hdd:%d", deregister);
10882
                                            }
10883

J
John Ferlan 已提交
10884
                                            VBOX_UTF16_FREE(controller);
10885
                                        }
10886
                                        vboxIIDUnalloc(&iid);
10887
                                    }
10888
                                    VBOX_MEDIUM_RELEASE(hdd);
10889 10890 10891
                                }
                            }
                        }
10892
                        vboxArrayRelease(&hddAttachments);
10893
                        VBOX_RELEASE(machine);
10894
                    }
10895
                    VBOX_SESSION_CLOSE();
10896
                }
10897 10898

                vboxIIDUnalloc(&machineId);
10899
            }
10900

10901
            vboxArrayUnalloc(&machineIds);
10902

10903 10904 10905
            if (machineIdsSize == 0 || machineIdsSize == deregister) {
                IProgress *progress = NULL;
                rc = hardDisk->vtbl->DeleteStorage(hardDisk, &progress);
10906

10907 10908 10909
                if (NS_SUCCEEDED(rc) && progress) {
                    progress->vtbl->WaitForCompletion(progress, -1);
                    VBOX_RELEASE(progress);
10910
                    DEBUGIID("HardDisk deleted, UUID", hddIID.value);
10911
                    ret = 0;
10912 10913 10914
                }
            }
        }
10915 10916

        VBOX_MEDIUM_RELEASE(hardDisk);
10917 10918
    }

10919
    vboxIIDUnalloc(&hddIID);
10920

10921 10922 10923
    return ret;
}

10924 10925 10926
static int
vboxStorageVolGetInfo(virStorageVolPtr vol, virStorageVolInfoPtr info)
{
10927
    VBOX_OBJECT_CHECK(vol->conn, int, -1);
10928
    IHardDisk *hardDisk  = NULL;
10929 10930
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
10931 10932
    nsresult rc;

10933
    if (!info)
10934
        return ret;
10935

10936
    if (virUUIDParse(vol->key, uuid) < 0) {
10937 10938
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
10939
        return ret;
10940
    }
10941

10942
    vboxIIDFromUUID(&hddIID, uuid);
10943
#if VBOX_API_VERSION < 4000000
10944
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
10945
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
10946 10947
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
10948 10949 10950 10951
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
10952
#endif /* VBOX_API_VERSION >= 4000000 */
10953 10954
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
10955

10956 10957
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
10958
#if VBOX_API_VERSION < 4000000
10959 10960
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
10961
#else /* VBOX_API_VERSION >= 4000000 */
10962 10963
            PRInt64 hddLogicalSize;
            PRInt64 hddActualSize;
10964
#endif /* VBOX_API_VERSION >= 4000000 */
10965

10966
            info->type = VIR_STORAGE_VOL_FILE;
10967

10968
            hardDisk->vtbl->GetLogicalSize(hardDisk, &hddLogicalSize);
10969
#if VBOX_API_VERSION < 4000000
10970
            info->capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
10971
#else /* VBOX_API_VERSION >= 4000000 */
10972
            info->capacity = hddLogicalSize;
10973
#endif /* VBOX_API_VERSION >= 4000000 */
10974

10975 10976
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            info->allocation = hddActualSize;
10977

10978
            ret = 0;
10979

10980 10981 10982 10983
            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);
10984
        }
10985 10986

        VBOX_MEDIUM_RELEASE(hardDisk);
10987 10988
    }

10989
    vboxIIDUnalloc(&hddIID);
10990

10991 10992 10993
    return ret;
}

E
Eric Blake 已提交
10994 10995
static char *vboxStorageVolGetXMLDesc(virStorageVolPtr vol, unsigned int flags)
{
10996
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
10997
    IHardDisk *hardDisk  = NULL;
10998 10999
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
11000 11001 11002 11003 11004
    virStoragePoolDef pool;
    virStorageVolDef def;
    int defOk = 0;
    nsresult rc;

E
Eric Blake 已提交
11005 11006
    virCheckFlags(0, NULL);

11007 11008 11009
    memset(&pool, 0, sizeof(pool));
    memset(&def, 0, sizeof(def));

11010
    if (virUUIDParse(vol->key, uuid) < 0) {
11011 11012
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
11013
        return ret;
11014
    }
11015

11016
    vboxIIDFromUUID(&hddIID, uuid);
11017
#if VBOX_API_VERSION < 4000000
11018
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
11019
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
11020 11021
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
11022 11023 11024 11025
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
11026
#endif /* VBOX_API_VERSION >= 4000000 */
11027 11028 11029 11030 11031 11032
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;

        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (NS_SUCCEEDED(rc) && hddstate != MediaState_Inaccessible) {
            PRUnichar *hddFormatUtf16 = NULL;
11033
#if VBOX_API_VERSION < 4000000
11034 11035
            PRUint64 hddLogicalSize;
            PRUint64 hddActualSize;
11036
#else /* VBOX_API_VERSION >= 4000000 */
11037 11038
            PRInt64 hddLogicalSize;
            PRInt64 hddActualSize;
11039
#endif /* VBOX_API_VERSION >= 4000000 */
11040 11041 11042 11043 11044 11045 11046 11047 11048 11049 11050

            /* 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);
11051
            if (NS_SUCCEEDED(rc) && defOk) {
11052
#if VBOX_API_VERSION < 4000000
11053
                def.target.capacity = hddLogicalSize * 1024 * 1024; /* MB => Bytes */
11054
#else /* VBOX_API_VERSION >= 4000000 */
11055
                def.target.capacity = hddLogicalSize;
11056
#endif /* VBOX_API_VERSION >= 4000000 */
11057
            } else
11058 11059 11060 11061
                defOk = 0;

            rc = VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetSize, &hddActualSize);
            if (NS_SUCCEEDED(rc) && defOk)
11062
                def.target.allocation = hddActualSize;
11063 11064 11065
            else
                defOk = 0;

11066
            if (VIR_STRDUP(def.name, vol->name) < 0)
11067 11068
                defOk = 0;

11069
            if (VIR_STRDUP(def.key, vol->key) < 0)
11070 11071 11072 11073 11074 11075 11076 11077 11078
                defOk = 0;

            rc = hardDisk->vtbl->GetFormat(hardDisk, &hddFormatUtf16);
            if (NS_SUCCEEDED(rc) && defOk) {
                char *hddFormatUtf8 = NULL;

                VBOX_UTF16_TO_UTF8(hddFormatUtf16, &hddFormatUtf8);
                if (hddFormatUtf8) {

11079
                    VIR_DEBUG("Storage Volume Format: %s", hddFormatUtf8);
11080 11081 11082 11083 11084

                    if (STRCASEEQ("vmdk", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VMDK;
                    else if (STRCASEEQ("vhd", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VPC;
11085 11086
                    else if (STRCASEEQ("vdi", hddFormatUtf8))
                        def.target.format = VIR_STORAGE_FILE_VDI;
11087
                    else
11088
                        def.target.format = VIR_STORAGE_FILE_RAW;
11089

11090
                    VBOX_UTF8_FREE(hddFormatUtf8);
11091 11092
                }

11093 11094 11095
                VBOX_UTF16_FREE(hddFormatUtf16);
            } else {
                defOk = 0;
11096 11097
            }
        }
11098 11099

        VBOX_MEDIUM_RELEASE(hardDisk);
11100 11101
    }

11102
    vboxIIDUnalloc(&hddIID);
11103

11104
    if (defOk)
11105
        ret = virStorageVolDefFormat(&pool, &def);
11106 11107 11108 11109 11110

    return ret;
}

static char *vboxStorageVolGetPath(virStorageVolPtr vol) {
11111
    VBOX_OBJECT_CHECK(vol->conn, char *, NULL);
11112
    IHardDisk *hardDisk  = NULL;
11113 11114
    unsigned char uuid[VIR_UUID_BUFLEN];
    vboxIID hddIID = VBOX_IID_INITIALIZER;
11115 11116
    nsresult rc;

11117
    if (virUUIDParse(vol->key, uuid) < 0) {
11118 11119
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Could not parse UUID from '%s'"), vol->key);
11120
        return ret;
11121
    }
11122

11123
    vboxIIDFromUUID(&hddIID, uuid);
11124
#if VBOX_API_VERSION < 4000000
11125
    rc = data->vboxObj->vtbl->GetHardDisk(data->vboxObj, hddIID.value, &hardDisk);
11126
#elif VBOX_API_VERSION >= 4000000 && VBOX_API_VERSION < 4002000
11127 11128
    rc = data->vboxObj->vtbl->FindMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, &hardDisk);
11129 11130 11131 11132
#else
    rc = data->vboxObj->vtbl->OpenMedium(data->vboxObj, hddIID.value,
                                         DeviceType_HardDisk, AccessMode_ReadWrite,
                                         PR_FALSE, &hardDisk);
11133
#endif /* VBOX_API_VERSION >= 4000000 */
11134 11135
    if (NS_SUCCEEDED(rc)) {
        PRUint32 hddstate;
11136

11137 11138 11139 11140
        VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetState, &hddstate);
        if (hddstate != MediaState_Inaccessible) {
            PRUnichar *hddLocationUtf16 = NULL;
            char      *hddLocationUtf8  = NULL;
11141

11142
            VBOX_MEDIUM_FUNC_ARG1(hardDisk, GetLocation, &hddLocationUtf16);
11143

11144 11145
            VBOX_UTF16_TO_UTF8(hddLocationUtf16, &hddLocationUtf8);
            if (hddLocationUtf8) {
11146

11147
                ignore_value(VIR_STRDUP(ret, hddLocationUtf8));
11148

11149 11150 11151
                VIR_DEBUG("Storage Volume Name: %s", vol->name);
                VIR_DEBUG("Storage Volume Path: %s", hddLocationUtf8);
                VIR_DEBUG("Storage Volume Pool: %s", vol->pool);
11152

11153
                VBOX_UTF8_FREE(hddLocationUtf8);
11154 11155
            }

11156
            VBOX_UTF16_FREE(hddLocationUtf16);
11157
        }
11158 11159

        VBOX_MEDIUM_RELEASE(hardDisk);
11160 11161
    }

11162
    vboxIIDUnalloc(&hddIID);
11163

11164 11165
    return ret;
}
11166

11167
#if VBOX_API_VERSION >= 4000000
11168 11169 11170 11171
static char *
vboxDomainScreenshot(virDomainPtr dom,
                     virStreamPtr st,
                     unsigned int screen,
E
Eric Blake 已提交
11172
                     unsigned int flags)
11173 11174 11175 11176 11177 11178 11179 11180 11181 11182
{
    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 已提交
11183 11184
    virCheckFlags(0, NULL);

11185 11186 11187
    vboxIIDFromUUID(&iid, dom->uuid);
    rc = VBOX_OBJECT_GET_MACHINE(iid.value, &machine);
    if (NS_FAILED(rc)) {
11188 11189
        virReportError(VIR_ERR_NO_DOMAIN, "%s",
                       _("no domain with matching uuid"));
11190 11191 11192 11193 11194
        return NULL;
    }

    rc = machine->vtbl->GetMonitorCount(machine, &max_screen);
    if (NS_FAILED(rc)) {
11195 11196
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("unable to get monitor count"));
11197 11198 11199 11200 11201
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (screen >= max_screen) {
11202 11203 11204
        virReportError(VIR_ERR_INVALID_ARG,
                       _("screen ID higher than monitor "
                         "count (%d)"), max_screen);
11205 11206 11207 11208 11209 11210 11211 11212 11213
        VBOX_RELEASE(machine);
        return NULL;
    }

    if (virAsprintf(&tmp, "%s/cache/libvirt/vbox.screendump.XXXXXX", LOCALSTATEDIR) < 0) {
        VBOX_RELEASE(machine);
        return NULL;
    }

11214 11215
    if ((tmp_fd = mkostemp(tmp, O_CLOEXEC)) == -1) {
        virReportSystemError(errno, _("mkostemp(\"%s\") failed"), tmp);
11216 11217 11218 11219 11220 11221 11222 11223 11224 11225 11226 11227 11228 11229 11230 11231 11232 11233
        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;
11234
# if VBOX_API_VERSION >= 4003000
R
Ryota Ozaki 已提交
11235 11236
                PRInt32 xOrigin, yOrigin;
# endif
11237 11238 11239

                rc = display->vtbl->GetScreenResolution(display, screen,
                                                        &width, &height,
11240
# if VBOX_API_VERSION < 4003000
11241
                                                        &bitsPerPixel);
R
Ryota Ozaki 已提交
11242 11243 11244 11245
# else
                                                        &bitsPerPixel,
                                                        &xOrigin, &yOrigin);
# endif
11246 11247

                if (NS_FAILED(rc) || !width || !height) {
11248 11249
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("unable to get screen resolution"));
11250 11251 11252 11253 11254 11255 11256 11257
                    goto endjob;
                }

                rc = display->vtbl->TakeScreenShotPNGToArray(display, screen,
                                                             width, height,
                                                             &screenDataSize,
                                                             &screenData);
                if (NS_FAILED(rc)) {
11258 11259
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("failed to take screenshot"));
11260 11261 11262 11263 11264 11265 11266 11267 11268 11269 11270 11271 11272 11273 11274
                    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;
                }

11275 11276 11277
                if (VIR_STRDUP(ret, "image/png") < 0)
                    goto endjob;

E
Eric Blake 已提交
11278
                if (virFDStreamOpenFile(st, tmp, 0, 0, O_RDONLY) < 0) {
11279 11280
                    virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                                   _("unable to open stream"));
11281
                    VIR_FREE(ret);
11282
                }
11283
 endjob:
11284 11285 11286 11287 11288 11289 11290 11291 11292
                VIR_FREE(screenData);
                VBOX_RELEASE(display);
            }
            VBOX_RELEASE(console);
        }
        VBOX_SESSION_CLOSE();
    }

    VIR_FORCE_CLOSE(tmp_fd);
E
Eric Blake 已提交
11293
    unlink(tmp);
11294 11295 11296 11297 11298
    VIR_FREE(tmp);
    VBOX_RELEASE(machine);
    vboxIIDUnalloc(&iid);
    return ret;
}
11299
#endif /* VBOX_API_VERSION >= 4000000 */
11300

11301 11302 11303

#define MATCH(FLAG) (flags & (FLAG))
static int
11304 11305 11306
vboxConnectListAllDomains(virConnectPtr conn,
                          virDomainPtr **domains,
                          unsigned int flags)
11307 11308 11309 11310 11311 11312 11313 11314 11315
{
    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;
11316
    size_t i;
11317 11318 11319 11320 11321 11322
    virDomainPtr dom;
    virDomainPtr *doms = NULL;
    int count = 0;
    bool active;
    PRUint32 snapshotCount;

O
Osier Yang 已提交
11323
    virCheckFlags(VIR_CONNECT_LIST_DOMAINS_FILTERS_ALL, -1);
11324 11325 11326 11327 11328 11329 11330 11331 11332 11333 11334 11335 11336 11337

    /* 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)
11338
            goto cleanup;
11339 11340 11341 11342 11343 11344 11345

        ret = 0;
        goto cleanup;
    }

    rc = vboxArrayGet(&machines, data->vboxObj, data->vboxObj->vtbl->GetMachines);
    if (NS_FAILED(rc)) {
11346 11347
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Could not get list of domains, rc=%08x"), (unsigned)rc);
11348 11349 11350 11351 11352
        goto cleanup;
    }

    if (domains &&
        VIR_ALLOC_N(doms, machines.count + 1) < 0)
11353
        goto cleanup;
11354 11355 11356 11357 11358 11359 11360 11361 11362 11363 11364 11365 11366 11367 11368 11369 11370

    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 已提交
11371
                if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
11372 11373 11374 11375 11376
                    !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) && active) ||
                      (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) && !active)))
                    continue;

                /* filter by snapshot existence */
O
Osier Yang 已提交
11377
                if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
11378 11379
                    rc = machine->vtbl->GetSnapshotCount(machine, &snapshotCount);
                    if (NS_FAILED(rc)) {
11380
                        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
11381
                                       _("could not get snapshot count for listed domains"));
11382 11383 11384 11385 11386 11387 11388 11389 11390 11391
                        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 已提交
11392
                if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE) &&
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 11430 11431 11432 11433 11434 11435 11436 11437 11438 11439 11440 11441 11442
                    !((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;

11443
 cleanup:
11444 11445 11446 11447 11448 11449 11450 11451 11452 11453 11454 11455 11456 11457
    if (doms) {
        for (i = 0; i < count; i++) {
            if (doms[i])
                virDomainFree(doms[i]);
        }
    }
    VIR_FREE(doms);

    vboxArrayRelease(&machines);
    return ret;
}
#undef MATCH


11458 11459 11460 11461 11462 11463 11464 11465 11466 11467 11468 11469 11470 11471 11472 11473 11474 11475 11476 11477 11478
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)
{
11479 11480 11481 11482
    unsigned long long freeMem;
    if (nodeGetMemory(NULL, &freeMem) < 0)
        return 0;
    return freeMem;
11483 11484
}

11485

11486 11487 11488 11489 11490 11491 11492 11493 11494 11495 11496 11497 11498 11499 11500
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);
}


11501 11502 11503 11504
/**
 * Function Tables
 */

11505
virDriver NAME(Driver) = {
11506 11507
    .no = VIR_DRV_VBOX,
    .name = "VBOX",
11508 11509 11510
    .connectOpen = vboxConnectOpen, /* 0.6.3 */
    .connectClose = vboxConnectClose, /* 0.6.3 */
    .connectGetVersion = vboxConnectGetVersion, /* 0.6.3 */
11511
    .connectGetHostname = vboxConnectGetHostname, /* 0.6.3 */
11512
    .connectGetMaxVcpus = vboxConnectGetMaxVcpus, /* 0.6.3 */
11513
    .nodeGetInfo = vboxNodeGetInfo, /* 0.6.3 */
11514 11515 11516 11517
    .connectGetCapabilities = vboxConnectGetCapabilities, /* 0.6.3 */
    .connectListDomains = vboxConnectListDomains, /* 0.6.3 */
    .connectNumOfDomains = vboxConnectNumOfDomains, /* 0.6.3 */
    .connectListAllDomains = vboxConnectListAllDomains, /* 0.9.13 */
11518 11519 11520 11521 11522 11523 11524
    .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 */
11525
    .domainShutdownFlags = vboxDomainShutdownFlags, /* 0.9.10 */
11526 11527
    .domainReboot = vboxDomainReboot, /* 0.6.3 */
    .domainDestroy = vboxDomainDestroy, /* 0.6.3 */
11528
    .domainDestroyFlags = vboxDomainDestroyFlags, /* 0.9.4 */
11529 11530 11531 11532 11533 11534 11535 11536 11537 11538
    .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 */
11539 11540
    .connectListDefinedDomains = vboxConnectListDefinedDomains, /* 0.6.3 */
    .connectNumOfDefinedDomains = vboxConnectNumOfDefinedDomains, /* 0.6.3 */
11541 11542 11543 11544
    .domainCreate = vboxDomainCreate, /* 0.6.3 */
    .domainCreateWithFlags = vboxDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = vboxDomainDefineXML, /* 0.6.3 */
    .domainUndefine = vboxDomainUndefine, /* 0.6.3 */
11545
    .domainUndefineFlags = vboxDomainUndefineFlags, /* 0.9.5 */
11546 11547 11548 11549 11550
    .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 */
11551 11552
    .nodeGetCellsFreeMemory = vboxNodeGetCellsFreeMemory, /* 0.6.5 */
    .nodeGetFreeMemory = vboxNodeGetFreeMemory, /* 0.6.5 */
11553
#if VBOX_API_VERSION >= 4000000
11554
    .domainScreenshot = vboxDomainScreenshot, /* 0.9.2 */
11555
#endif
11556
#if VBOX_API_VERSION > 2002000 && VBOX_API_VERSION < 4000000
11557 11558
    .connectDomainEventRegister = vboxConnectDomainEventRegister, /* 0.7.0 */
    .connectDomainEventDeregister = vboxConnectDomainEventDeregister, /* 0.7.0 */
11559
#endif
11560 11561
    .connectIsEncrypted = vboxConnectIsEncrypted, /* 0.7.3 */
    .connectIsSecure = vboxConnectIsSecure, /* 0.7.3 */
11562 11563 11564
    .domainIsActive = vboxDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = vboxDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = vboxDomainIsUpdated, /* 0.8.6 */
11565
#if VBOX_API_VERSION > 2002000 && VBOX_API_VERSION < 4000000
11566 11567
    .connectDomainEventRegisterAny = vboxConnectDomainEventRegisterAny, /* 0.8.0 */
    .connectDomainEventDeregisterAny = vboxConnectDomainEventDeregisterAny, /* 0.8.0 */
11568
#endif
11569 11570 11571 11572 11573 11574
    .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 */
11575
    .domainSnapshotGetParent = vboxDomainSnapshotGetParent, /* 0.9.7 */
11576
    .domainSnapshotCurrent = vboxDomainSnapshotCurrent, /* 0.8.0 */
11577 11578
    .domainSnapshotIsCurrent = vboxDomainSnapshotIsCurrent, /* 0.9.13 */
    .domainSnapshotHasMetadata = vboxDomainSnapshotHasMetadata, /* 0.9.13 */
11579 11580
    .domainRevertToSnapshot = vboxDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = vboxDomainSnapshotDelete, /* 0.8.0 */
11581
    .connectIsAlive = vboxConnectIsAlive, /* 0.9.8 */
11582
    .nodeGetFreePages = vboxNodeGetFreePages, /* 1.2.6 */
11583
};
11584 11585 11586

virNetworkDriver NAME(NetworkDriver) = {
    "VBOX",
11587 11588
    .networkOpen = vboxNetworkOpen, /* 0.6.4 */
    .networkClose = vboxNetworkClose, /* 0.6.4 */
11589 11590 11591 11592
    .connectNumOfNetworks = vboxConnectNumOfNetworks, /* 0.6.4 */
    .connectListNetworks = vboxConnectListNetworks, /* 0.6.4 */
    .connectNumOfDefinedNetworks = vboxConnectNumOfDefinedNetworks, /* 0.6.4 */
    .connectListDefinedNetworks = vboxConnectListDefinedNetworks, /* 0.6.4 */
11593 11594 11595 11596 11597 11598 11599 11600
    .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 */
11601
};
11602 11603 11604

virStorageDriver NAME(StorageDriver) = {
    .name               = "VBOX",
11605 11606
    .storageOpen = vboxStorageOpen, /* 0.7.1 */
    .storageClose = vboxStorageClose, /* 0.7.1 */
11607 11608
    .connectNumOfStoragePools = vboxConnectNumOfStoragePools, /* 0.7.1 */
    .connectListStoragePools = vboxConnectListStoragePools, /* 0.7.1 */
11609 11610 11611 11612 11613 11614 11615 11616 11617 11618 11619 11620
    .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 */
11621
};