VirtualBox

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

Last change on this file since 25414 was 25310, checked in by vboxsync, 14 years ago

Main: lock validator, first batch: implement per-thread stack to trace locking (disabled by default, use VBOX_WITH_LOCK_VALIDATOR, but that WILL FAIL presently)

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

© 2023 Oracle
ContactPrivacy policyTerms of Use