VirtualBox

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

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

Main: Bstr makeover (third attempt) -- make Bstr(NULL) and Bstr() behave the same; resulting cleanup; make some more internal methods use Utf8Str instead of Bstr; fix a lot of CheckComArgNotNull??() usage

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