VirtualBox

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

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

Main: new method Medium::RefreshState() which refreshes medium state; make the ::state attribute return the state only without refreshing

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