VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImpl.cpp@ 24525

Last change on this file since 24525 was 24525, checked in by vboxsync, 15 years ago

ApplianceImpl: Fixed to build on Windows.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 192.3 KB
Line 
1/* $Id: ApplianceImpl.cpp 24525 2009-11-09 19:02:41Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2009 Sun Microsystems, Inc.
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 *
18 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
19 * Clara, CA 95054 USA or visit http://www.sun.com if you need
20 * additional information or have any questions.
21 */
22
23#include <iprt/stream.h>
24#include <iprt/path.h>
25#include <iprt/dir.h>
26#include <iprt/file.h>
27#include <iprt/s3.h>
28#include <iprt/sha.h>
29#include <iprt/manifest.h>
30
31#include "ovfreader.h"
32
33#include <VBox/param.h>
34#include <VBox/version.h>
35
36#include "ApplianceImpl.h"
37#include "VFSExplorerImpl.h"
38#include "VirtualBoxImpl.h"
39#include "GuestOSTypeImpl.h"
40#include "ProgressImpl.h"
41#include "MachineImpl.h"
42#include "MediumImpl.h"
43
44#include "HostNetworkInterfaceImpl.h"
45
46#include "Logging.h"
47
48using namespace std;
49
50////////////////////////////////////////////////////////////////////////////////
51//
52// Appliance data definition
53//
54////////////////////////////////////////////////////////////////////////////////
55
56/* Describe a location for the import/export. The location could be a file on a
57 * local hard disk or a remote target based on the supported inet protocols. */
58struct Appliance::LocationInfo
59{
60 LocationInfo()
61 : storageType(VFSType_File) {}
62 VFSType_T storageType; /* Which type of storage should be handled */
63 Utf8Str strPath; /* File path for the import/export */
64 Utf8Str strHostname; /* Hostname on remote storage locations (could be empty) */
65 Utf8Str strUsername; /* Username on remote storage locations (could be empty) */
66 Utf8Str strPassword; /* Password on remote storage locations (could be empty) */
67};
68
69// opaque private instance data of Appliance class
70struct Appliance::Data
71{
72 Data()
73 : pReader(NULL) {}
74
75 ~Data()
76 {
77 if (pReader)
78 {
79 delete pReader;
80 pReader = NULL;
81 }
82 }
83
84 LocationInfo locInfo; /* The location info for the currently processed OVF */
85
86 OVFReader *pReader;
87
88 list< ComObjPtr<VirtualSystemDescription> > virtualSystemDescriptions;
89
90 list<Utf8Str> llWarnings;
91
92 ULONG ulWeightPerOperation;
93 Utf8Str strOVFSHA1Digest;
94};
95
96struct VirtualSystemDescription::Data
97{
98 list<VirtualSystemDescriptionEntry> llDescriptions;
99};
100
101////////////////////////////////////////////////////////////////////////////////
102//
103// internal helpers
104//
105////////////////////////////////////////////////////////////////////////////////
106
107static const struct
108{
109 CIMOSType_T cim;
110 const char *pcszVbox;
111}
112g_osTypes[] =
113{
114 { CIMOSType_CIMOS_Unknown, SchemaDefs_OSTypeId_Other },
115 { CIMOSType_CIMOS_OS2, SchemaDefs_OSTypeId_OS2 },
116 { CIMOSType_CIMOS_MSDOS, SchemaDefs_OSTypeId_DOS },
117 { CIMOSType_CIMOS_WIN3x, SchemaDefs_OSTypeId_Windows31 },
118 { CIMOSType_CIMOS_WIN95, SchemaDefs_OSTypeId_Windows95 },
119 { CIMOSType_CIMOS_WIN98, SchemaDefs_OSTypeId_Windows98 },
120 { CIMOSType_CIMOS_WINNT, SchemaDefs_OSTypeId_WindowsNT4 },
121 { CIMOSType_CIMOS_NetWare, SchemaDefs_OSTypeId_Netware },
122 { CIMOSType_CIMOS_NovellOES, SchemaDefs_OSTypeId_Netware },
123 { CIMOSType_CIMOS_Solaris, SchemaDefs_OSTypeId_OpenSolaris },
124 { CIMOSType_CIMOS_SunOS, SchemaDefs_OSTypeId_OpenSolaris },
125 { CIMOSType_CIMOS_FreeBSD, SchemaDefs_OSTypeId_FreeBSD },
126 { CIMOSType_CIMOS_NetBSD, SchemaDefs_OSTypeId_NetBSD },
127 { CIMOSType_CIMOS_QNX, SchemaDefs_OSTypeId_QNX },
128 { CIMOSType_CIMOS_Windows2000, SchemaDefs_OSTypeId_Windows2000 },
129 { CIMOSType_CIMOS_WindowsMe, SchemaDefs_OSTypeId_WindowsMe },
130 { CIMOSType_CIMOS_OpenBSD, SchemaDefs_OSTypeId_OpenBSD },
131 { CIMOSType_CIMOS_WindowsXP, SchemaDefs_OSTypeId_WindowsXP },
132 { CIMOSType_CIMOS_WindowsXPEmbedded, SchemaDefs_OSTypeId_WindowsXP },
133 { CIMOSType_CIMOS_WindowsEmbeddedforPointofService, SchemaDefs_OSTypeId_WindowsXP },
134 { CIMOSType_CIMOS_MicrosoftWindowsServer2003, SchemaDefs_OSTypeId_Windows2003 },
135 { CIMOSType_CIMOS_MicrosoftWindowsServer2003_64, SchemaDefs_OSTypeId_Windows2003_64 },
136 { CIMOSType_CIMOS_WindowsXP_64, SchemaDefs_OSTypeId_WindowsXP_64 },
137 { CIMOSType_CIMOS_WindowsVista, SchemaDefs_OSTypeId_WindowsVista },
138 { CIMOSType_CIMOS_WindowsVista_64, SchemaDefs_OSTypeId_WindowsVista_64 },
139 { CIMOSType_CIMOS_MicrosoftWindowsServer2008, SchemaDefs_OSTypeId_Windows2008 },
140 { CIMOSType_CIMOS_MicrosoftWindowsServer2008_64, SchemaDefs_OSTypeId_Windows2008_64 },
141 { CIMOSType_CIMOS_FreeBSD_64, SchemaDefs_OSTypeId_FreeBSD_64 },
142 { CIMOSType_CIMOS_RedHatEnterpriseLinux, SchemaDefs_OSTypeId_RedHat },
143 { CIMOSType_CIMOS_RedHatEnterpriseLinux_64, SchemaDefs_OSTypeId_RedHat_64 },
144 { CIMOSType_CIMOS_Solaris_64, SchemaDefs_OSTypeId_OpenSolaris_64 },
145 { CIMOSType_CIMOS_SUSE, SchemaDefs_OSTypeId_OpenSUSE },
146 { CIMOSType_CIMOS_SLES, SchemaDefs_OSTypeId_OpenSUSE },
147 { CIMOSType_CIMOS_NovellLinuxDesktop, SchemaDefs_OSTypeId_OpenSUSE },
148 { CIMOSType_CIMOS_SUSE_64, SchemaDefs_OSTypeId_OpenSUSE_64 },
149 { CIMOSType_CIMOS_SLES_64, SchemaDefs_OSTypeId_OpenSUSE_64 },
150 { CIMOSType_CIMOS_LINUX, SchemaDefs_OSTypeId_Linux },
151 { CIMOSType_CIMOS_SunJavaDesktopSystem, SchemaDefs_OSTypeId_Linux },
152 { CIMOSType_CIMOS_TurboLinux, SchemaDefs_OSTypeId_Linux},
153
154 // { CIMOSType_CIMOS_TurboLinux_64, },
155
156 { CIMOSType_CIMOS_Mandriva, SchemaDefs_OSTypeId_Mandriva },
157 { CIMOSType_CIMOS_Mandriva_64, SchemaDefs_OSTypeId_Mandriva_64 },
158 { CIMOSType_CIMOS_Ubuntu, SchemaDefs_OSTypeId_Ubuntu },
159 { CIMOSType_CIMOS_Ubuntu_64, SchemaDefs_OSTypeId_Ubuntu_64 },
160 { CIMOSType_CIMOS_Debian, SchemaDefs_OSTypeId_Debian },
161 { CIMOSType_CIMOS_Debian_64, SchemaDefs_OSTypeId_Debian_64 },
162 { CIMOSType_CIMOS_Linux_2_4_x, SchemaDefs_OSTypeId_Linux24 },
163 { CIMOSType_CIMOS_Linux_2_4_x_64, SchemaDefs_OSTypeId_Linux24_64 },
164 { CIMOSType_CIMOS_Linux_2_6_x, SchemaDefs_OSTypeId_Linux26 },
165 { CIMOSType_CIMOS_Linux_2_6_x_64, SchemaDefs_OSTypeId_Linux26_64 },
166 { CIMOSType_CIMOS_Linux_64, SchemaDefs_OSTypeId_Linux26_64 }
167};
168
169/* Pattern structure for matching the OS type description field */
170struct osTypePattern
171{
172 const char *pcszPattern;
173 const char *pcszVbox;
174};
175
176/* These are the 32-Bit ones. They are sorted by priority. */
177static const osTypePattern g_osTypesPattern[] =
178{
179 {"Windows NT", SchemaDefs_OSTypeId_WindowsNT4},
180 {"Windows XP", SchemaDefs_OSTypeId_WindowsXP},
181 {"Windows 2000", SchemaDefs_OSTypeId_Windows2000},
182 {"Windows 2003", SchemaDefs_OSTypeId_Windows2003},
183 {"Windows Vista", SchemaDefs_OSTypeId_WindowsVista},
184 {"Windows 2008", SchemaDefs_OSTypeId_Windows2008},
185 {"SUSE", SchemaDefs_OSTypeId_OpenSUSE},
186 {"Novell", SchemaDefs_OSTypeId_OpenSUSE},
187 {"Red Hat", SchemaDefs_OSTypeId_RedHat},
188 {"Mandriva", SchemaDefs_OSTypeId_Mandriva},
189 {"Ubuntu", SchemaDefs_OSTypeId_Ubuntu},
190 {"Debian", SchemaDefs_OSTypeId_Debian},
191 {"QNX", SchemaDefs_OSTypeId_QNX},
192 {"Linux 2.4", SchemaDefs_OSTypeId_Linux24},
193 {"Linux 2.6", SchemaDefs_OSTypeId_Linux26},
194 {"Linux", SchemaDefs_OSTypeId_Linux},
195 {"OpenSolaris", SchemaDefs_OSTypeId_OpenSolaris},
196 {"Solaris", SchemaDefs_OSTypeId_OpenSolaris},
197 {"FreeBSD", SchemaDefs_OSTypeId_FreeBSD},
198 {"NetBSD", SchemaDefs_OSTypeId_NetBSD},
199 {"Windows 95", SchemaDefs_OSTypeId_Windows95},
200 {"Windows 98", SchemaDefs_OSTypeId_Windows98},
201 {"Windows Me", SchemaDefs_OSTypeId_WindowsMe},
202 {"Windows 3.", SchemaDefs_OSTypeId_Windows31},
203 {"DOS", SchemaDefs_OSTypeId_DOS},
204 {"OS2", SchemaDefs_OSTypeId_OS2}
205};
206
207/* These are the 64-Bit ones. They are sorted by priority. */
208static const osTypePattern g_osTypesPattern64[] =
209{
210 {"Windows XP", SchemaDefs_OSTypeId_WindowsXP_64},
211 {"Windows 2003", SchemaDefs_OSTypeId_Windows2003_64},
212 {"Windows Vista", SchemaDefs_OSTypeId_WindowsVista_64},
213 {"Windows 2008", SchemaDefs_OSTypeId_Windows2008_64},
214 {"SUSE", SchemaDefs_OSTypeId_OpenSUSE_64},
215 {"Novell", SchemaDefs_OSTypeId_OpenSUSE_64},
216 {"Red Hat", SchemaDefs_OSTypeId_RedHat_64},
217 {"Mandriva", SchemaDefs_OSTypeId_Mandriva_64},
218 {"Ubuntu", SchemaDefs_OSTypeId_Ubuntu_64},
219 {"Debian", SchemaDefs_OSTypeId_Debian_64},
220 {"Linux 2.4", SchemaDefs_OSTypeId_Linux24_64},
221 {"Linux 2.6", SchemaDefs_OSTypeId_Linux26_64},
222 {"Linux", SchemaDefs_OSTypeId_Linux26_64},
223 {"OpenSolaris", SchemaDefs_OSTypeId_OpenSolaris_64},
224 {"Solaris", SchemaDefs_OSTypeId_OpenSolaris_64},
225 {"FreeBSD", SchemaDefs_OSTypeId_FreeBSD_64},
226};
227
228/**
229 * Private helper func that suggests a VirtualBox guest OS type
230 * for the given OVF operating system type.
231 * @param osTypeVBox
232 * @param c
233 * @param cStr
234 */
235static void convertCIMOSType2VBoxOSType(Utf8Str &strType, CIMOSType_T c, const Utf8Str &cStr)
236{
237 /* First check if the type is other/other_64 */
238 if (c == CIMOSType_CIMOS_Other)
239 {
240 for (size_t i=0; i < RT_ELEMENTS(g_osTypesPattern); ++i)
241 if (cStr.contains (g_osTypesPattern[i].pcszPattern, Utf8Str::CaseInsensitive))
242 {
243 strType = g_osTypesPattern[i].pcszVbox;
244 return;
245 }
246 }
247 else if (c == CIMOSType_CIMOS_Other_64)
248 {
249 for (size_t i=0; i < RT_ELEMENTS(g_osTypesPattern64); ++i)
250 if (cStr.contains (g_osTypesPattern64[i].pcszPattern, Utf8Str::CaseInsensitive))
251 {
252 strType = g_osTypesPattern64[i].pcszVbox;
253 return;
254 }
255 }
256
257 for (size_t i = 0; i < RT_ELEMENTS(g_osTypes); ++i)
258 {
259 if (c == g_osTypes[i].cim)
260 {
261 strType = g_osTypes[i].pcszVbox;
262 return;
263 }
264 }
265
266 strType = SchemaDefs_OSTypeId_Other;
267}
268
269/**
270 * Private helper func that suggests a VirtualBox guest OS type
271 * for the given OVF operating system type.
272 * @param osTypeVBox
273 * @param c
274 */
275static CIMOSType_T convertVBoxOSType2CIMOSType(const char *pcszVbox)
276{
277 for (size_t i = 0; i < RT_ELEMENTS(g_osTypes); ++i)
278 {
279 if (!RTStrICmp(pcszVbox, g_osTypes[i].pcszVbox))
280 return g_osTypes[i].cim;
281 }
282
283 return CIMOSType_CIMOS_Other;
284}
285
286////////////////////////////////////////////////////////////////////////////////
287//
288// IVirtualBox public methods
289//
290////////////////////////////////////////////////////////////////////////////////
291
292// This code is here so we won't have to include the appliance headers in the
293// IVirtualBox implementation.
294
295/**
296 * Implementation for IVirtualBox::createAppliance.
297 *
298 * @param anAppliance IAppliance object created if S_OK is returned.
299 * @return S_OK or error.
300 */
301STDMETHODIMP VirtualBox::CreateAppliance(IAppliance** anAppliance)
302{
303 HRESULT rc;
304
305 ComObjPtr<Appliance> appliance;
306 appliance.createObject();
307 rc = appliance->init(this);
308
309 if (SUCCEEDED(rc))
310 appliance.queryInterfaceTo(anAppliance);
311
312 return rc;
313}
314
315////////////////////////////////////////////////////////////////////////////////
316//
317// Appliance constructor / destructor
318//
319////////////////////////////////////////////////////////////////////////////////
320
321DEFINE_EMPTY_CTOR_DTOR(Appliance)
322
323/**
324 * Appliance COM initializer.
325 * @param
326 * @return
327 */
328HRESULT Appliance::init(VirtualBox *aVirtualBox)
329{
330 /* Enclose the state transition NotReady->InInit->Ready */
331 AutoInitSpan autoInitSpan(this);
332 AssertReturn(autoInitSpan.isOk(), E_FAIL);
333
334 /* Weak reference to a VirtualBox object */
335 unconst(mVirtualBox) = aVirtualBox;
336
337 // initialize data
338 m = new Data;
339
340 /* Confirm a successful initialization */
341 autoInitSpan.setSucceeded();
342
343 return S_OK;
344}
345
346/**
347 * Appliance COM uninitializer.
348 * @return
349 */
350void Appliance::uninit()
351{
352 /* Enclose the state transition Ready->InUninit->NotReady */
353 AutoUninitSpan autoUninitSpan(this);
354 if (autoUninitSpan.uninitDone())
355 return;
356
357 delete m;
358 m = NULL;
359}
360
361////////////////////////////////////////////////////////////////////////////////
362//
363// Appliance private methods
364//
365////////////////////////////////////////////////////////////////////////////////
366
367HRESULT Appliance::searchUniqueVMName(Utf8Str& aName) const
368{
369 IMachine *machine = NULL;
370 char *tmpName = RTStrDup(aName.c_str());
371 int i = 1;
372 /* @todo: Maybe too cost-intensive; try to find a lighter way */
373 while (mVirtualBox->FindMachine(Bstr(tmpName), &machine) != VBOX_E_OBJECT_NOT_FOUND)
374 {
375 RTStrFree(tmpName);
376 RTStrAPrintf(&tmpName, "%s_%d", aName.c_str(), i);
377 ++i;
378 }
379 aName = tmpName;
380 RTStrFree(tmpName);
381
382 return S_OK;
383}
384
385HRESULT Appliance::searchUniqueDiskImageFilePath(Utf8Str& aName) const
386{
387 IMedium *harddisk = NULL;
388 char *tmpName = RTStrDup(aName.c_str());
389 int i = 1;
390 /* Check if the file exists or if a file with this path is registered
391 * already */
392 /* @todo: Maybe too cost-intensive; try to find a lighter way */
393 while (RTPathExists(tmpName) ||
394 mVirtualBox->FindHardDisk(Bstr(tmpName), &harddisk) != VBOX_E_OBJECT_NOT_FOUND)
395 {
396 RTStrFree(tmpName);
397 char *tmpDir = RTStrDup(aName.c_str());
398 RTPathStripFilename(tmpDir);;
399 char *tmpFile = RTStrDup(RTPathFilename(aName.c_str()));
400 RTPathStripExt(tmpFile);
401 const char *tmpExt = RTPathExt(aName.c_str());
402 RTStrAPrintf(&tmpName, "%s%c%s_%d%s", tmpDir, RTPATH_DELIMITER, tmpFile, i, tmpExt);
403 RTStrFree(tmpFile);
404 RTStrFree(tmpDir);
405 ++i;
406 }
407 aName = tmpName;
408 RTStrFree(tmpName);
409
410 return S_OK;
411}
412
413/**
414 * Called from the import and export background threads to synchronize the second
415 * background disk thread's progress object with the current progress object so
416 * that the user interface sees progress correctly and that cancel signals are
417 * passed on to the second thread.
418 * @param pProgressThis Progress object of the current thread.
419 * @param pProgressAsync Progress object of asynchronous task running in background.
420 */
421void Appliance::waitForAsyncProgress(ComObjPtr<Progress> &pProgressThis,
422 ComPtr<IProgress> &pProgressAsync)
423{
424 HRESULT rc;
425
426 // now loop until the asynchronous operation completes and then report its result
427 BOOL fCompleted;
428 BOOL fCanceled;
429 ULONG currentPercent;
430 while (SUCCEEDED(pProgressAsync->COMGETTER(Completed(&fCompleted))))
431 {
432 rc = pProgressThis->COMGETTER(Canceled)(&fCanceled);
433 if (FAILED(rc)) throw rc;
434 if (fCanceled)
435 {
436 pProgressAsync->Cancel();
437 break;
438 }
439
440 rc = pProgressAsync->COMGETTER(Percent(&currentPercent));
441 if (FAILED(rc)) throw rc;
442 if (!pProgressThis.isNull())
443 pProgressThis->SetCurrentOperationProgress(currentPercent);
444 if (fCompleted)
445 break;
446
447 /* Make sure the loop is not too tight */
448 rc = pProgressAsync->WaitForCompletion(100);
449 if (FAILED(rc)) throw rc;
450 }
451 // report result of asynchronous operation
452 LONG iRc;
453 rc = pProgressAsync->COMGETTER(ResultCode)(&iRc);
454 if (FAILED(rc)) throw rc;
455
456
457 // if the thread of the progress object has an error, then
458 // retrieve the error info from there, or it'll be lost
459 if (FAILED(iRc))
460 {
461 ProgressErrorInfo info(pProgressAsync);
462 Utf8Str str(info.getText());
463 const char *pcsz = str.c_str();
464 HRESULT rc2 = setError(iRc, pcsz);
465 throw rc2;
466 }
467}
468
469void Appliance::addWarning(const char* aWarning, ...)
470{
471 va_list args;
472 va_start(args, aWarning);
473 Utf8StrFmtVA str(aWarning, args);
474 va_end(args);
475 m->llWarnings.push_back(str);
476}
477
478void Appliance::disksWeight(uint32_t &ulTotalMB, uint32_t &cDisks) const
479{
480 ulTotalMB = 0;
481 cDisks = 0;
482 /* Weigh the disk images according to their sizes */
483 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
484 for (it = m->virtualSystemDescriptions.begin();
485 it != m->virtualSystemDescriptions.end();
486 ++it)
487 {
488 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
489 /* One for every hard disk of the Virtual System */
490 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
491 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
492 for (itH = avsdeHDs.begin();
493 itH != avsdeHDs.end();
494 ++itH)
495 {
496 const VirtualSystemDescriptionEntry *pHD = *itH;
497 ulTotalMB += pHD->ulSizeMB;
498 ++cDisks;
499 }
500 }
501
502}
503
504HRESULT Appliance::setUpProgressFS(ComObjPtr<Progress> &pProgress, const Bstr &bstrDescription)
505{
506 HRESULT rc;
507
508 /* Create the progress object */
509 pProgress.createObject();
510
511 /* Weigh the disk images according to their sizes */
512 uint32_t ulTotalMB;
513 uint32_t cDisks;
514 disksWeight(ulTotalMB, cDisks);
515
516 ULONG cOperations = 1 + cDisks; // one op per disk plus 1 for the XML
517
518 ULONG ulTotalOperationsWeight;
519 if (ulTotalMB)
520 {
521 m->ulWeightPerOperation = (ULONG)((double)ulTotalMB * 1 / 100); // use 1% of the progress for the XML
522 ulTotalOperationsWeight = ulTotalMB + m->ulWeightPerOperation;
523 }
524 else
525 {
526 // no disks to export:
527 ulTotalOperationsWeight = 1;
528 m->ulWeightPerOperation = 1;
529 }
530
531 Log(("Setting up progress object: ulTotalMB = %d, cDisks = %d, => cOperations = %d, ulTotalOperationsWeight = %d, m->ulWeightPerOperation = %d\n",
532 ulTotalMB, cDisks, cOperations, ulTotalOperationsWeight, m->ulWeightPerOperation));
533
534 rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
535 bstrDescription,
536 TRUE /* aCancelable */,
537 cOperations, // ULONG cOperations,
538 ulTotalOperationsWeight, // ULONG ulTotalOperationsWeight,
539 bstrDescription, // CBSTR bstrFirstOperationDescription,
540 m->ulWeightPerOperation); // ULONG ulFirstOperationWeight,
541 return rc;
542}
543
544HRESULT Appliance::setUpProgressImportS3(ComObjPtr<Progress> &pProgress, const Bstr &bstrDescription)
545{
546 HRESULT rc;
547
548 /* Create the progress object */
549 pProgress.createObject();
550
551 /* Weigh the disk images according to their sizes */
552 uint32_t ulTotalMB;
553 uint32_t cDisks;
554 disksWeight(ulTotalMB, cDisks);
555
556 ULONG cOperations = 1 + 1 + 1 + cDisks; // one op per disk plus 1 for init, plus 1 for the manifest file & 1 plus for the import */
557
558 ULONG ulTotalOperationsWeight = ulTotalMB;
559 if (!ulTotalOperationsWeight)
560 // no disks to export:
561 ulTotalOperationsWeight = 1;
562
563 ULONG ulImportWeight = (ULONG)((double)ulTotalOperationsWeight * 50 / 100); // use 50% for import
564 ulTotalOperationsWeight += ulImportWeight;
565
566 m->ulWeightPerOperation = ulImportWeight; /* save for using later */
567
568 ULONG ulInitWeight = (ULONG)((double)ulTotalOperationsWeight * 0.1 / 100); // use 0.1% for init
569 ulTotalOperationsWeight += ulInitWeight;
570
571 Log(("Setting up progress object: ulTotalMB = %d, cDisks = %d, => cOperations = %d, ulTotalOperationsWeight = %d, m->ulWeightPerOperation = %d\n",
572 ulTotalMB, cDisks, cOperations, ulTotalOperationsWeight, m->ulWeightPerOperation));
573
574 rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
575 bstrDescription,
576 TRUE /* aCancelable */,
577 cOperations, // ULONG cOperations,
578 ulTotalOperationsWeight, // ULONG ulTotalOperationsWeight,
579 Bstr(tr("Init")), // CBSTR bstrFirstOperationDescription,
580 ulInitWeight); // ULONG ulFirstOperationWeight,
581 return rc;
582}
583
584HRESULT Appliance::setUpProgressWriteS3(ComObjPtr<Progress> &pProgress, const Bstr &bstrDescription)
585{
586 HRESULT rc;
587
588 /* Create the progress object */
589 pProgress.createObject();
590
591 /* Weigh the disk images according to their sizes */
592 uint32_t ulTotalMB;
593 uint32_t cDisks;
594 disksWeight(ulTotalMB, cDisks);
595
596 ULONG cOperations = 1 + 1 + 1 + cDisks; // one op per disk plus 1 for the OVF, plus 1 for the mf & 1 plus to the temporary creation */
597
598 ULONG ulTotalOperationsWeight;
599 if (ulTotalMB)
600 {
601 m->ulWeightPerOperation = (ULONG)((double)ulTotalMB * 1 / 100); // use 1% of the progress for OVF file upload (we didn't know the size at this point)
602 ulTotalOperationsWeight = ulTotalMB + m->ulWeightPerOperation;
603 }
604 else
605 {
606 // no disks to export:
607 ulTotalOperationsWeight = 1;
608 m->ulWeightPerOperation = 1;
609 }
610 ULONG ulOVFCreationWeight = (ULONG)((double)ulTotalOperationsWeight * 50.0 / 100.0); /* Use 50% for the creation of the OVF & the disks */
611 ulTotalOperationsWeight += ulOVFCreationWeight;
612
613 Log(("Setting up progress object: ulTotalMB = %d, cDisks = %d, => cOperations = %d, ulTotalOperationsWeight = %d, m->ulWeightPerOperation = %d\n",
614 ulTotalMB, cDisks, cOperations, ulTotalOperationsWeight, m->ulWeightPerOperation));
615
616 rc = pProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
617 bstrDescription,
618 TRUE /* aCancelable */,
619 cOperations, // ULONG cOperations,
620 ulTotalOperationsWeight, // ULONG ulTotalOperationsWeight,
621 bstrDescription, // CBSTR bstrFirstOperationDescription,
622 ulOVFCreationWeight); // ULONG ulFirstOperationWeight,
623 return rc;
624}
625
626void Appliance::parseURI(Utf8Str strUri, LocationInfo &locInfo) const
627{
628 /* Check the URI for the protocol */
629 if (strUri.startsWith("file://", Utf8Str::CaseInsensitive)) /* File based */
630 {
631 locInfo.storageType = VFSType_File;
632 strUri = strUri.substr(sizeof("file://") - 1);
633 }
634 else if (strUri.startsWith("SunCloud://", Utf8Str::CaseInsensitive)) /* Sun Cloud service */
635 {
636 locInfo.storageType = VFSType_S3;
637 strUri = strUri.substr(sizeof("SunCloud://") - 1);
638 }
639 else if (strUri.startsWith("S3://", Utf8Str::CaseInsensitive)) /* S3 service */
640 {
641 locInfo.storageType = VFSType_S3;
642 strUri = strUri.substr(sizeof("S3://") - 1);
643 }
644 else if (strUri.startsWith("webdav://", Utf8Str::CaseInsensitive)) /* webdav service */
645 throw E_NOTIMPL;
646
647 /* Not necessary on a file based URI */
648 if (locInfo.storageType != VFSType_File)
649 {
650 size_t uppos = strUri.find("@"); /* username:password combo */
651 if (uppos != Utf8Str::npos)
652 {
653 locInfo.strUsername = strUri.substr(0, uppos);
654 strUri = strUri.substr(uppos + 1);
655 size_t upos = locInfo.strUsername.find(":");
656 if (upos != Utf8Str::npos)
657 {
658 locInfo.strPassword = locInfo.strUsername.substr(upos + 1);
659 locInfo.strUsername = locInfo.strUsername.substr(0, upos);
660 }
661 }
662 size_t hpos = strUri.find("/"); /* hostname part */
663 if (hpos != Utf8Str::npos)
664 {
665 locInfo.strHostname = strUri.substr(0, hpos);
666 strUri = strUri.substr(hpos);
667 }
668 }
669
670 locInfo.strPath = strUri;
671}
672
673void Appliance::parseBucket(Utf8Str &aPath, Utf8Str &aBucket) const
674{
675 /* Buckets are S3 specific. So parse the bucket out of the file path */
676 if (!aPath.startsWith("/"))
677 throw setError(E_INVALIDARG,
678 tr("The path '%s' must start with /"), aPath.c_str());
679 size_t bpos = aPath.find("/", 1);
680 if (bpos != Utf8Str::npos)
681 {
682 aBucket = aPath.substr(1, bpos - 1); /* The bucket without any slashes */
683 aPath = aPath.substr(bpos); /* The rest of the file path */
684 }
685 /* If there is no bucket name provided reject it */
686 if (aBucket.isEmpty())
687 throw setError(E_INVALIDARG,
688 tr("You doesn't provide a bucket name in the URI '%s'"), aPath.c_str());
689}
690
691Utf8Str Appliance::manifestFileName(Utf8Str aPath) const
692{
693 /* Get the name part */
694 char *pszMfName = RTStrDup(RTPathFilename(aPath.c_str()));
695 /* Strip any extensions */
696 RTPathStripExt(pszMfName);
697 /* Path without the filename */
698 aPath.stripFilename();
699 /* Format the manifest path */
700 Utf8StrFmt strMfFile("%s/%s.mf", aPath.c_str(), pszMfName);
701 RTStrFree(pszMfName);
702 return strMfFile;
703}
704
705struct Appliance::TaskOVF
706{
707 TaskOVF(Appliance *aThat)
708 : pAppliance(aThat)
709 , rc(S_OK) {}
710
711 static int updateProgress(unsigned uPercent, void *pvUser);
712
713 LocationInfo locInfo;
714 Appliance *pAppliance;
715 ComObjPtr<Progress> progress;
716 HRESULT rc;
717};
718
719struct Appliance::TaskImportOVF: Appliance::TaskOVF
720{
721 enum TaskType
722 {
723 Read,
724 Import
725 };
726
727 TaskImportOVF(Appliance *aThat)
728 : TaskOVF(aThat)
729 , taskType(Read) {}
730
731 int startThread();
732
733 TaskType taskType;
734};
735
736struct Appliance::TaskExportOVF: Appliance::TaskOVF
737{
738 enum OVFFormat
739 {
740 unspecified,
741 OVF_0_9,
742 OVF_1_0
743 };
744 enum TaskType
745 {
746 Write
747 };
748
749 TaskExportOVF(Appliance *aThat)
750 : TaskOVF(aThat)
751 , taskType(Write) {}
752
753 int startThread();
754
755 TaskType taskType;
756 OVFFormat enFormat;
757};
758
759struct MyHardDiskAttachment
760{
761 Guid uuid;
762 ComPtr<IMachine> pMachine;
763 Bstr controllerType;
764 int32_t lChannel;
765 int32_t lDevice;
766};
767
768/* static */
769int Appliance::TaskOVF::updateProgress(unsigned uPercent, void *pvUser)
770{
771 Appliance::TaskOVF* pTask = *(Appliance::TaskOVF**)pvUser;
772
773 if (pTask &&
774 !pTask->progress.isNull())
775 {
776 BOOL fCanceled;
777 pTask->progress->COMGETTER(Canceled)(&fCanceled);
778 if (fCanceled)
779 return -1;
780 pTask->progress->SetCurrentOperationProgress(uPercent);
781 }
782 return VINF_SUCCESS;
783}
784
785HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
786{
787 /* Initialize our worker task */
788 std::auto_ptr<TaskImportOVF> task(new TaskImportOVF(this));
789 /* What should the task do */
790 task->taskType = TaskImportOVF::Read;
791 /* Copy the current location info to the task */
792 task->locInfo = aLocInfo;
793
794 BstrFmt bstrDesc = BstrFmt(tr("Read appliance '%s'"),
795 aLocInfo.strPath.c_str());
796 HRESULT rc;
797 /* Create the progress object */
798 aProgress.createObject();
799 if (task->locInfo.storageType == VFSType_File)
800 {
801 /* 1 operation only */
802 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
803 bstrDesc,
804 TRUE /* aCancelable */);
805 }
806 else
807 {
808 /* 4/5 is downloading, 1/5 is reading */
809 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
810 bstrDesc,
811 TRUE /* aCancelable */,
812 2, // ULONG cOperations,
813 5, // ULONG ulTotalOperationsWeight,
814 BstrFmt(tr("Download appliance '%s'"),
815 aLocInfo.strPath.c_str()), // CBSTR bstrFirstOperationDescription,
816 4); // ULONG ulFirstOperationWeight,
817 }
818 if (FAILED(rc)) throw rc;
819
820 task->progress = aProgress;
821
822 rc = task->startThread();
823 CheckComRCThrowRC(rc);
824
825 /* Don't destruct on success */
826 task.release();
827
828 return rc;
829}
830
831HRESULT Appliance::importImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
832{
833 /* Initialize our worker task */
834 std::auto_ptr<TaskImportOVF> task(new TaskImportOVF(this));
835 /* What should the task do */
836 task->taskType = TaskImportOVF::Import;
837 /* Copy the current location info to the task */
838 task->locInfo = aLocInfo;
839
840 Bstr progressDesc = BstrFmt(tr("Import appliance '%s'"),
841 aLocInfo.strPath.c_str());
842
843 HRESULT rc = S_OK;
844
845 /* todo: This progress init stuff should be done a little bit more generic */
846 if (task->locInfo.storageType == VFSType_File)
847 rc = setUpProgressFS(aProgress, progressDesc);
848 else
849 rc = setUpProgressImportS3(aProgress, progressDesc);
850 if (FAILED(rc)) throw rc;
851
852 task->progress = aProgress;
853
854 rc = task->startThread();
855 CheckComRCThrowRC(rc);
856
857 /* Don't destruct on success */
858 task.release();
859
860 return rc;
861}
862
863/**
864 * Worker thread implementation for Read() (ovf reader).
865 * @param aThread
866 * @param pvUser
867 */
868/* static */
869DECLCALLBACK(int) Appliance::taskThreadImportOVF(RTTHREAD /* aThread */, void *pvUser)
870{
871 std::auto_ptr<TaskImportOVF> task(static_cast<TaskImportOVF*>(pvUser));
872 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
873
874 Appliance *pAppliance = task->pAppliance;
875
876 LogFlowFuncEnter();
877 LogFlowFunc(("Appliance %p\n", pAppliance));
878
879 HRESULT rc = S_OK;
880
881 switch(task->taskType)
882 {
883 case TaskImportOVF::Read:
884 {
885 if (task->locInfo.storageType == VFSType_File)
886 rc = pAppliance->readFS(task.get());
887 else if (task->locInfo.storageType == VFSType_S3)
888 rc = pAppliance->readS3(task.get());
889 break;
890 }
891 case TaskImportOVF::Import:
892 {
893 if (task->locInfo.storageType == VFSType_File)
894 rc = pAppliance->importFS(task.get());
895 else if (task->locInfo.storageType == VFSType_S3)
896 rc = pAppliance->importS3(task.get());
897 break;
898 }
899 }
900
901 LogFlowFunc(("rc=%Rhrc\n", rc));
902 LogFlowFuncLeave();
903
904 return VINF_SUCCESS;
905}
906
907int Appliance::TaskImportOVF::startThread()
908{
909 int vrc = RTThreadCreate(NULL, Appliance::taskThreadImportOVF, this,
910 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
911 "Appliance::Task");
912
913 ComAssertMsgRCRet(vrc,
914 ("Could not create taskThreadImportOVF (%Rrc)\n", vrc), E_FAIL);
915
916 return S_OK;
917}
918
919int Appliance::readFS(TaskImportOVF *pTask)
920{
921 LogFlowFuncEnter();
922 LogFlowFunc(("Appliance %p\n", this));
923
924 AutoCaller autoCaller(this);
925 CheckComRCReturnRC(autoCaller.rc());
926
927 AutoWriteLock appLock(this);
928
929 HRESULT rc = S_OK;
930
931 try
932 {
933 /* Read & parse the XML structure of the OVF file */
934 m->pReader = new OVFReader(pTask->locInfo.strPath);
935 /* Create the SHA1 sum of the OVF file for later validation */
936 char *pszDigest;
937 int vrc = RTSha1Digest(pTask->locInfo.strPath.c_str(), &pszDigest);
938 if (RT_FAILURE(vrc))
939 throw setError(VBOX_E_FILE_ERROR,
940 tr("Couldn't calculate SHA1 digest for file '%s' (%Rrc)"),
941 RTPathFilename(pTask->locInfo.strPath.c_str()), vrc);
942 m->strOVFSHA1Digest = pszDigest;
943 RTStrFree(pszDigest);
944 }
945 catch(xml::Error &x)
946 {
947 rc = setError(VBOX_E_FILE_ERROR,
948 x.what());
949 }
950
951 pTask->rc = rc;
952
953 if (!pTask->progress.isNull())
954 pTask->progress->notifyComplete(rc);
955
956 LogFlowFunc(("rc=%Rhrc\n", rc));
957 LogFlowFuncLeave();
958
959 return VINF_SUCCESS;
960}
961
962int Appliance::readS3(TaskImportOVF *pTask)
963{
964 LogFlowFuncEnter();
965 LogFlowFunc(("Appliance %p\n", this));
966
967 AutoCaller autoCaller(this);
968 CheckComRCReturnRC(autoCaller.rc());
969
970 AutoWriteLock appLock(this);
971
972 HRESULT rc = S_OK;
973 int vrc = VINF_SUCCESS;
974 RTS3 hS3 = NIL_RTS3;
975 char szOSTmpDir[RTPATH_MAX];
976 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
977 /* The template for the temporary directory created below */
978 char *pszTmpDir;
979 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
980 list< pair<Utf8Str, ULONG> > filesList;
981 Utf8Str strTmpOvf;
982
983 try
984 {
985 /* Extract the bucket */
986 Utf8Str tmpPath = pTask->locInfo.strPath;
987 Utf8Str bucket;
988 parseBucket(tmpPath, bucket);
989
990 /* We need a temporary directory which we can put the OVF file & all
991 * disk images in */
992 vrc = RTDirCreateTemp(pszTmpDir);
993 if (RT_FAILURE(vrc))
994 throw setError(VBOX_E_FILE_ERROR,
995 tr("Cannot create temporary directory '%s'"), pszTmpDir);
996
997 /* The temporary name of the target OVF file */
998 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
999
1000 /* Next we have to download the OVF */
1001 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1002 if(RT_FAILURE(vrc))
1003 throw setError(VBOX_E_IPRT_ERROR,
1004 tr("Cannot create S3 service handler"));
1005 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1006
1007 /* Get it */
1008 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
1009 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
1010 if (RT_FAILURE(vrc))
1011 {
1012 if(vrc == VERR_S3_CANCELED)
1013 throw S_OK; /* todo: !!!!!!!!!!!!! */
1014 else if(vrc == VERR_S3_ACCESS_DENIED)
1015 throw setError(E_ACCESSDENIED,
1016 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
1017 else if(vrc == VERR_S3_NOT_FOUND)
1018 throw setError(VBOX_E_FILE_ERROR,
1019 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1020 else
1021 throw setError(VBOX_E_IPRT_ERROR,
1022 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1023 }
1024
1025 /* Close the connection early */
1026 RTS3Destroy(hS3);
1027 hS3 = NIL_RTS3;
1028
1029 if (!pTask->progress.isNull())
1030 pTask->progress->SetNextOperation(Bstr(tr("Reading")), 1);
1031
1032 /* Prepare the temporary reading of the OVF */
1033 ComObjPtr<Progress> progress;
1034 LocationInfo li;
1035 li.strPath = strTmpOvf;
1036 /* Start the reading from the fs */
1037 rc = readImpl(li, progress);
1038 if (FAILED(rc)) throw rc;
1039
1040 /* Unlock the appliance for the reading thread */
1041 appLock.unlock();
1042 /* Wait until the reading is done, but report the progress back to the
1043 caller */
1044 ComPtr<IProgress> progressInt(progress);
1045 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
1046
1047 /* Again lock the appliance for the next steps */
1048 appLock.lock();
1049 }
1050 catch(HRESULT aRC)
1051 {
1052 rc = aRC;
1053 }
1054 /* Cleanup */
1055 RTS3Destroy(hS3);
1056 /* Delete all files which where temporary created */
1057 if (RTPathExists(strTmpOvf.c_str()))
1058 {
1059 vrc = RTFileDelete(strTmpOvf.c_str());
1060 if(RT_FAILURE(vrc))
1061 rc = setError(VBOX_E_FILE_ERROR,
1062 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
1063 }
1064 /* Delete the temporary directory */
1065 if (RTPathExists(pszTmpDir))
1066 {
1067 vrc = RTDirRemove(pszTmpDir);
1068 if(RT_FAILURE(vrc))
1069 rc = setError(VBOX_E_FILE_ERROR,
1070 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
1071 }
1072 if (pszTmpDir)
1073 RTStrFree(pszTmpDir);
1074
1075 pTask->rc = rc;
1076
1077 if (!pTask->progress.isNull())
1078 pTask->progress->notifyComplete(rc);
1079
1080 LogFlowFunc(("rc=%Rhrc\n", rc));
1081 LogFlowFuncLeave();
1082
1083 return VINF_SUCCESS;
1084}
1085
1086int Appliance::importFS(TaskImportOVF *pTask)
1087{
1088 LogFlowFuncEnter();
1089 LogFlowFunc(("Appliance %p\n", this));
1090
1091 AutoCaller autoCaller(this);
1092 CheckComRCReturnRC(autoCaller.rc());
1093
1094 AutoWriteLock appLock(this);
1095
1096 HRESULT rc = S_OK;
1097
1098 // rollback for errors:
1099 // a list of images that we created/imported
1100 list<MyHardDiskAttachment> llHardDiskAttachments;
1101 list< ComPtr<IMedium> > llHardDisksCreated;
1102 list<Guid> llMachinesRegistered;
1103
1104 ComPtr<ISession> session;
1105 bool fSessionOpen = false;
1106 rc = session.createInprocObject(CLSID_Session);
1107 CheckComRCReturnRC(rc);
1108
1109 const OVFReader reader = *m->pReader;
1110 // this is safe to access because this thread only gets started
1111 // if pReader != NULL
1112
1113 /* If an manifest file exists, verify the content. Therefor we need all
1114 * files which are referenced by the OVF & the OVF itself */
1115 Utf8Str strMfFile = manifestFileName(pTask->locInfo.strPath);
1116 list<Utf8Str> filesList;
1117 if (RTPathExists(strMfFile.c_str()))
1118 {
1119 Utf8Str strSrcDir(pTask->locInfo.strPath);
1120 strSrcDir.stripFilename();
1121 /* Add every disks of every virtual system to an internal list */
1122 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1123 for (it = m->virtualSystemDescriptions.begin();
1124 it != m->virtualSystemDescriptions.end();
1125 ++it)
1126 {
1127 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1128 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1129 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1130 for (itH = avsdeHDs.begin();
1131 itH != avsdeHDs.end();
1132 ++itH)
1133 {
1134 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1135 /* Find the disk from the OVF's disk list */
1136 DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1137 const DiskImage &di = itDiskImage->second;
1138 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1139 filesList.push_back(strSrcFilePath);
1140 }
1141 }
1142 /* Create the test list */
1143 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST)*(filesList.size()+1));
1144 pTestList[0].pszTestFile = (char*)pTask->locInfo.strPath.c_str();
1145 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1146 int vrc = VINF_SUCCESS;
1147 size_t i = 1;
1148 list<Utf8Str>::const_iterator it1;
1149 for (it1 = filesList.begin();
1150 it1 != filesList.end();
1151 ++it1, ++i)
1152 {
1153 char* pszDigest;
1154 vrc = RTSha1Digest((*it1).c_str(), &pszDigest);
1155 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1156 pTestList[i].pszTestDigest = pszDigest;
1157 }
1158 size_t cIndexOnError;
1159 vrc = RTManifestVerify(strMfFile.c_str(), pTestList, filesList.size() + 1, &cIndexOnError);
1160 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1161 rc = setError(VBOX_E_FILE_ERROR,
1162 tr("The SHA1 digest of '%s' doesn't match to the one in '%s'"),
1163 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1164 RTPathFilename(strMfFile.c_str()));
1165 else if (RT_FAILURE(vrc))
1166 rc = setError(VBOX_E_FILE_ERROR,
1167 tr("Couldn't verify the content of '%s' against the available files (%Rrc)"),
1168 RTPathFilename(strMfFile.c_str()),
1169 vrc);
1170 /* Cleanup */
1171 for (size_t i=1; i < filesList.size(); ++i)
1172 RTStrFree(pTestList[i].pszTestDigest);
1173 RTMemFree(pTestList);
1174 if (FAILED(rc))
1175 {
1176 /* Return on error */
1177 pTask->rc = rc;
1178
1179 if (!pTask->progress.isNull())
1180 pTask->progress->notifyComplete(rc);
1181 return rc;
1182 }
1183 }
1184
1185 list<VirtualSystem>::const_iterator it;
1186 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1187 /* Iterate through all virtual systems of that appliance */
1188 size_t i = 0;
1189 for (it = reader.m_llVirtualSystems.begin(),
1190 it1 = m->virtualSystemDescriptions.begin();
1191 it != reader.m_llVirtualSystems.end();
1192 ++it, ++it1, ++i)
1193 {
1194 const VirtualSystem &vsysThis = *it;
1195 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1196
1197 ComPtr<IMachine> pNewMachine;
1198
1199 /* Catch possible errors */
1200 try
1201 {
1202 /* Guest OS type */
1203 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1204 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1205 if (vsdeOS.size() < 1)
1206 throw setError(VBOX_E_FILE_ERROR,
1207 tr("Missing guest OS type"));
1208 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strVbox;
1209
1210 /* Now that we know the base system get our internal defaults based on that. */
1211 ComPtr<IGuestOSType> osType;
1212 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1213 if (FAILED(rc)) throw rc;
1214
1215 /* Create the machine */
1216 /* First get the name */
1217 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1218 if (vsdeName.size() < 1)
1219 throw setError(VBOX_E_FILE_ERROR,
1220 tr("Missing VM name"));
1221 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
1222 rc = mVirtualBox->CreateMachine(Bstr(strNameVBox), Bstr(strOsTypeVBox),
1223 Bstr(), Bstr(),
1224 pNewMachine.asOutParam());
1225 if (FAILED(rc)) throw rc;
1226
1227 // and the description
1228 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1229 if (vsdeDescription.size())
1230 {
1231 const Utf8Str &strDescription = vsdeDescription.front()->strVbox;
1232 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1233 if (FAILED(rc)) throw rc;
1234 }
1235
1236 /* CPU count */
1237 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType (VirtualSystemDescriptionType_CPU);
1238 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1239 const Utf8Str &cpuVBox = vsdeCPU.front()->strVbox;
1240 ULONG tmpCount = (ULONG)RTStrToUInt64(cpuVBox.c_str());
1241 rc = pNewMachine->COMSETTER(CPUCount)(tmpCount);
1242 if (FAILED(rc)) throw rc;
1243 bool fEnableIOApic = false;
1244 /* We need HWVirt & IO-APIC if more than one CPU is requested */
1245 if (tmpCount > 1)
1246 {
1247 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1248 if (FAILED(rc)) throw rc;
1249
1250 fEnableIOApic = true;
1251 }
1252
1253 /* RAM */
1254 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1255 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1256 const Utf8Str &memoryVBox = vsdeRAM.front()->strVbox;
1257 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1258 rc = pNewMachine->COMSETTER(MemorySize)(tt);
1259 if (FAILED(rc)) throw rc;
1260
1261 /* VRAM */
1262 /* Get the recommended VRAM for this guest OS type */
1263 ULONG vramVBox;
1264 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1265 if (FAILED(rc)) throw rc;
1266
1267 /* Set the VRAM */
1268 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1269 if (FAILED(rc)) throw rc;
1270
1271 /* I/O APIC: so far we have no setting for this. Enable it if we
1272 import a Windows VM because if if Windows was installed without IOAPIC,
1273 it will not mind finding an one later on, but if Windows was installed
1274 _with_ an IOAPIC, it will bluescreen if it's not found */
1275 Bstr bstrFamilyId;
1276 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1277 if (FAILED(rc)) throw rc;
1278
1279 Utf8Str strFamilyId(bstrFamilyId);
1280 if (strFamilyId == "Windows")
1281 fEnableIOApic = true;
1282
1283 /* If IP-APIC should be enabled could be have different reasons.
1284 See CPU count & the Win test above. Here we enable it if it was
1285 previously requested. */
1286 if (fEnableIOApic)
1287 {
1288 ComPtr<IBIOSSettings> pBIOSSettings;
1289 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1290 if (FAILED(rc)) throw rc;
1291
1292 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1293 if (FAILED(rc)) throw rc;
1294 }
1295
1296 /* Audio Adapter */
1297 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1298 /* @todo: we support one audio adapter only */
1299 if (vsdeAudioAdapter.size() > 0)
1300 {
1301 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strVbox;
1302 if (audioAdapterVBox.compare("null", Utf8Str::CaseInsensitive) != 0)
1303 {
1304 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1305 ComPtr<IAudioAdapter> audioAdapter;
1306 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1307 if (FAILED(rc)) throw rc;
1308 rc = audioAdapter->COMSETTER(Enabled)(true);
1309 if (FAILED(rc)) throw rc;
1310 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1311 if (FAILED(rc)) throw rc;
1312 }
1313 }
1314
1315#ifdef VBOX_WITH_USB
1316 /* USB Controller */
1317 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1318 // USB support is enabled if there's at least one such entry; to disable USB support,
1319 // the type of the USB item would have been changed to "ignore"
1320 bool fUSBEnabled = vsdeUSBController.size() > 0;
1321
1322 ComPtr<IUSBController> usbController;
1323 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1324 if (FAILED(rc)) throw rc;
1325 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1326 if (FAILED(rc)) throw rc;
1327#endif /* VBOX_WITH_USB */
1328
1329 /* Change the network adapters */
1330 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1331 if (vsdeNW.size() == 0)
1332 {
1333 /* No network adapters, so we have to disable our default one */
1334 ComPtr<INetworkAdapter> nwVBox;
1335 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1336 if (FAILED(rc)) throw rc;
1337 rc = nwVBox->COMSETTER(Enabled)(false);
1338 if (FAILED(rc)) throw rc;
1339 }
1340 else
1341 {
1342 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1343 /* Iterate through all network cards. We support 8 network adapters
1344 * at the maximum. (@todo: warn if there are more!) */
1345 size_t a = 0;
1346 for (nwIt = vsdeNW.begin();
1347 (nwIt != vsdeNW.end() && a < SchemaDefs::NetworkAdapterCount);
1348 ++nwIt, ++a)
1349 {
1350 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1351
1352 const Utf8Str &nwTypeVBox = pvsys->strVbox;
1353 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1354 ComPtr<INetworkAdapter> pNetworkAdapter;
1355 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1356 if (FAILED(rc)) throw rc;
1357 /* Enable the network card & set the adapter type */
1358 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1359 if (FAILED(rc)) throw rc;
1360 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1361 if (FAILED(rc)) throw rc;
1362
1363 // default is NAT; change to "bridged" if extra conf says so
1364 if (!pvsys->strExtraConfig.compare("type=Bridged", Utf8Str::CaseInsensitive))
1365 {
1366 /* Attach to the right interface */
1367 rc = pNetworkAdapter->AttachToBridgedInterface();
1368 if (FAILED(rc)) throw rc;
1369 ComPtr<IHost> host;
1370 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1371 if (FAILED(rc)) throw rc;
1372 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1373 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1374 if (FAILED(rc)) throw rc;
1375 /* We search for the first host network interface which
1376 * is usable for bridged networking */
1377 for (size_t i=0; i < nwInterfaces.size(); ++i)
1378 {
1379 HostNetworkInterfaceType_T itype;
1380 rc = nwInterfaces[i]->COMGETTER(InterfaceType)(&itype);
1381 if (FAILED(rc)) throw rc;
1382 if (itype == HostNetworkInterfaceType_Bridged)
1383 {
1384 Bstr name;
1385 rc = nwInterfaces[i]->COMGETTER(Name)(name.asOutParam());
1386 if (FAILED(rc)) throw rc;
1387 /* Set the interface name to attach to */
1388 pNetworkAdapter->COMSETTER(HostInterface)(name);
1389 if (FAILED(rc)) throw rc;
1390 break;
1391 }
1392 }
1393 }
1394 /* Next test for host only interfaces */
1395 else if (!pvsys->strExtraConfig.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1396 {
1397 /* Attach to the right interface */
1398 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1399 if (FAILED(rc)) throw rc;
1400 ComPtr<IHost> host;
1401 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1402 if (FAILED(rc)) throw rc;
1403 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1404 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1405 if (FAILED(rc)) throw rc;
1406 /* We search for the first host network interface which
1407 * is usable for host only networking */
1408 for (size_t i=0; i < nwInterfaces.size(); ++i)
1409 {
1410 HostNetworkInterfaceType_T itype;
1411 rc = nwInterfaces[i]->COMGETTER(InterfaceType)(&itype);
1412 if (FAILED(rc)) throw rc;
1413 if (itype == HostNetworkInterfaceType_HostOnly)
1414 {
1415 Bstr name;
1416 rc = nwInterfaces[i]->COMGETTER(Name)(name.asOutParam());
1417 if (FAILED(rc)) throw rc;
1418 /* Set the interface name to attach to */
1419 pNetworkAdapter->COMSETTER(HostInterface)(name);
1420 if (FAILED(rc)) throw rc;
1421 break;
1422 }
1423 }
1424 }
1425 }
1426 }
1427
1428 // Floppy support
1429 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1430 if (vsdeFloppy.size() > 1)
1431 throw setError(VBOX_E_FILE_ERROR,
1432 tr("Too many floppy controllers in OVF; import facility only supports one"));
1433 if (vsdeFloppy.size() == 1)
1434 {
1435 ComPtr<IStorageController> pController;
1436 rc = pNewMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1437 if (FAILED(rc)) throw rc;
1438
1439 Bstr bstrName;
1440 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1441 if (FAILED(rc)) throw rc;
1442
1443 rc = pNewMachine->AttachDevice(bstrName, 0, 0, DeviceType_Floppy, Bstr(""));
1444 if (FAILED(rc)) throw rc;
1445 }
1446
1447 /* Hard disk controller IDE */
1448 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1449 if (vsdeHDCIDE.size() > 1)
1450 throw setError(VBOX_E_FILE_ERROR,
1451 tr("Too many IDE controllers in OVF; import facility only supports one"));
1452 if (vsdeHDCIDE.size() == 1)
1453 {
1454 ComPtr<IStorageController> pController;
1455 rc = pNewMachine->AddStorageController(Bstr("IDE Controller"), StorageBus_IDE, pController.asOutParam());
1456 if (FAILED(rc)) throw rc;
1457
1458 const char *pcszIDEType = vsdeHDCIDE.front()->strVbox.c_str();
1459 if (!strcmp(pcszIDEType, "PIIX3"))
1460 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1461 else if (!strcmp(pcszIDEType, "PIIX4"))
1462 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1463 else if (!strcmp(pcszIDEType, "ICH6"))
1464 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1465 else
1466 throw setError(VBOX_E_FILE_ERROR,
1467 tr("Invalid IDE controller type \"%s\""),
1468 pcszIDEType);
1469 if (FAILED(rc)) throw rc;
1470 }
1471#ifdef VBOX_WITH_AHCI
1472 /* Hard disk controller SATA */
1473 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1474 if (vsdeHDCSATA.size() > 1)
1475 throw setError(VBOX_E_FILE_ERROR,
1476 tr("Too many SATA controllers in OVF; VirtualBox only supports one"));
1477 if (vsdeHDCSATA.size() > 0)
1478 {
1479 ComPtr<IStorageController> pController;
1480 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVbox;
1481 if (hdcVBox == "AHCI")
1482 {
1483 rc = pNewMachine->AddStorageController(Bstr("SATA Controller"), StorageBus_SATA, pController.asOutParam());
1484 if (FAILED(rc)) throw rc;
1485 }
1486 else
1487 throw setError(VBOX_E_FILE_ERROR,
1488 tr("Invalid SATA controller type \"%s\""),
1489 hdcVBox.c_str());
1490 }
1491#endif /* VBOX_WITH_AHCI */
1492
1493#ifdef VBOX_WITH_LSILOGIC
1494 /* Hard disk controller SCSI */
1495 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1496 if (vsdeHDCSCSI.size() > 1)
1497 throw setError(VBOX_E_FILE_ERROR,
1498 tr("Too many SCSI controllers in OVF; VirtualBox only supports one"));
1499 if (vsdeHDCSCSI.size() > 0)
1500 {
1501 ComPtr<IStorageController> pController;
1502 StorageControllerType_T controllerType;
1503 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVbox;
1504 if (hdcVBox == "LsiLogic")
1505 controllerType = StorageControllerType_LsiLogic;
1506 else if (hdcVBox == "BusLogic")
1507 controllerType = StorageControllerType_BusLogic;
1508 else
1509 throw setError(VBOX_E_FILE_ERROR,
1510 tr("Invalid SCSI controller type \"%s\""),
1511 hdcVBox.c_str());
1512
1513 rc = pNewMachine->AddStorageController(Bstr("SCSI Controller"), StorageBus_SCSI, pController.asOutParam());
1514 if (FAILED(rc)) throw rc;
1515 rc = pController->COMSETTER(ControllerType)(controllerType);
1516 if (FAILED(rc)) throw rc;
1517 }
1518#endif /* VBOX_WITH_LSILOGIC */
1519
1520 /* Now its time to register the machine before we add any hard disks */
1521 rc = mVirtualBox->RegisterMachine(pNewMachine);
1522 if (FAILED(rc)) throw rc;
1523
1524 Bstr newMachineId_;
1525 rc = pNewMachine->COMGETTER(Id)(newMachineId_.asOutParam());
1526 if (FAILED(rc)) throw rc;
1527 Guid newMachineId(newMachineId_);
1528
1529 // store new machine for roll-back in case of errors
1530 llMachinesRegistered.push_back(newMachineId);
1531
1532 /* Create the hard disks & connect them to the appropriate controllers. */
1533 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1534 if (avsdeHDs.size() > 0)
1535 {
1536 /* If in the next block an error occur we have to deregister
1537 the machine, so make an extra try/catch block. */
1538 ComPtr<IMedium> srcHdVBox;
1539 bool fSourceHdNeedsClosing = false;
1540
1541 try
1542 {
1543 /* In order to attach hard disks we need to open a session
1544 * for the new machine */
1545 rc = mVirtualBox->OpenSession(session, newMachineId_);
1546 if (FAILED(rc)) throw rc;
1547 fSessionOpen = true;
1548
1549 /* The disk image has to be on the same place as the OVF file. So
1550 * strip the filename out of the full file path. */
1551 Utf8Str strSrcDir(pTask->locInfo.strPath);
1552 strSrcDir.stripFilename();
1553
1554 /* Iterate over all given disk images */
1555 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1556 for (itHD = avsdeHDs.begin();
1557 itHD != avsdeHDs.end();
1558 ++itHD)
1559 {
1560 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1561
1562 /* Check if the destination file exists already or the
1563 * destination path is empty. */
1564 if ( vsdeHD->strVbox.isEmpty()
1565 || RTPathExists(vsdeHD->strVbox.c_str())
1566 )
1567 /* This isn't allowed */
1568 throw setError(VBOX_E_FILE_ERROR,
1569 tr("Destination file '%s' exists",
1570 vsdeHD->strVbox.c_str()));
1571
1572 /* Find the disk from the OVF's disk list */
1573 DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1574 /* vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1575 in the virtual system's disks map under that ID and also in the global images map. */
1576 VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1577
1578 if ( itDiskImage == reader.m_mapDisks.end()
1579 || itVirtualDisk == vsysThis.mapVirtualDisks.end()
1580 )
1581 throw setError(E_FAIL,
1582 tr("Internal inconsistency looking up disk images."));
1583
1584 const DiskImage &di = itDiskImage->second;
1585 const VirtualDisk &vd = itVirtualDisk->second;
1586
1587 /* Make sure all target directories exists */
1588 rc = VirtualBox::ensureFilePathExists(vsdeHD->strVbox.c_str());
1589 if (FAILED(rc))
1590 throw rc;
1591
1592 // subprogress object for hard disk
1593 ComPtr<IProgress> pProgress2;
1594
1595 ComPtr<IMedium> dstHdVBox;
1596 /* If strHref is empty we have to create a new file */
1597 if (di.strHref.isEmpty())
1598 {
1599 /* Which format to use? */
1600 Bstr srcFormat = L"VDI";
1601 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1602 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
1603 srcFormat = L"VMDK";
1604 /* Create an empty hard disk */
1605 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(vsdeHD->strVbox), dstHdVBox.asOutParam());
1606 if (FAILED(rc)) throw rc;
1607
1608 /* Create a dynamic growing disk image with the given capacity */
1609 rc = dstHdVBox->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1610 if (FAILED(rc)) throw rc;
1611
1612 /* Advance to the next operation */
1613 if (!pTask->progress.isNull())
1614 pTask->progress->SetNextOperation(BstrFmt(tr("Creating virtual disk image '%s'"), vsdeHD->strVbox.c_str()),
1615 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally
1616 }
1617 else
1618 {
1619 /* Construct the source file path */
1620 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1621 /* Check if the source file exists */
1622 if (!RTPathExists(strSrcFilePath.c_str()))
1623 /* This isn't allowed */
1624 throw setError(VBOX_E_FILE_ERROR,
1625 tr("Source virtual disk image file '%s' doesn't exist"),
1626 strSrcFilePath.c_str());
1627
1628 /* Clone the disk image (this is necessary cause the id has
1629 * to be recreated for the case the same hard disk is
1630 * attached already from a previous import) */
1631
1632 /* First open the existing disk image */
1633 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1634 AccessMode_ReadOnly,
1635 false, Bstr(""), false, Bstr(""),
1636 srcHdVBox.asOutParam());
1637 if (FAILED(rc)) throw rc;
1638 fSourceHdNeedsClosing = true;
1639
1640 /* We need the format description of the source disk image */
1641 Bstr srcFormat;
1642 rc = srcHdVBox->COMGETTER(Format)(srcFormat.asOutParam());
1643 if (FAILED(rc)) throw rc;
1644 /* Create a new hard disk interface for the destination disk image */
1645 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(vsdeHD->strVbox), dstHdVBox.asOutParam());
1646 if (FAILED(rc)) throw rc;
1647 /* Clone the source disk image */
1648 rc = srcHdVBox->CloneTo(dstHdVBox, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1649 if (FAILED(rc)) throw rc;
1650
1651 /* Advance to the next operation */
1652 if (!pTask->progress.isNull())
1653 pTask->progress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1654 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally);
1655 }
1656
1657 // now wait for the background disk operation to complete; this throws HRESULTs on error
1658 waitForAsyncProgress(pTask->progress, pProgress2);
1659
1660 if (fSourceHdNeedsClosing)
1661 {
1662 rc = srcHdVBox->Close();
1663 if (FAILED(rc)) throw rc;
1664 fSourceHdNeedsClosing = false;
1665 }
1666
1667 llHardDisksCreated.push_back(dstHdVBox);
1668 /* Now use the new uuid to attach the disk image to our new machine */
1669 ComPtr<IMachine> sMachine;
1670 rc = session->COMGETTER(Machine)(sMachine.asOutParam());
1671 if (FAILED(rc)) throw rc;
1672 Bstr hdId;
1673 rc = dstHdVBox->COMGETTER(Id)(hdId.asOutParam());
1674 if (FAILED(rc)) throw rc;
1675
1676 /* For now we assume we have one controller of every type only */
1677 HardDiskController hdc = (*vsysThis.mapControllers.find(vd.idController)).second;
1678
1679 // this is for rollback later
1680 MyHardDiskAttachment mhda;
1681 mhda.uuid = newMachineId;
1682 mhda.pMachine = pNewMachine;
1683
1684 switch (hdc.system)
1685 {
1686 case HardDiskController::IDE:
1687 // For the IDE bus, the channel parameter can be either 0 or 1, to specify the primary
1688 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1689 // the device number can be either 0 or 1, to specify the master or the slave device,
1690 // respectively. For the secondary IDE controller, the device number is always 1 because
1691 // the master device is reserved for the CD-ROM drive.
1692 mhda.controllerType = Bstr("IDE Controller");
1693 switch (vd.ulAddressOnParent)
1694 {
1695 case 0: // interpret this as primary master
1696 mhda.lChannel = (long)0;
1697 mhda.lDevice = (long)0;
1698 break;
1699
1700 case 1: // interpret this as primary slave
1701 mhda.lChannel = (long)0;
1702 mhda.lDevice = (long)1;
1703 break;
1704
1705 case 2: // interpret this as secondary slave
1706 mhda.lChannel = (long)1;
1707 mhda.lDevice = (long)1;
1708 break;
1709
1710 default:
1711 throw setError(VBOX_E_NOT_SUPPORTED,
1712 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"), vd.ulAddressOnParent);
1713 break;
1714 }
1715 break;
1716
1717 case HardDiskController::SATA:
1718 mhda.controllerType = Bstr("SATA Controller");
1719 mhda.lChannel = (long)vd.ulAddressOnParent;
1720 mhda.lDevice = (long)0;
1721 break;
1722
1723 case HardDiskController::SCSI:
1724 mhda.controllerType = Bstr("SCSI Controller");
1725 mhda.lChannel = (long)vd.ulAddressOnParent;
1726 mhda.lDevice = (long)0;
1727 break;
1728
1729 default: break;
1730 }
1731
1732 Log(("Attaching disk %s to channel %d on device %d\n", vsdeHD->strVbox.c_str(), mhda.lChannel, mhda.lDevice));
1733
1734 rc = sMachine->AttachDevice(mhda.controllerType,
1735 mhda.lChannel,
1736 mhda.lDevice,
1737 DeviceType_HardDisk,
1738 hdId);
1739 if (FAILED(rc)) throw rc;
1740
1741 llHardDiskAttachments.push_back(mhda);
1742
1743 rc = sMachine->SaveSettings();
1744 if (FAILED(rc)) throw rc;
1745 } // end for (itHD = avsdeHDs.begin();
1746
1747 // only now that we're done with all disks, close the session
1748 rc = session->Close();
1749 if (FAILED(rc)) throw rc;
1750 fSessionOpen = false;
1751 }
1752 catch(HRESULT /* aRC */)
1753 {
1754 if (fSourceHdNeedsClosing)
1755 srcHdVBox->Close();
1756
1757 if (fSessionOpen)
1758 session->Close();
1759
1760 throw;
1761 }
1762 }
1763
1764#if 0 // @todo Implement CD-ROM import for 3.1 final
1765 // Add CD-ROMs to the appropriate controllers.
1766 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1767 if (avsdeHDs.size() > 0)
1768 {
1769 /* If in the next block an error occur we have to deregister
1770 the machine, so make an extra try/catch block. */
1771 ComPtr<IMedium> srcHdVBox;
1772 bool fSourceHdNeedsClosing = false;
1773
1774 try
1775 {
1776 /* In order to attach hard disks we need to open a session
1777 * for the new machine */
1778 rc = mVirtualBox->OpenSession(session, newMachineId_);
1779 if (FAILED(rc)) throw rc;
1780 fSessionOpen = true;
1781
1782 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator it = vsdeCDROM.begin();
1783 it != vsdeCDROM.end();
1784 ++it)
1785 {
1786 VirtualSystemDescriptionEntry *pVSDE = *it;
1787
1788 // @@todo
1789
1790 } // end for (itHD = avsdeHDs.begin();
1791
1792 // only now that we're done with all disks, close the session
1793 rc = session->Close();
1794 if (FAILED(rc)) throw rc;
1795 fSessionOpen = false;
1796 }
1797 catch(HRESULT /* aRC */)
1798 {
1799 if (fSourceHdNeedsClosing)
1800 srcHdVBox->Close();
1801
1802 if (fSessionOpen)
1803 session->Close();
1804
1805 throw;
1806 }
1807 }
1808#endif
1809 }
1810 catch(HRESULT aRC)
1811 {
1812 rc = aRC;
1813 }
1814
1815 if (FAILED(rc))
1816 break;
1817
1818 } // for (it = pAppliance->m->llVirtualSystems.begin(),
1819
1820 if (FAILED(rc))
1821 {
1822 // with _whatever_ error we've had, do a complete roll-back of
1823 // machines and disks we've created; unfortunately this is
1824 // not so trivially done...
1825
1826 HRESULT rc2;
1827 // detach all hard disks from all machines we created
1828 list<MyHardDiskAttachment>::iterator itM;
1829 for (itM = llHardDiskAttachments.begin();
1830 itM != llHardDiskAttachments.end();
1831 ++itM)
1832 {
1833 const MyHardDiskAttachment &mhda = *itM;
1834 rc2 = mVirtualBox->OpenSession(session, Bstr(mhda.uuid));
1835 if (SUCCEEDED(rc2))
1836 {
1837 ComPtr<IMachine> sMachine;
1838 rc2 = session->COMGETTER(Machine)(sMachine.asOutParam());
1839 if (SUCCEEDED(rc2))
1840 {
1841 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lChannel, mhda.lDevice);
1842 rc2 = sMachine->SaveSettings();
1843 }
1844 session->Close();
1845 }
1846 }
1847
1848 // now clean up all hard disks we created
1849 list< ComPtr<IMedium> >::iterator itHD;
1850 for (itHD = llHardDisksCreated.begin();
1851 itHD != llHardDisksCreated.end();
1852 ++itHD)
1853 {
1854 ComPtr<IMedium> pDisk = *itHD;
1855 ComPtr<IProgress> pProgress;
1856 rc2 = pDisk->DeleteStorage(pProgress.asOutParam());
1857 rc2 = pProgress->WaitForCompletion(-1);
1858 }
1859
1860 // finally, deregister and remove all machines
1861 list<Guid>::iterator itID;
1862 for (itID = llMachinesRegistered.begin();
1863 itID != llMachinesRegistered.end();
1864 ++itID)
1865 {
1866 const Guid &guid = *itID;
1867 ComPtr<IMachine> failedMachine;
1868 rc2 = mVirtualBox->UnregisterMachine(guid.toUtf16(), failedMachine.asOutParam());
1869 if (SUCCEEDED(rc2))
1870 rc2 = failedMachine->DeleteSettings();
1871 }
1872 }
1873
1874 pTask->rc = rc;
1875
1876 if (!pTask->progress.isNull())
1877 pTask->progress->notifyComplete(rc);
1878
1879 LogFlowFunc(("rc=%Rhrc\n", rc));
1880 LogFlowFuncLeave();
1881
1882 return VINF_SUCCESS;
1883}
1884
1885int Appliance::importS3(TaskImportOVF *pTask)
1886{
1887 LogFlowFuncEnter();
1888 LogFlowFunc(("Appliance %p\n", this));
1889
1890 AutoCaller autoCaller(this);
1891 CheckComRCReturnRC(autoCaller.rc());
1892
1893 AutoWriteLock appLock(this);
1894
1895 int vrc = VINF_SUCCESS;
1896 RTS3 hS3 = NIL_RTS3;
1897 char szOSTmpDir[RTPATH_MAX];
1898 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1899 /* The template for the temporary directory created below */
1900 char *pszTmpDir;
1901 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1902 list< pair<Utf8Str, ULONG> > filesList;
1903
1904 HRESULT rc = S_OK;
1905 try
1906 {
1907 /* Extract the bucket */
1908 Utf8Str tmpPath = pTask->locInfo.strPath;
1909 Utf8Str bucket;
1910 parseBucket(tmpPath, bucket);
1911
1912 /* We need a temporary directory which we can put the all disk images
1913 * in */
1914 vrc = RTDirCreateTemp(pszTmpDir);
1915 if (RT_FAILURE(vrc))
1916 throw setError(VBOX_E_FILE_ERROR,
1917 tr("Cannot create temporary directory '%s'"), pszTmpDir);
1918
1919 /* Add every disks of every virtual system to an internal list */
1920 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1921 for (it = m->virtualSystemDescriptions.begin();
1922 it != m->virtualSystemDescriptions.end();
1923 ++it)
1924 {
1925 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1926 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1927 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1928 for (itH = avsdeHDs.begin();
1929 itH != avsdeHDs.end();
1930 ++itH)
1931 {
1932 const Utf8Str &strTargetFile = (*itH)->strOvf;
1933 if (!strTargetFile.isEmpty())
1934 {
1935 /* The temporary name of the target disk file */
1936 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
1937 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1938 }
1939 }
1940 }
1941
1942 /* Next we have to download the disk images */
1943 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1944 if(RT_FAILURE(vrc))
1945 throw setError(VBOX_E_IPRT_ERROR,
1946 tr("Cannot create S3 service handler"));
1947 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1948
1949 /* Download all files */
1950 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1951 {
1952 const pair<Utf8Str, ULONG> &s = (*it1);
1953 const Utf8Str &strSrcFile = s.first;
1954 /* Construct the source file name */
1955 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1956 /* Advance to the next operation */
1957 if (!pTask->progress.isNull())
1958 pTask->progress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
1959
1960 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1961 if (RT_FAILURE(vrc))
1962 {
1963 if(vrc == VERR_S3_CANCELED)
1964 throw S_OK; /* todo: !!!!!!!!!!!!! */
1965 else if(vrc == VERR_S3_ACCESS_DENIED)
1966 throw setError(E_ACCESSDENIED,
1967 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
1968 else if(vrc == VERR_S3_NOT_FOUND)
1969 throw setError(VBOX_E_FILE_ERROR,
1970 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1971 else
1972 throw setError(VBOX_E_IPRT_ERROR,
1973 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1974 }
1975 }
1976
1977 /* Provide a OVF file (haven't to exist) so the import routine can
1978 * figure out where the disk images/manifest file are located. */
1979 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
1980 /* Now check if there is an manifest file. This is optional. */
1981 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
1982 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1983 if (!pTask->progress.isNull())
1984 pTask->progress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
1985
1986 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1987 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1988 if (RT_SUCCESS(vrc))
1989 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1990 else if (RT_FAILURE(vrc))
1991 {
1992 if(vrc == VERR_S3_CANCELED)
1993 throw S_OK; /* todo: !!!!!!!!!!!!! */
1994 else if(vrc == VERR_S3_NOT_FOUND)
1995 vrc = VINF_SUCCESS; /* Not found is ok */
1996 else if(vrc == VERR_S3_ACCESS_DENIED)
1997 throw setError(E_ACCESSDENIED,
1998 tr("Cannot download file '%s' from S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
1999 else
2000 throw setError(VBOX_E_IPRT_ERROR,
2001 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2002 }
2003
2004 /* Close the connection early */
2005 RTS3Destroy(hS3);
2006 hS3 = NIL_RTS3;
2007
2008 if (!pTask->progress.isNull())
2009 pTask->progress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightPerOperation);
2010
2011 ComObjPtr<Progress> progress;
2012 /* Import the whole temporary OVF & the disk images */
2013 LocationInfo li;
2014 li.strPath = strTmpOvf;
2015 rc = importImpl(li, progress);
2016 if (FAILED(rc)) throw rc;
2017
2018 /* Unlock the appliance for the fs import thread */
2019 appLock.unlock();
2020 /* Wait until the import is done, but report the progress back to the
2021 caller */
2022 ComPtr<IProgress> progressInt(progress);
2023 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
2024
2025 /* Again lock the appliance for the next steps */
2026 appLock.lock();
2027 }
2028 catch(HRESULT aRC)
2029 {
2030 rc = aRC;
2031 }
2032 /* Cleanup */
2033 RTS3Destroy(hS3);
2034 /* Delete all files which where temporary created */
2035 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2036 {
2037 const char *pszFilePath = (*it1).first.c_str();
2038 if (RTPathExists(pszFilePath))
2039 {
2040 vrc = RTFileDelete(pszFilePath);
2041 if(RT_FAILURE(vrc))
2042 rc = setError(VBOX_E_FILE_ERROR,
2043 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2044 }
2045 }
2046 /* Delete the temporary directory */
2047 if (RTPathExists(pszTmpDir))
2048 {
2049 vrc = RTDirRemove(pszTmpDir);
2050 if(RT_FAILURE(vrc))
2051 rc = setError(VBOX_E_FILE_ERROR,
2052 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2053 }
2054 if (pszTmpDir)
2055 RTStrFree(pszTmpDir);
2056
2057 pTask->rc = rc;
2058
2059 if (!pTask->progress.isNull())
2060 pTask->progress->notifyComplete(rc);
2061
2062 LogFlowFunc(("rc=%Rhrc\n", rc));
2063 LogFlowFuncLeave();
2064
2065 return VINF_SUCCESS;
2066}
2067
2068HRESULT Appliance::writeImpl(int aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
2069{
2070 HRESULT rc = S_OK;
2071 try
2072 {
2073 /* Initialize our worker task */
2074 std::auto_ptr<TaskExportOVF> task(new TaskExportOVF(this));
2075 /* What should the task do */
2076 task->taskType = TaskExportOVF::Write;
2077 /* The OVF version to write */
2078 task->enFormat = (TaskExportOVF::OVFFormat)aFormat;
2079 /* Copy the current location info to the task */
2080 task->locInfo = aLocInfo;
2081
2082 Bstr progressDesc = BstrFmt(tr("Export appliance '%s'"),
2083 task->locInfo.strPath.c_str());
2084
2085 /* todo: This progress init stuff should be done a little bit more generic */
2086 if (task->locInfo.storageType == VFSType_File)
2087 rc = setUpProgressFS(aProgress, progressDesc);
2088 else
2089 rc = setUpProgressWriteS3(aProgress, progressDesc);
2090
2091 task->progress = aProgress;
2092
2093 rc = task->startThread();
2094 CheckComRCThrowRC(rc);
2095
2096 /* Don't destruct on success */
2097 task.release();
2098 }
2099 catch (HRESULT aRC)
2100 {
2101 rc = aRC;
2102 }
2103
2104 return rc;
2105}
2106
2107DECLCALLBACK(int) Appliance::taskThreadWriteOVF(RTTHREAD /* aThread */, void *pvUser)
2108{
2109 std::auto_ptr<TaskExportOVF> task(static_cast<TaskExportOVF*>(pvUser));
2110 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
2111
2112 Appliance *pAppliance = task->pAppliance;
2113
2114 LogFlowFuncEnter();
2115 LogFlowFunc(("Appliance %p\n", pAppliance));
2116
2117 HRESULT rc = S_OK;
2118
2119 switch(task->taskType)
2120 {
2121 case TaskExportOVF::Write:
2122 {
2123 if (task->locInfo.storageType == VFSType_File)
2124 rc = pAppliance->writeFS(task.get());
2125 else if (task->locInfo.storageType == VFSType_S3)
2126 rc = pAppliance->writeS3(task.get());
2127 break;
2128 }
2129 }
2130
2131 LogFlowFunc(("rc=%Rhrc\n", rc));
2132 LogFlowFuncLeave();
2133
2134 return VINF_SUCCESS;
2135}
2136
2137int Appliance::TaskExportOVF::startThread()
2138{
2139 int vrc = RTThreadCreate(NULL, Appliance::taskThreadWriteOVF, this,
2140 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
2141 "Appliance::Task");
2142
2143 ComAssertMsgRCRet(vrc,
2144 ("Could not create taskThreadWriteOVF (%Rrc)\n", vrc), E_FAIL);
2145
2146 return S_OK;
2147}
2148
2149int Appliance::writeFS(TaskExportOVF *pTask)
2150{
2151 LogFlowFuncEnter();
2152 LogFlowFunc(("Appliance %p\n", this));
2153
2154 AutoCaller autoCaller(this);
2155 CheckComRCReturnRC(autoCaller.rc());
2156
2157 AutoWriteLock appLock(this);
2158
2159 HRESULT rc = S_OK;
2160
2161 try
2162 {
2163 xml::Document doc;
2164 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
2165
2166 pelmRoot->setAttribute("ovf:version", (pTask->enFormat == TaskExportOVF::OVF_1_0) ? "1.0" : "0.9");
2167 pelmRoot->setAttribute("xml:lang", "en-US");
2168
2169 Utf8Str strNamespace = (pTask->enFormat == TaskExportOVF::OVF_0_9)
2170 ? "http://www.vmware.com/schema/ovf/1/envelope" // 0.9
2171 : "http://schemas.dmtf.org/ovf/envelope/1"; // 1.0
2172 pelmRoot->setAttribute("xmlns", strNamespace);
2173 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
2174
2175// pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
2176 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
2177 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
2178 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
2179// pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
2180
2181 // <Envelope>/<References>
2182 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
2183
2184 /* <Envelope>/<DiskSection>:
2185 <DiskSection>
2186 <Info>List of the virtual disks used in the package</Info>
2187 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="http://www.vmware.com/specifications/vmdk.html#compressed" ovf:populatedSize="1924967692"/>
2188 </DiskSection> */
2189 xml::ElementNode *pelmDiskSection;
2190 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2191 {
2192 // <Section xsi:type="ovf:DiskSection_Type">
2193 pelmDiskSection = pelmRoot->createChild("Section");
2194 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
2195 }
2196 else
2197 pelmDiskSection = pelmRoot->createChild("DiskSection");
2198
2199 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
2200 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
2201 // for now, set up a map so we have a list of unique disk names (to make
2202 // sure the same disk name is only added once)
2203 map<Utf8Str, const VirtualSystemDescriptionEntry*> mapDisks;
2204
2205 /* <Envelope>/<NetworkSection>:
2206 <NetworkSection>
2207 <Info>Logical networks used in the package</Info>
2208 <Network ovf:name="VM Network">
2209 <Description>The network that the LAMP Service will be available on</Description>
2210 </Network>
2211 </NetworkSection> */
2212 xml::ElementNode *pelmNetworkSection;
2213 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2214 {
2215 // <Section xsi:type="ovf:NetworkSection_Type">
2216 pelmNetworkSection = pelmRoot->createChild("Section");
2217 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
2218 }
2219 else
2220 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
2221
2222 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
2223 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
2224 // for now, set up a map so we have a list of unique network names (to make
2225 // sure the same network name is only added once)
2226 map<Utf8Str, bool> mapNetworks;
2227 // we fill this later below when we iterate over the networks
2228
2229 // and here come the virtual systems:
2230
2231 // write a collection if we have more than one virtual system _and_ we're
2232 // writing OVF 1.0; otherwise fail since ovftool can't import more than
2233 // one machine, it seems
2234 xml::ElementNode *pelmToAddVirtualSystemsTo;
2235 if (m->virtualSystemDescriptions.size() > 1)
2236 {
2237 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2238 throw setError(VBOX_E_FILE_ERROR,
2239 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
2240
2241 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
2242 /* xml::AttributeNode *pattrVirtualSystemCollectionId = */ pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
2243 }
2244 else
2245 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
2246
2247 uint32_t cDisks = 0;
2248
2249 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2250 /* Iterate through all virtual systems of that appliance */
2251 for (it = m->virtualSystemDescriptions.begin();
2252 it != m->virtualSystemDescriptions.end();
2253 ++it)
2254 {
2255 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2256
2257 xml::ElementNode *pelmVirtualSystem;
2258 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2259 {
2260 // <Section xsi:type="ovf:NetworkSection_Type">
2261 pelmVirtualSystem = pelmToAddVirtualSystemsTo->createChild("Content");
2262 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
2263 }
2264 else
2265 pelmVirtualSystem = pelmToAddVirtualSystemsTo->createChild("VirtualSystem");
2266
2267 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
2268
2269 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2270 if (llName.size() != 1)
2271 throw setError(VBOX_E_NOT_SUPPORTED,
2272 tr("Missing VM name"));
2273 Utf8Str &strVMName = llName.front()->strVbox;
2274 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
2275
2276 // product info
2277 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
2278 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
2279 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
2280 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
2281 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
2282 bool fProduct = llProduct.size() && !llProduct.front()->strVbox.isEmpty();
2283 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVbox.isEmpty();
2284 bool fVendor = llVendor.size() && !llVendor.front()->strVbox.isEmpty();
2285 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVbox.isEmpty();
2286 bool fVersion = llVersion.size() && !llVersion.front()->strVbox.isEmpty();
2287 if (fProduct ||
2288 fProductUrl ||
2289 fVersion ||
2290 fVendorUrl ||
2291 fVersion)
2292 {
2293 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
2294 <Info>Meta-information about the installed software</Info>
2295 <Product>VAtest</Product>
2296 <Vendor>SUN Microsystems</Vendor>
2297 <Version>10.0</Version>
2298 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
2299 <VendorUrl>http://www.sun.com</VendorUrl>
2300 </Section> */
2301 xml::ElementNode *pelmAnnotationSection;
2302 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2303 {
2304 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
2305 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
2306 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
2307 }
2308 else
2309 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
2310
2311 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
2312 if (fProduct)
2313 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVbox);
2314 if (fVendor)
2315 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVbox);
2316 if (fVersion)
2317 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVbox);
2318 if (fProductUrl)
2319 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVbox);
2320 if (fVendorUrl)
2321 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVbox);
2322 }
2323
2324 // description
2325 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
2326 if (llDescription.size() &&
2327 !llDescription.front()->strVbox.isEmpty())
2328 {
2329 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
2330 <Info>A human-readable annotation</Info>
2331 <Annotation>Plan 9</Annotation>
2332 </Section> */
2333 xml::ElementNode *pelmAnnotationSection;
2334 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2335 {
2336 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
2337 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
2338 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
2339 }
2340 else
2341 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
2342
2343 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
2344 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVbox);
2345 }
2346
2347 // license
2348 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
2349 if (llLicense.size() &&
2350 !llLicense.front()->strVbox.isEmpty())
2351 {
2352 /* <EulaSection>
2353 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
2354 <License ovf:msgid="1">License terms can go in here.</License>
2355 </EulaSection> */
2356 xml::ElementNode *pelmEulaSection;
2357 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2358 {
2359 pelmEulaSection = pelmVirtualSystem->createChild("Section");
2360 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
2361 }
2362 else
2363 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
2364
2365 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
2366 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVbox);
2367 }
2368
2369 // operating system
2370 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
2371 if (llOS.size() != 1)
2372 throw setError(VBOX_E_NOT_SUPPORTED,
2373 tr("Missing OS type"));
2374 /* <OperatingSystemSection ovf:id="82">
2375 <Info>Guest Operating System</Info>
2376 <Description>Linux 2.6.x</Description>
2377 </OperatingSystemSection> */
2378 xml::ElementNode *pelmOperatingSystemSection;
2379 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2380 {
2381 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
2382 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
2383 }
2384 else
2385 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
2386
2387 pelmOperatingSystemSection->setAttribute("ovf:id", llOS.front()->strOvf);
2388 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
2389 Utf8Str strOSDesc;
2390 convertCIMOSType2VBoxOSType(strOSDesc, (CIMOSType_T)llOS.front()->strOvf.toInt32(), "");
2391 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
2392
2393 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
2394 xml::ElementNode *pelmVirtualHardwareSection;
2395 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2396 {
2397 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
2398 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
2399 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
2400 }
2401 else
2402 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
2403
2404 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
2405
2406 /* <System>
2407 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
2408 <vssd:ElementName>vmware</vssd:ElementName>
2409 <vssd:InstanceID>1</vssd:InstanceID>
2410 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
2411 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
2412 </System> */
2413 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
2414
2415 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
2416
2417 // <vssd:InstanceId>0</vssd:InstanceId>
2418 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2419 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
2420 else // capitalization changed...
2421 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
2422
2423 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
2424 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
2425 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
2426 const char *pcszHardware = "virtualbox-2.2";
2427 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2428 // pretend to be vmware compatible then
2429 pcszHardware = "vmx-6";
2430 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
2431
2432 // loop thru all description entries twice; once to write out all
2433 // devices _except_ disk images, and a second time to assign the
2434 // disk images; this is because disk images need to reference
2435 // IDE controllers, and we can't know their instance IDs without
2436 // assigning them first
2437
2438 uint32_t idIDEController = 0;
2439 int32_t lIDEControllerIndex = 0;
2440 uint32_t idSATAController = 0;
2441 int32_t lSATAControllerIndex = 0;
2442 uint32_t idSCSIController = 0;
2443 int32_t lSCSIControllerIndex = 0;
2444
2445 uint32_t ulInstanceID = 1;
2446
2447 for (size_t uLoop = 1;
2448 uLoop <= 2;
2449 ++uLoop)
2450 {
2451 int32_t lIndexThis = 0;
2452 list<VirtualSystemDescriptionEntry>::const_iterator itD;
2453 for (itD = vsdescThis->m->llDescriptions.begin();
2454 itD != vsdescThis->m->llDescriptions.end();
2455 ++itD, ++lIndexThis)
2456 {
2457 const VirtualSystemDescriptionEntry &desc = *itD;
2458
2459 OVFResourceType_T type = (OVFResourceType_T)0; // if this becomes != 0 then we do stuff
2460 Utf8Str strResourceSubType;
2461
2462 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
2463 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
2464
2465 uint32_t ulParent = 0;
2466
2467 int32_t lVirtualQuantity = -1;
2468 Utf8Str strAllocationUnits;
2469
2470 int32_t lAddress = -1;
2471 int32_t lBusNumber = -1;
2472 int32_t lAddressOnParent = -1;
2473
2474 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
2475 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
2476 Utf8Str strHostResource;
2477
2478 uint64_t uTemp;
2479
2480 switch (desc.type)
2481 {
2482 case VirtualSystemDescriptionType_CPU:
2483 /* <Item>
2484 <rasd:Caption>1 virtual CPU</rasd:Caption>
2485 <rasd:Description>Number of virtual CPUs</rasd:Description>
2486 <rasd:ElementName>virtual CPU</rasd:ElementName>
2487 <rasd:InstanceID>1</rasd:InstanceID>
2488 <rasd:ResourceType>3</rasd:ResourceType>
2489 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2490 </Item> */
2491 if (uLoop == 1)
2492 {
2493 strDescription = "Number of virtual CPUs";
2494 type = OVFResourceType_Processor; // 3
2495 desc.strVbox.toInt(uTemp);
2496 lVirtualQuantity = (int32_t)uTemp;
2497 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
2498 }
2499 break;
2500
2501 case VirtualSystemDescriptionType_Memory:
2502 /* <Item>
2503 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
2504 <rasd:Caption>256 MB of memory</rasd:Caption>
2505 <rasd:Description>Memory Size</rasd:Description>
2506 <rasd:ElementName>Memory</rasd:ElementName>
2507 <rasd:InstanceID>2</rasd:InstanceID>
2508 <rasd:ResourceType>4</rasd:ResourceType>
2509 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
2510 </Item> */
2511 if (uLoop == 1)
2512 {
2513 strDescription = "Memory Size";
2514 type = OVFResourceType_Memory; // 4
2515 desc.strVbox.toInt(uTemp);
2516 lVirtualQuantity = (int32_t)(uTemp / _1M);
2517 strAllocationUnits = "MegaBytes";
2518 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
2519 }
2520 break;
2521
2522 case VirtualSystemDescriptionType_HardDiskControllerIDE:
2523 /* <Item>
2524 <rasd:Caption>ideController1</rasd:Caption>
2525 <rasd:Description>IDE Controller</rasd:Description>
2526 <rasd:InstanceId>5</rasd:InstanceId>
2527 <rasd:ResourceType>5</rasd:ResourceType>
2528 <rasd:Address>1</rasd:Address>
2529 <rasd:BusNumber>1</rasd:BusNumber>
2530 </Item> */
2531 if (uLoop == 1)
2532 {
2533 strDescription = "IDE Controller";
2534 strCaption = "ideController0";
2535 type = OVFResourceType_IDEController; // 5
2536 strResourceSubType = desc.strVbox;
2537 // it seems that OVFTool always writes these two, and since we can only
2538 // have one IDE controller, we'll use this as well
2539 lAddress = 1;
2540 lBusNumber = 1;
2541
2542 // remember this ID
2543 idIDEController = ulInstanceID;
2544 lIDEControllerIndex = lIndexThis;
2545 }
2546 break;
2547
2548 case VirtualSystemDescriptionType_HardDiskControllerSATA:
2549 /* <Item>
2550 <rasd:Caption>sataController0</rasd:Caption>
2551 <rasd:Description>SATA Controller</rasd:Description>
2552 <rasd:InstanceId>4</rasd:InstanceId>
2553 <rasd:ResourceType>20</rasd:ResourceType>
2554 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
2555 <rasd:Address>0</rasd:Address>
2556 <rasd:BusNumber>0</rasd:BusNumber>
2557 </Item>
2558 */
2559 if (uLoop == 1)
2560 {
2561 strDescription = "SATA Controller";
2562 strCaption = "sataController0";
2563 type = OVFResourceType_OtherStorageDevice; // 20
2564 // it seems that OVFTool always writes these two, and since we can only
2565 // have one SATA controller, we'll use this as well
2566 lAddress = 0;
2567 lBusNumber = 0;
2568
2569 if ( desc.strVbox.isEmpty() // AHCI is the default in VirtualBox
2570 || (!desc.strVbox.compare("ahci", Utf8Str::CaseInsensitive))
2571 )
2572 strResourceSubType = "AHCI";
2573 else
2574 throw setError(VBOX_E_NOT_SUPPORTED,
2575 tr("Invalid config string \"%s\" in SATA controller"), desc.strVbox.c_str());
2576
2577 // remember this ID
2578 idSATAController = ulInstanceID;
2579 lSATAControllerIndex = lIndexThis;
2580 }
2581 break;
2582
2583 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
2584 /* <Item>
2585 <rasd:Caption>scsiController0</rasd:Caption>
2586 <rasd:Description>SCSI Controller</rasd:Description>
2587 <rasd:InstanceId>4</rasd:InstanceId>
2588 <rasd:ResourceType>6</rasd:ResourceType>
2589 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
2590 <rasd:Address>0</rasd:Address>
2591 <rasd:BusNumber>0</rasd:BusNumber>
2592 </Item>
2593 */
2594 if (uLoop == 1)
2595 {
2596 strDescription = "SCSI Controller";
2597 strCaption = "scsiController0";
2598 type = OVFResourceType_ParallelSCSIHBA; // 6
2599 // it seems that OVFTool always writes these two, and since we can only
2600 // have one SATA controller, we'll use this as well
2601 lAddress = 0;
2602 lBusNumber = 0;
2603
2604 if ( desc.strVbox.isEmpty() // LsiLogic is the default in VirtualBox
2605 || (!desc.strVbox.compare("lsilogic", Utf8Str::CaseInsensitive))
2606 )
2607 strResourceSubType = "lsilogic";
2608 else if (!desc.strVbox.compare("buslogic", Utf8Str::CaseInsensitive))
2609 strResourceSubType = "buslogic";
2610 else
2611 throw setError(VBOX_E_NOT_SUPPORTED,
2612 tr("Invalid config string \"%s\" in SCSI controller"), desc.strVbox.c_str());
2613
2614 // remember this ID
2615 idSCSIController = ulInstanceID;
2616 lSCSIControllerIndex = lIndexThis;
2617 }
2618 break;
2619
2620 case VirtualSystemDescriptionType_HardDiskImage:
2621 /* <Item>
2622 <rasd:Caption>disk1</rasd:Caption>
2623 <rasd:InstanceId>8</rasd:InstanceId>
2624 <rasd:ResourceType>17</rasd:ResourceType>
2625 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
2626 <rasd:Parent>4</rasd:Parent>
2627 <rasd:AddressOnParent>0</rasd:AddressOnParent>
2628 </Item> */
2629 if (uLoop == 2)
2630 {
2631 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
2632
2633 strDescription = "Disk Image";
2634 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
2635 type = OVFResourceType_HardDisk; // 17
2636
2637 // the following references the "<Disks>" XML block
2638 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
2639
2640 // controller=<index>;channel=<c>
2641 size_t pos1 = desc.strExtraConfig.find("controller=");
2642 size_t pos2 = desc.strExtraConfig.find("channel=");
2643 if (pos1 != Utf8Str::npos)
2644 {
2645 int32_t lControllerIndex = -1;
2646 RTStrToInt32Ex(desc.strExtraConfig.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
2647 if (lControllerIndex == lIDEControllerIndex)
2648 ulParent = idIDEController;
2649 else if (lControllerIndex == lSCSIControllerIndex)
2650 ulParent = idSCSIController;
2651 else if (lControllerIndex == lSATAControllerIndex)
2652 ulParent = idSATAController;
2653 }
2654 if (pos2 != Utf8Str::npos)
2655 RTStrToInt32Ex(desc.strExtraConfig.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
2656
2657 if ( !ulParent
2658 || lAddressOnParent == -1
2659 )
2660 throw setError(VBOX_E_NOT_SUPPORTED,
2661 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfig.c_str());
2662
2663 mapDisks[strDiskID] = &desc;
2664 }
2665 break;
2666
2667 case VirtualSystemDescriptionType_Floppy:
2668 if (uLoop == 1)
2669 {
2670 strDescription = "Floppy Drive";
2671 strCaption = "floppy0"; // this is what OVFTool writes
2672 type = OVFResourceType_FloppyDrive; // 14
2673 lAutomaticAllocation = 0;
2674 lAddressOnParent = 0; // this is what OVFTool writes
2675 }
2676 break;
2677
2678 case VirtualSystemDescriptionType_CDROM:
2679 if (uLoop == 2)
2680 {
2681 // we can't have a CD without an IDE controller
2682 if (!idIDEController)
2683 throw setError(VBOX_E_NOT_SUPPORTED,
2684 tr("Can't have CD-ROM without IDE controller"));
2685
2686 strDescription = "CD-ROM Drive";
2687 strCaption = "cdrom1"; // this is what OVFTool writes
2688 type = OVFResourceType_CDDrive; // 15
2689 lAutomaticAllocation = 1;
2690 ulParent = idIDEController;
2691 lAddressOnParent = 0; // this is what OVFTool writes
2692 }
2693 break;
2694
2695 case VirtualSystemDescriptionType_NetworkAdapter:
2696 /* <Item>
2697 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
2698 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
2699 <rasd:Connection>VM Network</rasd:Connection>
2700 <rasd:ElementName>VM network</rasd:ElementName>
2701 <rasd:InstanceID>3</rasd:InstanceID>
2702 <rasd:ResourceType>10</rasd:ResourceType>
2703 </Item> */
2704 if (uLoop == 1)
2705 {
2706 lAutomaticAllocation = 1;
2707 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
2708 type = OVFResourceType_EthernetAdapter; // 10
2709 /* Set the hardware type to something useful.
2710 * To be compatible with vmware & others we set
2711 * PCNet32 for our PCNet types & E1000 for the
2712 * E1000 cards. */
2713 switch (desc.strVbox.toInt32())
2714 {
2715 case NetworkAdapterType_Am79C970A:
2716 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
2717#ifdef VBOX_WITH_E1000
2718 case NetworkAdapterType_I82540EM:
2719 case NetworkAdapterType_I82545EM:
2720 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
2721#endif /* VBOX_WITH_E1000 */
2722 }
2723 strConnection = desc.strOvf;
2724
2725 mapNetworks[desc.strOvf] = true;
2726 }
2727 break;
2728
2729 case VirtualSystemDescriptionType_USBController:
2730 /* <Item ovf:required="false">
2731 <rasd:Caption>usb</rasd:Caption>
2732 <rasd:Description>USB Controller</rasd:Description>
2733 <rasd:InstanceId>3</rasd:InstanceId>
2734 <rasd:ResourceType>23</rasd:ResourceType>
2735 <rasd:Address>0</rasd:Address>
2736 <rasd:BusNumber>0</rasd:BusNumber>
2737 </Item> */
2738 if (uLoop == 1)
2739 {
2740 strDescription = "USB Controller";
2741 strCaption = "usb";
2742 type = OVFResourceType_USBController; // 23
2743 lAddress = 0; // this is what OVFTool writes
2744 lBusNumber = 0; // this is what OVFTool writes
2745 }
2746 break;
2747
2748 case VirtualSystemDescriptionType_SoundCard:
2749 /* <Item ovf:required="false">
2750 <rasd:Caption>sound</rasd:Caption>
2751 <rasd:Description>Sound Card</rasd:Description>
2752 <rasd:InstanceId>10</rasd:InstanceId>
2753 <rasd:ResourceType>35</rasd:ResourceType>
2754 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
2755 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
2756 <rasd:AddressOnParent>3</rasd:AddressOnParent>
2757 </Item> */
2758 if (uLoop == 1)
2759 {
2760 strDescription = "Sound Card";
2761 strCaption = "sound";
2762 type = OVFResourceType_SoundCard; // 35
2763 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
2764 lAutomaticAllocation = 0;
2765 lAddressOnParent = 3; // what gives? this is what OVFTool writes
2766 }
2767 break;
2768 }
2769
2770 if (type)
2771 {
2772 xml::ElementNode *pItem;
2773
2774 pItem = pelmVirtualHardwareSection->createChild("Item");
2775
2776 // NOTE: do not change the order of these items without good reason! While we don't care
2777 // about ordering, VMware's ovftool does and fails if the items are not written in
2778 // exactly this order, as stupid as it seems.
2779
2780 if (!strCaption.isEmpty())
2781 {
2782 pItem->createChild("rasd:Caption")->addContent(strCaption);
2783 if (pTask->enFormat == TaskExportOVF::OVF_1_0)
2784 pItem->createChild("rasd:ElementName")->addContent(strCaption);
2785 }
2786
2787 if (!strDescription.isEmpty())
2788 pItem->createChild("rasd:Description")->addContent(strDescription);
2789
2790 // <rasd:InstanceID>1</rasd:InstanceID>
2791 xml::ElementNode *pelmInstanceID;
2792 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2793 pelmInstanceID = pItem->createChild("rasd:InstanceId");
2794 else
2795 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
2796 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
2797
2798 // <rasd:ResourceType>3</rasd:ResourceType>
2799 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
2800 if (!strResourceSubType.isEmpty())
2801 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
2802
2803 if (!strHostResource.isEmpty())
2804 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
2805
2806 if (!strAllocationUnits.isEmpty())
2807 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
2808
2809 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2810 if (lVirtualQuantity != -1)
2811 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2812
2813 if (lAutomaticAllocation != -1)
2814 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
2815
2816 if (!strConnection.isEmpty())
2817 pItem->createChild("rasd:Connection")->addContent(strConnection);
2818
2819 if (lAddress != -1)
2820 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
2821
2822 if (lBusNumber != -1)
2823 if (pTask->enFormat == TaskExportOVF::OVF_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool compatibility
2824 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
2825
2826 if (ulParent)
2827 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
2828 if (lAddressOnParent != -1)
2829 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
2830 }
2831 }
2832 } // for (size_t uLoop = 0; ...
2833 }
2834
2835 // finally, fill in the network section we set up empty above according
2836 // to the networks we found with the hardware items
2837 map<Utf8Str, bool>::const_iterator itN;
2838 for (itN = mapNetworks.begin();
2839 itN != mapNetworks.end();
2840 ++itN)
2841 {
2842 const Utf8Str &strNetwork = itN->first;
2843 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
2844 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
2845 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
2846 }
2847
2848 list<Utf8Str> diskList;
2849 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
2850 uint32_t ulFile = 1;
2851 for (itS = mapDisks.begin();
2852 itS != mapDisks.end();
2853 ++itS)
2854 {
2855 const Utf8Str &strDiskID = itS->first;
2856 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
2857
2858 // source path: where the VBox image is
2859 const Utf8Str &strSrcFilePath = pDiskEntry->strVbox;
2860 Bstr bstrSrcFilePath(strSrcFilePath);
2861 if (!RTPathExists(strSrcFilePath.c_str()))
2862 /* This isn't allowed */
2863 throw setError(VBOX_E_FILE_ERROR,
2864 tr("Source virtual disk image file '%s' doesn't exist"),
2865 strSrcFilePath.c_str());
2866
2867 // output filename
2868 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2869 // target path needs to be composed from where the output OVF is
2870 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2871 strTargetFilePath.stripFilename();
2872 strTargetFilePath.append("/");
2873 strTargetFilePath.append(strTargetFileNameOnly);
2874
2875 // clone the disk:
2876 ComPtr<IMedium> pSourceDisk;
2877 ComPtr<IMedium> pTargetDisk;
2878 ComPtr<IProgress> pProgress2;
2879
2880 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
2881 rc = mVirtualBox->FindHardDisk(bstrSrcFilePath, pSourceDisk.asOutParam());
2882 if (FAILED(rc)) throw rc;
2883
2884 /* We are always exporting to vmdfk stream optimized for now */
2885 Bstr bstrSrcFormat = L"VMDK";
2886
2887 // create a new hard disk interface for the destination disk image
2888 Log(("Creating target disk \"%s\"\n", strTargetFilePath.raw()));
2889 rc = mVirtualBox->CreateHardDisk(bstrSrcFormat, Bstr(strTargetFilePath), pTargetDisk.asOutParam());
2890 if (FAILED(rc)) throw rc;
2891
2892 // the target disk is now registered and needs to be removed again,
2893 // both after successful cloning or if anything goes bad!
2894 try
2895 {
2896 // create a flat copy of the source disk image
2897 rc = pSourceDisk->CloneTo(pTargetDisk, MediumVariant_VmdkStreamOptimized, NULL, pProgress2.asOutParam());
2898 if (FAILED(rc)) throw rc;
2899
2900 // advance to the next operation
2901 if (!pTask->progress.isNull())
2902 pTask->progress->SetNextOperation(BstrFmt(tr("Exporting virtual disk image '%s'"), strSrcFilePath.c_str()),
2903 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally);
2904
2905 // now wait for the background disk operation to complete; this throws HRESULTs on error
2906 waitForAsyncProgress(pTask->progress, pProgress2);
2907 }
2908 catch (HRESULT rc3)
2909 {
2910 // upon error after registering, close the disk or
2911 // it'll stick in the registry forever
2912 pTargetDisk->Close();
2913 throw rc3;
2914 }
2915 diskList.push_back(strTargetFilePath);
2916
2917 // we need the following for the XML
2918 uint64_t cbFile = 0; // actual file size
2919 rc = pTargetDisk->COMGETTER(Size)(&cbFile);
2920 if (FAILED(rc)) throw rc;
2921
2922 ULONG64 cbCapacity = 0; // size reported to guest
2923 rc = pTargetDisk->COMGETTER(LogicalSize)(&cbCapacity);
2924 if (FAILED(rc)) throw rc;
2925 // capacity is reported in megabytes, so...
2926 cbCapacity *= _1M;
2927
2928 // upon success, close the disk as well
2929 rc = pTargetDisk->Close();
2930 if (FAILED(rc)) throw rc;
2931
2932 // now handle the XML for the disk:
2933 Utf8StrFmt strFileRef("file%RI32", ulFile++);
2934 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
2935 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
2936 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
2937 pelmFile->setAttribute("ovf:id", strFileRef);
2938 pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
2939
2940 // add disk to XML Disks section
2941 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="http://www.vmware.com/specifications/vmdk.html#sparse"/>
2942 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
2943 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
2944 pelmDisk->setAttribute("ovf:diskId", strDiskID);
2945 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
2946 pelmDisk->setAttribute("ovf:format", "http://www.vmware.com/specifications/vmdk.html#sparse"); // must be sparse or ovftool chokes
2947 }
2948
2949 // now go write the XML
2950 xml::XmlFileWriter writer(doc);
2951 writer.write(pTask->locInfo.strPath.c_str());
2952
2953 /* Create & write the manifest file */
2954 const char** ppManifestFiles = (const char**)RTMemAlloc(sizeof(char*)*diskList.size() + 1);
2955 ppManifestFiles[0] = pTask->locInfo.strPath.c_str();
2956 list<Utf8Str>::const_iterator it1;
2957 size_t i = 1;
2958 for (it1 = diskList.begin();
2959 it1 != diskList.end();
2960 ++it1, ++i)
2961 ppManifestFiles[i] = (*it1).c_str();
2962 Utf8Str strMfFile = manifestFileName(pTask->locInfo.strPath.c_str());
2963 int vrc = RTManifestWriteFiles(strMfFile.c_str(), ppManifestFiles, diskList.size()+1);
2964 if (RT_FAILURE(vrc))
2965 throw setError(VBOX_E_FILE_ERROR,
2966 tr("Couldn't create manifest file '%s' (%Rrc)"),
2967 RTPathFilename(strMfFile.c_str()), vrc);
2968 RTMemFree(ppManifestFiles);
2969 }
2970 catch(xml::Error &x)
2971 {
2972 rc = setError(VBOX_E_FILE_ERROR,
2973 x.what());
2974 }
2975 catch(HRESULT aRC)
2976 {
2977 rc = aRC;
2978 }
2979
2980 pTask->rc = rc;
2981
2982 if (!pTask->progress.isNull())
2983 pTask->progress->notifyComplete(rc);
2984
2985 LogFlowFunc(("rc=%Rhrc\n", rc));
2986 LogFlowFuncLeave();
2987
2988 return VINF_SUCCESS;
2989}
2990
2991int Appliance::writeS3(TaskExportOVF *pTask)
2992{
2993 LogFlowFuncEnter();
2994 LogFlowFunc(("Appliance %p\n", this));
2995
2996 AutoCaller autoCaller(this);
2997 CheckComRCReturnRC(autoCaller.rc());
2998
2999 HRESULT rc = S_OK;
3000
3001 AutoWriteLock appLock(this);
3002
3003 int vrc = VINF_SUCCESS;
3004 RTS3 hS3 = NIL_RTS3;
3005 char szOSTmpDir[RTPATH_MAX];
3006 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
3007 /* The template for the temporary directory created below */
3008 char *pszTmpDir;
3009 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
3010 list< pair<Utf8Str, ULONG> > filesList;
3011
3012 // todo:
3013 // - usable error codes
3014 // - seems snapshot filenames are problematic {uuid}.vdi
3015 try
3016 {
3017 /* Extract the bucket */
3018 Utf8Str tmpPath = pTask->locInfo.strPath;
3019 Utf8Str bucket;
3020 parseBucket(tmpPath, bucket);
3021
3022 /* We need a temporary directory which we can put the OVF file & all
3023 * disk images in */
3024 vrc = RTDirCreateTemp(pszTmpDir);
3025 if (RT_FAILURE(vrc))
3026 throw setError(VBOX_E_FILE_ERROR,
3027 tr("Cannot create temporary directory '%s'"), pszTmpDir);
3028
3029 /* The temporary name of the target OVF file */
3030 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
3031
3032 /* Prepare the temporary writing of the OVF */
3033 ComObjPtr<Progress> progress;
3034 /* Create a temporary file based location info for the sub task */
3035 LocationInfo li;
3036 li.strPath = strTmpOvf;
3037 rc = writeImpl(pTask->enFormat, li, progress);
3038 if (FAILED(rc)) throw rc;
3039
3040 /* Unlock the appliance for the writing thread */
3041 appLock.unlock();
3042 /* Wait until the writing is done, but report the progress back to the
3043 caller */
3044 ComPtr<IProgress> progressInt(progress);
3045 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
3046
3047 /* Again lock the appliance for the next steps */
3048 appLock.lock();
3049
3050 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
3051 if(RT_FAILURE(vrc))
3052 throw setError(VBOX_E_FILE_ERROR,
3053 tr("Cannot find source file '%s'"), strTmpOvf.c_str());
3054 /* Add the OVF file */
3055 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightPerOperation)); /* Use 1% of the total for the OVF file upload */
3056 Utf8Str strMfFile = manifestFileName(strTmpOvf);
3057 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightPerOperation)); /* Use 1% of the total for the manifest file upload */
3058
3059 /* Now add every disks of every virtual system */
3060 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
3061 for (it = m->virtualSystemDescriptions.begin();
3062 it != m->virtualSystemDescriptions.end();
3063 ++it)
3064 {
3065 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
3066 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
3067 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
3068 for (itH = avsdeHDs.begin();
3069 itH != avsdeHDs.end();
3070 ++itH)
3071 {
3072 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
3073 /* Target path needs to be composed from where the output OVF is */
3074 Utf8Str strTargetFilePath(strTmpOvf);
3075 strTargetFilePath.stripFilename();
3076 strTargetFilePath.append("/");
3077 strTargetFilePath.append(strTargetFileNameOnly);
3078 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
3079 if(RT_FAILURE(vrc))
3080 throw setError(VBOX_E_FILE_ERROR,
3081 tr("Cannot find source file '%s'"), strTargetFilePath.c_str());
3082 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
3083 }
3084 }
3085 /* Next we have to upload the OVF & all disk images */
3086 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
3087 if(RT_FAILURE(vrc))
3088 throw setError(VBOX_E_IPRT_ERROR,
3089 tr("Cannot create S3 service handler"));
3090 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
3091
3092 /* Upload all files */
3093 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
3094 {
3095 const pair<Utf8Str, ULONG> &s = (*it1);
3096 char *pszFilename = RTPathFilename(s.first.c_str());
3097 /* Advance to the next operation */
3098 if (!pTask->progress.isNull())
3099 pTask->progress->SetNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename), s.second);
3100 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
3101 if (RT_FAILURE(vrc))
3102 {
3103 if(vrc == VERR_S3_CANCELED)
3104 break;
3105 else if(vrc == VERR_S3_ACCESS_DENIED)
3106 throw setError(E_ACCESSDENIED,
3107 tr("Cannot upload file '%s' to S3 storage server (Access denied). Make sure that your credentials are right. Also check that your host clock is properly synced"), pszFilename);
3108 else if(vrc == VERR_S3_NOT_FOUND)
3109 throw setError(VBOX_E_FILE_ERROR,
3110 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
3111 else
3112 throw setError(VBOX_E_IPRT_ERROR,
3113 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
3114 }
3115 }
3116 }
3117 catch(HRESULT aRC)
3118 {
3119 rc = aRC;
3120 }
3121 /* Cleanup */
3122 RTS3Destroy(hS3);
3123 /* Delete all files which where temporary created */
3124 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
3125 {
3126 const char *pszFilePath = (*it1).first.c_str();
3127 if (RTPathExists(pszFilePath))
3128 {
3129 vrc = RTFileDelete(pszFilePath);
3130 if(RT_FAILURE(vrc))
3131 rc = setError(VBOX_E_FILE_ERROR,
3132 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
3133 }
3134 }
3135 /* Delete the temporary directory */
3136 if (RTPathExists(pszTmpDir))
3137 {
3138 vrc = RTDirRemove(pszTmpDir);
3139 if(RT_FAILURE(vrc))
3140 rc = setError(VBOX_E_FILE_ERROR,
3141 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
3142 }
3143 if (pszTmpDir)
3144 RTStrFree(pszTmpDir);
3145
3146 pTask->rc = rc;
3147
3148 if (!pTask->progress.isNull())
3149 pTask->progress->notifyComplete(rc);
3150
3151 LogFlowFunc(("rc=%Rhrc\n", rc));
3152 LogFlowFuncLeave();
3153
3154 return VINF_SUCCESS;
3155}
3156
3157////////////////////////////////////////////////////////////////////////////////
3158//
3159// IAppliance public methods
3160//
3161////////////////////////////////////////////////////////////////////////////////
3162
3163/**
3164 * Public method implementation.
3165 * @param
3166 * @return
3167 */
3168STDMETHODIMP Appliance::COMGETTER(Path)(BSTR *aPath)
3169{
3170 if (!aPath)
3171 return E_POINTER;
3172
3173 AutoCaller autoCaller(this);
3174 CheckComRCReturnRC(autoCaller.rc());
3175
3176 AutoReadLock alock(this);
3177
3178 Bstr bstrPath(m->locInfo.strPath);
3179 bstrPath.cloneTo(aPath);
3180
3181 return S_OK;
3182}
3183
3184/**
3185 * Public method implementation.
3186 * @param
3187 * @return
3188 */
3189STDMETHODIMP Appliance::COMGETTER(Disks)(ComSafeArrayOut(BSTR, aDisks))
3190{
3191 CheckComArgOutSafeArrayPointerValid(aDisks);
3192
3193 AutoCaller autoCaller(this);
3194 CheckComRCReturnRC(autoCaller.rc());
3195
3196 AutoReadLock alock(this);
3197
3198 if (m->pReader) // OVFReader instantiated?
3199 {
3200 size_t c = m->pReader->m_mapDisks.size();
3201 com::SafeArray<BSTR> sfaDisks(c);
3202
3203 DiskImagesMap::const_iterator it;
3204 size_t i = 0;
3205 for (it = m->pReader->m_mapDisks.begin();
3206 it != m->pReader->m_mapDisks.end();
3207 ++it, ++i)
3208 {
3209 // create a string representing this disk
3210 const DiskImage &d = it->second;
3211 char *psz = NULL;
3212 RTStrAPrintf(&psz,
3213 "%s\t"
3214 "%RI64\t"
3215 "%RI64\t"
3216 "%s\t"
3217 "%s\t"
3218 "%RI64\t"
3219 "%RI64\t"
3220 "%s",
3221 d.strDiskId.c_str(),
3222 d.iCapacity,
3223 d.iPopulatedSize,
3224 d.strFormat.c_str(),
3225 d.strHref.c_str(),
3226 d.iSize,
3227 d.iChunkSize,
3228 d.strCompression.c_str());
3229 Utf8Str utf(psz);
3230 Bstr bstr(utf);
3231 // push to safearray
3232 bstr.cloneTo(&sfaDisks[i]);
3233 RTStrFree(psz);
3234 }
3235
3236 sfaDisks.detachTo(ComSafeArrayOutArg(aDisks));
3237 }
3238
3239 return S_OK;
3240}
3241
3242/**
3243 * Public method implementation.
3244 * @param
3245 * @return
3246 */
3247STDMETHODIMP Appliance::COMGETTER(VirtualSystemDescriptions)(ComSafeArrayOut(IVirtualSystemDescription*, aVirtualSystemDescriptions))
3248{
3249 CheckComArgOutSafeArrayPointerValid(aVirtualSystemDescriptions);
3250
3251 AutoCaller autoCaller(this);
3252 CheckComRCReturnRC(autoCaller.rc());
3253
3254 AutoReadLock alock(this);
3255
3256 SafeIfaceArray<IVirtualSystemDescription> sfaVSD(m->virtualSystemDescriptions);
3257 sfaVSD.detachTo(ComSafeArrayOutArg(aVirtualSystemDescriptions));
3258
3259 return S_OK;
3260}
3261
3262/**
3263 * Public method implementation.
3264 * @param path
3265 * @return
3266 */
3267STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
3268{
3269 if (!path) return E_POINTER;
3270 CheckComArgOutPointerValid(aProgress);
3271
3272 AutoCaller autoCaller(this);
3273 CheckComRCReturnRC(autoCaller.rc());
3274
3275 AutoWriteLock alock(this);
3276
3277 if (m->pReader)
3278 {
3279 delete m->pReader;
3280 m->pReader = NULL;
3281 }
3282
3283 // see if we can handle this file; for now we insist it has an ".ovf" extension
3284 Utf8Str strPath (path);
3285 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
3286 return setError(VBOX_E_FILE_ERROR,
3287 tr("Appliance file must have .ovf extension"));
3288
3289 ComObjPtr<Progress> progress;
3290 HRESULT rc = S_OK;
3291 try
3292 {
3293 /* Parse all necessary info out of the URI */
3294 parseURI(strPath, m->locInfo);
3295 rc = readImpl(m->locInfo, progress);
3296 }
3297 catch (HRESULT aRC)
3298 {
3299 rc = aRC;
3300 }
3301
3302 if (SUCCEEDED(rc))
3303 /* Return progress to the caller */
3304 progress.queryInterfaceTo(aProgress);
3305
3306 return S_OK;
3307}
3308
3309/**
3310 * Public method implementation.
3311 * @return
3312 */
3313STDMETHODIMP Appliance::Interpret()
3314{
3315 // @todo:
3316 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk))
3317 // - Appropriate handle errors like not supported file formats
3318 AutoCaller autoCaller(this);
3319 CheckComRCReturnRC(autoCaller.rc());
3320
3321 AutoWriteLock(this);
3322
3323 HRESULT rc = S_OK;
3324
3325 /* Clear any previous virtual system descriptions */
3326 m->virtualSystemDescriptions.clear();
3327
3328 /* We need the default path for storing disk images */
3329 ComPtr<ISystemProperties> systemProps;
3330 rc = mVirtualBox->COMGETTER(SystemProperties)(systemProps.asOutParam());
3331 CheckComRCReturnRC(rc);
3332 Bstr bstrDefaultHardDiskLocation;
3333 rc = systemProps->COMGETTER(DefaultHardDiskFolder)(bstrDefaultHardDiskLocation.asOutParam());
3334 CheckComRCReturnRC(rc);
3335
3336 if (!m->pReader)
3337 return setError(E_FAIL,
3338 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
3339
3340 /* Try/catch so we can clean up on error */
3341 try
3342 {
3343 list<VirtualSystem>::const_iterator it;
3344 /* Iterate through all virtual systems */
3345 for (it = m->pReader->m_llVirtualSystems.begin();
3346 it != m->pReader->m_llVirtualSystems.end();
3347 ++it)
3348 {
3349 const VirtualSystem &vsysThis = *it;
3350
3351 ComObjPtr<VirtualSystemDescription> pNewDesc;
3352 rc = pNewDesc.createObject();
3353 CheckComRCThrowRC(rc);
3354 rc = pNewDesc->init();
3355 CheckComRCThrowRC(rc);
3356
3357 /* Guest OS type */
3358 Utf8Str strOsTypeVBox,
3359 strCIMOSType = Utf8StrFmt("%RI32", (uint32_t)vsysThis.cimos);
3360 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
3361 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
3362 "",
3363 strCIMOSType,
3364 strOsTypeVBox);
3365
3366 /* VM name */
3367 /* If the there isn't any name specified create a default one out of
3368 * the OS type */
3369 Utf8Str nameVBox = vsysThis.strName;
3370 if (nameVBox.isEmpty())
3371 nameVBox = strOsTypeVBox;
3372 searchUniqueVMName(nameVBox);
3373 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
3374 "",
3375 vsysThis.strName,
3376 nameVBox);
3377
3378 /* VM Product */
3379 if (!vsysThis.strProduct.isEmpty())
3380 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
3381 "",
3382 vsysThis.strProduct,
3383 vsysThis.strProduct);
3384
3385 /* VM Vendor */
3386 if (!vsysThis.strVendor.isEmpty())
3387 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
3388 "",
3389 vsysThis.strVendor,
3390 vsysThis.strVendor);
3391
3392 /* VM Version */
3393 if (!vsysThis.strVersion.isEmpty())
3394 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
3395 "",
3396 vsysThis.strVersion,
3397 vsysThis.strVersion);
3398
3399 /* VM ProductUrl */
3400 if (!vsysThis.strProductUrl.isEmpty())
3401 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
3402 "",
3403 vsysThis.strProductUrl,
3404 vsysThis.strProductUrl);
3405
3406 /* VM VendorUrl */
3407 if (!vsysThis.strVendorUrl.isEmpty())
3408 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
3409 "",
3410 vsysThis.strVendorUrl,
3411 vsysThis.strVendorUrl);
3412
3413 /* VM description */
3414 if (!vsysThis.strDescription.isEmpty())
3415 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
3416 "",
3417 vsysThis.strDescription,
3418 vsysThis.strDescription);
3419
3420 /* VM license */
3421 if (!vsysThis.strLicenseText.isEmpty())
3422 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
3423 "",
3424 vsysThis.strLicenseText,
3425 vsysThis.strLicenseText);
3426
3427 /* Now that we know the OS type, get our internal defaults based on that. */
3428 ComPtr<IGuestOSType> pGuestOSType;
3429 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), pGuestOSType.asOutParam());
3430 CheckComRCThrowRC(rc);
3431
3432 /* CPU count */
3433 ULONG cpuCountVBox = vsysThis.cCPUs;
3434 /* Check for the constrains */
3435 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
3436 {
3437 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
3438 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
3439 cpuCountVBox = SchemaDefs::MaxCPUCount;
3440 }
3441 if (vsysThis.cCPUs == 0)
3442 cpuCountVBox = 1;
3443 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
3444 "",
3445 Utf8StrFmt("%RI32", (uint32_t)vsysThis.cCPUs),
3446 Utf8StrFmt("%RI32", (uint32_t)cpuCountVBox));
3447
3448 /* RAM */
3449 uint64_t ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
3450 /* Check for the constrains */
3451 if (ullMemSizeVBox != 0 &&
3452 (ullMemSizeVBox < MM_RAM_MIN_IN_MB ||
3453 ullMemSizeVBox > MM_RAM_MAX_IN_MB))
3454 {
3455 addWarning(tr("The virtual system \"%s\" claims support for %llu MB RAM size, but VirtualBox has support for min %u & max %u MB RAM size only."),
3456 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
3457 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
3458 }
3459 if (vsysThis.ullMemorySize == 0)
3460 {
3461 /* If the RAM of the OVF is zero, use our predefined values */
3462 ULONG memSizeVBox2;
3463 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
3464 CheckComRCThrowRC(rc);
3465 /* VBox stores that in MByte */
3466 ullMemSizeVBox = (uint64_t)memSizeVBox2;
3467 }
3468 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
3469 "",
3470 Utf8StrFmt("%RI64", (uint64_t)vsysThis.ullMemorySize),
3471 Utf8StrFmt("%RI64", (uint64_t)ullMemSizeVBox));
3472
3473 /* Audio */
3474 if (!vsysThis.strSoundCardType.isEmpty())
3475 /* Currently we set the AC97 always.
3476 @todo: figure out the hardware which could be possible */
3477 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
3478 "",
3479 vsysThis.strSoundCardType,
3480 Utf8StrFmt("%RI32", (uint32_t)AudioControllerType_AC97));
3481
3482#ifdef VBOX_WITH_USB
3483 /* USB Controller */
3484 if (vsysThis.fHasUsbController)
3485 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
3486#endif /* VBOX_WITH_USB */
3487
3488 /* Network Controller */
3489 size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size();
3490 if (cEthernetAdapters > 0)
3491 {
3492 /* Check for the constrains */
3493 if (cEthernetAdapters > SchemaDefs::NetworkAdapterCount)
3494 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
3495 vsysThis.strName.c_str(), cEthernetAdapters, SchemaDefs::NetworkAdapterCount);
3496
3497 /* Get the default network adapter type for the selected guest OS */
3498 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
3499 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
3500 CheckComRCThrowRC(rc);
3501
3502 EthernetAdaptersList::const_iterator itEA;
3503 /* Iterate through all abstract networks. We support 8 network
3504 * adapters at the maximum, so the first 8 will be added only. */
3505 size_t a = 0;
3506 for (itEA = vsysThis.llEthernetAdapters.begin();
3507 itEA != vsysThis.llEthernetAdapters.end() && a < SchemaDefs::NetworkAdapterCount;
3508 ++itEA, ++a)
3509 {
3510 const EthernetAdapter &ea = *itEA; // logical network to connect to
3511 Utf8Str strNetwork = ea.strNetworkName;
3512 // make sure it's one of these two
3513 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
3514 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
3515 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
3516 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
3517 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
3518 )
3519 strNetwork = "Bridged"; // VMware assumes this is the default apparently
3520
3521 /* Figure out the hardware type */
3522 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
3523 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
3524 {
3525 /* If the default adapter is already one of the two
3526 * PCNet adapters use the default one. If not use the
3527 * Am79C970A as fallback. */
3528 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
3529 defaultAdapterVBox == NetworkAdapterType_Am79C973))
3530 nwAdapterVBox = NetworkAdapterType_Am79C970A;
3531 }
3532#ifdef VBOX_WITH_E1000
3533 /* VMWare accidentally write this with VirtualCenter 3.5,
3534 so make sure in this case always to use the VMWare one */
3535 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
3536 nwAdapterVBox = NetworkAdapterType_I82545EM;
3537 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
3538 {
3539 /* Check if this OVF was written by VirtualBox */
3540 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
3541 {
3542 /* If the default adapter is already one of the three
3543 * E1000 adapters use the default one. If not use the
3544 * I82545EM as fallback. */
3545 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
3546 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
3547 defaultAdapterVBox == NetworkAdapterType_I82545EM))
3548 nwAdapterVBox = NetworkAdapterType_I82540EM;
3549 }
3550 else
3551 /* Always use this one since it's what VMware uses */
3552 nwAdapterVBox = NetworkAdapterType_I82545EM;
3553 }
3554#endif /* VBOX_WITH_E1000 */
3555
3556 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
3557 "", // ref
3558 ea.strNetworkName, // orig
3559 Utf8StrFmt("%RI32", (uint32_t)nwAdapterVBox), // conf
3560 0,
3561 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
3562 }
3563 }
3564
3565 /* Floppy Drive */
3566 if (vsysThis.fHasFloppyDrive)
3567 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
3568
3569 /* CD Drive */
3570 /* @todo: I can't disable the CDROM. So nothing to do for now */
3571 /*
3572 if (vsysThis.fHasCdromDrive)
3573 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");*/
3574
3575 /* Hard disk Controller */
3576 uint16_t cIDEused = 0;
3577 uint16_t cSATAused = 0; NOREF(cSATAused);
3578 uint16_t cSCSIused = 0; NOREF(cSCSIused);
3579 ControllersMap::const_iterator hdcIt;
3580 /* Iterate through all hard disk controllers */
3581 for (hdcIt = vsysThis.mapControllers.begin();
3582 hdcIt != vsysThis.mapControllers.end();
3583 ++hdcIt)
3584 {
3585 const HardDiskController &hdc = hdcIt->second;
3586 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
3587
3588 switch (hdc.system)
3589 {
3590 case HardDiskController::IDE:
3591 {
3592 /* Check for the constrains */
3593 /* @todo: I'm very confused! Are these bits *one* controller or
3594 is every port/bus declared as an extra controller. */
3595 if (cIDEused < 4)
3596 {
3597 // @todo: figure out the IDE types
3598 /* Use PIIX4 as default */
3599 Utf8Str strType = "PIIX4";
3600 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
3601 strType = "PIIX3";
3602 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
3603 strType = "ICH6";
3604 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
3605 strControllerID,
3606 hdc.strControllerType,
3607 strType);
3608 }
3609 else
3610 {
3611 /* Warn only once */
3612 if (cIDEused == 1)
3613 addWarning(tr("The virtual \"%s\" system requests support for more than one IDE controller, but VirtualBox has support for only one."),
3614 vsysThis.strName.c_str());
3615
3616 }
3617 ++cIDEused;
3618 break;
3619 }
3620
3621 case HardDiskController::SATA:
3622 {
3623#ifdef VBOX_WITH_AHCI
3624 /* Check for the constrains */
3625 if (cSATAused < 1)
3626 {
3627 // @todo: figure out the SATA types
3628 /* We only support a plain AHCI controller, so use them always */
3629 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
3630 strControllerID,
3631 hdc.strControllerType,
3632 "AHCI");
3633 }
3634 else
3635 {
3636 /* Warn only once */
3637 if (cSATAused == 1)
3638 addWarning(tr("The virtual system \"%s\" requests support for more than one SATA controller, but VirtualBox has support for only one"),
3639 vsysThis.strName.c_str());
3640
3641 }
3642 ++cSATAused;
3643 break;
3644#else /* !VBOX_WITH_AHCI */
3645 addWarning(tr("The virtual system \"%s\" requests at least one SATA controller but this version of VirtualBox does not provide a SATA controller emulation"),
3646 vsysThis.strName.c_str());
3647#endif /* !VBOX_WITH_AHCI */
3648 }
3649
3650 case HardDiskController::SCSI:
3651 {
3652#ifdef VBOX_WITH_LSILOGIC
3653 /* Check for the constrains */
3654 if (cSCSIused < 1)
3655 {
3656 Utf8Str hdcController = "LsiLogic";
3657 if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
3658 hdcController = "BusLogic";
3659 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
3660 strControllerID,
3661 hdc.strControllerType,
3662 hdcController);
3663 }
3664 else
3665 addWarning(tr("The virtual system \"%s\" requests support for an additional SCSI controller of type \"%s\" with ID %s, but VirtualBox presently supports only one SCSI controller."),
3666 vsysThis.strName.c_str(),
3667 hdc.strControllerType.c_str(),
3668 strControllerID.c_str());
3669 ++cSCSIused;
3670 break;
3671#else /* !VBOX_WITH_LSILOGIC */
3672 addWarning(tr("The virtual system \"%s\" requests at least one SATA controller but this version of VirtualBox does not provide a SCSI controller emulation"),
3673 vsysThis.strName.c_str());
3674#endif /* !VBOX_WITH_LSILOGIC */
3675 }
3676 }
3677 }
3678
3679 /* Hard disks */
3680 if (vsysThis.mapVirtualDisks.size() > 0)
3681 {
3682 VirtualDisksMap::const_iterator itVD;
3683 /* Iterate through all hard disks ()*/
3684 for (itVD = vsysThis.mapVirtualDisks.begin();
3685 itVD != vsysThis.mapVirtualDisks.end();
3686 ++itVD)
3687 {
3688 const VirtualDisk &hd = itVD->second;
3689 /* Get the associated disk image */
3690 const DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
3691
3692 // @todo:
3693 // - figure out all possible vmdk formats we also support
3694 // - figure out if there is a url specifier for vhd already
3695 // - we need a url specifier for the vdi format
3696 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
3697 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
3698 {
3699 /* If the href is empty use the VM name as filename */
3700 Utf8Str strFilename = di.strHref;
3701 if (!strFilename.length())
3702 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
3703 /* Construct a unique target path */
3704 Utf8StrFmt strPath("%ls%c%s",
3705 bstrDefaultHardDiskLocation.raw(),
3706 RTPATH_DELIMITER,
3707 strFilename.c_str());
3708 searchUniqueDiskImageFilePath(strPath);
3709
3710 /* find the description for the hard disk controller
3711 * that has the same ID as hd.idController */
3712 const VirtualSystemDescriptionEntry *pController;
3713 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
3714 throw setError(E_FAIL,
3715 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
3716 hd.idController,
3717 di.strHref.c_str());
3718
3719 /* controller to attach to, and the bus within that controller */
3720 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
3721 pController->ulIndex,
3722 hd.ulAddressOnParent);
3723 ULONG ulSize = 0;
3724 if (di.iCapacity != -1)
3725 ulSize = (ULONG)(di.iCapacity / _1M);
3726 else if (di.iPopulatedSize != -1)
3727 ulSize = (ULONG)(di.iPopulatedSize / _1M);
3728 else if (di.iSize != -1)
3729 ulSize = (ULONG)(di.iSize / _1M);
3730 if (ulSize == 0)
3731 ulSize = 10000; // assume 10 GB, this is for the progress bar only anyway
3732 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
3733 hd.strDiskId,
3734 di.strHref,
3735 strPath,
3736 ulSize,
3737 strExtraConfig);
3738 }
3739 else
3740 throw setError(VBOX_E_FILE_ERROR,
3741 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
3742 }
3743 }
3744
3745 m->virtualSystemDescriptions.push_back(pNewDesc);
3746 }
3747 }
3748 catch (HRESULT aRC)
3749 {
3750 /* On error we clear the list & return */
3751 m->virtualSystemDescriptions.clear();
3752 rc = aRC;
3753 }
3754
3755 return rc;
3756}
3757
3758/**
3759 * Public method implementation.
3760 * @param aProgress
3761 * @return
3762 */
3763STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
3764{
3765 CheckComArgOutPointerValid(aProgress);
3766
3767 AutoCaller autoCaller(this);
3768 CheckComRCReturnRC(autoCaller.rc());
3769
3770 AutoReadLock(this);
3771
3772 if (!m->pReader)
3773 return setError(E_FAIL,
3774 tr("Cannot import machines without reading it first (call read() before importMachines())"));
3775
3776 ComObjPtr<Progress> progress;
3777 HRESULT rc = S_OK;
3778 try
3779 {
3780 rc = importImpl(m->locInfo, progress);
3781 }
3782 catch (HRESULT aRC)
3783 {
3784 rc = aRC;
3785 }
3786
3787 if (SUCCEEDED(rc))
3788 /* Return progress to the caller */
3789 progress.queryInterfaceTo(aProgress);
3790
3791 return rc;
3792}
3793
3794STDMETHODIMP Appliance::CreateVFSExplorer(IN_BSTR aURI, IVFSExplorer **aExplorer)
3795{
3796 CheckComArgOutPointerValid(aExplorer);
3797
3798 AutoCaller autoCaller(this);
3799 CheckComRCReturnRC(autoCaller.rc());
3800
3801 AutoReadLock(this);
3802
3803 ComObjPtr<VFSExplorer> explorer;
3804 HRESULT rc = S_OK;
3805 try
3806 {
3807 Utf8Str uri(aURI);
3808 /* Check which kind of export the user has requested */
3809 LocationInfo li;
3810 parseURI(uri, li);
3811 /* Create the explorer object */
3812 explorer.createObject();
3813 rc = explorer->init(li.storageType, li.strPath, li.strHostname, li.strUsername, li.strPassword, mVirtualBox);
3814 }
3815 catch (HRESULT aRC)
3816 {
3817 rc = aRC;
3818 }
3819
3820 if (SUCCEEDED(rc))
3821 /* Return explorer to the caller */
3822 explorer.queryInterfaceTo(aExplorer);
3823
3824 return rc;
3825}
3826
3827STDMETHODIMP Appliance::Write(IN_BSTR format, IN_BSTR path, IProgress **aProgress)
3828{
3829 if (!path) return E_POINTER;
3830 CheckComArgOutPointerValid(aProgress);
3831
3832 AutoCaller autoCaller(this);
3833 CheckComRCReturnRC(autoCaller.rc());
3834
3835 AutoWriteLock(this);
3836
3837 // see if we can handle this file; for now we insist it has an ".ovf" extension
3838 Utf8Str strPath = path;
3839 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
3840 return setError(VBOX_E_FILE_ERROR,
3841 tr("Appliance file must have .ovf extension"));
3842
3843 Utf8Str strFormat(format);
3844 TaskExportOVF::OVFFormat ovfF;
3845 if (strFormat == "ovf-0.9")
3846 ovfF = TaskExportOVF::OVF_0_9;
3847 else if (strFormat == "ovf-1.0")
3848 ovfF = TaskExportOVF::OVF_1_0;
3849 else
3850 return setError(VBOX_E_FILE_ERROR,
3851 tr("Invalid format \"%s\" specified"), strFormat.c_str());
3852
3853 ComObjPtr<Progress> progress;
3854 HRESULT rc = S_OK;
3855 try
3856 {
3857 /* Parse all necessary info out of the URI */
3858 parseURI(strPath, m->locInfo);
3859 rc = writeImpl(ovfF, m->locInfo, progress);
3860 }
3861 catch (HRESULT aRC)
3862 {
3863 rc = aRC;
3864 }
3865
3866 if (SUCCEEDED(rc))
3867 /* Return progress to the caller */
3868 progress.queryInterfaceTo(aProgress);
3869
3870 return rc;
3871}
3872
3873/**
3874* Public method implementation.
3875 * @return
3876 */
3877STDMETHODIMP Appliance::GetWarnings(ComSafeArrayOut(BSTR, aWarnings))
3878{
3879 if (ComSafeArrayOutIsNull(aWarnings))
3880 return E_POINTER;
3881
3882 AutoCaller autoCaller(this);
3883 CheckComRCReturnRC(autoCaller.rc());
3884
3885 AutoReadLock alock(this);
3886
3887 com::SafeArray<BSTR> sfaWarnings(m->llWarnings.size());
3888
3889 list<Utf8Str>::const_iterator it;
3890 size_t i = 0;
3891 for (it = m->llWarnings.begin();
3892 it != m->llWarnings.end();
3893 ++it, ++i)
3894 {
3895 Bstr bstr = *it;
3896 bstr.cloneTo(&sfaWarnings[i]);
3897 }
3898
3899 sfaWarnings.detachTo(ComSafeArrayOutArg(aWarnings));
3900
3901 return S_OK;
3902}
3903
3904////////////////////////////////////////////////////////////////////////////////
3905//
3906// IVirtualSystemDescription constructor / destructor
3907//
3908////////////////////////////////////////////////////////////////////////////////
3909
3910DEFINE_EMPTY_CTOR_DTOR(VirtualSystemDescription)
3911
3912/**
3913 * COM initializer.
3914 * @return
3915 */
3916HRESULT VirtualSystemDescription::init()
3917{
3918 /* Enclose the state transition NotReady->InInit->Ready */
3919 AutoInitSpan autoInitSpan(this);
3920 AssertReturn(autoInitSpan.isOk(), E_FAIL);
3921
3922 /* Initialize data */
3923 m = new Data();
3924
3925 /* Confirm a successful initialization */
3926 autoInitSpan.setSucceeded();
3927 return S_OK;
3928}
3929
3930/**
3931* COM uninitializer.
3932*/
3933
3934void VirtualSystemDescription::uninit()
3935{
3936 delete m;
3937 m = NULL;
3938}
3939
3940////////////////////////////////////////////////////////////////////////////////
3941//
3942// IVirtualSystemDescription public methods
3943//
3944////////////////////////////////////////////////////////////////////////////////
3945
3946/**
3947 * Public method implementation.
3948 * @param
3949 * @return
3950 */
3951STDMETHODIMP VirtualSystemDescription::COMGETTER(Count)(ULONG *aCount)
3952{
3953 if (!aCount)
3954 return E_POINTER;
3955
3956 AutoCaller autoCaller(this);
3957 CheckComRCReturnRC(autoCaller.rc());
3958
3959 AutoReadLock alock(this);
3960
3961 *aCount = (ULONG)m->llDescriptions.size();
3962
3963 return S_OK;
3964}
3965
3966/**
3967 * Public method implementation.
3968 * @return
3969 */
3970STDMETHODIMP VirtualSystemDescription::GetDescription(ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
3971 ComSafeArrayOut(BSTR, aRefs),
3972 ComSafeArrayOut(BSTR, aOrigValues),
3973 ComSafeArrayOut(BSTR, aVboxValues),
3974 ComSafeArrayOut(BSTR, aExtraConfigValues))
3975{
3976 if (ComSafeArrayOutIsNull(aTypes) ||
3977 ComSafeArrayOutIsNull(aRefs) ||
3978 ComSafeArrayOutIsNull(aOrigValues) ||
3979 ComSafeArrayOutIsNull(aVboxValues) ||
3980 ComSafeArrayOutIsNull(aExtraConfigValues))
3981 return E_POINTER;
3982
3983 AutoCaller autoCaller(this);
3984 CheckComRCReturnRC(autoCaller.rc());
3985
3986 AutoReadLock alock(this);
3987
3988 ULONG c = (ULONG)m->llDescriptions.size();
3989 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
3990 com::SafeArray<BSTR> sfaRefs(c);
3991 com::SafeArray<BSTR> sfaOrigValues(c);
3992 com::SafeArray<BSTR> sfaVboxValues(c);
3993 com::SafeArray<BSTR> sfaExtraConfigValues(c);
3994
3995 list<VirtualSystemDescriptionEntry>::const_iterator it;
3996 size_t i = 0;
3997 for (it = m->llDescriptions.begin();
3998 it != m->llDescriptions.end();
3999 ++it, ++i)
4000 {
4001 const VirtualSystemDescriptionEntry &vsde = (*it);
4002
4003 sfaTypes[i] = vsde.type;
4004
4005 Bstr bstr = vsde.strRef;
4006 bstr.cloneTo(&sfaRefs[i]);
4007
4008 bstr = vsde.strOvf;
4009 bstr.cloneTo(&sfaOrigValues[i]);
4010
4011 bstr = vsde.strVbox;
4012 bstr.cloneTo(&sfaVboxValues[i]);
4013
4014 bstr = vsde.strExtraConfig;
4015 bstr.cloneTo(&sfaExtraConfigValues[i]);
4016 }
4017
4018 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
4019 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
4020 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
4021 sfaVboxValues.detachTo(ComSafeArrayOutArg(aVboxValues));
4022 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
4023
4024 return S_OK;
4025}
4026
4027/**
4028 * Public method implementation.
4029 * @return
4030 */
4031STDMETHODIMP VirtualSystemDescription::GetDescriptionByType(VirtualSystemDescriptionType_T aType,
4032 ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
4033 ComSafeArrayOut(BSTR, aRefs),
4034 ComSafeArrayOut(BSTR, aOrigValues),
4035 ComSafeArrayOut(BSTR, aVboxValues),
4036 ComSafeArrayOut(BSTR, aExtraConfigValues))
4037{
4038 if (ComSafeArrayOutIsNull(aTypes) ||
4039 ComSafeArrayOutIsNull(aRefs) ||
4040 ComSafeArrayOutIsNull(aOrigValues) ||
4041 ComSafeArrayOutIsNull(aVboxValues) ||
4042 ComSafeArrayOutIsNull(aExtraConfigValues))
4043 return E_POINTER;
4044
4045 AutoCaller autoCaller(this);
4046 CheckComRCReturnRC(autoCaller.rc());
4047
4048 AutoReadLock alock(this);
4049
4050 std::list<VirtualSystemDescriptionEntry*> vsd = findByType (aType);
4051 ULONG c = (ULONG)vsd.size();
4052 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
4053 com::SafeArray<BSTR> sfaRefs(c);
4054 com::SafeArray<BSTR> sfaOrigValues(c);
4055 com::SafeArray<BSTR> sfaVboxValues(c);
4056 com::SafeArray<BSTR> sfaExtraConfigValues(c);
4057
4058 list<VirtualSystemDescriptionEntry*>::const_iterator it;
4059 size_t i = 0;
4060 for (it = vsd.begin();
4061 it != vsd.end();
4062 ++it, ++i)
4063 {
4064 const VirtualSystemDescriptionEntry *vsde = (*it);
4065
4066 sfaTypes[i] = vsde->type;
4067
4068 Bstr bstr = vsde->strRef;
4069 bstr.cloneTo(&sfaRefs[i]);
4070
4071 bstr = vsde->strOvf;
4072 bstr.cloneTo(&sfaOrigValues[i]);
4073
4074 bstr = vsde->strVbox;
4075 bstr.cloneTo(&sfaVboxValues[i]);
4076
4077 bstr = vsde->strExtraConfig;
4078 bstr.cloneTo(&sfaExtraConfigValues[i]);
4079 }
4080
4081 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
4082 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
4083 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
4084 sfaVboxValues.detachTo(ComSafeArrayOutArg(aVboxValues));
4085 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
4086
4087 return S_OK;
4088}
4089
4090/**
4091 * Public method implementation.
4092 * @return
4093 */
4094STDMETHODIMP VirtualSystemDescription::GetValuesByType(VirtualSystemDescriptionType_T aType,
4095 VirtualSystemDescriptionValueType_T aWhich,
4096 ComSafeArrayOut(BSTR, aValues))
4097{
4098 if (ComSafeArrayOutIsNull(aValues))
4099 return E_POINTER;
4100
4101 AutoCaller autoCaller(this);
4102 CheckComRCReturnRC(autoCaller.rc());
4103
4104 AutoReadLock alock(this);
4105
4106 std::list<VirtualSystemDescriptionEntry*> vsd = findByType (aType);
4107 com::SafeArray<BSTR> sfaValues((ULONG)vsd.size());
4108
4109 list<VirtualSystemDescriptionEntry*>::const_iterator it;
4110 size_t i = 0;
4111 for (it = vsd.begin();
4112 it != vsd.end();
4113 ++it, ++i)
4114 {
4115 const VirtualSystemDescriptionEntry *vsde = (*it);
4116
4117 Bstr bstr;
4118 switch (aWhich)
4119 {
4120 case VirtualSystemDescriptionValueType_Reference: bstr = vsde->strRef; break;
4121 case VirtualSystemDescriptionValueType_Original: bstr = vsde->strOvf; break;
4122 case VirtualSystemDescriptionValueType_Auto: bstr = vsde->strVbox; break;
4123 case VirtualSystemDescriptionValueType_ExtraConfig: bstr = vsde->strExtraConfig; break;
4124 }
4125
4126 bstr.cloneTo(&sfaValues[i]);
4127 }
4128
4129 sfaValues.detachTo(ComSafeArrayOutArg(aValues));
4130
4131 return S_OK;
4132}
4133
4134/**
4135 * Public method implementation.
4136 * @return
4137 */
4138STDMETHODIMP VirtualSystemDescription::SetFinalValues(ComSafeArrayIn(BOOL, aEnabled),
4139 ComSafeArrayIn(IN_BSTR, argVboxValues),
4140 ComSafeArrayIn(IN_BSTR, argExtraConfigValues))
4141{
4142#ifndef RT_OS_WINDOWS
4143 NOREF(aEnabledSize);
4144#endif /* RT_OS_WINDOWS */
4145
4146 CheckComArgSafeArrayNotNull(aEnabled);
4147 CheckComArgSafeArrayNotNull(argVboxValues);
4148 CheckComArgSafeArrayNotNull(argExtraConfigValues);
4149
4150 AutoCaller autoCaller(this);
4151 CheckComRCReturnRC(autoCaller.rc());
4152
4153 AutoWriteLock alock(this);
4154
4155 com::SafeArray<BOOL> sfaEnabled(ComSafeArrayInArg(aEnabled));
4156 com::SafeArray<IN_BSTR> sfaVboxValues(ComSafeArrayInArg(argVboxValues));
4157 com::SafeArray<IN_BSTR> sfaExtraConfigValues(ComSafeArrayInArg(argExtraConfigValues));
4158
4159 if ( (sfaEnabled.size() != m->llDescriptions.size())
4160 || (sfaVboxValues.size() != m->llDescriptions.size())
4161 || (sfaExtraConfigValues.size() != m->llDescriptions.size())
4162 )
4163 return E_INVALIDARG;
4164
4165 list<VirtualSystemDescriptionEntry>::iterator it;
4166 size_t i = 0;
4167 for (it = m->llDescriptions.begin();
4168 it != m->llDescriptions.end();
4169 ++it, ++i)
4170 {
4171 VirtualSystemDescriptionEntry& vsde = *it;
4172
4173 if (sfaEnabled[i])
4174 {
4175 vsde.strVbox = sfaVboxValues[i];
4176 vsde.strExtraConfig = sfaExtraConfigValues[i];
4177 }
4178 else
4179 vsde.type = VirtualSystemDescriptionType_Ignore;
4180 }
4181
4182 return S_OK;
4183}
4184
4185/**
4186 * Public method implementation.
4187 * @return
4188 */
4189STDMETHODIMP VirtualSystemDescription::AddDescription(VirtualSystemDescriptionType_T aType,
4190 IN_BSTR aVboxValue,
4191 IN_BSTR aExtraConfigValue)
4192{
4193 CheckComArgNotNull(aVboxValue);
4194 CheckComArgNotNull(aExtraConfigValue);
4195
4196 AutoCaller autoCaller(this);
4197 CheckComRCReturnRC(autoCaller.rc());
4198
4199 AutoWriteLock alock(this);
4200
4201 addEntry(aType, "", aVboxValue, aVboxValue, 0, aExtraConfigValue);
4202
4203 return S_OK;
4204}
4205
4206/**
4207 * Internal method; adds a new description item to the member list.
4208 * @param aType Type of description for the new item.
4209 * @param strRef Reference item; only used with hard disk controllers.
4210 * @param aOrigValue Corresponding original value from OVF.
4211 * @param aAutoValue Initial configuration value (can be overridden by caller with setFinalValues).
4212 * @param ulSizeMB Weight for IProgress
4213 * @param strExtraConfig Extra configuration; meaning dependent on type.
4214 */
4215void VirtualSystemDescription::addEntry(VirtualSystemDescriptionType_T aType,
4216 const Utf8Str &strRef,
4217 const Utf8Str &aOrigValue,
4218 const Utf8Str &aAutoValue,
4219 uint32_t ulSizeMB,
4220 const Utf8Str &strExtraConfig /*= ""*/)
4221{
4222 VirtualSystemDescriptionEntry vsde;
4223 vsde.ulIndex = (uint32_t)m->llDescriptions.size(); // each entry gets an index so the client side can reference them
4224 vsde.type = aType;
4225 vsde.strRef = strRef;
4226 vsde.strOvf = aOrigValue;
4227 vsde.strVbox = aAutoValue;
4228 vsde.strExtraConfig = strExtraConfig;
4229 vsde.ulSizeMB = ulSizeMB;
4230
4231 m->llDescriptions.push_back(vsde);
4232}
4233
4234/**
4235 * Private method; returns a list of description items containing all the items from the member
4236 * description items of this virtual system that match the given type.
4237 * @param aType
4238 * @return
4239 */
4240std::list<VirtualSystemDescriptionEntry*> VirtualSystemDescription::findByType(VirtualSystemDescriptionType_T aType)
4241{
4242 std::list<VirtualSystemDescriptionEntry*> vsd;
4243
4244 list<VirtualSystemDescriptionEntry>::iterator it;
4245 for (it = m->llDescriptions.begin();
4246 it != m->llDescriptions.end();
4247 ++it)
4248 {
4249 if (it->type == aType)
4250 vsd.push_back(&(*it));
4251 }
4252
4253 return vsd;
4254}
4255
4256/**
4257 * Private method; looks thru the member hardware items for the IDE, SATA, or SCSI controller with
4258 * the given reference ID. Useful when needing the controller for a particular
4259 * virtual disk.
4260 * @param id
4261 * @return
4262 */
4263const VirtualSystemDescriptionEntry* VirtualSystemDescription::findControllerFromID(uint32_t id)
4264{
4265 Utf8Str strRef = Utf8StrFmt("%RI32", id);
4266 list<VirtualSystemDescriptionEntry>::const_iterator it;
4267 for (it = m->llDescriptions.begin();
4268 it != m->llDescriptions.end();
4269 ++it)
4270 {
4271 const VirtualSystemDescriptionEntry &d = *it;
4272 switch (d.type)
4273 {
4274 case VirtualSystemDescriptionType_HardDiskControllerIDE:
4275 case VirtualSystemDescriptionType_HardDiskControllerSATA:
4276 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
4277 if (d.strRef == strRef)
4278 return &d;
4279 break;
4280 }
4281 }
4282
4283 return NULL;
4284}
4285
4286////////////////////////////////////////////////////////////////////////////////
4287//
4288// IMachine public methods
4289//
4290////////////////////////////////////////////////////////////////////////////////
4291
4292// This code is here so we won't have to include the appliance headers in the
4293// IMachine implementation, and we also need to access private appliance data.
4294
4295/**
4296* Public method implementation.
4297* @param appliance
4298* @return
4299*/
4300
4301STDMETHODIMP Machine::Export(IAppliance *aAppliance, IVirtualSystemDescription **aDescription)
4302{
4303 HRESULT rc = S_OK;
4304
4305 if (!aAppliance)
4306 return E_POINTER;
4307
4308 AutoCaller autoCaller(this);
4309 CheckComRCReturnRC(autoCaller.rc());
4310
4311 AutoReadLock alock(this);
4312
4313 ComObjPtr<VirtualSystemDescription> pNewDesc;
4314
4315 try
4316 {
4317 Bstr bstrName;
4318 Bstr bstrDescription;
4319 Bstr bstrGuestOSType;
4320 uint32_t cCPUs;
4321 uint32_t ulMemSizeMB;
4322 BOOL fDVDEnabled = FALSE;
4323 BOOL fFloppyEnabled = FALSE;
4324 BOOL fUSBEnabled;
4325 BOOL fAudioEnabled;
4326 AudioControllerType_T audioController;
4327
4328 ComPtr<IUSBController> pUsbController;
4329 ComPtr<IAudioAdapter> pAudioAdapter;
4330
4331 // get name
4332 bstrName = mUserData->mName;
4333 // get description
4334 bstrDescription = mUserData->mDescription;
4335 // get guest OS
4336 bstrGuestOSType = mUserData->mOSTypeId;
4337 // CPU count
4338 cCPUs = mHWData->mCPUCount;
4339 // memory size in MB
4340 ulMemSizeMB = mHWData->mMemorySize;
4341 // VRAM size?
4342 // BIOS settings?
4343 // 3D acceleration enabled?
4344 // hardware virtualization enabled?
4345 // nested paging enabled?
4346 // HWVirtExVPIDEnabled?
4347 // PAEEnabled?
4348 // snapshotFolder?
4349 // VRDPServer?
4350
4351/// @todo FIXME // @todo mediumbranch
4352#if 0
4353 // floppy
4354 rc = mFloppyDrive->COMGETTER(Enabled)(&fFloppyEnabled);
4355 if (FAILED(rc)) throw rc;
4356
4357 // CD-ROM ?!?
4358 // ComPtr<IDVDDrive> pDVDDrive;
4359 fDVDEnabled = 1;
4360#endif
4361
4362 // this is more tricky so use the COM method
4363 rc = COMGETTER(USBController)(pUsbController.asOutParam());
4364 if (FAILED(rc))
4365 fUSBEnabled = false;
4366 else
4367 rc = pUsbController->COMGETTER(Enabled)(&fUSBEnabled);
4368
4369 pAudioAdapter = mAudioAdapter;
4370 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
4371 if (FAILED(rc)) throw rc;
4372 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
4373 if (FAILED(rc)) throw rc;
4374
4375 // create a new virtual system
4376 rc = pNewDesc.createObject();
4377 CheckComRCThrowRC(rc);
4378 rc = pNewDesc->init();
4379 CheckComRCThrowRC(rc);
4380
4381 /* Guest OS type */
4382 Utf8Str strOsTypeVBox(bstrGuestOSType);
4383 CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str());
4384 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
4385 "",
4386 Utf8StrFmt("%RI32", cim),
4387 strOsTypeVBox);
4388
4389 /* VM name */
4390 Utf8Str strVMName(bstrName);
4391 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
4392 "",
4393 strVMName,
4394 strVMName);
4395
4396 // description
4397 Utf8Str strDescription(bstrDescription);
4398 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
4399 "",
4400 strDescription,
4401 strDescription);
4402
4403 /* CPU count*/
4404 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
4405 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
4406 "",
4407 strCpuCount,
4408 strCpuCount);
4409
4410 /* Memory */
4411 Utf8Str strMemory = Utf8StrFmt("%RI32", (uint64_t)ulMemSizeMB * _1M);
4412 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
4413 "",
4414 strMemory,
4415 strMemory);
4416
4417 int32_t lIDEControllerIndex = 0;
4418 int32_t lSATAControllerIndex = 0;
4419 int32_t lSCSIControllerIndex = 0;
4420
4421// <const name="HardDiskControllerIDE" value="6" />
4422 ComPtr<IStorageController> pController;
4423 rc = GetStorageControllerByName(Bstr("IDE Controller"), pController.asOutParam());
4424 if (FAILED(rc)) throw rc;
4425 Utf8Str strVbox;
4426 StorageControllerType_T ctlr;
4427 rc = pController->COMGETTER(ControllerType)(&ctlr);
4428 if (FAILED(rc)) throw rc;
4429 switch(ctlr)
4430 {
4431 case StorageControllerType_PIIX3: strVbox = "PIIX3"; break;
4432 case StorageControllerType_PIIX4: strVbox = "PIIX4"; break;
4433 case StorageControllerType_ICH6: strVbox = "ICH6"; break;
4434 }
4435
4436 if (strVbox.length())
4437 {
4438 lIDEControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4439 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
4440 Utf8StrFmt("%d", lIDEControllerIndex),
4441 strVbox,
4442 strVbox);
4443 }
4444
4445#ifdef VBOX_WITH_AHCI
4446// <const name="HardDiskControllerSATA" value="7" />
4447 rc = GetStorageControllerByName(Bstr("SATA Controller"), pController.asOutParam());
4448 if (SUCCEEDED(rc))
4449 {
4450 strVbox = "AHCI";
4451 lSATAControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4452 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
4453 Utf8StrFmt("%d", lSATAControllerIndex),
4454 strVbox,
4455 strVbox);
4456 }
4457#endif // VBOX_WITH_AHCI
4458
4459#ifdef VBOX_WITH_LSILOGIC
4460// <const name="HardDiskControllerSCSI" value="8" />
4461 rc = GetStorageControllerByName(Bstr("SCSI Controller"), pController.asOutParam());
4462 if (SUCCEEDED(rc))
4463 {
4464 rc = pController->COMGETTER(ControllerType)(&ctlr);
4465 if (SUCCEEDED(rc))
4466 {
4467 strVbox = "LsiLogic"; // the default in VBox
4468 switch(ctlr)
4469 {
4470 case StorageControllerType_LsiLogic: strVbox = "LsiLogic"; break;
4471 case StorageControllerType_BusLogic: strVbox = "BusLogic"; break;
4472 }
4473 lSCSIControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4474 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
4475 Utf8StrFmt("%d", lSCSIControllerIndex),
4476 strVbox,
4477 strVbox);
4478 }
4479 else
4480 throw rc;
4481 }
4482#endif // VBOX_WITH_LSILOGIC
4483
4484// <const name="HardDiskImage" value="9" />
4485 MediaData::AttachmentList::iterator itA;
4486 for (itA = mMediaData->mAttachments.begin();
4487 itA != mMediaData->mAttachments.end();
4488 ++itA)
4489 {
4490 ComObjPtr<MediumAttachment> pHDA = *itA;
4491
4492 // the attachment's data
4493 ComPtr<IMedium> pMedium;
4494 ComPtr<IStorageController> ctl;
4495 Bstr controllerName;
4496
4497 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
4498 if (FAILED(rc)) throw rc;
4499
4500 rc = GetStorageControllerByName(controllerName, ctl.asOutParam());
4501 if (FAILED(rc)) throw rc;
4502
4503 StorageBus_T storageBus;
4504 LONG lChannel;
4505 LONG lDevice;
4506
4507 rc = ctl->COMGETTER(Bus)(&storageBus);
4508 if (FAILED(rc)) throw rc;
4509
4510 rc = pHDA->COMGETTER(Medium)(pMedium.asOutParam());
4511 if (FAILED(rc)) throw rc;
4512
4513 rc = pHDA->COMGETTER(Port)(&lChannel);
4514 if (FAILED(rc)) throw rc;
4515
4516 rc = pHDA->COMGETTER(Device)(&lDevice);
4517 if (FAILED(rc)) throw rc;
4518
4519 Bstr bstrLocation;
4520 Bstr bstrName;
4521 if (pMedium) // @todo mediumbranch only for hard disks
4522 {
4523 rc = pMedium->COMGETTER(Location)(bstrLocation.asOutParam());
4524 if (FAILED(rc)) throw rc;
4525 rc = pMedium->COMGETTER(Name)(bstrName.asOutParam());
4526 if (FAILED(rc)) throw rc;
4527
4528 // force reading state, or else size will be returned as 0
4529 MediumState_T ms;
4530 rc = pMedium->RefreshState(&ms);
4531 if (FAILED(rc)) throw rc;
4532
4533 ULONG64 ullSize;
4534 rc = pMedium->COMGETTER(Size)(&ullSize);
4535 if (FAILED(rc)) throw rc;
4536
4537 // and how this translates to the virtual system
4538 int32_t lControllerVsys = 0;
4539 LONG lChannelVsys;
4540
4541 switch (storageBus)
4542 {
4543 case StorageBus_IDE:
4544 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
4545 // and it must be updated when that is changed!
4546
4547 if (lChannel == 0 && lDevice == 0) // primary master
4548 lChannelVsys = 0;
4549 else if (lChannel == 0 && lDevice == 1) // primary slave
4550 lChannelVsys = 1;
4551 else if (lChannel == 1 && lDevice == 1) // secondary slave; secondary master is always CDROM
4552 lChannelVsys = 2;
4553 else
4554 throw setError(VBOX_E_NOT_SUPPORTED,
4555 tr("Cannot handle hard disk attachment: channel is %d, device is %d"), lChannel, lDevice);
4556
4557 lControllerVsys = lIDEControllerIndex;
4558 break;
4559
4560 case StorageBus_SATA:
4561 lChannelVsys = lChannel; // should be between 0 and 29
4562 lControllerVsys = lSATAControllerIndex;
4563 break;
4564
4565 case StorageBus_SCSI:
4566 lChannelVsys = lChannel; // should be between 0 and 15
4567 lControllerVsys = lSCSIControllerIndex;
4568 break;
4569
4570 default:
4571 throw setError(VBOX_E_NOT_SUPPORTED,
4572 tr("Cannot handle hard disk attachment: storageBus is %d, channel is %d, device is %d"), storageBus, lChannel, lDevice);
4573 break;
4574 }
4575
4576 Utf8Str strTargetVmdkName(bstrName);
4577 strTargetVmdkName.stripExt();
4578 strTargetVmdkName.append(".vmdk");
4579
4580 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
4581 strTargetVmdkName, // disk ID: let's use the name
4582 strTargetVmdkName, // OVF value:
4583 Utf8Str(bstrLocation), // vbox value: media path
4584 (uint32_t)(ullSize / _1M),
4585 Utf8StrFmt("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys));
4586 }
4587 }
4588
4589 /* Floppy Drive */
4590 if (fFloppyEnabled) // @todo mediumbranch
4591 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
4592
4593 /* CD Drive */
4594 if (fDVDEnabled) // @todo mediumbranch
4595 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
4596
4597// <const name="NetworkAdapter" />
4598 size_t a;
4599 for (a = 0;
4600 a < SchemaDefs::NetworkAdapterCount;
4601 ++a)
4602 {
4603 ComPtr<INetworkAdapter> pNetworkAdapter;
4604 BOOL fEnabled;
4605 NetworkAdapterType_T adapterType;
4606 NetworkAttachmentType_T attachmentType;
4607
4608 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
4609 if (FAILED(rc)) throw rc;
4610 /* Enable the network card & set the adapter type */
4611 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
4612 if (FAILED(rc)) throw rc;
4613
4614 if (fEnabled)
4615 {
4616 Utf8Str strAttachmentType;
4617
4618 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4619 if (FAILED(rc)) throw rc;
4620
4621 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4622 if (FAILED(rc)) throw rc;
4623
4624 switch (attachmentType)
4625 {
4626 case NetworkAttachmentType_Null:
4627 strAttachmentType = "Null";
4628 break;
4629
4630 case NetworkAttachmentType_NAT:
4631 strAttachmentType = "NAT";
4632 break;
4633
4634 case NetworkAttachmentType_Bridged:
4635 strAttachmentType = "Bridged";
4636 break;
4637
4638 case NetworkAttachmentType_Internal:
4639 strAttachmentType = "Internal";
4640 break;
4641
4642 case NetworkAttachmentType_HostOnly:
4643 strAttachmentType = "HostOnly";
4644 break;
4645 }
4646
4647 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
4648 "", // ref
4649 strAttachmentType, // orig
4650 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
4651 0,
4652 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
4653 }
4654 }
4655
4656// <const name="USBController" />
4657#ifdef VBOX_WITH_USB
4658 if (fUSBEnabled)
4659 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
4660#endif /* VBOX_WITH_USB */
4661
4662// <const name="SoundCard" />
4663 if (fAudioEnabled)
4664 {
4665 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
4666 "",
4667 "ensoniq1371", // this is what OVFTool writes and VMware supports
4668 Utf8StrFmt("%RI32", audioController));
4669 }
4670
4671 // finally, add the virtual system to the appliance
4672 Appliance *pAppliance = static_cast<Appliance*>(aAppliance);
4673 AutoCaller autoCaller1(pAppliance);
4674 CheckComRCReturnRC(autoCaller1.rc());
4675
4676 /* We return the new description to the caller */
4677 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
4678 copy.queryInterfaceTo(aDescription);
4679
4680 AutoWriteLock alock(pAppliance);
4681
4682 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
4683 }
4684 catch(HRESULT arc)
4685 {
4686 rc = arc;
4687 }
4688
4689 return rc;
4690}
4691
4692/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette