VirtualBox

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

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

OVF: fix import and export of floppy and DVD attachments broken by medium change; fix export progress bars for media with differencing images

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