VirtualBox

source: vbox/trunk/src/VBox/Main/ApplianceImplImport.cpp@ 29924

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

IPRT: added progress callback support to SHA1 digest calculation and manifest verification

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 94.9 KB
Line 
1/* $Id: ApplianceImplImport.cpp 29901 2010-05-31 12:53:25Z vboxsync $ */
2/** @file
3 *
4 * IAppliance and IVirtualSystem COM class implementations.
5 */
6
7/*
8 * Copyright (C) 2008-2010 Oracle Corporation
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
19#include <iprt/path.h>
20#include <iprt/dir.h>
21#include <iprt/file.h>
22#include <iprt/s3.h>
23#include <iprt/sha.h>
24#include <iprt/manifest.h>
25
26#include <VBox/com/array.h>
27
28#include "ApplianceImpl.h"
29#include "VirtualBoxImpl.h"
30#include "GuestOSTypeImpl.h"
31#include "ProgressImpl.h"
32#include "MachineImpl.h"
33
34#include "AutoCaller.h"
35#include "Logging.h"
36
37#include "ApplianceImplPrivate.h"
38
39#include <VBox/param.h>
40#include <VBox/version.h>
41#include <VBox/settings.h>
42
43using namespace std;
44
45////////////////////////////////////////////////////////////////////////////////
46//
47// IAppliance public methods
48//
49////////////////////////////////////////////////////////////////////////////////
50
51/**
52 * Public method implementation. This opens the OVF with ovfreader.cpp.
53 * Thread implementation is in Appliance::readImpl().
54 *
55 * @param path
56 * @return
57 */
58STDMETHODIMP Appliance::Read(IN_BSTR path, IProgress **aProgress)
59{
60 if (!path) return E_POINTER;
61 CheckComArgOutPointerValid(aProgress);
62
63 AutoCaller autoCaller(this);
64 if (FAILED(autoCaller.rc())) return autoCaller.rc();
65
66 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
67
68 if (!isApplianceIdle())
69 return E_ACCESSDENIED;
70
71 if (m->pReader)
72 {
73 delete m->pReader;
74 m->pReader = NULL;
75 }
76
77 // see if we can handle this file; for now we insist it has an ".ovf" extension
78 Utf8Str strPath (path);
79 if (!strPath.endsWith(".ovf", Utf8Str::CaseInsensitive))
80 return setError(VBOX_E_FILE_ERROR,
81 tr("Appliance file must have .ovf extension"));
82
83 ComObjPtr<Progress> progress;
84 HRESULT rc = S_OK;
85 try
86 {
87 /* Parse all necessary info out of the URI */
88 parseURI(strPath, m->locInfo);
89 rc = readImpl(m->locInfo, progress);
90 }
91 catch (HRESULT aRC)
92 {
93 rc = aRC;
94 }
95
96 if (SUCCEEDED(rc))
97 /* Return progress to the caller */
98 progress.queryInterfaceTo(aProgress);
99
100 return S_OK;
101}
102
103/**
104 * Public method implementation. This looks at the output of ovfreader.cpp and creates
105 * VirtualSystemDescription instances.
106 * @return
107 */
108STDMETHODIMP Appliance::Interpret()
109{
110 // @todo:
111 // - don't use COM methods but the methods directly (faster, but needs appropriate locking of that objects itself (s. HardDisk))
112 // - Appropriate handle errors like not supported file formats
113 AutoCaller autoCaller(this);
114 if (FAILED(autoCaller.rc())) return autoCaller.rc();
115
116 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
117
118 if (!isApplianceIdle())
119 return E_ACCESSDENIED;
120
121 HRESULT rc = S_OK;
122
123 /* Clear any previous virtual system descriptions */
124 m->virtualSystemDescriptions.clear();
125
126 Utf8Str strDefaultHardDiskFolder;
127 rc = getDefaultHardDiskFolder(strDefaultHardDiskFolder);
128 if (FAILED(rc)) return rc;
129
130 if (!m->pReader)
131 return setError(E_FAIL,
132 tr("Cannot interpret appliance without reading it first (call read() before interpret())"));
133
134 // Change the appliance state so we can safely leave the lock while doing time-consuming
135 // disk imports; also the below method calls do all kinds of locking which conflicts with
136 // the appliance object lock
137 m->state = Data::ApplianceImporting;
138 alock.release();
139
140 /* Try/catch so we can clean up on error */
141 try
142 {
143 list<ovf::VirtualSystem>::const_iterator it;
144 /* Iterate through all virtual systems */
145 for (it = m->pReader->m_llVirtualSystems.begin();
146 it != m->pReader->m_llVirtualSystems.end();
147 ++it)
148 {
149 const ovf::VirtualSystem &vsysThis = *it;
150
151 ComObjPtr<VirtualSystemDescription> pNewDesc;
152 rc = pNewDesc.createObject();
153 if (FAILED(rc)) throw rc;
154 rc = pNewDesc->init();
155 if (FAILED(rc)) throw rc;
156
157 // if the virtual system in OVF had a <vbox:Machine> element, have the
158 // VirtualBox settings code parse that XML now
159 if (vsysThis.pelmVboxMachine)
160 pNewDesc->importVboxMachineXML(*vsysThis.pelmVboxMachine);
161
162 /* Guest OS type */
163 Utf8Str strOsTypeVBox,
164 strCIMOSType = Utf8StrFmt("%RI32", (uint32_t)vsysThis.cimos);
165 convertCIMOSType2VBoxOSType(strOsTypeVBox, vsysThis.cimos, vsysThis.strCimosDesc);
166 pNewDesc->addEntry(VirtualSystemDescriptionType_OS,
167 "",
168 strCIMOSType,
169 strOsTypeVBox);
170
171 /* VM name */
172 /* If the there isn't any name specified create a default one out of
173 * the OS type */
174 Utf8Str nameVBox = vsysThis.strName;
175 if (nameVBox.isEmpty())
176 nameVBox = strOsTypeVBox;
177 searchUniqueVMName(nameVBox);
178 pNewDesc->addEntry(VirtualSystemDescriptionType_Name,
179 "",
180 vsysThis.strName,
181 nameVBox);
182
183 /* VM Product */
184 if (!vsysThis.strProduct.isEmpty())
185 pNewDesc->addEntry(VirtualSystemDescriptionType_Product,
186 "",
187 vsysThis.strProduct,
188 vsysThis.strProduct);
189
190 /* VM Vendor */
191 if (!vsysThis.strVendor.isEmpty())
192 pNewDesc->addEntry(VirtualSystemDescriptionType_Vendor,
193 "",
194 vsysThis.strVendor,
195 vsysThis.strVendor);
196
197 /* VM Version */
198 if (!vsysThis.strVersion.isEmpty())
199 pNewDesc->addEntry(VirtualSystemDescriptionType_Version,
200 "",
201 vsysThis.strVersion,
202 vsysThis.strVersion);
203
204 /* VM ProductUrl */
205 if (!vsysThis.strProductUrl.isEmpty())
206 pNewDesc->addEntry(VirtualSystemDescriptionType_ProductUrl,
207 "",
208 vsysThis.strProductUrl,
209 vsysThis.strProductUrl);
210
211 /* VM VendorUrl */
212 if (!vsysThis.strVendorUrl.isEmpty())
213 pNewDesc->addEntry(VirtualSystemDescriptionType_VendorUrl,
214 "",
215 vsysThis.strVendorUrl,
216 vsysThis.strVendorUrl);
217
218 /* VM description */
219 if (!vsysThis.strDescription.isEmpty())
220 pNewDesc->addEntry(VirtualSystemDescriptionType_Description,
221 "",
222 vsysThis.strDescription,
223 vsysThis.strDescription);
224
225 /* VM license */
226 if (!vsysThis.strLicenseText.isEmpty())
227 pNewDesc->addEntry(VirtualSystemDescriptionType_License,
228 "",
229 vsysThis.strLicenseText,
230 vsysThis.strLicenseText);
231
232 /* Now that we know the OS type, get our internal defaults based on that. */
233 ComPtr<IGuestOSType> pGuestOSType;
234 rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), pGuestOSType.asOutParam());
235 if (FAILED(rc)) throw rc;
236
237 /* CPU count */
238 ULONG cpuCountVBox = vsysThis.cCPUs;
239 /* Check for the constrains */
240 if (cpuCountVBox > SchemaDefs::MaxCPUCount)
241 {
242 addWarning(tr("The virtual system \"%s\" claims support for %u CPU's, but VirtualBox has support for max %u CPU's only."),
243 vsysThis.strName.c_str(), cpuCountVBox, SchemaDefs::MaxCPUCount);
244 cpuCountVBox = SchemaDefs::MaxCPUCount;
245 }
246 if (vsysThis.cCPUs == 0)
247 cpuCountVBox = 1;
248 pNewDesc->addEntry(VirtualSystemDescriptionType_CPU,
249 "",
250 Utf8StrFmt("%RI32", (uint32_t)vsysThis.cCPUs),
251 Utf8StrFmt("%RI32", (uint32_t)cpuCountVBox));
252
253 /* RAM */
254 uint64_t ullMemSizeVBox = vsysThis.ullMemorySize / _1M;
255 /* Check for the constrains */
256 if ( ullMemSizeVBox != 0
257 && ( ullMemSizeVBox < MM_RAM_MIN_IN_MB
258 || ullMemSizeVBox > MM_RAM_MAX_IN_MB
259 )
260 )
261 {
262 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."),
263 vsysThis.strName.c_str(), ullMemSizeVBox, MM_RAM_MIN_IN_MB, MM_RAM_MAX_IN_MB);
264 ullMemSizeVBox = RT_MIN(RT_MAX(ullMemSizeVBox, MM_RAM_MIN_IN_MB), MM_RAM_MAX_IN_MB);
265 }
266 if (vsysThis.ullMemorySize == 0)
267 {
268 /* If the RAM of the OVF is zero, use our predefined values */
269 ULONG memSizeVBox2;
270 rc = pGuestOSType->COMGETTER(RecommendedRAM)(&memSizeVBox2);
271 if (FAILED(rc)) throw rc;
272 /* VBox stores that in MByte */
273 ullMemSizeVBox = (uint64_t)memSizeVBox2;
274 }
275 pNewDesc->addEntry(VirtualSystemDescriptionType_Memory,
276 "",
277 Utf8StrFmt("%RI64", (uint64_t)vsysThis.ullMemorySize),
278 Utf8StrFmt("%RI64", (uint64_t)ullMemSizeVBox));
279
280 /* Audio */
281 if (!vsysThis.strSoundCardType.isEmpty())
282 /* Currently we set the AC97 always.
283 @todo: figure out the hardware which could be possible */
284 pNewDesc->addEntry(VirtualSystemDescriptionType_SoundCard,
285 "",
286 vsysThis.strSoundCardType,
287 Utf8StrFmt("%RI32", (uint32_t)AudioControllerType_AC97));
288
289#ifdef VBOX_WITH_USB
290 /* USB Controller */
291 if (vsysThis.fHasUsbController)
292 pNewDesc->addEntry(VirtualSystemDescriptionType_USBController, "", "", "");
293#endif /* VBOX_WITH_USB */
294
295 /* Network Controller */
296 size_t cEthernetAdapters = vsysThis.llEthernetAdapters.size();
297 if (cEthernetAdapters > 0)
298 {
299 /* Check for the constrains */
300 if (cEthernetAdapters > SchemaDefs::NetworkAdapterCount)
301 addWarning(tr("The virtual system \"%s\" claims support for %zu network adapters, but VirtualBox has support for max %u network adapter only."),
302 vsysThis.strName.c_str(), cEthernetAdapters, SchemaDefs::NetworkAdapterCount);
303
304 /* Get the default network adapter type for the selected guest OS */
305 NetworkAdapterType_T defaultAdapterVBox = NetworkAdapterType_Am79C970A;
306 rc = pGuestOSType->COMGETTER(AdapterType)(&defaultAdapterVBox);
307 if (FAILED(rc)) throw rc;
308
309 ovf::EthernetAdaptersList::const_iterator itEA;
310 /* Iterate through all abstract networks. We support 8 network
311 * adapters at the maximum, so the first 8 will be added only. */
312 size_t a = 0;
313 for (itEA = vsysThis.llEthernetAdapters.begin();
314 itEA != vsysThis.llEthernetAdapters.end() && a < SchemaDefs::NetworkAdapterCount;
315 ++itEA, ++a)
316 {
317 const ovf::EthernetAdapter &ea = *itEA; // logical network to connect to
318 Utf8Str strNetwork = ea.strNetworkName;
319 // make sure it's one of these two
320 if ( (strNetwork.compare("Null", Utf8Str::CaseInsensitive))
321 && (strNetwork.compare("NAT", Utf8Str::CaseInsensitive))
322 && (strNetwork.compare("Bridged", Utf8Str::CaseInsensitive))
323 && (strNetwork.compare("Internal", Utf8Str::CaseInsensitive))
324 && (strNetwork.compare("HostOnly", Utf8Str::CaseInsensitive))
325 )
326 strNetwork = "Bridged"; // VMware assumes this is the default apparently
327
328 /* Figure out the hardware type */
329 NetworkAdapterType_T nwAdapterVBox = defaultAdapterVBox;
330 if (!ea.strAdapterType.compare("PCNet32", Utf8Str::CaseInsensitive))
331 {
332 /* If the default adapter is already one of the two
333 * PCNet adapters use the default one. If not use the
334 * Am79C970A as fallback. */
335 if (!(defaultAdapterVBox == NetworkAdapterType_Am79C970A ||
336 defaultAdapterVBox == NetworkAdapterType_Am79C973))
337 nwAdapterVBox = NetworkAdapterType_Am79C970A;
338 }
339#ifdef VBOX_WITH_E1000
340 /* VMWare accidentally write this with VirtualCenter 3.5,
341 so make sure in this case always to use the VMWare one */
342 else if (!ea.strAdapterType.compare("E10000", Utf8Str::CaseInsensitive))
343 nwAdapterVBox = NetworkAdapterType_I82545EM;
344 else if (!ea.strAdapterType.compare("E1000", Utf8Str::CaseInsensitive))
345 {
346 /* Check if this OVF was written by VirtualBox */
347 if (Utf8Str(vsysThis.strVirtualSystemType).contains("virtualbox", Utf8Str::CaseInsensitive))
348 {
349 /* If the default adapter is already one of the three
350 * E1000 adapters use the default one. If not use the
351 * I82545EM as fallback. */
352 if (!(defaultAdapterVBox == NetworkAdapterType_I82540EM ||
353 defaultAdapterVBox == NetworkAdapterType_I82543GC ||
354 defaultAdapterVBox == NetworkAdapterType_I82545EM))
355 nwAdapterVBox = NetworkAdapterType_I82540EM;
356 }
357 else
358 /* Always use this one since it's what VMware uses */
359 nwAdapterVBox = NetworkAdapterType_I82545EM;
360 }
361#endif /* VBOX_WITH_E1000 */
362
363 pNewDesc->addEntry(VirtualSystemDescriptionType_NetworkAdapter,
364 "", // ref
365 ea.strNetworkName, // orig
366 Utf8StrFmt("%RI32", (uint32_t)nwAdapterVBox), // conf
367 0,
368 Utf8StrFmt("type=%s", strNetwork.c_str())); // extra conf
369 }
370 }
371
372 /* Floppy Drive */
373 if (vsysThis.fHasFloppyDrive)
374 pNewDesc->addEntry(VirtualSystemDescriptionType_Floppy, "", "", "");
375
376 /* CD Drive */
377 if (vsysThis.fHasCdromDrive)
378 pNewDesc->addEntry(VirtualSystemDescriptionType_CDROM, "", "", "");
379
380 /* Hard disk Controller */
381 uint16_t cIDEused = 0;
382 uint16_t cSATAused = 0; NOREF(cSATAused);
383 uint16_t cSCSIused = 0; NOREF(cSCSIused);
384 ovf::ControllersMap::const_iterator hdcIt;
385 /* Iterate through all hard disk controllers */
386 for (hdcIt = vsysThis.mapControllers.begin();
387 hdcIt != vsysThis.mapControllers.end();
388 ++hdcIt)
389 {
390 const ovf::HardDiskController &hdc = hdcIt->second;
391 Utf8Str strControllerID = Utf8StrFmt("%RI32", (uint32_t)hdc.idController);
392
393 switch (hdc.system)
394 {
395 case ovf::HardDiskController::IDE:
396 /* Check for the constrains */
397 if (cIDEused < 4)
398 {
399 // @todo: figure out the IDE types
400 /* Use PIIX4 as default */
401 Utf8Str strType = "PIIX4";
402 if (!hdc.strControllerType.compare("PIIX3", Utf8Str::CaseInsensitive))
403 strType = "PIIX3";
404 else if (!hdc.strControllerType.compare("ICH6", Utf8Str::CaseInsensitive))
405 strType = "ICH6";
406 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerIDE,
407 strControllerID, // strRef
408 hdc.strControllerType, // aOvfValue
409 strType); // aVboxValue
410 }
411 else
412 /* Warn only once */
413 if (cIDEused == 2)
414 addWarning(tr("The virtual \"%s\" system requests support for more than two IDE controller channels, but VirtualBox supports only two."),
415 vsysThis.strName.c_str());
416
417 ++cIDEused;
418 break;
419
420 case ovf::HardDiskController::SATA:
421 /* Check for the constrains */
422 if (cSATAused < 1)
423 {
424 // @todo: figure out the SATA types
425 /* We only support a plain AHCI controller, so use them always */
426 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSATA,
427 strControllerID,
428 hdc.strControllerType,
429 "AHCI");
430 }
431 else
432 {
433 /* Warn only once */
434 if (cSATAused == 1)
435 addWarning(tr("The virtual system \"%s\" requests support for more than one SATA controller, but VirtualBox has support for only one"),
436 vsysThis.strName.c_str());
437
438 }
439 ++cSATAused;
440 break;
441
442 case ovf::HardDiskController::SCSI:
443 /* Check for the constrains */
444 if (cSCSIused < 1)
445 {
446 Utf8Str hdcController = "LsiLogic";
447 if (!hdc.strControllerType.compare("lsilogicsas", Utf8Str::CaseInsensitive))
448 hdcController = "LsiLogicSas";
449 else if (!hdc.strControllerType.compare("BusLogic", Utf8Str::CaseInsensitive))
450 hdcController = "BusLogic";
451 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskControllerSCSI,
452 strControllerID,
453 hdc.strControllerType,
454 hdcController);
455 }
456 else
457 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."),
458 vsysThis.strName.c_str(),
459 hdc.strControllerType.c_str(),
460 strControllerID.c_str());
461 ++cSCSIused;
462 break;
463 }
464 }
465
466 /* Hard disks */
467 if (vsysThis.mapVirtualDisks.size() > 0)
468 {
469 ovf::VirtualDisksMap::const_iterator itVD;
470 /* Iterate through all hard disks ()*/
471 for (itVD = vsysThis.mapVirtualDisks.begin();
472 itVD != vsysThis.mapVirtualDisks.end();
473 ++itVD)
474 {
475 const ovf::VirtualDisk &hd = itVD->second;
476 /* Get the associated disk image */
477 const ovf::DiskImage &di = m->pReader->m_mapDisks[hd.strDiskId];
478
479 // @todo:
480 // - figure out all possible vmdk formats we also support
481 // - figure out if there is a url specifier for vhd already
482 // - we need a url specifier for the vdi format
483 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
484 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
485 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
486 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
487 )
488 {
489 /* If the href is empty use the VM name as filename */
490 Utf8Str strFilename = di.strHref;
491 if (!strFilename.length())
492 strFilename = Utf8StrFmt("%s.vmdk", nameVBox.c_str());
493 /* Construct a unique target path */
494 Utf8StrFmt strPath("%s%c%s",
495 strDefaultHardDiskFolder.raw(),
496 RTPATH_DELIMITER,
497 strFilename.c_str());
498 searchUniqueDiskImageFilePath(strPath);
499
500 /* find the description for the hard disk controller
501 * that has the same ID as hd.idController */
502 const VirtualSystemDescriptionEntry *pController;
503 if (!(pController = pNewDesc->findControllerFromID(hd.idController)))
504 throw setError(E_FAIL,
505 tr("Cannot find hard disk controller with OVF instance ID %RI32 to which disk \"%s\" should be attached"),
506 hd.idController,
507 di.strHref.c_str());
508
509 /* controller to attach to, and the bus within that controller */
510 Utf8StrFmt strExtraConfig("controller=%RI16;channel=%RI16",
511 pController->ulIndex,
512 hd.ulAddressOnParent);
513 pNewDesc->addEntry(VirtualSystemDescriptionType_HardDiskImage,
514 hd.strDiskId,
515 di.strHref,
516 strPath,
517 di.ulSuggestedSizeMB,
518 strExtraConfig);
519 }
520 else
521 throw setError(VBOX_E_FILE_ERROR,
522 tr("Unsupported format for virtual disk image in OVF: \"%s\"", di.strFormat.c_str()));
523 }
524 }
525
526 m->virtualSystemDescriptions.push_back(pNewDesc);
527 }
528 }
529 catch (HRESULT aRC)
530 {
531 /* On error we clear the list & return */
532 m->virtualSystemDescriptions.clear();
533 rc = aRC;
534 }
535
536 // reset the appliance state
537 alock.acquire();
538 m->state = Data::ApplianceIdle;
539
540 return rc;
541}
542
543/**
544 * Public method implementation. This creates one or more new machines according to the
545 * VirtualSystemScription instances created by Appliance::Interpret().
546 * Thread implementation is in Appliance::importImpl().
547 * @param aProgress
548 * @return
549 */
550STDMETHODIMP Appliance::ImportMachines(IProgress **aProgress)
551{
552 CheckComArgOutPointerValid(aProgress);
553
554 AutoCaller autoCaller(this);
555 if (FAILED(autoCaller.rc())) return autoCaller.rc();
556
557 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
558
559 // do not allow entering this method if the appliance is busy reading or writing
560 if (!isApplianceIdle())
561 return E_ACCESSDENIED;
562
563 if (!m->pReader)
564 return setError(E_FAIL,
565 tr("Cannot import machines without reading it first (call read() before importMachines())"));
566
567 ComObjPtr<Progress> progress;
568 HRESULT rc = S_OK;
569 try
570 {
571 rc = importImpl(m->locInfo, progress);
572 }
573 catch (HRESULT aRC)
574 {
575 rc = aRC;
576 }
577
578 if (SUCCEEDED(rc))
579 /* Return progress to the caller */
580 progress.queryInterfaceTo(aProgress);
581
582 return rc;
583}
584
585////////////////////////////////////////////////////////////////////////////////
586//
587// Appliance private methods
588//
589////////////////////////////////////////////////////////////////////////////////
590
591/**
592 * Implementation for reading an OVF. This starts a new thread which will call
593 * Appliance::taskThreadImportOrExport() which will then call readFS() or readS3().
594 * This will then open the OVF with ovfreader.cpp.
595 *
596 * This is in a separate private method because it is used from two locations:
597 *
598 * 1) from the public Appliance::Read().
599 * 2) from Appliance::readS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
600 *
601 * @param aLocInfo
602 * @param aProgress
603 * @return
604 */
605HRESULT Appliance::readImpl(const LocationInfo &aLocInfo, ComObjPtr<Progress> &aProgress)
606{
607 BstrFmt bstrDesc = BstrFmt(tr("Reading appliance '%s'"),
608 aLocInfo.strPath.c_str());
609 HRESULT rc;
610 /* Create the progress object */
611 aProgress.createObject();
612 if (aLocInfo.storageType == VFSType_File)
613 /* 1 operation only */
614 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
615 bstrDesc,
616 TRUE /* aCancelable */);
617 else
618 /* 4/5 is downloading, 1/5 is reading */
619 rc = aProgress->init(mVirtualBox, static_cast<IAppliance*>(this),
620 bstrDesc,
621 TRUE /* aCancelable */,
622 2, // ULONG cOperations,
623 5, // ULONG ulTotalOperationsWeight,
624 BstrFmt(tr("Download appliance '%s'"),
625 aLocInfo.strPath.c_str()), // CBSTR bstrFirstOperationDescription,
626 4); // ULONG ulFirstOperationWeight,
627 if (FAILED(rc)) throw rc;
628
629 /* Initialize our worker task */
630 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Read, aLocInfo, aProgress));
631
632 rc = task->startThread();
633 if (FAILED(rc)) throw rc;
634
635 /* Don't destruct on success */
636 task.release();
637
638 return rc;
639}
640
641/**
642 * Actual worker code for reading an OVF from disk. This is called from Appliance::taskThreadImportOrExport()
643 * and therefore runs on the OVF read worker thread. This opens the OVF with ovfreader.cpp.
644 *
645 * This runs in two contexts:
646 *
647 * 1) in a first worker thread; in that case, Appliance::Read() called Appliance::readImpl();
648 *
649 * 2) in a second worker thread; in that case, Appliance::Read() called Appliance::readImpl(), which
650 * called Appliance::readS3(), which called Appliance::readImpl(), which then called this.
651 *
652 * @param pTask
653 * @return
654 */
655HRESULT Appliance::readFS(const LocationInfo &locInfo)
656{
657 LogFlowFuncEnter();
658 LogFlowFunc(("Appliance %p\n", this));
659
660 AutoCaller autoCaller(this);
661 if (FAILED(autoCaller.rc())) return autoCaller.rc();
662
663 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
664
665 HRESULT rc = S_OK;
666
667 try
668 {
669 /* Read & parse the XML structure of the OVF file */
670 m->pReader = new ovf::OVFReader(locInfo.strPath);
671 /* Create the SHA1 sum of the OVF file for later validation */
672 char *pszDigest;
673 int vrc = RTSha1Digest(locInfo.strPath.c_str(), &pszDigest, NULL, NULL);
674 if (RT_FAILURE(vrc))
675 throw setError(VBOX_E_FILE_ERROR,
676 tr("Couldn't calculate SHA1 digest for file '%s' (%Rrc)"),
677 RTPathFilename(locInfo.strPath.c_str()), vrc);
678 m->strOVFSHA1Digest = pszDigest;
679 RTStrFree(pszDigest);
680 }
681 catch(xml::Error &x)
682 {
683 rc = setError(VBOX_E_FILE_ERROR,
684 x.what());
685 }
686 catch(HRESULT aRC)
687 {
688 rc = aRC;
689 }
690
691 LogFlowFunc(("rc=%Rhrc\n", rc));
692 LogFlowFuncLeave();
693
694 return rc;
695}
696
697/**
698 * Worker code for reading OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
699 * in S3 mode and therefore runs on the OVF read worker thread. This then starts a second worker
700 * thread to create temporary files (see Appliance::readFS()).
701 *
702 * @param pTask
703 * @return
704 */
705HRESULT Appliance::readS3(TaskOVF *pTask)
706{
707 LogFlowFuncEnter();
708 LogFlowFunc(("Appliance %p\n", this));
709
710 AutoCaller autoCaller(this);
711 if (FAILED(autoCaller.rc())) return autoCaller.rc();
712
713 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
714
715 HRESULT rc = S_OK;
716 int vrc = VINF_SUCCESS;
717 RTS3 hS3 = NIL_RTS3;
718 char szOSTmpDir[RTPATH_MAX];
719 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
720 /* The template for the temporary directory created below */
721 char *pszTmpDir;
722 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
723 list< pair<Utf8Str, ULONG> > filesList;
724 Utf8Str strTmpOvf;
725
726 try
727 {
728 /* Extract the bucket */
729 Utf8Str tmpPath = pTask->locInfo.strPath;
730 Utf8Str bucket;
731 parseBucket(tmpPath, bucket);
732
733 /* We need a temporary directory which we can put the OVF file & all
734 * disk images in */
735 vrc = RTDirCreateTemp(pszTmpDir);
736 if (RT_FAILURE(vrc))
737 throw setError(VBOX_E_FILE_ERROR,
738 tr("Cannot create temporary directory '%s'"), pszTmpDir);
739
740 /* The temporary name of the target OVF file */
741 strTmpOvf = Utf8StrFmt("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
742
743 /* Next we have to download the OVF */
744 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
745 if (RT_FAILURE(vrc))
746 throw setError(VBOX_E_IPRT_ERROR,
747 tr("Cannot create S3 service handler"));
748 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
749
750 /* Get it */
751 char *pszFilename = RTPathFilename(strTmpOvf.c_str());
752 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strTmpOvf.c_str());
753 if (RT_FAILURE(vrc))
754 {
755 if (vrc == VERR_S3_CANCELED)
756 throw S_OK; /* todo: !!!!!!!!!!!!! */
757 else if (vrc == VERR_S3_ACCESS_DENIED)
758 throw setError(E_ACCESSDENIED,
759 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);
760 else if (vrc == VERR_S3_NOT_FOUND)
761 throw setError(VBOX_E_FILE_ERROR,
762 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
763 else
764 throw setError(VBOX_E_IPRT_ERROR,
765 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
766 }
767
768 /* Close the connection early */
769 RTS3Destroy(hS3);
770 hS3 = NIL_RTS3;
771
772 pTask->pProgress->SetNextOperation(Bstr(tr("Reading")), 1);
773
774 /* Prepare the temporary reading of the OVF */
775 ComObjPtr<Progress> progress;
776 LocationInfo li;
777 li.strPath = strTmpOvf;
778 /* Start the reading from the fs */
779 rc = readImpl(li, progress);
780 if (FAILED(rc)) throw rc;
781
782 /* Unlock the appliance for the reading thread */
783 appLock.release();
784 /* Wait until the reading is done, but report the progress back to the
785 caller */
786 ComPtr<IProgress> progressInt(progress);
787 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
788
789 /* Again lock the appliance for the next steps */
790 appLock.acquire();
791 }
792 catch(HRESULT aRC)
793 {
794 rc = aRC;
795 }
796 /* Cleanup */
797 RTS3Destroy(hS3);
798 /* Delete all files which where temporary created */
799 if (RTPathExists(strTmpOvf.c_str()))
800 {
801 vrc = RTFileDelete(strTmpOvf.c_str());
802 if (RT_FAILURE(vrc))
803 rc = setError(VBOX_E_FILE_ERROR,
804 tr("Cannot delete file '%s' (%Rrc)"), strTmpOvf.c_str(), vrc);
805 }
806 /* Delete the temporary directory */
807 if (RTPathExists(pszTmpDir))
808 {
809 vrc = RTDirRemove(pszTmpDir);
810 if (RT_FAILURE(vrc))
811 rc = setError(VBOX_E_FILE_ERROR,
812 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
813 }
814 if (pszTmpDir)
815 RTStrFree(pszTmpDir);
816
817 LogFlowFunc(("rc=%Rhrc\n", rc));
818 LogFlowFuncLeave();
819
820 return rc;
821}
822
823/**
824 * Helper that converts VirtualSystem attachment values into VirtualBox attachment values.
825 * Throws HRESULT values on errors!
826 *
827 * @param hdc in: the HardDiskController structure to attach to.
828 * @param ulAddressOnParent in: the AddressOnParent parameter from OVF.
829 * @param controllerType out: the name of the hard disk controller to attach to (e.g. "IDE Controller").
830 * @param lControllerPort out: the channel (controller port) of the controller to attach to.
831 * @param lDevice out: the device number to attach to.
832 */
833void Appliance::convertDiskAttachmentValues(const ovf::HardDiskController &hdc,
834 uint32_t ulAddressOnParent,
835 Bstr &controllerType,
836 int32_t &lControllerPort,
837 int32_t &lDevice)
838{
839 Log(("Appliance::convertDiskAttachmentValues: hdc.system=%d, hdc.fPrimary=%d, ulAddressOnParent=%d\n", hdc.system, hdc.fPrimary, ulAddressOnParent));
840
841 switch (hdc.system)
842 {
843 case ovf::HardDiskController::IDE:
844 // For the IDE bus, the port parameter can be either 0 or 1, to specify the primary
845 // or secondary IDE controller, respectively. For the primary controller of the IDE bus,
846 // the device number can be either 0 or 1, to specify the master or the slave device,
847 // respectively. For the secondary IDE controller, the device number is always 1 because
848 // the master device is reserved for the CD-ROM drive.
849 controllerType = Bstr("IDE Controller");
850 switch (ulAddressOnParent)
851 {
852 case 0: // master
853 if (!hdc.fPrimary)
854 {
855 // secondary master
856 lControllerPort = (long)1;
857 lDevice = (long)0;
858 }
859 else // primary master
860 {
861 lControllerPort = (long)0;
862 lDevice = (long)0;
863 }
864 break;
865
866 case 1: // slave
867 if (!hdc.fPrimary)
868 {
869 // secondary slave
870 lControllerPort = (long)1;
871 lDevice = (long)1;
872 }
873 else // primary slave
874 {
875 lControllerPort = (long)0;
876 lDevice = (long)1;
877 }
878 break;
879
880 // used by older VBox exports
881 case 2: // interpret this as secondary master
882 lControllerPort = (long)1;
883 lDevice = (long)0;
884 break;
885
886 // used by older VBox exports
887 case 3: // interpret this as secondary slave
888 lControllerPort = (long)1;
889 lDevice = (long)1;
890 break;
891
892 default:
893 throw setError(VBOX_E_NOT_SUPPORTED,
894 tr("Invalid channel %RI16 specified; IDE controllers support only 0, 1 or 2"), ulAddressOnParent);
895 break;
896 }
897 break;
898
899 case ovf::HardDiskController::SATA:
900 controllerType = Bstr("SATA Controller");
901 lControllerPort = (long)ulAddressOnParent;
902 lDevice = (long)0;
903 break;
904
905 case ovf::HardDiskController::SCSI:
906 controllerType = Bstr("SCSI Controller");
907 lControllerPort = (long)ulAddressOnParent;
908 lDevice = (long)0;
909 break;
910
911 default: break;
912 }
913
914 Log(("=> lControllerPort=%d, lDevice=%d\n", lControllerPort, lDevice));
915}
916
917/**
918 * Implementation for importing OVF data into VirtualBox. This starts a new thread which will call
919 * Appliance::taskThreadImportOrExport().
920 *
921 * This creates one or more new machines according to the VirtualSystemScription instances created by
922 * Appliance::Interpret().
923 *
924 * This is in a separate private method because it is used from two locations:
925 *
926 * 1) from the public Appliance::ImportMachines().
927 * 2) from Appliance::importS3(), which got called from a previous instance of Appliance::taskThreadImportOrExport().
928 *
929 * @param aLocInfo
930 * @param aProgress
931 * @return
932 */
933HRESULT Appliance::importImpl(const LocationInfo &aLocInfo,
934 ComObjPtr<Progress> &aProgress)
935{
936 HRESULT rc = S_OK;
937
938 SetUpProgressMode mode;
939 m->strManifestFile.setNull();
940 if (aLocInfo.storageType == VFSType_File)
941 {
942 Utf8Str strMfFile = manifestFileName(aLocInfo.strPath);
943 if (RTPathExists(strMfFile.c_str()))
944 {
945 m->strManifestFile = strMfFile;
946 mode = ImportFileWithManifest;
947 }
948 else
949 mode = ImportFileNoManifest;
950 }
951 else
952 mode = ImportS3;
953
954 rc = setUpProgress(aProgress,
955 BstrFmt(tr("Importing appliance '%s'"), aLocInfo.strPath.c_str()),
956 mode);
957 if (FAILED(rc)) throw rc;
958
959 /* Initialize our worker task */
960 std::auto_ptr<TaskOVF> task(new TaskOVF(this, TaskOVF::Import, aLocInfo, aProgress));
961
962 rc = task->startThread();
963 if (FAILED(rc)) throw rc;
964
965 /* Don't destruct on success */
966 task.release();
967
968 return rc;
969}
970
971/**
972 * Used by Appliance::importMachineGeneric() to store
973 * input parameters and rollback information.
974 */
975struct Appliance::ImportStack
976{
977 // input pointers
978 const LocationInfo &locInfo; // ptr to location info from Appliance::importFS()
979 Utf8Str strSourceDir; // directory where source files reside
980 const ovf::DiskImagesMap &mapDisks; // ptr to disks map in OVF
981 ComObjPtr<Progress> &pProgress; // progress object passed into Appliance::importFS()
982
983 // session (not initially created)
984 ComPtr<ISession> pSession; // session opened in Appliance::importFS() for machine manipulation
985 bool fSessionOpen; // true if the pSession is currently open and needs closing
986
987 // a list of images that we created/imported; this is initially empty
988 // and will be cleaned up on errors
989 list<MyHardDiskAttachment> llHardDiskAttachments; // disks that were attached
990 list< ComPtr<IMedium> > llHardDisksCreated; // media that were created
991 list<Bstr> llMachinesRegistered; // machines that were registered; list of string UUIDs
992
993 ImportStack(const LocationInfo &aLocInfo,
994 const ovf::DiskImagesMap &aMapDisks,
995 ComObjPtr<Progress> &aProgress)
996 : locInfo(aLocInfo),
997 mapDisks(aMapDisks),
998 pProgress(aProgress),
999 fSessionOpen(false)
1000 {
1001 // disk images have to be on the same place as the OVF file. So
1002 // strip the filename out of the full file path
1003 strSourceDir = aLocInfo.strPath;
1004 strSourceDir.stripFilename();
1005 }
1006};
1007
1008/**
1009 * Checks if a manifest file exists in the given location and, if so, verifies
1010 * that the relevant files (the OVF XML and the disks referenced by it, as
1011 * represented by the VirtualSystemDescription instances contained in this appliance)
1012 * match it. Requires a previous read() and interpret().
1013 *
1014 * @param locInfo
1015 * @param reader
1016 * @return
1017 */
1018HRESULT Appliance::manifestVerify(const LocationInfo &locInfo,
1019 const ovf::OVFReader &reader,
1020 ComObjPtr<Progress> &pProgress)
1021{
1022 HRESULT rc = S_OK;
1023
1024 if (!m->strManifestFile.isEmpty())
1025 {
1026 const char *pcszManifestFileOnly = RTPathFilename(m->strManifestFile.c_str());
1027 pProgress->SetNextOperation(BstrFmt(tr("Verifying manifest file '%s'"), pcszManifestFileOnly),
1028 m->ulWeightForManifestOperation); // operation's weight, as set up with the IProgress originally
1029
1030 list<Utf8Str> filesList;
1031 Utf8Str strSrcDir(locInfo.strPath);
1032 strSrcDir.stripFilename();
1033 // add every disks of every virtual system to an internal list
1034 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
1035 for (it = m->virtualSystemDescriptions.begin();
1036 it != m->virtualSystemDescriptions.end();
1037 ++it)
1038 {
1039 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
1040 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1041 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
1042 for (itH = avsdeHDs.begin();
1043 itH != avsdeHDs.end();
1044 ++itH)
1045 {
1046 VirtualSystemDescriptionEntry *vsdeHD = *itH;
1047 // find the disk from the OVF's disk list
1048 ovf::DiskImagesMap::const_iterator itDiskImage = reader.m_mapDisks.find(vsdeHD->strRef);
1049 const ovf::DiskImage &di = itDiskImage->second;
1050 Utf8StrFmt strSrcFilePath("%s%c%s", strSrcDir.c_str(), RTPATH_DELIMITER, di.strHref.c_str());
1051 filesList.push_back(strSrcFilePath);
1052 }
1053 }
1054
1055 // create the test list
1056 PRTMANIFESTTEST pTestList = (PRTMANIFESTTEST)RTMemAllocZ(sizeof(RTMANIFESTTEST) * (filesList.size() + 1));
1057 pTestList[0].pszTestFile = (char*)locInfo.strPath.c_str();
1058 pTestList[0].pszTestDigest = (char*)m->strOVFSHA1Digest.c_str();
1059 int vrc = VINF_SUCCESS;
1060 size_t i = 1;
1061 list<Utf8Str>::const_iterator it1;
1062 for (it1 = filesList.begin();
1063 it1 != filesList.end();
1064 ++it1, ++i)
1065 {
1066 char* pszDigest;
1067 vrc = RTSha1Digest((*it1).c_str(), &pszDigest, NULL, NULL);
1068 pTestList[i].pszTestFile = (char*)(*it1).c_str();
1069 pTestList[i].pszTestDigest = pszDigest;
1070 }
1071
1072 // this call can take a very long time
1073 size_t cIndexOnError;
1074 vrc = RTManifestVerify(m->strManifestFile.c_str(),
1075 pTestList,
1076 filesList.size() + 1,
1077 &cIndexOnError);
1078
1079 if (vrc == VERR_MANIFEST_DIGEST_MISMATCH)
1080 rc = setError(VBOX_E_FILE_ERROR,
1081 tr("The SHA1 digest of '%s' does not match the one in '%s'"),
1082 RTPathFilename(pTestList[cIndexOnError].pszTestFile),
1083 pcszManifestFileOnly);
1084 else if (RT_FAILURE(vrc))
1085 rc = setError(VBOX_E_FILE_ERROR,
1086 tr("Could not verify the content of '%s' against the available files (%Rrc)"),
1087 pcszManifestFileOnly,
1088 vrc);
1089
1090 // clean up
1091 for (size_t j = 1;
1092 j < filesList.size();
1093 ++j)
1094 RTStrFree(pTestList[j].pszTestDigest);
1095 RTMemFree(pTestList);
1096 }
1097
1098 return rc;
1099}
1100
1101/**
1102 * Actual worker code for importing OVF data into VirtualBox. This is called from Appliance::taskThreadImportOrExport()
1103 * and therefore runs on the OVF import worker thread. This creates one or more new machines according to the
1104 * VirtualSystemScription instances created by Appliance::Interpret().
1105 *
1106 * This runs in two contexts:
1107 *
1108 * 1) in a first worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl();
1109 *
1110 * 2) in a second worker thread; in that case, Appliance::ImportMachines() called Appliance::importImpl(), which
1111 * called Appliance::importS3(), which called Appliance::importImpl(), which then called this.
1112 *
1113 * @param pTask
1114 * @return
1115 */
1116HRESULT Appliance::importFS(const LocationInfo &locInfo,
1117 ComObjPtr<Progress> &pProgress)
1118{
1119 LogFlowFuncEnter();
1120 LogFlowFunc(("Appliance %p\n", this));
1121
1122 AutoCaller autoCaller(this);
1123 if (FAILED(autoCaller.rc())) return autoCaller.rc();
1124
1125 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
1126
1127 if (!isApplianceIdle())
1128 return E_ACCESSDENIED;
1129
1130 Assert(!pProgress.isNull());
1131
1132 // Change the appliance state so we can safely leave the lock while doing time-consuming
1133 // disk imports; also the below method calls do all kinds of locking which conflicts with
1134 // the appliance object lock
1135 m->state = Data::ApplianceImporting;
1136 appLock.release();
1137
1138 HRESULT rc = S_OK;
1139
1140 const ovf::OVFReader &reader = *m->pReader;
1141 // this is safe to access because this thread only gets started
1142 // if pReader != NULL
1143
1144 // rollback for errors:
1145 ImportStack stack(locInfo, reader.m_mapDisks, pProgress);
1146
1147 try
1148 {
1149 // if a manifest file exists, verify the content; we then need all files which are referenced by the OVF & the OVF itself
1150 rc = manifestVerify(locInfo, reader, pProgress);
1151 if (FAILED(rc)) throw rc;
1152
1153 // create a session for the machine + disks we manipulate below
1154 rc = stack.pSession.createInprocObject(CLSID_Session);
1155 if (FAILED(rc)) throw rc;
1156
1157 list<ovf::VirtualSystem>::const_iterator it;
1158 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it1;
1159 /* Iterate through all virtual systems of that appliance */
1160 size_t i = 0;
1161 for (it = reader.m_llVirtualSystems.begin(),
1162 it1 = m->virtualSystemDescriptions.begin();
1163 it != reader.m_llVirtualSystems.end();
1164 ++it, ++it1, ++i)
1165 {
1166 const ovf::VirtualSystem &vsysThis = *it;
1167 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it1);
1168
1169 ComPtr<IMachine> pNewMachine;
1170
1171 // there are two ways in which we can create a vbox machine from OVF:
1172 // -- either this OVF was written by vbox 3.2 or later, in which case there is a <vbox:Machine> element
1173 // in the <VirtualSystem>; then the VirtualSystemDescription::Data has a settings::MachineConfigFile
1174 // with all the machine config pretty-parsed;
1175 // -- or this is an OVF from an older vbox or an external source, and then we need to translate the
1176 // VirtualSystemDescriptionEntry and do import work
1177
1178 // @todo r=dj make this selection configurable at run-time, and from the GUI as well
1179
1180 if (vsdescThis->m->pConfig)
1181 importVBoxMachine(vsdescThis, pNewMachine, stack);
1182 else
1183 importMachineGeneric(vsysThis, vsdescThis, pNewMachine, stack);
1184
1185 } // for (it = pAppliance->m->llVirtualSystems.begin() ...
1186 }
1187 catch (HRESULT rc2)
1188 {
1189 rc = rc2;
1190 }
1191
1192 if (FAILED(rc))
1193 {
1194 // with _whatever_ error we've had, do a complete roll-back of
1195 // machines and disks we've created; unfortunately this is
1196 // not so trivially done...
1197
1198 HRESULT rc2;
1199 // detach all hard disks from all machines we created
1200 list<MyHardDiskAttachment>::iterator itM;
1201 for (itM = stack.llHardDiskAttachments.begin();
1202 itM != stack.llHardDiskAttachments.end();
1203 ++itM)
1204 {
1205 const MyHardDiskAttachment &mhda = *itM;
1206 Bstr bstrUuid(mhda.bstrUuid); // make a copy, Windows can't handle const Bstr
1207 rc2 = mVirtualBox->OpenSession(stack.pSession, bstrUuid);
1208 if (SUCCEEDED(rc2))
1209 {
1210 ComPtr<IMachine> sMachine;
1211 rc2 = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1212 if (SUCCEEDED(rc2))
1213 {
1214 rc2 = sMachine->DetachDevice(Bstr(mhda.controllerType), mhda.lControllerPort, mhda.lDevice);
1215 rc2 = sMachine->SaveSettings();
1216 }
1217 stack.pSession->Close();
1218 }
1219 }
1220
1221 // now clean up all hard disks we created
1222 list< ComPtr<IMedium> >::iterator itHD;
1223 for (itHD = stack.llHardDisksCreated.begin();
1224 itHD != stack.llHardDisksCreated.end();
1225 ++itHD)
1226 {
1227 ComPtr<IMedium> pDisk = *itHD;
1228 ComPtr<IProgress> pProgress2;
1229 rc2 = pDisk->DeleteStorage(pProgress2.asOutParam());
1230 rc2 = pProgress2->WaitForCompletion(-1);
1231 }
1232
1233 // finally, deregister and remove all machines
1234 list<Bstr>::iterator itID;
1235 for (itID = stack.llMachinesRegistered.begin();
1236 itID != stack.llMachinesRegistered.end();
1237 ++itID)
1238 {
1239 Bstr bstrGuid = *itID; // make a copy, Windows can't handle const Bstr
1240 ComPtr<IMachine> failedMachine;
1241 rc2 = mVirtualBox->UnregisterMachine(bstrGuid, failedMachine.asOutParam());
1242 if (SUCCEEDED(rc2))
1243 rc2 = failedMachine->DeleteSettings();
1244 }
1245 }
1246
1247 // restore the appliance state
1248 appLock.acquire();
1249 m->state = Data::ApplianceIdle;
1250 appLock.release();
1251
1252 LogFlowFunc(("rc=%Rhrc\n", rc));
1253 LogFlowFuncLeave();
1254
1255 return rc;
1256}
1257
1258/**
1259 * Imports one disk image. This is common code shared between
1260 * -- importMachineGeneric() for the OVF case; in that case the information comes from
1261 * the OVF virtual systems;
1262 * -- importVBoxMachine(); in that case, the information comes from the <vbox:Machine>
1263 * tag.
1264 *
1265 * Both ways of describing machines use the OVF disk references section, so in both cases
1266 * the caller needs to pass in the ovf::DiskImage structure from ovfreader.cpp.
1267 *
1268 * As a result, in both cases, if di.strHref is empty, we create a new disk as per the OVF
1269 * spec, even though this cannot really happen in the vbox:Machine case since such data
1270 * would never have been exported.
1271 *
1272 * This advances stack.pProgress by one operation with the disk's weight.
1273 *
1274 * @param di ovfreader.cpp structure describing the disk image from the OVF that is to be imported
1275 * @param ulSizeMB Size of the disk image (for progress reporting)
1276 * @param strTargetPath Where to create the target image.
1277 * @param pTargetHD out: The newly created target disk. This also gets pushed on stack.llHardDisksCreated for cleanup.
1278 * @param stack
1279 */
1280void Appliance::importOneDiskImage(const ovf::DiskImage &di,
1281 const Utf8Str &strTargetPath,
1282 ComPtr<IMedium> &pTargetHD,
1283 ImportStack &stack)
1284{
1285 ComPtr<IMedium> pSourceHD;
1286 bool fSourceHdNeedsClosing = false;
1287
1288 try
1289 {
1290 // destination file must not exist
1291 if ( strTargetPath.isEmpty()
1292 || RTPathExists(strTargetPath.c_str())
1293 )
1294 /* This isn't allowed */
1295 throw setError(VBOX_E_FILE_ERROR,
1296 tr("Destination file '%s' exists"),
1297 strTargetPath.c_str());
1298
1299 const Utf8Str &strSourceOVF = di.strHref;
1300
1301 // Make sure target directory exists
1302 HRESULT rc = VirtualBox::ensureFilePathExists(strTargetPath.c_str());
1303 if (FAILED(rc))
1304 throw rc;
1305
1306 // subprogress object for hard disk
1307 ComPtr<IProgress> pProgress2;
1308
1309 /* If strHref is empty we have to create a new file */
1310 if (strSourceOVF.isEmpty())
1311 {
1312 // which format to use?
1313 Bstr srcFormat = L"VDI";
1314 if ( di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#sparse", Utf8Str::CaseInsensitive)
1315 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized", Utf8Str::CaseInsensitive)
1316 || di.strFormat.compare("http://www.vmware.com/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1317 || di.strFormat.compare("http://www.vmware.com/interfaces/specifications/vmdk.html#compressed", Utf8Str::CaseInsensitive)
1318 )
1319 srcFormat = L"VMDK";
1320 // create an empty hard disk
1321 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1322 if (FAILED(rc)) throw rc;
1323
1324 // create a dynamic growing disk image with the given capacity
1325 rc = pTargetHD->CreateBaseStorage(di.iCapacity / _1M, MediumVariant_Standard, pProgress2.asOutParam());
1326 if (FAILED(rc)) throw rc;
1327
1328 // advance to the next operation
1329 stack.pProgress->SetNextOperation(BstrFmt(tr("Creating disk image '%s'"), strTargetPath.c_str()),
1330 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally
1331 }
1332 else
1333 {
1334 // construct source file path
1335 Utf8StrFmt strSrcFilePath("%s%c%s", stack.strSourceDir.c_str(), RTPATH_DELIMITER, strSourceOVF.c_str());
1336 // source path must exist
1337 if (!RTPathExists(strSrcFilePath.c_str()))
1338 throw setError(VBOX_E_FILE_ERROR,
1339 tr("Source virtual disk image file '%s' doesn't exist"),
1340 strSrcFilePath.c_str());
1341
1342 // Clone the disk image (this is necessary cause the id has
1343 // to be recreated for the case the same hard disk is
1344 // attached already from a previous import)
1345
1346 // First open the existing disk image
1347 rc = mVirtualBox->OpenHardDisk(Bstr(strSrcFilePath),
1348 AccessMode_ReadOnly,
1349 false,
1350 NULL,
1351 false,
1352 NULL,
1353 pSourceHD.asOutParam());
1354 if (FAILED(rc)) throw rc;
1355 fSourceHdNeedsClosing = true;
1356
1357 /* We need the format description of the source disk image */
1358 Bstr srcFormat;
1359 rc = pSourceHD->COMGETTER(Format)(srcFormat.asOutParam());
1360 if (FAILED(rc)) throw rc;
1361 /* Create a new hard disk interface for the destination disk image */
1362 rc = mVirtualBox->CreateHardDisk(srcFormat, Bstr(strTargetPath), pTargetHD.asOutParam());
1363 if (FAILED(rc)) throw rc;
1364 /* Clone the source disk image */
1365 rc = pSourceHD->CloneTo(pTargetHD, MediumVariant_Standard, NULL, pProgress2.asOutParam());
1366 if (FAILED(rc)) throw rc;
1367
1368 /* Advance to the next operation */
1369 stack.pProgress->SetNextOperation(BstrFmt(tr("Importing virtual disk image '%s'"), strSrcFilePath.c_str()),
1370 di.ulSuggestedSizeMB); // operation's weight, as set up with the IProgress originally);
1371 }
1372
1373 // now wait for the background disk operation to complete; this throws HRESULTs on error
1374 waitForAsyncProgress(stack.pProgress, pProgress2);
1375
1376 if (fSourceHdNeedsClosing)
1377 {
1378 rc = pSourceHD->Close();
1379 if (FAILED(rc)) throw rc;
1380 fSourceHdNeedsClosing = false;
1381 }
1382
1383 stack.llHardDisksCreated.push_back(pTargetHD);
1384 }
1385 catch (...)
1386 {
1387 if (fSourceHdNeedsClosing)
1388 pSourceHD->Close();
1389
1390 throw;
1391 }
1392}
1393
1394/**
1395 * Imports one OVF virtual system (described by the given ovf::VirtualSystem and VirtualSystemDescription)
1396 * into VirtualBox by creating an IMachine instance, which is returned.
1397 *
1398 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1399 * up any leftovers from this function. For this, the given ImportStack instance has received information
1400 * about what needs cleaning up (to support rollback).
1401 *
1402 * @param vsysThis OVF virtual system (machine) to import.
1403 * @param vsdescThis Matching virtual system description (machine) to import.
1404 * @param pNewMachine out: Newly created machine.
1405 * @param stack Cleanup stack for when this throws.
1406 */
1407void Appliance::importMachineGeneric(const ovf::VirtualSystem &vsysThis,
1408 ComObjPtr<VirtualSystemDescription> &vsdescThis,
1409 ComPtr<IMachine> &pNewMachine,
1410 ImportStack &stack)
1411{
1412 /* Guest OS type */
1413 std::list<VirtualSystemDescriptionEntry*> vsdeOS;
1414 vsdeOS = vsdescThis->findByType(VirtualSystemDescriptionType_OS);
1415 if (vsdeOS.size() < 1)
1416 throw setError(VBOX_E_FILE_ERROR,
1417 tr("Missing guest OS type"));
1418 const Utf8Str &strOsTypeVBox = vsdeOS.front()->strVbox;
1419
1420 /* Now that we know the base system get our internal defaults based on that. */
1421 ComPtr<IGuestOSType> osType;
1422 HRESULT rc = mVirtualBox->GetGuestOSType(Bstr(strOsTypeVBox), osType.asOutParam());
1423 if (FAILED(rc)) throw rc;
1424
1425 /* Create the machine */
1426 /* First get the name */
1427 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
1428 if (vsdeName.size() < 1)
1429 throw setError(VBOX_E_FILE_ERROR,
1430 tr("Missing VM name"));
1431 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
1432 rc = mVirtualBox->CreateMachine(Bstr(strNameVBox),
1433 Bstr(strOsTypeVBox),
1434 NULL,
1435 NULL,
1436 FALSE,
1437 pNewMachine.asOutParam());
1438 if (FAILED(rc)) throw rc;
1439
1440 // and the description
1441 std::list<VirtualSystemDescriptionEntry*> vsdeDescription = vsdescThis->findByType(VirtualSystemDescriptionType_Description);
1442 if (vsdeDescription.size())
1443 {
1444 const Utf8Str &strDescription = vsdeDescription.front()->strVbox;
1445 rc = pNewMachine->COMSETTER(Description)(Bstr(strDescription));
1446 if (FAILED(rc)) throw rc;
1447 }
1448
1449 /* CPU count */
1450 std::list<VirtualSystemDescriptionEntry*> vsdeCPU = vsdescThis->findByType(VirtualSystemDescriptionType_CPU);
1451 ComAssertMsgThrow(vsdeCPU.size() == 1, ("CPU count missing"), E_FAIL);
1452 const Utf8Str &cpuVBox = vsdeCPU.front()->strVbox;
1453 ULONG tmpCount = (ULONG)RTStrToUInt64(cpuVBox.c_str());
1454 rc = pNewMachine->COMSETTER(CPUCount)(tmpCount);
1455 if (FAILED(rc)) throw rc;
1456 bool fEnableIOApic = false;
1457 /* We need HWVirt & IO-APIC if more than one CPU is requested */
1458 if (tmpCount > 1)
1459 {
1460 rc = pNewMachine->SetHWVirtExProperty(HWVirtExPropertyType_Enabled, TRUE);
1461 if (FAILED(rc)) throw rc;
1462
1463 fEnableIOApic = true;
1464 }
1465
1466 /* RAM */
1467 std::list<VirtualSystemDescriptionEntry*> vsdeRAM = vsdescThis->findByType(VirtualSystemDescriptionType_Memory);
1468 ComAssertMsgThrow(vsdeRAM.size() == 1, ("RAM size missing"), E_FAIL);
1469 const Utf8Str &memoryVBox = vsdeRAM.front()->strVbox;
1470 ULONG tt = (ULONG)RTStrToUInt64(memoryVBox.c_str());
1471 rc = pNewMachine->COMSETTER(MemorySize)(tt);
1472 if (FAILED(rc)) throw rc;
1473
1474 /* VRAM */
1475 /* Get the recommended VRAM for this guest OS type */
1476 ULONG vramVBox;
1477 rc = osType->COMGETTER(RecommendedVRAM)(&vramVBox);
1478 if (FAILED(rc)) throw rc;
1479
1480 /* Set the VRAM */
1481 rc = pNewMachine->COMSETTER(VRAMSize)(vramVBox);
1482 if (FAILED(rc)) throw rc;
1483
1484 // I/O APIC: Generic OVF has no setting for this. Enable it if we
1485 // import a Windows VM because if if Windows was installed without IOAPIC,
1486 // it will not mind finding an one later on, but if Windows was installed
1487 // _with_ an IOAPIC, it will bluescreen if it's not found
1488 if (!fEnableIOApic)
1489 {
1490 Bstr bstrFamilyId;
1491 rc = osType->COMGETTER(FamilyId)(bstrFamilyId.asOutParam());
1492 if (FAILED(rc)) throw rc;
1493 if (bstrFamilyId == "Windows")
1494 fEnableIOApic = true;
1495 }
1496
1497 if (fEnableIOApic)
1498 {
1499 ComPtr<IBIOSSettings> pBIOSSettings;
1500 rc = pNewMachine->COMGETTER(BIOSSettings)(pBIOSSettings.asOutParam());
1501 if (FAILED(rc)) throw rc;
1502
1503 rc = pBIOSSettings->COMSETTER(IOAPICEnabled)(TRUE);
1504 if (FAILED(rc)) throw rc;
1505 }
1506
1507 /* Audio Adapter */
1508 std::list<VirtualSystemDescriptionEntry*> vsdeAudioAdapter = vsdescThis->findByType(VirtualSystemDescriptionType_SoundCard);
1509 /* @todo: we support one audio adapter only */
1510 if (vsdeAudioAdapter.size() > 0)
1511 {
1512 const Utf8Str& audioAdapterVBox = vsdeAudioAdapter.front()->strVbox;
1513 if (audioAdapterVBox.compare("null", Utf8Str::CaseInsensitive) != 0)
1514 {
1515 uint32_t audio = RTStrToUInt32(audioAdapterVBox.c_str());
1516 ComPtr<IAudioAdapter> audioAdapter;
1517 rc = pNewMachine->COMGETTER(AudioAdapter)(audioAdapter.asOutParam());
1518 if (FAILED(rc)) throw rc;
1519 rc = audioAdapter->COMSETTER(Enabled)(true);
1520 if (FAILED(rc)) throw rc;
1521 rc = audioAdapter->COMSETTER(AudioController)(static_cast<AudioControllerType_T>(audio));
1522 if (FAILED(rc)) throw rc;
1523 }
1524 }
1525
1526#ifdef VBOX_WITH_USB
1527 /* USB Controller */
1528 std::list<VirtualSystemDescriptionEntry*> vsdeUSBController = vsdescThis->findByType(VirtualSystemDescriptionType_USBController);
1529 // USB support is enabled if there's at least one such entry; to disable USB support,
1530 // the type of the USB item would have been changed to "ignore"
1531 bool fUSBEnabled = vsdeUSBController.size() > 0;
1532
1533 ComPtr<IUSBController> usbController;
1534 rc = pNewMachine->COMGETTER(USBController)(usbController.asOutParam());
1535 if (FAILED(rc)) throw rc;
1536 rc = usbController->COMSETTER(Enabled)(fUSBEnabled);
1537 if (FAILED(rc)) throw rc;
1538#endif /* VBOX_WITH_USB */
1539
1540 /* Change the network adapters */
1541 std::list<VirtualSystemDescriptionEntry*> vsdeNW = vsdescThis->findByType(VirtualSystemDescriptionType_NetworkAdapter);
1542 if (vsdeNW.size() == 0)
1543 {
1544 /* No network adapters, so we have to disable our default one */
1545 ComPtr<INetworkAdapter> nwVBox;
1546 rc = pNewMachine->GetNetworkAdapter(0, nwVBox.asOutParam());
1547 if (FAILED(rc)) throw rc;
1548 rc = nwVBox->COMSETTER(Enabled)(false);
1549 if (FAILED(rc)) throw rc;
1550 }
1551 else if (vsdeNW.size() > SchemaDefs::NetworkAdapterCount)
1552 throw setError(VBOX_E_FILE_ERROR,
1553 tr("Too many network adapters: OVF requests %d network adapters, but VirtualBox only supports %d"),
1554 vsdeNW.size(), SchemaDefs::NetworkAdapterCount);
1555 else
1556 {
1557 list<VirtualSystemDescriptionEntry*>::const_iterator nwIt;
1558 size_t a = 0;
1559 for (nwIt = vsdeNW.begin();
1560 nwIt != vsdeNW.end();
1561 ++nwIt, ++a)
1562 {
1563 const VirtualSystemDescriptionEntry* pvsys = *nwIt;
1564
1565 const Utf8Str &nwTypeVBox = pvsys->strVbox;
1566 uint32_t tt1 = RTStrToUInt32(nwTypeVBox.c_str());
1567 ComPtr<INetworkAdapter> pNetworkAdapter;
1568 rc = pNewMachine->GetNetworkAdapter((ULONG)a, pNetworkAdapter.asOutParam());
1569 if (FAILED(rc)) throw rc;
1570 /* Enable the network card & set the adapter type */
1571 rc = pNetworkAdapter->COMSETTER(Enabled)(true);
1572 if (FAILED(rc)) throw rc;
1573 rc = pNetworkAdapter->COMSETTER(AdapterType)(static_cast<NetworkAdapterType_T>(tt1));
1574 if (FAILED(rc)) throw rc;
1575
1576 // default is NAT; change to "bridged" if extra conf says so
1577 if (!pvsys->strExtraConfig.compare("type=Bridged", Utf8Str::CaseInsensitive))
1578 {
1579 /* Attach to the right interface */
1580 rc = pNetworkAdapter->AttachToBridgedInterface();
1581 if (FAILED(rc)) throw rc;
1582 ComPtr<IHost> host;
1583 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1584 if (FAILED(rc)) throw rc;
1585 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1586 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1587 if (FAILED(rc)) throw rc;
1588 // We search for the first host network interface which
1589 // is usable for bridged networking
1590 for (size_t j = 0;
1591 j < nwInterfaces.size();
1592 ++j)
1593 {
1594 HostNetworkInterfaceType_T itype;
1595 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1596 if (FAILED(rc)) throw rc;
1597 if (itype == HostNetworkInterfaceType_Bridged)
1598 {
1599 Bstr name;
1600 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1601 if (FAILED(rc)) throw rc;
1602 /* Set the interface name to attach to */
1603 pNetworkAdapter->COMSETTER(HostInterface)(name);
1604 if (FAILED(rc)) throw rc;
1605 break;
1606 }
1607 }
1608 }
1609 /* Next test for host only interfaces */
1610 else if (!pvsys->strExtraConfig.compare("type=HostOnly", Utf8Str::CaseInsensitive))
1611 {
1612 /* Attach to the right interface */
1613 rc = pNetworkAdapter->AttachToHostOnlyInterface();
1614 if (FAILED(rc)) throw rc;
1615 ComPtr<IHost> host;
1616 rc = mVirtualBox->COMGETTER(Host)(host.asOutParam());
1617 if (FAILED(rc)) throw rc;
1618 com::SafeIfaceArray<IHostNetworkInterface> nwInterfaces;
1619 rc = host->COMGETTER(NetworkInterfaces)(ComSafeArrayAsOutParam(nwInterfaces));
1620 if (FAILED(rc)) throw rc;
1621 // We search for the first host network interface which
1622 // is usable for host only networking
1623 for (size_t j = 0;
1624 j < nwInterfaces.size();
1625 ++j)
1626 {
1627 HostNetworkInterfaceType_T itype;
1628 rc = nwInterfaces[j]->COMGETTER(InterfaceType)(&itype);
1629 if (FAILED(rc)) throw rc;
1630 if (itype == HostNetworkInterfaceType_HostOnly)
1631 {
1632 Bstr name;
1633 rc = nwInterfaces[j]->COMGETTER(Name)(name.asOutParam());
1634 if (FAILED(rc)) throw rc;
1635 /* Set the interface name to attach to */
1636 pNetworkAdapter->COMSETTER(HostInterface)(name);
1637 if (FAILED(rc)) throw rc;
1638 break;
1639 }
1640 }
1641 }
1642 }
1643 }
1644
1645 // IDE Hard disk controller
1646 std::list<VirtualSystemDescriptionEntry*> vsdeHDCIDE = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerIDE);
1647 // In OVF (at least VMware's version of it), an IDE controller has two ports, so VirtualBox's single IDE controller
1648 // with two channels and two ports each counts as two OVF IDE controllers -- so we accept one or two such IDE controllers
1649 uint32_t cIDEControllers = vsdeHDCIDE.size();
1650 if (cIDEControllers > 2)
1651 throw setError(VBOX_E_FILE_ERROR,
1652 tr("Too many IDE controllers in OVF; import facility only supports two"));
1653 if (vsdeHDCIDE.size() > 0)
1654 {
1655 // one or two IDE controllers present in OVF: add one VirtualBox controller
1656 ComPtr<IStorageController> pController;
1657 rc = pNewMachine->AddStorageController(Bstr("IDE Controller"), StorageBus_IDE, pController.asOutParam());
1658 if (FAILED(rc)) throw rc;
1659
1660 const char *pcszIDEType = vsdeHDCIDE.front()->strVbox.c_str();
1661 if (!strcmp(pcszIDEType, "PIIX3"))
1662 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX3);
1663 else if (!strcmp(pcszIDEType, "PIIX4"))
1664 rc = pController->COMSETTER(ControllerType)(StorageControllerType_PIIX4);
1665 else if (!strcmp(pcszIDEType, "ICH6"))
1666 rc = pController->COMSETTER(ControllerType)(StorageControllerType_ICH6);
1667 else
1668 throw setError(VBOX_E_FILE_ERROR,
1669 tr("Invalid IDE controller type \"%s\""),
1670 pcszIDEType);
1671 if (FAILED(rc)) throw rc;
1672 }
1673
1674 /* Hard disk controller SATA */
1675 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSATA = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSATA);
1676 if (vsdeHDCSATA.size() > 1)
1677 throw setError(VBOX_E_FILE_ERROR,
1678 tr("Too many SATA controllers in OVF; import facility only supports one"));
1679 if (vsdeHDCSATA.size() > 0)
1680 {
1681 ComPtr<IStorageController> pController;
1682 const Utf8Str &hdcVBox = vsdeHDCSATA.front()->strVbox;
1683 if (hdcVBox == "AHCI")
1684 {
1685 rc = pNewMachine->AddStorageController(Bstr("SATA Controller"), StorageBus_SATA, pController.asOutParam());
1686 if (FAILED(rc)) throw rc;
1687 }
1688 else
1689 throw setError(VBOX_E_FILE_ERROR,
1690 tr("Invalid SATA controller type \"%s\""),
1691 hdcVBox.c_str());
1692 }
1693
1694 /* Hard disk controller SCSI */
1695 std::list<VirtualSystemDescriptionEntry*> vsdeHDCSCSI = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskControllerSCSI);
1696 if (vsdeHDCSCSI.size() > 1)
1697 throw setError(VBOX_E_FILE_ERROR,
1698 tr("Too many SCSI controllers in OVF; import facility only supports one"));
1699 if (vsdeHDCSCSI.size() > 0)
1700 {
1701 ComPtr<IStorageController> pController;
1702 Bstr bstrName(L"SCSI Controller");
1703 StorageBus_T busType = StorageBus_SCSI;
1704 StorageControllerType_T controllerType;
1705 const Utf8Str &hdcVBox = vsdeHDCSCSI.front()->strVbox;
1706 if (hdcVBox == "LsiLogic")
1707 controllerType = StorageControllerType_LsiLogic;
1708 else if (hdcVBox == "LsiLogicSas")
1709 {
1710 // OVF treats LsiLogicSas as a SCSI controller but VBox considers it a class of its own
1711 bstrName = L"SAS Controller";
1712 busType = StorageBus_SAS;
1713 controllerType = StorageControllerType_LsiLogicSas;
1714 }
1715 else if (hdcVBox == "BusLogic")
1716 controllerType = StorageControllerType_BusLogic;
1717 else
1718 throw setError(VBOX_E_FILE_ERROR,
1719 tr("Invalid SCSI controller type \"%s\""),
1720 hdcVBox.c_str());
1721
1722 rc = pNewMachine->AddStorageController(bstrName, busType, pController.asOutParam());
1723 if (FAILED(rc)) throw rc;
1724 rc = pController->COMSETTER(ControllerType)(controllerType);
1725 if (FAILED(rc)) throw rc;
1726 }
1727
1728 /* Now its time to register the machine before we add any hard disks */
1729 rc = mVirtualBox->RegisterMachine(pNewMachine);
1730 if (FAILED(rc)) throw rc;
1731
1732 // store new machine for roll-back in case of errors
1733 Bstr bstrNewMachineId;
1734 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
1735 if (FAILED(rc)) throw rc;
1736 stack.llMachinesRegistered.push_back(bstrNewMachineId);
1737
1738 // Add floppies and CD-ROMs to the appropriate controllers.
1739 std::list<VirtualSystemDescriptionEntry*> vsdeFloppy = vsdescThis->findByType(VirtualSystemDescriptionType_Floppy);
1740 if (vsdeFloppy.size() > 1)
1741 throw setError(VBOX_E_FILE_ERROR,
1742 tr("Too many floppy controllers in OVF; import facility only supports one"));
1743 std::list<VirtualSystemDescriptionEntry*> vsdeCDROM = vsdescThis->findByType(VirtualSystemDescriptionType_CDROM);
1744 if ( (vsdeFloppy.size() > 0)
1745 || (vsdeCDROM.size() > 0)
1746 )
1747 {
1748 // If there's an error here we need to close the session, so
1749 // we need another try/catch block.
1750
1751 try
1752 {
1753 // to attach things we need to open a session for the new machine
1754 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1755 if (FAILED(rc)) throw rc;
1756 stack.fSessionOpen = true;
1757
1758 ComPtr<IMachine> sMachine;
1759 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1760 if (FAILED(rc)) throw rc;
1761
1762 // floppy first
1763 if (vsdeFloppy.size() == 1)
1764 {
1765 ComPtr<IStorageController> pController;
1766 rc = sMachine->AddStorageController(Bstr("Floppy Controller"), StorageBus_Floppy, pController.asOutParam());
1767 if (FAILED(rc)) throw rc;
1768
1769 Bstr bstrName;
1770 rc = pController->COMGETTER(Name)(bstrName.asOutParam());
1771 if (FAILED(rc)) throw rc;
1772
1773 // this is for rollback later
1774 MyHardDiskAttachment mhda;
1775 mhda.bstrUuid = bstrNewMachineId;
1776 mhda.pMachine = pNewMachine;
1777 mhda.controllerType = bstrName;
1778 mhda.lControllerPort = 0;
1779 mhda.lDevice = 0;
1780
1781 Log(("Attaching floppy\n"));
1782
1783 rc = sMachine->AttachDevice(mhda.controllerType,
1784 mhda.lControllerPort,
1785 mhda.lDevice,
1786 DeviceType_Floppy,
1787 NULL);
1788 if (FAILED(rc)) throw rc;
1789
1790 stack.llHardDiskAttachments.push_back(mhda);
1791 }
1792
1793 // CD-ROMs next
1794 for (std::list<VirtualSystemDescriptionEntry*>::const_iterator jt = vsdeCDROM.begin();
1795 jt != vsdeCDROM.end();
1796 ++jt)
1797 {
1798 // for now always attach to secondary master on IDE controller;
1799 // there seems to be no useful information in OVF where else to
1800 // attach it (@todo test with latest versions of OVF software)
1801
1802 // find the IDE controller
1803 const ovf::HardDiskController *pController = NULL;
1804 for (ovf::ControllersMap::const_iterator kt = vsysThis.mapControllers.begin();
1805 kt != vsysThis.mapControllers.end();
1806 ++kt)
1807 {
1808 if (kt->second.system == ovf::HardDiskController::IDE)
1809 {
1810 pController = &kt->second;
1811 break;
1812 }
1813 }
1814
1815 if (!pController)
1816 throw setError(VBOX_E_FILE_ERROR,
1817 tr("OVF wants a CD-ROM drive but cannot find IDE controller, which is required in this version of VirtualBox"));
1818
1819 // this is for rollback later
1820 MyHardDiskAttachment mhda;
1821 mhda.bstrUuid = bstrNewMachineId;
1822 mhda.pMachine = pNewMachine;
1823
1824 convertDiskAttachmentValues(*pController,
1825 2, // interpreted as secondary master
1826 mhda.controllerType, // Bstr
1827 mhda.lControllerPort,
1828 mhda.lDevice);
1829
1830 Log(("Attaching CD-ROM to port %d on device %d\n", mhda.lControllerPort, mhda.lDevice));
1831
1832 rc = sMachine->AttachDevice(mhda.controllerType,
1833 mhda.lControllerPort,
1834 mhda.lDevice,
1835 DeviceType_DVD,
1836 NULL);
1837 if (FAILED(rc)) throw rc;
1838
1839 stack.llHardDiskAttachments.push_back(mhda);
1840 } // end for (itHD = avsdeHDs.begin();
1841
1842 rc = sMachine->SaveSettings();
1843 if (FAILED(rc)) throw rc;
1844
1845 // only now that we're done with all disks, close the session
1846 rc = stack.pSession->Close();
1847 if (FAILED(rc)) throw rc;
1848 stack.fSessionOpen = false;
1849 }
1850 catch(HRESULT /* aRC */)
1851 {
1852 if (stack.fSessionOpen)
1853 stack.pSession->Close();
1854
1855 throw;
1856 }
1857 }
1858
1859 // create the hard disks & connect them to the appropriate controllers
1860 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
1861 if (avsdeHDs.size() > 0)
1862 {
1863 // If there's an error here we need to close the session, so
1864 // we need another try/catch block.
1865 try
1866 {
1867 // to attach things we need to open a session for the new machine
1868 rc = mVirtualBox->OpenSession(stack.pSession, bstrNewMachineId);
1869 if (FAILED(rc)) throw rc;
1870 stack.fSessionOpen = true;
1871
1872 /* Iterate over all given disk images */
1873 list<VirtualSystemDescriptionEntry*>::const_iterator itHD;
1874 for (itHD = avsdeHDs.begin();
1875 itHD != avsdeHDs.end();
1876 ++itHD)
1877 {
1878 VirtualSystemDescriptionEntry *vsdeHD = *itHD;
1879
1880 // vsdeHD->strRef contains the disk identifier (e.g. "vmdisk1"), which should exist
1881 // in the virtual system's disks map under that ID and also in the global images map
1882 ovf::VirtualDisksMap::const_iterator itVirtualDisk = vsysThis.mapVirtualDisks.find(vsdeHD->strRef);
1883 // and find the disk from the OVF's disk list
1884 ovf::DiskImagesMap::const_iterator itDiskImage = stack.mapDisks.find(vsdeHD->strRef);
1885 if ( (itVirtualDisk == vsysThis.mapVirtualDisks.end())
1886 || (itDiskImage == stack.mapDisks.end())
1887 )
1888 throw setError(E_FAIL,
1889 tr("Internal inconsistency looking up disk image '%s'"),
1890 vsdeHD->strRef.c_str());
1891
1892 const ovf::DiskImage &ovfDiskImage = itDiskImage->second;
1893 const ovf::VirtualDisk &ovfVdisk = itVirtualDisk->second;
1894
1895 ComPtr<IMedium> pTargetHD;
1896 importOneDiskImage(ovfDiskImage,
1897 vsdeHD->strVbox,
1898 pTargetHD,
1899 stack);
1900
1901 // now use the new uuid to attach the disk image to our new machine
1902 ComPtr<IMachine> sMachine;
1903 rc = stack.pSession->COMGETTER(Machine)(sMachine.asOutParam());
1904 if (FAILED(rc)) throw rc;
1905 Bstr hdId;
1906 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
1907 if (FAILED(rc)) throw rc;
1908
1909 // find the hard disk controller to which we should attach
1910 ovf::HardDiskController hdc = (*vsysThis.mapControllers.find(ovfVdisk.idController)).second;
1911
1912 // this is for rollback later
1913 MyHardDiskAttachment mhda;
1914 mhda.bstrUuid = bstrNewMachineId;
1915 mhda.pMachine = pNewMachine;
1916
1917 convertDiskAttachmentValues(hdc,
1918 ovfVdisk.ulAddressOnParent,
1919 mhda.controllerType, // Bstr
1920 mhda.lControllerPort,
1921 mhda.lDevice);
1922
1923 Log(("Attaching disk %s to port %d on device %d\n", vsdeHD->strVbox.c_str(), mhda.lControllerPort, mhda.lDevice));
1924
1925 rc = sMachine->AttachDevice(mhda.controllerType, // wstring name
1926 mhda.lControllerPort, // long controllerPort
1927 mhda.lDevice, // long device
1928 DeviceType_HardDisk, // DeviceType_T type
1929 hdId); // uuid id
1930 if (FAILED(rc)) throw rc;
1931
1932 stack.llHardDiskAttachments.push_back(mhda);
1933
1934 rc = sMachine->SaveSettings();
1935 if (FAILED(rc)) throw rc;
1936 } // end for (itHD = avsdeHDs.begin();
1937
1938 // only now that we're done with all disks, close the session
1939 rc = stack.pSession->Close();
1940 if (FAILED(rc)) throw rc;
1941 stack.fSessionOpen = false;
1942 }
1943 catch(HRESULT /* aRC */)
1944 {
1945 if (stack.fSessionOpen)
1946 stack.pSession->Close();
1947
1948 throw;
1949 }
1950 }
1951}
1952
1953/**
1954 * Imports one OVF virtual system (described by a vbox:Machine tag represented by the given config
1955 * structure) into VirtualBox by creating an IMachine instance, which is returned.
1956 *
1957 * This throws HRESULT error codes for anything that goes wrong, in which case the caller must clean
1958 * up any leftovers from this function. For this, the given ImportStack instance has received information
1959 * about what needs cleaning up (to support rollback).
1960 *
1961 * The machine config stored in the settings::MachineConfigFile structure contains the UUIDs of
1962 * the disk attachments used by the machine when it was exported. We also add vbox:uuid attributes
1963 * to the OVF disks sections so we can look them up. While importing these UUIDs into a second host
1964 * will most probably work, reimporting them into the same host will cause conflicts, so we always
1965 * generate new ones on import. This involves the following:
1966 *
1967 * 1) Scan the machine config for disk attachments.
1968 *
1969 * 2) For each disk attachment found, look up the OVF disk image from the disk references section
1970 * and import the disk into VirtualBox, which creates a new UUID for it. In the machine config,
1971 * replace the old UUID with the new one.
1972 *
1973 * 3) Create the VirtualBox machine with the modfified machine config.
1974 *
1975 * @param config
1976 * @param pNewMachine
1977 * @param stack
1978 */
1979void Appliance::importVBoxMachine(ComObjPtr<VirtualSystemDescription> &vsdescThis,
1980 ComPtr<IMachine> &pReturnNewMachine,
1981 ImportStack &stack)
1982{
1983 Assert(vsdescThis->m->pConfig);
1984
1985 settings::MachineConfigFile &config = *vsdescThis->m->pConfig;
1986
1987 Utf8Str strDefaultHardDiskFolder;
1988 HRESULT rc = getDefaultHardDiskFolder(strDefaultHardDiskFolder);
1989 if (FAILED(rc)) throw rc;
1990
1991 // step 1): scan the machine config for attachments
1992 for (settings::StorageControllersList::iterator sit = config.storageMachine.llStorageControllers.begin();
1993 sit != config.storageMachine.llStorageControllers.end();
1994 ++sit)
1995 {
1996 settings::StorageController &sc = *sit;
1997
1998 for (settings::AttachedDevicesList::iterator dit = sc.llAttachedDevices.begin();
1999 dit != sc.llAttachedDevices.end();
2000 ++dit)
2001 {
2002 settings::AttachedDevice &d = *dit;
2003
2004 if (d.uuid.isEmpty())
2005 // empty DVD and floppy media
2006 continue;
2007
2008 // convert the Guid to string
2009 Utf8Str strUuid = d.uuid.toString();
2010
2011 // there must be an image in the OVF disk structs with the same UUID
2012 bool fFound = false;
2013 for (ovf::DiskImagesMap::const_iterator oit = stack.mapDisks.begin();
2014 oit != stack.mapDisks.end();
2015 ++oit)
2016 {
2017 const ovf::DiskImage &di = oit->second;
2018
2019 if (di.uuidVbox == strUuid)
2020 {
2021 Utf8Str strTargetPath(strDefaultHardDiskFolder);
2022 strTargetPath.append(RTPATH_DELIMITER);
2023 strTargetPath.append(di.strHref);
2024 searchUniqueDiskImageFilePath(strTargetPath);
2025
2026 // step 2): for each attachment, import the disk...
2027 ComPtr<IMedium> pTargetHD;
2028 importOneDiskImage(di,
2029 strTargetPath,
2030 pTargetHD,
2031 stack);
2032
2033 // ... and replace the old UUID in the machine config with the one of
2034 // the imported disk that was just created
2035 Bstr hdId;
2036 rc = pTargetHD->COMGETTER(Id)(hdId.asOutParam());
2037 if (FAILED(rc)) throw rc;
2038
2039 d.uuid = hdId;
2040
2041 fFound = true;
2042 break;
2043 }
2044 }
2045
2046 // no disk with such a UUID found:
2047 if (!fFound)
2048 throw setError(E_FAIL,
2049 tr("<vbox:Machine> element in OVF contains a medium attachment for the disk image %s but the OVF describes no such image"),
2050 strUuid.raw());
2051 } // for (settings::AttachedDevicesList::const_iterator dit = sc.llAttachedDevices.begin();
2052 } // for (settings::StorageControllersList::const_iterator sit = config.storageMachine.llStorageControllers.begin();
2053
2054 // step 3): create the machine and have it import the config
2055
2056 // use the name that we computed in the OVF fields to avoid duplicates
2057 std::list<VirtualSystemDescriptionEntry*> vsdeName = vsdescThis->findByType(VirtualSystemDescriptionType_Name);
2058 if (vsdeName.size() < 1)
2059 throw setError(VBOX_E_FILE_ERROR,
2060 tr("Missing VM name"));
2061 const Utf8Str &strNameVBox = vsdeName.front()->strVbox;
2062
2063 ComObjPtr<Machine> pNewMachine;
2064 rc = pNewMachine.createObject();
2065 if (FAILED(rc)) throw rc;
2066
2067 // this magic constructor fills the new machine object with the MachineConfig
2068 // instance that we created from the vbox:Machine
2069 rc = pNewMachine->init(mVirtualBox,
2070 strNameVBox, // name from just above (can be suffixed to avoid duplicates)
2071 config); // the whole machine config
2072 if (FAILED(rc)) throw rc;
2073
2074 // return the new machine as an IMachine
2075 IMachine *p;
2076 rc = pNewMachine.queryInterfaceTo(&p);
2077 if (FAILED(rc)) throw rc;
2078 pReturnNewMachine = p;
2079
2080 // and register it
2081 rc = mVirtualBox->RegisterMachine(pNewMachine);
2082 if (FAILED(rc)) throw rc;
2083
2084 // store new machine for roll-back in case of errors
2085 Bstr bstrNewMachineId;
2086 rc = pNewMachine->COMGETTER(Id)(bstrNewMachineId.asOutParam());
2087 if (FAILED(rc)) throw rc;
2088 stack.llMachinesRegistered.push_back(bstrNewMachineId);
2089}
2090
2091/**
2092 * Worker code for importing OVF from the cloud. This is called from Appliance::taskThreadImportOrExport()
2093 * in S3 mode and therefore runs on the OVF import worker thread. This then starts a second worker
2094 * thread to import from temporary files (see Appliance::importFS()).
2095 * @param pTask
2096 * @return
2097 */
2098HRESULT Appliance::importS3(TaskOVF *pTask)
2099{
2100 LogFlowFuncEnter();
2101 LogFlowFunc(("Appliance %p\n", this));
2102
2103 AutoCaller autoCaller(this);
2104 if (FAILED(autoCaller.rc())) return autoCaller.rc();
2105
2106 AutoWriteLock appLock(this COMMA_LOCKVAL_SRC_POS);
2107
2108 int vrc = VINF_SUCCESS;
2109 RTS3 hS3 = NIL_RTS3;
2110 char szOSTmpDir[RTPATH_MAX];
2111 RTPathTemp(szOSTmpDir, sizeof(szOSTmpDir));
2112 /* The template for the temporary directory created below */
2113 char *pszTmpDir;
2114 RTStrAPrintf(&pszTmpDir, "%s"RTPATH_SLASH_STR"vbox-ovf-XXXXXX", szOSTmpDir);
2115 list< pair<Utf8Str, ULONG> > filesList;
2116
2117 HRESULT rc = S_OK;
2118 try
2119 {
2120 /* Extract the bucket */
2121 Utf8Str tmpPath = pTask->locInfo.strPath;
2122 Utf8Str bucket;
2123 parseBucket(tmpPath, bucket);
2124
2125 /* We need a temporary directory which we can put the all disk images
2126 * in */
2127 vrc = RTDirCreateTemp(pszTmpDir);
2128 if (RT_FAILURE(vrc))
2129 throw setError(VBOX_E_FILE_ERROR,
2130 tr("Cannot create temporary directory '%s'"), pszTmpDir);
2131
2132 /* Add every disks of every virtual system to an internal list */
2133 list< ComObjPtr<VirtualSystemDescription> >::const_iterator it;
2134 for (it = m->virtualSystemDescriptions.begin();
2135 it != m->virtualSystemDescriptions.end();
2136 ++it)
2137 {
2138 ComObjPtr<VirtualSystemDescription> vsdescThis = (*it);
2139 std::list<VirtualSystemDescriptionEntry*> avsdeHDs = vsdescThis->findByType(VirtualSystemDescriptionType_HardDiskImage);
2140 std::list<VirtualSystemDescriptionEntry*>::const_iterator itH;
2141 for (itH = avsdeHDs.begin();
2142 itH != avsdeHDs.end();
2143 ++itH)
2144 {
2145 const Utf8Str &strTargetFile = (*itH)->strOvf;
2146 if (!strTargetFile.isEmpty())
2147 {
2148 /* The temporary name of the target disk file */
2149 Utf8StrFmt strTmpDisk("%s/%s", pszTmpDir, RTPathFilename(strTargetFile.c_str()));
2150 filesList.push_back(pair<Utf8Str, ULONG>(strTmpDisk, (*itH)->ulSizeMB));
2151 }
2152 }
2153 }
2154
2155 /* Next we have to download the disk images */
2156 vrc = RTS3Create(&hS3, pTask->locInfo.strUsername.c_str(), pTask->locInfo.strPassword.c_str(), pTask->locInfo.strHostname.c_str(), "virtualbox-agent/"VBOX_VERSION_STRING);
2157 if (RT_FAILURE(vrc))
2158 throw setError(VBOX_E_IPRT_ERROR,
2159 tr("Cannot create S3 service handler"));
2160 RTS3SetProgressCallback(hS3, pTask->updateProgress, &pTask);
2161
2162 /* Download all files */
2163 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2164 {
2165 const pair<Utf8Str, ULONG> &s = (*it1);
2166 const Utf8Str &strSrcFile = s.first;
2167 /* Construct the source file name */
2168 char *pszFilename = RTPathFilename(strSrcFile.c_str());
2169 /* Advance to the next operation */
2170 if (!pTask->pProgress.isNull())
2171 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), s.second);
2172
2173 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strSrcFile.c_str());
2174 if (RT_FAILURE(vrc))
2175 {
2176 if (vrc == VERR_S3_CANCELED)
2177 throw S_OK; /* todo: !!!!!!!!!!!!! */
2178 else if (vrc == VERR_S3_ACCESS_DENIED)
2179 throw setError(E_ACCESSDENIED,
2180 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);
2181 else if (vrc == VERR_S3_NOT_FOUND)
2182 throw setError(VBOX_E_FILE_ERROR,
2183 tr("Cannot download file '%s' from S3 storage server (File not found)"), pszFilename);
2184 else
2185 throw setError(VBOX_E_IPRT_ERROR,
2186 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2187 }
2188 }
2189
2190 /* Provide a OVF file (haven't to exist) so the import routine can
2191 * figure out where the disk images/manifest file are located. */
2192 Utf8StrFmt strTmpOvf("%s/%s", pszTmpDir, RTPathFilename(tmpPath.c_str()));
2193 /* Now check if there is an manifest file. This is optional. */
2194 Utf8Str strManifestFile = manifestFileName(strTmpOvf);
2195 char *pszFilename = RTPathFilename(strManifestFile.c_str());
2196 if (!pTask->pProgress.isNull())
2197 pTask->pProgress->SetNextOperation(BstrFmt(tr("Downloading file '%s'"), pszFilename), 1);
2198
2199 /* Try to download it. If the error is VERR_S3_NOT_FOUND, it isn't fatal. */
2200 vrc = RTS3GetKey(hS3, bucket.c_str(), pszFilename, strManifestFile.c_str());
2201 if (RT_SUCCESS(vrc))
2202 filesList.push_back(pair<Utf8Str, ULONG>(strManifestFile, 0));
2203 else if (RT_FAILURE(vrc))
2204 {
2205 if (vrc == VERR_S3_CANCELED)
2206 throw S_OK; /* todo: !!!!!!!!!!!!! */
2207 else if (vrc == VERR_S3_NOT_FOUND)
2208 vrc = VINF_SUCCESS; /* Not found is ok */
2209 else if (vrc == VERR_S3_ACCESS_DENIED)
2210 throw setError(E_ACCESSDENIED,
2211 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);
2212 else
2213 throw setError(VBOX_E_IPRT_ERROR,
2214 tr("Cannot download file '%s' from S3 storage server (%Rrc)"), pszFilename, vrc);
2215 }
2216
2217 /* Close the connection early */
2218 RTS3Destroy(hS3);
2219 hS3 = NIL_RTS3;
2220
2221 pTask->pProgress->SetNextOperation(BstrFmt(tr("Importing appliance")), m->ulWeightForXmlOperation);
2222
2223 ComObjPtr<Progress> progress;
2224 /* Import the whole temporary OVF & the disk images */
2225 LocationInfo li;
2226 li.strPath = strTmpOvf;
2227 rc = importImpl(li, progress);
2228 if (FAILED(rc)) throw rc;
2229
2230 /* Unlock the appliance for the fs import thread */
2231 appLock.release();
2232 /* Wait until the import is done, but report the progress back to the
2233 caller */
2234 ComPtr<IProgress> progressInt(progress);
2235 waitForAsyncProgress(pTask->pProgress, progressInt); /* Any errors will be thrown */
2236
2237 /* Again lock the appliance for the next steps */
2238 appLock.acquire();
2239 }
2240 catch(HRESULT aRC)
2241 {
2242 rc = aRC;
2243 }
2244 /* Cleanup */
2245 RTS3Destroy(hS3);
2246 /* Delete all files which where temporary created */
2247 for (list< pair<Utf8Str, ULONG> >::const_iterator it1 = filesList.begin(); it1 != filesList.end(); ++it1)
2248 {
2249 const char *pszFilePath = (*it1).first.c_str();
2250 if (RTPathExists(pszFilePath))
2251 {
2252 vrc = RTFileDelete(pszFilePath);
2253 if (RT_FAILURE(vrc))
2254 rc = setError(VBOX_E_FILE_ERROR,
2255 tr("Cannot delete file '%s' (%Rrc)"), pszFilePath, vrc);
2256 }
2257 }
2258 /* Delete the temporary directory */
2259 if (RTPathExists(pszTmpDir))
2260 {
2261 vrc = RTDirRemove(pszTmpDir);
2262 if (RT_FAILURE(vrc))
2263 rc = setError(VBOX_E_FILE_ERROR,
2264 tr("Cannot delete temporary directory '%s' (%Rrc)"), pszTmpDir, vrc);
2265 }
2266 if (pszTmpDir)
2267 RTStrFree(pszTmpDir);
2268
2269 LogFlowFunc(("rc=%Rhrc\n", rc));
2270 LogFlowFuncLeave();
2271
2272 return rc;
2273}
2274
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette