VirtualBox

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

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

Main: coding style: have Main obey the standard VirtualBox coding style rules (no functional changes)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 189.9 KB
Line 
1/* $Id: ApplianceImpl.cpp 21878 2009-07-30 12:42:08Z 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/sha1.h>
29#include <iprt/manifest.h>
30
31#include "ovfreader.h"
32
33#include <VBox/param.h>
34#include <VBox/version.h>
35
36#include "ApplianceImpl.h"
37#include "VFSExplorerImpl.h"
38#include "VirtualBoxImpl.h"
39#include "GuestOSTypeImpl.h"
40#include "ProgressImpl.h"
41#include "MachineImpl.h"
42#include "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 IHardDisk *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 CheckComRCThrowRC(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 CheckComRCThrowRC(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 CheckComRCReturnRC(autoCaller.rc());
924
925 AutoWriteLock appLock(this);
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 CheckComRCReturnRC(autoCaller.rc());
967
968 AutoWriteLock appLock(this);
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(rc))
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));
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.unlock();
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.lock();
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 CheckComRCReturnRC(autoCaller.rc());
1091
1092 AutoWriteLock appLock(this);
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<IHardDisk> > llHardDisksCreated;
1100 list<Guid> llMachinesRegistered;
1101
1102 ComPtr<ISession> session;
1103 bool fSessionOpen = false;
1104 rc = session.createInprocObject(CLSID_Session);
1105 CheckComRCReturnRC(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 i=1; i < filesList.size(); ++i)
1170 RTStrFree(pTestList[i].pszTestDigest);
1171 RTMemFree(pTestList);
1172 if (FAILED(rc))
1173 {
1174 /* Return on error */
1175 pTask->rc = rc;
1176
1177 if (!pTask->progress.isNull())
1178 pTask->progress->notifyComplete(rc);
1179 return rc;
1180 }
1181 }
1182
1183 list<VirtualSystem>::const_iterator it;
1184 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1185 /* Iterate through all virtual systems of that appliance */
1186 size_t i = 0;
1187 for (it = reader.m_llVirtualSystems.begin(),
1188 it1 = m->virtualSystemDescriptions.begin();
1189 it != reader.m_llVirtualSystems.end();
1190 ++it, ++it1, ++i)
1191 {
1192 const VirtualSystem &vsysThis = *it;
1193 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1194
1195 ComPtr<IMachine> pNewMachine;
1196
1197 /* Catch possible errors */
1198 try
1199 {
1200 /* Guest OS type */
1201 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1202 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1203 if (vsdeOS.size() < 1)
1204 throw setError(VBOX_E_FILE_ERROR,
1205 tr("Missing guest OS type"));
1206 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strVbox;
1207
1208 /* Now that we know the base system get our internal defaults based on that. */
1209 ComPtr<IGuestOSType> osType;
1210 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1211 if (FAILED(rc)) throw rc;
1212
1213 /* Create the machine */
1214 /* First get the name */
1215 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1216 if (vsdeName.size() < 1)
1217 throw setError(VBOX_E_FILE_ERROR,
1218 tr("Missing VM name"));
1219 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
1220 rc = mVirtualBox->CreateMachine(Bstr(strNameVBox), Bstr(strOsTypeVBox),
1221 Bstr(), Bstr(),
1222 pNewMachine.asOutParam());
1223 if (FAILED(rc)) throw rc;
1224
1225 // and the description
1226 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1227 if (vsdeDescription.size())
1228 {
1229 const Utf8Str &strDescription = vsdeDescription.front()->strVbox;
1230 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1231 if (FAILED(rc)) throw rc;
1232 }
1233
1234 /* CPU count */
1235 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType (VirtualSystemDescriptionType_CPU);
1236 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1237 const Utf8Str &cpuVBox = vsdeCPU.front()->strVbox;
1238 ULONG tmpCount = (ULONG)RTStrToUInt64(cpuVBox.c_str());
1239 rc = pNewMachine->COMSETTER(CPUCount)(tmpCount);
1240 if (FAILED(rc)) throw rc;
1241 bool fEnableIOApic = false;
1242 /* We need HWVirt & IO-APIC if more than one CPU is requested */
1243 if (tmpCount > 1)
1244 {
1245 rc = pNewMachine->COMSETTER(HWVirtExEnabled)(TRUE);
1246 if (FAILED(rc)) throw rc;
1247
1248 fEnableIOApic = true;
1249 }
1250
1251 /* RAM */
1252 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1253 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1254 const Utf8Str &memoryVBox = vsdeRAM.front()->strVbox;
1255 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1256 rc = pNewMachine->COMSETTER(MemorySize)(tt);
1257 if (FAILED(rc)) throw rc;
1258
1259 /* VRAM */
1260 /* Get the recommended VRAM for this guest OS type */
1261 ULONG vramVBox;
1262 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1263 if (FAILED(rc)) throw rc;
1264
1265 /* Set the VRAM */
1266 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1267 if (FAILED(rc)) throw rc;
1268
1269 /* I/O APIC: so far we have no setting for this. Enable it if we
1270 import a Windows VM because if if Windows was installed without IOAPIC,
1271 it will not mind finding an one later on, but if Windows was installed
1272 _with_ an IOAPIC, it will bluescreen if it's not found */
1273 Bstr bstrFamilyId;
1274 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1275 if (FAILED(rc)) throw rc;
1276
1277 Utf8Str strFamilyId(bstrFamilyId);
1278 if (strFamilyId == "Windows")
1279 fEnableIOApic = true;
1280
1281 /* If IP-APIC should be enabled could be have different reasons.
1282 See CPU count & the Win test above. Here we enable it if it was
1283 previously requested. */
1284 if (fEnableIOApic)
1285 {
1286 ComPtr<IBIOSSettings> pBIOSSettings;
1287 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1288 if (FAILED(rc)) throw rc;
1289
1290 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1291 if (FAILED(rc)) throw rc;
1292 }
1293
1294 /* Audio Adapter */
1295 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1296 /* @todo: we support one audio adapter only */
1297 if (vsdeAudioAdapter.size() > 0)
1298 {
1299 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strVbox;
1300 if (audioAdapterVBox.compare("null", Utf8Str::CaseInsensitive) != 0)
1301 {
1302 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1303 ComPtr<IAudioAdapter> audioAdapter;
1304 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1305 if (FAILED(rc)) throw rc;
1306 rc = audioAdapter->COMSETTER(Enabled)(true);
1307 if (FAILED(rc)) throw rc;
1308 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1309 if (FAILED(rc)) throw rc;
1310 }
1311 }
1312
1313#ifdef VBOX_WITH_USB
1314 /* USB Controller */
1315 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1316 // USB support is enabled if there's at least one such entry; to disable USB support,
1317 // the type of the USB item would have been changed to "ignore"
1318 bool fUSBEnabled = vsdeUSBController.size() > 0;
1319
1320 ComPtr<IUSBController> usbController;
1321 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1322 if (FAILED(rc)) throw rc;
1323 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1324 if (FAILED(rc)) throw rc;
1325#endif /* VBOX_WITH_USB */
1326
1327 /* Change the network adapters */
1328 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1329 if (vsdeNW.size() == 0)
1330 {
1331 /* No network adapters, so we have to disable our default one */
1332 ComPtr<INetworkAdapter> nwVBox;
1333 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1334 if (FAILED(rc)) throw rc;
1335 rc = nwVBox->COMSETTER(Enabled)(false);
1336 if (FAILED(rc)) throw rc;
1337 }
1338 else
1339 {
1340 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1341 /* Iterate through all network cards. We support 8 network adapters
1342 * at the maximum. (@todo: warn if there are more!) */
1343 size_t a = 0;
1344 for (nwIt = vsdeNW.begin();
1345 (nwIt != vsdeNW.end() && a < SchemaDefs::NetworkAdapterCount);
1346 ++nwIt, ++a)
1347 {
1348 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1349
1350 const Utf8Str &nwTypeVBox = pvsys->strVbox;
1351 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1352 ComPtr<INetworkAdapter> pNetworkAdapter;
1353 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1354 if (FAILED(rc)) throw rc;
1355 /* Enable the network card & set the adapter type */
1356 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1357 if (FAILED(rc)) throw rc;
1358 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1359 if (FAILED(rc)) throw rc;
1360
1361 // default is NAT; change to "bridged" if extra conf says so
1362 if (!pvsys->strExtraConfig.compare("type=Bridged", Utf8Str::CaseInsensitive))
1363 {
1364 /* Attach to the right interface */
1365 rc = pNetworkAdapter->AttachToBridgedInterface();
1366 if (FAILED(rc)) throw rc;
1367 ComPtr<IHost> host;
1368 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1369 if (FAILED(rc)) throw rc;
1370 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1371 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1372 if (FAILED(rc)) throw rc;
1373 /* We search for the first host network interface which
1374 * is usable for bridged networking */
1375 for (size_t i=0; i < nwInterfaces.size(); ++i)
1376 {
1377 HostNetworkInterfaceType_T itype;
1378 rc = nwInterfaces[i]->COMGETTER(InterfaceType)(&itype);
1379 if (FAILED(rc)) throw rc;
1380 if (itype == HostNetworkInterfaceType_Bridged)
1381 {
1382 Bstr name;
1383 rc = nwInterfaces[i]->COMGETTER(Name)(name.asOutParam());
1384 if (FAILED(rc)) throw rc;
1385 /* Set the interface name to attach to */
1386 pNetworkAdapter->COMSETTER(HostInterface)(name);
1387 if (FAILED(rc)) throw rc;
1388 break;
1389 }
1390 }
1391 }
1392 /* Next test for host only interfaces */
1393 else if (!pvsys->strExtraConfig.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1394 {
1395 /* Attach to the right interface */
1396 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1397 if (FAILED(rc)) throw rc;
1398 ComPtr<IHost> host;
1399 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1400 if (FAILED(rc)) throw rc;
1401 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1402 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1403 if (FAILED(rc)) throw rc;
1404 /* We search for the first host network interface which
1405 * is usable for host only networking */
1406 for (size_t i=0; i < nwInterfaces.size(); ++i)
1407 {
1408 HostNetworkInterfaceType_T itype;
1409 rc = nwInterfaces[i]->COMGETTER(InterfaceType)(&itype);
1410 if (FAILED(rc)) throw rc;
1411 if (itype == HostNetworkInterfaceType_HostOnly)
1412 {
1413 Bstr name;
1414 rc = nwInterfaces[i]->COMGETTER(Name)(name.asOutParam());
1415 if (FAILED(rc)) throw rc;
1416 /* Set the interface name to attach to */
1417 pNetworkAdapter->COMSETTER(HostInterface)(name);
1418 if (FAILED(rc)) throw rc;
1419 break;
1420 }
1421 }
1422 }
1423 }
1424 }
1425
1426 /* Floppy drive */
1427 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1428 // Floppy support is enabled if there's at least one such entry; to disable floppy support,
1429 // the type of the floppy item would have been changed to "ignore"
1430 bool fFloppyEnabled = vsdeFloppy.size() > 0;
1431 ComPtr<IFloppyDrive> floppyDrive;
1432 rc = pNewMachine->COMGETTER(FloppyDrive)(floppyDrive.asOutParam());
1433 if (FAILED(rc)) throw rc;
1434 rc = floppyDrive->COMSETTER(Enabled)(fFloppyEnabled);
1435 if (FAILED(rc)) throw rc;
1436
1437 /* CDROM drive */
1438 /* @todo: I can't disable the CDROM. So nothing to do for now */
1439 // std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsd->findByType(VirtualSystemDescriptionType_CDROM);
1440
1441 /* Hard disk controller IDE */
1442 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1443 if (vsdeHDCIDE.size() > 1)
1444 throw setError(VBOX_E_FILE_ERROR,
1445 tr("Too many IDE controllers in OVF; VirtualBox only supports one"));
1446 if (vsdeHDCIDE.size() == 1)
1447 {
1448 ComPtr<IStorageController> pController;
1449 rc = pNewMachine->GetStorageControllerByName(Bstr("IDE"), pController.asOutParam());
1450 if (FAILED(rc)) throw rc;
1451
1452 const char *pcszIDEType = vsdeHDCIDE.front()->strVbox.c_str();
1453 if (!strcmp(pcszIDEType, "PIIX3"))
1454 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1455 else if (!strcmp(pcszIDEType, "PIIX4"))
1456 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1457 else if (!strcmp(pcszIDEType, "ICH6"))
1458 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1459 else
1460 throw setError(VBOX_E_FILE_ERROR,
1461 tr("Invalid IDE controller type \"%s\""),
1462 pcszIDEType);
1463 if (FAILED(rc)) throw rc;
1464 }
1465#ifdef VBOX_WITH_AHCI
1466 /* Hard disk controller SATA */
1467 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1468 if (vsdeHDCSATA.size() > 1)
1469 throw setError(VBOX_E_FILE_ERROR,
1470 tr("Too many SATA controllers in OVF; VirtualBox only supports one"));
1471 if (vsdeHDCSATA.size() > 0)
1472 {
1473 ComPtr<IStorageController> pController;
1474 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVbox;
1475 if (hdcVBox == "AHCI")
1476 {
1477 rc = pNewMachine->AddStorageController(Bstr("SATA"), StorageBus_SATA, pController.asOutParam());
1478 if (FAILED(rc)) throw rc;
1479 }
1480 else
1481 throw setError(VBOX_E_FILE_ERROR,
1482 tr("Invalid SATA controller type \"%s\""),
1483 hdcVBox.c_str());
1484 }
1485#endif /* VBOX_WITH_AHCI */
1486
1487#ifdef VBOX_WITH_LSILOGIC
1488 /* Hard disk controller SCSI */
1489 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1490 if (vsdeHDCSCSI.size() > 1)
1491 throw setError(VBOX_E_FILE_ERROR,
1492 tr("Too many SCSI controllers in OVF; VirtualBox only supports one"));
1493 if (vsdeHDCSCSI.size() > 0)
1494 {
1495 ComPtr<IStorageController> pController;
1496 StorageControllerType_T controllerType;
1497 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVbox;
1498 if (hdcVBox == "LsiLogic")
1499 controllerType = StorageControllerType_LsiLogic;
1500 else if (hdcVBox == "BusLogic")
1501 controllerType = StorageControllerType_BusLogic;
1502 else
1503 throw setError(VBOX_E_FILE_ERROR,
1504 tr("Invalid SCSI controller type \"%s\""),
1505 hdcVBox.c_str());
1506
1507 rc = pNewMachine->AddStorageController(Bstr("SCSI"), StorageBus_SCSI, pController.asOutParam());
1508 if (FAILED(rc)) throw rc;
1509 rc = pController->COMSETTER(ControllerType)(controllerType);
1510 if (FAILED(rc)) throw rc;
1511 }
1512#endif /* VBOX_WITH_LSILOGIC */
1513
1514 /* Now its time to register the machine before we add any hard disks */
1515 rc = mVirtualBox->RegisterMachine(pNewMachine);
1516 if (FAILED(rc)) throw rc;
1517
1518 Bstr newMachineId_;
1519 rc = pNewMachine->COMGETTER(Id)(newMachineId_.asOutParam());
1520 if (FAILED(rc)) throw rc;
1521 Guid newMachineId(newMachineId_);
1522
1523 // store new machine for roll-back in case of errors
1524 llMachinesRegistered.push_back(newMachineId);
1525
1526 /* Create the hard disks & connect them to the appropriate controllers. */
1527 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1528 if (avsdeHDs.size() > 0)
1529 {
1530 /* If in the next block an error occur we have to deregister
1531 the machine, so make an extra try/catch block. */
1532 ComPtr<IHardDisk> srcHdVBox;
1533 bool fSourceHdNeedsClosing = false;
1534
1535 try
1536 {
1537 /* In order to attach hard disks we need to open a session
1538 * for the new machine */
1539 rc = mVirtualBox->OpenSession(session, newMachineId_);
1540 if (FAILED(rc)) throw rc;
1541 fSessionOpen = true;
1542
1543 /* The disk image has to be on the same place as the OVF file. So
1544 * strip the filename out of the full file path. */
1545 Utf8Str strSrcDir(pTask->locInfo.strPath);
1546 strSrcDir.stripFilename();
1547
1548 /* Iterate over all given disk images */
1549 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1550 for (itHD = avsdeHDs.begin();
1551 itHD != avsdeHDs.end();
1552 ++itHD)
1553 {
1554 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1555
1556 const char *pcszDstFilePath = vsdeHD->strVbox.c_str();
1557 /* Check if the destination file exists already or the
1558 * destination path is empty. */
1559 if ( !(*pcszDstFilePath)
1560 || RTPathExists(pcszDstFilePath)
1561 )
1562 /* This isn't allowed */
1563 throw setError(VBOX_E_FILE_ERROR,
1564 tr("Destination file '%s' exists",
1565 pcszDstFilePath));
1566
1567 /* Find the disk from the OVF's disk list */
1568 DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1569 /* vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1570 in the virtual system's disks map under that ID and also in the global images map. */
1571 VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1572
1573 if ( itDiskImage == reader.m_mapDisks.end()
1574 || itVirtualDisk == vsysThis.mapVirtualDisks.end()
1575 )
1576 throw setError(E_FAIL,
1577 tr("Internal inconsistency looking up disk images."));
1578
1579 const DiskImage &di = itDiskImage->second;
1580 const VirtualDisk &vd = itVirtualDisk->second;
1581
1582 /* Make sure all target directories exists */
1583 rc = VirtualBox::ensureFilePathExists(pcszDstFilePath);
1584 if (FAILED(rc))
1585 throw rc;
1586
1587 // subprogress object for hard disk
1588 ComPtr<IProgress> pProgress2;
1589
1590 ComPtr<IHardDisk> dstHdVBox;
1591 /* If strHref is empty we have to create a new file */
1592 if (di.strHref.isEmpty())
1593 {
1594 /* Which format to use? */
1595 Bstr srcFormat = L"VDI";
1596 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1597 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
1598 srcFormat = L"VMDK";
1599 /* Create an empty hard disk */
1600 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(pcszDstFilePath), dstHdVBox.asOutParam());
1601 if (FAILED(rc)) throw rc;
1602
1603 /* Create a dynamic growing disk image with the given capacity */
1604 rc = dstHdVBox->CreateBaseStorage(di.iCapacity / _1M, HardDiskVariant_Standard, pProgress2.asOutParam());
1605 if (FAILED(rc)) throw rc;
1606
1607 /* Advance to the next operation */
1608 if (!pTask->progress.isNull())
1609 pTask->progress->setNextOperation(BstrFmt(tr("Creating virtual disk image '%s'"), pcszDstFilePath),
1610 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally
1611 }
1612 else
1613 {
1614 /* Construct the source file path */
1615 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1616 /* Check if the source file exists */
1617 if (!RTPathExists(strSrcFilePath.c_str()))
1618 /* This isn't allowed */
1619 throw setError(VBOX_E_FILE_ERROR,
1620 tr("Source virtual disk image file '%s' doesn't exist"),
1621 strSrcFilePath.c_str());
1622
1623 /* Clone the disk image (this is necessary cause the id has
1624 * to be recreated for the case the same hard disk is
1625 * attached already from a previous import) */
1626
1627 /* First open the existing disk image */
1628 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1629 AccessMode_ReadOnly,
1630 false, Bstr(""), false, Bstr(""),
1631 srcHdVBox.asOutParam());
1632 if (FAILED(rc)) throw rc;
1633 fSourceHdNeedsClosing = true;
1634
1635 /* We need the format description of the source disk image */
1636 Bstr srcFormat;
1637 rc = srcHdVBox->COMGETTER(Format)(srcFormat.asOutParam());
1638 if (FAILED(rc)) throw rc;
1639 /* Create a new hard disk interface for the destination disk image */
1640 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(pcszDstFilePath), dstHdVBox.asOutParam());
1641 if (FAILED(rc)) throw rc;
1642 /* Clone the source disk image */
1643 rc = srcHdVBox->CloneTo(dstHdVBox, HardDiskVariant_Standard, NULL, pProgress2.asOutParam());
1644 if (FAILED(rc)) throw rc;
1645
1646 /* Advance to the next operation */
1647 if (!pTask->progress.isNull())
1648 pTask->progress->setNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1649 vsdeHD->ulSizeMB); // operation's weight, as set up with the IProgress originally);
1650 }
1651
1652 // now wait for the background disk operation to complete; this throws HRESULTs on error
1653 waitForAsyncProgress(pTask->progress, pProgress2);
1654
1655 if (fSourceHdNeedsClosing)
1656 {
1657 rc = srcHdVBox->Close();
1658 if (FAILED(rc)) throw rc;
1659 fSourceHdNeedsClosing = false;
1660 }
1661
1662 llHardDisksCreated.push_back(dstHdVBox);
1663 /* Now use the new uuid to attach the disk image to our new machine */
1664 ComPtr<IMachine> sMachine;
1665 rc = session->COMGETTER(Machine)(sMachine.asOutParam());
1666 if (FAILED(rc)) throw rc;
1667 Bstr hdId;
1668 rc = dstHdVBox->COMGETTER(Id)(hdId.asOutParam());
1669 if (FAILED(rc)) throw rc;
1670
1671 /* For now we assume we have one controller of every type only */
1672 HardDiskController hdc = (*vsysThis.mapControllers.find(vd.idController)).second;
1673
1674 // this is for rollback later
1675 MyHardDiskAttachment mhda;
1676 mhda.uuid = newMachineId;
1677 mhda.pMachine = pNewMachine;
1678
1679 switch (hdc.system)
1680 {
1681 case HardDiskController::IDE:
1682 // For the IDE bus, the channel parameter can be either 0 or 1, to specify the primary
1683 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
1684 // the device number can be either 0 or 1, to specify the master or the slave device,
1685 // respectively. For the secondary IDE controller, the device number is always 1 because
1686 // the master device is reserved for the CD-ROM drive.
1687 mhda.controllerType = Bstr("IDE");
1688 switch (vd.ulAddressOnParent)
1689 {
1690 case 0: // interpret this as primary master
1691 mhda.lChannel = (long)0;
1692 mhda.lDevice = (long)0;
1693 break;
1694
1695 case 1: // interpret this as primary slave
1696 mhda.lChannel = (long)0;
1697 mhda.lDevice = (long)1;
1698 break;
1699
1700 case 2: // interpret this as secondary slave
1701 mhda.lChannel = (long)1;
1702 mhda.lDevice = (long)1;
1703 break;
1704
1705 default:
1706 throw setError(VBOX_E_NOT_SUPPORTED,
1707 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"), vd.ulAddressOnParent);
1708 break;
1709 }
1710 break;
1711
1712 case HardDiskController::SATA:
1713 mhda.controllerType = Bstr("SATA");
1714 mhda.lChannel = (long)vd.ulAddressOnParent;
1715 mhda.lDevice = (long)0;
1716 break;
1717
1718 case HardDiskController::SCSI:
1719 mhda.controllerType = Bstr("SCSI");
1720 mhda.lChannel = (long)vd.ulAddressOnParent;
1721 mhda.lDevice = (long)0;
1722 break;
1723
1724 default: break;
1725 }
1726
1727 Log(("Attaching disk %s to channel %d on device %d\n", pcszDstFilePath, mhda.lChannel, mhda.lDevice));
1728
1729 rc = sMachine->AttachHardDisk(hdId,
1730 mhda.controllerType,
1731 mhda.lChannel,
1732 mhda.lDevice);
1733 if (FAILED(rc)) throw rc;
1734
1735 llHardDiskAttachments.push_back(mhda);
1736
1737 rc = sMachine->SaveSettings();
1738 if (FAILED(rc)) throw rc;
1739 } // end for (itHD = avsdeHDs.begin();
1740
1741 // only now that we're done with all disks, close the session
1742 rc = session->Close();
1743 if (FAILED(rc)) throw rc;
1744 fSessionOpen = false;
1745 }
1746 catch(HRESULT /* aRC */)
1747 {
1748 if (fSourceHdNeedsClosing)
1749 srcHdVBox->Close();
1750
1751 if (fSessionOpen)
1752 session->Close();
1753
1754 throw;
1755 }
1756 }
1757 }
1758 catch(HRESULT aRC)
1759 {
1760 rc = aRC;
1761 }
1762
1763 if (FAILED(rc))
1764 break;
1765
1766 } // for (it = pAppliance->m->llVirtualSystems.begin(),
1767
1768 if (FAILED(rc))
1769 {
1770 // with _whatever_ error we've had, do a complete roll-back of
1771 // machines and disks we've created; unfortunately this is
1772 // not so trivially done...
1773
1774 HRESULT rc2;
1775 // detach all hard disks from all machines we created
1776 list<MyHardDiskAttachment>::iterator itM;
1777 for (itM = llHardDiskAttachments.begin();
1778 itM != llHardDiskAttachments.end();
1779 ++itM)
1780 {
1781 const MyHardDiskAttachment &mhda = *itM;
1782 rc2 = mVirtualBox->OpenSession(session, Bstr(mhda.uuid));
1783 if (SUCCEEDED(rc2))
1784 {
1785 ComPtr<IMachine> sMachine;
1786 rc2 = session->COMGETTER(Machine)(sMachine.asOutParam());
1787 if (SUCCEEDED(rc2))
1788 {
1789 rc2 = sMachine->DetachHardDisk(Bstr(mhda.controllerType), mhda.lChannel, mhda.lDevice);
1790 rc2 = sMachine->SaveSettings();
1791 }
1792 session->Close();
1793 }
1794 }
1795
1796 // now clean up all hard disks we created
1797 list< ComPtr<IHardDisk> >::iterator itHD;
1798 for (itHD = llHardDisksCreated.begin();
1799 itHD != llHardDisksCreated.end();
1800 ++itHD)
1801 {
1802 ComPtr<IHardDisk> pDisk = *itHD;
1803 ComPtr<IProgress> pProgress;
1804 rc2 = pDisk->DeleteStorage(pProgress.asOutParam());
1805 rc2 = pProgress->WaitForCompletion(-1);
1806 }
1807
1808 // finally, deregister and remove all machines
1809 list<Guid>::iterator itID;
1810 for (itID = llMachinesRegistered.begin();
1811 itID != llMachinesRegistered.end();
1812 ++itID)
1813 {
1814 const Guid &guid = *itID;
1815 ComPtr<IMachine> failedMachine;
1816 rc2 = mVirtualBox->UnregisterMachine(guid.toUtf16(), failedMachine.asOutParam());
1817 if (SUCCEEDED(rc2))
1818 rc2 = failedMachine->DeleteSettings();
1819 }
1820 }
1821
1822 pTask->rc = rc;
1823
1824 if (!pTask->progress.isNull())
1825 pTask->progress->notifyComplete(rc);
1826
1827 LogFlowFunc(("rc=%Rhrc\n", rc));
1828 LogFlowFuncLeave();
1829
1830 return VINF_SUCCESS;
1831}
1832
1833int Appliance::importS3(TaskImportOVF *pTask)
1834{
1835 LogFlowFuncEnter();
1836 LogFlowFunc(("Appliance %p\n", this));
1837
1838 AutoCaller autoCaller(this);
1839 CheckComRCReturnRC(autoCaller.rc());
1840
1841 AutoWriteLock appLock(this);
1842
1843 int vrc = VINF_SUCCESS;
1844 RTS3 hS3 = NIL_RTS3;
1845 char szOSTmpDir[RTPATH_MAX];
1846 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
1847 /* The template for the temporary directory created below */
1848 char *pszTmpDir;
1849 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
1850 list< pair<Utf8Str, ULONG> > filesList;
1851
1852 HRESULT rc = S_OK;
1853 try
1854 {
1855 /* Extract the bucket */
1856 Utf8Str tmpPath = pTask->locInfo.strPath;
1857 Utf8Str bucket;
1858 parseBucket(tmpPath, bucket);
1859
1860 /* We need a temporary directory which we can put the all disk images
1861 * in */
1862 vrc = RTDirCreateTemp(pszTmpDir);
1863 if (RT_FAILURE(rc))
1864 throw setError(VBOX_E_FILE_ERROR,
1865 tr("Cannot create temporary directory '%s'"), pszTmpDir);
1866
1867 /* Add every disks of every virtual system to an internal list */
1868 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1869 for (it = m->virtualSystemDescriptions.begin();
1870 it != m->virtualSystemDescriptions.end();
1871 ++it)
1872 {
1873 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1874 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1875 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1876 for (itH = avsdeHDs.begin();
1877 itH != avsdeHDs.end();
1878 ++itH)
1879 {
1880 const Utf8Str &strTargetFile = (*itH)->strOvf;
1881 if (!strTargetFile.isEmpty())
1882 {
1883 /* The temporary name of the target disk file */
1884 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile));
1885 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
1886 }
1887 }
1888 }
1889
1890 /* Next we have to download the disk images */
1891 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
1892 if(RT_FAILURE(vrc))
1893 throw setError(VBOX_E_IPRT_ERROR,
1894 tr("Cannot create S3 service handler"));
1895 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
1896
1897 /* Download all files */
1898 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1899 {
1900 const pair<Utf8Str, ULONG> &s = (*it1);
1901 const Utf8Str &strSrcFile = s.first;
1902 /* Construct the source file name */
1903 char *pszFilename = RTPathFilename(strSrcFile.c_str());
1904 /* Advance to the next operation */
1905 if (!pTask->progress.isNull())
1906 pTask->progress->setNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
1907
1908 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
1909 if (RT_FAILURE(vrc))
1910 {
1911 if(vrc == VERR_S3_CANCELED)
1912 throw S_OK; /* todo: !!!!!!!!!!!!! */
1913 else if(vrc == VERR_S3_ACCESS_DENIED)
1914 throw setError(E_ACCESSDENIED,
1915 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);
1916 else if(vrc == VERR_S3_NOT_FOUND)
1917 throw setError(VBOX_E_FILE_ERROR,
1918 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
1919 else
1920 throw setError(VBOX_E_IPRT_ERROR,
1921 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1922 }
1923 }
1924
1925 /* Provide a OVF file (haven't to exist) so the import routine can
1926 * figure out where the disk images/manifest file are located. */
1927 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath));
1928 /* Now check if there is an manifest file. This is optional. */
1929 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
1930 char *pszFilename = RTPathFilename(strManifestFile.c_str());
1931 if (!pTask->progress.isNull())
1932 pTask->progress->setNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
1933
1934 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
1935 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
1936 if (RT_SUCCESS(vrc))
1937 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
1938 else if (RT_FAILURE(vrc))
1939 {
1940 if(vrc == VERR_S3_CANCELED)
1941 throw S_OK; /* todo: !!!!!!!!!!!!! */
1942 else if(vrc == VERR_S3_NOT_FOUND)
1943 vrc = VINF_SUCCESS; /* Not found is ok */
1944 else if(vrc == VERR_S3_ACCESS_DENIED)
1945 throw setError(E_ACCESSDENIED,
1946 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);
1947 else
1948 throw setError(VBOX_E_IPRT_ERROR,
1949 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
1950 }
1951
1952 /* Close the connection early */
1953 RTS3Destroy(hS3);
1954 hS3 = NIL_RTS3;
1955
1956 if (!pTask->progress.isNull())
1957 pTask->progress->setNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightPerOperation);
1958
1959 ComObjPtr<Progress> progress;
1960 /* Import the whole temporary OVF & the disk images */
1961 LocationInfo li;
1962 li.strPath = strTmpOvf;
1963 rc = importImpl(li, progress);
1964 if (FAILED(rc)) throw rc;
1965
1966 /* Unlock the appliance for the fs import thread */
1967 appLock.unlock();
1968 /* Wait until the import is done, but report the progress back to the
1969 caller */
1970 ComPtr<IProgress> progressInt(progress);
1971 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
1972
1973 /* Again lock the appliance for the next steps */
1974 appLock.lock();
1975 }
1976 catch(HRESULT aRC)
1977 {
1978 rc = aRC;
1979 }
1980 /* Cleanup */
1981 RTS3Destroy(hS3);
1982 /* Delete all files which where temporary created */
1983 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
1984 {
1985 const char *pszFilePath = (*it1).first.c_str();
1986 if (RTPathExists(pszFilePath))
1987 {
1988 vrc = RTFileDelete(pszFilePath);
1989 if(RT_FAILURE(vrc))
1990 rc = setError(VBOX_E_FILE_ERROR,
1991 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
1992 }
1993 }
1994 /* Delete the temporary directory */
1995 if (RTPathExists(pszTmpDir))
1996 {
1997 vrc = RTDirRemove(pszTmpDir);
1998 if(RT_FAILURE(vrc))
1999 rc = setError(VBOX_E_FILE_ERROR,
2000 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2001 }
2002 if (pszTmpDir)
2003 RTStrFree(pszTmpDir);
2004
2005 pTask->rc = rc;
2006
2007 if (!pTask->progress.isNull())
2008 pTask->progress->notifyComplete(rc);
2009
2010 LogFlowFunc(("rc=%Rhrc\n", rc));
2011 LogFlowFuncLeave();
2012
2013 return VINF_SUCCESS;
2014}
2015
2016HRESULT Appliance::writeImpl(int aFormat, const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
2017{
2018 HRESULT rc = S_OK;
2019 try
2020 {
2021 /* Initialize our worker task */
2022 std::auto_ptr<TaskExportOVF> task(new TaskExportOVF(this));
2023 /* What should the task do */
2024 task->taskType = TaskExportOVF::Write;
2025 /* The OVF version to write */
2026 task->enFormat = (TaskExportOVF::OVFFormat)aFormat;
2027 /* Copy the current location info to the task */
2028 task->locInfo = aLocInfo;
2029
2030 Bstr progressDesc = BstrFmt(tr("Export appliance '%s'"),
2031 task->locInfo.strPath.c_str());
2032
2033 /* todo: This progress init stuff should be done a little bit more generic */
2034 if (task->locInfo.storageType == VFSType_File)
2035 rc = setUpProgressFS(aProgress, progressDesc);
2036 else
2037 rc = setUpProgressWriteS3(aProgress, progressDesc);
2038
2039 task->progress = aProgress;
2040
2041 rc = task->startThread();
2042 CheckComRCThrowRC(rc);
2043
2044 /* Don't destruct on success */
2045 task.release();
2046 }
2047 catch (HRESULT aRC)
2048 {
2049 rc = aRC;
2050 }
2051
2052 return rc;
2053}
2054
2055DECLCALLBACK(int) Appliance::taskThreadWriteOVF(RTTHREAD /* aThread */, void *pvUser)
2056{
2057 std::auto_ptr<TaskExportOVF> task(static_cast<TaskExportOVF*>(pvUser));
2058 AssertReturn(task.get(), VERR_GENERAL_FAILURE);
2059
2060 Appliance *pAppliance = task->pAppliance;
2061
2062 LogFlowFuncEnter();
2063 LogFlowFunc(("Appliance %p\n", pAppliance));
2064
2065 HRESULT rc = S_OK;
2066
2067 switch(task->taskType)
2068 {
2069 case TaskExportOVF::Write:
2070 {
2071 if (task->locInfo.storageType == VFSType_File)
2072 rc = pAppliance->writeFS(task.get());
2073 else if (task->locInfo.storageType == VFSType_S3)
2074 rc = pAppliance->writeS3(task.get());
2075 break;
2076 }
2077 }
2078
2079 LogFlowFunc(("rc=%Rhrc\n", rc));
2080 LogFlowFuncLeave();
2081
2082 return VINF_SUCCESS;
2083}
2084
2085int Appliance::TaskExportOVF::startThread()
2086{
2087 int vrc = RTThreadCreate(NULL, Appliance::taskThreadWriteOVF, this,
2088 0, RTTHREADTYPE_MAIN_HEAVY_WORKER, 0,
2089 "Appliance::Task");
2090
2091 ComAssertMsgRCRet(vrc,
2092 ("Could not create taskThreadWriteOVF (%Rrc)\n", vrc), E_FAIL);
2093
2094 return S_OK;
2095}
2096
2097int Appliance::writeFS(TaskExportOVF *pTask)
2098{
2099 LogFlowFuncEnter();
2100 LogFlowFunc(("Appliance %p\n", this));
2101
2102 AutoCaller autoCaller(this);
2103 CheckComRCReturnRC(autoCaller.rc());
2104
2105 AutoWriteLock appLock(this);
2106
2107 HRESULT rc = S_OK;
2108
2109 try
2110 {
2111 xml::Document doc;
2112 xml::ElementNode *pelmRoot = doc.createRootElement("Envelope");
2113
2114 pelmRoot->setAttribute("ovf:version", (pTask->enFormat == TaskExportOVF::OVF_1_0) ? "1.0" : "0.9");
2115 pelmRoot->setAttribute("xml:lang", "en-US");
2116
2117 Utf8Str strNamespace = (pTask->enFormat == TaskExportOVF::OVF_0_9)
2118 ? "http://www.vmware.com/schema/ovf/1/envelope" // 0.9
2119 : "http://schemas.dmtf.org/ovf/envelope/1"; // 1.0
2120 pelmRoot->setAttribute("xmlns", strNamespace);
2121 pelmRoot->setAttribute("xmlns:ovf", strNamespace);
2122
2123// pelmRoot->setAttribute("xmlns:ovfstr", "http://schema.dmtf.org/ovf/strings/1");
2124 pelmRoot->setAttribute("xmlns:rasd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData");
2125 pelmRoot->setAttribute("xmlns:vssd", "http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData");
2126 pelmRoot->setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
2127// pelmRoot->setAttribute("xsi:schemaLocation", "http://schemas.dmtf.org/ovf/envelope/1 ../ovf-envelope.xsd");
2128
2129 // <Envelope>/<References>
2130 xml::ElementNode *pelmReferences = pelmRoot->createChild("References"); // 0.9 and 1.0
2131
2132 /* <Envelope>/<DiskSection>:
2133 <DiskSection>
2134 <Info>List of the virtual disks used in the package</Info>
2135 <Disk ovf:capacity="4294967296" ovf:diskId="lamp" ovf:format="http://www.vmware.com/specifications/vmdk.html#compressed" ovf:populatedSize="1924967692"/>
2136 </DiskSection> */
2137 xml::ElementNode *pelmDiskSection;
2138 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2139 {
2140 // <Section xsi:type="ovf:DiskSection_Type">
2141 pelmDiskSection = pelmRoot->createChild("Section");
2142 pelmDiskSection->setAttribute("xsi:type", "ovf:DiskSection_Type");
2143 }
2144 else
2145 pelmDiskSection = pelmRoot->createChild("DiskSection");
2146
2147 xml::ElementNode *pelmDiskSectionInfo = pelmDiskSection->createChild("Info");
2148 pelmDiskSectionInfo->addContent("List of the virtual disks used in the package");
2149 // for now, set up a map so we have a list of unique disk names (to make
2150 // sure the same disk name is only added once)
2151 map<Utf8Str, const VirtualSystemDescriptionEntry*> mapDisks;
2152
2153 /* <Envelope>/<NetworkSection>:
2154 <NetworkSection>
2155 <Info>Logical networks used in the package</Info>
2156 <Network ovf:name="VM Network">
2157 <Description>The network that the LAMP Service will be available on</Description>
2158 </Network>
2159 </NetworkSection> */
2160 xml::ElementNode *pelmNetworkSection;
2161 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2162 {
2163 // <Section xsi:type="ovf:NetworkSection_Type">
2164 pelmNetworkSection = pelmRoot->createChild("Section");
2165 pelmNetworkSection->setAttribute("xsi:type", "ovf:NetworkSection_Type");
2166 }
2167 else
2168 pelmNetworkSection = pelmRoot->createChild("NetworkSection");
2169
2170 xml::ElementNode *pelmNetworkSectionInfo = pelmNetworkSection->createChild("Info");
2171 pelmNetworkSectionInfo->addContent("Logical networks used in the package");
2172 // for now, set up a map so we have a list of unique network names (to make
2173 // sure the same network name is only added once)
2174 map<Utf8Str, bool> mapNetworks;
2175 // we fill this later below when we iterate over the networks
2176
2177 // and here come the virtual systems:
2178
2179 // write a collection if we have more than one virtual system _and_ we're
2180 // writing OVF 1.0; otherwise fail since ovftool can't import more than
2181 // one machine, it seems
2182 xml::ElementNode *pelmToAddVirtualSystemsTo;
2183 if (m->virtualSystemDescriptions.size() > 1)
2184 {
2185 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2186 throw setError(VBOX_E_FILE_ERROR,
2187 tr("Cannot export more than one virtual system with OVF 0.9, use OVF 1.0"));
2188
2189 pelmToAddVirtualSystemsTo = pelmRoot->createChild("VirtualSystemCollection");
2190 /* xml::AttributeNode *pattrVirtualSystemCollectionId = */ pelmToAddVirtualSystemsTo->setAttribute("ovf:name", "ExportedVirtualBoxMachines"); // whatever
2191 }
2192 else
2193 pelmToAddVirtualSystemsTo = pelmRoot; // add virtual system directly under root element
2194
2195 uint32_t cDisks = 0;
2196
2197 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2198 /* Iterate through all virtual systems of that appliance */
2199 for (it = m->virtualSystemDescriptions.begin();
2200 it != m->virtualSystemDescriptions.end();
2201 ++it)
2202 {
2203 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2204
2205 xml::ElementNode *pelmVirtualSystem;
2206 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2207 {
2208 // <Section xsi:type="ovf:NetworkSection_Type">
2209 pelmVirtualSystem = pelmToAddVirtualSystemsTo->createChild("Content");
2210 pelmVirtualSystem->setAttribute("xsi:type", "ovf:VirtualSystem_Type");
2211 }
2212 else
2213 pelmVirtualSystem = pelmToAddVirtualSystemsTo->createChild("VirtualSystem");
2214
2215 /*xml::ElementNode *pelmVirtualSystemInfo =*/ pelmVirtualSystem->createChild("Info")->addContent("A virtual machine");
2216
2217 std::list<VirtualSystemDescriptionEntry*> llName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2218 if (llName.size() != 1)
2219 throw setError(VBOX_E_NOT_SUPPORTED,
2220 tr("Missing VM name"));
2221 Utf8Str &strVMName = llName.front()->strVbox;
2222 pelmVirtualSystem->setAttribute("ovf:id", strVMName);
2223
2224 // product info
2225 std::list<VirtualSystemDescriptionEntry*> llProduct = vsdescThis->findByType(VirtualSystemDescriptionType_Product);
2226 std::list<VirtualSystemDescriptionEntry*> llProductUrl = vsdescThis->findByType(VirtualSystemDescriptionType_ProductUrl);
2227 std::list<VirtualSystemDescriptionEntry*> llVendor = vsdescThis->findByType(VirtualSystemDescriptionType_Vendor);
2228 std::list<VirtualSystemDescriptionEntry*> llVendorUrl = vsdescThis->findByType(VirtualSystemDescriptionType_VendorUrl);
2229 std::list<VirtualSystemDescriptionEntry*> llVersion = vsdescThis->findByType(VirtualSystemDescriptionType_Version);
2230 bool fProduct = llProduct.size() && !llProduct.front()->strVbox.isEmpty();
2231 bool fProductUrl = llProductUrl.size() && !llProductUrl.front()->strVbox.isEmpty();
2232 bool fVendor = llVendor.size() && !llVendor.front()->strVbox.isEmpty();
2233 bool fVendorUrl = llVendorUrl.size() && !llVendorUrl.front()->strVbox.isEmpty();
2234 bool fVersion = llVersion.size() && !llVersion.front()->strVbox.isEmpty();
2235 if (fProduct ||
2236 fProductUrl ||
2237 fVersion ||
2238 fVendorUrl ||
2239 fVersion)
2240 {
2241 /* <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
2242 <Info>Meta-information about the installed software</Info>
2243 <Product>VAtest</Product>
2244 <Vendor>SUN Microsystems</Vendor>
2245 <Version>10.0</Version>
2246 <ProductUrl>http://blogs.sun.com/VirtualGuru</ProductUrl>
2247 <VendorUrl>http://www.sun.com</VendorUrl>
2248 </Section> */
2249 xml::ElementNode *pelmAnnotationSection;
2250 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2251 {
2252 // <Section ovf:required="false" xsi:type="ovf:ProductSection_Type">
2253 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
2254 pelmAnnotationSection->setAttribute("xsi:type", "ovf:ProductSection_Type");
2255 }
2256 else
2257 pelmAnnotationSection = pelmVirtualSystem->createChild("ProductSection");
2258
2259 pelmAnnotationSection->createChild("Info")->addContent("Meta-information about the installed software");
2260 if (fProduct)
2261 pelmAnnotationSection->createChild("Product")->addContent(llProduct.front()->strVbox);
2262 if (fVendor)
2263 pelmAnnotationSection->createChild("Vendor")->addContent(llVendor.front()->strVbox);
2264 if (fVersion)
2265 pelmAnnotationSection->createChild("Version")->addContent(llVersion.front()->strVbox);
2266 if (fProductUrl)
2267 pelmAnnotationSection->createChild("ProductUrl")->addContent(llProductUrl.front()->strVbox);
2268 if (fVendorUrl)
2269 pelmAnnotationSection->createChild("VendorUrl")->addContent(llVendorUrl.front()->strVbox);
2270 }
2271
2272 // description
2273 std::list<VirtualSystemDescriptionEntry*> llDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
2274 if (llDescription.size() &&
2275 !llDescription.front()->strVbox.isEmpty())
2276 {
2277 /* <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
2278 <Info>A human-readable annotation</Info>
2279 <Annotation>Plan 9</Annotation>
2280 </Section> */
2281 xml::ElementNode *pelmAnnotationSection;
2282 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2283 {
2284 // <Section ovf:required="false" xsi:type="ovf:AnnotationSection_Type">
2285 pelmAnnotationSection = pelmVirtualSystem->createChild("Section");
2286 pelmAnnotationSection->setAttribute("xsi:type", "ovf:AnnotationSection_Type");
2287 }
2288 else
2289 pelmAnnotationSection = pelmVirtualSystem->createChild("AnnotationSection");
2290
2291 pelmAnnotationSection->createChild("Info")->addContent("A human-readable annotation");
2292 pelmAnnotationSection->createChild("Annotation")->addContent(llDescription.front()->strVbox);
2293 }
2294
2295 // license
2296 std::list<VirtualSystemDescriptionEntry*> llLicense = vsdescThis->findByType(VirtualSystemDescriptionType_License);
2297 if (llLicense.size() &&
2298 !llLicense.front()->strVbox.isEmpty())
2299 {
2300 /* <EulaSection>
2301 <Info ovf:msgid="6">License agreement for the Virtual System.</Info>
2302 <License ovf:msgid="1">License terms can go in here.</License>
2303 </EulaSection> */
2304 xml::ElementNode *pelmEulaSection;
2305 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2306 {
2307 pelmEulaSection = pelmVirtualSystem->createChild("Section");
2308 pelmEulaSection->setAttribute("xsi:type", "ovf:EulaSection_Type");
2309 }
2310 else
2311 pelmEulaSection = pelmVirtualSystem->createChild("EulaSection");
2312
2313 pelmEulaSection->createChild("Info")->addContent("License agreement for the virtual system");
2314 pelmEulaSection->createChild("License")->addContent(llLicense.front()->strVbox);
2315 }
2316
2317 // operating system
2318 std::list<VirtualSystemDescriptionEntry*> llOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
2319 if (llOS.size() != 1)
2320 throw setError(VBOX_E_NOT_SUPPORTED,
2321 tr("Missing OS type"));
2322 /* <OperatingSystemSection ovf:id="82">
2323 <Info>Guest Operating System</Info>
2324 <Description>Linux 2.6.x</Description>
2325 </OperatingSystemSection> */
2326 xml::ElementNode *pelmOperatingSystemSection;
2327 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2328 {
2329 pelmOperatingSystemSection = pelmVirtualSystem->createChild("Section");
2330 pelmOperatingSystemSection->setAttribute("xsi:type", "ovf:OperatingSystemSection_Type");
2331 }
2332 else
2333 pelmOperatingSystemSection = pelmVirtualSystem->createChild("OperatingSystemSection");
2334
2335 pelmOperatingSystemSection->setAttribute("ovf:id", llOS.front()->strOvf);
2336 pelmOperatingSystemSection->createChild("Info")->addContent("The kind of installed guest operating system");
2337 Utf8Str strOSDesc;
2338 convertCIMOSType2VBoxOSType(strOSDesc, (CIMOSType_T)llOS.front()->strOvf.toInt32(), "");
2339 pelmOperatingSystemSection->createChild("Description")->addContent(strOSDesc);
2340
2341 // <VirtualHardwareSection ovf:id="hw1" ovf:transport="iso">
2342 xml::ElementNode *pelmVirtualHardwareSection;
2343 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2344 {
2345 // <Section xsi:type="ovf:VirtualHardwareSection_Type">
2346 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("Section");
2347 pelmVirtualHardwareSection->setAttribute("xsi:type", "ovf:VirtualHardwareSection_Type");
2348 }
2349 else
2350 pelmVirtualHardwareSection = pelmVirtualSystem->createChild("VirtualHardwareSection");
2351
2352 pelmVirtualHardwareSection->createChild("Info")->addContent("Virtual hardware requirements for a virtual machine");
2353
2354 /* <System>
2355 <vssd:Description>Description of the virtual hardware section.</vssd:Description>
2356 <vssd:ElementName>vmware</vssd:ElementName>
2357 <vssd:InstanceID>1</vssd:InstanceID>
2358 <vssd:VirtualSystemIdentifier>MyLampService</vssd:VirtualSystemIdentifier>
2359 <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
2360 </System> */
2361 xml::ElementNode *pelmSystem = pelmVirtualHardwareSection->createChild("System");
2362
2363 pelmSystem->createChild("vssd:ElementName")->addContent("Virtual Hardware Family"); // required OVF 1.0
2364
2365 // <vssd:InstanceId>0</vssd:InstanceId>
2366 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2367 pelmSystem->createChild("vssd:InstanceId")->addContent("0");
2368 else // capitalization changed...
2369 pelmSystem->createChild("vssd:InstanceID")->addContent("0");
2370
2371 // <vssd:VirtualSystemIdentifier>VAtest</vssd:VirtualSystemIdentifier>
2372 pelmSystem->createChild("vssd:VirtualSystemIdentifier")->addContent(strVMName);
2373 // <vssd:VirtualSystemType>vmx-4</vssd:VirtualSystemType>
2374 const char *pcszHardware = "virtualbox-2.2";
2375 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2376 // pretend to be vmware compatible then
2377 pcszHardware = "vmx-6";
2378 pelmSystem->createChild("vssd:VirtualSystemType")->addContent(pcszHardware);
2379
2380 // loop thru all description entries twice; once to write out all
2381 // devices _except_ disk images, and a second time to assign the
2382 // disk images; this is because disk images need to reference
2383 // IDE controllers, and we can't know their instance IDs without
2384 // assigning them first
2385
2386 uint32_t idIDEController = 0;
2387 int32_t lIDEControllerIndex = 0;
2388 uint32_t idSATAController = 0;
2389 int32_t lSATAControllerIndex = 0;
2390 uint32_t idSCSIController = 0;
2391 int32_t lSCSIControllerIndex = 0;
2392
2393 uint32_t ulInstanceID = 1;
2394
2395 for (size_t uLoop = 1;
2396 uLoop <= 2;
2397 ++uLoop)
2398 {
2399 int32_t lIndexThis = 0;
2400 list<VirtualSystemDescriptionEntry>::const_iterator itD;
2401 for (itD = vsdescThis->m->llDescriptions.begin();
2402 itD != vsdescThis->m->llDescriptions.end();
2403 ++itD, ++lIndexThis)
2404 {
2405 const VirtualSystemDescriptionEntry &desc = *itD;
2406
2407 OVFResourceType_T type = (OVFResourceType_T)0; // if this becomes != 0 then we do stuff
2408 Utf8Str strResourceSubType;
2409
2410 Utf8Str strDescription; // results in <rasd:Description>...</rasd:Description> block
2411 Utf8Str strCaption; // results in <rasd:Caption>...</rasd:Caption> block
2412
2413 uint32_t ulParent = 0;
2414
2415 int32_t lVirtualQuantity = -1;
2416 Utf8Str strAllocationUnits;
2417
2418 int32_t lAddress = -1;
2419 int32_t lBusNumber = -1;
2420 int32_t lAddressOnParent = -1;
2421
2422 int32_t lAutomaticAllocation = -1; // 0 means "false", 1 means "true"
2423 Utf8Str strConnection; // results in <rasd:Connection>...</rasd:Connection> block
2424 Utf8Str strHostResource;
2425
2426 uint64_t uTemp;
2427
2428 switch (desc.type)
2429 {
2430 case VirtualSystemDescriptionType_CPU:
2431 /* <Item>
2432 <rasd:Caption>1 virtual CPU</rasd:Caption>
2433 <rasd:Description>Number of virtual CPUs</rasd:Description>
2434 <rasd:ElementName>virtual CPU</rasd:ElementName>
2435 <rasd:InstanceID>1</rasd:InstanceID>
2436 <rasd:ResourceType>3</rasd:ResourceType>
2437 <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2438 </Item> */
2439 if (uLoop == 1)
2440 {
2441 strDescription = "Number of virtual CPUs";
2442 type = OVFResourceType_Processor; // 3
2443 desc.strVbox.toInt(uTemp);
2444 lVirtualQuantity = uTemp;
2445 strCaption = Utf8StrFmt("%d virtual CPU", lVirtualQuantity); // without this ovftool won't eat the item
2446 }
2447 break;
2448
2449 case VirtualSystemDescriptionType_Memory:
2450 /* <Item>
2451 <rasd:AllocationUnits>MegaBytes</rasd:AllocationUnits>
2452 <rasd:Caption>256 MB of memory</rasd:Caption>
2453 <rasd:Description>Memory Size</rasd:Description>
2454 <rasd:ElementName>Memory</rasd:ElementName>
2455 <rasd:InstanceID>2</rasd:InstanceID>
2456 <rasd:ResourceType>4</rasd:ResourceType>
2457 <rasd:VirtualQuantity>256</rasd:VirtualQuantity>
2458 </Item> */
2459 if (uLoop == 1)
2460 {
2461 strDescription = "Memory Size";
2462 type = OVFResourceType_Memory; // 4
2463 desc.strVbox.toInt(uTemp);
2464 lVirtualQuantity = (int32_t)(uTemp / _1M);
2465 strAllocationUnits = "MegaBytes";
2466 strCaption = Utf8StrFmt("%d MB of memory", lVirtualQuantity); // without this ovftool won't eat the item
2467 }
2468 break;
2469
2470 case VirtualSystemDescriptionType_HardDiskControllerIDE:
2471 /* <Item>
2472 <rasd:Caption>ideController1</rasd:Caption>
2473 <rasd:Description>IDE Controller</rasd:Description>
2474 <rasd:InstanceId>5</rasd:InstanceId>
2475 <rasd:ResourceType>5</rasd:ResourceType>
2476 <rasd:Address>1</rasd:Address>
2477 <rasd:BusNumber>1</rasd:BusNumber>
2478 </Item> */
2479 if (uLoop == 1)
2480 {
2481 strDescription = "IDE Controller";
2482 strCaption = "ideController0";
2483 type = OVFResourceType_IDEController; // 5
2484 strResourceSubType = desc.strVbox;
2485 // it seems that OVFTool always writes these two, and since we can only
2486 // have one IDE controller, we'll use this as well
2487 lAddress = 1;
2488 lBusNumber = 1;
2489
2490 // remember this ID
2491 idIDEController = ulInstanceID;
2492 lIDEControllerIndex = lIndexThis;
2493 }
2494 break;
2495
2496 case VirtualSystemDescriptionType_HardDiskControllerSATA:
2497 /* <Item>
2498 <rasd:Caption>sataController0</rasd:Caption>
2499 <rasd:Description>SATA Controller</rasd:Description>
2500 <rasd:InstanceId>4</rasd:InstanceId>
2501 <rasd:ResourceType>20</rasd:ResourceType>
2502 <rasd:ResourceSubType>ahci</rasd:ResourceSubType>
2503 <rasd:Address>0</rasd:Address>
2504 <rasd:BusNumber>0</rasd:BusNumber>
2505 </Item>
2506 */
2507 if (uLoop == 1)
2508 {
2509 strDescription = "SATA Controller";
2510 strCaption = "sataController0";
2511 type = OVFResourceType_OtherStorageDevice; // 20
2512 // it seems that OVFTool always writes these two, and since we can only
2513 // have one SATA controller, we'll use this as well
2514 lAddress = 0;
2515 lBusNumber = 0;
2516
2517 if ( desc.strVbox.isEmpty() // AHCI is the default in VirtualBox
2518 || (!desc.strVbox.compare("ahci", Utf8Str::CaseInsensitive))
2519 )
2520 strResourceSubType = "AHCI";
2521 else
2522 throw setError(VBOX_E_NOT_SUPPORTED,
2523 tr("Invalid config string \"%s\" in SATA controller"), desc.strVbox.c_str());
2524
2525 // remember this ID
2526 idSATAController = ulInstanceID;
2527 lSATAControllerIndex = lIndexThis;
2528 }
2529 break;
2530
2531 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
2532 /* <Item>
2533 <rasd:Caption>scsiController0</rasd:Caption>
2534 <rasd:Description>SCSI Controller</rasd:Description>
2535 <rasd:InstanceId>4</rasd:InstanceId>
2536 <rasd:ResourceType>6</rasd:ResourceType>
2537 <rasd:ResourceSubType>buslogic</rasd:ResourceSubType>
2538 <rasd:Address>0</rasd:Address>
2539 <rasd:BusNumber>0</rasd:BusNumber>
2540 </Item>
2541 */
2542 if (uLoop == 1)
2543 {
2544 strDescription = "SCSI Controller";
2545 strCaption = "scsiController0";
2546 type = OVFResourceType_ParallelSCSIHBA; // 6
2547 // it seems that OVFTool always writes these two, and since we can only
2548 // have one SATA controller, we'll use this as well
2549 lAddress = 0;
2550 lBusNumber = 0;
2551
2552 if ( desc.strVbox.isEmpty() // LsiLogic is the default in VirtualBox
2553 || (!desc.strVbox.compare("lsilogic", Utf8Str::CaseInsensitive))
2554 )
2555 strResourceSubType = "lsilogic";
2556 else if (!desc.strVbox.compare("buslogic", Utf8Str::CaseInsensitive))
2557 strResourceSubType = "buslogic";
2558 else
2559 throw setError(VBOX_E_NOT_SUPPORTED,
2560 tr("Invalid config string \"%s\" in SCSI controller"), desc.strVbox.c_str());
2561
2562 // remember this ID
2563 idSCSIController = ulInstanceID;
2564 lSCSIControllerIndex = lIndexThis;
2565 }
2566 break;
2567
2568 case VirtualSystemDescriptionType_HardDiskImage:
2569 /* <Item>
2570 <rasd:Caption>disk1</rasd:Caption>
2571 <rasd:InstanceId>8</rasd:InstanceId>
2572 <rasd:ResourceType>17</rasd:ResourceType>
2573 <rasd:HostResource>/disk/vmdisk1</rasd:HostResource>
2574 <rasd:Parent>4</rasd:Parent>
2575 <rasd:AddressOnParent>0</rasd:AddressOnParent>
2576 </Item> */
2577 if (uLoop == 2)
2578 {
2579 Utf8Str strDiskID = Utf8StrFmt("vmdisk%RI32", ++cDisks);
2580
2581 strDescription = "Disk Image";
2582 strCaption = Utf8StrFmt("disk%RI32", cDisks); // this is not used for anything else
2583 type = OVFResourceType_HardDisk; // 17
2584
2585 // the following references the "<Disks>" XML block
2586 strHostResource = Utf8StrFmt("/disk/%s", strDiskID.c_str());
2587
2588 // controller=<index>;channel=<c>
2589 size_t pos1 = desc.strExtraConfig.find("controller=");
2590 size_t pos2 = desc.strExtraConfig.find("channel=");
2591 if (pos1 != Utf8Str::npos)
2592 {
2593 int32_t lControllerIndex = -1;
2594 RTStrToInt32Ex(desc.strExtraConfig.c_str() + pos1 + 11, NULL, 0, &lControllerIndex);
2595 if (lControllerIndex == lIDEControllerIndex)
2596 ulParent = idIDEController;
2597 else if (lControllerIndex == lSCSIControllerIndex)
2598 ulParent = idSCSIController;
2599 else if (lControllerIndex == lSATAControllerIndex)
2600 ulParent = idSATAController;
2601 }
2602 if (pos2 != Utf8Str::npos)
2603 RTStrToInt32Ex(desc.strExtraConfig.c_str() + pos2 + 8, NULL, 0, &lAddressOnParent);
2604
2605 if ( !ulParent
2606 || lAddressOnParent == -1
2607 )
2608 throw setError(VBOX_E_NOT_SUPPORTED,
2609 tr("Missing or bad extra config string in hard disk image: \"%s\""), desc.strExtraConfig.c_str());
2610
2611 mapDisks[strDiskID] = &desc;
2612 }
2613 break;
2614
2615 case VirtualSystemDescriptionType_Floppy:
2616 if (uLoop == 1)
2617 {
2618 strDescription = "Floppy Drive";
2619 strCaption = "floppy0"; // this is what OVFTool writes
2620 type = OVFResourceType_FloppyDrive; // 14
2621 lAutomaticAllocation = 0;
2622 lAddressOnParent = 0; // this is what OVFTool writes
2623 }
2624 break;
2625
2626 case VirtualSystemDescriptionType_CDROM:
2627 if (uLoop == 2)
2628 {
2629 // we can't have a CD without an IDE controller
2630 if (!idIDEController)
2631 throw setError(VBOX_E_NOT_SUPPORTED,
2632 tr("Can't have CD-ROM without IDE controller"));
2633
2634 strDescription = "CD-ROM Drive";
2635 strCaption = "cdrom1"; // this is what OVFTool writes
2636 type = OVFResourceType_CDDrive; // 15
2637 lAutomaticAllocation = 1;
2638 ulParent = idIDEController;
2639 lAddressOnParent = 0; // this is what OVFTool writes
2640 }
2641 break;
2642
2643 case VirtualSystemDescriptionType_NetworkAdapter:
2644 /* <Item>
2645 <rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
2646 <rasd:Caption>Ethernet adapter on 'VM Network'</rasd:Caption>
2647 <rasd:Connection>VM Network</rasd:Connection>
2648 <rasd:ElementName>VM network</rasd:ElementName>
2649 <rasd:InstanceID>3</rasd:InstanceID>
2650 <rasd:ResourceType>10</rasd:ResourceType>
2651 </Item> */
2652 if (uLoop == 1)
2653 {
2654 lAutomaticAllocation = 1;
2655 strCaption = Utf8StrFmt("Ethernet adapter on '%s'", desc.strOvf.c_str());
2656 type = OVFResourceType_EthernetAdapter; // 10
2657 /* Set the hardware type to something useful.
2658 * To be compatible with vmware & others we set
2659 * PCNet32 for our PCNet types & E1000 for the
2660 * E1000 cards. */
2661 switch (desc.strVbox.toInt32())
2662 {
2663 case NetworkAdapterType_Am79C970A:
2664 case NetworkAdapterType_Am79C973: strResourceSubType = "PCNet32"; break;
2665#ifdef VBOX_WITH_E1000
2666 case NetworkAdapterType_I82540EM:
2667 case NetworkAdapterType_I82545EM:
2668 case NetworkAdapterType_I82543GC: strResourceSubType = "E1000"; break;
2669#endif /* VBOX_WITH_E1000 */
2670 }
2671 strConnection = desc.strOvf;
2672
2673 mapNetworks[desc.strOvf] = true;
2674 }
2675 break;
2676
2677 case VirtualSystemDescriptionType_USBController:
2678 /* <Item ovf:required="false">
2679 <rasd:Caption>usb</rasd:Caption>
2680 <rasd:Description>USB Controller</rasd:Description>
2681 <rasd:InstanceId>3</rasd:InstanceId>
2682 <rasd:ResourceType>23</rasd:ResourceType>
2683 <rasd:Address>0</rasd:Address>
2684 <rasd:BusNumber>0</rasd:BusNumber>
2685 </Item> */
2686 if (uLoop == 1)
2687 {
2688 strDescription = "USB Controller";
2689 strCaption = "usb";
2690 type = OVFResourceType_USBController; // 23
2691 lAddress = 0; // this is what OVFTool writes
2692 lBusNumber = 0; // this is what OVFTool writes
2693 }
2694 break;
2695
2696 case VirtualSystemDescriptionType_SoundCard:
2697 /* <Item ovf:required="false">
2698 <rasd:Caption>sound</rasd:Caption>
2699 <rasd:Description>Sound Card</rasd:Description>
2700 <rasd:InstanceId>10</rasd:InstanceId>
2701 <rasd:ResourceType>35</rasd:ResourceType>
2702 <rasd:ResourceSubType>ensoniq1371</rasd:ResourceSubType>
2703 <rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
2704 <rasd:AddressOnParent>3</rasd:AddressOnParent>
2705 </Item> */
2706 if (uLoop == 1)
2707 {
2708 strDescription = "Sound Card";
2709 strCaption = "sound";
2710 type = OVFResourceType_SoundCard; // 35
2711 strResourceSubType = desc.strOvf; // e.g. ensoniq1371
2712 lAutomaticAllocation = 0;
2713 lAddressOnParent = 3; // what gives? this is what OVFTool writes
2714 }
2715 break;
2716 }
2717
2718 if (type)
2719 {
2720 xml::ElementNode *pItem;
2721
2722 pItem = pelmVirtualHardwareSection->createChild("Item");
2723
2724 // NOTE: do not change the order of these items without good reason! While we don't care
2725 // about ordering, VMware's ovftool does and fails if the items are not written in
2726 // exactly this order, as stupid as it seems.
2727
2728 if (!strCaption.isEmpty())
2729 {
2730 pItem->createChild("rasd:Caption")->addContent(strCaption);
2731 if (pTask->enFormat == TaskExportOVF::OVF_1_0)
2732 pItem->createChild("rasd:ElementName")->addContent(strCaption);
2733 }
2734
2735 if (!strDescription.isEmpty())
2736 pItem->createChild("rasd:Description")->addContent(strDescription);
2737
2738 // <rasd:InstanceID>1</rasd:InstanceID>
2739 xml::ElementNode *pelmInstanceID;
2740 if (pTask->enFormat == TaskExportOVF::OVF_0_9)
2741 pelmInstanceID = pItem->createChild("rasd:InstanceId");
2742 else
2743 pelmInstanceID = pItem->createChild("rasd:InstanceID"); // capitalization changed...
2744 pelmInstanceID->addContent(Utf8StrFmt("%d", ulInstanceID++));
2745
2746 // <rasd:ResourceType>3</rasd:ResourceType>
2747 pItem->createChild("rasd:ResourceType")->addContent(Utf8StrFmt("%d", type));
2748 if (!strResourceSubType.isEmpty())
2749 pItem->createChild("rasd:ResourceSubType")->addContent(strResourceSubType);
2750
2751 if (!strHostResource.isEmpty())
2752 pItem->createChild("rasd:HostResource")->addContent(strHostResource);
2753
2754 if (!strAllocationUnits.isEmpty())
2755 pItem->createChild("rasd:AllocationUnits")->addContent(strAllocationUnits);
2756
2757 // <rasd:VirtualQuantity>1</rasd:VirtualQuantity>
2758 if (lVirtualQuantity != -1)
2759 pItem->createChild("rasd:VirtualQuantity")->addContent(Utf8StrFmt("%d", lVirtualQuantity));
2760
2761 if (lAutomaticAllocation != -1)
2762 pItem->createChild("rasd:AutomaticAllocation")->addContent( (lAutomaticAllocation) ? "true" : "false" );
2763
2764 if (!strConnection.isEmpty())
2765 pItem->createChild("rasd:Connection")->addContent(strConnection);
2766
2767 if (lAddress != -1)
2768 pItem->createChild("rasd:Address")->addContent(Utf8StrFmt("%d", lAddress));
2769
2770 if (lBusNumber != -1)
2771 if (pTask->enFormat == TaskExportOVF::OVF_0_9) // BusNumber is invalid OVF 1.0 so only write it in 0.9 mode for OVFTool compatibility
2772 pItem->createChild("rasd:BusNumber")->addContent(Utf8StrFmt("%d", lBusNumber));
2773
2774 if (ulParent)
2775 pItem->createChild("rasd:Parent")->addContent(Utf8StrFmt("%d", ulParent));
2776 if (lAddressOnParent != -1)
2777 pItem->createChild("rasd:AddressOnParent")->addContent(Utf8StrFmt("%d", lAddressOnParent));
2778 }
2779 }
2780 } // for (size_t uLoop = 0; ...
2781 }
2782
2783 // finally, fill in the network section we set up empty above according
2784 // to the networks we found with the hardware items
2785 map<Utf8Str, bool>::const_iterator itN;
2786 for (itN = mapNetworks.begin();
2787 itN != mapNetworks.end();
2788 ++itN)
2789 {
2790 const Utf8Str &strNetwork = itN->first;
2791 xml::ElementNode *pelmNetwork = pelmNetworkSection->createChild("Network");
2792 pelmNetwork->setAttribute("ovf:name", strNetwork.c_str());
2793 pelmNetwork->createChild("Description")->addContent("Logical network used by this appliance.");
2794 }
2795
2796 list<Utf8Str> diskList;
2797 map<Utf8Str, const VirtualSystemDescriptionEntry*>::const_iterator itS;
2798 uint32_t ulFile = 1;
2799 for (itS = mapDisks.begin();
2800 itS != mapDisks.end();
2801 ++itS)
2802 {
2803 const Utf8Str &strDiskID = itS->first;
2804 const VirtualSystemDescriptionEntry *pDiskEntry = itS->second;
2805
2806 // source path: where the VBox image is
2807 const Utf8Str &strSrcFilePath = pDiskEntry->strVbox;
2808 Bstr bstrSrcFilePath(strSrcFilePath);
2809 if (!RTPathExists(strSrcFilePath.c_str()))
2810 /* This isn't allowed */
2811 throw setError(VBOX_E_FILE_ERROR,
2812 tr("Source virtual disk image file '%s' doesn't exist"),
2813 strSrcFilePath.c_str());
2814
2815 // output filename
2816 const Utf8Str &strTargetFileNameOnly = pDiskEntry->strOvf;
2817 // target path needs to be composed from where the output OVF is
2818 Utf8Str strTargetFilePath(pTask->locInfo.strPath);
2819 strTargetFilePath.stripFilename();
2820 strTargetFilePath.append("/");
2821 strTargetFilePath.append(strTargetFileNameOnly);
2822
2823 // clone the disk:
2824 ComPtr<IHardDisk> pSourceDisk;
2825 ComPtr<IHardDisk> pTargetDisk;
2826 ComPtr<IProgress> pProgress2;
2827
2828 Log(("Finding source disk \"%ls\"\n", bstrSrcFilePath.raw()));
2829 rc = mVirtualBox->FindHardDisk(bstrSrcFilePath, pSourceDisk.asOutParam());
2830 if (FAILED(rc)) throw rc;
2831
2832 /* We are always exporting to vmdfk stream optimized for now */
2833 Bstr bstrSrcFormat = L"VMDK";
2834
2835 // create a new hard disk interface for the destination disk image
2836 Log(("Creating target disk \"%s\"\n", strTargetFilePath.raw()));
2837 rc = mVirtualBox->CreateHardDisk(bstrSrcFormat, Bstr(strTargetFilePath), pTargetDisk.asOutParam());
2838 if (FAILED(rc)) throw rc;
2839
2840 // the target disk is now registered and needs to be removed again,
2841 // both after successful cloning or if anything goes bad!
2842 try
2843 {
2844 // create a flat copy of the source disk image
2845 rc = pSourceDisk->CloneTo(pTargetDisk, HardDiskVariant_VmdkStreamOptimized, NULL, pProgress2.asOutParam());
2846 if (FAILED(rc)) throw rc;
2847
2848 // advance to the next operation
2849 if (!pTask->progress.isNull())
2850 pTask->progress->setNextOperation(BstrFmt(tr("Exporting virtual disk image '%s'"), strSrcFilePath.c_str()),
2851 pDiskEntry->ulSizeMB); // operation's weight, as set up with the IProgress originally);
2852
2853 // now wait for the background disk operation to complete; this throws HRESULTs on error
2854 waitForAsyncProgress(pTask->progress, pProgress2);
2855 }
2856 catch (HRESULT rc3)
2857 {
2858 // upon error after registering, close the disk or
2859 // it'll stick in the registry forever
2860 pTargetDisk->Close();
2861 throw;
2862 }
2863 diskList.push_back(strTargetFilePath);
2864
2865 // we need the following for the XML
2866 uint64_t cbFile = 0; // actual file size
2867 rc = pTargetDisk->COMGETTER(Size)(&cbFile);
2868 if (FAILED(rc)) throw rc;
2869
2870 ULONG64 cbCapacity = 0; // size reported to guest
2871 rc = pTargetDisk->COMGETTER(LogicalSize)(&cbCapacity);
2872 if (FAILED(rc)) throw rc;
2873 // capacity is reported in megabytes, so...
2874 cbCapacity *= _1M;
2875
2876 // upon success, close the disk as well
2877 rc = pTargetDisk->Close();
2878 if (FAILED(rc)) throw rc;
2879
2880 // now handle the XML for the disk:
2881 Utf8StrFmt strFileRef("file%RI32", ulFile++);
2882 // <File ovf:href="WindowsXpProfessional-disk1.vmdk" ovf:id="file1" ovf:size="1710381056"/>
2883 xml::ElementNode *pelmFile = pelmReferences->createChild("File");
2884 pelmFile->setAttribute("ovf:href", strTargetFileNameOnly);
2885 pelmFile->setAttribute("ovf:id", strFileRef);
2886 pelmFile->setAttribute("ovf:size", Utf8StrFmt("%RI64", cbFile).c_str());
2887
2888 // add disk to XML Disks section
2889 // <Disk ovf:capacity="8589934592" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="http://www.vmware.com/specifications/vmdk.html#sparse"/>
2890 xml::ElementNode *pelmDisk = pelmDiskSection->createChild("Disk");
2891 pelmDisk->setAttribute("ovf:capacity", Utf8StrFmt("%RI64", cbCapacity).c_str());
2892 pelmDisk->setAttribute("ovf:diskId", strDiskID);
2893 pelmDisk->setAttribute("ovf:fileRef", strFileRef);
2894 pelmDisk->setAttribute("ovf:format", "http://www.vmware.com/specifications/vmdk.html#sparse"); // must be sparse or ovftool chokes
2895 }
2896
2897 // now go write the XML
2898 xml::XmlFileWriter writer(doc);
2899 writer.write(pTask->locInfo.strPath.c_str());
2900
2901 /* Create & write the manifest file */
2902 const char** ppManifestFiles = (const char**)RTMemAlloc(sizeof(char*)*diskList.size() + 1);
2903 ppManifestFiles[0] = pTask->locInfo.strPath.c_str();
2904 list<Utf8Str>::const_iterator it1;
2905 size_t i = 1;
2906 for (it1 = diskList.begin();
2907 it1 != diskList.end();
2908 ++it1, ++i)
2909 ppManifestFiles[i] = (*it1).c_str();
2910 Utf8Str strMfFile = manifestFileName(pTask->locInfo.strPath.c_str());
2911 int vrc = RTManifestWriteFiles(strMfFile.c_str(), ppManifestFiles, diskList.size()+1);
2912 if (RT_FAILURE(vrc))
2913 throw setError(VBOX_E_FILE_ERROR,
2914 tr("Couldn't create manifest file '%s' (%Rrc)"),
2915 RTPathFilename(strMfFile.c_str()), vrc);
2916 RTMemFree(ppManifestFiles);
2917 }
2918 catch(xml::Error &x)
2919 {
2920 rc = setError(VBOX_E_FILE_ERROR,
2921 x.what());
2922 }
2923 catch(HRESULT aRC)
2924 {
2925 rc = aRC;
2926 }
2927
2928 pTask->rc = rc;
2929
2930 if (!pTask->progress.isNull())
2931 pTask->progress->notifyComplete(rc);
2932
2933 LogFlowFunc(("rc=%Rhrc\n", rc));
2934 LogFlowFuncLeave();
2935
2936 return VINF_SUCCESS;
2937}
2938
2939int Appliance::writeS3(TaskExportOVF *pTask)
2940{
2941 LogFlowFuncEnter();
2942 LogFlowFunc(("Appliance %p\n", this));
2943
2944 AutoCaller autoCaller(this);
2945 CheckComRCReturnRC(autoCaller.rc());
2946
2947 HRESULT rc = S_OK;
2948
2949 AutoWriteLock appLock(this);
2950
2951 int vrc = VINF_SUCCESS;
2952 RTS3 hS3 = NIL_RTS3;
2953 char szOSTmpDir[RTPATH_MAX];
2954 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2955 /* The template for the temporary directory created below */
2956 char *pszTmpDir;
2957 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
2958 list< pair<Utf8Str, ULONG> > filesList;
2959
2960 // todo:
2961 // - usable error codes
2962 // - seems snapshot filenames are problematic {uuid}.vdi
2963 try
2964 {
2965 /* Extract the bucket */
2966 Utf8Str tmpPath = pTask->locInfo.strPath;
2967 Utf8Str bucket;
2968 parseBucket(tmpPath, bucket);
2969
2970 /* We need a temporary directory which we can put the OVF file & all
2971 * disk images in */
2972 vrc = RTDirCreateTemp(pszTmpDir);
2973 if (RT_FAILURE(rc))
2974 throw setError(VBOX_E_FILE_ERROR,
2975 tr("Cannot create temporary directory '%s'"), pszTmpDir);
2976
2977 /* The temporary name of the target OVF file */
2978 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath));
2979
2980 /* Prepare the temporary writing of the OVF */
2981 ComObjPtr<Progress> progress;
2982 /* Create a temporary file based location info for the sub task */
2983 LocationInfo li;
2984 li.strPath = strTmpOvf;
2985 rc = writeImpl(pTask->enFormat, li, progress);
2986 if (FAILED(rc)) throw rc;
2987
2988 /* Unlock the appliance for the writing thread */
2989 appLock.unlock();
2990 /* Wait until the writing is done, but report the progress back to the
2991 caller */
2992 ComPtr<IProgress> progressInt(progress);
2993 waitForAsyncProgress(pTask->progress, progressInt); /* Any errors will be thrown */
2994
2995 /* Again lock the appliance for the next steps */
2996 appLock.lock();
2997
2998 vrc = RTPathExists(strTmpOvf.c_str()); /* Paranoid check */
2999 if(RT_FAILURE(vrc))
3000 throw setError(VBOX_E_FILE_ERROR,
3001 tr("Cannot find source file '%s'"), strTmpOvf.c_str());
3002 /* Add the OVF file */
3003 filesList.push_back(pair<Utf8Str, ULONG>(strTmpOvf, m->ulWeightPerOperation)); /* Use 1% of the total for the OVF file upload */
3004 Utf8Str strMfFile = manifestFileName(strTmpOvf);
3005 filesList.push_back(pair<Utf8Str, ULONG>(strMfFile , m->ulWeightPerOperation)); /* Use 1% of the total for the manifest file upload */
3006
3007 /* Now add every disks of every virtual system */
3008 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
3009 for (it = m->virtualSystemDescriptions.begin();
3010 it != m->virtualSystemDescriptions.end();
3011 ++it)
3012 {
3013 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
3014 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
3015 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
3016 for (itH = avsdeHDs.begin();
3017 itH != avsdeHDs.end();
3018 ++itH)
3019 {
3020 const Utf8Str &strTargetFileNameOnly = (*itH)->strOvf;
3021 /* Target path needs to be composed from where the output OVF is */
3022 Utf8Str strTargetFilePath(strTmpOvf);
3023 strTargetFilePath.stripFilename();
3024 strTargetFilePath.append("/");
3025 strTargetFilePath.append(strTargetFileNameOnly);
3026 vrc = RTPathExists(strTargetFilePath.c_str()); /* Paranoid check */
3027 if(RT_FAILURE(vrc))
3028 throw setError(VBOX_E_FILE_ERROR,
3029 tr("Cannot find source file '%s'"), strTargetFilePath.c_str());
3030 filesList.push_back(pair<Utf8Str, ULONG>(strTargetFilePath, (*itH)->ulSizeMB));
3031 }
3032 }
3033 /* Next we have to upload the OVF & all disk images */
3034 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
3035 if(RT_FAILURE(vrc))
3036 throw setError(VBOX_E_IPRT_ERROR,
3037 tr("Cannot create S3 service handler"));
3038 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
3039
3040 /* Upload all files */
3041 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
3042 {
3043 const pair<Utf8Str, ULONG> &s = (*it1);
3044 char *pszFilename = RTPathFilename(s.first.c_str());
3045 /* Advance to the next operation */
3046 if (!pTask->progress.isNull())
3047 pTask->progress->setNextOperation(BstrFmt(tr("Uploading file '%s'"), pszFilename), s.second);
3048 vrc = RTS3PutKey(hS3, bucket.c_str(), pszFilename, s.first.c_str());
3049 if (RT_FAILURE(vrc))
3050 {
3051 if(vrc == VERR_S3_CANCELED)
3052 break;
3053 else if(vrc == VERR_S3_ACCESS_DENIED)
3054 throw setError(E_ACCESSDENIED,
3055 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);
3056 else if(vrc == VERR_S3_NOT_FOUND)
3057 throw setError(VBOX_E_FILE_ERROR,
3058 tr("Cannot upload file '%s' to S3 storage server (File not found)"), pszFilename);
3059 else
3060 throw setError(VBOX_E_IPRT_ERROR,
3061 tr("Cannot upload file '%s' to S3 storage server (%Rrc)"), pszFilename, vrc);
3062 }
3063 }
3064 }
3065 catch(HRESULT aRC)
3066 {
3067 rc = aRC;
3068 }
3069 /* Cleanup */
3070 RTS3Destroy(hS3);
3071 /* Delete all files which where temporary created */
3072 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
3073 {
3074 const char *pszFilePath = (*it1).first.c_str();
3075 if (RTPathExists(pszFilePath))
3076 {
3077 vrc = RTFileDelete(pszFilePath);
3078 if(RT_FAILURE(vrc))
3079 rc = setError(VBOX_E_FILE_ERROR,
3080 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
3081 }
3082 }
3083 /* Delete the temporary directory */
3084 if (RTPathExists(pszTmpDir))
3085 {
3086 vrc = RTDirRemove(pszTmpDir);
3087 if(RT_FAILURE(vrc))
3088 rc = setError(VBOX_E_FILE_ERROR,
3089 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
3090 }
3091 if (pszTmpDir)
3092 RTStrFree(pszTmpDir);
3093
3094 pTask->rc = rc;
3095
3096 if (!pTask->progress.isNull())
3097 pTask->progress->notifyComplete(rc);
3098
3099 LogFlowFunc(("rc=%Rhrc\n", rc));
3100 LogFlowFuncLeave();
3101
3102 return VINF_SUCCESS;
3103}
3104
3105////////////////////////////////////////////////////////////////////////////////
3106//
3107// IAppliance public methods
3108//
3109////////////////////////////////////////////////////////////////////////////////
3110
3111/**
3112 * Public method implementation.
3113 * @param
3114 * @return
3115 */
3116STDMETHODIMP Appliance::COMGETTER(Path)(BSTR *aPath)
3117{
3118 if (!aPath)
3119 return E_POINTER;
3120
3121 AutoCaller autoCaller(this);
3122 CheckComRCReturnRC(autoCaller.rc());
3123
3124 AutoReadLock alock(this);
3125
3126 Bstr bstrPath(m->locInfo.strPath);
3127 bstrPath.cloneTo(aPath);
3128
3129 return S_OK;
3130}
3131
3132/**
3133 * Public method implementation.
3134 * @param
3135 * @return
3136 */
3137STDMETHODIMP Appliance::COMGETTER(Disks)(ComSafeArrayOut(BSTR, aDisks))
3138{
3139 CheckComArgOutSafeArrayPointerValid(aDisks);
3140
3141 AutoCaller autoCaller(this);
3142 CheckComRCReturnRC(autoCaller.rc());
3143
3144 AutoReadLock alock(this);
3145
3146 if (m->pReader) // OVFReader instantiated?
3147 {
3148 size_t c = m->pReader->m_mapDisks.size();
3149 com::SafeArray<BSTR> sfaDisks(c);
3150
3151 DiskImagesMap::const_iterator it;
3152 size_t i = 0;
3153 for (it = m->pReader->m_mapDisks.begin();
3154 it != m->pReader->m_mapDisks.end();
3155 ++it, ++i)
3156 {
3157 // create a string representing this disk
3158 const DiskImage &d = it->second;
3159 char *psz = NULL;
3160 RTStrAPrintf(&psz,
3161 "%s\t"
3162 "%RI64\t"
3163 "%RI64\t"
3164 "%s\t"
3165 "%s\t"
3166 "%RI64\t"
3167 "%RI64\t"
3168 "%s",
3169 d.strDiskId.c_str(),
3170 d.iCapacity,
3171 d.iPopulatedSize,
3172 d.strFormat.c_str(),
3173 d.strHref.c_str(),
3174 d.iSize,
3175 d.iChunkSize,
3176 d.strCompression.c_str());
3177 Utf8Str utf(psz);
3178 Bstr bstr(utf);
3179 // push to safearray
3180 bstr.cloneTo(&sfaDisks[i]);
3181 RTStrFree(psz);
3182 }
3183
3184 sfaDisks.detachTo(ComSafeArrayOutArg(aDisks));
3185 }
3186
3187 return S_OK;
3188}
3189
3190/**
3191 * Public method implementation.
3192 * @param
3193 * @return
3194 */
3195STDMETHODIMP Appliance::COMGETTER(VirtualSystemDescriptions)(ComSafeArrayOut(IVirtualSystemDescription*, aVirtualSystemDescriptions))
3196{
3197 CheckComArgOutSafeArrayPointerValid(aVirtualSystemDescriptions);
3198
3199 AutoCaller autoCaller(this);
3200 CheckComRCReturnRC(autoCaller.rc());
3201
3202 AutoReadLock alock(this);
3203
3204 SafeIfaceArray<IVirtualSystemDescription> sfaVSD(m->virtualSystemDescriptions);
3205 sfaVSD.detachTo(ComSafeArrayOutArg(aVirtualSystemDescriptions));
3206
3207 return S_OK;
3208}
3209
3210/**
3211 * Public method implementation.
3212 * @param path
3213 * @return
3214 */
3215STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
3216{
3217 if (!path) return E_POINTER;
3218 CheckComArgOutPointerValid(aProgress);
3219
3220 AutoCaller autoCaller(this);
3221 CheckComRCReturnRC(autoCaller.rc());
3222
3223 AutoWriteLock alock(this);
3224
3225 if (m->pReader)
3226 {
3227 delete m->pReader;
3228 m->pReader = NULL;
3229 }
3230
3231 // see if we can handle this file; for now we insist it has an ".ovf" extension
3232 Utf8Str strPath (path);
3233 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
3234 return setError(VBOX_E_FILE_ERROR,
3235 tr("Appliance file must have .ovf extension"));
3236
3237 ComObjPtr<Progress> progress;
3238 HRESULT rc = S_OK;
3239 try
3240 {
3241 /* Parse all necessary info out of the URI */
3242 parseURI(strPath, m->locInfo);
3243 rc = readImpl(m->locInfo, progress);
3244 }
3245 catch (HRESULT aRC)
3246 {
3247 rc = aRC;
3248 }
3249
3250 if (SUCCEEDED(rc))
3251 /* Return progress to the caller */
3252 progress.queryInterfaceTo(aProgress);
3253
3254 return S_OK;
3255}
3256
3257/**
3258 * Public method implementation.
3259 * @return
3260 */
3261STDMETHODIMP Appliance::Interpret()
3262{
3263 // @todo:
3264 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk))
3265 // - Appropriate handle errors like not supported file formats
3266 AutoCaller autoCaller(this);
3267 CheckComRCReturnRC(autoCaller.rc());
3268
3269 AutoWriteLock(this);
3270
3271 HRESULT rc = S_OK;
3272
3273 /* Clear any previous virtual system descriptions */
3274 m->virtualSystemDescriptions.clear();
3275
3276 /* We need the default path for storing disk images */
3277 ComPtr<ISystemProperties> systemProps;
3278 rc = mVirtualBox->COMGETTER(SystemProperties)(systemProps.asOutParam());
3279 CheckComRCReturnRC(rc);
3280 Bstr bstrDefaultHardDiskLocation;
3281 rc = systemProps->COMGETTER(DefaultHardDiskFolder)(bstrDefaultHardDiskLocation.asOutParam());
3282 CheckComRCReturnRC(rc);
3283
3284 if (!m->pReader)
3285 return setError(E_FAIL,
3286 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
3287
3288 /* Try/catch so we can clean up on error */
3289 try
3290 {
3291 list<VirtualSystem>::const_iterator it;
3292 /* Iterate through all virtual systems */
3293 for (it = m->pReader->m_llVirtualSystems.begin();
3294 it != m->pReader->m_llVirtualSystems.end();
3295 ++it)
3296 {
3297 const VirtualSystem &vsysThis = *it;
3298
3299 ComObjPtr<VirtualSystemDescription> pNewDesc;
3300 rc = pNewDesc.createObject();
3301 CheckComRCThrowRC(rc);
3302 rc = pNewDesc->init();
3303 CheckComRCThrowRC(rc);
3304
3305 /* Guest OS type */
3306 Utf8Str strOsTypeVBox,
3307 strCIMOSType = Utf8StrFmt("%RI32", (uint32_t)vsysThis.cimos);
3308 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
3309 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
3310 "",
3311 strCIMOSType,
3312 strOsTypeVBox);
3313
3314 /* VM name */
3315 /* If the there isn't any name specified create a default one out of
3316 * the OS type */
3317 Utf8Str nameVBox = vsysThis.strName;
3318 if (nameVBox.isEmpty())
3319 nameVBox = strOsTypeVBox;
3320 searchUniqueVMName(nameVBox);
3321 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
3322 "",
3323 vsysThis.strName,
3324 nameVBox);
3325
3326 /* VM Product */
3327 if (!vsysThis.strProduct.isEmpty())
3328 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
3329 "",
3330 vsysThis.strProduct,
3331 vsysThis.strProduct);
3332
3333 /* VM Vendor */
3334 if (!vsysThis.strVendor.isEmpty())
3335 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
3336 "",
3337 vsysThis.strVendor,
3338 vsysThis.strVendor);
3339
3340 /* VM Version */
3341 if (!vsysThis.strVersion.isEmpty())
3342 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
3343 "",
3344 vsysThis.strVersion,
3345 vsysThis.strVersion);
3346
3347 /* VM ProductUrl */
3348 if (!vsysThis.strProductUrl.isEmpty())
3349 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
3350 "",
3351 vsysThis.strProductUrl,
3352 vsysThis.strProductUrl);
3353
3354 /* VM VendorUrl */
3355 if (!vsysThis.strVendorUrl.isEmpty())
3356 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
3357 "",
3358 vsysThis.strVendorUrl,
3359 vsysThis.strVendorUrl);
3360
3361 /* VM description */
3362 if (!vsysThis.strDescription.isEmpty())
3363 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
3364 "",
3365 vsysThis.strDescription,
3366 vsysThis.strDescription);
3367
3368 /* VM license */
3369 if (!vsysThis.strLicenseText.isEmpty())
3370 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
3371 "",
3372 vsysThis.strLicenseText,
3373 vsysThis.strLicenseText);
3374
3375 /* Now that we know the OS type, get our internal defaults based on that. */
3376 ComPtr<IGuestOSType> pGuestOSType;
3377 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), pGuestOSType.asOutParam());
3378 CheckComRCThrowRC(rc);
3379
3380 /* CPU count */
3381 ULONG cpuCountVBox = vsysThis.cCPUs;
3382 /* Check for the constrains */
3383 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
3384 {
3385 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
3386 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
3387 cpuCountVBox = SchemaDefs::MaxCPUCount;
3388 }
3389 if (vsysThis.cCPUs == 0)
3390 cpuCountVBox = 1;
3391 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
3392 "",
3393 Utf8StrFmt("%RI32", (uint32_t)vsysThis.cCPUs),
3394 Utf8StrFmt("%RI32", (uint32_t)cpuCountVBox));
3395
3396 /* RAM */
3397 uint64_t ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
3398 /* Check for the constrains */
3399 if (ullMemSizeVBox != 0 &&
3400 (ullMemSizeVBox < MM_RAM_MIN_IN_MB ||
3401 ullMemSizeVBox > MM_RAM_MAX_IN_MB))
3402 {
3403 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."),
3404 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
3405 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
3406 }
3407 if (vsysThis.ullMemorySize == 0)
3408 {
3409 /* If the RAM of the OVF is zero, use our predefined values */
3410 ULONG memSizeVBox2;
3411 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
3412 CheckComRCThrowRC(rc);
3413 /* VBox stores that in MByte */
3414 ullMemSizeVBox = (uint64_t)memSizeVBox2;
3415 }
3416 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
3417 "",
3418 Utf8StrFmt("%RI64", (uint64_t)vsysThis.ullMemorySize),
3419 Utf8StrFmt("%RI64", (uint64_t)ullMemSizeVBox));
3420
3421 /* Audio */
3422 if (!vsysThis.strSoundCardType.isEmpty())
3423 /* Currently we set the AC97 always.
3424 @todo: figure out the hardware which could be possible */
3425 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
3426 "",
3427 vsysThis.strSoundCardType,
3428 Utf8StrFmt("%RI32", (uint32_t)AudioControllerType_AC97));
3429
3430#ifdef VBOX_WITH_USB
3431 /* USB Controller */
3432 if (vsysThis.fHasUsbController)
3433 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
3434#endif /* VBOX_WITH_USB */
3435
3436 /* Network Controller */
3437 size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size();
3438 if (cEthernetAdapters > 0)
3439 {
3440 /* Check for the constrains */
3441 if (cEthernetAdapters > SchemaDefs::NetworkAdapterCount)
3442 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
3443 vsysThis.strName.c_str(), cEthernetAdapters, SchemaDefs::NetworkAdapterCount);
3444
3445 /* Get the default network adapter type for the selected guest OS */
3446 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
3447 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
3448 CheckComRCThrowRC(rc);
3449
3450 EthernetAdaptersList::const_iterator itEA;
3451 /* Iterate through all abstract networks. We support 8 network
3452 * adapters at the maximum, so the first 8 will be added only. */
3453 size_t a = 0;
3454 for (itEA = vsysThis.llEthernetAdapters.begin();
3455 itEA != vsysThis.llEthernetAdapters.end() && a < SchemaDefs::NetworkAdapterCount;
3456 ++itEA, ++a)
3457 {
3458 const EthernetAdapter &ea = *itEA; // logical network to connect to
3459 Utf8Str strNetwork = ea.strNetworkName;
3460 // make sure it's one of these two
3461 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
3462 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
3463 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
3464 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
3465 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
3466 )
3467 strNetwork = "Bridged"; // VMware assumes this is the default apparently
3468
3469 /* Figure out the hardware type */
3470 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
3471 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
3472 {
3473 /* If the default adapter is already one of the two
3474 * PCNet adapters use the default one. If not use the
3475 * Am79C970A as fallback. */
3476 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
3477 defaultAdapterVBox == NetworkAdapterType_Am79C973))
3478 nwAdapterVBox = NetworkAdapterType_Am79C970A;
3479 }
3480#ifdef VBOX_WITH_E1000
3481 /* VMWare accidentally write this with VirtualCenter 3.5,
3482 so make sure in this case always to use the VMWare one */
3483 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
3484 nwAdapterVBox = NetworkAdapterType_I82545EM;
3485 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
3486 {
3487 /* Check if this OVF was written by VirtualBox */
3488 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
3489 {
3490 /* If the default adapter is already one of the three
3491 * E1000 adapters use the default one. If not use the
3492 * I82545EM as fallback. */
3493 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
3494 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
3495 defaultAdapterVBox == NetworkAdapterType_I82545EM))
3496 nwAdapterVBox = NetworkAdapterType_I82540EM;
3497 }
3498 else
3499 /* Always use this one since it's what VMware uses */
3500 nwAdapterVBox = NetworkAdapterType_I82545EM;
3501 }
3502#endif /* VBOX_WITH_E1000 */
3503
3504 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
3505 "", // ref
3506 ea.strNetworkName, // orig
3507 Utf8StrFmt("%RI32", (uint32_t)nwAdapterVBox), // conf
3508 0,
3509 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
3510 }
3511 }
3512
3513 /* Floppy Drive */
3514 if (vsysThis.fHasFloppyDrive)
3515 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
3516
3517 /* CD Drive */
3518 /* @todo: I can't disable the CDROM. So nothing to do for now */
3519 /*
3520 if (vsysThis.fHasCdromDrive)
3521 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");*/
3522
3523 /* Hard disk Controller */
3524 uint16_t cIDEused = 0;
3525 uint16_t cSATAused = 0; NOREF(cSATAused);
3526 uint16_t cSCSIused = 0; NOREF(cSCSIused);
3527 ControllersMap::const_iterator hdcIt;
3528 /* Iterate through all hard disk controllers */
3529 for (hdcIt = vsysThis.mapControllers.begin();
3530 hdcIt != vsysThis.mapControllers.end();
3531 ++hdcIt)
3532 {
3533 const HardDiskController &hdc = hdcIt->second;
3534 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
3535
3536 switch (hdc.system)
3537 {
3538 case HardDiskController::IDE:
3539 {
3540 /* Check for the constrains */
3541 /* @todo: I'm very confused! Are these bits *one* controller or
3542 is every port/bus declared as an extra controller. */
3543 if (cIDEused < 4)
3544 {
3545 // @todo: figure out the IDE types
3546 /* Use PIIX4 as default */
3547 Utf8Str strType = "PIIX4";
3548 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
3549 strType = "PIIX3";
3550 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
3551 strType = "ICH6";
3552 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
3553 strControllerID,
3554 hdc.strControllerType,
3555 strType);
3556 }
3557 else
3558 {
3559 /* Warn only once */
3560 if (cIDEused == 1)
3561 addWarning(tr("The virtual \"%s\" system requests support for more than one IDE controller, but VirtualBox has support for only one."),
3562 vsysThis.strName.c_str());
3563
3564 }
3565 ++cIDEused;
3566 break;
3567 }
3568
3569 case HardDiskController::SATA:
3570 {
3571#ifdef VBOX_WITH_AHCI
3572 /* Check for the constrains */
3573 if (cSATAused < 1)
3574 {
3575 // @todo: figure out the SATA types
3576 /* We only support a plain AHCI controller, so use them always */
3577 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
3578 strControllerID,
3579 hdc.strControllerType,
3580 "AHCI");
3581 }
3582 else
3583 {
3584 /* Warn only once */
3585 if (cSATAused == 1)
3586 addWarning(tr("The virtual system \"%s\" requests support for more than one SATA controller, but VirtualBox has support for only one"),
3587 vsysThis.strName.c_str());
3588
3589 }
3590 ++cSATAused;
3591 break;
3592#else /* !VBOX_WITH_AHCI */
3593 addWarning(tr("The virtual system \"%s\" requests at least one SATA controller but this version of VirtualBox does not provide a SATA controller emulation"),
3594 vsysThis.strName.c_str());
3595#endif /* !VBOX_WITH_AHCI */
3596 }
3597
3598 case HardDiskController::SCSI:
3599 {
3600#ifdef VBOX_WITH_LSILOGIC
3601 /* Check for the constrains */
3602 if (cSCSIused < 1)
3603 {
3604 Utf8Str hdcController = "LsiLogic";
3605 if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
3606 hdcController = "BusLogic";
3607 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
3608 strControllerID,
3609 hdc.strControllerType,
3610 hdcController);
3611 }
3612 else
3613 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."),
3614 vsysThis.strName.c_str(),
3615 hdc.strControllerType.c_str(),
3616 strControllerID.c_str());
3617 ++cSCSIused;
3618 break;
3619#else /* !VBOX_WITH_LSILOGIC */
3620 addWarning(tr("The virtual system \"%s\" requests at least one SATA controller but this version of VirtualBox does not provide a SCSI controller emulation"),
3621 vsysThis.strName.c_str());
3622#endif /* !VBOX_WITH_LSILOGIC */
3623 }
3624 }
3625 }
3626
3627 /* Hard disks */
3628 if (vsysThis.mapVirtualDisks.size() > 0)
3629 {
3630 VirtualDisksMap::const_iterator itVD;
3631 /* Iterate through all hard disks ()*/
3632 for (itVD = vsysThis.mapVirtualDisks.begin();
3633 itVD != vsysThis.mapVirtualDisks.end();
3634 ++itVD)
3635 {
3636 const VirtualDisk &hd = itVD->second;
3637 /* Get the associated disk image */
3638 const DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
3639
3640 // @todo:
3641 // - figure out all possible vmdk formats we also support
3642 // - figure out if there is a url specifier for vhd already
3643 // - we need a url specifier for the vdi format
3644 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
3645 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive))
3646 {
3647 /* If the href is empty use the VM name as filename */
3648 Utf8Str strFilename = di.strHref;
3649 if (!strFilename.length())
3650 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
3651 /* Construct a unique target path */
3652 Utf8StrFmt strPath("%ls%c%s",
3653 bstrDefaultHardDiskLocation.raw(),
3654 RTPATH_DELIMITER,
3655 strFilename.c_str());
3656 searchUniqueDiskImageFilePath(strPath);
3657
3658 /* find the description for the hard disk controller
3659 * that has the same ID as hd.idController */
3660 const VirtualSystemDescriptionEntry *pController;
3661 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
3662 throw setError(E_FAIL,
3663 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
3664 hd.idController,
3665 di.strHref.c_str());
3666
3667 /* controller to attach to, and the bus within that controller */
3668 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
3669 pController->ulIndex,
3670 hd.ulAddressOnParent);
3671 ULONG ulSize = 0;
3672 if (di.iCapacity != -1)
3673 ulSize = (ULONG)(di.iCapacity / _1M);
3674 else if (di.iPopulatedSize != -1)
3675 ulSize = (ULONG)(di.iPopulatedSize / _1M);
3676 else if (di.iSize != -1)
3677 ulSize = (ULONG)(di.iSize / _1M);
3678 if (ulSize == 0)
3679 ulSize = 10000; // assume 10 GB, this is for the progress bar only anyway
3680 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
3681 hd.strDiskId,
3682 di.strHref,
3683 strPath,
3684 ulSize,
3685 strExtraConfig);
3686 }
3687 else
3688 throw setError(VBOX_E_FILE_ERROR,
3689 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
3690 }
3691 }
3692
3693 m->virtualSystemDescriptions.push_back(pNewDesc);
3694 }
3695 }
3696 catch (HRESULT aRC)
3697 {
3698 /* On error we clear the list & return */
3699 m->virtualSystemDescriptions.clear();
3700 rc = aRC;
3701 }
3702
3703 return rc;
3704}
3705
3706/**
3707 * Public method implementation.
3708 * @param aProgress
3709 * @return
3710 */
3711STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
3712{
3713 CheckComArgOutPointerValid(aProgress);
3714
3715 AutoCaller autoCaller(this);
3716 CheckComRCReturnRC(autoCaller.rc());
3717
3718 AutoReadLock(this);
3719
3720 if (!m->pReader)
3721 return setError(E_FAIL,
3722 tr("Cannot import machines without reading it first (call read() before importMachines())"));
3723
3724 ComObjPtr<Progress> progress;
3725 HRESULT rc = S_OK;
3726 try
3727 {
3728 rc = importImpl(m->locInfo, progress);
3729 }
3730 catch (HRESULT aRC)
3731 {
3732 rc = aRC;
3733 }
3734
3735 if (SUCCEEDED(rc))
3736 /* Return progress to the caller */
3737 progress.queryInterfaceTo(aProgress);
3738
3739 return rc;
3740}
3741
3742STDMETHODIMP Appliance::CreateVFSExplorer(IN_BSTR aURI, IVFSExplorer **aExplorer)
3743{
3744 CheckComArgOutPointerValid(aExplorer);
3745
3746 AutoCaller autoCaller(this);
3747 CheckComRCReturnRC(autoCaller.rc());
3748
3749 AutoReadLock(this);
3750
3751 ComObjPtr<VFSExplorer> explorer;
3752 HRESULT rc = S_OK;
3753 try
3754 {
3755 Utf8Str uri(aURI);
3756 /* Check which kind of export the user has requested */
3757 LocationInfo li;
3758 parseURI(uri, li);
3759 /* Create the explorer object */
3760 explorer.createObject();
3761 rc = explorer->init(li.storageType, li.strPath, li.strHostname, li.strUsername, li.strPassword, mVirtualBox);
3762 }
3763 catch (HRESULT aRC)
3764 {
3765 rc = aRC;
3766 }
3767
3768 if (SUCCEEDED(rc))
3769 /* Return explorer to the caller */
3770 explorer.queryInterfaceTo(aExplorer);
3771
3772 return rc;
3773}
3774
3775STDMETHODIMP Appliance::Write(IN_BSTR format, IN_BSTR path, IProgress **aProgress)
3776{
3777 if (!path) return E_POINTER;
3778 CheckComArgOutPointerValid(aProgress);
3779
3780 AutoCaller autoCaller(this);
3781 CheckComRCReturnRC(autoCaller.rc());
3782
3783 AutoWriteLock(this);
3784
3785 // see if we can handle this file; for now we insist it has an ".ovf" extension
3786 Utf8Str strPath = path;
3787 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
3788 return setError(VBOX_E_FILE_ERROR,
3789 tr("Appliance file must have .ovf extension"));
3790
3791 Utf8Str strFormat(format);
3792 TaskExportOVF::OVFFormat ovfF;
3793 if (strFormat == "ovf-0.9")
3794 ovfF = TaskExportOVF::OVF_0_9;
3795 else if (strFormat == "ovf-1.0")
3796 ovfF = TaskExportOVF::OVF_1_0;
3797 else
3798 return setError(VBOX_E_FILE_ERROR,
3799 tr("Invalid format \"%s\" specified"), strFormat.c_str());
3800
3801 ComObjPtr<Progress> progress;
3802 HRESULT rc = S_OK;
3803 try
3804 {
3805 /* Parse all necessary info out of the URI */
3806 parseURI(strPath, m->locInfo);
3807 rc = writeImpl(ovfF, m->locInfo, progress);
3808 }
3809 catch (HRESULT aRC)
3810 {
3811 rc = aRC;
3812 }
3813
3814 if (SUCCEEDED(rc))
3815 /* Return progress to the caller */
3816 progress.queryInterfaceTo(aProgress);
3817
3818 return rc;
3819}
3820
3821/**
3822* Public method implementation.
3823 * @return
3824 */
3825STDMETHODIMP Appliance::GetWarnings(ComSafeArrayOut(BSTR, aWarnings))
3826{
3827 if (ComSafeArrayOutIsNull(aWarnings))
3828 return E_POINTER;
3829
3830 AutoCaller autoCaller(this);
3831 CheckComRCReturnRC(autoCaller.rc());
3832
3833 AutoReadLock alock(this);
3834
3835 com::SafeArray<BSTR> sfaWarnings(m->llWarnings.size());
3836
3837 list<Utf8Str>::const_iterator it;
3838 size_t i = 0;
3839 for (it = m->llWarnings.begin();
3840 it != m->llWarnings.end();
3841 ++it, ++i)
3842 {
3843 Bstr bstr = *it;
3844 bstr.cloneTo(&sfaWarnings[i]);
3845 }
3846
3847 sfaWarnings.detachTo(ComSafeArrayOutArg(aWarnings));
3848
3849 return S_OK;
3850}
3851
3852////////////////////////////////////////////////////////////////////////////////
3853//
3854// IVirtualSystemDescription constructor / destructor
3855//
3856////////////////////////////////////////////////////////////////////////////////
3857
3858DEFINE_EMPTY_CTOR_DTOR(VirtualSystemDescription)
3859
3860/**
3861 * COM initializer.
3862 * @return
3863 */
3864HRESULT VirtualSystemDescription::init()
3865{
3866 /* Enclose the state transition NotReady->InInit->Ready */
3867 AutoInitSpan autoInitSpan(this);
3868 AssertReturn(autoInitSpan.isOk(), E_FAIL);
3869
3870 /* Initialize data */
3871 m = new Data();
3872
3873 /* Confirm a successful initialization */
3874 autoInitSpan.setSucceeded();
3875 return S_OK;
3876}
3877
3878/**
3879* COM uninitializer.
3880*/
3881
3882void VirtualSystemDescription::uninit()
3883{
3884 delete m;
3885 m = NULL;
3886}
3887
3888////////////////////////////////////////////////////////////////////////////////
3889//
3890// IVirtualSystemDescription public methods
3891//
3892////////////////////////////////////////////////////////////////////////////////
3893
3894/**
3895 * Public method implementation.
3896 * @param
3897 * @return
3898 */
3899STDMETHODIMP VirtualSystemDescription::COMGETTER(Count)(ULONG *aCount)
3900{
3901 if (!aCount)
3902 return E_POINTER;
3903
3904 AutoCaller autoCaller(this);
3905 CheckComRCReturnRC(autoCaller.rc());
3906
3907 AutoReadLock alock(this);
3908
3909 *aCount = (ULONG)m->llDescriptions.size();
3910
3911 return S_OK;
3912}
3913
3914/**
3915 * Public method implementation.
3916 * @return
3917 */
3918STDMETHODIMP VirtualSystemDescription::GetDescription(ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
3919 ComSafeArrayOut(BSTR, aRefs),
3920 ComSafeArrayOut(BSTR, aOrigValues),
3921 ComSafeArrayOut(BSTR, aVboxValues),
3922 ComSafeArrayOut(BSTR, aExtraConfigValues))
3923{
3924 if (ComSafeArrayOutIsNull(aTypes) ||
3925 ComSafeArrayOutIsNull(aRefs) ||
3926 ComSafeArrayOutIsNull(aOrigValues) ||
3927 ComSafeArrayOutIsNull(aVboxValues) ||
3928 ComSafeArrayOutIsNull(aExtraConfigValues))
3929 return E_POINTER;
3930
3931 AutoCaller autoCaller(this);
3932 CheckComRCReturnRC(autoCaller.rc());
3933
3934 AutoReadLock alock(this);
3935
3936 ULONG c = (ULONG)m->llDescriptions.size();
3937 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
3938 com::SafeArray<BSTR> sfaRefs(c);
3939 com::SafeArray<BSTR> sfaOrigValues(c);
3940 com::SafeArray<BSTR> sfaVboxValues(c);
3941 com::SafeArray<BSTR> sfaExtraConfigValues(c);
3942
3943 list<VirtualSystemDescriptionEntry>::const_iterator it;
3944 size_t i = 0;
3945 for (it = m->llDescriptions.begin();
3946 it != m->llDescriptions.end();
3947 ++it, ++i)
3948 {
3949 const VirtualSystemDescriptionEntry &vsde = (*it);
3950
3951 sfaTypes[i] = vsde.type;
3952
3953 Bstr bstr = vsde.strRef;
3954 bstr.cloneTo(&sfaRefs[i]);
3955
3956 bstr = vsde.strOvf;
3957 bstr.cloneTo(&sfaOrigValues[i]);
3958
3959 bstr = vsde.strVbox;
3960 bstr.cloneTo(&sfaVboxValues[i]);
3961
3962 bstr = vsde.strExtraConfig;
3963 bstr.cloneTo(&sfaExtraConfigValues[i]);
3964 }
3965
3966 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
3967 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
3968 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
3969 sfaVboxValues.detachTo(ComSafeArrayOutArg(aVboxValues));
3970 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
3971
3972 return S_OK;
3973}
3974
3975/**
3976 * Public method implementation.
3977 * @return
3978 */
3979STDMETHODIMP VirtualSystemDescription::GetDescriptionByType(VirtualSystemDescriptionType_T aType,
3980 ComSafeArrayOut(VirtualSystemDescriptionType_T, aTypes),
3981 ComSafeArrayOut(BSTR, aRefs),
3982 ComSafeArrayOut(BSTR, aOrigValues),
3983 ComSafeArrayOut(BSTR, aVboxValues),
3984 ComSafeArrayOut(BSTR, aExtraConfigValues))
3985{
3986 if (ComSafeArrayOutIsNull(aTypes) ||
3987 ComSafeArrayOutIsNull(aRefs) ||
3988 ComSafeArrayOutIsNull(aOrigValues) ||
3989 ComSafeArrayOutIsNull(aVboxValues) ||
3990 ComSafeArrayOutIsNull(aExtraConfigValues))
3991 return E_POINTER;
3992
3993 AutoCaller autoCaller(this);
3994 CheckComRCReturnRC(autoCaller.rc());
3995
3996 AutoReadLock alock(this);
3997
3998 std::list<VirtualSystemDescriptionEntry*> vsd = findByType (aType);
3999 ULONG c = (ULONG)vsd.size();
4000 com::SafeArray<VirtualSystemDescriptionType_T> sfaTypes(c);
4001 com::SafeArray<BSTR> sfaRefs(c);
4002 com::SafeArray<BSTR> sfaOrigValues(c);
4003 com::SafeArray<BSTR> sfaVboxValues(c);
4004 com::SafeArray<BSTR> sfaExtraConfigValues(c);
4005
4006 list<VirtualSystemDescriptionEntry*>::const_iterator it;
4007 size_t i = 0;
4008 for (it = vsd.begin();
4009 it != vsd.end();
4010 ++it, ++i)
4011 {
4012 const VirtualSystemDescriptionEntry *vsde = (*it);
4013
4014 sfaTypes[i] = vsde->type;
4015
4016 Bstr bstr = vsde->strRef;
4017 bstr.cloneTo(&sfaRefs[i]);
4018
4019 bstr = vsde->strOvf;
4020 bstr.cloneTo(&sfaOrigValues[i]);
4021
4022 bstr = vsde->strVbox;
4023 bstr.cloneTo(&sfaVboxValues[i]);
4024
4025 bstr = vsde->strExtraConfig;
4026 bstr.cloneTo(&sfaExtraConfigValues[i]);
4027 }
4028
4029 sfaTypes.detachTo(ComSafeArrayOutArg(aTypes));
4030 sfaRefs.detachTo(ComSafeArrayOutArg(aRefs));
4031 sfaOrigValues.detachTo(ComSafeArrayOutArg(aOrigValues));
4032 sfaVboxValues.detachTo(ComSafeArrayOutArg(aVboxValues));
4033 sfaExtraConfigValues.detachTo(ComSafeArrayOutArg(aExtraConfigValues));
4034
4035 return S_OK;
4036}
4037
4038/**
4039 * Public method implementation.
4040 * @return
4041 */
4042STDMETHODIMP VirtualSystemDescription::GetValuesByType(VirtualSystemDescriptionType_T aType,
4043 VirtualSystemDescriptionValueType_T aWhich,
4044 ComSafeArrayOut(BSTR, aValues))
4045{
4046 if (ComSafeArrayOutIsNull(aValues))
4047 return E_POINTER;
4048
4049 AutoCaller autoCaller(this);
4050 CheckComRCReturnRC(autoCaller.rc());
4051
4052 AutoReadLock alock(this);
4053
4054 std::list<VirtualSystemDescriptionEntry*> vsd = findByType (aType);
4055 com::SafeArray<BSTR> sfaValues((ULONG)vsd.size());
4056
4057 list<VirtualSystemDescriptionEntry*>::const_iterator it;
4058 size_t i = 0;
4059 for (it = vsd.begin();
4060 it != vsd.end();
4061 ++it, ++i)
4062 {
4063 const VirtualSystemDescriptionEntry *vsde = (*it);
4064
4065 Bstr bstr;
4066 switch (aWhich)
4067 {
4068 case VirtualSystemDescriptionValueType_Reference: bstr = vsde->strRef; break;
4069 case VirtualSystemDescriptionValueType_Original: bstr = vsde->strOvf; break;
4070 case VirtualSystemDescriptionValueType_Auto: bstr = vsde->strVbox; break;
4071 case VirtualSystemDescriptionValueType_ExtraConfig: bstr = vsde->strExtraConfig; break;
4072 }
4073
4074 bstr.cloneTo(&sfaValues[i]);
4075 }
4076
4077 sfaValues.detachTo(ComSafeArrayOutArg(aValues));
4078
4079 return S_OK;
4080}
4081
4082/**
4083 * Public method implementation.
4084 * @return
4085 */
4086STDMETHODIMP VirtualSystemDescription::SetFinalValues(ComSafeArrayIn(BOOL, aEnabled),
4087 ComSafeArrayIn(IN_BSTR, argVboxValues),
4088 ComSafeArrayIn(IN_BSTR, argExtraConfigValues))
4089{
4090#ifndef RT_OS_WINDOWS
4091 NOREF(aEnabledSize);
4092#endif /* RT_OS_WINDOWS */
4093
4094 CheckComArgSafeArrayNotNull(aEnabled);
4095 CheckComArgSafeArrayNotNull(argVboxValues);
4096 CheckComArgSafeArrayNotNull(argExtraConfigValues);
4097
4098 AutoCaller autoCaller(this);
4099 CheckComRCReturnRC(autoCaller.rc());
4100
4101 AutoWriteLock alock(this);
4102
4103 com::SafeArray<BOOL> sfaEnabled(ComSafeArrayInArg(aEnabled));
4104 com::SafeArray<IN_BSTR> sfaVboxValues(ComSafeArrayInArg(argVboxValues));
4105 com::SafeArray<IN_BSTR> sfaExtraConfigValues(ComSafeArrayInArg(argExtraConfigValues));
4106
4107 if ( (sfaEnabled.size() != m->llDescriptions.size())
4108 || (sfaVboxValues.size() != m->llDescriptions.size())
4109 || (sfaExtraConfigValues.size() != m->llDescriptions.size())
4110 )
4111 return E_INVALIDARG;
4112
4113 list<VirtualSystemDescriptionEntry>::iterator it;
4114 size_t i = 0;
4115 for (it = m->llDescriptions.begin();
4116 it != m->llDescriptions.end();
4117 ++it, ++i)
4118 {
4119 VirtualSystemDescriptionEntry& vsde = *it;
4120
4121 if (sfaEnabled[i])
4122 {
4123 vsde.strVbox = sfaVboxValues[i];
4124 vsde.strExtraConfig = sfaExtraConfigValues[i];
4125 }
4126 else
4127 vsde.type = VirtualSystemDescriptionType_Ignore;
4128 }
4129
4130 return S_OK;
4131}
4132
4133/**
4134 * Public method implementation.
4135 * @return
4136 */
4137STDMETHODIMP VirtualSystemDescription::AddDescription(VirtualSystemDescriptionType_T aType,
4138 IN_BSTR aVboxValue,
4139 IN_BSTR aExtraConfigValue)
4140{
4141 CheckComArgNotNull(aVboxValue);
4142 CheckComArgNotNull(aExtraConfigValue);
4143
4144 AutoCaller autoCaller(this);
4145 CheckComRCReturnRC(autoCaller.rc());
4146
4147 AutoWriteLock alock(this);
4148
4149 addEntry(aType, "", aVboxValue, aVboxValue, 0, aExtraConfigValue);
4150
4151 return S_OK;
4152}
4153
4154/**
4155 * Internal method; adds a new description item to the member list.
4156 * @param aType Type of description for the new item.
4157 * @param strRef Reference item; only used with hard disk controllers.
4158 * @param aOrigValue Corresponding original value from OVF.
4159 * @param aAutoValue Initial configuration value (can be overridden by caller with setFinalValues).
4160 * @param ulSizeMB Weight for IProgress
4161 * @param strExtraConfig Extra configuration; meaning dependent on type.
4162 */
4163void VirtualSystemDescription::addEntry(VirtualSystemDescriptionType_T aType,
4164 const Utf8Str &strRef,
4165 const Utf8Str &aOrigValue,
4166 const Utf8Str &aAutoValue,
4167 uint32_t ulSizeMB,
4168 const Utf8Str &strExtraConfig /*= ""*/)
4169{
4170 VirtualSystemDescriptionEntry vsde;
4171 vsde.ulIndex = (uint32_t)m->llDescriptions.size(); // each entry gets an index so the client side can reference them
4172 vsde.type = aType;
4173 vsde.strRef = strRef;
4174 vsde.strOvf = aOrigValue;
4175 vsde.strVbox = aAutoValue;
4176 vsde.strExtraConfig = strExtraConfig;
4177 vsde.ulSizeMB = ulSizeMB;
4178
4179 m->llDescriptions.push_back(vsde);
4180}
4181
4182/**
4183 * Private method; returns a list of description items containing all the items from the member
4184 * description items of this virtual system that match the given type.
4185 * @param aType
4186 * @return
4187 */
4188std::list<VirtualSystemDescriptionEntry*> VirtualSystemDescription::findByType(VirtualSystemDescriptionType_T aType)
4189{
4190 std::list<VirtualSystemDescriptionEntry*> vsd;
4191
4192 list<VirtualSystemDescriptionEntry>::iterator it;
4193 for (it = m->llDescriptions.begin();
4194 it != m->llDescriptions.end();
4195 ++it)
4196 {
4197 if (it->type == aType)
4198 vsd.push_back(&(*it));
4199 }
4200
4201 return vsd;
4202}
4203
4204/**
4205 * Private method; looks thru the member hardware items for the IDE, SATA, or SCSI controller with
4206 * the given reference ID. Useful when needing the controller for a particular
4207 * virtual disk.
4208 * @param id
4209 * @return
4210 */
4211const VirtualSystemDescriptionEntry* VirtualSystemDescription::findControllerFromID(uint32_t id)
4212{
4213 Utf8Str strRef = Utf8StrFmt("%RI32", id);
4214 list<VirtualSystemDescriptionEntry>::const_iterator it;
4215 for (it = m->llDescriptions.begin();
4216 it != m->llDescriptions.end();
4217 ++it)
4218 {
4219 const VirtualSystemDescriptionEntry &d = *it;
4220 switch (d.type)
4221 {
4222 case VirtualSystemDescriptionType_HardDiskControllerIDE:
4223 case VirtualSystemDescriptionType_HardDiskControllerSATA:
4224 case VirtualSystemDescriptionType_HardDiskControllerSCSI:
4225 if (d.strRef == strRef)
4226 return &d;
4227 break;
4228 }
4229 }
4230
4231 return NULL;
4232}
4233
4234////////////////////////////////////////////////////////////////////////////////
4235//
4236// IMachine public methods
4237//
4238////////////////////////////////////////////////////////////////////////////////
4239
4240// This code is here so we won't have to include the appliance headers in the
4241// IMachine implementation, and we also need to access private appliance data.
4242
4243/**
4244* Public method implementation.
4245* @param appliance
4246* @return
4247*/
4248
4249STDMETHODIMP Machine::Export(IAppliance *aAppliance, IVirtualSystemDescription **aDescription)
4250{
4251 HRESULT rc = S_OK;
4252
4253 if (!aAppliance)
4254 return E_POINTER;
4255
4256 AutoCaller autoCaller(this);
4257 CheckComRCReturnRC(autoCaller.rc());
4258
4259 AutoReadLock alock(this);
4260
4261 ComObjPtr<VirtualSystemDescription> pNewDesc;
4262
4263 try
4264 {
4265 Bstr bstrName;
4266 Bstr bstrDescription;
4267 Bstr bstrGuestOSType;
4268 uint32_t cCPUs;
4269 uint32_t ulMemSizeMB;
4270 BOOL fDVDEnabled;
4271 BOOL fFloppyEnabled;
4272 BOOL fUSBEnabled;
4273 BOOL fAudioEnabled;
4274 AudioControllerType_T audioController;
4275
4276 ComPtr<IUSBController> pUsbController;
4277 ComPtr<IAudioAdapter> pAudioAdapter;
4278
4279 // get name
4280 bstrName = mUserData->mName;
4281 // get description
4282 bstrDescription = mUserData->mDescription;
4283 // get guest OS
4284 bstrGuestOSType = mUserData->mOSTypeId;
4285 // CPU count
4286 cCPUs = mHWData->mCPUCount;
4287 // memory size in MB
4288 ulMemSizeMB = mHWData->mMemorySize;
4289 // VRAM size?
4290 // BIOS settings?
4291 // 3D acceleration enabled?
4292 // hardware virtualization enabled?
4293 // nested paging enabled?
4294 // HWVirtExVPIDEnabled?
4295 // PAEEnabled?
4296 // snapshotFolder?
4297 // VRDPServer?
4298
4299 // floppy
4300 rc = mFloppyDrive->COMGETTER(Enabled)(&fFloppyEnabled);
4301 if (FAILED(rc)) throw rc;
4302
4303 // CD-ROM ?!?
4304 // ComPtr<IDVDDrive> pDVDDrive;
4305 fDVDEnabled = 1;
4306
4307 // this is more tricky so use the COM method
4308 rc = COMGETTER(USBController)(pUsbController.asOutParam());
4309 if (FAILED(rc))
4310 fUSBEnabled = false;
4311 else
4312 rc = pUsbController->COMGETTER(Enabled)(&fUSBEnabled);
4313
4314 pAudioAdapter = mAudioAdapter;
4315 rc = pAudioAdapter->COMGETTER(Enabled)(&fAudioEnabled);
4316 if (FAILED(rc)) throw rc;
4317 rc = pAudioAdapter->COMGETTER(AudioController)(&audioController);
4318 if (FAILED(rc)) throw rc;
4319
4320 // create a new virtual system
4321 rc = pNewDesc.createObject();
4322 CheckComRCThrowRC(rc);
4323 rc = pNewDesc->init();
4324 CheckComRCThrowRC(rc);
4325
4326 /* Guest OS type */
4327 Utf8Str strOsTypeVBox(bstrGuestOSType);
4328 CIMOSType_T cim = convertVBoxOSType2CIMOSType(strOsTypeVBox.c_str());
4329 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
4330 "",
4331 Utf8StrFmt("%RI32", cim),
4332 strOsTypeVBox);
4333
4334 /* VM name */
4335 Utf8Str strVMName(bstrName);
4336 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
4337 "",
4338 strVMName,
4339 strVMName);
4340
4341 // description
4342 Utf8Str strDescription(bstrDescription);
4343 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
4344 "",
4345 strDescription,
4346 strDescription);
4347
4348 /* CPU count*/
4349 Utf8Str strCpuCount = Utf8StrFmt("%RI32", cCPUs);
4350 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
4351 "",
4352 strCpuCount,
4353 strCpuCount);
4354
4355 /* Memory */
4356 Utf8Str strMemory = Utf8StrFmt("%RI32", (uint64_t)ulMemSizeMB * _1M);
4357 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
4358 "",
4359 strMemory,
4360 strMemory);
4361
4362 int32_t lIDEControllerIndex = 0;
4363 int32_t lSATAControllerIndex = 0;
4364 int32_t lSCSIControllerIndex = 0;
4365
4366// <const name="HardDiskControllerIDE" value="6" />
4367 ComPtr<IStorageController> pController;
4368 rc = GetStorageControllerByName(Bstr("IDE"), pController.asOutParam());
4369 if (FAILED(rc)) throw rc;
4370 Utf8Str strVbox;
4371 StorageControllerType_T ctlr;
4372 rc = pController->COMGETTER(ControllerType)(&ctlr);
4373 if (FAILED(rc)) throw rc;
4374 switch(ctlr)
4375 {
4376 case StorageControllerType_PIIX3: strVbox = "PIIX3"; break;
4377 case StorageControllerType_PIIX4: strVbox = "PIIX4"; break;
4378 case StorageControllerType_ICH6: strVbox = "ICH6"; break;
4379 }
4380
4381 if (strVbox.length())
4382 {
4383 lIDEControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4384 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
4385 Utf8StrFmt("%d", lIDEControllerIndex),
4386 strVbox,
4387 strVbox);
4388 }
4389
4390#ifdef VBOX_WITH_AHCI
4391// <const name="HardDiskControllerSATA" value="7" />
4392 rc = GetStorageControllerByName(Bstr("SATA"), pController.asOutParam());
4393 if (SUCCEEDED(rc))
4394 {
4395 strVbox = "AHCI";
4396 lSATAControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4397 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
4398 Utf8StrFmt("%d", lSATAControllerIndex),
4399 strVbox,
4400 strVbox);
4401 }
4402#endif // VBOX_WITH_AHCI
4403
4404#ifdef VBOX_WITH_LSILOGIC
4405// <const name="HardDiskControllerSCSI" value="8" />
4406 rc = GetStorageControllerByName(Bstr("SCSI"), pController.asOutParam());
4407 if (SUCCEEDED(rc))
4408 {
4409 rc = pController->COMGETTER(ControllerType)(&ctlr);
4410 if (SUCCEEDED(rc))
4411 {
4412 strVbox = "LsiLogic"; // the default in VBox
4413 switch(ctlr)
4414 {
4415 case StorageControllerType_LsiLogic: strVbox = "LsiLogic"; break;
4416 case StorageControllerType_BusLogic: strVbox = "BusLogic"; break;
4417 }
4418 lSCSIControllerIndex = (int32_t)pNewDesc->m->llDescriptions.size();
4419 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
4420 Utf8StrFmt("%d", lSCSIControllerIndex),
4421 strVbox,
4422 strVbox);
4423 }
4424 else
4425 throw rc;
4426 }
4427#endif // VBOX_WITH_LSILOGIC
4428
4429// <const name="HardDiskImage" value="9" />
4430 HDData::AttachmentList::iterator itA;
4431 for (itA = mHDData->mAttachments.begin();
4432 itA != mHDData->mAttachments.end();
4433 ++itA)
4434 {
4435 ComObjPtr<HardDiskAttachment> pHDA = *itA;
4436
4437 // the attachment's data
4438 ComPtr<IHardDisk> pHardDisk;
4439 ComPtr<IStorageController> ctl;
4440 Bstr controllerName;
4441
4442 rc = pHDA->COMGETTER(Controller)(controllerName.asOutParam());
4443 if (FAILED(rc)) throw rc;
4444
4445 rc = GetStorageControllerByName(controllerName, ctl.asOutParam());
4446 if (FAILED(rc)) throw rc;
4447
4448 StorageBus_T storageBus;
4449 LONG lChannel;
4450 LONG lDevice;
4451
4452 rc = ctl->COMGETTER(Bus)(&storageBus);
4453 if (FAILED(rc)) throw rc;
4454
4455 rc = pHDA->COMGETTER(HardDisk)(pHardDisk.asOutParam());
4456 if (FAILED(rc)) throw rc;
4457
4458 rc = pHDA->COMGETTER(Port)(&lChannel);
4459 if (FAILED(rc)) throw rc;
4460
4461 rc = pHDA->COMGETTER(Device)(&lDevice);
4462 if (FAILED(rc)) throw rc;
4463
4464 Bstr bstrLocation;
4465 rc = pHardDisk->COMGETTER(Location)(bstrLocation.asOutParam());
4466 if (FAILED(rc)) throw rc;
4467 Bstr bstrName;
4468 rc = pHardDisk->COMGETTER(Name)(bstrName.asOutParam());
4469 if (FAILED(rc)) throw rc;
4470
4471 // force reading state, or else size will be returned as 0
4472 MediaState_T ms;
4473 rc = pHardDisk->COMGETTER(State)(&ms);
4474 if (FAILED(rc)) throw rc;
4475
4476 ULONG64 ullSize;
4477 rc = pHardDisk->COMGETTER(Size)(&ullSize);
4478 if (FAILED(rc)) throw rc;
4479
4480 // and how this translates to the virtual system
4481 int32_t lControllerVsys = 0;
4482 LONG lChannelVsys;
4483
4484 switch (storageBus)
4485 {
4486 case StorageBus_IDE:
4487 // this is the exact reverse to what we're doing in Appliance::taskThreadImportMachines,
4488 // and it must be updated when that is changed!
4489
4490 if (lChannel == 0 && lDevice == 0) // primary master
4491 lChannelVsys = 0;
4492 else if (lChannel == 0 && lDevice == 1) // primary slave
4493 lChannelVsys = 1;
4494 else if (lChannel == 1 && lDevice == 1) // secondary slave; secondary master is always CDROM
4495 lChannelVsys = 2;
4496 else
4497 throw setError(VBOX_E_NOT_SUPPORTED,
4498 tr("Cannot handle hard disk attachment: channel is %d, device is %d"), lChannel, lDevice);
4499
4500 lControllerVsys = lIDEControllerIndex;
4501 break;
4502
4503 case StorageBus_SATA:
4504 lChannelVsys = lChannel; // should be between 0 and 29
4505 lControllerVsys = lSATAControllerIndex;
4506 break;
4507
4508 case StorageBus_SCSI:
4509 lChannelVsys = lChannel; // should be between 0 and 15
4510 lControllerVsys = lSCSIControllerIndex;
4511 break;
4512
4513 default:
4514 throw setError(VBOX_E_NOT_SUPPORTED,
4515 tr("Cannot handle hard disk attachment: storageBus is %d, channel is %d, device is %d"), storageBus, lChannel, lDevice);
4516 break;
4517 }
4518
4519 Utf8Str strTargetVmdkName(bstrName);
4520 strTargetVmdkName.stripExt();
4521 strTargetVmdkName.append(".vmdk");
4522
4523 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
4524 strTargetVmdkName, // disk ID: let's use the name
4525 strTargetVmdkName, // OVF value:
4526 Utf8Str(bstrLocation), // vbox value: media path
4527 (uint32_t)(ullSize / _1M),
4528 Utf8StrFmt("controller=%RI32;channel=%RI32", lControllerVsys, lChannelVsys));
4529 }
4530
4531 /* Floppy Drive */
4532 if (fFloppyEnabled)
4533 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
4534
4535 /* CD Drive */
4536 if (fDVDEnabled)
4537 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
4538
4539// <const name="NetworkAdapter" />
4540 size_t a;
4541 for (a = 0;
4542 a < SchemaDefs::NetworkAdapterCount;
4543 ++a)
4544 {
4545 ComPtr<INetworkAdapter> pNetworkAdapter;
4546 BOOL fEnabled;
4547 NetworkAdapterType_T adapterType;
4548 NetworkAttachmentType_T attachmentType;
4549
4550 rc = GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
4551 if (FAILED(rc)) throw rc;
4552 /* Enable the network card & set the adapter type */
4553 rc = pNetworkAdapter->COMGETTER(Enabled)(&fEnabled);
4554 if (FAILED(rc)) throw rc;
4555
4556 if (fEnabled)
4557 {
4558 Utf8Str strAttachmentType;
4559
4560 rc = pNetworkAdapter->COMGETTER(AdapterType)(&adapterType);
4561 if (FAILED(rc)) throw rc;
4562
4563 rc = pNetworkAdapter->COMGETTER(AttachmentType)(&attachmentType);
4564 if (FAILED(rc)) throw rc;
4565
4566 switch (attachmentType)
4567 {
4568 case NetworkAttachmentType_Null:
4569 strAttachmentType = "Null";
4570 break;
4571
4572 case NetworkAttachmentType_NAT:
4573 strAttachmentType = "NAT";
4574 break;
4575
4576 case NetworkAttachmentType_Bridged:
4577 strAttachmentType = "Bridged";
4578 break;
4579
4580 case NetworkAttachmentType_Internal:
4581 strAttachmentType = "Internal";
4582 break;
4583
4584 case NetworkAttachmentType_HostOnly:
4585 strAttachmentType = "HostOnly";
4586 break;
4587 }
4588
4589 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
4590 "", // ref
4591 strAttachmentType, // orig
4592 Utf8StrFmt("%RI32", (uint32_t)adapterType), // conf
4593 0,
4594 Utf8StrFmt("type=%s", strAttachmentType.c_str())); // extra conf
4595 }
4596 }
4597
4598// <const name="USBController" />
4599#ifdef VBOX_WITH_USB
4600 if (fUSBEnabled)
4601 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
4602#endif /* VBOX_WITH_USB */
4603
4604// <const name="SoundCard" />
4605 if (fAudioEnabled)
4606 {
4607 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
4608 "",
4609 "ensoniq1371", // this is what OVFTool writes and VMware supports
4610 Utf8StrFmt("%RI32", audioController));
4611 }
4612
4613 // finally, add the virtual system to the appliance
4614 Appliance *pAppliance = static_cast<Appliance*>(aAppliance);
4615 AutoCaller autoCaller1(pAppliance);
4616 CheckComRCReturnRC(autoCaller1.rc());
4617
4618 /* We return the new description to the caller */
4619 ComPtr<IVirtualSystemDescription> copy(pNewDesc);
4620 copy.queryInterfaceTo(aDescription);
4621
4622 AutoWriteLock alock(pAppliance);
4623
4624 pAppliance->m->virtualSystemDescriptions.push_back(pNewDesc);
4625 }
4626 catch(HRESULT arc)
4627 {
4628 rc = arc;
4629 }
4630
4631 return rc;
4632}
4633
4634/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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