VirtualBox

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

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

OVF: fix broken floppy and cd-rom import

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