VirtualBox

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

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

Main: cleanup: get rid of VirtualBoxBaseProto, move AutoCaller*/*Span* classes out of VirtualBoxBaseProto class scope and into separate header; move CombinedProgress into separate header (it's only used by Console any more)

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